Fix `org-check-before-invisible-edit', part 2
[org-mode/org-tableheadings.git] / lisp / org.el
blob916f54b888d25174518b8696e52cb3c38304859b
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 (match-end 3)
6212 (org-display-custom-time (match-beginning 3) (match-end 3))
6213 (org-display-custom-time (match-beginning 1) (match-end 1))))
6216 (defvar-local org-target-link-regexp nil
6217 "Regular expression matching radio targets in plain text.")
6219 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6220 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6221 border border border))
6222 "Regular expression matching a link target.")
6224 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6225 "Regular expression matching a radio target.")
6227 (defconst org-any-target-regexp
6228 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6229 "Regular expression matching any target.")
6231 (defun org-activate-target-links (limit)
6232 "Add text properties for target matches."
6233 (when org-target-link-regexp
6234 (let ((case-fold-search t))
6235 (when (re-search-forward org-target-link-regexp limit t)
6236 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6237 (add-text-properties (match-beginning 1) (match-end 1)
6238 (list 'mouse-face 'highlight
6239 'keymap org-mouse-map
6240 'help-echo "Radio target link"
6241 'org-linked-text t))
6242 (org-rear-nonsticky-at (match-end 1))
6243 t))))
6245 (defun org-update-radio-target-regexp ()
6246 "Find all radio targets in this file and update the regular expression.
6247 Also refresh fontification if needed."
6248 (interactive)
6249 (let ((old-regexp org-target-link-regexp)
6250 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6251 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6252 (targets
6253 (org-with-wide-buffer
6254 (goto-char (point-min))
6255 (let (rtn)
6256 (while (re-search-forward org-radio-target-regexp nil t)
6257 ;; Make sure point is really within the object.
6258 (backward-char)
6259 (let ((obj (org-element-context)))
6260 (when (eq (org-element-type obj) 'radio-target)
6261 (cl-pushnew (org-element-property :value obj) rtn
6262 :test #'equal))))
6263 rtn))))
6264 (setq org-target-link-regexp
6265 (and targets
6266 (concat before-re
6267 (mapconcat
6268 (lambda (x)
6269 (replace-regexp-in-string
6270 " +" "\\s-+" (regexp-quote x) t t))
6271 targets
6272 "\\|")
6273 after-re)))
6274 (unless (equal old-regexp org-target-link-regexp)
6275 ;; Clean-up cache.
6276 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6277 ((not org-target-link-regexp) old-regexp)
6279 (concat before-re
6280 (mapconcat
6281 (lambda (re)
6282 (substring re (length before-re)
6283 (- (length after-re))))
6284 (list old-regexp org-target-link-regexp)
6285 "\\|")
6286 after-re)))))
6287 (org-with-wide-buffer
6288 (goto-char (point-min))
6289 (while (re-search-forward regexp nil t)
6290 (org-element-cache-refresh (match-beginning 1)))))
6291 ;; Re fontify buffer.
6292 (when (memq 'radio org-highlight-links)
6293 (org-restart-font-lock)))))
6295 (defun org-hide-wide-columns (limit)
6296 (let (s e)
6297 (setq s (text-property-any (point) (or limit (point-max))
6298 'org-cwidth t))
6299 (when s
6300 (setq e (next-single-property-change s 'org-cwidth))
6301 (add-text-properties s e '(invisible org-cwidth))
6302 (goto-char e)
6303 t)))
6305 (defvar org-latex-and-related-regexp nil
6306 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6308 (defun org-compute-latex-and-related-regexp ()
6309 "Compute regular expression for LaTeX, entities and sub/superscript.
6310 Result depends on variable `org-highlight-latex-and-related'."
6311 (setq-local
6312 org-latex-and-related-regexp
6313 (let* ((re-sub
6314 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6315 ((eq org-use-sub-superscripts '{})
6316 (list org-match-substring-with-braces-regexp))
6317 (org-use-sub-superscripts (list org-match-substring-regexp))))
6318 (re-latex
6319 (when (memq 'latex org-highlight-latex-and-related)
6320 (let ((matchers (plist-get org-format-latex-options :matchers)))
6321 (delq nil
6322 (mapcar (lambda (x)
6323 (and (member (car x) matchers) (nth 1 x)))
6324 org-latex-regexps)))))
6325 (re-entities
6326 (when (memq 'entities org-highlight-latex-and-related)
6327 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6328 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6330 (defun org-do-latex-and-related (limit)
6331 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6332 LIMIT bounds the search for syntax to highlight. Stop at first
6333 highlighted object, if any. Return t if some highlighting was
6334 done, nil otherwise."
6335 (when (org-string-nw-p org-latex-and-related-regexp)
6336 (catch 'found
6337 (while (re-search-forward org-latex-and-related-regexp limit t)
6338 (unless
6339 (cl-some
6340 (lambda (f)
6341 (memq f '(org-code org-verbatim underline org-special-keyword)))
6342 (save-excursion
6343 (goto-char (1+ (match-beginning 0)))
6344 (face-at-point nil t)))
6345 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6346 '(?_ ?^))
6348 0)))
6349 (font-lock-prepend-text-property
6350 (+ offset (match-beginning 0)) (match-end 0)
6351 'face 'org-latex-and-related)
6352 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6353 '(font-lock-multiline t)))
6354 (throw 'found t)))
6355 nil)))
6357 (defun org-restart-font-lock ()
6358 "Restart `font-lock-mode', to force refontification."
6359 (when (and (boundp 'font-lock-mode) font-lock-mode)
6360 (font-lock-mode -1)
6361 (font-lock-mode 1)))
6363 (defun org-activate-tags (limit)
6364 (when (re-search-forward
6365 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6366 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6367 (add-text-properties (match-beginning 1) (match-end 1)
6368 (list 'mouse-face 'highlight
6369 'keymap org-mouse-map))
6370 (org-rear-nonsticky-at (match-end 1))
6373 (defun org-outline-level ()
6374 "Compute the outline level of the heading at point.
6376 If this is called at a normal headline, the level is the number
6377 of stars. Use `org-reduced-level' to remove the effect of
6378 `org-odd-levels'. Unlike to `org-current-level', this function
6379 takes into consideration inlinetasks."
6380 (org-with-wide-buffer
6381 (end-of-line)
6382 (if (re-search-backward org-outline-regexp-bol nil t)
6383 (1- (- (match-end 0) (match-beginning 0)))
6384 0)))
6386 (defvar org-font-lock-keywords nil)
6388 (defsubst org-re-property (property &optional literal allow-null value)
6389 "Return a regexp matching a PROPERTY line.
6391 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6392 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6393 non-nil, match properties even without a value.
6395 Match group 3 is set to the value when it exists. If there is no
6396 value and ALLOW-NULL is non-nil, it is set to the empty string.
6398 With optional argument VALUE, match only property lines with
6399 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6400 unless LITERAL is non-nil."
6401 (concat
6402 "^\\(?4:[ \t]*\\)"
6403 (format "\\(?1::\\(?2:%s\\):\\)"
6404 (if literal property (regexp-quote property)))
6405 (cond (value
6406 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6407 (if literal value (regexp-quote value))))
6408 (allow-null
6409 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6411 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6413 (defconst org-property-re
6414 (org-re-property "\\S-+" 'literal t)
6415 "Regular expression matching a property line.
6416 There are four matching groups:
6417 1: :PROPKEY: including the leading and trailing colon,
6418 2: PROPKEY without the leading and trailing colon,
6419 3: PROPVAL without leading or trailing spaces,
6420 4: the indentation of the current line,
6421 5: trailing whitespace.")
6423 (defvar org-font-lock-hook nil
6424 "Functions to be called for special font lock stuff.")
6426 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6428 (defvar org-font-lock-set-keywords-hook nil
6429 "Functions that can manipulate `org-font-lock-extra-keywords'.
6430 This is called after `org-font-lock-extra-keywords' is defined, but before
6431 it is installed to be used by font lock. This can be useful if something
6432 needs to be inserted at a specific position in the font-lock sequence.")
6434 (defun org-font-lock-hook (limit)
6435 "Run `org-font-lock-hook' within LIMIT."
6436 (run-hook-with-args 'org-font-lock-hook limit))
6438 (defun org-set-font-lock-defaults ()
6439 "Set font lock defaults for the current buffer."
6440 (let* ((em org-fontify-emphasized-text)
6441 (lk org-highlight-links)
6442 (org-font-lock-extra-keywords
6443 (list
6444 ;; Call the hook
6445 '(org-font-lock-hook)
6446 ;; Headlines
6447 `(,(if org-fontify-whole-heading-line
6448 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6449 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6450 (1 (org-get-level-face 1))
6451 (2 (org-get-level-face 2))
6452 (3 (org-get-level-face 3)))
6453 ;; Table lines
6454 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6455 (1 'org-table t))
6456 ;; Table internals
6457 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6458 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6459 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6460 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6461 ;; Drawers
6462 '(org-fontify-drawers)
6463 ;; Properties
6464 (list org-property-re
6465 '(1 'org-special-keyword t)
6466 '(3 'org-property-value t))
6467 ;; Link related fontification.
6468 '(org-activate-links)
6469 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6470 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6471 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6472 (when (memq 'footnote lk) '(org-activate-footnote-links))
6473 ;; Targets.
6474 (list org-any-target-regexp '(0 'org-target t))
6475 ;; Diary sexps.
6476 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6477 ;; Macro
6478 '(org-fontify-macros)
6479 '(org-hide-wide-columns (0 nil append))
6480 ;; TODO keyword
6481 (list (format org-heading-keyword-regexp-format
6482 org-todo-regexp)
6483 '(2 (org-get-todo-face 2) t))
6484 ;; DONE
6485 (if org-fontify-done-headline
6486 (list (format org-heading-keyword-regexp-format
6487 (concat
6488 "\\(?:"
6489 (mapconcat 'regexp-quote org-done-keywords "\\|")
6490 "\\)"))
6491 '(2 'org-headline-done t))
6492 nil)
6493 ;; Priorities
6494 '(org-font-lock-add-priority-faces)
6495 ;; Tags
6496 '(org-font-lock-add-tag-faces)
6497 ;; Tags groups
6498 (when (and org-group-tags org-tag-groups-alist)
6499 (list (concat org-outline-regexp-bol ".+\\(:"
6500 (regexp-opt (mapcar 'car org-tag-groups-alist))
6501 ":\\).*$")
6502 '(1 'org-tag-group prepend)))
6503 ;; Special keywords
6504 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6505 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6506 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6507 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6508 ;; Emphasis
6509 (when em '(org-do-emphasis-faces))
6510 ;; Checkboxes
6511 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6512 1 'org-checkbox prepend)
6513 (when (cdr (assq 'checkbox org-list-automatic-rules))
6514 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6515 (0 (org-get-checkbox-statistics-face) t)))
6516 ;; Description list items
6517 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6518 1 'org-list-dt prepend)
6519 ;; ARCHIVEd headings
6520 (list (concat
6521 org-outline-regexp-bol
6522 "\\(.*:" org-archive-tag ":.*\\)")
6523 '(1 'org-archived prepend))
6524 ;; Specials
6525 '(org-do-latex-and-related)
6526 '(org-fontify-entities)
6527 '(org-raise-scripts)
6528 ;; Code
6529 '(org-activate-code (1 'org-code t))
6530 ;; COMMENT
6531 (list (format
6532 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6533 org-todo-regexp
6534 org-comment-string)
6535 '(9 'org-special-keyword t))
6536 ;; Blocks and meta lines
6537 '(org-fontify-meta-lines-and-blocks))))
6538 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6539 (run-hooks 'org-font-lock-set-keywords-hook)
6540 ;; Now set the full font-lock-keywords
6541 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6542 (setq-local font-lock-defaults
6543 '(org-font-lock-keywords t nil nil backward-paragraph))
6544 (kill-local-variable 'font-lock-keywords)
6545 nil))
6547 (defun org-toggle-pretty-entities ()
6548 "Toggle the composition display of entities as UTF8 characters."
6549 (interactive)
6550 (setq-local org-pretty-entities (not org-pretty-entities))
6551 (org-restart-font-lock)
6552 (if org-pretty-entities
6553 (message "Entities are now displayed as UTF8 characters")
6554 (save-restriction
6555 (widen)
6556 (decompose-region (point-min) (point-max))
6557 (message "Entities are now displayed as plain text"))))
6559 (defvar-local org-custom-properties-overlays nil
6560 "List of overlays used for custom properties.")
6562 (defun org-toggle-custom-properties-visibility ()
6563 "Display or hide properties in `org-custom-properties'."
6564 (interactive)
6565 (if org-custom-properties-overlays
6566 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6567 (setq org-custom-properties-overlays nil))
6568 (when org-custom-properties
6569 (org-with-wide-buffer
6570 (goto-char (point-min))
6571 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6572 (while (re-search-forward regexp nil t)
6573 (let ((end (cdr (save-match-data (org-get-property-block)))))
6574 (when (and end (< (point) end))
6575 ;; Hide first custom property in current drawer.
6576 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6577 (overlay-put o 'invisible t)
6578 (overlay-put o 'org-custom-property t)
6579 (push o org-custom-properties-overlays))
6580 ;; Hide additional custom properties in the same drawer.
6581 (while (re-search-forward regexp end t)
6582 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6583 (overlay-put o 'invisible t)
6584 (overlay-put o 'org-custom-property t)
6585 (push o org-custom-properties-overlays)))))
6586 ;; Each entry is limited to a single property drawer.
6587 (outline-next-heading)))))))
6589 (defun org-fontify-entities (limit)
6590 "Find an entity to fontify."
6591 (let (ee)
6592 (when org-pretty-entities
6593 (catch 'match
6594 ;; "\_ "-family is left out on purpose. Only the first one,
6595 ;; i.e., "\_ ", could be fontified anyway, and it would be
6596 ;; confusing when adding a second white space character.
6597 (while (re-search-forward
6598 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6599 limit t)
6600 (when (and (not (org-at-comment-p))
6601 (setq ee (org-entity-get (match-string 1)))
6602 (= (length (nth 6 ee)) 1))
6603 (let* ((end (if (equal (match-string 2) "{}")
6604 (match-end 2)
6605 (match-end 1))))
6606 (add-text-properties
6607 (match-beginning 0) end
6608 (list 'font-lock-fontified t))
6609 (compose-region (match-beginning 0) end
6610 (nth 6 ee) nil)
6611 (backward-char 1)
6612 (throw 'match t))))
6613 nil))))
6615 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6616 "Fontify string S like in Org mode."
6617 (with-temp-buffer
6618 (insert s)
6619 (let ((org-odd-levels-only odd-levels))
6620 (org-mode)
6621 (org-font-lock-ensure)
6622 (buffer-string))))
6624 (defvar org-m nil)
6625 (defvar org-l nil)
6626 (defvar org-f nil)
6627 (defun org-get-level-face (n)
6628 "Get the right face for match N in font-lock matching of headlines."
6629 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6630 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6631 (if org-cycle-level-faces
6632 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6633 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6634 (cond
6635 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6636 ((eq n 2) org-f)
6637 (t (unless org-level-color-stars-only org-f))))
6639 (defun org-face-from-face-or-color (context inherit face-or-color)
6640 "Create a face list that inherits INHERIT, but sets the foreground color.
6641 When FACE-OR-COLOR is not a string, just return it."
6642 (if (stringp face-or-color)
6643 (list :inherit inherit
6644 (cdr (assoc context org-faces-easy-properties))
6645 face-or-color)
6646 face-or-color))
6648 (defun org-get-todo-face (kwd)
6649 "Get the right face for a TODO keyword KWD.
6650 If KWD is a number, get the corresponding match group."
6651 (when (numberp kwd) (setq kwd (match-string kwd)))
6652 (or (org-face-from-face-or-color
6653 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6654 (and (member kwd org-done-keywords) 'org-done)
6655 'org-todo))
6657 (defun org-get-priority-face (priority)
6658 "Get the right face for PRIORITY.
6659 PRIORITY is a character."
6660 (or (org-face-from-face-or-color
6661 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6662 'org-priority))
6664 (defun org-get-tag-face (tag)
6665 "Get the right face for TAG.
6666 If TAG is a number, get the corresponding match group."
6667 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6668 (or (org-face-from-face-or-color
6669 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6670 'org-tag)))
6672 (defun org-font-lock-add-priority-faces (limit)
6673 "Add the special priority faces."
6674 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6675 (add-text-properties
6676 (match-beginning 1) (match-end 1)
6677 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6678 'font-lock-fontified t))))
6680 (defun org-font-lock-add-tag-faces (limit)
6681 "Add the special tag faces."
6682 (when (and org-tag-faces org-tags-special-faces-re)
6683 (while (re-search-forward org-tags-special-faces-re limit t)
6684 (add-text-properties (match-beginning 1) (match-end 1)
6685 (list 'face (org-get-tag-face 1)
6686 'font-lock-fontified t))
6687 (backward-char 1))))
6689 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6690 "Remove fontification and activation overlays from links."
6691 (font-lock-default-unfontify-region beg end)
6692 (let* ((buffer-undo-list t)
6693 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6694 (inhibit-modification-hooks t)
6695 deactivate-mark buffer-file-name buffer-file-truename)
6696 (decompose-region beg end)
6697 (remove-text-properties beg end
6698 '(mouse-face t keymap t org-linked-text t
6699 invisible t intangible t
6700 org-emphasis t))
6701 (org-remove-font-lock-display-properties beg end)))
6703 (defconst org-script-display '(((raise -0.3) (height 0.7))
6704 ((raise 0.3) (height 0.7))
6705 ((raise -0.5))
6706 ((raise 0.5)))
6707 "Display properties for showing superscripts and subscripts.")
6709 (defun org-remove-font-lock-display-properties (beg end)
6710 "Remove specific display properties that have been added by font lock.
6711 The will remove the raise properties that are used to show superscripts
6712 and subscripts."
6713 (let (next prop)
6714 (while (< beg end)
6715 (setq next (next-single-property-change beg 'display nil end)
6716 prop (get-text-property beg 'display))
6717 (when (member prop org-script-display)
6718 (put-text-property beg next 'display nil))
6719 (setq beg next))))
6721 (defun org-raise-scripts (limit)
6722 "Add raise properties to sub/superscripts."
6723 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6724 (re-search-forward
6725 (if (eq org-use-sub-superscripts t)
6726 org-match-substring-regexp
6727 org-match-substring-with-braces-regexp)
6728 limit t))
6729 (let* ((pos (point)) table-p comment-p
6730 (mpos (match-beginning 3))
6731 (emph-p (get-text-property mpos 'org-emphasis))
6732 (link-p (get-text-property mpos 'mouse-face))
6733 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6734 (goto-char (point-at-bol))
6735 (setq table-p (looking-at-p org-table-dataline-regexp)
6736 comment-p (looking-at-p "^[ \t]*#[ +]"))
6737 (goto-char pos)
6738 ;; Handle a_b^c
6739 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6740 (unless (or comment-p emph-p link-p keyw-p)
6741 (put-text-property (match-beginning 3) (match-end 0)
6742 'display
6743 (if (equal (char-after (match-beginning 2)) ?^)
6744 (nth (if table-p 3 1) org-script-display)
6745 (nth (if table-p 2 0) org-script-display)))
6746 (add-text-properties (match-beginning 2) (match-end 2)
6747 (list 'invisible t
6748 'org-dwidth t 'org-dwidth-n 1))
6749 (if (and (eq (char-after (match-beginning 3)) ?{)
6750 (eq (char-before (match-end 3)) ?}))
6751 (progn
6752 (add-text-properties
6753 (match-beginning 3) (1+ (match-beginning 3))
6754 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6755 (add-text-properties
6756 (1- (match-end 3)) (match-end 3)
6757 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6758 t)))
6760 ;;;; Visibility cycling, including org-goto and indirect buffer
6762 ;;; Cycling
6764 (defvar-local org-cycle-global-status nil)
6765 (put 'org-cycle-global-status 'org-state t)
6766 (defvar-local org-cycle-subtree-status nil)
6767 (put 'org-cycle-subtree-status 'org-state t)
6769 (defvar org-inlinetask-min-level)
6771 (defun org-unlogged-message (&rest args)
6772 "Display a message, but avoid logging it in the *Messages* buffer."
6773 (let ((message-log-max nil))
6774 (apply 'message args)))
6776 ;;;###autoload
6777 (defun org-cycle (&optional arg)
6778 "TAB-action and visibility cycling for Org mode.
6780 This is the command invoked in Org mode by the `TAB' key. Its main
6781 purpose is outline visibility cycling, but it also invokes other actions
6782 in special contexts.
6784 When this function is called with a `\\[universal-argument]' prefix, rotate \
6785 the entire
6786 buffer through 3 states (global cycling)
6787 1. OVERVIEW: Show only top-level headlines.
6788 2. CONTENTS: Show all headlines of all levels, but no body text.
6789 3. SHOW ALL: Show everything.
6791 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6792 switch to the startup visibility,
6793 determined by the variable `org-startup-folded', and by any VISIBILITY
6794 properties in the buffer.
6796 With a `\\[universal-argument] \\[universal-argument] \
6797 \\[universal-argument]' prefix argument, show the entire buffer, including
6798 any drawers.
6800 When inside a table, re-align the table and move to the next field.
6802 When point is at the beginning of a headline, rotate the subtree started
6803 by this line through 3 different states (local cycling)
6804 1. FOLDED: Only the main headline is shown.
6805 2. CHILDREN: The main headline and the direct children are shown.
6806 From this state, you can move to one of the children
6807 and zoom in further.
6808 3. SUBTREE: Show the entire subtree, including body text.
6809 If there is no subtree, switch directly from CHILDREN to FOLDED.
6811 When point is at the beginning of an empty headline and the variable
6812 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6813 of the headline by demoting and promoting it to likely levels. This
6814 speeds up creation document structure by pressing `TAB' once or several
6815 times right after creating a new headline.
6817 When there is a numeric prefix, go up to a heading with level ARG, do
6818 a `show-subtree' and return to the previous cursor position. If ARG
6819 is negative, go up that many levels.
6821 When point is not at the beginning of a headline, execute the global
6822 binding for `TAB', which is re-indenting the line. See the option
6823 `org-cycle-emulate-tab' for details.
6825 As a special case, if point is at the beginning of the buffer and there is
6826 no headline in line 1, this function will act as if called with prefix arg
6827 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6828 prefix arg, but only
6829 if the variable `org-cycle-global-at-bob' is t."
6830 (interactive "P")
6831 (org-load-modules-maybe)
6832 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6833 (and org-cycle-level-after-item/entry-creation
6834 (or (org-cycle-level)
6835 (org-cycle-item-indentation))))
6836 (let* ((limit-level
6837 (or org-cycle-max-level
6838 (and (boundp 'org-inlinetask-min-level)
6839 org-inlinetask-min-level
6840 (1- org-inlinetask-min-level))))
6841 (nstars (and limit-level
6842 (if org-odd-levels-only
6843 (and limit-level (1- (* limit-level 2)))
6844 limit-level)))
6845 (org-outline-regexp
6846 (if (not (derived-mode-p 'org-mode))
6847 outline-regexp
6848 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6849 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6850 (not (looking-at org-outline-regexp))))
6851 (org-cycle-hook
6852 (if bob-special
6853 (delq 'org-optimize-window-after-visibility-change
6854 (copy-sequence org-cycle-hook))
6855 org-cycle-hook))
6856 (pos (point)))
6858 (cond
6860 ((equal arg '(16))
6861 (setq last-command 'dummy)
6862 (org-set-startup-visibility)
6863 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6865 ((equal arg '(64))
6866 (outline-show-all)
6867 (org-unlogged-message "Entire buffer visible, including drawers"))
6869 ((equal arg '(4)) (org-cycle-internal-global))
6871 ;; Try hiding block at point.
6872 ((org-hide-block-toggle-maybe))
6874 ;; Try cdlatex TAB completion
6875 ((org-try-cdlatex-tab))
6877 ;; Table: enter it or move to the next field.
6878 ((org-at-table-p 'any)
6879 (if (org-at-table.el-p)
6880 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6881 Use `\\[org-edit-special]' to edit table.el tables"))
6882 (if arg (org-table-edit-field t)
6883 (org-table-justify-field-maybe)
6884 (call-interactively 'org-table-next-field))))
6886 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6888 ;; Global cycling: delegate to `org-cycle-internal-global'.
6889 (bob-special (org-cycle-internal-global))
6891 ;; Drawers: delegate to `org-flag-drawer'.
6892 ((save-excursion
6893 (beginning-of-line 1)
6894 (looking-at org-drawer-regexp))
6895 (org-flag-drawer ; toggle block visibility
6896 (not (get-char-property (match-end 0) 'invisible))))
6898 ;; Show-subtree, ARG levels up from here.
6899 ((integerp arg)
6900 (save-excursion
6901 (org-back-to-heading)
6902 (outline-up-heading (if (< arg 0) (- arg)
6903 (- (funcall outline-level) arg)))
6904 (org-show-subtree)))
6906 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6907 ((and (featurep 'org-inlinetask)
6908 (org-inlinetask-at-task-p)
6909 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6910 (org-inlinetask-toggle-visibility))
6912 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6913 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6914 (save-excursion (move-beginning-of-line 1)
6915 (looking-at org-outline-regexp)))
6916 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6917 (org-cycle-internal-local))
6919 ;; From there: TAB emulation and template completion.
6920 (buffer-read-only (org-back-to-heading))
6922 ((run-hook-with-args-until-success
6923 'org-tab-after-check-for-cycling-hook))
6925 ((org-try-structure-completion))
6927 ((run-hook-with-args-until-success
6928 'org-tab-before-tab-emulation-hook))
6930 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6931 (or (not (bolp))
6932 (not (looking-at org-outline-regexp))))
6933 (call-interactively (global-key-binding "\t")))
6935 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6936 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6937 (or (and (eq org-cycle-emulate-tab 'white)
6938 (= (match-end 0) (point-at-eol)))
6939 (and (eq org-cycle-emulate-tab 'whitestart)
6940 (>= (match-end 0) pos))))
6942 (eq org-cycle-emulate-tab t))
6943 (call-interactively (global-key-binding "\t")))
6945 (t (save-excursion
6946 (org-back-to-heading)
6947 (org-cycle)))))))
6949 (defun org-cycle-internal-global ()
6950 "Do the global cycling action."
6951 ;; Hack to avoid display of messages for .org attachments in Gnus
6952 (let ((ga (string-match "\\*fontification" (buffer-name))))
6953 (cond
6954 ((and (eq last-command this-command)
6955 (eq org-cycle-global-status 'overview))
6956 ;; We just created the overview - now do table of contents
6957 ;; This can be slow in very large buffers, so indicate action
6958 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6959 (unless ga (org-unlogged-message "CONTENTS..."))
6960 (org-content)
6961 (unless ga (org-unlogged-message "CONTENTS...done"))
6962 (setq org-cycle-global-status 'contents)
6963 (run-hook-with-args 'org-cycle-hook 'contents))
6965 ((and (eq last-command this-command)
6966 (eq org-cycle-global-status 'contents))
6967 ;; We just showed the table of contents - now show everything
6968 (run-hook-with-args 'org-pre-cycle-hook 'all)
6969 (outline-show-all)
6970 (unless ga (org-unlogged-message "SHOW ALL"))
6971 (setq org-cycle-global-status 'all)
6972 (run-hook-with-args 'org-cycle-hook 'all))
6975 ;; Default action: go to overview
6976 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6977 (org-overview)
6978 (unless ga (org-unlogged-message "OVERVIEW"))
6979 (setq org-cycle-global-status 'overview)
6980 (run-hook-with-args 'org-cycle-hook 'overview)))))
6982 (defvar org-called-with-limited-levels nil
6983 "Non-nil when `org-with-limited-levels' is currently active.")
6985 (defun org-invisible-p (&optional pos)
6986 "Non-nil if the character after POS is invisible.
6987 If POS is nil, use `point' instead."
6988 (get-char-property (or pos (point)) 'invisible))
6990 (defun org-cycle-internal-local ()
6991 "Do the local cycling action."
6992 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6993 ;; First, determine end of headline (EOH), end of subtree or item
6994 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6995 (save-excursion
6996 (if (org-at-item-p)
6997 (progn
6998 (beginning-of-line)
6999 (setq struct (org-list-struct))
7000 (setq eoh (point-at-eol))
7001 (setq eos (org-list-get-item-end-before-blank (point) struct))
7002 (setq has-children (org-list-has-child-p (point) struct)))
7003 (org-back-to-heading)
7004 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7005 (setq eos (save-excursion (org-end-of-subtree t t)
7006 (when (bolp) (backward-char)) (point)))
7007 (setq has-children
7008 (or (save-excursion
7009 (let ((level (funcall outline-level)))
7010 (outline-next-heading)
7011 (and (org-at-heading-p t)
7012 (> (funcall outline-level) level))))
7013 (save-excursion
7014 (org-list-search-forward (org-item-beginning-re) eos t)))))
7015 ;; Determine end invisible part of buffer (EOL)
7016 (beginning-of-line 2)
7017 (while (and (not (eobp)) ;This is like `next-line'.
7018 (get-char-property (1- (point)) 'invisible))
7019 (goto-char (next-single-char-property-change (point) 'invisible))
7020 (and (eolp) (beginning-of-line 2)))
7021 (setq eol (point)))
7022 ;; Find out what to do next and set `this-command'
7023 (cond
7024 ((= eos eoh)
7025 ;; Nothing is hidden behind this heading
7026 (unless (org-before-first-heading-p)
7027 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7028 (org-unlogged-message "EMPTY ENTRY")
7029 (setq org-cycle-subtree-status nil)
7030 (save-excursion
7031 (goto-char eos)
7032 (outline-next-heading)
7033 (when (org-invisible-p) (org-flag-heading nil))))
7034 ((and (or (>= eol eos)
7035 (not (string-match "\\S-" (buffer-substring eol eos))))
7036 (or has-children
7037 (not (setq children-skipped
7038 org-cycle-skip-children-state-if-no-children))))
7039 ;; Entire subtree is hidden in one line: children view
7040 (unless (org-before-first-heading-p)
7041 (run-hook-with-args 'org-pre-cycle-hook 'children))
7042 (if (org-at-item-p)
7043 (org-list-set-item-visibility (point-at-bol) struct 'children)
7044 (org-show-entry)
7045 (org-with-limited-levels (org-show-children))
7046 ;; FIXME: This slows down the func way too much.
7047 ;; How keep drawers hidden in subtree anyway?
7048 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7049 ;; (org-cycle-hide-drawers 'subtree))
7051 ;; Fold every list in subtree to top-level items.
7052 (when (eq org-cycle-include-plain-lists 'integrate)
7053 (save-excursion
7054 (org-back-to-heading)
7055 (while (org-list-search-forward (org-item-beginning-re) eos t)
7056 (beginning-of-line 1)
7057 (let* ((struct (org-list-struct))
7058 (prevs (org-list-prevs-alist struct))
7059 (end (org-list-get-bottom-point struct)))
7060 (dolist (e (org-list-get-all-items (point) struct prevs))
7061 (org-list-set-item-visibility e struct 'folded))
7062 (goto-char (if (< end eos) end eos)))))))
7063 (org-unlogged-message "CHILDREN")
7064 (save-excursion
7065 (goto-char eos)
7066 (outline-next-heading)
7067 (when (org-invisible-p) (org-flag-heading nil)))
7068 (setq org-cycle-subtree-status 'children)
7069 (unless (org-before-first-heading-p)
7070 (run-hook-with-args 'org-cycle-hook 'children)))
7071 ((or children-skipped
7072 (and (eq last-command this-command)
7073 (eq org-cycle-subtree-status 'children)))
7074 ;; We just showed the children, or no children are there,
7075 ;; now show everything.
7076 (unless (org-before-first-heading-p)
7077 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7078 (outline-flag-region eoh eos nil)
7079 (org-unlogged-message
7080 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7081 (setq org-cycle-subtree-status 'subtree)
7082 (unless (org-before-first-heading-p)
7083 (run-hook-with-args 'org-cycle-hook 'subtree)))
7085 ;; Default action: hide the subtree.
7086 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7087 (outline-flag-region eoh eos t)
7088 (org-unlogged-message "FOLDED")
7089 (setq org-cycle-subtree-status 'folded)
7090 (unless (org-before-first-heading-p)
7091 (run-hook-with-args 'org-cycle-hook 'folded))))))
7093 ;;;###autoload
7094 (defun org-global-cycle (&optional arg)
7095 "Cycle the global visibility. For details see `org-cycle'.
7096 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7097 With a numeric prefix, show all headlines up to that level."
7098 (interactive "P")
7099 (let ((org-cycle-include-plain-lists
7100 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7101 (cond
7102 ((integerp arg)
7103 (outline-show-all)
7104 (outline-hide-sublevels arg)
7105 (setq org-cycle-global-status 'contents))
7106 ((equal arg '(4))
7107 (org-set-startup-visibility)
7108 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7110 (org-cycle '(4))))))
7112 (defun org-set-startup-visibility ()
7113 "Set the visibility required by startup options and properties."
7114 (cond
7115 ((eq org-startup-folded t)
7116 (org-overview))
7117 ((eq org-startup-folded 'content)
7118 (org-content))
7119 ((or (eq org-startup-folded 'showeverything)
7120 (eq org-startup-folded nil))
7121 (outline-show-all)))
7122 (unless (eq org-startup-folded 'showeverything)
7123 (when org-hide-block-startup (org-hide-block-all))
7124 (org-set-visibility-according-to-property 'no-cleanup)
7125 (org-cycle-hide-archived-subtrees 'all)
7126 (org-cycle-hide-drawers 'all)
7127 (org-cycle-show-empty-lines t)))
7129 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7130 "Switch subtree visibilities according to :VISIBILITY: property."
7131 (interactive)
7132 (org-with-wide-buffer
7133 (goto-char (point-min))
7134 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7135 (if (not (org-at-property-p)) (outline-next-heading)
7136 (let ((state (match-string 3)))
7137 (save-excursion
7138 (org-back-to-heading t)
7139 (outline-hide-subtree)
7140 (org-reveal)
7141 (cond
7142 ((equal state "folded")
7143 (outline-hide-subtree))
7144 ((equal state "children")
7145 (org-show-hidden-entry)
7146 (org-show-children))
7147 ((equal state "content")
7148 (save-excursion
7149 (save-restriction
7150 (org-narrow-to-subtree)
7151 (org-content))))
7152 ((member state '("all" "showall"))
7153 (outline-show-subtree)))))))
7154 (unless no-cleanup
7155 (org-cycle-hide-archived-subtrees 'all)
7156 (org-cycle-hide-drawers 'all)
7157 (org-cycle-show-empty-lines 'all))))
7159 ;; This function uses outline-regexp instead of the more fundamental
7160 ;; org-outline-regexp so that org-cycle-global works outside of Org
7161 ;; buffers, where outline-regexp is needed.
7162 (defun org-overview ()
7163 "Switch to overview mode, showing only top-level headlines.
7164 This shows all headlines with a level equal or greater than the level
7165 of the first headline in the buffer. This is important, because if the
7166 first headline is not level one, then (hide-sublevels 1) gives confusing
7167 results."
7168 (interactive)
7169 (save-excursion
7170 (let ((level
7171 (save-excursion
7172 (goto-char (point-min))
7173 (when (re-search-forward (concat "^" outline-regexp) nil t)
7174 (goto-char (match-beginning 0))
7175 (funcall outline-level)))))
7176 (and level (outline-hide-sublevels level)))))
7178 (defun org-content (&optional arg)
7179 "Show all headlines in the buffer, like a table of contents.
7180 With numerical argument N, show content up to level N."
7181 (interactive "P")
7182 (org-overview)
7183 (save-excursion
7184 ;; Visit all headings and show their offspring
7185 (and (integerp arg) (org-overview))
7186 (goto-char (point-max))
7187 (catch 'exit
7188 (while (and (progn (condition-case nil
7189 (outline-previous-visible-heading 1)
7190 (error (goto-char (point-min))))
7192 (looking-at org-outline-regexp))
7193 (if (integerp arg)
7194 (org-show-children (1- arg))
7195 (outline-show-branches))
7196 (when (bobp) (throw 'exit nil))))))
7198 (defun org-optimize-window-after-visibility-change (state)
7199 "Adjust the window after a change in outline visibility.
7200 This function is the default value of the hook `org-cycle-hook'."
7201 (when (get-buffer-window (current-buffer))
7202 (cond
7203 ((eq state 'content) nil)
7204 ((eq state 'all) nil)
7205 ((eq state 'folded) nil)
7206 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7207 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7209 (defun org-remove-empty-overlays-at (pos)
7210 "Remove outline overlays that do not contain non-white stuff."
7211 (dolist (o (overlays-at pos))
7212 (and (eq 'outline (overlay-get o 'invisible))
7213 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7214 (overlay-end o))))
7215 (delete-overlay o))))
7217 (defun org-clean-visibility-after-subtree-move ()
7218 "Fix visibility issues after moving a subtree."
7219 ;; First, find a reasonable region to look at:
7220 ;; Start two siblings above, end three below
7221 (let* ((beg (save-excursion
7222 (and (org-get-last-sibling)
7223 (org-get-last-sibling))
7224 (point)))
7225 (end (save-excursion
7226 (and (org-get-next-sibling)
7227 (org-get-next-sibling)
7228 (org-get-next-sibling))
7229 (if (org-at-heading-p)
7230 (point-at-eol)
7231 (point))))
7232 (level (looking-at "\\*+"))
7233 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7234 (save-excursion
7235 (save-restriction
7236 (narrow-to-region beg end)
7237 (when re
7238 ;; Properly fold already folded siblings
7239 (goto-char (point-min))
7240 (while (re-search-forward re nil t)
7241 (when (and (not (org-invisible-p))
7242 (save-excursion
7243 (goto-char (point-at-eol)) (org-invisible-p)))
7244 (outline-hide-entry))))
7245 (org-cycle-show-empty-lines 'overview)
7246 (org-cycle-hide-drawers 'overview)))))
7248 (defun org-cycle-show-empty-lines (state)
7249 "Show empty lines above all visible headlines.
7250 The region to be covered depends on STATE when called through
7251 `org-cycle-hook'. Lisp program can use t for STATE to get the
7252 entire buffer covered. Note that an empty line is only shown if there
7253 are at least `org-cycle-separator-lines' empty lines before the headline."
7254 (when (/= org-cycle-separator-lines 0)
7255 (save-excursion
7256 (let* ((n (abs org-cycle-separator-lines))
7257 (re (cond
7258 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7259 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7260 (t (let ((ns (number-to-string (- n 2))))
7261 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7262 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7263 beg end)
7264 (cond
7265 ((memq state '(overview contents t))
7266 (setq beg (point-min) end (point-max)))
7267 ((memq state '(children folded))
7268 (setq beg (point)
7269 end (progn (org-end-of-subtree t t)
7270 (line-beginning-position 2)))))
7271 (when beg
7272 (goto-char beg)
7273 (while (re-search-forward re end t)
7274 (unless (get-char-property (match-end 1) 'invisible)
7275 (let ((e (match-end 1))
7276 (b (if (>= org-cycle-separator-lines 0)
7277 (match-beginning 1)
7278 (save-excursion
7279 (goto-char (match-beginning 0))
7280 (skip-chars-backward " \t\n")
7281 (line-end-position)))))
7282 (outline-flag-region b e nil))))))))
7283 ;; Never hide empty lines at the end of the file.
7284 (save-excursion
7285 (goto-char (point-max))
7286 (outline-previous-heading)
7287 (outline-end-of-heading)
7288 (when (and (looking-at "[ \t\n]+")
7289 (= (match-end 0) (point-max)))
7290 (outline-flag-region (point) (match-end 0) nil))))
7292 (defun org-show-empty-lines-in-parent ()
7293 "Move to the parent and re-show empty lines before visible headlines."
7294 (save-excursion
7295 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7296 (org-cycle-show-empty-lines context))))
7298 (defun org-files-list ()
7299 "Return `org-agenda-files' list, plus all open Org files.
7300 This is useful for operations that need to scan all of a user's
7301 open and agenda-wise Org files."
7302 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7303 (dolist (buf (buffer-list))
7304 (with-current-buffer buf
7305 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7306 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7307 files))
7309 (defsubst org-entry-beginning-position ()
7310 "Return the beginning position of the current entry."
7311 (save-excursion (org-back-to-heading t) (point)))
7313 (defsubst org-entry-end-position ()
7314 "Return the end position of the current entry."
7315 (save-excursion (outline-next-heading) (point)))
7317 (defun org-cycle-hide-drawers (state &optional exceptions)
7318 "Re-hide all drawers after a visibility state change.
7319 When non-nil, optional argument EXCEPTIONS is a list of strings
7320 specifying which drawers should not be hidden."
7321 (when (and (derived-mode-p 'org-mode)
7322 (not (memq state '(overview folded contents))))
7323 (save-excursion
7324 (let* ((globalp (memq state '(contents all)))
7325 (beg (if globalp (point-min) (point)))
7326 (end (if globalp (point-max)
7327 (if (eq state 'children)
7328 (save-excursion (outline-next-heading) (point))
7329 (org-end-of-subtree t)))))
7330 (goto-char beg)
7331 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7332 (unless (member-ignore-case (match-string 1) exceptions)
7333 (let ((drawer (org-element-at-point)))
7334 (when (memq (org-element-type drawer) '(drawer property-drawer))
7335 (org-flag-drawer t drawer)
7336 ;; Make sure to skip drawer entirely or we might flag
7337 ;; it another time when matching its ending line with
7338 ;; `org-drawer-regexp'.
7339 (goto-char (org-element-property :end drawer))))))))))
7341 (defun org-flag-drawer (flag &optional element)
7342 "When FLAG is non-nil, hide the drawer we are at.
7343 Otherwise make it visible. When optional argument ELEMENT is
7344 a parsed drawer, as returned by `org-element-at-point', hide or
7345 show that drawer instead."
7346 (let ((drawer (or element
7347 (and (save-excursion
7348 (beginning-of-line)
7349 (looking-at-p org-drawer-regexp))
7350 (org-element-at-point)))))
7351 (when (memq (org-element-type drawer) '(drawer property-drawer))
7352 (let ((post (org-element-property :post-affiliated drawer)))
7353 (save-excursion
7354 (outline-flag-region
7355 (progn (goto-char post) (line-end-position))
7356 (progn (goto-char (org-element-property :end drawer))
7357 (skip-chars-backward " \r\t\n")
7358 (line-end-position))
7359 flag))
7360 ;; When the drawer is hidden away, make sure point lies in
7361 ;; a visible part of the buffer.
7362 (when (and flag (> (line-beginning-position) post))
7363 (goto-char post))))))
7365 (defun org-subtree-end-visible-p ()
7366 "Is the end of the current subtree visible?"
7367 (pos-visible-in-window-p
7368 (save-excursion (org-end-of-subtree t) (point))))
7370 (defun org-first-headline-recenter ()
7371 "Move cursor to the first headline and recenter the headline."
7372 (let ((window (get-buffer-window)))
7373 (when window
7374 (goto-char (point-min))
7375 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7376 (set-window-start window (line-beginning-position))))))
7378 ;;; Saving and restoring visibility
7380 (defun org-outline-overlay-data (&optional use-markers)
7381 "Return a list of the locations of all outline overlays.
7382 These are overlays with the `invisible' property value `outline'.
7383 The return value is a list of cons cells, with start and stop
7384 positions for each overlay.
7385 If USE-MARKERS is set, return the positions as markers."
7386 (let (beg end)
7387 (org-with-wide-buffer
7388 (delq nil
7389 (mapcar (lambda (o)
7390 (when (eq (overlay-get o 'invisible) 'outline)
7391 (setq beg (overlay-start o)
7392 end (overlay-end o))
7393 (and beg end (> end beg)
7394 (if use-markers
7395 (cons (copy-marker beg)
7396 (copy-marker end t))
7397 (cons beg end)))))
7398 (overlays-in (point-min) (point-max)))))))
7400 (defun org-set-outline-overlay-data (data)
7401 "Create visibility overlays for all positions in DATA.
7402 DATA should have been made by `org-outline-overlay-data'."
7403 (org-with-wide-buffer
7404 (outline-show-all)
7405 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7407 ;;; Folding of blocks
7409 (defvar-local org-hide-block-overlays nil
7410 "Overlays hiding blocks.")
7412 (defun org-block-map (function &optional start end)
7413 "Call FUNCTION at the head of all source blocks in the current buffer.
7414 Optional arguments START and END can be used to limit the range."
7415 (let ((start (or start (point-min)))
7416 (end (or end (point-max))))
7417 (save-excursion
7418 (goto-char start)
7419 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7420 (save-excursion
7421 (save-match-data
7422 (goto-char (match-beginning 0))
7423 (funcall function)))))))
7425 (defun org-hide-block-toggle-all ()
7426 "Toggle the visibility of all blocks in the current buffer."
7427 (org-block-map 'org-hide-block-toggle))
7429 (defun org-hide-block-all ()
7430 "Fold all blocks in the current buffer."
7431 (interactive)
7432 (org-show-block-all)
7433 (org-block-map 'org-hide-block-toggle-maybe))
7435 (defun org-show-block-all ()
7436 "Unfold all blocks in the current buffer."
7437 (interactive)
7438 (mapc #'delete-overlay org-hide-block-overlays)
7439 (setq org-hide-block-overlays nil))
7441 (defun org-hide-block-toggle-maybe ()
7442 "Toggle visibility of block at point.
7443 Unlike to `org-hide-block-toggle', this function does not throw
7444 an error. Return a non-nil value when toggling is successful."
7445 (interactive)
7446 (ignore-errors (org-hide-block-toggle)))
7448 (defun org-hide-block-toggle (&optional force)
7449 "Toggle the visibility of the current block.
7450 When optional argument FORCE is `off', make block visible. If it
7451 is non-nil, hide it unconditionally. Throw an error when not at
7452 a block. Return a non-nil value when toggling is successful."
7453 (interactive)
7454 (let ((element (org-element-at-point)))
7455 (unless (memq (org-element-type element)
7456 '(center-block comment-block dynamic-block example-block
7457 export-block quote-block special-block
7458 src-block verse-block))
7459 (user-error "Not at a block"))
7460 (let* ((start (save-excursion
7461 (goto-char (org-element-property :post-affiliated element))
7462 (line-end-position)))
7463 (end (save-excursion
7464 (goto-char (org-element-property :end element))
7465 (skip-chars-backward " \r\t\n")
7466 (line-end-position)))
7467 (overlays (overlays-at start)))
7468 (cond
7469 ;; Do nothing when not before or at the block opening line or
7470 ;; at the block closing line.
7471 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7472 ((and (not (eq force 'off))
7473 (not (memq t (mapcar
7474 (lambda (o)
7475 (eq (overlay-get o 'invisible) 'org-hide-block))
7476 overlays))))
7477 (let ((ov (make-overlay start end)))
7478 (overlay-put ov 'invisible 'org-hide-block)
7479 ;; Make the block accessible to `isearch'.
7480 (overlay-put
7481 ov 'isearch-open-invisible
7482 (lambda (ov)
7483 (when (memq ov org-hide-block-overlays)
7484 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7485 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7486 (delete-overlay ov))))
7487 (push ov org-hide-block-overlays)
7488 ;; When the block is hidden away, make sure point is left in
7489 ;; a visible part of the buffer.
7490 (when (> (line-beginning-position) start)
7491 (goto-char start)
7492 (beginning-of-line))
7493 ;; Signal successful toggling.
7495 ((or (not force) (eq force 'off))
7496 (dolist (ov overlays t)
7497 (when (memq ov org-hide-block-overlays)
7498 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7499 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7500 (delete-overlay ov))))))))
7502 ;; Remove overlays when changing major mode
7503 (add-hook 'org-mode-hook
7504 (lambda () (add-hook 'change-major-mode-hook
7505 'org-show-block-all 'append 'local)))
7507 ;;; Org-goto
7509 (defvar org-goto-window-configuration nil)
7510 (defvar org-goto-marker nil)
7511 (defvar org-goto-map)
7512 (defun org-goto-map ()
7513 "Set the keymap `org-goto'."
7514 (setq org-goto-map
7515 (let ((map (make-sparse-keymap)))
7516 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7517 mouse-drag-region universal-argument org-occur)))
7518 (dolist (cmd cmds)
7519 (substitute-key-definition cmd cmd map global-map)))
7520 (suppress-keymap map)
7521 (org-defkey map "\C-m" 'org-goto-ret)
7522 (org-defkey map [(return)] 'org-goto-ret)
7523 (org-defkey map [(left)] 'org-goto-left)
7524 (org-defkey map [(right)] 'org-goto-right)
7525 (org-defkey map [(control ?g)] 'org-goto-quit)
7526 (org-defkey map "\C-i" 'org-cycle)
7527 (org-defkey map [(tab)] 'org-cycle)
7528 (org-defkey map [(down)] 'outline-next-visible-heading)
7529 (org-defkey map [(up)] 'outline-previous-visible-heading)
7530 (if org-goto-auto-isearch
7531 (if (fboundp 'define-key-after)
7532 (define-key-after map [t] 'org-goto-local-auto-isearch)
7533 nil)
7534 (org-defkey map "q" 'org-goto-quit)
7535 (org-defkey map "n" 'outline-next-visible-heading)
7536 (org-defkey map "p" 'outline-previous-visible-heading)
7537 (org-defkey map "f" 'outline-forward-same-level)
7538 (org-defkey map "b" 'outline-backward-same-level)
7539 (org-defkey map "u" 'outline-up-heading))
7540 (org-defkey map "/" 'org-occur)
7541 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7542 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7543 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7544 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7545 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7546 map)))
7548 (defconst org-goto-help
7549 "Browse buffer copy, to find location or copy text.%s
7550 RET=jump to location C-g=quit and return to previous location
7551 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7553 (defvar org-goto-start-pos) ; dynamically scoped parameter
7555 (defun org-goto (&optional alternative-interface)
7556 "Look up a different location in the current file, keeping current visibility.
7558 When you want look-up or go to a different location in a
7559 document, the fastest way is often to fold the entire buffer and
7560 then dive into the tree. This method has the disadvantage, that
7561 the previous location will be folded, which may not be what you
7562 want.
7564 This command works around this by showing a copy of the current
7565 buffer in an indirect buffer, in overview mode. You can dive
7566 into the tree in that copy, use org-occur and incremental search
7567 to find a location. When pressing RET or `Q', the command
7568 returns to the original buffer in which the visibility is still
7569 unchanged. After RET it will also jump to the location selected
7570 in the indirect buffer and expose the headline hierarchy above.
7572 With a prefix argument, use the alternative interface: e.g., if
7573 `org-goto-interface' is `outline' use `outline-path-completion'."
7574 (interactive "P")
7575 (org-goto-map)
7576 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7577 (org-refile-use-outline-path t)
7578 (org-refile-target-verify-function nil)
7579 (interface
7580 (if (not alternative-interface)
7581 org-goto-interface
7582 (if (eq org-goto-interface 'outline)
7583 'outline-path-completion
7584 'outline)))
7585 (org-goto-start-pos (point))
7586 (selected-point
7587 (if (eq interface 'outline)
7588 (car (org-get-location (current-buffer) org-goto-help))
7589 (let ((pa (org-refile-get-location "Goto")))
7590 (org-refile-check-position pa)
7591 (nth 3 pa)))))
7592 (if selected-point
7593 (progn
7594 (org-mark-ring-push org-goto-start-pos)
7595 (goto-char selected-point)
7596 (when (or (org-invisible-p) (org-invisible-p2))
7597 (org-show-context 'org-goto)))
7598 (message "Quit"))))
7600 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7601 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7602 (defvar org-goto-local-auto-isearch-map) ; defined below
7604 (defun org-get-location (_buf help)
7605 "Let the user select a location in current buffer.
7606 This function uses a recursive edit. It returns the selected position
7607 or nil."
7608 (org-no-popups
7609 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7610 (isearch-hide-immediately nil)
7611 (isearch-search-fun-function
7612 (lambda () 'org-goto-local-search-headings))
7613 (org-goto-selected-point org-goto-exit-command))
7614 (save-excursion
7615 (save-window-excursion
7616 (delete-other-windows)
7617 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7618 (pop-to-buffer-same-window
7619 (condition-case nil
7620 (make-indirect-buffer (current-buffer) "*org-goto*")
7621 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7622 (with-output-to-temp-buffer "*Org Help*"
7623 (princ (format help (if org-goto-auto-isearch
7624 " Just type for auto-isearch."
7625 " n/p/f/b/u to navigate, q to quit."))))
7626 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7627 (setq buffer-read-only nil)
7628 (let ((org-startup-truncated t)
7629 (org-startup-folded nil)
7630 (org-startup-align-all-tables nil))
7631 (org-mode)
7632 (org-overview))
7633 (setq buffer-read-only t)
7634 (if (and (boundp 'org-goto-start-pos)
7635 (integer-or-marker-p org-goto-start-pos))
7636 (progn (goto-char org-goto-start-pos)
7637 (when (org-invisible-p)
7638 (org-show-set-visibility 'lineage)))
7639 (goto-char (point-min)))
7640 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7641 (message "Select location and press RET")
7642 (use-local-map org-goto-map)
7643 (recursive-edit)))
7644 (kill-buffer "*org-goto*")
7645 (cons org-goto-selected-point org-goto-exit-command))))
7647 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7648 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7649 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7650 (if (fboundp 'isearch-other-control-char)
7651 (progn
7652 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7653 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7654 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7655 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7656 (define-key org-goto-local-auto-isearch-map [return] nil))
7658 (defun org-goto-local-search-headings (string bound noerror)
7659 "Search and make sure that any matches are in headlines."
7660 (catch 'return
7661 (while (if isearch-forward
7662 (search-forward string bound noerror)
7663 (search-backward string bound noerror))
7664 (when (save-match-data
7665 (and (save-excursion
7666 (beginning-of-line)
7667 (looking-at org-complex-heading-regexp))
7668 (or (not (match-beginning 5))
7669 (< (point) (match-beginning 5)))))
7670 (throw 'return (point))))))
7672 (defun org-goto-local-auto-isearch ()
7673 "Start isearch."
7674 (interactive)
7675 (goto-char (point-min))
7676 (let ((keys (this-command-keys)))
7677 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7678 (isearch-mode t)
7679 (isearch-process-search-char (string-to-char keys)))))
7681 (defun org-goto-ret (&optional _arg)
7682 "Finish `org-goto' by going to the new location."
7683 (interactive "P")
7684 (setq org-goto-selected-point (point))
7685 (setq org-goto-exit-command 'return)
7686 (throw 'exit nil))
7688 (defun org-goto-left ()
7689 "Finish `org-goto' by going to the new location."
7690 (interactive)
7691 (if (org-at-heading-p)
7692 (progn
7693 (beginning-of-line 1)
7694 (setq org-goto-selected-point (point)
7695 org-goto-exit-command 'left)
7696 (throw 'exit nil))
7697 (user-error "Not on a heading")))
7699 (defun org-goto-right ()
7700 "Finish `org-goto' by going to the new location."
7701 (interactive)
7702 (if (org-at-heading-p)
7703 (progn
7704 (setq org-goto-selected-point (point)
7705 org-goto-exit-command 'right)
7706 (throw 'exit nil))
7707 (user-error "Not on a heading")))
7709 (defun org-goto-quit ()
7710 "Finish `org-goto' without cursor motion."
7711 (interactive)
7712 (setq org-goto-selected-point nil)
7713 (setq org-goto-exit-command 'quit)
7714 (throw 'exit nil))
7716 ;;; Indirect buffer display of subtrees
7718 (defvar org-indirect-dedicated-frame nil
7719 "This is the frame being used for indirect tree display.")
7720 (defvar org-last-indirect-buffer nil)
7722 (defun org-tree-to-indirect-buffer (&optional arg)
7723 "Create indirect buffer and narrow it to current subtree.
7725 With a numerical prefix ARG, go up to this level and then take that tree.
7726 If ARG is negative, go up that many levels.
7728 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7729 indirect buffer previously made with this command, to avoid proliferation of
7730 indirect buffers. However, when you call the command with a \
7731 `\\[universal-argument]' prefix, or
7732 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7733 so that you can work with several indirect buffers at the same time. If
7734 `org-indirect-buffer-display' is `dedicated-frame', the \
7735 `\\[universal-argument]' prefix also
7736 requests that a new frame be made for the new buffer, so that the dedicated
7737 frame is not changed."
7738 (interactive "P")
7739 (let ((cbuf (current-buffer))
7740 (cwin (selected-window))
7741 (pos (point))
7742 beg end level heading ibuf)
7743 (save-excursion
7744 (org-back-to-heading t)
7745 (when (numberp arg)
7746 (setq level (org-outline-level))
7747 (when (< arg 0) (setq arg (+ level arg)))
7748 (while (> (setq level (org-outline-level)) arg)
7749 (org-up-heading-safe)))
7750 (setq beg (point)
7751 heading (org-get-heading 'no-tags))
7752 (org-end-of-subtree t t)
7753 (when (org-at-heading-p) (backward-char 1))
7754 (setq end (point)))
7755 (when (and (buffer-live-p org-last-indirect-buffer)
7756 (not (eq org-indirect-buffer-display 'new-frame))
7757 (not arg))
7758 (kill-buffer org-last-indirect-buffer))
7759 (setq ibuf (org-get-indirect-buffer cbuf heading)
7760 org-last-indirect-buffer ibuf)
7761 (cond
7762 ((or (eq org-indirect-buffer-display 'new-frame)
7763 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7764 (select-frame (make-frame))
7765 (delete-other-windows)
7766 (pop-to-buffer-same-window ibuf)
7767 (org-set-frame-title heading))
7768 ((eq org-indirect-buffer-display 'dedicated-frame)
7769 (raise-frame
7770 (select-frame (or (and org-indirect-dedicated-frame
7771 (frame-live-p org-indirect-dedicated-frame)
7772 org-indirect-dedicated-frame)
7773 (setq org-indirect-dedicated-frame (make-frame)))))
7774 (delete-other-windows)
7775 (pop-to-buffer-same-window ibuf)
7776 (org-set-frame-title (concat "Indirect: " heading)))
7777 ((eq org-indirect-buffer-display 'current-window)
7778 (pop-to-buffer-same-window ibuf))
7779 ((eq org-indirect-buffer-display 'other-window)
7780 (pop-to-buffer ibuf))
7781 (t (error "Invalid value")))
7782 (narrow-to-region beg end)
7783 (outline-show-all)
7784 (goto-char pos)
7785 (run-hook-with-args 'org-cycle-hook 'all)
7786 (and (window-live-p cwin) (select-window cwin))))
7788 (defun org-get-indirect-buffer (&optional buffer heading)
7789 (setq buffer (or buffer (current-buffer)))
7790 (let ((n 1) (base (buffer-name buffer)) bname)
7791 (while (buffer-live-p
7792 (get-buffer
7793 (setq bname
7794 (concat base "-"
7795 (if heading (concat heading "-" (number-to-string n))
7796 (number-to-string n))))))
7797 (setq n (1+ n)))
7798 (condition-case nil
7799 (make-indirect-buffer buffer bname 'clone)
7800 (error (make-indirect-buffer buffer bname)))))
7802 (defun org-set-frame-title (title)
7803 "Set the title of the current frame to the string TITLE."
7804 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7806 ;;;; Structure editing
7808 ;;; Inserting headlines
7810 (defun org--line-empty-p (n)
7811 "Is the Nth next line empty?
7813 Counts the current line as N = 1 and the previous line as N = 0;
7814 see `beginning-of-line'."
7815 (save-excursion
7816 (and (not (bobp))
7817 (or (beginning-of-line n) t)
7818 (save-match-data
7819 (looking-at "[ \t]*$")))))
7821 (defun org-previous-line-empty-p ()
7822 "Is the previous line a blank line?
7823 When NEXT is non-nil, check the next line instead."
7824 (org--line-empty-p 0))
7826 (defun org-next-line-empty-p ()
7827 "Is the previous line a blank line?
7828 When NEXT is non-nil, check the next line instead."
7829 (org--line-empty-p 2))
7831 (defun org-insert-heading (&optional arg invisible-ok top)
7832 "Insert a new heading or an item with the same depth at point.
7834 If point is at the beginning of a heading or a list item, insert
7835 a new heading or a new item above the current one. When at the
7836 beginning of a regular line of text, turn it into a heading.
7838 If point is in the middle of a line, split it and create a new
7839 headline/item with the text in the current line after point (see
7840 `org-M-RET-may-split-line' on how to modify this behavior). As
7841 a special case, on a headline, splitting can only happen on the
7842 title itself. E.g., this excludes breaking stars or tags.
7844 With a `\\[universal-argument]' prefix, set \
7845 `org-insert-heading-respect-content' to
7846 a non-nil value for the duration of the command. This forces the
7847 insertion of a heading after the current subtree, independently
7848 on the location of point.
7850 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7851 insert the heading at the end of the tree
7852 above the current heading. For example, if point is within a
7853 2nd-level heading, then it will insert a 2nd-level heading at
7854 the end of the 1st-level parent subtree.
7856 When INVISIBLE-OK is set, stop at invisible headlines when going
7857 back. This is important for non-interactive uses of the
7858 command.
7860 When optional argument TOP is non-nil, insert a level 1 heading,
7861 unconditionally."
7862 (interactive "P")
7863 (let ((itemp (and (not top) (org-in-item-p)))
7864 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7865 (respect-content (or org-insert-heading-respect-content
7866 (equal arg '(4))))
7867 (initial-content ""))
7869 (cond
7871 ((or (= (buffer-size) 0)
7872 (and (not (save-excursion
7873 (and (ignore-errors (org-back-to-heading invisible-ok))
7874 (org-at-heading-p))))
7875 (or arg (not itemp))))
7876 ;; At beginning of buffer or so high up that only a heading
7877 ;; makes sense.
7878 (cond ((and (bolp) (not respect-content)) (insert "* "))
7879 ((not respect-content)
7880 (unless may-split (end-of-line))
7881 (insert "\n* "))
7882 ((re-search-forward org-outline-regexp-bol nil t)
7883 (beginning-of-line)
7884 (insert "* \n")
7885 (backward-char))
7886 (t (goto-char (point-max))
7887 (insert "\n* ")))
7888 (run-hooks 'org-insert-heading-hook))
7890 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7893 ;; Maybe move at the end of the subtree
7894 (when (equal arg '(16))
7895 (org-up-heading-safe)
7896 (org-end-of-subtree t))
7897 ;; Insert a heading
7898 (save-restriction
7899 (widen)
7900 (let* ((level nil)
7901 (on-heading (org-at-heading-p))
7902 (empty-line-p (if on-heading
7903 (org-previous-line-empty-p)
7904 ;; We will decide later
7905 nil))
7906 ;; Get a level string to fall back on.
7907 (fix-level
7908 (if (org-before-first-heading-p) "*"
7909 (save-excursion
7910 (org-back-to-heading t)
7911 (when (org-previous-line-empty-p) (setq empty-line-p t))
7912 (looking-at org-outline-regexp)
7913 (make-string (1- (length (match-string 0))) ?*))))
7914 (stars
7915 (save-excursion
7916 (condition-case nil
7917 (if top "* "
7918 (org-back-to-heading invisible-ok)
7919 (when (and (not on-heading)
7920 (featurep 'org-inlinetask)
7921 (integerp org-inlinetask-min-level)
7922 (>= (length (match-string 0))
7923 org-inlinetask-min-level))
7924 ;; Find a heading level before the inline
7925 ;; task.
7926 (while (and (setq level (org-up-heading-safe))
7927 (>= level org-inlinetask-min-level)))
7928 (if (org-at-heading-p)
7929 (org-back-to-heading invisible-ok)
7930 (error "This should not happen")))
7931 (unless (and (save-excursion
7932 (save-match-data
7933 (org-backward-heading-same-level
7934 1 invisible-ok))
7935 (= (point) (match-beginning 0)))
7936 (not (org-next-line-empty-p)))
7937 (setq empty-line-p (or empty-line-p
7938 (org-previous-line-empty-p))))
7939 (match-string 0))
7940 (error (or fix-level "* ")))))
7941 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7942 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7944 ;; If we insert after content, move there and clean up
7945 ;; whitespace.
7946 (when respect-content
7947 (if (not (org-before-first-heading-p))
7948 (org-end-of-subtree nil t)
7949 (re-search-forward org-outline-regexp-bol)
7950 (beginning-of-line 0))
7951 (skip-chars-backward " \r\t\n")
7952 (and (not (looking-back "^\\*+" (line-beginning-position)))
7953 (looking-at "[ \t]+") (replace-match ""))
7954 (unless (eobp) (forward-char 1))
7955 (when (looking-at "^\\*")
7956 (unless (bobp) (backward-char 1))
7957 (insert "\n")))
7959 ;; If we are splitting, grab the text that should be moved
7960 ;; to the new headline.
7961 (when may-split
7962 (if (org-at-heading-p)
7963 ;; This is a heading: split intelligently (keeping
7964 ;; tags).
7965 (let ((pos (point)))
7966 (beginning-of-line)
7967 (let ((case-fold-search nil))
7968 (unless (looking-at org-complex-heading-regexp)
7969 (error "This should not happen")))
7970 (when (and (match-beginning 4)
7971 (> pos (match-beginning 4))
7972 (< pos (match-end 4)))
7973 (setq initial-content (buffer-substring pos (match-end 4)))
7974 (goto-char pos)
7975 (delete-region (point) (match-end 4))
7976 (if (looking-at "[ \t]*$")
7977 (replace-match "")
7978 (insert (make-string (length initial-content) ?\s)))
7979 (setq initial-content (org-trim initial-content)))
7980 (goto-char pos))
7981 ;; A normal line.
7982 (setq initial-content
7983 (org-trim
7984 (delete-and-extract-region (point) (line-end-position))))))
7986 ;; If we are at the beginning of the line, insert before it.
7987 ;; Otherwise, after it.
7988 (cond
7989 ((and (bolp) (looking-at "[ \t]*$")))
7990 ((bolp) (save-excursion (insert "\n")))
7991 (t (end-of-line)
7992 (insert "\n")))
7994 ;; Insert the new heading
7995 (insert stars)
7996 (just-one-space)
7997 (insert initial-content)
7998 (unless (and blank (org-previous-line-empty-p))
7999 (org-N-empty-lines-before-current (if blank 1 0)))
8000 ;; Adjust visibility, which may be messed up if we removed
8001 ;; blank lines while previous entry was hidden.
8002 (let ((bol (line-beginning-position)))
8003 (dolist (o (overlays-at (1- bol)))
8004 (when (and (eq (overlay-get o 'invisible) 'outline)
8005 (eq (overlay-end o) bol))
8006 (move-overlay o (overlay-start o) (1- bol)))))
8007 (run-hooks 'org-insert-heading-hook)))))))
8009 (defun org-N-empty-lines-before-current (N)
8010 "Make the number of empty lines before current exactly N.
8011 So this will delete or add empty lines."
8012 (save-excursion
8013 (beginning-of-line)
8014 (let ((p (point)))
8015 (skip-chars-backward " \r\t\n")
8016 (unless (bolp) (forward-line))
8017 (delete-region (point) p))
8018 (when (> N 0) (insert (make-string N ?\n)))))
8020 (defun org-get-heading (&optional no-tags no-todo)
8021 "Return the heading of the current entry, without the stars.
8022 When NO-TAGS is non-nil, don't include tags.
8023 When NO-TODO is non-nil, don't include TODO keywords."
8024 (save-excursion
8025 (org-back-to-heading t)
8026 (let ((case-fold-search nil))
8027 (cond
8028 ((and no-tags no-todo)
8029 (looking-at org-complex-heading-regexp)
8030 ;; Return value has to be a string, but match group 4 is
8031 ;; optional.
8032 (or (match-string 4) ""))
8033 (no-tags
8034 (looking-at (concat org-outline-regexp
8035 "\\(.*?\\)"
8036 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8037 (match-string 1))
8038 (no-todo
8039 (looking-at org-todo-line-regexp)
8040 (match-string 3))
8041 (t (looking-at org-heading-regexp)
8042 (match-string 2))))))
8044 (defvar orgstruct-mode) ; defined below
8046 (defun org-heading-components ()
8047 "Return the components of the current heading.
8048 This is a list with the following elements:
8049 - the level as an integer
8050 - the reduced level, different if `org-odd-levels-only' is set.
8051 - the TODO keyword, or nil
8052 - the priority character, like ?A, or nil if no priority is given
8053 - the headline text itself, or the tags string if no headline text
8054 - the tags string, or nil."
8055 (save-excursion
8056 (org-back-to-heading t)
8057 (when (let (case-fold-search)
8058 (looking-at
8059 (if orgstruct-mode
8060 org-heading-regexp
8061 org-complex-heading-regexp)))
8062 (if orgstruct-mode
8063 (list (length (match-string 1))
8064 (org-reduced-level (length (match-string 1)))
8067 (match-string 2)
8068 nil)
8069 (list (length (match-string 1))
8070 (org-reduced-level (length (match-string 1)))
8071 (match-string-no-properties 2)
8072 (and (match-end 3) (aref (match-string 3) 2))
8073 (match-string-no-properties 4)
8074 (match-string-no-properties 5))))))
8076 (defun org-get-entry ()
8077 "Get the entry text, after heading, entire subtree."
8078 (save-excursion
8079 (org-back-to-heading t)
8080 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8082 (defun org-edit-headline (&optional heading)
8083 "Edit the current headline.
8084 Set it to HEADING when provided."
8085 (interactive)
8086 (org-with-wide-buffer
8087 (org-back-to-heading t)
8088 (let ((case-fold-search nil))
8089 (when (looking-at org-complex-heading-regexp)
8090 (let* ((old (match-string-no-properties 4))
8091 (new (save-match-data
8092 (org-trim (or heading (read-string "Edit: " old))))))
8093 (unless (equal old new)
8094 (if old (replace-match new t t nil 4)
8095 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8096 (insert " " new))
8097 (org-set-tags nil t)
8098 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8100 (defun org-insert-heading-after-current ()
8101 "Insert a new heading with same level as current, after current subtree."
8102 (interactive)
8103 (org-back-to-heading)
8104 (org-insert-heading)
8105 (org-move-subtree-down)
8106 (end-of-line 1))
8108 (defun org-insert-heading-respect-content (&optional invisible-ok)
8109 "Insert heading with `org-insert-heading-respect-content' set to t."
8110 (interactive)
8111 (org-insert-heading '(4) invisible-ok))
8113 (defun org-insert-todo-heading-respect-content (&optional force-state)
8114 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8115 (interactive)
8116 (org-insert-todo-heading force-state '(4)))
8118 (defun org-insert-todo-heading (arg &optional force-heading)
8119 "Insert a new heading with the same level and TODO state as current heading.
8121 If the heading has no TODO state, or if the state is DONE, use
8122 the first state (TODO by default). Also with one prefix arg,
8123 force first state. With two prefix args, force inserting at the
8124 end of the parent subtree.
8126 When called at a plain list item, insert a new item with an
8127 unchecked check box."
8128 (interactive "P")
8129 (when (or force-heading (not (org-insert-item 'checkbox)))
8130 (org-insert-heading (or (and (equal arg '(16)) '(16))
8131 force-heading))
8132 (save-excursion
8133 (org-back-to-heading)
8134 (outline-previous-heading)
8135 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8136 (let* ((new-mark-x
8137 (if (or (equal arg '(4))
8138 (not (match-beginning 2))
8139 (member (match-string 2) org-done-keywords))
8140 (car org-todo-keywords-1)
8141 (match-string 2)))
8142 (new-mark
8144 (run-hook-with-args-until-success
8145 'org-todo-get-default-hook new-mark-x nil)
8146 new-mark-x)))
8147 (beginning-of-line 1)
8148 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8149 (if org-treat-insert-todo-heading-as-state-change
8150 (org-todo new-mark)
8151 (insert new-mark " "))))
8152 (when org-provide-todo-statistics
8153 (org-update-parent-todo-statistics))))
8155 (defun org-insert-subheading (arg)
8156 "Insert a new subheading and demote it.
8157 Works for outline headings and for plain lists alike."
8158 (interactive "P")
8159 (org-insert-heading arg)
8160 (cond
8161 ((org-at-heading-p) (org-do-demote))
8162 ((org-at-item-p) (org-indent-item))))
8164 (defun org-insert-todo-subheading (arg)
8165 "Insert a new subheading with TODO keyword or checkbox and demote it.
8166 Works for outline headings and for plain lists alike."
8167 (interactive "P")
8168 (org-insert-todo-heading arg)
8169 (cond
8170 ((org-at-heading-p) (org-do-demote))
8171 ((org-at-item-p) (org-indent-item))))
8173 ;;; Promotion and Demotion
8175 (defvar org-after-demote-entry-hook nil
8176 "Hook run after an entry has been demoted.
8177 The cursor will be at the beginning of the entry.
8178 When a subtree is being demoted, the hook will be called for each node.")
8180 (defvar org-after-promote-entry-hook nil
8181 "Hook run after an entry has been promoted.
8182 The cursor will be at the beginning of the entry.
8183 When a subtree is being promoted, the hook will be called for each node.")
8185 (defun org-promote-subtree ()
8186 "Promote the entire subtree.
8187 See also `org-promote'."
8188 (interactive)
8189 (save-excursion
8190 (org-with-limited-levels (org-map-tree 'org-promote)))
8191 (org-fix-position-after-promote))
8193 (defun org-demote-subtree ()
8194 "Demote the entire subtree.
8195 See `org-demote' and `org-promote'."
8196 (interactive)
8197 (save-excursion
8198 (org-with-limited-levels (org-map-tree 'org-demote)))
8199 (org-fix-position-after-promote))
8201 (defun org-do-promote ()
8202 "Promote the current heading higher up the tree.
8203 If the region is active in `transient-mark-mode', promote all
8204 headings in the region."
8205 (interactive)
8206 (save-excursion
8207 (if (org-region-active-p)
8208 (org-map-region 'org-promote (region-beginning) (region-end))
8209 (org-promote)))
8210 (org-fix-position-after-promote))
8212 (defun org-do-demote ()
8213 "Demote the current heading lower down the tree.
8214 If the region is active in `transient-mark-mode', demote all
8215 headings in the region."
8216 (interactive)
8217 (save-excursion
8218 (if (org-region-active-p)
8219 (org-map-region 'org-demote (region-beginning) (region-end))
8220 (org-demote)))
8221 (org-fix-position-after-promote))
8223 (defun org-fix-position-after-promote ()
8224 "Fix cursor position and indentation after demoting/promoting."
8225 (let ((pos (point)))
8226 (when (save-excursion
8227 (beginning-of-line)
8228 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8229 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8230 (cond ((eobp) (insert " "))
8231 ((eolp) (insert " "))
8232 ((equal (char-after) ?\s) (forward-char 1))))))
8234 (defun org-current-level ()
8235 "Return the level of the current entry, or nil if before the first headline.
8236 The level is the number of stars at the beginning of the
8237 headline. Use `org-reduced-level' to remove the effect of
8238 `org-odd-levels'. Unlike to `org-outline-level', this function
8239 ignores inlinetasks."
8240 (let ((level (org-with-limited-levels (org-outline-level))))
8241 (and (> level 0) level)))
8243 (defun org-get-previous-line-level ()
8244 "Return the outline depth of the last headline before the current line.
8245 Returns 0 for the first headline in the buffer, and nil if before the
8246 first headline."
8247 (and (org-current-level)
8248 (or (and (/= (line-beginning-position) (point-min))
8249 (save-excursion (beginning-of-line 0) (org-current-level)))
8250 0)))
8252 (defun org-reduced-level (l)
8253 "Compute the effective level of a heading.
8254 This takes into account the setting of `org-odd-levels-only'."
8255 (cond
8256 ((zerop l) 0)
8257 (org-odd-levels-only (1+ (floor (/ l 2))))
8258 (t l)))
8260 (defun org-level-increment ()
8261 "Return the number of stars that will be added or removed at a
8262 time to headlines when structure editing, based on the value of
8263 `org-odd-levels-only'."
8264 (if org-odd-levels-only 2 1))
8266 (defun org-get-valid-level (level &optional change)
8267 "Rectify a level change under the influence of `org-odd-levels-only'
8268 LEVEL is a current level, CHANGE is by how much the level should be
8269 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8270 even level numbers will become the next higher odd number."
8271 (if org-odd-levels-only
8272 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8273 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8274 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8275 (max 1 (+ level (or change 0)))))
8277 (defun org-promote ()
8278 "Promote the current heading higher up the tree."
8279 (org-with-wide-buffer
8280 (org-back-to-heading t)
8281 (let* ((after-change-functions (remq 'flyspell-after-change-function
8282 after-change-functions))
8283 (level (save-match-data (funcall outline-level)))
8284 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8285 (diff (abs (- level (length up-head) -1))))
8286 (cond
8287 ((and (= level 1) org-allow-promoting-top-level-subtree)
8288 (replace-match "# " nil t))
8289 ((= level 1)
8290 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8291 (t (replace-match up-head nil t)))
8292 (unless (= level 1)
8293 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8294 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8295 (run-hooks 'org-after-promote-entry-hook))))
8297 (defun org-demote ()
8298 "Demote the current heading lower down the tree."
8299 (org-with-wide-buffer
8300 (org-back-to-heading t)
8301 (let* ((after-change-functions (remq 'flyspell-after-change-function
8302 after-change-functions))
8303 (level (save-match-data (funcall outline-level)))
8304 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8305 (diff (abs (- level (length down-head) -1))))
8306 (replace-match down-head nil t)
8307 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8308 (when org-adapt-indentation (org-fixup-indentation diff))
8309 (run-hooks 'org-after-demote-entry-hook))))
8311 (defun org-cycle-level ()
8312 "Cycle the level of an empty headline through possible states.
8313 This goes first to child, then to parent, level, then up the hierarchy.
8314 After top level, it switches back to sibling level."
8315 (interactive)
8316 (let ((org-adapt-indentation nil))
8317 (when (org-point-at-end-of-empty-headline)
8318 (setq this-command 'org-cycle-level) ; Only needed for caching
8319 (let ((cur-level (org-current-level))
8320 (prev-level (org-get-previous-line-level)))
8321 (cond
8322 ;; If first headline in file, promote to top-level.
8323 ((= prev-level 0)
8324 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8325 do (org-do-promote)))
8326 ;; If same level as prev, demote one.
8327 ((= prev-level cur-level)
8328 (org-do-demote))
8329 ;; If parent is top-level, promote to top level if not already.
8330 ((= prev-level 1)
8331 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8332 do (org-do-promote)))
8333 ;; If top-level, return to prev-level.
8334 ((= cur-level 1)
8335 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8336 do (org-do-demote)))
8337 ;; If less than prev-level, promote one.
8338 ((< cur-level prev-level)
8339 (org-do-promote))
8340 ;; If deeper than prev-level, promote until higher than
8341 ;; prev-level.
8342 ((> cur-level prev-level)
8343 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8344 do (org-do-promote))))
8345 t))))
8347 (defun org-map-tree (fun)
8348 "Call FUN for every heading underneath the current one."
8349 (org-back-to-heading t)
8350 (let ((level (funcall outline-level)))
8351 (save-excursion
8352 (funcall fun)
8353 (while (and (progn
8354 (outline-next-heading)
8355 (> (funcall outline-level) level))
8356 (not (eobp)))
8357 (funcall fun)))))
8359 (defun org-map-region (fun beg end)
8360 "Call FUN for every heading between BEG and END."
8361 (let ((org-ignore-region t))
8362 (save-excursion
8363 (setq end (copy-marker end))
8364 (goto-char beg)
8365 (when (and (re-search-forward org-outline-regexp-bol nil t)
8366 (< (point) end))
8367 (funcall fun))
8368 (while (and (progn
8369 (outline-next-heading)
8370 (< (point) end))
8371 (not (eobp)))
8372 (funcall fun)))))
8374 (defun org-fixup-indentation (diff)
8375 "Change the indentation in the current entry by DIFF.
8377 DIFF is an integer. Indentation is done according to the
8378 following rules:
8380 - Planning information and property drawers are always indented
8381 according to the new level of the headline;
8383 - Footnote definitions and their contents are ignored;
8385 - Inlinetasks' boundaries are not shifted;
8387 - Empty lines are ignored;
8389 - Other lines' indentation are shifted by DIFF columns, unless
8390 it would introduce a structural change in the document, in
8391 which case no shifting is done at all.
8393 Assume point is at a heading or an inlinetask beginning."
8394 (org-with-wide-buffer
8395 (narrow-to-region (line-beginning-position)
8396 (save-excursion
8397 (if (org-with-limited-levels (org-at-heading-p))
8398 (org-with-limited-levels (outline-next-heading))
8399 (org-inlinetask-goto-end))
8400 (point)))
8401 (forward-line)
8402 ;; Indent properly planning info and property drawer.
8403 (when (looking-at-p org-planning-line-re)
8404 (org-indent-line)
8405 (forward-line))
8406 (when (looking-at org-property-drawer-re)
8407 (goto-char (match-end 0))
8408 (forward-line)
8409 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8410 (catch 'no-shift
8411 (when (zerop diff) (throw 'no-shift nil))
8412 ;; If DIFF is negative, first check if a shift is possible at all
8413 ;; (e.g., it doesn't break structure). This can only happen if
8414 ;; some contents are not properly indented.
8415 (let ((case-fold-search t))
8416 (when (< diff 0)
8417 (let ((diff (- diff))
8418 (forbidden-re (concat org-outline-regexp
8419 "\\|"
8420 (substring org-footnote-definition-re 1))))
8421 (save-excursion
8422 (while (not (eobp))
8423 (cond
8424 ((looking-at-p "[ \t]*$") (forward-line))
8425 ((and (looking-at-p org-footnote-definition-re)
8426 (let ((e (org-element-at-point)))
8427 (and (eq (org-element-type e) 'footnote-definition)
8428 (goto-char (org-element-property :end e))))))
8429 ((looking-at-p org-outline-regexp) (forward-line))
8430 ;; Give up if shifting would move before column 0 or
8431 ;; if it would introduce a headline or a footnote
8432 ;; definition.
8434 (skip-chars-forward " \t")
8435 (let ((ind (current-column)))
8436 (when (or (< ind diff)
8437 (and (= ind diff) (looking-at-p forbidden-re)))
8438 (throw 'no-shift nil)))
8439 ;; Ignore contents of example blocks and source
8440 ;; blocks if their indentation is meant to be
8441 ;; preserved. Jump to block's closing line.
8442 (beginning-of-line)
8443 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8444 (let ((e (org-element-at-point)))
8445 (and (memq (org-element-type e)
8446 '(example-block src-block))
8447 (or org-src-preserve-indentation
8448 (org-element-property :preserve-indent e))
8449 (goto-char (org-element-property :end e))
8450 (progn (skip-chars-backward " \r\t\n")
8451 (beginning-of-line)
8452 t))))
8453 (forward-line))))))))
8454 ;; Shift lines but footnote definitions, inlinetasks boundaries
8455 ;; by DIFF. Also skip contents of source or example blocks
8456 ;; when indentation is meant to be preserved.
8457 (while (not (eobp))
8458 (cond
8459 ((and (looking-at-p org-footnote-definition-re)
8460 (let ((e (org-element-at-point)))
8461 (and (eq (org-element-type e) 'footnote-definition)
8462 (goto-char (org-element-property :end e))))))
8463 ((looking-at-p org-outline-regexp) (forward-line))
8464 ((looking-at-p "[ \t]*$") (forward-line))
8466 (indent-line-to (+ (org-get-indentation) diff))
8467 (beginning-of-line)
8468 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8469 (let ((e (org-element-at-point)))
8470 (and (memq (org-element-type e)
8471 '(example-block src-block))
8472 (or org-src-preserve-indentation
8473 (org-element-property :preserve-indent e))
8474 (goto-char (org-element-property :end e))
8475 (progn (skip-chars-backward " \r\t\n")
8476 (beginning-of-line)
8477 t))))
8478 (forward-line)))))))))
8480 (defun org-convert-to-odd-levels ()
8481 "Convert an Org file with all levels allowed to one with odd levels.
8482 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8483 level 5 etc."
8484 (interactive)
8485 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8486 (let ((outline-level 'org-outline-level)
8487 (org-odd-levels-only nil) n)
8488 (save-excursion
8489 (goto-char (point-min))
8490 (while (re-search-forward "^\\*\\*+ " nil t)
8491 (setq n (- (length (match-string 0)) 2))
8492 (while (>= (setq n (1- n)) 0)
8493 (org-demote))
8494 (end-of-line 1))))))
8496 (defun org-convert-to-oddeven-levels ()
8497 "Convert an Org file with only odd levels to one with odd/even levels.
8498 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8499 file contains a section with an even level, conversion would
8500 destroy the structure of the file. An error is signaled in this
8501 case."
8502 (interactive)
8503 (goto-char (point-min))
8504 ;; First check if there are no even levels
8505 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8506 (org-show-set-visibility 'canonical)
8507 (error "Not all levels are odd in this file. Conversion not possible"))
8508 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8509 (let ((outline-regexp org-outline-regexp)
8510 (outline-level 'org-outline-level)
8511 (org-odd-levels-only nil) n)
8512 (save-excursion
8513 (goto-char (point-min))
8514 (while (re-search-forward "^\\*\\*+ " nil t)
8515 (setq n (/ (1- (length (match-string 0))) 2))
8516 (while (>= (setq n (1- n)) 0)
8517 (org-promote))
8518 (end-of-line 1))))))
8520 (defun org-tr-level (n)
8521 "Make N odd if required."
8522 (if org-odd-levels-only (1+ (/ n 2)) n))
8524 ;;; Vertical tree motion, cutting and pasting of subtrees
8526 (defun org-move-subtree-up (&optional arg)
8527 "Move the current subtree up past ARG headlines of the same level."
8528 (interactive "p")
8529 (org-move-subtree-down (- (prefix-numeric-value arg))))
8531 (defun org-move-subtree-down (&optional arg)
8532 "Move the current subtree down past ARG headlines of the same level."
8533 (interactive "p")
8534 (setq arg (prefix-numeric-value arg))
8535 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8536 'org-get-last-sibling))
8537 (ins-point (make-marker))
8538 (cnt (abs arg))
8539 (col (current-column))
8540 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8541 ;; Select the tree
8542 (org-back-to-heading)
8543 (setq beg0 (point))
8544 (save-excursion
8545 (setq ne-beg (org-back-over-empty-lines))
8546 (setq beg (point)))
8547 (save-match-data
8548 (save-excursion (outline-end-of-heading)
8549 (setq folded (org-invisible-p)))
8550 (progn (org-end-of-subtree nil t)
8551 (unless (eobp) (backward-char))))
8552 (outline-next-heading)
8553 (setq ne-end (org-back-over-empty-lines))
8554 (setq end (point))
8555 (goto-char beg0)
8556 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8557 ;; include less whitespace
8558 (save-excursion
8559 (goto-char beg)
8560 (forward-line (- ne-beg ne-end))
8561 (setq beg (point))))
8562 ;; Find insertion point, with error handling
8563 (while (> cnt 0)
8564 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8565 (progn (goto-char beg0)
8566 (user-error "Cannot move past superior level or buffer limit")))
8567 (setq cnt (1- cnt)))
8568 (when (> arg 0)
8569 ;; Moving forward - still need to move over subtree
8570 (org-end-of-subtree t t)
8571 (save-excursion
8572 (org-back-over-empty-lines)
8573 (or (bolp) (newline))))
8574 (setq ne-ins (org-back-over-empty-lines))
8575 (move-marker ins-point (point))
8576 (setq txt (buffer-substring beg end))
8577 (org-save-markers-in-region beg end)
8578 (delete-region beg end)
8579 (org-remove-empty-overlays-at beg)
8580 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8581 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8582 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8583 (let ((bbb (point)))
8584 (insert-before-markers txt)
8585 (org-reinstall-markers-in-region bbb)
8586 (move-marker ins-point bbb))
8587 (or (bolp) (insert "\n"))
8588 (setq ins-end (point))
8589 (goto-char ins-point)
8590 (org-skip-whitespace)
8591 (when (and (< arg 0)
8592 (org-first-sibling-p)
8593 (> ne-ins ne-beg))
8594 ;; Move whitespace back to beginning
8595 (save-excursion
8596 (goto-char ins-end)
8597 (let ((kill-whole-line t))
8598 (kill-line (- ne-ins ne-beg)) (point)))
8599 (insert (make-string (- ne-ins ne-beg) ?\n)))
8600 (move-marker ins-point nil)
8601 (if folded
8602 (outline-hide-subtree)
8603 (org-show-entry)
8604 (org-show-children)
8605 (org-cycle-hide-drawers 'children))
8606 (org-clean-visibility-after-subtree-move)
8607 ;; move back to the initial column we were at
8608 (move-to-column col)))
8610 (defvar org-subtree-clip ""
8611 "Clipboard for cut and paste of subtrees.
8612 This is actually only a copy of the kill, because we use the normal kill
8613 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8615 (defvar org-subtree-clip-folded nil
8616 "Was the last copied subtree folded?
8617 This is used to fold the tree back after pasting.")
8619 (defun org-cut-subtree (&optional n)
8620 "Cut the current subtree into the clipboard.
8621 With prefix arg N, cut this many sequential subtrees.
8622 This is a short-hand for marking the subtree and then cutting it."
8623 (interactive "p")
8624 (org-copy-subtree n 'cut))
8626 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8627 "Copy the current subtree it in the clipboard.
8628 With prefix arg N, copy this many sequential subtrees.
8629 This is a short-hand for marking the subtree and then copying it.
8630 If CUT is non-nil, actually cut the subtree.
8631 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8632 of some markers in the region, even if CUT is non-nil. This is
8633 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8634 (interactive "p")
8635 (let (beg end folded (beg0 (point)))
8636 (if (called-interactively-p 'any)
8637 (org-back-to-heading nil) ; take what looks like a subtree
8638 (org-back-to-heading t)) ; take what is really there
8639 (setq beg (point))
8640 (skip-chars-forward " \t\r\n")
8641 (save-match-data
8642 (if nosubtrees
8643 (outline-next-heading)
8644 (save-excursion (outline-end-of-heading)
8645 (setq folded (org-invisible-p)))
8646 (ignore-errors (org-forward-heading-same-level (1- n) t))
8647 (org-end-of-subtree t t)))
8648 ;; Include the end of an inlinetask
8649 (when (and (featurep 'org-inlinetask)
8650 (looking-at-p (concat (org-inlinetask-outline-regexp)
8651 "END[ \t]*$")))
8652 (end-of-line))
8653 (setq end (point))
8654 (goto-char beg0)
8655 (when (> end beg)
8656 (setq org-subtree-clip-folded folded)
8657 (when (or cut force-store-markers)
8658 (org-save-markers-in-region beg end))
8659 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8660 (setq org-subtree-clip (current-kill 0))
8661 (message "%s: Subtree(s) with %d characters"
8662 (if cut "Cut" "Copied")
8663 (length org-subtree-clip)))))
8665 (defun org-paste-subtree (&optional level tree for-yank remove)
8666 "Paste the clipboard as a subtree, with modification of headline level.
8667 The entire subtree is promoted or demoted in order to match a new headline
8668 level.
8670 If the cursor is at the beginning of a headline, the same level as
8671 that headline is used to paste the tree.
8673 If not, the new level is derived from the *visible* headings
8674 before and after the insertion point, and taken to be the inferior headline
8675 level of the two. So if the previous visible heading is level 3 and the
8676 next is level 4 (or vice versa), level 4 will be used for insertion.
8677 This makes sure that the subtree remains an independent subtree and does
8678 not swallow low level entries.
8680 You can also force a different level, either by using a numeric prefix
8681 argument, or by inserting the heading marker by hand. For example, if the
8682 cursor is after \"*****\", then the tree will be shifted to level 5.
8684 If optional TREE is given, use this text instead of the kill ring.
8686 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8687 move back over whitespace before inserting, and move point to the end of
8688 the inserted text when done.
8690 When REMOVE is non-nil, remove the subtree from the clipboard."
8691 (interactive "P")
8692 (setq tree (or tree (and kill-ring (current-kill 0))))
8693 (unless (org-kill-is-subtree-p tree)
8694 (user-error "%s"
8695 (substitute-command-keys
8696 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8697 (org-with-limited-levels
8698 (let* ((visp (not (org-invisible-p)))
8699 (txt tree)
8700 (^re_ "\\(\\*+\\)[ \t]*")
8701 (old-level (if (string-match org-outline-regexp-bol txt)
8702 (- (match-end 0) (match-beginning 0) 1)
8703 -1))
8704 (force-level (cond (level (prefix-numeric-value level))
8705 ((and (looking-at "[ \t]*$")
8706 (string-match
8707 "^\\*+$" (buffer-substring
8708 (point-at-bol) (point))))
8709 (- (match-end 0) (match-beginning 0)))
8710 ((and (bolp)
8711 (looking-at org-outline-regexp))
8712 (- (match-end 0) (point) 1))))
8713 (previous-level (save-excursion
8714 (condition-case nil
8715 (progn
8716 (outline-previous-visible-heading 1)
8717 (if (looking-at ^re_)
8718 (- (match-end 0) (match-beginning 0) 1)
8720 (error 1))))
8721 (next-level (save-excursion
8722 (condition-case nil
8723 (progn
8724 (or (looking-at org-outline-regexp)
8725 (outline-next-visible-heading 1))
8726 (if (looking-at ^re_)
8727 (- (match-end 0) (match-beginning 0) 1)
8729 (error 1))))
8730 (new-level (or force-level (max previous-level next-level)))
8731 (shift (if (or (= old-level -1)
8732 (= new-level -1)
8733 (= old-level new-level))
8735 (- new-level old-level)))
8736 (delta (if (> shift 0) -1 1))
8737 (func (if (> shift 0) 'org-demote 'org-promote))
8738 (org-odd-levels-only nil)
8739 beg end newend)
8740 ;; Remove the forced level indicator
8741 (when force-level
8742 (delete-region (point-at-bol) (point)))
8743 ;; Paste
8744 (beginning-of-line (if (bolp) 1 2))
8745 (setq beg (point))
8746 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8747 (insert-before-markers txt)
8748 (unless (string-suffix-p "\n" txt) (insert "\n"))
8749 (setq newend (point))
8750 (org-reinstall-markers-in-region beg)
8751 (setq end (point))
8752 (goto-char beg)
8753 (skip-chars-forward " \t\n\r")
8754 (setq beg (point))
8755 (when (and (org-invisible-p) visp)
8756 (save-excursion (outline-show-heading)))
8757 ;; Shift if necessary
8758 (unless (= shift 0)
8759 (save-restriction
8760 (narrow-to-region beg end)
8761 (while (not (= shift 0))
8762 (org-map-region func (point-min) (point-max))
8763 (setq shift (+ delta shift)))
8764 (goto-char (point-min))
8765 (setq newend (point-max))))
8766 (when (or (called-interactively-p 'interactive) for-yank)
8767 (message "Clipboard pasted as level %d subtree" new-level))
8768 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8769 kill-ring
8770 (eq org-subtree-clip (current-kill 0))
8771 org-subtree-clip-folded)
8772 ;; The tree was folded before it was killed/copied
8773 (outline-hide-subtree))
8774 (and for-yank (goto-char newend))
8775 (and remove (setq kill-ring (cdr kill-ring))))))
8777 (defun org-kill-is-subtree-p (&optional txt)
8778 "Check if the current kill is an outline subtree, or a set of trees.
8779 Returns nil if kill does not start with a headline, or if the first
8780 headline level is not the largest headline level in the tree.
8781 So this will actually accept several entries of equal levels as well,
8782 which is OK for `org-paste-subtree'.
8783 If optional TXT is given, check this string instead of the current kill."
8784 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8785 (re (org-get-limited-outline-regexp))
8786 (^re (concat "^" re))
8787 (start-level (and kill
8788 (string-match
8789 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8790 kill)
8791 (- (match-end 2) (match-beginning 2) 1)))
8792 (start (1+ (or (match-beginning 2) -1))))
8793 (if (not start-level)
8794 (progn
8795 nil) ;; does not even start with a heading
8796 (catch 'exit
8797 (while (setq start (string-match ^re kill (1+ start)))
8798 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8799 (throw 'exit nil)))
8800 t))))
8802 (defvar org-markers-to-move nil
8803 "Markers that should be moved with a cut-and-paste operation.
8804 Those markers are stored together with their positions relative to
8805 the start of the region.")
8807 (defun org-save-markers-in-region (beg end)
8808 "Check markers in region.
8809 If these markers are between BEG and END, record their position relative
8810 to BEG, so that after moving the block of text, we can put the markers back
8811 into place.
8812 This function gets called just before an entry or tree gets cut from the
8813 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8814 called immediately, to move the markers with the entries."
8815 (setq org-markers-to-move nil)
8816 (when (featurep 'org-clock)
8817 (org-clock-save-markers-for-cut-and-paste beg end))
8818 (when (featurep 'org-agenda)
8819 (org-agenda-save-markers-for-cut-and-paste beg end)))
8821 (defun org-check-and-save-marker (marker beg end)
8822 "Check if MARKER is between BEG and END.
8823 If yes, remember the marker and the distance to BEG."
8824 (when (and (marker-buffer marker)
8825 (equal (marker-buffer marker) (current-buffer))
8826 (>= marker beg) (< marker end))
8827 (push (cons marker (- marker beg)) org-markers-to-move)))
8829 (defun org-reinstall-markers-in-region (beg)
8830 "Move all remembered markers to their position relative to BEG."
8831 (dolist (x org-markers-to-move)
8832 (move-marker (car x) (+ beg (cdr x))))
8833 (setq org-markers-to-move nil))
8835 (defun org-narrow-to-subtree ()
8836 "Narrow buffer to the current subtree."
8837 (interactive)
8838 (save-excursion
8839 (save-match-data
8840 (org-with-limited-levels
8841 (narrow-to-region
8842 (progn (org-back-to-heading t) (point))
8843 (progn (org-end-of-subtree t t)
8844 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8845 (point)))))))
8847 (defun org-narrow-to-block ()
8848 "Narrow buffer to the current block."
8849 (interactive)
8850 (let* ((case-fold-search t)
8851 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8852 "^[ \t]*#\\+end_.*")))
8853 (if blockp
8854 (narrow-to-region (car blockp) (cdr blockp))
8855 (user-error "Not in a block"))))
8857 (defun org-clone-subtree-with-time-shift (n &optional shift)
8858 "Clone the task (subtree) at point N times.
8859 The clones will be inserted as siblings.
8861 In interactive use, the user will be prompted for the number of
8862 clones to be produced. If the entry has a timestamp, the user
8863 will also be prompted for a time shift, which may be a repeater
8864 as used in time stamps, for example `+3d'. To disable this,
8865 you can call the function with a universal prefix argument.
8867 When a valid repeater is given and the entry contains any time
8868 stamps, the clones will become a sequence in time, with time
8869 stamps in the subtree shifted for each clone produced. If SHIFT
8870 is nil or the empty string, time stamps will be left alone. The
8871 ID property of the original subtree is removed.
8873 In each clone, all the CLOCK entries will be removed. This
8874 prevents Org from considering that the clocked times overlap.
8876 If the original subtree did contain time stamps with a repeater,
8877 the following will happen:
8878 - the repeater will be removed in each clone
8879 - an additional clone will be produced, with the current, unshifted
8880 date(s) in the entry.
8881 - the original entry will be placed *after* all the clones, with
8882 repeater intact.
8883 - the start days in the repeater in the original entry will be shifted
8884 to past the last clone.
8885 In this way you can spell out a number of instances of a repeating task,
8886 and still retain the repeater to cover future instances of the task.
8888 As described above, N+1 clones are produced when the original
8889 subtree has a repeater. Setting N to 0, then, can be used to
8890 remove the repeater from a subtree and create a shifted clone
8891 with the original repeater."
8892 (interactive "nNumber of clones to produce: ")
8893 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8894 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8895 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8896 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8897 (shift
8898 (or shift
8899 (if (and (not (equal current-prefix-arg '(4)))
8900 (save-excursion
8901 (goto-char beg)
8902 (re-search-forward org-ts-regexp-both end-of-tree t)))
8903 (read-from-minibuffer
8904 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8905 ""))) ;No time shift
8906 (doshift
8907 (and (org-string-nw-p shift)
8908 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8909 shift)
8910 (user-error "Invalid shift specification %s" shift)))))
8911 (goto-char end-of-tree)
8912 (unless (bolp) (insert "\n"))
8913 (let* ((end (point))
8914 (template (buffer-substring beg end))
8915 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8916 (shift-what (pcase (and doshift (match-string 2 shift))
8917 (`nil nil)
8918 ("d" 'day)
8919 ("w" (setq shift-n (* 7 shift-n)) 'day)
8920 ("m" 'month)
8921 ("y" 'year)
8922 (_ (error "Unsupported time unit"))))
8923 (nmin 1)
8924 (nmax n)
8925 (n-no-remove -1)
8926 (idprop (org-entry-get nil "ID")))
8927 (when (and doshift
8928 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8929 template))
8930 (delete-region beg end)
8931 (setq end beg)
8932 (setq nmin 0)
8933 (setq nmax (1+ nmax))
8934 (setq n-no-remove nmax))
8935 (goto-char end)
8936 (cl-loop for n from nmin to nmax do
8937 (insert
8938 ;; Prepare clone.
8939 (with-temp-buffer
8940 (insert template)
8941 (org-mode)
8942 (goto-char (point-min))
8943 (org-show-subtree)
8944 (and idprop (if org-clone-delete-id
8945 (org-entry-delete nil "ID")
8946 (org-id-get-create t)))
8947 (unless (= n 0)
8948 (while (re-search-forward org-clock-line-re nil t)
8949 (delete-region (line-beginning-position)
8950 (line-beginning-position 2)))
8951 (goto-char (point-min))
8952 (while (re-search-forward org-drawer-regexp nil t)
8953 (org-remove-empty-drawer-at (point))))
8954 (goto-char (point-min))
8955 (when doshift
8956 (while (re-search-forward org-ts-regexp-both nil t)
8957 (org-timestamp-change (* n shift-n) shift-what))
8958 (unless (= n n-no-remove)
8959 (goto-char (point-min))
8960 (while (re-search-forward org-ts-regexp nil t)
8961 (save-excursion
8962 (goto-char (match-beginning 0))
8963 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8964 (delete-region (match-beginning 1) (match-end 1)))))))
8965 (buffer-string)))))
8966 (goto-char beg)))
8968 ;;; Outline Sorting
8970 (defun org-sort (with-case)
8971 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8972 Optional argument WITH-CASE means sort case-sensitively."
8973 (interactive "P")
8974 (cond
8975 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8976 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8978 (org-call-with-arg 'org-sort-entries with-case))))
8980 (defun org-sort-remove-invisible (s)
8981 "Remove invisible links from string S."
8982 (remove-text-properties 0 (length s) org-rm-props s)
8983 (while (string-match org-bracket-link-regexp s)
8984 (setq s (replace-match (if (match-end 2)
8985 (match-string 3 s)
8986 (match-string 1 s))
8987 t t s)))
8988 (let ((st (format " %s " s)))
8989 (while (string-match org-emph-re st)
8990 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8991 (setq s (substring st 1 -1)))
8994 (defvar org-priority-regexp) ; defined later in the file
8996 (defvar org-after-sorting-entries-or-items-hook nil
8997 "Hook that is run after a bunch of entries or items have been sorted.
8998 When children are sorted, the cursor is in the parent line when this
8999 hook gets called. When a region or a plain list is sorted, the cursor
9000 will be in the first entry of the sorted region/list.")
9002 (defun org-sort-entries
9003 (&optional with-case sorting-type getkey-func compare-func property
9004 interactive?)
9005 "Sort entries on a certain level of an outline tree.
9006 If there is an active region, the entries in the region are sorted.
9007 Else, if the cursor is before the first entry, sort the top-level items.
9008 Else, the children of the entry at point are sorted.
9010 Sorting can be alphabetically, numerically, by date/time as given by
9011 a time stamp, by a property, by priority order, or by a custom function.
9013 The command prompts for the sorting type unless it has been given to the
9014 function through the SORTING-TYPE argument, which needs to be a character,
9015 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9016 the precise meaning of each character:
9018 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9019 c By creation time, which is assumed to be the first inactive time stamp
9020 at the beginning of a line.
9021 d By deadline date/time.
9022 k By clocking time.
9023 n Numerically, by converting the beginning of the entry/item to a number.
9024 o By order of TODO keywords.
9025 p By priority according to the cookie.
9026 r By the value of a property.
9027 s By scheduled date/time.
9028 t By date/time, either the first active time stamp in the entry, or, if
9029 none exist, by the first inactive one.
9031 Capital letters will reverse the sort order.
9033 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9034 called with point at the beginning of the record. It must return a
9035 value that is compatible with COMPARE-FUNC, the function used to
9036 compare entries.
9038 Comparing entries ignores case by default. However, with an optional argument
9039 WITH-CASE, the sorting considers case as well.
9041 Sorting is done against the visible part of the headlines, it ignores hidden
9042 links.
9044 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9046 A non-nil value for INTERACTIVE? is used to signal that this
9047 function is being called interactively."
9048 (interactive (list current-prefix-arg nil nil nil nil t))
9049 (let ((case-func (if with-case 'identity 'downcase))
9050 (cmstr
9051 ;; The clock marker is lost when using `sort-subr', let's
9052 ;; store the clocking string.
9053 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9054 (save-excursion
9055 (goto-char org-clock-marker)
9056 (buffer-substring-no-properties (line-beginning-position)
9057 (point)))))
9058 start beg end stars re re2
9059 txt what tmp)
9060 ;; Find beginning and end of region to sort
9061 (cond
9062 ((org-region-active-p)
9063 ;; we will sort the region
9064 (setq end (region-end)
9065 what "region")
9066 (goto-char (region-beginning))
9067 (unless (org-at-heading-p) (outline-next-heading))
9068 (setq start (point)))
9069 ((or (org-at-heading-p)
9070 (ignore-errors (progn (org-back-to-heading) t)))
9071 ;; we will sort the children of the current headline
9072 (org-back-to-heading)
9073 (setq start (point)
9074 end (progn (org-end-of-subtree t t)
9075 (or (bolp) (insert "\n"))
9076 (when (>= (org-back-over-empty-lines) 1)
9077 (forward-line 1))
9078 (point))
9079 what "children")
9080 (goto-char start)
9081 (outline-show-subtree)
9082 (outline-next-heading))
9084 ;; we will sort the top-level entries in this file
9085 (goto-char (point-min))
9086 (or (org-at-heading-p) (outline-next-heading))
9087 (setq start (point))
9088 (goto-char (point-max))
9089 (beginning-of-line 1)
9090 (when (looking-at ".*?\\S-")
9091 ;; File ends in a non-white line
9092 (end-of-line 1)
9093 (insert "\n"))
9094 (setq end (point-max))
9095 (setq what "top-level")
9096 (goto-char start)
9097 (outline-show-all)))
9099 (setq beg (point))
9100 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9102 (looking-at "\\(\\*+\\)")
9103 (setq stars (match-string 1)
9104 re (concat "^" (regexp-quote stars) " +")
9105 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9106 txt (buffer-substring beg end))
9107 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9108 (when (and (not (equal stars "*")) (string-match re2 txt))
9109 (user-error "Region to sort contains a level above the first entry"))
9111 (unless sorting-type
9112 (message
9113 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9114 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9115 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9116 what)
9117 (setq sorting-type (read-char-exclusive)))
9119 (unless getkey-func
9120 (and (= (downcase sorting-type) ?f)
9121 (setq getkey-func
9122 (or (and interactive?
9123 (org-read-function
9124 "Function for extracting keys: "))
9125 (error "Missing key extractor")))))
9127 (and (= (downcase sorting-type) ?r)
9128 (not property)
9129 (setq property
9130 (completing-read "Property: "
9131 (mapcar #'list (org-buffer-property-keys t))
9132 nil t)))
9134 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9135 (message "Sorting entries...")
9137 (save-restriction
9138 (narrow-to-region start end)
9139 (let ((dcst (downcase sorting-type))
9140 (case-fold-search nil)
9141 (now (current-time)))
9142 (sort-subr
9143 (/= dcst sorting-type)
9144 ;; This function moves to the beginning character of the "record" to
9145 ;; be sorted.
9146 (lambda nil
9147 (if (re-search-forward re nil t)
9148 (goto-char (match-beginning 0))
9149 (goto-char (point-max))))
9150 ;; This function moves to the last character of the "record" being
9151 ;; sorted.
9152 (lambda nil
9153 (save-match-data
9154 (condition-case nil
9155 (outline-forward-same-level 1)
9156 (error
9157 (goto-char (point-max))))))
9158 ;; This function returns the value that gets sorted against.
9159 (lambda nil
9160 (cond
9161 ((= dcst ?n)
9162 (if (looking-at org-complex-heading-regexp)
9163 (string-to-number (org-sort-remove-invisible (match-string 4)))
9164 nil))
9165 ((= dcst ?a)
9166 (if (looking-at org-complex-heading-regexp)
9167 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9168 nil))
9169 ((= dcst ?k)
9170 (or (get-text-property (point) :org-clock-minutes) 0))
9171 ((= dcst ?t)
9172 (let ((end (save-excursion (outline-next-heading) (point))))
9173 (if (or (re-search-forward org-ts-regexp end t)
9174 (re-search-forward org-ts-regexp-both end t))
9175 (org-time-string-to-seconds (match-string 0))
9176 (float-time now))))
9177 ((= dcst ?c)
9178 (let ((end (save-excursion (outline-next-heading) (point))))
9179 (if (re-search-forward
9180 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9181 end t)
9182 (org-time-string-to-seconds (match-string 0))
9183 (float-time now))))
9184 ((= dcst ?s)
9185 (let ((end (save-excursion (outline-next-heading) (point))))
9186 (if (re-search-forward org-scheduled-time-regexp end t)
9187 (org-time-string-to-seconds (match-string 1))
9188 (float-time now))))
9189 ((= dcst ?d)
9190 (let ((end (save-excursion (outline-next-heading) (point))))
9191 (if (re-search-forward org-deadline-time-regexp end t)
9192 (org-time-string-to-seconds (match-string 1))
9193 (float-time now))))
9194 ((= dcst ?p)
9195 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9196 (string-to-char (match-string 2))
9197 org-default-priority))
9198 ((= dcst ?r)
9199 (or (org-entry-get nil property) ""))
9200 ((= dcst ?o)
9201 (when (looking-at org-complex-heading-regexp)
9202 (let* ((m (match-string 2))
9203 (s (if (member m org-done-keywords) '- '+)))
9204 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9205 ((= dcst ?f)
9206 (if getkey-func
9207 (progn
9208 (setq tmp (funcall getkey-func))
9209 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9210 tmp)
9211 (error "Invalid key function `%s'" getkey-func)))
9212 (t (error "Invalid sorting type `%c'" sorting-type))))
9214 (cond
9215 ((= dcst ?a) 'string<)
9216 ((= dcst ?f)
9217 (or compare-func
9218 (and interactive?
9219 (org-read-function
9220 (concat "Function for comparing keys "
9221 "(empty for default `sort-subr' predicate): ")
9222 'allow-empty))))
9223 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9224 (run-hooks 'org-after-sorting-entries-or-items-hook)
9225 ;; Reset the clock marker if needed
9226 (when cmstr
9227 (save-excursion
9228 (goto-char start)
9229 (search-forward cmstr nil t)
9230 (move-marker org-clock-marker (point))))
9231 (message "Sorting entries...done")))
9233 ;;; The orgstruct minor mode
9235 ;; Define a minor mode which can be used in other modes in order to
9236 ;; integrate the Org mode structure editing commands.
9238 ;; This is really a hack, because the Org mode structure commands use
9239 ;; keys which normally belong to the major mode. Here is how it
9240 ;; works: The minor mode defines all the keys necessary to operate the
9241 ;; structure commands, but wraps the commands into a function which
9242 ;; tests if the cursor is currently at a headline or a plain list
9243 ;; item. If that is the case, the structure command is used,
9244 ;; temporarily setting many Org mode variables like regular
9245 ;; expressions for filling etc. However, when any of those keys is
9246 ;; used at a different location, function uses `key-binding' to look
9247 ;; up if the key has an associated command in another currently active
9248 ;; keymap (minor modes, major mode, global), and executes that
9249 ;; command. There might be problems if any of the keys is otherwise
9250 ;; used as a prefix key.
9252 (defcustom orgstruct-heading-prefix-regexp ""
9253 "Regexp that matches the custom prefix of Org headlines in
9254 orgstruct(++)-mode."
9255 :group 'org
9256 :version "24.4"
9257 :package-version '(Org . "8.3")
9258 :type 'regexp)
9259 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9261 (defcustom orgstruct-setup-hook nil
9262 "Hook run after orgstruct-mode-map is filled."
9263 :group 'org
9264 :version "24.4"
9265 :package-version '(Org . "8.0")
9266 :type 'hook)
9268 (defvar orgstruct-initialized nil)
9270 (defvar org-local-vars nil
9271 "List of local variables, for use by `orgstruct-mode'.")
9273 ;;;###autoload
9274 (define-minor-mode orgstruct-mode
9275 "Toggle the minor mode `orgstruct-mode'.
9276 This mode is for using Org mode structure commands in other
9277 modes. The following keys behave as if Org mode were active, if
9278 the cursor is on a headline, or on a plain list item (both as
9279 defined by Org mode)."
9280 nil " OrgStruct" (make-sparse-keymap)
9281 (funcall (if orgstruct-mode
9282 'add-to-invisibility-spec
9283 'remove-from-invisibility-spec)
9284 '(outline . t))
9285 (when orgstruct-mode
9286 (org-load-modules-maybe)
9287 (unless orgstruct-initialized
9288 (orgstruct-setup)
9289 (setq orgstruct-initialized t))))
9291 ;;;###autoload
9292 (defun turn-on-orgstruct ()
9293 "Unconditionally turn on `orgstruct-mode'."
9294 (orgstruct-mode 1))
9296 (defvar-local orgstruct-is-++ nil
9297 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9298 (defvar-local org-fb-vars nil)
9299 (defun orgstruct++-mode (&optional arg)
9300 "Toggle `orgstruct-mode', the enhanced version of it.
9301 In addition to setting orgstruct-mode, this also exports all
9302 indentation and autofilling variables from Org mode into the
9303 buffer. It will also recognize item context in multiline items."
9304 (interactive "P")
9305 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9306 (if (< arg 1)
9307 (progn (orgstruct-mode -1)
9308 (dolist (v org-fb-vars)
9309 (set (make-local-variable (car v))
9310 (if (eq (car-safe (cadr v)) 'quote)
9311 (cl-cadadr v)
9312 (nth 1 v)))))
9313 (orgstruct-mode 1)
9314 (setq org-fb-vars nil)
9315 (unless org-local-vars
9316 (setq org-local-vars (org-get-local-variables)))
9317 (let (var val)
9318 (dolist (x org-local-vars)
9319 (when (string-match
9320 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9321 \\|fill-prefix\\|indent-\\)"
9322 (symbol-name (car x)))
9323 (setq var (car x) val (nth 1 x))
9324 (push (list var `(quote ,(eval var))) org-fb-vars)
9325 (set (make-local-variable var)
9326 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9327 (setq-local orgstruct-is-++ t))))
9329 ;;;###autoload
9330 (defun turn-on-orgstruct++ ()
9331 "Unconditionally turn on `orgstruct++-mode'."
9332 (orgstruct++-mode 1))
9334 (defun orgstruct-error ()
9335 "Error when there is no default binding for a structure key."
9336 (interactive)
9337 (funcall (if (fboundp 'user-error)
9338 'user-error
9339 'error)
9340 "This key has no function outside structure elements"))
9342 (defun orgstruct-setup ()
9343 "Setup orgstruct keymap."
9344 (dolist (cell '((org-demote . t)
9345 (org-metaleft . t)
9346 (org-metaright . t)
9347 (org-promote . t)
9348 (org-shiftmetaleft . t)
9349 (org-shiftmetaright . t)
9350 org-backward-element
9351 org-backward-heading-same-level
9352 org-ctrl-c-ret
9353 org-ctrl-c-minus
9354 org-ctrl-c-star
9355 org-cycle
9356 org-force-cycle-archived
9357 org-forward-heading-same-level
9358 org-insert-heading
9359 org-insert-heading-respect-content
9360 org-kill-note-or-show-branches
9361 org-mark-subtree
9362 org-meta-return
9363 org-metadown
9364 org-metaup
9365 org-narrow-to-subtree
9366 org-promote-subtree
9367 org-reveal
9368 org-shiftdown
9369 org-shiftleft
9370 org-shiftmetadown
9371 org-shiftmetaup
9372 org-shiftright
9373 org-shifttab
9374 org-shifttab
9375 org-shiftup
9376 org-show-children
9377 org-show-subtree
9378 org-sort
9379 org-up-element
9380 outline-demote
9381 outline-next-visible-heading
9382 outline-previous-visible-heading
9383 outline-promote
9384 outline-up-heading))
9385 (let ((f (or (car-safe cell) cell))
9386 (disable-when-heading-prefix (cdr-safe cell)))
9387 (when (fboundp f)
9388 (let ((new-bindings))
9389 (dolist (binding (nconc (where-is-internal f org-mode-map)
9390 (where-is-internal f outline-mode-map)))
9391 (push binding new-bindings)
9392 ;; TODO use local-function-key-map
9393 (dolist (rep '(("<tab>" . "TAB")
9394 ("<return>" . "RET")
9395 ("<escape>" . "ESC")
9396 ("<delete>" . "DEL")))
9397 (setq binding (read-kbd-macro
9398 (let ((case-fold-search))
9399 (replace-regexp-in-string
9400 (regexp-quote (cdr rep))
9401 (car rep)
9402 (key-description binding)))))
9403 (cl-pushnew binding new-bindings :test 'equal)))
9404 (dolist (binding new-bindings)
9405 (let ((key (lookup-key orgstruct-mode-map binding)))
9406 (when (or (not key) (numberp key))
9407 (ignore-errors
9408 (org-defkey orgstruct-mode-map
9409 binding
9410 (orgstruct-make-binding
9411 f binding disable-when-heading-prefix))))))))))
9412 (run-hooks 'orgstruct-setup-hook))
9414 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9415 "Create a function for binding in the structure minor mode.
9416 FUN is the command to call inside a table. KEY is the key that
9417 should be checked in for a command to execute outside of tables.
9418 Non-nil `disable-when-heading-prefix' means to disable the command
9419 if `orgstruct-heading-prefix-regexp' is not empty."
9420 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9421 (let ((nname name)
9422 (i 0))
9423 (while (fboundp (intern nname))
9424 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9425 (setq name (intern nname)))
9426 (eval
9427 (let ((bindings '((org-heading-regexp
9428 (concat "^"
9429 orgstruct-heading-prefix-regexp
9430 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9431 (org-outline-regexp
9432 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9433 (org-outline-regexp-bol
9434 (concat "^" org-outline-regexp))
9435 (outline-regexp org-outline-regexp)
9436 (outline-heading-end-regexp "\n")
9437 (outline-level 'org-outline-level)
9438 (outline-heading-alist))))
9439 `(defun ,name (arg)
9440 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9441 "Outside of structure, run the binding of `"
9442 (key-description key) "'."
9443 (when disable-when-heading-prefix
9444 (concat
9445 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9446 "back to the default binding due to limitations of Org's implementation of\n"
9447 "`" (symbol-name fun) "'.")))
9448 (interactive "p")
9449 (let* ((disable
9450 ,(and disable-when-heading-prefix
9451 '(not (string= orgstruct-heading-prefix-regexp ""))))
9452 (fallback
9453 (or disable
9454 (not
9455 (let* ,bindings
9456 (org-context-p 'headline 'item
9457 ,(when (memq fun
9458 '(org-insert-heading
9459 org-insert-heading-respect-content
9460 org-meta-return))
9461 '(when orgstruct-is-++
9462 'item-body))))))))
9463 (if fallback
9464 (let* ((orgstruct-mode)
9465 (binding
9466 (let ((key ,key))
9467 (catch 'exit
9468 (dolist
9469 (rep
9470 '(nil
9471 ("<\\([^>]*\\)tab>" . "\\1TAB")
9472 ("<\\([^>]*\\)return>" . "\\1RET")
9473 ("<\\([^>]*\\)escape>" . "\\1ESC")
9474 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9475 nil)
9476 (when rep
9477 (setq key (read-kbd-macro
9478 (let ((case-fold-search))
9479 (replace-regexp-in-string
9480 (car rep)
9481 (cdr rep)
9482 (key-description key))))))
9483 (when (key-binding key)
9484 (throw 'exit (key-binding key))))))))
9485 (if (keymapp binding)
9486 (org-set-transient-map binding)
9487 (let ((func (or binding
9488 (unless disable
9489 'orgstruct-error))))
9490 (when func
9491 (call-interactively func)))))
9492 (org-run-like-in-org-mode
9493 (lambda ()
9494 (interactive)
9495 (let* ,bindings
9496 (call-interactively ',fun)))))))))
9497 name))
9499 (defun org-contextualize-keys (alist contexts)
9500 "Return valid elements in ALIST depending on CONTEXTS.
9502 `org-agenda-custom-commands' or `org-capture-templates' are the
9503 values used for ALIST, and `org-agenda-custom-commands-contexts'
9504 or `org-capture-templates-contexts' are the associated contexts
9505 definitions."
9506 (let ((contexts
9507 ;; normalize contexts
9508 (mapcar
9509 (lambda(c) (cond ((listp (cadr c))
9510 (list (car c) (car c) (nth 1 c)))
9511 ((string= "" (cadr c))
9512 (list (car c) (car c) (nth 2 c)))
9513 (t c)))
9514 contexts))
9515 (a alist) r s)
9516 ;; loop over all commands or templates
9517 (dolist (c a)
9518 (let (vrules repl)
9519 (cond
9520 ((not (assoc (car c) contexts))
9521 (push c r))
9522 ((and (assoc (car c) contexts)
9523 (setq vrules (org-contextualize-validate-key
9524 (car c) contexts)))
9525 (mapc (lambda (vr)
9526 (unless (equal (car vr) (cadr vr))
9527 (setq repl vr)))
9528 vrules)
9529 (if (not repl) (push c r)
9530 (push (cadr repl) s)
9531 (push
9532 (cons (car c)
9533 (cdr (or (assoc (cadr repl) alist)
9534 (error "Undefined key `%s' as contextual replacement for `%s'"
9535 (cadr repl) (car c)))))
9536 r))))))
9537 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9538 (delq
9540 (delete-dups
9541 (mapcar (lambda (x)
9542 (let ((tpl (car x)))
9543 (unless (delq
9545 (mapcar (lambda (y)
9546 (equal y tpl))
9548 x)))
9549 (reverse r))))))
9551 (defun org-contextualize-validate-key (key contexts)
9552 "Check CONTEXTS for agenda or capture KEY."
9553 (let (res)
9554 (dolist (r contexts)
9555 (dolist (rr (car (last r)))
9556 (when
9557 (and (equal key (car r))
9558 (if (functionp rr) (funcall rr)
9559 (or (and (eq (car rr) 'in-file)
9560 (buffer-file-name)
9561 (string-match (cdr rr) (buffer-file-name)))
9562 (and (eq (car rr) 'in-mode)
9563 (string-match (cdr rr) (symbol-name major-mode)))
9564 (and (eq (car rr) 'in-buffer)
9565 (string-match (cdr rr) (buffer-name)))
9566 (when (and (eq (car rr) 'not-in-file)
9567 (buffer-file-name))
9568 (not (string-match (cdr rr) (buffer-file-name))))
9569 (when (eq (car rr) 'not-in-mode)
9570 (not (string-match (cdr rr) (symbol-name major-mode))))
9571 (when (eq (car rr) 'not-in-buffer)
9572 (not (string-match (cdr rr) (buffer-name)))))))
9573 (push r res))))
9574 (delete-dups (delq nil res))))
9576 (defun org-context-p (&rest contexts)
9577 "Check if local context is any of CONTEXTS.
9578 Possible values in the list of contexts are `table', `headline', and `item'."
9579 (let ((pos (point)))
9580 (goto-char (point-at-bol))
9581 (prog1 (or (and (memq 'table contexts)
9582 (looking-at "[ \t]*|"))
9583 (and (memq 'headline contexts)
9584 (looking-at org-outline-regexp))
9585 (and (memq 'item contexts)
9586 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9587 (and (memq 'item-body contexts)
9588 (org-in-item-p)))
9589 (goto-char pos))))
9591 (defconst org-unique-local-variables
9592 '(org-element--cache
9593 org-element--cache-objects
9594 org-element--cache-sync-keys
9595 org-element--cache-sync-requests
9596 org-element--cache-sync-timer)
9597 "List of local variables that cannot be transferred to another buffer.")
9599 (defun org-get-local-variables ()
9600 "Return a list of all local variables in an Org mode buffer."
9601 (delq nil
9602 (mapcar
9603 (lambda (x)
9604 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9605 (name (car binding)))
9606 (and (not (get name 'org-state))
9607 (not (memq name org-unique-local-variables))
9608 (string-match-p
9609 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9610 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9611 (symbol-name name))
9612 binding)))
9613 (with-temp-buffer
9614 (org-mode)
9615 (buffer-local-variables)))))
9617 (defun org-clone-local-variables (from-buffer &optional regexp)
9618 "Clone local variables from FROM-BUFFER.
9619 Optional argument REGEXP selects variables to clone."
9620 (dolist (pair (buffer-local-variables from-buffer))
9621 (pcase pair
9622 (`(,name . ,value) ;ignore unbound variables
9623 (when (and (not (memq name org-unique-local-variables))
9624 (or (null regexp) (string-match-p regexp (symbol-name name))))
9625 (set (make-local-variable name) value))))))
9627 ;;;###autoload
9628 (defun org-run-like-in-org-mode (cmd)
9629 "Run a command, pretending that the current buffer is in Org mode.
9630 This will temporarily bind local variables that are typically bound in
9631 Org mode to the values they have in Org mode, and then interactively
9632 call CMD."
9633 (org-load-modules-maybe)
9634 (unless org-local-vars
9635 (setq org-local-vars (org-get-local-variables)))
9636 (let (binds)
9637 (dolist (var org-local-vars)
9638 (when (or (not (boundp (car var)))
9639 (eq (symbol-value (car var))
9640 (default-value (car var))))
9641 (push (list (car var) `(quote ,(cadr var))) binds)))
9642 (eval `(let ,binds
9643 (call-interactively (quote ,cmd))))))
9645 (defun org-get-category (&optional pos force-refresh)
9646 "Get the category applying to position POS."
9647 (save-match-data
9648 (when force-refresh (org-refresh-category-properties))
9649 (let ((pos (or pos (point))))
9650 (or (get-text-property pos 'org-category)
9651 (progn (org-refresh-category-properties)
9652 (get-text-property pos 'org-category))))))
9654 ;;; Refresh properties
9656 (defun org-refresh-properties (dprop tprop)
9657 "Refresh buffer text properties.
9658 DPROP is the drawer property and TPROP is either the
9659 corresponding text property to set, or an alist with each element
9660 being a text property (as a symbol) and a function to apply to
9661 the value of the drawer property."
9662 (let* ((case-fold-search t)
9663 (inhibit-read-only t)
9664 (inherit? (org-property-inherit-p dprop))
9665 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9666 (global (and inherit? (org--property-global-value dprop nil))))
9667 (org-with-silent-modifications
9668 (org-with-point-at 1
9669 ;; Set global values (e.g., values defined through
9670 ;; "#+PROPERTY:" keywords) to the whole buffer.
9671 (when global (put-text-property (point-min) (point-max) tprop global))
9672 ;; Set local values.
9673 (while (re-search-forward property-re nil t)
9674 (when (org-at-property-p)
9675 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9676 (outline-next-heading))))))
9678 (defun org-refresh-property (tprop p &optional inherit)
9679 "Refresh the buffer text property TPROP from the drawer property P.
9680 The refresh happens only for the current headline, or the whole
9681 sub-tree if optional argument INHERIT is non-nil."
9682 (unless (org-before-first-heading-p)
9683 (save-excursion
9684 (org-back-to-heading t)
9685 (let ((start (point))
9686 (end (save-excursion
9687 (if inherit (org-end-of-subtree t t)
9688 (or (outline-next-heading) (point-max))))))
9689 (if (symbolp tprop)
9690 ;; TPROP is a text property symbol.
9691 (put-text-property start end tprop p)
9692 ;; TPROP is an alist with (property . function) elements.
9693 (pcase-dolist (`(,prop . ,f) tprop)
9694 (put-text-property start end prop (funcall f p))))))))
9696 (defun org-refresh-category-properties ()
9697 "Refresh category text properties in the buffer."
9698 (let ((case-fold-search t)
9699 (inhibit-read-only t)
9700 (default-category
9701 (cond ((null org-category)
9702 (if buffer-file-name
9703 (file-name-sans-extension
9704 (file-name-nondirectory buffer-file-name))
9705 "???"))
9706 ((symbolp org-category) (symbol-name org-category))
9707 (t org-category))))
9708 (org-with-silent-modifications
9709 (org-with-wide-buffer
9710 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9711 ;; This is the default category for the buffer. If none is
9712 ;; found, fall-back to `org-category' or buffer file name.
9713 (put-text-property
9714 (point-min) (point-max)
9715 'org-category
9716 (catch 'buffer-category
9717 (goto-char (point-max))
9718 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9719 (let ((element (org-element-at-point)))
9720 (when (eq (org-element-type element) 'keyword)
9721 (throw 'buffer-category
9722 (org-element-property :value element)))))
9723 default-category))
9724 ;; Set sub-tree specific categories.
9725 (goto-char (point-min))
9726 (let ((regexp (org-re-property "CATEGORY")))
9727 (while (re-search-forward regexp nil t)
9728 (let ((value (match-string-no-properties 3)))
9729 (when (org-at-property-p)
9730 (put-text-property
9731 (save-excursion (org-back-to-heading t) (point))
9732 (save-excursion (org-end-of-subtree t t) (point))
9733 'org-category
9734 value)))))))))
9736 (defun org-refresh-stats-properties ()
9737 "Refresh stats text properties in the buffer."
9738 (org-with-silent-modifications
9739 (org-with-point-at 1
9740 (let ((regexp (concat org-outline-regexp-bol
9741 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9742 (while (re-search-forward regexp nil t)
9743 (let* ((numerator (string-to-number (match-string 1)))
9744 (denominator (and (match-end 2)
9745 (string-to-number (match-string 2))))
9746 (stats (cond ((not denominator) numerator) ;percent
9747 ((= denominator 0) 0)
9748 (t (/ (* numerator 100) denominator)))))
9749 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9750 'org-stats stats)))))))
9752 (defun org-refresh-effort-properties ()
9753 "Refresh effort properties"
9754 (org-refresh-properties
9755 org-effort-property
9756 '((effort . identity)
9757 (effort-minutes . org-duration-string-to-minutes))))
9759 ;;;; Link Stuff
9761 ;;; Link abbreviations
9763 (defun org-link-expand-abbrev (link)
9764 "Apply replacements as defined in `org-link-abbrev-alist'."
9765 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9766 (let* ((key (match-string 1 link))
9767 (as (or (assoc key org-link-abbrev-alist-local)
9768 (assoc key org-link-abbrev-alist)))
9769 (tag (and (match-end 2) (match-string 3 link)))
9770 rpl)
9771 (if (not as)
9772 link
9773 (setq rpl (cdr as))
9774 (cond
9775 ((symbolp rpl) (funcall rpl tag))
9776 ((string-match "%(\\([^)]+\\))" rpl)
9777 (replace-match
9778 (save-match-data
9779 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9780 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9781 ((string-match "%h" rpl)
9782 (replace-match (url-hexify-string (or tag "")) t t rpl))
9783 (t (concat rpl tag)))))
9784 link))
9786 ;;; Storing and inserting links
9788 (defvar org-insert-link-history nil
9789 "Minibuffer history for links inserted with `org-insert-link'.")
9791 (defvar org-stored-links nil
9792 "Contains the links stored with `org-store-link'.")
9794 (defvar org-store-link-plist nil
9795 "Plist with info about the most recently link created with `org-store-link'.")
9797 (defun org-store-link-functions ()
9798 "Return a list of functions that are called to create and store a link.
9799 The functions defined in the :store property of
9800 `org-link-parameters'.
9802 Each function will be called in turn until one returns a non-nil
9803 value. Each function should check if it is responsible for
9804 creating this link (for example by looking at the major mode).
9805 If not, it must exit and return nil. If yes, it should return
9806 a non-nil value after calling `org-store-link-props' with a list
9807 of properties and values. Special properties are:
9809 :type The link prefix, like \"http\". This must be given.
9810 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9811 This is obligatory as well.
9812 :description Optional default description for the second pair
9813 of brackets in an Org mode link. The user can still change
9814 this when inserting this link into an Org mode buffer.
9816 In addition to these, any additional properties can be specified
9817 and then used in capture templates."
9818 (cl-loop for link in org-link-parameters
9819 with store-func
9820 do (setq store-func (org-link-get-parameter (car link) :store))
9821 if store-func
9822 collect store-func))
9824 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9825 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9827 ;;;###autoload
9828 (defun org-store-link (arg)
9829 "Store an org-link to the current location.
9830 \\<org-mode-map>
9831 This link is added to `org-stored-links' and can later be inserted
9832 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9834 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9835 A single
9836 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9837 `org-gnus-prefer-web-links' for links to Usenet articles.
9839 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9840 skipping storing functions that are not
9841 part of Org core.
9843 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9844 prefix ARG forces storing a link for each line in the
9845 active region."
9846 (interactive "P")
9847 (org-load-modules-maybe)
9848 (if (and (equal arg '(64)) (org-region-active-p))
9849 (save-excursion
9850 (let ((end (region-end)))
9851 (goto-char (region-beginning))
9852 (set-mark (point))
9853 (while (< (point-at-eol) end)
9854 (move-end-of-line 1) (activate-mark)
9855 (let (current-prefix-arg)
9856 (call-interactively 'org-store-link))
9857 (move-beginning-of-line 2)
9858 (set-mark (point)))))
9859 (setq org-store-link-plist nil)
9860 (let (link cpltxt desc description search
9861 txt custom-id agenda-link sfuns sfunsn)
9862 (cond
9864 ;; Store a link using an external link type
9865 ((and (not (equal arg '(16)))
9866 (setq sfuns
9867 (delq
9868 nil (mapcar (lambda (f)
9869 (let (fs) (if (funcall f) (push f fs))))
9870 (org-store-link-functions)))
9871 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9872 (or (and (cdr sfuns)
9873 (funcall (intern
9874 (completing-read
9875 "Which function for creating the link? "
9876 sfunsn nil t (car sfunsn)))))
9877 (funcall (caar sfuns)))
9878 (setq link (plist-get org-store-link-plist :link)
9879 desc (or (plist-get org-store-link-plist
9880 :description)
9881 link))))
9883 ;; Store a link from a source code buffer.
9884 ((org-src-edit-buffer-p)
9885 (let ((coderef-format (org-src-coderef-format)))
9886 (cond ((save-excursion
9887 (beginning-of-line)
9888 (looking-at (org-src-coderef-regexp coderef-format)))
9889 (setq link (format "(%s)" (match-string-no-properties 3))))
9890 ((called-interactively-p 'any)
9891 (let ((label (read-string "Code line label: ")))
9892 (end-of-line)
9893 (setq link (format coderef-format label))
9894 (let ((gc (- 79 (length link))))
9895 (if (< (current-column) gc)
9896 (org-move-to-column gc t)
9897 (insert " ")))
9898 (insert link)
9899 (setq link (concat "(" label ")"))
9900 (setq desc nil)))
9901 (t (setq link nil)))))
9903 ;; We are in the agenda, link to referenced location
9904 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9905 (let ((m (or (get-text-property (point) 'org-hd-marker)
9906 (get-text-property (point) 'org-marker))))
9907 (when m
9908 (org-with-point-at m
9909 (setq agenda-link
9910 (if (called-interactively-p 'any)
9911 (call-interactively 'org-store-link)
9912 (org-store-link nil)))))))
9914 ((eq major-mode 'calendar-mode)
9915 (let ((cd (calendar-cursor-to-date)))
9916 (setq link
9917 (format-time-string
9918 (car org-time-stamp-formats)
9919 (apply 'encode-time
9920 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9921 nil nil nil))))
9922 (org-store-link-props :type "calendar" :date cd)))
9924 ((eq major-mode 'help-mode)
9925 (setq link (concat "help:" (save-excursion
9926 (goto-char (point-min))
9927 (looking-at "^[^ ]+")
9928 (match-string 0))))
9929 (org-store-link-props :type "help"))
9931 ((eq major-mode 'w3-mode)
9932 (setq cpltxt (if (and (buffer-name)
9933 (not (string-match "Untitled" (buffer-name))))
9934 (buffer-name)
9935 (url-view-url t))
9936 link (url-view-url t))
9937 (org-store-link-props :type "w3" :url (url-view-url t)))
9939 ((eq major-mode 'image-mode)
9940 (setq cpltxt (concat "file:"
9941 (abbreviate-file-name buffer-file-name))
9942 link cpltxt)
9943 (org-store-link-props :type "image" :file buffer-file-name))
9945 ;; In dired, store a link to the file of the current line
9946 ((derived-mode-p 'dired-mode)
9947 (let ((file (dired-get-filename nil t)))
9948 (setq file (if file
9949 (abbreviate-file-name
9950 (expand-file-name (dired-get-filename nil t)))
9951 ;; otherwise, no file so use current directory.
9952 default-directory))
9953 (setq cpltxt (concat "file:" file)
9954 link cpltxt)))
9956 ((setq search (run-hook-with-args-until-success
9957 'org-create-file-search-functions))
9958 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9959 "::" search))
9960 (setq cpltxt (or description link)))
9962 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9963 (org-with-limited-levels
9964 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9965 (cond
9966 ;; Store a link using the target at point
9967 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9968 (setq cpltxt
9969 (concat "file:"
9970 (abbreviate-file-name
9971 (buffer-file-name (buffer-base-buffer)))
9972 "::" (match-string 1))
9973 link cpltxt))
9974 ((and (featurep 'org-id)
9975 (or (eq org-id-link-to-org-use-id t)
9976 (and (called-interactively-p 'any)
9977 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9978 (and (eq org-id-link-to-org-use-id
9979 'create-if-interactive-and-no-custom-id)
9980 (not custom-id))))
9981 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9982 ;; Store a link using the ID at point
9983 (setq link (condition-case nil
9984 (prog1 (org-id-store-link)
9985 (setq desc (or (plist-get org-store-link-plist
9986 :description)
9987 "")))
9988 (error
9989 ;; Probably before first headline, link only to file
9990 (concat "file:"
9991 (abbreviate-file-name
9992 (buffer-file-name (buffer-base-buffer))))))))
9994 ;; Just link to current headline
9995 (setq cpltxt (concat "file:"
9996 (abbreviate-file-name
9997 (buffer-file-name (buffer-base-buffer)))))
9998 ;; Add a context search string
9999 (when (org-xor org-context-in-file-links
10000 (equal arg '(4)))
10001 (let* ((element (org-element-at-point))
10002 (name (org-element-property :name element)))
10003 (setq txt (cond
10004 ((org-at-heading-p) nil)
10005 (name)
10006 ((org-region-active-p)
10007 (buffer-substring (region-beginning) (region-end)))))
10008 (when (or (null txt) (string-match "\\S-" txt))
10009 (setq cpltxt
10010 (concat cpltxt "::"
10011 (condition-case nil
10012 (org-make-org-heading-search-string txt)
10013 (error "")))
10014 desc (or name
10015 (nth 4 (ignore-errors (org-heading-components)))
10016 "NONE")))))
10017 (when (string-match "::\\'" cpltxt)
10018 (setq cpltxt (substring cpltxt 0 -2)))
10019 (setq link cpltxt)))))
10021 ((buffer-file-name (buffer-base-buffer))
10022 ;; Just link to this file here.
10023 (setq cpltxt (concat "file:"
10024 (abbreviate-file-name
10025 (buffer-file-name (buffer-base-buffer)))))
10026 ;; Add a context string.
10027 (when (org-xor org-context-in-file-links
10028 (equal arg '(4)))
10029 (setq txt (if (org-region-active-p)
10030 (buffer-substring (region-beginning) (region-end))
10031 (buffer-substring (point-at-bol) (point-at-eol))))
10032 ;; Only use search option if there is some text.
10033 (when (string-match "\\S-" txt)
10034 (setq cpltxt
10035 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10036 desc "NONE")))
10037 (setq link cpltxt))
10039 ((called-interactively-p 'interactive)
10040 (user-error "No method for storing a link from this buffer"))
10042 (t (setq link nil)))
10044 ;; We're done setting link and desc, clean up
10045 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10046 (setq link (or link cpltxt)
10047 desc (or desc cpltxt))
10048 (cond ((not desc))
10049 ((equal desc "NONE") (setq desc nil))
10050 (t (setq desc
10051 (replace-regexp-in-string
10052 org-bracket-link-analytic-regexp
10053 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10054 desc))))
10055 ;; Return the link
10056 (if (not (and (or (called-interactively-p 'any)
10057 executing-kbd-macro)
10058 link))
10059 (or agenda-link (and link (org-make-link-string link desc)))
10060 (push (list link desc) org-stored-links)
10061 (message "Stored: %s" (or desc link))
10062 (when custom-id
10063 (setq link (concat "file:" (abbreviate-file-name
10064 (buffer-file-name)) "::#" custom-id))
10065 (push (list link desc) org-stored-links))
10066 (car org-stored-links)))))
10068 (defun org-store-link-props (&rest plist)
10069 "Store link properties, extract names, addresses and dates."
10070 (let ((x (plist-get plist :from)))
10071 (when x
10072 (let ((adr (mail-extract-address-components x)))
10073 (setq plist (plist-put plist :fromname (car adr)))
10074 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10075 (let ((x (plist-get plist :to)))
10076 (when x
10077 (let ((adr (mail-extract-address-components x)))
10078 (setq plist (plist-put plist :toname (car adr)))
10079 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10080 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10081 (when x
10082 (setq plist (plist-put plist :date-timestamp
10083 (format-time-string
10084 (org-time-stamp-format t) x)))
10085 (setq plist (plist-put plist :date-timestamp-inactive
10086 (format-time-string
10087 (org-time-stamp-format t t) x)))))
10088 (let ((from (plist-get plist :from))
10089 (to (plist-get plist :to)))
10090 (when (and from to org-from-is-user-regexp)
10091 (setq plist
10092 (plist-put plist :fromto
10093 (if (string-match org-from-is-user-regexp from)
10094 (concat "to %t")
10095 (concat "from %f"))))))
10096 (setq org-store-link-plist plist))
10098 (defun org-add-link-props (&rest plist)
10099 "Add these properties to the link property list."
10100 (let (key value)
10101 (while plist
10102 (setq key (pop plist) value (pop plist))
10103 (setq org-store-link-plist
10104 (plist-put org-store-link-plist key value)))))
10106 (defun org-email-link-description (&optional fmt)
10107 "Return the description part of an email link.
10108 This takes information from `org-store-link-plist' and formats it
10109 according to FMT (default from `org-email-link-description-format')."
10110 (setq fmt (or fmt org-email-link-description-format))
10111 (let* ((p org-store-link-plist)
10112 (to (plist-get p :toaddress))
10113 (from (plist-get p :fromaddress))
10114 (table
10115 (list
10116 (cons "%c" (plist-get p :fromto))
10117 (cons "%F" (plist-get p :from))
10118 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10119 (cons "%T" (plist-get p :to))
10120 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10121 (cons "%s" (plist-get p :subject))
10122 (cons "%d" (plist-get p :date))
10123 (cons "%m" (plist-get p :message-id)))))
10124 (when (string-match "%c" fmt)
10125 ;; Check if the user wrote this message
10126 (if (and org-from-is-user-regexp from to
10127 (save-match-data (string-match org-from-is-user-regexp from)))
10128 (setq fmt (replace-match "to %t" t t fmt))
10129 (setq fmt (replace-match "from %f" t t fmt))))
10130 (org-replace-escapes fmt table)))
10132 (defun org-make-org-heading-search-string (&optional string)
10133 "Make search string for the current headline or STRING."
10134 (let ((s (or string
10135 (and (derived-mode-p 'org-mode)
10136 (save-excursion
10137 (org-back-to-heading t)
10138 (org-element-property :raw-value (org-element-at-point))))))
10139 (lines org-context-in-file-links))
10140 (or string (setq s (concat "*" s))) ; Add * for headlines
10141 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10142 (when (and string (integerp lines) (> lines 0))
10143 (let ((slines (org-split-string s "\n")))
10144 (when (< lines (length slines))
10145 (setq s (mapconcat
10146 'identity
10147 (reverse (nthcdr (- (length slines) lines)
10148 (reverse slines))) "\n")))))
10149 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10151 (defun org-make-link-string (link &optional description)
10152 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10153 (unless (org-string-nw-p link) (error "Empty link"))
10154 (let ((uri (cond ((string-match org-link-types-re link)
10155 (concat (match-string 1 link)
10156 (org-link-escape (substring link (match-end 1)))))
10157 ;; For readability, url-encode internal links only
10158 ;; when absolutely needed (i.e, when they contain
10159 ;; square brackets). File links however, are
10160 ;; encoded since, e.g., spaces are significant.
10161 ((or (file-name-absolute-p link)
10162 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10163 (org-link-escape link))
10164 (t link)))
10165 (description
10166 (and (org-string-nw-p description)
10167 ;; Remove brackets from description, as they are fatal.
10168 (replace-regexp-in-string
10169 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10170 (org-trim description)))))
10171 (format "[[%s]%s]"
10173 (if description (format "[%s]" description) ""))))
10175 (defconst org-link-escape-chars
10176 ;;%20 %5B %5D %25
10177 '(?\s ?\[ ?\] ?%)
10178 "List of characters that should be escaped in a link when stored to Org.
10179 This is the list that is used for internal purposes.")
10181 (defun org-link-escape (text &optional table merge)
10182 "Return percent escaped representation of TEXT.
10183 TEXT is a string with the text to escape.
10184 Optional argument TABLE is a list with characters that should be
10185 escaped. When nil, `org-link-escape-chars' is used.
10186 If optional argument MERGE is set, merge TABLE into
10187 `org-link-escape-chars'."
10188 (let ((characters-to-encode
10189 (cond ((null table) org-link-escape-chars)
10190 (merge (append org-link-escape-chars table))
10191 (t table))))
10192 (mapconcat
10193 (lambda (c)
10194 (if (or (memq c characters-to-encode)
10195 (and org-url-hexify-p (or (< c 32) (> c 126))))
10196 (mapconcat (lambda (e) (format "%%%.2X" e))
10197 (or (encode-coding-char c 'utf-8)
10198 (error "Unable to percent escape character: %c" c))
10200 (char-to-string c)))
10201 text "")))
10203 (defun org-link-unescape (str)
10204 "Unhex hexified Unicode parts in string STR.
10205 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10206 reciprocal of `org-link-escape', which see."
10207 (if (org-string-nw-p str)
10208 (replace-regexp-in-string
10209 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10210 str))
10212 (defun org-link-unescape-compound (hex)
10213 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10214 Note: this function also decodes single byte encodings like
10215 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10216 (save-match-data
10217 (let* ((bytes (cdr (split-string hex "%")))
10218 (ret "")
10219 (eat 0)
10220 (sum 0))
10221 (while bytes
10222 (let* ((val (string-to-number (pop bytes) 16))
10223 (shift-xor
10224 (if (= 0 eat)
10225 (cond
10226 ((>= val 252) (cons 6 252))
10227 ((>= val 248) (cons 5 248))
10228 ((>= val 240) (cons 4 240))
10229 ((>= val 224) (cons 3 224))
10230 ((>= val 192) (cons 2 192))
10231 (t (cons 0 0)))
10232 (cons 6 128))))
10233 (when (>= val 192) (setq eat (car shift-xor)))
10234 (setq val (logxor val (cdr shift-xor)))
10235 (setq sum (+ (lsh sum (car shift-xor)) val))
10236 (when (> eat 0) (setq eat (- eat 1)))
10237 (cond
10238 ((= 0 eat) ;multi byte
10239 (setq ret (concat ret (char-to-string sum)))
10240 (setq sum 0))
10241 ((not bytes) ; single byte(s)
10242 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10243 ret)))
10245 (defun org-link-unescape-single-byte-sequence (hex)
10246 "Unhexify hex-encoded single byte character sequences."
10247 (mapconcat (lambda (byte)
10248 (char-to-string (string-to-number byte 16)))
10249 (cdr (split-string hex "%")) ""))
10251 (defun org-xor (a b)
10252 "Exclusive or."
10253 (if a (not b) b))
10255 (defun org-fixup-message-id-for-http (s)
10256 "Replace special characters in a message id, so it can be used in an http query."
10257 (when (string-match "%" s)
10258 (setq s (mapconcat (lambda (c)
10259 (if (eq c ?%)
10260 "%25"
10261 (char-to-string c)))
10262 s "")))
10263 (while (string-match "<" s)
10264 (setq s (replace-match "%3C" t t s)))
10265 (while (string-match ">" s)
10266 (setq s (replace-match "%3E" t t s)))
10267 (while (string-match "@" s)
10268 (setq s (replace-match "%40" t t s)))
10271 (defun org-link-prettify (link)
10272 "Return a human-readable representation of LINK.
10273 The car of LINK must be a raw link.
10274 The cdr of LINK must be either a link description or nil."
10275 (let ((desc (or (cadr link) "<no description>")))
10276 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10277 "<" (car link) ">")))
10279 ;;;###autoload
10280 (defun org-insert-link-global ()
10281 "Insert a link like Org mode does.
10282 This command can be called in any mode to insert a link in Org syntax."
10283 (interactive)
10284 (org-load-modules-maybe)
10285 (org-run-like-in-org-mode 'org-insert-link))
10287 (defun org-insert-all-links (arg &optional pre post)
10288 "Insert all links in `org-stored-links'.
10289 When a universal prefix, do not delete the links from `org-stored-links'.
10290 When `ARG' is a number, insert the last N link(s).
10291 `PRE' and `POST' are optional arguments to define a string to
10292 prepend or to append."
10293 (interactive "P")
10294 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10295 (links (copy-sequence org-stored-links))
10296 (pr (or pre "- "))
10297 (po (or post "\n"))
10298 (cnt 1) l)
10299 (if (null org-stored-links)
10300 (message "No link to insert")
10301 (while (and (or (listp arg) (>= arg cnt))
10302 (setq l (if (listp arg)
10303 (pop links)
10304 (pop org-stored-links))))
10305 (setq cnt (1+ cnt))
10306 (insert pr)
10307 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10308 (insert po)))))
10310 (defun org-insert-last-stored-link (arg)
10311 "Insert the last link stored in `org-stored-links'."
10312 (interactive "p")
10313 (org-insert-all-links arg "" "\n"))
10315 (defun org-link-fontify-links-to-this-file ()
10316 "Fontify links to the current file in `org-stored-links'."
10317 (let ((f (buffer-file-name)) a b)
10318 (setq a (mapcar (lambda(l)
10319 (let ((ll (car l)))
10320 (when (and (string-match "^file:\\(.+\\)::" ll)
10321 (equal f (expand-file-name (match-string 1 ll))))
10322 ll)))
10323 org-stored-links))
10324 (when (featurep 'org-id)
10325 (setq b (mapcar (lambda(l)
10326 (let ((ll (car l)))
10327 (when (and (string-match "^id:\\(.+\\)$" ll)
10328 (equal f (expand-file-name
10329 (or (org-id-find-id-file
10330 (match-string 1 ll)) ""))))
10331 ll)))
10332 org-stored-links)))
10333 (mapcar (lambda(l)
10334 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10335 (delq nil (append a b)))))
10337 (defvar org--links-history nil)
10338 (defun org-insert-link (&optional complete-file link-location default-description)
10339 "Insert a link. At the prompt, enter the link.
10341 Completion can be used to insert any of the link protocol prefixes in use.
10343 The history can be used to select a link previously stored with
10344 `org-store-link'. When the empty string is entered (i.e. if you just
10345 press `RET' at the prompt), the link defaults to the most recently
10346 stored link. As `SPC' triggers completion in the minibuffer, you need to
10347 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10349 You will also be prompted for a description, and if one is given, it will
10350 be displayed in the buffer instead of the link.
10352 If there is already a link at point, this command will allow you to edit
10353 link and description parts.
10355 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10356 file name can be
10357 selected using completion. The path to the file will be relative to the
10358 current directory if the file is in the current directory or a subdirectory.
10359 Otherwise, the link will be the absolute path as completed in the minibuffer
10360 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10361 option `org-link-file-path-type'.
10363 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10364 absolute path even if the file is in
10365 the current directory or below.
10367 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10368 prefix negates `org-keep-stored-link-after-insertion'.
10370 If `org-make-link-description-function' is non-nil, this function will be
10371 called with the link target, and the result will be the default
10372 link description.
10374 If the LINK-LOCATION parameter is non-nil, this value will be used as
10375 the link location instead of reading one interactively.
10377 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10378 as the default description."
10379 (interactive "P")
10380 (let* ((wcf (current-window-configuration))
10381 (origbuf (current-buffer))
10382 (region (when (org-region-active-p)
10383 (buffer-substring (region-beginning) (region-end))))
10384 (remove (and region (list (region-beginning) (region-end))))
10385 (desc region)
10386 (link link-location)
10387 (abbrevs org-link-abbrev-alist-local)
10388 entry all-prefixes auto-desc)
10389 (cond
10390 (link-location) ; specified by arg, just use it.
10391 ((org-in-regexp org-bracket-link-regexp 1)
10392 ;; We do have a link at point, and we are going to edit it.
10393 (setq remove (list (match-beginning 0) (match-end 0)))
10394 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10395 (setq link (read-string "Link: "
10396 (org-link-unescape
10397 (match-string-no-properties 1)))))
10398 ((or (org-in-regexp org-angle-link-re)
10399 (org-in-regexp org-plain-link-re))
10400 ;; Convert to bracket link
10401 (setq remove (list (match-beginning 0) (match-end 0))
10402 link (read-string "Link: "
10403 (org-unbracket-string "<" ">" (match-string 0)))))
10404 ((member complete-file '((4) (16)))
10405 ;; Completing read for file names.
10406 (setq link (org-file-complete-link complete-file)))
10408 ;; Read link, with completion for stored links.
10409 (org-link-fontify-links-to-this-file)
10410 (org-switch-to-buffer-other-window "*Org Links*")
10411 (with-current-buffer "*Org Links*"
10412 (erase-buffer)
10413 (insert "Insert a link.
10414 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10415 (when org-stored-links
10416 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10417 (insert (mapconcat 'org-link-prettify
10418 (reverse org-stored-links) "\n")))
10419 (goto-char (point-min)))
10420 (let ((cw (selected-window)))
10421 (select-window (get-buffer-window "*Org Links*" 'visible))
10422 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10423 (unless (pos-visible-in-window-p (point-max))
10424 (org-fit-window-to-buffer))
10425 (and (window-live-p cw) (select-window cw)))
10426 (setq all-prefixes (append (mapcar 'car abbrevs)
10427 (mapcar 'car org-link-abbrev-alist)
10428 (org-link-types)))
10429 (unwind-protect
10430 ;; Fake a link history, containing the stored links.
10431 (let ((org--links-history
10432 (append (mapcar #'car org-stored-links)
10433 org-insert-link-history)))
10434 (setq link
10435 (org-completing-read
10436 "Link: "
10437 (append
10438 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10439 (mapcar #'car org-stored-links))
10440 nil nil nil
10441 'org--links-history
10442 (caar org-stored-links)))
10443 (unless (org-string-nw-p link) (user-error "No link selected"))
10444 (dolist (l org-stored-links)
10445 (when (equal link (cadr l))
10446 (setq link (car l))
10447 (setq auto-desc t)))
10448 (when (or (member link all-prefixes)
10449 (and (equal ":" (substring link -1))
10450 (member (substring link 0 -1) all-prefixes)
10451 (setq link (substring link 0 -1))))
10452 (setq link (with-current-buffer origbuf
10453 (org-link-try-special-completion link)))))
10454 (set-window-configuration wcf)
10455 (kill-buffer "*Org Links*"))
10456 (setq entry (assoc link org-stored-links))
10457 (or entry (push link org-insert-link-history))
10458 (setq desc (or desc (nth 1 entry)))))
10460 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10461 (not org-keep-stored-link-after-insertion))
10462 (setq org-stored-links (delq (assoc link org-stored-links)
10463 org-stored-links)))
10465 (when (and (string-match org-plain-link-re link)
10466 (not (string-match org-ts-regexp link)))
10467 ;; URL-like link, normalize the use of angular brackets.
10468 (setq link (org-unbracket-string "<" ">" link)))
10470 ;; Check if we are linking to the current file with a search
10471 ;; option If yes, simplify the link by using only the search
10472 ;; option.
10473 (when (and buffer-file-name
10474 (let ((case-fold-search nil))
10475 (string-match "\\`file:\\(.+?\\)::" link)))
10476 (let ((path (match-string-no-properties 1 link))
10477 (search (substring-no-properties link (match-end 0))))
10478 (save-match-data
10479 (when (equal (file-truename buffer-file-name) (file-truename path))
10480 ;; We are linking to this same file, with a search option
10481 (setq link search)))))
10483 ;; Check if we can/should use a relative path. If yes, simplify the link
10484 (let ((case-fold-search nil))
10485 (when (string-match "\\`\\(file\\|docview\\):" link)
10486 (let* ((type (match-string-no-properties 0 link))
10487 (path (substring-no-properties link (match-end 0)))
10488 (origpath path))
10489 (cond
10490 ((or (eq org-link-file-path-type 'absolute)
10491 (equal complete-file '(16)))
10492 (setq path (abbreviate-file-name (expand-file-name path))))
10493 ((eq org-link-file-path-type 'noabbrev)
10494 (setq path (expand-file-name path)))
10495 ((eq org-link-file-path-type 'relative)
10496 (setq path (file-relative-name path)))
10498 (save-match-data
10499 (if (string-match (concat "^" (regexp-quote
10500 (expand-file-name
10501 (file-name-as-directory
10502 default-directory))))
10503 (expand-file-name path))
10504 ;; We are linking a file with relative path name.
10505 (setq path (substring (expand-file-name path)
10506 (match-end 0)))
10507 (setq path (abbreviate-file-name (expand-file-name path)))))))
10508 (setq link (concat type path))
10509 (when (equal desc origpath)
10510 (setq desc path)))))
10512 (if org-make-link-description-function
10513 (setq desc
10514 (or (condition-case nil
10515 (funcall org-make-link-description-function link desc)
10516 (error (progn (message "Can't get link description from `%s'"
10517 (symbol-name org-make-link-description-function))
10518 (sit-for 2) nil)))
10519 (read-string "Description: " default-description)))
10520 (if default-description (setq desc default-description)
10521 (setq desc (or (and auto-desc desc)
10522 (read-string "Description: " desc)))))
10524 (unless (string-match "\\S-" desc) (setq desc nil))
10525 (when remove (apply 'delete-region remove))
10526 (insert (org-make-link-string link desc))
10527 ;; Redisplay so as the new link has proper invisible characters.
10528 (sit-for 0)))
10530 (defun org-link-try-special-completion (type)
10531 "If there is completion support for link type TYPE, offer it."
10532 (let ((fun (org-link-get-parameter type :complete)))
10533 (if (functionp fun)
10534 (funcall fun)
10535 (read-string "Link (no completion support): " (concat type ":")))))
10537 (defun org-file-complete-link (&optional arg)
10538 "Create a file link using completion."
10539 (let ((file (read-file-name "File: "))
10540 (pwd (file-name-as-directory (expand-file-name ".")))
10541 (pwd1 (file-name-as-directory (abbreviate-file-name
10542 (expand-file-name ".")))))
10543 (cond ((equal arg '(16))
10544 (concat "file:"
10545 (abbreviate-file-name (expand-file-name file))))
10546 ((string-match
10547 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10548 (concat "file:" (match-string 1 file)))
10549 ((string-match
10550 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10551 (expand-file-name file))
10552 (concat "file:"
10553 (match-string 1 (expand-file-name file))))
10554 (t (concat "file:" file)))))
10556 (defun org-completing-read (&rest args)
10557 "Completing-read with SPACE being a normal character."
10558 (let ((enable-recursive-minibuffers t)
10559 (minibuffer-local-completion-map
10560 (copy-keymap minibuffer-local-completion-map)))
10561 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10562 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10563 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10564 'org-time-stamp-inactive)
10565 (apply #'completing-read args)))
10567 ;;; Opening/following a link
10569 (defvar org-link-search-failed nil)
10571 (defvar org-open-link-functions nil
10572 "Hook for functions finding a plain text link.
10573 These functions must take a single argument, the link content.
10574 They will be called for links that look like [[link text][description]]
10575 when LINK TEXT does not have a protocol like \"http:\" and does not look
10576 like a filename (e.g. \"./blue.png\").
10578 These functions will be called *before* Org attempts to resolve the
10579 link by doing text searches in the current buffer - so if you want a
10580 link \"[[target]]\" to still find \"<<target>>\", your function should
10581 handle this as a special case.
10583 When the function does handle the link, it must return a non-nil value.
10584 If it decides that it is not responsible for this link, it must return
10585 nil to indicate that that Org can continue with other options like
10586 exact and fuzzy text search.")
10588 (defun org-next-link (&optional search-backward)
10589 "Move forward to the next link.
10590 If the link is in hidden text, expose it."
10591 (interactive "P")
10592 (when (and org-link-search-failed (eq this-command last-command))
10593 (goto-char (point-min))
10594 (message "Link search wrapped back to beginning of buffer"))
10595 (setq org-link-search-failed nil)
10596 (let* ((pos (point))
10597 (ct (org-context))
10598 (a (assq :link ct))
10599 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10600 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10601 ((looking-at org-any-link-re)
10602 ;; Don't stay stuck at link without an org-link face
10603 (forward-char (if search-backward -1 1))))
10604 (if (funcall srch-fun org-any-link-re nil t)
10605 (progn
10606 (goto-char (match-beginning 0))
10607 (when (org-invisible-p) (org-show-context)))
10608 (goto-char pos)
10609 (setq org-link-search-failed t)
10610 (message "No further link found"))))
10612 (defun org-previous-link ()
10613 "Move backward to the previous link.
10614 If the link is in hidden text, expose it."
10615 (interactive)
10616 (funcall 'org-next-link t))
10618 (defun org-translate-link (s)
10619 "Translate a link string if a translation function has been defined."
10620 (with-temp-buffer
10621 (insert (org-trim s))
10622 (org-trim (org-element-interpret-data (org-element-context)))))
10624 (defun org-translate-link-from-planner (type path)
10625 "Translate a link from Emacs Planner syntax so that Org can follow it.
10626 This is still an experimental function, your mileage may vary."
10627 (cond
10628 ((member type '("http" "https" "news" "ftp"))
10629 ;; standard Internet links are the same.
10630 nil)
10631 ((and (equal type "irc") (string-match "^//" path))
10632 ;; Planner has two / at the beginning of an irc link, we have 1.
10633 ;; We should have zero, actually....
10634 (setq path (substring path 1)))
10635 ((and (equal type "lisp") (string-match "^/" path))
10636 ;; Planner has a slash, we do not.
10637 (setq type "elisp" path (substring path 1)))
10638 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10639 ;; A typical message link. Planner has the id after the final slash,
10640 ;; we separate it with a hash mark
10641 (setq path (concat (match-string 1 path) "#"
10642 (org-unbracket-string "<" ">" (match-string 2 path))))))
10643 (cons type path))
10645 (defun org-find-file-at-mouse (ev)
10646 "Open file link or URL at mouse."
10647 (interactive "e")
10648 (mouse-set-point ev)
10649 (org-open-at-point 'in-emacs))
10651 (defun org-open-at-mouse (ev)
10652 "Open file link or URL at mouse.
10653 See the docstring of `org-open-file' for details."
10654 (interactive "e")
10655 (mouse-set-point ev)
10656 (when (eq major-mode 'org-agenda-mode)
10657 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10658 (org-open-at-point))
10660 (defvar org-window-config-before-follow-link nil
10661 "The window configuration before following a link.
10662 This is saved in case the need arises to restore it.")
10664 ;;;###autoload
10665 (defun org-open-at-point-global ()
10666 "Follow a link or time-stamp like Org mode does.
10667 This command can be called in any mode to follow an external link
10668 or a time-stamp that has Org mode syntax. Its behavior is
10669 undefined when called on internal links (e.g., fuzzy links).
10670 Raise an error when there is nothing to follow. "
10671 (interactive)
10672 (cond ((org-in-regexp org-any-link-re)
10673 (org-open-link-from-string (match-string-no-properties 0)))
10674 ((or (org-in-regexp org-ts-regexp-both nil t)
10675 (org-in-regexp org-tsr-regexp-both nil t))
10676 (org-follow-timestamp-link))
10677 (t (user-error "No link found"))))
10679 ;;;###autoload
10680 (defun org-open-link-from-string (s &optional arg reference-buffer)
10681 "Open a link in the string S, as if it was in Org mode."
10682 (interactive "sLink: \nP")
10683 (let ((reference-buffer (or reference-buffer (current-buffer))))
10684 (with-temp-buffer
10685 (let ((org-inhibit-startup (not reference-buffer)))
10686 (org-mode)
10687 (insert s)
10688 (goto-char (point-min))
10689 (when reference-buffer
10690 (setq org-link-abbrev-alist-local
10691 (with-current-buffer reference-buffer
10692 org-link-abbrev-alist-local)))
10693 (org-open-at-point arg reference-buffer)))))
10695 (defvar org-open-at-point-functions nil
10696 "Hook that is run when following a link at point.
10698 Functions in this hook must return t if they identify and follow
10699 a link at point. If they don't find anything interesting at point,
10700 they must return nil.")
10702 (defvar org-link-search-inhibit-query nil)
10703 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10704 (defun org--open-doi-link (path)
10705 "Open a \"doi\" type link.
10706 PATH is a the path to search for, as a string."
10707 (browse-url (url-encode-url (concat org-doi-server-url path))))
10709 (defun org--open-elisp-link (path)
10710 "Open a \"elisp\" type link.
10711 PATH is the sexp to evaluate, as a string."
10712 (let ((cmd path))
10713 (if (or (and (org-string-nw-p
10714 org-confirm-elisp-link-not-regexp)
10715 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10716 (not org-confirm-elisp-link-function)
10717 (funcall org-confirm-elisp-link-function
10718 (format "Execute \"%s\" as elisp? "
10719 (org-add-props cmd nil 'face 'org-warning))))
10720 (message "%s => %s" cmd
10721 (if (eq (string-to-char cmd) ?\()
10722 (eval (read cmd))
10723 (call-interactively (read cmd))))
10724 (user-error "Abort"))))
10726 (defun org--open-help-link (path)
10727 "Open a \"help\" type link.
10728 PATH is a symbol name, as a string."
10729 (pcase (intern path)
10730 ((and (pred fboundp) variable) (describe-function variable))
10731 ((and (pred boundp) function) (describe-variable function))
10732 (name (user-error "Unknown function or variable: %s" name))))
10734 (defun org--open-shell-link (path)
10735 "Open a \"shell\" type link.
10736 PATH is the command to execute, as a string."
10737 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10738 (cmd path))
10739 (if (or (and (org-string-nw-p
10740 org-confirm-shell-link-not-regexp)
10741 (string-match
10742 org-confirm-shell-link-not-regexp cmd))
10743 (not org-confirm-shell-link-function)
10744 (funcall org-confirm-shell-link-function
10745 (format "Execute \"%s\" in shell? "
10746 (org-add-props cmd nil
10747 'face 'org-warning))))
10748 (progn
10749 (message "Executing %s" cmd)
10750 (shell-command cmd buf)
10751 (when (featurep 'midnight)
10752 (setq clean-buffer-list-kill-buffer-names
10753 (cons (buffer-name buf)
10754 clean-buffer-list-kill-buffer-names))))
10755 (user-error "Abort"))))
10757 (defun org-open-at-point (&optional arg reference-buffer)
10758 "Open link, timestamp, footnote or tags at point.
10760 When point is on a link, follow it. Normally, files will be
10761 opened by an appropriate application. If the optional prefix
10762 argument ARG is non-nil, Emacs will visit the file. With
10763 a double prefix argument, try to open outside of Emacs, in the
10764 application the system uses for this file type.
10766 When point is on a timestamp, open the agenda at the day
10767 specified.
10769 When point is a footnote definition, move to the first reference
10770 found. If it is on a reference, move to the associated
10771 definition.
10773 When point is on a headline, display a list of every link in the
10774 entry, so it is possible to pick one, or all, of them. If point
10775 is on a tag, call `org-tags-view' instead.
10777 When optional argument REFERENCE-BUFFER is non-nil, it should
10778 specify a buffer from where the link search should happen. This
10779 is used internally by `org-open-link-from-string'.
10781 On top of syntactically correct links, this function will also
10782 try to open links and time-stamps in comments, example
10783 blocks... i.e., whenever point is on something looking like
10784 a timestamp or a link."
10785 (interactive "P")
10786 ;; On a code block, open block's results.
10787 (unless (call-interactively 'org-babel-open-src-block-result)
10788 (org-load-modules-maybe)
10789 (setq org-window-config-before-follow-link (current-window-configuration))
10790 (org-remove-occur-highlights nil nil t)
10791 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10792 (let* ((context
10793 ;; Only consider supported types, even if they are not
10794 ;; the closest one.
10795 (org-element-lineage
10796 (org-element-context)
10797 '(clock footnote-definition footnote-reference headline
10798 inlinetask link timestamp)
10800 (type (org-element-type context))
10801 (value (org-element-property :value context)))
10802 (cond
10803 ;; On a headline or an inlinetask, but not on a timestamp,
10804 ;; a link, a footnote reference or on tags.
10805 ((and (memq type '(headline inlinetask))
10806 ;; Not on tags.
10807 (let ((case-fold-search nil))
10808 (and (org-match-line org-complex-heading-regexp)
10809 (or (not (match-beginning 5))
10810 (< (point) (match-beginning 5))))))
10811 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10812 (links (car data))
10813 (links-end (cdr data)))
10814 (if links
10815 (dolist (link (if (stringp links) (list links) links))
10816 (search-forward link nil links-end)
10817 (goto-char (match-beginning 0))
10818 (org-open-at-point))
10819 (require 'org-attach)
10820 (org-attach-reveal 'if-exists))))
10821 ;; On a footnote reference or at definition's label.
10822 ((or (eq type 'footnote-reference)
10823 (and (eq type 'footnote-definition)
10824 (save-excursion
10825 ;; Do not validate action when point is on the
10826 ;; spaces right after the footnote label, in
10827 ;; order to be on par with behaviour on links.
10828 (skip-chars-forward " \t")
10829 (let ((begin
10830 (org-element-property :contents-begin context)))
10831 (if begin (< (point) begin)
10832 (= (org-element-property :post-affiliated context)
10833 (line-beginning-position)))))))
10834 (org-footnote-action))
10835 ;; No valid context. Ignore catch-all types like `headline'.
10836 ;; If point is on something looking like a link or
10837 ;; a time-stamp, try opening it. It may be useful in
10838 ;; comments, example blocks...
10839 ((memq type '(footnote-definition headline inlinetask nil))
10840 (call-interactively #'org-open-at-point-global))
10841 ;; On a clock line, make sure point is on the timestamp
10842 ;; before opening it.
10843 ((and (eq type 'clock)
10844 value
10845 (>= (point) (org-element-property :begin value))
10846 (<= (point) (org-element-property :end value)))
10847 (org-follow-timestamp-link))
10848 ;; Do nothing on white spaces after an object.
10849 ((>= (point)
10850 (save-excursion
10851 (goto-char (org-element-property :end context))
10852 (skip-chars-backward " \t")
10853 (point)))
10854 (user-error "No link found"))
10855 ((eq type 'timestamp) (org-follow-timestamp-link))
10856 ;; On tags within a headline or an inlinetask.
10857 ((and (memq type '(headline inlinetask))
10858 (let ((case-fold-search nil))
10859 (save-excursion (beginning-of-line)
10860 (looking-at org-complex-heading-regexp))
10861 (and (match-beginning 5)
10862 (>= (point) (match-beginning 5)))))
10863 (org-tags-view arg (substring (match-string 5) 0 -1)))
10864 ((eq type 'link)
10865 ;; When link is located within the description of another
10866 ;; link (e.g., an inline image), always open the parent
10867 ;; link.
10868 (let* ((link (let ((up (org-element-property :parent context)))
10869 (if (eq (org-element-type up) 'link) up context)))
10870 (type (org-element-property :type link))
10871 (path (org-link-unescape (org-element-property :path link))))
10872 ;; Switch back to REFERENCE-BUFFER needed when called in
10873 ;; a temporary buffer through `org-open-link-from-string'.
10874 (with-current-buffer (or reference-buffer (current-buffer))
10875 (cond
10876 ((equal type "file")
10877 (if (string-match "[*?{]" (file-name-nondirectory path))
10878 (dired path)
10879 ;; Look into `org-link-parameters' in order to find
10880 ;; a DEDICATED-FUNCTION to open file. The function
10881 ;; will be applied on raw link instead of parsed
10882 ;; link due to the limitation in `org-add-link-type'
10883 ;; ("open" function called with a single argument).
10884 ;; If no such function is found, fallback to
10885 ;; `org-open-file'.
10886 (let* ((option (org-element-property :search-option link))
10887 (app (org-element-property :application link))
10888 (dedicated-function
10889 (org-link-get-parameter
10890 (if app (concat type "+" app) type)
10891 :follow)))
10892 (if dedicated-function
10893 (funcall dedicated-function
10894 (concat path
10895 (and option (concat "::" option))))
10896 (apply #'org-open-file
10897 path
10898 (cond (arg)
10899 ((equal app "emacs") 'emacs)
10900 ((equal app "sys") 'system))
10901 (cond ((not option) nil)
10902 ((string-match-p "\\`[0-9]+\\'" option)
10903 (list (string-to-number option)))
10904 (t (list nil
10905 (org-link-unescape option)))))))))
10906 ((functionp (org-link-get-parameter type :follow))
10907 (funcall (org-link-get-parameter type :follow) path))
10908 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10909 (unless (run-hook-with-args-until-success
10910 'org-open-link-functions path)
10911 (if (not arg) (org-mark-ring-push)
10912 (switch-to-buffer-other-window
10913 (org-get-buffer-for-internal-link (current-buffer))))
10914 (let ((destination
10915 (org-with-wide-buffer
10916 (if (equal type "radio")
10917 (org-search-radio-target
10918 (org-element-property :path link))
10919 (org-link-search
10920 (if (member type '("custom-id" "coderef"))
10921 (org-element-property :raw-link link)
10922 path)
10923 ;; Prevent fuzzy links from matching
10924 ;; themselves.
10925 (and (equal type "fuzzy")
10926 (+ 2 (org-element-property :begin link)))))
10927 (point))))
10928 (unless (and (<= (point-min) destination)
10929 (>= (point-max) destination))
10930 (widen))
10931 (goto-char destination))))
10932 (t (browse-url-at-point))))))
10933 (t (user-error "No link found")))))
10934 (run-hook-with-args 'org-follow-link-hook)))
10936 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10937 "Offer links in the current entry and return the selected link.
10938 If there is only one link, return it.
10939 If NTH is an integer, return the NTH link found.
10940 If ZERO is a string, check also this string for a link, and if
10941 there is one, return it."
10942 (with-current-buffer buffer
10943 (org-with-wide-buffer
10944 (goto-char marker)
10945 (let ((cnt ?0)
10946 have-zero end links link c)
10947 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10948 (push (match-string 0 zero) links)
10949 (setq cnt (1- cnt) have-zero t))
10950 (save-excursion
10951 (org-back-to-heading t)
10952 (setq end (save-excursion (outline-next-heading) (point)))
10953 (while (re-search-forward org-any-link-re end t)
10954 (push (match-string 0) links))
10955 (setq links (org-uniquify (reverse links))))
10956 (cond
10957 ((null links)
10958 (message "No links"))
10959 ((equal (length links) 1)
10960 (setq link (car links)))
10961 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10962 (setq link (nth (if have-zero nth (1- nth)) links)))
10963 (t ; we have to select a link
10964 (save-excursion
10965 (save-window-excursion
10966 (delete-other-windows)
10967 (with-output-to-temp-buffer "*Select Link*"
10968 (dolist (l links)
10969 (cond
10970 ((not (string-match org-bracket-link-regexp l))
10971 (princ (format "[%c] %s\n" (cl-incf cnt)
10972 (org-unbracket-string "<" ">" l))))
10973 ((match-end 3)
10974 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10975 (match-string 3 l) (match-string 1 l))))
10976 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10977 (match-string 1 l)))))))
10978 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10979 (message "Select link to open, RET to open all:")
10980 (setq c (read-char-exclusive))
10981 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10982 (when (equal c ?q) (user-error "Abort"))
10983 (if (equal c ?\C-m)
10984 (setq link links)
10985 (setq nth (- c ?0))
10986 (when have-zero (setq nth (1+ nth)))
10987 (unless (and (integerp nth) (>= (length links) nth))
10988 (user-error "Invalid link selection"))
10989 (setq link (nth (1- nth) links)))))
10990 (cons link end)))))
10992 ;; TODO: These functions are deprecated since `org-open-at-point'
10993 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10994 (defun org-open-file-with-system (path)
10995 "Open file at PATH using the system way of opening it."
10996 (org-open-file path 'system))
10997 (defun org-open-file-with-emacs (path)
10998 "Open file at PATH in Emacs."
10999 (org-open-file path 'emacs))
11002 ;;; File search
11004 (defvar org-create-file-search-functions nil
11005 "List of functions to construct the right search string for a file link.
11006 These functions are called in turn with point at the location to
11007 which the link should point.
11009 A function in the hook should first test if it would like to
11010 handle this file type, for example by checking the `major-mode'
11011 or the file extension. If it decides not to handle this file, it
11012 should just return nil to give other functions a chance. If it
11013 does handle the file, it must return the search string to be used
11014 when following the link. The search string will be part of the
11015 file link, given after a double colon, and `org-open-at-point'
11016 will automatically search for it. If special measures must be
11017 taken to make the search successful, another function should be
11018 added to the companion hook `org-execute-file-search-functions',
11019 which see.
11021 A function in this hook may also use `setq' to set the variable
11022 `description' to provide a suggestion for the descriptive text to
11023 be used for this link when it gets inserted into an Org buffer
11024 with \\[org-insert-link].")
11026 (defvar org-execute-file-search-functions nil
11027 "List of functions to execute a file search triggered by a link.
11029 Functions added to this hook must accept a single argument, the
11030 search string that was part of the file link, the part after the
11031 double colon. The function must first check if it would like to
11032 handle this search, for example by checking the `major-mode' or
11033 the file extension. If it decides not to handle this search, it
11034 should just return nil to give other functions a chance. If it
11035 does handle the search, it must return a non-nil value to keep
11036 other functions from trying.
11038 Each function can access the current prefix argument through the
11039 variable `current-prefix-arg'. Note that a single prefix is used
11040 to force opening a link in Emacs, so it may be good to only use a
11041 numeric or double prefix to guide the search function.
11043 In case this is needed, a function in this hook can also restore
11044 the window configuration before `org-open-at-point' was called using:
11046 (set-window-configuration org-window-config-before-follow-link)")
11048 (defun org-search-radio-target (target)
11049 "Search a radio target matching TARGET in current buffer.
11050 White spaces are not significant."
11051 (let ((re (format "<<<%s>>>"
11052 (mapconcat #'regexp-quote
11053 (org-split-string target "[ \t\n]+")
11054 "[ \t]+\\(?:\n[ \t]*\\)?")))
11055 (origin (point)))
11056 (goto-char (point-min))
11057 (catch :radio-match
11058 (while (re-search-forward re nil t)
11059 (backward-char)
11060 (let ((object (org-element-context)))
11061 (when (eq (org-element-type object) 'radio-target)
11062 (goto-char (org-element-property :begin object))
11063 (org-show-context 'link-search)
11064 (throw :radio-match nil))))
11065 (goto-char origin)
11066 (user-error "No match for radio target: %s" target))))
11068 (defun org-link-search (s &optional avoid-pos stealth)
11069 "Search for a search string S.
11071 If S starts with \"#\", it triggers a custom ID search.
11073 If S is enclosed within parenthesis, it initiates a coderef
11074 search.
11076 If S is surrounded by forward slashes, it is interpreted as
11077 a regular expression. In Org mode files, this will create an
11078 `org-occur' sparse tree. In ordinary files, `occur' will be used
11079 to list matches. If the current buffer is in `dired-mode', grep
11080 will be used to search in all files.
11082 When AVOID-POS is given, ignore matches near that position.
11084 When optional argument STEALTH is non-nil, do not modify
11085 visibility around point, thus ignoring `org-show-context-detail'
11086 variable.
11088 Search is case-insensitive and ignores white spaces. Return type
11089 of matched result, which is either `dedicated' or `fuzzy'."
11090 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11091 (let* ((case-fold-search t)
11092 (origin (point))
11093 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11094 (starred (eq (string-to-char normalized) ?*))
11095 (words (split-string (if starred (substring s 1) s)))
11096 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11097 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11098 type)
11099 (cond
11100 ;; Check if there are any special search functions.
11101 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11102 ((eq (string-to-char s) ?#)
11103 ;; Look for a custom ID S if S starts with "#".
11104 (let* ((id (substring normalized 1))
11105 (match (org-find-property "CUSTOM_ID" id)))
11106 (if match (progn (goto-char match) (setf type 'dedicated))
11107 (error "No match for custom ID: %s" id))))
11108 ((string-match "\\`(\\(.*\\))\\'" normalized)
11109 ;; Look for coderef targets if S is enclosed within parenthesis.
11110 (let ((coderef (match-string-no-properties 1 normalized))
11111 (re (substring s-single-re 1 -1)))
11112 (goto-char (point-min))
11113 (catch :coderef-match
11114 (while (re-search-forward re nil t)
11115 (let ((element (org-element-at-point)))
11116 (when (and (memq (org-element-type element)
11117 '(example-block src-block))
11118 ;; Build proper regexp according to current
11119 ;; block's label format.
11120 (let ((label-fmt
11121 (regexp-quote
11122 (or (org-element-property :label-fmt element)
11123 org-coderef-label-format))))
11124 (save-excursion
11125 (beginning-of-line)
11126 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11127 (format label-fmt coderef))))))
11128 (setq type 'dedicated)
11129 (goto-char (match-beginning 1))
11130 (throw :coderef-match nil))))
11131 (goto-char origin)
11132 (error "No match for coderef: %s" coderef))))
11133 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11134 ;; Look for a regular expression.
11135 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11136 (match-string 1 s)))
11137 ;; From here, we handle fuzzy links.
11139 ;; Look for targets, only if not in a headline search.
11140 ((and (not starred)
11141 (let ((target (format "<<%s>>" s-multi-re)))
11142 (catch :target-match
11143 (goto-char (point-min))
11144 (while (re-search-forward target nil t)
11145 (backward-char)
11146 (let ((context (org-element-context)))
11147 (when (eq (org-element-type context) 'target)
11148 (setq type 'dedicated)
11149 (goto-char (org-element-property :begin context))
11150 (throw :target-match t))))
11151 nil))))
11152 ;; Look for elements named after S, only if not in a headline
11153 ;; search.
11154 ((and (not starred)
11155 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11156 (catch :name-match
11157 (goto-char (point-min))
11158 (while (re-search-forward name nil t)
11159 (let ((element (org-element-at-point)))
11160 (when (equal words
11161 (split-string
11162 (org-element-property :name element)))
11163 (setq type 'dedicated)
11164 (beginning-of-line)
11165 (throw :name-match t))))
11166 nil))))
11167 ;; Regular text search. Prefer headlines in Org mode buffers.
11168 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11169 ;; statistics cookies and tags.
11170 ((and (derived-mode-p 'org-mode)
11171 (let ((title-re
11172 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11173 org-outline-regexp-bol
11174 org-comment-string
11175 (mapconcat #'regexp-quote words ".+")))
11176 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11177 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11178 (goto-char (point-min))
11179 (catch :found
11180 (while (re-search-forward title-re nil t)
11181 (when (equal words
11182 (split-string
11183 (replace-regexp-in-string
11184 cookie-re ""
11185 (replace-regexp-in-string
11186 comment-re "" (org-get-heading t t)))))
11187 (throw :found t)))
11188 nil)))
11189 (beginning-of-line)
11190 (setq type 'dedicated))
11191 ;; Offer to create non-existent headline depending on
11192 ;; `org-link-search-must-match-exact-headline'.
11193 ((and (derived-mode-p 'org-mode)
11194 (not org-link-search-inhibit-query)
11195 (eq org-link-search-must-match-exact-headline 'query-to-create)
11196 (yes-or-no-p "No match - create this as a new heading? "))
11197 (goto-char (point-max))
11198 (unless (bolp) (newline))
11199 (org-insert-heading nil t t)
11200 (insert s "\n")
11201 (beginning-of-line 0))
11202 ;; Only headlines are looked after. No need to process
11203 ;; further: throw an error.
11204 ((and (derived-mode-p 'org-mode)
11205 (or starred org-link-search-must-match-exact-headline))
11206 (goto-char origin)
11207 (error "No match for fuzzy expression: %s" normalized))
11208 ;; Regular text search.
11209 ((catch :fuzzy-match
11210 (goto-char (point-min))
11211 (while (re-search-forward s-multi-re nil t)
11212 ;; Skip match if it contains AVOID-POS or it is included in
11213 ;; a link with a description but outside the description.
11214 (unless (or (and avoid-pos
11215 (<= (match-beginning 0) avoid-pos)
11216 (> (match-end 0) avoid-pos))
11217 (and (save-match-data
11218 (org-in-regexp org-bracket-link-regexp))
11219 (match-beginning 3)
11220 (or (> (match-beginning 3) (point))
11221 (<= (match-end 3) (point)))
11222 (org-element-lineage
11223 (save-match-data (org-element-context))
11224 '(link) t)))
11225 (goto-char (match-beginning 0))
11226 (setq type 'fuzzy)
11227 (throw :fuzzy-match t)))
11228 nil))
11229 ;; All failed. Throw an error.
11230 (t (goto-char origin)
11231 (error "No match for fuzzy expression: %s" normalized)))
11232 ;; Disclose surroundings of match, if appropriate.
11233 (when (and (derived-mode-p 'org-mode) (not stealth))
11234 (org-show-context 'link-search))
11235 type))
11237 (defun org-get-buffer-for-internal-link (buffer)
11238 "Return a buffer to be used for displaying the link target of internal links."
11239 (cond
11240 ((not org-display-internal-link-with-indirect-buffer)
11241 buffer)
11242 ((string-suffix-p "(Clone)" (buffer-name buffer))
11243 (message "Buffer is already a clone, not making another one")
11244 ;; we also do not modify visibility in this case
11245 buffer)
11246 (t ; make a new indirect buffer for displaying the link
11247 (let* ((bn (buffer-name buffer))
11248 (ibn (concat bn "(Clone)"))
11249 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11250 (with-current-buffer ib (org-overview))
11251 ib))))
11253 (defun org-do-occur (regexp &optional cleanup)
11254 "Call the Emacs command `occur'.
11255 If CLEANUP is non-nil, remove the printout of the regular expression
11256 in the *Occur* buffer. This is useful if the regex is long and not useful
11257 to read."
11258 (occur regexp)
11259 (when cleanup
11260 (let ((cwin (selected-window)) win beg end)
11261 (when (setq win (get-buffer-window "*Occur*"))
11262 (select-window win))
11263 (goto-char (point-min))
11264 (when (re-search-forward "match[a-z]+" nil t)
11265 (setq beg (match-end 0))
11266 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11267 (setq end (1- (match-beginning 0)))))
11268 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11269 (goto-char (point-min))
11270 (select-window cwin))))
11272 ;;; The mark ring for links jumps
11274 (defvar org-mark-ring nil
11275 "Mark ring for positions before jumps in Org mode.")
11276 (defvar org-mark-ring-last-goto nil
11277 "Last position in the mark ring used to go back.")
11278 ;; Fill and close the ring
11279 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11280 (dotimes (_ org-mark-ring-length)
11281 (push (make-marker) org-mark-ring))
11282 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11283 org-mark-ring)
11285 (defun org-mark-ring-push (&optional pos buffer)
11286 "Put the current position or POS into the mark ring and rotate it."
11287 (interactive)
11288 (setq pos (or pos (point)))
11289 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11290 (move-marker (car org-mark-ring)
11291 (or pos (point))
11292 (or buffer (current-buffer)))
11293 (message "%s"
11294 (substitute-command-keys
11295 "Position saved to mark ring, go back with \
11296 `\\[org-mark-ring-goto]'.")))
11298 (defun org-mark-ring-goto (&optional n)
11299 "Jump to the previous position in the mark ring.
11300 With prefix arg N, jump back that many stored positions. When
11301 called several times in succession, walk through the entire ring.
11302 Org mode commands jumping to a different position in the current file,
11303 or to another Org file, automatically push the old position onto the ring."
11304 (interactive "p")
11305 (let (p m)
11306 (if (eq last-command this-command)
11307 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11308 (setq p org-mark-ring))
11309 (setq org-mark-ring-last-goto p)
11310 (setq m (car p))
11311 (pop-to-buffer-same-window (marker-buffer m))
11312 (goto-char m)
11313 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11315 (defun org-add-angle-brackets (s)
11316 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11317 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11320 ;;; Following specific links
11322 (defvar org-agenda-buffer-tmp-name)
11323 (defvar org-agenda-start-on-weekday)
11324 (defun org-follow-timestamp-link ()
11325 "Open an agenda view for the time-stamp date/range at point."
11326 (cond
11327 ((org-at-date-range-p t)
11328 (let ((org-agenda-start-on-weekday)
11329 (t1 (match-string 1))
11330 (t2 (match-string 2)) tt1 tt2)
11331 (setq tt1 (time-to-days (org-time-string-to-time t1))
11332 tt2 (time-to-days (org-time-string-to-time t2)))
11333 (let ((org-agenda-buffer-tmp-name
11334 (format "*Org Agenda(a:%s)"
11335 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11336 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11337 ((org-at-timestamp-p t)
11338 (let ((org-agenda-buffer-tmp-name
11339 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11340 (org-agenda-list nil (time-to-days (org-time-string-to-time
11341 (substring (match-string 1) 0 10)))
11342 1)))
11343 (t (error "This should not happen"))))
11346 ;;; Following file links
11347 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11348 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11349 (declare-function mailcap-mime-info
11350 "mailcap" (string &optional request no-decode))
11351 (defvar org-wait nil)
11352 (defun org-open-file (path &optional in-emacs line search)
11353 "Open the file at PATH.
11354 First, this expands any special file name abbreviations. Then the
11355 configuration variable `org-file-apps' is checked if it contains an
11356 entry for this file type, and if yes, the corresponding command is launched.
11358 If no application is found, Emacs simply visits the file.
11360 With optional prefix argument IN-EMACS, Emacs will visit the file.
11361 With a double \\[universal-argument] \\[universal-argument] \
11362 prefix arg, Org tries to avoid opening in Emacs
11363 and to use an external application to visit the file.
11365 Optional LINE specifies a line to go to, optional SEARCH a string
11366 to search for. If LINE or SEARCH is given, the file will be
11367 opened in Emacs, unless an entry from org-file-apps that makes
11368 use of groups in a regexp matches.
11370 If you want to change the way frames are used when following a
11371 link, please customize `org-link-frame-setup'.
11373 If the file does not exist, an error is thrown."
11374 (let* ((file (if (equal path "")
11375 buffer-file-name
11376 (substitute-in-file-name (expand-file-name path))))
11377 (file-apps (append org-file-apps (org-default-apps)))
11378 (apps (cl-remove-if
11379 'org-file-apps-entry-match-against-dlink-p file-apps))
11380 (apps-dlink (cl-remove-if-not
11381 'org-file-apps-entry-match-against-dlink-p file-apps))
11382 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11383 (dirp (unless remp (file-directory-p file)))
11384 (file (if (and dirp org-open-directory-means-index-dot-org)
11385 (concat (file-name-as-directory file) "index.org")
11386 file))
11387 (a-m-a-p (assq 'auto-mode apps))
11388 (dfile (downcase file))
11389 ;; Reconstruct the original link from the PATH, LINE and
11390 ;; SEARCH args.
11391 (link (cond (line (concat file "::" (number-to-string line)))
11392 (search (concat file "::" search))
11393 (t file)))
11394 (dlink (downcase link))
11395 (old-buffer (current-buffer))
11396 (old-pos (point))
11397 (old-mode major-mode)
11398 (ext
11399 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11400 (match-string 1 dfile)))
11401 cmd link-match-data)
11402 (cond
11403 ((member in-emacs '((16) system))
11404 (setq cmd (cdr (assq 'system apps))))
11405 (in-emacs (setq cmd 'emacs))
11407 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11408 (and dirp (cdr (assq 'directory apps)))
11409 ;; First, try matching against apps-dlink if we
11410 ;; get a match here, store the match data for
11411 ;; later.
11412 (let ((match (assoc-default dlink apps-dlink
11413 'string-match)))
11414 (if match
11415 (progn (setq link-match-data (match-data))
11416 match)
11417 (progn (setq in-emacs (or in-emacs line search))
11418 nil))) ; if we have no match in apps-dlink,
11419 ; always open the file in emacs if line or search
11420 ; is given (for backwards compatibility)
11421 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11422 'string-match)
11423 (cdr (assoc ext apps))
11424 (cdr (assq t apps))))))
11425 (when (eq cmd 'system)
11426 (setq cmd (cdr (assq 'system apps))))
11427 (when (eq cmd 'default)
11428 (setq cmd (cdr (assoc t apps))))
11429 (when (eq cmd 'mailcap)
11430 (require 'mailcap)
11431 (mailcap-parse-mailcaps)
11432 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11433 (command (mailcap-mime-info mime-type)))
11434 (if (stringp command)
11435 (setq cmd command)
11436 (setq cmd 'emacs))))
11437 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11438 (not (file-exists-p file))
11439 (not org-open-non-existing-files))
11440 (user-error "No such file: %s" file))
11441 (cond
11442 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11443 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11444 (while (string-match "['\"]%s['\"]" cmd)
11445 (setq cmd (replace-match "%s" t t cmd)))
11446 (setq cmd (replace-regexp-in-string
11447 "%s"
11448 (shell-quote-argument (convert-standard-filename file))
11450 nil t))
11452 ;; Replace "%1", "%2" etc. in command with group matches from regex
11453 (save-match-data
11454 (let ((match-index 1)
11455 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11456 (set-match-data link-match-data)
11457 (while (<= match-index number-of-groups)
11458 (let ((regex (concat "%" (number-to-string match-index)))
11459 (replace-with (match-string match-index dlink)))
11460 (while (string-match regex cmd)
11461 (setq cmd (replace-match replace-with t t cmd))))
11462 (setq match-index (+ match-index 1)))))
11464 (save-window-excursion
11465 (message "Running %s...done" cmd)
11466 (start-process-shell-command cmd nil cmd)
11467 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11468 ((or (stringp cmd)
11469 (eq cmd 'emacs))
11470 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11471 (widen)
11472 (cond (line (org-goto-line line)
11473 (when (derived-mode-p 'org-mode) (org-reveal)))
11474 (search (org-link-search search))))
11475 ((functionp cmd)
11476 (save-match-data
11477 (set-match-data link-match-data)
11478 (condition-case nil
11479 (funcall cmd file link)
11480 ;; FIXME: Remove this check when most default installations
11481 ;; of Emacs have at least Org 9.0.
11482 ((debug wrong-number-of-arguments wrong-type-argument
11483 invalid-function)
11484 (user-error "Please see Org News for version 9.0 about \
11485 `org-file-apps'--Lisp error: %S" cmd)))))
11486 ((consp cmd)
11487 ;; FIXME: Remove this check when most default installations of
11488 ;; Emacs have at least Org 9.0.
11489 ;; Heads-up instead of silently fall back to
11490 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11491 ;; with sexp instead of a function for `cmd'.
11492 (user-error "Please see Org News for version 9.0 about \
11493 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11494 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11495 (and (derived-mode-p 'org-mode)
11496 (eq old-mode 'org-mode)
11497 (or (not (eq old-buffer (current-buffer)))
11498 (not (eq old-pos (point))))
11499 (org-mark-ring-push old-pos old-buffer))))
11501 (defun org-file-apps-entry-match-against-dlink-p (entry)
11502 "This function returns non-nil if `entry' uses a regular
11503 expression which should be matched against the whole link by
11504 org-open-file.
11506 It assumes that is the case when the entry uses a regular
11507 expression which has at least one grouping construct and the
11508 action is either a lisp form or a command string containing
11509 `%1', i.e. using at least one subexpression match as a
11510 parameter."
11511 (let ((selector (car entry))
11512 (action (cdr entry)))
11513 (if (stringp selector)
11514 (and (> (regexp-opt-depth selector) 0)
11515 (or (and (stringp action)
11516 (string-match "%[0-9]" action))
11517 (consp action)))
11518 nil)))
11520 (defun org-default-apps ()
11521 "Return the default applications for this operating system."
11522 (cond
11523 ((eq system-type 'darwin)
11524 org-file-apps-defaults-macosx)
11525 ((eq system-type 'windows-nt)
11526 org-file-apps-defaults-windowsnt)
11527 (t org-file-apps-defaults-gnu)))
11529 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11530 "Convert extensions to regular expressions in the cars of LIST.
11531 Also, weed out any non-string entries, because the return value is used
11532 only for regexp matching.
11533 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11534 point to the symbol `emacs', indicating that the file should
11535 be opened in Emacs."
11536 (append
11537 (delq nil
11538 (mapcar (lambda (x)
11539 (unless (not (stringp (car x)))
11540 (if (string-match "\\W" (car x))
11542 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11543 list))
11544 (when add-auto-mode
11545 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11547 (defvar ange-ftp-name-format)
11548 (defun org-file-remote-p (file)
11549 "Test whether FILE specifies a location on a remote system.
11550 Return non-nil if the location is indeed remote.
11552 For example, the filename \"/user@host:/foo\" specifies a location
11553 on the system \"/user@host:\"."
11554 (cond ((fboundp 'file-remote-p)
11555 (file-remote-p file))
11556 ((fboundp 'tramp-handle-file-remote-p)
11557 (tramp-handle-file-remote-p file))
11558 ((and (boundp 'ange-ftp-name-format)
11559 (string-match (car ange-ftp-name-format) file))
11560 t)))
11563 ;;;; Refiling
11565 (defun org-get-org-file ()
11566 "Read a filename, with default directory `org-directory'."
11567 (let ((default (or org-default-notes-file remember-data-file)))
11568 (read-file-name (format "File name [%s]: " default)
11569 (file-name-as-directory org-directory)
11570 default)))
11572 (defun org-notes-order-reversed-p ()
11573 "Check if the current file should receive notes in reversed order."
11574 (cond
11575 ((not org-reverse-note-order) nil)
11576 ((eq t org-reverse-note-order) t)
11577 ((not (listp org-reverse-note-order)) nil)
11578 (t (catch 'exit
11579 (dolist (entry org-reverse-note-order)
11580 (when (string-match (car entry) buffer-file-name)
11581 (throw 'exit (cdr entry))))))))
11583 (defvar org-refile-target-table nil
11584 "The list of refile targets, created by `org-refile'.")
11586 (defvar org-agenda-new-buffers nil
11587 "Buffers created to visit agenda files.")
11589 (defvar org-refile-cache nil
11590 "Cache for refile targets.")
11592 (defvar org-refile-markers nil
11593 "All the markers used for caching refile locations.")
11595 (defun org-refile-marker (pos)
11596 "Get a new refile marker, but only if caching is in use."
11597 (if (not org-refile-use-cache)
11599 (let ((m (make-marker)))
11600 (move-marker m pos)
11601 (push m org-refile-markers)
11602 m)))
11604 (defun org-refile-cache-clear ()
11605 "Clear the refile cache and disable all the markers."
11606 (dolist (m org-refile-markers) (move-marker m nil))
11607 (setq org-refile-markers nil)
11608 (setq org-refile-cache nil)
11609 (message "Refile cache has been cleared"))
11611 (defun org-refile-cache-check-set (set)
11612 "Check if all the markers in the cache still have live buffers."
11613 (let (marker)
11614 (catch 'exit
11615 (while (and set (setq marker (nth 3 (pop set))))
11616 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11617 (when (and marker (null (marker-buffer marker)))
11618 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11619 (sit-for 3)
11620 (throw 'exit nil)))
11621 t)))
11623 (defun org-refile-cache-put (set &rest identifiers)
11624 "Push the refile targets SET into the cache, under IDENTIFIERS."
11625 (let* ((key (sha1 (prin1-to-string identifiers)))
11626 (entry (assoc key org-refile-cache)))
11627 (if entry
11628 (setcdr entry set)
11629 (push (cons key set) org-refile-cache))))
11631 (defun org-refile-cache-get (&rest identifiers)
11632 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11633 (cond
11634 ((not org-refile-cache) nil)
11635 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11637 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11638 org-refile-cache))))
11639 (and set (org-refile-cache-check-set set) set)))))
11641 (defvar org-outline-path-cache nil
11642 "Alist between buffer positions and outline paths.
11643 It value is an alist (POSITION . PATH) where POSITION is the
11644 buffer position at the beginning of an entry and PATH is a list
11645 of strings describing the outline path for that entry, in reverse
11646 order.")
11648 (defun org-refile-get-targets (&optional default-buffer)
11649 "Produce a table with refile targets."
11650 (let ((case-fold-search nil)
11651 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11652 (entries (or org-refile-targets '((nil . (:level . 1)))))
11653 targets tgs files desc descre)
11654 (message "Getting targets...")
11655 (with-current-buffer (or default-buffer (current-buffer))
11656 (dolist (entry entries)
11657 (setq files (car entry) desc (cdr entry))
11658 (cond
11659 ((null files) (setq files (list (current-buffer))))
11660 ((eq files 'org-agenda-files)
11661 (setq files (org-agenda-files 'unrestricted)))
11662 ((and (symbolp files) (fboundp files))
11663 (setq files (funcall files)))
11664 ((and (symbolp files) (boundp files))
11665 (setq files (symbol-value files))))
11666 (when (stringp files) (setq files (list files)))
11667 (cond
11668 ((eq (car desc) :tag)
11669 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11670 ((eq (car desc) :todo)
11671 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11672 ((eq (car desc) :regexp)
11673 (setq descre (cdr desc)))
11674 ((eq (car desc) :level)
11675 (setq descre (concat "^\\*\\{" (number-to-string
11676 (if org-odd-levels-only
11677 (1- (* 2 (cdr desc)))
11678 (cdr desc)))
11679 "\\}[ \t]")))
11680 ((eq (car desc) :maxlevel)
11681 (setq descre (concat "^\\*\\{1," (number-to-string
11682 (if org-odd-levels-only
11683 (1- (* 2 (cdr desc)))
11684 (cdr desc)))
11685 "\\}[ \t]")))
11686 (t (error "Bad refiling target description %s" desc)))
11687 (dolist (f files)
11688 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11690 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11691 (progn
11692 (when (bufferp f)
11693 (setq f (buffer-file-name (buffer-base-buffer f))))
11694 (setq f (and f (expand-file-name f)))
11695 (when (eq org-refile-use-outline-path 'file)
11696 (push (list (file-name-nondirectory f) f nil nil) tgs))
11697 (org-with-wide-buffer
11698 (goto-char (point-min))
11699 (setq org-outline-path-cache nil)
11700 (while (re-search-forward descre nil t)
11701 (beginning-of-line)
11702 (let ((case-fold-search nil))
11703 (looking-at org-complex-heading-regexp))
11704 (let ((begin (point))
11705 (heading (match-string-no-properties 4)))
11706 (unless (or (and
11707 org-refile-target-verify-function
11708 (not
11709 (funcall org-refile-target-verify-function)))
11710 (not heading))
11711 (let ((re (format org-complex-heading-regexp-format
11712 (regexp-quote heading)))
11713 (target
11714 (if (not org-refile-use-outline-path) heading
11715 (mapconcat
11716 #'org-protect-slash
11717 (append
11718 (pcase org-refile-use-outline-path
11719 (`file (list (file-name-nondirectory
11720 (buffer-file-name
11721 (buffer-base-buffer)))))
11722 (`full-file-path
11723 (list (buffer-file-name
11724 (buffer-base-buffer))))
11725 (_ nil))
11726 (org-get-outline-path t t))
11727 "/"))))
11728 (push (list target f re (org-refile-marker (point)))
11729 tgs)))
11730 (when (= (point) begin)
11731 ;; Verification function has not moved point.
11732 (end-of-line)))))))
11733 (when org-refile-use-cache
11734 (org-refile-cache-put tgs (buffer-file-name) descre))
11735 (setq targets (append tgs targets))))))
11736 (message "Getting targets...done")
11737 (delete-dups (nreverse targets))))
11739 (defun org-protect-slash (s)
11740 (replace-regexp-in-string "/" "\\/" s nil t))
11742 (defun org--get-outline-path-1 (&optional use-cache)
11743 "Return outline path to current headline.
11745 Outline path is a list of strings, in reverse order. When
11746 optional argument USE-CACHE is non-nil, make use of a cache. See
11747 `org-get-outline-path' for details.
11749 Assume buffer is widened and point is on a headline."
11750 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11751 (let ((p (point))
11752 (heading (let ((case-fold-search nil))
11753 (looking-at org-complex-heading-regexp)
11754 (if (not (match-end 4)) ""
11755 ;; Remove statistics cookies.
11756 (org-trim
11757 (org-link-display-format
11758 (replace-regexp-in-string
11759 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11760 (match-string-no-properties 4))))))))
11761 (if (org-up-heading-safe)
11762 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11763 (when use-cache
11764 (push (cons p path) org-outline-path-cache))
11765 path)
11766 ;; This is a new root node. Since we assume we are moving
11767 ;; forward, we can drop previous cache so as to limit number
11768 ;; of associations there.
11769 (let ((path (list heading)))
11770 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11771 path)))))
11773 (defun org-get-outline-path (&optional with-self use-cache)
11774 "Return the outline path to the current entry.
11776 An outline path is a list of ancestors for current headline, as
11777 a list of strings. Statistics cookies are removed and links are
11778 replaced with their description, if any, or their path otherwise.
11780 When optional argument WITH-SELF is non-nil, the path also
11781 includes the current headline.
11783 When optional argument USE-CACHE is non-nil, cache outline paths
11784 between calls to this function so as to avoid backtracking. This
11785 argument is useful when planning to find more than one outline
11786 path in the same document. In that case, there are two
11787 conditions to satisfy:
11788 - `org-outline-path-cache' is set to nil before starting the
11789 process;
11790 - outline paths are computed by increasing buffer positions."
11791 (org-with-wide-buffer
11792 (and (or (and with-self (org-back-to-heading t))
11793 (org-up-heading-safe))
11794 (reverse (org--get-outline-path-1 use-cache)))))
11796 (defun org-format-outline-path (path &optional width prefix separator)
11797 "Format the outline path PATH for display.
11798 WIDTH is the maximum number of characters that is available.
11799 PREFIX is a prefix to be included in the returned string,
11800 such as the file name.
11801 SEPARATOR is inserted between the different parts of the path,
11802 the default is \"/\"."
11803 (setq width (or width 79))
11804 (setq path (delq nil path))
11805 (unless (> width 0)
11806 (user-error "Argument `width' must be positive"))
11807 (setq separator (or separator "/"))
11808 (let* ((org-odd-levels-only nil)
11809 (fpath (concat
11810 prefix (and prefix path separator)
11811 (mapconcat
11812 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11813 (cl-loop for head in path
11814 for n from 0
11815 collect (org-add-props
11816 head nil 'face
11817 (nth (% n org-n-level-faces) org-level-faces)))
11818 separator))))
11819 (when (> (length fpath) width)
11820 (if (< width 7)
11821 ;; It's unlikely that `width' will be this small, but don't
11822 ;; waste characters by adding ".." if it is.
11823 (setq fpath (substring fpath 0 width))
11824 (setf (substring fpath (- width 2)) "..")))
11825 fpath))
11827 (defun org-display-outline-path (&optional file current separator just-return-string)
11828 "Display the current outline path in the echo area.
11830 If FILE is non-nil, prepend the output with the file name.
11831 If CURRENT is non-nil, append the current heading to the output.
11832 SEPARATOR is passed through to `org-format-outline-path'. It separates
11833 the different parts of the path and defaults to \"/\".
11834 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11835 (interactive "P")
11836 (let* (case-fold-search
11837 (bfn (buffer-file-name (buffer-base-buffer)))
11838 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11839 res)
11840 (when current (setq path (append path
11841 (save-excursion
11842 (org-back-to-heading t)
11843 (when (looking-at org-complex-heading-regexp)
11844 (list (match-string 4)))))))
11845 (setq res
11846 (org-format-outline-path
11847 path
11848 (1- (frame-width))
11849 (and file bfn (concat (file-name-nondirectory bfn) separator))
11850 separator))
11851 (if just-return-string
11852 (org-no-properties res)
11853 (org-unlogged-message "%s" res))))
11855 (defvar org-refile-history nil
11856 "History for refiling operations.")
11858 (defvar org-after-refile-insert-hook nil
11859 "Hook run after `org-refile' has inserted its stuff at the new location.
11860 Note that this is still *before* the stuff will be removed from
11861 the *old* location.")
11863 (defvar org-capture-last-stored-marker)
11864 (defvar org-refile-keep nil
11865 "Non-nil means `org-refile' will copy instead of refile.")
11867 (defun org-copy ()
11868 "Like `org-refile', but copy."
11869 (interactive)
11870 (let ((org-refile-keep t))
11871 (funcall 'org-refile nil nil nil "Copy")))
11873 (defun org-refile (&optional arg default-buffer rfloc msg)
11874 "Move the entry or entries at point to another heading.
11876 The list of target headings is compiled using the information in
11877 `org-refile-targets', which see.
11879 At the target location, the entry is filed as a subitem of the
11880 target heading. Depending on `org-reverse-note-order', the new
11881 subitem will either be the first or the last subitem.
11883 If there is an active region, all entries in that region will be
11884 refiled. However, the region must fulfill the requirement that
11885 the first heading sets the top-level of the moved text.
11887 With a `\\[universal-argument]' ARG, the command will only visit the target \
11888 location
11889 and not actually move anything.
11891 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11892 location where the last
11893 refiling operation has put the subtree.
11895 With a numeric prefix argument of `2', refile to the running clock.
11897 With a numeric prefix argument of `3', emulate `org-refile-keep'
11898 being set to t and copy to the target location, don't move it.
11899 Beware that keeping refiled entries may result in duplicated ID
11900 properties.
11902 RFLOC can be a refile location obtained in a different way.
11904 MSG is a string to replace \"Refile\" in the default prompt with
11905 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11907 See also `org-refile-use-outline-path'.
11909 If you are using target caching (see `org-refile-use-cache'), you
11910 have to clear the target cache in order to find new targets.
11911 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11912 prefix argument (`C-u C-u C-u C-c C-w')."
11913 (interactive "P")
11914 (if (member arg '(0 (64)))
11915 (org-refile-cache-clear)
11916 (let* ((actionmsg (cond (msg msg)
11917 ((equal arg 3) "Refile (and keep)")
11918 (t "Refile")))
11919 (regionp (org-region-active-p))
11920 (region-start (and regionp (region-beginning)))
11921 (region-end (and regionp (region-end)))
11922 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11923 pos it nbuf file level reversed)
11924 (setq last-command nil)
11925 (when regionp
11926 (goto-char region-start)
11927 (or (bolp) (goto-char (point-at-bol)))
11928 (setq region-start (point))
11929 (unless (or (org-kill-is-subtree-p
11930 (buffer-substring region-start region-end))
11931 (prog1 org-refile-active-region-within-subtree
11932 (let ((s (point-at-eol)))
11933 (org-toggle-heading)
11934 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11935 (user-error "The region is not a (sequence of) subtree(s)")))
11936 (if (equal arg '(16))
11937 (org-refile-goto-last-stored)
11938 (when (or
11939 (and (equal arg 2)
11940 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11941 (prog1
11942 (setq it (list (or org-clock-heading "running clock")
11943 (buffer-file-name
11944 (marker-buffer org-clock-hd-marker))
11946 (marker-position org-clock-hd-marker)))
11947 (setq arg nil)))
11948 (setq it
11949 (or rfloc
11950 (let (heading-text)
11951 (save-excursion
11952 (unless (and arg (listp arg))
11953 (org-back-to-heading t)
11954 (setq heading-text
11955 (replace-regexp-in-string
11956 org-bracket-link-regexp
11957 "\\3"
11958 (or (nth 4 (org-heading-components))
11959 ""))))
11960 (org-refile-get-location
11961 (cond ((and arg (listp arg)) "Goto")
11962 (regionp (concat actionmsg " region to"))
11963 (t (concat actionmsg " subtree \""
11964 heading-text "\" to")))
11965 default-buffer
11966 (and (not (equal '(4) arg))
11967 org-refile-allow-creating-parent-nodes)))))))
11968 (setq file (nth 1 it)
11969 pos (nth 3 it))
11970 (when (and (not arg)
11972 (equal (buffer-file-name) file)
11973 (if regionp
11974 (and (>= pos region-start)
11975 (<= pos region-end))
11976 (and (>= pos (point))
11977 (< pos (save-excursion
11978 (org-end-of-subtree t t))))))
11979 (error "Cannot refile to position inside the tree or region"))
11980 (setq nbuf (or (find-buffer-visiting file)
11981 (find-file-noselect file)))
11982 (if (and arg (not (equal arg 3)))
11983 (progn
11984 (pop-to-buffer-same-window nbuf)
11985 (goto-char pos)
11986 (org-show-context 'org-goto))
11987 (if regionp
11988 (progn
11989 (org-kill-new (buffer-substring region-start region-end))
11990 (org-save-markers-in-region region-start region-end))
11991 (org-copy-subtree 1 nil t))
11992 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11993 (find-file-noselect file)))
11994 (setq reversed (org-notes-order-reversed-p))
11995 (org-with-wide-buffer
11996 (if pos
11997 (progn
11998 (goto-char pos)
11999 (looking-at org-outline-regexp)
12000 (setq level (org-get-valid-level (funcall outline-level) 1))
12001 (goto-char
12002 (if reversed
12003 (or (outline-next-heading) (point-max))
12004 (or (save-excursion (org-get-next-sibling))
12005 (org-end-of-subtree t t)
12006 (point-max)))))
12007 (setq level 1)
12008 (if (not reversed)
12009 (goto-char (point-max))
12010 (goto-char (point-min))
12011 (or (outline-next-heading) (goto-char (point-max)))))
12012 (unless (bolp) (newline))
12013 (org-paste-subtree level nil nil t)
12014 (when org-log-refile
12015 (org-add-log-setup 'refile nil nil org-log-refile)
12016 (unless (eq org-log-refile 'note)
12017 (save-excursion (org-add-log-note))))
12018 (and org-auto-align-tags
12019 (let ((org-loop-over-headlines-in-active-region nil))
12020 (org-set-tags nil t)))
12021 (let ((bookmark-name (plist-get org-bookmark-names-plist
12022 :last-refile)))
12023 (when bookmark-name
12024 (with-demoted-errors
12025 (bookmark-set bookmark-name))))
12026 ;; If we are refiling for capture, make sure that the
12027 ;; last-capture pointers point here
12028 (when (bound-and-true-p org-capture-is-refiling)
12029 (let ((bookmark-name (plist-get org-bookmark-names-plist
12030 :last-capture-marker)))
12031 (when bookmark-name
12032 (with-demoted-errors
12033 (bookmark-set bookmark-name))))
12034 (move-marker org-capture-last-stored-marker (point)))
12035 (when (fboundp 'deactivate-mark) (deactivate-mark))
12036 (run-hooks 'org-after-refile-insert-hook)))
12037 (unless org-refile-keep
12038 (if regionp
12039 (delete-region (point) (+ (point) (- region-end region-start)))
12040 (delete-region
12041 (and (org-back-to-heading t) (point))
12042 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12043 (when (featurep 'org-inlinetask)
12044 (org-inlinetask-remove-END-maybe))
12045 (setq org-markers-to-move nil)
12046 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12048 (defun org-refile-goto-last-stored ()
12049 "Go to the location where the last refile was stored."
12050 (interactive)
12051 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12052 (message "This is the location of the last refile"))
12054 (defun org-refile--get-location (refloc tbl)
12055 "When user refile to REFLOC, find the associated target in TBL.
12056 Also check `org-refile-target-table'."
12057 (car (delq
12059 (mapcar
12060 (lambda (r) (or (assoc r tbl)
12061 (assoc r org-refile-target-table)))
12062 (list (replace-regexp-in-string "/$" "" refloc)
12063 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12065 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12066 "Prompt the user for a refile location, using PROMPT.
12067 PROMPT should not be suffixed with a colon and a space, because
12068 this function appends the default value from
12069 `org-refile-history' automatically, if that is not empty."
12070 (let ((org-refile-targets org-refile-targets)
12071 (org-refile-use-outline-path org-refile-use-outline-path))
12072 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12073 (unless org-refile-target-table
12074 (user-error "No refile targets"))
12075 (let* ((cbuf (current-buffer))
12076 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12077 (cfunc (if (and org-refile-use-outline-path
12078 org-outline-path-complete-in-steps)
12079 #'org-olpath-completing-read
12080 #'completing-read))
12081 (extra (if org-refile-use-outline-path "/" ""))
12082 (cbnex (concat (buffer-name) extra))
12083 (filename (and cfn (expand-file-name cfn)))
12084 (tbl (mapcar
12085 (lambda (x)
12086 (if (and (not (member org-refile-use-outline-path
12087 '(file full-file-path)))
12088 (not (equal filename (nth 1 x))))
12089 (cons (concat (car x) extra " ("
12090 (file-name-nondirectory (nth 1 x)) ")")
12091 (cdr x))
12092 (cons (concat (car x) extra) (cdr x))))
12093 org-refile-target-table))
12094 (completion-ignore-case t)
12095 cdef
12096 (prompt (concat prompt
12097 (or (and (car org-refile-history)
12098 (concat " (default " (car org-refile-history) ")"))
12099 (and (assoc cbnex tbl) (setq cdef cbnex)
12100 (concat " (default " cbnex ")"))) ": "))
12101 pa answ parent-target child parent old-hist)
12102 (setq old-hist org-refile-history)
12103 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12104 nil 'org-refile-history (or cdef (car org-refile-history))))
12105 (if (setq pa (org-refile--get-location answ tbl))
12106 (progn
12107 (org-refile-check-position pa)
12108 (when (or (not org-refile-history)
12109 (not (eq old-hist org-refile-history))
12110 (not (equal (car pa) (car org-refile-history))))
12111 (setq org-refile-history
12112 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12113 org-refile-history
12114 (cdr org-refile-history))))
12115 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12116 (pop org-refile-history)))
12118 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12119 (progn
12120 (setq parent (match-string 1 answ)
12121 child (match-string 2 answ))
12122 (setq parent-target (org-refile--get-location parent tbl))
12123 (when (and parent-target
12124 (or (eq new-nodes t)
12125 (and (eq new-nodes 'confirm)
12126 (y-or-n-p (format "Create new node \"%s\"? "
12127 child)))))
12128 (org-refile-new-child parent-target child)))
12129 (user-error "Invalid target location")))))
12131 (declare-function org-string-nw-p "org-macs" (s))
12132 (defun org-refile-check-position (refile-pointer)
12133 "Check if the refile pointer matches the headline to which it points."
12134 (let* ((file (nth 1 refile-pointer))
12135 (re (nth 2 refile-pointer))
12136 (pos (nth 3 refile-pointer))
12137 buffer)
12138 (if (and (not (markerp pos)) (not file))
12139 (user-error "Please indicate a target file in the refile path")
12140 (when (org-string-nw-p re)
12141 (setq buffer (if (markerp pos)
12142 (marker-buffer pos)
12143 (or (find-buffer-visiting file)
12144 (find-file-noselect file))))
12145 (with-current-buffer buffer
12146 (org-with-wide-buffer
12147 (goto-char pos)
12148 (beginning-of-line 1)
12149 (unless (looking-at-p re)
12150 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12152 (defun org-refile-new-child (parent-target child)
12153 "Use refile target PARENT-TARGET to add new CHILD below it."
12154 (unless parent-target
12155 (error "Cannot find parent for new node"))
12156 (let ((file (nth 1 parent-target))
12157 (pos (nth 3 parent-target))
12158 level)
12159 (with-current-buffer (or (find-buffer-visiting file)
12160 (find-file-noselect file))
12161 (org-with-wide-buffer
12162 (if pos
12163 (goto-char pos)
12164 (goto-char (point-max))
12165 (unless (bolp) (newline)))
12166 (when (looking-at org-outline-regexp)
12167 (setq level (funcall outline-level))
12168 (org-end-of-subtree t t))
12169 (org-back-over-empty-lines)
12170 (insert "\n" (make-string
12171 (if pos (org-get-valid-level level 1) 1) ?*)
12172 " " child "\n")
12173 (beginning-of-line 0)
12174 (list (concat (car parent-target) "/" child) file "" (point))))))
12176 (defun org-olpath-completing-read (prompt collection &rest args)
12177 "Read an outline path like a file name."
12178 (let ((thetable collection))
12179 (apply #'completing-read
12180 prompt
12181 (lambda (string predicate &optional flag)
12182 (cond
12183 ((eq flag nil) (try-completion string thetable))
12184 ((eq flag t)
12185 (let ((l (length string)))
12186 (mapcar (lambda (x)
12187 (let ((r (substring x l))
12188 (f (if (string-match " ([^)]*)$" x)
12189 (match-string 0 x)
12190 "")))
12191 (if (string-match "/" r)
12192 (concat string (substring r 0 (match-end 0)) f)
12193 x)))
12194 (all-completions string thetable predicate))))
12195 ;; Exact match?
12196 ((eq flag 'lambda) (assoc string thetable))))
12197 args)))
12199 ;;;; Dynamic blocks
12201 (defun org-find-dblock (name)
12202 "Find the first dynamic block with name NAME in the buffer.
12203 If not found, stay at current position and return nil."
12204 (let ((case-fold-search t) pos)
12205 (save-excursion
12206 (goto-char (point-min))
12207 (setq pos (and (re-search-forward
12208 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12209 (match-beginning 0))))
12210 (when pos (goto-char pos))
12211 pos))
12213 (defun org-create-dblock (plist)
12214 "Create a dynamic block section, with parameters taken from PLIST.
12215 PLIST must contain a :name entry which is used as the name of the block."
12216 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12217 (end-of-line 1)
12218 (newline))
12219 (let ((col (current-column))
12220 (name (plist-get plist :name)))
12221 (insert "#+BEGIN: " name)
12222 (while plist
12223 (if (eq (car plist) :name)
12224 (setq plist (cddr plist))
12225 (insert " " (prin1-to-string (pop plist)))))
12226 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12227 (beginning-of-line -2)))
12229 (defun org-prepare-dblock ()
12230 "Prepare dynamic block for refresh.
12231 This empties the block, puts the cursor at the insert position and returns
12232 the property list including an extra property :name with the block name."
12233 (unless (looking-at org-dblock-start-re)
12234 (user-error "Not at a dynamic block"))
12235 (let* ((begdel (1+ (match-end 0)))
12236 (name (org-no-properties (match-string 1)))
12237 (params (append (list :name name)
12238 (read (concat "(" (match-string 3) ")")))))
12239 (save-excursion
12240 (beginning-of-line 1)
12241 (skip-chars-forward " \t")
12242 (setq params (plist-put params :indentation-column (current-column))))
12243 (unless (re-search-forward org-dblock-end-re nil t)
12244 (error "Dynamic block not terminated"))
12245 (setq params
12246 (append params
12247 (list :content (buffer-substring
12248 begdel (match-beginning 0)))))
12249 (delete-region begdel (match-beginning 0))
12250 (goto-char begdel)
12251 (open-line 1)
12252 params))
12254 (defun org-map-dblocks (&optional command)
12255 "Apply COMMAND to all dynamic blocks in the current buffer.
12256 If COMMAND is not given, use `org-update-dblock'."
12257 (let ((cmd (or command 'org-update-dblock)))
12258 (save-excursion
12259 (goto-char (point-min))
12260 (while (re-search-forward org-dblock-start-re nil t)
12261 (goto-char (match-beginning 0))
12262 (save-excursion
12263 (condition-case nil
12264 (funcall cmd)
12265 (error (message "Error during update of dynamic block"))))
12266 (unless (re-search-forward org-dblock-end-re nil t)
12267 (error "Dynamic block not terminated"))))))
12269 (defun org-dblock-update (&optional arg)
12270 "User command for updating dynamic blocks.
12271 Update the dynamic block at point. With prefix ARG, update all dynamic
12272 blocks in the buffer."
12273 (interactive "P")
12274 (if arg
12275 (org-update-all-dblocks)
12276 (or (looking-at org-dblock-start-re)
12277 (org-beginning-of-dblock))
12278 (org-update-dblock)))
12280 (defun org-update-dblock ()
12281 "Update the dynamic block at point.
12282 This means to empty the block, parse for parameters and then call
12283 the correct writing function."
12284 (interactive)
12285 (save-excursion
12286 (let* ((win (selected-window))
12287 (pos (point))
12288 (line (org-current-line))
12289 (params (org-prepare-dblock))
12290 (name (plist-get params :name))
12291 (indent (plist-get params :indentation-column))
12292 (cmd (intern (concat "org-dblock-write:" name))))
12293 (message "Updating dynamic block `%s' at line %d..." name line)
12294 (funcall cmd params)
12295 (message "Updating dynamic block `%s' at line %d...done" name line)
12296 (goto-char pos)
12297 (when (and indent (> indent 0))
12298 (setq indent (make-string indent ?\ ))
12299 (save-excursion
12300 (select-window win)
12301 (org-beginning-of-dblock)
12302 (forward-line 1)
12303 (while (not (looking-at org-dblock-end-re))
12304 (insert indent)
12305 (beginning-of-line 2))
12306 (when (looking-at org-dblock-end-re)
12307 (and (looking-at "[ \t]+")
12308 (replace-match ""))
12309 (insert indent)))))))
12311 (defun org-beginning-of-dblock ()
12312 "Find the beginning of the dynamic block at point.
12313 Error if there is no such block at point."
12314 (let ((pos (point))
12315 beg)
12316 (end-of-line 1)
12317 (if (and (re-search-backward org-dblock-start-re nil t)
12318 (setq beg (match-beginning 0))
12319 (re-search-forward org-dblock-end-re nil t)
12320 (> (match-end 0) pos))
12321 (goto-char beg)
12322 (goto-char pos)
12323 (error "Not in a dynamic block"))))
12325 (defun org-update-all-dblocks ()
12326 "Update all dynamic blocks in the buffer.
12327 This function can be used in a hook."
12328 (interactive)
12329 (when (derived-mode-p 'org-mode)
12330 (org-map-dblocks 'org-update-dblock)))
12333 ;;;; Completion
12335 (declare-function org-export-backend-options "ox" (cl-x) t)
12336 (defun org-get-export-keywords ()
12337 "Return a list of all currently understood export keywords.
12338 Export keywords include options, block names, attributes and
12339 keywords relative to each registered export back-end."
12340 (let (keywords)
12341 (dolist (backend
12342 (bound-and-true-p org-export-registered-backends)
12343 (delq nil keywords))
12344 ;; Back-end name (for keywords, like #+LATEX:)
12345 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12346 (dolist (option-entry (org-export-backend-options backend))
12347 ;; Back-end options.
12348 (push (nth 1 option-entry) keywords)))))
12350 (defconst org-options-keywords
12351 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12352 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12353 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12354 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12355 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12357 (defcustom org-structure-template-alist
12358 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12359 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12360 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12361 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12362 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12363 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12364 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12365 ("L" "#+LaTeX: ")
12366 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12367 ("H" "#+HTML: ")
12368 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12369 ("A" "#+ASCII: ")
12370 ("i" "#+INDEX: ?")
12371 ("I" "#+INCLUDE: %file ?"))
12372 "Structure completion elements.
12373 This is a list of abbreviation keys and values. The value gets inserted
12374 if you type `<' followed by the key and then press the completion key,
12375 usually `TAB'. %file will be replaced by a file name after prompting
12376 for the file using completion. The cursor will be placed at the position
12377 of the `?' in the template.
12378 There are two templates for each key, the first uses the original Org syntax,
12379 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12380 the default when the /org-mtags.el/ module has been loaded. See also the
12381 variable `org-mtags-prefer-muse-templates'."
12382 :group 'org-completion
12383 :type '(repeat
12384 (list
12385 (string :tag "Key")
12386 (string :tag "Template")))
12387 :version "26.1"
12388 :package-version '(Org . "8.3"))
12390 (defun org-try-structure-completion ()
12391 "Try to complete a structure template before point.
12392 This looks for strings like \"<e\" on an otherwise empty line and
12393 expands them."
12394 (let ((l (buffer-substring (point-at-bol) (point)))
12396 (when (and (looking-at "[ \t]*$")
12397 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12398 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12399 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12400 (match-beginning 1)) a)
12401 t)))
12403 (defun org-complete-expand-structure-template (start cell)
12404 "Expand a structure template."
12405 (let ((rpl (nth 1 cell))
12406 (ind ""))
12407 (delete-region start (point))
12408 (when (string-match "\\`[ \t]*#\\+" rpl)
12409 (cond
12410 ((bolp))
12411 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12412 (setq ind (buffer-substring (point-at-bol) (point))))
12413 (t (newline))))
12414 (setq start (point))
12415 (when (string-match "%file" rpl)
12416 (setq rpl (replace-match
12417 (concat
12418 "\""
12419 (save-match-data
12420 (abbreviate-file-name (read-file-name "Include file: ")))
12421 "\"")
12422 t t rpl)))
12423 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12424 (concat "\n" ind)))
12425 (insert rpl)
12426 (when (re-search-backward "\\?" start t) (delete-char 1))))
12428 ;;;; TODO, DEADLINE, Comments
12430 (defun org-toggle-comment ()
12431 "Change the COMMENT state of an entry."
12432 (interactive)
12433 (save-excursion
12434 (org-back-to-heading)
12435 (let ((case-fold-search nil))
12436 (looking-at org-complex-heading-regexp))
12437 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12438 (skip-chars-forward " \t")
12439 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12440 (if (org-in-commented-heading-p t)
12441 (delete-region (point)
12442 (progn (search-forward " " (line-end-position) 'move)
12443 (skip-chars-forward " \t")
12444 (point)))
12445 (insert org-comment-string)
12446 (unless (eolp) (insert " ")))))
12448 (defvar org-last-todo-state-is-todo nil
12449 "This is non-nil when the last TODO state change led to a TODO state.
12450 If the last change removed the TODO tag or switched to DONE, then
12451 this is nil.")
12453 (defvar org-setting-tags nil) ; dynamically skipped
12455 (defvar org-todo-setup-filter-hook nil
12456 "Hook for functions that pre-filter todo specs.
12457 Each function takes a todo spec and returns either nil or the spec
12458 transformed into canonical form." )
12460 (defvar org-todo-get-default-hook nil
12461 "Hook for functions that get a default item for todo.
12462 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12463 nil or a string to be used for the todo mark." )
12465 (defvar org-agenda-headline-snapshot-before-repeat)
12467 (defun org-current-effective-time ()
12468 "Return current time adjusted for `org-extend-today-until' variable."
12469 (let* ((ct (org-current-time))
12470 (dct (decode-time ct))
12471 (ct1
12472 (cond
12473 (org-use-last-clock-out-time-as-effective-time
12474 (or (org-clock-get-last-clock-out-time) ct))
12475 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12476 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12477 (t ct))))
12478 ct1))
12480 (defun org-todo-yesterday (&optional arg)
12481 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12482 (interactive "P")
12483 (if (eq major-mode 'org-agenda-mode)
12484 (apply 'org-agenda-todo-yesterday arg)
12485 (let* ((org-use-effective-time t)
12486 (hour (nth 2 (decode-time (org-current-time))))
12487 (org-extend-today-until (1+ hour)))
12488 (org-todo arg))))
12490 (defvar org-block-entry-blocking ""
12491 "First entry preventing the TODO state change.")
12493 (defun org-cancel-repeater ()
12494 "Cancel a repeater by setting its numeric value to zero."
12495 (interactive)
12496 (save-excursion
12497 (org-back-to-heading t)
12498 (let ((bound1 (point))
12499 (bound0 (save-excursion (outline-next-heading) (point))))
12500 (when (and (re-search-forward
12501 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12502 org-deadline-time-regexp "\\)\\|\\("
12503 org-ts-regexp "\\)")
12504 bound0 t)
12505 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12506 bound1 t))
12507 (replace-match "0" t nil nil 1)))))
12509 (defvar org-state)
12510 (defvar org-blocked-by-checkboxes)
12511 (defun org-todo (&optional arg)
12512 "Change the TODO state of an item.
12514 The state of an item is given by a keyword at the start of the heading,
12515 like
12516 *** TODO Write paper
12517 *** DONE Call mom
12519 The different keywords are specified in the variable `org-todo-keywords'.
12520 By default the available states are \"TODO\" and \"DONE\". So, for this
12521 example: when the item starts with TODO, it is changed to DONE.
12522 When it starts with DONE, the DONE is removed. And when neither TODO nor
12523 DONE are present, add TODO at the beginning of the heading.
12525 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12526 state.
12527 With numeric prefix ARG, switch to that state.
12528 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12529 next set of TODO \
12530 keywords (nextset).
12531 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12532 prefix, circumvent any state blocking.
12533 With a numeric prefix arg of 0, inhibit note taking for the change.
12534 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12536 When called through ELisp, arg is also interpreted in the following way:
12537 `none' -> empty state
12538 \"\" -> switch to empty state
12539 `done' -> switch to DONE
12540 `nextset' -> switch to the next set of keywords
12541 `previousset' -> switch to the previous set of keywords
12542 \"WAITING\" -> switch to the specified keyword, but only if it
12543 really is a member of `org-todo-keywords'."
12544 (interactive "P")
12545 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12546 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12547 'region-start-level 'region))
12548 org-loop-over-headlines-in-active-region)
12549 (org-map-entries
12550 `(org-todo ,arg)
12551 org-loop-over-headlines-in-active-region
12552 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12553 (when (equal arg '(16)) (setq arg 'nextset))
12554 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12555 (let ((org-blocker-hook org-blocker-hook)
12556 commentp
12557 case-fold-search)
12558 (when (equal arg '(64))
12559 (setq arg nil org-blocker-hook nil))
12560 (when (and org-blocker-hook
12561 (or org-inhibit-blocking
12562 (org-entry-get nil "NOBLOCKING")))
12563 (setq org-blocker-hook nil))
12564 (save-excursion
12565 (catch 'exit
12566 (org-back-to-heading t)
12567 (when (org-in-commented-heading-p t)
12568 (org-toggle-comment)
12569 (setq commentp t))
12570 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12571 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12572 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12573 (let* ((match-data (match-data))
12574 (startpos (point-at-bol))
12575 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12576 (org-log-done org-log-done)
12577 (org-log-repeat org-log-repeat)
12578 (org-todo-log-states org-todo-log-states)
12579 (org-inhibit-logging
12580 (if (equal arg 0)
12581 (progn (setq arg nil) 'note) org-inhibit-logging))
12582 (this (match-string 1))
12583 (hl-pos (match-beginning 0))
12584 (head (org-get-todo-sequence-head this))
12585 (ass (assoc head org-todo-kwd-alist))
12586 (interpret (nth 1 ass))
12587 (done-word (nth 3 ass))
12588 (final-done-word (nth 4 ass))
12589 (org-last-state (or this ""))
12590 (completion-ignore-case t)
12591 (member (member this org-todo-keywords-1))
12592 (tail (cdr member))
12593 (org-state (cond
12594 ((and org-todo-key-trigger
12595 (or (and (equal arg '(4))
12596 (eq org-use-fast-todo-selection 'prefix))
12597 (and (not arg) org-use-fast-todo-selection
12598 (not (eq org-use-fast-todo-selection
12599 'prefix)))))
12600 ;; Use fast selection.
12601 (org-fast-todo-selection))
12602 ((and (equal arg '(4))
12603 (or (not org-use-fast-todo-selection)
12604 (not org-todo-key-trigger)))
12605 ;; Read a state with completion.
12606 (completing-read
12607 "State: " (mapcar #'list org-todo-keywords-1)
12608 nil t))
12609 ((eq arg 'right)
12610 (if this
12611 (if tail (car tail) nil)
12612 (car org-todo-keywords-1)))
12613 ((eq arg 'left)
12614 (unless (equal member org-todo-keywords-1)
12615 (if this
12616 (nth (- (length org-todo-keywords-1)
12617 (length tail) 2)
12618 org-todo-keywords-1)
12619 (org-last org-todo-keywords-1))))
12620 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12621 (setq arg nil))) ;hack to fall back to cycling
12622 (arg
12623 ;; User or caller requests a specific state.
12624 (cond
12625 ((equal arg "") nil)
12626 ((eq arg 'none) nil)
12627 ((eq arg 'done) (or done-word (car org-done-keywords)))
12628 ((eq arg 'nextset)
12629 (or (car (cdr (member head org-todo-heads)))
12630 (car org-todo-heads)))
12631 ((eq arg 'previousset)
12632 (let ((org-todo-heads (reverse org-todo-heads)))
12633 (or (car (cdr (member head org-todo-heads)))
12634 (car org-todo-heads))))
12635 ((car (member arg org-todo-keywords-1)))
12636 ((stringp arg)
12637 (user-error "State `%s' not valid in this file" arg))
12638 ((nth (1- (prefix-numeric-value arg))
12639 org-todo-keywords-1))))
12640 ((null member) (or head (car org-todo-keywords-1)))
12641 ((equal this final-done-word) nil) ;-> make empty
12642 ((null tail) nil) ;-> first entry
12643 ((memq interpret '(type priority))
12644 (if (eq this-command last-command)
12645 (car tail)
12646 (if (> (length tail) 0)
12647 (or done-word (car org-done-keywords))
12648 nil)))
12650 (car tail))))
12651 (org-state (or
12652 (run-hook-with-args-until-success
12653 'org-todo-get-default-hook org-state org-last-state)
12654 org-state))
12655 (next (if org-state (concat " " org-state " ") " "))
12656 (change-plist (list :type 'todo-state-change :from this :to org-state
12657 :position startpos))
12658 dolog now-done-p)
12659 (when org-blocker-hook
12660 (let (org-blocked-by-checkboxes block-reason)
12661 (setq org-last-todo-state-is-todo
12662 (not (member this org-done-keywords)))
12663 (unless (save-excursion
12664 (save-match-data
12665 (org-with-wide-buffer
12666 (run-hook-with-args-until-failure
12667 'org-blocker-hook change-plist))))
12668 (setq block-reason (if org-blocked-by-checkboxes
12669 "contained checkboxes"
12670 (format "\"%s\"" org-block-entry-blocking)))
12671 (if (called-interactively-p 'interactive)
12672 (user-error "TODO state change from %s to %s blocked (by %s)"
12673 this org-state block-reason)
12674 ;; Fail silently.
12675 (message "TODO state change from %s to %s blocked (by %s)"
12676 this org-state block-reason)
12677 (throw 'exit nil)))))
12678 (store-match-data match-data)
12679 (replace-match next t t)
12680 (cond ((equal this org-state)
12681 (message "TODO state was already %s" (org-trim next)))
12682 ((not (pos-visible-in-window-p hl-pos))
12683 (message "TODO state changed to %s" (org-trim next))))
12684 (unless head
12685 (setq head (org-get-todo-sequence-head org-state)
12686 ass (assoc head org-todo-kwd-alist)
12687 interpret (nth 1 ass)
12688 done-word (nth 3 ass)
12689 final-done-word (nth 4 ass)))
12690 (when (memq arg '(nextset previousset))
12691 (message "Keyword-Set %d/%d: %s"
12692 (- (length org-todo-sets) -1
12693 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12694 (length org-todo-sets)
12695 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12696 (setq org-last-todo-state-is-todo
12697 (not (member org-state org-done-keywords)))
12698 (setq now-done-p (and (member org-state org-done-keywords)
12699 (not (member this org-done-keywords))))
12700 (and logging (org-local-logging logging))
12701 (when (and (or org-todo-log-states org-log-done)
12702 (not (eq org-inhibit-logging t))
12703 (not (memq arg '(nextset previousset))))
12704 ;; We need to look at recording a time and note.
12705 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12706 (nth 2 (assoc this org-todo-log-states))))
12707 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12708 (setq dolog 'time))
12709 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12710 (and org-state
12711 (member org-state org-not-done-keywords)
12712 (not (member this org-not-done-keywords))))
12713 ;; This is now a todo state and was not one before
12714 ;; If there was a CLOSED time stamp, get rid of it.
12715 (org-add-planning-info nil nil 'closed))
12716 (when (and now-done-p org-log-done)
12717 ;; It is now done, and it was not done before.
12718 (org-add-planning-info 'closed (org-current-effective-time))
12719 (when (and (not dolog) (eq 'note org-log-done))
12720 (org-add-log-setup 'done org-state this 'note)))
12721 (when (and org-state dolog)
12722 ;; This is a non-nil state, and we need to log it.
12723 (org-add-log-setup 'state org-state this dolog)))
12724 ;; Fixup tag positioning.
12725 (org-todo-trigger-tag-changes org-state)
12726 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12727 (when org-provide-todo-statistics
12728 (org-update-parent-todo-statistics))
12729 (run-hooks 'org-after-todo-state-change-hook)
12730 (when (and arg (not (member org-state org-done-keywords)))
12731 (setq head (org-get-todo-sequence-head org-state)))
12732 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12733 ;; Do we need to trigger a repeat?
12734 (when now-done-p
12735 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12736 ;; This is for the agenda, take a snapshot of the headline.
12737 (save-match-data
12738 (setq org-agenda-headline-snapshot-before-repeat
12739 (org-get-heading))))
12740 (org-auto-repeat-maybe org-state))
12741 ;; Fixup cursor location if close to the keyword.
12742 (when (and (outline-on-heading-p)
12743 (not (bolp))
12744 (save-excursion (beginning-of-line 1)
12745 (looking-at org-todo-line-regexp))
12746 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12747 (goto-char (or (match-end 2) (match-end 1)))
12748 (and (looking-at " ") (just-one-space)))
12749 (when org-trigger-hook
12750 (save-excursion
12751 (run-hook-with-args 'org-trigger-hook change-plist)))
12752 (when commentp (org-toggle-comment))))))))
12754 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12755 "Block turning an entry into a TODO, using the hierarchy.
12756 This checks whether the current task should be blocked from state
12757 changes. Such blocking occurs when:
12759 1. The task has children which are not all in a completed state.
12761 2. A task has a parent with the property :ORDERED:, and there
12762 are siblings prior to the current task with incomplete
12763 status.
12765 3. The parent of the task is blocked because it has siblings that should
12766 be done first, or is child of a block grandparent TODO entry."
12768 (if (not org-enforce-todo-dependencies)
12769 t ; if locally turned off don't block
12770 (catch 'dont-block
12771 ;; If this is not a todo state change, or if this entry is already DONE,
12772 ;; do not block
12773 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12774 (member (plist-get change-plist :from)
12775 (cons 'done org-done-keywords))
12776 (member (plist-get change-plist :to)
12777 (cons 'todo org-not-done-keywords))
12778 (not (plist-get change-plist :to)))
12779 (throw 'dont-block t))
12780 ;; If this task has children, and any are undone, it's blocked
12781 (save-excursion
12782 (org-back-to-heading t)
12783 (let ((this-level (funcall outline-level)))
12784 (outline-next-heading)
12785 (let ((child-level (funcall outline-level)))
12786 (while (and (not (eobp))
12787 (> child-level this-level))
12788 ;; this todo has children, check whether they are all
12789 ;; completed
12790 (when (and (not (org-entry-is-done-p))
12791 (org-entry-is-todo-p))
12792 (setq org-block-entry-blocking (org-get-heading))
12793 (throw 'dont-block nil))
12794 (outline-next-heading)
12795 (setq child-level (funcall outline-level))))))
12796 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12797 ;; any previous siblings are undone, it's blocked
12798 (save-excursion
12799 (org-back-to-heading t)
12800 (let* ((pos (point))
12801 (parent-pos (and (org-up-heading-safe) (point)))
12802 (case-fold-search nil))
12803 (unless parent-pos (throw 'dont-block t)) ; no parent
12804 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12805 (forward-line 1)
12806 (re-search-forward org-not-done-heading-regexp pos t))
12807 (setq org-block-entry-blocking (match-string 0))
12808 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12809 ;; Search further up the hierarchy, to see if an ancestor is blocked
12810 (while t
12811 (goto-char parent-pos)
12812 (unless (looking-at org-not-done-heading-regexp)
12813 (throw 'dont-block t)) ; do not block, parent is not a TODO
12814 (setq pos (point))
12815 (setq parent-pos (and (org-up-heading-safe) (point)))
12816 (unless parent-pos (throw 'dont-block t)) ; no parent
12817 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12818 (forward-line 1)
12819 (re-search-forward org-not-done-heading-regexp pos t)
12820 (setq org-block-entry-blocking (org-get-heading)))
12821 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12823 (defcustom org-track-ordered-property-with-tag nil
12824 "Should the ORDERED property also be shown as a tag?
12825 The ORDERED property decides if an entry should require subtasks to be
12826 completed in sequence. Since a property is not very visible, setting
12827 this option means that toggling the ORDERED property with the command
12828 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12829 not relevant for the behavior, but it makes things more visible.
12831 Note that toggling the tag with tags commands will not change the property
12832 and therefore not influence behavior!
12834 This can be t, meaning the tag ORDERED should be used, It can also be a
12835 string to select a different tag for this task."
12836 :group 'org-todo
12837 :type '(choice
12838 (const :tag "No tracking" nil)
12839 (const :tag "Track with ORDERED tag" t)
12840 (string :tag "Use other tag")))
12842 (defun org-toggle-ordered-property ()
12843 "Toggle the ORDERED property of the current entry.
12844 For better visibility, you can track the value of this property with a tag.
12845 See variable `org-track-ordered-property-with-tag'."
12846 (interactive)
12847 (let* ((t1 org-track-ordered-property-with-tag)
12848 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12849 (save-excursion
12850 (org-back-to-heading)
12851 (if (org-entry-get nil "ORDERED")
12852 (progn
12853 (org-delete-property "ORDERED")
12854 (and tag (org-toggle-tag tag 'off))
12855 (message "Subtasks can be completed in arbitrary order"))
12856 (org-entry-put nil "ORDERED" "t")
12857 (and tag (org-toggle-tag tag 'on))
12858 (message "Subtasks must be completed in sequence")))))
12860 (defun org-block-todo-from-checkboxes (change-plist)
12861 "Block turning an entry into a TODO, using checkboxes.
12862 This checks whether the current task should be blocked from state
12863 changes because there are unchecked boxes in this entry."
12864 (if (not org-enforce-todo-checkbox-dependencies)
12865 t ; if locally turned off don't block
12866 (catch 'dont-block
12867 ;; If this is not a todo state change, or if this entry is already DONE,
12868 ;; do not block
12869 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12870 (member (plist-get change-plist :from)
12871 (cons 'done org-done-keywords))
12872 (member (plist-get change-plist :to)
12873 (cons 'todo org-not-done-keywords))
12874 (not (plist-get change-plist :to)))
12875 (throw 'dont-block t))
12876 ;; If this task has checkboxes that are not checked, it's blocked
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (let ((beg (point)) end)
12880 (outline-next-heading)
12881 (setq end (point))
12882 (goto-char beg)
12883 (when (org-list-search-forward
12884 (concat (org-item-beginning-re)
12885 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12886 "\\[[- ]\\]")
12887 end t)
12888 (when (boundp 'org-blocked-by-checkboxes)
12889 (setq org-blocked-by-checkboxes t))
12890 (throw 'dont-block nil))))
12891 t))) ; do not block
12893 (defun org-entry-blocked-p ()
12894 "Non-nil if entry at point is blocked."
12895 (and (not (org-entry-get nil "NOBLOCKING"))
12896 (member (org-entry-get nil "TODO") org-not-done-keywords)
12897 (not (run-hook-with-args-until-failure
12898 'org-blocker-hook
12899 (list :type 'todo-state-change
12900 :position (point)
12901 :from 'todo
12902 :to 'done)))))
12904 (defun org-update-statistics-cookies (all)
12905 "Update the statistics cookie, either from TODO or from checkboxes.
12906 This should be called with the cursor in a line with a statistics
12907 cookie. When called with a \\[universal-argument] prefix, update
12908 all statistics cookies in the buffer."
12909 (interactive "P")
12910 (if all
12911 (progn
12912 (org-update-checkbox-count 'all)
12913 (org-map-entries 'org-update-parent-todo-statistics))
12914 (if (not (org-at-heading-p))
12915 (org-update-checkbox-count)
12916 (let ((pos (point-marker))
12917 end l1 l2)
12918 (ignore-errors (org-back-to-heading t))
12919 (if (not (org-at-heading-p))
12920 (org-update-checkbox-count)
12921 (setq l1 (org-outline-level))
12922 (setq end (save-excursion
12923 (outline-next-heading)
12924 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12925 (point)))
12926 (if (and (save-excursion
12927 (re-search-forward
12928 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12929 (not (save-excursion (re-search-forward
12930 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12931 (org-update-checkbox-count)
12932 (if (and l2 (> l2 l1))
12933 (progn
12934 (goto-char end)
12935 (org-update-parent-todo-statistics))
12936 (goto-char pos)
12937 (beginning-of-line 1)
12938 (while (re-search-forward
12939 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12940 (point-at-eol) t)
12941 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12942 (goto-char pos)
12943 (move-marker pos nil)))))
12945 (defvar org-entry-property-inherited-from) ;; defined below
12946 (defun org-update-parent-todo-statistics ()
12947 "Update any statistics cookie in the parent of the current headline.
12948 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12949 the entire subtree and this will travel up the hierarchy and update
12950 statistics everywhere."
12951 (let* ((prop (save-excursion (org-up-heading-safe)
12952 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12953 (recursive (or (not org-hierarchical-todo-statistics)
12954 (and prop (string-match "\\<recursive\\>" prop))))
12955 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12957 (first t)
12958 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12959 level ltoggle l1 new ndel
12960 (cnt-all 0) (cnt-done 0) is-percent kwd
12961 checkbox-beg cookie-present)
12962 (catch 'exit
12963 (save-excursion
12964 (beginning-of-line 1)
12965 (setq ltoggle (funcall outline-level))
12966 ;; Three situations are to consider:
12968 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12969 ;; to the top-level ancestor on the headline;
12971 ;; 2. If parent has "recursive" property, repeat up to the
12972 ;; headline setting that property, taking inheritance into
12973 ;; account;
12975 ;; 3. Else, move up to direct parent and proceed only once.
12976 (while (and (setq level (org-up-heading-safe))
12977 (or recursive first)
12978 (>= (point) lim))
12979 (setq first nil cookie-present nil)
12980 (unless (and level
12981 (not (string-match
12982 "\\<checkbox\\>"
12983 (downcase (or (org-entry-get nil "COOKIE_DATA")
12984 "")))))
12985 (throw 'exit nil))
12986 (while (re-search-forward box-re (point-at-eol) t)
12987 (setq cnt-all 0 cnt-done 0 cookie-present t)
12988 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12989 (save-match-data
12990 (unless (outline-next-heading) (throw 'exit nil))
12991 (while (and (looking-at org-complex-heading-regexp)
12992 (> (setq l1 (length (match-string 1))) level))
12993 (setq kwd (and (or recursive (= l1 ltoggle))
12994 (match-string 2)))
12995 (if (or (eq org-provide-todo-statistics 'all-headlines)
12996 (and (eq org-provide-todo-statistics t)
12997 (or (member kwd org-done-keywords)))
12998 (and (listp org-provide-todo-statistics)
12999 (stringp (car org-provide-todo-statistics))
13000 (or (member kwd org-provide-todo-statistics)
13001 (member kwd org-done-keywords)))
13002 (and (listp org-provide-todo-statistics)
13003 (listp (car org-provide-todo-statistics))
13004 (or (member kwd (car org-provide-todo-statistics))
13005 (and (member kwd org-done-keywords)
13006 (member kwd (cadr org-provide-todo-statistics))))))
13007 (setq cnt-all (1+ cnt-all))
13008 (and (eq org-provide-todo-statistics t)
13010 (setq cnt-all (1+ cnt-all))))
13011 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13012 (member kwd org-done-keywords))
13013 (and (listp org-provide-todo-statistics)
13014 (listp (car org-provide-todo-statistics))
13015 (member kwd org-done-keywords)
13016 (member kwd (cadr org-provide-todo-statistics)))
13017 (and (listp org-provide-todo-statistics)
13018 (stringp (car org-provide-todo-statistics))
13019 (member kwd org-done-keywords)))
13020 (setq cnt-done (1+ cnt-done)))
13021 (outline-next-heading)))
13022 (setq new
13023 (if is-percent
13024 (format "[%d%%]" (floor (* 100.0 cnt-done)
13025 (max 1 cnt-all)))
13026 (format "[%d/%d]" cnt-done cnt-all))
13027 ndel (- (match-end 0) checkbox-beg))
13028 (goto-char checkbox-beg)
13029 (insert new)
13030 (delete-region (point) (+ (point) ndel))
13031 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13032 (when cookie-present
13033 (run-hook-with-args 'org-after-todo-statistics-hook
13034 cnt-done (- cnt-all cnt-done))))))
13035 (run-hooks 'org-todo-statistics-hook)))
13037 (defvar org-after-todo-statistics-hook nil
13038 "Hook that is called after a TODO statistics cookie has been updated.
13039 Each function is called with two arguments: the number of not-done entries
13040 and the number of done entries.
13042 For example, the following function, when added to this hook, will switch
13043 an entry to DONE when all children are done, and back to TODO when new
13044 entries are set to a TODO status. Note that this hook is only called
13045 when there is a statistics cookie in the headline!
13047 (defun org-summary-todo (n-done n-not-done)
13048 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13049 (let (org-log-done org-log-states) ; turn off logging
13050 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13053 (defvar org-todo-statistics-hook nil
13054 "Hook that is run whenever Org thinks TODO statistics should be updated.
13055 This hook runs even if there is no statistics cookie present, in which case
13056 `org-after-todo-statistics-hook' would not run.")
13058 (defun org-todo-trigger-tag-changes (state)
13059 "Apply the changes defined in `org-todo-state-tags-triggers'."
13060 (let ((l org-todo-state-tags-triggers)
13061 changes)
13062 (when (or (not state) (equal state ""))
13063 (setq changes (append changes (cdr (assoc "" l)))))
13064 (when (and (stringp state) (> (length state) 0))
13065 (setq changes (append changes (cdr (assoc state l)))))
13066 (when (member state org-not-done-keywords)
13067 (setq changes (append changes (cdr (assq 'todo l)))))
13068 (when (member state org-done-keywords)
13069 (setq changes (append changes (cdr (assq 'done l)))))
13070 (dolist (c changes)
13071 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13073 (defun org-local-logging (value)
13074 "Get logging settings from a property VALUE."
13075 ;; Directly set the variables, they are already local.
13076 (setq org-log-done nil
13077 org-log-repeat nil
13078 org-todo-log-states nil)
13079 (dolist (w (org-split-string value))
13080 (let (a)
13081 (cond
13082 ((setq a (assoc w org-startup-options))
13083 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13084 (set (nth 1 a) (nth 2 a))))
13085 ((setq a (org-extract-log-state-settings w))
13086 (and (member (car a) org-todo-keywords-1)
13087 (push a org-todo-log-states)))))))
13089 (defun org-get-todo-sequence-head (kwd)
13090 "Return the head of the TODO sequence to which KWD belongs.
13091 If KWD is not set, check if there is a text property remembering the
13092 right sequence."
13093 (let (p)
13094 (cond
13095 ((not kwd)
13096 (or (get-text-property (point-at-bol) 'org-todo-head)
13097 (progn
13098 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13099 nil (point-at-eol)))
13100 (get-text-property p 'org-todo-head))))
13101 ((not (member kwd org-todo-keywords-1))
13102 (car org-todo-keywords-1))
13103 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13105 (defun org-fast-todo-selection ()
13106 "Fast TODO keyword selection with single keys.
13107 Returns the new TODO keyword, or nil if no state change should occur."
13108 (let* ((fulltable org-todo-key-alist)
13109 (done-keywords org-done-keywords) ;; needed for the faces.
13110 (maxlen (apply 'max (mapcar
13111 (lambda (x)
13112 (if (stringp (car x)) (string-width (car x)) 0))
13113 fulltable)))
13114 (expert nil)
13115 (fwidth (+ maxlen 3 1 3))
13116 (ncol (/ (- (window-width) 4) fwidth))
13117 tg cnt e c tbl
13118 groups ingroup)
13119 (save-excursion
13120 (save-window-excursion
13121 (if expert
13122 (set-buffer (get-buffer-create " *Org todo*"))
13123 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13124 (erase-buffer)
13125 (setq-local org-done-keywords done-keywords)
13126 (setq tbl fulltable cnt 0)
13127 (while (setq e (pop tbl))
13128 (cond
13129 ((equal e '(:startgroup))
13130 (push '() groups) (setq ingroup t)
13131 (unless (= cnt 0)
13132 (setq cnt 0)
13133 (insert "\n"))
13134 (insert "{ "))
13135 ((equal e '(:endgroup))
13136 (setq ingroup nil cnt 0)
13137 (insert "}\n"))
13138 ((equal e '(:newline))
13139 (unless (= cnt 0)
13140 (setq cnt 0)
13141 (insert "\n")
13142 (setq e (car tbl))
13143 (while (equal (car tbl) '(:newline))
13144 (insert "\n")
13145 (setq tbl (cdr tbl)))))
13147 (setq tg (car e) c (cdr e))
13148 (when ingroup (push tg (car groups)))
13149 (setq tg (org-add-props tg nil 'face
13150 (org-get-todo-face tg)))
13151 (when (and (= cnt 0) (not ingroup)) (insert " "))
13152 (insert "[" c "] " tg (make-string
13153 (- fwidth 4 (length tg)) ?\ ))
13154 (when (= (setq cnt (1+ cnt)) ncol)
13155 (insert "\n")
13156 (when ingroup (insert " "))
13157 (setq cnt 0)))))
13158 (insert "\n")
13159 (goto-char (point-min))
13160 (unless expert (org-fit-window-to-buffer))
13161 (message "[a-z..]:Set [SPC]:clear")
13162 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13163 (cond
13164 ((or (= c ?\C-g)
13165 (and (= c ?q) (not (rassoc c fulltable))))
13166 (setq quit-flag t))
13167 ((= c ?\ ) nil)
13168 ((setq e (rassoc c fulltable) tg (car e))
13170 (t (setq quit-flag t)))))))
13172 (defun org-entry-is-todo-p ()
13173 (member (org-get-todo-state) org-not-done-keywords))
13175 (defun org-entry-is-done-p ()
13176 (member (org-get-todo-state) org-done-keywords))
13178 (defun org-get-todo-state ()
13179 "Return the TODO keyword of the current subtree."
13180 (save-excursion
13181 (org-back-to-heading t)
13182 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13183 (match-end 2)
13184 (match-string 2))))
13186 (defun org-at-date-range-p (&optional inactive-ok)
13187 "Non-nil if point is inside a date range.
13189 When optional argument INACTIVE-OK is non-nil, also consider
13190 inactive time ranges.
13192 When this function returns a non-nil value, match data is set
13193 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13194 on INACTIVE-OK."
13195 (interactive)
13196 (save-excursion
13197 (catch 'exit
13198 (let ((pos (point)))
13199 (skip-chars-backward "^[<\r\n")
13200 (skip-chars-backward "<[")
13201 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13202 (>= (match-end 0) pos)
13203 (throw 'exit t))
13204 (skip-chars-backward "^<[\r\n")
13205 (skip-chars-backward "<[")
13206 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13207 (>= (match-end 0) pos)
13208 (throw 'exit t)))
13209 nil)))
13211 (defun org-get-repeat (&optional tagline)
13212 "Check if there is a deadline/schedule with repeater in this entry."
13213 (save-match-data
13214 (save-excursion
13215 (org-back-to-heading t)
13216 (and (re-search-forward (if tagline
13217 (concat tagline "\\s-*" org-repeat-re)
13218 org-repeat-re)
13219 (org-entry-end-position) t)
13220 (match-string-no-properties 1)))))
13222 (defvar org-last-changed-timestamp)
13223 (defvar org-last-inserted-timestamp)
13224 (defvar org-log-post-message)
13225 (defvar org-log-note-purpose)
13226 (defvar org-log-note-how nil)
13227 (defvar org-log-note-extra)
13228 (defun org-auto-repeat-maybe (done-word)
13229 "Check if the current headline contains a repeated time-stamp.
13231 If yes, set TODO state back to what it was and change the base date
13232 of repeating deadline/scheduled time stamps to new date.
13234 This function is run automatically after each state change to a DONE state."
13235 (let* ((repeat (org-get-repeat))
13236 (aa (assoc org-last-state org-todo-kwd-alist))
13237 (interpret (nth 1 aa))
13238 (head (nth 2 aa))
13239 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13240 (msg "Entry repeats: ")
13241 (org-log-done nil)
13242 (org-todo-log-states nil))
13243 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13244 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13245 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13246 org-todo-repeat-to-state)))
13247 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13248 to-state)
13249 ((eq interpret 'type) org-last-state)
13250 (head)
13251 (t 'none))))
13252 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13253 (org-entry-put nil "LAST_REPEAT" (format-time-string
13254 (org-time-stamp-format t t))))
13255 (when org-log-repeat
13256 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13257 (memq 'org-add-log-note post-command-hook))
13258 ;; We are already setup for some record.
13259 (when (eq org-log-repeat 'note)
13260 ;; Make sure we take a note, not only a time stamp.
13261 (setq org-log-note-how 'note))
13262 ;; Set up for taking a record.
13263 (org-add-log-setup 'state
13264 (or done-word (car org-done-keywords))
13265 org-last-state
13266 org-log-repeat)))
13267 (org-back-to-heading t)
13268 (org-add-planning-info nil nil 'closed)
13269 (let ((end (save-excursion (outline-next-heading) (point)))
13270 (planning-re (regexp-opt
13271 (list org-scheduled-string org-deadline-string))))
13272 (while (re-search-forward org-ts-regexp end t)
13273 (let* ((ts (match-string 0))
13274 (planning? (org-at-planning-p))
13275 (type (if (not planning?) "Plain:"
13276 (save-excursion
13277 (re-search-backward
13278 planning-re (line-beginning-position) t)
13279 (match-string 0)))))
13280 (cond
13281 ;; Ignore fake time-stamps (e.g., within comments).
13282 ((and (not planning?)
13283 (not (org-at-property-p))
13284 (not (eq 'timestamp
13285 (org-element-type (save-excursion
13286 (backward-char)
13287 (org-element-context)))))))
13288 ;; Time-stamps without a repeater are usually skipped.
13289 ;; However, a SCHEDULED time-stamp without one is
13290 ;; removed, as it is considered as no longer relevant.
13291 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13292 (when (equal type org-scheduled-string)
13293 (org-remove-timestamp-with-keyword type)))
13295 (let ((n (string-to-number (match-string 2 ts)))
13296 (what (match-string 3 ts)))
13297 (when (equal what "w") (setq n (* n 7) what "d"))
13298 (when (and (equal what "h")
13299 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13300 ts)))
13301 (user-error
13302 "Cannot repeat in Repeat in %d hour(s) because no hour \
13303 has been set"
13305 ;; Preparation, see if we need to modify the start
13306 ;; date for the change.
13307 (when (match-end 1)
13308 (let ((time (save-match-data (org-time-string-to-time ts))))
13309 (cond
13310 ((equal (match-string 1 ts) ".")
13311 ;; Shift starting date to today
13312 (org-timestamp-change
13313 (- (org-today) (time-to-days time))
13314 'day))
13315 ((equal (match-string 1 ts) "+")
13316 (let ((nshiftmax 10)
13317 (nshift 0))
13318 (while (or (= nshift 0)
13319 (not (time-less-p (current-time) time)))
13320 (when (= (cl-incf nshift) nshiftmax)
13321 (or (y-or-n-p
13322 (format "%d repeater intervals were not \
13323 enough to shift date past today. Continue? "
13324 nshift))
13325 (user-error "Abort")))
13326 (org-timestamp-change n (cdr (assoc what whata)))
13327 (org-at-timestamp-p t)
13328 (setq ts (match-string 1))
13329 (setq time
13330 (save-match-data
13331 (org-time-string-to-time ts)))))
13332 (org-timestamp-change (- n) (cdr (assoc what whata)))
13333 ;; Rematch, so that we have everything in place
13334 ;; for the real shift.
13335 (org-at-timestamp-p t)
13336 (setq ts (match-string 1))
13337 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13338 ts)))))
13339 (save-excursion
13340 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13341 (setq msg
13342 (concat
13343 msg type " " org-last-changed-timestamp " "))))))))
13344 (setq org-log-post-message msg)
13345 (message "%s" msg))))
13347 (defun org-show-todo-tree (arg)
13348 "Make a compact tree which shows all headlines marked with TODO.
13349 The tree will show the lines where the regexp matches, and all higher
13350 headlines above the match.
13351 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13352 With a numeric prefix N, construct a sparse tree for the Nth element
13353 of `org-todo-keywords-1'."
13354 (interactive "P")
13355 (let ((case-fold-search nil)
13356 (kwd-re
13357 (cond ((null arg) org-not-done-regexp)
13358 ((equal arg '(4))
13359 (let ((kwd
13360 (completing-read "Keyword (or KWD1|KWD2|...): "
13361 (mapcar #'list org-todo-keywords-1))))
13362 (concat "\\("
13363 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13364 "\\)\\>")))
13365 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13366 (regexp-quote (nth (1- (prefix-numeric-value arg))
13367 org-todo-keywords-1)))
13368 (t (user-error "Invalid prefix argument: %s" arg)))))
13369 (message "%d TODO entries found"
13370 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13372 (defun org--deadline-or-schedule (arg type time)
13373 "Insert DEADLINE or SCHEDULE information in current entry.
13374 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13375 `org-schedule' for information about ARG and TIME arguments."
13376 (let* ((deadline? (eq type 'deadline))
13377 (keyword (if deadline? org-deadline-string org-scheduled-string))
13378 (log (if deadline? org-log-redeadline org-log-reschedule))
13379 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13380 (old-date-time (and old-date (org-time-string-to-time old-date)))
13381 ;; Save repeater cookie from either TIME or current scheduled
13382 ;; time stamp. We are going to insert it back at the end of
13383 ;; the process.
13384 (repeater (or (and (org-string-nw-p time)
13385 ;; We use `org-repeat-re' because we need
13386 ;; to tell the difference between a real
13387 ;; repeater and a time delta, e.g. "+2d".
13388 (string-match org-repeat-re time)
13389 (match-string 1 time))
13390 (and (org-string-nw-p old-date)
13391 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13392 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13393 old-date)
13394 (match-string 1 old-date)))))
13395 (pcase arg
13396 (`(4)
13397 (when (and old-date log)
13398 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13399 nil old-date log))
13400 (org-remove-timestamp-with-keyword keyword)
13401 (message (if deadline? "Item no longer has a deadline."
13402 "Item is no longer scheduled.")))
13403 (`(16)
13404 (save-excursion
13405 (org-back-to-heading t)
13406 (let ((regexp (if deadline? org-deadline-time-regexp
13407 org-scheduled-time-regexp)))
13408 (if (not (re-search-forward regexp (line-end-position 2) t))
13409 (user-error (if deadline? "No deadline information to update"
13410 "No scheduled information to update"))
13411 (let* ((rpl0 (match-string 1))
13412 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13413 (msg (if deadline? "Warn starting from" "Delay until")))
13414 (replace-match
13415 (concat keyword
13416 " <" rpl
13417 (format " -%dd"
13418 (abs (- (time-to-days
13419 (save-match-data
13420 (org-read-date
13421 nil t nil msg old-date-time)))
13422 (time-to-days old-date-time))))
13423 ">") t t))))))
13425 (org-add-planning-info type time 'closed)
13426 (when (and old-date
13428 (not (equal old-date org-last-inserted-timestamp)))
13429 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13430 org-last-inserted-timestamp
13431 old-date
13432 log))
13433 (when repeater
13434 (save-excursion
13435 (org-back-to-heading t)
13436 (when (re-search-forward
13437 (concat keyword " " org-last-inserted-timestamp)
13438 (line-end-position 2)
13440 (goto-char (1- (match-end 0)))
13441 (insert " " repeater)
13442 (setq org-last-inserted-timestamp
13443 (concat (substring org-last-inserted-timestamp 0 -1)
13444 " " repeater
13445 (substring org-last-inserted-timestamp -1))))))
13446 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13447 org-last-inserted-timestamp)))))
13449 (defun org-deadline (arg &optional time)
13450 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13451 With one universal prefix argument, remove any deadline from the item.
13452 With two universal prefix arguments, prompt for a warning delay.
13453 With argument TIME, set the deadline at the corresponding date. TIME
13454 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13455 (interactive "P")
13456 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13457 (org-map-entries
13458 (lambda () (org--deadline-or-schedule arg 'deadline time))
13460 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13461 'region-start-level
13462 'region)
13463 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13464 (org--deadline-or-schedule arg 'deadline time)))
13466 (defun org-schedule (arg &optional time)
13467 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13468 With one universal prefix argument, remove any scheduling date from the item.
13469 With two universal prefix arguments, prompt for a delay cookie.
13470 With argument TIME, scheduled at the corresponding date. TIME can
13471 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13472 (interactive "P")
13473 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13474 (org-map-entries
13475 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13477 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13478 'region-start-level
13479 'region)
13480 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13481 (org--deadline-or-schedule arg 'scheduled time)))
13483 (defun org-get-scheduled-time (pom &optional inherit)
13484 "Get the scheduled time as a time tuple, of a format suitable
13485 for calling org-schedule with, or if there is no scheduling,
13486 returns nil."
13487 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13488 (when time
13489 (apply 'encode-time (org-parse-time-string time)))))
13491 (defun org-get-deadline-time (pom &optional inherit)
13492 "Get the deadline as a time tuple, of a format suitable for
13493 calling org-deadline with, or if there is no scheduling, returns
13494 nil."
13495 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13496 (when time
13497 (apply 'encode-time (org-parse-time-string time)))))
13499 (defun org-remove-timestamp-with-keyword (keyword)
13500 "Remove all time stamps with KEYWORD in the current entry."
13501 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13502 beg)
13503 (save-excursion
13504 (org-back-to-heading t)
13505 (setq beg (point))
13506 (outline-next-heading)
13507 (while (re-search-backward re beg t)
13508 (replace-match "")
13509 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13510 (equal (char-before) ?\ ))
13511 (backward-delete-char 1)
13512 (when (string-match "^[ \t]*$" (buffer-substring
13513 (point-at-bol) (point-at-eol)))
13514 (delete-region (point-at-bol)
13515 (min (point-max) (1+ (point-at-eol))))))))))
13517 (defvar org-time-was-given) ; dynamically scoped parameter
13518 (defvar org-end-time-was-given) ; dynamically scoped parameter
13520 (defun org-at-planning-p ()
13521 "Non-nil when point is on a planning info line."
13522 ;; This is as accurate and faster than `org-element-at-point' since
13523 ;; planning info location is fixed in the section.
13524 (org-with-wide-buffer
13525 (beginning-of-line)
13526 (and (looking-at-p org-planning-line-re)
13527 (eq (point)
13528 (ignore-errors
13529 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13530 (org-back-to-heading t)
13531 (org-with-limited-levels (org-back-to-heading t)))
13532 (line-beginning-position 2))))))
13534 (defun org-add-planning-info (what &optional time &rest remove)
13535 "Insert new timestamp with keyword in the planning line.
13536 WHAT indicates what kind of time stamp to add. It is a symbol
13537 among `closed', `deadline', `scheduled' and nil. TIME indicates
13538 the time to use. If none is given, the user is prompted for
13539 a date. REMOVE indicates what kind of entries to remove. An old
13540 WHAT entry will also be removed."
13541 (let (org-time-was-given org-end-time-was-given default-time default-input)
13542 (catch 'exit
13543 (when (and (memq what '(scheduled deadline))
13544 (or (not time)
13545 (and (stringp time)
13546 (string-match "^[-+]+[0-9]" time))))
13547 ;; Try to get a default date/time from existing timestamp
13548 (save-excursion
13549 (org-back-to-heading t)
13550 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13551 (when (re-search-forward (if (eq what 'scheduled)
13552 org-scheduled-time-regexp
13553 org-deadline-time-regexp)
13554 end t)
13555 (setq ts (match-string 1)
13556 default-time (apply 'encode-time (org-parse-time-string ts))
13557 default-input (and ts (org-get-compact-tod ts)))))))
13558 (when what
13559 (setq time
13560 (if (stringp time)
13561 ;; This is a string (relative or absolute), set
13562 ;; proper date.
13563 (apply #'encode-time
13564 (org-read-date-analyze
13565 time default-time (decode-time default-time)))
13566 ;; If necessary, get the time from the user
13567 (or time (org-read-date nil 'to-time nil nil
13568 default-time default-input)))))
13570 (org-with-wide-buffer
13571 (org-back-to-heading t)
13572 (forward-line)
13573 (unless (bolp) (insert "\n"))
13574 (cond ((looking-at-p org-planning-line-re)
13575 ;; Move to current indentation.
13576 (skip-chars-forward " \t")
13577 ;; Check if we have to remove something.
13578 (dolist (type (if what (cons what remove) remove))
13579 (save-excursion
13580 (when (re-search-forward
13581 (cl-case type
13582 (closed org-closed-time-regexp)
13583 (deadline org-deadline-time-regexp)
13584 (scheduled org-scheduled-time-regexp)
13585 (otherwise
13586 (error "Invalid planning type: %s" type)))
13587 (line-end-position) t)
13588 ;; Delete until next keyword or end of line.
13589 (delete-region
13590 (match-beginning 0)
13591 (if (re-search-forward org-keyword-time-not-clock-regexp
13592 (line-end-position)
13594 (match-beginning 0)
13595 (line-end-position))))))
13596 ;; If there is nothing more to add and no more keyword
13597 ;; is left, remove the line completely.
13598 (if (and (looking-at-p "[ \t]*$") (not what))
13599 (delete-region (line-beginning-position)
13600 (line-beginning-position 2))
13601 ;; If we removed last keyword, do not leave trailing
13602 ;; white space at the end of line.
13603 (let ((p (point)))
13604 (save-excursion
13605 (end-of-line)
13606 (unless (= (skip-chars-backward " \t" p) 0)
13607 (delete-region (point) (line-end-position)))))))
13608 ((not what) (throw 'exit nil)) ; Nothing to do.
13609 (t (insert-before-markers "\n")
13610 (backward-char 1)
13611 (when org-adapt-indentation
13612 (indent-to-column (1+ (org-outline-level))))))
13613 (when what
13614 ;; Insert planning keyword.
13615 (insert (cl-case what
13616 (closed org-closed-string)
13617 (deadline org-deadline-string)
13618 (scheduled org-scheduled-string)
13619 (otherwise (error "Invalid planning type: %s" what)))
13620 " ")
13621 ;; Insert associated timestamp.
13622 (let ((ts (org-insert-time-stamp
13623 time
13624 (or org-time-was-given
13625 (and (eq what 'closed) org-log-done-with-time))
13626 (eq what 'closed)
13627 nil nil (list org-end-time-was-given))))
13628 (unless (eolp) (insert " "))
13629 ts))))))
13631 (defvar org-log-note-marker (make-marker)
13632 "Marker pointing at the entry where the note is to be inserted.")
13633 (defvar org-log-note-purpose nil)
13634 (defvar org-log-note-state nil)
13635 (defvar org-log-note-previous-state nil)
13636 (defvar org-log-note-extra nil)
13637 (defvar org-log-note-window-configuration nil)
13638 (defvar org-log-note-return-to (make-marker))
13639 (defvar org-log-note-effective-time nil
13640 "Remembered current time so that dynamically scoped
13641 `org-extend-today-until' affects timestamps in state change log")
13643 (defvar org-log-post-message nil
13644 "Message to be displayed after a log note has been stored.
13645 The auto-repeater uses this.")
13647 (defun org-add-note ()
13648 "Add a note to the current entry.
13649 This is done in the same way as adding a state change note."
13650 (interactive)
13651 (org-add-log-setup 'note))
13653 (defun org-log-beginning (&optional create)
13654 "Return expected start of log notes in current entry.
13655 When optional argument CREATE is non-nil, the function creates
13656 a drawer to store notes, if necessary. Returned position ignores
13657 narrowing."
13658 (org-with-wide-buffer
13659 (let ((drawer (org-log-into-drawer)))
13660 (cond
13661 (drawer
13662 (org-end-of-meta-data)
13663 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13664 (end (if (org-at-heading-p) (point)
13665 (save-excursion (outline-next-heading) (point))))
13666 (case-fold-search t))
13667 (catch 'exit
13668 ;; Try to find existing drawer.
13669 (while (re-search-forward regexp end t)
13670 (let ((element (org-element-at-point)))
13671 (when (eq (org-element-type element) 'drawer)
13672 (let ((cend (org-element-property :contents-end element)))
13673 (when (and (not org-log-states-order-reversed) cend)
13674 (goto-char cend)))
13675 (throw 'exit nil))))
13676 ;; No drawer found. Create one, if permitted.
13677 (when create
13678 (unless (bolp) (insert "\n"))
13679 (let ((beg (point)))
13680 (insert ":" drawer ":\n:END:\n")
13681 (org-indent-region beg (point)))
13682 (end-of-line -1)))))
13684 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13685 (skip-chars-forward " \t\n")
13686 (beginning-of-line)
13687 (unless org-log-states-order-reversed
13688 (org-skip-over-state-notes)
13689 (skip-chars-backward " \t\n")
13690 (forward-line)))))
13691 (if (bolp) (point) (line-beginning-position 2))))
13693 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13694 "Set up the post command hook to take a note.
13695 If this is about to TODO state change, the new state is expected in STATE.
13696 HOW is an indicator what kind of note should be created.
13697 EXTRA is additional text that will be inserted into the notes buffer."
13698 (move-marker org-log-note-marker (point))
13699 (setq org-log-note-purpose purpose
13700 org-log-note-state state
13701 org-log-note-previous-state prev-state
13702 org-log-note-how how
13703 org-log-note-extra extra
13704 org-log-note-effective-time (org-current-effective-time))
13705 (add-hook 'post-command-hook 'org-add-log-note 'append))
13707 (defun org-skip-over-state-notes ()
13708 "Skip past the list of State notes in an entry."
13709 (when (ignore-errors (goto-char (org-in-item-p)))
13710 (let* ((struct (org-list-struct))
13711 (prevs (org-list-prevs-alist struct))
13712 (regexp
13713 (concat "[ \t]*- +"
13714 (replace-regexp-in-string
13715 " +" " +"
13716 (org-replace-escapes
13717 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13718 `(("%d" . ,org-ts-regexp-inactive)
13719 ("%D" . ,org-ts-regexp)
13720 ("%s" . "\"\\S-+\"")
13721 ("%S" . "\"\\S-+\"")
13722 ("%t" . ,org-ts-regexp-inactive)
13723 ("%T" . ,org-ts-regexp)
13724 ("%u" . ".*?")
13725 ("%U" . ".*?")))))))
13726 (while (looking-at-p regexp)
13727 (goto-char (or (org-list-get-next-item (point) struct prevs)
13728 (org-list-get-item-end (point) struct)))))))
13730 (defun org-add-log-note (&optional _purpose)
13731 "Pop up a window for taking a note, and add this note later."
13732 (remove-hook 'post-command-hook 'org-add-log-note)
13733 (setq org-log-note-window-configuration (current-window-configuration))
13734 (delete-other-windows)
13735 (move-marker org-log-note-return-to (point))
13736 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13737 (goto-char org-log-note-marker)
13738 (org-switch-to-buffer-other-window "*Org Note*")
13739 (erase-buffer)
13740 (if (memq org-log-note-how '(time state))
13741 (let (current-prefix-arg) (org-store-log-note))
13742 (let ((org-inhibit-startup t)) (org-mode))
13743 (insert (format "# Insert note for %s.
13744 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13745 (cond
13746 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13747 ((eq org-log-note-purpose 'done) "closed todo item")
13748 ((eq org-log-note-purpose 'state)
13749 (format "state change from \"%s\" to \"%s\""
13750 (or org-log-note-previous-state "")
13751 (or org-log-note-state "")))
13752 ((eq org-log-note-purpose 'reschedule)
13753 "rescheduling")
13754 ((eq org-log-note-purpose 'delschedule)
13755 "no longer scheduled")
13756 ((eq org-log-note-purpose 'redeadline)
13757 "changing deadline")
13758 ((eq org-log-note-purpose 'deldeadline)
13759 "removing deadline")
13760 ((eq org-log-note-purpose 'refile)
13761 "refiling")
13762 ((eq org-log-note-purpose 'note)
13763 "this entry")
13764 (t (error "This should not happen")))))
13765 (when org-log-note-extra (insert org-log-note-extra))
13766 (setq-local org-finish-function 'org-store-log-note)
13767 (run-hooks 'org-log-buffer-setup-hook)))
13769 (defvar org-note-abort nil) ; dynamically scoped
13770 (defun org-store-log-note ()
13771 "Finish taking a log note, and insert it to where it belongs."
13772 (let ((txt (prog1 (buffer-string)
13773 (kill-buffer)))
13774 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13775 lines)
13776 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13777 (setq txt (replace-match "" t t txt)))
13778 (when (string-match "\\s-+\\'" txt)
13779 (setq txt (replace-match "" t t txt)))
13780 (setq lines (org-split-string txt "\n"))
13781 (when (org-string-nw-p note)
13782 (setq note
13783 (org-replace-escapes
13784 note
13785 (list (cons "%u" (user-login-name))
13786 (cons "%U" user-full-name)
13787 (cons "%t" (format-time-string
13788 (org-time-stamp-format 'long 'inactive)
13789 org-log-note-effective-time))
13790 (cons "%T" (format-time-string
13791 (org-time-stamp-format 'long nil)
13792 org-log-note-effective-time))
13793 (cons "%d" (format-time-string
13794 (org-time-stamp-format nil 'inactive)
13795 org-log-note-effective-time))
13796 (cons "%D" (format-time-string
13797 (org-time-stamp-format nil nil)
13798 org-log-note-effective-time))
13799 (cons "%s" (cond
13800 ((not org-log-note-state) "")
13801 ((string-match-p org-ts-regexp
13802 org-log-note-state)
13803 (format "\"[%s]\""
13804 (substring org-log-note-state 1 -1)))
13805 (t (format "\"%s\"" org-log-note-state))))
13806 (cons "%S"
13807 (cond
13808 ((not org-log-note-previous-state) "")
13809 ((string-match-p org-ts-regexp
13810 org-log-note-previous-state)
13811 (format "\"[%s]\""
13812 (substring
13813 org-log-note-previous-state 1 -1)))
13814 (t (format "\"%s\""
13815 org-log-note-previous-state)))))))
13816 (when lines (setq note (concat note " \\\\")))
13817 (push note lines))
13818 (when (and lines (not (or current-prefix-arg org-note-abort)))
13819 (with-current-buffer (marker-buffer org-log-note-marker)
13820 (org-with-wide-buffer
13821 ;; Find location for the new note.
13822 (goto-char org-log-note-marker)
13823 (set-marker org-log-note-marker nil)
13824 ;; Note associated to a clock is to be located right after
13825 ;; the clock. Do not move point.
13826 (unless (eq org-log-note-purpose 'clock-out)
13827 (goto-char (org-log-beginning t)))
13828 ;; Make sure point is at the beginning of an empty line.
13829 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13830 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13831 ;; In an existing list, add a new item at the top level.
13832 ;; Otherwise, indent line like a regular one.
13833 (let ((itemp (org-in-item-p)))
13834 (if itemp
13835 (indent-line-to
13836 (let ((struct (save-excursion
13837 (goto-char itemp) (org-list-struct))))
13838 (org-list-get-ind (org-list-get-top-point struct) struct)))
13839 (org-indent-line)))
13840 (insert (org-list-bullet-string "-") (pop lines))
13841 (let ((ind (org-list-item-body-column (line-beginning-position))))
13842 (dolist (line lines)
13843 (insert "\n")
13844 (indent-line-to ind)
13845 (insert line)))
13846 (message "Note stored")
13847 (org-back-to-heading t)
13848 (org-cycle-hide-drawers 'children))
13849 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13850 ;; from within `org-add-log-note' because `buffer-undo-list'
13851 ;; is then modified outside of `org-with-remote-undo'.
13852 (when (eq this-command 'org-agenda-todo)
13853 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13854 ;; Don't add undo information when called from `org-agenda-todo'.
13855 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13856 (set-window-configuration org-log-note-window-configuration)
13857 (with-current-buffer (marker-buffer org-log-note-return-to)
13858 (goto-char org-log-note-return-to))
13859 (move-marker org-log-note-return-to nil)
13860 (when org-log-post-message (message "%s" org-log-post-message))))
13862 (defun org-remove-empty-drawer-at (pos)
13863 "Remove an empty drawer at position POS.
13864 POS may also be a marker."
13865 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13866 (org-with-wide-buffer
13867 (goto-char pos)
13868 (let ((drawer (org-element-at-point)))
13869 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13870 (not (org-element-property :contents-begin drawer)))
13871 (delete-region (org-element-property :begin drawer)
13872 (progn (goto-char (org-element-property :end drawer))
13873 (skip-chars-backward " \r\t\n")
13874 (forward-line)
13875 (point))))))))
13877 (defvar org-ts-type nil)
13878 (defun org-sparse-tree (&optional arg type)
13879 "Create a sparse tree, prompt for the details.
13880 This command can create sparse trees. You first need to select the type
13881 of match used to create the tree:
13883 t Show all TODO entries.
13884 T Show entries with a specific TODO keyword.
13885 m Show entries selected by a tags/property match.
13886 p Enter a property name and its value (both with completion on existing
13887 names/values) and show entries with that property.
13888 r Show entries matching a regular expression (`/' can be used as well).
13889 b Show deadlines and scheduled items before a date.
13890 a Show deadlines and scheduled items after a date.
13891 d Show deadlines due within `org-deadline-warning-days'.
13892 D Show deadlines and scheduled items between a date range."
13893 (interactive "P")
13894 (setq type (or type org-sparse-tree-default-date-type))
13895 (setq org-ts-type type)
13896 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13897 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13898 \[c]ycle through date types: %s"
13899 (cl-case type
13900 (all "all timestamps")
13901 (scheduled "only scheduled")
13902 (deadline "only deadline")
13903 (active "only active timestamps")
13904 (inactive "only inactive timestamps")
13905 (closed "with a closed time-stamp")
13906 (otherwise "scheduled/deadline")))
13907 (let ((answer (read-char-exclusive)))
13908 (cl-case answer
13910 (org-sparse-tree
13912 (cadr
13913 (memq type '(nil all scheduled deadline active inactive closed)))))
13914 (?d (call-interactively 'org-check-deadlines))
13915 (?b (call-interactively 'org-check-before-date))
13916 (?a (call-interactively 'org-check-after-date))
13917 (?D (call-interactively 'org-check-dates-range))
13918 (?t (call-interactively 'org-show-todo-tree))
13919 (?T (org-show-todo-tree '(4)))
13920 (?m (call-interactively 'org-match-sparse-tree))
13921 ((?p ?P)
13922 (let* ((kwd (completing-read
13923 "Property: " (mapcar #'list (org-buffer-property-keys))))
13924 (value (completing-read
13925 "Value: " (mapcar #'list (org-property-values kwd)))))
13926 (unless (string-match "\\`{.*}\\'" value)
13927 (setq value (concat "\"" value "\"")))
13928 (org-match-sparse-tree arg (concat kwd "=" value))))
13929 ((?r ?R ?/) (call-interactively 'org-occur))
13930 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13932 (defvar-local org-occur-highlights nil
13933 "List of overlays used for occur matches.")
13934 (defvar-local org-occur-parameters nil
13935 "Parameters of the active org-occur calls.
13936 This is a list, each call to org-occur pushes as cons cell,
13937 containing the regular expression and the callback, onto the list.
13938 The list can contain several entries if `org-occur' has been called
13939 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13940 will only contain one set of parameters. When the highlights are
13941 removed (for example with `C-c C-c', or with the next edit (depending
13942 on `org-remove-highlights-with-change'), this variable is emptied
13943 as well.")
13945 (defun org-occur (regexp &optional keep-previous callback)
13946 "Make a compact tree which shows all matches of REGEXP.
13948 The tree will show the lines where the regexp matches, and any other context
13949 defined in `org-show-context-detail', which see.
13951 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13952 done by a previous call to `org-occur' will be kept, to allow stacking of
13953 calls to this command.
13955 Optional argument CALLBACK can be a function of no argument. In this case,
13956 it is called with point at the end of the match, match data being set
13957 accordingly. Current match is shown only if the return value is non-nil.
13958 The function must neither move point nor alter narrowing."
13959 (interactive "sRegexp: \nP")
13960 (when (equal regexp "")
13961 (user-error "Regexp cannot be empty"))
13962 (unless keep-previous
13963 (org-remove-occur-highlights nil nil t))
13964 (push (cons regexp callback) org-occur-parameters)
13965 (let ((cnt 0))
13966 (save-excursion
13967 (goto-char (point-min))
13968 (when (or (not keep-previous) ; do not want to keep
13969 (not org-occur-highlights)) ; no previous matches
13970 ;; hide everything
13971 (org-overview))
13972 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13973 (isearch-no-upper-case-p regexp t)
13974 org-occur-case-fold-search)))
13975 (while (re-search-forward regexp nil t)
13976 (when (or (not callback)
13977 (save-match-data (funcall callback)))
13978 (setq cnt (1+ cnt))
13979 (when org-highlight-sparse-tree-matches
13980 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13981 (org-show-context 'occur-tree)))))
13982 (when org-remove-highlights-with-change
13983 (add-hook 'before-change-functions 'org-remove-occur-highlights
13984 nil 'local))
13985 (unless org-sparse-tree-open-archived-trees
13986 (org-hide-archived-subtrees (point-min) (point-max)))
13987 (run-hooks 'org-occur-hook)
13988 (when (called-interactively-p 'interactive)
13989 (message "%d match(es) for regexp %s" cnt regexp))
13990 cnt))
13992 (defun org-occur-next-match (&optional n _reset)
13993 "Function for `next-error-function' to find sparse tree matches.
13994 N is the number of matches to move, when negative move backwards.
13995 This function always goes back to the starting point when no
13996 match is found."
13997 (let* ((limit (if (< n 0) (point-min) (point-max)))
13998 (search-func (if (< n 0)
13999 'previous-single-char-property-change
14000 'next-single-char-property-change))
14001 (n (abs n))
14002 (pos (point))
14004 (catch 'exit
14005 (while (setq p1 (funcall search-func (point) 'org-type))
14006 (when (equal p1 limit)
14007 (goto-char pos)
14008 (user-error "No more matches"))
14009 (when (equal (get-char-property p1 'org-type) 'org-occur)
14010 (setq n (1- n))
14011 (when (= n 0)
14012 (goto-char p1)
14013 (throw 'exit (point))))
14014 (goto-char p1))
14015 (goto-char p1)
14016 (user-error "No more matches"))))
14018 (defun org-show-context (&optional key)
14019 "Make sure point and context are visible.
14020 Optional argument KEY, when non-nil, is a symbol. See
14021 `org-show-context-detail' for allowed values and how much is to
14022 be shown."
14023 (org-show-set-visibility
14024 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14025 ((cdr (assq key org-show-context-detail)))
14026 (t (cdr (assq 'default org-show-context-detail))))))
14028 (defun org-show-set-visibility (detail)
14029 "Set visibility around point according to DETAIL.
14030 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14031 `tree', `canonical' or t. See `org-show-context-detail' for more
14032 information."
14033 ;; Show current heading and possibly its entry, following headline
14034 ;; or all children.
14035 (if (and (org-at-heading-p) (not (eq detail 'local)))
14036 (org-flag-heading nil)
14037 (org-show-entry)
14038 ;; If point is hidden within a drawer or a block, make sure to
14039 ;; expose it.
14040 (dolist (o (overlays-at (point)))
14041 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14042 (delete-overlay o)))
14043 (unless (org-before-first-heading-p)
14044 (org-with-limited-levels
14045 (cl-case detail
14046 ((tree canonical t) (org-show-children))
14047 ((nil minimal ancestors))
14048 (t (save-excursion
14049 (outline-next-heading)
14050 (org-flag-heading nil)))))))
14051 ;; Show all siblings.
14052 (when (eq detail 'lineage) (org-show-siblings))
14053 ;; Show ancestors, possibly with their children.
14054 (when (memq detail '(ancestors lineage tree canonical t))
14055 (save-excursion
14056 (while (org-up-heading-safe)
14057 (org-flag-heading nil)
14058 (when (memq detail '(canonical t)) (org-show-entry))
14059 (when (memq detail '(tree canonical t)) (org-show-children))))))
14061 (defvar org-reveal-start-hook nil
14062 "Hook run before revealing a location.")
14064 (defun org-reveal (&optional siblings)
14065 "Show current entry, hierarchy above it, and the following headline.
14067 This can be used to show a consistent set of context around
14068 locations exposed with `org-show-context'.
14070 With optional argument SIBLINGS, on each level of the hierarchy all
14071 siblings are shown. This repairs the tree structure to what it would
14072 look like when opened with hierarchical calls to `org-cycle'.
14074 With a \\[universal-argument] \\[universal-argument] prefix, \
14075 go to the parent and show the entire tree."
14076 (interactive "P")
14077 (run-hooks 'org-reveal-start-hook)
14078 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14079 ((equal siblings '(16))
14080 (save-excursion
14081 (when (org-up-heading-safe)
14082 (org-show-subtree)
14083 (run-hook-with-args 'org-cycle-hook 'subtree))))
14084 (t (org-show-set-visibility 'lineage))))
14086 (defun org-highlight-new-match (beg end)
14087 "Highlight from BEG to END and mark the highlight is an occur headline."
14088 (let ((ov (make-overlay beg end)))
14089 (overlay-put ov 'face 'secondary-selection)
14090 (overlay-put ov 'org-type 'org-occur)
14091 (push ov org-occur-highlights)))
14093 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14094 "Remove the occur highlights from the buffer.
14095 BEG and END are ignored. If NOREMOVE is nil, remove this function
14096 from the `before-change-functions' in the current buffer."
14097 (interactive)
14098 (unless org-inhibit-highlight-removal
14099 (mapc #'delete-overlay org-occur-highlights)
14100 (setq org-occur-highlights nil)
14101 (setq org-occur-parameters nil)
14102 (unless noremove
14103 (remove-hook 'before-change-functions
14104 'org-remove-occur-highlights 'local))))
14106 ;;;; Priorities
14108 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14109 "Regular expression matching the priority indicator.")
14111 (defvar org-remove-priority-next-time nil)
14113 (defun org-priority-up ()
14114 "Increase the priority of the current item."
14115 (interactive)
14116 (org-priority 'up))
14118 (defun org-priority-down ()
14119 "Decrease the priority of the current item."
14120 (interactive)
14121 (org-priority 'down))
14123 (defun org-priority (&optional action _show)
14124 "Change the priority of an item.
14125 ACTION can be `set', `up', `down', or a character."
14126 (interactive "P")
14127 (if (equal action '(4))
14128 (org-show-priority)
14129 (unless org-enable-priority-commands
14130 (user-error "Priority commands are disabled"))
14131 (setq action (or action 'set))
14132 (let (current new news have remove)
14133 (save-excursion
14134 (org-back-to-heading t)
14135 (when (looking-at org-priority-regexp)
14136 (setq current (string-to-char (match-string 2))
14137 have t))
14138 (cond
14139 ((eq action 'remove)
14140 (setq remove t new ?\ ))
14141 ((or (eq action 'set)
14142 (integerp action))
14143 (if (not (eq action 'set))
14144 (setq new action)
14145 (message "Priority %c-%c, SPC to remove: "
14146 org-highest-priority org-lowest-priority)
14147 (save-match-data
14148 (setq new (read-char-exclusive))))
14149 (when (and (= (upcase org-highest-priority) org-highest-priority)
14150 (= (upcase org-lowest-priority) org-lowest-priority))
14151 (setq new (upcase new)))
14152 (cond ((equal new ?\ ) (setq remove t))
14153 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14154 (user-error "Priority must be between `%c' and `%c'"
14155 org-highest-priority org-lowest-priority))))
14156 ((eq action 'up)
14157 (setq new (if have
14158 (1- current) ; normal cycling
14159 ;; last priority was empty
14160 (if (eq last-command this-command)
14161 org-lowest-priority ; wrap around empty to lowest
14162 ;; default
14163 (if org-priority-start-cycle-with-default
14164 org-default-priority
14165 (1- org-default-priority))))))
14166 ((eq action 'down)
14167 (setq new (if have
14168 (1+ current) ; normal cycling
14169 ;; last priority was empty
14170 (if (eq last-command this-command)
14171 org-highest-priority ; wrap around empty to highest
14172 ;; default
14173 (if org-priority-start-cycle-with-default
14174 org-default-priority
14175 (1+ org-default-priority))))))
14176 (t (user-error "Invalid action")))
14177 (when (or (< (upcase new) org-highest-priority)
14178 (> (upcase new) org-lowest-priority))
14179 (if (and (memq action '(up down))
14180 (not have) (not (eq last-command this-command)))
14181 ;; `new' is from default priority
14182 (error
14183 "The default can not be set, see `org-default-priority' why")
14184 ;; normal cycling: `new' is beyond highest/lowest priority
14185 ;; and is wrapped around to the empty priority
14186 (setq remove t)))
14187 (setq news (format "%c" new))
14188 (if have
14189 (if remove
14190 (replace-match "" t t nil 1)
14191 (replace-match news t t nil 2))
14192 (if remove
14193 (user-error "No priority cookie found in line")
14194 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14195 (if (match-end 2)
14196 (progn
14197 (goto-char (match-end 2))
14198 (insert " [#" news "]"))
14199 (goto-char (match-beginning 3))
14200 (insert "[#" news "] "))))
14201 (org-set-tags nil 'align))
14202 (if remove
14203 (message "Priority removed")
14204 (message "Priority of current item set to %s" news)))))
14206 (defun org-show-priority ()
14207 "Show the priority of the current item.
14208 This priority is composed of the main priority given with the [#A] cookies,
14209 and by additional input from the age of a schedules or deadline entry."
14210 (interactive)
14211 (let ((pri (if (eq major-mode 'org-agenda-mode)
14212 (org-get-at-bol 'priority)
14213 (save-excursion
14214 (save-match-data
14215 (beginning-of-line)
14216 (and (looking-at org-heading-regexp)
14217 (org-get-priority (match-string 0))))))))
14218 (message "Priority is %d" (if pri pri -1000))))
14220 (defun org-get-priority (s)
14221 "Find priority cookie and return priority."
14222 (save-match-data
14223 (if (functionp org-get-priority-function)
14224 (funcall org-get-priority-function)
14225 (if (not (string-match org-priority-regexp s))
14226 (* 1000 (- org-lowest-priority org-default-priority))
14227 (* 1000 (- org-lowest-priority
14228 (string-to-char (match-string 2 s))))))))
14230 ;;;; Tags
14232 (defvar org-agenda-archives-mode)
14233 (defvar org-map-continue-from nil
14234 "Position from where mapping should continue.
14235 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14237 (defvar org-scanner-tags nil
14238 "The current tag list while the tags scanner is running.")
14240 (defvar org-trust-scanner-tags nil
14241 "Should `org-get-tags-at' use the tags for the scanner.
14242 This is for internal dynamical scoping only.
14243 When this is non-nil, the function `org-get-tags-at' will return the value
14244 of `org-scanner-tags' instead of building the list by itself. This
14245 can lead to large speed-ups when the tags scanner is used in a file with
14246 many entries, and when the list of tags is retrieved, for example to
14247 obtain a list of properties. Building the tags list for each entry in such
14248 a file becomes an N^2 operation - but with this variable set, it scales
14249 as N.")
14251 (defvar org--matcher-tags-todo-only nil)
14253 (defun org-scan-tags (action matcher todo-only &optional start-level)
14254 "Scan headline tags with inheritance and produce output ACTION.
14256 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14257 or `agenda' to produce an entry list for an agenda view. It can also be
14258 a Lisp form or a function that should be called at each matched headline, in
14259 this case the return value is a list of all return values from these calls.
14261 MATCHER is a function accepting three arguments, returning
14262 a non-nil value whenever a given set of tags qualifies a headline
14263 for inclusion. See `org-make-tags-matcher' for more information.
14264 As a special case, it can also be set to t (respectively nil) in
14265 order to match all (respectively none) headline.
14267 When TODO-ONLY is non-nil, only lines with a not-done TODO
14268 keyword are included in the output.
14270 START-LEVEL can be a string with asterisks, reducing the scope to
14271 headlines matching this string."
14272 (require 'org-agenda)
14273 (let* ((re (concat "^"
14274 (if start-level
14275 ;; Get the correct level to match
14276 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14277 org-outline-regexp)
14278 " *\\(\\<\\("
14279 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14280 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14281 (props (list 'face 'default
14282 'done-face 'org-agenda-done
14283 'undone-face 'default
14284 'mouse-face 'highlight
14285 'org-not-done-regexp org-not-done-regexp
14286 'org-todo-regexp org-todo-regexp
14287 'org-complex-heading-regexp org-complex-heading-regexp
14288 'help-echo
14289 (format "mouse-2 or RET jump to org file %s"
14290 (abbreviate-file-name
14291 (or (buffer-file-name (buffer-base-buffer))
14292 (buffer-name (buffer-base-buffer)))))))
14293 (org-map-continue-from nil)
14294 lspos tags tags-list
14295 (tags-alist (list (cons 0 org-file-tags)))
14296 (llast 0) rtn rtn1 level category i txt
14297 todo marker entry priority
14298 ts-date ts-date-type ts-date-pair)
14299 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14300 (setq action (list 'lambda nil action)))
14301 (save-excursion
14302 (goto-char (point-min))
14303 (when (eq action 'sparse-tree)
14304 (org-overview)
14305 (org-remove-occur-highlights))
14306 (while (let (case-fold-search)
14307 (re-search-forward re nil t))
14308 (setq org-map-continue-from nil)
14309 (catch :skip
14310 (setq todo
14311 ;; TODO: is the 1-2 difference a bug?
14312 (when (match-end 1) (match-string-no-properties 2))
14313 tags (when (match-end 4) (match-string-no-properties 4)))
14314 (goto-char (setq lspos (match-beginning 0)))
14315 (setq level (org-reduced-level (org-outline-level))
14316 category (org-get-category))
14317 (when (eq action 'agenda)
14318 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14319 ts-date (car ts-date-pair)
14320 ts-date-type (cdr ts-date-pair)))
14321 (setq i llast llast level)
14322 ;; remove tag lists from same and sublevels
14323 (while (>= i level)
14324 (when (setq entry (assoc i tags-alist))
14325 (setq tags-alist (delete entry tags-alist)))
14326 (setq i (1- i)))
14327 ;; add the next tags
14328 (when tags
14329 (setq tags (org-split-string tags ":")
14330 tags-alist
14331 (cons (cons level tags) tags-alist)))
14332 ;; compile tags for current headline
14333 (setq tags-list
14334 (if org-use-tag-inheritance
14335 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14336 tags)
14337 org-scanner-tags tags-list)
14338 (when org-use-tag-inheritance
14339 (setcdr (car tags-alist)
14340 (mapcar (lambda (x)
14341 (setq x (copy-sequence x))
14342 (org-add-prop-inherited x))
14343 (cdar tags-alist))))
14344 (when (and tags org-use-tag-inheritance
14345 (or (not (eq t org-use-tag-inheritance))
14346 org-tags-exclude-from-inheritance))
14347 ;; Selective inheritance, remove uninherited ones.
14348 (setcdr (car tags-alist)
14349 (org-remove-uninherited-tags (cdar tags-alist))))
14350 (when (and
14352 ;; eval matcher only when the todo condition is OK
14353 (and (or (not todo-only) (member todo org-not-done-keywords))
14354 (if (functionp matcher)
14355 (let ((case-fold-search t) (org-trust-scanner-tags t))
14356 (funcall matcher todo tags-list level))
14357 matcher))
14359 ;; Call the skipper, but return t if it does not
14360 ;; skip, so that the `and' form continues evaluating.
14361 (progn
14362 (unless (eq action 'sparse-tree) (org-agenda-skip))
14365 ;; Check if timestamps are deselecting this entry
14366 (or (not todo-only)
14367 (and (member todo org-not-done-keywords)
14368 (or (not org-agenda-tags-todo-honor-ignore-options)
14369 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14371 ;; select this headline
14372 (cond
14373 ((eq action 'sparse-tree)
14374 (and org-highlight-sparse-tree-matches
14375 (org-get-heading) (match-end 0)
14376 (org-highlight-new-match
14377 (match-beginning 1) (match-end 1)))
14378 (org-show-context 'tags-tree))
14379 ((eq action 'agenda)
14380 (setq txt (org-agenda-format-item
14382 (concat
14383 (if (eq org-tags-match-list-sublevels 'indented)
14384 (make-string (1- level) ?.) "")
14385 (org-get-heading))
14386 (make-string level ?\s)
14387 category
14388 tags-list)
14389 priority (org-get-priority txt))
14390 (goto-char lspos)
14391 (setq marker (org-agenda-new-marker))
14392 (org-add-props txt props
14393 'org-marker marker 'org-hd-marker marker 'org-category category
14394 'todo-state todo
14395 'ts-date ts-date
14396 'priority priority
14397 'type (concat "tagsmatch" ts-date-type))
14398 (push txt rtn))
14399 ((functionp action)
14400 (setq org-map-continue-from nil)
14401 (save-excursion
14402 (setq rtn1 (funcall action))
14403 (push rtn1 rtn)))
14404 (t (user-error "Invalid action")))
14406 ;; if we are to skip sublevels, jump to end of subtree
14407 (unless org-tags-match-list-sublevels
14408 (org-end-of-subtree t)
14409 (backward-char 1))))
14410 ;; Get the correct position from where to continue
14411 (if org-map-continue-from
14412 (goto-char org-map-continue-from)
14413 (and (= (point) lspos) (end-of-line 1)))))
14414 (when (and (eq action 'sparse-tree)
14415 (not org-sparse-tree-open-archived-trees))
14416 (org-hide-archived-subtrees (point-min) (point-max)))
14417 (nreverse rtn)))
14419 (defun org-remove-uninherited-tags (tags)
14420 "Remove all tags that are not inherited from the list TAGS."
14421 (cond
14422 ((eq org-use-tag-inheritance t)
14423 (if org-tags-exclude-from-inheritance
14424 (org-delete-all org-tags-exclude-from-inheritance tags)
14425 tags))
14426 ((not org-use-tag-inheritance) nil)
14427 ((stringp org-use-tag-inheritance)
14428 (delq nil (mapcar
14429 (lambda (x)
14430 (if (and (string-match org-use-tag-inheritance x)
14431 (not (member x org-tags-exclude-from-inheritance)))
14432 x nil))
14433 tags)))
14434 ((listp org-use-tag-inheritance)
14435 (delq nil (mapcar
14436 (lambda (x)
14437 (if (member x org-use-tag-inheritance) x nil))
14438 tags)))))
14440 (defun org-match-sparse-tree (&optional todo-only match)
14441 "Create a sparse tree according to tags string MATCH.
14443 MATCH is a string with match syntax. It can contain a selection
14444 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14445 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14446 those. See the manual for details.
14448 If optional argument TODO-ONLY is non-nil, only select lines that
14449 are also TODO tasks."
14450 (interactive "P")
14451 (org-agenda-prepare-buffers (list (current-buffer)))
14452 (let ((org--matcher-tags-todo-only todo-only))
14453 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14454 org--matcher-tags-todo-only)))
14456 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14458 (defvar org-cached-props nil)
14459 (defun org-cached-entry-get (pom property)
14460 (if (or (eq t org-use-property-inheritance)
14461 (and (stringp org-use-property-inheritance)
14462 (let ((case-fold-search t))
14463 (string-match-p org-use-property-inheritance property)))
14464 (and (listp org-use-property-inheritance)
14465 (member-ignore-case property org-use-property-inheritance)))
14466 ;; Caching is not possible, check it directly.
14467 (org-entry-get pom property 'inherit)
14468 ;; Get all properties, so we can do complicated checks easily.
14469 (cdr (assoc-string property
14470 (or org-cached-props
14471 (setq org-cached-props (org-entry-properties pom)))
14472 t))))
14474 (defun org-global-tags-completion-table (&optional files)
14475 "Return the list of all tags in all agenda buffer/files.
14476 Optional FILES argument is a list of files which can be used
14477 instead of the agenda files."
14478 (save-excursion
14479 (org-uniquify
14480 (delq nil
14481 (apply #'append
14482 (mapcar
14483 (lambda (file)
14484 (set-buffer (find-file-noselect file))
14485 (mapcar (lambda (x)
14486 (and (stringp (car-safe x))
14487 (list (car-safe x))))
14488 (or org-current-tag-alist (org-get-buffer-tags))))
14489 (if (car-safe files) files
14490 (org-agenda-files))))))))
14492 (defun org-make-tags-matcher (match)
14493 "Create the TAGS/TODO matcher form for the selection string MATCH.
14495 Returns a cons of the selection string MATCH and a function
14496 implementing the matcher.
14498 The matcher is to be called at an Org entry, with point on the
14499 headline, and returns non-nil if the entry matches the selection
14500 string MATCH. It must be called with three arguments: the TODO
14501 keyword at the entry (or nil if none), the list of all tags at
14502 the entry including inherited ones and the reduced level of the
14503 headline. Additionally, the category of the entry, if any, must
14504 be specified as the text property `org-category' on the headline.
14506 This function sets the variable `org--matcher-tags-todo-only' to
14507 a non-nil value if the matcher restricts matching to TODO
14508 entries, otherwise it is not touched.
14510 See also `org-scan-tags'."
14511 (unless match
14512 ;; Get a new match request, with completion against the global
14513 ;; tags table and the local tags in current buffer.
14514 (let ((org-last-tags-completion-table
14515 (org-uniquify
14516 (delq nil (append (org-get-buffer-tags)
14517 (org-global-tags-completion-table))))))
14518 (setq match
14519 (completing-read
14520 "Match: "
14521 'org-tags-completion-function nil nil nil 'org-tags-history))))
14523 (let ((match0 match)
14524 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14525 (start 0)
14526 tagsmatch todomatch tagsmatcher todomatcher)
14528 ;; Expand group tags.
14529 (setq match (org-tags-expand match))
14531 ;; Check if there is a TODO part of this match, which would be the
14532 ;; part after a "/". To make sure that this slash is not part of
14533 ;; a property value to be matched against, we also check that
14534 ;; there is no / after that slash. First, find the last slash.
14535 (let ((s 0))
14536 (while (string-match "/+" match s)
14537 (setq start (match-beginning 0))
14538 (setq s (match-end 0))))
14539 (if (and (string-match "/+" match start)
14540 (not (string-match-p "\"" match start)))
14541 ;; Match contains also a TODO-matching request.
14542 (progn
14543 (setq tagsmatch (substring match 0 (match-beginning 0)))
14544 (setq todomatch (substring match (match-end 0)))
14545 (when (string-prefix-p "!" todomatch)
14546 (setq org--matcher-tags-todo-only t)
14547 (setq todomatch (substring todomatch 1)))
14548 (when (string-match "\\`\\s-*\\'" todomatch)
14549 (setq todomatch nil)))
14550 ;; Only matching tags.
14551 (setq tagsmatch match)
14552 (setq todomatch nil))
14554 ;; Make the tags matcher.
14555 (when (org-string-nw-p tagsmatch)
14556 (let ((orlist nil)
14557 (orterms (org-split-string tagsmatch "|"))
14558 term)
14559 (while (setq term (pop orterms))
14560 (while (and (equal (substring term -1) "\\") orterms)
14561 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14562 (while (string-match re term)
14563 (let* ((rest (substring term (match-end 0)))
14564 (minus (and (match-end 1)
14565 (equal (match-string 1 term) "-")))
14566 (tag (save-match-data
14567 (replace-regexp-in-string
14568 "\\\\-" "-" (match-string 2 term))))
14569 (regexp (eq (string-to-char tag) ?{))
14570 (levelp (match-end 4))
14571 (propp (match-end 5))
14573 (cond
14574 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14575 (levelp
14576 `(,(org-op-to-function (match-string 3 term))
14577 level
14578 ,(string-to-number (match-string 4 term))))
14579 (propp
14580 (let* ((gv (pcase (upcase (match-string 5 term))
14581 ("CATEGORY"
14582 '(get-text-property (point) 'org-category))
14583 ("TODO" 'todo)
14584 (p `(org-cached-entry-get nil ,p))))
14585 (pv (match-string 7 term))
14586 (regexp (eq (string-to-char pv) ?{))
14587 (strp (eq (string-to-char pv) ?\"))
14588 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14589 (po (org-op-to-function (match-string 6 term)
14590 (if timep 'time strp))))
14591 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14592 (when timep (setq pv (org-matcher-time pv)))
14593 (cond ((and regexp (eq po 'org<>))
14594 `(not (string-match ,pv (or ,gv ""))))
14595 (regexp `(string-match ,pv (or ,gv "")))
14596 (strp `(,po (or ,gv "") ,pv))
14598 `(,po
14599 (string-to-number (or ,gv ""))
14600 ,(string-to-number pv))))))
14601 (t `(member ,tag tags-list)))))
14602 (push (if minus `(not ,mm) mm) tagsmatcher)
14603 (setq term rest)))
14604 (push `(and ,@tagsmatcher) orlist)
14605 (setq tagsmatcher nil))
14606 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14608 ;; Make the TODO matcher.
14609 (when (org-string-nw-p todomatch)
14610 (let ((orlist nil))
14611 (dolist (term (org-split-string todomatch "|"))
14612 (while (string-match re term)
14613 (let* ((minus (and (match-end 1)
14614 (equal (match-string 1 term) "-")))
14615 (kwd (match-string 2 term))
14616 (regexp (eq (string-to-char kwd) ?{))
14617 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14618 `(equal todo ,kwd))))
14619 (push (if minus `(not ,mm) mm) todomatcher))
14620 (setq term (substring term (match-end 0))))
14621 (push (if (> (length todomatcher) 1)
14622 (cons 'and todomatcher)
14623 (car todomatcher))
14624 orlist)
14625 (setq todomatcher nil))
14626 (setq todomatcher (cons 'or orlist))))
14628 ;; Return the string and function of the matcher. If no
14629 ;; tags-specific or todo-specific matcher exists, match
14630 ;; everything.
14631 (let ((matcher (if (and tagsmatcher todomatcher)
14632 `(and ,tagsmatcher ,todomatcher)
14633 (or tagsmatcher todomatcher t))))
14634 (when org--matcher-tags-todo-only
14635 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14636 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14638 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14639 "Expand group tags in MATCH.
14641 This replaces every group tag in MATCH with a regexp tag search.
14642 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14643 will be replaced like this:
14645 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14646 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14647 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14649 Replacing by a regexp preserves the structure of the match.
14650 E.g., this expansion
14652 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14654 will match anything tagged with \"Lab\" and \"Home\", or tagged
14655 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14657 A group tag in MATCH can contain regular expressions of its own.
14658 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14659 will be replaced like this:
14661 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14663 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14664 assumed to be a single group tag, and the function will return
14665 the list of tags in this group.
14667 When DOWNCASE is non-nil, expand downcased TAGS."
14668 (if org-group-tags
14669 (let* ((case-fold-search t)
14670 (stable org-mode-syntax-table)
14671 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14672 (taggroups (if downcased
14673 (mapcar (lambda (tg) (mapcar #'downcase tg))
14674 taggroups)
14675 taggroups))
14676 (taggroups-keys (mapcar #'car taggroups))
14677 (return-match (if downcased (downcase match) match))
14678 (count 0)
14679 (work-already-expanded tags-already-expanded)
14680 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14681 ;; @ and _ are allowed as word-components in tags.
14682 (modify-syntax-entry ?@ "w" stable)
14683 (modify-syntax-entry ?_ "w" stable)
14684 ;; Temporarily replace regexp-expressions in the match-expression.
14685 (while (string-match "{.+?}" return-match)
14686 (cl-incf count)
14687 (push (match-string 0 return-match) regexps-in-match)
14688 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14689 (while (and taggroups-keys
14690 (with-syntax-table stable
14691 (string-match
14692 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14693 (regexp-opt taggroups-keys) "\\>\\)")
14694 return-match)))
14695 (let* ((dir (match-string 1 return-match))
14696 (tag (match-string 2 return-match))
14697 (tag (if downcased (downcase tag) tag)))
14698 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14699 (member tag work-already-expanded))
14700 (setq tags-in-group (assoc tag taggroups))
14701 (push tag work-already-expanded)
14702 ;; Recursively expand each tag in the group, if the tag hasn't
14703 ;; already been expanded. Restore the match-data after all recursive calls.
14704 (save-match-data
14705 (let (tags-expanded)
14706 (dolist (x (cdr tags-in-group))
14707 (if (and (member x taggroups-keys)
14708 (not (member x work-already-expanded)))
14709 (setq tags-expanded
14710 (delete-dups
14711 (append
14712 (org-tags-expand x t downcased
14713 work-already-expanded)
14714 tags-expanded)))
14715 (setq tags-expanded
14716 (append (list x) tags-expanded)))
14717 (setq work-already-expanded
14718 (delete-dups
14719 (append tags-expanded
14720 work-already-expanded))))
14721 (setq tags-in-group
14722 (delete-dups (cons (car tags-in-group)
14723 tags-expanded)))))
14724 ;; Filter tag-regexps from tags.
14725 (setq regexp-in-group-escaped
14726 (delq nil (mapcar (lambda (x)
14727 (if (stringp x)
14728 (and (equal "{" (substring x 0 1))
14729 (equal "}" (substring x -1))
14732 tags-in-group))
14733 regexp-in-group
14734 (mapcar (lambda (x)
14735 (substring x 1 -1))
14736 regexp-in-group-escaped)
14737 tags-in-group
14738 (delq nil (mapcar (lambda (x)
14739 (if (stringp x)
14740 (and (not (equal "{" (substring x 0 1)))
14741 (not (equal "}" (substring x -1)))
14744 tags-in-group)))
14745 ;; If single-as-list, do no more in the while-loop.
14746 (if (not single-as-list)
14747 (progn
14748 (when regexp-in-group
14749 (setq regexp-in-group
14750 (concat "\\|"
14751 (mapconcat 'identity regexp-in-group
14752 "\\|"))))
14753 (setq tags-in-group
14754 (concat dir
14755 "{\\<"
14756 (regexp-opt tags-in-group)
14757 "\\>"
14758 regexp-in-group
14759 "}"))
14760 (when (stringp tags-in-group)
14761 (org-add-props tags-in-group '(grouptag t)))
14762 (setq return-match
14763 (replace-match tags-in-group t t return-match)))
14764 (setq tags-in-group
14765 (append regexp-in-group-escaped tags-in-group))))
14766 (setq taggroups-keys (delete tag taggroups-keys))))
14767 ;; Add the regular expressions back into the match-expression again.
14768 (while regexps-in-match
14769 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14770 (pop regexps-in-match)
14771 return-match t t))
14772 (cl-decf count))
14773 (if single-as-list
14774 (if tags-in-group tags-in-group (list return-match))
14775 return-match))
14776 (if single-as-list
14777 (list (if downcased (downcase match) match))
14778 match)))
14780 (defun org-op-to-function (op &optional stringp)
14781 "Turn an operator into the appropriate function."
14782 (setq op
14783 (cond
14784 ((equal op "<" ) '(< string< org-time<))
14785 ((equal op ">" ) '(> org-string> org-time>))
14786 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14787 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14788 ((member op '("=" "==")) '(= string= org-time=))
14789 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14790 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14792 (defun org<> (a b) (not (= a b)))
14793 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14794 (defun org-string>= (a b) (not (string< a b)))
14795 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14796 (defun org-string<> (a b) (not (string= a b)))
14797 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
14803 (defun org-2ft (s)
14804 "Convert S to a floating point time.
14805 If S is already a number, just return it. If it is a string, parse
14806 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14807 (cond
14808 ((numberp s) s)
14809 ((stringp s)
14810 (condition-case nil
14811 (float-time (apply 'encode-time (org-parse-time-string s)))
14812 (error 0.)))
14813 (t 0.)))
14815 (defun org-time-today ()
14816 "Time in seconds today at 0:00.
14817 Returns the float number of seconds since the beginning of the
14818 epoch to the beginning of today (00:00)."
14819 (float-time (apply 'encode-time
14820 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14822 (defun org-matcher-time (s)
14823 "Interpret a time comparison value."
14824 (save-match-data
14825 (cond
14826 ((string= s "<now>") (float-time))
14827 ((string= s "<today>") (org-time-today))
14828 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14829 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14830 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14831 (+ (org-time-today)
14832 (* (string-to-number (match-string 1 s))
14833 (cdr (assoc (match-string 2 s)
14834 '(("d" . 86400.0) ("w" . 604800.0)
14835 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14836 (t (org-2ft s)))))
14838 (defun org-match-any-p (re list)
14839 "Does re match any element of list?"
14840 (setq list (mapcar (lambda (x) (string-match re x)) list))
14841 (delq nil list))
14843 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14844 (defvar org-tags-overlay (make-overlay 1 1))
14845 (delete-overlay org-tags-overlay)
14847 (defun org-get-local-tags-at (&optional pos)
14848 "Get a list of tags defined in the current headline."
14849 (org-get-tags-at pos 'local))
14851 (defun org-get-local-tags ()
14852 "Get a list of tags defined in the current headline."
14853 (org-get-tags-at nil 'local))
14855 (defun org-get-tags-at (&optional pos local)
14856 "Get a list of all headline tags applicable at POS.
14857 POS defaults to point. If tags are inherited, the list contains
14858 the targets in the same sequence as the headlines appear, i.e.
14859 the tags of the current headline come last.
14860 When LOCAL is non-nil, only return tags from the current headline,
14861 ignore inherited ones."
14862 (interactive)
14863 (if (and org-trust-scanner-tags
14864 (or (not pos) (equal pos (point)))
14865 (not local))
14866 org-scanner-tags
14867 (let (tags ltags lastpos parent)
14868 (save-excursion
14869 (save-restriction
14870 (widen)
14871 (goto-char (or pos (point)))
14872 (save-match-data
14873 (catch 'done
14874 (condition-case nil
14875 (progn
14876 (org-back-to-heading t)
14877 (while (not (equal lastpos (point)))
14878 (setq lastpos (point))
14879 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14880 (setq ltags (org-split-string
14881 (match-string-no-properties 1) ":"))
14882 (when parent
14883 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14884 (setq tags (append
14885 (if parent
14886 (org-remove-uninherited-tags ltags)
14887 ltags)
14888 tags)))
14889 (or org-use-tag-inheritance (throw 'done t))
14890 (when local (throw 'done t))
14891 (or (org-up-heading-safe) (error nil))
14892 (setq parent t)))
14893 (error nil)))))
14894 (if local
14895 tags
14896 (reverse (delete-dups
14897 (reverse (append
14898 (org-remove-uninherited-tags
14899 org-file-tags)
14900 tags)))))))))
14902 (defun org-add-prop-inherited (s)
14903 (add-text-properties 0 (length s) '(inherited t) s)
14906 (defun org-toggle-tag (tag &optional onoff)
14907 "Toggle the tag TAG for the current line.
14908 If ONOFF is `on' or `off', don't toggle but set to this state."
14909 (let (res current)
14910 (save-excursion
14911 (org-back-to-heading t)
14912 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14913 (point-at-eol) t)
14914 (progn
14915 (setq current (match-string 1))
14916 (replace-match ""))
14917 (setq current ""))
14918 (setq current (nreverse (org-split-string current ":")))
14919 (cond
14920 ((eq onoff 'on)
14921 (setq res t)
14922 (or (member tag current) (push tag current)))
14923 ((eq onoff 'off)
14924 (or (not (member tag current)) (setq current (delete tag current))))
14925 (t (if (member tag current)
14926 (setq current (delete tag current))
14927 (setq res t)
14928 (push tag current))))
14929 (end-of-line 1)
14930 (if current
14931 (progn
14932 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14933 (org-set-tags nil t))
14934 (delete-horizontal-space))
14935 (run-hooks 'org-after-tags-change-hook))
14936 res))
14938 (defun org--align-tags-here (to-col)
14939 "Align tags on the current headline to TO-COL.
14940 Assume point is on a headline."
14941 (let ((pos (point)))
14942 (beginning-of-line)
14943 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14944 (>= pos (match-beginning 2)))
14945 ;; No tags or point within tags: do not align.
14946 (goto-char pos)
14947 (goto-char (match-beginning 1))
14948 (let ((shift (max (- (if (>= to-col 0) to-col
14949 (- (abs to-col) (string-width (match-string 2))))
14950 (current-column))
14951 1)))
14952 (replace-match (make-string shift ?\s) nil nil nil 1)
14953 ;; Preserve initial position, if possible. In any case, stop
14954 ;; before tags.
14955 (when (< pos (point)) (goto-char pos))))))
14957 (defun org-set-tags-command (&optional arg just-align)
14958 "Call the set-tags command for the current entry."
14959 (interactive "P")
14960 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14961 (org-set-tags arg just-align)
14962 (save-excursion
14963 (unless (and (org-region-active-p)
14964 org-loop-over-headlines-in-active-region)
14965 (org-back-to-heading t))
14966 (org-set-tags arg just-align))))
14968 (defun org-set-tags-to (data)
14969 "Set the tags of the current entry to DATA, replacing the current tags.
14970 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14971 If DATA is nil or the empty string, any tags will be removed."
14972 (interactive "sTags: ")
14973 (setq data
14974 (cond
14975 ((eq data nil) "")
14976 ((equal data "") "")
14977 ((stringp data)
14978 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14979 ":"))
14980 ((listp data)
14981 (concat ":" (mapconcat 'identity data ":") ":"))))
14982 (when data
14983 (save-excursion
14984 (org-back-to-heading t)
14985 (when (let ((case-fold-search nil))
14986 (looking-at org-complex-heading-regexp))
14987 (if (match-end 5)
14988 (progn
14989 (goto-char (match-beginning 5))
14990 (insert data)
14991 (delete-region (point) (point-at-eol))
14992 (org-set-tags nil 'align))
14993 (goto-char (point-at-eol))
14994 (insert " " data)
14995 (org-set-tags nil 'align)))
14996 (beginning-of-line 1)
14997 (when (looking-at ".*?\\([ \t]+\\)$")
14998 (delete-region (match-beginning 1) (match-end 1))))))
15000 (defun org-align-all-tags ()
15001 "Align the tags in all headings."
15002 (interactive)
15003 (save-excursion
15004 (or (ignore-errors (org-back-to-heading t))
15005 (outline-next-heading))
15006 (if (org-at-heading-p)
15007 (org-set-tags t)
15008 (message "No headings"))))
15010 (defvar org-indent-indentation-per-level)
15011 (defun org-set-tags (&optional arg just-align)
15012 "Set the tags for the current headline.
15013 With prefix ARG, realign all tags in headings in the current buffer.
15014 When JUST-ALIGN is non-nil, only align tags."
15015 (interactive "P")
15016 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15017 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15018 'region-start-level
15019 'region))
15020 org-loop-over-headlines-in-active-region)
15021 (org-map-entries
15022 ;; We don't use ARG and JUST-ALIGN here because these args
15023 ;; are not useful when looping over headlines.
15024 #'org-set-tags
15025 org-loop-over-headlines-in-active-region
15027 '(when (org-invisible-p) (org-end-of-subtree nil t))))
15028 (let ((org-setting-tags t))
15029 (if arg
15030 (save-excursion
15031 (goto-char (point-min))
15032 (while (re-search-forward org-outline-regexp-bol nil t)
15033 (org-set-tags nil t)
15034 (end-of-line))
15035 (message "All tags realigned to column %d" org-tags-column))
15036 (let* ((current (org-get-tags-string))
15037 (tags
15038 (if just-align current
15039 ;; Get a new set of tags from the user.
15040 (save-excursion
15041 (let* ((seen)
15042 (table
15043 (setq
15044 org-last-tags-completion-table
15045 ;; Uniquify tags in alists, yet preserve
15046 ;; structure (i.e., keywords).
15047 (delq nil
15048 (mapcar
15049 (lambda (pair)
15050 (let ((head (car pair)))
15051 (cond ((symbolp head) pair)
15052 ((member head seen) nil)
15053 (t (push head seen)
15054 pair))))
15055 (append
15056 (or org-current-tag-alist
15057 (org-get-buffer-tags))
15058 (and
15059 org-complete-tags-always-offer-all-agenda-tags
15060 (org-global-tags-completion-table
15061 (org-agenda-files))))))))
15062 (current-tags (org-split-string current ":"))
15063 (inherited-tags
15064 (nreverse (nthcdr (length current-tags)
15065 (nreverse (org-get-tags-at))))))
15066 (replace-regexp-in-string
15067 "\\([-+&]+\\|,\\)"
15069 (if (or (eq t org-use-fast-tag-selection)
15070 (and org-use-fast-tag-selection
15071 (delq nil (mapcar #'cdr table))))
15072 (org-fast-tag-selection
15073 current-tags inherited-tags table
15074 (and org-fast-tag-selection-include-todo
15075 org-todo-key-alist))
15076 (let ((org-add-colon-after-tag-completion
15077 (< 1 (length table))))
15078 (org-trim
15079 (completing-read
15080 "Tags: "
15081 #'org-tags-completion-function
15082 nil nil current 'org-tags-history))))))))))
15084 (when org-tags-sort-function
15085 (setq tags
15086 (mapconcat
15087 #'identity
15088 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15089 org-tags-sort-function)
15090 ":")))
15092 (if (or (string= ":" tags)
15093 (string= "::" tags))
15094 (setq tags ""))
15095 (if (not (org-string-nw-p tags)) (setq tags "")
15096 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15097 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15099 ;; Insert new tags at the correct column.
15100 (unless (equal current tags)
15101 (save-excursion
15102 (beginning-of-line)
15103 (let ((case-fold-search nil))
15104 (looking-at org-complex-heading-regexp))
15105 ;; Remove current tags, if any.
15106 (when (match-end 5) (replace-match "" nil nil nil 5))
15107 ;; Insert new tags, if any. Otherwise, remove trailing
15108 ;; white spaces.
15109 (end-of-line)
15110 (if (not (equal tags ""))
15111 ;; When text is being inserted on an invisible
15112 ;; region boundary, it can be inadvertently sucked
15113 ;; into invisibility.
15114 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15115 (skip-chars-backward " \t")
15116 (delete-region (point) (line-end-position)))))
15117 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15118 ;; is on.
15119 (unless (equal tags "")
15120 (let* ((level (save-excursion
15121 (beginning-of-line)
15122 (skip-chars-forward "\\*")))
15123 (offset (if (bound-and-true-p org-indent-mode)
15124 (* (1- org-indent-indentation-per-level)
15125 (1- level))
15127 (tags-column
15128 (+ org-tags-column
15129 (if (> org-tags-column 0) (- offset) offset))))
15130 (org--align-tags-here tags-column))))
15131 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15133 (defun org-change-tag-in-region (beg end tag off)
15134 "Add or remove TAG for each entry in the region.
15135 This works in the agenda, and also in an Org buffer."
15136 (interactive
15137 (list (region-beginning) (region-end)
15138 (let ((org-last-tags-completion-table
15139 (if (derived-mode-p 'org-mode)
15140 (org-uniquify
15141 (delq nil (append (org-get-buffer-tags)
15142 (org-global-tags-completion-table))))
15143 (org-global-tags-completion-table))))
15144 (completing-read
15145 "Tag: " 'org-tags-completion-function nil nil nil
15146 'org-tags-history))
15147 (progn
15148 (message "[s]et or [r]emove? ")
15149 (equal (read-char-exclusive) ?r))))
15150 (when (fboundp 'deactivate-mark) (deactivate-mark))
15151 (let ((agendap (equal major-mode 'org-agenda-mode))
15152 l1 l2 m buf pos newhead (cnt 0))
15153 (goto-char end)
15154 (setq l2 (1- (org-current-line)))
15155 (goto-char beg)
15156 (setq l1 (org-current-line))
15157 (cl-loop for l from l1 to l2 do
15158 (org-goto-line l)
15159 (setq m (get-text-property (point) 'org-hd-marker))
15160 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15161 (and agendap m))
15162 (setq buf (if agendap (marker-buffer m) (current-buffer))
15163 pos (if agendap m (point)))
15164 (with-current-buffer buf
15165 (save-excursion
15166 (save-restriction
15167 (goto-char pos)
15168 (setq cnt (1+ cnt))
15169 (org-toggle-tag tag (if off 'off 'on))
15170 (setq newhead (org-get-heading)))))
15171 (and agendap (org-agenda-change-all-lines newhead m))))
15172 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15174 (defun org-tags-completion-function (string _predicate &optional flag)
15175 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15176 (confirm (lambda (x) (stringp (car x)))))
15177 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15178 (setq s1 (match-string 1 string)
15179 s2 (match-string 2 string))
15180 (setq s1 "" s2 string))
15181 (cond
15182 ((eq flag nil)
15183 ;; try completion
15184 (setq rtn (try-completion s2 ctable confirm))
15185 (when (stringp rtn)
15186 (setq rtn
15187 (concat s1 s2 (substring rtn (length s2))
15188 (if (and org-add-colon-after-tag-completion
15189 (assoc rtn ctable))
15190 ":" ""))))
15191 rtn)
15192 ((eq flag t)
15193 ;; all-completions
15194 (all-completions s2 ctable confirm))
15195 ((eq flag 'lambda)
15196 ;; exact match?
15197 (assoc s2 ctable)))))
15199 (defun org-fast-tag-insert (kwd tags face &optional end)
15200 "Insert KDW, and the TAGS, the latter with face FACE.
15201 Also insert END."
15202 (insert (format "%-12s" (concat kwd ":"))
15203 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15204 (or end "")))
15206 (defun org-fast-tag-show-exit (flag)
15207 (save-excursion
15208 (org-goto-line 3)
15209 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15210 (replace-match ""))
15211 (when flag
15212 (end-of-line 1)
15213 (org-move-to-column (- (window-width) 19) t)
15214 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15216 (defun org-set-current-tags-overlay (current prefix)
15217 "Add an overlay to CURRENT tag with PREFIX."
15218 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15219 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15220 (org-overlay-display org-tags-overlay (concat prefix s))))
15222 (defvar org-last-tag-selection-key nil)
15223 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15224 "Fast tag selection with single keys.
15225 CURRENT is the current list of tags in the headline, INHERITED is the
15226 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15227 possibly with grouping information. TODO-TABLE is a similar table with
15228 TODO keywords, should these have keys assigned to them.
15229 If the keys are nil, a-z are automatically assigned.
15230 Returns the new tags string, or nil to not change the current settings."
15231 (let* ((fulltable (append table todo-table))
15232 (maxlen (apply 'max (mapcar
15233 (lambda (x)
15234 (if (stringp (car x)) (string-width (car x)) 0))
15235 fulltable)))
15236 (buf (current-buffer))
15237 (expert (eq org-fast-tag-selection-single-key 'expert))
15238 (buffer-tags nil)
15239 (fwidth (+ maxlen 3 1 3))
15240 (ncol (/ (- (window-width) 4) fwidth))
15241 (i-face 'org-done)
15242 (c-face 'org-todo)
15243 tg cnt e c char c1 c2 ntable tbl rtn
15244 ov-start ov-end ov-prefix
15245 (exit-after-next org-fast-tag-selection-single-key)
15246 (done-keywords org-done-keywords)
15247 groups ingroup intaggroup)
15248 (save-excursion
15249 (beginning-of-line 1)
15250 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15251 (setq ov-start (match-beginning 1)
15252 ov-end (match-end 1)
15253 ov-prefix "")
15254 (setq ov-start (1- (point-at-eol))
15255 ov-end (1+ ov-start))
15256 (skip-chars-forward "^\n\r")
15257 (setq ov-prefix
15258 (concat
15259 (buffer-substring (1- (point)) (point))
15260 (if (> (current-column) org-tags-column)
15262 (make-string (- org-tags-column (current-column)) ?\ ))))))
15263 (move-overlay org-tags-overlay ov-start ov-end)
15264 (save-window-excursion
15265 (if expert
15266 (set-buffer (get-buffer-create " *Org tags*"))
15267 (delete-other-windows)
15268 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15269 (org-switch-to-buffer-other-window " *Org tags*"))
15270 (erase-buffer)
15271 (setq-local org-done-keywords done-keywords)
15272 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15273 (org-fast-tag-insert "Current" current c-face "\n\n")
15274 (org-fast-tag-show-exit exit-after-next)
15275 (org-set-current-tags-overlay current ov-prefix)
15276 (setq tbl fulltable char ?a cnt 0)
15277 (while (setq e (pop tbl))
15278 (cond
15279 ((eq (car e) :startgroup)
15280 (push '() groups) (setq ingroup t)
15281 (unless (zerop cnt)
15282 (setq cnt 0)
15283 (insert "\n"))
15284 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15285 ((eq (car e) :endgroup)
15286 (setq ingroup nil cnt 0)
15287 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15288 ((eq (car e) :startgrouptag)
15289 (setq intaggroup t)
15290 (unless (zerop cnt)
15291 (setq cnt 0)
15292 (insert "\n"))
15293 (insert "[ "))
15294 ((eq (car e) :endgrouptag)
15295 (setq intaggroup nil cnt 0)
15296 (insert "]\n"))
15297 ((equal e '(:newline))
15298 (unless (zerop cnt)
15299 (setq cnt 0)
15300 (insert "\n")
15301 (setq e (car tbl))
15302 (while (equal (car tbl) '(:newline))
15303 (insert "\n")
15304 (setq tbl (cdr tbl)))))
15305 ((equal e '(:grouptags)) (insert " : "))
15307 (setq tg (copy-sequence (car e)) c2 nil)
15308 (if (cdr e)
15309 (setq c (cdr e))
15310 ;; automatically assign a character.
15311 (setq c1 (string-to-char
15312 (downcase (substring
15313 tg (if (= (string-to-char tg) ?@) 1 0)))))
15314 (if (or (rassoc c1 ntable) (rassoc c1 table))
15315 (while (or (rassoc char ntable) (rassoc char table))
15316 (setq char (1+ char)))
15317 (setq c2 c1))
15318 (setq c (or c2 char)))
15319 (when ingroup (push tg (car groups)))
15320 (setq tg (org-add-props tg nil 'face
15321 (cond
15322 ((not (assoc tg table))
15323 (org-get-todo-face tg))
15324 ((member tg current) c-face)
15325 ((member tg inherited) i-face))))
15326 (when (equal (caar tbl) :grouptags)
15327 (org-add-props tg nil 'face 'org-tag-group))
15328 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15329 (insert "[" c "] " tg (make-string
15330 (- fwidth 4 (length tg)) ?\ ))
15331 (push (cons tg c) ntable)
15332 (when (= (cl-incf cnt) ncol)
15333 (insert "\n")
15334 (when (or ingroup intaggroup) (insert " "))
15335 (setq cnt 0)))))
15336 (setq ntable (nreverse ntable))
15337 (insert "\n")
15338 (goto-char (point-min))
15339 (unless expert (org-fit-window-to-buffer))
15340 (setq rtn
15341 (catch 'exit
15342 (while t
15343 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15344 (if (not groups) "no " "")
15345 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15346 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15347 (setq org-last-tag-selection-key c)
15348 (cond
15349 ((= c ?\r) (throw 'exit t))
15350 ((= c ?!)
15351 (setq groups (not groups))
15352 (goto-char (point-min))
15353 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15354 ((= c ?\C-c)
15355 (if (not expert)
15356 (org-fast-tag-show-exit
15357 (setq exit-after-next (not exit-after-next)))
15358 (setq expert nil)
15359 (delete-other-windows)
15360 (set-window-buffer (split-window-vertically) " *Org tags*")
15361 (org-switch-to-buffer-other-window " *Org tags*")
15362 (org-fit-window-to-buffer)))
15363 ((or (= c ?\C-g)
15364 (and (= c ?q) (not (rassoc c ntable))))
15365 (delete-overlay org-tags-overlay)
15366 (setq quit-flag t))
15367 ((= c ?\ )
15368 (setq current nil)
15369 (when exit-after-next (setq exit-after-next 'now)))
15370 ((= c ?\t)
15371 (condition-case nil
15372 (setq tg (completing-read
15373 "Tag: "
15374 (or buffer-tags
15375 (with-current-buffer buf
15376 (setq buffer-tags
15377 (org-get-buffer-tags))))))
15378 (quit (setq tg "")))
15379 (when (string-match "\\S-" tg)
15380 (cl-pushnew (list tg) buffer-tags :test #'equal)
15381 (if (member tg current)
15382 (setq current (delete tg current))
15383 (push tg current)))
15384 (when exit-after-next (setq exit-after-next 'now)))
15385 ((setq e (rassoc c todo-table) tg (car e))
15386 (with-current-buffer buf
15387 (save-excursion (org-todo tg)))
15388 (when exit-after-next (setq exit-after-next 'now)))
15389 ((setq e (rassoc c ntable) tg (car e))
15390 (if (member tg current)
15391 (setq current (delete tg current))
15392 (cl-loop for g in groups do
15393 (when (member tg g)
15394 (dolist (x g) (setq current (delete x current)))))
15395 (push tg current))
15396 (when exit-after-next (setq exit-after-next 'now))))
15398 ;; Create a sorted list
15399 (setq current
15400 (sort current
15401 (lambda (a b)
15402 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15403 (when (eq exit-after-next 'now) (throw 'exit t))
15404 (goto-char (point-min))
15405 (beginning-of-line 2)
15406 (delete-region (point) (point-at-eol))
15407 (org-fast-tag-insert "Current" current c-face)
15408 (org-set-current-tags-overlay current ov-prefix)
15409 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15410 (setq tg (match-string 1))
15411 (add-text-properties
15412 (match-beginning 1) (match-end 1)
15413 (list 'face
15414 (cond
15415 ((member tg current) c-face)
15416 ((member tg inherited) i-face)
15417 (t (get-text-property (match-beginning 1) 'face))))))
15418 (goto-char (point-min)))))
15419 (delete-overlay org-tags-overlay)
15420 (if rtn
15421 (mapconcat 'identity current ":")
15422 nil))))
15424 (defun org-get-tags-string ()
15425 "Get the TAGS string in the current headline."
15426 (unless (org-at-heading-p t)
15427 (user-error "Not on a heading"))
15428 (save-excursion
15429 (beginning-of-line 1)
15430 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15431 (match-string-no-properties 1)
15432 "")))
15434 (defun org-get-tags ()
15435 "Get the list of tags specified in the current headline."
15436 (org-split-string (org-get-tags-string) ":"))
15438 (defun org-get-buffer-tags ()
15439 "Get a table of all tags used in the buffer, for completion."
15440 (org-with-wide-buffer
15441 (goto-char (point-min))
15442 (let ((tag-re (concat org-outline-regexp-bol
15443 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15444 tags)
15445 (while (re-search-forward tag-re nil t)
15446 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15447 (push tag tags)))
15448 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15450 ;;;; The mapping API
15452 (defvar org-agenda-skip-comment-trees)
15453 (defvar org-agenda-skip-function)
15454 (defun org-map-entries (func &optional match scope &rest skip)
15455 "Call FUNC at each headline selected by MATCH in SCOPE.
15457 FUNC is a function or a lisp form. The function will be called without
15458 arguments, with the cursor positioned at the beginning of the headline.
15459 The return values of all calls to the function will be collected and
15460 returned as a list.
15462 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15463 does not need to preserve point. After evaluation, the cursor will be
15464 moved to the end of the line (presumably of the headline of the
15465 processed entry) and search continues from there. Under some
15466 circumstances, this may not produce the wanted results. For example,
15467 if you have removed (e.g. archived) the current (sub)tree it could
15468 mean that the next entry will be skipped entirely. In such cases, you
15469 can specify the position from where search should continue by making
15470 FUNC set the variable `org-map-continue-from' to the desired buffer
15471 position.
15473 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15474 Only headlines that are matched by this query will be considered during
15475 the iteration. When MATCH is nil or t, all headlines will be
15476 visited by the iteration.
15478 SCOPE determines the scope of this command. It can be any of:
15480 nil The current buffer, respecting the restriction if any
15481 tree The subtree started with the entry at point
15482 region The entries within the active region, if any
15483 region-start-level
15484 The entries within the active region, but only those at
15485 the same level than the first one.
15486 file The current buffer, without restriction
15487 file-with-archives
15488 The current buffer, and any archives associated with it
15489 agenda All agenda files
15490 agenda-with-archives
15491 All agenda files with any archive files associated with them
15492 \(file1 file2 ...)
15493 If this is a list, all files in the list will be scanned
15495 The remaining args are treated as settings for the skipping facilities of
15496 the scanner. The following items can be given here:
15498 archive skip trees with the archive tag
15499 comment skip trees with the COMMENT keyword
15500 function or Emacs Lisp form:
15501 will be used as value for `org-agenda-skip-function', so
15502 whenever the function returns a position, FUNC will not be
15503 called for that entry and search will continue from the
15504 position returned
15506 If your function needs to retrieve the tags including inherited tags
15507 at the *current* entry, you can use the value of the variable
15508 `org-scanner-tags' which will be much faster than getting the value
15509 with `org-get-tags-at'. If your function gets properties with
15510 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15511 to t around the call to `org-entry-properties' to get the same speedup.
15512 Note that if your function moves around to retrieve tags and properties at
15513 a *different* entry, you cannot use these techniques."
15514 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15515 (not (org-region-active-p)))
15516 (let* ((org-agenda-archives-mode nil) ; just to make sure
15517 (org-agenda-skip-archived-trees (memq 'archive skip))
15518 (org-agenda-skip-comment-trees (memq 'comment skip))
15519 (org-agenda-skip-function
15520 (car (org-delete-all '(comment archive) skip)))
15521 (org-tags-match-list-sublevels t)
15522 (start-level (eq scope 'region-start-level))
15523 matcher res
15524 org-todo-keywords-for-agenda
15525 org-done-keywords-for-agenda
15526 org-todo-keyword-alist-for-agenda
15527 org-tag-alist-for-agenda
15528 org--matcher-tags-todo-only)
15530 (cond
15531 ((eq match t) (setq matcher t))
15532 ((eq match nil) (setq matcher t))
15533 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15535 (save-excursion
15536 (save-restriction
15537 (cond ((eq scope 'tree)
15538 (org-back-to-heading t)
15539 (org-narrow-to-subtree)
15540 (setq scope nil))
15541 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15542 (org-region-active-p))
15543 ;; If needed, set start-level to a string like "2"
15544 (when start-level
15545 (save-excursion
15546 (goto-char (region-beginning))
15547 (unless (org-at-heading-p) (outline-next-heading))
15548 (setq start-level (org-current-level))))
15549 (narrow-to-region (region-beginning)
15550 (save-excursion
15551 (goto-char (region-end))
15552 (unless (and (bolp) (org-at-heading-p))
15553 (outline-next-heading))
15554 (point)))
15555 (setq scope nil)))
15557 (if (not scope)
15558 (progn
15559 (org-agenda-prepare-buffers
15560 (and buffer-file-name (list buffer-file-name)))
15561 (setq res
15562 (org-scan-tags
15563 func matcher org--matcher-tags-todo-only start-level)))
15564 ;; Get the right scope
15565 (cond
15566 ((and scope (listp scope) (symbolp (car scope)))
15567 (setq scope (eval scope)))
15568 ((eq scope 'agenda)
15569 (setq scope (org-agenda-files t)))
15570 ((eq scope 'agenda-with-archives)
15571 (setq scope (org-agenda-files t))
15572 (setq scope (org-add-archive-files scope)))
15573 ((eq scope 'file)
15574 (setq scope (and buffer-file-name (list buffer-file-name))))
15575 ((eq scope 'file-with-archives)
15576 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15577 (org-agenda-prepare-buffers scope)
15578 (dolist (file scope)
15579 (with-current-buffer (org-find-base-buffer-visiting file)
15580 (org-with-wide-buffer
15581 (goto-char (point-min))
15582 (setq res
15583 (append
15585 (org-scan-tags
15586 func matcher org--matcher-tags-todo-only)))))))))
15587 res)))
15589 ;;; Properties API
15591 (defconst org-special-properties
15592 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15593 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15594 "The special properties valid in Org mode.
15595 These are properties that are not defined in the property drawer,
15596 but in some other way.")
15598 (defconst org-default-properties
15599 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15600 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15601 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15602 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15603 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15604 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15605 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15606 "Some properties that are used by Org mode for various purposes.
15607 Being in this list makes sure that they are offered for completion.")
15609 (defun org--valid-property-p (property)
15610 "Non nil when string PROPERTY is a valid property name."
15611 (not
15612 (or (equal property "")
15613 (string-match-p "\\s-" property))))
15615 (defun org--update-property-plist (key val props)
15616 "Associate KEY to VAL in alist PROPS.
15617 Modifications are made by side-effect. Return new alist."
15618 (let* ((appending (string= (substring key -1) "+"))
15619 (key (if appending (substring key 0 -1) key))
15620 (old (assoc-string key props t)))
15621 (if (not old) (cons (cons key val) props)
15622 (setcdr old (if appending (concat (cdr old) " " val) val))
15623 props)))
15625 (defun org-get-property-block (&optional beg force)
15626 "Return the (beg . end) range of the body of the property drawer.
15627 BEG is the beginning of the current subtree, or of the part
15628 before the first headline. If it is not given, it will be found.
15629 If the drawer does not exist, create it if FORCE is non-nil, or
15630 return nil."
15631 (org-with-wide-buffer
15632 (when beg (goto-char beg))
15633 (unless (org-before-first-heading-p)
15634 (let ((beg (cond (beg)
15635 ((or (not (featurep 'org-inlinetask))
15636 (org-inlinetask-in-task-p))
15637 (org-back-to-heading t))
15638 (t (org-with-limited-levels (org-back-to-heading t))))))
15639 (forward-line)
15640 (when (looking-at-p org-planning-line-re) (forward-line))
15641 (cond ((looking-at org-property-drawer-re)
15642 (forward-line)
15643 (cons (point) (progn (goto-char (match-end 0))
15644 (line-beginning-position))))
15645 (force
15646 (goto-char beg)
15647 (org-insert-property-drawer)
15648 (let ((pos (save-excursion (search-forward ":END:")
15649 (line-beginning-position))))
15650 (cons pos pos))))))))
15652 (defun org-at-property-p ()
15653 "Non-nil when point is inside a property drawer.
15654 See `org-property-re' for match data, if applicable."
15655 (save-excursion
15656 (beginning-of-line)
15657 (and (looking-at org-property-re)
15658 (let ((property-drawer (save-match-data (org-get-property-block))))
15659 (and property-drawer
15660 (>= (point) (car property-drawer))
15661 (< (point) (cdr property-drawer)))))))
15663 (defun org-property-action ()
15664 "Do an action on properties."
15665 (interactive)
15666 (unless (org-at-property-p) (user-error "Not at a property"))
15667 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15668 (let ((c (read-char-exclusive)))
15669 (cl-case c
15670 (?s (call-interactively #'org-set-property))
15671 (?d (call-interactively #'org-delete-property))
15672 (?D (call-interactively #'org-delete-property-globally))
15673 (?c (call-interactively #'org-compute-property-at-point))
15674 (otherwise (user-error "No such property action %c" c)))))
15676 (defun org-inc-effort ()
15677 "Increment the value of the effort property in the current entry."
15678 (interactive)
15679 (org-set-effort nil t))
15681 (defvar org-clock-effort) ; Defined in org-clock.el.
15682 (defvar org-clock-current-task) ; Defined in org-clock.el.
15683 (defun org-set-effort (&optional value increment)
15684 "Set the effort property of the current entry.
15685 With numerical prefix arg, use the nth allowed value, 0 stands for the
15686 10th allowed value.
15688 When INCREMENT is non-nil, set the property to the next allowed value."
15689 (interactive "P")
15690 (when (equal value 0) (setq value 10))
15691 (let* ((completion-ignore-case t)
15692 (prop org-effort-property)
15693 (cur (org-entry-get nil prop))
15694 (allowed (org-property-get-allowed-values nil prop 'table))
15695 (existing (mapcar 'list (org-property-values prop)))
15696 (heading (nth 4 (org-heading-components)))
15698 (val (cond
15699 ((stringp value) value)
15700 ((and allowed (integerp value))
15701 (or (car (nth (1- value) allowed))
15702 (car (org-last allowed))))
15703 ((and allowed increment)
15704 (or (cl-caadr (member (list cur) allowed))
15705 (user-error "Allowed effort values are not set")))
15706 (allowed
15707 (message "Select 1-9,0, [RET%s]: %s"
15708 (if cur (concat "=" cur) "")
15709 (mapconcat 'car allowed " "))
15710 (setq rpl (read-char-exclusive))
15711 (if (equal rpl ?\r)
15713 (setq rpl (- rpl ?0))
15714 (when (equal rpl 0) (setq rpl 10))
15715 (if (and (> rpl 0) (<= rpl (length allowed)))
15716 (car (nth (1- rpl) allowed))
15717 (org-completing-read "Effort: " allowed nil))))
15719 (org-completing-read
15720 (concat "Effort" (and cur (string-match "\\S-" cur)
15721 (concat " [" cur "]"))
15722 ": ")
15723 existing nil nil "" nil cur)))))
15724 (unless (equal (org-entry-get nil prop) val)
15725 (org-entry-put nil prop val))
15726 (org-refresh-property
15727 '((effort . identity)
15728 (effort-minutes . org-duration-string-to-minutes))
15729 val)
15730 (when (equal heading (bound-and-true-p org-clock-current-task))
15731 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15732 (org-clock-update-mode-line))
15733 (message "%s is now %s" prop val)))
15735 (defun org-entry-properties (&optional pom which)
15736 "Get all properties of the current entry.
15738 When POM is a buffer position, get all properties from the entry
15739 there instead.
15741 This includes the TODO keyword, the tags, time strings for
15742 deadline, scheduled, and clocking, and any additional properties
15743 defined in the entry.
15745 If WHICH is nil or `all', get all properties. If WHICH is
15746 `special' or `standard', only get that subclass. If WHICH is
15747 a string, only get that property.
15749 Return value is an alist. Keys are properties, as upcased
15750 strings."
15751 (org-with-point-at pom
15752 (when (and (derived-mode-p 'org-mode)
15753 (ignore-errors (org-back-to-heading t)))
15754 (catch 'exit
15755 (let* ((beg (point))
15756 (specific (and (stringp which) (upcase which)))
15757 (which (cond ((not specific) which)
15758 ((member specific org-special-properties) 'special)
15759 (t 'standard)))
15760 props)
15761 ;; Get the special properties, like TODO and TAGS.
15762 (when (memq which '(nil all special))
15763 (when (or (not specific) (string= specific "CLOCKSUM"))
15764 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15765 (when clocksum
15766 (push (cons "CLOCKSUM"
15767 (org-minutes-to-clocksum-string clocksum))
15768 props)))
15769 (when specific (throw 'exit props)))
15770 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15771 (let ((clocksumt (get-text-property (point)
15772 :org-clock-minutes-today)))
15773 (when clocksumt
15774 (push (cons "CLOCKSUM_T"
15775 (org-minutes-to-clocksum-string clocksumt))
15776 props)))
15777 (when specific (throw 'exit props)))
15778 (when (or (not specific) (string= specific "ITEM"))
15779 (let ((case-fold-search nil))
15780 (when (looking-at org-complex-heading-regexp)
15781 (push (cons "ITEM"
15782 (let ((title (match-string-no-properties 4)))
15783 (if (org-string-nw-p title)
15784 (org-remove-tabs title)
15785 "")))
15786 props)))
15787 (when specific (throw 'exit props)))
15788 (when (or (not specific) (string= specific "TODO"))
15789 (let ((case-fold-search nil))
15790 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15791 (push (cons "TODO" (match-string-no-properties 2)) props)))
15792 (when specific (throw 'exit props)))
15793 (when (or (not specific) (string= specific "PRIORITY"))
15794 (push (cons "PRIORITY"
15795 (if (looking-at org-priority-regexp)
15796 (match-string-no-properties 2)
15797 (char-to-string org-default-priority)))
15798 props)
15799 (when specific (throw 'exit props)))
15800 (when (or (not specific) (string= specific "FILE"))
15801 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15802 props)
15803 (when specific (throw 'exit props)))
15804 (when (or (not specific) (string= specific "TAGS"))
15805 (let ((value (org-string-nw-p (org-get-tags-string))))
15806 (when value (push (cons "TAGS" value) props)))
15807 (when specific (throw 'exit props)))
15808 (when (or (not specific) (string= specific "ALLTAGS"))
15809 (let ((value (org-get-tags-at)))
15810 (when value
15811 (push (cons "ALLTAGS"
15812 (format ":%s:" (mapconcat #'identity value ":")))
15813 props)))
15814 (when specific (throw 'exit props)))
15815 (when (or (not specific) (string= specific "BLOCKED"))
15816 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15817 (when specific (throw 'exit props)))
15818 (when (or (not specific)
15819 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15820 (forward-line)
15821 (when (looking-at-p org-planning-line-re)
15822 (end-of-line)
15823 (let ((bol (line-beginning-position))
15824 ;; Backward compatibility: time keywords used to
15825 ;; be configurable (before 8.3). Make sure we
15826 ;; get the correct keyword.
15827 (key-assoc `(("CLOSED" . ,org-closed-string)
15828 ("DEADLINE" . ,org-deadline-string)
15829 ("SCHEDULED" . ,org-scheduled-string))))
15830 (dolist (pair (if specific (list (assoc specific key-assoc))
15831 key-assoc))
15832 (save-excursion
15833 (when (search-backward (cdr pair) bol t)
15834 (goto-char (match-end 0))
15835 (skip-chars-forward " \t")
15836 (and (looking-at org-ts-regexp-both)
15837 (push (cons (car pair)
15838 (match-string-no-properties 0))
15839 props)))))))
15840 (when specific (throw 'exit props)))
15841 (when (or (not specific)
15842 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15843 (let ((find-ts
15844 (lambda (end ts)
15845 ;; Fix next time-stamp before END. TS is the
15846 ;; list of time-stamps found so far.
15847 (let ((ts ts)
15848 (regexp (cond
15849 ((string= specific "TIMESTAMP")
15850 org-ts-regexp)
15851 ((string= specific "TIMESTAMP_IA")
15852 org-ts-regexp-inactive)
15853 ((assoc "TIMESTAMP_IA" ts)
15854 org-ts-regexp)
15855 ((assoc "TIMESTAMP" ts)
15856 org-ts-regexp-inactive)
15857 (t org-ts-regexp-both))))
15858 (catch 'next
15859 (while (re-search-forward regexp end t)
15860 (backward-char)
15861 (let ((object (org-element-context)))
15862 ;; Accept to match timestamps in node
15863 ;; properties, too.
15864 (when (memq (org-element-type object)
15865 '(node-property timestamp))
15866 (let ((type
15867 (org-element-property :type object)))
15868 (cond
15869 ((and (memq type '(active active-range))
15870 (not (equal specific "TIMESTAMP_IA")))
15871 (unless (assoc "TIMESTAMP" ts)
15872 (push (cons "TIMESTAMP"
15873 (org-element-property
15874 :raw-value object))
15876 (when specific (throw 'exit ts))))
15877 ((and (memq type '(inactive inactive-range))
15878 (not (string= specific "TIMESTAMP")))
15879 (unless (assoc "TIMESTAMP_IA" ts)
15880 (push (cons "TIMESTAMP_IA"
15881 (org-element-property
15882 :raw-value object))
15884 (when specific (throw 'exit ts))))))
15885 ;; Both timestamp types are found,
15886 ;; move to next part.
15887 (when (= (length ts) 2) (throw 'next ts)))))
15888 ts)))))
15889 (goto-char beg)
15890 ;; First look for timestamps within headline.
15891 (let ((ts (funcall find-ts (line-end-position) nil)))
15892 (if (= (length ts) 2) (setq props (nconc ts props))
15893 ;; Then find timestamps in the section, skipping
15894 ;; planning line.
15895 (let ((end (save-excursion (outline-next-heading))))
15896 (forward-line)
15897 (when (looking-at-p org-planning-line-re) (forward-line))
15898 (setq props (nconc (funcall find-ts end ts) props))))))))
15899 ;; Get the standard properties, like :PROP:.
15900 (when (memq which '(nil all standard))
15901 ;; If we are looking after a specific property, delegate
15902 ;; to `org-entry-get', which is faster. However, make an
15903 ;; exception for "CATEGORY", since it can be also set
15904 ;; through keywords (i.e. #+CATEGORY).
15905 (if (and specific (not (equal specific "CATEGORY")))
15906 (let ((value (org-entry-get beg specific nil t)))
15907 (throw 'exit (and value (list (cons specific value)))))
15908 (let ((range (org-get-property-block beg)))
15909 (when range
15910 (let ((end (cdr range)) seen-base)
15911 (goto-char (car range))
15912 ;; Unlike to `org--update-property-plist', we
15913 ;; handle the case where base values is found
15914 ;; after its extension. We also forbid standard
15915 ;; properties to be named as special properties.
15916 (while (re-search-forward org-property-re end t)
15917 (let* ((key (upcase (match-string-no-properties 2)))
15918 (extendp (string-match-p "\\+\\'" key))
15919 (key-base (if extendp (substring key 0 -1) key))
15920 (value (match-string-no-properties 3)))
15921 (cond
15922 ((member-ignore-case key-base org-special-properties))
15923 (extendp
15924 (setq props
15925 (org--update-property-plist key value props)))
15926 ((member key seen-base))
15927 (t (push key seen-base)
15928 (let ((p (assoc-string key props t)))
15929 (if p (setcdr p (concat value " " (cdr p)))
15930 (push (cons key value) props))))))))))))
15931 (unless (assoc "CATEGORY" props)
15932 (push (cons "CATEGORY" (org-get-category beg)) props)
15933 (when (string= specific "CATEGORY") (throw 'exit props)))
15934 ;; Return value.
15935 props)))))
15937 (defun org--property-local-values (property literal-nil)
15938 "Return value for PROPERTY in current entry.
15939 Value is a list whose car is the base value for PROPERTY and cdr
15940 a list of accumulated values. Return nil if neither is found in
15941 the entry. Also return nil when PROPERTY is set to \"nil\",
15942 unless LITERAL-NIL is non-nil."
15943 (let ((range (org-get-property-block)))
15944 (when range
15945 (goto-char (car range))
15946 (let* ((case-fold-search t)
15947 (end (cdr range))
15948 (value
15949 ;; Base value.
15950 (save-excursion
15951 (let ((v (and (re-search-forward
15952 (org-re-property property nil t) end t)
15953 (match-string-no-properties 3))))
15954 (list (if literal-nil v (org-not-nil v)))))))
15955 ;; Find additional values.
15956 (let* ((property+ (org-re-property (concat property "+") nil t)))
15957 (while (re-search-forward property+ end t)
15958 (push (match-string-no-properties 3) value)))
15959 ;; Return final values.
15960 (and (not (equal value '(nil))) (nreverse value))))))
15962 (defun org--property-global-value (property literal-nil)
15963 "Return value for PROPERTY in current buffer.
15964 Return value is a string. Return nil if property is not set
15965 globally. Also return nil when PROPERTY is set to \"nil\",
15966 unless LITERAL-NIL is non-nil."
15967 (let ((global
15968 (cdr (or (assoc-string property org-file-properties t)
15969 (assoc-string property org-global-properties t)
15970 (assoc-string property org-global-properties-fixed t)))))
15971 (if literal-nil global (org-not-nil global))))
15973 (defun org-entry-get (pom property &optional inherit literal-nil)
15974 "Get value of PROPERTY for entry or content at point-or-marker POM.
15976 If INHERIT is non-nil and the entry does not have the property,
15977 then also check higher levels of the hierarchy. If INHERIT is
15978 the symbol `selective', use inheritance only if the setting in
15979 `org-use-property-inheritance' selects PROPERTY for inheritance.
15981 If the property is present but empty, the return value is the
15982 empty string. If the property is not present at all, nil is
15983 returned. In any other case, return the value as a string.
15984 Search is case-insensitive.
15986 If LITERAL-NIL is set, return the string value \"nil\" as
15987 a string, do not interpret it as the list atom nil. This is used
15988 for inheritance when a \"nil\" value can supersede a non-nil
15989 value higher up the hierarchy."
15990 (org-with-point-at pom
15991 (cond
15992 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15993 ;; We need a special property. Use `org-entry-properties' to
15994 ;; retrieve it, but specify the wanted property.
15995 (cdr (assoc-string property (org-entry-properties nil property))))
15996 ((and inherit
15997 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15998 (org-entry-get-with-inheritance property literal-nil))
16000 (let* ((local (org--property-local-values property literal-nil))
16001 (value (and local (mapconcat #'identity (delq nil local) " "))))
16002 (if literal-nil value (org-not-nil value)))))))
16004 (defun org-property-or-variable-value (var &optional inherit)
16005 "Check if there is a property fixing the value of VAR.
16006 If yes, return this value. If not, return the current value of the variable."
16007 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16008 (if (and prop (stringp prop) (string-match "\\S-" prop))
16009 (read prop)
16010 (symbol-value var))))
16012 (defun org-entry-delete (pom property)
16013 "Delete PROPERTY from entry at point-or-marker POM.
16014 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16015 non-nil when a property was removed."
16016 (org-with-point-at pom
16017 (pcase (org-get-property-block)
16018 (`(,begin . ,origin)
16019 (let* ((end (copy-marker origin))
16020 (re (org-re-property
16021 (concat (regexp-quote property) "\\+?") t t)))
16022 (goto-char begin)
16023 (while (re-search-forward re end t)
16024 (delete-region (match-beginning 0) (line-beginning-position 2)))
16025 ;; If drawer is empty, remove it altogether.
16026 (when (= begin end)
16027 (delete-region (line-beginning-position 0)
16028 (line-beginning-position 2)))
16029 ;; Return non-nil if some property was removed.
16030 (prog1 (/= end origin) (set-marker end nil))))
16031 (_ nil))))
16033 ;; Multi-values properties are properties that contain multiple values
16034 ;; These values are assumed to be single words, separated by whitespace.
16035 (defun org-entry-add-to-multivalued-property (pom property value)
16036 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16037 (let* ((old (org-entry-get pom property))
16038 (values (and old (org-split-string old "[ \t]"))))
16039 (setq value (org-entry-protect-space value))
16040 (unless (member value values)
16041 (setq values (append values (list value)))
16042 (org-entry-put pom property
16043 (mapconcat 'identity values " ")))))
16045 (defun org-entry-remove-from-multivalued-property (pom property value)
16046 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16047 (let* ((old (org-entry-get pom property))
16048 (values (and old (org-split-string old "[ \t]"))))
16049 (setq value (org-entry-protect-space value))
16050 (when (member value values)
16051 (setq values (delete value values))
16052 (org-entry-put pom property
16053 (mapconcat 'identity values " ")))))
16055 (defun org-entry-member-in-multivalued-property (pom property value)
16056 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16057 (let* ((old (org-entry-get pom property))
16058 (values (and old (org-split-string old "[ \t]"))))
16059 (setq value (org-entry-protect-space value))
16060 (member value values)))
16062 (defun org-entry-get-multivalued-property (pom property)
16063 "Return a list of values in a multivalued property."
16064 (let* ((value (org-entry-get pom property))
16065 (values (and value (org-split-string value "[ \t]"))))
16066 (mapcar 'org-entry-restore-space values)))
16068 (defun org-entry-put-multivalued-property (pom property &rest values)
16069 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16070 VALUES should be a list of strings. Spaces will be protected."
16071 (org-entry-put pom property
16072 (mapconcat 'org-entry-protect-space values " "))
16073 (let* ((value (org-entry-get pom property))
16074 (values (and value (org-split-string value "[ \t]"))))
16075 (mapcar 'org-entry-restore-space values)))
16077 (defun org-entry-protect-space (s)
16078 "Protect spaces and newline in string S."
16079 (while (string-match " " s)
16080 (setq s (replace-match "%20" t t s)))
16081 (while (string-match "\n" s)
16082 (setq s (replace-match "%0A" t t s)))
16085 (defun org-entry-restore-space (s)
16086 "Restore spaces and newline in string S."
16087 (while (string-match "%20" s)
16088 (setq s (replace-match " " t t s)))
16089 (while (string-match "%0A" s)
16090 (setq s (replace-match "\n" t t s)))
16093 (defvar org-entry-property-inherited-from (make-marker)
16094 "Marker pointing to the entry from where a property was inherited.
16095 Each call to `org-entry-get-with-inheritance' will set this marker to the
16096 location of the entry where the inheritance search matched. If there was
16097 no match, the marker will point nowhere.
16098 Note that also `org-entry-get' calls this function, if the INHERIT flag
16099 is set.")
16101 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16102 "Get PROPERTY of entry or content at point, search higher levels if needed.
16103 The search will stop at the first ancestor which has the property defined.
16104 If the value found is \"nil\", return nil to show that the property
16105 should be considered as undefined (this is the meaning of nil here).
16106 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16107 (move-marker org-entry-property-inherited-from nil)
16108 (org-with-wide-buffer
16109 (let (value)
16110 (catch 'exit
16111 (while t
16112 (let ((v (org--property-local-values property literal-nil)))
16113 (when v
16114 (setq value
16115 (concat (mapconcat #'identity (delq nil v) " ")
16116 (and value " ")
16117 value)))
16118 (cond
16119 ((car v)
16120 (org-back-to-heading t)
16121 (move-marker org-entry-property-inherited-from (point))
16122 (throw 'exit nil))
16123 ((org-up-heading-safe))
16125 (let ((global (org--property-global-value property literal-nil)))
16126 (cond ((not global))
16127 (value (setq value (concat global " " value)))
16128 (t (setq value global))))
16129 (throw 'exit nil))))))
16130 (if literal-nil value (org-not-nil value)))))
16132 (defvar org-property-changed-functions nil
16133 "Hook called when the value of a property has changed.
16134 Each hook function should accept two arguments, the name of the property
16135 and the new value.")
16137 (defun org-entry-put (pom property value)
16138 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16140 If the value is nil, it is converted to the empty string. If it
16141 is not a string, an error is raised. Also raise an error on
16142 invalid property names.
16144 PROPERTY can be any regular property (see
16145 `org-special-properties'). It can also be \"TODO\",
16146 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16148 For the last two properties, VALUE may have any of the special
16149 values \"earlier\" and \"later\". The function then increases or
16150 decreases scheduled or deadline date by one day."
16151 (cond ((null value) (setq value ""))
16152 ((not (stringp value)) (error "Properties values should be strings"))
16153 ((not (org--valid-property-p property))
16154 (user-error "Invalid property name: \"%s\"" property)))
16155 (org-with-point-at pom
16156 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16157 (org-back-to-heading t)
16158 (org-with-limited-levels (org-back-to-heading t)))
16159 (let ((beg (point)))
16160 (cond
16161 ((equal property "TODO")
16162 (cond ((not (org-string-nw-p value)) (setq value 'none))
16163 ((not (member value org-todo-keywords-1))
16164 (user-error "\"%s\" is not a valid TODO state" value)))
16165 (org-todo value)
16166 (org-set-tags nil 'align))
16167 ((equal property "PRIORITY")
16168 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16169 (org-set-tags nil 'align))
16170 ((equal property "SCHEDULED")
16171 (forward-line)
16172 (if (and (looking-at-p org-planning-line-re)
16173 (re-search-forward
16174 org-scheduled-time-regexp (line-end-position) t))
16175 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16176 ((string= value "later") (org-timestamp-change 1 'day))
16177 ((string= value "") (org-schedule '(4)))
16178 (t (org-schedule nil value)))
16179 (if (member value '("earlier" "later" ""))
16180 (call-interactively #'org-schedule)
16181 (org-schedule nil value))))
16182 ((equal property "DEADLINE")
16183 (forward-line)
16184 (if (and (looking-at-p org-planning-line-re)
16185 (re-search-forward
16186 org-deadline-time-regexp (line-end-position) t))
16187 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16188 ((string= value "later") (org-timestamp-change 1 'day))
16189 ((string= value "") (org-deadline '(4)))
16190 (t (org-deadline nil value)))
16191 (if (member value '("earlier" "later" ""))
16192 (call-interactively #'org-deadline)
16193 (org-deadline nil value))))
16194 ((member property org-special-properties)
16195 (error "The %s property cannot be set with `org-entry-put'" property))
16197 (let* ((range (org-get-property-block beg 'force))
16198 (end (cdr range))
16199 (case-fold-search t))
16200 (goto-char (car range))
16201 (if (re-search-forward (org-re-property property nil t) end t)
16202 (progn (delete-region (match-beginning 0) (match-end 0))
16203 (goto-char (match-beginning 0)))
16204 (goto-char end)
16205 (insert "\n")
16206 (backward-char))
16207 (insert ":" property ":")
16208 (when value (insert " " value))
16209 (org-indent-line)))))
16210 (run-hook-with-args 'org-property-changed-functions property value)))
16212 (defun org-buffer-property-keys
16213 (&optional specials defaults columns ignore-malformed)
16214 "Get all property keys in the current buffer.
16216 When SPECIALS is non-nil, also list the special properties that
16217 reflect things like tags and TODO state.
16219 When DEFAULTS is non-nil, also include properties that has
16220 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16221 DESCRIPTION, LOCATION, and LOGGING and others.
16223 When COLUMNS in non-nil, also include property names given in
16224 COLUMN formats in the current buffer.
16226 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16227 automatically performed, such drawers will be silently ignored."
16228 (let ((case-fold-search t)
16229 (props (append
16230 (and specials org-special-properties)
16231 (and defaults (cons org-effort-property org-default-properties))
16232 nil)))
16233 (org-with-wide-buffer
16234 (goto-char (point-min))
16235 (while (re-search-forward org-property-start-re nil t)
16236 (let ((range (org-get-property-block)))
16237 (catch 'skip
16238 (unless range
16239 (when (and (not ignore-malformed)
16240 (not (org-before-first-heading-p))
16241 (y-or-n-p (format "Malformed drawer at %d, repair?"
16242 (line-beginning-position))))
16243 (org-get-property-block nil t))
16244 (throw 'skip nil))
16245 (goto-char (car range))
16246 (let ((begin (car range))
16247 (end (cdr range)))
16248 ;; Make sure that found property block is not located
16249 ;; before current point, as it would generate an infloop.
16250 ;; It can happen, for example, in the following
16251 ;; situation:
16253 ;; * Headline
16254 ;; :PROPERTIES:
16255 ;; ...
16256 ;; :END:
16257 ;; *************** Inlinetask
16258 ;; #+BEGIN_EXAMPLE
16259 ;; :PROPERTIES:
16260 ;; #+END_EXAMPLE
16262 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16263 (while (< (point) end)
16264 (let ((p (progn (looking-at org-property-re)
16265 (match-string-no-properties 2))))
16266 ;; Only add true property name, not extension symbol.
16267 (push (if (not (string-match-p "\\+\\'" p)) p
16268 (substring p 0 -1))
16269 props))
16270 (forward-line))))
16271 (outline-next-heading)))
16272 (when columns
16273 (goto-char (point-min))
16274 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16275 (let ((element (org-element-at-point)))
16276 (when (memq (org-element-type element) '(keyword node-property))
16277 (let ((value (org-element-property :value element))
16278 (start 0))
16279 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16280 (setq start (match-end 0))
16281 (let ((p (match-string-no-properties 1 value)))
16282 (unless (member-ignore-case p org-special-properties)
16283 (push p props))))))))))
16284 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16286 (defun org-property-values (key)
16287 "List all non-nil values of property KEY in current buffer."
16288 (org-with-wide-buffer
16289 (goto-char (point-min))
16290 (let ((case-fold-search t)
16291 (re (org-re-property key))
16292 values)
16293 (while (re-search-forward re nil t)
16294 (push (org-entry-get (point) key) values))
16295 (delete-dups values))))
16297 (defun org-insert-property-drawer ()
16298 "Insert a property drawer into the current entry."
16299 (org-with-wide-buffer
16300 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16301 (org-back-to-heading t)
16302 (org-with-limited-levels (org-back-to-heading t)))
16303 (forward-line)
16304 (when (looking-at-p org-planning-line-re) (forward-line))
16305 (unless (looking-at-p org-property-drawer-re)
16306 ;; Make sure we start editing a line from current entry, not from
16307 ;; next one. It prevents extending text properties or overlays
16308 ;; belonging to the latter.
16309 (when (bolp) (backward-char))
16310 (let ((begin (1+ (point)))
16311 (inhibit-read-only t))
16312 (insert "\n:PROPERTIES:\n:END:")
16313 (when (eobp) (insert "\n"))
16314 (org-indent-region begin (point))))))
16316 (defun org-insert-drawer (&optional arg drawer)
16317 "Insert a drawer at point.
16319 When optional argument ARG is non-nil, insert a property drawer.
16321 Optional argument DRAWER, when non-nil, is a string representing
16322 drawer's name. Otherwise, the user is prompted for a name.
16324 If a region is active, insert the drawer around that region
16325 instead.
16327 Point is left between drawer's boundaries."
16328 (interactive "P")
16329 (let* ((drawer (if arg "PROPERTIES"
16330 (or drawer (read-from-minibuffer "Drawer: ")))))
16331 (cond
16332 ;; With C-u, fall back on `org-insert-property-drawer'
16333 (arg (org-insert-property-drawer))
16334 ;; Check validity of suggested drawer's name.
16335 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16336 (user-error "Invalid drawer name"))
16337 ;; With an active region, insert a drawer at point.
16338 ((not (org-region-active-p))
16339 (progn
16340 (unless (bolp) (insert "\n"))
16341 (insert (format ":%s:\n\n:END:\n" drawer))
16342 (forward-line -2)))
16343 ;; Otherwise, insert the drawer at point
16345 (let ((rbeg (region-beginning))
16346 (rend (copy-marker (region-end))))
16347 (unwind-protect
16348 (progn
16349 (goto-char rbeg)
16350 (beginning-of-line)
16351 (when (save-excursion
16352 (re-search-forward org-outline-regexp-bol rend t))
16353 (user-error "Drawers cannot contain headlines"))
16354 ;; Position point at the beginning of the first
16355 ;; non-blank line in region. Insert drawer's opening
16356 ;; there, then indent it.
16357 (org-skip-whitespace)
16358 (beginning-of-line)
16359 (insert ":" drawer ":\n")
16360 (forward-line -1)
16361 (indent-for-tab-command)
16362 ;; Move point to the beginning of the first blank line
16363 ;; after the last non-blank line in region. Insert
16364 ;; drawer's closing, then indent it.
16365 (goto-char rend)
16366 (skip-chars-backward " \r\t\n")
16367 (insert "\n:END:")
16368 (deactivate-mark t)
16369 (indent-for-tab-command)
16370 (unless (eolp) (insert "\n")))
16371 ;; Clear marker, whatever the outcome of insertion is.
16372 (set-marker rend nil)))))))
16374 (defvar org-property-set-functions-alist nil
16375 "Property set function alist.
16376 Each entry should have the following format:
16378 (PROPERTY . READ-FUNCTION)
16380 The read function will be called with the same argument as
16381 `org-completing-read'.")
16383 (defun org-set-property-function (property)
16384 "Get the function that should be used to set PROPERTY.
16385 This is computed according to `org-property-set-functions-alist'."
16386 (or (cdr (assoc property org-property-set-functions-alist))
16387 'org-completing-read))
16389 (defun org-read-property-value (property)
16390 "Read PROPERTY value from user."
16391 (let* ((completion-ignore-case t)
16392 (allowed (org-property-get-allowed-values nil property 'table))
16393 (cur (org-entry-get nil property))
16394 (prompt (concat property " value"
16395 (if (and cur (string-match "\\S-" cur))
16396 (concat " [" cur "]") "") ": "))
16397 (set-function (org-set-property-function property))
16398 (val (if allowed
16399 (funcall set-function prompt allowed nil
16400 (not (get-text-property 0 'org-unrestricted
16401 (caar allowed))))
16402 (funcall set-function prompt
16403 (mapcar 'list (org-property-values property))
16404 nil nil "" nil cur))))
16405 (org-trim val)))
16407 (defvar org-last-set-property nil)
16408 (defvar org-last-set-property-value nil)
16409 (defun org-read-property-name ()
16410 "Read a property name."
16411 (let ((completion-ignore-case t)
16412 (default-prop (or (and (org-at-property-p)
16413 (match-string-no-properties 2))
16414 org-last-set-property)))
16415 (org-completing-read
16416 (concat "Property"
16417 (if default-prop (concat " [" default-prop "]") "")
16418 ": ")
16419 (mapcar #'list (org-buffer-property-keys nil t t))
16420 nil nil nil nil default-prop)))
16422 (defun org-set-property-and-value (use-last)
16423 "Allow to set [PROPERTY]: [value] direction from prompt.
16424 When use-default, don't even ask, just use the last
16425 \"[PROPERTY]: [value]\" string from the history."
16426 (interactive "P")
16427 (let* ((completion-ignore-case t)
16428 (pv (or (and use-last org-last-set-property-value)
16429 (org-completing-read
16430 "Enter a \"[Property]: [value]\" pair: "
16431 nil nil nil nil nil
16432 org-last-set-property-value)))
16433 prop val)
16434 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16435 (setq prop (match-string 1 pv)
16436 val (match-string 2 pv))
16437 (org-set-property prop val))))
16439 (defun org-set-property (property value)
16440 "In the current entry, set PROPERTY to VALUE.
16442 When called interactively, this will prompt for a property name, offering
16443 completion on existing and default properties. And then it will prompt
16444 for a value, offering completion either on allowed values (via an inherited
16445 xxx_ALL property) or on existing values in other instances of this property
16446 in the current file.
16448 Throw an error when trying to set a property with an invalid name."
16449 (interactive (list nil nil))
16450 (let ((property (or property (org-read-property-name))))
16451 ;; `org-entry-put' also makes the following check, but this one
16452 ;; avoids polluting `org-last-set-property' and
16453 ;; `org-last-set-property-value' needlessly.
16454 (unless (org--valid-property-p property)
16455 (user-error "Invalid property name: \"%s\"" property))
16456 (let ((value (or value (org-read-property-value property)))
16457 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16458 (setq org-last-set-property property)
16459 (setq org-last-set-property-value (concat property ": " value))
16460 ;; Possibly postprocess the inserted value:
16461 (when fn (setq value (funcall fn value)))
16462 (unless (equal (org-entry-get nil property) value)
16463 (org-entry-put nil property value)))))
16465 (defun org-find-property (property &optional value)
16466 "Find first entry in buffer that sets PROPERTY.
16468 When optional argument VALUE is non-nil, only consider an entry
16469 if it contains PROPERTY set to this value. If PROPERTY should be
16470 explicitly set to nil, use string \"nil\" for VALUE.
16472 Return position where the entry begins, or nil if there is no
16473 such entry. If narrowing is in effect, only search the visible
16474 part of the buffer."
16475 (save-excursion
16476 (goto-char (point-min))
16477 (let ((case-fold-search t)
16478 (re (org-re-property property nil (not value) value)))
16479 (catch 'exit
16480 (while (re-search-forward re nil t)
16481 (when (if value (org-at-property-p)
16482 (org-entry-get (point) property nil t))
16483 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16485 (defun org-delete-property (property)
16486 "In the current entry, delete PROPERTY."
16487 (interactive
16488 (let* ((completion-ignore-case t)
16489 (cat (org-entry-get (point) "CATEGORY"))
16490 (props0 (org-entry-properties nil 'standard))
16491 (props (if cat props0
16492 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16493 (prop (if (< 1 (length props))
16494 (completing-read "Property: " props nil t)
16495 (caar props))))
16496 (list prop)))
16497 (if (not property)
16498 (message "No property to delete in this entry")
16499 (org-entry-delete nil property)
16500 (message "Property \"%s\" deleted" property)))
16502 (defun org-delete-property-globally (property)
16503 "Remove PROPERTY globally, from all entries.
16504 This function ignores narrowing, if any."
16505 (interactive
16506 (let* ((completion-ignore-case t)
16507 (prop (completing-read
16508 "Globally remove property: "
16509 (mapcar #'list (org-buffer-property-keys)))))
16510 (list prop)))
16511 (org-with-wide-buffer
16512 (goto-char (point-min))
16513 (let ((count 0)
16514 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16515 (while (re-search-forward re nil t)
16516 (when (org-entry-delete (point) property) (cl-incf count)))
16517 (message "Property \"%s\" removed from %d entries" property count))))
16519 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16521 (defun org-compute-property-at-point ()
16522 "Compute the property at point.
16523 This looks for an enclosing column format, extracts the operator and
16524 then applies it to the property in the column format's scope."
16525 (interactive)
16526 (unless (org-at-property-p)
16527 (user-error "Not at a property"))
16528 (let ((prop (match-string-no-properties 2)))
16529 (org-columns-get-format-and-top-level)
16530 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16531 (user-error "No operator defined for property %s" prop))
16532 (org-columns-compute prop)))
16534 (defvar org-property-allowed-value-functions nil
16535 "Hook for functions supplying allowed values for a specific property.
16536 The functions must take a single argument, the name of the property, and
16537 return a flat list of allowed values. If \":ETC\" is one of
16538 the values, this means that these values are intended as defaults for
16539 completion, but that other values should be allowed too.
16540 The functions must return nil if they are not responsible for this
16541 property.")
16543 (defun org-property-get-allowed-values (pom property &optional table)
16544 "Get allowed values for the property PROPERTY.
16545 When TABLE is non-nil, return an alist that can directly be used for
16546 completion."
16547 (let (vals)
16548 (cond
16549 ((equal property "TODO")
16550 (setq vals (org-with-point-at pom
16551 (append org-todo-keywords-1 '("")))))
16552 ((equal property "PRIORITY")
16553 (let ((n org-lowest-priority))
16554 (while (>= n org-highest-priority)
16555 (push (char-to-string n) vals)
16556 (setq n (1- n)))))
16557 ((equal property "CATEGORY"))
16558 ((member property org-special-properties))
16559 ((setq vals (run-hook-with-args-until-success
16560 'org-property-allowed-value-functions property)))
16562 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16563 (when (and vals (string-match "\\S-" vals))
16564 (setq vals (car (read-from-string (concat "(" vals ")"))))
16565 (setq vals (mapcar (lambda (x)
16566 (cond ((stringp x) x)
16567 ((numberp x) (number-to-string x))
16568 ((symbolp x) (symbol-name x))
16569 (t "???")))
16570 vals)))))
16571 (when (member ":ETC" vals)
16572 (setq vals (remove ":ETC" vals))
16573 (org-add-props (car vals) '(org-unrestricted t)))
16574 (if table (mapcar 'list vals) vals)))
16576 (defun org-property-previous-allowed-value (&optional _previous)
16577 "Switch to the next allowed value for this property."
16578 (interactive)
16579 (org-property-next-allowed-value t))
16581 (defun org-property-next-allowed-value (&optional previous)
16582 "Switch to the next allowed value for this property."
16583 (interactive)
16584 (unless (org-at-property-p)
16585 (user-error "Not at a property"))
16586 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16587 (key (match-string 2))
16588 (value (match-string 3))
16589 (allowed (or (org-property-get-allowed-values (point) key)
16590 (and (member value '("[ ]" "[-]" "[X]"))
16591 '("[ ]" "[X]"))))
16592 (heading (save-match-data (nth 4 (org-heading-components))))
16593 nval)
16594 (unless allowed
16595 (user-error "Allowed values for this property have not been defined"))
16596 (when previous (setq allowed (reverse allowed)))
16597 (when (member value allowed)
16598 (setq nval (car (cdr (member value allowed)))))
16599 (setq nval (or nval (car allowed)))
16600 (when (equal nval value)
16601 (user-error "Only one allowed value for this property"))
16602 (org-at-property-p)
16603 (replace-match (concat " :" key ": " nval) t t)
16604 (org-indent-line)
16605 (beginning-of-line 1)
16606 (skip-chars-forward " \t")
16607 (when (equal prop org-effort-property)
16608 (org-refresh-property
16609 '((effort . identity)
16610 (effort-minutes . org-duration-string-to-minutes))
16611 nval)
16612 (when (string= org-clock-current-task heading)
16613 (setq org-clock-effort nval)
16614 (org-clock-update-mode-line)))
16615 (run-hook-with-args 'org-property-changed-functions key nval)))
16617 (defun org-find-olp (path &optional this-buffer)
16618 "Return a marker pointing to the entry at outline path OLP.
16619 If anything goes wrong, throw an error.
16620 You can wrap this call to catch the error like this:
16622 (condition-case msg
16623 (org-mobile-locate-entry (match-string 4))
16624 (error (nth 1 msg)))
16626 The return value will then be either a string with the error message,
16627 or a marker if everything is OK.
16629 If THIS-BUFFER is set, the outline path does not contain a file,
16630 only headings."
16631 (let* ((file (if this-buffer buffer-file-name (pop path)))
16632 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16633 (level 1)
16634 (lmin 1)
16635 (lmax 1)
16636 end found flevel)
16637 (unless buffer (error "File not found :%s" file))
16638 (with-current-buffer buffer
16639 (org-with-wide-buffer
16640 (goto-char (point-min))
16641 (dolist (heading path)
16642 (let ((re (format org-complex-heading-regexp-format
16643 (regexp-quote heading)))
16644 (cnt 0))
16645 (while (re-search-forward re end t)
16646 (setq level (- (match-end 1) (match-beginning 1)))
16647 (when (and (>= level lmin) (<= level lmax))
16648 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16649 (when (= cnt 0)
16650 (error "Heading not found on level %d: %s" lmax heading))
16651 (when (> cnt 1)
16652 (error "Heading not unique on level %d: %s" lmax heading))
16653 (goto-char found)
16654 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16655 (setq end (save-excursion (org-end-of-subtree t t)))))
16656 (when (org-at-heading-p)
16657 (point-marker))))))
16659 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16660 "Find node HEADING in BUFFER.
16661 Return a marker to the heading if it was found, or nil if not.
16662 If POS-ONLY is set, return just the position instead of a marker.
16664 The heading text must match exact, but it may have a TODO keyword,
16665 a priority cookie and tags in the standard locations."
16666 (with-current-buffer (or buffer (current-buffer))
16667 (org-with-wide-buffer
16668 (goto-char (point-min))
16669 (let (case-fold-search)
16670 (when (re-search-forward
16671 (format org-complex-heading-regexp-format
16672 (regexp-quote heading)) nil t)
16673 (if pos-only
16674 (match-beginning 0)
16675 (move-marker (make-marker) (match-beginning 0))))))))
16677 (defun org-find-exact-heading-in-directory (heading &optional dir)
16678 "Find Org node headline HEADING in all .org files in directory DIR.
16679 When the target headline is found, return a marker to this location."
16680 (let ((files (directory-files (or dir default-directory)
16681 t "\\`[^.#].*\\.org\\'"))
16682 visiting m buffer)
16683 (catch 'found
16684 (dolist (file files)
16685 (message "trying %s" file)
16686 (setq visiting (org-find-base-buffer-visiting file))
16687 (setq buffer (or visiting (find-file-noselect file)))
16688 (setq m (org-find-exact-headline-in-buffer
16689 heading buffer))
16690 (when (and (not m) (not visiting)) (kill-buffer buffer))
16691 (and m (throw 'found m))))))
16693 (defun org-find-entry-with-id (ident)
16694 "Locate the entry that contains the ID property with exact value IDENT.
16695 IDENT can be a string, a symbol or a number, this function will search for
16696 the string representation of it.
16697 Return the position where this entry starts, or nil if there is no such entry."
16698 (interactive "sID: ")
16699 (let ((id (cond
16700 ((stringp ident) ident)
16701 ((symbolp ident) (symbol-name ident))
16702 ((numberp ident) (number-to-string ident))
16703 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16704 (org-with-wide-buffer (org-find-property "ID" id))))
16706 ;;;; Timestamps
16708 (defvar org-last-changed-timestamp nil)
16709 (defvar org-last-inserted-timestamp nil
16710 "The last time stamp inserted with `org-insert-time-stamp'.")
16711 (defvar org-ts-what) ; dynamically scoped parameter
16713 (defun org-time-stamp (arg &optional inactive)
16714 "Prompt for a date/time and insert a time stamp.
16716 If the user specifies a time like HH:MM or if this command is
16717 called with at least one prefix argument, the time stamp contains
16718 the date and the time. Otherwise, only the date is included.
16720 All parts of a date not specified by the user are filled in from
16721 the timestamp at point, if any, or the current date/time
16722 otherwise.
16724 If there is already a timestamp at the cursor, it is replaced.
16726 With two universal prefix arguments, insert an active timestamp
16727 with the current time without prompting the user.
16729 When called from lisp, the timestamp is inactive if INACTIVE is
16730 non-nil."
16731 (interactive "P")
16732 (let* ((ts (cond
16733 ((org-at-date-range-p t)
16734 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16735 ((org-at-timestamp-p t) (match-string 0))))
16736 ;; Default time is either the timestamp at point or today.
16737 ;; When entering a range, only the range start is considered.
16738 (default-time (if (not ts) (current-time)
16739 (apply #'encode-time (org-parse-time-string ts))))
16740 (default-input (and ts (org-get-compact-tod ts)))
16741 (repeater (and ts
16742 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16743 (match-string 0 ts)))
16744 org-time-was-given
16745 org-end-time-was-given
16746 (time
16747 (and (if (equal arg '(16)) (current-time)
16748 ;; Preserve `this-command' and `last-command'.
16749 (let ((this-command this-command)
16750 (last-command last-command))
16751 (org-read-date
16752 arg 'totime nil nil default-time default-input
16753 inactive))))))
16754 (cond
16755 ((and ts
16756 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16757 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16758 (insert "--")
16759 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16761 ;; Make sure we're on a timestamp. When in the middle of a date
16762 ;; range, move arbitrarily to range end.
16763 (unless (org-at-timestamp-p t)
16764 (skip-chars-forward "-")
16765 (org-at-timestamp-p t))
16766 (replace-match "")
16767 (setq org-last-changed-timestamp
16768 (org-insert-time-stamp
16769 time (or org-time-was-given arg)
16770 inactive nil nil (list org-end-time-was-given)))
16771 (when repeater
16772 (backward-char)
16773 (insert " " repeater)
16774 (setq org-last-changed-timestamp
16775 (concat (substring org-last-inserted-timestamp 0 -1)
16776 " " repeater ">")))
16777 (message "Timestamp updated"))
16778 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16779 (t (org-insert-time-stamp
16780 time (or org-time-was-given arg) inactive nil nil
16781 (list org-end-time-was-given))))))
16783 ;; FIXME: can we use this for something else, like computing time differences?
16784 (defun org-get-compact-tod (s)
16785 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16786 (let* ((t1 (match-string 1 s))
16787 (h1 (string-to-number (match-string 2 s)))
16788 (m1 (string-to-number (match-string 3 s)))
16789 (t2 (and (match-end 4) (match-string 5 s)))
16790 (h2 (and t2 (string-to-number (match-string 6 s))))
16791 (m2 (and t2 (string-to-number (match-string 7 s))))
16792 dh dm)
16793 (if (not t2)
16795 (setq dh (- h2 h1) dm (- m2 m1))
16796 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16797 (concat t1 "+" (number-to-string dh)
16798 (and (/= 0 dm) (format ":%02d" dm)))))))
16800 (defun org-time-stamp-inactive (&optional arg)
16801 "Insert an inactive time stamp.
16802 An inactive time stamp is enclosed in square brackets instead of angle
16803 brackets. It is inactive in the sense that it does not trigger agenda entries,
16804 does not link to the calendar and cannot be changed with the S-cursor keys.
16805 So these are more for recording a certain time/date."
16806 (interactive "P")
16807 (org-time-stamp arg 'inactive))
16809 (defvar org-date-ovl (make-overlay 1 1))
16810 (overlay-put org-date-ovl 'face 'org-date-selected)
16811 (delete-overlay org-date-ovl)
16813 (defvar org-ans1) ; dynamically scoped parameter
16814 (defvar org-ans2) ; dynamically scoped parameter
16816 (defvar org-plain-time-of-day-regexp) ; defined below
16818 (defvar org-overriding-default-time nil) ; dynamically scoped
16819 (defvar org-read-date-overlay nil)
16820 (defvar org-dcst nil) ; dynamically scoped
16821 (defvar org-read-date-history nil)
16822 (defvar org-read-date-final-answer nil)
16823 (defvar org-read-date-analyze-futurep nil)
16824 (defvar org-read-date-analyze-forced-year nil)
16825 (defvar org-read-date-inactive)
16827 (defvar org-read-date-minibuffer-local-map
16828 (let* ((map (make-sparse-keymap)))
16829 (set-keymap-parent map minibuffer-local-map)
16830 (org-defkey map (kbd ".")
16831 (lambda () (interactive)
16832 ;; Are we at the beginning of the prompt?
16833 (if (looking-back "^[^:]+: "
16834 (let ((inhibit-field-text-motion t))
16835 (line-beginning-position)))
16836 (org-eval-in-calendar '(calendar-goto-today))
16837 (insert "."))))
16838 (org-defkey map (kbd "C-.")
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-goto-today))))
16841 (org-defkey map [(meta shift left)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-backward-month 1))))
16844 (org-defkey map [(meta shift right)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-forward-month 1))))
16847 (org-defkey map [(meta shift up)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-backward-year 1))))
16850 (org-defkey map [(meta shift down)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-forward-year 1))))
16853 (org-defkey map [?\e (shift left)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-backward-month 1))))
16856 (org-defkey map [?\e (shift right)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-forward-month 1))))
16859 (org-defkey map [?\e (shift up)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-backward-year 1))))
16862 (org-defkey map [?\e (shift down)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-forward-year 1))))
16865 (org-defkey map [(shift up)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-backward-week 1))))
16868 (org-defkey map [(shift down)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-forward-week 1))))
16871 (org-defkey map [(shift left)]
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-backward-day 1))))
16874 (org-defkey map [(shift right)]
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(calendar-forward-day 1))))
16877 (org-defkey map "!"
16878 (lambda () (interactive)
16879 (org-eval-in-calendar '(diary-view-entries))
16880 (message "")))
16881 (org-defkey map ">"
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-scroll-left 1))))
16884 (org-defkey map "<"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-scroll-right 1))))
16887 (org-defkey map "\C-v"
16888 (lambda () (interactive)
16889 (org-eval-in-calendar
16890 '(calendar-scroll-left-three-months 1))))
16891 (org-defkey map "\M-v"
16892 (lambda () (interactive)
16893 (org-eval-in-calendar
16894 '(calendar-scroll-right-three-months 1))))
16895 map)
16896 "Keymap for minibuffer commands when using `org-read-date'.")
16898 (defvar org-def)
16899 (defvar org-defdecode)
16900 (defvar org-with-time)
16902 (defvar calendar-setup) ; Dynamically scoped.
16903 (defun org-read-date (&optional with-time to-time from-string prompt
16904 default-time default-input inactive)
16905 "Read a date, possibly a time, and make things smooth for the user.
16906 The prompt will suggest to enter an ISO date, but you can also enter anything
16907 which will at least partially be understood by `parse-time-string'.
16908 Unrecognized parts of the date will default to the current day, month, year,
16909 hour and minute. If this command is called to replace a timestamp at point,
16910 or to enter the second timestamp of a range, the default time is taken
16911 from the existing stamp. Furthermore, the command prefers the future,
16912 so if you are giving a date where the year is not given, and the day-month
16913 combination is already past in the current year, it will assume you
16914 mean next year. For details, see the manual. A few examples:
16916 3-2-5 --> 2003-02-05
16917 feb 15 --> currentyear-02-15
16918 2/15 --> currentyear-02-15
16919 sep 12 9 --> 2009-09-12
16920 12:45 --> today 12:45
16921 22 sept 0:34 --> currentyear-09-22 0:34
16922 12 --> currentyear-currentmonth-12
16923 Fri --> nearest Friday after today
16924 -Tue --> last Tuesday
16925 etc.
16927 Furthermore you can specify a relative date by giving, as the *first* thing
16928 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16929 change in days weeks, months, years.
16930 With a single plus or minus, the date is relative to today. With a double
16931 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16932 +4d --> four days from today
16933 +4 --> same as above
16934 +2w --> two weeks from today
16935 ++5 --> five days from default date
16937 The function understands only English month and weekday abbreviations.
16939 While prompting, a calendar is popped up - you can also select the
16940 date with the mouse (button 1). The calendar shows a period of three
16941 months. To scroll it to other months, use the keys `>' and `<'.
16942 If you don't like the calendar, turn it off with
16943 (setq org-read-date-popup-calendar nil)
16945 With optional argument TO-TIME, the date will immediately be converted
16946 to an internal time.
16947 With an optional argument WITH-TIME, the prompt will suggest to
16948 also insert a time. Note that when WITH-TIME is not set, you can
16949 still enter a time, and this function will inform the calling routine
16950 about this change. The calling routine may then choose to change the
16951 format used to insert the time stamp into the buffer to include the time.
16952 With optional argument FROM-STRING, read from this string instead from
16953 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16954 the time/date that is used for everything that is not specified by the
16955 user."
16956 (require 'parse-time)
16957 (let* ((org-with-time with-time)
16958 (org-time-stamp-rounding-minutes
16959 (if (equal org-with-time '(16))
16960 '(0 0)
16961 org-time-stamp-rounding-minutes))
16962 (org-dcst org-display-custom-times)
16963 (ct (org-current-time))
16964 (org-def (or org-overriding-default-time default-time ct))
16965 (org-defdecode (decode-time org-def))
16966 (cur-frame (selected-frame))
16967 (mouse-autoselect-window nil) ; Don't let the mouse jump
16968 (calendar-setup
16969 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16970 (calendar-move-hook nil)
16971 (calendar-view-diary-initially-flag nil)
16972 (calendar-view-holidays-initially-flag nil)
16973 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16974 ;; Rationalize `org-def' and `org-defdecode', if required.
16975 (when (< (nth 2 org-defdecode) org-extend-today-until)
16976 (setf (nth 2 org-defdecode) -1)
16977 (setf (nth 1 org-defdecode) 59)
16978 (setq org-def (apply #'encode-time org-defdecode))
16979 (setq org-defdecode (decode-time org-def)))
16980 (let* ((timestr (format-time-string
16981 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16982 org-def))
16983 (prompt (concat (if prompt (concat prompt " ") "")
16984 (format "Date+time [%s]: " timestr))))
16985 (cond
16986 (from-string (setq ans from-string))
16987 (org-read-date-popup-calendar
16988 (save-excursion
16989 (save-window-excursion
16990 (calendar)
16991 (when (eq calendar-setup 'calendar-only)
16992 (setq cal-frame
16993 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16994 (select-frame cal-frame))
16995 (org-eval-in-calendar '(setq cursor-type nil) t)
16996 (unwind-protect
16997 (progn
16998 (calendar-forward-day (- (time-to-days org-def)
16999 (calendar-absolute-from-gregorian
17000 (calendar-current-date))))
17001 (org-eval-in-calendar nil t)
17002 (let* ((old-map (current-local-map))
17003 (map (copy-keymap calendar-mode-map))
17004 (minibuffer-local-map
17005 (copy-keymap org-read-date-minibuffer-local-map)))
17006 (org-defkey map (kbd "RET") 'org-calendar-select)
17007 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17008 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17009 (unwind-protect
17010 (progn
17011 (use-local-map map)
17012 (setq org-read-date-inactive inactive)
17013 (add-hook 'post-command-hook 'org-read-date-display)
17014 (setq org-ans0
17015 (read-string prompt
17016 default-input
17017 'org-read-date-history
17018 nil))
17019 ;; org-ans0: from prompt
17020 ;; org-ans1: from mouse click
17021 ;; org-ans2: from calendar motion
17022 (setq ans
17023 (concat org-ans0 " " (or org-ans1 org-ans2))))
17024 (remove-hook 'post-command-hook 'org-read-date-display)
17025 (use-local-map old-map)
17026 (when org-read-date-overlay
17027 (delete-overlay org-read-date-overlay)
17028 (setq org-read-date-overlay nil)))))
17029 (bury-buffer "*Calendar*")
17030 (when cal-frame
17031 (delete-frame cal-frame)
17032 (select-frame-set-input-focus cur-frame))))))
17034 (t ; Naked prompt only
17035 (unwind-protect
17036 (setq ans (read-string prompt default-input
17037 'org-read-date-history timestr))
17038 (when org-read-date-overlay
17039 (delete-overlay org-read-date-overlay)
17040 (setq org-read-date-overlay nil))))))
17042 (setq final (org-read-date-analyze ans org-def org-defdecode))
17044 (when org-read-date-analyze-forced-year
17045 (message "Year was forced into %s"
17046 (if org-read-date-force-compatible-dates
17047 "compatible range (1970-2037)"
17048 "range representable on this machine"))
17049 (ding))
17051 ;; One round trip to get rid of 34th of August and stuff like that....
17052 (setq final (decode-time (apply 'encode-time final)))
17054 (setq org-read-date-final-answer ans)
17056 (if to-time
17057 (apply 'encode-time final)
17058 (if (and (boundp 'org-time-was-given) org-time-was-given)
17059 (format "%04d-%02d-%02d %02d:%02d"
17060 (nth 5 final) (nth 4 final) (nth 3 final)
17061 (nth 2 final) (nth 1 final))
17062 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17064 (defun org-read-date-display ()
17065 "Display the current date prompt interpretation in the minibuffer."
17066 (when org-read-date-display-live
17067 (when org-read-date-overlay
17068 (delete-overlay org-read-date-overlay))
17069 (when (minibufferp (current-buffer))
17070 (save-excursion
17071 (end-of-line 1)
17072 (while (not (equal (buffer-substring
17073 (max (point-min) (- (point) 4)) (point))
17074 " "))
17075 (insert " ")))
17076 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17077 " " (or org-ans1 org-ans2)))
17078 (org-end-time-was-given nil)
17079 (f (org-read-date-analyze ans org-def org-defdecode))
17080 (fmts (if org-dcst
17081 org-time-stamp-custom-formats
17082 org-time-stamp-formats))
17083 (fmt (if (or org-with-time
17084 (and (boundp 'org-time-was-given) org-time-was-given))
17085 (cdr fmts)
17086 (car fmts)))
17087 (txt (format-time-string fmt (apply 'encode-time f)))
17088 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17089 (txt (concat "=> " txt)))
17090 (when (and org-end-time-was-given
17091 (string-match org-plain-time-of-day-regexp txt))
17092 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17093 org-end-time-was-given
17094 (substring txt (match-end 0)))))
17095 (when org-read-date-analyze-futurep
17096 (setq txt (concat txt " (=>F)")))
17097 (setq org-read-date-overlay
17098 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17099 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17101 (defun org-read-date-analyze (ans def defdecode)
17102 "Analyze the combined answer of the date prompt."
17103 ;; FIXME: cleanup and comment
17104 ;; Pass `current-time' result to `decode-time' (instead of calling
17105 ;; without arguments) so that only `current-time' has to be
17106 ;; overriden in tests.
17107 (let ((org-def def)
17108 (org-defdecode defdecode)
17109 (nowdecode (decode-time (current-time)))
17110 delta deltan deltaw deltadef year month day
17111 hour minute second wday pm h2 m2 tl wday1
17112 iso-year iso-weekday iso-week iso-date futurep kill-year)
17113 (setq org-read-date-analyze-futurep nil
17114 org-read-date-analyze-forced-year nil)
17115 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17116 (setq ans "+0"))
17118 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17119 (setq ans (replace-match "" t t ans)
17120 deltan (car delta)
17121 deltaw (nth 1 delta)
17122 deltadef (nth 2 delta)))
17124 ;; Check if there is an iso week date in there. If yes, store the
17125 ;; info and postpone interpreting it until the rest of the parsing
17126 ;; is done.
17127 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17128 (setq iso-year (when (match-end 1)
17129 (org-small-year-to-year
17130 (string-to-number (match-string 1 ans))))
17131 iso-weekday (when (match-end 3)
17132 (string-to-number (match-string 3 ans)))
17133 iso-week (string-to-number (match-string 2 ans)))
17134 (setq ans (replace-match "" t t ans)))
17136 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17137 (when (string-match
17138 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17139 (setq year (if (match-end 2)
17140 (string-to-number (match-string 2 ans))
17141 (progn (setq kill-year t)
17142 (string-to-number (format-time-string "%Y"))))
17143 month (string-to-number (match-string 3 ans))
17144 day (string-to-number (match-string 4 ans)))
17145 (setq year (org-small-year-to-year year))
17146 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17147 t nil ans)))
17149 ;; Help matching dotted european dates
17150 (when (string-match
17151 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17152 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17153 (setq kill-year t)
17154 (string-to-number (format-time-string "%Y")))
17155 day (string-to-number (match-string 1 ans))
17156 month (string-to-number (match-string 2 ans))
17157 ans (replace-match (format "%04d-%02d-%02d" year month day)
17158 t nil ans)))
17160 ;; Help matching american dates, like 5/30 or 5/30/7
17161 (when (string-match
17162 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17163 (setq year (if (match-end 4)
17164 (string-to-number (match-string 4 ans))
17165 (progn (setq kill-year t)
17166 (string-to-number (format-time-string "%Y"))))
17167 month (string-to-number (match-string 1 ans))
17168 day (string-to-number (match-string 2 ans)))
17169 (setq year (org-small-year-to-year year))
17170 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17171 t nil ans)))
17172 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17173 ;; If there is a time with am/pm, and *no* time without it, we convert
17174 ;; so that matching will be successful.
17175 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17176 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17177 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17178 (setq hour (string-to-number (match-string 1 ans))
17179 minute (if (match-end 3)
17180 (string-to-number (match-string 3 ans))
17182 pm (equal ?p
17183 (string-to-char (downcase (match-string 4 ans)))))
17184 (if (and (= hour 12) (not pm))
17185 (setq hour 0)
17186 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17187 (setq ans (replace-match (format "%02d:%02d" hour minute)
17188 t t ans))))
17190 ;; Check if a time range is given as a duration
17191 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17192 (setq hour (string-to-number (match-string 1 ans))
17193 h2 (+ hour (string-to-number (match-string 3 ans)))
17194 minute (string-to-number (match-string 2 ans))
17195 m2 (+ minute (if (match-end 5) (string-to-number
17196 (match-string 5 ans))0)))
17197 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17198 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17199 t t ans)))
17201 ;; Check if there is a time range
17202 (when (boundp 'org-end-time-was-given)
17203 (setq org-time-was-given nil)
17204 (when (and (string-match org-plain-time-of-day-regexp ans)
17205 (match-end 8))
17206 (setq org-end-time-was-given (match-string 8 ans))
17207 (setq ans (concat (substring ans 0 (match-beginning 7))
17208 (substring ans (match-end 7))))))
17210 (setq tl (parse-time-string ans)
17211 day (or (nth 3 tl) (nth 3 org-defdecode))
17212 month
17213 (cond ((nth 4 tl))
17214 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17215 ;; Day was specified. Make sure DAY+MONTH
17216 ;; combination happens in the future.
17217 ((nth 3 tl)
17218 (setq futurep t)
17219 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17220 (nth 4 nowdecode)))
17221 (t (nth 4 org-defdecode)))
17222 year
17223 (cond ((and (not kill-year) (nth 5 tl)))
17224 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17225 ;; Month was guessed in the future and is at least
17226 ;; equal to NOWDECODE's. Fix year accordingly.
17227 (futurep
17228 (if (or (> month (nth 4 nowdecode))
17229 (>= day (nth 3 nowdecode)))
17230 (nth 5 nowdecode)
17231 (1+ (nth 5 nowdecode))))
17232 ;; Month was specified. Make sure MONTH+YEAR
17233 ;; combination happens in the future.
17234 ((nth 4 tl)
17235 (setq futurep t)
17236 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17237 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17238 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17239 (t (nth 5 nowdecode))))
17240 (t (nth 5 org-defdecode)))
17241 hour (or (nth 2 tl) (nth 2 org-defdecode))
17242 minute (or (nth 1 tl) (nth 1 org-defdecode))
17243 second (or (nth 0 tl) 0)
17244 wday (nth 6 tl))
17246 (when (and (eq org-read-date-prefer-future 'time)
17247 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17248 (equal day (nth 3 nowdecode))
17249 (equal month (nth 4 nowdecode))
17250 (equal year (nth 5 nowdecode))
17251 (nth 2 tl)
17252 (or (< (nth 2 tl) (nth 2 nowdecode))
17253 (and (= (nth 2 tl) (nth 2 nowdecode))
17254 (nth 1 tl)
17255 (< (nth 1 tl) (nth 1 nowdecode)))))
17256 (setq day (1+ day)
17257 futurep t))
17259 ;; Special date definitions below
17260 (cond
17261 (iso-week
17262 ;; There was an iso week
17263 (require 'cal-iso)
17264 (setq futurep nil)
17265 (setq year (or iso-year year)
17266 day (or iso-weekday wday 1)
17267 wday nil ; to make sure that the trigger below does not match
17268 iso-date (calendar-gregorian-from-absolute
17269 (calendar-iso-to-absolute
17270 (list iso-week day year))))
17271 ; FIXME: Should we also push ISO weeks into the future?
17272 ; (when (and org-read-date-prefer-future
17273 ; (not iso-year)
17274 ; (< (calendar-absolute-from-gregorian iso-date)
17275 ; (time-to-days (current-time))))
17276 ; (setq year (1+ year)
17277 ; iso-date (calendar-gregorian-from-absolute
17278 ; (calendar-iso-to-absolute
17279 ; (list iso-week day year)))))
17280 (setq month (car iso-date)
17281 year (nth 2 iso-date)
17282 day (nth 1 iso-date)))
17283 (deltan
17284 (setq futurep nil)
17285 (unless deltadef
17286 ;; Pass `current-time' result to `decode-time' (instead of
17287 ;; calling without arguments) so that only `current-time' has
17288 ;; to be overriden in tests.
17289 (let ((now (decode-time (current-time))))
17290 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17291 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17292 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17293 ((equal deltaw "m") (setq month (+ month deltan)))
17294 ((equal deltaw "y") (setq year (+ year deltan)))))
17295 ((and wday (not (nth 3 tl)))
17296 ;; Weekday was given, but no day, so pick that day in the week
17297 ;; on or after the derived date.
17298 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17299 (unless (equal wday wday1)
17300 (setq day (+ day (% (- wday wday1 -7) 7))))))
17301 (when (and (boundp 'org-time-was-given)
17302 (nth 2 tl))
17303 (setq org-time-was-given t))
17304 (when (< year 100) (setq year (+ 2000 year)))
17305 ;; Check of the date is representable
17306 (if org-read-date-force-compatible-dates
17307 (progn
17308 (when (< year 1970)
17309 (setq year 1970 org-read-date-analyze-forced-year t))
17310 (when (> year 2037)
17311 (setq year 2037 org-read-date-analyze-forced-year t)))
17312 (condition-case nil
17313 (ignore (encode-time second minute hour day month year))
17314 (error
17315 (setq year (nth 5 org-defdecode))
17316 (setq org-read-date-analyze-forced-year t))))
17317 (setq org-read-date-analyze-futurep futurep)
17318 (list second minute hour day month year)))
17320 (defvar parse-time-weekdays)
17321 (defun org-read-date-get-relative (s today default)
17322 "Check string S for special relative date string.
17323 TODAY and DEFAULT are internal times, for today and for a default.
17324 Return shift list (N what def-flag)
17325 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17326 N is the number of WHATs to shift.
17327 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17328 the DEFAULT date rather than TODAY."
17329 (require 'parse-time)
17330 (when (and
17331 (string-match
17332 (concat
17333 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17334 "\\([0-9]+\\)?"
17335 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17336 "\\([ \t]\\|$\\)") s)
17337 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17338 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17339 (string-to-char (substring (match-string 1 s) -1))
17340 ?+))
17341 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17342 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17343 (what (if (match-end 3) (match-string 3 s) "d"))
17344 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17345 (date (if rel default today))
17346 (wday (nth 6 (decode-time date)))
17347 delta)
17348 (if wday1
17349 (progn
17350 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17351 (when (= delta 0) (setq delta 7))
17352 (when (= dir ?-)
17353 (setq delta (- delta 7))
17354 (when (= delta 0) (setq delta -7)))
17355 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17356 (list delta "d" rel))
17357 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17359 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17360 "Turn a user-specified date into the internal representation.
17361 The internal representation needed by the calendar is (month day year).
17362 This is a wrapper to handle the brain-dead convention in calendar that
17363 user function argument order change dependent on argument order."
17364 (pcase calendar-date-style
17365 (`american (list arg1 arg2 arg3))
17366 (`european (list arg2 arg1 arg3))
17367 (`iso (list arg2 arg3 arg1))))
17369 (defun org-eval-in-calendar (form &optional keepdate)
17370 "Eval FORM in the calendar window and return to current window.
17371 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17372 (let ((sf (selected-frame))
17373 (sw (selected-window)))
17374 (select-window (get-buffer-window "*Calendar*" t))
17375 (eval form)
17376 (when (and (not keepdate) (calendar-cursor-to-date))
17377 (let* ((date (calendar-cursor-to-date))
17378 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17379 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17380 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17381 (select-window sw)
17382 (select-frame-set-input-focus sf)))
17384 (defun org-calendar-select ()
17385 "Return to `org-read-date' with the date currently selected.
17386 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17387 (interactive)
17388 (when (calendar-cursor-to-date)
17389 (let* ((date (calendar-cursor-to-date))
17390 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17391 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17392 (when (active-minibuffer-window) (exit-minibuffer))))
17394 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17395 "Insert a date stamp for the date given by the internal TIME.
17396 See `format-time-string' for the format of TIME.
17397 WITH-HM means use the stamp format that includes the time of the day.
17398 INACTIVE means use square brackets instead of angular ones, so that the
17399 stamp will not contribute to the agenda.
17400 PRE and POST are optional strings to be inserted before and after the
17401 stamp.
17402 The command returns the inserted time stamp."
17403 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17404 stamp)
17405 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17406 (insert-before-markers (or pre ""))
17407 (when (listp extra)
17408 (setq extra (car extra))
17409 (if (and (stringp extra)
17410 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17411 (setq extra (format "-%02d:%02d"
17412 (string-to-number (match-string 1 extra))
17413 (string-to-number (match-string 2 extra))))
17414 (setq extra nil)))
17415 (when extra
17416 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17417 (insert-before-markers (setq stamp (format-time-string fmt time)))
17418 (insert-before-markers (or post ""))
17419 (setq org-last-inserted-timestamp stamp)))
17421 (defun org-toggle-time-stamp-overlays ()
17422 "Toggle the use of custom time stamp formats."
17423 (interactive)
17424 (setq org-display-custom-times (not org-display-custom-times))
17425 (unless org-display-custom-times
17426 (let ((p (point-min)) (bmp (buffer-modified-p)))
17427 (while (setq p (next-single-property-change p 'display))
17428 (when (and (get-text-property p 'display)
17429 (eq (get-text-property p 'face) 'org-date))
17430 (remove-text-properties
17431 p (setq p (next-single-property-change p 'display))
17432 '(display t))))
17433 (set-buffer-modified-p bmp)))
17434 (org-restart-font-lock)
17435 (setq org-table-may-need-update t)
17436 (if org-display-custom-times
17437 (message "Time stamps are overlaid with custom format")
17438 (message "Time stamp overlays removed")))
17440 (defun org-display-custom-time (beg end)
17441 "Overlay modified time stamp format over timestamp between BEG and END."
17442 (let* ((ts (buffer-substring beg end))
17443 t1 w1 with-hm tf time str w2 (off 0))
17444 (save-match-data
17445 (setq t1 (org-parse-time-string ts t))
17446 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17447 (setq off (- (match-end 0) (match-beginning 0)))))
17448 (setq end (- end off))
17449 (setq w1 (- end beg)
17450 with-hm (and (nth 1 t1) (nth 2 t1))
17451 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17452 time (org-fix-decoded-time t1)
17453 str (org-add-props
17454 (format-time-string
17455 (substring tf 1 -1) (apply 'encode-time time))
17456 nil 'mouse-face 'highlight)
17457 w2 (length str))
17458 (unless (= w2 w1)
17459 (add-text-properties (1+ beg) (+ 2 beg)
17460 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17461 (put-text-property beg end 'display str)))
17463 (defun org-fix-decoded-time (time)
17464 "Set 0 instead of nil for the first 6 elements of time.
17465 Don't touch the rest."
17466 (let ((n 0))
17467 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17469 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17470 "Difference between TIMESTAMP-STRING and now in days.
17471 If SECONDS is non-nil, return the difference in seconds."
17472 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17473 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17474 (funcall fdiff (current-time)))))
17476 (defun org-deadline-close-p (timestamp-string &optional ndays)
17477 "Is the time in TIMESTAMP-STRING close to the current date?"
17478 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17479 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17480 (not (org-entry-is-done-p))))
17482 (defun org-get-wdays (ts &optional delay zero-delay)
17483 "Get the deadline lead time appropriate for timestring TS.
17484 When DELAY is non-nil, get the delay time for scheduled items
17485 instead of the deadline lead time. When ZERO-DELAY is non-nil
17486 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17487 don't try to find the delay cookie in the scheduled timestamp."
17488 (let ((tv (if delay org-scheduled-delay-days
17489 org-deadline-warning-days)))
17490 (cond
17491 ((or (and delay (< tv 0))
17492 (and delay zero-delay (<= tv 0))
17493 (and (not delay) (<= tv 0)))
17494 ;; Enforce this value no matter what
17495 (- tv))
17496 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17497 ;; lead time is specified.
17498 (floor (* (string-to-number (match-string 1 ts))
17499 (cdr (assoc (match-string 2 ts)
17500 '(("d" . 1) ("w" . 7)
17501 ("m" . 30.4) ("y" . 365.25)
17502 ("h" . 0.041667)))))))
17503 ;; go for the default.
17504 (t tv))))
17506 (defun org-calendar-select-mouse (ev)
17507 "Return to `org-read-date' with the date currently selected.
17508 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17509 (interactive "e")
17510 (mouse-set-point ev)
17511 (when (calendar-cursor-to-date)
17512 (let* ((date (calendar-cursor-to-date))
17513 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17514 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17515 (when (active-minibuffer-window) (exit-minibuffer))))
17517 (defun org-check-deadlines (ndays)
17518 "Check if there are any deadlines due or past due.
17519 A deadline is considered due if it happens within `org-deadline-warning-days'
17520 days from today's date. If the deadline appears in an entry marked DONE,
17521 it is not shown. A numeric prefix argument NDAYS can be used to test that
17522 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17523 are shown."
17524 (interactive "P")
17525 (let* ((org-warn-days
17526 (cond
17527 ((equal ndays '(4)) 100000)
17528 (ndays (prefix-numeric-value ndays))
17529 (t (abs org-deadline-warning-days))))
17530 (case-fold-search nil)
17531 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17532 (callback
17533 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17534 (message "%d deadlines past-due or due within %d days"
17535 (org-occur regexp nil callback)
17536 org-warn-days)))
17538 (defsubst org-re-timestamp (type)
17539 "Return a regexp for timestamp TYPE.
17540 Allowed values for TYPE are:
17542 all: all timestamps
17543 active: only active timestamps (<...>)
17544 inactive: only inactive timestamps ([...])
17545 scheduled: only scheduled timestamps
17546 deadline: only deadline timestamps
17547 closed: only closed time-stamps
17549 When TYPE is nil, fall back on returning a regexp that matches
17550 both scheduled and deadline timestamps."
17551 (cl-case type
17552 (all org-ts-regexp-both)
17553 (active org-ts-regexp)
17554 (inactive org-ts-regexp-inactive)
17555 (scheduled org-scheduled-time-regexp)
17556 (deadline org-deadline-time-regexp)
17557 (closed org-closed-time-regexp)
17558 (otherwise
17559 (concat "\\<"
17560 (regexp-opt (list org-deadline-string org-scheduled-string))
17561 " *<\\([^>]+\\)>"))))
17563 (defun org-check-before-date (d)
17564 "Check if there are deadlines or scheduled entries before date D."
17565 (interactive (list (org-read-date)))
17566 (let* ((case-fold-search nil)
17567 (regexp (org-re-timestamp org-ts-type))
17568 (ts-type org-ts-type)
17569 (callback
17570 (lambda ()
17571 (let ((match (match-string 1)))
17572 (and (if (memq ts-type '(active inactive all))
17573 (eq (org-element-type (save-excursion
17574 (backward-char)
17575 (org-element-context)))
17576 'timestamp)
17577 (org-at-planning-p))
17578 (time-less-p
17579 (org-time-string-to-time match)
17580 (org-time-string-to-time d)))))))
17581 (message "%d entries before %s"
17582 (org-occur regexp nil callback)
17583 d)))
17585 (defun org-check-after-date (d)
17586 "Check if there are deadlines or scheduled entries after date D."
17587 (interactive (list (org-read-date)))
17588 (let* ((case-fold-search nil)
17589 (regexp (org-re-timestamp org-ts-type))
17590 (ts-type org-ts-type)
17591 (callback
17592 (lambda ()
17593 (let ((match (match-string 1)))
17594 (and (if (memq ts-type '(active inactive all))
17595 (eq (org-element-type (save-excursion
17596 (backward-char)
17597 (org-element-context)))
17598 'timestamp)
17599 (org-at-planning-p))
17600 (not (time-less-p
17601 (org-time-string-to-time match)
17602 (org-time-string-to-time d))))))))
17603 (message "%d entries after %s"
17604 (org-occur regexp nil callback)
17605 d)))
17607 (defun org-check-dates-range (start-date end-date)
17608 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17609 (interactive (list (org-read-date nil nil nil "Range starts")
17610 (org-read-date nil nil nil "Range end")))
17611 (let ((case-fold-search nil)
17612 (regexp (org-re-timestamp org-ts-type))
17613 (callback
17614 (let ((type org-ts-type))
17615 (lambda ()
17616 (let ((match (match-string 1)))
17617 (and
17618 (if (memq type '(active inactive all))
17619 (eq (org-element-type (save-excursion
17620 (backward-char)
17621 (org-element-context)))
17622 'timestamp)
17623 (org-at-planning-p))
17624 (not (time-less-p
17625 (org-time-string-to-time match)
17626 (org-time-string-to-time start-date)))
17627 (time-less-p
17628 (org-time-string-to-time match)
17629 (org-time-string-to-time end-date))))))))
17630 (message "%d entries between %s and %s"
17631 (org-occur regexp nil callback) start-date end-date)))
17633 (defun org-evaluate-time-range (&optional to-buffer)
17634 "Evaluate a time range by computing the difference between start and end.
17635 Normally the result is just printed in the echo area, but with prefix arg
17636 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17637 If the time range is actually in a table, the result is inserted into the
17638 next column.
17639 For time difference computation, a year is assumed to be exactly 365
17640 days in order to avoid rounding problems."
17641 (interactive "P")
17643 (org-clock-update-time-maybe)
17644 (save-excursion
17645 (unless (org-at-date-range-p t)
17646 (goto-char (point-at-bol))
17647 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17648 (unless (org-at-date-range-p t)
17649 (user-error "Not at a time-stamp range, and none found in current line")))
17650 (let* ((ts1 (match-string 1))
17651 (ts2 (match-string 2))
17652 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17653 (match-end (match-end 0))
17654 (time1 (org-time-string-to-time ts1))
17655 (time2 (org-time-string-to-time ts2))
17656 (t1 (float-time time1))
17657 (t2 (float-time time2))
17658 (diff (abs (- t2 t1)))
17659 (negative (< (- t2 t1) 0))
17660 ;; (ys (floor (* 365 24 60 60)))
17661 (ds (* 24 60 60))
17662 (hs (* 60 60))
17663 (fy "%dy %dd %02d:%02d")
17664 (fy1 "%dy %dd")
17665 (fd "%dd %02d:%02d")
17666 (fd1 "%dd")
17667 (fh "%02d:%02d")
17668 y d h m align)
17669 (if havetime
17670 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17672 d (floor (/ diff ds)) diff (mod diff ds)
17673 h (floor (/ diff hs)) diff (mod diff hs)
17674 m (floor (/ diff 60)))
17675 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17677 d (floor (+ (/ diff ds) 0.5))
17678 h 0 m 0))
17679 (if (not to-buffer)
17680 (message "%s" (org-make-tdiff-string y d h m))
17681 (if (org-at-table-p)
17682 (progn
17683 (goto-char match-end)
17684 (setq align t)
17685 (and (looking-at " *|") (goto-char (match-end 0))))
17686 (goto-char match-end))
17687 (when (looking-at
17688 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17689 (replace-match ""))
17690 (when negative (insert " -"))
17691 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17692 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17693 (insert " " (format fh h m))))
17694 (when align (org-table-align))
17695 (message "Time difference inserted")))))
17697 (defun org-make-tdiff-string (y d h m)
17698 (let ((fmt "")
17699 (l nil))
17700 (when (> y 0)
17701 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17702 (push y l))
17703 (when (> d 0)
17704 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17705 (push d l))
17706 (when (> h 0)
17707 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17708 (push h l))
17709 (when (> m 0)
17710 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17711 (push m l))
17712 (apply 'format fmt (nreverse l))))
17714 (defun org-time-string-to-time (s &optional buffer pos)
17715 "Convert a timestamp string into internal time."
17716 (condition-case errdata
17717 (apply 'encode-time (org-parse-time-string s))
17718 (error (error "Bad timestamp `%s'%s\nError was: %s"
17719 s (if (not (and buffer pos))
17721 (format-message " at %d in buffer `%s'" pos buffer))
17722 (cdr errdata)))))
17724 (defun org-time-string-to-seconds (s)
17725 "Convert a timestamp string to a number of seconds."
17726 (float-time (org-time-string-to-time s)))
17728 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17730 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17731 "Convert time stamp S to an absolute day number.
17733 If DAYNR in non-nil, and there is a specifier for a cyclic time
17734 stamp, get the closest date to DAYNR. If PREFER is
17735 `past' (respectively `future') return a date past (respectively
17736 after) or equal to DAYNR.
17738 POS is the location of time stamp S, as a buffer position in
17739 BUFFER.
17741 Diary sexp timestamps are matched against DAYNR, when non-nil.
17742 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17743 signalled."
17744 (cond
17745 ((string-match "\\`%%\\((.*)\\)" s)
17746 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17747 ;; only able to match individual dates. If it fails, raise an
17748 ;; error.
17749 (if (and daynr
17750 (org-diary-sexp-entry
17751 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17752 daynr
17753 (signal 'org-diary-sexp-no-match (list s))))
17754 (daynr (org-closest-date s daynr prefer))
17755 (t (time-to-days
17756 (condition-case errdata
17757 (apply #'encode-time (org-parse-time-string s))
17758 (error (error "Bad timestamp `%s'%s\nError was: %s"
17760 (if (not (and buffer pos)) ""
17761 (format-message " at %d in buffer `%s'" pos buffer))
17762 (cdr errdata))))))))
17764 (defun org-days-to-iso-week (days)
17765 "Return the iso week number."
17766 (require 'cal-iso)
17767 (car (calendar-iso-from-absolute days)))
17769 (defun org-small-year-to-year (year)
17770 "Convert 2-digit years into 4-digit years.
17771 YEAR is expanded into one of the 30 next years, if possible, or
17772 into a past one. Any year larger than 99 is returned unchanged."
17773 (if (>= year 100) year
17774 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17775 (century (/ current 100))
17776 (offset (- year (% current 100))))
17777 (cond ((> offset 30) (+ (* (1- century) 100) year))
17778 ((> offset -70) (+ (* century 100) year))
17779 (t (+ (* (1+ century) 100) year))))))
17781 (defun org-time-from-absolute (d)
17782 "Return the time corresponding to date D.
17783 D may be an absolute day number, or a calendar-type list (month day year)."
17784 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17785 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17787 (defvar org-agenda-current-date)
17788 (defun org-calendar-holiday ()
17789 "List of holidays, for Diary display in Org mode."
17790 (require 'holidays)
17791 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17792 (and hl (mapconcat #'identity hl "; "))))
17794 (defun org-diary-sexp-entry (sexp entry d)
17795 "Process a SEXP diary ENTRY for date D."
17796 (require 'diary-lib)
17797 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17798 ;; dynamically.
17799 (let* ((sexp `(let ((entry ,entry)
17800 (date ',d))
17801 ,(car (read-from-string sexp))))
17802 (result (if calendar-debug-sexp (eval sexp)
17803 (condition-case nil
17804 (eval sexp)
17805 (error
17806 (beep)
17807 (message "Bad sexp at line %d in %s: %s"
17808 (org-current-line)
17809 (buffer-file-name) sexp)
17810 (sleep-for 2))))))
17811 (cond ((stringp result) (split-string result "; "))
17812 ((and (consp result)
17813 (not (consp (cdr result)))
17814 (stringp (cdr result))) (cdr result))
17815 ((and (consp result)
17816 (stringp (car result))) result)
17817 (result entry))))
17819 (defun org-diary-to-ical-string (frombuf)
17820 "Get iCalendar entries from diary entries in buffer FROMBUF.
17821 This uses the icalendar.el library."
17822 (let* ((tmpdir temporary-file-directory)
17823 (tmpfile (make-temp-name
17824 (expand-file-name "orgics" tmpdir)))
17825 buf rtn b e)
17826 (with-current-buffer frombuf
17827 (icalendar-export-region (point-min) (point-max) tmpfile)
17828 (setq buf (find-buffer-visiting tmpfile))
17829 (set-buffer buf)
17830 (goto-char (point-min))
17831 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17832 (setq b (match-beginning 0)))
17833 (goto-char (point-max))
17834 (when (re-search-backward "^END:VEVENT" nil t)
17835 (setq e (match-end 0)))
17836 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17837 (kill-buffer buf)
17838 (delete-file tmpfile)
17839 rtn))
17841 (defun org-closest-date (start current prefer)
17842 "Return closest date to CURRENT starting from START.
17844 CURRENT and START are both time stamps.
17846 When PREFER is `past', return a date that is either CURRENT or
17847 past. When PREFER is `future', return a date that is either
17848 CURRENT or future.
17850 Only time stamps with a repeater are modified. Any other time
17851 stamp stay unchanged. In any case, return value is an absolute
17852 day number."
17853 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17854 ;; No repeater. Do not shift time stamp.
17855 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17856 (let ((value (string-to-number (match-string 1 start)))
17857 (type (match-string 2 start)))
17858 (if (= 0 value)
17859 ;; Repeater with a 0-value is considered as void.
17860 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17861 (let* ((base (org-date-to-gregorian start))
17862 (target (org-date-to-gregorian current))
17863 (sday (calendar-absolute-from-gregorian base))
17864 (cday (calendar-absolute-from-gregorian target))
17865 n1 n2)
17866 ;; If START is already past CURRENT, just return START.
17867 (if (<= cday sday) sday
17868 ;; Compute closest date before (N1) and closest date past
17869 ;; (N2) CURRENT.
17870 (pcase type
17871 ("h"
17872 (let ((missing-hours
17873 (mod (+ (- (* 24 (- cday sday))
17874 (nth 2 (org-parse-time-string start)))
17875 org-extend-today-until)
17876 value)))
17877 (setf n1 (if (= missing-hours 0) cday
17878 (- cday (1+ (/ missing-hours 24)))))
17879 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17880 ((or "d" "w")
17881 (let ((value (if (equal type "w") (* 7 value) value)))
17882 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17883 (setf n2 (+ n1 value))))
17884 ("m"
17885 (let* ((add-months
17886 (lambda (d n)
17887 ;; Add N months to gregorian date D, i.e.,
17888 ;; a list (MONTH DAY YEAR). Return a valid
17889 ;; gregorian date.
17890 (let ((m (+ (nth 0 d) n)))
17891 (list (mod m 12)
17892 (nth 1 d)
17893 (+ (/ m 12) (nth 2 d))))))
17894 (months ; Complete months to TARGET.
17895 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17896 (- (nth 0 target) (nth 0 base))
17897 ;; If START's day is greater than
17898 ;; TARGET's, remove incomplete month.
17899 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17900 value)
17901 value))
17902 (before (funcall add-months base months)))
17903 (setf n1 (calendar-absolute-from-gregorian before))
17904 (setf n2
17905 (calendar-absolute-from-gregorian
17906 (funcall add-months before value)))))
17908 (let* ((d (nth 1 base))
17909 (m (nth 0 base))
17910 (y (nth 2 base))
17911 (years ; Complete years to TARGET.
17912 (* (/ (- (nth 2 target)
17914 ;; If START's month and day are
17915 ;; greater than TARGET's, remove
17916 ;; incomplete year.
17917 (if (or (> (nth 0 target) m)
17918 (and (= (nth 0 target) m)
17919 (> (nth 1 target) d)))
17922 value)
17923 value))
17924 (before (list m d (+ y years))))
17925 (setf n1 (calendar-absolute-from-gregorian before))
17926 (setf n2 (calendar-absolute-from-gregorian
17927 (list m d (+ (nth 2 before) value)))))))
17928 ;; Handle PREFER parameter, if any.
17929 (cond
17930 ((eq prefer 'past) (if (= cday n2) n2 n1))
17931 ((eq prefer 'future) (if (= cday n1) n1 n2))
17932 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17934 (defun org-date-to-gregorian (d)
17935 "Turn any specification of date D into a Gregorian date for the calendar."
17936 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17937 ((and (listp d) (= (length d) 3)) d)
17938 ((stringp d)
17939 (let ((d (org-parse-time-string d)))
17940 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17941 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17943 (defun org-parse-time-string (s &optional nodefault zone)
17944 "Parse the standard Org time string.
17946 This should be a lot faster than the normal `parse-time-string'.
17948 If time is not given, defaults to 0:00. However, with optional
17949 NODEFAULT, hour and minute fields will be nil if not given.
17951 The optional ZONE is omitted or nil for Emacs local time, t for
17952 Universal Time, ‘wall’ for system wall clock time, or a string as
17953 in the TZ environment variable."
17954 (cond ((string-match org-ts-regexp0 s)
17955 (list 0
17956 (when (or (match-beginning 8) (not nodefault))
17957 (string-to-number (or (match-string 8 s) "0")))
17958 (when (or (match-beginning 7) (not nodefault))
17959 (string-to-number (or (match-string 7 s) "0")))
17960 (string-to-number (match-string 4 s))
17961 (string-to-number (match-string 3 s))
17962 (string-to-number (match-string 2 s))
17963 nil nil zone))
17964 ((string-match "^<[^>]+>$" s)
17965 ;; FIXME: `decode-time' needs to be called with ZONE as its
17966 ;; second argument. However, this requires at least Emacs
17967 ;; 25.1. We can do it when we switch to this version as our
17968 ;; minimal requirement.
17969 (decode-time (seconds-to-time (org-matcher-time s))))
17970 (t (error "Not a standard Org time string: %s" s))))
17972 (defun org-timestamp-up (&optional arg)
17973 "Increase the date item at the cursor by one.
17974 If the cursor is on the year, change the year. If it is on the month,
17975 the day or the time, change that.
17976 With prefix ARG, change by that many units."
17977 (interactive "p")
17978 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17980 (defun org-timestamp-down (&optional arg)
17981 "Decrease the date item at the cursor by one.
17982 If the cursor is on the year, change the year. If it is on the month,
17983 the day or the time, change that.
17984 With prefix ARG, change by that many units."
17985 (interactive "p")
17986 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17988 (defun org-timestamp-up-day (&optional arg)
17989 "Increase the date in the time stamp by one day.
17990 With prefix ARG, change that many days."
17991 (interactive "p")
17992 (if (and (not (org-at-timestamp-p t))
17993 (org-at-heading-p))
17994 (org-todo 'up)
17995 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17997 (defun org-timestamp-down-day (&optional arg)
17998 "Decrease the date in the time stamp by one day.
17999 With prefix ARG, change that many days."
18000 (interactive "p")
18001 (if (and (not (org-at-timestamp-p t))
18002 (org-at-heading-p))
18003 (org-todo 'down)
18004 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18006 (defun org-at-timestamp-p (&optional inactive-ok)
18007 "Non-nil if point is inside a timestamp.
18009 When optional argument INACTIVE-OK is non-nil, also consider
18010 inactive timestamps.
18012 When this function returns a non-nil value, match data is set
18013 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18014 INACTIVE-OK."
18015 (interactive)
18016 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18017 (pos (point))
18018 (ans (or (looking-at tsr)
18019 (save-excursion
18020 (skip-chars-backward "^[<\n\r\t")
18021 (when (> (point) (point-min)) (backward-char 1))
18022 (and (looking-at tsr)
18023 (> (- (match-end 0) pos) -1))))))
18024 (and ans
18025 (boundp 'org-ts-what)
18026 (setq org-ts-what
18027 (cond
18028 ((= pos (match-beginning 0)) 'bracket)
18029 ;; Point is considered to be "on the bracket" whether
18030 ;; it's really on it or right after it.
18031 ((= pos (1- (match-end 0))) 'bracket)
18032 ((= pos (match-end 0)) 'after)
18033 ((org-pos-in-match-range pos 2) 'year)
18034 ((org-pos-in-match-range pos 3) 'month)
18035 ((org-pos-in-match-range pos 7) 'hour)
18036 ((org-pos-in-match-range pos 8) 'minute)
18037 ((or (org-pos-in-match-range pos 4)
18038 (org-pos-in-match-range pos 5)) 'day)
18039 ((and (> pos (or (match-end 8) (match-end 5)))
18040 (< pos (match-end 0)))
18041 (- pos (or (match-end 8) (match-end 5))))
18042 (t 'day))))
18043 ans))
18045 (defun org-toggle-timestamp-type ()
18046 "Toggle the type (<active> or [inactive]) of a time stamp."
18047 (interactive)
18048 (when (org-at-timestamp-p t)
18049 (let ((beg (match-beginning 0)) (end (match-end 0))
18050 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18051 (save-excursion
18052 (goto-char beg)
18053 (while (re-search-forward "[][<>]" end t)
18054 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18055 t t)))
18056 (message "Timestamp is now %sactive"
18057 (if (equal (char-after beg) ?<) "" "in")))))
18059 (defun org-at-clock-log-p nil
18060 "Is the cursor on the clock log line?"
18061 (save-excursion
18062 (beginning-of-line)
18063 (looking-at org-clock-line-re)))
18065 (defvar org-clock-history) ; defined in org-clock.el
18066 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18067 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18068 "Change the date in the time stamp at point.
18069 The date will be changed by N times WHAT. WHAT can be `day', `month',
18070 `year', `minute', `second'. If WHAT is not given, the cursor position
18071 in the timestamp determines what will be changed.
18072 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18073 (let ((origin (point)) origin-cat
18074 with-hm inactive
18075 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18076 org-ts-what
18077 extra rem
18078 ts time time0 fixnext clrgx)
18079 (unless (org-at-timestamp-p t)
18080 (user-error "Not at a timestamp"))
18081 (if (and (not what) (eq org-ts-what 'bracket))
18082 (org-toggle-timestamp-type)
18083 ;; Point isn't on brackets. Remember the part of the time-stamp
18084 ;; the point was in. Indeed, size of time-stamps may change,
18085 ;; but point must be kept in the same category nonetheless.
18086 (setq origin-cat org-ts-what)
18087 (when (and (not what) (not (eq org-ts-what 'day))
18088 org-display-custom-times
18089 (get-text-property (point) 'display)
18090 (not (get-text-property (1- (point)) 'display)))
18091 (setq org-ts-what 'day))
18092 (setq org-ts-what (or what org-ts-what)
18093 inactive (= (char-after (match-beginning 0)) ?\[)
18094 ts (match-string 0))
18095 (replace-match "")
18096 (when (string-match
18097 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18099 (setq extra (match-string 1 ts))
18100 (when suppress-tmp-delay
18101 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18102 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18103 (setq with-hm t))
18104 (setq time0 (org-parse-time-string ts))
18105 (when (and updown
18106 (eq org-ts-what 'minute)
18107 (not current-prefix-arg))
18108 ;; This looks like s-up and s-down. Change by one rounding step.
18109 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18110 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18111 (setcar (cdr time0) (+ (nth 1 time0)
18112 (if (> n 0) (- rem) (- dm rem))))))
18113 (setq time
18114 (apply #'encode-time
18115 (or (car time0) 0)
18116 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18117 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18118 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18119 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18120 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18121 (nthcdr 6 time0)))
18122 (when (and (member org-ts-what '(hour minute))
18123 extra
18124 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18125 (setq extra (org-modify-ts-extra
18126 extra
18127 (if (eq org-ts-what 'hour) 2 5)
18128 n dm)))
18129 (when (integerp org-ts-what)
18130 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18131 (when (eq what 'calendar)
18132 (let ((cal-date (org-get-date-from-calendar)))
18133 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18134 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18135 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18136 (setcar time0 (or (car time0) 0))
18137 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18138 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18139 (setq time (apply 'encode-time time0))))
18140 ;; Insert the new time-stamp, and ensure point stays in the same
18141 ;; category as before (i.e. not after the last position in that
18142 ;; category).
18143 (let ((pos (point)))
18144 ;; Stay before inserted string. `save-excursion' is of no use.
18145 (setq org-last-changed-timestamp
18146 (org-insert-time-stamp time with-hm inactive nil nil extra))
18147 (goto-char pos))
18148 (save-match-data
18149 (looking-at org-ts-regexp3)
18150 (goto-char
18151 (pcase origin-cat
18152 ;; `day' category ends before `hour' if any, or at the end
18153 ;; of the day name.
18154 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18155 (`hour (min (match-end 7) origin))
18156 (`minute (min (1- (match-end 8)) origin))
18157 ((pred integerp) (min (1- (match-end 0)) origin))
18158 ;; Point was right after the time-stamp. However, the
18159 ;; time-stamp length might have changed, so refer to
18160 ;; (match-end 0) instead.
18161 (`after (match-end 0))
18162 ;; `year' and `month' have both fixed size: point couldn't
18163 ;; have moved into another part.
18164 (_ origin))))
18165 ;; Update clock if on a CLOCK line.
18166 (org-clock-update-time-maybe)
18167 ;; Maybe adjust the closest clock in `org-clock-history'
18168 (when org-clock-adjust-closest
18169 (if (not (and (org-at-clock-log-p)
18170 (< 1 (length (delq nil (mapcar 'marker-position
18171 org-clock-history))))))
18172 (message "No clock to adjust")
18173 (cond ((save-excursion ; fix previous clock?
18174 (re-search-backward org-ts-regexp0 nil t)
18175 (looking-back (concat org-clock-string " \\[")
18176 (line-beginning-position)))
18177 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18178 ((save-excursion ; fix next clock?
18179 (re-search-backward org-ts-regexp0 nil t)
18180 (looking-at (concat org-ts-regexp0 "\\] =>")))
18181 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18182 (save-window-excursion
18183 ;; Find closest clock to point, adjust the previous/next one in history
18184 (let* ((p (save-excursion (org-back-to-heading t)))
18185 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18186 (clfixnth
18187 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18188 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18189 (if (not clfixpos)
18190 (message "No clock to adjust")
18191 (save-excursion
18192 (org-goto-marker-or-bmk clfixpos)
18193 (org-show-subtree)
18194 (when (re-search-forward clrgx nil t)
18195 (goto-char (match-beginning 1))
18196 (let (org-clock-adjust-closest)
18197 (org-timestamp-change n org-ts-what updown))
18198 (message "Clock adjusted in %s for heading: %s"
18199 (file-name-nondirectory (buffer-file-name))
18200 (org-get-heading t t)))))))))
18201 ;; Try to recenter the calendar window, if any.
18202 (when (and org-calendar-follow-timestamp-change
18203 (get-buffer-window "*Calendar*" t)
18204 (memq org-ts-what '(day month year)))
18205 (org-recenter-calendar (time-to-days time))))))
18207 (defun org-modify-ts-extra (s pos n dm)
18208 "Change the different parts of the lead-time and repeat fields in timestamp."
18209 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18210 ng h m new rem)
18211 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18212 (cond
18213 ((or (org-pos-in-match-range pos 2)
18214 (org-pos-in-match-range pos 3))
18215 (setq m (string-to-number (match-string 3 s))
18216 h (string-to-number (match-string 2 s)))
18217 (if (org-pos-in-match-range pos 2)
18218 (setq h (+ h n))
18219 (setq n (* dm (with-no-warnings (signum n))))
18220 (unless (= 0 (setq rem (% m dm)))
18221 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18222 (setq m (+ m n)))
18223 (when (< m 0) (setq m (+ m 60) h (1- h)))
18224 (when (> m 59) (setq m (- m 60) h (1+ h)))
18225 (setq h (mod h 24))
18226 (setq ng 1 new (format "-%02d:%02d" h m)))
18227 ((org-pos-in-match-range pos 6)
18228 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18229 ((org-pos-in-match-range pos 5)
18230 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18232 ((org-pos-in-match-range pos 9)
18233 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18234 ((org-pos-in-match-range pos 8)
18235 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18237 (when ng
18238 (setq s (concat
18239 (substring s 0 (match-beginning ng))
18241 (substring s (match-end ng))))))
18244 (defun org-recenter-calendar (d)
18245 "If the calendar is visible, recenter it to date D."
18246 (let ((cwin (get-buffer-window "*Calendar*" t)))
18247 (when cwin
18248 (let ((calendar-move-hook nil))
18249 (with-selected-window cwin
18250 (calendar-goto-date
18251 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18253 (defun org-goto-calendar (&optional arg)
18254 "Go to the Emacs calendar at the current date.
18255 If there is a time stamp in the current line, go to that date.
18256 A prefix ARG can be used to force the current date."
18257 (interactive "P")
18258 (let ((tsr org-ts-regexp) diff
18259 (calendar-move-hook nil)
18260 (calendar-view-holidays-initially-flag nil)
18261 (calendar-view-diary-initially-flag nil))
18262 (when (or (org-at-timestamp-p)
18263 (save-excursion
18264 (beginning-of-line 1)
18265 (looking-at (concat ".*" tsr))))
18266 (let ((d1 (time-to-days (current-time)))
18267 (d2 (time-to-days
18268 (org-time-string-to-time (match-string 1)))))
18269 (setq diff (- d2 d1))))
18270 (calendar)
18271 (calendar-goto-today)
18272 (when (and diff (not arg)) (calendar-forward-day diff))))
18274 (defun org-get-date-from-calendar ()
18275 "Return a list (month day year) of date at point in calendar."
18276 (with-current-buffer "*Calendar*"
18277 (save-match-data
18278 (calendar-cursor-to-date))))
18280 (defun org-date-from-calendar ()
18281 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18282 If there is already a time stamp at the cursor position, update it."
18283 (interactive)
18284 (if (org-at-timestamp-p t)
18285 (org-timestamp-change 0 'calendar)
18286 (let ((cal-date (org-get-date-from-calendar)))
18287 (org-insert-time-stamp
18288 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18290 (defcustom org-effort-durations
18291 `(("min" . 1)
18292 ("h" . 60)
18293 ("d" . ,(* 60 8))
18294 ("w" . ,(* 60 8 5))
18295 ("m" . ,(* 60 8 5 4))
18296 ("y" . ,(* 60 8 5 40)))
18297 "Conversion factor to minutes for an effort modifier.
18299 Each entry has the form (MODIFIER . MINUTES).
18301 In an effort string, a number followed by MODIFIER is multiplied
18302 by the specified number of MINUTES to obtain an effort in
18303 minutes.
18305 For example, if the value of this variable is ((\"hours\" . 60)), then an
18306 effort string \"2hours\" is equivalent to 120 minutes."
18307 :group 'org-agenda
18308 :version "26.1"
18309 :package-version '(Org . "8.3")
18310 :type '(alist :key-type (string :tag "Modifier")
18311 :value-type (number :tag "Minutes")))
18313 (defun org-minutes-to-clocksum-string (m)
18314 "Format number of minutes as a clocksum string.
18315 The format is determined by `org-time-clocksum-format',
18316 `org-time-clocksum-use-fractional' and
18317 `org-time-clocksum-fractional-format' and
18318 `org-time-clocksum-use-effort-durations'."
18319 (let ((clocksum "")
18320 (m (round m)) ; Don't allow fractions of minutes
18321 h d w mo y fmt n)
18322 (setq h (if org-time-clocksum-use-effort-durations
18323 (cdr (assoc "h" org-effort-durations)) 60)
18324 d (if org-time-clocksum-use-effort-durations
18325 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18326 w (if org-time-clocksum-use-effort-durations
18327 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18328 mo (if org-time-clocksum-use-effort-durations
18329 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18330 y (if org-time-clocksum-use-effort-durations
18331 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18332 ;; fractional format
18333 (if org-time-clocksum-use-fractional
18334 (cond
18335 ;; single format string
18336 ((stringp org-time-clocksum-fractional-format)
18337 (format org-time-clocksum-fractional-format (/ m (float h))))
18338 ;; choice of fractional formats for different time units
18339 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18340 (> (/ (truncate m) (* y d h)) 0))
18341 (format fmt (/ m (* y d (float h)))))
18342 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18343 (> (/ (truncate m) (* mo d h)) 0))
18344 (format fmt (/ m (* mo d (float h)))))
18345 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18346 (> (/ (truncate m) (* w d h)) 0))
18347 (format fmt (/ m (* w d (float h)))))
18348 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18349 (> (/ (truncate m) (* d h)) 0))
18350 (format fmt (/ m (* d (float h)))))
18351 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18352 (> (/ (truncate m) h) 0))
18353 (format fmt (/ m (float h))))
18354 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18355 (format fmt m))
18356 ;; fall back to smallest time unit with a format
18357 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18358 (format fmt (/ m (float h))))
18359 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18360 (format fmt (/ m (* d (float h)))))
18361 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18362 (format fmt (/ m (* w d (float h)))))
18363 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18364 (format fmt (/ m (* mo d (float h)))))
18365 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18366 (format fmt (/ m (* y d (float h))))))
18367 ;; standard (non-fractional) format, with single format string
18368 (if (stringp org-time-clocksum-format)
18369 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18370 ;; separate formats components
18371 (and (setq fmt (plist-get org-time-clocksum-format :years))
18372 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18373 (plist-get org-time-clocksum-format :require-years))
18374 (setq clocksum (concat clocksum (format fmt n))
18375 m (- m (* n y d h))))
18376 (and (setq fmt (plist-get org-time-clocksum-format :months))
18377 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18378 (plist-get org-time-clocksum-format :require-months))
18379 (setq clocksum (concat clocksum (format fmt n))
18380 m (- m (* n mo d h))))
18381 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18382 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18383 (plist-get org-time-clocksum-format :require-weeks))
18384 (setq clocksum (concat clocksum (format fmt n))
18385 m (- m (* n w d h))))
18386 (and (setq fmt (plist-get org-time-clocksum-format :days))
18387 (or (> (setq n (/ (truncate m) (* d h))) 0)
18388 (plist-get org-time-clocksum-format :require-days))
18389 (setq clocksum (concat clocksum (format fmt n))
18390 m (- m (* n d h))))
18391 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18392 (or (> (setq n (/ (truncate m) h)) 0)
18393 (plist-get org-time-clocksum-format :require-hours))
18394 (setq clocksum (concat clocksum (format fmt n))
18395 m (- m (* n h))))
18396 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18397 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18398 (setq clocksum (concat clocksum (format fmt m))))
18399 ;; return formatted time duration
18400 clocksum))))
18402 (defun org-hours-to-clocksum-string (n)
18403 (org-minutes-to-clocksum-string (* n 60)))
18405 (defun org-hh:mm-string-to-minutes (s)
18406 "Convert a string H:MM to a number of minutes.
18407 If the string is just a number, interpret it as minutes.
18408 In fact, the first hh:mm or number in the string will be taken,
18409 there can be extra stuff in the string.
18410 If no number is found, the return value is 0."
18411 (cond
18412 ((integerp s) s)
18413 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18414 (+ (* (string-to-number (match-string 1 s)) 60)
18415 (string-to-number (match-string 2 s))))
18416 ((string-match "\\([0-9]+\\)" s)
18417 (string-to-number (match-string 1 s)))
18418 (t 0)))
18420 (defcustom org-image-actual-width t
18421 "Should we use the actual width of images when inlining them?
18423 When set to t, always use the image width.
18425 When set to a number, use imagemagick (when available) to set
18426 the image's width to this value.
18428 When set to a number in a list, try to get the width from any
18429 #+ATTR.* keyword if it matches a width specification like
18431 #+ATTR_HTML: :width 300px
18433 and fall back on that number if none is found.
18435 When set to nil, try to get the width from an #+ATTR.* keyword
18436 and fall back on the original width if none is found.
18438 This requires Emacs >= 24.1, build with imagemagick support."
18439 :group 'org-appearance
18440 :version "24.4"
18441 :package-version '(Org . "8.0")
18442 :type '(choice
18443 (const :tag "Use the image width" t)
18444 (integer :tag "Use a number of pixels")
18445 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18446 (const :tag "Use #+ATTR* or don't resize" nil)))
18448 (defcustom org-agenda-inhibit-startup nil
18449 "Inhibit startup when preparing agenda buffers.
18450 When this variable is t, the initialization of the Org agenda
18451 buffers is inhibited: e.g. the visibility state is not set, the
18452 tables are not re-aligned, etc."
18453 :type 'boolean
18454 :version "24.3"
18455 :group 'org-agenda)
18457 (defcustom org-agenda-ignore-properties nil
18458 "Avoid updating text properties when building the agenda.
18459 Properties are used to prepare buffers for effort estimates,
18460 appointments, statistics and subtree-local categories.
18461 If you don't use these in the agenda, you can add them to this
18462 list and agenda building will be a bit faster.
18463 The value is a list, with zero or more of the symbols `effort', `appt',
18464 `stats' or `category'."
18465 :type '(set :greedy t
18466 (const effort)
18467 (const appt)
18468 (const stats)
18469 (const category))
18470 :version "26.1"
18471 :package-version '(Org . "8.3")
18472 :group 'org-agenda)
18474 (defun org-duration-string-to-minutes (s &optional output-to-string)
18475 "Convert a duration string S to minutes.
18477 A bare number is interpreted as minutes, modifiers can be set by
18478 customizing `org-effort-durations' (which see).
18480 Entries containing a colon are interpreted as H:MM by
18481 `org-hh:mm-string-to-minutes'."
18482 (let ((result 0)
18483 (re (concat "\\([0-9.]+\\) *\\("
18484 (regexp-opt (mapcar 'car org-effort-durations))
18485 "\\)")))
18486 (while (string-match re s)
18487 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18488 (string-to-number (match-string 1 s))))
18489 (setq s (replace-match "" nil t s)))
18490 (setq result (floor result))
18491 (cl-incf result (org-hh:mm-string-to-minutes s))
18492 (if output-to-string (number-to-string result) result)))
18494 ;;;; Files
18496 (defun org-save-all-org-buffers ()
18497 "Save all Org buffers without user confirmation."
18498 (interactive)
18499 (message "Saving all Org buffers...")
18500 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18501 (when (featurep 'org-id) (org-id-locations-save))
18502 (message "Saving all Org buffers... done"))
18504 (defun org-revert-all-org-buffers ()
18505 "Revert all Org buffers.
18506 Prompt for confirmation when there are unsaved changes.
18507 Be sure you know what you are doing before letting this function
18508 overwrite your changes.
18510 This function is useful in a setup where one tracks org files
18511 with a version control system, to revert on one machine after pulling
18512 changes from another. I believe the procedure must be like this:
18514 1. M-x org-save-all-org-buffers
18515 2. Pull changes from the other machine, resolve conflicts
18516 3. M-x org-revert-all-org-buffers"
18517 (interactive)
18518 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18519 (user-error "Abort"))
18520 (save-excursion
18521 (save-window-excursion
18522 (dolist (b (buffer-list))
18523 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18524 (with-current-buffer b buffer-file-name))
18525 (pop-to-buffer-same-window b)
18526 (revert-buffer t 'no-confirm)))
18527 (when (and (featurep 'org-id) org-id-track-globally)
18528 (org-id-locations-load)))))
18530 ;;;; Agenda files
18532 ;;;###autoload
18533 (defun org-switchb (&optional arg)
18534 "Switch between Org buffers.
18536 With `\\[universal-argument]' prefix, restrict available buffers to files.
18538 With `\\[universal-argument] \\[universal-argument]' \
18539 prefix, restrict available buffers to agenda files."
18540 (interactive "P")
18541 (let ((blist (org-buffer-list
18542 (cond ((equal arg '(4)) 'files)
18543 ((equal arg '(16)) 'agenda)))))
18544 (pop-to-buffer-same-window
18545 (completing-read "Org buffer: "
18546 (mapcar #'list (mapcar #'buffer-name blist))
18547 nil t))))
18549 (defun org-buffer-list (&optional predicate exclude-tmp)
18550 "Return a list of Org buffers.
18551 PREDICATE can be `export', `files' or `agenda'.
18553 export restrict the list to Export buffers.
18554 files restrict the list to buffers visiting Org files.
18555 agenda restrict the list to buffers visiting agenda files.
18557 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18558 (let* ((bfn nil)
18559 (agenda-files (and (eq predicate 'agenda)
18560 (mapcar 'file-truename (org-agenda-files t))))
18561 (filter
18562 (cond
18563 ((eq predicate 'files)
18564 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18565 ((eq predicate 'export)
18566 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18567 ((eq predicate 'agenda)
18568 (lambda (b)
18569 (with-current-buffer b
18570 (and (derived-mode-p 'org-mode)
18571 (setq bfn (buffer-file-name b))
18572 (member (file-truename bfn) agenda-files)))))
18573 (t (lambda (b) (with-current-buffer b
18574 (or (derived-mode-p 'org-mode)
18575 (string-match "\\*Org .*Export"
18576 (buffer-name b)))))))))
18577 (delq nil
18578 (mapcar
18579 (lambda(b)
18580 (if (and (funcall filter b)
18581 (or (not exclude-tmp)
18582 (not (string-match "tmp" (buffer-name b)))))
18584 nil))
18585 (buffer-list)))))
18587 (defun org-agenda-files (&optional unrestricted archives)
18588 "Get the list of agenda files.
18589 Optional UNRESTRICTED means return the full list even if a restriction
18590 is currently in place.
18591 When ARCHIVES is t, include all archive files that are really being
18592 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18593 `org-agenda-archives-mode' is t."
18594 (let ((files
18595 (cond
18596 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18597 ((stringp org-agenda-files) (org-read-agenda-file-list))
18598 ((listp org-agenda-files) org-agenda-files)
18599 (t (error "Invalid value of `org-agenda-files'")))))
18600 (setq files (apply 'append
18601 (mapcar (lambda (f)
18602 (if (file-directory-p f)
18603 (directory-files
18604 f t org-agenda-file-regexp)
18605 (list f)))
18606 files)))
18607 (when org-agenda-skip-unavailable-files
18608 (setq files (delq nil
18609 (mapcar (function
18610 (lambda (file)
18611 (and (file-readable-p file) file)))
18612 files))))
18613 (when (or (eq archives t)
18614 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18615 (setq files (org-add-archive-files files)))
18616 files))
18618 (defun org-agenda-file-p (&optional file)
18619 "Return non-nil, if FILE is an agenda file.
18620 If FILE is omitted, use the file associated with the current
18621 buffer."
18622 (let ((fname (or file (buffer-file-name))))
18623 (and fname
18624 (member (file-truename fname)
18625 (mapcar #'file-truename (org-agenda-files t))))))
18627 (defun org-edit-agenda-file-list ()
18628 "Edit the list of agenda files.
18629 Depending on setup, this either uses customize to edit the variable
18630 `org-agenda-files', or it visits the file that is holding the list. In the
18631 latter case, the buffer is set up in a way that saving it automatically kills
18632 the buffer and restores the previous window configuration."
18633 (interactive)
18634 (if (stringp org-agenda-files)
18635 (let ((cw (current-window-configuration)))
18636 (find-file org-agenda-files)
18637 (setq-local org-window-configuration cw)
18638 (add-hook 'after-save-hook
18639 (lambda ()
18640 (set-window-configuration
18641 (prog1 org-window-configuration
18642 (kill-buffer (current-buffer))))
18643 (org-install-agenda-files-menu)
18644 (message "New agenda file list installed"))
18645 nil 'local)
18646 (message "%s" (substitute-command-keys
18647 "Edit list and finish with \\[save-buffer]")))
18648 (customize-variable 'org-agenda-files)))
18650 (defun org-store-new-agenda-file-list (list)
18651 "Set new value for the agenda file list and save it correctly."
18652 (if (stringp org-agenda-files)
18653 (let ((fe (org-read-agenda-file-list t)) b u)
18654 (while (setq b (find-buffer-visiting org-agenda-files))
18655 (kill-buffer b))
18656 (with-temp-file org-agenda-files
18657 (insert
18658 (mapconcat
18659 (lambda (f) ;; Keep un-expanded entries.
18660 (if (setq u (assoc f fe))
18661 (cdr u)
18663 list "\n")
18664 "\n")))
18665 (let ((org-mode-hook nil) (org-inhibit-startup t)
18666 (org-insert-mode-line-in-empty-file nil))
18667 (setq org-agenda-files list)
18668 (customize-save-variable 'org-agenda-files org-agenda-files))))
18670 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18671 "Read the list of agenda files from a file.
18672 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18673 filenames, used by `org-store-new-agenda-file-list' to write back
18674 un-expanded file names."
18675 (when (file-directory-p org-agenda-files)
18676 (error "`org-agenda-files' cannot be a single directory"))
18677 (when (stringp org-agenda-files)
18678 (with-temp-buffer
18679 (insert-file-contents org-agenda-files)
18680 (mapcar
18681 (lambda (f)
18682 (let ((e (expand-file-name (substitute-in-file-name f)
18683 org-directory)))
18684 (if pair-with-expansion
18685 (cons e f)
18686 e)))
18687 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18689 ;;;###autoload
18690 (defun org-cycle-agenda-files ()
18691 "Cycle through the files in `org-agenda-files'.
18692 If the current buffer visits an agenda file, find the next one in the list.
18693 If the current buffer does not, find the first agenda file."
18694 (interactive)
18695 (let* ((fs (or (org-agenda-files t)
18696 (user-error "No agenda files")))
18697 (files (copy-sequence fs))
18698 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18699 file)
18700 (when tcf
18701 (while (and (setq file (pop files))
18702 (not (equal (file-truename file) tcf)))))
18703 (find-file (car (or files fs)))
18704 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18706 (defun org-agenda-file-to-front (&optional to-end)
18707 "Move/add the current file to the top of the agenda file list.
18708 If the file is not present in the list, it is added to the front. If it is
18709 present, it is moved there. With optional argument TO-END, add/move to the
18710 end of the list."
18711 (interactive "P")
18712 (let ((org-agenda-skip-unavailable-files nil)
18713 (file-alist (mapcar (lambda (x)
18714 (cons (file-truename x) x))
18715 (org-agenda-files t)))
18716 (ctf (file-truename
18717 (or buffer-file-name
18718 (user-error "Please save the current buffer to a file"))))
18719 x had)
18720 (setq x (assoc ctf file-alist) had x)
18722 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18723 (if to-end
18724 (setq file-alist (append (delq x file-alist) (list x)))
18725 (setq file-alist (cons x (delq x file-alist))))
18726 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18727 (org-install-agenda-files-menu)
18728 (message "File %s to %s of agenda file list"
18729 (if had "moved" "added") (if to-end "end" "front"))))
18731 (defun org-remove-file (&optional file)
18732 "Remove current file from the list of files in variable `org-agenda-files'.
18733 These are the files which are being checked for agenda entries.
18734 Optional argument FILE means use this file instead of the current."
18735 (interactive)
18736 (let* ((org-agenda-skip-unavailable-files nil)
18737 (file (or file buffer-file-name
18738 (user-error "Current buffer does not visit a file")))
18739 (true-file (file-truename file))
18740 (afile (abbreviate-file-name file))
18741 (files (delq nil (mapcar
18742 (lambda (x)
18743 (unless (equal true-file
18744 (file-truename x))
18746 (org-agenda-files t)))))
18747 (if (not (= (length files) (length (org-agenda-files t))))
18748 (progn
18749 (org-store-new-agenda-file-list files)
18750 (org-install-agenda-files-menu)
18751 (message "Removed from Org Agenda list: %s" afile))
18752 (message "File was not in list: %s (not removed)" afile))))
18754 (defun org-file-menu-entry (file)
18755 (vector file (list 'find-file file) t))
18757 (defun org-check-agenda-file (file)
18758 "Make sure FILE exists. If not, ask user what to do."
18759 (unless (file-exists-p file)
18760 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18761 (abbreviate-file-name file))
18762 (let ((r (downcase (read-char-exclusive))))
18763 (cond
18764 ((equal r ?r)
18765 (org-remove-file file)
18766 (throw 'nextfile t))
18767 (t (user-error "Abort"))))))
18769 (defun org-get-agenda-file-buffer (file)
18770 "Get an agenda buffer visiting FILE.
18771 If the buffer needs to be created, add it to the list of buffers
18772 which might be released later."
18773 (let ((buf (org-find-base-buffer-visiting file)))
18774 (if buf
18775 buf ; just return it
18776 ;; Make a new buffer and remember it
18777 (setq buf (find-file-noselect file))
18778 (when buf (push buf org-agenda-new-buffers))
18779 buf)))
18781 (defun org-release-buffers (blist)
18782 "Release all buffers in list, asking the user for confirmation when needed.
18783 When a buffer is unmodified, it is just killed. When modified, it is saved
18784 \(if the user agrees) and then killed."
18785 (let (file)
18786 (dolist (buf blist)
18787 (setq file (buffer-file-name buf))
18788 (when (and (buffer-modified-p buf)
18789 file
18790 (y-or-n-p (format "Save file %s? " file)))
18791 (with-current-buffer buf (save-buffer)))
18792 (kill-buffer buf))))
18794 (defun org-agenda-prepare-buffers (files)
18795 "Create buffers for all agenda files, protect archived trees and comments."
18796 (interactive)
18797 (let ((pa '(:org-archived t))
18798 (pc '(:org-comment t))
18799 (pall '(:org-archived t :org-comment t))
18800 (inhibit-read-only t)
18801 (org-inhibit-startup org-agenda-inhibit-startup)
18802 (rea (concat ":" org-archive-tag ":"))
18803 re pos)
18804 (setq org-tag-alist-for-agenda nil
18805 org-tag-groups-alist-for-agenda nil)
18806 (save-excursion
18807 (save-restriction
18808 (dolist (file files)
18809 (catch 'nextfile
18810 (if (bufferp file)
18811 (set-buffer file)
18812 (org-check-agenda-file file)
18813 (set-buffer (org-get-agenda-file-buffer file)))
18814 (widen)
18815 (org-set-regexps-and-options 'tags-only)
18816 (setq pos (point))
18817 (or (memq 'category org-agenda-ignore-properties)
18818 (org-refresh-category-properties))
18819 (or (memq 'stats org-agenda-ignore-properties)
18820 (org-refresh-stats-properties))
18821 (or (memq 'effort org-agenda-ignore-properties)
18822 (org-refresh-effort-properties))
18823 (or (memq 'appt org-agenda-ignore-properties)
18824 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18825 (setq org-todo-keywords-for-agenda
18826 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18827 (setq org-done-keywords-for-agenda
18828 (append org-done-keywords-for-agenda org-done-keywords))
18829 (setq org-todo-keyword-alist-for-agenda
18830 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18831 (setq org-tag-alist-for-agenda
18832 (org-uniquify
18833 (append org-tag-alist-for-agenda
18834 org-current-tag-alist)))
18835 ;; Merge current file's tag groups into global
18836 ;; `org-tag-groups-alist-for-agenda'.
18837 (when org-group-tags
18838 (dolist (alist org-tag-groups-alist)
18839 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18840 (if old
18841 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18842 (push alist org-tag-groups-alist-for-agenda)))))
18843 (org-with-silent-modifications
18844 (save-excursion
18845 (remove-text-properties (point-min) (point-max) pall)
18846 (when org-agenda-skip-archived-trees
18847 (goto-char (point-min))
18848 (while (re-search-forward rea nil t)
18849 (when (org-at-heading-p t)
18850 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18851 (goto-char (point-min))
18852 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18853 (while (re-search-forward re nil t)
18854 (when (save-match-data (org-in-commented-heading-p t))
18855 (add-text-properties
18856 (match-beginning 0) (org-end-of-subtree t) pc)))))
18857 (goto-char pos)))))
18858 (setq org-todo-keywords-for-agenda
18859 (org-uniquify org-todo-keywords-for-agenda))
18860 (setq org-todo-keyword-alist-for-agenda
18861 (org-uniquify org-todo-keyword-alist-for-agenda))))
18864 ;;;; CDLaTeX minor mode
18866 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18867 "Keymap for the minor `org-cdlatex-mode'.")
18869 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18870 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18871 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18872 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18873 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18875 (defvar org-cdlatex-texmathp-advice-is-done nil
18876 "Flag remembering if we have applied the advice to texmathp already.")
18878 (define-minor-mode org-cdlatex-mode
18879 "Toggle the minor `org-cdlatex-mode'.
18880 This mode supports entering LaTeX environment and math in LaTeX fragments
18881 in Org mode.
18882 \\{org-cdlatex-mode-map}"
18883 nil " OCDL" nil
18884 (when org-cdlatex-mode
18885 (require 'cdlatex)
18886 (run-hooks 'cdlatex-mode-hook)
18887 (cdlatex-compute-tables))
18888 (unless org-cdlatex-texmathp-advice-is-done
18889 (setq org-cdlatex-texmathp-advice-is-done t)
18890 (defadvice texmathp (around org-math-always-on activate)
18891 "Always return t in Org buffers.
18892 This is because we want to insert math symbols without dollars even outside
18893 the LaTeX math segments. If Org mode thinks that point is actually inside
18894 an embedded LaTeX fragment, let `texmathp' do its job.
18895 `\\[org-cdlatex-mode-map]'"
18896 (interactive)
18897 (let (p)
18898 (cond
18899 ((not (derived-mode-p 'org-mode)) ad-do-it)
18900 ((eq this-command 'cdlatex-math-symbol)
18901 (setq ad-return-value t
18902 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18904 (let ((p (org-inside-LaTeX-fragment-p)))
18905 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18906 (setq ad-return-value t
18907 texmathp-why '("Org mode embedded math" . 0))
18908 (when p ad-do-it)))))))))
18910 (defun turn-on-org-cdlatex ()
18911 "Unconditionally turn on `org-cdlatex-mode'."
18912 (org-cdlatex-mode 1))
18914 (defun org-try-cdlatex-tab ()
18915 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18916 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18917 - inside a LaTeX fragment, or
18918 - after the first word in a line, where an abbreviation expansion could
18919 insert a LaTeX environment."
18920 (when org-cdlatex-mode
18921 (cond
18922 ;; Before any word on the line: No expansion possible.
18923 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18924 ;; Just after first word on the line: Expand it. Make sure it
18925 ;; cannot happen on headlines, though.
18926 ((save-excursion
18927 (skip-chars-backward "a-zA-Z0-9*")
18928 (skip-chars-backward " \t")
18929 (and (bolp) (not (org-at-heading-p))))
18930 (cdlatex-tab) t)
18931 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18933 (defun org-cdlatex-underscore-caret (&optional _arg)
18934 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18935 Revert to the normal definition outside of these fragments."
18936 (interactive "P")
18937 (if (org-inside-LaTeX-fragment-p)
18938 (call-interactively 'cdlatex-sub-superscript)
18939 (let (org-cdlatex-mode)
18940 (call-interactively (key-binding (vector last-input-event))))))
18942 (defun org-cdlatex-math-modify (&optional _arg)
18943 "Execute `cdlatex-math-modify' in LaTeX fragments.
18944 Revert to the normal definition outside of these fragments."
18945 (interactive "P")
18946 (if (org-inside-LaTeX-fragment-p)
18947 (call-interactively 'cdlatex-math-modify)
18948 (let (org-cdlatex-mode)
18949 (call-interactively (key-binding (vector last-input-event))))))
18951 (defun org-cdlatex-environment-indent (&optional environment item)
18952 "Execute `cdlatex-environment' and indent the inserted environment.
18954 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18956 The inserted environment is indented to current indentation
18957 unless point is at the beginning of the line, in which the
18958 environment remains unintended."
18959 (interactive)
18960 ;; cdlatex-environment always return nil. Therefore, capture output
18961 ;; first and determine if an environment was selected.
18962 (let* ((beg (point-marker))
18963 (end (copy-marker (point) t))
18964 (inserted (progn
18965 (ignore-errors (cdlatex-environment environment item))
18966 (< beg end)))
18967 ;; Figure out how many lines to move forward after the
18968 ;; environment has been inserted.
18969 (lines (when inserted
18970 (save-excursion
18971 (- (cl-loop while (< beg (point))
18972 with x = 0
18973 do (forward-line -1)
18974 (cl-incf x)
18975 finally return x)
18976 (if (progn (goto-char beg)
18977 (and (progn (skip-chars-forward " \t") (eolp))
18978 (progn (skip-chars-backward " \t") (bolp))))
18979 1 0)))))
18980 (env (org-trim (delete-and-extract-region beg end))))
18981 (when inserted
18982 ;; Get indentation of next line unless at column 0.
18983 (let ((ind (if (bolp) 0
18984 (save-excursion
18985 (org-return-indent)
18986 (prog1 (org-get-indentation)
18987 (when (progn (skip-chars-forward " \t") (eolp))
18988 (delete-region beg (point)))))))
18989 (bol (progn (skip-chars-backward " \t") (bolp))))
18990 ;; Insert a newline before environment unless at column zero
18991 ;; to "escape" the current line. Insert a newline if
18992 ;; something is one the same line as \end{ENVIRONMENT}.
18993 (insert
18994 (concat (unless bol "\n") env
18995 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18996 (unless (zerop ind)
18997 (save-excursion
18998 (goto-char beg)
18999 (while (< (point) end)
19000 (unless (eolp) (indent-line-to ind))
19001 (forward-line))))
19002 (goto-char beg)
19003 (forward-line lines)
19004 (indent-line-to ind)))
19005 (set-marker beg nil)
19006 (set-marker end nil)))
19009 ;;;; LaTeX fragments
19011 (defun org-inside-LaTeX-fragment-p ()
19012 "Test if point is inside a LaTeX fragment.
19013 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19014 sequence appearing also before point.
19015 Even though the matchers for math are configurable, this function assumes
19016 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19017 delimiters are skipped when they have been removed by customization.
19018 The return value is nil, or a cons cell with the delimiter and the
19019 position of this delimiter.
19021 This function does a reasonably good job, but can locally be fooled by
19022 for example currency specifications. For example it will assume being in
19023 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19024 fragments that are properly closed, but during editing, we have to live
19025 with the uncertainty caused by missing closing delimiters. This function
19026 looks only before point, not after."
19027 (catch 'exit
19028 (let ((pos (point))
19029 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19030 (lim (progn
19031 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19032 (point)))
19033 dd-on str (start 0) m re)
19034 (goto-char pos)
19035 (when dodollar
19036 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19037 re (nth 1 (assoc "$" org-latex-regexps)))
19038 (while (string-match re str start)
19039 (cond
19040 ((= (match-end 0) (length str))
19041 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19042 ((= (match-end 0) (- (length str) 5))
19043 (throw 'exit nil))
19044 (t (setq start (match-end 0))))))
19045 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19046 (goto-char pos)
19047 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19048 (and (match-beginning 2) (throw 'exit nil))
19049 ;; count $$
19050 (while (re-search-backward "\\$\\$" lim t)
19051 (setq dd-on (not dd-on)))
19052 (goto-char pos)
19053 (when dd-on (cons "$$" m))))))
19055 (defun org-inside-latex-macro-p ()
19056 "Is point inside a LaTeX macro or its arguments?"
19057 (save-match-data
19058 (org-in-regexp
19059 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19061 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19062 "Build an overlay between BEG and END using IMAGE file.
19063 Argument IMAGETYPE is the extension of the displayed image,
19064 as a string. It defaults to \"png\"."
19065 (let ((ov (make-overlay beg end))
19066 (imagetype (or (intern imagetype) 'png)))
19067 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19068 (overlay-put ov 'evaporate t)
19069 (overlay-put ov
19070 'modification-hooks
19071 (list (lambda (o _flag _beg _end &optional _l)
19072 (delete-overlay o))))
19073 (overlay-put ov
19074 'display
19075 (list 'image :type imagetype :file image :ascent 'center))))
19077 (defun org--list-latex-overlays (&optional beg end)
19078 "List all Org LaTeX overlays in current buffer.
19079 Limit to overlays between BEG and END when those are provided."
19080 (cl-remove-if-not
19081 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19082 (overlays-in (or beg (point-min)) (or end (point-max)))))
19084 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19085 "Remove all overlays with LaTeX fragment images in current buffer.
19086 When optional arguments BEG and END are non-nil, remove all
19087 overlays between them instead. Return a non-nil value when some
19088 overlays were removed, nil otherwise."
19089 (let ((overlays (org--list-latex-overlays beg end)))
19090 (mapc #'delete-overlay overlays)
19091 overlays))
19093 (defun org-toggle-latex-fragment (&optional arg)
19094 "Preview the LaTeX fragment at point, or all locally or globally.
19096 If the cursor is on a LaTeX fragment, create the image and overlay
19097 it over the source code, if there is none. Remove it otherwise.
19098 If there is no fragment at point, display all fragments in the
19099 current section.
19101 With prefix ARG, preview or clear image for all fragments in the
19102 current subtree or in the whole buffer when used before the first
19103 headline. With a prefix ARG `\\[universal-argument] \
19104 \\[universal-argument]' preview or clear images
19105 for all fragments in the buffer."
19106 (interactive "P")
19107 (when (display-graphic-p)
19108 (catch 'exit
19109 (save-excursion
19110 (let (beg end msg)
19111 (cond
19112 ((or (equal arg '(16))
19113 (and (equal arg '(4))
19114 (org-with-limited-levels (org-before-first-heading-p))))
19115 (if (org-remove-latex-fragment-image-overlays)
19116 (progn (message "LaTeX fragments images removed from buffer")
19117 (throw 'exit nil))
19118 (setq msg "Creating images for buffer...")))
19119 ((equal arg '(4))
19120 (org-with-limited-levels (org-back-to-heading t))
19121 (setq beg (point))
19122 (setq end (progn (org-end-of-subtree t) (point)))
19123 (if (org-remove-latex-fragment-image-overlays beg end)
19124 (progn
19125 (message "LaTeX fragment images removed from subtree")
19126 (throw 'exit nil))
19127 (setq msg "Creating images for subtree...")))
19128 ((let ((datum (org-element-context)))
19129 (when (memq (org-element-type datum)
19130 '(latex-environment latex-fragment))
19131 (setq beg (org-element-property :begin datum))
19132 (setq end (org-element-property :end datum))
19133 (if (org-remove-latex-fragment-image-overlays beg end)
19134 (progn (message "LaTeX fragment image removed")
19135 (throw 'exit nil))
19136 (setq msg "Creating image...")))))
19138 (org-with-limited-levels
19139 (setq beg (if (org-at-heading-p) (line-beginning-position)
19140 (outline-previous-heading)
19141 (point)))
19142 (setq end (progn (outline-next-heading) (point)))
19143 (if (org-remove-latex-fragment-image-overlays beg end)
19144 (progn
19145 (message "LaTeX fragment images removed from section")
19146 (throw 'exit nil))
19147 (setq msg "Creating images for section...")))))
19148 (let ((file (buffer-file-name (buffer-base-buffer))))
19149 (org-format-latex
19150 (concat org-preview-latex-image-directory "org-ltximg")
19151 beg end
19152 ;; Emacs cannot overlay images from remote hosts. Create
19153 ;; it in `temporary-file-directory' instead.
19154 (if (or (not file) (file-remote-p file))
19155 temporary-file-directory
19156 default-directory)
19157 'overlays msg 'forbuffer org-preview-latex-default-process))
19158 (message (concat msg "done")))))))
19160 (defun org-format-latex
19161 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19162 "Replace LaTeX fragments with links to an image.
19164 The function takes care of creating the replacement image.
19166 Only consider fragments between BEG and END when those are
19167 provided.
19169 When optional argument OVERLAYS is non-nil, display the image on
19170 top of the fragment instead of replacing it.
19172 PROCESSING-TYPE is the conversion method to use, as a symbol.
19174 Some of the options can be changed using the variable
19175 `org-format-latex-options', which see."
19176 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19177 (unless (eq processing-type 'verbatim)
19178 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19179 (cnt 0)
19180 checkdir-flag)
19181 (goto-char (or beg (point-min)))
19182 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19183 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19184 (overlay-recenter (or end (point-max))))
19185 (while (re-search-forward math-regexp end t)
19186 (unless (and overlays
19187 (eq (get-char-property (point) 'org-overlay-type)
19188 'org-latex-overlay))
19189 (let* ((context (org-element-context))
19190 (type (org-element-type context)))
19191 (when (memq type '(latex-environment latex-fragment))
19192 (let ((block-type (eq type 'latex-environment))
19193 (value (org-element-property :value context))
19194 (beg (org-element-property :begin context))
19195 (end (save-excursion
19196 (goto-char (org-element-property :end context))
19197 (skip-chars-backward " \r\t\n")
19198 (point))))
19199 (cond
19200 ((eq processing-type 'mathjax)
19201 ;; Prepare for MathJax processing.
19202 (if (not (string-match "\\`\\$\\$?" value))
19203 (goto-char end)
19204 (delete-region beg end)
19205 (if (string= (match-string 0 value) "$$")
19206 (insert "\\[" (substring value 2 -2) "\\]")
19207 (insert "\\(" (substring value 1 -1) "\\)"))))
19208 ((assq processing-type org-preview-latex-process-alist)
19209 ;; Process to an image.
19210 (cl-incf cnt)
19211 (goto-char beg)
19212 (let* ((processing-info
19213 (cdr (assq processing-type org-preview-latex-process-alist)))
19214 (face (face-at-point))
19215 ;; Get the colors from the face at point.
19217 (let ((color (plist-get org-format-latex-options
19218 :foreground)))
19219 (if (and forbuffer (eq color 'auto))
19220 (face-attribute face :foreground nil 'default)
19221 color)))
19223 (let ((color (plist-get org-format-latex-options
19224 :background)))
19225 (if (and forbuffer (eq color 'auto))
19226 (face-attribute face :background nil 'default)
19227 color)))
19228 (hash (sha1 (prin1-to-string
19229 (list org-format-latex-header
19230 org-latex-default-packages-alist
19231 org-latex-packages-alist
19232 org-format-latex-options
19233 forbuffer value fg bg))))
19234 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19235 (absprefix (expand-file-name prefix dir))
19236 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19237 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19238 (sep (and block-type "\n\n"))
19239 (link (concat sep "[[file:" linkfile "]]" sep))
19240 (options
19241 (org-combine-plists
19242 org-format-latex-options
19243 `(:foreground ,fg :background ,bg))))
19244 (when msg (message msg cnt))
19245 (unless checkdir-flag ; Ensure the directory exists.
19246 (setq checkdir-flag t)
19247 (let ((todir (file-name-directory absprefix)))
19248 (unless (file-directory-p todir)
19249 (make-directory todir t))))
19250 (unless (file-exists-p movefile)
19251 (org-create-formula-image
19252 value movefile options forbuffer processing-type))
19253 (if overlays
19254 (progn
19255 (dolist (o (overlays-in beg end))
19256 (when (eq (overlay-get o 'org-overlay-type)
19257 'org-latex-overlay)
19258 (delete-overlay o)))
19259 (org--format-latex-make-overlay beg end movefile imagetype)
19260 (goto-char end))
19261 (delete-region beg end)
19262 (insert
19263 (org-add-props link
19264 (list 'org-latex-src
19265 (replace-regexp-in-string "\"" "" value)
19266 'org-latex-src-embed-type
19267 (if block-type 'paragraph 'character)))))))
19268 ((eq processing-type 'mathml)
19269 ;; Process to MathML.
19270 (unless (org-format-latex-mathml-available-p)
19271 (user-error "LaTeX to MathML converter not configured"))
19272 (cl-incf cnt)
19273 (when msg (message msg cnt))
19274 (goto-char beg)
19275 (delete-region beg end)
19276 (insert (org-format-latex-as-mathml
19277 value block-type prefix dir)))
19279 (error "Unknown conversion process %s for LaTeX fragments"
19280 processing-type)))))))))))
19282 (defun org-create-math-formula (latex-frag &optional mathml-file)
19283 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19284 Use `org-latex-to-mathml-convert-command'. If the conversion is
19285 sucessful, return the portion between \"<math...> </math>\"
19286 elements otherwise return nil. When MATHML-FILE is specified,
19287 write the results in to that file. When invoked as an
19288 interactive command, prompt for LATEX-FRAG, with initial value
19289 set to the current active region and echo the results for user
19290 inspection."
19291 (interactive (list (let ((frag (when (org-region-active-p)
19292 (buffer-substring-no-properties
19293 (region-beginning) (region-end)))))
19294 (read-string "LaTeX Fragment: " frag nil frag))))
19295 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19296 (let* ((tmp-in-file
19297 (let ((file (file-relative-name
19298 (make-temp-name (expand-file-name "ltxmathml-in")))))
19299 (write-region latex-frag nil file)
19300 file))
19301 (tmp-out-file (file-relative-name
19302 (make-temp-name (expand-file-name "ltxmathml-out"))))
19303 (cmd (format-spec
19304 org-latex-to-mathml-convert-command
19305 `((?j . ,(and org-latex-to-mathml-jar-file
19306 (shell-quote-argument
19307 (expand-file-name
19308 org-latex-to-mathml-jar-file))))
19309 (?I . ,(shell-quote-argument tmp-in-file))
19310 (?i . ,latex-frag)
19311 (?o . ,(shell-quote-argument tmp-out-file)))))
19312 mathml shell-command-output)
19313 (when (called-interactively-p 'any)
19314 (unless (org-format-latex-mathml-available-p)
19315 (user-error "LaTeX to MathML converter not configured")))
19316 (message "Running %s" cmd)
19317 (setq shell-command-output (shell-command-to-string cmd))
19318 (setq mathml
19319 (when (file-readable-p tmp-out-file)
19320 (with-current-buffer (find-file-noselect tmp-out-file t)
19321 (goto-char (point-min))
19322 (when (re-search-forward
19323 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19324 (regexp-quote
19325 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19326 nil t)
19327 (prog1 (match-string 0) (kill-buffer))))))
19328 (cond
19329 (mathml
19330 (setq mathml
19331 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19332 (when mathml-file
19333 (write-region mathml nil mathml-file))
19334 (when (called-interactively-p 'any)
19335 (message mathml)))
19336 ((message "LaTeX to MathML conversion failed")
19337 (message shell-command-output)))
19338 (delete-file tmp-in-file)
19339 (when (file-exists-p tmp-out-file)
19340 (delete-file tmp-out-file))
19341 mathml))
19343 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19344 prefix &optional dir)
19345 "Use `org-create-math-formula' but check local cache first."
19346 (let* ((absprefix (expand-file-name prefix dir))
19347 (print-length nil) (print-level nil)
19348 (formula-id (concat
19349 "formula-"
19350 (sha1
19351 (prin1-to-string
19352 (list latex-frag
19353 org-latex-to-mathml-convert-command)))))
19354 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19355 (formula-cache-dir (file-name-directory formula-cache)))
19357 (unless (file-directory-p formula-cache-dir)
19358 (make-directory formula-cache-dir t))
19360 (unless (file-exists-p formula-cache)
19361 (org-create-math-formula latex-frag formula-cache))
19363 (if (file-exists-p formula-cache)
19364 ;; Successful conversion. Return the link to MathML file.
19365 (org-add-props
19366 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19367 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19368 'org-latex-src-embed-type (if latex-frag-type
19369 'paragraph 'character)))
19370 ;; Failed conversion. Return the LaTeX fragment verbatim
19371 latex-frag)))
19373 (defun org--get-display-dpi ()
19374 "Get the DPI of the display.
19375 The function assumes that the display has the same pixel width in
19376 the horizontal and vertical directions."
19377 (if (display-graphic-p)
19378 (round (/ (display-pixel-height)
19379 (/ (display-mm-height) 25.4)))
19380 (error "Attempt to calculate the dpi of a non-graphic display")))
19382 (defun org-create-formula-image
19383 (string tofile options buffer &optional processing-type)
19384 "Create an image from LaTeX source using external processes.
19386 The LaTeX STRING is saved to a temporary LaTeX file, then
19387 converted to an image file by process PROCESSING-TYPE defined in
19388 `org-preview-latex-process-alist'. A nil value defaults to
19389 `org-preview-latex-default-process'.
19391 The generated image file is eventually moved to TOFILE.
19393 The OPTIONS argument controls the size, foreground color and
19394 background color of the generated image.
19396 When BUFFER non-nil, this function is used for LaTeX previewing.
19397 Otherwise, it is used to deal with LaTeX snippets showed in
19398 a HTML file."
19399 (let* ((processing-type (or processing-type
19400 org-preview-latex-default-process))
19401 (processing-info
19402 (cdr (assq processing-type org-preview-latex-process-alist)))
19403 (programs (plist-get processing-info :programs))
19404 (error-message (or (plist-get processing-info :message) ""))
19405 (use-xcolor (plist-get processing-info :use-xcolor))
19406 (image-input-type (plist-get processing-info :image-input-type))
19407 (image-output-type (plist-get processing-info :image-output-type))
19408 (post-clean (or (plist-get processing-info :post-clean)
19409 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19410 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19411 (latex-header
19412 (or (plist-get processing-info :latex-header)
19413 (org-latex-make-preamble
19414 (org-export-get-environment (org-export-get-backend 'latex))
19415 org-format-latex-header
19416 'snippet)))
19417 (latex-compiler (plist-get processing-info :latex-compiler))
19418 (image-converter (plist-get processing-info :image-converter))
19419 (tmpdir temporary-file-directory)
19420 (texfilebase (make-temp-name
19421 (expand-file-name "orgtex" tmpdir)))
19422 (texfile (concat texfilebase ".tex"))
19423 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19424 '(1.0 . 1.0)))
19425 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19426 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19427 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19428 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19429 "Black"))
19430 (bg (or (plist-get options (if buffer :background :html-background))
19431 "Transparent"))
19432 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19433 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19434 (dolist (program programs)
19435 (org-check-external-command program error-message))
19436 (if use-xcolor
19437 (progn (if (eq fg 'default)
19438 (setq fg (org-latex-color :foreground))
19439 (setq fg (org-latex-color-format fg)))
19440 (if (eq bg 'default)
19441 (setq bg (org-latex-color :background))
19442 (setq bg (org-latex-color-format
19443 (if (string= bg "Transparent") "white" bg))))
19444 (with-temp-file texfile
19445 (insert latex-header)
19446 (insert "\n\\begin{document}\n"
19447 "\\definecolor{fg}{rgb}{" fg "}\n"
19448 "\\definecolor{bg}{rgb}{" bg "}\n"
19449 "\n\\pagecolor{bg}\n"
19450 "\n{\\color{fg}\n"
19451 string
19452 "\n}\n"
19453 "\n\\end{document}\n")))
19454 (if (eq fg 'default)
19455 (setq fg (org-dvipng-color :foreground))
19456 (unless (string= fg "Transparent")
19457 (setq fg (org-dvipng-color-format fg))))
19458 (if (eq bg 'default)
19459 (setq bg (org-dvipng-color :background))
19460 (unless (string= bg "Transparent")
19461 (setq bg (org-dvipng-color-format bg))))
19462 (with-temp-file texfile
19463 (insert latex-header)
19464 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19466 (let* ((err-msg (format "Please adjust '%s' part of \
19467 `org-preview-latex-process-alist'."
19468 processing-type))
19469 (image-input-file
19470 (org-compile-file
19471 texfile latex-compiler image-input-type err-msg log-buf))
19472 (image-output-file
19473 (org-compile-file
19474 image-input-file image-converter image-output-type err-msg log-buf
19475 `((?F . ,(shell-quote-argument fg))
19476 (?B . ,(shell-quote-argument bg))
19477 (?D . ,(shell-quote-argument (format "%s" dpi)))
19478 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19479 (copy-file image-output-file tofile 'replace)
19480 (dolist (e post-clean)
19481 (when (file-exists-p (concat texfilebase e))
19482 (delete-file (concat texfilebase e))))
19483 image-output-file)))
19485 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19486 "Fill a LaTeX header template TPL.
19487 In the template, the following place holders will be recognized:
19489 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19490 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19491 [PACKAGES] \\usepackage statements for PKG
19492 [NO-PACKAGES] do not include PKG
19493 [EXTRA] the string EXTRA
19494 [NO-EXTRA] do not include EXTRA
19496 For backward compatibility, if both the positive and the negative place
19497 holder is missing, the positive one (without the \"NO-\") will be
19498 assumed to be present at the end of the template.
19499 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19500 EXTRA is a string.
19501 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19502 (let (rpl (end ""))
19503 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19504 (setq rpl (if (or (match-end 1) (not def-pkg))
19505 "" (org-latex-packages-to-string def-pkg snippets-p t))
19506 tpl (replace-match rpl t t tpl))
19507 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19509 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19510 (setq rpl (if (or (match-end 1) (not pkg))
19511 "" (org-latex-packages-to-string pkg snippets-p t))
19512 tpl (replace-match rpl t t tpl))
19513 (when pkg (setq end
19514 (concat end "\n"
19515 (org-latex-packages-to-string pkg snippets-p)))))
19517 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19518 (setq rpl (if (or (match-end 1) (not extra))
19519 "" (concat extra "\n"))
19520 tpl (replace-match rpl t t tpl))
19521 (when (and extra (string-match "\\S-" extra))
19522 (setq end (concat end "\n" extra))))
19524 (if (string-match "\\S-" end)
19525 (concat tpl "\n" end)
19526 tpl)))
19528 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19529 "Turn an alist of packages into a string with the \\usepackage macros."
19530 (setq pkg (mapconcat (lambda(p)
19531 (cond
19532 ((stringp p) p)
19533 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19534 (format "%% Package %s omitted" (cadr p)))
19535 ((equal "" (car p))
19536 (format "\\usepackage{%s}" (cadr p)))
19538 (format "\\usepackage[%s]{%s}"
19539 (car p) (cadr p)))))
19541 "\n"))
19542 (if newline (concat pkg "\n") pkg))
19544 (defun org-dvipng-color (attr)
19545 "Return a RGB color specification for dvipng."
19546 (org-dvipng-color-format (face-attribute 'default attr nil)))
19548 (defun org-dvipng-color-format (color-name)
19549 "Convert COLOR-NAME to a RGB color value for dvipng."
19550 (apply #'format "rgb %s %s %s"
19551 (mapcar 'org-normalize-color
19552 (color-values color-name))))
19554 (defun org-latex-color (attr)
19555 "Return a RGB color for the LaTeX color package."
19556 (org-latex-color-format (face-attribute 'default attr nil)))
19558 (defun org-latex-color-format (color-name)
19559 "Convert COLOR-NAME to a RGB color value."
19560 (apply #'format "%s,%s,%s"
19561 (mapcar 'org-normalize-color
19562 (color-values color-name))))
19564 (defun org-normalize-color (value)
19565 "Return string to be used as color value for an RGB component."
19566 (format "%g" (/ value 65535.0)))
19570 ;; Image display
19572 (defvar-local org-inline-image-overlays nil)
19574 (defun org-toggle-inline-images (&optional include-linked)
19575 "Toggle the display of inline images.
19576 INCLUDE-LINKED is passed to `org-display-inline-images'."
19577 (interactive "P")
19578 (if org-inline-image-overlays
19579 (progn
19580 (org-remove-inline-images)
19581 (when (called-interactively-p 'interactive)
19582 (message "Inline image display turned off")))
19583 (org-display-inline-images include-linked)
19584 (when (called-interactively-p 'interactive)
19585 (message (if org-inline-image-overlays
19586 (format "%d images displayed inline"
19587 (length org-inline-image-overlays))
19588 "No images to display inline")))))
19590 (defun org-redisplay-inline-images ()
19591 "Refresh the display of inline images."
19592 (interactive)
19593 (if (not org-inline-image-overlays)
19594 (org-toggle-inline-images)
19595 (org-toggle-inline-images)
19596 (org-toggle-inline-images)))
19598 (defun org-display-inline-images (&optional include-linked refresh beg end)
19599 "Display inline images.
19601 An inline image is a link which follows either of these
19602 conventions:
19604 1. Its path is a file with an extension matching return value
19605 from `image-file-name-regexp' and it has no contents.
19607 2. Its description consists in a single link of the previous
19608 type.
19610 When optional argument INCLUDE-LINKED is non-nil, also links with
19611 a text description part will be inlined. This can be nice for
19612 a quick look at those images, but it does not reflect what
19613 exported files will look like.
19615 When optional argument REFRESH is non-nil, refresh existing
19616 images between BEG and END. This will create new image displays
19617 only if necessary. BEG and END default to the buffer
19618 boundaries."
19619 (interactive "P")
19620 (when (display-graphic-p)
19621 (unless refresh
19622 (org-remove-inline-images)
19623 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19624 (org-with-wide-buffer
19625 (goto-char (or beg (point-min)))
19626 (let ((case-fold-search t)
19627 (file-extension-re (image-file-name-regexp)))
19628 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19629 (let ((link (save-match-data (org-element-context))))
19630 ;; Check if we're at an inline image.
19631 (when (and (equal (org-element-property :type link) "file")
19632 (or include-linked
19633 (not (org-element-property :contents-begin link)))
19634 (let ((parent (org-element-property :parent link)))
19635 (or (not (eq (org-element-type parent) 'link))
19636 (not (cdr (org-element-contents parent)))))
19637 (string-match-p file-extension-re
19638 (org-element-property :path link)))
19639 (let ((file (expand-file-name
19640 (org-link-unescape
19641 (org-element-property :path link)))))
19642 (when (file-exists-p file)
19643 (let ((width
19644 ;; Apply `org-image-actual-width' specifications.
19645 (cond
19646 ((not (image-type-available-p 'imagemagick)) nil)
19647 ((eq org-image-actual-width t) nil)
19648 ((listp org-image-actual-width)
19650 ;; First try to find a width among
19651 ;; attributes associated to the paragraph
19652 ;; containing link.
19653 (let ((paragraph
19654 (let ((e link))
19655 (while (and (setq e (org-element-property
19656 :parent e))
19657 (not (eq (org-element-type e)
19658 'paragraph))))
19659 e)))
19660 (when paragraph
19661 (save-excursion
19662 (goto-char (org-element-property :begin paragraph))
19663 (when
19664 (re-search-forward
19665 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19666 (org-element-property
19667 :post-affiliated paragraph)
19669 (string-to-number (match-string 1))))))
19670 ;; Otherwise, fall-back to provided number.
19671 (car org-image-actual-width)))
19672 ((numberp org-image-actual-width)
19673 org-image-actual-width)))
19674 (old (get-char-property-and-overlay
19675 (org-element-property :begin link)
19676 'org-image-overlay)))
19677 (if (and (car-safe old) refresh)
19678 (image-refresh (overlay-get (cdr old) 'display))
19679 (let ((image (create-image file
19680 (and width 'imagemagick)
19682 :width width)))
19683 (when image
19684 (let* ((link
19685 ;; If inline image is the description
19686 ;; of another link, be sure to
19687 ;; consider the latter as the one to
19688 ;; apply the overlay on.
19689 (let ((parent
19690 (org-element-property :parent link)))
19691 (if (eq (org-element-type parent) 'link)
19692 parent
19693 link)))
19694 (ov (make-overlay
19695 (org-element-property :begin link)
19696 (progn
19697 (goto-char
19698 (org-element-property :end link))
19699 (skip-chars-backward " \t")
19700 (point)))))
19701 (overlay-put ov 'display image)
19702 (overlay-put ov 'face 'default)
19703 (overlay-put ov 'org-image-overlay t)
19704 (overlay-put
19705 ov 'modification-hooks
19706 (list 'org-display-inline-remove-overlay))
19707 (push ov org-inline-image-overlays)))))))))))))))
19709 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19710 "Remove inline-display overlay if a corresponding region is modified."
19711 (let ((inhibit-modification-hooks t))
19712 (when (and ov after)
19713 (delete ov org-inline-image-overlays)
19714 (delete-overlay ov))))
19716 (defun org-remove-inline-images ()
19717 "Remove inline display of images."
19718 (interactive)
19719 (mapc #'delete-overlay org-inline-image-overlays)
19720 (setq org-inline-image-overlays nil))
19722 ;;;; Key bindings
19724 ;; Outline functions from `outline-mode-prefix-map'
19725 ;; that can be remapped in Org:
19726 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19727 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19728 (define-key org-mode-map [remap outline-forward-same-level]
19729 'org-forward-heading-same-level)
19730 (define-key org-mode-map [remap outline-backward-same-level]
19731 'org-backward-heading-same-level)
19732 (define-key org-mode-map [remap outline-show-branches]
19733 'org-kill-note-or-show-branches)
19734 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19735 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19736 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19737 (define-key org-mode-map [remap outline-next-visible-heading]
19738 'org-next-visible-heading)
19739 (define-key org-mode-map [remap outline-previous-visible-heading]
19740 'org-previous-visible-heading)
19741 (define-key org-mode-map [remap show-children] 'org-show-children)
19743 ;; Outline functions from `outline-mode-prefix-map' that can not
19744 ;; be remapped in Org:
19746 ;; - the column "key binding" shows whether the Outline function is still
19747 ;; available in Org mode on the same key that it has been bound to in
19748 ;; Outline mode:
19749 ;; - "overridden": key used for a different functionality in Org mode
19750 ;; - else: key still bound to the same Outline function in Org mode
19752 ;; | Outline function | key binding | Org replacement |
19753 ;; |------------------------------------+-------------+--------------------------|
19754 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19755 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19756 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19757 ;; | `show-entry' | overridden | no replacement |
19758 ;; | `show-branches' | `C-c C-k' | still same function |
19759 ;; | `show-subtree' | overridden | visibility cycling |
19760 ;; | `show-all' | overridden | no replacement |
19761 ;; | `hide-subtree' | overridden | visibility cycling |
19762 ;; | `hide-body' | overridden | no replacement |
19763 ;; | `hide-entry' | overridden | visibility cycling |
19764 ;; | `hide-leaves' | overridden | no replacement |
19765 ;; | `hide-sublevels' | overridden | no replacement |
19766 ;; | `hide-other' | overridden | no replacement |
19768 ;; Make `C-c C-x' a prefix key
19769 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19771 ;; TAB key with modifiers
19772 (org-defkey org-mode-map "\C-i" 'org-cycle)
19773 (org-defkey org-mode-map [(tab)] 'org-cycle)
19774 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19775 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19776 ;; The following line is necessary under Suse GNU/Linux
19777 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19778 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19779 (define-key org-mode-map [backtab] 'org-shifttab)
19781 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19782 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19783 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19785 ;; Cursor keys with modifiers
19786 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19787 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19788 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19789 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19791 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19792 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19793 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19794 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19795 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19796 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19798 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19799 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19800 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19801 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19803 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19804 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19805 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19806 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19808 ;; Babel keys
19809 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19810 (dolist (pair org-babel-key-bindings)
19811 (define-key org-babel-map (car pair) (cdr pair)))
19813 ;;; Extra keys for tty access.
19814 ;; We only set them when really needed because otherwise the
19815 ;; menus don't show the simple keys
19817 (when (or org-use-extra-keys (not window-system))
19818 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19819 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19820 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19821 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19822 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19823 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19824 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19825 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19826 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19827 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19828 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19829 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19830 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19831 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19832 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19833 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19834 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19835 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19836 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19837 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19838 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19839 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19840 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19841 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19842 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19843 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19844 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19845 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19847 ;; All the other keys
19849 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19850 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19851 (if (boundp 'narrow-map)
19852 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19853 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19854 (if (boundp 'narrow-map)
19855 (org-defkey narrow-map "b" 'org-narrow-to-block)
19856 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19857 (if (boundp 'narrow-map)
19858 (org-defkey narrow-map "e" 'org-narrow-to-element)
19859 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19860 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19861 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19862 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19863 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19864 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19865 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19866 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19867 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19868 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19869 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19870 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19871 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19872 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19873 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19874 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19875 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19876 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19877 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19878 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19879 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19880 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19881 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19882 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19883 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19884 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19885 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19886 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19887 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19888 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19889 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19890 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19891 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19892 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19893 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19894 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19895 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19896 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19897 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19898 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19899 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19900 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19901 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19902 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19903 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19904 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19905 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19906 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19907 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19908 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19909 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19910 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19911 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19912 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19913 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19914 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19915 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19916 (org-defkey org-mode-map "\C-c^" 'org-sort)
19917 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19918 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19919 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19920 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19921 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19922 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19923 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19924 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19925 (org-defkey org-mode-map "\C-m" 'org-return)
19926 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19927 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19928 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19929 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19930 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19931 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19932 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19933 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19934 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19935 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19936 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19937 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19938 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19939 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19940 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19941 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19942 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19943 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19944 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19945 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19946 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19947 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19948 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19949 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19950 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19952 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19953 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19954 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19956 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19957 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19958 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19959 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19960 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19961 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19962 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19963 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19964 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19965 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19966 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19967 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19968 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19969 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19970 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19971 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19972 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19973 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19974 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19975 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19976 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19977 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19979 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19980 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19981 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19982 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19983 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19985 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19987 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19989 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19990 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19992 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19995 (defconst org-speed-commands-default
19997 ("Outline Navigation")
19998 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19999 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20000 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20001 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20002 ("F" . org-next-block)
20003 ("B" . org-previous-block)
20004 ("u" . (org-speed-move-safe 'outline-up-heading))
20005 ("j" . org-goto)
20006 ("g" . (org-refile t))
20007 ("Outline Visibility")
20008 ("c" . org-cycle)
20009 ("C" . org-shifttab)
20010 (" " . org-display-outline-path)
20011 ("s" . org-narrow-to-subtree)
20012 ("=" . org-columns)
20013 ("Outline Structure Editing")
20014 ("U" . org-metaup)
20015 ("D" . org-metadown)
20016 ("r" . org-metaright)
20017 ("l" . org-metaleft)
20018 ("R" . org-shiftmetaright)
20019 ("L" . org-shiftmetaleft)
20020 ("i" . (progn (forward-char 1) (call-interactively
20021 'org-insert-heading-respect-content)))
20022 ("^" . org-sort)
20023 ("w" . org-refile)
20024 ("a" . org-archive-subtree-default-with-confirmation)
20025 ("@" . org-mark-subtree)
20026 ("#" . org-toggle-comment)
20027 ("Clock Commands")
20028 ("I" . org-clock-in)
20029 ("O" . org-clock-out)
20030 ("Meta Data Editing")
20031 ("t" . org-todo)
20032 ("," . (org-priority))
20033 ("0" . (org-priority ?\ ))
20034 ("1" . (org-priority ?A))
20035 ("2" . (org-priority ?B))
20036 ("3" . (org-priority ?C))
20037 (":" . org-set-tags-command)
20038 ("e" . org-set-effort)
20039 ("E" . org-inc-effort)
20040 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20041 (org-entry-put (point) "APPT_WARNTIME" m)))
20042 ("Agenda Views etc")
20043 ("v" . org-agenda)
20044 ("/" . org-sparse-tree)
20045 ("Misc")
20046 ("o" . org-open-at-point)
20047 ("?" . org-speed-command-help)
20048 ("<" . (org-agenda-set-restriction-lock 'subtree))
20049 (">" . (org-agenda-remove-restriction-lock))
20051 "The default speed commands.")
20053 (defun org-print-speed-command (e)
20054 (if (> (length (car e)) 1)
20055 (progn
20056 (princ "\n")
20057 (princ (car e))
20058 (princ "\n")
20059 (princ (make-string (length (car e)) ?-))
20060 (princ "\n"))
20061 (princ (car e))
20062 (princ " ")
20063 (if (symbolp (cdr e))
20064 (princ (symbol-name (cdr e)))
20065 (prin1 (cdr e)))
20066 (princ "\n")))
20068 (defun org-speed-command-help ()
20069 "Show the available speed commands."
20070 (interactive)
20071 (if (not org-use-speed-commands)
20072 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20073 (with-output-to-temp-buffer "*Help*"
20074 (princ "User-defined Speed commands\n===========================\n")
20075 (mapc #'org-print-speed-command org-speed-commands-user)
20076 (princ "\n")
20077 (princ "Built-in Speed commands\n=======================\n")
20078 (mapc #'org-print-speed-command org-speed-commands-default))
20079 (with-current-buffer "*Help*"
20080 (setq truncate-lines t))))
20082 (defun org-speed-move-safe (cmd)
20083 "Execute CMD, but make sure that the cursor always ends up in a headline.
20084 If not, return to the original position and throw an error."
20085 (interactive)
20086 (let ((pos (point)))
20087 (call-interactively cmd)
20088 (unless (and (bolp) (org-at-heading-p))
20089 (goto-char pos)
20090 (error "Boundary reached while executing %s" cmd))))
20092 (defvar org-self-insert-command-undo-counter 0)
20094 (defvar org-table-auto-blank-field) ; defined in org-table.el
20095 (defvar org-speed-command nil)
20097 (defun org-speed-command-activate (keys)
20098 "Hook for activating single-letter speed commands.
20099 `org-speed-commands-default' specifies a minimal command set.
20100 Use `org-speed-commands-user' for further customization."
20101 (when (or (and (bolp) (looking-at org-outline-regexp))
20102 (and (functionp org-use-speed-commands)
20103 (funcall org-use-speed-commands)))
20104 (cdr (assoc keys (append org-speed-commands-user
20105 org-speed-commands-default)))))
20107 (defun org-babel-speed-command-activate (keys)
20108 "Hook for activating single-letter code block commands."
20109 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20110 (cdr (assoc keys org-babel-key-bindings))))
20112 (defcustom org-speed-command-hook
20113 '(org-speed-command-default-hook org-babel-speed-command-hook)
20114 "Hook for activating speed commands at strategic locations.
20115 Hook functions are called in sequence until a valid handler is
20116 found.
20118 Each hook takes a single argument, a user-pressed command key
20119 which is also a `self-insert-command' from the global map.
20121 Within the hook, examine the cursor position and the command key
20122 and return nil or a valid handler as appropriate. Handler could
20123 be one of an interactive command, a function, or a form.
20125 Set `org-use-speed-commands' to non-nil value to enable this
20126 hook. The default setting is `org-speed-command-activate'."
20127 :group 'org-structure
20128 :version "24.1"
20129 :type 'hook)
20131 (defun org-self-insert-command (N)
20132 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20133 If the cursor is in a table looking at whitespace, the whitespace is
20134 overwritten, and the table is not marked as requiring realignment."
20135 (interactive "p")
20136 (org-check-before-invisible-edit 'insert)
20137 (cond
20138 ((and org-use-speed-commands
20139 (let ((kv (this-command-keys-vector)))
20140 (setq org-speed-command
20141 (run-hook-with-args-until-success
20142 'org-speed-command-hook
20143 (make-string 1 (aref kv (1- (length kv))))))))
20144 (cond
20145 ((commandp org-speed-command)
20146 (setq this-command org-speed-command)
20147 (call-interactively org-speed-command))
20148 ((functionp org-speed-command)
20149 (funcall org-speed-command))
20150 ((and org-speed-command (listp org-speed-command))
20151 (eval org-speed-command))
20152 (t (let (org-use-speed-commands)
20153 (call-interactively 'org-self-insert-command)))))
20154 ((and
20155 (org-at-table-p)
20156 (progn
20157 ;; Check if we blank the field, and if that triggers align.
20158 (and (featurep 'org-table) org-table-auto-blank-field
20159 (memq last-command
20160 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20161 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20162 ;; Got extra space, this field does not determine
20163 ;; column width.
20164 (let (org-table-may-need-update) (org-table-blank-field))
20165 ;; No extra space, this field may determine column
20166 ;; width.
20167 (org-table-blank-field)))
20169 (eq N 1)
20170 (looking-at "[^|\n]* \\( \\)|"))
20171 ;; There is room for insertion without re-aligning the table.
20172 (delete-region (match-beginning 1) (match-end 1))
20173 (self-insert-command N))
20175 (setq org-table-may-need-update t)
20176 (self-insert-command N)
20177 (org-fix-tags-on-the-fly)
20178 (when org-self-insert-cluster-for-undo
20179 (if (not (eq last-command 'org-self-insert-command))
20180 (setq org-self-insert-command-undo-counter 1)
20181 (if (>= org-self-insert-command-undo-counter 20)
20182 (setq org-self-insert-command-undo-counter 1)
20183 (and (> org-self-insert-command-undo-counter 0)
20184 buffer-undo-list (listp buffer-undo-list)
20185 (not (cadr buffer-undo-list)) ; remove nil entry
20186 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20187 (setq org-self-insert-command-undo-counter
20188 (1+ org-self-insert-command-undo-counter))))))))
20190 (defun org-check-before-invisible-edit (kind)
20191 "Check is editing if kind KIND would be dangerous with invisible text around.
20192 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20193 ;; First, try to get out of here as quickly as possible, to reduce overhead
20194 (when (and org-catch-invisible-edits
20195 (or (not (boundp 'visible-mode)) (not visible-mode))
20196 (or (get-char-property (point) 'invisible)
20197 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20198 ;; OK, we need to take a closer look. Do not consider
20199 ;; invisibility obtained through text properties (e.g., link
20200 ;; fontification), as it cannot be toggled.
20201 (let* ((invisible-at-point
20202 (pcase (get-char-property-and-overlay (point) 'invisible)
20203 (`(,_ . ,(and (pred overlayp) o)) o)))
20204 ;; Assume that point cannot land in the middle of an
20205 ;; overlay, or between two overlays.
20206 (invisible-before-point
20207 (and (not invisible-at-point)
20208 (not (bobp))
20209 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
20210 (`(,_ . ,(and (pred overlayp) o)) o))))
20211 (border-and-ok-direction
20213 ;; Check if we are acting predictably before invisible
20214 ;; text.
20215 (and invisible-at-point
20216 (memq kind '(insert delete-backward)))
20217 ;; Check if we are acting predictably after invisible text
20218 ;; This works not well, and I have turned it off. It seems
20219 ;; better to always show and stop after invisible text.
20220 ;; (and (not invisible-at-point) invisible-before-point
20221 ;; (memq kind '(insert delete)))
20223 (when (or invisible-at-point invisible-before-point)
20224 (when (eq org-catch-invisible-edits 'error)
20225 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20226 (if (and org-custom-properties-overlays
20227 (y-or-n-p "Display invisible properties in this buffer? "))
20228 (org-toggle-custom-properties-visibility)
20229 ;; Make the area visible
20230 (save-excursion
20231 (when invisible-before-point
20232 (goto-char
20233 (previous-single-char-property-change (point) 'invisible)))
20234 ;; Remove whatever overlay is currently making yet-to-be
20235 ;; edited text invisible. Also remove nested invisibility
20236 ;; related overlays.
20237 (delete-overlay (or invisible-at-point invisible-before-point))
20238 (let ((origin (if invisible-at-point (point) (1- (point)))))
20239 (while (pcase (get-char-property-and-overlay origin 'invisible)
20240 (`(,_ . ,(and (pred overlayp) o))
20241 (delete-overlay o)
20242 t)))))
20243 (cond
20244 ((eq org-catch-invisible-edits 'show)
20245 ;; That's it, we do the edit after showing
20246 (message
20247 "Unfolding invisible region around point before editing")
20248 (sit-for 1))
20249 ((and (eq org-catch-invisible-edits 'smart)
20250 border-and-ok-direction)
20251 (message "Unfolding invisible region around point before editing"))
20253 ;; Don't do the edit, make the user repeat it in full visibility
20254 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20256 (defun org-fix-tags-on-the-fly ()
20257 "Align tags in headline at point.
20258 Unlike to `org-set-tags', it ignores region and sorting."
20259 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20260 (org-at-heading-p))
20261 (let ((org-ignore-region t)
20262 (org-tags-sort-function nil))
20263 (org-set-tags nil t))))
20265 (defun org-delete-backward-char (N)
20266 "Like `delete-backward-char', insert whitespace at field end in tables.
20267 When deleting backwards, in tables this function will insert whitespace in
20268 front of the next \"|\" separator, to keep the table aligned. The table will
20269 still be marked for re-alignment if the field did fill the entire column,
20270 because, in this case the deletion might narrow the column."
20271 (interactive "p")
20272 (save-match-data
20273 (org-check-before-invisible-edit 'delete-backward)
20274 (if (and (org-at-table-p)
20275 (eq N 1)
20276 (string-match "|" (buffer-substring (point-at-bol) (point)))
20277 (looking-at ".*?|"))
20278 (let ((pos (point))
20279 (noalign (looking-at "[^|\n\r]* |"))
20280 (c org-table-may-need-update))
20281 (backward-delete-char N)
20282 (unless overwrite-mode
20283 (skip-chars-forward "^|")
20284 (insert " ")
20285 (goto-char (1- pos)))
20286 ;; noalign: if there were two spaces at the end, this field
20287 ;; does not determine the width of the column.
20288 (when noalign (setq org-table-may-need-update c)))
20289 (backward-delete-char N)
20290 (org-fix-tags-on-the-fly))))
20292 (defun org-delete-char (N)
20293 "Like `delete-char', but insert whitespace at field end in tables.
20294 When deleting characters, in tables this function will insert whitespace in
20295 front of the next \"|\" separator, to keep the table aligned. The table will
20296 still be marked for re-alignment if the field did fill the entire column,
20297 because, in this case the deletion might narrow the column."
20298 (interactive "p")
20299 (save-match-data
20300 (org-check-before-invisible-edit 'delete)
20301 (if (and (org-at-table-p)
20302 (not (bolp))
20303 (not (= (char-after) ?|))
20304 (eq N 1))
20305 (if (looking-at ".*?|")
20306 (let ((pos (point))
20307 (noalign (looking-at "[^|\n\r]* |"))
20308 (c org-table-may-need-update))
20309 (replace-match
20310 (concat (substring (match-string 0) 1 -1) " |") nil t)
20311 (goto-char pos)
20312 ;; noalign: if there were two spaces at the end, this field
20313 ;; does not determine the width of the column.
20314 (when noalign (setq org-table-may-need-update c)))
20315 (delete-char N))
20316 (delete-char N)
20317 (org-fix-tags-on-the-fly))))
20319 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20320 (put 'org-self-insert-command 'delete-selection
20321 (lambda ()
20322 (not (run-hook-with-args-until-success
20323 'self-insert-uses-region-functions))))
20324 (put 'orgtbl-self-insert-command 'delete-selection
20325 (lambda ()
20326 (not (run-hook-with-args-until-success
20327 'self-insert-uses-region-functions))))
20328 (put 'org-delete-char 'delete-selection 'supersede)
20329 (put 'org-delete-backward-char 'delete-selection 'supersede)
20330 (put 'org-yank 'delete-selection 'yank)
20332 ;; Make `flyspell-mode' delay after some commands
20333 (put 'org-self-insert-command 'flyspell-delayed t)
20334 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20335 (put 'org-delete-char 'flyspell-delayed t)
20336 (put 'org-delete-backward-char 'flyspell-delayed t)
20338 ;; Make pabbrev-mode expand after Org mode commands
20339 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20340 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20342 (defun org-remap (map &rest commands)
20343 "In MAP, remap the functions given in COMMANDS.
20344 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20345 (let (new old)
20346 (while commands
20347 (setq old (pop commands) new (pop commands))
20348 (org-defkey map (vector 'remap old) new))))
20350 (defun org-transpose-words ()
20351 "Transpose words for Org.
20352 This uses the `org-mode-transpose-word-syntax-table' syntax
20353 table, which interprets characters in `org-emphasis-alist' as
20354 word constituents."
20355 (interactive)
20356 (with-syntax-table org-mode-transpose-word-syntax-table
20357 (call-interactively 'transpose-words)))
20358 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20360 (when (eq org-enable-table-editor 'optimized)
20361 ;; If the user wants maximum table support, we need to hijack
20362 ;; some standard editing functions
20363 (org-remap org-mode-map
20364 'self-insert-command 'org-self-insert-command
20365 'delete-char 'org-delete-char
20366 'delete-backward-char 'org-delete-backward-char)
20367 (org-defkey org-mode-map "|" 'org-force-self-insert))
20369 (defvar org-ctrl-c-ctrl-c-hook nil
20370 "Hook for functions attaching themselves to `C-c C-c'.
20372 This can be used to add additional functionality to the C-c C-c
20373 key which executes context-dependent commands. This hook is run
20374 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20375 run after the last test.
20377 Each function will be called with no arguments. The function
20378 must check if the context is appropriate for it to act. If yes,
20379 it should do its thing and then return a non-nil value. If the
20380 context is wrong, just do nothing and return nil.")
20382 (defvar org-ctrl-c-ctrl-c-final-hook nil
20383 "Hook for functions attaching themselves to `C-c C-c'.
20385 This can be used to add additional functionality to the C-c C-c
20386 key which executes context-dependent commands. This hook is run
20387 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20388 before the first test.
20390 Each function will be called with no arguments. The function
20391 must check if the context is appropriate for it to act. If yes,
20392 it should do its thing and then return a non-nil value. If the
20393 context is wrong, just do nothing and return nil.")
20395 (defvar org-tab-first-hook nil
20396 "Hook for functions to attach themselves to TAB.
20397 See `org-ctrl-c-ctrl-c-hook' for more information.
20398 This hook runs as the first action when TAB is pressed, even before
20399 `org-cycle' messes around with the `outline-regexp' to cater for
20400 inline tasks and plain list item folding.
20401 If any function in this hook returns t, any other actions that
20402 would have been caused by TAB (such as table field motion or visibility
20403 cycling) will not occur.")
20405 (defvar org-tab-after-check-for-table-hook nil
20406 "Hook for functions to attach themselves to TAB.
20407 See `org-ctrl-c-ctrl-c-hook' for more information.
20408 This hook runs after it has been established that the cursor is not in a
20409 table, but before checking if the cursor is in a headline or if global cycling
20410 should be done.
20411 If any function in this hook returns t, not other actions like visibility
20412 cycling will be done.")
20414 (defvar org-tab-after-check-for-cycling-hook nil
20415 "Hook for functions to attach themselves to TAB.
20416 See `org-ctrl-c-ctrl-c-hook' for more information.
20417 This hook runs after it has been established that not table field motion and
20418 not visibility should be done because of current context. This is probably
20419 the place where a package like yasnippets can hook in.")
20421 (defvar org-tab-before-tab-emulation-hook nil
20422 "Hook for functions to attach themselves to TAB.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.
20424 This hook runs after every other options for TAB have been exhausted, but
20425 before indentation and \t insertion takes place.")
20427 (defvar org-metaleft-hook nil
20428 "Hook for functions attaching themselves to `M-left'.
20429 See `org-ctrl-c-ctrl-c-hook' for more information.")
20430 (defvar org-metaright-hook nil
20431 "Hook for functions attaching themselves to `M-right'.
20432 See `org-ctrl-c-ctrl-c-hook' for more information.")
20433 (defvar org-metaup-hook nil
20434 "Hook for functions attaching themselves to `M-up'.
20435 See `org-ctrl-c-ctrl-c-hook' for more information.")
20436 (defvar org-metadown-hook nil
20437 "Hook for functions attaching themselves to `M-down'.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.")
20439 (defvar org-shiftmetaleft-hook nil
20440 "Hook for functions attaching themselves to `M-S-left'.
20441 See `org-ctrl-c-ctrl-c-hook' for more information.")
20442 (defvar org-shiftmetaright-hook nil
20443 "Hook for functions attaching themselves to `M-S-right'.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-shiftmetaup-hook nil
20446 "Hook for functions attaching themselves to `M-S-up'.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-shiftmetadown-hook nil
20449 "Hook for functions attaching themselves to `M-S-down'.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-metareturn-hook nil
20452 "Hook for functions attaching themselves to `M-RET'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftup-hook nil
20455 "Hook for functions attaching themselves to `S-up'.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-shiftup-final-hook nil
20458 "Hook for functions attaching themselves to `S-up'.
20459 This one runs after all other options except shift-select have been excluded.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftdown-hook nil
20462 "Hook for functions attaching themselves to `S-down'.
20463 See `org-ctrl-c-ctrl-c-hook' for more information.")
20464 (defvar org-shiftdown-final-hook nil
20465 "Hook for functions attaching themselves to `S-down'.
20466 This one runs after all other options except shift-select have been excluded.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftleft-hook nil
20469 "Hook for functions attaching themselves to `S-left'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-shiftleft-final-hook nil
20472 "Hook for functions attaching themselves to `S-left'.
20473 This one runs after all other options except shift-select have been excluded.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-shiftright-hook nil
20476 "Hook for functions attaching themselves to `S-right'.
20477 See `org-ctrl-c-ctrl-c-hook' for more information.")
20478 (defvar org-shiftright-final-hook nil
20479 "Hook for functions attaching themselves to `S-right'.
20480 This one runs after all other options except shift-select have been excluded.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.")
20483 (defun org-modifier-cursor-error ()
20484 "Throw an error, a modified cursor command was applied in wrong context."
20485 (user-error "This command is active in special context like tables, headlines or items"))
20487 (defun org-shiftselect-error ()
20488 "Throw an error because Shift-Cursor command was applied in wrong context."
20489 (if (and (boundp 'shift-select-mode) shift-select-mode)
20490 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20491 (user-error "This command works only in special context like headlines or timestamps")))
20493 (defun org-call-for-shift-select (cmd)
20494 (let ((this-command-keys-shift-translated t))
20495 (call-interactively cmd)))
20497 (defun org-shifttab (&optional arg)
20498 "Global visibility cycling or move to previous table field.
20499 Call `org-table-previous-field' within a table.
20500 When ARG is nil, cycle globally through visibility states.
20501 When ARG is a numeric prefix, show contents of this level."
20502 (interactive "P")
20503 (cond
20504 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20505 ((integerp arg)
20506 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20507 (message "Content view to level: %d" arg)
20508 (org-content (prefix-numeric-value arg2))
20509 (org-cycle-show-empty-lines t)
20510 (setq org-cycle-global-status 'overview)))
20511 (t (call-interactively 'org-global-cycle))))
20513 (defun org-shiftmetaleft ()
20514 "Promote subtree or delete table column.
20515 Calls `org-promote-subtree', `org-outdent-item-tree', or
20516 `org-table-delete-column', depending on context. See the
20517 individual commands for more information."
20518 (interactive)
20519 (cond
20520 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20521 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20522 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20523 ((if (not (org-region-active-p)) (org-at-item-p)
20524 (save-excursion (goto-char (region-beginning))
20525 (org-at-item-p)))
20526 (call-interactively 'org-outdent-item-tree))
20527 (t (org-modifier-cursor-error))))
20529 (defun org-shiftmetaright ()
20530 "Demote subtree or insert table column.
20531 Calls `org-demote-subtree', `org-indent-item-tree', or
20532 `org-table-insert-column', depending on context. See the
20533 individual commands for more information."
20534 (interactive)
20535 (cond
20536 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20537 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20538 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20539 ((if (not (org-region-active-p)) (org-at-item-p)
20540 (save-excursion (goto-char (region-beginning))
20541 (org-at-item-p)))
20542 (call-interactively 'org-indent-item-tree))
20543 (t (org-modifier-cursor-error))))
20545 (defun org-shiftmetaup (&optional _arg)
20546 "Drag the line at point up.
20547 In a table, kill the current row.
20548 On a clock timestamp, update the value of the timestamp like `S-<up>'
20549 but also adjust the previous clocked item in the clock history.
20550 Everywhere else, drag the line at point up."
20551 (interactive "P")
20552 (cond
20553 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20554 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20555 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20556 (call-interactively 'org-timestamp-up)))
20557 (t (call-interactively 'org-drag-line-backward))))
20559 (defun org-shiftmetadown (&optional _arg)
20560 "Drag the line at point down.
20561 In a table, insert an empty row at the current line.
20562 On a clock timestamp, update the value of the timestamp like `S-<down>'
20563 but also adjust the previous clocked item in the clock history.
20564 Everywhere else, drag the line at point down."
20565 (interactive "P")
20566 (cond
20567 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20568 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20569 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20570 (call-interactively 'org-timestamp-down)))
20571 (t (call-interactively 'org-drag-line-forward))))
20573 (defsubst org-hidden-tree-error ()
20574 (user-error
20575 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20577 (defun org-metaleft (&optional _arg)
20578 "Promote heading, list item at point or move table column left.
20580 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20581 depending on context. With no specific context, calls the Emacs
20582 default `backward-word'. See the individual commands for more
20583 information.
20585 This function runs the hook `org-metaleft-hook' as a first step,
20586 and returns at first non-nil value."
20587 (interactive "P")
20588 (cond
20589 ((run-hook-with-args-until-success 'org-metaleft-hook))
20590 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20591 ((org-with-limited-levels
20592 (or (org-at-heading-p)
20593 (and (org-region-active-p)
20594 (save-excursion
20595 (goto-char (region-beginning))
20596 (org-at-heading-p)))))
20597 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20598 (call-interactively 'org-do-promote))
20599 ;; At an inline task.
20600 ((org-at-heading-p)
20601 (call-interactively 'org-inlinetask-promote))
20602 ((or (org-at-item-p)
20603 (and (org-region-active-p)
20604 (save-excursion
20605 (goto-char (region-beginning))
20606 (org-at-item-p))))
20607 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20608 (call-interactively 'org-outdent-item))
20609 (t (call-interactively 'backward-word))))
20611 (defun org-metaright (&optional _arg)
20612 "Demote heading, list item at point or move table column right.
20614 In front of a drawer or a block keyword, indent it correctly.
20616 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20617 `org-indent-drawer' or `org-indent-block' depending on context.
20618 With no specific context, calls the Emacs default `forward-word'.
20619 See the individual commands for more information.
20621 This function runs the hook `org-metaright-hook' as a first step,
20622 and returns at first non-nil value."
20623 (interactive "P")
20624 (cond
20625 ((run-hook-with-args-until-success 'org-metaright-hook))
20626 ((org-at-table-p) (call-interactively 'org-table-move-column))
20627 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20628 ((org-at-block-p) (call-interactively 'org-indent-block))
20629 ((org-with-limited-levels
20630 (or (org-at-heading-p)
20631 (and (org-region-active-p)
20632 (save-excursion
20633 (goto-char (region-beginning))
20634 (org-at-heading-p)))))
20635 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20636 (call-interactively 'org-do-demote))
20637 ;; At an inline task.
20638 ((org-at-heading-p)
20639 (call-interactively 'org-inlinetask-demote))
20640 ((or (org-at-item-p)
20641 (and (org-region-active-p)
20642 (save-excursion
20643 (goto-char (region-beginning))
20644 (org-at-item-p))))
20645 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20646 (call-interactively 'org-indent-item))
20647 (t (call-interactively 'forward-word))))
20649 (defun org-check-for-hidden (what)
20650 "Check if there are hidden headlines/items in the current visual line.
20651 WHAT can be either `headlines' or `items'. If the current line is
20652 an outline or item heading and it has a folded subtree below it,
20653 this function returns t, nil otherwise."
20654 (let ((re (cond
20655 ((eq what 'headlines) org-outline-regexp-bol)
20656 ((eq what 'items) (org-item-beginning-re))
20657 (t (error "This should not happen"))))
20658 beg end)
20659 (save-excursion
20660 (catch 'exit
20661 (unless (org-region-active-p)
20662 (setq beg (point-at-bol))
20663 (beginning-of-line 2)
20664 (while (and (not (eobp)) ;; this is like `next-line'
20665 (get-char-property (1- (point)) 'invisible))
20666 (beginning-of-line 2))
20667 (setq end (point))
20668 (goto-char beg)
20669 (goto-char (point-at-eol))
20670 (setq end (max end (point)))
20671 (while (re-search-forward re end t)
20672 (when (get-char-property (match-beginning 0) 'invisible)
20673 (throw 'exit t))))
20674 nil))))
20676 (defun org-metaup (&optional _arg)
20677 "Move subtree up or move table row up.
20678 Calls `org-move-subtree-up' or `org-table-move-row' or
20679 `org-move-item-up', depending on context. See the individual commands
20680 for more information."
20681 (interactive "P")
20682 (cond
20683 ((run-hook-with-args-until-success 'org-metaup-hook))
20684 ((org-region-active-p)
20685 (let* ((a (min (region-beginning) (region-end)))
20686 (b (1- (max (region-beginning) (region-end))))
20687 (c (save-excursion (goto-char a)
20688 (move-beginning-of-line 0)))
20689 (d (save-excursion (goto-char a)
20690 (move-end-of-line 0) (point))))
20691 (transpose-regions a b c d)
20692 (goto-char c)))
20693 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20694 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20695 ((org-at-item-p) (call-interactively 'org-move-item-up))
20696 (t (org-drag-element-backward))))
20698 (defun org-metadown (&optional _arg)
20699 "Move subtree down or move table row down.
20700 Calls `org-move-subtree-down' or `org-table-move-row' or
20701 `org-move-item-down', depending on context. See the individual
20702 commands for more information."
20703 (interactive "P")
20704 (cond
20705 ((run-hook-with-args-until-success 'org-metadown-hook))
20706 ((org-region-active-p)
20707 (let* ((a (min (region-beginning) (region-end)))
20708 (b (max (region-beginning) (region-end)))
20709 (c (save-excursion (goto-char b)
20710 (move-beginning-of-line 1)))
20711 (d (save-excursion (goto-char b)
20712 (move-end-of-line 1) (1+ (point)))))
20713 (transpose-regions a b c d)
20714 (goto-char d)))
20715 ((org-at-table-p) (call-interactively 'org-table-move-row))
20716 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20717 ((org-at-item-p) (call-interactively 'org-move-item-down))
20718 (t (org-drag-element-forward))))
20720 (defun org-shiftup (&optional arg)
20721 "Increase item in timestamp or increase priority of current headline.
20722 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20723 depending on context. See the individual commands for more information."
20724 (interactive "P")
20725 (cond
20726 ((run-hook-with-args-until-success 'org-shiftup-hook))
20727 ((and org-support-shift-select (org-region-active-p))
20728 (org-call-for-shift-select 'previous-line))
20729 ((org-at-timestamp-p t)
20730 (call-interactively (if org-edit-timestamp-down-means-later
20731 'org-timestamp-down 'org-timestamp-up)))
20732 ((and (not (eq org-support-shift-select 'always))
20733 org-enable-priority-commands
20734 (org-at-heading-p))
20735 (call-interactively 'org-priority-up))
20736 ((and (not org-support-shift-select) (org-at-item-p))
20737 (call-interactively 'org-previous-item))
20738 ((org-clocktable-try-shift 'up arg))
20739 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20740 (org-support-shift-select
20741 (org-call-for-shift-select 'previous-line))
20742 (t (org-shiftselect-error))))
20744 (defun org-shiftdown (&optional arg)
20745 "Decrease item in timestamp or decrease priority of current headline.
20746 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20747 depending on context. See the individual commands for more information."
20748 (interactive "P")
20749 (cond
20750 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20751 ((and org-support-shift-select (org-region-active-p))
20752 (org-call-for-shift-select 'next-line))
20753 ((org-at-timestamp-p t)
20754 (call-interactively (if org-edit-timestamp-down-means-later
20755 'org-timestamp-up 'org-timestamp-down)))
20756 ((and (not (eq org-support-shift-select 'always))
20757 org-enable-priority-commands
20758 (org-at-heading-p))
20759 (call-interactively 'org-priority-down))
20760 ((and (not org-support-shift-select) (org-at-item-p))
20761 (call-interactively 'org-next-item))
20762 ((org-clocktable-try-shift 'down arg))
20763 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20764 (org-support-shift-select
20765 (org-call-for-shift-select 'next-line))
20766 (t (org-shiftselect-error))))
20768 (defun org-shiftright (&optional arg)
20769 "Cycle the thing at point or in the current line, depending on context.
20770 Depending on context, this does one of the following:
20772 - switch a timestamp at point one day into the future
20773 - on a headline, switch to the next TODO keyword.
20774 - on an item, switch entire list to the next bullet type
20775 - on a property line, switch to the next allowed value
20776 - on a clocktable definition line, move time block into the future"
20777 (interactive "P")
20778 (cond
20779 ((run-hook-with-args-until-success 'org-shiftright-hook))
20780 ((and org-support-shift-select (org-region-active-p))
20781 (org-call-for-shift-select 'forward-char))
20782 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20783 ((and (not (eq org-support-shift-select 'always))
20784 (org-at-heading-p))
20785 (let ((org-inhibit-logging
20786 (not org-treat-S-cursor-todo-selection-as-state-change))
20787 (org-inhibit-blocking
20788 (not org-treat-S-cursor-todo-selection-as-state-change)))
20789 (org-call-with-arg 'org-todo 'right)))
20790 ((or (and org-support-shift-select
20791 (not (eq org-support-shift-select 'always))
20792 (org-at-item-bullet-p))
20793 (and (not org-support-shift-select) (org-at-item-p)))
20794 (org-call-with-arg 'org-cycle-list-bullet nil))
20795 ((and (not (eq org-support-shift-select 'always))
20796 (org-at-property-p))
20797 (call-interactively 'org-property-next-allowed-value))
20798 ((org-clocktable-try-shift 'right arg))
20799 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20800 (org-support-shift-select
20801 (org-call-for-shift-select 'forward-char))
20802 (t (org-shiftselect-error))))
20804 (defun org-shiftleft (&optional arg)
20805 "Cycle the thing at point or in the current line, depending on context.
20806 Depending on context, this does one of the following:
20808 - switch a timestamp at point one day into the past
20809 - on a headline, switch to the previous TODO keyword.
20810 - on an item, switch entire list to the previous bullet type
20811 - on a property line, switch to the previous allowed value
20812 - on a clocktable definition line, move time block into the past"
20813 (interactive "P")
20814 (cond
20815 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20816 ((and org-support-shift-select (org-region-active-p))
20817 (org-call-for-shift-select 'backward-char))
20818 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20819 ((and (not (eq org-support-shift-select 'always))
20820 (org-at-heading-p))
20821 (let ((org-inhibit-logging
20822 (not org-treat-S-cursor-todo-selection-as-state-change))
20823 (org-inhibit-blocking
20824 (not org-treat-S-cursor-todo-selection-as-state-change)))
20825 (org-call-with-arg 'org-todo 'left)))
20826 ((or (and org-support-shift-select
20827 (not (eq org-support-shift-select 'always))
20828 (org-at-item-bullet-p))
20829 (and (not org-support-shift-select) (org-at-item-p)))
20830 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20831 ((and (not (eq org-support-shift-select 'always))
20832 (org-at-property-p))
20833 (call-interactively 'org-property-previous-allowed-value))
20834 ((org-clocktable-try-shift 'left arg))
20835 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20836 (org-support-shift-select
20837 (org-call-for-shift-select 'backward-char))
20838 (t (org-shiftselect-error))))
20840 (defun org-shiftcontrolright ()
20841 "Switch to next TODO set."
20842 (interactive)
20843 (cond
20844 ((and org-support-shift-select (org-region-active-p))
20845 (org-call-for-shift-select 'forward-word))
20846 ((and (not (eq org-support-shift-select 'always))
20847 (org-at-heading-p))
20848 (org-call-with-arg 'org-todo 'nextset))
20849 (org-support-shift-select
20850 (org-call-for-shift-select 'forward-word))
20851 (t (org-shiftselect-error))))
20853 (defun org-shiftcontrolleft ()
20854 "Switch to previous TODO set."
20855 (interactive)
20856 (cond
20857 ((and org-support-shift-select (org-region-active-p))
20858 (org-call-for-shift-select 'backward-word))
20859 ((and (not (eq org-support-shift-select 'always))
20860 (org-at-heading-p))
20861 (org-call-with-arg 'org-todo 'previousset))
20862 (org-support-shift-select
20863 (org-call-for-shift-select 'backward-word))
20864 (t (org-shiftselect-error))))
20866 (defun org-shiftcontrolup (&optional n)
20867 "Change timestamps synchronously up in CLOCK log lines.
20868 Optional argument N tells to change by that many units."
20869 (interactive "P")
20870 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20871 (let (org-support-shift-select)
20872 (org-clock-timestamps-up n))
20873 (user-error "Not at a clock log")))
20875 (defun org-shiftcontroldown (&optional n)
20876 "Change timestamps synchronously down in CLOCK log lines.
20877 Optional argument N tells to change by that many units."
20878 (interactive "P")
20879 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20880 (let (org-support-shift-select)
20881 (org-clock-timestamps-down n))
20882 (user-error "Not at a clock log")))
20884 (defun org-increase-number-at-point (&optional inc)
20885 "Increment the number at point.
20886 With an optional prefix numeric argument INC, increment using
20887 this numeric value."
20888 (interactive "p")
20889 (if (not (number-at-point))
20890 (user-error "Not on a number")
20891 (unless inc (setq inc 1))
20892 (let ((pos (point))
20893 (beg (skip-chars-backward "-+^/*0-9eE."))
20894 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20895 (setq nap (buffer-substring-no-properties
20896 (+ pos beg) (+ pos beg end)))
20897 (delete-region (+ pos beg) (+ pos beg end))
20898 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20899 (when (org-at-table-p)
20900 (org-table-align)
20901 (org-table-end-of-field 1))))
20903 (defun org-decrease-number-at-point (&optional inc)
20904 "Decrement the number at point.
20905 With an optional prefix numeric argument INC, decrement using
20906 this numeric value."
20907 (interactive "p")
20908 (org-increase-number-at-point (- (or inc 1))))
20910 (defun org-ctrl-c-ret ()
20911 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20912 (interactive)
20913 (cond
20914 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20915 (t (call-interactively 'org-insert-heading))))
20917 (defun org-find-visible ()
20918 (let ((s (point)))
20919 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20920 (get-char-property s 'invisible)))
20922 (defun org-find-invisible ()
20923 (let ((s (point)))
20924 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20925 (not (get-char-property s 'invisible))))
20928 (defun org-copy-visible (beg end)
20929 "Copy the visible parts of the region."
20930 (interactive "r")
20931 (let (snippets s)
20932 (save-excursion
20933 (save-restriction
20934 (narrow-to-region beg end)
20935 (setq s (goto-char (point-min)))
20936 (while (not (= (point) (point-max)))
20937 (goto-char (org-find-invisible))
20938 (push (buffer-substring s (point)) snippets)
20939 (setq s (goto-char (org-find-visible))))))
20940 (kill-new (apply 'concat (nreverse snippets)))))
20942 (defun org-copy-special ()
20943 "Copy region in table or copy current subtree.
20944 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20945 context. See the individual commands for more information."
20946 (interactive)
20947 (call-interactively
20948 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20950 (defun org-cut-special ()
20951 "Cut region in table or cut current subtree.
20952 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20953 context. See the individual commands for more information."
20954 (interactive)
20955 (call-interactively
20956 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20958 (defun org-paste-special (arg)
20959 "Paste rectangular region into table, or past subtree relative to level.
20960 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20961 See the individual commands for more information."
20962 (interactive "P")
20963 (if (org-at-table-p)
20964 (org-table-paste-rectangle)
20965 (org-paste-subtree arg)))
20967 (defun org-edit-special (&optional arg)
20968 "Call a special editor for the element at point.
20969 When at a table, call the formula editor with `org-table-edit-formulas'.
20970 When in a source code block, call `org-edit-src-code'.
20971 When in a fixed-width region, call `org-edit-fixed-width-region'.
20972 When in an export block, call `org-edit-export-block'.
20973 When at an #+INCLUDE keyword, visit the included file.
20974 When at a footnote reference, call `org-edit-footnote-reference'
20975 On a link, call `ffap' to visit the link at point.
20976 Otherwise, return a user error."
20977 (interactive "P")
20978 (let ((element (org-element-at-point)))
20979 (barf-if-buffer-read-only)
20980 (pcase (org-element-type element)
20981 (`src-block
20982 (if (not arg) (org-edit-src-code)
20983 (let* ((info (org-babel-get-src-block-info))
20984 (lang (nth 0 info))
20985 (params (nth 2 info))
20986 (session (cdr (assq :session params))))
20987 (if (not session) (org-edit-src-code)
20988 ;; At a src-block with a session and function called with
20989 ;; an ARG: switch to the buffer related to the inferior
20990 ;; process.
20991 (switch-to-buffer
20992 (funcall (intern (concat "org-babel-prep-session:" lang))
20993 session params))))))
20994 (`keyword
20995 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20996 (org-open-link-from-string
20997 (format "[[%s]]"
20998 (expand-file-name
20999 (let ((value (org-element-property :value element)))
21000 (cond ((not (org-string-nw-p value))
21001 (user-error "No file to edit"))
21002 ((string-match "\\`\"\\(.*?\\)\"" value)
21003 (match-string 1 value))
21004 ((string-match "\\`[^ \t\"]\\S-*" value)
21005 (match-string 0 value))
21006 (t (user-error "No valid file specified")))))))
21007 (user-error "No special environment to edit here")))
21008 (`table
21009 (if (eq (org-element-property :type element) 'table.el)
21010 (org-edit-table.el)
21011 (call-interactively 'org-table-edit-formulas)))
21012 ;; Only Org tables contain `table-row' type elements.
21013 (`table-row (call-interactively 'org-table-edit-formulas))
21014 (`example-block (org-edit-src-code))
21015 (`export-block (org-edit-export-block))
21016 (`fixed-width (org-edit-fixed-width-region))
21018 ;; No notable element at point. Though, we may be at a link or
21019 ;; a footnote reference, which are objects. Thus, scan deeper.
21020 (let ((context (org-element-context element)))
21021 (pcase (org-element-type context)
21022 (`footnote-reference (org-edit-footnote-reference))
21023 (`inline-src-block (org-edit-inline-src-code))
21024 (`link (call-interactively #'ffap))
21025 (_ (user-error "No special environment to edit here"))))))))
21027 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21028 (defun org-ctrl-c-ctrl-c (&optional arg)
21029 "Set tags in headline, or update according to changed information at point.
21031 This command does many different things, depending on context:
21033 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21034 this is what we do.
21036 - If the cursor is on a statistics cookie, update it.
21038 - If the cursor is in a headline, prompt for tags and insert them
21039 into the current line, aligned to `org-tags-column'. When called
21040 with prefix arg, realign all tags in the current buffer.
21042 - If the cursor is in one of the special #+KEYWORD lines, this
21043 triggers scanning the buffer for these lines and updating the
21044 information.
21046 - If the cursor is inside a table, realign the table. This command
21047 works even if the automatic table editor has been turned off.
21049 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21050 the entire table.
21052 - If the cursor is at a footnote reference or definition, jump to
21053 the corresponding definition or references, respectively.
21055 - If the cursor is a the beginning of a dynamic block, update it.
21057 - If the current buffer is a capture buffer, close note and file it.
21059 - If the cursor is on a <<<target>>>, update radio targets and
21060 corresponding links in this buffer.
21062 - If the cursor is on a numbered item in a plain list, renumber the
21063 ordered list.
21065 - If the cursor is on a checkbox, toggle it.
21067 - If the cursor is on a code block, evaluate it. The variable
21068 `org-confirm-babel-evaluate' can be used to control prompting
21069 before code block evaluation, by default every code block
21070 evaluation requires confirmation. Code block evaluation can be
21071 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21072 (interactive "P")
21073 (cond
21074 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21075 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21076 (org-remove-occur-highlights)
21077 (message "Temporary highlights/overlays removed from current buffer"))
21078 ((and (local-variable-p 'org-finish-function)
21079 (fboundp org-finish-function))
21080 (funcall org-finish-function))
21081 ((org-babel-hash-at-point))
21082 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21084 (let* ((context
21085 (org-element-lineage
21086 (org-element-context)
21087 ;; Limit to supported contexts.
21088 '(babel-call clock dynamic-block footnote-definition
21089 footnote-reference inline-babel-call inline-src-block
21090 inlinetask item keyword node-property paragraph
21091 plain-list property-drawer radio-target src-block
21092 statistics-cookie table table-cell table-row
21093 timestamp)
21095 (type (org-element-type context)))
21096 ;; For convenience: at the first line of a paragraph on the same
21097 ;; line as an item, apply function on that item instead.
21098 (when (eq type 'paragraph)
21099 (let ((parent (org-element-property :parent context)))
21100 (when (and (eq (org-element-type parent) 'item)
21101 (= (line-beginning-position)
21102 (org-element-property :begin parent)))
21103 (setq context parent)
21104 (setq type 'item))))
21105 ;; Act according to type of element or object at point.
21107 ;; Do nothing on a blank line, except if it is contained in
21108 ;; a src block. Hence, we first check if point is in such
21109 ;; a block and then if it is at a blank line.
21110 (pcase type
21111 ((or `inline-src-block `src-block)
21112 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21113 (org-babel-eval-wipe-error-buffer)
21114 (org-babel-execute-src-block
21115 current-prefix-arg (org-babel-get-src-block-info nil context))))
21116 ((guard (org-match-line "[ \t]*$"))
21117 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21118 (user-error
21119 (substitute-command-keys
21120 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21121 ((or `babel-call `inline-babel-call)
21122 (let ((info (org-babel-lob-get-info context)))
21123 (when info (org-babel-execute-src-block nil info))))
21124 (`clock (org-clock-update-time-maybe))
21125 (`dynamic-block
21126 (save-excursion
21127 (goto-char (org-element-property :post-affiliated context))
21128 (org-update-dblock)))
21129 (`footnote-definition
21130 (goto-char (org-element-property :post-affiliated context))
21131 (call-interactively 'org-footnote-action))
21132 (`footnote-reference (call-interactively #'org-footnote-action))
21133 ((or `headline `inlinetask)
21134 (save-excursion (goto-char (org-element-property :begin context))
21135 (call-interactively #'org-set-tags)))
21136 (`item
21137 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21138 ;; unconditionally, whereas `C-u' will toggle its presence.
21139 ;; Without a universal argument, if the item has a checkbox,
21140 ;; toggle it. Otherwise repair the list.
21141 (let* ((box (org-element-property :checkbox context))
21142 (struct (org-element-property :structure context))
21143 (old-struct (copy-tree struct))
21144 (parents (org-list-parents-alist struct))
21145 (prevs (org-list-prevs-alist struct))
21146 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21147 (org-list-set-checkbox
21148 (org-element-property :begin context) struct
21149 (cond ((equal arg '(16)) "[-]")
21150 ((and (not box) (equal arg '(4))) "[ ]")
21151 ((or (not box) (equal arg '(4))) nil)
21152 ((eq box 'on) "[ ]")
21153 (t "[X]")))
21154 ;; Mimic `org-list-write-struct' but with grabbing a return
21155 ;; value from `org-list-struct-fix-box'.
21156 (org-list-struct-fix-ind struct parents 2)
21157 (org-list-struct-fix-item-end struct)
21158 (org-list-struct-fix-bul struct prevs)
21159 (org-list-struct-fix-ind struct parents)
21160 (let ((block-item
21161 (org-list-struct-fix-box struct parents prevs orderedp)))
21162 (if (and box (equal struct old-struct))
21163 (if (equal arg '(16))
21164 (message "Checkboxes already reset")
21165 (user-error "Cannot toggle this checkbox: %s"
21166 (if (eq box 'on)
21167 "all subitems checked"
21168 "unchecked subitems")))
21169 (org-list-struct-apply-struct struct old-struct)
21170 (org-update-checkbox-count-maybe))
21171 (when block-item
21172 (message "Checkboxes were removed due to empty box at line %d"
21173 (org-current-line block-item))))))
21174 (`keyword
21175 (let ((org-inhibit-startup-visibility-stuff t)
21176 (org-startup-align-all-tables nil))
21177 (when (boundp 'org-table-coordinate-overlays)
21178 (mapc #'delete-overlay org-table-coordinate-overlays)
21179 (setq org-table-coordinate-overlays nil))
21180 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21181 (message "Local setup has been refreshed"))
21182 (`plain-list
21183 ;; At a plain list, with a double C-u argument, set
21184 ;; checkboxes of each item to "[-]", whereas a single one
21185 ;; will toggle their presence according to the state of the
21186 ;; first item in the list. Without an argument, repair the
21187 ;; list.
21188 (let* ((begin (org-element-property :contents-begin context))
21189 (beginm (move-marker (make-marker) begin))
21190 (struct (org-element-property :structure context))
21191 (old-struct (copy-tree struct))
21192 (first-box (save-excursion
21193 (goto-char begin)
21194 (looking-at org-list-full-item-re)
21195 (match-string-no-properties 3)))
21196 (new-box (cond ((equal arg '(16)) "[-]")
21197 ((equal arg '(4)) (unless first-box "[ ]"))
21198 ((equal first-box "[X]") "[ ]")
21199 (t "[X]"))))
21200 (cond
21201 (arg
21202 (dolist (pos
21203 (org-list-get-all-items
21204 begin struct (org-list-prevs-alist struct)))
21205 (org-list-set-checkbox pos struct new-box)))
21206 ((and first-box (eq (point) begin))
21207 ;; For convenience, when point is at bol on the first
21208 ;; item of the list and no argument is provided, simply
21209 ;; toggle checkbox of that item, if any.
21210 (org-list-set-checkbox begin struct new-box)))
21211 (org-list-write-struct
21212 struct (org-list-parents-alist struct) old-struct)
21213 (org-update-checkbox-count-maybe)
21214 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21215 ((or `property-drawer `node-property)
21216 (call-interactively #'org-property-action))
21217 (`radio-target
21218 (call-interactively #'org-update-radio-target-regexp))
21219 (`statistics-cookie
21220 (call-interactively #'org-update-statistics-cookies))
21221 ((or `table `table-cell `table-row)
21222 ;; At a table, recalculate every field and align it. Also
21223 ;; send the table if necessary. If the table has
21224 ;; a `table.el' type, just give up. At a table row or cell,
21225 ;; maybe recalculate line but always align table.
21226 (if (eq (org-element-property :type context) 'table.el)
21227 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21228 Use `\\[org-edit-special]' to edit table.el tables"))
21229 (let ((org-enable-table-editor t))
21230 (if (or (eq type 'table)
21231 ;; Check if point is at a TBLFM line.
21232 (and (eq type 'table-row)
21233 (= (point) (org-element-property :end context))))
21234 (save-excursion
21235 (if (org-at-TBLFM-p)
21236 (progn (require 'org-table)
21237 (org-table-calc-current-TBLFM))
21238 (goto-char (org-element-property :contents-begin context))
21239 (org-call-with-arg 'org-table-recalculate (or arg t))
21240 (orgtbl-send-table 'maybe)))
21241 (org-table-maybe-eval-formula)
21242 (cond (arg (call-interactively #'org-table-recalculate))
21243 ((org-table-maybe-recalculate-line))
21244 (t (org-table-align)))))))
21245 (`timestamp (org-timestamp-change 0 'day))
21246 ((and `nil (guard (org-at-heading-p)))
21247 ;; When point is on an unsupported object type, we can miss
21248 ;; the fact that it also is at a heading. Handle it here.
21249 (call-interactively #'org-set-tags))
21250 ((guard
21251 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21253 (user-error
21254 (substitute-command-keys
21255 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21257 (defun org-mode-restart ()
21258 (interactive)
21259 (let ((indent-status (bound-and-true-p org-indent-mode)))
21260 (funcall major-mode)
21261 (hack-local-variables)
21262 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21263 (org-indent-mode -1)))
21264 (message "%s restarted" major-mode))
21266 (defun org-kill-note-or-show-branches ()
21267 "Abort storing current note, or call `outline-show-branches'."
21268 (interactive)
21269 (if (not org-finish-function)
21270 (progn
21271 (outline-hide-subtree)
21272 (call-interactively 'outline-show-branches))
21273 (let ((org-note-abort t))
21274 (funcall org-finish-function))))
21276 (defun org-delete-indentation (&optional arg)
21277 "Join current line to previous and fix whitespace at join.
21279 If previous line is a headline add to headline title. Otherwise
21280 the function calls `delete-indentation'.
21282 With a non-nil optional argument, join it to the following one."
21283 (interactive "*P")
21284 (if (save-excursion
21285 (beginning-of-line (if arg 1 0))
21286 (let ((case-fold-search nil))
21287 (looking-at org-complex-heading-regexp)))
21288 ;; At headline.
21289 (let ((tags-column (when (match-beginning 5)
21290 (save-excursion (goto-char (match-beginning 5))
21291 (current-column))))
21292 (string (concat " " (progn (when arg (forward-line 1))
21293 (org-trim (delete-and-extract-region
21294 (line-beginning-position)
21295 (line-end-position)))))))
21296 (unless (bobp) (delete-region (point) (1- (point))))
21297 (goto-char (or (match-end 4)
21298 (match-beginning 5)
21299 (match-end 0)))
21300 (skip-chars-backward " \t")
21301 (save-excursion (insert string))
21302 ;; Adjust alignment of tags.
21303 (cond
21304 ((not tags-column)) ;no tags
21305 (org-auto-align-tags (org-set-tags nil t))
21306 (t (org--align-tags-here tags-column)))) ;preserve tags column
21307 (delete-indentation arg)))
21309 (defun org-open-line (n)
21310 "Insert a new row in tables, call `open-line' elsewhere.
21311 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21312 As a special case, when a document starts with a table, allow to
21313 call `open-line' on the very first character."
21314 (interactive "*p")
21315 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21316 (org-table-insert-row)
21317 (open-line n)))
21319 (defun org-return (&optional indent)
21320 "Goto next table row or insert a newline.
21322 Calls `org-table-next-row' or `newline', depending on context.
21324 When optional INDENT argument is non-nil, call
21325 `newline-and-indent' instead of `newline'.
21327 When `org-return-follows-link' is non-nil and point is on
21328 a timestamp or a link, call `org-open-at-point'. However, it
21329 will not happen if point is in a table or on a \"dead\"
21330 object (e.g., within a comment). In these case, you need to use
21331 `org-open-at-point' directly."
21332 (interactive)
21333 (let ((context (if org-return-follows-link (org-element-context)
21334 (org-element-at-point))))
21335 (cond
21336 ;; In a table, call `org-table-next-row'.
21337 ((or (and (eq (org-element-type context) 'table)
21338 (>= (point) (org-element-property :contents-begin context))
21339 (< (point) (org-element-property :contents-end context)))
21340 (org-element-lineage context '(table-row table-cell) t))
21341 (org-table-justify-field-maybe)
21342 (call-interactively #'org-table-next-row))
21343 ;; On a link or a timestamp, call `org-open-at-point' if
21344 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21345 ;; locations, e.g., in a comment, as `org-open-at-point'.
21346 ((and org-return-follows-link
21347 (or (org-in-regexp org-ts-regexp-both nil t)
21348 (org-in-regexp org-tsr-regexp-both nil t)
21349 (org-in-regexp org-any-link-re nil t)))
21350 (call-interactively #'org-open-at-point))
21351 ;; Insert newline in heading, but preserve tags.
21352 ((and (not (bolp))
21353 (save-excursion (beginning-of-line)
21354 (let ((case-fold-search nil))
21355 (looking-at org-complex-heading-regexp))))
21356 ;; At headline. Split line. However, if point is on keyword,
21357 ;; priority cookie or tags, do not break any of them: add
21358 ;; a newline after the headline instead.
21359 (let ((tags-column (and (match-beginning 5)
21360 (save-excursion (goto-char (match-beginning 5))
21361 (current-column))))
21362 (string
21363 (when (and (match-end 4) (org-point-in-group (point) 4))
21364 (delete-and-extract-region (point) (match-end 4)))))
21365 ;; Adjust tag alignment.
21366 (cond
21367 ((not (and tags-column string)))
21368 (org-auto-align-tags (org-set-tags nil t))
21369 (t (org--align-tags-here tags-column))) ;preserve tags column
21370 (end-of-line)
21371 (org-show-entry)
21372 (if indent (newline-and-indent) (newline))
21373 (when string (save-excursion (insert (org-trim string))))))
21374 ;; In a list, make sure indenting keeps trailing text within.
21375 ((and indent
21376 (not (eolp))
21377 (org-element-lineage context '(item)))
21378 (let ((trailing-data
21379 (delete-and-extract-region (point) (line-end-position))))
21380 (newline-and-indent)
21381 (save-excursion (insert trailing-data))))
21382 (t (if indent (newline-and-indent) (newline))))))
21384 (defun org-return-indent ()
21385 "Goto next table row or insert a newline and indent.
21386 Calls `org-table-next-row' or `newline-and-indent', depending on
21387 context. See the individual commands for more information."
21388 (interactive)
21389 (org-return t))
21391 (defun org-ctrl-c-star ()
21392 "Compute table, or change heading status of lines.
21393 Calls `org-table-recalculate' or `org-toggle-heading',
21394 depending on context."
21395 (interactive)
21396 (cond
21397 ((org-at-table-p)
21398 (call-interactively 'org-table-recalculate))
21400 ;; Convert all lines in region to list items
21401 (call-interactively 'org-toggle-heading))))
21403 (defun org-ctrl-c-minus ()
21404 "Insert separator line in table or modify bullet status of line.
21405 Also turns a plain line or a region of lines into list items.
21406 Calls `org-table-insert-hline', `org-toggle-item', or
21407 `org-cycle-list-bullet', depending on context."
21408 (interactive)
21409 (cond
21410 ((org-at-table-p)
21411 (call-interactively 'org-table-insert-hline))
21412 ((org-region-active-p)
21413 (call-interactively 'org-toggle-item))
21414 ((org-in-item-p)
21415 (call-interactively 'org-cycle-list-bullet))
21417 (call-interactively 'org-toggle-item))))
21419 (defun org-toggle-heading (&optional nstars)
21420 "Convert headings to normal text, or items or text to headings.
21421 If there is no active region, only convert the current line.
21423 With a `\\[universal-argument]' prefix, convert the whole list at
21424 point into heading.
21426 In a region:
21428 - If the first non blank line is a headline, remove the stars
21429 from all headlines in the region.
21431 - If it is a normal line, turn each and every normal line (i.e.,
21432 not an heading or an item) in the region into headings. If you
21433 want to convert only the first line of this region, use one
21434 universal prefix argument.
21436 - If it is a plain list item, turn all plain list items into headings.
21438 When converting a line into a heading, the number of stars is chosen
21439 such that the lines become children of the current entry. However,
21440 when a numeric prefix argument is given, its value determines the
21441 number of stars to add."
21442 (interactive "P")
21443 (let ((skip-blanks
21444 (function
21445 ;; Return beginning of first non-blank line, starting from
21446 ;; line at POS.
21447 (lambda (pos)
21448 (save-excursion
21449 (goto-char pos)
21450 (while (org-at-comment-p) (forward-line))
21451 (skip-chars-forward " \r\t\n")
21452 (point-at-bol)))))
21453 beg end toggled)
21454 ;; Determine boundaries of changes. If a universal prefix has
21455 ;; been given, put the list in a region. If region ends at a bol,
21456 ;; do not consider the last line to be in the region.
21458 (when (and current-prefix-arg (org-at-item-p))
21459 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21460 (org-mark-element))
21462 (if (org-region-active-p)
21463 (setq beg (funcall skip-blanks (region-beginning))
21464 end (copy-marker (save-excursion
21465 (goto-char (region-end))
21466 (if (bolp) (point) (point-at-eol)))))
21467 (setq beg (funcall skip-blanks (point-at-bol))
21468 end (copy-marker (point-at-eol))))
21469 ;; Ensure inline tasks don't count as headings.
21470 (org-with-limited-levels
21471 (save-excursion
21472 (goto-char beg)
21473 (cond
21474 ;; Case 1. Started at an heading: de-star headings.
21475 ((org-at-heading-p)
21476 (while (< (point) end)
21477 (when (org-at-heading-p t)
21478 (looking-at org-outline-regexp) (replace-match "")
21479 (setq toggled t))
21480 (forward-line)))
21481 ;; Case 2. Started at an item: change items into headlines.
21482 ;; One star will be added by `org-list-to-subtree'.
21483 ((org-at-item-p)
21484 (while (< (point) end)
21485 (when (org-at-item-p)
21486 ;; Pay attention to cases when region ends before list.
21487 (let* ((struct (org-list-struct))
21488 (list-end
21489 (min (org-list-get-bottom-point struct) (1+ end))))
21490 (save-restriction
21491 (narrow-to-region (point) list-end)
21492 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21493 (setq toggled t))
21494 (forward-line)))
21495 ;; Case 3. Started at normal text: make every line an heading,
21496 ;; skipping headlines and items.
21497 (t (let* ((stars
21498 (make-string
21499 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21500 (add-stars
21501 (cond (nstars "") ; stars from prefix only
21502 ((equal stars "") "*") ; before first heading
21503 (org-odd-levels-only "**") ; inside heading, odd
21504 (t "*"))) ; inside heading, oddeven
21505 (rpl (concat stars add-stars " "))
21506 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21507 (while (< (point) (if (equal nstars '(4)) lend end))
21508 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21509 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21510 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21511 (forward-line)))))))
21512 (unless toggled (message "Cannot toggle heading from here"))))
21514 (defun org-meta-return (&optional _arg)
21515 "Insert a new heading or wrap a region in a table.
21516 Calls `org-insert-heading' or `org-table-wrap-region', depending
21517 on context. See the individual commands for more information."
21518 (interactive)
21519 (org-check-before-invisible-edit 'insert)
21520 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21521 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21522 #'org-insert-heading))))
21524 ;;; Menu entries
21526 (defsubst org-in-subtree-not-table-p ()
21527 "Are we in a subtree and not in a table?"
21528 (and (not (org-before-first-heading-p))
21529 (not (org-at-table-p))))
21531 ;; Define the Org mode menus
21532 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21533 '("Tbl"
21534 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21535 ["Next Field" org-cycle (org-at-table-p)]
21536 ["Previous Field" org-shifttab (org-at-table-p)]
21537 ["Next Row" org-return (org-at-table-p)]
21538 "--"
21539 ["Blank Field" org-table-blank-field (org-at-table-p)]
21540 ["Edit Field" org-table-edit-field (org-at-table-p)]
21541 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21542 "--"
21543 ("Column"
21544 ["Move Column Left" org-metaleft (org-at-table-p)]
21545 ["Move Column Right" org-metaright (org-at-table-p)]
21546 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21547 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21548 ("Row"
21549 ["Move Row Up" org-metaup (org-at-table-p)]
21550 ["Move Row Down" org-metadown (org-at-table-p)]
21551 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21552 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21553 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21554 "--"
21555 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21556 ("Rectangle"
21557 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21558 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21559 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21560 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21561 "--"
21562 ("Calculate"
21563 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21564 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21565 ["Edit Formulas" org-edit-special (org-at-table-p)]
21566 "--"
21567 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21568 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21569 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21570 "--"
21571 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21572 "--"
21573 ["Sum Column/Rectangle" org-table-sum
21574 (or (org-at-table-p) (org-region-active-p))]
21575 ["Which Column?" org-table-current-column (org-at-table-p)])
21576 ["Debug Formulas"
21577 org-table-toggle-formula-debugger
21578 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21579 ["Show Col/Row Numbers"
21580 org-table-toggle-coordinate-overlays
21581 :style toggle
21582 :selected (bound-and-true-p org-table-overlay-coordinates)]
21583 "--"
21584 ["Create" org-table-create (and (not (org-at-table-p))
21585 org-enable-table-editor)]
21586 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21587 ["Import from File" org-table-import (not (org-at-table-p))]
21588 ["Export to File" org-table-export (org-at-table-p)]
21589 "--"
21590 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21591 "--"
21592 ("Plot"
21593 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21594 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21596 (easy-menu-define org-org-menu org-mode-map "Org menu"
21597 '("Org"
21598 ("Show/Hide"
21599 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21600 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21601 ["Sparse Tree..." org-sparse-tree t]
21602 ["Reveal Context" org-reveal t]
21603 ["Show All" outline-show-all t]
21604 "--"
21605 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21606 "--"
21607 ["New Heading" org-insert-heading t]
21608 ("Navigate Headings"
21609 ["Up" outline-up-heading t]
21610 ["Next" outline-next-visible-heading t]
21611 ["Previous" outline-previous-visible-heading t]
21612 ["Next Same Level" outline-forward-same-level t]
21613 ["Previous Same Level" outline-backward-same-level t]
21614 "--"
21615 ["Jump" org-goto t])
21616 ("Edit Structure"
21617 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21618 "--"
21619 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21620 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21621 "--"
21622 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21623 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21624 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21625 "--"
21626 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21627 "--"
21628 ["Copy visible text" org-copy-visible t]
21629 "--"
21630 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21631 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21632 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21633 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21634 "--"
21635 ["Sort Region/Children" org-sort t]
21636 "--"
21637 ["Convert to odd levels" org-convert-to-odd-levels t]
21638 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21639 ("Editing"
21640 ["Emphasis..." org-emphasize t]
21641 ["Edit Source Example" org-edit-special t]
21642 "--"
21643 ["Footnote new/jump" org-footnote-action t]
21644 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21645 ("Archive"
21646 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21647 "--"
21648 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21649 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21650 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21652 "--"
21653 ("Hyperlinks"
21654 ["Store Link (Global)" org-store-link t]
21655 ["Find existing link to here" org-occur-link-in-agenda-files t]
21656 ["Insert Link" org-insert-link t]
21657 ["Follow Link" org-open-at-point t]
21658 "--"
21659 ["Next link" org-next-link t]
21660 ["Previous link" org-previous-link t]
21661 "--"
21662 ["Descriptive Links"
21663 org-toggle-link-display
21664 :style radio
21665 :selected org-descriptive-links
21667 ["Literal Links"
21668 org-toggle-link-display
21669 :style radio
21670 :selected (not org-descriptive-links)])
21671 "--"
21672 ("TODO Lists"
21673 ["TODO/DONE/-" org-todo t]
21674 ("Select keyword"
21675 ["Next keyword" org-shiftright (org-at-heading-p)]
21676 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21677 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21678 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21679 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21680 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21681 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21682 "--"
21683 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21684 :selected org-enforce-todo-dependencies :style toggle :active t]
21685 "Settings for tree at point"
21686 ["Do Children sequentially" org-toggle-ordered-property :style radio
21687 :selected (org-entry-get nil "ORDERED")
21688 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21689 ["Do Children parallel" org-toggle-ordered-property :style radio
21690 :selected (not (org-entry-get nil "ORDERED"))
21691 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21692 "--"
21693 ["Set Priority" org-priority t]
21694 ["Priority Up" org-shiftup t]
21695 ["Priority Down" org-shiftdown t]
21696 "--"
21697 ["Get news from all feeds" org-feed-update-all t]
21698 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21699 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21700 ("TAGS and Properties"
21701 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21702 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21703 "--"
21704 ["Set property" org-set-property (not (org-before-first-heading-p))]
21705 ["Column view of properties" org-columns t]
21706 ["Insert Column View DBlock" org-columns-insert-dblock t])
21707 ("Dates and Scheduling"
21708 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21709 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21710 ("Change Date"
21711 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21712 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21713 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21714 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21715 ["Compute Time Range" org-evaluate-time-range t]
21716 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21717 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21718 "--"
21719 ["Custom time format" org-toggle-time-stamp-overlays
21720 :style radio :selected org-display-custom-times]
21721 "--"
21722 ["Goto Calendar" org-goto-calendar t]
21723 ["Date from Calendar" org-date-from-calendar t]
21724 "--"
21725 ["Start/Restart Timer" org-timer-start t]
21726 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21727 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21728 ["Insert Timer String" org-timer t]
21729 ["Insert Timer Item" org-timer-item t])
21730 ("Logging work"
21731 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21732 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21733 ["Clock out" org-clock-out t]
21734 ["Clock cancel" org-clock-cancel t]
21735 "--"
21736 ["Mark as default task" org-clock-mark-default-task t]
21737 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21738 ["Goto running clock" org-clock-goto t]
21739 "--"
21740 ["Display times" org-clock-display t]
21741 ["Create clock table" org-clock-report t]
21742 "--"
21743 ["Record DONE time"
21744 (progn (setq org-log-done (not org-log-done))
21745 (message "Switching to %s will %s record a timestamp"
21746 (car org-done-keywords)
21747 (if org-log-done "automatically" "not")))
21748 :style toggle :selected org-log-done])
21749 "--"
21750 ["Agenda Command..." org-agenda t]
21751 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21752 ("File List for Agenda")
21753 ("Special views current file"
21754 ["TODO Tree" org-show-todo-tree t]
21755 ["Check Deadlines" org-check-deadlines t]
21756 ["Timeline" org-timeline t]
21757 ["Tags/Property tree" org-match-sparse-tree t])
21758 "--"
21759 ["Export/Publish..." org-export-dispatch t]
21760 ("LaTeX"
21761 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21762 :selected org-cdlatex-mode]
21763 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21764 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21765 ["Modify math symbol" org-cdlatex-math-modify
21766 (org-inside-LaTeX-fragment-p)]
21767 ["Insert citation" org-reftex-citation t])
21768 "--"
21769 ("MobileOrg"
21770 ["Push Files and Views" org-mobile-push t]
21771 ["Get Captured and Flagged" org-mobile-pull t]
21772 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21773 "--"
21774 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21775 "--"
21776 ("Documentation"
21777 ["Show Version" org-version t]
21778 ["Info Documentation" org-info t])
21779 ("Customize"
21780 ["Browse Org Group" org-customize t]
21781 "--"
21782 ["Expand This Menu" org-create-customize-menu
21783 (fboundp 'customize-menu-create)])
21784 ["Send bug report" org-submit-bug-report t]
21785 "--"
21786 ("Refresh/Reload"
21787 ["Refresh setup current buffer" org-mode-restart t]
21788 ["Reload Org (after update)" org-reload t]
21789 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21792 (defun org-info (&optional node)
21793 "Read documentation for Org in the info system.
21794 With optional NODE, go directly to that node."
21795 (interactive)
21796 (info (format "(org)%s" (or node ""))))
21798 ;;;###autoload
21799 (defun org-submit-bug-report ()
21800 "Submit a bug report on Org via mail.
21802 Don't hesitate to report any problems or inaccurate documentation.
21804 If you don't have setup sending mail from (X)Emacs, please copy the
21805 output buffer into your mail program, as it gives us important
21806 information about your Org version and configuration."
21807 (interactive)
21808 (require 'reporter)
21809 (defvar reporter-prompt-for-summary-p)
21810 (org-load-modules-maybe)
21811 (org-require-autoloaded-modules)
21812 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21813 (reporter-submit-bug-report
21814 "emacs-orgmode@gnu.org"
21815 (org-version nil 'full)
21816 (let (list)
21817 (save-window-excursion
21818 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21819 (delete-other-windows)
21820 (erase-buffer)
21821 (insert "You are about to submit a bug report to the Org mailing list.
21823 We would like to add your full Org and Outline configuration to the
21824 bug report. This greatly simplifies the work of the maintainer and
21825 other experts on the mailing list.
21827 HOWEVER, some variables you have customized may contain private
21828 information. The names of customers, colleagues, or friends, might
21829 appear in the form of file names, tags, todo states, or search strings.
21830 If you answer yes to the prompt, you might want to check and remove
21831 such private information before sending the email.")
21832 (add-text-properties (point-min) (point-max) '(face org-warning))
21833 (when (yes-or-no-p "Include your Org configuration ")
21834 (mapatoms
21835 (lambda (v)
21836 (and (boundp v)
21837 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21838 (or (and (symbol-value v)
21839 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21840 (and
21841 (get v 'custom-type) (get v 'standard-value)
21842 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21843 (push v list)))))
21844 (kill-buffer (get-buffer "*Warn about privacy*"))
21845 list))
21846 nil nil
21847 "Remember to cover the basics, that is, what you expected to happen and
21848 what in fact did happen. You don't know how to make a good report? See
21850 http://orgmode.org/manual/Feedback.html#Feedback
21852 Your bug report will be posted to the Org mailing list.
21853 ------------------------------------------------------------------------")
21854 (save-excursion
21855 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21856 (replace-match "\\1Bug: \\3 [\\2]")))))
21859 (defun org-install-agenda-files-menu ()
21860 (let ((bl (buffer-list)))
21861 (save-excursion
21862 (while bl
21863 (set-buffer (pop bl))
21864 (when (derived-mode-p 'org-mode) (setq bl nil)))
21865 (when (derived-mode-p 'org-mode)
21866 (easy-menu-change
21867 '("Org") "File List for Agenda"
21868 (append
21869 (list
21870 ["Edit File List" (org-edit-agenda-file-list) t]
21871 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21872 ["Remove Current File from List" org-remove-file t]
21873 ["Cycle through agenda files" org-cycle-agenda-files t]
21874 ["Occur in all agenda files" org-occur-in-agenda-files t]
21875 "--")
21876 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21878 ;;;; Documentation
21880 (defun org-require-autoloaded-modules ()
21881 (interactive)
21882 (mapc #'require
21883 '(org-agenda org-archive org-attach org-clock org-colview org-id
21884 org-table org-timer)))
21886 ;;;###autoload
21887 (defun org-reload (&optional uncompiled)
21888 "Reload all org lisp files.
21889 With prefix arg UNCOMPILED, load the uncompiled versions."
21890 (interactive "P")
21891 (require 'loadhist)
21892 (let* ((org-dir (org-find-library-dir "org"))
21893 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21894 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21895 (remove-re (format "\\`%s\\'"
21896 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21897 (feats (delete-dups
21898 (mapcar 'file-name-sans-extension
21899 (mapcar 'file-name-nondirectory
21900 (delq nil
21901 (mapcar 'feature-file
21902 features))))))
21903 (lfeat (append
21904 (sort
21905 (setq feats
21906 (delq nil (mapcar
21907 (lambda (f)
21908 (if (and (string-match feature-re f)
21909 (not (string-match remove-re f)))
21910 f nil))
21911 feats)))
21912 'string-lessp)
21913 (list "org-version" "org")))
21914 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21915 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21916 load-uncore load-misses)
21917 (setq load-misses
21918 (delq 't
21919 (mapcar (lambda (f)
21920 (or (org-load-noerror-mustsuffix (concat org-dir f))
21921 (and (string= org-dir contrib-dir)
21922 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21923 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21924 (add-to-list 'load-uncore f 'append)
21927 lfeat)))
21928 (when load-uncore
21929 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21930 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21931 (if load-misses
21932 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21933 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21934 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21936 ;;;###autoload
21937 (defun org-customize ()
21938 "Call the customize function with org as argument."
21939 (interactive)
21940 (org-load-modules-maybe)
21941 (org-require-autoloaded-modules)
21942 (customize-browse 'org))
21944 (defun org-create-customize-menu ()
21945 "Create a full customization menu for Org mode, insert it into the menu."
21946 (interactive)
21947 (org-load-modules-maybe)
21948 (org-require-autoloaded-modules)
21949 (if (fboundp 'customize-menu-create)
21950 (progn
21951 (easy-menu-change
21952 '("Org") "Customize"
21953 `(["Browse Org group" org-customize t]
21954 "--"
21955 ,(customize-menu-create 'org)
21956 ["Set" Custom-set t]
21957 ["Save" Custom-save t]
21958 ["Reset to Current" Custom-reset-current t]
21959 ["Reset to Saved" Custom-reset-saved t]
21960 ["Reset to Standard Settings" Custom-reset-standard t]))
21961 (message "\"Org\"-menu now contains full customization menu"))
21962 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21964 ;;;; Miscellaneous stuff
21966 ;;; Generally useful functions
21968 (defun org-get-at-eol (property n)
21969 "Get text property PROPERTY at the end of line less N characters."
21970 (get-text-property (- (point-at-eol) n) property))
21972 (defun org-find-text-property-in-string (prop s)
21973 "Return the first non-nil value of property PROP in string S."
21974 (or (get-text-property 0 prop s)
21975 (get-text-property (or (next-single-property-change 0 prop s) 0)
21976 prop s)))
21978 (defun org-display-warning (message)
21979 "Display the given MESSAGE as a warning."
21980 (display-warning 'org message :warning))
21982 (defun org-eval (form)
21983 "Eval FORM and return result."
21984 (condition-case error
21985 (eval form)
21986 (error (format "%%![Error: %s]" error))))
21988 (defun org-in-clocktable-p ()
21989 "Check if the cursor is in a clocktable."
21990 (let ((pos (point)) start)
21991 (save-excursion
21992 (end-of-line 1)
21993 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21994 (setq start (match-beginning 0))
21995 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21996 (>= (match-end 0) pos)
21997 start))))
21999 (defun org-in-verbatim-emphasis ()
22000 (save-match-data
22001 (and (org-in-regexp org-emph-re 2)
22002 (>= (point) (match-beginning 3))
22003 (<= (point) (match-end 4))
22004 (member (match-string 3) '("=" "~")))))
22006 (defun org-overlay-display (ovl text &optional face evap)
22007 "Make overlay OVL display TEXT with face FACE."
22008 (overlay-put ovl 'display text)
22009 (if face (overlay-put ovl 'face face))
22010 (if evap (overlay-put ovl 'evaporate t)))
22012 (defun org-overlay-before-string (ovl text &optional face evap)
22013 "Make overlay OVL display TEXT with face FACE."
22014 (if face (org-add-props text nil 'face face))
22015 (overlay-put ovl 'before-string text)
22016 (if evap (overlay-put ovl 'evaporate t)))
22018 (defun org-find-overlays (prop &optional pos delete)
22019 "Find all overlays specifying PROP at POS or point.
22020 If DELETE is non-nil, delete all those overlays."
22021 (let (found)
22022 (dolist (ov (overlays-at (or pos (point))) found)
22023 (cond ((not (overlay-get ov prop)))
22024 (delete (delete-overlay ov))
22025 (t (push ov found))))))
22027 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22028 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22029 (if (and marker (marker-buffer marker)
22030 (buffer-live-p (marker-buffer marker)))
22031 (progn
22032 (pop-to-buffer-same-window (marker-buffer marker))
22033 (when (or (> marker (point-max)) (< marker (point-min)))
22034 (widen))
22035 (goto-char marker)
22036 (org-show-context 'org-goto))
22037 (if bookmark
22038 (bookmark-jump bookmark)
22039 (error "Cannot find location"))))
22041 (defun org-quote-csv-field (s)
22042 "Quote field for inclusion in CSV material."
22043 (if (string-match "[\",]" s)
22044 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22047 (defun org-force-self-insert (N)
22048 "Needed to enforce self-insert under remapping."
22049 (interactive "p")
22050 (self-insert-command N))
22052 (defun org-string-width (s)
22053 "Compute width of string, ignoring invisible characters.
22054 This ignores character with invisibility property `org-link', and also
22055 characters with property `org-cwidth', because these will become invisible
22056 upon the next fontification round."
22057 (let (b l)
22058 (when (or (eq t buffer-invisibility-spec)
22059 (assq 'org-link buffer-invisibility-spec))
22060 (while (setq b (text-property-any 0 (length s)
22061 'invisible 'org-link s))
22062 (setq s (concat (substring s 0 b)
22063 (substring s (or (next-single-property-change
22064 b 'invisible s)
22065 (length s)))))))
22066 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22067 (setq s (concat (substring s 0 b)
22068 (substring s (or (next-single-property-change
22069 b 'org-cwidth s)
22070 (length s))))))
22071 (setq l (string-width s) b -1)
22072 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22073 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22076 (defun org-shorten-string (s maxlength)
22077 "Shorten string S so that it is no longer than MAXLENGTH characters.
22078 If the string is shorter or has length MAXLENGTH, just return the
22079 original string. If it is longer, the functions finds a space in the
22080 string, breaks this string off at that locations and adds three dots
22081 as ellipsis. Including the ellipsis, the string will not be longer
22082 than MAXLENGTH. If finding a good breaking point in the string does
22083 not work, the string is just chopped off in the middle of a word
22084 if necessary."
22085 (if (<= (length s) maxlength)
22087 (let* ((n (max (- maxlength 4) 1))
22088 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22089 (if (string-match re s)
22090 (concat (match-string 1 s) "...")
22091 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22093 (defun org-get-indentation (&optional line)
22094 "Get the indentation of the current line, interpreting tabs.
22095 When LINE is given, assume it represents a line and compute its indentation."
22096 (if line
22097 (when (string-match "^ *" (org-remove-tabs line))
22098 (match-end 0))
22099 (save-excursion
22100 (beginning-of-line 1)
22101 (skip-chars-forward " \t")
22102 (current-column))))
22104 (defun org-get-string-indentation (s)
22105 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22106 (let ((n -1) (i 0) (w tab-width) c)
22107 (catch 'exit
22108 (while (< (setq n (1+ n)) (length s))
22109 (setq c (aref s n))
22110 (cond ((= c ?\ ) (setq i (1+ i)))
22111 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22112 (t (throw 'exit t)))))
22115 (defun org-remove-tabs (s &optional width)
22116 "Replace tabulators in S with spaces.
22117 Assumes that s is a single line, starting in column 0."
22118 (setq width (or width tab-width))
22119 (while (string-match "\t" s)
22120 (setq s (replace-match
22121 (make-string
22122 (- (* width (/ (+ (match-beginning 0) width) width))
22123 (match-beginning 0)) ?\ )
22124 t t s)))
22127 (defun org-fix-indentation (line ind)
22128 "Fix indentation in LINE.
22129 IND is a cons cell with target and minimum indentation.
22130 If the current indentation in LINE is smaller than the minimum,
22131 leave it alone. If it is larger than ind, set it to the target."
22132 (let* ((l (org-remove-tabs line))
22133 (i (org-get-indentation l))
22134 (i1 (car ind)) (i2 (cdr ind)))
22135 (when (>= i i2) (setq l (substring line i2)))
22136 (if (> i1 0)
22137 (concat (make-string i1 ?\ ) l)
22138 l)))
22140 (defun org-remove-indentation (code &optional n)
22141 "Remove maximum common indentation in string CODE and return it.
22142 N may optionally be the number of columns to remove. Return CODE
22143 as-is if removal failed."
22144 (with-temp-buffer
22145 (insert code)
22146 (if (org-do-remove-indentation n) (buffer-string) code)))
22148 (defun org-do-remove-indentation (&optional n)
22149 "Remove the maximum common indentation from the buffer.
22150 When optional argument N is a positive integer, remove exactly
22151 that much characters from indentation, if possible. Return nil
22152 if it fails."
22153 (catch :exit
22154 (goto-char (point-min))
22155 ;; Find maximum common indentation, if not specified.
22156 (let ((n (or n
22157 (let ((min-ind (point-max)))
22158 (save-excursion
22159 (while (re-search-forward "^[ \t]*\\S-" nil t)
22160 (let ((ind (1- (current-column))))
22161 (if (zerop ind) (throw :exit nil)
22162 (setq min-ind (min min-ind ind))))))
22163 min-ind))))
22164 (if (zerop n) (throw :exit nil)
22165 ;; Remove exactly N indentation, but give up if not possible.
22166 (while (not (eobp))
22167 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22168 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22169 ((< ind n) (throw :exit nil))
22170 (t (indent-line-to (- ind n))))
22171 (forward-line)))
22172 ;; Signal success.
22173 t))))
22175 (defun org-fill-template (template alist)
22176 "Find each %key of ALIST in TEMPLATE and replace it."
22177 (let ((case-fold-search nil))
22178 (dolist (entry (sort (copy-sequence alist)
22179 (lambda (a b) (< (length (car a)) (length (car b))))))
22180 (setq template
22181 (replace-regexp-in-string
22182 (concat "%" (regexp-quote (car entry)))
22183 (or (cdr entry) "") template t t)))
22184 template))
22186 (defun org-base-buffer (buffer)
22187 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22188 (if (not buffer)
22189 buffer
22190 (or (buffer-base-buffer buffer)
22191 buffer)))
22193 (defun org-wrap (string &optional width lines)
22194 "Wrap string to either a number of lines, or a width in characters.
22195 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22196 that costs. If there is a word longer than WIDTH, the text is actually
22197 wrapped to the length of that word.
22198 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22199 many lines, whatever width that takes.
22200 The return value is a list of lines, without newlines at the end."
22201 (let* ((words (org-split-string string "[ \t\n]+"))
22202 (maxword (apply 'max (mapcar 'org-string-width words)))
22203 w ll)
22204 (cond (width
22205 (org-do-wrap words (max maxword width)))
22206 (lines
22207 (setq w maxword)
22208 (setq ll (org-do-wrap words maxword))
22209 (if (<= (length ll) lines)
22211 (setq ll words)
22212 (while (> (length ll) lines)
22213 (setq w (1+ w))
22214 (setq ll (org-do-wrap words w)))
22215 ll))
22216 (t (error "Cannot wrap this")))))
22218 (defun org-do-wrap (words width)
22219 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22220 (let (lines line)
22221 (while words
22222 (setq line (pop words))
22223 (while (and words (< (+ (length line) (length (car words))) width))
22224 (setq line (concat line " " (pop words))))
22225 (setq lines (push line lines)))
22226 (nreverse lines)))
22228 (defun org-split-string (string &optional separators)
22229 "Splits STRING into substrings at SEPARATORS.
22230 SEPARATORS is a regular expression.
22231 No empty strings are returned if there are matches at the beginning
22232 and end of string."
22233 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22234 (let ((start 0) notfirst list)
22235 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22236 (if (and notfirst
22237 (= start (match-beginning 0))
22238 (< start (length string)))
22239 (1+ start) start))
22240 (< (match-beginning 0) (length string)))
22241 (setq notfirst t)
22242 (or (eq (match-beginning 0) 0)
22243 (and (eq (match-beginning 0) (match-end 0))
22244 (eq (match-beginning 0) start))
22245 (push (substring string start (match-beginning 0)) list))
22246 (setq start (match-end 0)))
22247 (or (eq start (length string))
22248 (push (substring string start) list))
22249 (nreverse list)))
22251 (defun org-quote-vert (s)
22252 "Replace \"|\" with \"\\vert\"."
22253 (while (string-match "|" s)
22254 (setq s (replace-match "\\vert" t t s)))
22257 (defun org-uuidgen-p (s)
22258 "Is S an ID created by UUIDGEN?"
22259 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22261 (defun org-in-src-block-p (&optional inside)
22262 "Whether point is in a code source block.
22263 When INSIDE is non-nil, don't consider we are within a src block
22264 when point is at #+BEGIN_SRC or #+END_SRC."
22265 (let ((case-fold-search t))
22266 (or (and (eq (get-char-property (point) 'src-block) t))
22267 (and (not inside)
22268 (save-match-data
22269 (save-excursion
22270 (beginning-of-line)
22271 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22273 (defun org-context ()
22274 "Return a list of contexts of the current cursor position.
22275 If several contexts apply, all are returned.
22276 Each context entry is a list with a symbol naming the context, and
22277 two positions indicating start and end of the context. Possible
22278 contexts are:
22280 :headline anywhere in a headline
22281 :headline-stars on the leading stars in a headline
22282 :todo-keyword on a TODO keyword (including DONE) in a headline
22283 :tags on the TAGS in a headline
22284 :priority on the priority cookie in a headline
22285 :item on the first line of a plain list item
22286 :item-bullet on the bullet/number of a plain list item
22287 :checkbox on the checkbox in a plain list item
22288 :table in an Org table
22289 :table-special on a special filed in a table
22290 :table-table in a table.el table
22291 :clocktable in a clocktable
22292 :src-block in a source block
22293 :link on a hyperlink
22294 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22295 :target on a <<target>>
22296 :radio-target on a <<<radio-target>>>
22297 :latex-fragment on a LaTeX fragment
22298 :latex-preview on a LaTeX fragment with overlaid preview image
22300 This function expects the position to be visible because it uses font-lock
22301 faces as a help to recognize the following contexts: :table-special, :link,
22302 and :keyword."
22303 (let* ((f (get-text-property (point) 'face))
22304 (faces (if (listp f) f (list f)))
22305 (case-fold-search t)
22306 (p (point)) clist o)
22307 ;; First the large context
22308 (cond
22309 ((org-at-heading-p t)
22310 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22311 (when (progn
22312 (beginning-of-line 1)
22313 (looking-at org-todo-line-tags-regexp))
22314 (push (org-point-in-group p 1 :headline-stars) clist)
22315 (push (org-point-in-group p 2 :todo-keyword) clist)
22316 (push (org-point-in-group p 4 :tags) clist))
22317 (goto-char p)
22318 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22319 (when (looking-at "\\[#[A-Z0-9]\\]")
22320 (push (org-point-in-group p 0 :priority) clist)))
22322 ((org-at-item-p)
22323 (push (org-point-in-group p 2 :item-bullet) clist)
22324 (push (list :item (point-at-bol)
22325 (save-excursion (org-end-of-item) (point)))
22326 clist)
22327 (and (org-at-item-checkbox-p)
22328 (push (org-point-in-group p 0 :checkbox) clist)))
22330 ((org-at-table-p)
22331 (push (list :table (org-table-begin) (org-table-end)) clist)
22332 (when (memq 'org-formula faces)
22333 (push (list :table-special
22334 (previous-single-property-change p 'face)
22335 (next-single-property-change p 'face)) clist)))
22336 ((org-at-table-p 'any)
22337 (push (list :table-table) clist)))
22338 (goto-char p)
22340 (let ((case-fold-search t))
22341 ;; New the "medium" contexts: clocktables, source blocks
22342 (cond ((org-in-clocktable-p)
22343 (push (list :clocktable
22344 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22345 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22346 (match-beginning 1))
22347 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22348 (match-end 0))) clist))
22349 ((org-in-src-block-p)
22350 (push (list :src-block
22351 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22352 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22353 (match-beginning 1))
22354 (and (search-forward "#+END_SRC" nil t)
22355 (match-beginning 0))) clist))))
22356 (goto-char p)
22358 ;; Now the small context
22359 (cond
22360 ((org-at-timestamp-p)
22361 (push (org-point-in-group p 0 :timestamp) clist))
22362 ((memq 'org-link faces)
22363 (push (list :link
22364 (previous-single-property-change p 'face)
22365 (next-single-property-change p 'face)) clist))
22366 ((memq 'org-special-keyword faces)
22367 (push (list :keyword
22368 (previous-single-property-change p 'face)
22369 (next-single-property-change p 'face)) clist))
22370 ((org-at-target-p)
22371 (push (org-point-in-group p 0 :target) clist)
22372 (goto-char (1- (match-beginning 0)))
22373 (when (looking-at org-radio-target-regexp)
22374 (push (org-point-in-group p 0 :radio-target) clist))
22375 (goto-char p))
22376 ((setq o (cl-some
22377 (lambda (o)
22378 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22380 (overlays-at (point))))
22381 (push (list :latex-fragment
22382 (overlay-start o) (overlay-end o)) clist)
22383 (push (list :latex-preview
22384 (overlay-start o) (overlay-end o)) clist))
22385 ((org-inside-LaTeX-fragment-p)
22386 ;; FIXME: positions wrong.
22387 (push (list :latex-fragment (point) (point)) clist)))
22389 (setq clist (nreverse (delq nil clist)))
22390 clist))
22392 (defun org-in-regexp (regexp &optional nlines visually)
22393 "Check if point is inside a match of REGEXP.
22395 Normally only the current line is checked, but you can include
22396 NLINES extra lines around point into the search. If VISUALLY is
22397 set, require that the cursor is not after the match but really
22398 on, so that the block visually is on the match.
22400 Return nil or a cons cell (BEG . END) where BEG and END are,
22401 respectively, the positions at the beginning and the end of the
22402 match."
22403 (catch :exit
22404 (let ((pos (point))
22405 (eol (line-end-position (if nlines (1+ nlines) 1))))
22406 (save-excursion
22407 (beginning-of-line (- 1 (or nlines 0)))
22408 (while (and (re-search-forward regexp eol t)
22409 (<= (match-beginning 0) pos))
22410 (let ((end (match-end 0)))
22411 (when (or (> end pos) (and (= end pos) (not visually)))
22412 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22414 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22415 "Non-nil when point is between matches of START-RE and END-RE.
22417 Also return a non-nil value when point is on one of the matches.
22419 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22420 buffer positions. Default values are the positions of headlines
22421 surrounding the point.
22423 The functions returns a cons cell whose car (resp. cdr) is the
22424 position before START-RE (resp. after END-RE)."
22425 (save-match-data
22426 (let ((pos (point))
22427 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22428 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22429 beg end)
22430 (save-excursion
22431 ;; Point is on a block when on START-RE or if START-RE can be
22432 ;; found before it...
22433 (and (or (org-in-regexp start-re)
22434 (re-search-backward start-re limit-up t))
22435 (setq beg (match-beginning 0))
22436 ;; ... and END-RE after it...
22437 (goto-char (match-end 0))
22438 (re-search-forward end-re limit-down t)
22439 (> (setq end (match-end 0)) pos)
22440 ;; ... without another START-RE in-between.
22441 (goto-char (match-beginning 0))
22442 (not (re-search-backward start-re (1+ beg) t))
22443 ;; Return value.
22444 (cons beg end))))))
22446 (defun org-in-block-p (names)
22447 "Non-nil when point belongs to a block whose name belongs to NAMES.
22449 NAMES is a list of strings containing names of blocks.
22451 Return first block name matched, or nil. Beware that in case of
22452 nested blocks, the returned name may not belong to the closest
22453 block from point."
22454 (save-match-data
22455 (catch 'exit
22456 (let ((case-fold-search t)
22457 (lim-up (save-excursion (outline-previous-heading)))
22458 (lim-down (save-excursion (outline-next-heading))))
22459 (dolist (name names)
22460 (let ((n (regexp-quote name)))
22461 (when (org-between-regexps-p
22462 (concat "^[ \t]*#\\+begin_" n)
22463 (concat "^[ \t]*#\\+end_" n)
22464 lim-up lim-down)
22465 (throw 'exit n)))))
22466 nil)))
22468 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22469 "Call `multi-occur' with buffers for all agenda files."
22470 (interactive "sOrg-files matching: ")
22471 (let* ((files (org-agenda-files))
22472 (tnames (mapcar #'file-truename files))
22473 (extra org-agenda-text-search-extra-files))
22474 (when (eq (car extra) 'agenda-archives)
22475 (setq extra (cdr extra))
22476 (setq files (org-add-archive-files files)))
22477 (dolist (f extra)
22478 (unless (member (file-truename f) tnames)
22479 (unless (member f files) (setq files (append files (list f))))
22480 (setq tnames (append tnames (list (file-truename f))))))
22481 (multi-occur
22482 (mapcar (lambda (x)
22483 (with-current-buffer
22484 ;; FIXME: Why not just (find-file-noselect x)?
22485 ;; Is it to avoid the "revert buffer" prompt?
22486 (or (get-file-buffer x) (find-file-noselect x))
22487 (widen)
22488 (current-buffer)))
22489 files)
22490 regexp)))
22492 (add-hook 'occur-mode-find-occurrence-hook
22493 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22495 (defun org-occur-link-in-agenda-files ()
22496 "Create a link and search for it in the agendas.
22497 The link is not stored in `org-stored-links', it is just created
22498 for the search purpose."
22499 (interactive)
22500 (let ((link (condition-case nil
22501 (org-store-link nil)
22502 (error "Unable to create a link to here"))))
22503 (org-occur-in-agenda-files (regexp-quote link))))
22505 (defun org-reverse-string (string)
22506 "Return the reverse of STRING."
22507 (apply 'string (reverse (string-to-list string))))
22509 ;; defsubst org-uniquify must be defined before first use
22511 (defun org-uniquify-alist (alist)
22512 "Merge elements of ALIST with the same key.
22514 For example, in this alist:
22516 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22517 => \\='((a 1 3) (b 2))
22519 merge (a 1) and (a 3) into (a 1 3).
22521 The function returns the new ALIST."
22522 (let (rtn)
22523 (dolist (e alist rtn)
22524 (let (n)
22525 (if (not (assoc (car e) rtn))
22526 (push e rtn)
22527 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22528 (setq rtn (assq-delete-all (car e) rtn))
22529 (push n rtn))))))
22531 (defun org-delete-all (elts list)
22532 "Remove all elements in ELTS from LIST.
22533 Comparison is done with `equal'. It is a destructive operation
22534 that may remove elements by altering the list structure."
22535 (while elts
22536 (setq list (delete (pop elts) list)))
22537 list)
22539 (defun org-back-over-empty-lines ()
22540 "Move backwards over whitespace, to the beginning of the first empty line.
22541 Returns the number of empty lines passed."
22542 (let ((pos (point)))
22543 (if (cdr (assq 'heading org-blank-before-new-entry))
22544 (skip-chars-backward " \t\n\r")
22545 (unless (eobp)
22546 (forward-line -1)))
22547 (beginning-of-line 2)
22548 (goto-char (min (point) pos))
22549 (count-lines (point) pos)))
22551 (defun org-skip-whitespace ()
22552 (skip-chars-forward " \t\n\r"))
22554 (defun org-point-in-group (point group &optional context)
22555 "Check if POINT is in match-group GROUP.
22556 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22557 match. If the match group does not exist or point is not inside it,
22558 return nil."
22559 (and (match-beginning group)
22560 (>= point (match-beginning group))
22561 (<= point (match-end group))
22562 (if context
22563 (list context (match-beginning group) (match-end group))
22564 t)))
22566 (defun org-switch-to-buffer-other-window (&rest args)
22567 "Switch to buffer in a second window on the current frame.
22568 In particular, do not allow pop-up frames.
22569 Returns the newly created buffer."
22570 (org-no-popups
22571 (apply 'switch-to-buffer-other-window args)))
22573 (defun org-combine-plists (&rest plists)
22574 "Create a single property list from all plists in PLISTS.
22575 The process starts by copying the first list, and then setting properties
22576 from the other lists. Settings in the last list are the most significant
22577 ones and overrule settings in the other lists."
22578 (let ((rtn (copy-sequence (pop plists)))
22579 p v ls)
22580 (while plists
22581 (setq ls (pop plists))
22582 (while ls
22583 (setq p (pop ls) v (pop ls))
22584 (setq rtn (plist-put rtn p v))))
22585 rtn))
22587 (defun org-replace-escapes (string table)
22588 "Replace %-escapes in STRING with values in TABLE.
22589 TABLE is an association list with keys like \"%a\" and string values.
22590 The sequences in STRING may contain normal field width and padding information,
22591 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22592 so values can contain further %-escapes if they are define later in TABLE."
22593 (let ((tbl (copy-alist table))
22594 (case-fold-search nil)
22595 (pchg 0)
22596 re rpl)
22597 (dolist (e tbl)
22598 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22599 (when (and (cdr e) (string-match re (cdr e)))
22600 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22601 (safe "SREF"))
22602 (add-text-properties 0 3 (list 'sref sref) safe)
22603 (setcdr e (replace-match safe t t (cdr e)))))
22604 (while (string-match re string)
22605 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22606 (cdr e)))
22607 (setq string (replace-match rpl t t string))))
22608 (while (setq pchg (next-property-change pchg string))
22609 (let ((sref (get-text-property pchg 'sref string)))
22610 (when (and sref (string-match "SREF" string pchg))
22611 (setq string (replace-match sref t t string)))))
22612 string))
22614 (defun org-find-base-buffer-visiting (file)
22615 "Like `find-buffer-visiting' but always return the base buffer and
22616 not an indirect buffer."
22617 (let ((buf (or (get-file-buffer file)
22618 (find-buffer-visiting file))))
22619 (if buf
22620 (or (buffer-base-buffer buf) buf)
22621 nil)))
22623 ;;; TODO: Only called once, from ox-odt which should probably use
22624 ;;; org-export-inline-image-p or something.
22625 (defun org-file-image-p (file)
22626 "Return non-nil if FILE is an image."
22627 (save-match-data
22628 (string-match (image-file-name-regexp) file)))
22630 (defun org-get-cursor-date (&optional with-time)
22631 "Return the date at cursor in as a time.
22632 This works in the calendar and in the agenda, anywhere else it just
22633 returns the current time.
22634 If WITH-TIME is non-nil, returns the time of the event at point (in
22635 the agenda) or the current time of the day."
22636 (let (date day defd tp hod mod)
22637 (when with-time
22638 (setq tp (get-text-property (point) 'time))
22639 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22640 (setq hod (string-to-number (match-string 1 tp))
22641 mod (string-to-number (match-string 2 tp))))
22642 (or tp (let ((now (decode-time)))
22643 (setq hod (nth 2 now)
22644 mod (nth 1 now)))))
22645 (cond
22646 ((eq major-mode 'calendar-mode)
22647 (setq date (calendar-cursor-to-date)
22648 defd (encode-time 0 (or mod 0) (or hod 0)
22649 (nth 1 date) (nth 0 date) (nth 2 date))))
22650 ((eq major-mode 'org-agenda-mode)
22651 (setq day (get-text-property (point) 'day))
22652 (when day
22653 (setq date (calendar-gregorian-from-absolute day)
22654 defd (encode-time 0 (or mod 0) (or hod 0)
22655 (nth 1 date) (nth 0 date) (nth 2 date))))))
22656 (or defd (current-time))))
22658 (defun org-mark-subtree (&optional up)
22659 "Mark the current subtree.
22660 This puts point at the start of the current subtree, and mark at
22661 the end. If a numeric prefix UP is given, move up into the
22662 hierarchy of headlines by UP levels before marking the subtree."
22663 (interactive "P")
22664 (org-with-limited-levels
22665 (cond ((org-at-heading-p) (beginning-of-line))
22666 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22667 (t (outline-previous-visible-heading 1))))
22668 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22669 (if (called-interactively-p 'any)
22670 (call-interactively 'org-mark-element)
22671 (org-mark-element)))
22673 (defun org-file-newer-than-p (file time)
22674 "Non-nil if FILE is newer than TIME.
22675 FILE is a filename, as a string, TIME is a list of integers, as
22676 returned by, e.g., `current-time'."
22677 (and (file-exists-p file)
22678 ;; Only compare times up to whole seconds as some file-systems
22679 ;; (e.g. HFS+) do not retain any finer granularity. As
22680 ;; a consequence, make sure we return non-nil when the two
22681 ;; times are equal.
22682 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22683 (cl-subseq time 0 2)))))
22685 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22686 "Compile a SOURCE file using PROCESS.
22688 PROCESS is either a function or a list of shell commands, as
22689 strings. EXT is a file extension, without the leading dot, as
22690 a string. It is used to check if the process actually succeeded.
22692 PROCESS must create a file with the same base name and directory
22693 as SOURCE, but ending with EXT. The function then returns its
22694 filename. Otherwise, it raises an error. The error message can
22695 then be refined by providing string ERR-MSG, which is appended to
22696 the standard message.
22698 If PROCESS is a function, it is called with a single argument:
22699 the SOURCE file.
22701 If it is a list of commands, each of them is called using
22702 `shell-command'. By default, in each command, %b, %f, %F, %o and
22703 %O are replaced with, respectively, SOURCE base name, name, full
22704 name, directory and absolute output file name. It is possible,
22705 however, to use more place-holders by specifying them in optional
22706 argument SPEC, as an alist following the pattern
22708 (CHARACTER . REPLACEMENT-STRING).
22710 When PROCESS is a list of commands, optional argument LOG-BUF can
22711 be set to a buffer or a buffer name. `shell-command' then uses
22712 it for output."
22713 (let* ((base-name (file-name-base source))
22714 (full-name (file-truename source))
22715 (out-dir (or (file-name-directory source) "./"))
22716 (output (expand-file-name (concat base-name "." ext) out-dir))
22717 (time (current-time))
22718 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22719 (save-window-excursion
22720 (pcase process
22721 ((pred functionp) (funcall process (shell-quote-argument source)))
22722 ((pred consp)
22723 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22724 (spec (append spec
22725 `((?b . ,(shell-quote-argument base-name))
22726 (?f . ,(shell-quote-argument source))
22727 (?F . ,(shell-quote-argument full-name))
22728 (?o . ,(shell-quote-argument out-dir))
22729 (?O . ,(shell-quote-argument output))))))
22730 (dolist (command process)
22731 (shell-command (format-spec command spec) log-buf))))
22732 (_ (error "No valid command to process %S%s" source err-msg))))
22733 ;; Check for process failure. Output file is expected to be
22734 ;; located in the same directory as SOURCE.
22735 (unless (org-file-newer-than-p output time)
22736 (error (format "File %S wasn't produced%s" output err-msg)))
22737 output))
22739 ;;; Indentation
22741 (defvar org-element-greater-elements)
22742 (defun org--get-expected-indentation (element contentsp)
22743 "Expected indentation column for current line, according to ELEMENT.
22744 ELEMENT is an element containing point. CONTENTSP is non-nil
22745 when indentation is to be computed according to contents of
22746 ELEMENT."
22747 (let ((type (org-element-type element))
22748 (start (org-element-property :begin element))
22749 (post-affiliated (org-element-property :post-affiliated element)))
22750 (org-with-wide-buffer
22751 (cond
22752 (contentsp
22753 (cl-case type
22754 ((diary-sexp footnote-definition) 0)
22755 ((headline inlinetask nil)
22756 (if (not org-adapt-indentation) 0
22757 (let ((level (org-current-level)))
22758 (if level (1+ level) 0))))
22759 ((item plain-list) (org-list-item-body-column post-affiliated))
22761 (goto-char start)
22762 (org-get-indentation))))
22763 ((memq type '(headline inlinetask nil))
22764 (if (org-match-line "[ \t]*$")
22765 (org--get-expected-indentation element t)
22767 ((memq type '(diary-sexp footnote-definition)) 0)
22768 ;; First paragraph of a footnote definition or an item.
22769 ;; Indent like parent.
22770 ((< (line-beginning-position) start)
22771 (org--get-expected-indentation
22772 (org-element-property :parent element) t))
22773 ;; At first line: indent according to previous sibling, if any,
22774 ;; ignoring footnote definitions and inline tasks, or parent's
22775 ;; contents.
22776 ((= (line-beginning-position) start)
22777 (catch 'exit
22778 (while t
22779 (if (= (point-min) start) (throw 'exit 0)
22780 (goto-char (1- start))
22781 (let* ((previous (org-element-at-point))
22782 (parent previous))
22783 (while (and parent (<= (org-element-property :end parent) start))
22784 (setq previous parent
22785 parent (org-element-property :parent parent)))
22786 (cond
22787 ((not previous) (throw 'exit 0))
22788 ((> (org-element-property :end previous) start)
22789 (throw 'exit (org--get-expected-indentation previous t)))
22790 ((memq (org-element-type previous)
22791 '(footnote-definition inlinetask))
22792 (setq start (org-element-property :begin previous)))
22793 (t (goto-char (org-element-property :begin previous))
22794 (throw 'exit
22795 (if (bolp) (org-get-indentation)
22796 ;; At first paragraph in an item or
22797 ;; a footnote definition.
22798 (org--get-expected-indentation
22799 (org-element-property :parent previous) t))))))))))
22800 ;; Otherwise, move to the first non-blank line above.
22802 (beginning-of-line)
22803 (let ((pos (point)))
22804 (skip-chars-backward " \r\t\n")
22805 (cond
22806 ;; Two blank lines end a footnote definition or a plain
22807 ;; list. When we indent an empty line after them, the
22808 ;; containing list or footnote definition is over, so it
22809 ;; qualifies as a previous sibling. Therefore, we indent
22810 ;; like its first line.
22811 ((and (memq type '(footnote-definition plain-list))
22812 (> (count-lines (point) pos) 2))
22813 (goto-char start)
22814 (org-get-indentation))
22815 ;; Line above is the first one of a paragraph at the
22816 ;; beginning of an item or a footnote definition. Indent
22817 ;; like parent.
22818 ((< (line-beginning-position) start)
22819 (org--get-expected-indentation
22820 (org-element-property :parent element) t))
22821 ;; Line above is the beginning of an element, i.e., point
22822 ;; was originally on the blank lines between element's start
22823 ;; and contents.
22824 ((= (line-beginning-position) post-affiliated)
22825 (org--get-expected-indentation element t))
22826 ;; POS is after contents in a greater element. Indent like
22827 ;; the beginning of the element.
22828 ((and (memq type org-element-greater-elements)
22829 (let ((cend (org-element-property :contents-end element)))
22830 (and cend (<= cend pos))))
22831 ;; As a special case, if point is at the end of a footnote
22832 ;; definition or an item, indent like the very last element
22833 ;; within. If that last element is an item, indent like
22834 ;; its contents.
22835 (if (memq type '(footnote-definition item plain-list))
22836 (let ((last (org-element-at-point)))
22837 (goto-char pos)
22838 (org--get-expected-indentation
22839 last (eq (org-element-type last) 'item)))
22840 (goto-char start)
22841 (org-get-indentation)))
22842 ;; In any other case, indent like the current line.
22843 (t (org-get-indentation)))))))))
22845 (defun org--align-node-property ()
22846 "Align node property at point.
22847 Alignment is done according to `org-property-format', which see."
22848 (when (save-excursion
22849 (beginning-of-line)
22850 (looking-at org-property-re))
22851 (replace-match
22852 (concat (match-string 4)
22853 (org-trim
22854 (format org-property-format (match-string 1) (match-string 3))))
22855 t t)))
22857 (defun org-indent-line ()
22858 "Indent line depending on context.
22860 Indentation is done according to the following rules:
22862 - Footnote definitions, diary sexps, headlines and inline tasks
22863 have to start at column 0.
22865 - On the very first line of an element, consider, in order, the
22866 next rules until one matches:
22868 1. If there's a sibling element before, ignoring footnote
22869 definitions and inline tasks, indent like its first line.
22871 2. If element has a parent, indent like its contents. More
22872 precisely, if parent is an item, indent after the
22873 description part, if any, or the bullet (see
22874 `org-list-description-max-indent'). Else, indent like
22875 parent's first line.
22877 3. Otherwise, indent relatively to current level, if
22878 `org-adapt-indentation' is non-nil, or to left margin.
22880 - On a blank line at the end of an element, indent according to
22881 the type of the element. More precisely
22883 1. If element is a plain list, an item, or a footnote
22884 definition, indent like the very last element within.
22886 2. If element is a paragraph, indent like its last non blank
22887 line.
22889 3. Otherwise, indent like its very first line.
22891 - In the code part of a source block, use language major mode
22892 to indent current line if `org-src-tab-acts-natively' is
22893 non-nil. If it is nil, do nothing.
22895 - Otherwise, indent like the first non-blank line above.
22897 The function doesn't indent an item as it could break the whole
22898 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22899 `\\[org-shiftmetaright]'.
22901 Also align node properties according to `org-property-format'."
22902 (interactive)
22903 (cond
22904 (orgstruct-is-++
22905 (let ((indent-line-function
22906 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22907 (indent-according-to-mode)))
22908 ((org-at-heading-p) 'noindent)
22910 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22911 (type (org-element-type element)))
22912 (cond ((and (memq type '(plain-list item))
22913 (= (line-beginning-position)
22914 (org-element-property :post-affiliated element)))
22915 'noindent)
22916 ((and (eq type 'latex-environment)
22917 (>= (point) (org-element-property :post-affiliated element))
22918 (< (point) (org-with-wide-buffer
22919 (goto-char (org-element-property :end element))
22920 (skip-chars-backward " \r\t\n")
22921 (line-beginning-position 2))))
22922 'noindent)
22923 ((and (eq type 'src-block)
22924 org-src-tab-acts-natively
22925 (> (line-beginning-position)
22926 (org-element-property :post-affiliated element))
22927 (< (line-beginning-position)
22928 (org-with-wide-buffer
22929 (goto-char (org-element-property :end element))
22930 (skip-chars-backward " \r\t\n")
22931 (line-beginning-position))))
22932 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22934 (let ((column (org--get-expected-indentation element nil)))
22935 ;; Preserve current column.
22936 (if (<= (current-column) (current-indentation))
22937 (indent-line-to column)
22938 (save-excursion (indent-line-to column))))
22939 ;; Align node property. Also preserve current column.
22940 (when (eq type 'node-property)
22941 (let ((column (current-column)))
22942 (org--align-node-property)
22943 (org-move-to-column column)))))))))
22945 (defun org-indent-region (start end)
22946 "Indent each non-blank line in the region.
22947 Called from a program, START and END specify the region to
22948 indent. The function will not indent contents of example blocks,
22949 verse blocks and export blocks as leading white spaces are
22950 assumed to be significant there."
22951 (interactive "r")
22952 (save-excursion
22953 (goto-char start)
22954 (skip-chars-forward " \r\t\n")
22955 (unless (eobp) (beginning-of-line))
22956 (let ((indent-to
22957 (lambda (ind pos)
22958 ;; Set IND as indentation for all lines between point and
22959 ;; POS. Blank lines are ignored. Leave point after POS
22960 ;; once done.
22961 (let ((limit (copy-marker pos)))
22962 (while (< (point) limit)
22963 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22964 (forward-line))
22965 (set-marker limit nil))))
22966 (end (copy-marker end)))
22967 (while (< (point) end)
22968 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22969 (let* ((element (org-element-at-point))
22970 (type (org-element-type element))
22971 (element-end (copy-marker (org-element-property :end element)))
22972 (ind (org--get-expected-indentation element nil)))
22973 (cond
22974 ;; Element indented as a single block. Example blocks
22975 ;; preserving indentation are a special case since the
22976 ;; "contents" must not be indented whereas the block
22977 ;; boundaries can.
22978 ((or (memq type '(export-block latex-environment))
22979 (and (eq type 'example-block)
22980 (not
22981 (or org-src-preserve-indentation
22982 (org-element-property :preserve-indent element)))))
22983 (let ((offset (- ind (org-get-indentation))))
22984 (unless (zerop offset)
22985 (indent-rigidly (org-element-property :begin element)
22986 (org-element-property :end element)
22987 offset)))
22988 (goto-char element-end))
22989 ;; Elements indented line wise. Be sure to exclude
22990 ;; example blocks (preserving indentation) and source
22991 ;; blocks from this category as they are treated
22992 ;; specially later.
22993 ((or (memq type '(paragraph table table-row))
22994 (not (or (org-element-property :contents-begin element)
22995 (memq type '(example-block src-block)))))
22996 (when (eq type 'node-property)
22997 (org--align-node-property)
22998 (beginning-of-line))
22999 (funcall indent-to ind (min element-end end)))
23000 ;; Elements consisting of three parts: before the
23001 ;; contents, the contents, and after the contents. The
23002 ;; contents are treated specially, according to the
23003 ;; element type, or not indented at all. Other parts are
23004 ;; indented as a single block.
23006 (let* ((post (copy-marker
23007 (org-element-property :post-affiliated element)))
23008 (cbeg
23009 (copy-marker
23010 (cond
23011 ((not (org-element-property :contents-begin element))
23012 ;; Fake contents for source blocks.
23013 (org-with-wide-buffer
23014 (goto-char post)
23015 (line-beginning-position 2)))
23016 ((memq type '(footnote-definition item plain-list))
23017 ;; Contents in these elements could start on
23018 ;; the same line as the beginning of the
23019 ;; element. Make sure we start indenting
23020 ;; from the second line.
23021 (org-with-wide-buffer
23022 (goto-char post)
23023 (end-of-line)
23024 (skip-chars-forward " \r\t\n")
23025 (if (eobp) (point) (line-beginning-position))))
23026 (t (org-element-property :contents-begin element)))))
23027 (cend (copy-marker
23028 (or (org-element-property :contents-end element)
23029 ;; Fake contents for source blocks.
23030 (org-with-wide-buffer
23031 (goto-char element-end)
23032 (skip-chars-backward " \r\t\n")
23033 (line-beginning-position)))
23034 t)))
23035 ;; Do not change items indentation individually as it
23036 ;; might break the list as a whole. On the other
23037 ;; hand, when at a plain list, indent it as a whole.
23038 (cond ((eq type 'plain-list)
23039 (let ((offset (- ind (org-get-indentation))))
23040 (unless (zerop offset)
23041 (indent-rigidly (org-element-property :begin element)
23042 (org-element-property :end element)
23043 offset))
23044 (goto-char cbeg)))
23045 ((eq type 'item) (goto-char cbeg))
23046 (t (funcall indent-to ind (min cbeg end))))
23047 (when (< (point) end)
23048 (cl-case type
23049 ((example-block verse-block))
23050 (src-block
23051 ;; In a source block, indent source code
23052 ;; according to language major mode, but only if
23053 ;; `org-src-tab-acts-natively' is non-nil.
23054 (when (and (< (point) end) org-src-tab-acts-natively)
23055 (ignore-errors
23056 (org-babel-do-in-edit-buffer
23057 (indent-region (point-min) (point-max))))))
23058 (t (org-indent-region (point) (min cend end))))
23059 (goto-char (min cend end))
23060 (when (< (point) end)
23061 (funcall indent-to ind (min element-end end))))
23062 (set-marker post nil)
23063 (set-marker cbeg nil)
23064 (set-marker cend nil))))
23065 (set-marker element-end nil))))
23066 (set-marker end nil))))
23068 (defun org-indent-drawer ()
23069 "Indent the drawer at point."
23070 (interactive)
23071 (unless (save-excursion
23072 (beginning-of-line)
23073 (looking-at-p org-drawer-regexp))
23074 (user-error "Not at a drawer"))
23075 (let ((element (org-element-at-point)))
23076 (unless (memq (org-element-type element) '(drawer property-drawer))
23077 (user-error "Not at a drawer"))
23078 (org-with-wide-buffer
23079 (org-indent-region (org-element-property :begin element)
23080 (org-element-property :end element))))
23081 (message "Drawer at point indented"))
23083 (defun org-indent-block ()
23084 "Indent the block at point."
23085 (interactive)
23086 (unless (save-excursion
23087 (beginning-of-line)
23088 (let ((case-fold-search t))
23089 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23090 (user-error "Not at a block"))
23091 (let ((element (org-element-at-point)))
23092 (unless (memq (org-element-type element)
23093 '(comment-block center-block dynamic-block example-block
23094 export-block quote-block special-block
23095 src-block verse-block))
23096 (user-error "Not at a block"))
23097 (org-with-wide-buffer
23098 (org-indent-region (org-element-property :begin element)
23099 (org-element-property :end element))))
23100 (message "Block at point indented"))
23103 ;;; Filling
23105 ;; We use our own fill-paragraph and auto-fill functions.
23107 ;; `org-fill-paragraph' relies on adaptive filling and context
23108 ;; checking. Appropriate `fill-prefix' is computed with
23109 ;; `org-adaptive-fill-function'.
23111 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23112 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23113 ;; `org-adaptive-fill-function' value. Internally,
23114 ;; `org-comment-line-break-function' breaks the line.
23116 ;; `org-setup-filling' installs filling and auto-filling related
23117 ;; variables during `org-mode' initialization.
23119 (defvar org-element-paragraph-separate) ; org-element.el
23120 (defun org-setup-filling ()
23121 (require 'org-element)
23122 ;; Prevent auto-fill from inserting unwanted new items.
23123 (when (boundp 'fill-nobreak-predicate)
23124 (setq-local
23125 fill-nobreak-predicate
23126 (org-uniquify
23127 (append fill-nobreak-predicate
23128 '(org-fill-line-break-nobreak-p
23129 org-fill-paragraph-with-timestamp-nobreak-p)))))
23130 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23131 (setq-local paragraph-start paragraph-ending)
23132 (setq-local paragraph-separate paragraph-ending))
23133 (setq-local fill-paragraph-function 'org-fill-paragraph)
23134 (setq-local auto-fill-inhibit-regexp nil)
23135 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23136 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23137 (setq-local comment-line-break-function 'org-comment-line-break-function))
23139 (defun org-fill-line-break-nobreak-p ()
23140 "Non-nil when a new line at point would create an Org line break."
23141 (save-excursion
23142 (skip-chars-backward "[ \t]")
23143 (skip-chars-backward "\\\\")
23144 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23146 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23147 "Non-nil when a new line at point would split a timestamp."
23148 (and (org-at-timestamp-p t)
23149 (not (looking-at org-ts-regexp-both))))
23151 (declare-function message-in-body-p "message" ())
23152 (defvar orgtbl-line-start-regexp) ; From org-table.el
23153 (defun org-adaptive-fill-function ()
23154 "Compute a fill prefix for the current line.
23155 Return fill prefix, as a string, or nil if current line isn't
23156 meant to be filled. For convenience, if `adaptive-fill-regexp'
23157 matches in paragraphs or comments, use it."
23158 (catch 'exit
23159 (when (derived-mode-p 'message-mode)
23160 (save-excursion
23161 (beginning-of-line)
23162 (cond ((not (message-in-body-p)) (throw 'exit nil))
23163 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23164 ((looking-at message-cite-prefix-regexp)
23165 (throw 'exit (match-string-no-properties 0)))
23166 ((looking-at org-outline-regexp)
23167 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23168 (org-with-wide-buffer
23169 (unless (org-at-heading-p)
23170 (let* ((p (line-beginning-position))
23171 (element (save-excursion
23172 (beginning-of-line)
23173 (org-element-at-point)))
23174 (type (org-element-type element))
23175 (post-affiliated (org-element-property :post-affiliated element)))
23176 (unless (< p post-affiliated)
23177 (cl-case type
23178 (comment
23179 (save-excursion
23180 (beginning-of-line)
23181 (looking-at "[ \t]*")
23182 (concat (match-string 0) "# ")))
23183 (footnote-definition "")
23184 ((item plain-list)
23185 (make-string (org-list-item-body-column post-affiliated) ?\s))
23186 (paragraph
23187 ;; Fill prefix is usually the same as the current line,
23188 ;; unless the paragraph is at the beginning of an item.
23189 (let ((parent (org-element-property :parent element)))
23190 (save-excursion
23191 (beginning-of-line)
23192 (cond ((eq (org-element-type parent) 'item)
23193 (make-string (org-list-item-body-column
23194 (org-element-property :begin parent))
23195 ?\s))
23196 ((and adaptive-fill-regexp
23197 ;; Locally disable
23198 ;; `adaptive-fill-function' to let
23199 ;; `fill-context-prefix' handle
23200 ;; `adaptive-fill-regexp' variable.
23201 (let (adaptive-fill-function)
23202 (fill-context-prefix
23203 post-affiliated
23204 (org-element-property :end element)))))
23205 ((looking-at "[ \t]+") (match-string 0))
23206 (t "")))))
23207 (comment-block
23208 ;; Only fill contents if P is within block boundaries.
23209 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23210 (forward-line)
23211 (point)))
23212 (cend (save-excursion
23213 (goto-char (org-element-property :end element))
23214 (skip-chars-backward " \r\t\n")
23215 (line-beginning-position))))
23216 (when (and (>= p cbeg) (< p cend))
23217 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23218 (match-string 0)
23219 "")))))))))))
23221 (declare-function message-goto-body "message" ())
23222 (defvar message-cite-prefix-regexp) ; From message.el
23223 (defun org-fill-paragraph (&optional justify)
23224 "Fill element at point, when applicable.
23226 This function only applies to comment blocks, comments, example
23227 blocks and paragraphs. Also, as a special case, re-align table
23228 when point is at one.
23230 If JUSTIFY is non-nil (interactively, with prefix argument),
23231 justify as well. If `sentence-end-double-space' is non-nil, then
23232 period followed by one space does not end a sentence, so don't
23233 break a line there. The variable `fill-column' controls the
23234 width for filling.
23236 For convenience, when point is at a plain list, an item or
23237 a footnote definition, try to fill the first paragraph within."
23238 (interactive)
23239 (if (and (derived-mode-p 'message-mode)
23240 (or (not (message-in-body-p))
23241 (save-excursion (move-beginning-of-line 1)
23242 (looking-at message-cite-prefix-regexp))))
23243 ;; First ensure filling is correct in message-mode.
23244 (let ((fill-paragraph-function
23245 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23246 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23247 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23248 (paragraph-separate
23249 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23250 (fill-paragraph nil))
23251 (with-syntax-table org-mode-transpose-word-syntax-table
23252 ;; Move to end of line in order to get the first paragraph
23253 ;; within a plain list or a footnote definition.
23254 (let ((element (save-excursion
23255 (end-of-line)
23256 (or (ignore-errors (org-element-at-point))
23257 (user-error "An element cannot be parsed line %d"
23258 (line-number-at-pos (point)))))))
23259 ;; First check if point is in a blank line at the beginning of
23260 ;; the buffer. In that case, ignore filling.
23261 (cl-case (org-element-type element)
23262 ;; Use major mode filling function is src blocks.
23263 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23264 ;; Align Org tables, leave table.el tables as-is.
23265 (table-row (org-table-align) t)
23266 (table
23267 (when (eq (org-element-property :type element) 'org)
23268 (save-excursion
23269 (goto-char (org-element-property :post-affiliated element))
23270 (org-table-align)))
23272 (paragraph
23273 ;; Paragraphs may contain `line-break' type objects.
23274 (let ((beg (max (point-min)
23275 (org-element-property :contents-begin element)))
23276 (end (min (point-max)
23277 (org-element-property :contents-end element))))
23278 ;; Do nothing if point is at an affiliated keyword.
23279 (if (< (line-end-position) beg) t
23280 (when (derived-mode-p 'message-mode)
23281 ;; In `message-mode', do not fill following citation
23282 ;; in current paragraph nor text before message body.
23283 (let ((body-start (save-excursion (message-goto-body))))
23284 (when body-start (setq beg (max body-start beg))))
23285 (when (save-excursion
23286 (re-search-forward
23287 (concat "^" message-cite-prefix-regexp) end t))
23288 (setq end (match-beginning 0))))
23289 ;; Fill paragraph, taking line breaks into account.
23290 (save-excursion
23291 (goto-char beg)
23292 (let ((cuts (list beg)))
23293 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23294 (when (eq 'line-break
23295 (org-element-type
23296 (save-excursion (backward-char)
23297 (org-element-context))))
23298 (push (point) cuts)))
23299 (dolist (c (delq end cuts))
23300 (fill-region-as-paragraph c end justify)
23301 (setq end c))))
23302 t)))
23303 ;; Contents of `comment-block' type elements should be
23304 ;; filled as plain text, but only if point is within block
23305 ;; markers.
23306 (comment-block
23307 (let* ((case-fold-search t)
23308 (beg (save-excursion
23309 (goto-char (org-element-property :begin element))
23310 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23311 (forward-line)
23312 (point)))
23313 (end (save-excursion
23314 (goto-char (org-element-property :end element))
23315 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23316 (line-beginning-position))))
23317 (if (or (< (point) beg) (> (point) end)) t
23318 (fill-region-as-paragraph
23319 (save-excursion (end-of-line)
23320 (re-search-backward "^[ \t]*$" beg 'move)
23321 (line-beginning-position))
23322 (save-excursion (beginning-of-line)
23323 (re-search-forward "^[ \t]*$" end 'move)
23324 (line-beginning-position))
23325 justify))))
23326 ;; Fill comments.
23327 (comment
23328 (let ((begin (org-element-property :post-affiliated element))
23329 (end (org-element-property :end element)))
23330 (when (and (>= (point) begin) (<= (point) end))
23331 (let ((begin (save-excursion
23332 (end-of-line)
23333 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23334 (progn (forward-line) (point))
23335 begin)))
23336 (end (save-excursion
23337 (end-of-line)
23338 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23339 (1- (line-beginning-position))
23340 (skip-chars-backward " \r\t\n")
23341 (line-end-position)))))
23342 ;; Do not fill comments when at a blank line.
23343 (when (> end begin)
23344 (let ((fill-prefix
23345 (save-excursion
23346 (beginning-of-line)
23347 (looking-at "[ \t]*#")
23348 (let ((comment-prefix (match-string 0)))
23349 (goto-char (match-end 0))
23350 (if (looking-at adaptive-fill-regexp)
23351 (concat comment-prefix (match-string 0))
23352 (concat comment-prefix " "))))))
23353 (save-excursion
23354 (fill-region-as-paragraph begin end justify))))))
23356 ;; Ignore every other element.
23357 (otherwise t))))))
23359 (defun org-auto-fill-function ()
23360 "Auto-fill function."
23361 ;; Check if auto-filling is meaningful.
23362 (let ((fc (current-fill-column)))
23363 (when (and fc (> (current-column) fc))
23364 (let* ((fill-prefix (org-adaptive-fill-function))
23365 ;; Enforce empty fill prefix, if required. Otherwise, it
23366 ;; will be computed again.
23367 (adaptive-fill-mode (not (equal fill-prefix ""))))
23368 (when fill-prefix (do-auto-fill))))))
23370 (defun org-comment-line-break-function (&optional soft)
23371 "Break line at point and indent, continuing comment if within one.
23372 The inserted newline is marked hard if variable
23373 `use-hard-newlines' is true, unless optional argument SOFT is
23374 non-nil."
23375 (if soft (insert-and-inherit ?\n) (newline 1))
23376 (save-excursion (forward-char -1) (delete-horizontal-space))
23377 (delete-horizontal-space)
23378 (indent-to-left-margin)
23379 (insert-before-markers-and-inherit fill-prefix))
23382 ;;; Fixed Width Areas
23384 (defun org-toggle-fixed-width ()
23385 "Toggle fixed-width markup.
23387 Add or remove fixed-width markup on current line, whenever it
23388 makes sense. Return an error otherwise.
23390 If a region is active and if it contains only fixed-width areas
23391 or blank lines, remove all fixed-width markup in it. If the
23392 region contains anything else, convert all non-fixed-width lines
23393 to fixed-width ones.
23395 Blank lines at the end of the region are ignored unless the
23396 region only contains such lines."
23397 (interactive)
23398 (if (not (org-region-active-p))
23399 ;; No region:
23401 ;; Remove fixed width marker only in a fixed-with element.
23403 ;; Add fixed width maker in paragraphs, in blank lines after
23404 ;; elements or at the beginning of a headline or an inlinetask,
23405 ;; and before any one-line elements (e.g., a clock).
23406 (progn
23407 (beginning-of-line)
23408 (let* ((element (org-element-at-point))
23409 (type (org-element-type element)))
23410 (cond
23411 ((and (eq type 'fixed-width)
23412 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23413 (replace-match
23414 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23415 ((and (memq type '(babel-call clock comment diary-sexp headline
23416 horizontal-rule keyword paragraph
23417 planning))
23418 (<= (org-element-property :post-affiliated element) (point)))
23419 (skip-chars-forward " \t")
23420 (insert ": "))
23421 ((and (looking-at-p "[ \t]*$")
23422 (or (eq type 'inlinetask)
23423 (save-excursion
23424 (skip-chars-forward " \r\t\n")
23425 (<= (org-element-property :end element) (point)))))
23426 (delete-region (point) (line-end-position))
23427 (org-indent-line)
23428 (insert ": "))
23429 (t (user-error "Cannot insert a fixed-width line here")))))
23430 ;; Region active.
23431 (let* ((begin (save-excursion
23432 (goto-char (region-beginning))
23433 (line-beginning-position)))
23434 (end (copy-marker
23435 (save-excursion
23436 (goto-char (region-end))
23437 (unless (eolp) (beginning-of-line))
23438 (if (save-excursion (re-search-backward "\\S-" begin t))
23439 (progn (skip-chars-backward " \r\t\n") (point))
23440 (point)))))
23441 (all-fixed-width-p
23442 (catch 'not-all-p
23443 (save-excursion
23444 (goto-char begin)
23445 (skip-chars-forward " \r\t\n")
23446 (when (eobp) (throw 'not-all-p nil))
23447 (while (< (point) end)
23448 (let ((element (org-element-at-point)))
23449 (if (eq (org-element-type element) 'fixed-width)
23450 (goto-char (org-element-property :end element))
23451 (throw 'not-all-p nil))))
23452 t))))
23453 (if all-fixed-width-p
23454 (save-excursion
23455 (goto-char begin)
23456 (while (< (point) end)
23457 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23458 (replace-match
23459 "" nil nil nil
23460 (if (= (line-end-position) (match-end 0)) 0 1)))
23461 (forward-line)))
23462 (let ((min-ind (point-max)))
23463 ;; Find minimum indentation across all lines.
23464 (save-excursion
23465 (goto-char begin)
23466 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23467 (setq min-ind 0)
23468 (catch 'zerop
23469 (while (< (point) end)
23470 (unless (looking-at-p "[ \t]*$")
23471 (let ((ind (org-get-indentation)))
23472 (setq min-ind (min min-ind ind))
23473 (when (zerop ind) (throw 'zerop t))))
23474 (forward-line)))))
23475 ;; Loop over all lines and add fixed-width markup everywhere
23476 ;; but in fixed-width lines.
23477 (save-excursion
23478 (goto-char begin)
23479 (while (< (point) end)
23480 (cond
23481 ((org-at-heading-p)
23482 (insert ": ")
23483 (forward-line)
23484 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23485 (insert ":")
23486 (forward-line)))
23487 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23488 (let* ((element (org-element-at-point))
23489 (element-end (org-element-property :end element)))
23490 (if (eq (org-element-type element) 'fixed-width)
23491 (progn (goto-char element-end)
23492 (skip-chars-backward " \r\t\n")
23493 (forward-line))
23494 (let ((limit (min end element-end)))
23495 (while (< (point) limit)
23496 (org-move-to-column min-ind t)
23497 (insert ": ")
23498 (forward-line))))))
23500 (org-move-to-column min-ind t)
23501 (insert ": ")
23502 (forward-line)))))))
23503 (set-marker end nil))))
23506 ;;; Comments
23508 ;; Org comments syntax is quite complex. It requires the entire line
23509 ;; to be just a comment. Also, even with the right syntax at the
23510 ;; beginning of line, some some elements (i.e. verse-block or
23511 ;; example-block) don't accept comments. Usual Emacs comment commands
23512 ;; cannot cope with those requirements. Therefore, Org replaces them.
23514 ;; Org still relies on `comment-dwim', but cannot trust
23515 ;; `comment-only-p'. So, `comment-region-function' and
23516 ;; `uncomment-region-function' both point
23517 ;; to`org-comment-or-uncomment-region'. Eventually,
23518 ;; `org-insert-comment' takes care of insertion of comments at the
23519 ;; beginning of line.
23521 ;; `org-setup-comments-handling' install comments related variables
23522 ;; during `org-mode' initialization.
23524 (defun org-setup-comments-handling ()
23525 (interactive)
23526 (setq-local comment-use-syntax nil)
23527 (setq-local comment-start "# ")
23528 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23529 (setq-local comment-insert-comment-function 'org-insert-comment)
23530 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23531 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23533 (defun org-insert-comment ()
23534 "Insert an empty comment above current line.
23535 If the line is empty, insert comment at its beginning. When
23536 point is within a source block, comment according to the related
23537 major mode."
23538 (if (let ((element (org-element-at-point)))
23539 (and (eq (org-element-type element) 'src-block)
23540 (< (save-excursion
23541 (goto-char (org-element-property :post-affiliated element))
23542 (line-end-position))
23543 (point))
23544 (> (save-excursion
23545 (goto-char (org-element-property :end element))
23546 (skip-chars-backward " \r\t\n")
23547 (line-beginning-position))
23548 (point))))
23549 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23550 (beginning-of-line)
23551 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23552 (open-line 1))
23553 (org-indent-line)
23554 (insert "# ")))
23556 (defvar comment-empty-lines) ; From newcomment.el.
23557 (defun org-comment-or-uncomment-region (beg end &rest _)
23558 "Comment or uncomment each non-blank line in the region.
23559 Uncomment each non-blank line between BEG and END if it only
23560 contains commented lines. Otherwise, comment them. If region is
23561 strictly within a source block, use appropriate comment syntax."
23562 (if (let ((element (org-element-at-point)))
23563 (and (eq (org-element-type element) 'src-block)
23564 (< (save-excursion
23565 (goto-char (org-element-property :post-affiliated element))
23566 (line-end-position))
23567 beg)
23568 (>= (save-excursion
23569 (goto-char (org-element-property :end element))
23570 (skip-chars-backward " \r\t\n")
23571 (line-beginning-position))
23572 end)))
23573 ;; Translate region boundaries for the Org buffer to the source
23574 ;; buffer.
23575 (let ((offset (- end beg)))
23576 (save-excursion
23577 (goto-char beg)
23578 (org-babel-do-in-edit-buffer
23579 (comment-or-uncomment-region (point) (+ offset (point))))))
23580 (save-restriction
23581 ;; Restrict region
23582 (narrow-to-region (save-excursion (goto-char beg)
23583 (skip-chars-forward " \r\t\n" end)
23584 (line-beginning-position))
23585 (save-excursion (goto-char end)
23586 (skip-chars-backward " \r\t\n" beg)
23587 (line-end-position)))
23588 (let ((uncommentp
23589 ;; UNCOMMENTP is non-nil when every non blank line between
23590 ;; BEG and END is a comment.
23591 (save-excursion
23592 (goto-char (point-min))
23593 (while (and (not (eobp))
23594 (let ((element (org-element-at-point)))
23595 (and (eq (org-element-type element) 'comment)
23596 (goto-char (min (point-max)
23597 (org-element-property
23598 :end element)))))))
23599 (eobp))))
23600 (if uncommentp
23601 ;; Only blank lines and comments in region: uncomment it.
23602 (save-excursion
23603 (goto-char (point-min))
23604 (while (not (eobp))
23605 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23606 (replace-match "" nil nil nil 1))
23607 (forward-line)))
23608 ;; Comment each line in region.
23609 (let ((min-indent (point-max)))
23610 ;; First find the minimum indentation across all lines.
23611 (save-excursion
23612 (goto-char (point-min))
23613 (while (and (not (eobp)) (not (zerop min-indent)))
23614 (unless (looking-at "[ \t]*$")
23615 (setq min-indent (min min-indent (current-indentation))))
23616 (forward-line)))
23617 ;; Then loop over all lines.
23618 (save-excursion
23619 (goto-char (point-min))
23620 (while (not (eobp))
23621 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23622 ;; Don't get fooled by invisible text (e.g. link path)
23623 ;; when moving to column MIN-INDENT.
23624 (let ((buffer-invisibility-spec nil))
23625 (org-move-to-column min-indent t))
23626 (insert comment-start))
23627 (forward-line)))))))))
23629 (defun org-comment-dwim (_arg)
23630 "Call `comment-dwim' within a source edit buffer if needed."
23631 (interactive "*P")
23632 (if (org-in-src-block-p)
23633 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23634 (call-interactively 'comment-dwim)))
23637 ;;; Timestamps API
23639 ;; This section contains tools to operate on timestamp objects, as
23640 ;; returned by, e.g. `org-element-context'.
23642 (defun org-timestamp--to-internal-time (timestamp &optional end)
23643 "Encode TIMESTAMP object into Emacs internal time.
23644 Use end of date range or time range when END is non-nil."
23645 (apply #'encode-time
23646 (cons 0
23647 (mapcar
23648 (lambda (prop) (or (org-element-property prop timestamp) 0))
23649 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23650 '(:minute-start :hour-start :day-start :month-start
23651 :year-start))))))
23653 (defun org-timestamp-has-time-p (timestamp)
23654 "Non-nil when TIMESTAMP has a time specified."
23655 (org-element-property :hour-start timestamp))
23657 (defun org-timestamp-format (timestamp format &optional end utc)
23658 "Format a TIMESTAMP object into a string.
23660 FORMAT is a format specifier to be passed to
23661 `format-time-string'.
23663 When optional argument END is non-nil, use end of date-range or
23664 time-range, if possible.
23666 When optional argument UTC is non-nil, time will be expressed as
23667 Universal Time."
23668 (format-time-string
23669 format (org-timestamp--to-internal-time timestamp end)
23670 (and utc t)))
23672 (defun org-timestamp-split-range (timestamp &optional end)
23673 "Extract a TIMESTAMP object from a date or time range.
23675 END, when non-nil, means extract the end of the range.
23676 Otherwise, extract its start.
23678 Return a new timestamp object."
23679 (let ((type (org-element-property :type timestamp)))
23680 (if (memq type '(active inactive diary)) timestamp
23681 (let ((split-ts (org-element-copy timestamp)))
23682 ;; Set new type.
23683 (org-element-put-property
23684 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23685 ;; Copy start properties over end properties if END is
23686 ;; non-nil. Otherwise, copy end properties over `start' ones.
23687 (let ((p-alist '((:minute-start . :minute-end)
23688 (:hour-start . :hour-end)
23689 (:day-start . :day-end)
23690 (:month-start . :month-end)
23691 (:year-start . :year-end))))
23692 (dolist (p-cell p-alist)
23693 (org-element-put-property
23694 split-ts
23695 (funcall (if end #'car #'cdr) p-cell)
23696 (org-element-property
23697 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23698 ;; Eventually refresh `:raw-value'.
23699 (org-element-put-property split-ts :raw-value nil)
23700 (org-element-put-property
23701 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23703 (defun org-timestamp-translate (timestamp &optional boundary)
23704 "Translate TIMESTAMP object to custom format.
23706 Format string is defined in `org-time-stamp-custom-formats',
23707 which see.
23709 When optional argument BOUNDARY is non-nil, it is either the
23710 symbol `start' or `end'. In this case, only translate the
23711 starting or ending part of TIMESTAMP if it is a date or time
23712 range. Otherwise, translate both parts.
23714 Return timestamp as-is if `org-display-custom-times' is nil or if
23715 it has a `diary' type."
23716 (let ((type (org-element-property :type timestamp)))
23717 (if (or (not org-display-custom-times) (eq type 'diary))
23718 (org-element-interpret-data timestamp)
23719 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23720 org-time-stamp-custom-formats)))
23721 (if (and (not boundary) (memq type '(active-range inactive-range)))
23722 (concat (org-timestamp-format timestamp fmt)
23723 "--"
23724 (org-timestamp-format timestamp fmt t))
23725 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23729 ;;; Other stuff.
23731 (defvar reftex-docstruct-symbol)
23732 (defvar org--rds)
23734 (defun org-reftex-citation ()
23735 "Use reftex-citation to insert a citation into the buffer.
23736 This looks for a line like
23738 #+BIBLIOGRAPHY: foo plain option:-d
23740 and derives from it that foo.bib is the bibliography file relevant
23741 for this document. It then installs the necessary environment for RefTeX
23742 to work in this buffer and calls `reftex-citation' to insert a citation
23743 into the buffer.
23745 Export of such citations to both LaTeX and HTML is handled by the contributed
23746 package ox-bibtex by Taru Karttunen."
23747 (interactive)
23748 (let ((reftex-docstruct-symbol 'org--rds)
23749 org--rds bib)
23750 (org-with-wide-buffer
23751 (let ((case-fold-search t)
23752 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23753 (if (not (save-excursion
23754 (or (re-search-forward re nil t)
23755 (re-search-backward re nil t))))
23756 (user-error "No bibliography defined in file")
23757 (setq bib (concat (match-string 1) ".bib")
23758 org--rds (list (list 'bib bib))))))
23759 (call-interactively 'reftex-citation)))
23761 ;;;; Functions extending outline functionality
23763 (defun org-beginning-of-line (&optional n)
23764 "Go to the beginning of the current visible line.
23766 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23767 tags on the first attempt, and only move to after the tags when
23768 the cursor is already beyond the end of the headline.
23770 With argument N not nil or 1, move forward N - 1 lines first."
23771 (interactive "^p")
23772 (let ((origin (point))
23773 (special (pcase org-special-ctrl-a/e
23774 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23775 deactivate-mark)
23776 ;; First move to a visible line.
23777 (if (bound-and-true-p visual-line-mode)
23778 (beginning-of-visual-line n)
23779 (move-beginning-of-line n)
23780 ;; `move-beginning-of-line' may leave point after invisible
23781 ;; characters if line starts with such of these (e.g., with
23782 ;; a link at column 0). Really move to the beginning of the
23783 ;; current visible line.
23784 (beginning-of-line))
23785 (cond
23786 ;; No special behavior. Point is already at the beginning of
23787 ;; a line, logical or visual.
23788 ((not special))
23789 ;; `beginning-of-visual-line' left point before logical beginning
23790 ;; of line: point is at the beginning of a visual line. Bail
23791 ;; out.
23792 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23793 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23794 ;; At a headline, special position is before the title, but
23795 ;; after any TODO keyword or priority cookie.
23796 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23797 (line-end-position)))
23798 (bol (point)))
23799 (if (eq special 'reversed)
23800 (when (and (= origin bol) (eq last-command this-command))
23801 (goto-char refpos))
23802 (when (or (> origin refpos) (= origin bol))
23803 (goto-char refpos)))))
23804 ((and (looking-at org-list-full-item-re)
23805 (memq (org-element-type (save-match-data (org-element-at-point)))
23806 '(item plain-list)))
23807 ;; Set special position at first white space character after
23808 ;; bullet, and check-box, if any.
23809 (let ((after-bullet
23810 (let ((box (match-end 3)))
23811 (cond ((not box) (match-end 1))
23812 ((eq (char-after box) ?\s) (1+ box))
23813 (t box)))))
23814 (if (eq special 'reversed)
23815 (when (and (= (point) origin) (eq last-command this-command))
23816 (goto-char after-bullet))
23817 (when (or (> origin after-bullet) (= (point) origin))
23818 (goto-char after-bullet)))))
23819 ;; No special context. Point is already at beginning of line.
23820 (t nil))))
23822 (defun org-end-of-line (&optional n)
23823 "Go to the end of the line, but before ellipsis, if any.
23825 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23826 tags on the first attempt, and only move to after the tags when
23827 the cursor is already beyond the end of the headline.
23829 With argument N not nil or 1, move forward N - 1 lines first."
23830 (interactive "^p")
23831 (let ((origin (point))
23832 (special (pcase org-special-ctrl-a/e
23833 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23834 deactivate-mark)
23835 ;; First move to a visible line.
23836 (if (bound-and-true-p visual-line-mode)
23837 (beginning-of-visual-line n)
23838 (move-beginning-of-line n))
23839 (cond
23840 ;; At a headline, with tags.
23841 ((and special
23842 (save-excursion
23843 (beginning-of-line)
23844 (let ((case-fold-search nil))
23845 (looking-at org-complex-heading-regexp)))
23846 (match-end 5))
23847 (let ((tags (save-excursion
23848 (goto-char (match-beginning 5))
23849 (skip-chars-backward " \t")
23850 (point)))
23851 (visual-end (and (bound-and-true-p visual-line-mode)
23852 (save-excursion
23853 (end-of-visual-line)
23854 (point)))))
23855 ;; If `end-of-visual-line' brings us before end of line or
23856 ;; even tags, i.e., the headline spans over multiple visual
23857 ;; lines, move there.
23858 (cond ((and visual-end
23859 (< visual-end tags)
23860 (<= origin visual-end))
23861 (goto-char visual-end))
23862 ((eq special 'reversed)
23863 (if (and (= origin (line-end-position))
23864 (eq this-command last-command))
23865 (goto-char tags)
23866 (end-of-line)))
23868 (if (or (< origin tags) (= origin (line-end-position)))
23869 (goto-char tags)
23870 (end-of-line))))))
23871 ((bound-and-true-p visual-line-mode)
23872 (let ((bol (line-beginning-position)))
23873 (end-of-visual-line)
23874 ;; If `end-of-visual-line' gets us past the ellipsis at the
23875 ;; end of a line, backtrack and use `end-of-line' instead.
23876 (when (/= bol (line-beginning-position))
23877 (goto-char bol)
23878 (end-of-line))))
23879 (t (end-of-line)))))
23881 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23882 (define-key org-mode-map "\C-e" 'org-end-of-line)
23884 (defun org-backward-sentence (&optional _arg)
23885 "Go to beginning of sentence, or beginning of table field.
23886 This will call `backward-sentence' or `org-table-beginning-of-field',
23887 depending on context."
23888 (interactive)
23889 (let* ((element (org-element-at-point))
23890 (contents-begin (org-element-property :contents-begin element))
23891 (table (org-element-lineage element '(table) t)))
23892 (if (and table
23893 (> (point) contents-begin)
23894 (<= (point) (org-element-property :contents-end table)))
23895 (call-interactively #'org-table-beginning-of-field)
23896 (save-restriction
23897 (when (and contents-begin
23898 (< (point-min) contents-begin)
23899 (> (point) contents-begin))
23900 (narrow-to-region contents-begin
23901 (org-element-property :contents-end element)))
23902 (call-interactively #'backward-sentence)))))
23904 (defun org-forward-sentence (&optional _arg)
23905 "Go to end of sentence, or end of table field.
23906 This will call `forward-sentence' or `org-table-end-of-field',
23907 depending on context."
23908 (interactive)
23909 (let* ((element (org-element-at-point))
23910 (contents-end (org-element-property :contents-end element))
23911 (table (org-element-lineage element '(table) t)))
23912 (if (and table
23913 (>= (point) (org-element-property :contents-begin table))
23914 (< (point) contents-end))
23915 (call-interactively #'org-table-end-of-field)
23916 (save-restriction
23917 (when (and contents-end
23918 (> (point-max) contents-end)
23919 ;; Skip blank lines between elements.
23920 (< (org-element-property :end element)
23921 (save-excursion (goto-char contents-end)
23922 (skip-chars-forward " \r\t\n"))))
23923 (narrow-to-region (org-element-property :contents-begin element)
23924 contents-end))
23925 (call-interactively #'forward-sentence)))))
23927 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23928 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23930 (defun org-kill-line (&optional _arg)
23931 "Kill line, to tags or end of line."
23932 (interactive)
23933 (cond
23934 ((or (not org-special-ctrl-k)
23935 (bolp)
23936 (not (org-at-heading-p)))
23937 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23938 org-ctrl-k-protect-subtree
23939 (or (eq org-ctrl-k-protect-subtree 'error)
23940 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23941 (user-error "C-k aborted as it would kill a hidden subtree"))
23942 (call-interactively
23943 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23944 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23945 (kill-region (point) (match-beginning 1))
23946 (org-set-tags nil t))
23947 (t (kill-region (point) (point-at-eol)))))
23949 (define-key org-mode-map "\C-k" 'org-kill-line)
23951 (defun org-yank (&optional arg)
23952 "Yank. If the kill is a subtree, treat it specially.
23953 This command will look at the current kill and check if is a single
23954 subtree, or a series of subtrees[1]. If it passes the test, and if the
23955 cursor is at the beginning of a line or after the stars of a currently
23956 empty headline, then the yank is handled specially. How exactly depends
23957 on the value of the following variables.
23959 `org-yank-folded-subtrees'
23960 By default, this variable is non-nil, which results in
23961 subtree(s) being folded after insertion, except if doing so
23962 would swallow text after the yanked text.
23964 `org-yank-adjusted-subtrees'
23965 When non-nil (the default value is nil), the subtree will be
23966 promoted or demoted in order to fit into the local outline tree
23967 structure, which means that the level will be adjusted so that it
23968 becomes the smaller one of the two *visible* surrounding headings.
23970 Any prefix to this command will cause `yank' to be called directly with
23971 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23972 will just
23973 plainly yank the text as it is.
23975 \[1] The test checks if the first non-white line is a heading
23976 and if there are no other headings with fewer stars."
23977 (interactive "P")
23978 (org-yank-generic 'yank arg))
23980 (defun org-yank-generic (command arg)
23981 "Perform some yank-like command.
23983 This function implements the behavior described in the `org-yank'
23984 documentation. However, it has been generalized to work for any
23985 interactive command with similar behavior."
23987 ;; pretend to be command COMMAND
23988 (setq this-command command)
23990 (if arg
23991 (call-interactively command)
23993 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23994 (and (org-kill-is-subtree-p)
23995 (or (bolp)
23996 (and (looking-at "[ \t]*$")
23997 (string-match
23998 "\\`\\*+\\'"
23999 (buffer-substring (point-at-bol) (point)))))))
24000 swallowp)
24001 (cond
24002 ((and subtreep org-yank-folded-subtrees)
24003 (let ((beg (point))
24004 end)
24005 (if (and subtreep org-yank-adjusted-subtrees)
24006 (org-paste-subtree nil nil 'for-yank)
24007 (call-interactively command))
24009 (setq end (point))
24010 (goto-char beg)
24011 (when (and (bolp) subtreep
24012 (not (setq swallowp
24013 (org-yank-folding-would-swallow-text beg end))))
24014 (org-with-limited-levels
24015 (or (looking-at org-outline-regexp)
24016 (re-search-forward org-outline-regexp-bol end t))
24017 (while (and (< (point) end) (looking-at org-outline-regexp))
24018 (outline-hide-subtree)
24019 (org-cycle-show-empty-lines 'folded)
24020 (condition-case nil
24021 (outline-forward-same-level 1)
24022 (error (goto-char end))))))
24023 (when swallowp
24024 (message
24025 "Inserted text not folded because that would swallow text"))
24027 (goto-char end)
24028 (skip-chars-forward " \t\n\r")
24029 (beginning-of-line 1)
24030 (push-mark beg 'nomsg)))
24031 ((and subtreep org-yank-adjusted-subtrees)
24032 (let ((beg (point-at-bol)))
24033 (org-paste-subtree nil nil 'for-yank)
24034 (push-mark beg 'nomsg)))
24036 (call-interactively command))))))
24038 (defun org-yank-folding-would-swallow-text (beg end)
24039 "Would hide-subtree at BEG swallow any text after END?"
24040 (let (level)
24041 (org-with-limited-levels
24042 (save-excursion
24043 (goto-char beg)
24044 (when (or (looking-at org-outline-regexp)
24045 (re-search-forward org-outline-regexp-bol end t))
24046 (setq level (org-outline-level)))
24047 (goto-char end)
24048 (skip-chars-forward " \t\r\n\v\f")
24049 (not (or (eobp)
24050 (and (bolp) (looking-at-p org-outline-regexp)
24051 (<= (org-outline-level) level))))))))
24053 (define-key org-mode-map "\C-y" 'org-yank)
24055 (defun org-truely-invisible-p ()
24056 "Check if point is at a character currently not visible.
24057 This version does not only check the character property, but also
24058 `visible-mode'."
24059 (unless (bound-and-true-p visible-mode)
24060 (org-invisible-p)))
24062 (defun org-invisible-p2 ()
24063 "Check if point is at a character currently not visible.
24065 If the point is at EOL (and not at the beginning of a buffer too),
24066 move it back by one char before doing this check."
24067 (save-excursion
24068 (when (and (eolp) (not (bobp)))
24069 (backward-char 1))
24070 (org-invisible-p)))
24072 (defun org-back-to-heading (&optional invisible-ok)
24073 "Call `outline-back-to-heading', but provide a better error message."
24074 (condition-case nil
24075 (outline-back-to-heading invisible-ok)
24076 (error (error "Before first headline at position %d in buffer %s"
24077 (point) (current-buffer)))))
24079 (defun org-before-first-heading-p ()
24080 "Before first heading?"
24081 (save-excursion
24082 (end-of-line)
24083 (null (re-search-backward org-outline-regexp-bol nil t))))
24085 (defun org-at-heading-p (&optional ignored)
24086 (outline-on-heading-p t))
24088 (defun org-in-commented-heading-p (&optional no-inheritance)
24089 "Non-nil if point is under a commented heading.
24090 This function also checks ancestors of the current headline,
24091 unless optional argument NO-INHERITANCE is non-nil."
24092 (cond
24093 ((org-before-first-heading-p) nil)
24094 ((let ((headline (nth 4 (org-heading-components))))
24095 (and headline
24096 (let ((case-fold-search nil))
24097 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24098 headline)))))
24099 (no-inheritance nil)
24101 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24103 (defun org-at-comment-p nil
24104 "Is cursor in a commented line?"
24105 (save-excursion
24106 (save-match-data
24107 (beginning-of-line)
24108 (looking-at "^[ \t]*# "))))
24110 (defun org-at-drawer-p nil
24111 "Is cursor at a drawer keyword?"
24112 (save-excursion
24113 (move-beginning-of-line 1)
24114 (looking-at org-drawer-regexp)))
24116 (defun org-at-block-p nil
24117 "Is cursor at a block keyword?"
24118 (save-excursion
24119 (move-beginning-of-line 1)
24120 (looking-at org-block-regexp)))
24122 (defun org-point-at-end-of-empty-headline ()
24123 "If point is at the end of an empty headline, return t, else nil.
24124 If the heading only contains a TODO keyword, it is still still considered
24125 empty."
24126 (let ((case-fold-search nil))
24127 (and (looking-at "[ \t]*$")
24128 org-todo-line-regexp
24129 (save-excursion
24130 (beginning-of-line)
24131 (looking-at org-todo-line-regexp)
24132 (string= (match-string 3) "")))))
24134 (defun org-at-heading-or-item-p ()
24135 (or (org-at-heading-p) (org-at-item-p)))
24137 (defun org-at-target-p ()
24138 (or (org-in-regexp org-radio-target-regexp)
24139 (org-in-regexp org-target-regexp)))
24140 ;; Compatibility alias with Org versions < 7.8.03
24141 (defalias 'org-on-target-p 'org-at-target-p)
24143 (defun org-up-heading-all (arg)
24144 "Move to the heading line of which the present line is a subheading.
24145 This function considers both visible and invisible heading lines.
24146 With argument, move up ARG levels."
24147 (outline-up-heading arg t))
24149 (defun org-up-heading-safe ()
24150 "Move to the heading line of which the present line is a subheading.
24151 This version will not throw an error. It will return the level of the
24152 headline found, or nil if no higher level is found.
24154 Also, this function will be a lot faster than `outline-up-heading',
24155 because it relies on stars being the outline starters. This can really
24156 make a significant difference in outlines with very many siblings."
24157 (when (ignore-errors (org-back-to-heading t))
24158 (let ((level-up (1- (funcall outline-level))))
24159 (and (> level-up 0)
24160 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24161 (funcall outline-level)))))
24163 (defun org-first-sibling-p ()
24164 "Is this heading the first child of its parents?"
24165 (interactive)
24166 (let ((re org-outline-regexp-bol)
24167 level l)
24168 (unless (org-at-heading-p t)
24169 (user-error "Not at a heading"))
24170 (setq level (funcall outline-level))
24171 (save-excursion
24172 (if (not (re-search-backward re nil t))
24174 (setq l (funcall outline-level))
24175 (< l level)))))
24177 (defun org-goto-sibling (&optional previous)
24178 "Goto the next sibling, even if it is invisible.
24179 When PREVIOUS is set, go to the previous sibling instead. Returns t
24180 when a sibling was found. When none is found, return nil and don't
24181 move point."
24182 (let ((fun (if previous 're-search-backward 're-search-forward))
24183 (pos (point))
24184 (re org-outline-regexp-bol)
24185 level l)
24186 (when (ignore-errors (org-back-to-heading t))
24187 (setq level (funcall outline-level))
24188 (catch 'exit
24189 (or previous (forward-char 1))
24190 (while (funcall fun re nil t)
24191 (setq l (funcall outline-level))
24192 (when (< l level) (goto-char pos) (throw 'exit nil))
24193 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24194 (goto-char pos)
24195 nil))))
24197 (defun org-show-siblings ()
24198 "Show all siblings of the current headline."
24199 (save-excursion
24200 (while (org-goto-sibling) (org-flag-heading nil)))
24201 (save-excursion
24202 (while (org-goto-sibling 'previous)
24203 (org-flag-heading nil))))
24205 (defun org-goto-first-child ()
24206 "Goto the first child, even if it is invisible.
24207 Return t when a child was found. Otherwise don't move point and
24208 return nil."
24209 (let (level (pos (point)) (re org-outline-regexp-bol))
24210 (when (ignore-errors (org-back-to-heading t))
24211 (setq level (outline-level))
24212 (forward-char 1)
24213 (if (and (re-search-forward re nil t) (> (outline-level) level))
24214 (progn (goto-char (match-beginning 0)) t)
24215 (goto-char pos) nil))))
24217 (defun org-show-hidden-entry ()
24218 "Show an entry where even the heading is hidden."
24219 (save-excursion
24220 (org-show-entry)))
24222 (defun org-flag-heading (flag &optional entry)
24223 "Flag the current heading. FLAG non-nil means make invisible.
24224 When ENTRY is non-nil, show the entire entry."
24225 (save-excursion
24226 (org-back-to-heading t)
24227 ;; Check if we should show the entire entry
24228 (if entry
24229 (progn
24230 (org-show-entry)
24231 (save-excursion
24232 (and (outline-next-heading)
24233 (org-flag-heading nil))))
24234 (outline-flag-region (max (point-min) (1- (point)))
24235 (save-excursion (outline-end-of-heading) (point))
24236 flag))))
24238 (defun org-get-next-sibling ()
24239 "Move to next heading of the same level, and return point.
24240 If there is no such heading, return nil.
24241 This is like outline-next-sibling, but invisible headings are ok."
24242 (let ((level (funcall outline-level)))
24243 (outline-next-heading)
24244 (while (and (not (eobp)) (> (funcall outline-level) level))
24245 (outline-next-heading))
24246 (unless (or (eobp) (< (funcall outline-level) level))
24247 (point))))
24249 (defun org-get-last-sibling ()
24250 "Move to previous heading of the same level, and return point.
24251 If there is no such heading, return nil."
24252 (let ((opoint (point))
24253 (level (funcall outline-level)))
24254 (outline-previous-heading)
24255 (when (and (/= (point) opoint) (outline-on-heading-p t))
24256 (while (and (> (funcall outline-level) level)
24257 (not (bobp)))
24258 (outline-previous-heading))
24259 (unless (< (funcall outline-level) level)
24260 (point)))))
24262 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24263 "Goto to the end of a subtree."
24264 ;; This contains an exact copy of the original function, but it uses
24265 ;; `org-back-to-heading', to make it work also in invisible
24266 ;; trees. And is uses an invisible-ok argument.
24267 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24268 ;; Furthermore, when used inside Org, finding the end of a large subtree
24269 ;; with many children and grandchildren etc, this can be much faster
24270 ;; than the outline version.
24271 (org-back-to-heading invisible-ok)
24272 (let ((first t)
24273 (level (funcall outline-level)))
24274 (if (and (derived-mode-p 'org-mode) (< level 1000))
24275 ;; A true heading (not a plain list item), in Org
24276 ;; This means we can easily find the end by looking
24277 ;; only for the right number of stars. Using a regexp to do
24278 ;; this is so much faster than using a Lisp loop.
24279 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24280 (forward-char 1)
24281 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24282 ;; something else, do it the slow way
24283 (while (and (not (eobp))
24284 (or first (> (funcall outline-level) level)))
24285 (setq first nil)
24286 (outline-next-heading)))
24287 (unless to-heading
24288 (when (memq (preceding-char) '(?\n ?\^M))
24289 ;; Go to end of line before heading
24290 (forward-char -1)
24291 (when (memq (preceding-char) '(?\n ?\^M))
24292 ;; leave blank line before heading
24293 (forward-char -1)))))
24294 (point))
24296 (defun org-end-of-meta-data (&optional full)
24297 "Skip planning line and properties drawer in current entry.
24298 When optional argument FULL is non-nil, also skip empty lines,
24299 clocking lines and regular drawers at the beginning of the
24300 entry."
24301 (org-back-to-heading t)
24302 (forward-line)
24303 (when (looking-at-p org-planning-line-re) (forward-line))
24304 (when (looking-at org-property-drawer-re)
24305 (goto-char (match-end 0))
24306 (forward-line))
24307 (when (and full (not (org-at-heading-p)))
24308 (catch 'exit
24309 (let ((end (save-excursion (outline-next-heading) (point)))
24310 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24311 (while (not (eobp))
24312 (cond ((looking-at-p org-drawer-regexp)
24313 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24314 (forward-line)
24315 (throw 'exit t)))
24316 ((looking-at-p re) (forward-line))
24317 (t (throw 'exit t))))))))
24319 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24320 "Move forward to the ARG'th subheading at same level as this one.
24321 Stop at the first and last subheadings of a superior heading.
24322 Normally this only looks at visible headings, but when INVISIBLE-OK is
24323 non-nil it will also look at invisible ones."
24324 (interactive "p")
24325 (let ((backward? (and arg (< arg 0))))
24326 (if (org-before-first-heading-p)
24327 (if backward? (goto-char (point-min)) (outline-next-heading))
24328 (org-back-to-heading invisible-ok)
24329 (unless backward? (end-of-line)) ;do not match current headline
24330 (let ((level (- (match-end 0) (match-beginning 0) 1))
24331 (f (if backward? #'re-search-backward #'re-search-forward))
24332 (count (if arg (abs arg) 1))
24333 (result (point)))
24334 (while (and (> count 0)
24335 (funcall f org-outline-regexp-bol nil 'move))
24336 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24337 (cond ((< l level) (setq count 0))
24338 ((and (= l level)
24339 (or invisible-ok
24340 (not (org-invisible-p
24341 (line-beginning-position)))))
24342 (cl-decf count)
24343 (when (= l level) (setq result (point)))))))
24344 (goto-char result))
24345 (beginning-of-line))))
24347 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24348 "Move backward to the ARG'th subheading at same level as this one.
24349 Stop at the first and last subheadings of a superior heading."
24350 (interactive "p")
24351 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24353 (defun org-next-visible-heading (arg)
24354 "Move to the next visible heading.
24356 This function wraps `outline-next-visible-heading' with
24357 `org-with-limited-levels' in order to skip over inline tasks and
24358 respect customization of `org-odd-levels-only'."
24359 (interactive "p")
24360 (org-with-limited-levels
24361 (outline-next-visible-heading arg)))
24363 (defun org-previous-visible-heading (arg)
24364 "Move to the previous visible heading.
24366 This function wraps `outline-previous-visible-heading' with
24367 `org-with-limited-levels' in order to skip over inline tasks and
24368 respect customization of `org-odd-levels-only'."
24369 (interactive "p")
24370 (org-with-limited-levels
24371 (outline-previous-visible-heading arg)))
24373 (defun org-next-block (arg &optional backward block-regexp)
24374 "Jump to the next block.
24376 With a prefix argument ARG, jump forward ARG many blocks.
24378 When BACKWARD is non-nil, jump to the previous block.
24380 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24381 Match data is set according to this regexp when the function
24382 returns.
24384 Return point at beginning of the opening line of found block.
24385 Throw an error if no block is found."
24386 (interactive "p")
24387 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24388 (case-fold-search t)
24389 (search-fn (if backward #'re-search-backward #'re-search-forward))
24390 (count (or arg 1))
24391 (origin (point))
24392 last-element)
24393 (if backward (beginning-of-line) (end-of-line))
24394 (while (and (> count 0) (funcall search-fn re nil t))
24395 (let ((element (save-excursion
24396 (goto-char (match-beginning 0))
24397 (save-match-data (org-element-at-point)))))
24398 (when (and (memq (org-element-type element)
24399 '(center-block comment-block dynamic-block
24400 example-block export-block quote-block
24401 special-block src-block verse-block))
24402 (<= (match-beginning 0)
24403 (org-element-property :post-affiliated element)))
24404 (setq last-element element)
24405 (cl-decf count))))
24406 (if (= count 0)
24407 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24408 (save-match-data (org-show-context)))
24409 (goto-char origin)
24410 (user-error "No %s code blocks" (if backward "previous" "further")))))
24412 (defun org-previous-block (arg &optional block-regexp)
24413 "Jump to the previous block.
24414 With a prefix argument ARG, jump backward ARG many source blocks.
24415 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24416 (interactive "p")
24417 (org-next-block arg t block-regexp))
24419 (defun org-forward-paragraph ()
24420 "Move forward to beginning of next paragraph or equivalent.
24422 The function moves point to the beginning of the next visible
24423 structural element, which can be a paragraph, a table, a list
24424 item, etc. It also provides some special moves for convenience:
24426 - On an affiliated keyword, jump to the beginning of the
24427 relative element.
24428 - On an item or a footnote definition, move to the second
24429 element inside, if any.
24430 - On a table or a property drawer, jump after it.
24431 - On a verse or source block, stop after blank lines."
24432 (interactive)
24433 (when (eobp) (user-error "Cannot move further down"))
24434 (let* ((deactivate-mark nil)
24435 (element (org-element-at-point))
24436 (type (org-element-type element))
24437 (post-affiliated (org-element-property :post-affiliated element))
24438 (contents-begin (org-element-property :contents-begin element))
24439 (contents-end (org-element-property :contents-end element))
24440 (end (let ((end (org-element-property :end element)) (parent element))
24441 (while (and (setq parent (org-element-property :parent parent))
24442 (= (org-element-property :contents-end parent) end))
24443 (setq end (org-element-property :end parent)))
24444 end)))
24445 (cond ((not element)
24446 (skip-chars-forward " \r\t\n")
24447 (or (eobp) (beginning-of-line)))
24448 ;; On affiliated keywords, move to element's beginning.
24449 ((< (point) post-affiliated)
24450 (goto-char post-affiliated))
24451 ;; At a table row, move to the end of the table. Similarly,
24452 ;; at a node property, move to the end of the property
24453 ;; drawer.
24454 ((memq type '(node-property table-row))
24455 (goto-char (org-element-property
24456 :end (org-element-property :parent element))))
24457 ((memq type '(property-drawer table)) (goto-char end))
24458 ;; Consider blank lines as separators in verse and source
24459 ;; blocks to ease editing.
24460 ((memq type '(src-block verse-block))
24461 (when (eq type 'src-block)
24462 (setq contents-end
24463 (save-excursion (goto-char end)
24464 (skip-chars-backward " \r\t\n")
24465 (line-beginning-position))))
24466 (beginning-of-line)
24467 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24468 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24469 (goto-char end)
24470 (skip-chars-forward " \r\t\n")
24471 (if (= (point) contents-end) (goto-char end)
24472 (beginning-of-line))))
24473 ;; With no contents, just skip element.
24474 ((not contents-begin) (goto-char end))
24475 ;; If contents are invisible, skip the element altogether.
24476 ((org-invisible-p (line-end-position))
24477 (cl-case type
24478 (headline
24479 (org-with-limited-levels (outline-next-visible-heading 1)))
24480 ;; At a plain list, make sure we move to the next item
24481 ;; instead of skipping the whole list.
24482 (plain-list (forward-char)
24483 (org-forward-paragraph))
24484 (otherwise (goto-char end))))
24485 ((>= (point) contents-end) (goto-char end))
24486 ((>= (point) contents-begin)
24487 ;; This can only happen on paragraphs and plain lists.
24488 (cl-case type
24489 (paragraph (goto-char end))
24490 ;; At a plain list, try to move to second element in
24491 ;; first item, if possible.
24492 (plain-list (end-of-line)
24493 (org-forward-paragraph))))
24494 ;; When contents start on the middle of a line (e.g. in
24495 ;; items and footnote definitions), try to reach first
24496 ;; element starting after current line.
24497 ((> (line-end-position) contents-begin)
24498 (end-of-line)
24499 (org-forward-paragraph))
24500 (t (goto-char contents-begin)))))
24502 (defun org-backward-paragraph ()
24503 "Move backward to start of previous paragraph or equivalent.
24505 The function moves point to the beginning of the current
24506 structural element, which can be a paragraph, a table, a list
24507 item, etc., or to the beginning of the previous visible one if
24508 point is already there. It also provides some special moves for
24509 convenience:
24511 - On an affiliated keyword, jump to the first one.
24512 - On a table or a property drawer, move to its beginning.
24513 - On a verse or source block, stop before blank lines."
24514 (interactive)
24515 (when (bobp) (user-error "Cannot move further up"))
24516 (let* ((deactivate-mark nil)
24517 (element (org-element-at-point))
24518 (type (org-element-type element))
24519 (contents-begin (org-element-property :contents-begin element))
24520 (contents-end (org-element-property :contents-end element))
24521 (post-affiliated (org-element-property :post-affiliated element))
24522 (begin (org-element-property :begin element)))
24523 (cond
24524 ((not element) (goto-char (point-min)))
24525 ((= (point) begin)
24526 (backward-char)
24527 (org-backward-paragraph))
24528 ((<= (point) post-affiliated) (goto-char begin))
24529 ((memq type '(node-property table-row))
24530 (goto-char (org-element-property
24531 :post-affiliated (org-element-property :parent element))))
24532 ((memq type '(property-drawer table)) (goto-char begin))
24533 ((memq type '(src-block verse-block))
24534 (when (eq type 'src-block)
24535 (setq contents-begin
24536 (save-excursion (goto-char begin) (forward-line) (point))))
24537 (if (= (point) contents-begin) (goto-char post-affiliated)
24538 ;; Inside a verse block, see blank lines as paragraph
24539 ;; separators.
24540 (let ((origin (point)))
24541 (skip-chars-backward " \r\t\n" contents-begin)
24542 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24543 (skip-chars-forward " \r\t\n" origin)
24544 (if (= (point) origin) (goto-char contents-begin)
24545 (beginning-of-line))))))
24546 ((not contents-begin) (goto-char (or post-affiliated begin)))
24547 ((eq type 'paragraph)
24548 (goto-char contents-begin)
24549 ;; When at first paragraph in an item or a footnote definition,
24550 ;; move directly to beginning of line.
24551 (let ((parent-contents
24552 (org-element-property
24553 :contents-begin (org-element-property :parent element))))
24554 (when (and parent-contents (= parent-contents contents-begin))
24555 (beginning-of-line))))
24556 ;; At the end of a greater element, move to the beginning of the
24557 ;; last element within.
24558 ((>= (point) contents-end)
24559 (goto-char (1- contents-end))
24560 (org-backward-paragraph))
24561 (t (goto-char (or post-affiliated begin))))
24562 ;; Ensure we never leave point invisible.
24563 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24565 (defun org-forward-element ()
24566 "Move forward by one element.
24567 Move to the next element at the same level, when possible."
24568 (interactive)
24569 (cond ((eobp) (user-error "Cannot move further down"))
24570 ((org-with-limited-levels (org-at-heading-p))
24571 (let ((origin (point)))
24572 (goto-char (org-end-of-subtree nil t))
24573 (unless (org-with-limited-levels (org-at-heading-p))
24574 (goto-char origin)
24575 (user-error "Cannot move further down"))))
24577 (let* ((elem (org-element-at-point))
24578 (end (org-element-property :end elem))
24579 (parent (org-element-property :parent elem)))
24580 (cond ((and parent (= (org-element-property :contents-end parent) end))
24581 (goto-char (org-element-property :end parent)))
24582 ((integer-or-marker-p end) (goto-char end))
24583 (t (message "No element at point")))))))
24585 (defun org-backward-element ()
24586 "Move backward by one element.
24587 Move to the previous element at the same level, when possible."
24588 (interactive)
24589 (cond ((bobp) (user-error "Cannot move further up"))
24590 ((org-with-limited-levels (org-at-heading-p))
24591 ;; At a headline, move to the previous one, if any, or stay
24592 ;; here.
24593 (let ((origin (point)))
24594 (org-with-limited-levels (org-backward-heading-same-level 1))
24595 ;; When current headline has no sibling above, move to its
24596 ;; parent.
24597 (when (= (point) origin)
24598 (or (org-with-limited-levels (org-up-heading-safe))
24599 (progn (goto-char origin)
24600 (user-error "Cannot move further up"))))))
24602 (let* ((elem (org-element-at-point))
24603 (beg (org-element-property :begin elem)))
24604 (cond
24605 ;; Move to beginning of current element if point isn't
24606 ;; there already.
24607 ((null beg) (message "No element at point"))
24608 ((/= (point) beg) (goto-char beg))
24609 (t (goto-char beg)
24610 (skip-chars-backward " \r\t\n")
24611 (unless (bobp)
24612 (let ((prev (org-element-at-point)))
24613 (goto-char (org-element-property :begin prev))
24614 (while (and (setq prev (org-element-property :parent prev))
24615 (<= (org-element-property :end prev) beg))
24616 (goto-char (org-element-property :begin prev)))))))))))
24618 (defun org-up-element ()
24619 "Move to upper element."
24620 (interactive)
24621 (if (org-with-limited-levels (org-at-heading-p))
24622 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24623 (let* ((elem (org-element-at-point))
24624 (parent (org-element-property :parent elem)))
24625 (if parent (goto-char (org-element-property :begin parent))
24626 (if (org-with-limited-levels (org-before-first-heading-p))
24627 (user-error "No surrounding element")
24628 (org-with-limited-levels (org-back-to-heading)))))))
24630 (defun org-down-element ()
24631 "Move to inner element."
24632 (interactive)
24633 (let ((element (org-element-at-point)))
24634 (cond
24635 ((memq (org-element-type element) '(plain-list table))
24636 (goto-char (org-element-property :contents-begin element))
24637 (forward-char))
24638 ((memq (org-element-type element) org-element-greater-elements)
24639 ;; If contents are hidden, first disclose them.
24640 (when (org-invisible-p (line-end-position)) (org-cycle))
24641 (goto-char (or (org-element-property :contents-begin element)
24642 (user-error "No content for this element"))))
24643 (t (user-error "No inner element")))))
24645 (defun org-drag-element-backward ()
24646 "Move backward element at point."
24647 (interactive)
24648 (let ((elem (or (org-element-at-point)
24649 (user-error "No element at point"))))
24650 (if (eq (org-element-type elem) 'headline)
24651 ;; Preserve point when moving a whole tree, even if point was
24652 ;; on blank lines below the headline.
24653 (let ((offset (skip-chars-backward " \t\n")))
24654 (unwind-protect (org-move-subtree-up)
24655 (forward-char (- offset))))
24656 (let ((prev-elem
24657 (save-excursion
24658 (goto-char (org-element-property :begin elem))
24659 (skip-chars-backward " \r\t\n")
24660 (unless (bobp)
24661 (let* ((beg (org-element-property :begin elem))
24662 (prev (org-element-at-point))
24663 (up prev))
24664 (while (and (setq up (org-element-property :parent up))
24665 (<= (org-element-property :end up) beg))
24666 (setq prev up))
24667 prev)))))
24668 ;; Error out if no previous element or previous element is
24669 ;; a parent of the current one.
24670 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24671 (user-error "Cannot drag element backward")
24672 (let ((pos (point)))
24673 (org-element-swap-A-B prev-elem elem)
24674 (goto-char (+ (org-element-property :begin prev-elem)
24675 (- pos (org-element-property :begin elem))))))))))
24677 (defun org-drag-element-forward ()
24678 "Move forward element at point."
24679 (interactive)
24680 (let* ((pos (point))
24681 (elem (or (org-element-at-point)
24682 (user-error "No element at point"))))
24683 (when (= (point-max) (org-element-property :end elem))
24684 (user-error "Cannot drag element forward"))
24685 (goto-char (org-element-property :end elem))
24686 (let ((next-elem (org-element-at-point)))
24687 (when (or (org-element-nested-p elem next-elem)
24688 (and (eq (org-element-type next-elem) 'headline)
24689 (not (eq (org-element-type elem) 'headline))))
24690 (goto-char pos)
24691 (user-error "Cannot drag element forward"))
24692 ;; Compute new position of point: it's shifted by NEXT-ELEM
24693 ;; body's length (without final blanks) and by the length of
24694 ;; blanks between ELEM and NEXT-ELEM.
24695 (let ((size-next (- (save-excursion
24696 (goto-char (org-element-property :end next-elem))
24697 (skip-chars-backward " \r\t\n")
24698 (forward-line)
24699 ;; Small correction if buffer doesn't end
24700 ;; with a newline character.
24701 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24702 (org-element-property :begin next-elem)))
24703 (size-blank (- (org-element-property :end elem)
24704 (save-excursion
24705 (goto-char (org-element-property :end elem))
24706 (skip-chars-backward " \r\t\n")
24707 (forward-line)
24708 (point)))))
24709 (org-element-swap-A-B elem next-elem)
24710 (goto-char (+ pos size-next size-blank))))))
24712 (defun org-drag-line-forward (arg)
24713 "Drag the line at point ARG lines forward."
24714 (interactive "p")
24715 (dotimes (_ (abs arg))
24716 (let ((c (current-column)))
24717 (if (< 0 arg)
24718 (progn
24719 (beginning-of-line 2)
24720 (transpose-lines 1)
24721 (beginning-of-line 0))
24722 (transpose-lines 1)
24723 (beginning-of-line -1))
24724 (org-move-to-column c))))
24726 (defun org-drag-line-backward (arg)
24727 "Drag the line at point ARG lines backward."
24728 (interactive "p")
24729 (org-drag-line-forward (- arg)))
24731 (defun org-mark-element ()
24732 "Put point at beginning of this element, mark at end.
24734 Interactively, if this command is repeated or (in Transient Mark
24735 mode) if the mark is active, it marks the next element after the
24736 ones already marked."
24737 (interactive)
24738 (let (deactivate-mark)
24739 (if (and (called-interactively-p 'any)
24740 (or (and (eq last-command this-command) (mark t))
24741 (and transient-mark-mode mark-active)))
24742 (set-mark
24743 (save-excursion
24744 (goto-char (mark))
24745 (goto-char (org-element-property :end (org-element-at-point)))))
24746 (let ((element (org-element-at-point)))
24747 (end-of-line)
24748 (push-mark (org-element-property :end element) t t)
24749 (goto-char (org-element-property :begin element))))))
24751 (defun org-narrow-to-element ()
24752 "Narrow buffer to current element."
24753 (interactive)
24754 (let ((elem (org-element-at-point)))
24755 (cond
24756 ((eq (car elem) 'headline)
24757 (narrow-to-region
24758 (org-element-property :begin elem)
24759 (org-element-property :end elem)))
24760 ((memq (car elem) org-element-greater-elements)
24761 (narrow-to-region
24762 (org-element-property :contents-begin elem)
24763 (org-element-property :contents-end elem)))
24765 (narrow-to-region
24766 (org-element-property :begin elem)
24767 (org-element-property :end elem))))))
24769 (defun org-transpose-element ()
24770 "Transpose current and previous elements, keeping blank lines between.
24771 Point is moved after both elements."
24772 (interactive)
24773 (org-skip-whitespace)
24774 (let ((end (org-element-property :end (org-element-at-point))))
24775 (org-drag-element-backward)
24776 (goto-char end)))
24778 (defun org-unindent-buffer ()
24779 "Un-indent the visible part of the buffer.
24780 Relative indentation (between items, inside blocks, etc.) isn't
24781 modified."
24782 (interactive)
24783 (unless (eq major-mode 'org-mode)
24784 (user-error "Cannot un-indent a buffer not in Org mode"))
24785 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24786 (unindent-tree
24787 (lambda (contents)
24788 (dolist (element (reverse contents))
24789 (if (memq (org-element-type element) '(headline section))
24790 (funcall unindent-tree (org-element-contents element))
24791 (save-excursion
24792 (save-restriction
24793 (narrow-to-region
24794 (org-element-property :begin element)
24795 (org-element-property :end element))
24796 (org-do-remove-indentation))))))))
24797 (funcall unindent-tree (org-element-contents parse-tree))))
24799 (defun org-show-children (&optional level)
24800 "Show all direct subheadings of this heading.
24801 Prefix arg LEVEL is how many levels below the current level
24802 should be shown. Default is enough to cause the following
24803 heading to appear."
24804 (interactive "p")
24805 ;; If `orgstruct-mode' is active, use the slower version.
24806 (if orgstruct-mode (call-interactively #'outline-show-children)
24807 (save-excursion
24808 (org-back-to-heading t)
24809 (let* ((current-level (funcall outline-level))
24810 (max-level (org-get-valid-level
24811 current-level
24812 (if level (prefix-numeric-value level) 1)))
24813 (end (save-excursion (org-end-of-subtree t t)))
24814 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24815 (past-first-child nil)
24816 ;; Make sure to skip inlinetasks.
24817 (re (format regexp-fmt
24818 current-level
24819 (cond
24820 ((not (featurep 'org-inlinetask)) "")
24821 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24823 (t (1- org-inlinetask-min-level))))))
24824 ;; Display parent heading.
24825 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24826 (forward-line)
24827 ;; Display children. First child may be deeper than expected
24828 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24829 ;; MAX-LEVEL accordingly.
24830 (while (re-search-forward re end t)
24831 (unless past-first-child
24832 (setq re (format regexp-fmt
24833 current-level
24834 (max (funcall outline-level) max-level)))
24835 (setq past-first-child t))
24836 (outline-flag-region
24837 (line-end-position 0) (line-end-position) nil))))))
24839 (defun org-show-subtree ()
24840 "Show everything after this heading at deeper levels."
24841 (interactive)
24842 (outline-flag-region
24843 (point)
24844 (save-excursion
24845 (org-end-of-subtree t t))
24846 nil))
24848 (defun org-show-entry ()
24849 "Show the body directly following this heading.
24850 Show the heading too, if it is currently invisible."
24851 (interactive)
24852 (save-excursion
24853 (ignore-errors
24854 (org-back-to-heading t)
24855 (outline-flag-region
24856 (max (point-min) (1- (point)))
24857 (save-excursion
24858 (if (re-search-forward
24859 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24860 (match-beginning 1)
24861 (point-max)))
24862 nil)
24863 (org-cycle-hide-drawers 'children))))
24865 (defun org-make-options-regexp (kwds &optional extra)
24866 "Make a regular expression for keyword lines.
24867 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24868 when non-nil, is a regexp matching keywords names."
24869 (concat "^[ \t]*#\\+\\("
24870 (regexp-opt kwds)
24871 (and extra (concat (and kwds "\\|") extra))
24872 "\\):[ \t]*\\(.*\\)"))
24874 ;;;; Integration with and fixes for other packages
24876 ;;; Imenu support
24878 (defvar-local org-imenu-markers nil
24879 "All markers currently used by Imenu.")
24881 (defun org-imenu-new-marker (&optional pos)
24882 "Return a new marker for use by Imenu, and remember the marker."
24883 (let ((m (make-marker)))
24884 (move-marker m (or pos (point)))
24885 (push m org-imenu-markers)
24888 (defun org-imenu-get-tree ()
24889 "Produce the index for Imenu."
24890 (dolist (x org-imenu-markers) (move-marker x nil))
24891 (setq org-imenu-markers nil)
24892 (let* ((case-fold-search nil)
24893 (n org-imenu-depth)
24894 (re (concat "^" (org-get-limited-outline-regexp)))
24895 (subs (make-vector (1+ n) nil))
24896 (last-level 0)
24897 m level head0 head)
24898 (org-with-wide-buffer
24899 (goto-char (point-max))
24900 (while (re-search-backward re nil t)
24901 (setq level (org-reduced-level (funcall outline-level)))
24902 (when (and (<= level n)
24903 (looking-at org-complex-heading-regexp)
24904 (setq head0 (match-string-no-properties 4)))
24905 (setq head (org-link-display-format head0)
24906 m (org-imenu-new-marker))
24907 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24908 (if (>= level last-level)
24909 (push (cons head m) (aref subs level))
24910 (push (cons head (aref subs (1+ level))) (aref subs level))
24911 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24912 (setq last-level level))))
24913 (aref subs 1)))
24915 (eval-after-load "imenu"
24916 '(progn
24917 (add-hook 'imenu-after-jump-hook
24918 (lambda ()
24919 (when (derived-mode-p 'org-mode)
24920 (org-show-context 'org-goto))))))
24922 (defun org-link-display-format (s)
24923 "Replace links in string S with their description.
24924 If there is no description, use the link target."
24925 (save-match-data
24926 (replace-regexp-in-string
24927 org-bracket-link-analytic-regexp
24928 (lambda (m)
24929 (if (match-end 5) (match-string 5 m)
24930 (concat (match-string 1 m) (match-string 3 m))))
24931 s nil t)))
24933 (defun org-toggle-link-display ()
24934 "Toggle the literal or descriptive display of links."
24935 (interactive)
24936 (if org-descriptive-links
24937 (progn (org-remove-from-invisibility-spec '(org-link))
24938 (org-restart-font-lock)
24939 (setq org-descriptive-links nil))
24940 (progn (add-to-invisibility-spec '(org-link))
24941 (org-restart-font-lock)
24942 (setq org-descriptive-links t))))
24944 ;; Speedbar support
24946 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24947 "Overlay marking the agenda restriction line in speedbar.")
24948 (overlay-put org-speedbar-restriction-lock-overlay
24949 'face 'org-agenda-restriction-lock)
24950 (overlay-put org-speedbar-restriction-lock-overlay
24951 'help-echo "Agendas are currently limited to this item.")
24952 (delete-overlay org-speedbar-restriction-lock-overlay)
24954 (defun org-speedbar-set-agenda-restriction ()
24955 "Restrict future agenda commands to the location at point in speedbar.
24956 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24957 (interactive)
24958 (require 'org-agenda)
24959 (let (p m tp np dir txt)
24960 (cond
24961 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24962 'org-imenu t))
24963 (setq m (get-text-property p 'org-imenu-marker))
24964 (with-current-buffer (marker-buffer m)
24965 (goto-char m)
24966 (org-agenda-set-restriction-lock 'subtree)))
24967 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24968 'speedbar-function 'speedbar-find-file))
24969 (setq tp (previous-single-property-change
24970 (1+ p) 'speedbar-function)
24971 np (next-single-property-change
24972 tp 'speedbar-function)
24973 dir (speedbar-line-directory)
24974 txt (buffer-substring-no-properties (or tp (point-min))
24975 (or np (point-max))))
24976 (with-current-buffer (find-file-noselect
24977 (let ((default-directory dir))
24978 (expand-file-name txt)))
24979 (unless (derived-mode-p 'org-mode)
24980 (user-error "Cannot restrict to non-Org mode file"))
24981 (org-agenda-set-restriction-lock 'file)))
24982 (t (user-error "Don't know how to restrict Org mode agenda")))
24983 (move-overlay org-speedbar-restriction-lock-overlay
24984 (point-at-bol) (point-at-eol))
24985 (setq current-prefix-arg nil)
24986 (org-agenda-maybe-redo)))
24988 (defvar speedbar-file-key-map)
24989 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24990 (eval-after-load "speedbar"
24991 '(progn
24992 (speedbar-add-supported-extension ".org")
24993 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24994 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24995 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24996 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24997 (add-hook 'speedbar-visiting-tag-hook
24998 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25000 ;;; Fixes and Hacks for problems with other packages
25002 (defun org--flyspell-object-check-p (element)
25003 "Non-nil when Flyspell can check object at point.
25004 ELEMENT is the element at point."
25005 (let ((object (save-excursion
25006 (when (looking-at-p "\\>") (backward-char))
25007 (org-element-context element))))
25008 (cl-case (org-element-type object)
25009 ;; Prevent checks in links due to keybinding conflict with
25010 ;; Flyspell.
25011 ((code entity export-snippet inline-babel-call
25012 inline-src-block line-break latex-fragment link macro
25013 statistics-cookie target timestamp verbatim)
25014 nil)
25015 (footnote-reference
25016 ;; Only in inline footnotes, within the definition.
25017 (and (eq (org-element-property :type object) 'inline)
25018 (< (save-excursion
25019 (goto-char (org-element-property :begin object))
25020 (search-forward ":" nil t 2))
25021 (point))))
25022 (otherwise t))))
25024 (defun org-mode-flyspell-verify ()
25025 "Function used for `flyspell-generic-check-word-predicate'."
25026 (if (org-at-heading-p)
25027 ;; At a headline or an inlinetask, check title only. This is
25028 ;; faster than relying on `org-element-at-point'.
25029 (and (save-excursion (beginning-of-line)
25030 (and (let ((case-fold-search t))
25031 (not (looking-at-p "\\*+ END[ \t]*$")))
25032 (let ((case-fold-search nil))
25033 (looking-at org-complex-heading-regexp))))
25034 (match-beginning 4)
25035 (>= (point) (match-beginning 4))
25036 (or (not (match-beginning 5))
25037 (< (point) (match-beginning 5))))
25038 (let* ((element (org-element-at-point))
25039 (post-affiliated (org-element-property :post-affiliated element)))
25040 (cond
25041 ;; Ignore checks in all affiliated keywords but captions.
25042 ((< (point) post-affiliated)
25043 (and (save-excursion
25044 (beginning-of-line)
25045 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25046 (> (point) (match-end 0))
25047 (org--flyspell-object-check-p element)))
25048 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25049 ((let ((log (org-log-into-drawer)))
25050 (and log
25051 (let ((drawer (org-element-lineage element '(drawer))))
25052 (and drawer
25053 (eq (compare-strings
25054 log nil nil
25055 (org-element-property :drawer-name drawer) nil nil t)
25056 t)))))
25057 nil)
25059 (cl-case (org-element-type element)
25060 ((comment quote-section) t)
25061 (comment-block
25062 ;; Allow checks between block markers, not on them.
25063 (and (> (line-beginning-position) post-affiliated)
25064 (save-excursion
25065 (end-of-line)
25066 (skip-chars-forward " \r\t\n")
25067 (< (point) (org-element-property :end element)))))
25068 ;; Arbitrary list of keywords where checks are meaningful.
25069 ;; Make sure point is on the value part of the element.
25070 (keyword
25071 (and (member (org-element-property :key element)
25072 '("DESCRIPTION" "TITLE"))
25073 (save-excursion
25074 (search-backward ":" (line-beginning-position) t))))
25075 ;; Check is globally allowed in paragraphs verse blocks and
25076 ;; table rows (after affiliated keywords) but some objects
25077 ;; must not be affected.
25078 ((paragraph table-row verse-block)
25079 (let ((cbeg (org-element-property :contents-begin element))
25080 (cend (org-element-property :contents-end element)))
25081 (and cbeg (>= (point) cbeg) (< (point) cend)
25082 (org--flyspell-object-check-p element))))))))))
25083 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25085 (defun org-remove-flyspell-overlays-in (beg end)
25086 "Remove flyspell overlays in region."
25087 (and (bound-and-true-p flyspell-mode)
25088 (fboundp 'flyspell-delete-region-overlays)
25089 (flyspell-delete-region-overlays beg end)))
25091 (defvar flyspell-delayed-commands)
25092 (eval-after-load "flyspell"
25093 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25095 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25096 (eval-after-load "bookmark"
25097 '(if (boundp 'bookmark-after-jump-hook)
25098 ;; We can use the hook
25099 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25100 ;; Hook not available, use advice
25101 (defadvice bookmark-jump (after org-make-visible activate)
25102 "Make the position visible."
25103 (org-bookmark-jump-unhide))))
25105 ;; Make sure saveplace shows the location if it was hidden
25106 (eval-after-load "saveplace"
25107 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25108 "Make the position visible."
25109 (org-bookmark-jump-unhide)))
25111 ;; Make sure ecb shows the location if it was hidden
25112 (eval-after-load "ecb"
25113 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25114 "Make hierarchy visible when jumping into location from ECB tree buffer."
25115 (when (derived-mode-p 'org-mode)
25116 (org-show-context))))
25118 (defun org-bookmark-jump-unhide ()
25119 "Unhide the current position, to show the bookmark location."
25120 (and (derived-mode-p 'org-mode)
25121 (or (org-invisible-p)
25122 (save-excursion (goto-char (max (point-min) (1- (point))))
25123 (org-invisible-p)))
25124 (org-show-context 'bookmark-jump)))
25126 (defun org-mark-jump-unhide ()
25127 "Make the point visible with `org-show-context' after jumping to the mark."
25128 (when (and (derived-mode-p 'org-mode)
25129 (org-invisible-p))
25130 (org-show-context 'mark-goto)))
25132 (eval-after-load "simple"
25133 '(defadvice pop-to-mark-command (after org-make-visible activate)
25134 "Make the point visible with `org-show-context'."
25135 (org-mark-jump-unhide)))
25137 (eval-after-load "simple"
25138 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25139 "Make the point visible with `org-show-context'."
25140 (org-mark-jump-unhide)))
25142 (eval-after-load "simple"
25143 '(defadvice pop-global-mark (after org-make-visible activate)
25144 "Make the point visible with `org-show-context'."
25145 (org-mark-jump-unhide)))
25147 ;; Make session.el ignore our circular variable
25148 (defvar session-globals-exclude)
25149 (eval-after-load "session"
25150 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25152 ;;;; Finish up
25154 (provide 'org)
25156 (run-hooks 'org-load-hook)
25158 ;;; org.el ends here