Use `split-string' instead of `org-split-string'
[org-mode/org-tableheadings.git] / lisp / org.el
blob3d817947f1c53c3bcdae67fb5411129eef9fb2fc
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp) ;Silence byte-compiler
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s &optional keep-lead)
196 "Remove whitespace at the beginning and the end of string S.
197 When optional argument KEEP-LEAD is non-nil, removing blank lines
198 at the beginning of the string does not affect leading indentation."
199 (replace-regexp-in-string
200 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
201 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
203 ;; load languages based on value of `org-babel-load-languages'
204 (defvar org-babel-load-languages)
206 ;;;###autoload
207 (defun org-babel-do-load-languages (sym value)
208 "Load the languages defined in `org-babel-load-languages'."
209 (set-default sym value)
210 (dolist (pair org-babel-load-languages)
211 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
212 (if active
213 (require (intern (concat "ob-" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the Org file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 ;; Tangle-file traversal returns reversed list of tangled files
239 ;; and we want to evaluate the first target.
240 (setq exported-file
241 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
242 (message "%s %s"
243 (if compile
244 (progn (byte-compile-file exported-file 'load)
245 "Compiled and loaded")
246 (progn (load-file exported-file) "Loaded"))
247 exported-file)))
249 (defcustom org-babel-load-languages '((emacs-lisp . t))
250 "Languages which can be evaluated in Org buffers.
251 This list can be used to load support for any of the languages
252 below, note that each language will depend on a different set of
253 system executables and/or Emacs modes. When a language is
254 \"loaded\", then code blocks in that language can be evaluated
255 with `org-babel-execute-src-block' bound by default to C-c
256 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
257 be set to remove code block evaluation from the C-c C-c
258 keybinding. By default only Emacs Lisp (which has no
259 requirements) is loaded."
260 :group 'org-babel
261 :set 'org-babel-do-load-languages
262 :version "24.1"
263 :type '(alist :tag "Babel Languages"
264 :key-type
265 (choice
266 (const :tag "Awk" awk)
267 (const :tag "C" C)
268 (const :tag "R" R)
269 (const :tag "Asymptote" asymptote)
270 (const :tag "Calc" calc)
271 (const :tag "Clojure" clojure)
272 (const :tag "CSS" css)
273 (const :tag "Ditaa" ditaa)
274 (const :tag "Dot" dot)
275 (const :tag "Ebnf2ps" ebnf2ps)
276 (const :tag "Emacs Lisp" emacs-lisp)
277 (const :tag "Forth" forth)
278 (const :tag "Fortran" fortran)
279 (const :tag "Gnuplot" gnuplot)
280 (const :tag "Haskell" haskell)
281 (const :tag "hledger" hledger)
282 (const :tag "IO" io)
283 (const :tag "J" J)
284 (const :tag "Java" java)
285 (const :tag "Javascript" js)
286 (const :tag "LaTeX" latex)
287 (const :tag "Ledger" ledger)
288 (const :tag "Lilypond" lilypond)
289 (const :tag "Lisp" lisp)
290 (const :tag "Makefile" makefile)
291 (const :tag "Maxima" maxima)
292 (const :tag "Matlab" matlab)
293 (const :tag "Mscgen" mscgen)
294 (const :tag "Ocaml" ocaml)
295 (const :tag "Octave" octave)
296 (const :tag "Org" org)
297 (const :tag "Perl" perl)
298 (const :tag "Pico Lisp" picolisp)
299 (const :tag "PlantUML" plantuml)
300 (const :tag "Python" python)
301 (const :tag "Ruby" ruby)
302 (const :tag "Sass" sass)
303 (const :tag "Scala" scala)
304 (const :tag "Scheme" scheme)
305 (const :tag "Screen" screen)
306 (const :tag "Shell Script" shell)
307 (const :tag "Shen" shen)
308 (const :tag "Sql" sql)
309 (const :tag "Sqlite" sqlite)
310 (const :tag "Stan" stan)
311 (const :tag "Vala" vala))
312 :value-type (boolean :tag "Activate" :value t)))
314 ;;;; Customization variables
315 (defcustom org-clone-delete-id nil
316 "Remove ID property of clones of a subtree.
317 When non-nil, clones of a subtree don't inherit the ID property.
318 Otherwise they inherit the ID property with a new unique
319 identifier."
320 :type 'boolean
321 :version "24.1"
322 :group 'org-id)
324 ;;; Version
325 (org-check-version)
327 ;;;###autoload
328 (defun org-version (&optional here full message)
329 "Show the Org version.
330 Interactively, or when MESSAGE is non-nil, show it in echo area.
331 With prefix argument, or when HERE is non-nil, insert it at point.
332 In non-interactive uses, a reduced version string is output unless
333 FULL is given."
334 (interactive (list current-prefix-arg t (not current-prefix-arg)))
335 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
336 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
337 (load-suffixes (list ".el"))
338 (org-install-dir
339 (ignore-errors (org-find-library-dir "org-loaddefs"))))
340 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
341 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
342 (let* ((load-suffixes save-load-suffixes)
343 (release (org-release))
344 (git-version (org-git-version))
345 (version (format "Org mode version %s (%s @ %s)"
346 release
347 git-version
348 (if org-install-dir
349 (if (string= org-dir org-install-dir)
350 org-install-dir
351 (concat "mixed installation! "
352 org-install-dir
353 " and "
354 org-dir))
355 "org-loaddefs.el can not be found!")))
356 (version1 (if full version release)))
357 (when here (insert version1))
358 (when message (message "%s" version1))
359 version1)))
361 (defconst org-version (org-version))
364 ;;; Syntax Constants
366 ;;;; Block
368 (defconst org-block-regexp
369 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
370 "Regular expression for hiding blocks.")
372 (defconst org-dblock-start-re
373 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
374 "Matches the start line of a dynamic block, with parameters.")
376 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
377 "Matches the end of a dynamic block.")
379 ;;;; Clock and Planning
381 (defconst org-clock-string "CLOCK:"
382 "String used as prefix for timestamps clocking work hours on an item.")
384 (defvar org-closed-string "CLOSED:"
385 "String used as the prefix for timestamps logging closing a TODO entry.")
387 (defvar org-deadline-string "DEADLINE:"
388 "String to mark deadline entries.
389 \\<org-mode-map>
390 A deadline is this string, followed by a time stamp. It must be
391 a word, terminated by a colon. You can insert a schedule keyword
392 and a timestamp with `\\[org-deadline]'.")
394 (defvar org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 \\<org-mode-map>
397 A schedule is this string, followed by a time stamp. It must be
398 a word, terminated by a colon. You can insert a schedule keyword
399 and a timestamp with `\\[org-schedule]'.")
401 (defconst org-ds-keyword-length
402 (+ 2
403 (apply #'max
404 (mapcar #'length
405 (list org-deadline-string org-scheduled-string
406 org-clock-string org-closed-string))))
407 "Maximum length of the DEADLINE and SCHEDULED keywords.")
409 (defconst org-planning-line-re
410 (concat "^[ \t]*"
411 (regexp-opt
412 (list org-closed-string org-deadline-string org-scheduled-string)
414 "Matches a line with planning info.
415 Matched keyword is in group 1.")
417 (defconst org-clock-line-re
418 (concat "^[ \t]*" org-clock-string)
419 "Matches a line with clock info.")
421 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
422 "Matches the DEADLINE keyword.")
424 (defconst org-deadline-time-regexp
425 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
426 "Matches the DEADLINE keyword together with a time stamp.")
428 (defconst org-deadline-time-hour-regexp
429 (concat "\\<" org-deadline-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
433 (defconst org-deadline-line-regexp
434 (concat "\\<\\(" org-deadline-string "\\).*")
435 "Matches the DEADLINE keyword and the rest of the line.")
437 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
438 "Matches the SCHEDULED keyword.")
440 (defconst org-scheduled-time-regexp
441 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
442 "Matches the SCHEDULED keyword together with a time stamp.")
444 (defconst org-scheduled-time-hour-regexp
445 (concat "\\<" org-scheduled-string
446 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
447 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
449 (defconst org-closed-time-regexp
450 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
451 "Matches the CLOSED keyword together with a time stamp.")
453 (defconst org-keyword-time-regexp
454 (concat "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string
457 org-clock-string)
459 " *[[<]\\([^]>]+\\)[]>]")
460 "Matches any of the 4 keywords, together with the time stamp.")
462 (defconst org-keyword-time-not-clock-regexp
463 (concat
464 "\\<"
465 (regexp-opt
466 (list org-scheduled-string org-deadline-string org-closed-string) t)
467 " *[[<]\\([^]>]+\\)[]>]")
468 "Matches any of the 3 keywords, together with the time stamp.")
470 (defconst org-maybe-keyword-time-regexp
471 (concat "\\(\\<"
472 (regexp-opt
473 (list org-scheduled-string org-deadline-string org-closed-string
474 org-clock-string)
476 "\\)?"
477 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
478 "\\|"
479 "<%%([^\r\n>]*>\\)")
480 "Matches a timestamp, possibly preceded by a keyword.")
482 (defconst org-all-time-keywords
483 (mapcar (lambda (w) (substring w 0 -1))
484 (list org-scheduled-string org-deadline-string
485 org-clock-string org-closed-string))
486 "List of time keywords.")
488 ;;;; Drawer
490 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
491 "Matches first or last line of a hidden block.
492 Group 1 contains drawer's name or \"END\".")
494 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
495 "Regular expression matching the first line of a property drawer.")
497 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
498 "Regular expression matching the last line of a property drawer.")
500 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
501 "Regular expression matching the first line of a clock drawer.")
503 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
504 "Regular expression matching the last line of a clock drawer.")
506 (defconst org-property-drawer-re
507 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
508 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
509 "[ \t]*:END:[ \t]*$")
510 "Matches an entire property drawer.")
512 (defconst org-clock-drawer-re
513 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
514 org-clock-drawer-end-re "\\)\n?")
515 "Matches an entire clock drawer.")
517 ;;;; Headline
519 (defconst org-heading-keyword-regexp-format
520 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
521 "Printf format for a regexp matching a headline with some keyword.
522 This regexp will match the headline of any node which has the
523 exact keyword that is put into the format. The keyword isn't in
524 any group by default, but the stars and the body are.")
526 (defconst org-heading-keyword-maybe-regexp-format
527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
528 "Printf format for a regexp matching a headline, possibly with some keyword.
529 This regexp can match any headline with the specified keyword, or
530 without a keyword. The keyword isn't in any group by default,
531 but the stars and the body are.")
533 (defconst org-archive-tag "ARCHIVE"
534 "The tag that marks a subtree as archived.
535 An archived subtree does not open during visibility cycling, and does
536 not contribute to the agenda listings.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "24.4"
703 :package-version '(Org . "8.0")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
724 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
725 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
726 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
727 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
728 (const :tag "C collector: Collect properties into tables" org-collector)
729 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
730 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
731 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
732 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
733 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
734 (const :tag "C eval: Include command output as text" org-eval)
735 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
736 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
737 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
738 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
739 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
740 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
741 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
742 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
743 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
744 (const :tag "C man: Support for links to manpages in Org mode" org-man)
745 (const :tag "C mew: Links to Mew folders/messages" org-mew)
746 (const :tag "C mtags: Support for muse-like tags" org-mtags)
747 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
748 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
749 (const :tag "C registry: A registry for Org links" org-registry)
750 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
751 (const :tag "C secretary: Team management with org-mode" org-secretary)
752 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
753 (const :tag "C toc: Table of contents for Org buffer" org-toc)
754 (const :tag "C track: Keep up with Org mode development" org-track)
755 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
756 (const :tag "C vm: Links to VM folders/messages" org-vm)
757 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
758 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
759 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
761 (defvar org-export-registered-backends) ; From ox.el.
762 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
763 (declare-function org-export-backend-name "ox" (backend) t)
764 (defcustom org-export-backends '(ascii html icalendar latex odt)
765 "List of export back-ends that should be always available.
767 If a description starts with <C>, the file is not part of Emacs
768 and loading it will require that you have downloaded and properly
769 installed the Org mode distribution.
771 Unlike to `org-modules', libraries in this list will not be
772 loaded along with Org, but only once the export framework is
773 needed.
775 This variable needs to be set before org.el is loaded. If you
776 need to make a change while Emacs is running, use the customize
777 interface or run the following code, where VAL stands for the new
778 value of the variable, after updating it:
780 (progn
781 (setq org-export-registered-backends
782 (cl-remove-if-not
783 (lambda (backend)
784 (let ((name (org-export-backend-name backend)))
785 (or (memq name val)
786 (catch \\='parentp
787 (dolist (b val)
788 (and (org-export-derived-backend-p b name)
789 (throw \\='parentp t)))))))
790 org-export-registered-backends))
791 (let ((new-list (mapcar #\\='org-export-backend-name
792 org-export-registered-backends)))
793 (dolist (backend val)
794 (cond
795 ((not (load (format \"ox-%s\" backend) t t))
796 (message \"Problems while trying to load export back-end \\=`%s\\='\"
797 backend))
798 ((not (memq backend new-list)) (push backend new-list))))
799 (set-default \\='org-export-backends new-list)))
801 Adding a back-end to this list will also pull the back-end it
802 depends on, if any."
803 :group 'org
804 :group 'org-export
805 :version "26.1"
806 :package-version '(Org . "9.0")
807 :initialize 'custom-initialize-set
808 :set (lambda (var val)
809 (if (not (featurep 'ox)) (set-default var val)
810 ;; Any back-end not required anymore (not present in VAL and not
811 ;; a parent of any back-end in the new value) is removed from the
812 ;; list of registered back-ends.
813 (setq org-export-registered-backends
814 (cl-remove-if-not
815 (lambda (backend)
816 (let ((name (org-export-backend-name backend)))
817 (or (memq name val)
818 (catch 'parentp
819 (dolist (b val)
820 (and (org-export-derived-backend-p b name)
821 (throw 'parentp t)))))))
822 org-export-registered-backends))
823 ;; Now build NEW-LIST of both new back-ends and required
824 ;; parents.
825 (let ((new-list (mapcar #'org-export-backend-name
826 org-export-registered-backends)))
827 (dolist (backend val)
828 (cond
829 ((not (load (format "ox-%s" backend) t t))
830 (message "Problems while trying to load export back-end `%s'"
831 backend))
832 ((not (memq backend new-list)) (push backend new-list))))
833 ;; Set VAR to that list with fixed dependencies.
834 (set-default var new-list))))
835 :type '(set :greedy t
836 (const :tag " ascii Export buffer to ASCII format" ascii)
837 (const :tag " beamer Export buffer to Beamer presentation" beamer)
838 (const :tag " html Export buffer to HTML format" html)
839 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
840 (const :tag " latex Export buffer to LaTeX format" latex)
841 (const :tag " man Export buffer to MAN format" man)
842 (const :tag " md Export buffer to Markdown format" md)
843 (const :tag " odt Export buffer to ODT format" odt)
844 (const :tag " org Export buffer to Org format" org)
845 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
846 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
847 (const :tag "C deck Export buffer to deck.js presentations" deck)
848 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
849 (const :tag "C groff Export buffer to Groff format" groff)
850 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
851 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
852 (const :tag "C s5 Export buffer to s5 presentations" s5)
853 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
855 (eval-after-load 'ox
856 '(dolist (backend org-export-backends)
857 (condition-case nil (require (intern (format "ox-%s" backend)))
858 (error (message "Problems while trying to load export back-end `%s'"
859 backend)))))
861 (defcustom org-support-shift-select nil
862 "Non-nil means make shift-cursor commands select text when possible.
863 \\<org-mode-map>\
865 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
866 start selecting a region, or enlarge regions started in this way.
867 In Org mode, in special contexts, these same keys are used for
868 other purposes, important enough to compete with shift selection.
869 Org tries to balance these needs by supporting `shift-select-mode'
870 outside these special contexts, under control of this variable.
872 The default of this variable is nil, to avoid confusing behavior. Shifted
873 cursor keys will then execute Org commands in the following contexts:
874 - on a headline, changing TODO state (left/right) and priority (up/down)
875 - on a time stamp, changing the time
876 - in a plain list item, changing the bullet type
877 - in a property definition line, switching between allowed values
878 - in the BEGIN line of a clock table (changing the time block).
879 Outside these contexts, the commands will throw an error.
881 When this variable is t and the cursor is not in a special
882 context, Org mode will support shift-selection for making and
883 enlarging regions. To make this more effective, the bullet
884 cycling will no longer happen anywhere in an item line, but only
885 if the cursor is exactly on the bullet.
887 If you set this variable to the symbol `always', then the keys
888 will not be special in headlines, property lines, and item lines,
889 to make shift selection work there as well. If this is what you
890 want, you can use the following alternative commands:
891 `\\[org-todo]' and `\\[org-priority]' \
892 to change TODO state and priority,
893 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
894 can be used to switch TODO sets,
895 `\\[org-ctrl-c-minus]' to cycle item bullet types,
896 and properties can be edited by hand or in column view.
898 However, when the cursor is on a timestamp, shift-cursor commands
899 will still edit the time stamp - this is just too good to give up."
900 :group 'org
901 :type '(choice
902 (const :tag "Never" nil)
903 (const :tag "When outside special context" t)
904 (const :tag "Everywhere except timestamps" always)))
906 (defcustom org-loop-over-headlines-in-active-region nil
907 "Shall some commands act upon headlines in the active region?
909 When set to t, some commands will be performed in all headlines
910 within the active region.
912 When set to `start-level', some commands will be performed in all
913 headlines within the active region, provided that these headlines
914 are of the same level than the first one.
916 When set to a string, those commands will be performed on the
917 matching headlines within the active region. Such string must be
918 a tags/property/todo match as it is used in the agenda tags view.
920 The list of commands is: `org-schedule', `org-deadline',
921 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
922 `org-archive-to-archive-sibling'. The archiving commands skip
923 already archived entries."
924 :type '(choice (const :tag "Don't loop" nil)
925 (const :tag "All headlines in active region" t)
926 (const :tag "In active region, headlines at the same level than the first one" start-level)
927 (string :tag "Tags/Property/Todo matcher"))
928 :version "24.1"
929 :group 'org-todo
930 :group 'org-archive)
932 (defgroup org-startup nil
933 "Options concerning startup of Org mode."
934 :tag "Org Startup"
935 :group 'org)
937 (defcustom org-startup-folded t
938 "Non-nil means entering Org mode will switch to OVERVIEW.
940 This can also be configured on a per-file basis by adding one of
941 the following lines anywhere in the buffer:
943 #+STARTUP: fold (or `overview', this is equivalent)
944 #+STARTUP: nofold (or `showall', this is equivalent)
945 #+STARTUP: content
946 #+STARTUP: showeverything
948 Set `org-agenda-inhibit-startup' to a non-nil value if you want
949 to ignore this option when Org opens agenda files for the first
950 time."
951 :group 'org-startup
952 :type '(choice
953 (const :tag "nofold: show all" nil)
954 (const :tag "fold: overview" t)
955 (const :tag "content: all headlines" content)
956 (const :tag "show everything, even drawers" showeverything)))
958 (defcustom org-startup-truncated t
959 "Non-nil means entering Org mode will set `truncate-lines'.
960 This is useful since some lines containing links can be very long and
961 uninteresting. Also tables look terrible when wrapped.
963 The variable `org-startup-truncated' allows to configure
964 truncation for Org mode different to the other modes that use the
965 variable `truncate-lines' and as a shortcut instead of putting
966 the variable `truncate-lines' into the `org-mode-hook'. If one
967 wants to configure truncation for Org mode not statically but
968 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
969 the variable `truncate-lines' has to be used because in such a
970 case it is too late to set the variable `org-startup-truncated'."
971 :group 'org-startup
972 :type 'boolean)
974 (defcustom org-startup-indented nil
975 "Non-nil means turn on `org-indent-mode' on startup.
976 This can also be configured on a per-file basis by adding one of
977 the following lines anywhere in the buffer:
979 #+STARTUP: indent
980 #+STARTUP: noindent"
981 :group 'org-structure
982 :type '(choice
983 (const :tag "Not" nil)
984 (const :tag "Globally (slow on startup in large files)" t)))
986 (defcustom org-use-sub-superscripts t
987 "Non-nil means interpret \"_\" and \"^\" for display.
989 If you want to control how Org exports those characters, see
990 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
991 used to be an alias for `org-export-with-sub-superscripts' in
992 Org <8.0, it is not anymore.
994 When this option is turned on, you can use TeX-like syntax for
995 sub- and superscripts within the buffer. Several characters after
996 \"_\" or \"^\" will be considered as a single item - so grouping
997 with {} is normally not needed. For example, the following things
998 will be parsed as single sub- or superscripts:
1000 10^24 or 10^tau several digits will be considered 1 item.
1001 10^-12 or 10^-tau a leading sign with digits or a word
1002 x^2-y^3 will be read as x^2 - y^3, because items are
1003 terminated by almost any nonword/nondigit char.
1004 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1006 Still, ambiguity is possible. So when in doubt, use {} to enclose
1007 the sub/superscript. If you set this variable to the symbol `{}',
1008 the braces are *required* in order to trigger interpretations as
1009 sub/superscript. This can be helpful in documents that need \"_\"
1010 frequently in plain text."
1011 :group 'org-startup
1012 :version "24.4"
1013 :package-version '(Org . "8.0")
1014 :type '(choice
1015 (const :tag "Always interpret" t)
1016 (const :tag "Only with braces" {})
1017 (const :tag "Never interpret" nil)))
1019 (defcustom org-startup-with-beamer-mode nil
1020 "Non-nil means turn on `org-beamer-mode' on startup.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1024 #+STARTUP: beamer"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-align-all-tables nil
1030 "Non-nil means align all tables when visiting a file.
1031 This is useful when the column width in tables is forced with <N> cookies
1032 in table fields. Such tables will look correct only after the first re-align.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: align
1036 #+STARTUP: noalign"
1037 :group 'org-startup
1038 :type 'boolean)
1040 (defcustom org-startup-with-inline-images nil
1041 "Non-nil means show inline images when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: inlineimages
1045 #+STARTUP: noinlineimages"
1046 :group 'org-startup
1047 :version "24.1"
1048 :type 'boolean)
1050 (defcustom org-startup-with-latex-preview nil
1051 "Non-nil means preview LaTeX fragments when loading a new Org file.
1053 This can also be configured on a per-file basis by adding one of
1054 the following lines anywhere in the buffer:
1055 #+STARTUP: latexpreview
1056 #+STARTUP: nolatexpreview"
1057 :group 'org-startup
1058 :version "24.4"
1059 :package-version '(Org . "8.0")
1060 :type 'boolean)
1062 (defcustom org-insert-mode-line-in-empty-file nil
1063 "Non-nil means insert the first line setting Org mode in empty files.
1064 When the function `org-mode' is called interactively in an empty file, this
1065 normally means that the file name does not automatically trigger Org mode.
1066 To ensure that the file will always be in Org mode in the future, a
1067 line enforcing Org mode will be inserted into the buffer, if this option
1068 has been set."
1069 :group 'org-startup
1070 :type 'boolean)
1072 (defcustom org-replace-disputed-keys nil
1073 "Non-nil means use alternative key bindings for some keys.
1074 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1075 These keys are also used by other packages like shift-selection-mode'
1076 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1077 If you want to use Org mode together with one of these other modes,
1078 or more generally if you would like to move some Org mode commands to
1079 other keys, set this variable and configure the keys with the variable
1080 `org-disputed-keys'.
1082 This option is only relevant at load-time of Org mode, and must be set
1083 *before* org.el is loaded. Changing it requires a restart of Emacs to
1084 become effective."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defcustom org-use-extra-keys nil
1089 "Non-nil means use extra key sequence definitions for certain commands.
1090 This happens automatically if `window-system' is nil. This
1091 variable lets you do the same manually. You must set it before
1092 loading Org."
1093 :group 'org-startup
1094 :type 'boolean)
1096 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1098 (defcustom org-disputed-keys
1099 '(([(shift up)] . [(meta p)])
1100 ([(shift down)] . [(meta n)])
1101 ([(shift left)] . [(meta -)])
1102 ([(shift right)] . [(meta +)])
1103 ([(control shift right)] . [(meta shift +)])
1104 ([(control shift left)] . [(meta shift -)]))
1105 "Keys for which Org mode and other modes compete.
1106 This is an alist, cars are the default keys, second element specifies
1107 the alternative to use when `org-replace-disputed-keys' is t.
1109 Keys can be specified in any syntax supported by `define-key'.
1110 The value of this option takes effect only at Org mode startup,
1111 therefore you'll have to restart Emacs to apply it after changing."
1112 :group 'org-startup
1113 :type 'alist)
1115 (defun org-key (key)
1116 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1117 Or return the original if not disputed."
1118 (when org-replace-disputed-keys
1119 (let* ((nkey (key-description key))
1120 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1121 org-disputed-keys)))
1122 (setq key (if x (cdr x) key))))
1123 key)
1125 (defun org-defkey (keymap key def)
1126 "Define a key, possibly translated, as returned by `org-key'."
1127 (define-key keymap (org-key key) def))
1129 (defcustom org-ellipsis nil
1130 "The ellipsis to use in the Org mode outline.
1132 When nil, just use the standard three dots. When a non-empty string,
1133 use that string instead.
1135 The change affects only Org mode (which will then use its own display table).
1136 Changing this requires executing `\\[org-mode]' in a buffer to become
1137 effective."
1138 :group 'org-startup
1139 :type '(choice (const :tag "Default" nil)
1140 (string :tag "String" :value "...#"))
1141 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1143 (defvar org-display-table nil
1144 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1146 (defgroup org-keywords nil
1147 "Keywords in Org mode."
1148 :tag "Org Keywords"
1149 :group 'org)
1151 (defcustom org-closed-keep-when-no-todo nil
1152 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1153 :group 'org-todo
1154 :group 'org-keywords
1155 :version "24.4"
1156 :package-version '(Org . "8.0")
1157 :type 'boolean)
1159 (defgroup org-structure nil
1160 "Options concerning the general structure of Org files."
1161 :tag "Org Structure"
1162 :group 'org)
1164 (defgroup org-reveal-location nil
1165 "Options about how to make context of a location visible."
1166 :tag "Org Reveal Location"
1167 :group 'org-structure)
1169 (defcustom org-show-context-detail '((agenda . local)
1170 (bookmark-jump . lineage)
1171 (isearch . lineage)
1172 (default . ancestors))
1173 "Alist between context and visibility span when revealing a location.
1175 \\<org-mode-map>Some actions may move point into invisible
1176 locations. As a consequence, Org always expose a neighborhood
1177 around point. How much is shown depends on the initial action,
1178 or context. Valid contexts are
1180 agenda when exposing an entry from the agenda
1181 org-goto when using the command `org-goto' (`\\[org-goto]')
1182 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1183 tags-tree when constructing a sparse tree based on tags matches
1184 link-search when exposing search matches associated with a link
1185 mark-goto when exposing the jump goal of a mark
1186 bookmark-jump when exposing a bookmark location
1187 isearch when exiting from an incremental search
1188 default default for all contexts not set explicitly
1190 Allowed visibility spans are
1192 minimal show current headline; if point is not on headline,
1193 also show entry
1195 local show current headline, entry and next headline
1197 ancestors show current headline and its direct ancestors; if
1198 point is not on headline, also show entry
1200 lineage show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and first child
1204 tree show current headline, its direct ancestors and all
1205 their children; if point is not on headline, also show
1206 entry and all children
1208 canonical show current headline, its direct ancestors along with
1209 their entries and children; if point is not located on
1210 the headline, also show current entry and all children
1212 As special cases, a nil or t value means show all contexts in
1213 `minimal' or `canonical' view, respectively.
1215 Some views can make displayed information very compact, but also
1216 make it harder to edit the location of the match. In such
1217 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1218 more context."
1219 :group 'org-reveal-location
1220 :version "26.1"
1221 :package-version '(Org . "9.0")
1222 :type '(choice
1223 (const :tag "Canonical" t)
1224 (const :tag "Minimal" nil)
1225 (repeat :greedy t :tag "Individual contexts"
1226 (cons
1227 (choice :tag "Context"
1228 (const agenda)
1229 (const org-goto)
1230 (const occur-tree)
1231 (const tags-tree)
1232 (const link-search)
1233 (const mark-goto)
1234 (const bookmark-jump)
1235 (const isearch)
1236 (const default))
1237 (choice :tag "Detail level"
1238 (const minimal)
1239 (const local)
1240 (const ancestors)
1241 (const lineage)
1242 (const tree)
1243 (const canonical))))))
1245 (defcustom org-indirect-buffer-display 'other-window
1246 "How should indirect tree buffers be displayed?
1248 This applies to indirect buffers created with the commands
1249 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1251 Valid values are:
1252 current-window Display in the current window
1253 other-window Just display in another window.
1254 dedicated-frame Create one new frame, and re-use it each time.
1255 new-frame Make a new frame each time. Note that in this case
1256 previously-made indirect buffers are kept, and you need to
1257 kill these buffers yourself."
1258 :group 'org-structure
1259 :group 'org-agenda-windows
1260 :type '(choice
1261 (const :tag "In current window" current-window)
1262 (const :tag "In current frame, other window" other-window)
1263 (const :tag "Each time a new frame" new-frame)
1264 (const :tag "One dedicated frame" dedicated-frame)))
1266 (defcustom org-use-speed-commands nil
1267 "Non-nil means activate single letter commands at beginning of a headline.
1268 This may also be a function to test for appropriate locations where speed
1269 commands should be active.
1271 For example, to activate speed commands when the point is on any
1272 star at the beginning of the headline, you can do this:
1274 (setq org-use-speed-commands
1275 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1276 :group 'org-structure
1277 :type '(choice
1278 (const :tag "Never" nil)
1279 (const :tag "At beginning of headline stars" t)
1280 (function)))
1282 (defcustom org-speed-commands-user nil
1283 "Alist of additional speed commands.
1284 This list will be checked before `org-speed-commands-default'
1285 when the variable `org-use-speed-commands' is non-nil
1286 and when the cursor is at the beginning of a headline.
1287 The car if each entry is a string with a single letter, which must
1288 be assigned to `self-insert-command' in the global map.
1289 The cdr is either a command to be called interactively, a function
1290 to be called, or a form to be evaluated.
1291 An entry that is just a list with a single string will be interpreted
1292 as a descriptive headline that will be added when listing the speed
1293 commands in the Help buffer using the `?' speed command."
1294 :group 'org-structure
1295 :type '(repeat :value ("k" . ignore)
1296 (choice :value ("k" . ignore)
1297 (list :tag "Descriptive Headline" (string :tag "Headline"))
1298 (cons :tag "Letter and Command"
1299 (string :tag "Command letter")
1300 (choice
1301 (function)
1302 (sexp))))))
1304 (defcustom org-bookmark-names-plist
1305 '(:last-capture "org-capture-last-stored"
1306 :last-refile "org-refile-last-stored"
1307 :last-capture-marker "org-capture-last-stored-marker")
1308 "Names for bookmarks automatically set by some Org commands.
1309 This can provide strings as names for a number of bookmarks Org sets
1310 automatically. The following keys are currently implemented:
1311 :last-capture
1312 :last-capture-marker
1313 :last-refile
1314 When a key does not show up in the property list, the corresponding bookmark
1315 is not set."
1316 :group 'org-structure
1317 :type 'plist)
1319 (defgroup org-cycle nil
1320 "Options concerning visibility cycling in Org mode."
1321 :tag "Org Cycle"
1322 :group 'org-structure)
1324 (defcustom org-cycle-skip-children-state-if-no-children t
1325 "Non-nil means skip CHILDREN state in entries that don't have any."
1326 :group 'org-cycle
1327 :type 'boolean)
1329 (defcustom org-cycle-max-level nil
1330 "Maximum level which should still be subject to visibility cycling.
1331 Levels higher than this will, for cycling, be treated as text, not a headline.
1332 When `org-odd-levels-only' is set, a value of N in this variable actually
1333 means 2N-1 stars as the limiting headline.
1334 When nil, cycle all levels.
1335 Note that the limiting level of cycling is also influenced by
1336 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1337 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1338 than its value."
1339 :group 'org-cycle
1340 :type '(choice
1341 (const :tag "No limit" nil)
1342 (integer :tag "Maximum level")))
1344 (defcustom org-hide-block-startup nil
1345 "Non-nil means entering Org mode will fold all blocks.
1346 This can also be set in on a per-file basis with
1348 #+STARTUP: hideblocks
1349 #+STARTUP: showblocks"
1350 :group 'org-startup
1351 :group 'org-cycle
1352 :type 'boolean)
1354 (defcustom org-cycle-global-at-bob nil
1355 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use `S-TAB'
1358 or `\\[universal-argument] TAB'. For this special case to work, the first \
1359 line of the buffer
1360 must not be a headline -- it may be empty or some other text.
1362 When used in this way, `org-cycle-hook' is disabled temporarily to make
1363 sure the cursor stays at the beginning of the buffer.
1365 When this option is nil, don't do anything special at the beginning of
1366 the buffer."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-level-after-item/entry-creation t
1371 "Non-nil means cycle entry level or item indentation in new empty entries.
1373 When the cursor is at the end of an empty headline, i.e., with only stars
1374 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1375 and then all possible ancestor states, before returning to the original state.
1376 This makes data entry extremely fast: M-RET to create a new headline,
1377 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1379 When the cursor is at the end of an empty plain list item, one TAB will
1380 make it a subitem, two or more tabs will back up to make this an item
1381 higher up in the item hierarchy."
1382 :group 'org-cycle
1383 :type 'boolean)
1385 (defcustom org-cycle-emulate-tab t
1386 "Where should `org-cycle' emulate TAB.
1387 nil Never
1388 white Only in completely white lines
1389 whitestart Only at the beginning of lines, before the first non-white char
1390 t Everywhere except in headlines
1391 exc-hl-bol Everywhere except at the start of a headline
1392 If TAB is used in a place where it does not emulate TAB, the current subtree
1393 visibility is cycled."
1394 :group 'org-cycle
1395 :type '(choice (const :tag "Never" nil)
1396 (const :tag "Only in completely white lines" white)
1397 (const :tag "Before first char in a line" whitestart)
1398 (const :tag "Everywhere except in headlines" t)
1399 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1401 (defcustom org-cycle-separator-lines 2
1402 "Number of empty lines needed to keep an empty line between collapsed trees.
1403 If you leave an empty line between the end of a subtree and the following
1404 headline, this empty line is hidden when the subtree is folded.
1405 Org mode will leave (exactly) one empty line visible if the number of
1406 empty lines is equal or larger to the number given in this variable.
1407 So the default 2 means at least 2 empty lines after the end of a subtree
1408 are needed to produce free space between a collapsed subtree and the
1409 following headline.
1411 If the number is negative, and the number of empty lines is at least -N,
1412 all empty lines are shown.
1414 Special case: when 0, never leave empty lines in collapsed view."
1415 :group 'org-cycle
1416 :type 'integer)
1417 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1419 (defcustom org-pre-cycle-hook nil
1420 "Hook that is run before visibility cycling is happening.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that will be set right after running this hook. The
1423 argument is a symbol. Before a global state change, it can have the values
1424 `overview', `content', or `all'. Before a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook)
1429 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1430 org-cycle-hide-drawers
1431 org-cycle-show-empty-lines
1432 org-optimize-window-after-visibility-change)
1433 "Hook that is run after `org-cycle' has changed the buffer visibility.
1434 The function(s) in this hook must accept a single argument which indicates
1435 the new state that was set by the most recent `org-cycle' command. The
1436 argument is a symbol. After a global state change, it can have the values
1437 `overview', `contents', or `all'. After a local state change, it can have
1438 the values `folded', `children', or `subtree'."
1439 :group 'org-cycle
1440 :type 'hook
1441 :version "26.1"
1442 :package-version '(Org . "8.3"))
1444 (defgroup org-edit-structure nil
1445 "Options concerning structure editing in Org mode."
1446 :tag "Org Edit Structure"
1447 :group 'org-structure)
1449 (defcustom org-odd-levels-only nil
1450 "Non-nil means skip even levels and only use odd levels for the outline.
1451 This has the effect that two stars are being added/taken away in
1452 promotion/demotion commands. It also influences how levels are
1453 handled by the exporters.
1454 Changing it requires restart of `font-lock-mode' to become effective
1455 for fontification also in regions already fontified.
1456 You may also set this on a per-file basis by adding one of the following
1457 lines to the buffer:
1459 #+STARTUP: odd
1460 #+STARTUP: oddeven"
1461 :group 'org-edit-structure
1462 :group 'org-appearance
1463 :type 'boolean)
1465 (defcustom org-adapt-indentation t
1466 "Non-nil means adapt indentation to outline node level.
1468 When this variable is set, Org assumes that you write outlines by
1469 indenting text in each node to align with the headline (after the
1470 stars). The following issues are influenced by this variable:
1472 - The indentation is increased by one space in a demotion
1473 command, and decreased by one in a promotion command. However,
1474 in the latter case, if shifting some line in the entry body
1475 would alter document structure (e.g., insert a new headline),
1476 indentation is not changed at all.
1478 - Property drawers and planning information is inserted indented
1479 when this variable is set. When nil, they will not be indented.
1481 - TAB indents a line relative to current level. The lines below
1482 a headline will be indented when this variable is set.
1484 Note that this is all about true indentation, by adding and
1485 removing space characters. See also `org-indent.el' which does
1486 level-dependent indentation in a virtual way, i.e. at display
1487 time in Emacs."
1488 :group 'org-edit-structure
1489 :type 'boolean)
1491 (defcustom org-special-ctrl-a/e nil
1492 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1494 When t, `C-a' will bring back the cursor to the beginning of the
1495 headline text, i.e. after the stars and after a possible TODO
1496 keyword. In an item, this will be the position after bullet and
1497 check-box, if any. When the cursor is already at that position,
1498 another `C-a' will bring it to the beginning of the line.
1500 `C-e' will jump to the end of the headline, ignoring the presence
1501 of tags in the headline. A second `C-e' will then jump to the
1502 true end of the line, after any tags. This also means that, when
1503 this variable is non-nil, `C-e' also will never jump beyond the
1504 end of the heading of a folded section, i.e. not after the
1505 ellipses.
1507 When set to the symbol `reversed', the first `C-a' or `C-e' works
1508 normally, going to the true line boundary first. Only a directly
1509 following, identical keypress will bring the cursor to the
1510 special positions.
1512 This may also be a cons cell where the behavior for `C-a' and
1513 `C-e' is set separately."
1514 :group 'org-edit-structure
1515 :type '(choice
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet and before tags first" t)
1518 (const :tag "reversed: true line boundary first" reversed)
1519 (cons :tag "Set C-a and C-e separately"
1520 (choice :tag "Special C-a"
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet first" t)
1523 (const :tag "reversed: before stars/bullet first" reversed))
1524 (choice :tag "Special C-e"
1525 (const :tag "off" nil)
1526 (const :tag "on: before tags first" t)
1527 (const :tag "reversed: after tags first" reversed)))))
1528 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1530 (defcustom org-special-ctrl-k nil
1531 "Non-nil means `C-k' will behave specially in headlines.
1532 When nil, `C-k' will call the default `kill-line' command.
1533 When t, the following will happen while the cursor is in the headline:
1535 - When the cursor is at the beginning of a headline, kill the entire
1536 line and possible the folded subtree below the line.
1537 - When in the middle of the headline text, kill the headline up to the tags.
1538 - When after the headline text, kill the tags."
1539 :group 'org-edit-structure
1540 :type 'boolean)
1542 (defcustom org-ctrl-k-protect-subtree nil
1543 "Non-nil means, do not delete a hidden subtree with C-k.
1544 When set to the symbol `error', simply throw an error when C-k is
1545 used to kill (part-of) a headline that has hidden text behind it.
1546 Any other non-nil value will result in a query to the user, if it is
1547 OK to kill that hidden subtree. When nil, kill without remorse."
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not protect hidden subtrees" nil)
1552 (const :tag "Protect hidden subtrees with a security query" t)
1553 (const :tag "Never kill a hidden subtree with C-k" error)))
1555 (defcustom org-special-ctrl-o t
1556 "Non-nil means, make `C-o' insert a row in tables."
1557 :group 'org-edit-structure
1558 :type 'boolean)
1560 (defcustom org-catch-invisible-edits nil
1561 "Check if in invisible region before inserting or deleting a character.
1562 Valid values are:
1564 nil Do not check, so just do invisible edits.
1565 error Throw an error and do nothing.
1566 show Make point visible, and do the requested edit.
1567 show-and-error Make point visible, then throw an error and abort the edit.
1568 smart Make point visible, and do insertion/deletion if it is
1569 adjacent to visible text and the change feels predictable.
1570 Never delete a previously invisible character or add in the
1571 middle or right after an invisible region. Basically, this
1572 allows insertion and backward-delete right before ellipses.
1573 FIXME: maybe in this case we should not even show?"
1574 :group 'org-edit-structure
1575 :version "24.1"
1576 :type '(choice
1577 (const :tag "Do not check" nil)
1578 (const :tag "Throw error when trying to edit" error)
1579 (const :tag "Unhide, but do not do the edit" show-and-error)
1580 (const :tag "Show invisible part and do the edit" show)
1581 (const :tag "Be smart and do the right thing" smart)))
1583 (defcustom org-yank-folded-subtrees t
1584 "Non-nil means when yanking subtrees, fold them.
1585 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1586 it starts with a heading and all other headings in it are either children
1587 or siblings, then fold all the subtrees. However, do this only if no
1588 text after the yank would be swallowed into a folded tree by this action."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-yank-adjusted-subtrees nil
1593 "Non-nil means when yanking subtrees, adjust the level.
1594 With this setting, `org-paste-subtree' is used to insert the subtree, see
1595 this function for details."
1596 :group 'org-edit-structure
1597 :type 'boolean)
1599 (defcustom org-M-RET-may-split-line '((default . t))
1600 "Non-nil means M-RET will split the line at the cursor position.
1601 When nil, it will go to the end of the line before making a
1602 new line.
1603 You may also set this option in a different way for different
1604 contexts. Valid contexts are:
1606 headline when creating a new headline
1607 item when creating a new item
1608 table in a table field
1609 default the value to be used for all contexts not explicitly
1610 customized"
1611 :group 'org-structure
1612 :group 'org-table
1613 :type '(choice
1614 (const :tag "Always" t)
1615 (const :tag "Never" nil)
1616 (repeat :greedy t :tag "Individual contexts"
1617 (cons
1618 (choice :tag "Context"
1619 (const headline)
1620 (const item)
1621 (const table)
1622 (const default))
1623 (boolean)))))
1626 (defcustom org-insert-heading-respect-content nil
1627 "Non-nil means insert new headings after the current subtree.
1628 \\<org-mode-map>
1629 When nil, the new heading is created directly after the current line.
1630 The commands `\\[org-insert-heading-respect-content]' and \
1631 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1632 for the duration of the command."
1633 :group 'org-structure
1634 :type 'boolean)
1636 (defcustom org-blank-before-new-entry '((heading . auto)
1637 (plain-list-item . auto))
1638 "Should `org-insert-heading' leave a blank line before new heading/item?
1639 The value is an alist, with `heading' and `plain-list-item' as CAR,
1640 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1641 which case Org will look at the surrounding headings/items and try to
1642 make an intelligent decision whether to insert a blank line or not."
1643 :group 'org-edit-structure
1644 :type '(list
1645 (cons (const heading)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))
1649 (cons (const plain-list-item)
1650 (choice (const :tag "Never" nil)
1651 (const :tag "Always" t)
1652 (const :tag "Auto" auto)))))
1654 (defcustom org-insert-heading-hook nil
1655 "Hook being run after inserting a new heading."
1656 :group 'org-edit-structure
1657 :type 'hook)
1659 (defcustom org-enable-fixed-width-editor t
1660 "Non-nil means lines starting with \":\" are treated as fixed-width.
1661 This currently only means they are never auto-wrapped.
1662 When nil, such lines will be treated like ordinary lines."
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defcustom org-goto-auto-isearch t
1667 "Non-nil means typing characters in `org-goto' starts incremental search.
1668 When nil, you can use these keybindings to navigate the buffer:
1670 q Quit the org-goto interface
1671 n Go to the next visible heading
1672 p Go to the previous visible heading
1673 f Go one heading forward on same level
1674 b Go one heading backward on same level
1675 u Go one heading up"
1676 :group 'org-edit-structure
1677 :type 'boolean)
1679 (defgroup org-sparse-trees nil
1680 "Options concerning sparse trees in Org mode."
1681 :tag "Org Sparse Trees"
1682 :group 'org-structure)
1684 (defcustom org-highlight-sparse-tree-matches t
1685 "Non-nil means highlight all matches that define a sparse tree.
1686 The highlights will automatically disappear the next time the buffer is
1687 changed by an edit command."
1688 :group 'org-sparse-trees
1689 :type 'boolean)
1691 (defcustom org-remove-highlights-with-change t
1692 "Non-nil means any change to the buffer will remove temporary highlights.
1693 \\<org-mode-map>\
1694 Such highlights are created by `org-occur' and `org-clock-display'.
1695 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1696 to get rid of the highlights.
1697 The highlights created by `org-toggle-latex-fragment' always need
1698 `\\[org-toggle-latex-fragment]' to be removed."
1699 :group 'org-sparse-trees
1700 :group 'org-time
1701 :type 'boolean)
1703 (defcustom org-occur-case-fold-search t
1704 "Non-nil means `org-occur' should be case-insensitive.
1705 If set to `smart' the search will be case-insensitive only if it
1706 doesn't specify any upper case character."
1707 :group 'org-sparse-trees
1708 :version "26.1"
1709 :type '(choice
1710 (const :tag "Case-sensitive" nil)
1711 (const :tag "Case-insensitive" t)
1712 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1714 (defcustom org-occur-hook '(org-first-headline-recenter)
1715 "Hook that is run after `org-occur' has constructed a sparse tree.
1716 This can be used to recenter the window to show as much of the structure
1717 as possible."
1718 :group 'org-sparse-trees
1719 :type 'hook)
1721 (defgroup org-imenu-and-speedbar nil
1722 "Options concerning imenu and speedbar in Org mode."
1723 :tag "Org Imenu and Speedbar"
1724 :group 'org-structure)
1726 (defcustom org-imenu-depth 2
1727 "The maximum level for Imenu access to Org headlines.
1728 This also applied for speedbar access."
1729 :group 'org-imenu-and-speedbar
1730 :type 'integer)
1732 (defgroup org-table nil
1733 "Options concerning tables in Org mode."
1734 :tag "Org Table"
1735 :group 'org)
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-parameters
1762 '(("doi" :follow org--open-doi-link)
1763 ("elisp" :follow org--open-elisp-link)
1764 ("file" :complete org-file-complete-link)
1765 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1766 ("help" :follow org--open-help-link)
1767 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1768 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1769 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1770 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1771 ("shell" :follow org--open-shell-link))
1772 "An alist of properties that defines all the links in Org mode.
1773 The key in each association is a string of the link type.
1774 Subsequent optional elements make up a p-list of link properties.
1776 :follow - A function that takes the link path as an argument.
1778 :export - A function that takes the link path, description and
1779 export-backend as arguments.
1781 :store - A function responsible for storing the link. See the
1782 function `org-store-link-functions'.
1784 :complete - A function that inserts a link with completion. The
1785 function takes one optional prefix arg.
1787 :face - A face for the link, or a function that returns a face.
1788 The function takes one argument which is the link path. The
1789 default face is `org-link'.
1791 :mouse-face - The mouse-face. The default is `highlight'.
1793 :display - `full' will not fold the link in descriptive
1794 display. Default is `org-link'.
1796 :help-echo - A string or function that takes (window object position)
1797 as arguments and returns a string.
1799 :keymap - A keymap that is active on the link. The default is
1800 `org-mouse-map'.
1802 :htmlize-link - A function for the htmlize-link. Defaults
1803 to (list :uri \"type:path\")
1805 :activate-func - A function to run at the end of font-lock
1806 activation. The function must accept (link-start link-end path bracketp)
1807 as arguments."
1808 :group 'org-link
1809 :type '(alist :tag "Link display parameters"
1810 :value-type plist)
1811 :version "26.1"
1812 :package-version '(Org . "9.1"))
1814 (defun org-link-get-parameter (type key)
1815 "Get TYPE link property for KEY.
1816 TYPE is a string and KEY is a plist keyword."
1817 (plist-get
1818 (cdr (assoc type org-link-parameters))
1819 key))
1821 (defun org-link-set-parameters (type &rest parameters)
1822 "Set link TYPE properties to PARAMETERS.
1823 PARAMETERS should be :key val pairs."
1824 (let ((data (assoc type org-link-parameters)))
1825 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1826 (push (cons type parameters) org-link-parameters)
1827 (org-make-link-regexps)
1828 (org-element-update-syntax))))
1830 (defun org-link-types ()
1831 "Return a list of known link types."
1832 (mapcar #'car org-link-parameters))
1834 (defcustom org-link-abbrev-alist nil
1835 "Alist of link abbreviations.
1836 The car of each element is a string, to be replaced at the start of a link.
1837 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1838 links in Org buffers can have an optional tag after a double colon, e.g.,
1840 [[linkkey:tag][description]]
1842 The `linkkey' must be a single word, starting with a letter, followed
1843 by letters, numbers, `-' or `_'.
1845 If REPLACE is a string, the tag will simply be appended to create the link.
1846 If the string contains \"%s\", the tag will be inserted there. If the string
1847 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1848 at that point (see the function `url-hexify-string'). If the string contains
1849 the specifier \"%(my-function)\", then the custom function `my-function' will
1850 be invoked: this function takes the tag as its only argument and must return
1851 a string.
1853 REPLACE may also be a function that will be called with the tag as the
1854 only argument to create the link, which should be returned as a string.
1856 See the manual for examples."
1857 :group 'org-link
1858 :type '(repeat
1859 (cons
1860 (string :tag "Protocol")
1861 (choice
1862 (string :tag "Format")
1863 (function)))))
1865 (defcustom org-descriptive-links t
1866 "Non-nil means Org will display descriptive links.
1867 E.g. [[http://orgmode.org][Org website]] will be displayed as
1868 \"Org Website\", hiding the link itself and just displaying its
1869 description. When set to nil, Org will display the full links
1870 literally.
1872 You can interactively set the value of this variable by calling
1873 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1874 :group 'org-link
1875 :type 'boolean)
1877 (defcustom org-link-file-path-type 'adaptive
1878 "How the path name in file links should be stored.
1879 Valid values are:
1881 relative Relative to the current directory, i.e. the directory of the file
1882 into which the link is being inserted.
1883 absolute Absolute path, if possible with ~ for home directory.
1884 noabbrev Absolute path, no abbreviation of home directory.
1885 adaptive Use relative path for files in the current directory and sub-
1886 directories of it. For other files, use an absolute path."
1887 :group 'org-link
1888 :type '(choice
1889 (const relative)
1890 (const absolute)
1891 (const noabbrev)
1892 (const adaptive)))
1894 (defvaralias 'org-activate-links 'org-highlight-links)
1895 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1896 "Types of links that should be highlighted in Org files.
1898 This is a list of symbols, each one of them leading to the
1899 highlighting of a certain link type.
1901 You can still open links that are not highlighted.
1903 In principle, it does not hurt to turn on highlighting for all
1904 link types. There may be a small gain when turning off unused
1905 link types. The types are:
1907 bracket The recommended [[link][description]] or [[link]] links with hiding.
1908 angle Links in angular brackets that may contain whitespace like
1909 <bbdb:Carsten Dominik>.
1910 plain Plain links in normal text, no whitespace, like http://google.com.
1911 radio Text that is matched by a radio target, see manual for details.
1912 tag Tag settings in a headline (link to tag search).
1913 date Time stamps (link to calendar).
1914 footnote Footnote labels.
1916 If you set this variable during an Emacs session, use `org-mode-restart'
1917 in the Org buffer so that the change takes effect."
1918 :group 'org-link
1919 :group 'org-appearance
1920 :type '(set :greedy t
1921 (const :tag "Double bracket links" bracket)
1922 (const :tag "Angular bracket links" angle)
1923 (const :tag "Plain text links" plain)
1924 (const :tag "Radio target matches" radio)
1925 (const :tag "Tags" tag)
1926 (const :tag "Timestamps" date)
1927 (const :tag "Footnotes" footnote)))
1929 (defcustom org-make-link-description-function nil
1930 "Function to use for generating link descriptions from links.
1931 When nil, the link location will be used. This function must take
1932 two parameters: the first one is the link, the second one is the
1933 description generated by `org-insert-link'. The function should
1934 return the description to use."
1935 :group 'org-link
1936 :type '(choice (const nil) (function)))
1938 (defgroup org-link-store nil
1939 "Options concerning storing links in Org mode."
1940 :tag "Org Store Link"
1941 :group 'org-link)
1943 (defcustom org-url-hexify-p t
1944 "When non-nil, hexify URL when creating a link."
1945 :type 'boolean
1946 :version "24.3"
1947 :group 'org-link-store)
1949 (defcustom org-email-link-description-format "Email %c: %.30s"
1950 "Format of the description part of a link to an email or usenet message.
1951 The following %-escapes will be replaced by corresponding information:
1953 %F full \"From\" field
1954 %f name, taken from \"From\" field, address if no name
1955 %T full \"To\" field
1956 %t first name in \"To\" field, address if no name
1957 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1958 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1959 %s subject
1960 %d date
1961 %m message-id.
1963 You may use normal field width specification between the % and the letter.
1964 This is for example useful to limit the length of the subject.
1966 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1967 :group 'org-link-store
1968 :type 'string)
1970 (defcustom org-from-is-user-regexp
1971 (let (r1 r2)
1972 (when (and user-mail-address (not (string= user-mail-address "")))
1973 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1974 (when (and user-full-name (not (string= user-full-name "")))
1975 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1976 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1977 "Regexp matched against the \"From:\" header of an email or usenet message.
1978 It should match if the message is from the user him/herself."
1979 :group 'org-link-store
1980 :type 'regexp)
1982 (defcustom org-context-in-file-links t
1983 "Non-nil means file links from `org-store-link' contain context.
1984 \\<org-mode-map>
1985 A search string will be added to the file name with :: as separator
1986 and used to find the context when the link is activated by the command
1987 `org-open-at-point'. When this option is t, the entire active region
1988 will be placed in the search string of the file link. If set to a
1989 positive integer, only the first n lines of context will be stored.
1991 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1992 \\[org-store-link]')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
1999 \\<org-mode-map>
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links).
2005 When this option is nil, every link which has been inserted once using
2006 `\\[org-insert-link]' will be removed from the list, to make completing the \
2007 unused
2008 links more efficient."
2009 :group 'org-link-store
2010 :type 'boolean)
2012 (defgroup org-link-follow nil
2013 "Options concerning following links in Org mode."
2014 :tag "Org Follow Link"
2015 :group 'org-link)
2017 (defcustom org-link-translation-function nil
2018 "Function to translate links with different syntax to Org syntax.
2019 This can be used to translate links created for example by the Planner
2020 or emacs-wiki packages to Org syntax.
2021 The function must accept two parameters, a TYPE containing the link
2022 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2023 which is everything after the link protocol. It should return a cons
2024 with possibly modified values of type and path.
2025 Org contains a function for this, so if you set this variable to
2026 `org-translate-link-from-planner', you should be able follow many
2027 links created by planner."
2028 :group 'org-link-follow
2029 :type '(choice (const nil) (function)))
2031 (defcustom org-follow-link-hook nil
2032 "Hook that is run after a link has been followed."
2033 :group 'org-link-follow
2034 :type 'hook)
2036 (defcustom org-tab-follows-link nil
2037 "Non-nil means on links TAB will follow the link.
2038 Needs to be set before org.el is loaded.
2039 This really should not be used, it does not make sense, and the
2040 implementation is bad."
2041 :group 'org-link-follow
2042 :type 'boolean)
2044 (defcustom org-return-follows-link nil
2045 "Non-nil means on links RET will follow the link.
2046 In tables, the special behavior of RET has precedence."
2047 :group 'org-link-follow
2048 :type 'boolean)
2050 (defcustom org-mouse-1-follows-link
2051 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2052 "Non-nil means mouse-1 on a link will follow the link.
2053 A longer mouse click will still set point. Needs to be set
2054 before org.el is loaded."
2055 :group 'org-link-follow
2056 :version "24.4"
2057 :package-version '(Org . "8.3")
2058 :type '(choice
2059 (const :tag "A double click follows the link" double)
2060 (const :tag "Unconditionally follow the link with mouse-1" t)
2061 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2063 (defcustom org-mark-ring-length 4
2064 "Number of different positions to be recorded in the ring.
2065 Changing this requires a restart of Emacs to work correctly."
2066 :group 'org-link-follow
2067 :type 'integer)
2069 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2070 "Non-nil means internal fuzzy links can only match headlines.
2072 When nil, the a fuzzy link may point to a target or a named
2073 construct in the document. When set to the special value
2074 `query-to-create', offer to create a new headline when none
2075 matched.
2077 Spaces and statistics cookies are ignored during heading searches."
2078 :group 'org-link-follow
2079 :version "24.1"
2080 :type '(choice
2081 (const :tag "Use fuzzy text search" nil)
2082 (const :tag "Match only exact headline" t)
2083 (const :tag "Match exact headline or query to create it"
2084 query-to-create))
2085 :safe #'symbolp)
2087 (defcustom org-link-frame-setup
2088 '((vm . vm-visit-folder-other-frame)
2089 (vm-imap . vm-visit-imap-folder-other-frame)
2090 (gnus . org-gnus-no-new-news)
2091 (file . find-file-other-window)
2092 (wl . wl-other-frame))
2093 "Setup the frame configuration for following links.
2094 When following a link with Emacs, it may often be useful to display
2095 this link in another window or frame. This variable can be used to
2096 set this up for the different types of links.
2097 For VM, use any of
2098 `vm-visit-folder'
2099 `vm-visit-folder-other-window'
2100 `vm-visit-folder-other-frame'
2101 For Gnus, use any of
2102 `gnus'
2103 `gnus-other-frame'
2104 `org-gnus-no-new-news'
2105 For FILE, use any of
2106 `find-file'
2107 `find-file-other-window'
2108 `find-file-other-frame'
2109 For Wanderlust use any of
2110 `wl'
2111 `wl-other-frame'
2112 For the calendar, use the variable `calendar-setup'.
2113 For BBDB, it is currently only possible to display the matches in
2114 another window."
2115 :group 'org-link-follow
2116 :type '(list
2117 (cons (const vm)
2118 (choice
2119 (const vm-visit-folder)
2120 (const vm-visit-folder-other-window)
2121 (const vm-visit-folder-other-frame)))
2122 (cons (const vm-imap)
2123 (choice
2124 (const vm-visit-imap-folder)
2125 (const vm-visit-imap-folder-other-window)
2126 (const vm-visit-imap-folder-other-frame)))
2127 (cons (const gnus)
2128 (choice
2129 (const gnus)
2130 (const gnus-other-frame)
2131 (const org-gnus-no-new-news)))
2132 (cons (const file)
2133 (choice
2134 (const find-file)
2135 (const find-file-other-window)
2136 (const find-file-other-frame)))
2137 (cons (const wl)
2138 (choice
2139 (const wl)
2140 (const wl-other-frame)))))
2142 (defcustom org-display-internal-link-with-indirect-buffer nil
2143 "Non-nil means use indirect buffer to display infile links.
2144 Activating internal links (from one location in a file to another location
2145 in the same file) normally just jumps to the location. When the link is
2146 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2147 is displayed in
2148 another window. When this option is set, the other window actually displays
2149 an indirect buffer clone of the current buffer, to avoid any visibility
2150 changes to the current buffer."
2151 :group 'org-link-follow
2152 :type 'boolean)
2154 (defcustom org-open-non-existing-files nil
2155 "Non-nil means `org-open-file' will open non-existing files.
2156 When nil, an error will be generated.
2157 This variable applies only to external applications because they
2158 might choke on non-existing files. If the link is to a file that
2159 will be opened in Emacs, the variable is ignored."
2160 :group 'org-link-follow
2161 :type 'boolean)
2163 (defcustom org-open-directory-means-index-dot-org nil
2164 "Non-nil means a link to a directory really means to index.org.
2165 When nil, following a directory link will run dired or open a finder/explorer
2166 window on that directory."
2167 :group 'org-link-follow
2168 :type 'boolean)
2170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2171 "Non-nil means ask for confirmation before executing shell links.
2172 Shell links can be dangerous: just think about a link
2174 [[shell:rm -rf ~/*][Google Search]]
2176 This link would show up in your Org document as \"Google Search\",
2177 but really it would remove your entire home directory.
2178 Therefore we advise against setting this variable to nil.
2179 Just change it to `y-or-n-p' if you want to confirm with a
2180 single keystroke rather than having to type \"yes\"."
2181 :group 'org-link-follow
2182 :type '(choice
2183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2184 (const :tag "with y-or-n (faster)" y-or-n-p)
2185 (const :tag "no confirmation (dangerous)" nil)))
2186 (put 'org-confirm-shell-link-function
2187 'safe-local-variable
2188 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2190 (defcustom org-confirm-shell-link-not-regexp ""
2191 "A regexp to skip confirmation for shell links."
2192 :group 'org-link-follow
2193 :version "24.1"
2194 :type 'regexp)
2196 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2197 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2198 Elisp links can be dangerous: just think about a link
2200 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2202 This link would show up in your Org document as \"Google Search\",
2203 but really it would remove your entire home directory.
2204 Therefore we advise against setting this variable to nil.
2205 Just change it to `y-or-n-p' if you want to confirm with a
2206 single keystroke rather than having to type \"yes\"."
2207 :group 'org-link-follow
2208 :type '(choice
2209 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2210 (const :tag "with y-or-n (faster)" y-or-n-p)
2211 (const :tag "no confirmation (dangerous)" nil)))
2212 (put 'org-confirm-shell-link-function
2213 'safe-local-variable
2214 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2216 (defcustom org-confirm-elisp-link-not-regexp ""
2217 "A regexp to skip confirmation for Elisp links."
2218 :group 'org-link-follow
2219 :version "24.1"
2220 :type 'regexp)
2222 (defconst org-file-apps-defaults-gnu
2223 '((remote . emacs)
2224 (system . mailcap)
2225 (t . mailcap))
2226 "Default file applications on a UNIX or GNU/Linux system.
2227 See `org-file-apps'.")
2229 (defconst org-file-apps-defaults-macosx
2230 '((remote . emacs)
2231 (system . "open %s")
2232 ("ps.gz" . "gv %s")
2233 ("eps.gz" . "gv %s")
2234 ("dvi" . "xdvi %s")
2235 ("fig" . "xfig %s")
2236 (t . "open %s"))
2237 "Default file applications on a macOS system.
2238 The system \"open\" is known as a default, but we use X11 applications
2239 for some files for which the OS does not have a good default.
2240 See `org-file-apps'.")
2242 (defconst org-file-apps-defaults-windowsnt
2243 (list '(remote . emacs)
2244 (cons 'system (lambda (file _path)
2245 (with-no-warnings (w32-shell-execute "open" file))))
2246 (cons t (lambda (file _path)
2247 (with-no-warnings (w32-shell-execute "open" file)))))
2248 "Default file applications on a Windows NT system.
2249 The system \"open\" is used for most files.
2250 See `org-file-apps'.")
2252 (defcustom org-file-apps
2253 '((auto-mode . emacs)
2254 ("\\.mm\\'" . default)
2255 ("\\.x?html?\\'" . default)
2256 ("\\.pdf\\'" . default))
2257 "External applications for opening `file:path' items in a document.
2258 \\<org-mode-map>\
2260 Org mode uses system defaults for different file types, but
2261 you can use this variable to set the application for a given file
2262 extension. The entries in this list are cons cells where the car identifies
2263 files and the cdr the corresponding command.
2265 Possible values for the file identifier are:
2267 \"string\" A string as a file identifier can be interpreted in different
2268 ways, depending on its contents:
2270 - Alphanumeric characters only:
2271 Match links with this file extension.
2272 Example: (\"pdf\" . \"evince %s\")
2273 to open PDFs with evince.
2275 - Regular expression: Match links where the
2276 filename matches the regexp. If you want to
2277 use groups here, use shy groups.
2279 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2280 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2281 to open *.html and *.xhtml with firefox.
2283 - Regular expression which contains (non-shy) groups:
2284 Match links where the whole link, including \"::\", and
2285 anything after that, matches the regexp.
2286 In a custom command string, %1, %2, etc. are replaced with
2287 the parts of the link that were matched by the groups.
2288 For backwards compatibility, if a command string is given
2289 that does not use any of the group matches, this case is
2290 handled identically to the second one (i.e. match against
2291 file name only).
2292 In a custom function, you can access the group matches with
2293 (match-string n link).
2295 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2296 \"evince -p %1 %s\")
2297 to open [[file:document.pdf::5]] with evince at page 5.
2299 `directory' Matches a directory
2300 `remote' Matches a remote file, accessible through tramp or efs.
2301 Remote files most likely should be visited through Emacs
2302 because external applications cannot handle such paths.
2303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2304 so all files Emacs knows how to handle. Using this with
2305 command `emacs' will open most files in Emacs. Beware that this
2306 will also open html files inside Emacs, unless you add
2307 (\"html\" . default) to the list as well.
2308 `system' The system command to open files, like `open' on Windows
2309 and macOS, and mailcap under GNU/Linux. This is the command
2310 that will be selected if you call `org-open-at-point' with a
2311 double prefix argument (`\\[universal-argument] \
2312 \\[universal-argument] \\[org-open-at-point]').
2313 t Default for files not matched by any of the other options.
2315 Possible values for the command are:
2317 `emacs' The file will be visited by the current Emacs process.
2318 `default' Use the default application for this file type, which is the
2319 association for t in the list, most likely in the system-specific
2320 part. This can be used to overrule an unwanted setting in the
2321 system-specific variable.
2322 `system' Use the system command for opening files, like \"open\".
2323 This command is specified by the entry whose car is `system'.
2324 Most likely, the system-specific version of this variable
2325 does define this command, but you can overrule/replace it
2326 here.
2327 `mailcap' Use command specified in the mailcaps.
2328 string A command to be executed by a shell; %s will be replaced
2329 by the path to the file.
2330 function A Lisp function, which will be called with two arguments:
2331 the file path and the original link string, without the
2332 \"file:\" prefix.
2334 For more examples, see the system specific constants
2335 `org-file-apps-defaults-macosx'
2336 `org-file-apps-defaults-windowsnt'
2337 `org-file-apps-defaults-gnu'."
2338 :group 'org-link-follow
2339 :type '(repeat
2340 (cons (choice :value ""
2341 (string :tag "Extension")
2342 (const :tag "System command to open files" system)
2343 (const :tag "Default for unrecognized files" t)
2344 (const :tag "Remote file" remote)
2345 (const :tag "Links to a directory" directory)
2346 (const :tag "Any files that have Emacs modes"
2347 auto-mode))
2348 (choice :value ""
2349 (const :tag "Visit with Emacs" emacs)
2350 (const :tag "Use default" default)
2351 (const :tag "Use the system command" system)
2352 (string :tag "Command")
2353 (function :tag "Function")))))
2355 (defcustom org-doi-server-url "http://dx.doi.org/"
2356 "The URL of the DOI server."
2357 :type 'string
2358 :version "24.3"
2359 :group 'org-link-follow)
2361 (defgroup org-refile nil
2362 "Options concerning refiling entries in Org mode."
2363 :tag "Org Refile"
2364 :group 'org)
2366 (defcustom org-directory "~/org"
2367 "Directory with Org files.
2368 This is just a default location to look for Org files. There is no need
2369 at all to put your files into this directory. It is used in the
2370 following situations:
2372 1. When a capture template specifies a target file that is not an
2373 absolute path. The path will then be interpreted relative to
2374 `org-directory'
2375 2. When the value of variable `org-agenda-files' is a single file, any
2376 relative paths in this file will be taken as relative to
2377 `org-directory'."
2378 :group 'org-refile
2379 :group 'org-capture
2380 :type 'directory)
2382 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2383 "Default target for storing notes.
2384 Used as a fall back file for org-capture.el, for templates that
2385 do not specify a target file."
2386 :group 'org-refile
2387 :group 'org-capture
2388 :type 'file)
2390 (defcustom org-goto-interface 'outline
2391 "The default interface to be used for `org-goto'.
2392 Allowed values are:
2393 outline The interface shows an outline of the relevant file
2394 and the correct heading is found by moving through
2395 the outline or by searching with incremental search.
2396 outline-path-completion Headlines in the current buffer are offered via
2397 completion. This is the interface also used by
2398 the refile command."
2399 :group 'org-refile
2400 :type '(choice
2401 (const :tag "Outline" outline)
2402 (const :tag "Outline-path-completion" outline-path-completion)))
2404 (defcustom org-goto-max-level 5
2405 "Maximum target level when running `org-goto' with refile interface."
2406 :group 'org-refile
2407 :type 'integer)
2409 (defcustom org-reverse-note-order nil
2410 "Non-nil means store new notes at the beginning of a file or entry.
2411 When nil, new notes will be filed to the end of a file or entry.
2412 This can also be a list with cons cells of regular expressions that
2413 are matched against file names, and values."
2414 :group 'org-capture
2415 :group 'org-refile
2416 :type '(choice
2417 (const :tag "Reverse always" t)
2418 (const :tag "Reverse never" nil)
2419 (repeat :tag "By file name regexp"
2420 (cons regexp boolean))))
2422 (defcustom org-log-refile nil
2423 "Information to record when a task is refiled.
2425 Possible values are:
2427 nil Don't add anything
2428 time Add a time stamp to the task
2429 note Prompt for a note and add it with template `org-log-note-headings'
2431 This option can also be set with on a per-file-basis with
2433 #+STARTUP: nologrefile
2434 #+STARTUP: logrefile
2435 #+STARTUP: lognoterefile
2437 You can have local logging settings for a subtree by setting the LOGGING
2438 property to one or more of these keywords.
2440 When bulk-refiling from the agenda, the value `note' is forbidden and
2441 will temporarily be changed to `time'."
2442 :group 'org-refile
2443 :group 'org-progress
2444 :version "24.1"
2445 :type '(choice
2446 (const :tag "No logging" nil)
2447 (const :tag "Record timestamp" time)
2448 (const :tag "Record timestamp with note." note)))
2450 (defcustom org-refile-targets nil
2451 "Targets for refiling entries with `\\[org-refile]'.
2452 This is a list of cons cells. Each cell contains:
2453 - a specification of the files to be considered, either a list of files,
2454 or a symbol whose function or variable value will be used to retrieve
2455 a file name or a list of file names. If you use `org-agenda-files' for
2456 that, all agenda files will be scanned for targets. Nil means consider
2457 headings in the current buffer.
2458 - A specification of how to find candidate refile targets. This may be
2459 any of:
2460 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2461 This tag has to be present in all target headlines, inheritance will
2462 not be considered.
2463 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2464 todo keyword.
2465 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2466 headlines that are refiling targets.
2467 - a cons cell (:level . N). Any headline of level N is considered a target.
2468 Note that, when `org-odd-levels-only' is set, level corresponds to
2469 order in hierarchy, not to the number of stars.
2470 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2471 Note that, when `org-odd-levels-only' is set, level corresponds to
2472 order in hierarchy, not to the number of stars.
2474 Each element of this list generates a set of possible targets.
2475 The union of these sets is presented (with completion) to
2476 the user by `org-refile'.
2478 You can set the variable `org-refile-target-verify-function' to a function
2479 to verify each headline found by the simple criteria above.
2481 When this variable is nil, all top-level headlines in the current buffer
2482 are used, equivalent to the value `((nil . (:level . 1))'."
2483 :group 'org-refile
2484 :type '(repeat
2485 (cons
2486 (choice :value org-agenda-files
2487 (const :tag "All agenda files" org-agenda-files)
2488 (const :tag "Current buffer" nil)
2489 (function) (variable) (file))
2490 (choice :tag "Identify target headline by"
2491 (cons :tag "Specific tag" (const :value :tag) (string))
2492 (cons :tag "TODO keyword" (const :value :todo) (string))
2493 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2494 (cons :tag "Level number" (const :value :level) (integer))
2495 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2497 (defcustom org-refile-target-verify-function nil
2498 "Function to verify if the headline at point should be a refile target.
2499 The function will be called without arguments, with point at the
2500 beginning of the headline. It should return t and leave point
2501 where it is if the headline is a valid target for refiling.
2503 If the target should not be selected, the function must return nil.
2504 In addition to this, it may move point to a place from where the search
2505 should be continued. For example, the function may decide that the entire
2506 subtree of the current entry should be excluded and move point to the end
2507 of the subtree."
2508 :group 'org-refile
2509 :type '(choice
2510 (const nil)
2511 (function)))
2513 (defcustom org-refile-use-cache nil
2514 "Non-nil means cache refile targets to speed up the process.
2515 \\<org-mode-map>\
2516 The cache for a particular file will be updated automatically when
2517 the buffer has been killed, or when any of the marker used for flagging
2518 refile targets no longer points at a live buffer.
2519 If you have added new entries to a buffer that might themselves be targets,
2520 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2521 if you find that easier, \
2522 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2523 \\[org-refile]'."
2524 :group 'org-refile
2525 :version "24.1"
2526 :type 'boolean)
2528 (defcustom org-refile-use-outline-path nil
2529 "Non-nil means provide refile targets as paths.
2530 So a level 3 headline will be available as level1/level2/level3.
2532 When the value is `file', also include the file name (without directory)
2533 into the path. In this case, you can also stop the completion after
2534 the file name, to get entries inserted as top level in the file.
2536 When `full-file-path', include the full file path.
2538 When `buffer-name', use the buffer name."
2539 :group 'org-refile
2540 :type '(choice
2541 (const :tag "Not" nil)
2542 (const :tag "Yes" t)
2543 (const :tag "Start with file name" file)
2544 (const :tag "Start with full file path" full-file-path)
2545 (const :tag "Start with buffer name" buffer-name)))
2547 (defcustom org-outline-path-complete-in-steps t
2548 "Non-nil means complete the outline path in hierarchical steps.
2549 When Org uses the refile interface to select an outline path (see
2550 `org-refile-use-outline-path'), the completion of the path can be
2551 done in a single go, or it can be done in steps down the headline
2552 hierarchy. Going in steps is probably the best if you do not use
2553 a special completion package like `ido' or `icicles'. However,
2554 when using these packages, going in one step can be very fast,
2555 while still showing the whole path to the entry."
2556 :group 'org-refile
2557 :type 'boolean)
2559 (defcustom org-refile-allow-creating-parent-nodes nil
2560 "Non-nil means allow the creation of new nodes as refile targets.
2561 New nodes are then created by adding \"/new node name\" to the completion
2562 of an existing node. When the value of this variable is `confirm',
2563 new node creation must be confirmed by the user (recommended).
2564 When nil, the completion must match an existing entry.
2566 Note that, if the new heading is not seen by the criteria
2567 listed in `org-refile-targets', multiple instances of the same
2568 heading would be created by trying again to file under the new
2569 heading."
2570 :group 'org-refile
2571 :type '(choice
2572 (const :tag "Never" nil)
2573 (const :tag "Always" t)
2574 (const :tag "Prompt for confirmation" confirm)))
2576 (defcustom org-refile-active-region-within-subtree nil
2577 "Non-nil means also refile active region within a subtree.
2579 By default `org-refile' doesn't allow refiling regions if they
2580 don't contain a set of subtrees, but it might be convenient to
2581 do so sometimes: in that case, the first line of the region is
2582 converted to a headline before refiling."
2583 :group 'org-refile
2584 :version "24.1"
2585 :type 'boolean)
2587 (defgroup org-todo nil
2588 "Options concerning TODO items in Org mode."
2589 :tag "Org TODO"
2590 :group 'org)
2592 (defgroup org-progress nil
2593 "Options concerning Progress logging in Org mode."
2594 :tag "Org Progress"
2595 :group 'org-time)
2597 (defvar org-todo-interpretation-widgets
2598 '((:tag "Sequence (cycling hits every state)" sequence)
2599 (:tag "Type (cycling directly to DONE)" type))
2600 "The available interpretation symbols for customizing `org-todo-keywords'.
2601 Interested libraries should add to this list.")
2603 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2604 "List of TODO entry keyword sequences and their interpretation.
2605 \\<org-mode-map>This is a list of sequences.
2607 Each sequence starts with a symbol, either `sequence' or `type',
2608 indicating if the keywords should be interpreted as a sequence of
2609 action steps, or as different types of TODO items. The first
2610 keywords are states requiring action - these states will select a headline
2611 for inclusion into the global TODO list Org produces. If one of the
2612 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2613 signify that no further action is necessary. If \"|\" is not found,
2614 the last keyword is treated as the only DONE state of the sequence.
2616 The command `\\[org-todo]' cycles an entry through these states, and one
2617 additional state where no keyword is present. For details about this
2618 cycling, see the manual.
2620 TODO keywords and interpretation can also be set on a per-file basis with
2621 the special #+SEQ_TODO and #+TYP_TODO lines.
2623 Each keyword can optionally specify a character for fast state selection
2624 \(in combination with the variable `org-use-fast-todo-selection')
2625 and specifiers for state change logging, using the same syntax that
2626 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2627 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2628 indicates to record a time stamp each time this state is selected.
2630 Each keyword may also specify if a timestamp or a note should be
2631 recorded when entering or leaving the state, by adding additional
2632 characters in the parenthesis after the keyword. This looks like this:
2633 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2634 record only the time of the state change. With X and Y being either
2635 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2636 Y when leaving the state if and only if the *target* state does not
2637 define X. You may omit any of the fast-selection key or X or /Y,
2638 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2640 For backward compatibility, this variable may also be just a list
2641 of keywords. In this case the interpretation (sequence or type) will be
2642 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2643 :group 'org-todo
2644 :group 'org-keywords
2645 :type '(choice
2646 (repeat :tag "Old syntax, just keywords"
2647 (string :tag "Keyword"))
2648 (repeat :tag "New syntax"
2649 (cons
2650 (choice
2651 :tag "Interpretation"
2652 ;;Quick and dirty way to see
2653 ;;`org-todo-interpretations'. This takes the
2654 ;;place of item arguments
2655 :convert-widget
2656 (lambda (widget)
2657 (widget-put widget
2658 :args (mapcar
2659 (lambda (x)
2660 (widget-convert
2661 (cons 'const x)))
2662 org-todo-interpretation-widgets))
2663 widget))
2664 (repeat
2665 (string :tag "Keyword"))))))
2667 (defvar-local org-todo-keywords-1 nil
2668 "All TODO and DONE keywords active in a buffer.")
2669 (defvar org-todo-keywords-for-agenda nil)
2670 (defvar org-done-keywords-for-agenda nil)
2671 (defvar org-todo-keyword-alist-for-agenda nil)
2672 (defvar org-tag-alist-for-agenda nil
2673 "Alist of all tags from all agenda files.")
2674 (defvar org-tag-groups-alist-for-agenda nil
2675 "Alist of all groups tags from all current agenda files.")
2676 (defvar-local org-tag-groups-alist nil)
2677 (defvar org-agenda-contributing-files nil)
2678 (defvar-local org-current-tag-alist nil
2679 "Alist of all tag groups in current buffer.
2680 This variable takes into consideration `org-tag-alist',
2681 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2682 (defvar-local org-not-done-keywords nil)
2683 (defvar-local org-done-keywords nil)
2684 (defvar-local org-todo-heads nil)
2685 (defvar-local org-todo-sets nil)
2686 (defvar-local org-todo-log-states nil)
2687 (defvar-local org-todo-kwd-alist nil)
2688 (defvar-local org-todo-key-alist nil)
2689 (defvar-local org-todo-key-trigger nil)
2691 (defcustom org-todo-interpretation 'sequence
2692 "Controls how TODO keywords are interpreted.
2693 This variable is in principle obsolete and is only used for
2694 backward compatibility, if the interpretation of todo keywords is
2695 not given already in `org-todo-keywords'. See that variable for
2696 more information."
2697 :group 'org-todo
2698 :group 'org-keywords
2699 :type '(choice (const sequence)
2700 (const type)))
2702 (defcustom org-use-fast-todo-selection t
2703 "\\<org-mode-map>\
2704 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2705 This variable describes if and under what circumstances the cycling
2706 mechanism for TODO keywords will be replaced by a single-key, direct
2707 selection scheme.
2709 When nil, fast selection is never used.
2711 When the symbol `prefix', it will be used when `org-todo' is called
2712 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2713 in an Org buffer, and
2714 `\\[universal-argument] t' in an agenda buffer.
2716 When t, fast selection is used by default. In this case, the prefix
2717 argument forces cycling instead.
2719 In all cases, the special interface is only used if access keys have
2720 actually been assigned by the user, i.e. if keywords in the configuration
2721 are followed by a letter in parenthesis, like TODO(t)."
2722 :group 'org-todo
2723 :type '(choice
2724 (const :tag "Never" nil)
2725 (const :tag "By default" t)
2726 (const :tag "Only with C-u C-c C-t" prefix)))
2728 (defcustom org-provide-todo-statistics t
2729 "Non-nil means update todo statistics after insert and toggle.
2730 ALL-HEADLINES means update todo statistics by including headlines
2731 with no TODO keyword as well, counting them as not done.
2732 A list of TODO keywords means the same, but skip keywords that are
2733 not in this list.
2734 When set to a list of two lists, the first list contains keywords
2735 to consider as TODO keywords, the second list contains keywords
2736 to consider as DONE keywords.
2738 When this is set, todo statistics is updated in the parent of the
2739 current entry each time a todo state is changed."
2740 :group 'org-todo
2741 :type '(choice
2742 (const :tag "Yes, only for TODO entries" t)
2743 (const :tag "Yes, including all entries" all-headlines)
2744 (repeat :tag "Yes, for TODOs in this list"
2745 (string :tag "TODO keyword"))
2746 (list :tag "Yes, for TODOs and DONEs in these lists"
2747 (repeat (string :tag "TODO keyword"))
2748 (repeat (string :tag "DONE keyword")))
2749 (other :tag "No TODO statistics" nil)))
2751 (defcustom org-hierarchical-todo-statistics t
2752 "Non-nil means TODO statistics covers just direct children.
2753 When nil, all entries in the subtree are considered.
2754 This has only an effect if `org-provide-todo-statistics' is set.
2755 To set this to nil for only a single subtree, use a COOKIE_DATA
2756 property and include the word \"recursive\" into the value."
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-after-todo-state-change-hook nil
2761 "Hook which is run after the state of a TODO item was changed.
2762 The new state (a string with a TODO keyword, or nil) is available in the
2763 Lisp variable `org-state'."
2764 :group 'org-todo
2765 :type 'hook)
2767 (defvar org-blocker-hook nil
2768 "Hook for functions that are allowed to block a state change.
2770 Functions in this hook should not modify the buffer.
2771 Each function gets as its single argument a property list,
2772 see `org-trigger-hook' for more information about this list.
2774 If any of the functions in this hook returns nil, the state change
2775 is blocked.")
2777 (defvar org-trigger-hook nil
2778 "Hook for functions that are triggered by a state change.
2780 Each function gets as its single argument a property list with at
2781 least the following elements:
2783 (:type type-of-change :position pos-at-entry-start
2784 :from old-state :to new-state)
2786 Depending on the type, more properties may be present.
2788 This mechanism is currently implemented for:
2790 TODO state changes
2791 ------------------
2792 :type todo-state-change
2793 :from previous state (keyword as a string), or nil, or a symbol
2794 `todo' or `done', to indicate the general type of state.
2795 :to new state, like in :from")
2797 (defcustom org-enforce-todo-dependencies nil
2798 "Non-nil means undone TODO entries will block switching the parent to DONE.
2799 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2800 be blocked if any prior sibling is not yet done.
2801 Finally, if the parent is blocked because of ordered siblings of its own,
2802 the child will also be blocked."
2803 :set (lambda (var val)
2804 (set var val)
2805 (if val
2806 (add-hook 'org-blocker-hook
2807 'org-block-todo-from-children-or-siblings-or-parent)
2808 (remove-hook 'org-blocker-hook
2809 'org-block-todo-from-children-or-siblings-or-parent)))
2810 :group 'org-todo
2811 :type 'boolean)
2813 (defcustom org-enforce-todo-checkbox-dependencies nil
2814 "Non-nil means unchecked boxes will block switching the parent to DONE.
2815 When this is nil, checkboxes have no influence on switching TODO states.
2816 When non-nil, you first need to check off all check boxes before the TODO
2817 entry can be switched to DONE.
2818 This variable needs to be set before org.el is loaded, and you need to
2819 restart Emacs after a change to make the change effective. The only way
2820 to change is while Emacs is running is through the customize interface."
2821 :set (lambda (var val)
2822 (set var val)
2823 (if val
2824 (add-hook 'org-blocker-hook
2825 'org-block-todo-from-checkboxes)
2826 (remove-hook 'org-blocker-hook
2827 'org-block-todo-from-checkboxes)))
2828 :group 'org-todo
2829 :type 'boolean)
2831 (defcustom org-treat-insert-todo-heading-as-state-change nil
2832 "Non-nil means inserting a TODO heading is treated as state change.
2833 So when the command `\\[org-insert-todo-heading]' is used, state change
2834 logging will apply if appropriate. When nil, the new TODO item will
2835 be inserted directly, and no logging will take place."
2836 :group 'org-todo
2837 :type 'boolean)
2839 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2840 "Non-nil means switching TODO states with S-cursor counts as state change.
2841 This is the default behavior. However, setting this to nil allows a
2842 convenient way to select a TODO state and bypass any logging associated
2843 with that."
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-todo-state-tags-triggers nil
2848 "Tag changes that should be triggered by TODO state changes.
2849 This is a list. Each entry is
2851 (state-change (tag . flag) .......)
2853 State-change can be a string with a state, and empty string to indicate the
2854 state that has no TODO keyword, or it can be one of the symbols `todo'
2855 or `done', meaning any not-done or done state, respectively."
2856 :group 'org-todo
2857 :group 'org-tags
2858 :type '(repeat
2859 (cons (choice :tag "When changing to"
2860 (const :tag "Not-done state" todo)
2861 (const :tag "Done state" done)
2862 (string :tag "State"))
2863 (repeat
2864 (cons :tag "Tag action"
2865 (string :tag "Tag")
2866 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2868 (defcustom org-log-done nil
2869 "Information to record when a task moves to the DONE state.
2871 Possible values are:
2873 nil Don't add anything, just change the keyword
2874 time Add a time stamp to the task
2875 note Prompt for a note and add it with template `org-log-note-headings'
2877 This option can also be set with on a per-file-basis with
2879 #+STARTUP: nologdone
2880 #+STARTUP: logdone
2881 #+STARTUP: lognotedone
2883 You can have local logging settings for a subtree by setting the LOGGING
2884 property to one or more of these keywords."
2885 :group 'org-todo
2886 :group 'org-progress
2887 :type '(choice
2888 (const :tag "No logging" nil)
2889 (const :tag "Record CLOSED timestamp" time)
2890 (const :tag "Record CLOSED timestamp with note." note)))
2892 ;; Normalize old uses of org-log-done.
2893 (cond
2894 ((eq org-log-done t) (setq org-log-done 'time))
2895 ((and (listp org-log-done) (memq 'done org-log-done))
2896 (setq org-log-done 'note)))
2898 (defcustom org-log-reschedule nil
2899 "Information to record when the scheduling date of a tasks is modified.
2901 Possible values are:
2903 nil Don't add anything, just change the date
2904 time Add a time stamp to the task
2905 note Prompt for a note and add it with template `org-log-note-headings'
2907 This option can also be set with on a per-file-basis with
2909 #+STARTUP: nologreschedule
2910 #+STARTUP: logreschedule
2911 #+STARTUP: lognotereschedule"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type '(choice
2915 (const :tag "No logging" nil)
2916 (const :tag "Record timestamp" time)
2917 (const :tag "Record timestamp with note." note)))
2919 (defcustom org-log-redeadline nil
2920 "Information to record when the deadline date of a tasks is modified.
2922 Possible values are:
2924 nil Don't add anything, just change the date
2925 time Add a time stamp to the task
2926 note Prompt for a note and add it with template `org-log-note-headings'
2928 This option can also be set with on a per-file-basis with
2930 #+STARTUP: nologredeadline
2931 #+STARTUP: logredeadline
2932 #+STARTUP: lognoteredeadline
2934 You can have local logging settings for a subtree by setting the LOGGING
2935 property to one or more of these keywords."
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type '(choice
2939 (const :tag "No logging" nil)
2940 (const :tag "Record timestamp" time)
2941 (const :tag "Record timestamp with note." note)))
2943 (defcustom org-log-note-clock-out nil
2944 "Non-nil means record a note when clocking out of an item.
2945 This can also be configured on a per-file basis by adding one of
2946 the following lines anywhere in the buffer:
2948 #+STARTUP: lognoteclock-out
2949 #+STARTUP: nolognoteclock-out"
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type 'boolean)
2954 (defcustom org-log-done-with-time t
2955 "Non-nil means the CLOSED time stamp will contain date and time.
2956 When nil, only the date will be recorded."
2957 :group 'org-progress
2958 :type 'boolean)
2960 (defcustom org-log-note-headings
2961 '((done . "CLOSING NOTE %t")
2962 (state . "State %-12s from %-12S %t")
2963 (note . "Note taken on %t")
2964 (reschedule . "Rescheduled from %S on %t")
2965 (delschedule . "Not scheduled, was %S on %t")
2966 (redeadline . "New deadline from %S on %t")
2967 (deldeadline . "Removed deadline, was %S on %t")
2968 (refile . "Refiled on %t")
2969 (clock-out . ""))
2970 "Headings for notes added to entries.
2972 The value is an alist, with the car being a symbol indicating the
2973 note context, and the cdr is the heading to be used. The heading
2974 may also be the empty string. The following placeholders can be
2975 used:
2977 %t a time stamp.
2978 %T an active time stamp instead the default inactive one
2979 %d a short-format time stamp.
2980 %D an active short-format time stamp.
2981 %s the new TODO state or time stamp (inactive), in double quotes.
2982 %S the old TODO state or time stamp (inactive), in double quotes.
2983 %u the user name.
2984 %U full user name.
2986 In fact, it is not a good idea to change the `state' entry,
2987 because Agenda Log mode depends on the format of these entries."
2988 :group 'org-todo
2989 :group 'org-progress
2990 :type '(list :greedy t
2991 (cons (const :tag "Heading when closing an item" done) string)
2992 (cons (const :tag
2993 "Heading when changing todo state (todo sequence only)"
2994 state) string)
2995 (cons (const :tag "Heading when just taking a note" note) string)
2996 (cons (const :tag "Heading when rescheduling" reschedule) string)
2997 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2998 (cons (const :tag "Heading when changing deadline" redeadline) string)
2999 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3000 (cons (const :tag "Heading when refiling" refile) string)
3001 (cons (const :tag "Heading when clocking out" clock-out) string)))
3003 (unless (assq 'note org-log-note-headings)
3004 (push '(note . "%t") org-log-note-headings))
3006 (defcustom org-log-into-drawer nil
3007 "Non-nil means insert state change notes and time stamps into a drawer.
3008 When nil, state changes notes will be inserted after the headline and
3009 any scheduling and clock lines, but not inside a drawer.
3011 The value of this variable should be the name of the drawer to use.
3012 LOGBOOK is proposed as the default drawer for this purpose, you can
3013 also set this to a string to define the drawer of your choice.
3015 A value of t is also allowed, representing \"LOGBOOK\".
3017 A value of t or nil can also be set with on a per-file-basis with
3019 #+STARTUP: logdrawer
3020 #+STARTUP: nologdrawer
3022 If this variable is set, `org-log-state-notes-insert-after-drawers'
3023 will be ignored.
3025 You can set the property LOG_INTO_DRAWER to overrule this setting for
3026 a subtree.
3028 Do not check directly this variable in a Lisp program. Call
3029 function `org-log-into-drawer' instead."
3030 :group 'org-todo
3031 :group 'org-progress
3032 :type '(choice
3033 (const :tag "Not into a drawer" nil)
3034 (const :tag "LOGBOOK" t)
3035 (string :tag "Other")))
3037 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3039 (defun org-log-into-drawer ()
3040 "Name of the log drawer, as a string, or nil.
3041 This is the value of `org-log-into-drawer'. However, if the
3042 current entry has or inherits a LOG_INTO_DRAWER property, it will
3043 be used instead of the default value."
3044 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3045 (cond ((equal p "nil") nil)
3046 ((equal p "t") "LOGBOOK")
3047 ((stringp p) p)
3048 (p "LOGBOOK")
3049 ((stringp org-log-into-drawer) org-log-into-drawer)
3050 (org-log-into-drawer "LOGBOOK"))))
3052 (defcustom org-log-state-notes-insert-after-drawers nil
3053 "Non-nil means insert state change notes after any drawers in entry.
3054 Only the drawers that *immediately* follow the headline and the
3055 deadline/scheduled line are skipped.
3056 When nil, insert notes right after the heading and perhaps the line
3057 with deadline/scheduling if present.
3059 This variable will have no effect if `org-log-into-drawer' is
3060 set."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-log-states-order-reversed t
3066 "Non-nil means the latest state note will be directly after heading.
3067 When nil, the state change notes will be ordered according to time.
3069 This option can also be set with on a per-file-basis with
3071 #+STARTUP: logstatesreversed
3072 #+STARTUP: nologstatesreversed"
3073 :group 'org-todo
3074 :group 'org-progress
3075 :type 'boolean)
3077 (defcustom org-todo-repeat-to-state nil
3078 "The TODO state to which a repeater should return the repeating task.
3079 By default this is the first task in a TODO sequence, or the previous state
3080 in a TODO_TYP set. But you can specify another task here.
3081 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3082 :group 'org-todo
3083 :version "24.1"
3084 :type '(choice (const :tag "Head of sequence" nil)
3085 (string :tag "Specific state")))
3087 (defcustom org-log-repeat 'time
3088 "Non-nil means record moving through the DONE state when triggering repeat.
3089 An auto-repeating task is immediately switched back to TODO when
3090 marked DONE. If you are not logging state changes (by adding \"@\"
3091 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3092 record a closing note, there will be no record of the task moving
3093 through DONE. This variable forces taking a note anyway.
3095 nil Don't force a record
3096 time Record a time stamp
3097 note Prompt for a note and add it with template `org-log-note-headings'
3099 This option can also be set with on a per-file-basis with
3101 #+STARTUP: nologrepeat
3102 #+STARTUP: logrepeat
3103 #+STARTUP: lognoterepeat
3105 You can have local logging settings for a subtree by setting the LOGGING
3106 property to one or more of these keywords."
3107 :group 'org-todo
3108 :group 'org-progress
3109 :type '(choice
3110 (const :tag "Don't force a record" nil)
3111 (const :tag "Force recording the DONE state" time)
3112 (const :tag "Force recording a note with the DONE state" note)))
3115 (defgroup org-priorities nil
3116 "Priorities in Org mode."
3117 :tag "Org Priorities"
3118 :group 'org-todo)
3120 (defcustom org-enable-priority-commands t
3121 "Non-nil means priority commands are active.
3122 When nil, these commands will be disabled, so that you never accidentally
3123 set a priority."
3124 :group 'org-priorities
3125 :type 'boolean)
3127 (defcustom org-highest-priority ?A
3128 "The highest priority of TODO items. A character like ?A, ?B etc.
3129 Must have a smaller ASCII number than `org-lowest-priority'."
3130 :group 'org-priorities
3131 :type 'character)
3133 (defcustom org-lowest-priority ?C
3134 "The lowest priority of TODO items. A character like ?A, ?B etc.
3135 Must have a larger ASCII number than `org-highest-priority'."
3136 :group 'org-priorities
3137 :type 'character)
3139 (defcustom org-default-priority ?B
3140 "The default priority of TODO items.
3141 This is the priority an item gets if no explicit priority is given.
3142 When starting to cycle on an empty priority the first step in the cycle
3143 depends on `org-priority-start-cycle-with-default'. The resulting first
3144 step priority must not exceed the range from `org-highest-priority' to
3145 `org-lowest-priority' which means that `org-default-priority' has to be
3146 in this range exclusive or inclusive the range boundaries. Else the
3147 first step refuses to set the default and the second will fall back
3148 to (depending on the command used) the highest or lowest priority."
3149 :group 'org-priorities
3150 :type 'character)
3152 (defcustom org-priority-start-cycle-with-default t
3153 "Non-nil means start with default priority when starting to cycle.
3154 When this is nil, the first step in the cycle will be (depending on the
3155 command used) one higher or lower than the default priority.
3156 See also `org-default-priority'."
3157 :group 'org-priorities
3158 :type 'boolean)
3160 (defcustom org-get-priority-function nil
3161 "Function to extract the priority from a string.
3162 The string is normally the headline. If this is nil Org computes the
3163 priority from the priority cookie like [#A] in the headline. It returns
3164 an integer, increasing by 1000 for each priority level.
3165 The user can set a different function here, which should take a string
3166 as an argument and return the numeric priority."
3167 :group 'org-priorities
3168 :version "24.1"
3169 :type '(choice
3170 (const nil)
3171 (function)))
3173 (defgroup org-time nil
3174 "Options concerning time stamps and deadlines in Org mode."
3175 :tag "Org Time"
3176 :group 'org)
3178 (defcustom org-time-stamp-rounding-minutes '(0 5)
3179 "Number of minutes to round time stamps to.
3180 \\<org-mode-map>\
3181 These are two values, the first applies when first creating a time stamp.
3182 The second applies when changing it with the commands `S-up' and `S-down'.
3183 When changing the time stamp, this means that it will change in steps
3184 of N minutes, as given by the second value.
3186 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3187 numbers should be factors of 60, so for example 5, 10, 15.
3189 When this is larger than 1, you can still force an exact time stamp by using
3190 a double prefix argument to a time stamp command like \
3191 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3192 and by using a prefix arg to `S-up/down' to specify the exact number
3193 of minutes to shift."
3194 :group 'org-time
3195 :get (lambda (var) ; Make sure both elements are there
3196 (if (integerp (default-value var))
3197 (list (default-value var) 5)
3198 (default-value var)))
3199 :type '(list
3200 (integer :tag "when inserting times")
3201 (integer :tag "when modifying times")))
3203 ;; Normalize old customizations of this variable.
3204 (when (integerp org-time-stamp-rounding-minutes)
3205 (setq org-time-stamp-rounding-minutes
3206 (list org-time-stamp-rounding-minutes
3207 org-time-stamp-rounding-minutes)))
3209 (defcustom org-display-custom-times nil
3210 "Non-nil means overlay custom formats over all time stamps.
3211 The formats are defined through the variable `org-time-stamp-custom-formats'.
3212 To turn this on on a per-file basis, insert anywhere in the file:
3213 #+STARTUP: customtime"
3214 :group 'org-time
3215 :set 'set-default
3216 :type 'sexp)
3217 (make-variable-buffer-local 'org-display-custom-times)
3219 (defcustom org-time-stamp-custom-formats
3220 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3221 "Custom formats for time stamps. See `format-time-string' for the syntax.
3222 These are overlaid over the default ISO format if the variable
3223 `org-display-custom-times' is set. Time like %H:%M should be at the
3224 end of the second format. The custom formats are also honored by export
3225 commands, if custom time display is turned on at the time of export."
3226 :group 'org-time
3227 :type 'sexp)
3229 (defun org-time-stamp-format (&optional long inactive)
3230 "Get the right format for a time string."
3231 (let ((f (if long (cdr org-time-stamp-formats)
3232 (car org-time-stamp-formats))))
3233 (if inactive
3234 (concat "[" (substring f 1 -1) "]")
3235 f)))
3237 (defcustom org-deadline-warning-days 14
3238 "Number of days before expiration during which a deadline becomes active.
3239 This variable governs the display in sparse trees and in the agenda.
3240 When 0 or negative, it means use this number (the absolute value of it)
3241 even if a deadline has a different individual lead time specified.
3243 Custom commands can set this variable in the options section."
3244 :group 'org-time
3245 :group 'org-agenda-daily/weekly
3246 :type 'integer)
3248 (defcustom org-scheduled-delay-days 0
3249 "Number of days before a scheduled item becomes active.
3250 This variable governs the display in sparse trees and in the agenda.
3251 The default value (i.e. 0) means: don't delay scheduled item.
3252 When negative, it means use this number (the absolute value of it)
3253 even if a scheduled item has a different individual delay time
3254 specified.
3256 Custom commands can set this variable in the options section."
3257 :group 'org-time
3258 :group 'org-agenda-daily/weekly
3259 :version "24.4"
3260 :package-version '(Org . "8.0")
3261 :type 'integer)
3263 (defcustom org-read-date-prefer-future t
3264 "Non-nil means assume future for incomplete date input from user.
3265 This affects the following situations:
3266 1. The user gives a month but not a year.
3267 For example, if it is April and you enter \"feb 2\", this will be read
3268 as Feb 2, *next* year. \"May 5\", however, will be this year.
3269 2. The user gives a day, but no month.
3270 For example, if today is the 15th, and you enter \"3\", Org will read
3271 this as the third of *next* month. However, if you enter \"17\",
3272 it will be considered as *this* month.
3274 If you set this variable to the symbol `time', then also the following
3275 will work:
3277 3. If the user gives a time.
3278 If the time is before now, it will be interpreted as tomorrow.
3280 Currently none of this works for ISO week specifications.
3282 When this option is nil, the current day, month and year will always be
3283 used as defaults.
3285 See also `org-agenda-jump-prefer-future'."
3286 :group 'org-time
3287 :type '(choice
3288 (const :tag "Never" nil)
3289 (const :tag "Check month and day" t)
3290 (const :tag "Check month, day, and time" time)))
3292 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3293 "Should the agenda jump command prefer the future for incomplete dates?
3294 The default is to do the same as configured in `org-read-date-prefer-future'.
3295 But you can also set a deviating value here.
3296 This may t or nil, or the symbol `org-read-date-prefer-future'."
3297 :group 'org-agenda
3298 :group 'org-time
3299 :version "24.1"
3300 :type '(choice
3301 (const :tag "Use org-read-date-prefer-future"
3302 org-read-date-prefer-future)
3303 (const :tag "Never" nil)
3304 (const :tag "Always" t)))
3306 (defcustom org-read-date-force-compatible-dates t
3307 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3309 Depending on the system Emacs is running on, certain dates cannot
3310 be represented with the type used internally to represent time.
3311 Dates between 1970-1-1 and 2038-1-1 can always be represented
3312 correctly. Some systems allow for earlier dates, some for later,
3313 some for both. One way to find out it to insert any date into an
3314 Org buffer, putting the cursor on the year and hitting S-up and
3315 S-down to test the range.
3317 When this variable is set to t, the date/time prompt will not let
3318 you specify dates outside the 1970-2037 range, so it is certain that
3319 these dates will work in whatever version of Emacs you are
3320 running, and also that you can move a file from one Emacs implementation
3321 to another. WHenever Org is forcing the year for you, it will display
3322 a message and beep.
3324 When this variable is nil, Org will check if the date is
3325 representable in the specific Emacs implementation you are using.
3326 If not, it will force a year, usually the current year, and beep
3327 to remind you. Currently this setting is not recommended because
3328 the likelihood that you will open your Org files in an Emacs that
3329 has limited date range is not negligible.
3331 A workaround for this problem is to use diary sexp dates for time
3332 stamps outside of this range."
3333 :group 'org-time
3334 :version "24.1"
3335 :type 'boolean)
3337 (defcustom org-read-date-display-live t
3338 "Non-nil means display current interpretation of date prompt live.
3339 This display will be in an overlay, in the minibuffer."
3340 :group 'org-time
3341 :type 'boolean)
3343 (defcustom org-read-date-popup-calendar t
3344 "Non-nil means pop up a calendar when prompting for a date.
3345 In the calendar, the date can be selected with mouse-1. However, the
3346 minibuffer will also be active, and you can simply enter the date as well.
3347 When nil, only the minibuffer will be available."
3348 :group 'org-time
3349 :type 'boolean)
3350 (defvaralias 'org-popup-calendar-for-date-prompt
3351 'org-read-date-popup-calendar)
3353 (defcustom org-extend-today-until 0
3354 "The hour when your day really ends. Must be an integer.
3355 This has influence for the following applications:
3356 - When switching the agenda to \"today\". It it is still earlier than
3357 the time given here, the day recognized as TODAY is actually yesterday.
3358 - When a date is read from the user and it is still before the time given
3359 here, the current date and time will be assumed to be yesterday, 23:59.
3360 Also, timestamps inserted in capture templates follow this rule.
3362 IMPORTANT: This is a feature whose implementation is and likely will
3363 remain incomplete. Really, it is only here because past midnight seems to
3364 be the favorite working time of John Wiegley :-)"
3365 :group 'org-time
3366 :type 'integer)
3368 (defcustom org-use-effective-time nil
3369 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3370 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3371 \"effective time\" of any timestamps between midnight and 8am will be
3372 23:59 of the previous day."
3373 :group 'org-time
3374 :version "24.1"
3375 :type 'boolean)
3377 (defcustom org-use-last-clock-out-time-as-effective-time nil
3378 "When non-nil, use the last clock out time for `org-todo'.
3379 Note that this option has precedence over the combined use of
3380 `org-use-effective-time' and `org-extend-today-until'."
3381 :group 'org-time
3382 :version "24.4"
3383 :package-version '(Org . "8.0")
3384 :type 'boolean)
3386 (defcustom org-edit-timestamp-down-means-later nil
3387 "Non-nil means S-down will increase the time in a time stamp.
3388 When nil, S-up will increase."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defcustom org-calendar-follow-timestamp-change t
3393 "Non-nil means make the calendar window follow timestamp changes.
3394 When a timestamp is modified and the calendar window is visible, it will be
3395 moved to the new date."
3396 :group 'org-time
3397 :type 'boolean)
3399 (defgroup org-tags nil
3400 "Options concerning tags in Org mode."
3401 :tag "Org Tags"
3402 :group 'org)
3404 (defcustom org-tag-alist nil
3405 "Default tags available in Org files.
3407 The value of this variable is an alist. Associations either:
3409 (TAG)
3410 (TAG . SELECT)
3411 (SPECIAL)
3413 where TAG is a tag as a string, SELECT is character, used to
3414 select that tag through the fast tag selection interface, and
3415 SPECIAL is one of the following keywords: `:startgroup',
3416 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3417 `:newline'. These keywords are used to define a hierarchy of
3418 tags. See manual for details.
3420 When this variable is nil, Org mode bases tag input on what is
3421 already in the buffer. The value can be overridden locally by
3422 using a TAGS keyword, e.g.,
3424 #+TAGS: tag1 tag2
3426 See also `org-tag-persistent-alist' to sidestep this behavior."
3427 :group 'org-tags
3428 :type '(repeat
3429 (choice
3430 (cons :tag "Tag with key"
3431 (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (list :tag "Tag" (string :tag "Tag name"))
3434 (const :tag "Start radio group" (:startgroup))
3435 (const :tag "Start tag group, non distinct" (:startgrouptag))
3436 (const :tag "Group tags delimiter" (:grouptags))
3437 (const :tag "End radio group" (:endgroup))
3438 (const :tag "End tag group, non distinct" (:endgrouptag))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-tag-persistent-alist nil
3442 "Tags always available in Org files.
3444 The value of this variable is an alist. Associations either:
3446 (TAG)
3447 (TAG . SELECT)
3448 (SPECIAL)
3450 where TAG is a tag as a string, SELECT is a character, used to
3451 select that tag through the fast tag selection interface, and
3452 SPECIAL is one of the following keywords: `:startgroup',
3453 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3454 `:newline'. These keywords are used to define a hierarchy of
3455 tags. See manual for details.
3457 Unlike to `org-tag-alist', tags defined in this variable do not
3458 depend on a local TAGS keyword. Instead, to disable these tags
3459 on a per-file basis, insert anywhere in the file:
3461 #+STARTUP: noptag"
3462 :group 'org-tags
3463 :type '(repeat
3464 (choice
3465 (cons :tag "Tag with key"
3466 (string :tag "Tag name")
3467 (character :tag "Access char"))
3468 (list :tag "Tag" (string :tag "Tag name"))
3469 (const :tag "Start radio group" (:startgroup))
3470 (const :tag "Start tag group, non distinct" (:startgrouptag))
3471 (const :tag "Group tags delimiter" (:grouptags))
3472 (const :tag "End radio group" (:endgroup))
3473 (const :tag "End tag group, non distinct" (:endgrouptag))
3474 (const :tag "New line" (:newline)))))
3476 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3477 "If non-nil, always offer completion for all tags of all agenda files.
3478 Instead of customizing this variable directly, you might want to
3479 set it locally for capture buffers, because there no list of
3480 tags in that file can be created dynamically (there are none).
3482 (add-hook \\='org-capture-mode-hook
3483 (lambda ()
3484 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3485 :group 'org-tags
3486 :version "24.1"
3487 :type 'boolean)
3489 (defvar org-file-tags nil
3490 "List of tags that can be inherited by all entries in the file.
3491 The tags will be inherited if the variable `org-use-tag-inheritance'
3492 says they should be.
3493 This variable is populated from #+FILETAGS lines.")
3495 (defcustom org-use-fast-tag-selection 'auto
3496 "Non-nil means use fast tag selection scheme.
3497 This is a special interface to select and deselect tags with single keys.
3498 When nil, fast selection is never used.
3499 When the symbol `auto', fast selection is used if and only if selection
3500 characters for tags have been configured, either through the variable
3501 `org-tag-alist' or through a #+TAGS line in the buffer.
3502 When t, fast selection is always used and selection keys are assigned
3503 automatically if necessary."
3504 :group 'org-tags
3505 :type '(choice
3506 (const :tag "Always" t)
3507 (const :tag "Never" nil)
3508 (const :tag "When selection characters are configured" auto)))
3510 (defcustom org-fast-tag-selection-single-key nil
3511 "Non-nil means fast tag selection exits after first change.
3512 When nil, you have to press RET to exit it.
3513 During fast tag selection, you can toggle this flag with `C-c'.
3514 This variable can also have the value `expert'. In this case, the window
3515 displaying the tags menu is not even shown, until you press C-c again."
3516 :group 'org-tags
3517 :type '(choice
3518 (const :tag "No" nil)
3519 (const :tag "Yes" t)
3520 (const :tag "Expert" expert)))
3522 (defvar org-fast-tag-selection-include-todo nil
3523 "Non-nil means fast tags selection interface will also offer TODO states.
3524 This is an undocumented feature, you should not rely on it.")
3526 (defcustom org-tags-column -77
3527 "The column to which tags should be indented in a headline.
3528 If this number is positive, it specifies the column. If it is negative,
3529 it means that the tags should be flushright to that column. For example,
3530 -80 works well for a normal 80 character screen.
3531 When 0, place tags directly after headline text, with only one space in
3532 between."
3533 :group 'org-tags
3534 :type 'integer)
3536 (defcustom org-auto-align-tags t
3537 "Non-nil keeps tags aligned when modifying headlines.
3538 Some operations (i.e. demoting) change the length of a headline and
3539 therefore shift the tags around. With this option turned on, after
3540 each such operation the tags are again aligned to `org-tags-column'."
3541 :group 'org-tags
3542 :type 'boolean)
3544 (defcustom org-use-tag-inheritance t
3545 "Non-nil means tags in levels apply also for sublevels.
3546 When nil, only the tags directly given in a specific line apply there.
3547 This may also be a list of tags that should be inherited, or a regexp that
3548 matches tags that should be inherited. Additional control is possible
3549 with the variable `org-tags-exclude-from-inheritance' which gives an
3550 explicit list of tags to be excluded from inheritance, even if the value of
3551 `org-use-tag-inheritance' would select it for inheritance.
3553 If this option is t, a match early-on in a tree can lead to a large
3554 number of matches in the subtree when constructing the agenda or creating
3555 a sparse tree. If you only want to see the first match in a tree during
3556 a search, check out the variable `org-tags-match-list-sublevels'."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "Not" nil)
3560 (const :tag "Always" t)
3561 (repeat :tag "Specific tags" (string :tag "Tag"))
3562 (regexp :tag "Tags matched by regexp")))
3564 (defcustom org-tags-exclude-from-inheritance nil
3565 "List of tags that should never be inherited.
3566 This is a way to exclude a few tags from inheritance. For way to do
3567 the opposite, to actively allow inheritance for selected tags,
3568 see the variable `org-use-tag-inheritance'."
3569 :group 'org-tags
3570 :type '(repeat (string :tag "Tag")))
3572 (defun org-tag-inherit-p (tag)
3573 "Check if TAG is one that should be inherited."
3574 (cond
3575 ((member tag org-tags-exclude-from-inheritance) nil)
3576 ((eq org-use-tag-inheritance t) t)
3577 ((not org-use-tag-inheritance) nil)
3578 ((stringp org-use-tag-inheritance)
3579 (string-match org-use-tag-inheritance tag))
3580 ((listp org-use-tag-inheritance)
3581 (member tag org-use-tag-inheritance))
3582 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3584 (defcustom org-tags-match-list-sublevels t
3585 "Non-nil means list also sublevels of headlines matching a search.
3586 This variable applies to tags/property searches, and also to stuck
3587 projects because this search is based on a tags match as well.
3589 When set to the symbol `indented', sublevels are indented with
3590 leading dots.
3592 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3593 the sublevels of a headline matching a tag search often also match
3594 the same search. Listing all of them can create very long lists.
3595 Setting this variable to nil causes subtrees of a match to be skipped.
3597 This variable is semi-obsolete and probably should always be true. It
3598 is better to limit inheritance to certain tags using the variables
3599 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3600 :group 'org-tags
3601 :type '(choice
3602 (const :tag "No, don't list them" nil)
3603 (const :tag "Yes, do list them" t)
3604 (const :tag "List them, indented with leading dots" indented)))
3606 (defcustom org-tags-sort-function nil
3607 "When set, tags are sorted using this function as a comparator."
3608 :group 'org-tags
3609 :type '(choice
3610 (const :tag "No sorting" nil)
3611 (const :tag "Alphabetical" string<)
3612 (const :tag "Reverse alphabetical" string>)
3613 (function :tag "Custom function" nil)))
3615 (defvar org-tags-history nil
3616 "History of minibuffer reads for tags.")
3617 (defvar org-last-tags-completion-table nil
3618 "The last used completion table for tags.")
3619 (defvar org-after-tags-change-hook nil
3620 "Hook that is run after the tags in a line have changed.")
3622 (defgroup org-properties nil
3623 "Options concerning properties in Org mode."
3624 :tag "Org Properties"
3625 :group 'org)
3627 (defcustom org-property-format "%-10s %s"
3628 "How property key/value pairs should be formatted by `indent-line'.
3629 When `indent-line' hits a property definition, it will format the line
3630 according to this format, mainly to make sure that the values are
3631 lined-up with respect to each other."
3632 :group 'org-properties
3633 :type 'string)
3635 (defcustom org-properties-postprocess-alist nil
3636 "Alist of properties and functions to adjust inserted values.
3637 Elements of this alist must be of the form
3639 ([string] [function])
3641 where [string] must be a property name and [function] must be a
3642 lambda expression: this lambda expression must take one argument,
3643 the value to adjust, and return the new value as a string.
3645 For example, this element will allow the property \"Remaining\"
3646 to be updated wrt the relation between the \"Effort\" property
3647 and the clock summary:
3649 ((\"Remaining\" (lambda(value)
3650 (let ((clocksum (org-clock-sum-current-item))
3651 (effort (org-duration-to-minutes
3652 (org-entry-get (point) \"Effort\"))))
3653 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3654 :group 'org-properties
3655 :version "24.1"
3656 :type '(alist :key-type (string :tag "Property")
3657 :value-type (function :tag "Function")))
3659 (defcustom org-use-property-inheritance nil
3660 "Non-nil means properties apply also for sublevels.
3662 This setting is chiefly used during property searches. Turning it on can
3663 cause significant overhead when doing a search, which is why it is not
3664 on by default.
3666 When nil, only the properties directly given in the current entry count.
3667 When t, every property is inherited. The value may also be a list of
3668 properties that should have inheritance, or a regular expression matching
3669 properties that should be inherited.
3671 However, note that some special properties use inheritance under special
3672 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3673 and the properties ending in \"_ALL\" when they are used as descriptor
3674 for valid values of a property.
3676 Note for programmers:
3677 When querying an entry with `org-entry-get', you can control if inheritance
3678 should be used. By default, `org-entry-get' looks only at the local
3679 properties. You can request inheritance by setting the inherit argument
3680 to t (to force inheritance) or to `selective' (to respect the setting
3681 in this variable)."
3682 :group 'org-properties
3683 :type '(choice
3684 (const :tag "Not" nil)
3685 (const :tag "Always" t)
3686 (repeat :tag "Specific properties" (string :tag "Property"))
3687 (regexp :tag "Properties matched by regexp")))
3689 (defun org-property-inherit-p (property)
3690 "Return a non-nil value if PROPERTY should be inherited."
3691 (cond
3692 ((eq org-use-property-inheritance t) t)
3693 ((not org-use-property-inheritance) nil)
3694 ((stringp org-use-property-inheritance)
3695 (string-match org-use-property-inheritance property))
3696 ((listp org-use-property-inheritance)
3697 (member-ignore-case property org-use-property-inheritance))
3698 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3700 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3701 "The default column format, if no other format has been defined.
3702 This variable can be set on the per-file basis by inserting a line
3704 #+COLUMNS: %25ITEM ....."
3705 :group 'org-properties
3706 :type 'string)
3708 (defcustom org-columns-ellipses ".."
3709 "The ellipses to be used when a field in column view is truncated.
3710 When this is the empty string, as many characters as possible are shown,
3711 but then there will be no visual indication that the field has been truncated.
3712 When this is a string of length N, the last N characters of a truncated
3713 field are replaced by this string. If the column is narrower than the
3714 ellipses string, only part of the ellipses string will be shown."
3715 :group 'org-properties
3716 :type 'string)
3718 (defconst org-global-properties-fixed
3719 '(("VISIBILITY_ALL" . "folded children content all")
3720 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3721 "List of property/value pairs that can be inherited by any entry.
3723 These are fixed values, for the preset properties. The user variable
3724 that can be used to add to this list is `org-global-properties'.
3726 The entries in this list are cons cells where the car is a property
3727 name and cdr is a string with the value. If the value represents
3728 multiple items like an \"_ALL\" property, separate the items by
3729 spaces.")
3731 (defcustom org-global-properties nil
3732 "List of property/value pairs that can be inherited by any entry.
3734 This list will be combined with the constant `org-global-properties-fixed'.
3736 The entries in this list are cons cells where the car is a property
3737 name and cdr is a string with the value.
3739 You can set buffer-local values for the same purpose in the variable
3740 `org-file-properties' this by adding lines like
3742 #+PROPERTY: NAME VALUE"
3743 :group 'org-properties
3744 :type '(repeat
3745 (cons (string :tag "Property")
3746 (string :tag "Value"))))
3748 (defvar-local org-file-properties nil
3749 "List of property/value pairs that can be inherited by any entry.
3750 Valid for the current buffer.
3751 This variable is populated from #+PROPERTY lines.")
3753 (defgroup org-agenda nil
3754 "Options concerning agenda views in Org mode."
3755 :tag "Org Agenda"
3756 :group 'org)
3758 (defvar-local org-category nil
3759 "Variable used by org files to set a category for agenda display.
3760 Such files should use a file variable to set it, for example
3762 # -*- mode: org; org-category: \"ELisp\"
3764 or contain a special line
3766 #+CATEGORY: ELisp
3768 If the file does not specify a category, then file's base name
3769 is used instead.")
3770 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3772 (defcustom org-agenda-files nil
3773 "The files to be used for agenda display.
3775 If an entry is a directory, all files in that directory that are matched
3776 by `org-agenda-file-regexp' will be part of the file list.
3778 If the value of the variable is not a list but a single file name, then
3779 the list of agenda files is actually stored and maintained in that file,
3780 one agenda file per line. In this file paths can be given relative to
3781 `org-directory'. Tilde expansion and environment variable substitution
3782 are also made.
3784 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3785 and removed with `\\[org-remove-file]'."
3786 :group 'org-agenda
3787 :type '(choice
3788 (repeat :tag "List of files and directories" file)
3789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3792 "Regular expression to match files for `org-agenda-files'.
3793 If any element in the list in that variable contains a directory instead
3794 of a normal file, all files in that directory that are matched by this
3795 regular expression will be included."
3796 :group 'org-agenda
3797 :type 'regexp)
3799 (defcustom org-agenda-text-search-extra-files nil
3800 "List of extra files to be searched by text search commands.
3801 These files will be searched in addition to the agenda files by the
3802 commands `org-search-view' (`\\[org-agenda] s') \
3803 and `org-occur-in-agenda-files'.
3804 Note that these files will only be searched for text search commands,
3805 not for the other agenda views like todo lists, tag searches or the weekly
3806 agenda. This variable is intended to list notes and possibly archive files
3807 that should also be searched by these two commands.
3808 In fact, if the first element in the list is the symbol `agenda-archives',
3809 then all archive files of all agenda files will be added to the search
3810 scope."
3811 :group 'org-agenda
3812 :type '(set :greedy t
3813 (const :tag "Agenda Archives" agenda-archives)
3814 (repeat :inline t (file))))
3816 (defvaralias 'org-agenda-multi-occur-extra-files
3817 'org-agenda-text-search-extra-files)
3819 (defcustom org-agenda-skip-unavailable-files nil
3820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3821 A nil value means to remove them, after a query, from the list."
3822 :group 'org-agenda
3823 :type 'boolean)
3825 (defcustom org-calendar-to-agenda-key [?c]
3826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3827 The command `org-calendar-goto-agenda' will be bound to this key. The
3828 default is the character `c' because then `c' can be used to switch back and
3829 forth between agenda and calendar."
3830 :group 'org-agenda
3831 :type 'sexp)
3833 (defcustom org-calendar-insert-diary-entry-key [?i]
3834 "The key to be installed in `calendar-mode-map' for adding diary entries.
3835 This option is irrelevant until `org-agenda-diary-file' has been configured
3836 to point to an Org file. When that is the case, the command
3837 `org-agenda-diary-entry' will be bound to the key given here, by default
3838 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3839 if you want to continue doing this, you need to change this to a different
3840 key."
3841 :group 'org-agenda
3842 :type 'sexp)
3844 (defcustom org-agenda-diary-file 'diary-file
3845 "File to which to add new entries with the `i' key in agenda and calendar.
3846 When this is the symbol `diary-file', the functionality in the Emacs
3847 calendar will be used to add entries to the `diary-file'. But when this
3848 points to a file, `org-agenda-diary-entry' will be used instead."
3849 :group 'org-agenda
3850 :type '(choice
3851 (const :tag "The standard Emacs diary file" diary-file)
3852 (file :tag "Special Org file diary entries")))
3854 (eval-after-load "calendar"
3855 '(progn
3856 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3857 'org-calendar-goto-agenda)
3858 (add-hook 'calendar-mode-hook
3859 (lambda ()
3860 (unless (eq org-agenda-diary-file 'diary-file)
3861 (define-key calendar-mode-map
3862 org-calendar-insert-diary-entry-key
3863 'org-agenda-diary-entry))))))
3865 (defgroup org-latex nil
3866 "Options for embedding LaTeX code into Org mode."
3867 :tag "Org LaTeX"
3868 :group 'org)
3870 (defcustom org-format-latex-options
3871 '(:foreground default :background default :scale 1.0
3872 :html-foreground "Black" :html-background "Transparent"
3873 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3874 "Options for creating images from LaTeX fragments.
3875 This is a property list with the following properties:
3876 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3877 `default' means use the foreground of the default face.
3878 `auto' means use the foreground from the text face.
3879 :background the background color, or \"Transparent\".
3880 `default' means use the background of the default face.
3881 `auto' means use the background from the text face.
3882 :scale a scaling factor for the size of the images, to get more pixels
3883 :html-foreground, :html-background, :html-scale
3884 the same numbers for HTML export.
3885 :matchers a list indicating which matchers should be used to
3886 find LaTeX fragments. Valid members of this list are:
3887 \"begin\" find environments
3888 \"$1\" find single characters surrounded by $.$
3889 \"$\" find math expressions surrounded by $...$
3890 \"$$\" find math expressions surrounded by $$....$$
3891 \"\\(\" find math expressions surrounded by \\(...\\)
3892 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3893 :group 'org-latex
3894 :type 'plist)
3896 (defcustom org-format-latex-signal-error t
3897 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3898 When nil, just push out a message."
3899 :group 'org-latex
3900 :version "24.1"
3901 :type 'boolean)
3903 (defcustom org-latex-to-mathml-jar-file nil
3904 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3905 Use this to specify additional executable file say a jar file.
3907 When using MathToWeb as the converter, specify the full-path to
3908 your mathtoweb.jar file."
3909 :group 'org-latex
3910 :version "24.1"
3911 :type '(choice
3912 (const :tag "None" nil)
3913 (file :tag "JAR file" :must-match t)))
3915 (defcustom org-latex-to-mathml-convert-command nil
3916 "Command to convert LaTeX fragments to MathML.
3917 Replace format-specifiers in the command as noted below and use
3918 `shell-command' to convert LaTeX to MathML.
3919 %j: Executable file in fully expanded form as specified by
3920 `org-latex-to-mathml-jar-file'.
3921 %I: Input LaTeX file in fully expanded form.
3922 %i: The latex fragment to be converted.
3923 %o: Output MathML file.
3925 This command is used by `org-create-math-formula'.
3927 When using MathToWeb as the converter, set this option to
3928 \"java -jar %j -unicode -force -df %o %I\".
3930 When using LaTeXML set this option to
3931 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3932 :group 'org-latex
3933 :version "24.1"
3934 :type '(choice
3935 (const :tag "None" nil)
3936 (string :tag "\nShell command")))
3938 (defcustom org-preview-latex-default-process 'dvipng
3939 "The default process to convert LaTeX fragments to image files.
3940 All available processes and theirs documents can be found in
3941 `org-preview-latex-process-alist', which see."
3942 :group 'org-latex
3943 :version "26.1"
3944 :package-version '(Org . "9.0")
3945 :type 'symbol)
3947 (defcustom org-preview-latex-process-alist
3948 '((dvipng
3949 :programs ("latex" "dvipng")
3950 :description "dvi > png"
3951 :message "you need to install the programs: latex and dvipng."
3952 :image-input-type "dvi"
3953 :image-output-type "png"
3954 :image-size-adjust (1.0 . 1.0)
3955 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3956 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3957 (dvisvgm
3958 :programs ("latex" "dvisvgm")
3959 :description "dvi > svg"
3960 :message "you need to install the programs: latex and dvisvgm."
3961 :use-xcolor t
3962 :image-input-type "dvi"
3963 :image-output-type "svg"
3964 :image-size-adjust (1.7 . 1.5)
3965 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3966 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3967 (imagemagick
3968 :programs ("latex" "convert")
3969 :description "pdf > png"
3970 :message "you need to install the programs: latex and imagemagick."
3971 :use-xcolor t
3972 :image-input-type "pdf"
3973 :image-output-type "png"
3974 :image-size-adjust (1.0 . 1.0)
3975 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3976 :image-converter
3977 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3978 "Definitions of external processes for LaTeX previewing.
3979 Org mode can use some external commands to generate TeX snippet's images for
3980 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3981 `org-create-formula-image' how to call them.
3983 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3984 PROPERTIES accepts the following attributes:
3986 :programs list of strings, required programs.
3987 :description string, describe the process.
3988 :message string, message it when required programs cannot be found.
3989 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3990 :image-output-type string, output file type of image converter (e.g., \"png\").
3991 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3992 deal with background and foreground color of image.
3993 Otherwise, dvipng style background and foreground color
3994 format are generated. You may then refer to them in
3995 command options with \"%F\" and \"%B\".
3996 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3997 image size showed in buffer and the cdr element is for
3998 HTML file. This option is only useful for process
3999 developers, users should use variable
4000 `org-format-latex-options' instead.
4001 :post-clean list of strings, files matched are to be cleaned up once
4002 the image is generated. When nil, the files with \".dvi\",
4003 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4004 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4005 be cleaned up.
4006 :latex-header list of strings, the LaTeX header of the snippet file.
4007 When nil, the fallback value is used instead, which is
4008 controlled by `org-format-latex-header',
4009 `org-latex-default-packages-alist' and
4010 `org-latex-packages-alist', which see.
4011 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4012 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4013 replaced with values defined below.
4014 :image-converter list of image converter commands strings. Each of them is
4015 given to the shell and supports any of the following
4016 place-holders defined below.
4018 Place-holders used by `:image-converter' and `:latex-compiler':
4020 %f input file name
4021 %b base name of input file
4022 %o base directory of input file
4023 %O absolute output file name
4025 Place-holders only used by `:image-converter':
4027 %F foreground of image
4028 %B background of image
4029 %D dpi, which is used to adjust image size by some processing commands.
4030 %S the image size scale ratio, which is used to adjust image size by some
4031 processing commands."
4032 :group 'org-latex
4033 :version "26.1"
4034 :package-version '(Org . "9.0")
4035 :type '(alist :tag "LaTeX to image backends"
4036 :value-type (plist)))
4038 (defcustom org-preview-latex-image-directory "ltximg/"
4039 "Path to store latex preview images.
4040 A relative path here creates many directories relative to the
4041 processed org files paths. An absolute path puts all preview
4042 images at the same place."
4043 :group 'org-latex
4044 :version "26.1"
4045 :package-version '(Org . "9.0")
4046 :type 'string)
4048 (defun org-format-latex-mathml-available-p ()
4049 "Return t if `org-latex-to-mathml-convert-command' is usable."
4050 (save-match-data
4051 (when (and (boundp 'org-latex-to-mathml-convert-command)
4052 org-latex-to-mathml-convert-command)
4053 (let ((executable (car (split-string
4054 org-latex-to-mathml-convert-command))))
4055 (when (executable-find executable)
4056 (if (string-match
4057 "%j" org-latex-to-mathml-convert-command)
4058 (file-readable-p org-latex-to-mathml-jar-file)
4059 t))))))
4061 (defcustom org-format-latex-header "\\documentclass{article}
4062 \\usepackage[usenames]{color}
4063 \[PACKAGES]
4064 \[DEFAULT-PACKAGES]
4065 \\pagestyle{empty} % do not remove
4066 % The settings below are copied from fullpage.sty
4067 \\setlength{\\textwidth}{\\paperwidth}
4068 \\addtolength{\\textwidth}{-3cm}
4069 \\setlength{\\oddsidemargin}{1.5cm}
4070 \\addtolength{\\oddsidemargin}{-2.54cm}
4071 \\setlength{\\evensidemargin}{\\oddsidemargin}
4072 \\setlength{\\textheight}{\\paperheight}
4073 \\addtolength{\\textheight}{-\\headheight}
4074 \\addtolength{\\textheight}{-\\headsep}
4075 \\addtolength{\\textheight}{-\\footskip}
4076 \\addtolength{\\textheight}{-3cm}
4077 \\setlength{\\topmargin}{1.5cm}
4078 \\addtolength{\\topmargin}{-2.54cm}"
4079 "The document header used for processing LaTeX fragments.
4080 It is imperative that this header make sure that no page number
4081 appears on the page. The package defined in the variables
4082 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4083 will either replace the placeholder \"[PACKAGES]\" in this
4084 header, or they will be appended."
4085 :group 'org-latex
4086 :type 'string)
4088 (defun org-set-packages-alist (var val)
4089 "Set the packages alist and make sure it has 3 elements per entry."
4090 (set var (mapcar (lambda (x)
4091 (if (and (consp x) (= (length x) 2))
4092 (list (car x) (nth 1 x) t)
4094 val)))
4096 (defun org-get-packages-alist (var)
4097 "Get the packages alist and make sure it has 3 elements per entry."
4098 (mapcar (lambda (x)
4099 (if (and (consp x) (= (length x) 2))
4100 (list (car x) (nth 1 x) t)
4102 (default-value var)))
4104 (defcustom org-latex-default-packages-alist
4105 '(("AUTO" "inputenc" t ("pdflatex"))
4106 ("T1" "fontenc" t ("pdflatex"))
4107 ("" "graphicx" t)
4108 ("" "grffile" t)
4109 ("" "longtable" nil)
4110 ("" "wrapfig" nil)
4111 ("" "rotating" nil)
4112 ("normalem" "ulem" t)
4113 ("" "amsmath" t)
4114 ("" "textcomp" t)
4115 ("" "amssymb" t)
4116 ("" "capt-of" nil)
4117 ("" "hyperref" nil))
4118 "Alist of default packages to be inserted in the header.
4120 Change this only if one of the packages here causes an
4121 incompatibility with another package you are using.
4123 The packages in this list are needed by one part or another of
4124 Org mode to function properly:
4126 - inputenc, fontenc: for basic font and character selection
4127 - graphicx: for including images
4128 - grffile: allow periods and spaces in graphics file names
4129 - longtable: For multipage tables
4130 - wrapfig: for figure placement
4131 - rotating: for sideways figures and tables
4132 - ulem: for underline and strike-through
4133 - amsmath: for subscript and superscript and math environments
4134 - textcomp, amssymb: for various symbols used
4135 for interpreting the entities in `org-entities'. You can skip
4136 some of these packages if you don't use any of their symbols.
4137 - capt-of: for captions outside of floats
4138 - hyperref: for cross references
4140 Therefore you should not modify this variable unless you know
4141 what you are doing. The one reason to change it anyway is that
4142 you might be loading some other package that conflicts with one
4143 of the default packages. Each element is either a cell or
4144 a string.
4146 A cell is of the format
4148 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4150 If SNIPPET-FLAG is non-nil, the package also needs to be included
4151 when compiling LaTeX snippets into images for inclusion into
4152 non-LaTeX output. COMPILERS is a list of compilers that should
4153 include the package, see `org-latex-compiler'. If the document
4154 compiler is not in the list, and the list is non-nil, the package
4155 will not be inserted in the final document.
4157 A string will be inserted as-is in the header of the document."
4158 :group 'org-latex
4159 :group 'org-export-latex
4160 :set 'org-set-packages-alist
4161 :get 'org-get-packages-alist
4162 :version "26.1"
4163 :package-version '(Org . "8.3")
4164 :type '(repeat
4165 (choice
4166 (list :tag "options/package pair"
4167 (string :tag "options")
4168 (string :tag "package")
4169 (boolean :tag "Snippet"))
4170 (string :tag "A line of LaTeX"))))
4172 (defcustom org-latex-packages-alist nil
4173 "Alist of packages to be inserted in every LaTeX header.
4175 These will be inserted after `org-latex-default-packages-alist'.
4176 Each element is either a cell or a string.
4178 A cell is of the format:
4180 (\"options\" \"package\" SNIPPET-FLAG)
4182 SNIPPET-FLAG, when non-nil, indicates that this package is also
4183 needed when turning LaTeX snippets into images for inclusion into
4184 non-LaTeX output.
4186 A string will be inserted as-is in the header of the document.
4188 Make sure that you only list packages here which:
4190 - you want in every file;
4191 - do not conflict with the setup in `org-format-latex-header';
4192 - do not conflict with the default packages in
4193 `org-latex-default-packages-alist'."
4194 :group 'org-latex
4195 :group 'org-export-latex
4196 :set 'org-set-packages-alist
4197 :get 'org-get-packages-alist
4198 :type '(repeat
4199 (choice
4200 (list :tag "options/package pair"
4201 (string :tag "options")
4202 (string :tag "package")
4203 (boolean :tag "Snippet"))
4204 (string :tag "A line of LaTeX"))))
4206 (defgroup org-appearance nil
4207 "Settings for Org mode appearance."
4208 :tag "Org Appearance"
4209 :group 'org)
4211 (defcustom org-level-color-stars-only nil
4212 "Non-nil means fontify only the stars in each headline.
4213 When nil, the entire headline is fontified.
4214 Changing it requires restart of `font-lock-mode' to become effective
4215 also in regions already fontified."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-hide-leading-stars nil
4220 "Non-nil means hide the first N-1 stars in a headline.
4221 This works by using the face `org-hide' for these stars. This
4222 face is white for a light background, and black for a dark
4223 background. You may have to customize the face `org-hide' to
4224 make this work.
4225 Changing it requires restart of `font-lock-mode' to become effective
4226 also in regions already fontified.
4227 You may also set this on a per-file basis by adding one of the following
4228 lines to the buffer:
4230 #+STARTUP: hidestars
4231 #+STARTUP: showstars"
4232 :group 'org-appearance
4233 :type 'boolean)
4235 (defcustom org-hidden-keywords nil
4236 "List of symbols corresponding to keywords to be hidden the org buffer.
4237 For example, a value \\='(title) for this list will make the document's title
4238 appear in the buffer without the initial #+TITLE: keyword."
4239 :group 'org-appearance
4240 :version "24.1"
4241 :type '(set (const :tag "#+AUTHOR" author)
4242 (const :tag "#+DATE" date)
4243 (const :tag "#+EMAIL" email)
4244 (const :tag "#+TITLE" title)))
4246 (defcustom org-custom-properties nil
4247 "List of properties (as strings) with a special meaning.
4248 The default use of these custom properties is to let the user
4249 hide them with `org-toggle-custom-properties-visibility'."
4250 :group 'org-properties
4251 :group 'org-appearance
4252 :version "24.3"
4253 :type '(repeat (string :tag "Property Name")))
4255 (defcustom org-fontify-done-headline nil
4256 "Non-nil means change the face of a headline if it is marked DONE.
4257 Normally, only the TODO/DONE keyword indicates the state of a headline.
4258 When this is non-nil, the headline after the keyword is set to the
4259 `org-headline-done' as an additional indication."
4260 :group 'org-appearance
4261 :type 'boolean)
4263 (defcustom org-fontify-emphasized-text t
4264 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4265 Changing this variable requires a restart of Emacs to take effect."
4266 :group 'org-appearance
4267 :type 'boolean)
4269 (defcustom org-fontify-whole-heading-line nil
4270 "Non-nil means fontify the whole line for headings.
4271 This is useful when setting a background color for the
4272 org-level-* faces."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-highlight-latex-and-related nil
4277 "Non-nil means highlight LaTeX related syntax in the buffer.
4278 When non nil, the value should be a list containing any of the
4279 following symbols:
4280 `latex' Highlight LaTeX snippets and environments.
4281 `script' Highlight subscript and superscript.
4282 `entities' Highlight entities."
4283 :group 'org-appearance
4284 :version "24.4"
4285 :package-version '(Org . "8.0")
4286 :type '(choice
4287 (const :tag "No highlighting" nil)
4288 (set :greedy t :tag "Highlight"
4289 (const :tag "LaTeX snippets and environments" latex)
4290 (const :tag "Subscript and superscript" script)
4291 (const :tag "Entities" entities))))
4293 (defcustom org-hide-emphasis-markers nil
4294 "Non-nil mean font-lock should hide the emphasis marker characters."
4295 :group 'org-appearance
4296 :type 'boolean)
4298 (defcustom org-hide-macro-markers nil
4299 "Non-nil mean font-lock should hide the brackets marking macro calls."
4300 :group 'org-appearance
4301 :type 'boolean)
4303 (defcustom org-pretty-entities nil
4304 "Non-nil means show entities as UTF8 characters.
4305 When nil, the \\name form remains in the buffer."
4306 :group 'org-appearance
4307 :version "24.1"
4308 :type 'boolean)
4310 (defcustom org-pretty-entities-include-sub-superscripts t
4311 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4312 :group 'org-appearance
4313 :version "24.1"
4314 :type 'boolean)
4316 (defvar org-emph-re nil
4317 "Regular expression for matching emphasis.
4318 After a match, the match groups contain these elements:
4319 0 The match of the full regular expression, including the characters
4320 before and after the proper match
4321 1 The character before the proper match, or empty at beginning of line
4322 2 The proper match, including the leading and trailing markers
4323 3 The leading marker like * or /, indicating the type of highlighting
4324 4 The text between the emphasis markers, not including the markers
4325 5 The character after the match, empty at the end of a line")
4327 (defvar org-verbatim-re nil
4328 "Regular expression for matching verbatim text.")
4330 (defvar org-emphasis-regexp-components) ; defined just below
4331 (defvar org-emphasis-alist) ; defined just below
4332 (defun org-set-emph-re (var val)
4333 "Set variable and compute the emphasis regular expression."
4334 (set var val)
4335 (when (and (boundp 'org-emphasis-alist)
4336 (boundp 'org-emphasis-regexp-components)
4337 org-emphasis-alist org-emphasis-regexp-components)
4338 (pcase-let*
4339 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4340 (body (if (<= nl 0) body
4341 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4342 (template
4343 (format (concat "\\([%s]\\|^\\)" ;before markers
4344 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4345 "\\([%s]\\|$\\)") ;after markers
4346 pre border border body border post)))
4347 (setq org-emph-re (format template "*/_+"))
4348 (setq org-verbatim-re (format template "=~")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after customizing this.")
4371 (defcustom org-emphasis-alist
4372 '(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" (:strike-through t)))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks '("src" "example" "export")
4398 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4399 This is needed for font-lock setup.")
4401 ;;; Functions and variables from their packages
4402 ;; Declared here to avoid compiler warnings
4403 (defvar mark-active)
4405 ;; Various packages
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 (declare-function calendar-forward-day "cal-move" (arg))
4408 (declare-function calendar-goto-date "cal-move" (date))
4409 (declare-function calendar-goto-today "cal-move" ())
4410 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4411 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4412 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4413 (declare-function cdlatex-tab "ext:cdlatex" ())
4414 (declare-function dired-get-filename
4415 "dired"
4416 (&optional localp no-error-if-not-filep))
4417 (declare-function iswitchb-read-buffer
4418 "iswitchb"
4419 (prompt &optional
4420 default require-match _predicate start matches-set))
4421 (declare-function org-agenda-change-all-lines
4422 "org-agenda"
4423 (newhead hdmarker &optional fixface just-this))
4424 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4425 "org-agenda"
4426 (&optional end))
4427 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4428 (declare-function org-agenda-format-item
4429 "org-agenda"
4430 (extra txt &optional level category tags dotime
4431 remove-re habitp))
4432 (declare-function org-agenda-maybe-redo "org-agenda" ())
4433 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4434 (declare-function org-agenda-save-markers-for-cut-and-paste
4435 "org-agenda"
4436 (beg end))
4437 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4438 (declare-function org-agenda-skip "org-agenda" ())
4439 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4440 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4441 (declare-function org-indent-mode "org-indent" (&optional arg))
4442 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4443 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4444 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4445 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4446 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4447 (declare-function parse-time-string "parse-time" (string))
4448 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4450 (defvar align-mode-rules-list)
4451 (defvar calc-embedded-close-formula)
4452 (defvar calc-embedded-open-formula)
4453 (defvar calc-embedded-open-mode)
4454 (defvar font-lock-unfontify-region-function)
4455 (defvar iswitchb-temp-buflist)
4456 (defvar org-agenda-tags-todo-honor-ignore-options)
4457 (defvar remember-data-file)
4458 (defvar texmathp-why)
4460 ;;;###autoload
4461 (defun turn-on-orgtbl ()
4462 "Unconditionally turn on `orgtbl-mode'."
4463 (require 'org-table)
4464 (orgtbl-mode 1))
4466 (defun org-at-table-p (&optional table-type)
4467 "Non-nil if the cursor is inside an Org table.
4468 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4469 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4470 (or (not (derived-mode-p 'org-mode))
4471 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4472 (and e (or table-type
4473 (eq 'org (org-element-property :type e))))))))
4475 (defun org-at-table.el-p ()
4476 "Non-nil when point is at a table.el table."
4477 (and (org-match-line "[ \t]*[|+]")
4478 (let ((element (org-element-at-point)))
4479 (and (eq (org-element-type element) 'table)
4480 (eq (org-element-property :type element) 'table.el)))))
4482 (defun org-at-table-hline-p ()
4483 "Non-nil when point is inside a hline in a table.
4484 Assume point is already in a table."
4485 (org-match-line org-table-hline-regexp))
4487 (defun org-table-map-tables (function &optional quietly)
4488 "Apply FUNCTION to the start of all tables in the buffer."
4489 (org-with-wide-buffer
4490 (goto-char (point-min))
4491 (while (re-search-forward org-table-any-line-regexp nil t)
4492 (unless quietly
4493 (message "Mapping tables: %d%%"
4494 (floor (* 100.0 (point)) (buffer-size))))
4495 (beginning-of-line 1)
4496 (when (and (looking-at org-table-line-regexp)
4497 ;; Exclude tables in src/example/verbatim/clocktable blocks
4498 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4499 (save-excursion (funcall function))
4500 (or (looking-at org-table-line-regexp)
4501 (forward-char 1)))
4502 (re-search-forward org-table-any-border-regexp nil 1)))
4503 (unless quietly (message "Mapping tables: done")))
4505 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4506 (declare-function org-clock-update-mode-line "org-clock" ())
4507 (declare-function org-resolve-clocks "org-clock"
4508 (&optional also-non-dangling-p prompt last-valid))
4510 (defun org-at-TBLFM-p (&optional pos)
4511 "Non-nil when point (or POS) is in #+TBLFM line."
4512 (save-excursion
4513 (goto-char (or pos (point)))
4514 (beginning-of-line)
4515 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4516 (eq (org-element-type (org-element-at-point)) 'table))))
4518 (defvar org-clock-start-time)
4519 (defvar org-clock-marker (make-marker)
4520 "Marker recording the last clock-in.")
4521 (defvar org-clock-hd-marker (make-marker)
4522 "Marker recording the last clock-in, but the headline position.")
4523 (defvar org-clock-heading ""
4524 "The heading of the current clock entry.")
4525 (defun org-clock-is-active ()
4526 "Return the buffer where the clock is currently running.
4527 Return nil if no clock is running."
4528 (marker-buffer org-clock-marker))
4530 (defun org-check-running-clock ()
4531 "Check if the current buffer contains the running clock.
4532 If yes, offer to stop it and to save the buffer with the changes."
4533 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4534 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4535 (buffer-name))))
4536 (org-clock-out)
4537 (when (y-or-n-p "Save changed buffer?")
4538 (save-buffer))))
4540 (defun org-clocktable-try-shift (dir n)
4541 "Check if this line starts a clock table, if yes, shift the time block."
4542 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4543 (org-clocktable-shift dir n)))
4545 ;;;###autoload
4546 (defun org-clock-persistence-insinuate ()
4547 "Set up hooks for clock persistence."
4548 (require 'org-clock)
4549 (add-hook 'org-mode-hook 'org-clock-load)
4550 (add-hook 'kill-emacs-hook 'org-clock-save))
4552 (defgroup org-archive nil
4553 "Options concerning archiving in Org mode."
4554 :tag "Org Archive"
4555 :group 'org-structure)
4557 (defcustom org-archive-location "%s_archive::"
4558 "The location where subtrees should be archived.
4560 The value of this variable is a string, consisting of two parts,
4561 separated by a double-colon. The first part is a filename and
4562 the second part is a headline.
4564 When the filename is omitted, archiving happens in the same file.
4565 %s in the filename will be replaced by the current file
4566 name (without the directory part). Archiving to a different file
4567 is useful to keep archived entries from contributing to the
4568 Org Agenda.
4570 The archived entries will be filed as subtrees of the specified
4571 headline. When the headline is omitted, the subtrees are simply
4572 filed away at the end of the file, as top-level entries. Also in
4573 the heading you can use %s to represent the file name, this can be
4574 useful when using the same archive for a number of different files.
4576 Here are a few examples:
4577 \"%s_archive::\"
4578 If the current file is Projects.org, archive in file
4579 Projects.org_archive, as top-level trees. This is the default.
4581 \"::* Archived Tasks\"
4582 Archive in the current file, under the top-level headline
4583 \"* Archived Tasks\".
4585 \"~/org/archive.org::\"
4586 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4588 \"~/org/archive.org::* From %s\"
4589 Archive in file ~/org/archive.org (absolute path), under headlines
4590 \"From FILENAME\" where file name is the current file name.
4592 \"~/org/datetree.org::datetree/* Finished Tasks\"
4593 The \"datetree/\" string is special, signifying to archive
4594 items to the datetree. Items are placed in either the CLOSED
4595 date of the item, or the current date if there is no CLOSED date.
4596 The heading will be a subentry to the current date. There doesn't
4597 need to be a heading, but there always needs to be a slash after
4598 datetree. For example, to store archived items directly in the
4599 datetree, use \"~/org/datetree.org::datetree/\".
4601 \"basement::** Finished Tasks\"
4602 Archive in file ./basement (relative path), as level 3 trees
4603 below the level 2 heading \"** Finished Tasks\".
4605 You may set this option on a per-file basis by adding to the buffer a
4606 line like
4608 #+ARCHIVE: basement::** Finished Tasks
4610 You may also define it locally for a subtree by setting an ARCHIVE property
4611 in the entry. If such a property is found in an entry, or anywhere up
4612 the hierarchy, it will be used."
4613 :group 'org-archive
4614 :type 'string)
4616 (defcustom org-agenda-skip-archived-trees t
4617 "Non-nil means the agenda will skip any items located in archived trees.
4618 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4619 variable is no longer recommended, you should leave it at the value t.
4620 Instead, use the key `v' to cycle the archives-mode in the agenda."
4621 :group 'org-archive
4622 :group 'org-agenda-skip
4623 :type 'boolean)
4625 (defcustom org-columns-skip-archived-trees t
4626 "Non-nil means ignore archived trees when creating column view."
4627 :group 'org-archive
4628 :group 'org-properties
4629 :type 'boolean)
4631 (defcustom org-cycle-open-archived-trees nil
4632 "Non-nil means `org-cycle' will open archived trees.
4633 An archived tree is a tree marked with the tag ARCHIVE.
4634 When nil, archived trees will stay folded. You can still open them with
4635 normal outline commands like `show-all', but not with the cycling commands."
4636 :group 'org-archive
4637 :group 'org-cycle
4638 :type 'boolean)
4640 (defcustom org-sparse-tree-open-archived-trees nil
4641 "Non-nil means sparse tree construction shows matches in archived trees.
4642 When nil, matches in these trees are highlighted, but the trees are kept in
4643 collapsed state."
4644 :group 'org-archive
4645 :group 'org-sparse-trees
4646 :type 'boolean)
4648 (defcustom org-sparse-tree-default-date-type nil
4649 "The default date type when building a sparse tree.
4650 When this is nil, a date is a scheduled or a deadline timestamp.
4651 Otherwise, these types are allowed:
4653 all: all timestamps
4654 active: only active timestamps (<...>)
4655 inactive: only inactive timestamps ([...])
4656 scheduled: only scheduled timestamps
4657 deadline: only deadline timestamps"
4658 :type '(choice (const :tag "Scheduled or deadline" nil)
4659 (const :tag "All timestamps" all)
4660 (const :tag "Only active timestamps" active)
4661 (const :tag "Only inactive timestamps" inactive)
4662 (const :tag "Only scheduled timestamps" scheduled)
4663 (const :tag "Only deadline timestamps" deadline)
4664 (const :tag "Only closed timestamps" closed))
4665 :version "26.1"
4666 :package-version '(Org . "8.3")
4667 :group 'org-sparse-trees)
4669 (defun org-cycle-hide-archived-subtrees (state)
4670 "Re-hide all archived subtrees after a visibility state change.
4671 STATE should be one of the symbols listed in the docstring of
4672 `org-cycle-hook'."
4673 (when (and (not org-cycle-open-archived-trees)
4674 (not (memq state '(overview folded))))
4675 (save-excursion
4676 (let* ((globalp (memq state '(contents all)))
4677 (beg (if globalp (point-min) (point)))
4678 (end (if globalp (point-max) (org-end-of-subtree t))))
4679 (org-hide-archived-subtrees beg end)
4680 (goto-char beg)
4681 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4682 (message "%s" (substitute-command-keys
4683 "Subtree is archived and stays closed. Use \
4684 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4686 (defun org-force-cycle-archived ()
4687 "Cycle subtree even if it is archived."
4688 (interactive)
4689 (setq this-command 'org-cycle)
4690 (let ((org-cycle-open-archived-trees t))
4691 (call-interactively 'org-cycle)))
4693 (defun org-hide-archived-subtrees (beg end)
4694 "Re-hide all archived subtrees after a visibility state change."
4695 (org-with-wide-buffer
4696 (let ((case-fold-search nil)
4697 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4698 (goto-char beg)
4699 ;; Include headline point is currently on.
4700 (beginning-of-line)
4701 (while (and (< (point) end) (re-search-forward re end t))
4702 (when (member org-archive-tag (org-get-tags))
4703 (org-flag-subtree t)
4704 (org-end-of-subtree t))))))
4706 (declare-function outline-end-of-heading "outline" ())
4707 (declare-function outline-flag-region "outline" (from to flag))
4708 (defun org-flag-subtree (flag)
4709 (save-excursion
4710 (org-back-to-heading t)
4711 (outline-end-of-heading)
4712 (outline-flag-region (point)
4713 (progn (org-end-of-subtree t) (point))
4714 flag)))
4716 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4718 ;; Declare Column View Code
4720 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4721 (declare-function org-columns-compute "org-colview" (property))
4723 ;; Declare ID code
4725 (declare-function org-id-store-link "org-id")
4726 (declare-function org-id-locations-load "org-id")
4727 (declare-function org-id-locations-save "org-id")
4728 (defvar org-id-track-globally)
4730 ;;; Variables for pre-computed regular expressions, all buffer local
4732 (defvar-local org-todo-regexp nil
4733 "Matches any of the TODO state keywords.
4734 Since TODO keywords are case-sensitive, `case-fold-search' is
4735 expected to be bound to nil when matching against this regexp.")
4737 (defvar-local org-not-done-regexp nil
4738 "Matches any of the TODO state keywords except the last one.
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-not-done-heading-regexp nil
4743 "Matches a TODO headline that is not done.
4744 Since TODO keywords are case-sensitive, `case-fold-search' is
4745 expected to be bound to nil when matching against this regexp.")
4747 (defvar-local org-todo-line-regexp nil
4748 "Matches a headline and puts TODO state into group 2 if present.
4749 Since TODO keywords are case-sensitive, `case-fold-search' is
4750 expected to be bound to nil when matching against this regexp.")
4752 (defvar-local org-complex-heading-regexp nil
4753 "Matches a headline and puts everything into groups:
4755 group 1: Stars
4756 group 2: The TODO keyword, maybe
4757 group 3: Priority cookie
4758 group 4: True headline
4759 group 5: Tags
4761 Since TODO keywords are case-sensitive, `case-fold-search' is
4762 expected to be bound to nil when matching against this regexp.")
4764 (defvar-local org-complex-heading-regexp-format nil
4765 "Printf format to make regexp to match an exact headline.
4766 This regexp will match the headline of any node which has the
4767 exact headline text that is put into the format, but may have any
4768 TODO state, priority and tags.")
4770 (defvar-local org-todo-line-tags-regexp nil
4771 "Matches a headline and puts TODO state into group 2 if present.
4772 Also put tags into group 4 if tags are present.")
4774 (defconst org-plain-time-of-day-regexp
4775 (concat
4776 "\\(\\<[012]?[0-9]"
4777 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4778 "\\(--?"
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\)?")
4782 "Regular expression to match a plain time or time range.
4783 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4784 groups carry important information:
4785 0 the full match
4786 1 the first time, range or not
4787 8 the second time, if it is a range.")
4789 (defconst org-plain-time-extension-regexp
4790 (concat
4791 "\\(\\<[012]?[0-9]"
4792 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4793 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4794 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4795 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4796 groups carry important information:
4797 0 the full match
4798 7 hours of duration
4799 9 minutes of duration")
4801 (defconst org-stamp-time-of-day-regexp
4802 (concat
4803 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4804 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4805 "\\(--?"
4806 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4807 "Regular expression to match a timestamp time or time range.
4808 After a match, the following groups carry important information:
4809 0 the full match
4810 1 date plus weekday, for back referencing to make sure both times are on the same day
4811 2 the first time, range or not
4812 4 the second time, if it is a range.")
4814 (defconst org-startup-options
4815 '(("fold" org-startup-folded t)
4816 ("overview" org-startup-folded t)
4817 ("nofold" org-startup-folded nil)
4818 ("showall" org-startup-folded nil)
4819 ("showeverything" org-startup-folded showeverything)
4820 ("content" org-startup-folded content)
4821 ("indent" org-startup-indented t)
4822 ("noindent" org-startup-indented nil)
4823 ("hidestars" org-hide-leading-stars t)
4824 ("showstars" org-hide-leading-stars nil)
4825 ("odd" org-odd-levels-only t)
4826 ("oddeven" org-odd-levels-only nil)
4827 ("align" org-startup-align-all-tables t)
4828 ("noalign" org-startup-align-all-tables nil)
4829 ("inlineimages" org-startup-with-inline-images t)
4830 ("noinlineimages" org-startup-with-inline-images nil)
4831 ("latexpreview" org-startup-with-latex-preview t)
4832 ("nolatexpreview" org-startup-with-latex-preview nil)
4833 ("customtime" org-display-custom-times t)
4834 ("logdone" org-log-done time)
4835 ("lognotedone" org-log-done note)
4836 ("nologdone" org-log-done nil)
4837 ("lognoteclock-out" org-log-note-clock-out t)
4838 ("nolognoteclock-out" org-log-note-clock-out nil)
4839 ("logrepeat" org-log-repeat state)
4840 ("lognoterepeat" org-log-repeat note)
4841 ("logdrawer" org-log-into-drawer t)
4842 ("nologdrawer" org-log-into-drawer nil)
4843 ("logstatesreversed" org-log-states-order-reversed t)
4844 ("nologstatesreversed" org-log-states-order-reversed nil)
4845 ("nologrepeat" org-log-repeat nil)
4846 ("logreschedule" org-log-reschedule time)
4847 ("lognotereschedule" org-log-reschedule note)
4848 ("nologreschedule" org-log-reschedule nil)
4849 ("logredeadline" org-log-redeadline time)
4850 ("lognoteredeadline" org-log-redeadline note)
4851 ("nologredeadline" org-log-redeadline nil)
4852 ("logrefile" org-log-refile time)
4853 ("lognoterefile" org-log-refile note)
4854 ("nologrefile" org-log-refile nil)
4855 ("fninline" org-footnote-define-inline t)
4856 ("nofninline" org-footnote-define-inline nil)
4857 ("fnlocal" org-footnote-section nil)
4858 ("fnauto" org-footnote-auto-label t)
4859 ("fnprompt" org-footnote-auto-label nil)
4860 ("fnconfirm" org-footnote-auto-label confirm)
4861 ("fnplain" org-footnote-auto-label plain)
4862 ("fnadjust" org-footnote-auto-adjust t)
4863 ("nofnadjust" org-footnote-auto-adjust nil)
4864 ("constcgs" constants-unit-system cgs)
4865 ("constSI" constants-unit-system SI)
4866 ("noptag" org-tag-persistent-alist nil)
4867 ("hideblocks" org-hide-block-startup t)
4868 ("nohideblocks" org-hide-block-startup nil)
4869 ("beamer" org-startup-with-beamer-mode t)
4870 ("entitiespretty" org-pretty-entities t)
4871 ("entitiesplain" org-pretty-entities nil))
4872 "Variable associated with STARTUP options for org-mode.
4873 Each element is a list of three items: the startup options (as written
4874 in the #+STARTUP line), the corresponding variable, and the value to set
4875 this variable to if the option is found. An optional forth element PUSH
4876 means to push this value onto the list in the variable.")
4878 (defcustom org-group-tags t
4879 "When non-nil (the default), use group tags.
4880 This can be turned on/off through `org-toggle-tags-groups'."
4881 :group 'org-tags
4882 :group 'org-startup
4883 :type 'boolean)
4885 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4887 (defun org-toggle-tags-groups ()
4888 "Toggle support for group tags.
4889 Support for group tags is controlled by the option
4890 `org-group-tags', which is non-nil by default."
4891 (interactive)
4892 (setq org-group-tags (not org-group-tags))
4893 (cond ((and (derived-mode-p 'org-agenda-mode)
4894 org-group-tags)
4895 (org-agenda-redo))
4896 ((derived-mode-p 'org-mode)
4897 (let ((org-inhibit-startup t)) (org-mode))))
4898 (message "Groups tags support has been turned %s"
4899 (if org-group-tags "on" "off")))
4901 (defun org-set-regexps-and-options (&optional tags-only)
4902 "Precompute regular expressions used in the current buffer.
4903 When optional argument TAGS-ONLY is non-nil, only compute tags
4904 related expressions."
4905 (when (derived-mode-p 'org-mode)
4906 (let ((alist (org--setup-collect-keywords
4907 (org-make-options-regexp
4908 (append '("FILETAGS" "TAGS" "SETUPFILE")
4909 (and (not tags-only)
4910 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4911 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4912 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4913 ;; Startup options. Get this early since it does change
4914 ;; behavior for other options (e.g., tags).
4915 (let ((startup (cdr (assq 'startup alist))))
4916 (dolist (option startup)
4917 (let ((entry (assoc-string option org-startup-options t)))
4918 (when entry
4919 (let ((var (nth 1 entry))
4920 (val (nth 2 entry)))
4921 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4922 (unless (listp (symbol-value var))
4923 (set (make-local-variable var) nil))
4924 (add-to-list var val)))))))
4925 (setq-local org-file-tags
4926 (mapcar #'org-add-prop-inherited
4927 (cdr (assq 'filetags alist))))
4928 (setq org-current-tag-alist
4929 (append org-tag-persistent-alist
4930 (let ((tags (cdr (assq 'tags alist))))
4931 (if tags (org-tag-string-to-alist tags)
4932 org-tag-alist))))
4933 (setq org-tag-groups-alist
4934 (org-tag-alist-to-groups org-current-tag-alist))
4935 (unless tags-only
4936 ;; File properties.
4937 (setq-local org-file-properties (cdr (assq 'property alist)))
4938 ;; Archive location.
4939 (let ((archive (cdr (assq 'archive alist))))
4940 (when archive (setq-local org-archive-location archive)))
4941 ;; Category.
4942 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4943 (when cat
4944 (setq-local org-category (intern cat))
4945 (setq-local org-file-properties
4946 (org--update-property-plist
4947 "CATEGORY" cat org-file-properties))))
4948 ;; Columns.
4949 (let ((column (cdr (assq 'columns alist))))
4950 (when column (setq-local org-columns-default-format column)))
4951 ;; Constants.
4952 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4953 ;; Link abbreviations.
4954 (let ((links (cdr (assq 'link alist))))
4955 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4956 ;; Priorities.
4957 (let ((priorities (cdr (assq 'priorities alist))))
4958 (when priorities
4959 (setq-local org-highest-priority (nth 0 priorities))
4960 (setq-local org-lowest-priority (nth 1 priorities))
4961 (setq-local org-default-priority (nth 2 priorities))))
4962 ;; Scripts.
4963 (let ((scripts (assq 'scripts alist)))
4964 (when scripts
4965 (setq-local org-use-sub-superscripts (cdr scripts))))
4966 ;; TODO keywords.
4967 (setq-local org-todo-kwd-alist nil)
4968 (setq-local org-todo-key-alist nil)
4969 (setq-local org-todo-key-trigger nil)
4970 (setq-local org-todo-keywords-1 nil)
4971 (setq-local org-done-keywords nil)
4972 (setq-local org-todo-heads nil)
4973 (setq-local org-todo-sets nil)
4974 (setq-local org-todo-log-states nil)
4975 (let ((todo-sequences
4976 (or (nreverse (cdr (assq 'todo alist)))
4977 (let ((d (default-value 'org-todo-keywords)))
4978 (if (not (stringp (car d))) d
4979 ;; XXX: Backward compatibility code.
4980 (list (cons org-todo-interpretation d)))))))
4981 (dolist (sequence todo-sequences)
4982 (let* ((sequence (or (run-hook-with-args-until-success
4983 'org-todo-setup-filter-hook sequence)
4984 sequence))
4985 (sequence-type (car sequence))
4986 (keywords (cdr sequence))
4987 (sep (member "|" keywords))
4988 names alist)
4989 (dolist (k (remove "|" keywords))
4990 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4992 (error "Invalid TODO keyword %s" k))
4993 (let ((name (match-string 1 k))
4994 (key (match-string 2 k))
4995 (log (org-extract-log-state-settings k)))
4996 (push name names)
4997 (push (cons name (and key (string-to-char key))) alist)
4998 (when log (push log org-todo-log-states))))
4999 (let* ((names (nreverse names))
5000 (done (if sep (org-remove-keyword-keys (cdr sep))
5001 (last names)))
5002 (head (car names))
5003 (tail (list sequence-type head (car done) (org-last done))))
5004 (add-to-list 'org-todo-heads head 'append)
5005 (push names org-todo-sets)
5006 (setq org-done-keywords (append org-done-keywords done nil))
5007 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5008 (setq org-todo-key-alist
5009 (append org-todo-key-alist
5010 (and alist
5011 (append '((:startgroup))
5012 (nreverse alist)
5013 '((:endgroup))))))
5014 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5015 (setq org-todo-sets (nreverse org-todo-sets)
5016 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5017 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5018 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5019 ;; Compute the regular expressions and other local variables.
5020 ;; Using `org-outline-regexp-bol' would complicate them much,
5021 ;; because of the fixed white space at the end of that string.
5022 (unless org-done-keywords
5023 (setq org-done-keywords
5024 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5025 (setq org-not-done-keywords
5026 (org-delete-all org-done-keywords
5027 (copy-sequence org-todo-keywords-1))
5028 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5029 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5030 org-not-done-heading-regexp
5031 (format org-heading-keyword-regexp-format org-not-done-regexp)
5032 org-todo-line-regexp
5033 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5034 org-complex-heading-regexp
5035 (concat "^\\(\\*+\\)"
5036 "\\(?: +" org-todo-regexp "\\)?"
5037 "\\(?: +\\(\\[#.\\]\\)\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5040 "[ \t]*$")
5041 org-complex-heading-regexp-format
5042 (concat "^\\(\\*+\\)"
5043 "\\(?: +" org-todo-regexp "\\)?"
5044 "\\(?: +\\(\\[#.\\]\\)\\)?"
5045 "\\(?: +"
5046 ;; Stats cookies can be stuck to body.
5047 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5048 "\\(%s\\)"
5049 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5050 "\\)"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-todo-line-tags-regexp
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5058 "[ \t]*$"))
5059 (org-compute-latex-and-related-regexp)))))
5061 (defun org--setup-collect-keywords (regexp &optional files alist)
5062 "Return setup keywords values as an alist.
5064 REGEXP matches a subset of setup keywords. FILES is a list of
5065 file names already visited. It is used to avoid circular setup
5066 files. ALIST, when non-nil, is the alist computed so far.
5068 Return value contains the following keys: `archive', `category',
5069 `columns', `constants', `filetags', `link', `priorities',
5070 `property', `scripts', `startup', `tags' and `todo'."
5071 (org-with-wide-buffer
5072 (goto-char (point-min))
5073 (let ((case-fold-search t))
5074 (while (re-search-forward regexp nil t)
5075 (let ((element (org-element-at-point)))
5076 (when (eq (org-element-type element) 'keyword)
5077 (let ((key (org-element-property :key element))
5078 (value (org-element-property :value element)))
5079 (cond
5080 ((equal key "ARCHIVE")
5081 (when (org-string-nw-p value)
5082 (push (cons 'archive value) alist)))
5083 ((equal key "CATEGORY") (push (cons 'category value) alist))
5084 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5085 ((equal key "CONSTANTS")
5086 (let* ((constants (assq 'constants alist))
5087 (store (cdr constants)))
5088 (dolist (pair (split-string value))
5089 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5090 pair)
5091 (let* ((name (match-string 1 pair))
5092 (value (match-string 2 pair))
5093 (old (assoc name store)))
5094 (if old (setcdr old value)
5095 (push (cons name value) store)))))
5096 (if constants (setcdr constants store)
5097 (push (cons 'constants store) alist))))
5098 ((equal key "FILETAGS")
5099 (when (org-string-nw-p value)
5100 (let ((old (assq 'filetags alist))
5101 (new (apply #'nconc
5102 (mapcar (lambda (x) (org-split-string x ":"))
5103 (split-string value)))))
5104 (if old (setcdr old (append new (cdr old)))
5105 (push (cons 'filetags new) alist)))))
5106 ((equal key "LINK")
5107 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5108 (let ((links (assq 'link alist))
5109 (pair (cons (match-string-no-properties 1 value)
5110 (match-string-no-properties 2 value))))
5111 (if links (push pair (cdr links))
5112 (push (list 'link pair) alist)))))
5113 ((equal key "OPTIONS")
5114 (when (and (org-string-nw-p value)
5115 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5116 (push (cons 'scripts (read (match-string 1 value))) alist)))
5117 ((equal key "PRIORITIES")
5118 (push (cons 'priorities
5119 (let ((prio (split-string value)))
5120 (if (< (length prio) 3) '(?A ?C ?B)
5121 (mapcar #'string-to-char prio))))
5122 alist))
5123 ((equal key "PROPERTY")
5124 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5125 (let* ((property (assq 'property alist))
5126 (value (org--update-property-plist
5127 (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value)
5129 (cdr property))))
5130 (if property (setcdr property value)
5131 (push (cons 'property value) alist)))))
5132 ((equal key "STARTUP")
5133 (let ((startup (assq 'startup alist)))
5134 (if startup
5135 (setcdr startup
5136 (append (cdr startup) (split-string value)))
5137 (push (cons 'startup (split-string value)) alist))))
5138 ((equal key "TAGS")
5139 (let ((tag-cell (assq 'tags alist)))
5140 (if tag-cell
5141 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5142 (push (cons 'tags value) alist))))
5143 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5144 (let ((todo (assq 'todo alist))
5145 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5146 (split-string value))))
5147 (if todo (push value (cdr todo))
5148 (push (list 'todo value) alist))))
5149 ((equal key "SETUPFILE")
5150 (unless buffer-read-only ; Do not check in Gnus messages.
5151 (let ((f (and (org-string-nw-p value)
5152 (expand-file-name
5153 (org-unbracket-string "\"" "\"" value)))))
5154 (when (and f (file-readable-p f) (not (member f files)))
5155 (with-temp-buffer
5156 (setq default-directory (file-name-directory f))
5157 (insert-file-contents f)
5158 (setq alist
5159 ;; Fake Org mode to benefit from cache
5160 ;; without recurring needlessly.
5161 (let ((major-mode 'org-mode))
5162 (org--setup-collect-keywords
5163 regexp (cons f files) alist)))))))))))))))
5164 alist)
5166 (defun org-tag-string-to-alist (s)
5167 "Return tag alist associated to string S.
5168 S is a value for TAGS keyword or produced with
5169 `org-tag-alist-to-string'. Return value is an alist suitable for
5170 `org-tag-alist' or `org-tag-persistent-alist'."
5171 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5172 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5173 "\\|{.+?}\\)" ; regular expression
5174 "\\(?:(\\(.\\))\\)?\\'"))
5175 alist group-flag)
5176 (dolist (tokens lines (cdr (nreverse alist)))
5177 (push '(:newline) alist)
5178 (while tokens
5179 (let ((token (pop tokens)))
5180 (pcase token
5181 ("{"
5182 (push '(:startgroup) alist)
5183 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5184 ("}"
5185 (push '(:endgroup) alist)
5186 (setq group-flag nil))
5187 ("["
5188 (push '(:startgrouptag) alist)
5189 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5190 ("]"
5191 (push '(:endgrouptag) alist)
5192 (setq group-flag nil))
5193 (":"
5194 (push '(:grouptags) alist))
5195 ((guard (string-match tag-re token))
5196 (let ((tag (match-string 1 token))
5197 (key (and (match-beginning 2)
5198 (string-to-char (match-string 2 token)))))
5199 ;; Push all tags in groups, no matter if they already
5200 ;; appear somewhere else in the list.
5201 (when (or group-flag (not (assoc tag alist)))
5202 (push (cons tag key) alist))))))))))
5204 (defun org-tag-alist-to-string (alist &optional skip-key)
5205 "Return tag string associated to ALIST.
5207 ALIST is an alist, as defined in `org-tag-alist' or
5208 `org-tag-persistent-alist', or produced with
5209 `org-tag-string-to-alist'.
5211 Return value is a string suitable as a value for \"TAGS\"
5212 keyword.
5214 When optional argument SKIP-KEY is non-nil, skip selection keys
5215 next to tags."
5216 (mapconcat (lambda (token)
5217 (pcase token
5218 (`(:startgroup) "{")
5219 (`(:endgroup) "}")
5220 (`(:startgrouptag) "[")
5221 (`(:endgrouptag) "]")
5222 (`(:grouptags) ":")
5223 (`(:newline) "\\n")
5224 ((and
5225 (guard (not skip-key))
5226 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5227 (format "%s(%c)" tag key))
5228 (`(,(and tag (pred stringp)) . ,_) tag)
5229 (_ (user-error "Invalid tag token: %S" token))))
5230 alist
5231 " "))
5233 (defun org-tag-alist-to-groups (alist)
5234 "Return group alist from tag ALIST.
5235 ALIST is an alist, as defined in `org-tag-alist' or
5236 `org-tag-persistent-alist', or produced with
5237 `org-tag-string-to-alist'. Return value is an alist following
5238 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5239 a string, summarizing TAGS, as a list of strings."
5240 (let (groups group-status current-group)
5241 (dolist (token alist (nreverse groups))
5242 (pcase token
5243 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5244 (`(,(or :endgroup :endgrouptag))
5245 (when (eq group-status 'append)
5246 (push (nreverse current-group) groups))
5247 (setq group-status nil))
5248 (`(:grouptags) (setq group-status 'append))
5249 ((and `(,tag . ,_) (guard group-status))
5250 (if (eq group-status 'append) (push tag current-group)
5251 (setq current-group (list tag))))
5252 (_ nil)))))
5254 (defvar org--file-cache (make-hash-table :test #'equal)
5255 "Hash table to store contents of files referenced via a URL.
5256 This is the cache of file URLs read using `org-file-contents'.")
5258 (defun org-reset-file-cache ()
5259 "Reset the cache of files downloaded by `org-file-contents'."
5260 (clrhash org--file-cache))
5262 (defun org-file-url-p (file)
5263 "Non-nil if FILE is a URL."
5264 (require 'ffap)
5265 (string-match-p ffap-url-regexp file))
5267 (defun org-file-contents (file &optional noerror nocache)
5268 "Return the contents of FILE, as a string.
5270 FILE can be a file name or URL.
5272 If FILE is a URL, download the contents. If the URL contents are
5273 already cached in the `org--file-cache' hash table, the download step
5274 is skipped.
5276 If NOERROR is non-nil, ignore the error when unable to read the FILE
5277 from file or URL.
5279 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5280 is available. This option applies only if FILE is a URL."
5281 (let* ((is-url (org-file-url-p file))
5282 (cache (and is-url
5283 (not nocache)
5284 (gethash file org--file-cache))))
5285 (cond
5286 (cache)
5287 (is-url
5288 (with-current-buffer (url-retrieve-synchronously file)
5289 (goto-char (point-min))
5290 ;; Move point to after the url-retrieve header.
5291 (search-forward "\n\n" nil :move)
5292 ;; Search for the success code only in the url-retrieve header.
5293 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5294 ;; Update the cache `org--file-cache' and return contents.
5295 (puthash file
5296 (buffer-substring-no-properties (point) (point-max))
5297 org--file-cache)
5298 (funcall (if noerror #'message #'user-error)
5299 "Unable to fetch file from %S"
5300 file))))
5302 (with-temp-buffer
5303 (condition-case err
5304 (progn
5305 (insert-file-contents file)
5306 (buffer-string))
5307 (file-error
5308 (funcall (if noerror #'message #'user-error)
5309 (error-message-string err)))))))))
5311 (defun org-extract-log-state-settings (x)
5312 "Extract the log state setting from a TODO keyword string.
5313 This will extract info from a string like \"WAIT(w@/!)\"."
5314 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5315 (let ((kw (match-string 1 x))
5316 (log1 (and (match-end 3) (match-string 3 x)))
5317 (log2 (and (match-end 4) (match-string 4 x))))
5318 (and (or log1 log2)
5319 (list kw
5320 (and log1 (if (equal log1 "!") 'time 'note))
5321 (and log2 (if (equal log2 "!") 'time 'note)))))))
5323 (defun org-remove-keyword-keys (list)
5324 "Remove a pair of parenthesis at the end of each string in LIST."
5325 (mapcar (lambda (x)
5326 (if (string-match "(.*)$" x)
5327 (substring x 0 (match-beginning 0))
5329 list))
5331 (defun org-assign-fast-keys (alist)
5332 "Assign fast keys to a keyword-key alist.
5333 Respect keys that are already there."
5334 (let (new e (alt ?0))
5335 (while (setq e (pop alist))
5336 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5337 (cdr e)) ;; Key already assigned.
5338 (push e new)
5339 (let ((clist (string-to-list (downcase (car e))))
5340 (used (append new alist)))
5341 (when (= (car clist) ?@)
5342 (pop clist))
5343 (while (and clist (rassoc (car clist) used))
5344 (pop clist))
5345 (unless clist
5346 (while (rassoc alt used)
5347 (cl-incf alt)))
5348 (push (cons (car e) (or (car clist) alt)) new))))
5349 (nreverse new)))
5351 ;;; Some variables used in various places
5353 (defvar org-window-configuration nil
5354 "Used in various places to store a window configuration.")
5355 (defvar org-selected-window nil
5356 "Used in various places to store a window configuration.")
5357 (defvar org-finish-function nil
5358 "Function to be called when `C-c C-c' is used.
5359 This is for getting out of special buffers like capture.")
5360 (defvar org-last-state)
5362 ;; Defined somewhere in this file, but used before definition.
5363 (defvar org-entities) ;; defined in org-entities.el
5364 (defvar org-struct-menu)
5365 (defvar org-org-menu)
5366 (defvar org-tbl-menu)
5368 ;;;; Define the Org mode
5370 ;; We use a before-change function to check if a table might need
5371 ;; an update.
5372 (defvar org-table-may-need-update t
5373 "Indicates that a table might need an update.
5374 This variable is set by `org-before-change-function'.
5375 `org-table-align' sets it back to nil.")
5376 (defun org-before-change-function (_beg _end)
5377 "Every change indicates that a table might need an update."
5378 (setq org-table-may-need-update t))
5379 (defvar org-mode-map)
5380 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5381 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5382 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5383 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5384 (defvar org-table-buffer-is-an nil)
5386 (defvar bidi-paragraph-direction)
5387 (defvar buffer-face-mode-face)
5389 (require 'outline)
5391 ;; Other stuff we need.
5392 (require 'time-date)
5393 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5394 (require 'easymenu)
5395 (autoload 'easy-menu-add "easymenu")
5396 (require 'overlay)
5398 ;; (require 'org-macs) moved higher up in the file before it is first used
5399 (require 'org-entities)
5400 ;; (require 'org-compat) moved higher up in the file before it is first used
5401 (require 'org-faces)
5402 (require 'org-list)
5403 (require 'org-pcomplete)
5404 (require 'org-src)
5405 (require 'org-footnote)
5406 (require 'org-macro)
5408 ;; babel
5409 (require 'ob)
5411 ;;;###autoload
5412 (define-derived-mode org-mode outline-mode "Org"
5413 "Outline-based notes management and organizer, alias
5414 \"Carsten's outline-mode for keeping track of everything.\"
5416 Org mode develops organizational tasks around a NOTES file which
5417 contains information about projects as plain text. Org mode is
5418 implemented on top of Outline mode, which is ideal to keep the content
5419 of large files well structured. It supports ToDo items, deadlines and
5420 time stamps, which magically appear in the diary listing of the Emacs
5421 calendar. Tables are easily created with a built-in table editor.
5422 Plain text URL-like links connect to websites, emails (VM), Usenet
5423 messages (Gnus), BBDB entries, and any files related to the project.
5424 For printing and sharing of notes, an Org file (or a part of it)
5425 can be exported as a structured ASCII or HTML file.
5427 The following commands are available:
5429 \\{org-mode-map}"
5431 ;; Get rid of Outline menus, they are not needed
5432 ;; Need to do this here because define-derived-mode sets up
5433 ;; the keymap so late. Still, it is a waste to call this each time
5434 ;; we switch another buffer into Org mode.
5435 (define-key org-mode-map [menu-bar headings] 'undefined)
5436 (define-key org-mode-map [menu-bar hide] 'undefined)
5437 (define-key org-mode-map [menu-bar show] 'undefined)
5439 (org-load-modules-maybe)
5440 (org-install-agenda-files-menu)
5441 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5442 (add-to-invisibility-spec '(org-cwidth))
5443 (add-to-invisibility-spec '(org-hide-block . t))
5444 (setq-local outline-regexp org-outline-regexp)
5445 (setq-local outline-level 'org-outline-level)
5446 (setq bidi-paragraph-direction 'left-to-right)
5447 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5448 (unless org-display-table
5449 (setq org-display-table (make-display-table)))
5450 (set-display-table-slot
5451 org-display-table 4
5452 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5453 org-ellipsis)))
5454 (setq buffer-display-table org-display-table))
5455 (org-set-regexps-and-options)
5456 (org-set-font-lock-defaults)
5457 (when (and org-tag-faces (not org-tags-special-faces-re))
5458 ;; tag faces set outside customize.... force initialization.
5459 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5460 ;; Calc embedded
5461 (setq-local calc-embedded-open-mode "# ")
5462 ;; Modify a few syntax entries
5463 (modify-syntax-entry ?@ "w")
5464 (modify-syntax-entry ?\" "\"")
5465 (modify-syntax-entry ?\\ "_")
5466 (modify-syntax-entry ?~ "_")
5467 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5468 ;; Activate before-change-function
5469 (setq-local org-table-may-need-update t)
5470 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5471 ;; Check for running clock before killing a buffer
5472 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5473 ;; Initialize macros templates.
5474 (org-macro-initialize-templates)
5475 ;; Initialize radio targets.
5476 (org-update-radio-target-regexp)
5477 ;; Indentation.
5478 (setq-local indent-line-function 'org-indent-line)
5479 (setq-local indent-region-function 'org-indent-region)
5480 ;; Filling and auto-filling.
5481 (org-setup-filling)
5482 ;; Comments.
5483 (org-setup-comments-handling)
5484 ;; Initialize cache.
5485 (org-element-cache-reset)
5486 ;; Beginning/end of defun
5487 (setq-local beginning-of-defun-function 'org-backward-element)
5488 (setq-local end-of-defun-function
5489 (lambda ()
5490 (if (not (org-at-heading-p))
5491 (org-forward-element)
5492 (org-forward-element)
5493 (forward-char -1))))
5494 ;; Next error for sparse trees
5495 (setq-local next-error-function 'org-occur-next-match)
5496 ;; Make sure dependence stuff works reliably, even for users who set it
5497 ;; too late :-(
5498 (if org-enforce-todo-dependencies
5499 (add-hook 'org-blocker-hook
5500 'org-block-todo-from-children-or-siblings-or-parent)
5501 (remove-hook 'org-blocker-hook
5502 'org-block-todo-from-children-or-siblings-or-parent))
5503 (if org-enforce-todo-checkbox-dependencies
5504 (add-hook 'org-blocker-hook
5505 'org-block-todo-from-checkboxes)
5506 (remove-hook 'org-blocker-hook
5507 'org-block-todo-from-checkboxes))
5509 ;; Align options lines
5510 (setq-local
5511 align-mode-rules-list
5512 '((org-in-buffer-settings
5513 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5514 (modes . '(org-mode)))))
5516 ;; Imenu
5517 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5519 ;; Make isearch reveal context
5520 (setq-local outline-isearch-open-invisible-function
5521 (lambda (&rest _) (org-show-context 'isearch)))
5523 ;; Setup the pcomplete hooks
5524 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5525 (setq-local pcomplete-command-name-function 'org-command-at-point)
5526 (setq-local pcomplete-default-completion-function 'ignore)
5527 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5528 (setq-local pcomplete-termination-string "")
5529 (setq-local buffer-face-mode-face 'org-default)
5531 ;; If empty file that did not turn on Org mode automatically, make
5532 ;; it to.
5533 (when (and org-insert-mode-line-in-empty-file
5534 (called-interactively-p 'any)
5535 (= (point-min) (point-max)))
5536 (insert "# -*- mode: org -*-\n\n"))
5537 (unless org-inhibit-startup
5538 (org-unmodified
5539 (when org-startup-with-beamer-mode (org-beamer-mode))
5540 (when org-startup-align-all-tables
5541 (org-table-map-tables #'org-table-align t))
5542 (when org-startup-with-inline-images (org-display-inline-images))
5543 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5544 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5545 (when org-startup-truncated (setq truncate-lines t))
5546 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5547 (org-refresh-effort-properties)))
5548 ;; Try to set `org-hide' face correctly.
5549 (let ((foreground (org-find-invisible-foreground)))
5550 (when foreground
5551 (set-face-foreground 'org-hide foreground))))
5553 ;; Update `customize-package-emacs-version-alist'
5554 (add-to-list 'customize-package-emacs-version-alist
5555 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5556 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5557 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5558 ("9.0" . "26.1")))
5560 (defvar org-mode-transpose-word-syntax-table
5561 (let ((st (make-syntax-table text-mode-syntax-table)))
5562 (dolist (c org-emphasis-alist st)
5563 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5565 (when (fboundp 'abbrev-table-put)
5566 (abbrev-table-put org-mode-abbrev-table
5567 :parents (list text-mode-abbrev-table)))
5569 (defun org-find-invisible-foreground ()
5570 (let ((candidates (remove
5571 "unspecified-bg"
5572 (nconc
5573 (list (face-background 'default)
5574 (face-background 'org-default))
5575 (mapcar
5576 (lambda (alist)
5577 (when (boundp alist)
5578 (cdr (assq 'background-color (symbol-value alist)))))
5579 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5580 (list (face-foreground 'org-hide))))))
5581 (car (remove nil candidates))))
5583 (defun org-current-time (&optional rounding-minutes past)
5584 "Current time, possibly rounded to ROUNDING-MINUTES.
5585 When ROUNDING-MINUTES is not an integer, fall back on the car of
5586 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5587 the rounding returns a past time."
5588 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5589 (car org-time-stamp-rounding-minutes)))
5590 (time (decode-time)) res)
5591 (if (< r 1)
5592 (current-time)
5593 (setq res
5594 (apply 'encode-time
5595 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5596 (nthcdr 2 time))))
5597 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5598 (seconds-to-time (- (float-time res) (* r 60)))
5599 res))))
5601 (defun org-today ()
5602 "Return today date, considering `org-extend-today-until'."
5603 (time-to-days
5604 (time-subtract (current-time)
5605 (list 0 (* 3600 org-extend-today-until) 0))))
5607 ;;;; Font-Lock stuff, including the activators
5609 (defvar org-mouse-map (make-sparse-keymap))
5610 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5611 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5612 (when org-mouse-1-follows-link
5613 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5614 (when org-tab-follows-link
5615 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5616 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5618 (require 'font-lock)
5620 (defconst org-non-link-chars "]\t\n\r<>")
5621 (defvar org-link-types-re nil
5622 "Matches a link that has a url-like prefix like \"http:\"")
5623 (defvar org-link-re-with-space nil
5624 "Matches a link with spaces, optional angular brackets around it.")
5625 (defvar org-link-re-with-space2 nil
5626 "Matches a link with spaces, optional angular brackets around it.")
5627 (defvar org-link-re-with-space3 nil
5628 "Matches a link with spaces, only for internal part in bracket links.")
5629 (defvar org-angle-link-re nil
5630 "Matches link with angular brackets, spaces are allowed.")
5631 (defvar org-plain-link-re nil
5632 "Matches plain link, without spaces.")
5633 (defvar org-bracket-link-regexp nil
5634 "Matches a link in double brackets.")
5635 (defvar org-bracket-link-analytic-regexp nil
5636 "Regular expression used to analyze links.
5637 Here is what the match groups contain after a match:
5638 1: http:
5639 2: http
5640 3: path
5641 4: [desc]
5642 5: desc")
5643 (defvar org-bracket-link-analytic-regexp++ nil
5644 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5645 (defvar org-any-link-re nil
5646 "Regular expression matching any link.")
5648 (defconst org-match-sexp-depth 3
5649 "Number of stacked braces for sub/superscript matching.")
5651 (defun org-create-multibrace-regexp (left right n)
5652 "Create a regular expression which will match a balanced sexp.
5653 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5654 as single character strings.
5655 The regexp returned will match the entire expression including the
5656 delimiters. It will also define a single group which contains the
5657 match except for the outermost delimiters. The maximum depth of
5658 stacked delimiters is N. Escaping delimiters is not possible."
5659 (let* ((nothing (concat "[^" left right "]*?"))
5660 (or "\\|")
5661 (re nothing)
5662 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5663 (while (> n 1)
5664 (setq n (1- n)
5665 re (concat re or next)
5666 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5667 (concat left "\\(" re "\\)" right)))
5669 (defconst org-match-substring-regexp
5670 (concat
5671 "\\(\\S-\\)\\([_^]\\)\\("
5672 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5673 "\\|"
5674 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5675 "\\|"
5676 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5677 "The regular expression matching a sub- or superscript.")
5679 (defconst org-match-substring-with-braces-regexp
5680 (concat
5681 "\\(\\S-\\)\\([_^]\\)"
5682 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5683 "The regular expression matching a sub- or superscript, forcing braces.")
5685 (defun org-make-link-regexps ()
5686 "Update the link regular expressions.
5687 This should be called after the variable `org-link-parameters' has changed."
5688 (let ((types-re (regexp-opt (org-link-types) t)))
5689 (setq org-link-types-re
5690 (concat "\\`" types-re ":")
5691 org-link-re-with-space
5692 (concat "<?" types-re ":"
5693 "\\([^" org-non-link-chars " ]"
5694 "[^" org-non-link-chars "]*"
5695 "[^" org-non-link-chars " ]\\)>?")
5696 org-link-re-with-space2
5697 (concat "<?" types-re ":"
5698 "\\([^" org-non-link-chars " ]"
5699 "[^\t\n\r]*"
5700 "[^" org-non-link-chars " ]\\)>?")
5701 org-link-re-with-space3
5702 (concat "<?" types-re ":"
5703 "\\([^" org-non-link-chars " ]"
5704 "[^\t\n\r]*\\)")
5705 org-angle-link-re
5706 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5707 types-re)
5708 org-plain-link-re
5709 (concat
5710 "\\<" types-re ":"
5711 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5712 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5713 org-bracket-link-regexp
5714 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5715 org-bracket-link-analytic-regexp
5716 (concat
5717 "\\[\\["
5718 "\\(" types-re ":\\)?"
5719 "\\([^]]+\\)"
5720 "\\]"
5721 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5722 "\\]")
5723 org-bracket-link-analytic-regexp++
5724 (concat
5725 "\\[\\["
5726 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5727 "\\([^]]+\\)"
5728 "\\]"
5729 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5730 "\\]")
5731 org-any-link-re
5732 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5733 org-angle-link-re "\\)\\|\\("
5734 org-plain-link-re "\\)"))))
5736 (org-make-link-regexps)
5738 (defvar org-emph-face nil)
5740 (defun org-do-emphasis-faces (limit)
5741 "Run through the buffer and emphasize strings."
5742 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5743 (car org-emphasis-regexp-components))))
5744 (catch :exit
5745 (while (re-search-forward quick-re limit t)
5746 (let* ((marker (match-string 2))
5747 (verbatim? (member marker '("~" "="))))
5748 (when (save-excursion
5749 (goto-char (match-beginning 0))
5750 ;; Do not match headline stars. Do not consider
5751 ;; stars of a headline as closing marker for bold
5752 ;; markup either. Do not match table hlines.
5753 (and
5754 (not (looking-at-p org-outline-regexp-bol))
5755 (not (and (equal marker "+")
5756 (org-match-line
5757 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5758 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5759 (not (string-match-p
5760 (concat org-outline-regexp-bol "\\'")
5761 (match-string 0)))))
5762 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5763 (font-lock-prepend-text-property
5764 (match-beginning 2) (match-end 2) 'face face)
5765 (when verbatim?
5766 (org-remove-flyspell-overlays-in
5767 (match-beginning 0) (match-end 0)))
5768 (add-text-properties (match-beginning 2) (match-end 2)
5769 '(font-lock-multiline t org-emphasis t))
5770 (when org-hide-emphasis-markers
5771 (add-text-properties (match-end 4) (match-beginning 5)
5772 '(invisible org-link))
5773 (add-text-properties (match-beginning 3) (match-end 3)
5774 '(invisible org-link)))
5775 (throw :exit t))))))))
5777 (defun org-emphasize (&optional char)
5778 "Insert or change an emphasis, i.e. a font like bold or italic.
5779 If there is an active region, change that region to a new emphasis.
5780 If there is no region, just insert the marker characters and position
5781 the cursor between them.
5782 CHAR should be the marker character. If it is a space, it means to
5783 remove the emphasis of the selected region.
5784 If CHAR is not given (for example in an interactive call) it will be
5785 prompted for."
5786 (interactive)
5787 (let ((erc org-emphasis-regexp-components)
5788 (string "") beg end move s)
5789 (if (org-region-active-p)
5790 (setq beg (region-beginning)
5791 end (region-end)
5792 string (buffer-substring beg end))
5793 (setq move t))
5795 (unless char
5796 (message "Emphasis marker or tag: [%s]"
5797 (mapconcat #'car org-emphasis-alist ""))
5798 (setq char (read-char-exclusive)))
5799 (if (equal char ?\s)
5800 (setq s ""
5801 move nil)
5802 (unless (assoc (char-to-string char) org-emphasis-alist)
5803 (user-error "No such emphasis marker: \"%c\"" char))
5804 (setq s (char-to-string char)))
5805 (while (and (> (length string) 1)
5806 (equal (substring string 0 1) (substring string -1))
5807 (assoc (substring string 0 1) org-emphasis-alist))
5808 (setq string (substring string 1 -1)))
5809 (setq string (concat s string s))
5810 (when beg (delete-region beg end))
5811 (unless (or (bolp)
5812 (string-match (concat "[" (nth 0 erc) "\n]")
5813 (char-to-string (char-before (point)))))
5814 (insert " "))
5815 (unless (or (eobp)
5816 (string-match (concat "[" (nth 1 erc) "\n]")
5817 (char-to-string (char-after (point)))))
5818 (insert " ") (backward-char 1))
5819 (insert string)
5820 (and move (backward-char 1))))
5822 (defconst org-nonsticky-props
5823 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5825 (defsubst org-rear-nonsticky-at (pos)
5826 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5828 (defun org-activate-links (limit)
5829 "Add link properties to links.
5830 This includes angle, plain, and bracket links."
5831 (catch :exit
5832 (while (re-search-forward org-any-link-re limit t)
5833 (let* ((start (match-beginning 0))
5834 (end (match-end 0))
5835 (style (cond ((eq ?< (char-after start)) 'angle)
5836 ((eq ?\[ (char-after (1+ start))) 'bracket)
5837 (t 'plain))))
5838 (when (and (memq style org-highlight-links)
5839 ;; Do not confuse plain links with tags.
5840 (not (and (eq style 'plain)
5841 (let ((face (get-text-property
5842 (max (1- start) (point-min)) 'face)))
5843 (if (consp face) (memq 'org-tag face)
5844 (eq 'org-tag face))))))
5845 (let* ((link-object (save-excursion
5846 (goto-char start)
5847 (save-match-data (org-element-link-parser))))
5848 (link (org-element-property :raw-link link-object))
5849 (type (org-element-property :type link-object))
5850 (path (org-element-property :path link-object))
5851 (properties ;for link's visible part
5852 (list
5853 'face (pcase (org-link-get-parameter type :face)
5854 ((and (pred functionp) face) (funcall face path))
5855 ((and (pred facep) face) face)
5856 ((and (pred consp) face) face) ;anonymous
5857 (_ 'org-link))
5858 'mouse-face (or (org-link-get-parameter type :mouse-face)
5859 'highlight)
5860 'keymap (or (org-link-get-parameter type :keymap)
5861 org-mouse-map)
5862 'help-echo (pcase (org-link-get-parameter type :help-echo)
5863 ((and (pred stringp) echo) echo)
5864 ((and (pred functionp) echo) echo)
5865 (_ (concat "LINK: " link)))
5866 'htmlize-link (pcase (org-link-get-parameter type
5867 :htmlize-link)
5868 ((and (pred functionp) f) (funcall f))
5869 (_ `(:uri ,link)))
5870 'font-lock-multiline t)))
5871 (org-remove-flyspell-overlays-in start end)
5872 (org-rear-nonsticky-at end)
5873 (if (not (eq 'bracket style))
5874 (add-text-properties start end properties)
5875 ;; Handle invisible parts in bracket links.
5876 (remove-text-properties start end '(invisible nil))
5877 (let ((hidden
5878 (append `(invisible
5879 ,(or (org-link-get-parameter type :display)
5880 'org-link))
5881 properties))
5882 (visible-start (or (match-beginning 4) (match-beginning 2)))
5883 (visible-end (or (match-end 4) (match-end 2))))
5884 (add-text-properties start visible-start hidden)
5885 (add-text-properties visible-start visible-end properties)
5886 (add-text-properties visible-end end hidden)
5887 (org-rear-nonsticky-at visible-start)
5888 (org-rear-nonsticky-at visible-end)))
5889 (let ((f (org-link-get-parameter type :activate-func)))
5890 (when (functionp f)
5891 (funcall f start end path (eq style 'bracket))))
5892 (throw :exit t))))) ;signal success
5893 nil))
5895 (defun org-activate-code (limit)
5896 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5897 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5898 (remove-text-properties (match-beginning 0) (match-end 0)
5899 '(display t invisible t intangible t))
5902 (defcustom org-src-fontify-natively t
5903 "When non-nil, fontify code in code blocks.
5904 See also the `org-block' face."
5905 :type 'boolean
5906 :version "24.4"
5907 :package-version '(Org . "8.3")
5908 :group 'org-appearance
5909 :group 'org-babel)
5911 (defcustom org-allow-promoting-top-level-subtree nil
5912 "When non-nil, allow promoting a top level subtree.
5913 The leading star of the top level headline will be replaced
5914 by a #."
5915 :type 'boolean
5916 :version "24.1"
5917 :group 'org-appearance)
5919 (defun org-fontify-meta-lines-and-blocks (limit)
5920 (condition-case nil
5921 (org-fontify-meta-lines-and-blocks-1 limit)
5922 (error (message "org-mode fontification error in %S at %d"
5923 (current-buffer)
5924 (line-number-at-pos)))))
5926 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5927 "Fontify #+ lines and blocks."
5928 (let ((case-fold-search t))
5929 (when (re-search-forward
5930 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5931 limit t)
5932 (let ((beg (match-beginning 0))
5933 (block-start (match-end 0))
5934 (block-end nil)
5935 (lang (match-string 7))
5936 (beg1 (line-beginning-position 2))
5937 (dc1 (downcase (match-string 2)))
5938 (dc3 (downcase (match-string 3)))
5939 end end1 quoting block-type)
5940 (cond
5941 ((and (match-end 4) (equal dc3 "+begin"))
5942 ;; Truly a block
5943 (setq block-type (downcase (match-string 5))
5944 quoting (member block-type org-protecting-blocks))
5945 (when (re-search-forward
5946 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5947 nil t) ;; on purpose, we look further than LIMIT
5948 (setq end (min (point-max) (match-end 0))
5949 end1 (min (point-max) (1- (match-beginning 0))))
5950 (setq block-end (match-beginning 0))
5951 (when quoting
5952 (org-remove-flyspell-overlays-in beg1 end1)
5953 (remove-text-properties beg end
5954 '(display t invisible t intangible t)))
5955 (add-text-properties
5956 beg end '(font-lock-fontified t font-lock-multiline t))
5957 (add-text-properties beg beg1 '(face org-meta-line))
5958 (org-remove-flyspell-overlays-in beg beg1)
5959 (add-text-properties ; For end_src
5960 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5961 (org-remove-flyspell-overlays-in end1 end)
5962 (cond
5963 ((and lang (not (string= lang "")) org-src-fontify-natively)
5964 (org-src-font-lock-fontify-block lang block-start block-end)
5965 (add-text-properties beg1 block-end '(src-block t)))
5966 (quoting
5967 (add-text-properties beg1 (min (point-max) (1+ end1))
5968 (list 'face
5969 (list :inherit
5970 (let ((face-name
5971 (intern (format "org-block-%s" lang))))
5972 (append (and (facep face-name) (list face-name))
5973 '(org-block))))))) ; end of source block
5974 ((not org-fontify-quote-and-verse-blocks))
5975 ((string= block-type "quote")
5976 (add-face-text-property
5977 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5978 ((string= block-type "verse")
5979 (add-face-text-property
5980 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5981 (add-text-properties beg beg1 '(face org-block-begin-line))
5982 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5983 '(face org-block-end-line))
5985 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5986 (org-remove-flyspell-overlays-in
5987 (match-beginning 0)
5988 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5989 (add-text-properties
5990 beg (match-end 3)
5991 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5992 '(font-lock-fontified t invisible t)
5993 '(font-lock-fontified t face org-document-info-keyword)))
5994 (add-text-properties
5995 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5996 (if (string-equal dc1 "+title:")
5997 '(font-lock-fontified t face org-document-title)
5998 '(font-lock-fontified t face org-document-info))))
5999 ((string-prefix-p "+caption" dc1)
6000 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6001 (remove-text-properties (match-beginning 0) (match-end 0)
6002 '(display t invisible t intangible t))
6003 ;; Handle short captions.
6004 (save-excursion
6005 (beginning-of-line)
6006 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6007 (add-text-properties (line-beginning-position) (match-end 1)
6008 '(font-lock-fontified t face org-meta-line))
6009 (add-text-properties (match-end 0) (line-end-position)
6010 '(font-lock-fontified t face org-block))
6012 ((member dc3 '(" " ""))
6013 (org-remove-flyspell-overlays-in beg (match-end 0))
6014 (add-text-properties
6015 beg (match-end 0)
6016 '(font-lock-fontified t face font-lock-comment-face)))
6017 (t ;; just any other in-buffer setting, but not indented
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(display t invisible t intangible t))
6021 (add-text-properties beg (match-end 0)
6022 '(font-lock-fontified t face org-meta-line))
6023 t))))))
6025 (defun org-fontify-drawers (limit)
6026 "Fontify drawers."
6027 (when (re-search-forward org-drawer-regexp limit t)
6028 (add-text-properties
6029 (match-beginning 0) (match-end 0)
6030 '(font-lock-fontified t face org-special-keyword))
6031 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (defun org-fontify-macros (limit)
6035 "Fontify macros."
6036 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6037 (add-text-properties
6038 (match-beginning 0) (match-end 0)
6039 '(font-lock-fontified t face org-macro))
6040 (when org-hide-macro-markers
6041 (add-text-properties (match-end 2) (match-beginning 2)
6042 '(invisible t))
6043 (add-text-properties (match-beginning 1) (match-end 1)
6044 '(invisible t)))
6045 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (defun org-activate-footnote-links (limit)
6049 "Add text properties for footnotes."
6050 (let ((fn (org-footnote-next-reference-or-definition limit)))
6051 (when fn
6052 (let* ((beg (nth 1 fn))
6053 (end (nth 2 fn))
6054 (label (car fn))
6055 (referencep (/= (line-beginning-position) beg)))
6056 (when (and referencep (nth 3 fn))
6057 (save-excursion
6058 (goto-char beg)
6059 (search-forward (or label "fn:"))
6060 (org-remove-flyspell-overlays-in beg (match-end 0))))
6061 (add-text-properties beg end
6062 (list 'mouse-face 'highlight
6063 'keymap org-mouse-map
6064 'help-echo
6065 (if referencep "Footnote reference"
6066 "Footnote definition")
6067 'font-lock-fontified t
6068 'font-lock-multiline t
6069 'face 'org-footnote))))))
6071 (defun org-activate-dates (limit)
6072 "Add text properties for dates."
6073 (when (and (re-search-forward org-tsr-regexp-both limit t)
6074 (not (equal (char-before (match-beginning 0)) 91)))
6075 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6076 (add-text-properties (match-beginning 0) (match-end 0)
6077 (list 'mouse-face 'highlight
6078 'keymap org-mouse-map))
6079 (org-rear-nonsticky-at (match-end 0))
6080 (when org-display-custom-times
6081 ;; If it's a date range, activate custom time for second date.
6082 (when (match-end 3)
6083 (org-display-custom-time (match-beginning 3) (match-end 3)))
6084 (org-display-custom-time (match-beginning 1) (match-end 1)))
6087 (defvar-local org-target-link-regexp nil
6088 "Regular expression matching radio targets in plain text.")
6090 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6091 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6092 border border border))
6093 "Regular expression matching a link target.")
6095 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6096 "Regular expression matching a radio target.")
6098 (defconst org-any-target-regexp
6099 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6100 "Regular expression matching any target.")
6102 (defun org-activate-target-links (limit)
6103 "Add text properties for target matches."
6104 (when org-target-link-regexp
6105 (let ((case-fold-search t))
6106 (when (re-search-forward org-target-link-regexp limit t)
6107 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6108 (add-text-properties (match-beginning 1) (match-end 1)
6109 (list 'mouse-face 'highlight
6110 'keymap org-mouse-map
6111 'help-echo "Radio target link"
6112 'org-linked-text t))
6113 (org-rear-nonsticky-at (match-end 1))
6114 t))))
6116 (defun org-update-radio-target-regexp ()
6117 "Find all radio targets in this file and update the regular expression.
6118 Also refresh fontification if needed."
6119 (interactive)
6120 (let ((old-regexp org-target-link-regexp)
6121 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6122 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6123 (targets
6124 (org-with-wide-buffer
6125 (goto-char (point-min))
6126 (let (rtn)
6127 (while (re-search-forward org-radio-target-regexp nil t)
6128 ;; Make sure point is really within the object.
6129 (backward-char)
6130 (let ((obj (org-element-context)))
6131 (when (eq (org-element-type obj) 'radio-target)
6132 (cl-pushnew (org-element-property :value obj) rtn
6133 :test #'equal))))
6134 rtn))))
6135 (setq org-target-link-regexp
6136 (and targets
6137 (concat before-re
6138 (mapconcat
6139 (lambda (x)
6140 (replace-regexp-in-string
6141 " +" "\\s-+" (regexp-quote x) t t))
6142 targets
6143 "\\|")
6144 after-re)))
6145 (unless (equal old-regexp org-target-link-regexp)
6146 ;; Clean-up cache.
6147 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6148 ((not org-target-link-regexp) old-regexp)
6150 (concat before-re
6151 (mapconcat
6152 (lambda (re)
6153 (substring re (length before-re)
6154 (- (length after-re))))
6155 (list old-regexp org-target-link-regexp)
6156 "\\|")
6157 after-re)))))
6158 (org-with-wide-buffer
6159 (goto-char (point-min))
6160 (while (re-search-forward regexp nil t)
6161 (org-element-cache-refresh (match-beginning 1)))))
6162 ;; Re fontify buffer.
6163 (when (memq 'radio org-highlight-links)
6164 (org-restart-font-lock)))))
6166 (defun org-hide-wide-columns (limit)
6167 (let (s e)
6168 (setq s (text-property-any (point) (or limit (point-max))
6169 'org-cwidth t))
6170 (when s
6171 (setq e (next-single-property-change s 'org-cwidth))
6172 (add-text-properties s e '(invisible org-cwidth))
6173 (goto-char e)
6174 t)))
6176 (defvar org-latex-and-related-regexp nil
6177 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6179 (defun org-compute-latex-and-related-regexp ()
6180 "Compute regular expression for LaTeX, entities and sub/superscript.
6181 Result depends on variable `org-highlight-latex-and-related'."
6182 (setq-local
6183 org-latex-and-related-regexp
6184 (let* ((re-sub
6185 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6186 ((eq org-use-sub-superscripts '{})
6187 (list org-match-substring-with-braces-regexp))
6188 (org-use-sub-superscripts (list org-match-substring-regexp))))
6189 (re-latex
6190 (when (memq 'latex org-highlight-latex-and-related)
6191 (let ((matchers (plist-get org-format-latex-options :matchers)))
6192 (delq nil
6193 (mapcar (lambda (x)
6194 (and (member (car x) matchers) (nth 1 x)))
6195 org-latex-regexps)))))
6196 (re-entities
6197 (when (memq 'entities org-highlight-latex-and-related)
6198 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6199 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6201 (defun org-do-latex-and-related (limit)
6202 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6203 LIMIT bounds the search for syntax to highlight. Stop at first
6204 highlighted object, if any. Return t if some highlighting was
6205 done, nil otherwise."
6206 (when (org-string-nw-p org-latex-and-related-regexp)
6207 (catch 'found
6208 (while (re-search-forward org-latex-and-related-regexp limit t)
6209 (unless
6210 (cl-some
6211 (lambda (f)
6212 (memq f '(org-code org-verbatim underline org-special-keyword)))
6213 (save-excursion
6214 (goto-char (1+ (match-beginning 0)))
6215 (face-at-point nil t)))
6216 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6217 '(?_ ?^))
6219 0)))
6220 (font-lock-prepend-text-property
6221 (+ offset (match-beginning 0)) (match-end 0)
6222 'face 'org-latex-and-related)
6223 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6224 '(font-lock-multiline t)))
6225 (throw 'found t)))
6226 nil)))
6228 (defun org-restart-font-lock ()
6229 "Restart `font-lock-mode', to force refontification."
6230 (when (and (boundp 'font-lock-mode) font-lock-mode)
6231 (font-lock-mode -1)
6232 (font-lock-mode 1)))
6234 (defun org-activate-tags (limit)
6235 (when (re-search-forward
6236 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6237 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6238 (add-text-properties (match-beginning 1) (match-end 1)
6239 (list 'mouse-face 'highlight
6240 'keymap org-mouse-map))
6241 (org-rear-nonsticky-at (match-end 1))
6244 (defun org-outline-level ()
6245 "Compute the outline level of the heading at point.
6247 If this is called at a normal headline, the level is the number
6248 of stars. Use `org-reduced-level' to remove the effect of
6249 `org-odd-levels'. Unlike to `org-current-level', this function
6250 takes into consideration inlinetasks."
6251 (org-with-wide-buffer
6252 (end-of-line)
6253 (if (re-search-backward org-outline-regexp-bol nil t)
6254 (1- (- (match-end 0) (match-beginning 0)))
6255 0)))
6257 (defvar org-font-lock-keywords nil)
6259 (defsubst org-re-property (property &optional literal allow-null value)
6260 "Return a regexp matching a PROPERTY line.
6262 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6263 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6264 non-nil, match properties even without a value.
6266 Match group 3 is set to the value when it exists. If there is no
6267 value and ALLOW-NULL is non-nil, it is set to the empty string.
6269 With optional argument VALUE, match only property lines with
6270 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6271 unless LITERAL is non-nil."
6272 (concat
6273 "^\\(?4:[ \t]*\\)"
6274 (format "\\(?1::\\(?2:%s\\):\\)"
6275 (if literal property (regexp-quote property)))
6276 (cond (value
6277 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6278 (if literal value (regexp-quote value))))
6279 (allow-null
6280 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6282 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6284 (defconst org-property-re
6285 (org-re-property "\\S-+" 'literal t)
6286 "Regular expression matching a property line.
6287 There are four matching groups:
6288 1: :PROPKEY: including the leading and trailing colon,
6289 2: PROPKEY without the leading and trailing colon,
6290 3: PROPVAL without leading or trailing spaces,
6291 4: the indentation of the current line,
6292 5: trailing whitespace.")
6294 (defvar org-font-lock-hook nil
6295 "Functions to be called for special font lock stuff.")
6297 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6299 (defvar org-font-lock-set-keywords-hook nil
6300 "Functions that can manipulate `org-font-lock-extra-keywords'.
6301 This is called after `org-font-lock-extra-keywords' is defined, but before
6302 it is installed to be used by font lock. This can be useful if something
6303 needs to be inserted at a specific position in the font-lock sequence.")
6305 (defun org-font-lock-hook (limit)
6306 "Run `org-font-lock-hook' within LIMIT."
6307 (run-hook-with-args 'org-font-lock-hook limit))
6309 (defun org-set-font-lock-defaults ()
6310 "Set font lock defaults for the current buffer."
6311 (let* ((em org-fontify-emphasized-text)
6312 (lk org-highlight-links)
6313 (org-font-lock-extra-keywords
6314 (list
6315 ;; Call the hook
6316 '(org-font-lock-hook)
6317 ;; Headlines
6318 `(,(if org-fontify-whole-heading-line
6319 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6320 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6321 (1 (org-get-level-face 1))
6322 (2 (org-get-level-face 2))
6323 (3 (org-get-level-face 3)))
6324 ;; Table lines
6325 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6326 (1 'org-table t))
6327 ;; Table internals
6328 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6329 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6330 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6331 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6332 ;; Drawers
6333 '(org-fontify-drawers)
6334 ;; Properties
6335 (list org-property-re
6336 '(1 'org-special-keyword t)
6337 '(3 'org-property-value t))
6338 ;; Link related fontification.
6339 '(org-activate-links)
6340 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6341 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6342 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6343 (when (memq 'footnote lk) '(org-activate-footnote-links))
6344 ;; Targets.
6345 (list org-any-target-regexp '(0 'org-target t))
6346 ;; Diary sexps.
6347 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6348 ;; Macro
6349 '(org-fontify-macros)
6350 '(org-hide-wide-columns (0 nil append))
6351 ;; TODO keyword
6352 (list (format org-heading-keyword-regexp-format
6353 org-todo-regexp)
6354 '(2 (org-get-todo-face 2) t))
6355 ;; DONE
6356 (if org-fontify-done-headline
6357 (list (format org-heading-keyword-regexp-format
6358 (concat
6359 "\\(?:"
6360 (mapconcat 'regexp-quote org-done-keywords "\\|")
6361 "\\)"))
6362 '(2 'org-headline-done t))
6363 nil)
6364 ;; Priorities
6365 '(org-font-lock-add-priority-faces)
6366 ;; Tags
6367 '(org-font-lock-add-tag-faces)
6368 ;; Tags groups
6369 (when (and org-group-tags org-tag-groups-alist)
6370 (list (concat org-outline-regexp-bol ".+\\(:"
6371 (regexp-opt (mapcar 'car org-tag-groups-alist))
6372 ":\\).*$")
6373 '(1 'org-tag-group prepend)))
6374 ;; Special keywords
6375 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6376 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6377 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6378 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6379 ;; Emphasis
6380 (when em '(org-do-emphasis-faces))
6381 ;; Checkboxes
6382 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6383 1 'org-checkbox prepend)
6384 (when (cdr (assq 'checkbox org-list-automatic-rules))
6385 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6386 (0 (org-get-checkbox-statistics-face) t)))
6387 ;; Description list items
6388 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6389 1 'org-list-dt prepend)
6390 ;; ARCHIVEd headings
6391 (list (concat
6392 org-outline-regexp-bol
6393 "\\(.*:" org-archive-tag ":.*\\)")
6394 '(1 'org-archived prepend))
6395 ;; Specials
6396 '(org-do-latex-and-related)
6397 '(org-fontify-entities)
6398 '(org-raise-scripts)
6399 ;; Code
6400 '(org-activate-code (1 'org-code t))
6401 ;; COMMENT
6402 (list (format
6403 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6404 org-todo-regexp
6405 org-comment-string)
6406 '(9 'org-special-keyword t))
6407 ;; Blocks and meta lines
6408 '(org-fontify-meta-lines-and-blocks))))
6409 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6410 (run-hooks 'org-font-lock-set-keywords-hook)
6411 ;; Now set the full font-lock-keywords
6412 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6413 (setq-local font-lock-defaults
6414 '(org-font-lock-keywords t nil nil backward-paragraph))
6415 (kill-local-variable 'font-lock-keywords)
6416 nil))
6418 (defun org-toggle-pretty-entities ()
6419 "Toggle the composition display of entities as UTF8 characters."
6420 (interactive)
6421 (setq-local org-pretty-entities (not org-pretty-entities))
6422 (org-restart-font-lock)
6423 (if org-pretty-entities
6424 (message "Entities are now displayed as UTF8 characters")
6425 (save-restriction
6426 (widen)
6427 (decompose-region (point-min) (point-max))
6428 (message "Entities are now displayed as plain text"))))
6430 (defvar-local org-custom-properties-overlays nil
6431 "List of overlays used for custom properties.")
6433 (defun org-toggle-custom-properties-visibility ()
6434 "Display or hide properties in `org-custom-properties'."
6435 (interactive)
6436 (if org-custom-properties-overlays
6437 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6438 (setq org-custom-properties-overlays nil))
6439 (when org-custom-properties
6440 (org-with-wide-buffer
6441 (goto-char (point-min))
6442 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6443 (while (re-search-forward regexp nil t)
6444 (let ((end (cdr (save-match-data (org-get-property-block)))))
6445 (when (and end (< (point) end))
6446 ;; Hide first custom property in current drawer.
6447 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6448 (overlay-put o 'invisible t)
6449 (overlay-put o 'org-custom-property t)
6450 (push o org-custom-properties-overlays))
6451 ;; Hide additional custom properties in the same drawer.
6452 (while (re-search-forward regexp end t)
6453 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6454 (overlay-put o 'invisible t)
6455 (overlay-put o 'org-custom-property t)
6456 (push o org-custom-properties-overlays)))))
6457 ;; Each entry is limited to a single property drawer.
6458 (outline-next-heading)))))))
6460 (defun org-fontify-entities (limit)
6461 "Find an entity to fontify."
6462 (let (ee)
6463 (when org-pretty-entities
6464 (catch 'match
6465 ;; "\_ "-family is left out on purpose. Only the first one,
6466 ;; i.e., "\_ ", could be fontified anyway, and it would be
6467 ;; confusing when adding a second white space character.
6468 (while (re-search-forward
6469 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6470 limit t)
6471 (when (and (not (org-at-comment-p))
6472 (setq ee (org-entity-get (match-string 1)))
6473 (= (length (nth 6 ee)) 1))
6474 (let* ((end (if (equal (match-string 2) "{}")
6475 (match-end 2)
6476 (match-end 1))))
6477 (add-text-properties
6478 (match-beginning 0) end
6479 (list 'font-lock-fontified t))
6480 (compose-region (match-beginning 0) end
6481 (nth 6 ee) nil)
6482 (backward-char 1)
6483 (throw 'match t))))
6484 nil))))
6486 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6487 "Fontify string S like in Org mode."
6488 (with-temp-buffer
6489 (insert s)
6490 (let ((org-odd-levels-only odd-levels))
6491 (org-mode)
6492 (org-font-lock-ensure)
6493 (buffer-string))))
6495 (defvar org-m nil)
6496 (defvar org-l nil)
6497 (defvar org-f nil)
6498 (defun org-get-level-face (n)
6499 "Get the right face for match N in font-lock matching of headlines."
6500 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6501 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6502 (if org-cycle-level-faces
6503 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6504 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6505 (cond
6506 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6507 ((eq n 2) org-f)
6508 (t (unless org-level-color-stars-only org-f))))
6510 (defun org-face-from-face-or-color (context inherit face-or-color)
6511 "Create a face list that inherits INHERIT, but sets the foreground color.
6512 When FACE-OR-COLOR is not a string, just return it."
6513 (if (stringp face-or-color)
6514 (list :inherit inherit
6515 (cdr (assoc context org-faces-easy-properties))
6516 face-or-color)
6517 face-or-color))
6519 (defun org-get-todo-face (kwd)
6520 "Get the right face for a TODO keyword KWD.
6521 If KWD is a number, get the corresponding match group."
6522 (when (numberp kwd) (setq kwd (match-string kwd)))
6523 (or (org-face-from-face-or-color
6524 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6525 (and (member kwd org-done-keywords) 'org-done)
6526 'org-todo))
6528 (defun org-get-priority-face (priority)
6529 "Get the right face for PRIORITY.
6530 PRIORITY is a character."
6531 (or (org-face-from-face-or-color
6532 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6533 'org-priority))
6535 (defun org-get-tag-face (tag)
6536 "Get the right face for TAG.
6537 If TAG is a number, get the corresponding match group."
6538 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6539 (or (org-face-from-face-or-color
6540 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6541 'org-tag)))
6543 (defun org-font-lock-add-priority-faces (limit)
6544 "Add the special priority faces."
6545 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6546 (add-text-properties
6547 (match-beginning 1) (match-end 1)
6548 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6549 'font-lock-fontified t))))
6551 (defun org-font-lock-add-tag-faces (limit)
6552 "Add the special tag faces."
6553 (when (and org-tag-faces org-tags-special-faces-re)
6554 (while (re-search-forward org-tags-special-faces-re limit t)
6555 (add-text-properties (match-beginning 1) (match-end 1)
6556 (list 'face (org-get-tag-face 1)
6557 'font-lock-fontified t))
6558 (backward-char 1))))
6560 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6561 "Remove fontification and activation overlays from links."
6562 (font-lock-default-unfontify-region beg end)
6563 (let* ((buffer-undo-list t)
6564 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6565 (inhibit-modification-hooks t)
6566 deactivate-mark buffer-file-name buffer-file-truename)
6567 (decompose-region beg end)
6568 (remove-text-properties beg end
6569 '(mouse-face t keymap t org-linked-text t
6570 invisible t intangible t
6571 org-emphasis t))
6572 (org-remove-font-lock-display-properties beg end)))
6574 (defconst org-script-display '(((raise -0.3) (height 0.7))
6575 ((raise 0.3) (height 0.7))
6576 ((raise -0.5))
6577 ((raise 0.5)))
6578 "Display properties for showing superscripts and subscripts.")
6580 (defun org-remove-font-lock-display-properties (beg end)
6581 "Remove specific display properties that have been added by font lock.
6582 The will remove the raise properties that are used to show superscripts
6583 and subscripts."
6584 (let (next prop)
6585 (while (< beg end)
6586 (setq next (next-single-property-change beg 'display nil end)
6587 prop (get-text-property beg 'display))
6588 (when (member prop org-script-display)
6589 (put-text-property beg next 'display nil))
6590 (setq beg next))))
6592 (defun org-raise-scripts (limit)
6593 "Add raise properties to sub/superscripts."
6594 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6595 (re-search-forward
6596 (if (eq org-use-sub-superscripts t)
6597 org-match-substring-regexp
6598 org-match-substring-with-braces-regexp)
6599 limit t))
6600 (let* ((pos (point)) table-p comment-p
6601 (mpos (match-beginning 3))
6602 (emph-p (get-text-property mpos 'org-emphasis))
6603 (link-p (get-text-property mpos 'mouse-face))
6604 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6605 (goto-char (point-at-bol))
6606 (setq table-p (looking-at-p org-table-dataline-regexp)
6607 comment-p (looking-at-p "^[ \t]*#[ +]"))
6608 (goto-char pos)
6609 ;; Handle a_b^c
6610 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6611 (unless (or comment-p emph-p link-p keyw-p)
6612 (put-text-property (match-beginning 3) (match-end 0)
6613 'display
6614 (if (equal (char-after (match-beginning 2)) ?^)
6615 (nth (if table-p 3 1) org-script-display)
6616 (nth (if table-p 2 0) org-script-display)))
6617 (add-text-properties (match-beginning 2) (match-end 2)
6618 (list 'invisible t))
6619 (when (and (eq (char-after (match-beginning 3)) ?{)
6620 (eq (char-before (match-end 3)) ?}))
6621 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6622 (list 'invisible t))
6623 (add-text-properties (1- (match-end 3)) (match-end 3)
6624 (list 'invisible t))))
6625 t)))
6627 ;;;; Visibility cycling, including org-goto and indirect buffer
6629 ;;; Cycling
6631 (defvar-local org-cycle-global-status nil)
6632 (put 'org-cycle-global-status 'org-state t)
6633 (defvar-local org-cycle-subtree-status nil)
6634 (put 'org-cycle-subtree-status 'org-state t)
6636 (defvar org-inlinetask-min-level)
6638 (defun org-unlogged-message (&rest args)
6639 "Display a message, but avoid logging it in the *Messages* buffer."
6640 (let ((message-log-max nil))
6641 (apply 'message args)))
6643 ;;;###autoload
6644 (defun org-cycle (&optional arg)
6645 "TAB-action and visibility cycling for Org mode.
6647 This is the command invoked in Org mode by the `TAB' key. Its main
6648 purpose is outline visibility cycling, but it also invokes other actions
6649 in special contexts.
6651 When this function is called with a `\\[universal-argument]' prefix, rotate \
6652 the entire
6653 buffer through 3 states (global cycling)
6654 1. OVERVIEW: Show only top-level headlines.
6655 2. CONTENTS: Show all headlines of all levels, but no body text.
6656 3. SHOW ALL: Show everything.
6658 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6659 switch to the startup visibility,
6660 determined by the variable `org-startup-folded', and by any VISIBILITY
6661 properties in the buffer.
6663 With a `\\[universal-argument] \\[universal-argument] \
6664 \\[universal-argument]' prefix argument, show the entire buffer, including
6665 any drawers.
6667 When inside a table, re-align the table and move to the next field.
6669 When point is at the beginning of a headline, rotate the subtree started
6670 by this line through 3 different states (local cycling)
6671 1. FOLDED: Only the main headline is shown.
6672 2. CHILDREN: The main headline and the direct children are shown.
6673 From this state, you can move to one of the children
6674 and zoom in further.
6675 3. SUBTREE: Show the entire subtree, including body text.
6676 If there is no subtree, switch directly from CHILDREN to FOLDED.
6678 When point is at the beginning of an empty headline and the variable
6679 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6680 of the headline by demoting and promoting it to likely levels. This
6681 speeds up creation document structure by pressing `TAB' once or several
6682 times right after creating a new headline.
6684 When there is a numeric prefix, go up to a heading with level ARG, do
6685 a `show-subtree' and return to the previous cursor position. If ARG
6686 is negative, go up that many levels.
6688 When point is not at the beginning of a headline, execute the global
6689 binding for `TAB', which is re-indenting the line. See the option
6690 `org-cycle-emulate-tab' for details.
6692 As a special case, if point is at the beginning of the buffer and there is
6693 no headline in line 1, this function will act as if called with prefix arg
6694 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6695 prefix arg, but only
6696 if the variable `org-cycle-global-at-bob' is t."
6697 (interactive "P")
6698 (org-load-modules-maybe)
6699 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6700 (and org-cycle-level-after-item/entry-creation
6701 (or (org-cycle-level)
6702 (org-cycle-item-indentation))))
6703 (let* ((limit-level
6704 (or org-cycle-max-level
6705 (and (boundp 'org-inlinetask-min-level)
6706 org-inlinetask-min-level
6707 (1- org-inlinetask-min-level))))
6708 (nstars (and limit-level
6709 (if org-odd-levels-only
6710 (and limit-level (1- (* limit-level 2)))
6711 limit-level)))
6712 (org-outline-regexp
6713 (if (not (derived-mode-p 'org-mode))
6714 outline-regexp
6715 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6716 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6717 (not (looking-at org-outline-regexp))))
6718 (org-cycle-hook
6719 (if bob-special
6720 (delq 'org-optimize-window-after-visibility-change
6721 (copy-sequence org-cycle-hook))
6722 org-cycle-hook))
6723 (pos (point)))
6725 (cond
6727 ((equal arg '(16))
6728 (setq last-command 'dummy)
6729 (org-set-startup-visibility)
6730 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6732 ((equal arg '(64))
6733 (outline-show-all)
6734 (org-unlogged-message "Entire buffer visible, including drawers"))
6736 ((equal arg '(4)) (org-cycle-internal-global))
6738 ;; Try hiding block at point.
6739 ((org-hide-block-toggle-maybe))
6741 ;; Try cdlatex TAB completion
6742 ((org-try-cdlatex-tab))
6744 ;; Table: enter it or move to the next field.
6745 ((org-at-table-p 'any)
6746 (if (org-at-table.el-p)
6747 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6748 Use `\\[org-edit-special]' to edit table.el tables"))
6749 (if arg (org-table-edit-field t)
6750 (org-table-justify-field-maybe)
6751 (call-interactively 'org-table-next-field))))
6753 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6755 ;; Global cycling: delegate to `org-cycle-internal-global'.
6756 (bob-special (org-cycle-internal-global))
6758 ;; Drawers: delegate to `org-flag-drawer'.
6759 ((save-excursion
6760 (beginning-of-line 1)
6761 (looking-at org-drawer-regexp))
6762 (org-flag-drawer ; toggle block visibility
6763 (not (get-char-property (match-end 0) 'invisible))))
6765 ;; Show-subtree, ARG levels up from here.
6766 ((integerp arg)
6767 (save-excursion
6768 (org-back-to-heading)
6769 (outline-up-heading (if (< arg 0) (- arg)
6770 (- (funcall outline-level) arg)))
6771 (org-show-subtree)))
6773 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6774 ((and (featurep 'org-inlinetask)
6775 (org-inlinetask-at-task-p)
6776 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6777 (org-inlinetask-toggle-visibility))
6779 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6780 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6781 (save-excursion (move-beginning-of-line 1)
6782 (looking-at org-outline-regexp)))
6783 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6784 (org-cycle-internal-local))
6786 ;; From there: TAB emulation and template completion.
6787 (buffer-read-only (org-back-to-heading))
6789 ((run-hook-with-args-until-success
6790 'org-tab-after-check-for-cycling-hook))
6792 ((org-try-structure-completion))
6794 ((run-hook-with-args-until-success
6795 'org-tab-before-tab-emulation-hook))
6797 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6798 (or (not (bolp))
6799 (not (looking-at org-outline-regexp))))
6800 (call-interactively (global-key-binding "\t")))
6802 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6803 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6804 (or (and (eq org-cycle-emulate-tab 'white)
6805 (= (match-end 0) (point-at-eol)))
6806 (and (eq org-cycle-emulate-tab 'whitestart)
6807 (>= (match-end 0) pos))))
6809 (eq org-cycle-emulate-tab t))
6810 (call-interactively (global-key-binding "\t")))
6812 (t (save-excursion
6813 (org-back-to-heading)
6814 (org-cycle)))))))
6816 (defun org-cycle-internal-global ()
6817 "Do the global cycling action."
6818 ;; Hack to avoid display of messages for .org attachments in Gnus
6819 (let ((ga (string-match "\\*fontification" (buffer-name))))
6820 (cond
6821 ((and (eq last-command this-command)
6822 (eq org-cycle-global-status 'overview))
6823 ;; We just created the overview - now do table of contents
6824 ;; This can be slow in very large buffers, so indicate action
6825 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6826 (unless ga (org-unlogged-message "CONTENTS..."))
6827 (org-content)
6828 (unless ga (org-unlogged-message "CONTENTS...done"))
6829 (setq org-cycle-global-status 'contents)
6830 (run-hook-with-args 'org-cycle-hook 'contents))
6832 ((and (eq last-command this-command)
6833 (eq org-cycle-global-status 'contents))
6834 ;; We just showed the table of contents - now show everything
6835 (run-hook-with-args 'org-pre-cycle-hook 'all)
6836 (outline-show-all)
6837 (unless ga (org-unlogged-message "SHOW ALL"))
6838 (setq org-cycle-global-status 'all)
6839 (run-hook-with-args 'org-cycle-hook 'all))
6842 ;; Default action: go to overview
6843 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6844 (org-overview)
6845 (unless ga (org-unlogged-message "OVERVIEW"))
6846 (setq org-cycle-global-status 'overview)
6847 (run-hook-with-args 'org-cycle-hook 'overview)))))
6849 (defvar org-called-with-limited-levels nil
6850 "Non-nil when `org-with-limited-levels' is currently active.")
6852 (defun org-invisible-p (&optional pos)
6853 "Non-nil if the character after POS is invisible.
6854 If POS is nil, use `point' instead."
6855 (get-char-property (or pos (point)) 'invisible))
6857 (defun org-cycle-internal-local ()
6858 "Do the local cycling action."
6859 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6860 ;; First, determine end of headline (EOH), end of subtree or item
6861 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6862 (save-excursion
6863 (if (org-at-item-p)
6864 (progn
6865 (beginning-of-line)
6866 (setq struct (org-list-struct))
6867 (setq eoh (point-at-eol))
6868 (setq eos (org-list-get-item-end-before-blank (point) struct))
6869 (setq has-children (org-list-has-child-p (point) struct)))
6870 (org-back-to-heading)
6871 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6872 (setq eos (save-excursion (org-end-of-subtree t t)
6873 (when (bolp) (backward-char)) (point)))
6874 (setq has-children
6875 (or (save-excursion
6876 (let ((level (funcall outline-level)))
6877 (outline-next-heading)
6878 (and (org-at-heading-p t)
6879 (> (funcall outline-level) level))))
6880 (save-excursion
6881 (org-list-search-forward (org-item-beginning-re) eos t)))))
6882 ;; Determine end invisible part of buffer (EOL)
6883 (beginning-of-line 2)
6884 (while (and (not (eobp)) ;This is like `next-line'.
6885 (get-char-property (1- (point)) 'invisible))
6886 (goto-char (next-single-char-property-change (point) 'invisible))
6887 (and (eolp) (beginning-of-line 2)))
6888 (setq eol (point)))
6889 ;; Find out what to do next and set `this-command'
6890 (cond
6891 ((= eos eoh)
6892 ;; Nothing is hidden behind this heading
6893 (unless (org-before-first-heading-p)
6894 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6895 (org-unlogged-message "EMPTY ENTRY")
6896 (setq org-cycle-subtree-status nil)
6897 (save-excursion
6898 (goto-char eos)
6899 (outline-next-heading)
6900 (when (org-invisible-p) (org-flag-heading nil))))
6901 ((and (or (>= eol eos)
6902 (not (string-match "\\S-" (buffer-substring eol eos))))
6903 (or has-children
6904 (not (setq children-skipped
6905 org-cycle-skip-children-state-if-no-children))))
6906 ;; Entire subtree is hidden in one line: children view
6907 (unless (org-before-first-heading-p)
6908 (run-hook-with-args 'org-pre-cycle-hook 'children))
6909 (if (org-at-item-p)
6910 (org-list-set-item-visibility (point-at-bol) struct 'children)
6911 (org-show-entry)
6912 (org-with-limited-levels (org-show-children))
6913 ;; FIXME: This slows down the func way too much.
6914 ;; How keep drawers hidden in subtree anyway?
6915 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6916 ;; (org-cycle-hide-drawers 'subtree))
6918 ;; Fold every list in subtree to top-level items.
6919 (when (eq org-cycle-include-plain-lists 'integrate)
6920 (save-excursion
6921 (org-back-to-heading)
6922 (while (org-list-search-forward (org-item-beginning-re) eos t)
6923 (beginning-of-line 1)
6924 (let* ((struct (org-list-struct))
6925 (prevs (org-list-prevs-alist struct))
6926 (end (org-list-get-bottom-point struct)))
6927 (dolist (e (org-list-get-all-items (point) struct prevs))
6928 (org-list-set-item-visibility e struct 'folded))
6929 (goto-char (if (< end eos) end eos)))))))
6930 (org-unlogged-message "CHILDREN")
6931 (save-excursion
6932 (goto-char eos)
6933 (outline-next-heading)
6934 (when (org-invisible-p) (org-flag-heading nil)))
6935 (setq org-cycle-subtree-status 'children)
6936 (unless (org-before-first-heading-p)
6937 (run-hook-with-args 'org-cycle-hook 'children)))
6938 ((or children-skipped
6939 (and (eq last-command this-command)
6940 (eq org-cycle-subtree-status 'children)))
6941 ;; We just showed the children, or no children are there,
6942 ;; now show everything.
6943 (unless (org-before-first-heading-p)
6944 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6945 (outline-flag-region eoh eos nil)
6946 (org-unlogged-message
6947 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6948 (setq org-cycle-subtree-status 'subtree)
6949 (unless (org-before-first-heading-p)
6950 (run-hook-with-args 'org-cycle-hook 'subtree)))
6952 ;; Default action: hide the subtree.
6953 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6954 (outline-flag-region eoh eos t)
6955 (org-unlogged-message "FOLDED")
6956 (setq org-cycle-subtree-status 'folded)
6957 (unless (org-before-first-heading-p)
6958 (run-hook-with-args 'org-cycle-hook 'folded))))))
6960 ;;;###autoload
6961 (defun org-global-cycle (&optional arg)
6962 "Cycle the global visibility. For details see `org-cycle'.
6963 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6964 With a numeric prefix, show all headlines up to that level."
6965 (interactive "P")
6966 (let ((org-cycle-include-plain-lists
6967 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6968 (cond
6969 ((integerp arg)
6970 (outline-show-all)
6971 (outline-hide-sublevels arg)
6972 (setq org-cycle-global-status 'contents))
6973 ((equal arg '(4))
6974 (org-set-startup-visibility)
6975 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6977 (org-cycle '(4))))))
6979 (defun org-set-startup-visibility ()
6980 "Set the visibility required by startup options and properties."
6981 (cond
6982 ((eq org-startup-folded t)
6983 (org-overview))
6984 ((eq org-startup-folded 'content)
6985 (org-content))
6986 ((or (eq org-startup-folded 'showeverything)
6987 (eq org-startup-folded nil))
6988 (outline-show-all)))
6989 (unless (eq org-startup-folded 'showeverything)
6990 (when org-hide-block-startup (org-hide-block-all))
6991 (org-set-visibility-according-to-property 'no-cleanup)
6992 (org-cycle-hide-archived-subtrees 'all)
6993 (org-cycle-hide-drawers 'all)
6994 (org-cycle-show-empty-lines t)))
6996 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6997 "Switch subtree visibilities according to :VISIBILITY: property."
6998 (interactive)
6999 (org-with-wide-buffer
7000 (goto-char (point-min))
7001 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7002 (if (not (org-at-property-p)) (outline-next-heading)
7003 (let ((state (match-string 3)))
7004 (save-excursion
7005 (org-back-to-heading t)
7006 (outline-hide-subtree)
7007 (org-reveal)
7008 (cond
7009 ((equal state "folded")
7010 (outline-hide-subtree))
7011 ((equal state "children")
7012 (org-show-hidden-entry)
7013 (org-show-children))
7014 ((equal state "content")
7015 (save-excursion
7016 (save-restriction
7017 (org-narrow-to-subtree)
7018 (org-content))))
7019 ((member state '("all" "showall"))
7020 (outline-show-subtree)))))))
7021 (unless no-cleanup
7022 (org-cycle-hide-archived-subtrees 'all)
7023 (org-cycle-hide-drawers 'all)
7024 (org-cycle-show-empty-lines 'all))))
7026 ;; This function uses outline-regexp instead of the more fundamental
7027 ;; org-outline-regexp so that org-cycle-global works outside of Org
7028 ;; buffers, where outline-regexp is needed.
7029 (defun org-overview ()
7030 "Switch to overview mode, showing only top-level headlines.
7031 This shows all headlines with a level equal or greater than the level
7032 of the first headline in the buffer. This is important, because if the
7033 first headline is not level one, then (hide-sublevels 1) gives confusing
7034 results."
7035 (interactive)
7036 (save-excursion
7037 (let ((level
7038 (save-excursion
7039 (goto-char (point-min))
7040 (when (re-search-forward (concat "^" outline-regexp) nil t)
7041 (goto-char (match-beginning 0))
7042 (funcall outline-level)))))
7043 (and level (outline-hide-sublevels level)))))
7045 (defun org-content (&optional arg)
7046 "Show all headlines in the buffer, like a table of contents.
7047 With numerical argument N, show content up to level N."
7048 (interactive "P")
7049 (org-overview)
7050 (save-excursion
7051 ;; Visit all headings and show their offspring
7052 (and (integerp arg) (org-overview))
7053 (goto-char (point-max))
7054 (catch 'exit
7055 (while (and (progn (condition-case nil
7056 (outline-previous-visible-heading 1)
7057 (error (goto-char (point-min))))
7059 (looking-at org-outline-regexp))
7060 (if (integerp arg)
7061 (org-show-children (1- arg))
7062 (outline-show-branches))
7063 (when (bobp) (throw 'exit nil))))))
7065 (defun org-optimize-window-after-visibility-change (state)
7066 "Adjust the window after a change in outline visibility.
7067 This function is the default value of the hook `org-cycle-hook'."
7068 (when (get-buffer-window (current-buffer))
7069 (cond
7070 ((eq state 'content) nil)
7071 ((eq state 'all) nil)
7072 ((eq state 'folded) nil)
7073 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7074 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7076 (defun org-remove-empty-overlays-at (pos)
7077 "Remove outline overlays that do not contain non-white stuff."
7078 (dolist (o (overlays-at pos))
7079 (and (eq 'outline (overlay-get o 'invisible))
7080 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7081 (overlay-end o))))
7082 (delete-overlay o))))
7084 (defun org-clean-visibility-after-subtree-move ()
7085 "Fix visibility issues after moving a subtree."
7086 ;; First, find a reasonable region to look at:
7087 ;; Start two siblings above, end three below
7088 (let* ((beg (save-excursion
7089 (and (org-get-last-sibling)
7090 (org-get-last-sibling))
7091 (point)))
7092 (end (save-excursion
7093 (and (org-get-next-sibling)
7094 (org-get-next-sibling)
7095 (org-get-next-sibling))
7096 (if (org-at-heading-p)
7097 (point-at-eol)
7098 (point))))
7099 (level (looking-at "\\*+"))
7100 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7101 (save-excursion
7102 (save-restriction
7103 (narrow-to-region beg end)
7104 (when re
7105 ;; Properly fold already folded siblings
7106 (goto-char (point-min))
7107 (while (re-search-forward re nil t)
7108 (when (and (not (org-invisible-p))
7109 (save-excursion
7110 (goto-char (point-at-eol)) (org-invisible-p)))
7111 (outline-hide-entry))))
7112 (org-cycle-show-empty-lines 'overview)
7113 (org-cycle-hide-drawers 'overview)))))
7115 (defun org-cycle-show-empty-lines (state)
7116 "Show empty lines above all visible headlines.
7117 The region to be covered depends on STATE when called through
7118 `org-cycle-hook'. Lisp program can use t for STATE to get the
7119 entire buffer covered. Note that an empty line is only shown if there
7120 are at least `org-cycle-separator-lines' empty lines before the headline."
7121 (when (/= org-cycle-separator-lines 0)
7122 (save-excursion
7123 (let* ((n (abs org-cycle-separator-lines))
7124 (re (cond
7125 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7126 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7127 (t (let ((ns (number-to-string (- n 2))))
7128 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7129 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7130 beg end)
7131 (cond
7132 ((memq state '(overview contents t))
7133 (setq beg (point-min) end (point-max)))
7134 ((memq state '(children folded))
7135 (setq beg (point)
7136 end (progn (org-end-of-subtree t t)
7137 (line-beginning-position 2)))))
7138 (when beg
7139 (goto-char beg)
7140 (while (re-search-forward re end t)
7141 (unless (get-char-property (match-end 1) 'invisible)
7142 (let ((e (match-end 1))
7143 (b (if (>= org-cycle-separator-lines 0)
7144 (match-beginning 1)
7145 (save-excursion
7146 (goto-char (match-beginning 0))
7147 (skip-chars-backward " \t\n")
7148 (line-end-position)))))
7149 (outline-flag-region b e nil))))))))
7150 ;; Never hide empty lines at the end of the file.
7151 (save-excursion
7152 (goto-char (point-max))
7153 (outline-previous-heading)
7154 (outline-end-of-heading)
7155 (when (and (looking-at "[ \t\n]+")
7156 (= (match-end 0) (point-max)))
7157 (outline-flag-region (point) (match-end 0) nil))))
7159 (defun org-show-empty-lines-in-parent ()
7160 "Move to the parent and re-show empty lines before visible headlines."
7161 (save-excursion
7162 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7163 (org-cycle-show-empty-lines context))))
7165 (defun org-files-list ()
7166 "Return `org-agenda-files' list, plus all open Org files.
7167 This is useful for operations that need to scan all of a user's
7168 open and agenda-wise Org files."
7169 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7170 (dolist (buf (buffer-list))
7171 (with-current-buffer buf
7172 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7173 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7174 files))
7176 (defsubst org-entry-beginning-position ()
7177 "Return the beginning position of the current entry."
7178 (save-excursion (org-back-to-heading t) (point)))
7180 (defsubst org-entry-end-position ()
7181 "Return the end position of the current entry."
7182 (save-excursion (outline-next-heading) (point)))
7184 (defun org-cycle-hide-drawers (state &optional exceptions)
7185 "Re-hide all drawers after a visibility state change.
7186 STATE should be one of the symbols listed in the docstring of
7187 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7188 a list of strings specifying which drawers should not be hidden."
7189 (when (and (derived-mode-p 'org-mode)
7190 (not (memq state '(overview folded contents))))
7191 (save-excursion
7192 (let* ((globalp (eq state 'all))
7193 (beg (if globalp (point-min) (point)))
7194 (end (if globalp (point-max)
7195 (if (eq state 'children)
7196 (save-excursion (outline-next-heading) (point))
7197 (org-end-of-subtree t)))))
7198 (goto-char beg)
7199 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7200 (unless (member-ignore-case (match-string 1) exceptions)
7201 (let ((drawer (org-element-at-point)))
7202 (when (memq (org-element-type drawer) '(drawer property-drawer))
7203 (org-flag-drawer t drawer)
7204 ;; Make sure to skip drawer entirely or we might flag
7205 ;; it another time when matching its ending line with
7206 ;; `org-drawer-regexp'.
7207 (goto-char (org-element-property :end drawer))))))))))
7209 (defun org-flag-drawer (flag &optional element)
7210 "When FLAG is non-nil, hide the drawer we are at.
7211 Otherwise make it visible. When optional argument ELEMENT is
7212 a parsed drawer, as returned by `org-element-at-point', hide or
7213 show that drawer instead."
7214 (let ((drawer (or element
7215 (and (save-excursion
7216 (beginning-of-line)
7217 (looking-at-p org-drawer-regexp))
7218 (org-element-at-point)))))
7219 (when (memq (org-element-type drawer) '(drawer property-drawer))
7220 (let ((post (org-element-property :post-affiliated drawer)))
7221 (save-excursion
7222 (outline-flag-region
7223 (progn (goto-char post) (line-end-position))
7224 (progn (goto-char (org-element-property :end drawer))
7225 (skip-chars-backward " \r\t\n")
7226 (line-end-position))
7227 flag))
7228 ;; When the drawer is hidden away, make sure point lies in
7229 ;; a visible part of the buffer.
7230 (when (and flag (> (line-beginning-position) post))
7231 (goto-char post))))))
7233 (defun org-subtree-end-visible-p ()
7234 "Is the end of the current subtree visible?"
7235 (pos-visible-in-window-p
7236 (save-excursion (org-end-of-subtree t) (point))))
7238 (defun org-first-headline-recenter ()
7239 "Move cursor to the first headline and recenter the headline."
7240 (let ((window (get-buffer-window)))
7241 (when window
7242 (goto-char (point-min))
7243 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7244 (set-window-start window (line-beginning-position))))))
7246 ;;; Saving and restoring visibility
7248 (defun org-outline-overlay-data (&optional use-markers)
7249 "Return a list of the locations of all outline overlays.
7250 These are overlays with the `invisible' property value `outline'.
7251 The return value is a list of cons cells, with start and stop
7252 positions for each overlay.
7253 If USE-MARKERS is set, return the positions as markers."
7254 (let (beg end)
7255 (org-with-wide-buffer
7256 (delq nil
7257 (mapcar (lambda (o)
7258 (when (eq (overlay-get o 'invisible) 'outline)
7259 (setq beg (overlay-start o)
7260 end (overlay-end o))
7261 (and beg end (> end beg)
7262 (if use-markers
7263 (cons (copy-marker beg)
7264 (copy-marker end t))
7265 (cons beg end)))))
7266 (overlays-in (point-min) (point-max)))))))
7268 (defun org-set-outline-overlay-data (data)
7269 "Create visibility overlays for all positions in DATA.
7270 DATA should have been made by `org-outline-overlay-data'."
7271 (org-with-wide-buffer
7272 (outline-show-all)
7273 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7275 ;;; Folding of blocks
7277 (defvar-local org-hide-block-overlays nil
7278 "Overlays hiding blocks.")
7280 (defun org-block-map (function &optional start end)
7281 "Call FUNCTION at the head of all source blocks in the current buffer.
7282 Optional arguments START and END can be used to limit the range."
7283 (let ((start (or start (point-min)))
7284 (end (or end (point-max))))
7285 (save-excursion
7286 (goto-char start)
7287 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7288 (save-excursion
7289 (save-match-data
7290 (goto-char (match-beginning 0))
7291 (funcall function)))))))
7293 (defun org-hide-block-toggle-all ()
7294 "Toggle the visibility of all blocks in the current buffer."
7295 (org-block-map 'org-hide-block-toggle))
7297 (defun org-hide-block-all ()
7298 "Fold all blocks in the current buffer."
7299 (interactive)
7300 (org-show-block-all)
7301 (org-block-map 'org-hide-block-toggle-maybe))
7303 (defun org-show-block-all ()
7304 "Unfold all blocks in the current buffer."
7305 (interactive)
7306 (mapc #'delete-overlay org-hide-block-overlays)
7307 (setq org-hide-block-overlays nil))
7309 (defun org-hide-block-toggle-maybe ()
7310 "Toggle visibility of block at point.
7311 Unlike to `org-hide-block-toggle', this function does not throw
7312 an error. Return a non-nil value when toggling is successful."
7313 (interactive)
7314 (ignore-errors (org-hide-block-toggle)))
7316 (defun org-hide-block-toggle (&optional force)
7317 "Toggle the visibility of the current block.
7318 When optional argument FORCE is `off', make block visible. If it
7319 is non-nil, hide it unconditionally. Throw an error when not at
7320 a block. Return a non-nil value when toggling is successful."
7321 (interactive)
7322 (let ((element (org-element-at-point)))
7323 (unless (memq (org-element-type element)
7324 '(center-block comment-block dynamic-block example-block
7325 export-block quote-block special-block
7326 src-block verse-block))
7327 (user-error "Not at a block"))
7328 (let* ((start (save-excursion
7329 (goto-char (org-element-property :post-affiliated element))
7330 (line-end-position)))
7331 (end (save-excursion
7332 (goto-char (org-element-property :end element))
7333 (skip-chars-backward " \r\t\n")
7334 (line-end-position)))
7335 (overlays (overlays-at start)))
7336 (cond
7337 ;; Do nothing when not before or at the block opening line or
7338 ;; at the block closing line.
7339 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7340 ((and (not (eq force 'off))
7341 (not (memq t (mapcar
7342 (lambda (o)
7343 (eq (overlay-get o 'invisible) 'org-hide-block))
7344 overlays))))
7345 (let ((ov (make-overlay start end)))
7346 (overlay-put ov 'invisible 'org-hide-block)
7347 ;; Make the block accessible to `isearch'.
7348 (overlay-put
7349 ov 'isearch-open-invisible
7350 (lambda (ov)
7351 (when (memq ov org-hide-block-overlays)
7352 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7353 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7354 (delete-overlay ov))))
7355 (push ov org-hide-block-overlays)
7356 ;; When the block is hidden away, make sure point is left in
7357 ;; a visible part of the buffer.
7358 (when (> (line-beginning-position) start)
7359 (goto-char start)
7360 (beginning-of-line))
7361 ;; Signal successful toggling.
7363 ((or (not force) (eq force 'off))
7364 (dolist (ov overlays t)
7365 (when (memq ov org-hide-block-overlays)
7366 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7367 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7368 (delete-overlay ov))))))))
7370 ;; Remove overlays when changing major mode
7371 (add-hook 'org-mode-hook
7372 (lambda () (add-hook 'change-major-mode-hook
7373 'org-show-block-all 'append 'local)))
7375 ;;; Org-goto
7377 (defvar org-goto-window-configuration nil)
7378 (defvar org-goto-marker nil)
7379 (defvar org-goto-map)
7380 (defun org-goto-map ()
7381 "Set the keymap `org-goto'."
7382 (setq org-goto-map
7383 (let ((map (make-sparse-keymap)))
7384 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7385 mouse-drag-region universal-argument org-occur)))
7386 (dolist (cmd cmds)
7387 (substitute-key-definition cmd cmd map global-map)))
7388 (suppress-keymap map)
7389 (org-defkey map "\C-m" 'org-goto-ret)
7390 (org-defkey map [(return)] 'org-goto-ret)
7391 (org-defkey map [(left)] 'org-goto-left)
7392 (org-defkey map [(right)] 'org-goto-right)
7393 (org-defkey map [(control ?g)] 'org-goto-quit)
7394 (org-defkey map "\C-i" 'org-cycle)
7395 (org-defkey map [(tab)] 'org-cycle)
7396 (org-defkey map [(down)] 'outline-next-visible-heading)
7397 (org-defkey map [(up)] 'outline-previous-visible-heading)
7398 (if org-goto-auto-isearch
7399 (if (fboundp 'define-key-after)
7400 (define-key-after map [t] 'org-goto-local-auto-isearch)
7401 nil)
7402 (org-defkey map "q" 'org-goto-quit)
7403 (org-defkey map "n" 'outline-next-visible-heading)
7404 (org-defkey map "p" 'outline-previous-visible-heading)
7405 (org-defkey map "f" 'outline-forward-same-level)
7406 (org-defkey map "b" 'outline-backward-same-level)
7407 (org-defkey map "u" 'outline-up-heading))
7408 (org-defkey map "/" 'org-occur)
7409 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7410 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7411 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7412 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7413 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7414 map)))
7416 (defconst org-goto-help
7417 "Browse buffer copy, to find location or copy text.%s
7418 RET=jump to location C-g=quit and return to previous location
7419 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7421 (defvar org-goto-start-pos) ; dynamically scoped parameter
7423 (defun org-goto (&optional alternative-interface)
7424 "Look up a different location in the current file, keeping current visibility.
7426 When you want look-up or go to a different location in a
7427 document, the fastest way is often to fold the entire buffer and
7428 then dive into the tree. This method has the disadvantage, that
7429 the previous location will be folded, which may not be what you
7430 want.
7432 This command works around this by showing a copy of the current
7433 buffer in an indirect buffer, in overview mode. You can dive
7434 into the tree in that copy, use org-occur and incremental search
7435 to find a location. When pressing RET or `Q', the command
7436 returns to the original buffer in which the visibility is still
7437 unchanged. After RET it will also jump to the location selected
7438 in the indirect buffer and expose the headline hierarchy above.
7440 With a prefix argument, use the alternative interface: e.g., if
7441 `org-goto-interface' is `outline' use `outline-path-completion'."
7442 (interactive "P")
7443 (org-goto-map)
7444 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7445 (org-refile-use-outline-path t)
7446 (org-refile-target-verify-function nil)
7447 (interface
7448 (if (not alternative-interface)
7449 org-goto-interface
7450 (if (eq org-goto-interface 'outline)
7451 'outline-path-completion
7452 'outline)))
7453 (org-goto-start-pos (point))
7454 (selected-point
7455 (if (eq interface 'outline)
7456 (car (org-get-location (current-buffer) org-goto-help))
7457 (let ((pa (org-refile-get-location "Goto")))
7458 (org-refile-check-position pa)
7459 (nth 3 pa)))))
7460 (if selected-point
7461 (progn
7462 (org-mark-ring-push org-goto-start-pos)
7463 (goto-char selected-point)
7464 (when (or (org-invisible-p) (org-invisible-p2))
7465 (org-show-context 'org-goto)))
7466 (message "Quit"))))
7468 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7469 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7470 (defvar org-goto-local-auto-isearch-map) ; defined below
7472 (defun org-get-location (_buf help)
7473 "Let the user select a location in current buffer.
7474 This function uses a recursive edit. It returns the selected position
7475 or nil."
7476 (org-no-popups
7477 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7478 (isearch-hide-immediately nil)
7479 (isearch-search-fun-function
7480 (lambda () 'org-goto-local-search-headings))
7481 (org-goto-selected-point org-goto-exit-command))
7482 (save-excursion
7483 (save-window-excursion
7484 (delete-other-windows)
7485 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7486 (pop-to-buffer-same-window
7487 (condition-case nil
7488 (make-indirect-buffer (current-buffer) "*org-goto*")
7489 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7490 (with-output-to-temp-buffer "*Org Help*"
7491 (princ (format help (if org-goto-auto-isearch
7492 " Just type for auto-isearch."
7493 " n/p/f/b/u to navigate, q to quit."))))
7494 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7495 (setq buffer-read-only nil)
7496 (let ((org-startup-truncated t)
7497 (org-startup-folded nil)
7498 (org-startup-align-all-tables nil))
7499 (org-mode)
7500 (org-overview))
7501 (setq buffer-read-only t)
7502 (if (and (boundp 'org-goto-start-pos)
7503 (integer-or-marker-p org-goto-start-pos))
7504 (progn (goto-char org-goto-start-pos)
7505 (when (org-invisible-p)
7506 (org-show-set-visibility 'lineage)))
7507 (goto-char (point-min)))
7508 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7509 (message "Select location and press RET")
7510 (use-local-map org-goto-map)
7511 (recursive-edit)))
7512 (kill-buffer "*org-goto*")
7513 (cons org-goto-selected-point org-goto-exit-command))))
7515 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7516 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7517 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7518 (if (fboundp 'isearch-other-control-char)
7519 (progn
7520 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7521 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7522 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7523 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7524 (define-key org-goto-local-auto-isearch-map [return] nil))
7526 (defun org-goto-local-search-headings (string bound noerror)
7527 "Search and make sure that any matches are in headlines."
7528 (catch 'return
7529 (while (if isearch-forward
7530 (search-forward string bound noerror)
7531 (search-backward string bound noerror))
7532 (when (save-match-data
7533 (and (save-excursion
7534 (beginning-of-line)
7535 (looking-at org-complex-heading-regexp))
7536 (or (not (match-beginning 5))
7537 (< (point) (match-beginning 5)))))
7538 (throw 'return (point))))))
7540 (defun org-goto-local-auto-isearch ()
7541 "Start isearch."
7542 (interactive)
7543 (goto-char (point-min))
7544 (let ((keys (this-command-keys)))
7545 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7546 (isearch-mode t)
7547 (isearch-process-search-char (string-to-char keys)))))
7549 (defun org-goto-ret (&optional _arg)
7550 "Finish `org-goto' by going to the new location."
7551 (interactive "P")
7552 (setq org-goto-selected-point (point))
7553 (setq org-goto-exit-command 'return)
7554 (throw 'exit nil))
7556 (defun org-goto-left ()
7557 "Finish `org-goto' by going to the new location."
7558 (interactive)
7559 (if (org-at-heading-p)
7560 (progn
7561 (beginning-of-line 1)
7562 (setq org-goto-selected-point (point)
7563 org-goto-exit-command 'left)
7564 (throw 'exit nil))
7565 (user-error "Not on a heading")))
7567 (defun org-goto-right ()
7568 "Finish `org-goto' by going to the new location."
7569 (interactive)
7570 (if (org-at-heading-p)
7571 (progn
7572 (setq org-goto-selected-point (point)
7573 org-goto-exit-command 'right)
7574 (throw 'exit nil))
7575 (user-error "Not on a heading")))
7577 (defun org-goto-quit ()
7578 "Finish `org-goto' without cursor motion."
7579 (interactive)
7580 (setq org-goto-selected-point nil)
7581 (setq org-goto-exit-command 'quit)
7582 (throw 'exit nil))
7584 ;;; Indirect buffer display of subtrees
7586 (defvar org-indirect-dedicated-frame nil
7587 "This is the frame being used for indirect tree display.")
7588 (defvar org-last-indirect-buffer nil)
7590 (defun org-tree-to-indirect-buffer (&optional arg)
7591 "Create indirect buffer and narrow it to current subtree.
7593 With a numerical prefix ARG, go up to this level and then take that tree.
7594 If ARG is negative, go up that many levels.
7596 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7597 indirect buffer previously made with this command, to avoid proliferation of
7598 indirect buffers. However, when you call the command with a \
7599 `\\[universal-argument]' prefix, or
7600 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7601 so that you can work with several indirect buffers at the same time. If
7602 `org-indirect-buffer-display' is `dedicated-frame', the \
7603 `\\[universal-argument]' prefix also
7604 requests that a new frame be made for the new buffer, so that the dedicated
7605 frame is not changed."
7606 (interactive "P")
7607 (let ((cbuf (current-buffer))
7608 (cwin (selected-window))
7609 (pos (point))
7610 beg end level heading ibuf)
7611 (save-excursion
7612 (org-back-to-heading t)
7613 (when (numberp arg)
7614 (setq level (org-outline-level))
7615 (when (< arg 0) (setq arg (+ level arg)))
7616 (while (> (setq level (org-outline-level)) arg)
7617 (org-up-heading-safe)))
7618 (setq beg (point)
7619 heading (org-get-heading 'no-tags))
7620 (org-end-of-subtree t t)
7621 (when (org-at-heading-p) (backward-char 1))
7622 (setq end (point)))
7623 (when (and (buffer-live-p org-last-indirect-buffer)
7624 (not (eq org-indirect-buffer-display 'new-frame))
7625 (not arg))
7626 (kill-buffer org-last-indirect-buffer))
7627 (setq ibuf (org-get-indirect-buffer cbuf heading)
7628 org-last-indirect-buffer ibuf)
7629 (cond
7630 ((or (eq org-indirect-buffer-display 'new-frame)
7631 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7632 (select-frame (make-frame))
7633 (delete-other-windows)
7634 (pop-to-buffer-same-window ibuf)
7635 (org-set-frame-title heading))
7636 ((eq org-indirect-buffer-display 'dedicated-frame)
7637 (raise-frame
7638 (select-frame (or (and org-indirect-dedicated-frame
7639 (frame-live-p org-indirect-dedicated-frame)
7640 org-indirect-dedicated-frame)
7641 (setq org-indirect-dedicated-frame (make-frame)))))
7642 (delete-other-windows)
7643 (pop-to-buffer-same-window ibuf)
7644 (org-set-frame-title (concat "Indirect: " heading)))
7645 ((eq org-indirect-buffer-display 'current-window)
7646 (pop-to-buffer-same-window ibuf))
7647 ((eq org-indirect-buffer-display 'other-window)
7648 (pop-to-buffer ibuf))
7649 (t (error "Invalid value")))
7650 (narrow-to-region beg end)
7651 (outline-show-all)
7652 (goto-char pos)
7653 (run-hook-with-args 'org-cycle-hook 'all)
7654 (and (window-live-p cwin) (select-window cwin))))
7656 (defun org-get-indirect-buffer (&optional buffer heading)
7657 (setq buffer (or buffer (current-buffer)))
7658 (let ((n 1) (base (buffer-name buffer)) bname)
7659 (while (buffer-live-p
7660 (get-buffer
7661 (setq bname
7662 (concat base "-"
7663 (if heading (concat heading "-" (number-to-string n))
7664 (number-to-string n))))))
7665 (setq n (1+ n)))
7666 (condition-case nil
7667 (make-indirect-buffer buffer bname 'clone)
7668 (error (make-indirect-buffer buffer bname)))))
7670 (defun org-set-frame-title (title)
7671 "Set the title of the current frame to the string TITLE."
7672 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7674 ;;;; Structure editing
7676 ;;; Inserting headlines
7678 (defun org--line-empty-p (n)
7679 "Is the Nth next line empty?
7681 Counts the current line as N = 1 and the previous line as N = 0;
7682 see `beginning-of-line'."
7683 (save-excursion
7684 (and (not (bobp))
7685 (or (beginning-of-line n) t)
7686 (save-match-data
7687 (looking-at "[ \t]*$")))))
7689 (defun org-previous-line-empty-p ()
7690 "Is the previous line a blank line?
7691 When NEXT is non-nil, check the next line instead."
7692 (org--line-empty-p 0))
7694 (defun org-next-line-empty-p ()
7695 "Is the previous line a blank line?
7696 When NEXT is non-nil, check the next line instead."
7697 (org--line-empty-p 2))
7699 (defun org--blank-before-heading-p (&optional parent)
7700 "Non-nil when an empty line should precede a new heading here.
7701 When optional argument PARENT is non-nil, consider parent
7702 headline instead of current one."
7703 (pcase (assq 'heading org-blank-before-new-entry)
7704 (`(heading . auto)
7705 (save-excursion
7706 (org-with-limited-levels
7707 (unless (and (org-before-first-heading-p)
7708 (not (outline-next-heading)))
7709 (org-back-to-heading t)
7710 (when parent (org-up-heading-safe))
7711 (cond ((not (bobp))
7712 (org-previous-line-empty-p))
7713 ((outline-next-heading)
7714 (org-previous-line-empty-p))
7715 ;; Ignore trailing spaces on last buffer line.
7716 ((progn (skip-chars-backward " \t") (bolp))
7717 (org-previous-line-empty-p))
7718 (t nil))))))
7719 (`(heading . ,value) value)
7720 (_ nil)))
7722 (defun org-insert-heading (&optional arg invisible-ok top)
7723 "Insert a new heading or an item with the same depth at point.
7725 If point is at the beginning of a heading, insert a new heading
7726 or a new headline above the current one. When at the beginning
7727 of a regular line of text, turn it into a heading.
7729 If point is in the middle of a line, split it and create a new
7730 headline with the text in the current line after point (see
7731 `org-M-RET-may-split-line' on how to modify this behavior). As
7732 a special case, on a headline, splitting can only happen on the
7733 title itself. E.g., this excludes breaking stars or tags.
7735 With a `\\[universal-argument]' prefix, set \
7736 `org-insert-heading-respect-content' to
7737 a non-nil value for the duration of the command. This forces the
7738 insertion of a heading after the current subtree, independently
7739 on the location of point.
7741 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7742 insert the heading at the end of the tree
7743 above the current heading. For example, if point is within a
7744 2nd-level heading, then it will insert a 2nd-level heading at
7745 the end of the 1st-level parent subtree.
7747 When INVISIBLE-OK is set, stop at invisible headlines when going
7748 back. This is important for non-interactive uses of the
7749 command.
7751 When optional argument TOP is non-nil, insert a level 1 heading,
7752 unconditionally."
7753 (interactive "P")
7754 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7755 (level (org-current-level))
7756 (stars (make-string (if (and level (not top)) level 1) ?*)))
7757 (cond
7758 ((or org-insert-heading-respect-content
7759 (member arg '((4) (16)))
7760 (and (not invisible-ok)
7761 (invisible-p (max (1- (point)) (point-min)))))
7762 ;; Position point at the location of insertion.
7763 (if (not level) ;before first headline
7764 (org-with-limited-levels (outline-next-heading))
7765 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7766 ;; is nil.
7767 (org-with-limited-levels (org-back-to-heading invisible-ok))
7768 (cond ((equal arg '(16))
7769 (org-up-heading-safe)
7770 (org-end-of-subtree t t))
7772 (org-end-of-subtree t t))))
7773 (unless (bolp) (insert "\n")) ;ensure final newline
7774 (unless (and blank? (org-previous-line-empty-p))
7775 (org-N-empty-lines-before-current (if blank? 1 0)))
7776 (insert stars " \n")
7777 (forward-char -1))
7778 ;; At a headline...
7779 ((org-at-heading-p)
7780 (cond ((bolp)
7781 (when blank? (save-excursion (insert "\n")))
7782 (save-excursion (insert stars " \n"))
7783 (unless (and blank? (org-previous-line-empty-p))
7784 (org-N-empty-lines-before-current (if blank? 1 0)))
7785 (end-of-line))
7786 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7787 (org-match-line org-complex-heading-regexp)
7788 (org-pos-in-match-range (point) 4))
7789 ;; Grab the text that should moved to the new headline.
7790 ;; Preserve tags.
7791 (let ((split (delete-and-extract-region (point) (match-end 4))))
7792 (if (looking-at "[ \t]*$") (replace-match "")
7793 (org-set-tags nil t))
7794 (end-of-line)
7795 (when blank? (insert "\n"))
7796 (insert "\n" stars " ")
7797 (when (org-string-nw-p split) (insert split))
7798 (when (eobp) (save-excursion (insert "\n")))))
7800 (end-of-line)
7801 (when blank? (insert "\n"))
7802 (insert "\n" stars " ")
7803 (when (eobp) (save-excursion (insert "\n"))))))
7804 ;; On regular text, turn line into a headline or split, if
7805 ;; appropriate.
7806 ((bolp)
7807 (insert stars " ")
7808 (unless (and blank? (org-previous-line-empty-p))
7809 (org-N-empty-lines-before-current (if blank? 1 0))))
7811 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7812 (end-of-line))
7813 (insert "\n" stars " ")
7814 (unless (and blank? (org-previous-line-empty-p))
7815 (org-N-empty-lines-before-current (if blank? 1 0))))))
7816 (run-hooks 'org-insert-heading-hook))
7818 (defun org-N-empty-lines-before-current (n)
7819 "Make the number of empty lines before current exactly N.
7820 So this will delete or add empty lines."
7821 (let ((column (current-column)))
7822 (beginning-of-line)
7823 (unless (bobp)
7824 (let ((start (save-excursion
7825 (skip-chars-backward " \r\t\n")
7826 (line-end-position))))
7827 (delete-region start (line-end-position 0))))
7828 (insert (make-string n ?\n))
7829 (move-to-column column)))
7831 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7832 "Return the heading of the current entry, without the stars.
7833 When NO-TAGS is non-nil, don't include tags.
7834 When NO-TODO is non-nil, don't include TODO keywords.
7835 When NO-PRIORITY is non-nil, don't include priority cookie.
7836 When NO-COMMENT is non-nil, don't include COMMENT string."
7837 (save-excursion
7838 (org-back-to-heading t)
7839 (let ((case-fold-search nil))
7840 (looking-at org-complex-heading-regexp)
7841 (let ((todo (and (not no-todo) (match-string 2)))
7842 (priority (and (not no-priority) (match-string 3)))
7843 (headline (pcase (match-string 4)
7844 (`nil "")
7845 ((and (guard no-comment) h)
7846 (replace-regexp-in-string
7847 (eval-when-compile
7848 (format "\\`%s[ \t]+" org-comment-string))
7849 "" h))
7850 (h h)))
7851 (tags (and (not no-tags) (match-string 5))))
7852 (mapconcat #'identity
7853 (delq nil (list todo priority headline tags))
7854 " ")))))
7856 (defvar orgstruct-mode) ; defined below
7858 (defun org-heading-components ()
7859 "Return the components of the current heading.
7860 This is a list with the following elements:
7861 - the level as an integer
7862 - the reduced level, different if `org-odd-levels-only' is set.
7863 - the TODO keyword, or nil
7864 - the priority character, like ?A, or nil if no priority is given
7865 - the headline text itself, or the tags string if no headline text
7866 - the tags string, or nil."
7867 (save-excursion
7868 (org-back-to-heading t)
7869 (when (let (case-fold-search)
7870 (looking-at
7871 (if orgstruct-mode
7872 org-heading-regexp
7873 org-complex-heading-regexp)))
7874 (if orgstruct-mode
7875 (list (length (match-string 1))
7876 (org-reduced-level (length (match-string 1)))
7879 (match-string 2)
7880 nil)
7881 (list (length (match-string 1))
7882 (org-reduced-level (length (match-string 1)))
7883 (match-string-no-properties 2)
7884 (and (match-end 3) (aref (match-string 3) 2))
7885 (match-string-no-properties 4)
7886 (match-string-no-properties 5))))))
7888 (defun org-get-entry ()
7889 "Get the entry text, after heading, entire subtree."
7890 (save-excursion
7891 (org-back-to-heading t)
7892 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7894 (defun org-edit-headline (&optional heading)
7895 "Edit the current headline.
7896 Set it to HEADING when provided."
7897 (interactive)
7898 (org-with-wide-buffer
7899 (org-back-to-heading t)
7900 (let ((case-fold-search nil))
7901 (when (looking-at org-complex-heading-regexp)
7902 (let* ((old (match-string-no-properties 4))
7903 (new (save-match-data
7904 (org-trim (or heading (read-string "Edit: " old))))))
7905 (unless (equal old new)
7906 (if old (replace-match new t t nil 4)
7907 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7908 (insert " " new))
7909 (org-set-tags nil t)
7910 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7912 (defun org-insert-heading-after-current ()
7913 "Insert a new heading with same level as current, after current subtree."
7914 (interactive)
7915 (org-back-to-heading)
7916 (org-insert-heading)
7917 (org-move-subtree-down)
7918 (end-of-line 1))
7920 (defun org-insert-heading-respect-content (&optional invisible-ok)
7921 "Insert heading with `org-insert-heading-respect-content' set to t."
7922 (interactive)
7923 (org-insert-heading '(4) invisible-ok))
7925 (defun org-insert-todo-heading-respect-content (&optional force-state)
7926 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7927 (interactive)
7928 (org-insert-todo-heading force-state '(4)))
7930 (defun org-insert-todo-heading (arg &optional force-heading)
7931 "Insert a new heading with the same level and TODO state as current heading.
7933 If the heading has no TODO state, or if the state is DONE, use
7934 the first state (TODO by default). Also with one prefix arg,
7935 force first state. With two prefix args, force inserting at the
7936 end of the parent subtree.
7938 When called at a plain list item, insert a new item with an
7939 unchecked check box."
7940 (interactive "P")
7941 (when (or force-heading (not (org-insert-item 'checkbox)))
7942 (org-insert-heading (or (and (equal arg '(16)) '(16))
7943 force-heading))
7944 (save-excursion
7945 (org-back-to-heading)
7946 (outline-previous-heading)
7947 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7948 (let* ((new-mark-x
7949 (if (or (equal arg '(4))
7950 (not (match-beginning 2))
7951 (member (match-string 2) org-done-keywords))
7952 (car org-todo-keywords-1)
7953 (match-string 2)))
7954 (new-mark
7956 (run-hook-with-args-until-success
7957 'org-todo-get-default-hook new-mark-x nil)
7958 new-mark-x)))
7959 (beginning-of-line 1)
7960 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7961 (if org-treat-insert-todo-heading-as-state-change
7962 (org-todo new-mark)
7963 (insert new-mark " "))))
7964 (when org-provide-todo-statistics
7965 (org-update-parent-todo-statistics))))
7967 (defun org-insert-subheading (arg)
7968 "Insert a new subheading and demote it.
7969 Works for outline headings and for plain lists alike."
7970 (interactive "P")
7971 (org-insert-heading arg)
7972 (cond
7973 ((org-at-heading-p) (org-do-demote))
7974 ((org-at-item-p) (org-indent-item))))
7976 (defun org-insert-todo-subheading (arg)
7977 "Insert a new subheading with TODO keyword or checkbox and demote it.
7978 Works for outline headings and for plain lists alike."
7979 (interactive "P")
7980 (org-insert-todo-heading arg)
7981 (cond
7982 ((org-at-heading-p) (org-do-demote))
7983 ((org-at-item-p) (org-indent-item))))
7985 ;;; Promotion and Demotion
7987 (defvar org-after-demote-entry-hook nil
7988 "Hook run after an entry has been demoted.
7989 The cursor will be at the beginning of the entry.
7990 When a subtree is being demoted, the hook will be called for each node.")
7992 (defvar org-after-promote-entry-hook nil
7993 "Hook run after an entry has been promoted.
7994 The cursor will be at the beginning of the entry.
7995 When a subtree is being promoted, the hook will be called for each node.")
7997 (defun org-promote-subtree ()
7998 "Promote the entire subtree.
7999 See also `org-promote'."
8000 (interactive)
8001 (save-excursion
8002 (org-with-limited-levels (org-map-tree 'org-promote)))
8003 (org-fix-position-after-promote))
8005 (defun org-demote-subtree ()
8006 "Demote the entire subtree.
8007 See `org-demote' and `org-promote'."
8008 (interactive)
8009 (save-excursion
8010 (org-with-limited-levels (org-map-tree 'org-demote)))
8011 (org-fix-position-after-promote))
8013 (defun org-do-promote ()
8014 "Promote the current heading higher up the tree.
8015 If the region is active in `transient-mark-mode', promote all
8016 headings in the region."
8017 (interactive)
8018 (save-excursion
8019 (if (org-region-active-p)
8020 (org-map-region 'org-promote (region-beginning) (region-end))
8021 (org-promote)))
8022 (org-fix-position-after-promote))
8024 (defun org-do-demote ()
8025 "Demote the current heading lower down the tree.
8026 If the region is active in `transient-mark-mode', demote all
8027 headings in the region."
8028 (interactive)
8029 (save-excursion
8030 (if (org-region-active-p)
8031 (org-map-region 'org-demote (region-beginning) (region-end))
8032 (org-demote)))
8033 (org-fix-position-after-promote))
8035 (defun org-fix-position-after-promote ()
8036 "Fix cursor position and indentation after demoting/promoting."
8037 (let ((pos (point)))
8038 (when (save-excursion
8039 (beginning-of-line)
8040 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8041 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8042 (cond ((eobp) (insert " "))
8043 ((eolp) (insert " "))
8044 ((equal (char-after) ?\s) (forward-char 1))))))
8046 (defun org-current-level ()
8047 "Return the level of the current entry, or nil if before the first headline.
8048 The level is the number of stars at the beginning of the
8049 headline. Use `org-reduced-level' to remove the effect of
8050 `org-odd-levels'. Unlike to `org-outline-level', this function
8051 ignores inlinetasks."
8052 (let ((level (org-with-limited-levels (org-outline-level))))
8053 (and (> level 0) level)))
8055 (defun org-get-previous-line-level ()
8056 "Return the outline depth of the last headline before the current line.
8057 Returns 0 for the first headline in the buffer, and nil if before the
8058 first headline."
8059 (and (org-current-level)
8060 (or (and (/= (line-beginning-position) (point-min))
8061 (save-excursion (beginning-of-line 0) (org-current-level)))
8062 0)))
8064 (defun org-reduced-level (l)
8065 "Compute the effective level of a heading.
8066 This takes into account the setting of `org-odd-levels-only'."
8067 (cond
8068 ((zerop l) 0)
8069 (org-odd-levels-only (1+ (floor (/ l 2))))
8070 (t l)))
8072 (defun org-level-increment ()
8073 "Return the number of stars that will be added or removed at a
8074 time to headlines when structure editing, based on the value of
8075 `org-odd-levels-only'."
8076 (if org-odd-levels-only 2 1))
8078 (defun org-get-valid-level (level &optional change)
8079 "Rectify a level change under the influence of `org-odd-levels-only'.
8080 LEVEL is a current level, CHANGE is by how much the level should
8081 be modified. Even if CHANGE is nil, LEVEL may be returned
8082 modified because even level numbers will become the next higher
8083 odd number. Returns values greater than 0."
8084 (if org-odd-levels-only
8085 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8086 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8087 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8088 (max 1 (+ level (or change 0)))))
8090 (defun org-promote ()
8091 "Promote the current heading higher up the tree."
8092 (org-with-wide-buffer
8093 (org-back-to-heading t)
8094 (let* ((after-change-functions (remq 'flyspell-after-change-function
8095 after-change-functions))
8096 (level (save-match-data (funcall outline-level)))
8097 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8098 (diff (abs (- level (length up-head) -1))))
8099 (cond
8100 ((and (= level 1) org-allow-promoting-top-level-subtree)
8101 (replace-match "# " nil t))
8102 ((= level 1)
8103 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8104 (t (replace-match up-head nil t)))
8105 (unless (= level 1)
8106 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8107 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8108 (run-hooks 'org-after-promote-entry-hook))))
8110 (defun org-demote ()
8111 "Demote the current heading lower down the tree."
8112 (org-with-wide-buffer
8113 (org-back-to-heading t)
8114 (let* ((after-change-functions (remq 'flyspell-after-change-function
8115 after-change-functions))
8116 (level (save-match-data (funcall outline-level)))
8117 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8118 (diff (abs (- level (length down-head) -1))))
8119 (replace-match down-head nil t)
8120 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8121 (when org-adapt-indentation (org-fixup-indentation diff))
8122 (run-hooks 'org-after-demote-entry-hook))))
8124 (defun org-cycle-level ()
8125 "Cycle the level of an empty headline through possible states.
8126 This goes first to child, then to parent, level, then up the hierarchy.
8127 After top level, it switches back to sibling level."
8128 (interactive)
8129 (let ((org-adapt-indentation nil))
8130 (when (org-point-at-end-of-empty-headline)
8131 (setq this-command 'org-cycle-level) ; Only needed for caching
8132 (let ((cur-level (org-current-level))
8133 (prev-level (org-get-previous-line-level)))
8134 (cond
8135 ;; If first headline in file, promote to top-level.
8136 ((= prev-level 0)
8137 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8138 do (org-do-promote)))
8139 ;; If same level as prev, demote one.
8140 ((= prev-level cur-level)
8141 (org-do-demote))
8142 ;; If parent is top-level, promote to top level if not already.
8143 ((= prev-level 1)
8144 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8145 do (org-do-promote)))
8146 ;; If top-level, return to prev-level.
8147 ((= cur-level 1)
8148 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8149 do (org-do-demote)))
8150 ;; If less than prev-level, promote one.
8151 ((< cur-level prev-level)
8152 (org-do-promote))
8153 ;; If deeper than prev-level, promote until higher than
8154 ;; prev-level.
8155 ((> cur-level prev-level)
8156 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8157 do (org-do-promote))))
8158 t))))
8160 (defun org-map-tree (fun)
8161 "Call FUN for every heading underneath the current one."
8162 (org-back-to-heading t)
8163 (let ((level (funcall outline-level)))
8164 (save-excursion
8165 (funcall fun)
8166 (while (and (progn
8167 (outline-next-heading)
8168 (> (funcall outline-level) level))
8169 (not (eobp)))
8170 (funcall fun)))))
8172 (defun org-map-region (fun beg end)
8173 "Call FUN for every heading between BEG and END."
8174 (let ((org-ignore-region t))
8175 (save-excursion
8176 (setq end (copy-marker end))
8177 (goto-char beg)
8178 (when (and (re-search-forward org-outline-regexp-bol nil t)
8179 (< (point) end))
8180 (funcall fun))
8181 (while (and (progn
8182 (outline-next-heading)
8183 (< (point) end))
8184 (not (eobp)))
8185 (funcall fun)))))
8187 (defun org-fixup-indentation (diff)
8188 "Change the indentation in the current entry by DIFF.
8190 DIFF is an integer. Indentation is done according to the
8191 following rules:
8193 - Planning information and property drawers are always indented
8194 according to the new level of the headline;
8196 - Footnote definitions and their contents are ignored;
8198 - Inlinetasks' boundaries are not shifted;
8200 - Empty lines are ignored;
8202 - Other lines' indentation are shifted by DIFF columns, unless
8203 it would introduce a structural change in the document, in
8204 which case no shifting is done at all.
8206 Assume point is at a heading or an inlinetask beginning."
8207 (org-with-wide-buffer
8208 (narrow-to-region (line-beginning-position)
8209 (save-excursion
8210 (if (org-with-limited-levels (org-at-heading-p))
8211 (org-with-limited-levels (outline-next-heading))
8212 (org-inlinetask-goto-end))
8213 (point)))
8214 (forward-line)
8215 ;; Indent properly planning info and property drawer.
8216 (when (looking-at-p org-planning-line-re)
8217 (org-indent-line)
8218 (forward-line))
8219 (when (looking-at org-property-drawer-re)
8220 (goto-char (match-end 0))
8221 (forward-line)
8222 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8223 (catch 'no-shift
8224 (when (zerop diff) (throw 'no-shift nil))
8225 ;; If DIFF is negative, first check if a shift is possible at all
8226 ;; (e.g., it doesn't break structure). This can only happen if
8227 ;; some contents are not properly indented.
8228 (let ((case-fold-search t))
8229 (when (< diff 0)
8230 (let ((diff (- diff))
8231 (forbidden-re (concat org-outline-regexp
8232 "\\|"
8233 (substring org-footnote-definition-re 1))))
8234 (save-excursion
8235 (while (not (eobp))
8236 (cond
8237 ((looking-at-p "[ \t]*$") (forward-line))
8238 ((and (looking-at-p org-footnote-definition-re)
8239 (let ((e (org-element-at-point)))
8240 (and (eq (org-element-type e) 'footnote-definition)
8241 (goto-char (org-element-property :end e))))))
8242 ((looking-at-p org-outline-regexp) (forward-line))
8243 ;; Give up if shifting would move before column 0 or
8244 ;; if it would introduce a headline or a footnote
8245 ;; definition.
8247 (skip-chars-forward " \t")
8248 (let ((ind (current-column)))
8249 (when (or (< ind diff)
8250 (and (= ind diff) (looking-at-p forbidden-re)))
8251 (throw 'no-shift nil)))
8252 ;; Ignore contents of example blocks and source
8253 ;; blocks if their indentation is meant to be
8254 ;; preserved. Jump to block's closing line.
8255 (beginning-of-line)
8256 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8257 (let ((e (org-element-at-point)))
8258 (and (memq (org-element-type e)
8259 '(example-block src-block))
8260 (or org-src-preserve-indentation
8261 (org-element-property :preserve-indent e))
8262 (goto-char (org-element-property :end e))
8263 (progn (skip-chars-backward " \r\t\n")
8264 (beginning-of-line)
8265 t))))
8266 (forward-line))))))))
8267 ;; Shift lines but footnote definitions, inlinetasks boundaries
8268 ;; by DIFF. Also skip contents of source or example blocks
8269 ;; when indentation is meant to be preserved.
8270 (while (not (eobp))
8271 (cond
8272 ((and (looking-at-p org-footnote-definition-re)
8273 (let ((e (org-element-at-point)))
8274 (and (eq (org-element-type e) 'footnote-definition)
8275 (goto-char (org-element-property :end e))))))
8276 ((looking-at-p org-outline-regexp) (forward-line))
8277 ((looking-at-p "[ \t]*$") (forward-line))
8279 (indent-line-to (+ (org-get-indentation) diff))
8280 (beginning-of-line)
8281 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8282 (let ((e (org-element-at-point)))
8283 (and (memq (org-element-type e)
8284 '(example-block src-block))
8285 (or org-src-preserve-indentation
8286 (org-element-property :preserve-indent e))
8287 (goto-char (org-element-property :end e))
8288 (progn (skip-chars-backward " \r\t\n")
8289 (beginning-of-line)
8290 t))))
8291 (forward-line)))))))))
8293 (defun org-convert-to-odd-levels ()
8294 "Convert an Org file with all levels allowed to one with odd levels.
8295 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8296 level 5 etc."
8297 (interactive)
8298 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8299 (let ((outline-level 'org-outline-level)
8300 (org-odd-levels-only nil) n)
8301 (save-excursion
8302 (goto-char (point-min))
8303 (while (re-search-forward "^\\*\\*+ " nil t)
8304 (setq n (- (length (match-string 0)) 2))
8305 (while (>= (setq n (1- n)) 0)
8306 (org-demote))
8307 (end-of-line 1))))))
8309 (defun org-convert-to-oddeven-levels ()
8310 "Convert an Org file with only odd levels to one with odd/even levels.
8311 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8312 file contains a section with an even level, conversion would
8313 destroy the structure of the file. An error is signaled in this
8314 case."
8315 (interactive)
8316 (goto-char (point-min))
8317 ;; First check if there are no even levels
8318 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8319 (org-show-set-visibility 'canonical)
8320 (error "Not all levels are odd in this file. Conversion not possible"))
8321 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8322 (let ((outline-regexp org-outline-regexp)
8323 (outline-level 'org-outline-level)
8324 (org-odd-levels-only nil) n)
8325 (save-excursion
8326 (goto-char (point-min))
8327 (while (re-search-forward "^\\*\\*+ " nil t)
8328 (setq n (/ (1- (length (match-string 0))) 2))
8329 (while (>= (setq n (1- n)) 0)
8330 (org-promote))
8331 (end-of-line 1))))))
8333 (defun org-tr-level (n)
8334 "Make N odd if required."
8335 (if org-odd-levels-only (1+ (/ n 2)) n))
8337 ;;; Vertical tree motion, cutting and pasting of subtrees
8339 (defun org-move-subtree-up (&optional arg)
8340 "Move the current subtree up past ARG headlines of the same level."
8341 (interactive "p")
8342 (org-move-subtree-down (- (prefix-numeric-value arg))))
8344 (defun org-move-subtree-down (&optional arg)
8345 "Move the current subtree down past ARG headlines of the same level."
8346 (interactive "p")
8347 (setq arg (prefix-numeric-value arg))
8348 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8349 'org-get-last-sibling))
8350 (ins-point (make-marker))
8351 (cnt (abs arg))
8352 (col (current-column))
8353 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8354 ;; Select the tree
8355 (org-back-to-heading)
8356 (setq beg0 (point))
8357 (save-excursion
8358 (setq ne-beg (org-back-over-empty-lines))
8359 (setq beg (point)))
8360 (save-match-data
8361 (save-excursion (outline-end-of-heading)
8362 (setq folded (org-invisible-p)))
8363 (progn (org-end-of-subtree nil t)
8364 (unless (eobp) (backward-char))))
8365 (outline-next-heading)
8366 (setq ne-end (org-back-over-empty-lines))
8367 (setq end (point))
8368 (goto-char beg0)
8369 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8370 ;; include less whitespace
8371 (save-excursion
8372 (goto-char beg)
8373 (forward-line (- ne-beg ne-end))
8374 (setq beg (point))))
8375 ;; Find insertion point, with error handling
8376 (while (> cnt 0)
8377 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8378 (progn (goto-char beg0)
8379 (user-error "Cannot move past superior level or buffer limit")))
8380 (setq cnt (1- cnt)))
8381 (when (> arg 0)
8382 ;; Moving forward - still need to move over subtree
8383 (org-end-of-subtree t t)
8384 (save-excursion
8385 (org-back-over-empty-lines)
8386 (or (bolp) (newline))))
8387 (setq ne-ins (org-back-over-empty-lines))
8388 (move-marker ins-point (point))
8389 (setq txt (buffer-substring beg end))
8390 (org-save-markers-in-region beg end)
8391 (delete-region beg end)
8392 (org-remove-empty-overlays-at beg)
8393 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8394 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8395 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8396 (let ((bbb (point)))
8397 (insert-before-markers txt)
8398 (org-reinstall-markers-in-region bbb)
8399 (move-marker ins-point bbb))
8400 (or (bolp) (insert "\n"))
8401 (setq ins-end (point))
8402 (goto-char ins-point)
8403 (org-skip-whitespace)
8404 (when (and (< arg 0)
8405 (org-first-sibling-p)
8406 (> ne-ins ne-beg))
8407 ;; Move whitespace back to beginning
8408 (save-excursion
8409 (goto-char ins-end)
8410 (let ((kill-whole-line t))
8411 (kill-line (- ne-ins ne-beg)) (point)))
8412 (insert (make-string (- ne-ins ne-beg) ?\n)))
8413 (move-marker ins-point nil)
8414 (if folded
8415 (outline-hide-subtree)
8416 (org-show-entry)
8417 (org-show-children)
8418 (org-cycle-hide-drawers 'children))
8419 (org-clean-visibility-after-subtree-move)
8420 ;; move back to the initial column we were at
8421 (move-to-column col)))
8423 (defvar org-subtree-clip ""
8424 "Clipboard for cut and paste of subtrees.
8425 This is actually only a copy of the kill, because we use the normal kill
8426 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8428 (defvar org-subtree-clip-folded nil
8429 "Was the last copied subtree folded?
8430 This is used to fold the tree back after pasting.")
8432 (defun org-cut-subtree (&optional n)
8433 "Cut the current subtree into the clipboard.
8434 With prefix arg N, cut this many sequential subtrees.
8435 This is a short-hand for marking the subtree and then cutting it."
8436 (interactive "p")
8437 (org-copy-subtree n 'cut))
8439 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8440 "Copy the current subtree it in the clipboard.
8441 With prefix arg N, copy this many sequential subtrees.
8442 This is a short-hand for marking the subtree and then copying it.
8443 If CUT is non-nil, actually cut the subtree.
8444 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8445 of some markers in the region, even if CUT is non-nil. This is
8446 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8447 (interactive "p")
8448 (let (beg end folded (beg0 (point)))
8449 (if (called-interactively-p 'any)
8450 (org-back-to-heading nil) ; take what looks like a subtree
8451 (org-back-to-heading t)) ; take what is really there
8452 (setq beg (point))
8453 (skip-chars-forward " \t\r\n")
8454 (save-match-data
8455 (if nosubtrees
8456 (outline-next-heading)
8457 (save-excursion (outline-end-of-heading)
8458 (setq folded (org-invisible-p)))
8459 (ignore-errors (org-forward-heading-same-level (1- n) t))
8460 (org-end-of-subtree t t)))
8461 ;; Include the end of an inlinetask
8462 (when (and (featurep 'org-inlinetask)
8463 (looking-at-p (concat (org-inlinetask-outline-regexp)
8464 "END[ \t]*$")))
8465 (end-of-line))
8466 (setq end (point))
8467 (goto-char beg0)
8468 (when (> end beg)
8469 (setq org-subtree-clip-folded folded)
8470 (when (or cut force-store-markers)
8471 (org-save-markers-in-region beg end))
8472 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8473 (setq org-subtree-clip (current-kill 0))
8474 (message "%s: Subtree(s) with %d characters"
8475 (if cut "Cut" "Copied")
8476 (length org-subtree-clip)))))
8478 (defun org-paste-subtree (&optional level tree for-yank remove)
8479 "Paste the clipboard as a subtree, with modification of headline level.
8480 The entire subtree is promoted or demoted in order to match a new headline
8481 level.
8483 If the cursor is at the beginning of a headline, the same level as
8484 that headline is used to paste the tree.
8486 If not, the new level is derived from the *visible* headings
8487 before and after the insertion point, and taken to be the inferior headline
8488 level of the two. So if the previous visible heading is level 3 and the
8489 next is level 4 (or vice versa), level 4 will be used for insertion.
8490 This makes sure that the subtree remains an independent subtree and does
8491 not swallow low level entries.
8493 You can also force a different level, either by using a numeric prefix
8494 argument, or by inserting the heading marker by hand. For example, if the
8495 cursor is after \"*****\", then the tree will be shifted to level 5.
8497 If optional TREE is given, use this text instead of the kill ring.
8499 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8500 move back over whitespace before inserting, and move point to the end of
8501 the inserted text when done.
8503 When REMOVE is non-nil, remove the subtree from the clipboard."
8504 (interactive "P")
8505 (setq tree (or tree (and kill-ring (current-kill 0))))
8506 (unless (org-kill-is-subtree-p tree)
8507 (user-error "%s"
8508 (substitute-command-keys
8509 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8510 (org-with-limited-levels
8511 (let* ((visp (not (org-invisible-p)))
8512 (txt tree)
8513 (^re_ "\\(\\*+\\)[ \t]*")
8514 (old-level (if (string-match org-outline-regexp-bol txt)
8515 (- (match-end 0) (match-beginning 0) 1)
8516 -1))
8517 (force-level (cond (level (prefix-numeric-value level))
8518 ((and (looking-at "[ \t]*$")
8519 (string-match
8520 "^\\*+$" (buffer-substring
8521 (point-at-bol) (point))))
8522 (- (match-end 0) (match-beginning 0)))
8523 ((and (bolp)
8524 (looking-at org-outline-regexp))
8525 (- (match-end 0) (point) 1))))
8526 (previous-level (save-excursion
8527 (condition-case nil
8528 (progn
8529 (outline-previous-visible-heading 1)
8530 (if (looking-at ^re_)
8531 (- (match-end 0) (match-beginning 0) 1)
8533 (error 1))))
8534 (next-level (save-excursion
8535 (condition-case nil
8536 (progn
8537 (or (looking-at org-outline-regexp)
8538 (outline-next-visible-heading 1))
8539 (if (looking-at ^re_)
8540 (- (match-end 0) (match-beginning 0) 1)
8542 (error 1))))
8543 (new-level (or force-level (max previous-level next-level)))
8544 (shift (if (or (= old-level -1)
8545 (= new-level -1)
8546 (= old-level new-level))
8548 (- new-level old-level)))
8549 (delta (if (> shift 0) -1 1))
8550 (func (if (> shift 0) 'org-demote 'org-promote))
8551 (org-odd-levels-only nil)
8552 beg end newend)
8553 ;; Remove the forced level indicator
8554 (when force-level
8555 (delete-region (point-at-bol) (point)))
8556 ;; Paste
8557 (beginning-of-line (if (bolp) 1 2))
8558 (setq beg (point))
8559 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8560 (insert-before-markers txt)
8561 (unless (string-suffix-p "\n" txt) (insert "\n"))
8562 (setq newend (point))
8563 (org-reinstall-markers-in-region beg)
8564 (setq end (point))
8565 (goto-char beg)
8566 (skip-chars-forward " \t\n\r")
8567 (setq beg (point))
8568 (when (and (org-invisible-p) visp)
8569 (save-excursion (outline-show-heading)))
8570 ;; Shift if necessary
8571 (unless (= shift 0)
8572 (save-restriction
8573 (narrow-to-region beg end)
8574 (while (not (= shift 0))
8575 (org-map-region func (point-min) (point-max))
8576 (setq shift (+ delta shift)))
8577 (goto-char (point-min))
8578 (setq newend (point-max))))
8579 (when (or (called-interactively-p 'interactive) for-yank)
8580 (message "Clipboard pasted as level %d subtree" new-level))
8581 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8582 kill-ring
8583 (eq org-subtree-clip (current-kill 0))
8584 org-subtree-clip-folded)
8585 ;; The tree was folded before it was killed/copied
8586 (outline-hide-subtree))
8587 (and for-yank (goto-char newend))
8588 (and remove (setq kill-ring (cdr kill-ring))))))
8590 (defun org-kill-is-subtree-p (&optional txt)
8591 "Check if the current kill is an outline subtree, or a set of trees.
8592 Returns nil if kill does not start with a headline, or if the first
8593 headline level is not the largest headline level in the tree.
8594 So this will actually accept several entries of equal levels as well,
8595 which is OK for `org-paste-subtree'.
8596 If optional TXT is given, check this string instead of the current kill."
8597 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8598 (re (org-get-limited-outline-regexp))
8599 (^re (concat "^" re))
8600 (start-level (and kill
8601 (string-match
8602 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8603 kill)
8604 (- (match-end 2) (match-beginning 2) 1)))
8605 (start (1+ (or (match-beginning 2) -1))))
8606 (if (not start-level)
8607 (progn
8608 nil) ;; does not even start with a heading
8609 (catch 'exit
8610 (while (setq start (string-match ^re kill (1+ start)))
8611 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8612 (throw 'exit nil)))
8613 t))))
8615 (defvar org-markers-to-move nil
8616 "Markers that should be moved with a cut-and-paste operation.
8617 Those markers are stored together with their positions relative to
8618 the start of the region.")
8620 (defun org-save-markers-in-region (beg end)
8621 "Check markers in region.
8622 If these markers are between BEG and END, record their position relative
8623 to BEG, so that after moving the block of text, we can put the markers back
8624 into place.
8625 This function gets called just before an entry or tree gets cut from the
8626 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8627 called immediately, to move the markers with the entries."
8628 (setq org-markers-to-move nil)
8629 (when (featurep 'org-clock)
8630 (org-clock-save-markers-for-cut-and-paste beg end))
8631 (when (featurep 'org-agenda)
8632 (org-agenda-save-markers-for-cut-and-paste beg end)))
8634 (defun org-check-and-save-marker (marker beg end)
8635 "Check if MARKER is between BEG and END.
8636 If yes, remember the marker and the distance to BEG."
8637 (when (and (marker-buffer marker)
8638 (equal (marker-buffer marker) (current-buffer))
8639 (>= marker beg) (< marker end))
8640 (push (cons marker (- marker beg)) org-markers-to-move)))
8642 (defun org-reinstall-markers-in-region (beg)
8643 "Move all remembered markers to their position relative to BEG."
8644 (dolist (x org-markers-to-move)
8645 (move-marker (car x) (+ beg (cdr x))))
8646 (setq org-markers-to-move nil))
8648 (defun org-narrow-to-subtree ()
8649 "Narrow buffer to the current subtree."
8650 (interactive)
8651 (save-excursion
8652 (save-match-data
8653 (org-with-limited-levels
8654 (narrow-to-region
8655 (progn (org-back-to-heading t) (point))
8656 (progn (org-end-of-subtree t t)
8657 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8658 (point)))))))
8660 (defun org-narrow-to-block ()
8661 "Narrow buffer to the current block."
8662 (interactive)
8663 (let* ((case-fold-search t)
8664 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8665 "^[ \t]*#\\+end_.*")))
8666 (if blockp
8667 (narrow-to-region (car blockp) (cdr blockp))
8668 (user-error "Not in a block"))))
8670 (defun org-clone-subtree-with-time-shift (n &optional shift)
8671 "Clone the task (subtree) at point N times.
8672 The clones will be inserted as siblings.
8674 In interactive use, the user will be prompted for the number of
8675 clones to be produced. If the entry has a timestamp, the user
8676 will also be prompted for a time shift, which may be a repeater
8677 as used in time stamps, for example `+3d'. To disable this,
8678 you can call the function with a universal prefix argument.
8680 When a valid repeater is given and the entry contains any time
8681 stamps, the clones will become a sequence in time, with time
8682 stamps in the subtree shifted for each clone produced. If SHIFT
8683 is nil or the empty string, time stamps will be left alone. The
8684 ID property of the original subtree is removed.
8686 In each clone, all the CLOCK entries will be removed. This
8687 prevents Org from considering that the clocked times overlap.
8689 If the original subtree did contain time stamps with a repeater,
8690 the following will happen:
8691 - the repeater will be removed in each clone
8692 - an additional clone will be produced, with the current, unshifted
8693 date(s) in the entry.
8694 - the original entry will be placed *after* all the clones, with
8695 repeater intact.
8696 - the start days in the repeater in the original entry will be shifted
8697 to past the last clone.
8698 In this way you can spell out a number of instances of a repeating task,
8699 and still retain the repeater to cover future instances of the task.
8701 As described above, N+1 clones are produced when the original
8702 subtree has a repeater. Setting N to 0, then, can be used to
8703 remove the repeater from a subtree and create a shifted clone
8704 with the original repeater."
8705 (interactive "nNumber of clones to produce: ")
8706 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8707 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8708 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8709 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8710 (shift
8711 (or shift
8712 (if (and (not (equal current-prefix-arg '(4)))
8713 (save-excursion
8714 (goto-char beg)
8715 (re-search-forward org-ts-regexp-both end-of-tree t)))
8716 (read-from-minibuffer
8717 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8718 ""))) ;No time shift
8719 (doshift
8720 (and (org-string-nw-p shift)
8721 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8722 shift)
8723 (user-error "Invalid shift specification %s" shift)))))
8724 (goto-char end-of-tree)
8725 (unless (bolp) (insert "\n"))
8726 (let* ((end (point))
8727 (template (buffer-substring beg end))
8728 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8729 (shift-what (pcase (and doshift (match-string 2 shift))
8730 (`nil nil)
8731 ("d" 'day)
8732 ("w" (setq shift-n (* 7 shift-n)) 'day)
8733 ("m" 'month)
8734 ("y" 'year)
8735 (_ (error "Unsupported time unit"))))
8736 (nmin 1)
8737 (nmax n)
8738 (n-no-remove -1)
8739 (idprop (org-entry-get nil "ID")))
8740 (when (and doshift
8741 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8742 template))
8743 (delete-region beg end)
8744 (setq end beg)
8745 (setq nmin 0)
8746 (setq nmax (1+ nmax))
8747 (setq n-no-remove nmax))
8748 (goto-char end)
8749 (cl-loop for n from nmin to nmax do
8750 (insert
8751 ;; Prepare clone.
8752 (with-temp-buffer
8753 (insert template)
8754 (org-mode)
8755 (goto-char (point-min))
8756 (org-show-subtree)
8757 (and idprop (if org-clone-delete-id
8758 (org-entry-delete nil "ID")
8759 (org-id-get-create t)))
8760 (unless (= n 0)
8761 (while (re-search-forward org-clock-line-re nil t)
8762 (delete-region (line-beginning-position)
8763 (line-beginning-position 2)))
8764 (goto-char (point-min))
8765 (while (re-search-forward org-drawer-regexp nil t)
8766 (org-remove-empty-drawer-at (point))))
8767 (goto-char (point-min))
8768 (when doshift
8769 (while (re-search-forward org-ts-regexp-both nil t)
8770 (org-timestamp-change (* n shift-n) shift-what))
8771 (unless (= n n-no-remove)
8772 (goto-char (point-min))
8773 (while (re-search-forward org-ts-regexp nil t)
8774 (save-excursion
8775 (goto-char (match-beginning 0))
8776 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8777 (delete-region (match-beginning 1) (match-end 1)))))))
8778 (buffer-string)))))
8779 (goto-char beg)))
8781 ;;; Outline Sorting
8783 (defun org-sort (&optional with-case)
8784 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8785 Optional argument WITH-CASE means sort case-sensitively."
8786 (interactive "P")
8787 (org-call-with-arg
8788 (cond ((org-at-table-p) #'org-table-sort-lines)
8789 ((org-at-item-p) #'org-sort-list)
8790 (t #'org-sort-entries))
8791 with-case))
8793 (defun org-sort-remove-invisible (s)
8794 "Remove invisible part of links and emphasis markers from string S."
8795 (remove-text-properties 0 (length s) org-rm-props s)
8796 (replace-regexp-in-string
8797 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8798 (replace-regexp-in-string
8799 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8800 (org-link-display-format s)
8801 t t) t t))
8803 (defvar org-priority-regexp) ; defined later in the file
8805 (defvar org-after-sorting-entries-or-items-hook nil
8806 "Hook that is run after a bunch of entries or items have been sorted.
8807 When children are sorted, the cursor is in the parent line when this
8808 hook gets called. When a region or a plain list is sorted, the cursor
8809 will be in the first entry of the sorted region/list.")
8811 (defun org-sort-entries
8812 (&optional with-case sorting-type getkey-func compare-func property
8813 interactive?)
8814 "Sort entries on a certain level of an outline tree.
8815 If there is an active region, the entries in the region are sorted.
8816 Else, if the cursor is before the first entry, sort the top-level items.
8817 Else, the children of the entry at point are sorted.
8819 Sorting can be alphabetically, numerically, by date/time as given by
8820 a time stamp, by a property, by priority order, or by a custom function.
8822 The command prompts for the sorting type unless it has been given to the
8823 function through the SORTING-TYPE argument, which needs to be a character,
8824 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8825 the precise meaning of each character:
8827 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8828 c By creation time, which is assumed to be the first inactive time stamp
8829 at the beginning of a line.
8830 d By deadline date/time.
8831 k By clocking time.
8832 n Numerically, by converting the beginning of the entry/item to a number.
8833 o By order of TODO keywords.
8834 p By priority according to the cookie.
8835 r By the value of a property.
8836 s By scheduled date/time.
8837 t By date/time, either the first active time stamp in the entry, or, if
8838 none exist, by the first inactive one.
8840 Capital letters will reverse the sort order.
8842 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8843 called with point at the beginning of the record. It must return a
8844 value that is compatible with COMPARE-FUNC, the function used to
8845 compare entries.
8847 Comparing entries ignores case by default. However, with an optional argument
8848 WITH-CASE, the sorting considers case as well.
8850 Sorting is done against the visible part of the headlines, it ignores hidden
8851 links.
8853 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8855 A non-nil value for INTERACTIVE? is used to signal that this
8856 function is being called interactively."
8857 (interactive (list current-prefix-arg nil nil nil nil t))
8858 (let ((case-func (if with-case 'identity 'downcase))
8859 start beg end stars re re2
8860 txt what tmp)
8861 ;; Find beginning and end of region to sort
8862 (cond
8863 ((org-region-active-p)
8864 ;; we will sort the region
8865 (setq end (region-end)
8866 what "region")
8867 (goto-char (region-beginning))
8868 (unless (org-at-heading-p) (outline-next-heading))
8869 (setq start (point)))
8870 ((or (org-at-heading-p)
8871 (ignore-errors (progn (org-back-to-heading) t)))
8872 ;; we will sort the children of the current headline
8873 (org-back-to-heading)
8874 (setq start (point)
8875 end (progn (org-end-of-subtree t t)
8876 (or (bolp) (insert "\n"))
8877 (when (>= (org-back-over-empty-lines) 1)
8878 (forward-line 1))
8879 (point))
8880 what "children")
8881 (goto-char start)
8882 (outline-show-subtree)
8883 (outline-next-heading))
8885 ;; we will sort the top-level entries in this file
8886 (goto-char (point-min))
8887 (or (org-at-heading-p) (outline-next-heading))
8888 (setq start (point))
8889 (goto-char (point-max))
8890 (beginning-of-line 1)
8891 (when (looking-at ".*?\\S-")
8892 ;; File ends in a non-white line
8893 (end-of-line 1)
8894 (insert "\n"))
8895 (setq end (point-max))
8896 (setq what "top-level")
8897 (goto-char start)
8898 (outline-show-all)))
8900 (setq beg (point))
8901 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8903 (looking-at "\\(\\*+\\)")
8904 (setq stars (match-string 1)
8905 re (concat "^" (regexp-quote stars) " +")
8906 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8907 txt (buffer-substring beg end))
8908 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8909 (when (and (not (equal stars "*")) (string-match re2 txt))
8910 (user-error "Region to sort contains a level above the first entry"))
8912 (unless sorting-type
8913 (message
8914 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8915 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8916 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8917 what)
8918 (setq sorting-type (read-char-exclusive)))
8920 (unless getkey-func
8921 (and (= (downcase sorting-type) ?f)
8922 (setq getkey-func
8923 (or (and interactive?
8924 (org-read-function
8925 "Function for extracting keys: "))
8926 (error "Missing key extractor")))))
8928 (and (= (downcase sorting-type) ?r)
8929 (not property)
8930 (setq property
8931 (completing-read "Property: "
8932 (mapcar #'list (org-buffer-property-keys t))
8933 nil t)))
8935 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8936 (message "Sorting entries...")
8938 (save-restriction
8939 (narrow-to-region start end)
8940 (let ((restore-clock?
8941 ;; The clock marker is lost when using `sort-subr'; mark
8942 ;; the clock with temporary `:org-clock-marker-backup'
8943 ;; text property.
8944 (when (and (eq (org-clock-is-active) (current-buffer))
8945 (<= start (marker-position org-clock-marker))
8946 (>= end (marker-position org-clock-marker)))
8947 (org-with-silent-modifications
8948 (put-text-property (1- org-clock-marker) org-clock-marker
8949 :org-clock-marker-backup t))
8951 (dcst (downcase sorting-type))
8952 (case-fold-search nil)
8953 (now (current-time)))
8954 (sort-subr
8955 (/= dcst sorting-type)
8956 ;; This function moves to the beginning character of the "record" to
8957 ;; be sorted.
8958 (lambda nil
8959 (if (re-search-forward re nil t)
8960 (goto-char (match-beginning 0))
8961 (goto-char (point-max))))
8962 ;; This function moves to the last character of the "record" being
8963 ;; sorted.
8964 (lambda nil
8965 (save-match-data
8966 (condition-case nil
8967 (outline-forward-same-level 1)
8968 (error
8969 (goto-char (point-max))))))
8970 ;; This function returns the value that gets sorted against.
8971 (lambda nil
8972 (cond
8973 ((= dcst ?n)
8974 (if (looking-at org-complex-heading-regexp)
8975 (string-to-number (org-sort-remove-invisible (match-string 4)))
8976 nil))
8977 ((= dcst ?a)
8978 (if (looking-at org-complex-heading-regexp)
8979 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8980 nil))
8981 ((= dcst ?k)
8982 (or (get-text-property (point) :org-clock-minutes) 0))
8983 ((= dcst ?t)
8984 (let ((end (save-excursion (outline-next-heading) (point))))
8985 (if (or (re-search-forward org-ts-regexp end t)
8986 (re-search-forward org-ts-regexp-both end t))
8987 (org-time-string-to-seconds (match-string 0))
8988 (float-time now))))
8989 ((= dcst ?c)
8990 (let ((end (save-excursion (outline-next-heading) (point))))
8991 (if (re-search-forward
8992 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8993 end t)
8994 (org-time-string-to-seconds (match-string 0))
8995 (float-time now))))
8996 ((= dcst ?s)
8997 (let ((end (save-excursion (outline-next-heading) (point))))
8998 (if (re-search-forward org-scheduled-time-regexp end t)
8999 (org-time-string-to-seconds (match-string 1))
9000 (float-time now))))
9001 ((= dcst ?d)
9002 (let ((end (save-excursion (outline-next-heading) (point))))
9003 (if (re-search-forward org-deadline-time-regexp end t)
9004 (org-time-string-to-seconds (match-string 1))
9005 (float-time now))))
9006 ((= dcst ?p)
9007 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9008 (string-to-char (match-string 2))
9009 org-default-priority))
9010 ((= dcst ?r)
9011 (or (org-entry-get nil property) ""))
9012 ((= dcst ?o)
9013 (when (looking-at org-complex-heading-regexp)
9014 (let* ((m (match-string 2))
9015 (s (if (member m org-done-keywords) '- '+)))
9016 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9017 ((= dcst ?f)
9018 (if getkey-func
9019 (progn
9020 (setq tmp (funcall getkey-func))
9021 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9022 tmp)
9023 (error "Invalid key function `%s'" getkey-func)))
9024 (t (error "Invalid sorting type `%c'" sorting-type))))
9026 (cond
9027 ((= dcst ?a) 'string<)
9028 ((= dcst ?f)
9029 (or compare-func
9030 (and interactive?
9031 (org-read-function
9032 (concat "Function for comparing keys "
9033 "(empty for default `sort-subr' predicate): ")
9034 'allow-empty))))
9035 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9036 (when restore-clock?
9037 (move-marker org-clock-marker
9038 (1+ (next-single-property-change
9039 start :org-clock-marker-backup)))
9040 (remove-text-properties (1- org-clock-marker) org-clock-marker
9041 '(:org-clock-marker-backup t)))))
9042 (run-hooks 'org-after-sorting-entries-or-items-hook)
9043 (message "Sorting entries...done")))
9045 ;;; The orgstruct minor mode
9047 ;; Define a minor mode which can be used in other modes in order to
9048 ;; integrate the Org mode structure editing commands.
9050 ;; This is really a hack, because the Org mode structure commands use
9051 ;; keys which normally belong to the major mode. Here is how it
9052 ;; works: The minor mode defines all the keys necessary to operate the
9053 ;; structure commands, but wraps the commands into a function which
9054 ;; tests if the cursor is currently at a headline or a plain list
9055 ;; item. If that is the case, the structure command is used,
9056 ;; temporarily setting many Org mode variables like regular
9057 ;; expressions for filling etc. However, when any of those keys is
9058 ;; used at a different location, function uses `key-binding' to look
9059 ;; up if the key has an associated command in another currently active
9060 ;; keymap (minor modes, major mode, global), and executes that
9061 ;; command. There might be problems if any of the keys is otherwise
9062 ;; used as a prefix key.
9064 (defcustom orgstruct-heading-prefix-regexp ""
9065 "Regexp that matches the custom prefix of Org headlines in
9066 orgstruct(++)-mode."
9067 :group 'org
9068 :version "24.4"
9069 :package-version '(Org . "8.3")
9070 :type 'regexp)
9071 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9073 (defcustom orgstruct-setup-hook nil
9074 "Hook run after orgstruct-mode-map is filled."
9075 :group 'org
9076 :version "24.4"
9077 :package-version '(Org . "8.0")
9078 :type 'hook)
9080 (defvar orgstruct-initialized nil)
9082 (defvar org-local-vars nil
9083 "List of local variables, for use by `orgstruct-mode'.")
9085 ;;;###autoload
9086 (define-minor-mode orgstruct-mode
9087 "Toggle the minor mode `orgstruct-mode'.
9088 This mode is for using Org mode structure commands in other
9089 modes. The following keys behave as if Org mode were active, if
9090 the cursor is on a headline, or on a plain list item (both as
9091 defined by Org mode)."
9092 nil " OrgStruct" (make-sparse-keymap)
9093 (funcall (if orgstruct-mode
9094 'add-to-invisibility-spec
9095 'remove-from-invisibility-spec)
9096 '(outline . t))
9097 (when orgstruct-mode
9098 (org-load-modules-maybe)
9099 (unless orgstruct-initialized
9100 (orgstruct-setup)
9101 (setq orgstruct-initialized t))))
9103 ;;;###autoload
9104 (defun turn-on-orgstruct ()
9105 "Unconditionally turn on `orgstruct-mode'."
9106 (orgstruct-mode 1))
9108 (defvar-local orgstruct-is-++ nil
9109 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9110 (defvar-local org-fb-vars nil)
9111 (defun orgstruct++-mode (&optional arg)
9112 "Toggle `orgstruct-mode', the enhanced version of it.
9113 In addition to setting orgstruct-mode, this also exports all
9114 indentation and autofilling variables from Org mode into the
9115 buffer. It will also recognize item context in multiline items."
9116 (interactive "P")
9117 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9118 (if (< arg 1)
9119 (progn (orgstruct-mode -1)
9120 (dolist (v org-fb-vars)
9121 (set (make-local-variable (car v))
9122 (if (eq (car-safe (cadr v)) 'quote)
9123 (cl-cadadr v)
9124 (nth 1 v)))))
9125 (orgstruct-mode 1)
9126 (setq org-fb-vars nil)
9127 (unless org-local-vars
9128 (setq org-local-vars (org-get-local-variables)))
9129 (let (var val)
9130 (dolist (x org-local-vars)
9131 (when (string-match
9132 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9133 \\|fill-prefix\\|indent-\\)"
9134 (symbol-name (car x)))
9135 (setq var (car x) val (nth 1 x))
9136 (push (list var `(quote ,(eval var))) org-fb-vars)
9137 (set (make-local-variable var)
9138 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9139 (setq-local orgstruct-is-++ t))))
9141 ;;;###autoload
9142 (defun turn-on-orgstruct++ ()
9143 "Unconditionally turn on `orgstruct++-mode'."
9144 (orgstruct++-mode 1))
9146 (defun orgstruct-error ()
9147 "Error when there is no default binding for a structure key."
9148 (interactive)
9149 (funcall (if (fboundp 'user-error)
9150 'user-error
9151 'error)
9152 "This key has no function outside structure elements"))
9154 (defun orgstruct-setup ()
9155 "Setup orgstruct keymap."
9156 (dolist (cell '((org-demote . t)
9157 (org-metaleft . t)
9158 (org-metaright . t)
9159 (org-promote . t)
9160 (org-shiftmetaleft . t)
9161 (org-shiftmetaright . t)
9162 org-backward-element
9163 org-backward-heading-same-level
9164 org-ctrl-c-ret
9165 org-ctrl-c-minus
9166 org-ctrl-c-star
9167 org-cycle
9168 org-force-cycle-archived
9169 org-forward-heading-same-level
9170 org-insert-heading
9171 org-insert-heading-respect-content
9172 org-kill-note-or-show-branches
9173 org-mark-subtree
9174 org-meta-return
9175 org-metadown
9176 org-metaup
9177 org-narrow-to-subtree
9178 org-promote-subtree
9179 org-reveal
9180 org-shiftdown
9181 org-shiftleft
9182 org-shiftmetadown
9183 org-shiftmetaup
9184 org-shiftright
9185 org-shifttab
9186 org-shifttab
9187 org-shiftup
9188 org-show-children
9189 org-show-subtree
9190 org-sort
9191 org-up-element
9192 outline-demote
9193 outline-next-visible-heading
9194 outline-previous-visible-heading
9195 outline-promote
9196 outline-up-heading))
9197 (let ((f (or (car-safe cell) cell))
9198 (disable-when-heading-prefix (cdr-safe cell)))
9199 (when (fboundp f)
9200 (let ((new-bindings))
9201 (dolist (binding (nconc (where-is-internal f org-mode-map)
9202 (where-is-internal f outline-mode-map)))
9203 (push binding new-bindings)
9204 ;; TODO use local-function-key-map
9205 (dolist (rep '(("<tab>" . "TAB")
9206 ("<return>" . "RET")
9207 ("<escape>" . "ESC")
9208 ("<delete>" . "DEL")))
9209 (setq binding (read-kbd-macro
9210 (let ((case-fold-search))
9211 (replace-regexp-in-string
9212 (regexp-quote (cdr rep))
9213 (car rep)
9214 (key-description binding)))))
9215 (cl-pushnew binding new-bindings :test 'equal)))
9216 (dolist (binding new-bindings)
9217 (let ((key (lookup-key orgstruct-mode-map binding)))
9218 (when (or (not key) (numberp key))
9219 (ignore-errors
9220 (org-defkey orgstruct-mode-map
9221 binding
9222 (orgstruct-make-binding
9223 f binding disable-when-heading-prefix))))))))))
9224 (run-hooks 'orgstruct-setup-hook))
9226 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9227 "Create a function for binding in the structure minor mode.
9228 FUN is the command to call inside a table. KEY is the key that
9229 should be checked in for a command to execute outside of tables.
9230 Non-nil `disable-when-heading-prefix' means to disable the command
9231 if `orgstruct-heading-prefix-regexp' is not empty."
9232 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9233 (let ((nname name)
9234 (i 0))
9235 (while (fboundp (intern nname))
9236 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9237 (setq name (intern nname)))
9238 (eval
9239 (let ((bindings '((org-heading-regexp
9240 (concat "^"
9241 orgstruct-heading-prefix-regexp
9242 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9243 (org-outline-regexp
9244 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9245 (org-outline-regexp-bol
9246 (concat "^" org-outline-regexp))
9247 (outline-regexp org-outline-regexp)
9248 (outline-heading-end-regexp "\n")
9249 (outline-level 'org-outline-level)
9250 (outline-heading-alist))))
9251 `(defun ,name (arg)
9252 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9253 "Outside of structure, run the binding of `"
9254 (key-description key) "'."
9255 (when disable-when-heading-prefix
9256 (concat
9257 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9258 "back to the default binding due to limitations of Org's implementation of\n"
9259 "`" (symbol-name fun) "'.")))
9260 (interactive "p")
9261 (let* ((disable
9262 ,(and disable-when-heading-prefix
9263 '(not (string= orgstruct-heading-prefix-regexp ""))))
9264 (fallback
9265 (or disable
9266 (not
9267 (let* ,bindings
9268 (org-context-p 'headline 'item
9269 ,(when (memq fun
9270 '(org-insert-heading
9271 org-insert-heading-respect-content
9272 org-meta-return))
9273 '(when orgstruct-is-++
9274 'item-body))))))))
9275 (if fallback
9276 (let* ((orgstruct-mode)
9277 (binding
9278 (let ((key ,key))
9279 (catch 'exit
9280 (dolist
9281 (rep
9282 '(nil
9283 ("<\\([^>]*\\)tab>" . "\\1TAB")
9284 ("<\\([^>]*\\)return>" . "\\1RET")
9285 ("<\\([^>]*\\)escape>" . "\\1ESC")
9286 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9287 nil)
9288 (when rep
9289 (setq key (read-kbd-macro
9290 (let ((case-fold-search))
9291 (replace-regexp-in-string
9292 (car rep)
9293 (cdr rep)
9294 (key-description key))))))
9295 (when (key-binding key)
9296 (throw 'exit (key-binding key))))))))
9297 (if (keymapp binding)
9298 (org-set-transient-map binding)
9299 (let ((func (or binding
9300 (unless disable
9301 'orgstruct-error))))
9302 (when func
9303 (call-interactively func)))))
9304 (org-run-like-in-org-mode
9305 (lambda ()
9306 (interactive)
9307 (let* ,bindings
9308 (call-interactively ',fun)))))))))
9309 name))
9311 (defun org-contextualize-keys (alist contexts)
9312 "Return valid elements in ALIST depending on CONTEXTS.
9314 `org-agenda-custom-commands' or `org-capture-templates' are the
9315 values used for ALIST, and `org-agenda-custom-commands-contexts'
9316 or `org-capture-templates-contexts' are the associated contexts
9317 definitions."
9318 (let ((contexts
9319 ;; normalize contexts
9320 (mapcar
9321 (lambda(c) (cond ((listp (cadr c))
9322 (list (car c) (car c) (nth 1 c)))
9323 ((string= "" (cadr c))
9324 (list (car c) (car c) (nth 2 c)))
9325 (t c)))
9326 contexts))
9327 (a alist) r s)
9328 ;; loop over all commands or templates
9329 (dolist (c a)
9330 (let (vrules repl)
9331 (cond
9332 ((not (assoc (car c) contexts))
9333 (push c r))
9334 ((and (assoc (car c) contexts)
9335 (setq vrules (org-contextualize-validate-key
9336 (car c) contexts)))
9337 (mapc (lambda (vr)
9338 (unless (equal (car vr) (cadr vr))
9339 (setq repl vr)))
9340 vrules)
9341 (if (not repl) (push c r)
9342 (push (cadr repl) s)
9343 (push
9344 (cons (car c)
9345 (cdr (or (assoc (cadr repl) alist)
9346 (error "Undefined key `%s' as contextual replacement for `%s'"
9347 (cadr repl) (car c)))))
9348 r))))))
9349 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9350 (delq
9352 (delete-dups
9353 (mapcar (lambda (x)
9354 (let ((tpl (car x)))
9355 (unless (delq
9357 (mapcar (lambda (y)
9358 (equal y tpl))
9360 x)))
9361 (reverse r))))))
9363 (defun org-contextualize-validate-key (key contexts)
9364 "Check CONTEXTS for agenda or capture KEY."
9365 (let (res)
9366 (dolist (r contexts)
9367 (dolist (rr (car (last r)))
9368 (when
9369 (and (equal key (car r))
9370 (if (functionp rr) (funcall rr)
9371 (or (and (eq (car rr) 'in-file)
9372 (buffer-file-name)
9373 (string-match (cdr rr) (buffer-file-name)))
9374 (and (eq (car rr) 'in-mode)
9375 (string-match (cdr rr) (symbol-name major-mode)))
9376 (and (eq (car rr) 'in-buffer)
9377 (string-match (cdr rr) (buffer-name)))
9378 (when (and (eq (car rr) 'not-in-file)
9379 (buffer-file-name))
9380 (not (string-match (cdr rr) (buffer-file-name))))
9381 (when (eq (car rr) 'not-in-mode)
9382 (not (string-match (cdr rr) (symbol-name major-mode))))
9383 (when (eq (car rr) 'not-in-buffer)
9384 (not (string-match (cdr rr) (buffer-name)))))))
9385 (push r res))))
9386 (delete-dups (delq nil res))))
9388 (defun org-context-p (&rest contexts)
9389 "Check if local context is any of CONTEXTS.
9390 Possible values in the list of contexts are `table', `headline', and `item'."
9391 (let ((pos (point)))
9392 (goto-char (point-at-bol))
9393 (prog1 (or (and (memq 'table contexts)
9394 (looking-at "[ \t]*|"))
9395 (and (memq 'headline contexts)
9396 (looking-at org-outline-regexp))
9397 (and (memq 'item contexts)
9398 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9399 (and (memq 'item-body contexts)
9400 (org-in-item-p)))
9401 (goto-char pos))))
9403 ;;;###autoload
9404 (defun org-run-like-in-org-mode (cmd)
9405 "Run a command, pretending that the current buffer is in Org mode.
9406 This will temporarily bind local variables that are typically bound in
9407 Org mode to the values they have in Org mode, and then interactively
9408 call CMD."
9409 (org-load-modules-maybe)
9410 (unless org-local-vars
9411 (setq org-local-vars (org-get-local-variables)))
9412 (let (binds)
9413 (dolist (var org-local-vars)
9414 (when (or (not (boundp (car var)))
9415 (eq (symbol-value (car var))
9416 (default-value (car var))))
9417 (push (list (car var) `(quote ,(cadr var))) binds)))
9418 (eval `(let ,binds
9419 (call-interactively (quote ,cmd))))))
9421 (defun org-get-category (&optional pos force-refresh)
9422 "Get the category applying to position POS."
9423 (save-match-data
9424 (when force-refresh (org-refresh-category-properties))
9425 (let ((pos (or pos (point))))
9426 (or (get-text-property pos 'org-category)
9427 (progn (org-refresh-category-properties)
9428 (get-text-property pos 'org-category))))))
9430 ;;; Refresh properties
9432 (defun org-refresh-properties (dprop tprop)
9433 "Refresh buffer text properties.
9434 DPROP is the drawer property and TPROP is either the
9435 corresponding text property to set, or an alist with each element
9436 being a text property (as a symbol) and a function to apply to
9437 the value of the drawer property."
9438 (let* ((case-fold-search t)
9439 (inhibit-read-only t)
9440 (inherit? (org-property-inherit-p dprop))
9441 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9442 (global (and inherit? (org--property-global-value dprop nil))))
9443 (org-with-silent-modifications
9444 (org-with-point-at 1
9445 ;; Set global values (e.g., values defined through
9446 ;; "#+PROPERTY:" keywords) to the whole buffer.
9447 (when global (put-text-property (point-min) (point-max) tprop global))
9448 ;; Set local values.
9449 (while (re-search-forward property-re nil t)
9450 (when (org-at-property-p)
9451 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9452 (outline-next-heading))))))
9454 (defun org-refresh-property (tprop p &optional inherit)
9455 "Refresh the buffer text property TPROP from the drawer property P.
9456 The refresh happens only for the current headline, or the whole
9457 sub-tree if optional argument INHERIT is non-nil."
9458 (unless (org-before-first-heading-p)
9459 (save-excursion
9460 (org-back-to-heading t)
9461 (let ((start (point))
9462 (end (save-excursion
9463 (if inherit (org-end-of-subtree t t)
9464 (or (outline-next-heading) (point-max))))))
9465 (if (symbolp tprop)
9466 ;; TPROP is a text property symbol.
9467 (put-text-property start end tprop p)
9468 ;; TPROP is an alist with (property . function) elements.
9469 (pcase-dolist (`(,prop . ,f) tprop)
9470 (put-text-property start end prop (funcall f p))))))))
9472 (defun org-refresh-category-properties ()
9473 "Refresh category text properties in the buffer."
9474 (let ((case-fold-search t)
9475 (inhibit-read-only t)
9476 (default-category
9477 (cond ((null org-category)
9478 (if buffer-file-name
9479 (file-name-sans-extension
9480 (file-name-nondirectory buffer-file-name))
9481 "???"))
9482 ((symbolp org-category) (symbol-name org-category))
9483 (t org-category))))
9484 (org-with-silent-modifications
9485 (org-with-wide-buffer
9486 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9487 ;; This is the default category for the buffer. If none is
9488 ;; found, fall-back to `org-category' or buffer file name.
9489 (put-text-property
9490 (point-min) (point-max)
9491 'org-category
9492 (catch 'buffer-category
9493 (goto-char (point-max))
9494 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9495 (let ((element (org-element-at-point)))
9496 (when (eq (org-element-type element) 'keyword)
9497 (throw 'buffer-category
9498 (org-element-property :value element)))))
9499 default-category))
9500 ;; Set sub-tree specific categories.
9501 (goto-char (point-min))
9502 (let ((regexp (org-re-property "CATEGORY")))
9503 (while (re-search-forward regexp nil t)
9504 (let ((value (match-string-no-properties 3)))
9505 (when (org-at-property-p)
9506 (put-text-property
9507 (save-excursion (org-back-to-heading t) (point))
9508 (save-excursion (org-end-of-subtree t t) (point))
9509 'org-category
9510 value)))))))))
9512 (defun org-refresh-stats-properties ()
9513 "Refresh stats text properties in the buffer."
9514 (org-with-silent-modifications
9515 (org-with-point-at 1
9516 (let ((regexp (concat org-outline-regexp-bol
9517 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9518 (while (re-search-forward regexp nil t)
9519 (let* ((numerator (string-to-number (match-string 1)))
9520 (denominator (and (match-end 2)
9521 (string-to-number (match-string 2))))
9522 (stats (cond ((not denominator) numerator) ;percent
9523 ((= denominator 0) 0)
9524 (t (/ (* numerator 100) denominator)))))
9525 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9526 'org-stats stats)))))))
9528 (defun org-refresh-effort-properties ()
9529 "Refresh effort properties"
9530 (org-refresh-properties
9531 org-effort-property
9532 '((effort . identity)
9533 (effort-minutes . org-duration-to-minutes))))
9535 ;;;; Link Stuff
9537 ;;; Link abbreviations
9539 (defun org-link-expand-abbrev (link)
9540 "Apply replacements as defined in `org-link-abbrev-alist'."
9541 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9542 (let* ((key (match-string 1 link))
9543 (as (or (assoc key org-link-abbrev-alist-local)
9544 (assoc key org-link-abbrev-alist)))
9545 (tag (and (match-end 2) (match-string 3 link)))
9546 rpl)
9547 (if (not as)
9548 link
9549 (setq rpl (cdr as))
9550 (cond
9551 ((symbolp rpl) (funcall rpl tag))
9552 ((string-match "%(\\([^)]+\\))" rpl)
9553 (replace-match
9554 (save-match-data
9555 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9556 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9557 ((string-match "%h" rpl)
9558 (replace-match (url-hexify-string (or tag "")) t t rpl))
9559 (t (concat rpl tag)))))
9560 link))
9562 ;;; Storing and inserting links
9564 (defvar org-insert-link-history nil
9565 "Minibuffer history for links inserted with `org-insert-link'.")
9567 (defvar org-stored-links nil
9568 "Contains the links stored with `org-store-link'.")
9570 (defvar org-store-link-plist nil
9571 "Plist with info about the most recently link created with `org-store-link'.")
9573 (defun org-store-link-functions ()
9574 "Return a list of functions that are called to create and store a link.
9575 The functions defined in the :store property of
9576 `org-link-parameters'.
9578 Each function will be called in turn until one returns a non-nil
9579 value. Each function should check if it is responsible for
9580 creating this link (for example by looking at the major mode).
9581 If not, it must exit and return nil. If yes, it should return
9582 a non-nil value after calling `org-store-link-props' with a list
9583 of properties and values. Special properties are:
9585 :type The link prefix, like \"http\". This must be given.
9586 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9587 This is obligatory as well.
9588 :description Optional default description for the second pair
9589 of brackets in an Org mode link. The user can still change
9590 this when inserting this link into an Org mode buffer.
9592 In addition to these, any additional properties can be specified
9593 and then used in capture templates."
9594 (cl-loop for link in org-link-parameters
9595 with store-func
9596 do (setq store-func (org-link-get-parameter (car link) :store))
9597 if store-func
9598 collect store-func))
9600 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9601 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9603 ;;;###autoload
9604 (defun org-store-link (arg)
9605 "Store an org-link to the current location.
9606 \\<org-mode-map>
9607 This link is added to `org-stored-links' and can later be inserted
9608 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9610 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9611 A single
9612 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9613 `org-gnus-prefer-web-links' for links to Usenet articles.
9615 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9616 skipping storing functions that are not
9617 part of Org core.
9619 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9620 prefix ARG forces storing a link for each line in the
9621 active region."
9622 (interactive "P")
9623 (org-load-modules-maybe)
9624 (if (and (equal arg '(64)) (org-region-active-p))
9625 (save-excursion
9626 (let ((end (region-end)))
9627 (goto-char (region-beginning))
9628 (set-mark (point))
9629 (while (< (point-at-eol) end)
9630 (move-end-of-line 1) (activate-mark)
9631 (let (current-prefix-arg)
9632 (call-interactively 'org-store-link))
9633 (move-beginning-of-line 2)
9634 (set-mark (point)))))
9635 (setq org-store-link-plist nil)
9636 (let (link cpltxt desc description search
9637 txt custom-id agenda-link sfuns sfunsn)
9638 (cond
9640 ;; Store a link using an external link type
9641 ((and (not (equal arg '(16)))
9642 (setq sfuns
9643 (delq
9644 nil (mapcar (lambda (f)
9645 (let (fs) (if (funcall f) (push f fs))))
9646 (org-store-link-functions)))
9647 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9648 (or (and (cdr sfuns)
9649 (funcall (intern
9650 (completing-read
9651 "Which function for creating the link? "
9652 sfunsn nil t (car sfunsn)))))
9653 (funcall (caar sfuns)))
9654 (setq link (plist-get org-store-link-plist :link)
9655 desc (or (plist-get org-store-link-plist
9656 :description)
9657 link))))
9659 ;; Store a link from a source code buffer.
9660 ((org-src-edit-buffer-p)
9661 (let ((coderef-format (org-src-coderef-format)))
9662 (cond ((save-excursion
9663 (beginning-of-line)
9664 (looking-at (org-src-coderef-regexp coderef-format)))
9665 (setq link (format "(%s)" (match-string-no-properties 3))))
9666 ((called-interactively-p 'any)
9667 (let ((label (read-string "Code line label: ")))
9668 (end-of-line)
9669 (setq link (format coderef-format label))
9670 (let ((gc (- 79 (length link))))
9671 (if (< (current-column) gc)
9672 (org-move-to-column gc t)
9673 (insert " ")))
9674 (insert link)
9675 (setq link (concat "(" label ")"))
9676 (setq desc nil)))
9677 (t (setq link nil)))))
9679 ;; We are in the agenda, link to referenced location
9680 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9681 (let ((m (or (get-text-property (point) 'org-hd-marker)
9682 (get-text-property (point) 'org-marker))))
9683 (when m
9684 (org-with-point-at m
9685 (setq agenda-link
9686 (if (called-interactively-p 'any)
9687 (call-interactively 'org-store-link)
9688 (org-store-link nil)))))))
9690 ((eq major-mode 'calendar-mode)
9691 (let ((cd (calendar-cursor-to-date)))
9692 (setq link
9693 (format-time-string
9694 (car org-time-stamp-formats)
9695 (apply 'encode-time
9696 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9697 nil nil nil))))
9698 (org-store-link-props :type "calendar" :date cd)))
9700 ((eq major-mode 'help-mode)
9701 (setq link (concat "help:" (save-excursion
9702 (goto-char (point-min))
9703 (looking-at "^[^ ]+")
9704 (match-string 0))))
9705 (org-store-link-props :type "help"))
9707 ((eq major-mode 'w3-mode)
9708 (setq cpltxt (if (and (buffer-name)
9709 (not (string-match "Untitled" (buffer-name))))
9710 (buffer-name)
9711 (url-view-url t))
9712 link (url-view-url t))
9713 (org-store-link-props :type "w3" :url (url-view-url t)))
9715 ((eq major-mode 'image-mode)
9716 (setq cpltxt (concat "file:"
9717 (abbreviate-file-name buffer-file-name))
9718 link cpltxt)
9719 (org-store-link-props :type "image" :file buffer-file-name))
9721 ;; In dired, store a link to the file of the current line
9722 ((derived-mode-p 'dired-mode)
9723 (let ((file (dired-get-filename nil t)))
9724 (setq file (if file
9725 (abbreviate-file-name
9726 (expand-file-name (dired-get-filename nil t)))
9727 ;; otherwise, no file so use current directory.
9728 default-directory))
9729 (setq cpltxt (concat "file:" file)
9730 link cpltxt)))
9732 ((setq search (run-hook-with-args-until-success
9733 'org-create-file-search-functions))
9734 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9735 "::" search))
9736 (setq cpltxt (or description link)))
9738 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9739 (org-with-limited-levels
9740 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9741 (cond
9742 ;; Store a link using the target at point
9743 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9744 (setq cpltxt
9745 (concat "file:"
9746 (abbreviate-file-name
9747 (buffer-file-name (buffer-base-buffer)))
9748 "::" (match-string 1))
9749 link cpltxt))
9750 ((and (featurep 'org-id)
9751 (or (eq org-id-link-to-org-use-id t)
9752 (and (called-interactively-p 'any)
9753 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9754 (and (eq org-id-link-to-org-use-id
9755 'create-if-interactive-and-no-custom-id)
9756 (not custom-id))))
9757 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9758 ;; Store a link using the ID at point
9759 (setq link (condition-case nil
9760 (prog1 (org-id-store-link)
9761 (setq desc (or (plist-get org-store-link-plist
9762 :description)
9763 "")))
9764 (error
9765 ;; Probably before first headline, link only to file
9766 (concat "file:"
9767 (abbreviate-file-name
9768 (buffer-file-name (buffer-base-buffer))))))))
9770 ;; Just link to current headline
9771 (setq cpltxt (concat "file:"
9772 (abbreviate-file-name
9773 (buffer-file-name (buffer-base-buffer)))))
9774 ;; Add a context search string
9775 (when (org-xor org-context-in-file-links
9776 (equal arg '(4)))
9777 (let* ((element (org-element-at-point))
9778 (name (org-element-property :name element)))
9779 (setq txt (cond
9780 ((org-at-heading-p) nil)
9781 (name)
9782 ((org-region-active-p)
9783 (buffer-substring (region-beginning) (region-end)))))
9784 (when (or (null txt) (string-match "\\S-" txt))
9785 (setq cpltxt
9786 (concat cpltxt "::"
9787 (condition-case nil
9788 (org-make-org-heading-search-string txt)
9789 (error "")))
9790 desc (or name
9791 (nth 4 (ignore-errors (org-heading-components)))
9792 "NONE")))))
9793 (when (string-match "::\\'" cpltxt)
9794 (setq cpltxt (substring cpltxt 0 -2)))
9795 (setq link cpltxt)))))
9797 ((buffer-file-name (buffer-base-buffer))
9798 ;; Just link to this file here.
9799 (setq cpltxt (concat "file:"
9800 (abbreviate-file-name
9801 (buffer-file-name (buffer-base-buffer)))))
9802 ;; Add a context string.
9803 (when (org-xor org-context-in-file-links
9804 (equal arg '(4)))
9805 (setq txt (if (org-region-active-p)
9806 (buffer-substring (region-beginning) (region-end))
9807 (buffer-substring (point-at-bol) (point-at-eol))))
9808 ;; Only use search option if there is some text.
9809 (when (string-match "\\S-" txt)
9810 (setq cpltxt
9811 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9812 desc "NONE")))
9813 (setq link cpltxt))
9815 ((called-interactively-p 'interactive)
9816 (user-error "No method for storing a link from this buffer"))
9818 (t (setq link nil)))
9820 ;; We're done setting link and desc, clean up
9821 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9822 (setq link (or link cpltxt)
9823 desc (or desc cpltxt))
9824 (cond ((not desc))
9825 ((equal desc "NONE") (setq desc nil))
9826 (t (setq desc
9827 (replace-regexp-in-string
9828 org-bracket-link-analytic-regexp
9829 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9830 desc))))
9831 ;; Return the link
9832 (if (not (and (or (called-interactively-p 'any)
9833 executing-kbd-macro)
9834 link))
9835 (or agenda-link (and link (org-make-link-string link desc)))
9836 (push (list link desc) org-stored-links)
9837 (message "Stored: %s" (or desc link))
9838 (when custom-id
9839 (setq link (concat "file:" (abbreviate-file-name
9840 (buffer-file-name)) "::#" custom-id))
9841 (push (list link desc) org-stored-links))
9842 (car org-stored-links)))))
9844 (defun org-store-link-props (&rest plist)
9845 "Store link properties, extract names, addresses and dates."
9846 (let ((x (plist-get plist :from)))
9847 (when x
9848 (let ((adr (mail-extract-address-components x)))
9849 (setq plist (plist-put plist :fromname (car adr)))
9850 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9851 (let ((x (plist-get plist :to)))
9852 (when x
9853 (let ((adr (mail-extract-address-components x)))
9854 (setq plist (plist-put plist :toname (car adr)))
9855 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9856 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9857 (when x
9858 (setq plist (plist-put plist :date-timestamp
9859 (format-time-string
9860 (org-time-stamp-format t) x)))
9861 (setq plist (plist-put plist :date-timestamp-inactive
9862 (format-time-string
9863 (org-time-stamp-format t t) x)))))
9864 (let ((from (plist-get plist :from))
9865 (to (plist-get plist :to)))
9866 (when (and from to org-from-is-user-regexp)
9867 (setq plist
9868 (plist-put plist :fromto
9869 (if (string-match org-from-is-user-regexp from)
9870 (concat "to %t")
9871 (concat "from %f"))))))
9872 (setq org-store-link-plist plist))
9874 (defun org-add-link-props (&rest plist)
9875 "Add these properties to the link property list."
9876 (let (key value)
9877 (while plist
9878 (setq key (pop plist) value (pop plist))
9879 (setq org-store-link-plist
9880 (plist-put org-store-link-plist key value)))))
9882 (defun org-email-link-description (&optional fmt)
9883 "Return the description part of an email link.
9884 This takes information from `org-store-link-plist' and formats it
9885 according to FMT (default from `org-email-link-description-format')."
9886 (setq fmt (or fmt org-email-link-description-format))
9887 (let* ((p org-store-link-plist)
9888 (to (plist-get p :toaddress))
9889 (from (plist-get p :fromaddress))
9890 (table
9891 (list
9892 (cons "%c" (plist-get p :fromto))
9893 (cons "%F" (plist-get p :from))
9894 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9895 (cons "%T" (plist-get p :to))
9896 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9897 (cons "%s" (plist-get p :subject))
9898 (cons "%d" (plist-get p :date))
9899 (cons "%m" (plist-get p :message-id)))))
9900 (when (string-match "%c" fmt)
9901 ;; Check if the user wrote this message
9902 (if (and org-from-is-user-regexp from to
9903 (save-match-data (string-match org-from-is-user-regexp from)))
9904 (setq fmt (replace-match "to %t" t t fmt))
9905 (setq fmt (replace-match "from %f" t t fmt))))
9906 (org-replace-escapes fmt table)))
9908 (defun org-make-org-heading-search-string (&optional string)
9909 "Make search string for the current headline or STRING."
9910 (let ((s (or string
9911 (and (derived-mode-p 'org-mode)
9912 (save-excursion
9913 (org-back-to-heading t)
9914 (org-element-property :raw-value (org-element-at-point))))))
9915 (lines org-context-in-file-links))
9916 (unless string (setq s (concat "*" s))) ;Add * for headlines
9917 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9918 (when (and string (integerp lines) (> lines 0))
9919 (let ((slines (org-split-string s "\n")))
9920 (when (< lines (length slines))
9921 (setq s (mapconcat
9922 'identity
9923 (reverse (nthcdr (- (length slines) lines)
9924 (reverse slines))) "\n")))))
9925 (mapconcat #'identity (split-string s) " ")))
9927 (defun org-make-link-string (link &optional description)
9928 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9929 (unless (org-string-nw-p link) (error "Empty link"))
9930 (let ((uri (cond ((string-match org-link-types-re link)
9931 (concat (match-string 1 link)
9932 (org-link-escape (substring link (match-end 1)))))
9933 ;; For readability, url-encode internal links only
9934 ;; when absolutely needed (i.e, when they contain
9935 ;; square brackets). File links however, are
9936 ;; encoded since, e.g., spaces are significant.
9937 ((or (file-name-absolute-p link)
9938 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9939 (org-link-escape link))
9940 (t link)))
9941 (description
9942 (and (org-string-nw-p description)
9943 ;; Remove brackets from description, as they are fatal.
9944 (replace-regexp-in-string
9945 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9946 (org-trim description)))))
9947 (format "[[%s]%s]"
9949 (if description (format "[%s]" description) ""))))
9951 (defconst org-link-escape-chars
9952 ;;%20 %5B %5D %25
9953 '(?\s ?\[ ?\] ?%)
9954 "List of characters that should be escaped in a link when stored to Org.
9955 This is the list that is used for internal purposes.")
9957 (defun org-link-escape (text &optional table merge)
9958 "Return percent escaped representation of TEXT.
9959 TEXT is a string with the text to escape.
9960 Optional argument TABLE is a list with characters that should be
9961 escaped. When nil, `org-link-escape-chars' is used.
9962 If optional argument MERGE is set, merge TABLE into
9963 `org-link-escape-chars'."
9964 (let ((characters-to-encode
9965 (cond ((null table) org-link-escape-chars)
9966 (merge (append org-link-escape-chars table))
9967 (t table))))
9968 (mapconcat
9969 (lambda (c)
9970 (if (or (memq c characters-to-encode)
9971 (and org-url-hexify-p (or (< c 32) (> c 126))))
9972 (mapconcat (lambda (e) (format "%%%.2X" e))
9973 (or (encode-coding-char c 'utf-8)
9974 (error "Unable to percent escape character: %c" c))
9976 (char-to-string c)))
9977 text "")))
9979 (defun org-link-unescape (str)
9980 "Unhex hexified Unicode parts in string STR.
9981 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9982 reciprocal of `org-link-escape', which see."
9983 (if (org-string-nw-p str)
9984 (replace-regexp-in-string
9985 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9986 str))
9988 (defun org-link-unescape-compound (hex)
9989 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9990 Note: this function also decodes single byte encodings like
9991 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9992 (save-match-data
9993 (let* ((bytes (cdr (split-string hex "%")))
9994 (ret "")
9995 (eat 0)
9996 (sum 0))
9997 (while bytes
9998 (let* ((val (string-to-number (pop bytes) 16))
9999 (shift-xor
10000 (if (= 0 eat)
10001 (cond
10002 ((>= val 252) (cons 6 252))
10003 ((>= val 248) (cons 5 248))
10004 ((>= val 240) (cons 4 240))
10005 ((>= val 224) (cons 3 224))
10006 ((>= val 192) (cons 2 192))
10007 (t (cons 0 0)))
10008 (cons 6 128))))
10009 (when (>= val 192) (setq eat (car shift-xor)))
10010 (setq val (logxor val (cdr shift-xor)))
10011 (setq sum (+ (lsh sum (car shift-xor)) val))
10012 (when (> eat 0) (setq eat (- eat 1)))
10013 (cond
10014 ((= 0 eat) ;multi byte
10015 (setq ret (concat ret (char-to-string sum)))
10016 (setq sum 0))
10017 ((not bytes) ; single byte(s)
10018 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10019 ret)))
10021 (defun org-link-unescape-single-byte-sequence (hex)
10022 "Unhexify hex-encoded single byte character sequences."
10023 (mapconcat (lambda (byte)
10024 (char-to-string (string-to-number byte 16)))
10025 (cdr (split-string hex "%")) ""))
10027 (defun org-xor (a b)
10028 "Exclusive or."
10029 (if a (not b) b))
10031 (defun org-fixup-message-id-for-http (s)
10032 "Replace special characters in a message id, so it can be used in an http query."
10033 (when (string-match "%" s)
10034 (setq s (mapconcat (lambda (c)
10035 (if (eq c ?%)
10036 "%25"
10037 (char-to-string c)))
10038 s "")))
10039 (while (string-match "<" s)
10040 (setq s (replace-match "%3C" t t s)))
10041 (while (string-match ">" s)
10042 (setq s (replace-match "%3E" t t s)))
10043 (while (string-match "@" s)
10044 (setq s (replace-match "%40" t t s)))
10047 (defun org-link-prettify (link)
10048 "Return a human-readable representation of LINK.
10049 The car of LINK must be a raw link.
10050 The cdr of LINK must be either a link description or nil."
10051 (let ((desc (or (cadr link) "<no description>")))
10052 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10053 "<" (car link) ">")))
10055 ;;;###autoload
10056 (defun org-insert-link-global ()
10057 "Insert a link like Org mode does.
10058 This command can be called in any mode to insert a link in Org syntax."
10059 (interactive)
10060 (org-load-modules-maybe)
10061 (org-run-like-in-org-mode 'org-insert-link))
10063 (defun org-insert-all-links (arg &optional pre post)
10064 "Insert all links in `org-stored-links'.
10065 When a universal prefix, do not delete the links from `org-stored-links'.
10066 When `ARG' is a number, insert the last N link(s).
10067 `PRE' and `POST' are optional arguments to define a string to
10068 prepend or to append."
10069 (interactive "P")
10070 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10071 (links (copy-sequence org-stored-links))
10072 (pr (or pre "- "))
10073 (po (or post "\n"))
10074 (cnt 1) l)
10075 (if (null org-stored-links)
10076 (message "No link to insert")
10077 (while (and (or (listp arg) (>= arg cnt))
10078 (setq l (if (listp arg)
10079 (pop links)
10080 (pop org-stored-links))))
10081 (setq cnt (1+ cnt))
10082 (insert pr)
10083 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10084 (insert po)))))
10086 (defun org-insert-last-stored-link (arg)
10087 "Insert the last link stored in `org-stored-links'."
10088 (interactive "p")
10089 (org-insert-all-links arg "" "\n"))
10091 (defun org-link-fontify-links-to-this-file ()
10092 "Fontify links to the current file in `org-stored-links'."
10093 (let ((f (buffer-file-name)) a b)
10094 (setq a (mapcar (lambda(l)
10095 (let ((ll (car l)))
10096 (when (and (string-match "^file:\\(.+\\)::" ll)
10097 (equal f (expand-file-name (match-string 1 ll))))
10098 ll)))
10099 org-stored-links))
10100 (when (featurep 'org-id)
10101 (setq b (mapcar (lambda(l)
10102 (let ((ll (car l)))
10103 (when (and (string-match "^id:\\(.+\\)$" ll)
10104 (equal f (expand-file-name
10105 (or (org-id-find-id-file
10106 (match-string 1 ll)) ""))))
10107 ll)))
10108 org-stored-links)))
10109 (mapcar (lambda(l)
10110 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10111 (delq nil (append a b)))))
10113 (defvar org--links-history nil)
10114 (defun org-insert-link (&optional complete-file link-location default-description)
10115 "Insert a link. At the prompt, enter the link.
10117 Completion can be used to insert any of the link protocol prefixes in use.
10119 The history can be used to select a link previously stored with
10120 `org-store-link'. When the empty string is entered (i.e. if you just
10121 press `RET' at the prompt), the link defaults to the most recently
10122 stored link. As `SPC' triggers completion in the minibuffer, you need to
10123 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10125 You will also be prompted for a description, and if one is given, it will
10126 be displayed in the buffer instead of the link.
10128 If there is already a link at point, this command will allow you to edit
10129 link and description parts.
10131 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10132 file name can be
10133 selected using completion. The path to the file will be relative to the
10134 current directory if the file is in the current directory or a subdirectory.
10135 Otherwise, the link will be the absolute path as completed in the minibuffer
10136 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10137 option `org-link-file-path-type'.
10139 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10140 absolute path even if the file is in
10141 the current directory or below.
10143 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10144 prefix negates `org-keep-stored-link-after-insertion'.
10146 If `org-make-link-description-function' is non-nil, this function will be
10147 called with the link target, and the result will be the default
10148 link description.
10150 If the LINK-LOCATION parameter is non-nil, this value will be used as
10151 the link location instead of reading one interactively.
10153 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10154 as the default description."
10155 (interactive "P")
10156 (let* ((wcf (current-window-configuration))
10157 (origbuf (current-buffer))
10158 (region (when (org-region-active-p)
10159 (buffer-substring (region-beginning) (region-end))))
10160 (remove (and region (list (region-beginning) (region-end))))
10161 (desc region)
10162 (link link-location)
10163 (abbrevs org-link-abbrev-alist-local)
10164 entry all-prefixes auto-desc)
10165 (cond
10166 (link-location) ; specified by arg, just use it.
10167 ((org-in-regexp org-bracket-link-regexp 1)
10168 ;; We do have a link at point, and we are going to edit it.
10169 (setq remove (list (match-beginning 0) (match-end 0)))
10170 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10171 (setq link (read-string "Link: "
10172 (org-link-unescape
10173 (match-string-no-properties 1)))))
10174 ((or (org-in-regexp org-angle-link-re)
10175 (org-in-regexp org-plain-link-re))
10176 ;; Convert to bracket link
10177 (setq remove (list (match-beginning 0) (match-end 0))
10178 link (read-string "Link: "
10179 (org-unbracket-string "<" ">" (match-string 0)))))
10180 ((member complete-file '((4) (16)))
10181 ;; Completing read for file names.
10182 (setq link (org-file-complete-link complete-file)))
10184 ;; Read link, with completion for stored links.
10185 (org-link-fontify-links-to-this-file)
10186 (org-switch-to-buffer-other-window "*Org Links*")
10187 (with-current-buffer "*Org Links*"
10188 (erase-buffer)
10189 (insert "Insert a link.
10190 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10191 (when org-stored-links
10192 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10193 (insert (mapconcat 'org-link-prettify
10194 (reverse org-stored-links) "\n")))
10195 (goto-char (point-min)))
10196 (let ((cw (selected-window)))
10197 (select-window (get-buffer-window "*Org Links*" 'visible))
10198 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10199 (unless (pos-visible-in-window-p (point-max))
10200 (org-fit-window-to-buffer))
10201 (and (window-live-p cw) (select-window cw)))
10202 (setq all-prefixes (append (mapcar 'car abbrevs)
10203 (mapcar 'car org-link-abbrev-alist)
10204 (org-link-types)))
10205 (unwind-protect
10206 ;; Fake a link history, containing the stored links.
10207 (let ((org--links-history
10208 (append (mapcar #'car org-stored-links)
10209 org-insert-link-history)))
10210 (setq link
10211 (org-completing-read
10212 "Link: "
10213 (append
10214 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10215 (mapcar #'car org-stored-links))
10216 nil nil nil
10217 'org--links-history
10218 (caar org-stored-links)))
10219 (unless (org-string-nw-p link) (user-error "No link selected"))
10220 (dolist (l org-stored-links)
10221 (when (equal link (cadr l))
10222 (setq link (car l))
10223 (setq auto-desc t)))
10224 (when (or (member link all-prefixes)
10225 (and (equal ":" (substring link -1))
10226 (member (substring link 0 -1) all-prefixes)
10227 (setq link (substring link 0 -1))))
10228 (setq link (with-current-buffer origbuf
10229 (org-link-try-special-completion link)))))
10230 (set-window-configuration wcf)
10231 (kill-buffer "*Org Links*"))
10232 (setq entry (assoc link org-stored-links))
10233 (or entry (push link org-insert-link-history))
10234 (setq desc (or desc (nth 1 entry)))))
10236 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10237 (not org-keep-stored-link-after-insertion))
10238 (setq org-stored-links (delq (assoc link org-stored-links)
10239 org-stored-links)))
10241 (when (and (string-match org-plain-link-re link)
10242 (not (string-match org-ts-regexp link)))
10243 ;; URL-like link, normalize the use of angular brackets.
10244 (setq link (org-unbracket-string "<" ">" link)))
10246 ;; Check if we are linking to the current file with a search
10247 ;; option If yes, simplify the link by using only the search
10248 ;; option.
10249 (when (and buffer-file-name
10250 (let ((case-fold-search nil))
10251 (string-match "\\`file:\\(.+?\\)::" link)))
10252 (let ((path (match-string-no-properties 1 link))
10253 (search (substring-no-properties link (match-end 0))))
10254 (save-match-data
10255 (when (equal (file-truename buffer-file-name) (file-truename path))
10256 ;; We are linking to this same file, with a search option
10257 (setq link search)))))
10259 ;; Check if we can/should use a relative path. If yes, simplify the link
10260 (let ((case-fold-search nil))
10261 (when (string-match "\\`\\(file\\|docview\\):" link)
10262 (let* ((type (match-string-no-properties 0 link))
10263 (path (substring-no-properties link (match-end 0)))
10264 (origpath path))
10265 (cond
10266 ((or (eq org-link-file-path-type 'absolute)
10267 (equal complete-file '(16)))
10268 (setq path (abbreviate-file-name (expand-file-name path))))
10269 ((eq org-link-file-path-type 'noabbrev)
10270 (setq path (expand-file-name path)))
10271 ((eq org-link-file-path-type 'relative)
10272 (setq path (file-relative-name path)))
10274 (save-match-data
10275 (if (string-match (concat "^" (regexp-quote
10276 (expand-file-name
10277 (file-name-as-directory
10278 default-directory))))
10279 (expand-file-name path))
10280 ;; We are linking a file with relative path name.
10281 (setq path (substring (expand-file-name path)
10282 (match-end 0)))
10283 (setq path (abbreviate-file-name (expand-file-name path)))))))
10284 (setq link (concat type path))
10285 (when (equal desc origpath)
10286 (setq desc path)))))
10288 (if org-make-link-description-function
10289 (setq desc
10290 (or (condition-case nil
10291 (funcall org-make-link-description-function link desc)
10292 (error (progn (message "Can't get link description from `%s'"
10293 (symbol-name org-make-link-description-function))
10294 (sit-for 2) nil)))
10295 (read-string "Description: " default-description)))
10296 (if default-description (setq desc default-description)
10297 (setq desc (or (and auto-desc desc)
10298 (read-string "Description: " desc)))))
10300 (unless (string-match "\\S-" desc) (setq desc nil))
10301 (when remove (apply 'delete-region remove))
10302 (insert (org-make-link-string link desc))
10303 ;; Redisplay so as the new link has proper invisible characters.
10304 (sit-for 0)))
10306 (defun org-link-try-special-completion (type)
10307 "If there is completion support for link type TYPE, offer it."
10308 (let ((fun (org-link-get-parameter type :complete)))
10309 (if (functionp fun)
10310 (funcall fun)
10311 (read-string "Link (no completion support): " (concat type ":")))))
10313 (defun org-file-complete-link (&optional arg)
10314 "Create a file link using completion."
10315 (let ((file (read-file-name "File: "))
10316 (pwd (file-name-as-directory (expand-file-name ".")))
10317 (pwd1 (file-name-as-directory (abbreviate-file-name
10318 (expand-file-name ".")))))
10319 (cond ((equal arg '(16))
10320 (concat "file:"
10321 (abbreviate-file-name (expand-file-name file))))
10322 ((string-match
10323 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10324 (concat "file:" (match-string 1 file)))
10325 ((string-match
10326 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10327 (expand-file-name file))
10328 (concat "file:"
10329 (match-string 1 (expand-file-name file))))
10330 (t (concat "file:" file)))))
10332 (defun org-completing-read (&rest args)
10333 "Completing-read with SPACE being a normal character."
10334 (let ((enable-recursive-minibuffers t)
10335 (minibuffer-local-completion-map
10336 (copy-keymap minibuffer-local-completion-map)))
10337 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10338 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10339 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10340 'org-time-stamp-inactive)
10341 (apply #'completing-read args)))
10343 ;;; Opening/following a link
10345 (defvar org-link-search-failed nil)
10347 (defvar org-open-link-functions nil
10348 "Hook for functions finding a plain text link.
10349 These functions must take a single argument, the link content.
10350 They will be called for links that look like [[link text][description]]
10351 when LINK TEXT does not have a protocol like \"http:\" and does not look
10352 like a filename (e.g. \"./blue.png\").
10354 These functions will be called *before* Org attempts to resolve the
10355 link by doing text searches in the current buffer - so if you want a
10356 link \"[[target]]\" to still find \"<<target>>\", your function should
10357 handle this as a special case.
10359 When the function does handle the link, it must return a non-nil value.
10360 If it decides that it is not responsible for this link, it must return
10361 nil to indicate that that Org can continue with other options like
10362 exact and fuzzy text search.")
10364 (defun org-next-link (&optional search-backward)
10365 "Move forward to the next link.
10366 If the link is in hidden text, expose it."
10367 (interactive "P")
10368 (when (and org-link-search-failed (eq this-command last-command))
10369 (goto-char (point-min))
10370 (message "Link search wrapped back to beginning of buffer"))
10371 (setq org-link-search-failed nil)
10372 (let* ((pos (point))
10373 (ct (org-context))
10374 (a (assq :link ct))
10375 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10376 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10377 ((looking-at org-any-link-re)
10378 ;; Don't stay stuck at link without an org-link face
10379 (forward-char (if search-backward -1 1))))
10380 (if (funcall srch-fun org-any-link-re nil t)
10381 (progn
10382 (goto-char (match-beginning 0))
10383 (when (org-invisible-p) (org-show-context)))
10384 (goto-char pos)
10385 (setq org-link-search-failed t)
10386 (message "No further link found"))))
10388 (defun org-previous-link ()
10389 "Move backward to the previous link.
10390 If the link is in hidden text, expose it."
10391 (interactive)
10392 (funcall 'org-next-link t))
10394 (defun org-translate-link (s)
10395 "Translate a link string if a translation function has been defined."
10396 (with-temp-buffer
10397 (insert (org-trim s))
10398 (org-trim (org-element-interpret-data (org-element-context)))))
10400 (defun org-translate-link-from-planner (type path)
10401 "Translate a link from Emacs Planner syntax so that Org can follow it.
10402 This is still an experimental function, your mileage may vary."
10403 (cond
10404 ((member type '("http" "https" "news" "ftp"))
10405 ;; standard Internet links are the same.
10406 nil)
10407 ((and (equal type "irc") (string-match "^//" path))
10408 ;; Planner has two / at the beginning of an irc link, we have 1.
10409 ;; We should have zero, actually....
10410 (setq path (substring path 1)))
10411 ((and (equal type "lisp") (string-match "^/" path))
10412 ;; Planner has a slash, we do not.
10413 (setq type "elisp" path (substring path 1)))
10414 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10415 ;; A typical message link. Planner has the id after the final slash,
10416 ;; we separate it with a hash mark
10417 (setq path (concat (match-string 1 path) "#"
10418 (org-unbracket-string "<" ">" (match-string 2 path))))))
10419 (cons type path))
10421 (defun org-find-file-at-mouse (ev)
10422 "Open file link or URL at mouse."
10423 (interactive "e")
10424 (mouse-set-point ev)
10425 (org-open-at-point 'in-emacs))
10427 (defun org-open-at-mouse (ev)
10428 "Open file link or URL at mouse.
10429 See the docstring of `org-open-file' for details."
10430 (interactive "e")
10431 (mouse-set-point ev)
10432 (when (eq major-mode 'org-agenda-mode)
10433 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10434 (org-open-at-point))
10436 (defvar org-window-config-before-follow-link nil
10437 "The window configuration before following a link.
10438 This is saved in case the need arises to restore it.")
10440 ;;;###autoload
10441 (defun org-open-at-point-global ()
10442 "Follow a link or time-stamp like Org mode does.
10443 This command can be called in any mode to follow an external link
10444 or a time-stamp that has Org mode syntax. Its behavior is
10445 undefined when called on internal links (e.g., fuzzy links).
10446 Raise an error when there is nothing to follow. "
10447 (interactive)
10448 (cond ((org-in-regexp org-any-link-re)
10449 (org-open-link-from-string (match-string-no-properties 0)))
10450 ((or (org-in-regexp org-ts-regexp-both nil t)
10451 (org-in-regexp org-tsr-regexp-both nil t))
10452 (org-follow-timestamp-link))
10453 (t (user-error "No link found"))))
10455 ;;;###autoload
10456 (defun org-open-link-from-string (s &optional arg reference-buffer)
10457 "Open a link in the string S, as if it was in Org mode."
10458 (interactive "sLink: \nP")
10459 (let ((reference-buffer (or reference-buffer (current-buffer))))
10460 (with-temp-buffer
10461 (let ((org-inhibit-startup (not reference-buffer)))
10462 (org-mode)
10463 (insert s)
10464 (goto-char (point-min))
10465 (when reference-buffer
10466 (setq org-link-abbrev-alist-local
10467 (with-current-buffer reference-buffer
10468 org-link-abbrev-alist-local)))
10469 (org-open-at-point arg reference-buffer)))))
10471 (defvar org-open-at-point-functions nil
10472 "Hook that is run when following a link at point.
10474 Functions in this hook must return t if they identify and follow
10475 a link at point. If they don't find anything interesting at point,
10476 they must return nil.")
10478 (defvar org-link-search-inhibit-query nil)
10479 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10480 (defun org--open-doi-link (path)
10481 "Open a \"doi\" type link.
10482 PATH is a the path to search for, as a string."
10483 (browse-url (url-encode-url (concat org-doi-server-url path))))
10485 (defun org--open-elisp-link (path)
10486 "Open a \"elisp\" type link.
10487 PATH is the sexp to evaluate, as a string."
10488 (let ((cmd path))
10489 (if (or (and (org-string-nw-p
10490 org-confirm-elisp-link-not-regexp)
10491 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10492 (not org-confirm-elisp-link-function)
10493 (funcall org-confirm-elisp-link-function
10494 (format "Execute \"%s\" as elisp? "
10495 (org-add-props cmd nil 'face 'org-warning))))
10496 (message "%s => %s" cmd
10497 (if (eq (string-to-char cmd) ?\()
10498 (eval (read cmd))
10499 (call-interactively (read cmd))))
10500 (user-error "Abort"))))
10502 (defun org--open-help-link (path)
10503 "Open a \"help\" type link.
10504 PATH is a symbol name, as a string."
10505 (pcase (intern path)
10506 ((and (pred fboundp) variable) (describe-function variable))
10507 ((and (pred boundp) function) (describe-variable function))
10508 (name (user-error "Unknown function or variable: %s" name))))
10510 (defun org--open-shell-link (path)
10511 "Open a \"shell\" type link.
10512 PATH is the command to execute, as a string."
10513 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10514 (cmd path))
10515 (if (or (and (org-string-nw-p
10516 org-confirm-shell-link-not-regexp)
10517 (string-match
10518 org-confirm-shell-link-not-regexp cmd))
10519 (not org-confirm-shell-link-function)
10520 (funcall org-confirm-shell-link-function
10521 (format "Execute \"%s\" in shell? "
10522 (org-add-props cmd nil
10523 'face 'org-warning))))
10524 (progn
10525 (message "Executing %s" cmd)
10526 (shell-command cmd buf)
10527 (when (featurep 'midnight)
10528 (setq clean-buffer-list-kill-buffer-names
10529 (cons (buffer-name buf)
10530 clean-buffer-list-kill-buffer-names))))
10531 (user-error "Abort"))))
10533 (defun org-open-at-point (&optional arg reference-buffer)
10534 "Open link, timestamp, footnote or tags at point.
10536 When point is on a link, follow it. Normally, files will be
10537 opened by an appropriate application. If the optional prefix
10538 argument ARG is non-nil, Emacs will visit the file. With
10539 a double prefix argument, try to open outside of Emacs, in the
10540 application the system uses for this file type.
10542 When point is on a timestamp, open the agenda at the day
10543 specified.
10545 When point is a footnote definition, move to the first reference
10546 found. If it is on a reference, move to the associated
10547 definition.
10549 When point is on a headline, display a list of every link in the
10550 entry, so it is possible to pick one, or all, of them. If point
10551 is on a tag, call `org-tags-view' instead.
10553 When optional argument REFERENCE-BUFFER is non-nil, it should
10554 specify a buffer from where the link search should happen. This
10555 is used internally by `org-open-link-from-string'.
10557 On top of syntactically correct links, this function will also
10558 try to open links and time-stamps in comments, example
10559 blocks... i.e., whenever point is on something looking like
10560 a timestamp or a link."
10561 (interactive "P")
10562 ;; On a code block, open block's results.
10563 (unless (call-interactively 'org-babel-open-src-block-result)
10564 (org-load-modules-maybe)
10565 (setq org-window-config-before-follow-link (current-window-configuration))
10566 (org-remove-occur-highlights nil nil t)
10567 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10568 (let* ((context
10569 ;; Only consider supported types, even if they are not
10570 ;; the closest one.
10571 (org-element-lineage
10572 (org-element-context)
10573 '(clock footnote-definition footnote-reference headline
10574 inlinetask link timestamp)
10576 (type (org-element-type context))
10577 (value (org-element-property :value context)))
10578 (cond
10579 ;; On a headline or an inlinetask, but not on a timestamp,
10580 ;; a link, a footnote reference.
10581 ((memq type '(headline inlinetask))
10582 (org-match-line org-complex-heading-regexp)
10583 (if (and (match-beginning 5)
10584 (>= (point) (match-beginning 5))
10585 (< (point) (match-end 5)))
10586 ;; On tags.
10587 (org-tags-view arg (substring (match-string 5) 0 -1))
10588 ;; Not on tags.
10589 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10590 (`(nil . ,_)
10591 (require 'org-attach)
10592 (org-attach-reveal 'if-exists))
10593 (`(,links . ,links-end)
10594 (dolist (link (if (stringp links) (list links) links))
10595 (search-forward link nil links-end)
10596 (goto-char (match-beginning 0))
10597 (org-open-at-point))))))
10598 ;; On a footnote reference or at definition's label.
10599 ((or (eq type 'footnote-reference)
10600 (and (eq type 'footnote-definition)
10601 (save-excursion
10602 ;; Do not validate action when point is on the
10603 ;; spaces right after the footnote label, in
10604 ;; order to be on par with behaviour on links.
10605 (skip-chars-forward " \t")
10606 (let ((begin
10607 (org-element-property :contents-begin context)))
10608 (if begin (< (point) begin)
10609 (= (org-element-property :post-affiliated context)
10610 (line-beginning-position)))))))
10611 (org-footnote-action))
10612 ;; No valid context. Ignore catch-all types like `headline'.
10613 ;; If point is on something looking like a link or
10614 ;; a time-stamp, try opening it. It may be useful in
10615 ;; comments, example blocks...
10616 ((memq type '(footnote-definition headline inlinetask nil))
10617 (call-interactively #'org-open-at-point-global))
10618 ;; On a clock line, make sure point is on the timestamp
10619 ;; before opening it.
10620 ((and (eq type 'clock)
10621 value
10622 (>= (point) (org-element-property :begin value))
10623 (<= (point) (org-element-property :end value)))
10624 (org-follow-timestamp-link))
10625 ;; Do nothing on white spaces after an object.
10626 ((>= (point)
10627 (save-excursion
10628 (goto-char (org-element-property :end context))
10629 (skip-chars-backward " \t")
10630 (point)))
10631 (user-error "No link found"))
10632 ((eq type 'timestamp) (org-follow-timestamp-link))
10633 ((eq type 'link)
10634 (let ((type (org-element-property :type context))
10635 (path (org-link-unescape (org-element-property :path context))))
10636 ;; Switch back to REFERENCE-BUFFER needed when called in
10637 ;; a temporary buffer through `org-open-link-from-string'.
10638 (with-current-buffer (or reference-buffer (current-buffer))
10639 (cond
10640 ((equal type "file")
10641 (if (string-match "[*?{]" (file-name-nondirectory path))
10642 (dired path)
10643 ;; Look into `org-link-parameters' in order to find
10644 ;; a DEDICATED-FUNCTION to open file. The function
10645 ;; will be applied on raw link instead of parsed
10646 ;; link due to the limitation in `org-add-link-type'
10647 ;; ("open" function called with a single argument).
10648 ;; If no such function is found, fallback to
10649 ;; `org-open-file'.
10650 (let* ((option (org-element-property :search-option context))
10651 (app (org-element-property :application context))
10652 (dedicated-function
10653 (org-link-get-parameter
10654 (if app (concat type "+" app) type)
10655 :follow)))
10656 (if dedicated-function
10657 (funcall dedicated-function
10658 (concat path
10659 (and option (concat "::" option))))
10660 (apply #'org-open-file
10661 path
10662 (cond (arg)
10663 ((equal app "emacs") 'emacs)
10664 ((equal app "sys") 'system))
10665 (cond ((not option) nil)
10666 ((string-match-p "\\`[0-9]+\\'" option)
10667 (list (string-to-number option)))
10668 (t (list nil
10669 (org-link-unescape option)))))))))
10670 ((functionp (org-link-get-parameter type :follow))
10671 (funcall (org-link-get-parameter type :follow) path))
10672 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10673 (unless (run-hook-with-args-until-success
10674 'org-open-link-functions path)
10675 (if (not arg) (org-mark-ring-push)
10676 (switch-to-buffer-other-window
10677 (org-get-buffer-for-internal-link (current-buffer))))
10678 (let ((destination
10679 (org-with-wide-buffer
10680 (if (equal type "radio")
10681 (org-search-radio-target
10682 (org-element-property :path context))
10683 (org-link-search
10684 (if (member type '("custom-id" "coderef"))
10685 (org-element-property :raw-link context)
10686 path)
10687 ;; Prevent fuzzy links from matching
10688 ;; themselves.
10689 (and (equal type "fuzzy")
10690 (+ 2 (org-element-property :begin context)))))
10691 (point))))
10692 (unless (and (<= (point-min) destination)
10693 (>= (point-max) destination))
10694 (widen))
10695 (goto-char destination))))
10696 (t (browse-url-at-point))))))
10697 (t (user-error "No link found")))))
10698 (run-hook-with-args 'org-follow-link-hook)))
10700 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10701 "Offer links in the current entry and return the selected link.
10702 If there is only one link, return it.
10703 If NTH is an integer, return the NTH link found.
10704 If ZERO is a string, check also this string for a link, and if
10705 there is one, return it."
10706 (with-current-buffer buffer
10707 (org-with-wide-buffer
10708 (goto-char marker)
10709 (let ((cnt ?0)
10710 have-zero end links link c)
10711 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10712 (push (match-string 0 zero) links)
10713 (setq cnt (1- cnt) have-zero t))
10714 (save-excursion
10715 (org-back-to-heading t)
10716 (setq end (save-excursion (outline-next-heading) (point)))
10717 (while (re-search-forward org-any-link-re end t)
10718 (push (match-string 0) links))
10719 (setq links (org-uniquify (reverse links))))
10720 (cond
10721 ((null links)
10722 (message "No links"))
10723 ((equal (length links) 1)
10724 (setq link (car links)))
10725 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10726 (setq link (nth (if have-zero nth (1- nth)) links)))
10727 (t ; we have to select a link
10728 (save-excursion
10729 (save-window-excursion
10730 (delete-other-windows)
10731 (with-output-to-temp-buffer "*Select Link*"
10732 (dolist (l links)
10733 (cond
10734 ((not (string-match org-bracket-link-regexp l))
10735 (princ (format "[%c] %s\n" (cl-incf cnt)
10736 (org-unbracket-string "<" ">" l))))
10737 ((match-end 3)
10738 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10739 (match-string 3 l) (match-string 1 l))))
10740 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10741 (match-string 1 l)))))))
10742 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10743 (message "Select link to open, RET to open all:")
10744 (setq c (read-char-exclusive))
10745 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10746 (when (equal c ?q) (user-error "Abort"))
10747 (if (equal c ?\C-m)
10748 (setq link links)
10749 (setq nth (- c ?0))
10750 (when have-zero (setq nth (1+ nth)))
10751 (unless (and (integerp nth) (>= (length links) nth))
10752 (user-error "Invalid link selection"))
10753 (setq link (nth (1- nth) links)))))
10754 (cons link end)))))
10756 ;; TODO: These functions are deprecated since `org-open-at-point'
10757 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10758 (defun org-open-file-with-system (path)
10759 "Open file at PATH using the system way of opening it."
10760 (org-open-file path 'system))
10761 (defun org-open-file-with-emacs (path)
10762 "Open file at PATH in Emacs."
10763 (org-open-file path 'emacs))
10766 ;;; File search
10768 (defvar org-create-file-search-functions nil
10769 "List of functions to construct the right search string for a file link.
10770 These functions are called in turn with point at the location to
10771 which the link should point.
10773 A function in the hook should first test if it would like to
10774 handle this file type, for example by checking the `major-mode'
10775 or the file extension. If it decides not to handle this file, it
10776 should just return nil to give other functions a chance. If it
10777 does handle the file, it must return the search string to be used
10778 when following the link. The search string will be part of the
10779 file link, given after a double colon, and `org-open-at-point'
10780 will automatically search for it. If special measures must be
10781 taken to make the search successful, another function should be
10782 added to the companion hook `org-execute-file-search-functions',
10783 which see.
10785 A function in this hook may also use `setq' to set the variable
10786 `description' to provide a suggestion for the descriptive text to
10787 be used for this link when it gets inserted into an Org buffer
10788 with \\[org-insert-link].")
10790 (defvar org-execute-file-search-functions nil
10791 "List of functions to execute a file search triggered by a link.
10793 Functions added to this hook must accept a single argument, the
10794 search string that was part of the file link, the part after the
10795 double colon. The function must first check if it would like to
10796 handle this search, for example by checking the `major-mode' or
10797 the file extension. If it decides not to handle this search, it
10798 should just return nil to give other functions a chance. If it
10799 does handle the search, it must return a non-nil value to keep
10800 other functions from trying.
10802 Each function can access the current prefix argument through the
10803 variable `current-prefix-arg'. Note that a single prefix is used
10804 to force opening a link in Emacs, so it may be good to only use a
10805 numeric or double prefix to guide the search function.
10807 In case this is needed, a function in this hook can also restore
10808 the window configuration before `org-open-at-point' was called using:
10810 (set-window-configuration org-window-config-before-follow-link)")
10812 (defun org-search-radio-target (target)
10813 "Search a radio target matching TARGET in current buffer.
10814 White spaces are not significant."
10815 (let ((re (format "<<<%s>>>"
10816 (mapconcat #'regexp-quote
10817 (split-string target)
10818 "[ \t]+\\(?:\n[ \t]*\\)?")))
10819 (origin (point)))
10820 (goto-char (point-min))
10821 (catch :radio-match
10822 (while (re-search-forward re nil t)
10823 (backward-char)
10824 (let ((object (org-element-context)))
10825 (when (eq (org-element-type object) 'radio-target)
10826 (goto-char (org-element-property :begin object))
10827 (org-show-context 'link-search)
10828 (throw :radio-match nil))))
10829 (goto-char origin)
10830 (user-error "No match for radio target: %s" target))))
10832 (defun org-link-search (s &optional avoid-pos stealth)
10833 "Search for a search string S.
10835 If S starts with \"#\", it triggers a custom ID search.
10837 If S is enclosed within parenthesis, it initiates a coderef
10838 search.
10840 If S is surrounded by forward slashes, it is interpreted as
10841 a regular expression. In Org mode files, this will create an
10842 `org-occur' sparse tree. In ordinary files, `occur' will be used
10843 to list matches. If the current buffer is in `dired-mode', grep
10844 will be used to search in all files.
10846 When AVOID-POS is given, ignore matches near that position.
10848 When optional argument STEALTH is non-nil, do not modify
10849 visibility around point, thus ignoring `org-show-context-detail'
10850 variable.
10852 Search is case-insensitive and ignores white spaces. Return type
10853 of matched result, which is either `dedicated' or `fuzzy'."
10854 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10855 (let* ((case-fold-search t)
10856 (origin (point))
10857 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10858 (starred (eq (string-to-char normalized) ?*))
10859 (words (split-string (if starred (substring s 1) s)))
10860 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10861 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10862 type)
10863 (cond
10864 ;; Check if there are any special search functions.
10865 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10866 ((eq (string-to-char s) ?#)
10867 ;; Look for a custom ID S if S starts with "#".
10868 (let* ((id (substring normalized 1))
10869 (match (org-find-property "CUSTOM_ID" id)))
10870 (if match (progn (goto-char match) (setf type 'dedicated))
10871 (error "No match for custom ID: %s" id))))
10872 ((string-match "\\`(\\(.*\\))\\'" normalized)
10873 ;; Look for coderef targets if S is enclosed within parenthesis.
10874 (let ((coderef (match-string-no-properties 1 normalized))
10875 (re (substring s-single-re 1 -1)))
10876 (goto-char (point-min))
10877 (catch :coderef-match
10878 (while (re-search-forward re nil t)
10879 (let ((element (org-element-at-point)))
10880 (when (and (memq (org-element-type element)
10881 '(example-block src-block))
10882 ;; Build proper regexp according to current
10883 ;; block's label format.
10884 (let ((label-fmt
10885 (regexp-quote
10886 (or (org-element-property :label-fmt element)
10887 org-coderef-label-format))))
10888 (save-excursion
10889 (beginning-of-line)
10890 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10891 (format label-fmt coderef))))))
10892 (setq type 'dedicated)
10893 (goto-char (match-beginning 1))
10894 (throw :coderef-match nil))))
10895 (goto-char origin)
10896 (error "No match for coderef: %s" coderef))))
10897 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10898 ;; Look for a regular expression.
10899 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10900 (match-string 1 s)))
10901 ;; From here, we handle fuzzy links.
10903 ;; Look for targets, only if not in a headline search.
10904 ((and (not starred)
10905 (let ((target (format "<<%s>>" s-multi-re)))
10906 (catch :target-match
10907 (goto-char (point-min))
10908 (while (re-search-forward target nil t)
10909 (backward-char)
10910 (let ((context (org-element-context)))
10911 (when (eq (org-element-type context) 'target)
10912 (setq type 'dedicated)
10913 (goto-char (org-element-property :begin context))
10914 (throw :target-match t))))
10915 nil))))
10916 ;; Look for elements named after S, only if not in a headline
10917 ;; search.
10918 ((and (not starred)
10919 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10920 (catch :name-match
10921 (goto-char (point-min))
10922 (while (re-search-forward name nil t)
10923 (let ((element (org-element-at-point)))
10924 (when (equal words
10925 (split-string
10926 (org-element-property :name element)))
10927 (setq type 'dedicated)
10928 (beginning-of-line)
10929 (throw :name-match t))))
10930 nil))))
10931 ;; Regular text search. Prefer headlines in Org mode buffers.
10932 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10933 ;; statistics cookies and tags.
10934 ((and (derived-mode-p 'org-mode)
10935 (let ((title-re
10936 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10937 org-outline-regexp-bol
10938 org-comment-string
10939 (mapconcat #'regexp-quote words ".+")))
10940 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10941 (comment-re (eval-when-compile
10942 (format "\\`%s[ \t]+" org-comment-string))))
10943 (goto-char (point-min))
10944 (catch :found
10945 (while (re-search-forward title-re nil t)
10946 (when (equal words
10947 (split-string
10948 (replace-regexp-in-string
10949 cookie-re ""
10950 (replace-regexp-in-string
10951 comment-re "" (org-get-heading t t t)))))
10952 (throw :found t)))
10953 nil)))
10954 (beginning-of-line)
10955 (setq type 'dedicated))
10956 ;; Offer to create non-existent headline depending on
10957 ;; `org-link-search-must-match-exact-headline'.
10958 ((and (derived-mode-p 'org-mode)
10959 (not org-link-search-inhibit-query)
10960 (eq org-link-search-must-match-exact-headline 'query-to-create)
10961 (yes-or-no-p "No match - create this as a new heading? "))
10962 (goto-char (point-max))
10963 (unless (bolp) (newline))
10964 (org-insert-heading nil t t)
10965 (insert s "\n")
10966 (beginning-of-line 0))
10967 ;; Only headlines are looked after. No need to process
10968 ;; further: throw an error.
10969 ((and (derived-mode-p 'org-mode)
10970 (or starred org-link-search-must-match-exact-headline))
10971 (goto-char origin)
10972 (error "No match for fuzzy expression: %s" normalized))
10973 ;; Regular text search.
10974 ((catch :fuzzy-match
10975 (goto-char (point-min))
10976 (while (re-search-forward s-multi-re nil t)
10977 ;; Skip match if it contains AVOID-POS or it is included in
10978 ;; a link with a description but outside the description.
10979 (unless (or (and avoid-pos
10980 (<= (match-beginning 0) avoid-pos)
10981 (> (match-end 0) avoid-pos))
10982 (and (save-match-data
10983 (org-in-regexp org-bracket-link-regexp))
10984 (match-beginning 3)
10985 (or (> (match-beginning 3) (point))
10986 (<= (match-end 3) (point)))
10987 (org-element-lineage
10988 (save-match-data (org-element-context))
10989 '(link) t)))
10990 (goto-char (match-beginning 0))
10991 (setq type 'fuzzy)
10992 (throw :fuzzy-match t)))
10993 nil))
10994 ;; All failed. Throw an error.
10995 (t (goto-char origin)
10996 (error "No match for fuzzy expression: %s" normalized)))
10997 ;; Disclose surroundings of match, if appropriate.
10998 (when (and (derived-mode-p 'org-mode) (not stealth))
10999 (org-show-context 'link-search))
11000 type))
11002 (defun org-get-buffer-for-internal-link (buffer)
11003 "Return a buffer to be used for displaying the link target of internal links."
11004 (cond
11005 ((not org-display-internal-link-with-indirect-buffer)
11006 buffer)
11007 ((string-suffix-p "(Clone)" (buffer-name buffer))
11008 (message "Buffer is already a clone, not making another one")
11009 ;; we also do not modify visibility in this case
11010 buffer)
11011 (t ; make a new indirect buffer for displaying the link
11012 (let* ((bn (buffer-name buffer))
11013 (ibn (concat bn "(Clone)"))
11014 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11015 (with-current-buffer ib (org-overview))
11016 ib))))
11018 (defun org-do-occur (regexp &optional cleanup)
11019 "Call the Emacs command `occur'.
11020 If CLEANUP is non-nil, remove the printout of the regular expression
11021 in the *Occur* buffer. This is useful if the regex is long and not useful
11022 to read."
11023 (occur regexp)
11024 (when cleanup
11025 (let ((cwin (selected-window)) win beg end)
11026 (when (setq win (get-buffer-window "*Occur*"))
11027 (select-window win))
11028 (goto-char (point-min))
11029 (when (re-search-forward "match[a-z]+" nil t)
11030 (setq beg (match-end 0))
11031 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11032 (setq end (1- (match-beginning 0)))))
11033 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11034 (goto-char (point-min))
11035 (select-window cwin))))
11037 ;;; The mark ring for links jumps
11039 (defvar org-mark-ring nil
11040 "Mark ring for positions before jumps in Org mode.")
11041 (defvar org-mark-ring-last-goto nil
11042 "Last position in the mark ring used to go back.")
11043 ;; Fill and close the ring
11044 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11045 (dotimes (_ org-mark-ring-length)
11046 (push (make-marker) org-mark-ring))
11047 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11048 org-mark-ring)
11050 (defun org-mark-ring-push (&optional pos buffer)
11051 "Put the current position or POS into the mark ring and rotate it."
11052 (interactive)
11053 (setq pos (or pos (point)))
11054 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11055 (move-marker (car org-mark-ring)
11056 (or pos (point))
11057 (or buffer (current-buffer)))
11058 (message "%s"
11059 (substitute-command-keys
11060 "Position saved to mark ring, go back with \
11061 `\\[org-mark-ring-goto]'.")))
11063 (defun org-mark-ring-goto (&optional n)
11064 "Jump to the previous position in the mark ring.
11065 With prefix arg N, jump back that many stored positions. When
11066 called several times in succession, walk through the entire ring.
11067 Org mode commands jumping to a different position in the current file,
11068 or to another Org file, automatically push the old position onto the ring."
11069 (interactive "p")
11070 (let (p m)
11071 (if (eq last-command this-command)
11072 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11073 (setq p org-mark-ring))
11074 (setq org-mark-ring-last-goto p)
11075 (setq m (car p))
11076 (pop-to-buffer-same-window (marker-buffer m))
11077 (goto-char m)
11078 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11080 (defun org-add-angle-brackets (s)
11081 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11082 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11085 ;;; Following specific links
11087 (defvar org-agenda-buffer-tmp-name)
11088 (defvar org-agenda-start-on-weekday)
11089 (defun org-follow-timestamp-link ()
11090 "Open an agenda view for the time-stamp date/range at point."
11091 (cond
11092 ((org-at-date-range-p t)
11093 (let ((org-agenda-start-on-weekday)
11094 (t1 (match-string 1))
11095 (t2 (match-string 2)) tt1 tt2)
11096 (setq tt1 (time-to-days (org-time-string-to-time t1))
11097 tt2 (time-to-days (org-time-string-to-time t2)))
11098 (let ((org-agenda-buffer-tmp-name
11099 (format "*Org Agenda(a:%s)"
11100 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11101 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11102 ((org-at-timestamp-p 'lax)
11103 (let ((org-agenda-buffer-tmp-name
11104 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11105 (org-agenda-list nil (time-to-days (org-time-string-to-time
11106 (substring (match-string 1) 0 10)))
11107 1)))
11108 (t (error "This should not happen"))))
11111 ;;; Following file links
11112 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11113 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11114 (declare-function mailcap-mime-info
11115 "mailcap" (string &optional request no-decode))
11116 (defvar org-wait nil)
11117 (defun org-open-file (path &optional in-emacs line search)
11118 "Open the file at PATH.
11119 First, this expands any special file name abbreviations. Then the
11120 configuration variable `org-file-apps' is checked if it contains an
11121 entry for this file type, and if yes, the corresponding command is launched.
11123 If no application is found, Emacs simply visits the file.
11125 With optional prefix argument IN-EMACS, Emacs will visit the file.
11126 With a double \\[universal-argument] \\[universal-argument] \
11127 prefix arg, Org tries to avoid opening in Emacs
11128 and to use an external application to visit the file.
11130 Optional LINE specifies a line to go to, optional SEARCH a string
11131 to search for. If LINE or SEARCH is given, the file will be
11132 opened in Emacs, unless an entry from org-file-apps that makes
11133 use of groups in a regexp matches.
11135 If you want to change the way frames are used when following a
11136 link, please customize `org-link-frame-setup'.
11138 If the file does not exist, an error is thrown."
11139 (let* ((file (if (equal path "")
11140 buffer-file-name
11141 (substitute-in-file-name (expand-file-name path))))
11142 (file-apps (append org-file-apps (org-default-apps)))
11143 (apps (cl-remove-if
11144 'org-file-apps-entry-match-against-dlink-p file-apps))
11145 (apps-dlink (cl-remove-if-not
11146 'org-file-apps-entry-match-against-dlink-p file-apps))
11147 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11148 (dirp (unless remp (file-directory-p file)))
11149 (file (if (and dirp org-open-directory-means-index-dot-org)
11150 (concat (file-name-as-directory file) "index.org")
11151 file))
11152 (a-m-a-p (assq 'auto-mode apps))
11153 (dfile (downcase file))
11154 ;; Reconstruct the original link from the PATH, LINE and
11155 ;; SEARCH args.
11156 (link (cond (line (concat file "::" (number-to-string line)))
11157 (search (concat file "::" search))
11158 (t file)))
11159 (dlink (downcase link))
11160 (ext
11161 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11162 (match-string 1 dfile)))
11163 (save-position-maybe
11164 (let ((old-buffer (current-buffer))
11165 (old-pos (point))
11166 (old-mode major-mode))
11167 (lambda ()
11168 (and (derived-mode-p 'org-mode)
11169 (eq old-mode 'org-mode)
11170 (or (not (eq old-buffer (current-buffer)))
11171 (not (eq old-pos (point))))
11172 (org-mark-ring-push old-pos old-buffer)))))
11173 cmd link-match-data)
11174 (cond
11175 ((member in-emacs '((16) system))
11176 (setq cmd (cdr (assq 'system apps))))
11177 (in-emacs (setq cmd 'emacs))
11179 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11180 (and dirp (cdr (assq 'directory apps)))
11181 ;; First, try matching against apps-dlink if we
11182 ;; get a match here, store the match data for
11183 ;; later.
11184 (let ((match (assoc-default dlink apps-dlink
11185 'string-match)))
11186 (if match
11187 (progn (setq link-match-data (match-data))
11188 match)
11189 (progn (setq in-emacs (or in-emacs line search))
11190 nil))) ; if we have no match in apps-dlink,
11191 ; always open the file in emacs if line or search
11192 ; is given (for backwards compatibility)
11193 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11194 'string-match)
11195 (cdr (assoc ext apps))
11196 (cdr (assq t apps))))))
11197 (when (eq cmd 'system)
11198 (setq cmd (cdr (assq 'system apps))))
11199 (when (eq cmd 'default)
11200 (setq cmd (cdr (assoc t apps))))
11201 (when (eq cmd 'mailcap)
11202 (require 'mailcap)
11203 (mailcap-parse-mailcaps)
11204 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11205 (command (mailcap-mime-info mime-type)))
11206 (if (stringp command)
11207 (setq cmd command)
11208 (setq cmd 'emacs))))
11209 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11210 (not (file-exists-p file))
11211 (not org-open-non-existing-files))
11212 (user-error "No such file: %s" file))
11213 (cond
11214 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11215 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11216 (while (string-match "['\"]%s['\"]" cmd)
11217 (setq cmd (replace-match "%s" t t cmd)))
11218 (setq cmd (replace-regexp-in-string
11219 "%s"
11220 (shell-quote-argument (convert-standard-filename file))
11222 nil t))
11224 ;; Replace "%1", "%2" etc. in command with group matches from regex
11225 (save-match-data
11226 (let ((match-index 1)
11227 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11228 (set-match-data link-match-data)
11229 (while (<= match-index number-of-groups)
11230 (let ((regex (concat "%" (number-to-string match-index)))
11231 (replace-with (match-string match-index dlink)))
11232 (while (string-match regex cmd)
11233 (setq cmd (replace-match replace-with t t cmd))))
11234 (setq match-index (+ match-index 1)))))
11236 (save-window-excursion
11237 (message "Running %s...done" cmd)
11238 (start-process-shell-command cmd nil cmd)
11239 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11240 ((or (stringp cmd)
11241 (eq cmd 'emacs))
11242 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11243 (widen)
11244 (cond (line (org-goto-line line)
11245 (when (derived-mode-p 'org-mode) (org-reveal)))
11246 (search (condition-case err
11247 (org-link-search search)
11248 ;; Save position before error-ing out so user
11249 ;; can easily move back to the original buffer.
11250 (error (funcall save-position-maybe)
11251 (error (nth 1 err)))))))
11252 ((functionp cmd)
11253 (save-match-data
11254 (set-match-data link-match-data)
11255 (condition-case nil
11256 (funcall cmd file link)
11257 ;; FIXME: Remove this check when most default installations
11258 ;; of Emacs have at least Org 9.0.
11259 ((debug wrong-number-of-arguments wrong-type-argument
11260 invalid-function)
11261 (user-error "Please see Org News for version 9.0 about \
11262 `org-file-apps'--Lisp error: %S" cmd)))))
11263 ((consp cmd)
11264 ;; FIXME: Remove this check when most default installations of
11265 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11266 ;; fall back to `org-link-frame-setup' for an old usage of
11267 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11268 (user-error "Please see Org News for version 9.0 about \
11269 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11270 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11271 (funcall save-position-maybe)))
11273 (defun org-file-apps-entry-match-against-dlink-p (entry)
11274 "This function returns non-nil if `entry' uses a regular
11275 expression which should be matched against the whole link by
11276 org-open-file.
11278 It assumes that is the case when the entry uses a regular
11279 expression which has at least one grouping construct and the
11280 action is either a lisp form or a command string containing
11281 `%1', i.e. using at least one subexpression match as a
11282 parameter."
11283 (let ((selector (car entry))
11284 (action (cdr entry)))
11285 (if (stringp selector)
11286 (and (> (regexp-opt-depth selector) 0)
11287 (or (and (stringp action)
11288 (string-match "%[0-9]" action))
11289 (consp action)))
11290 nil)))
11292 (defun org-default-apps ()
11293 "Return the default applications for this operating system."
11294 (cond
11295 ((eq system-type 'darwin)
11296 org-file-apps-defaults-macosx)
11297 ((eq system-type 'windows-nt)
11298 org-file-apps-defaults-windowsnt)
11299 (t org-file-apps-defaults-gnu)))
11301 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11302 "Convert extensions to regular expressions in the cars of LIST.
11303 Also, weed out any non-string entries, because the return value is used
11304 only for regexp matching.
11305 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11306 point to the symbol `emacs', indicating that the file should
11307 be opened in Emacs."
11308 (append
11309 (delq nil
11310 (mapcar (lambda (x)
11311 (unless (not (stringp (car x)))
11312 (if (string-match "\\W" (car x))
11314 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11315 list))
11316 (when add-auto-mode
11317 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11319 (defvar ange-ftp-name-format)
11320 (defun org-file-remote-p (file)
11321 "Test whether FILE specifies a location on a remote system.
11322 Return non-nil if the location is indeed remote.
11324 For example, the filename \"/user@host:/foo\" specifies a location
11325 on the system \"/user@host:\"."
11326 (cond ((fboundp 'file-remote-p)
11327 (file-remote-p file))
11328 ((fboundp 'tramp-handle-file-remote-p)
11329 (tramp-handle-file-remote-p file))
11330 ((and (boundp 'ange-ftp-name-format)
11331 (string-match (car ange-ftp-name-format) file))
11332 t)))
11335 ;;;; Refiling
11337 (defun org-get-org-file ()
11338 "Read a filename, with default directory `org-directory'."
11339 (let ((default (or org-default-notes-file remember-data-file)))
11340 (read-file-name (format "File name [%s]: " default)
11341 (file-name-as-directory org-directory)
11342 default)))
11344 (defun org-notes-order-reversed-p ()
11345 "Check if the current file should receive notes in reversed order."
11346 (cond
11347 ((not org-reverse-note-order) nil)
11348 ((eq t org-reverse-note-order) t)
11349 ((not (listp org-reverse-note-order)) nil)
11350 (t (catch 'exit
11351 (dolist (entry org-reverse-note-order)
11352 (when (string-match (car entry) buffer-file-name)
11353 (throw 'exit (cdr entry))))))))
11355 (defvar org-refile-target-table nil
11356 "The list of refile targets, created by `org-refile'.")
11358 (defvar org-agenda-new-buffers nil
11359 "Buffers created to visit agenda files.")
11361 (defvar org-refile-cache nil
11362 "Cache for refile targets.")
11364 (defvar org-refile-markers nil
11365 "All the markers used for caching refile locations.")
11367 (defun org-refile-marker (pos)
11368 "Get a new refile marker, but only if caching is in use."
11369 (if (not org-refile-use-cache)
11371 (let ((m (make-marker)))
11372 (move-marker m pos)
11373 (push m org-refile-markers)
11374 m)))
11376 (defun org-refile-cache-clear ()
11377 "Clear the refile cache and disable all the markers."
11378 (dolist (m org-refile-markers) (move-marker m nil))
11379 (setq org-refile-markers nil)
11380 (setq org-refile-cache nil)
11381 (message "Refile cache has been cleared"))
11383 (defun org-refile-cache-check-set (set)
11384 "Check if all the markers in the cache still have live buffers."
11385 (let (marker)
11386 (catch 'exit
11387 (while (and set (setq marker (nth 3 (pop set))))
11388 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11389 (when (and marker (null (marker-buffer marker)))
11390 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11391 (sit-for 3)
11392 (throw 'exit nil)))
11393 t)))
11395 (defun org-refile-cache-put (set &rest identifiers)
11396 "Push the refile targets SET into the cache, under IDENTIFIERS."
11397 (let* ((key (sha1 (prin1-to-string identifiers)))
11398 (entry (assoc key org-refile-cache)))
11399 (if entry
11400 (setcdr entry set)
11401 (push (cons key set) org-refile-cache))))
11403 (defun org-refile-cache-get (&rest identifiers)
11404 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11405 (cond
11406 ((not org-refile-cache) nil)
11407 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11409 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11410 org-refile-cache))))
11411 (and set (org-refile-cache-check-set set) set)))))
11413 (defvar org-outline-path-cache nil
11414 "Alist between buffer positions and outline paths.
11415 It value is an alist (POSITION . PATH) where POSITION is the
11416 buffer position at the beginning of an entry and PATH is a list
11417 of strings describing the outline path for that entry, in reverse
11418 order.")
11420 (defun org-refile-get-targets (&optional default-buffer)
11421 "Produce a table with refile targets."
11422 (let ((case-fold-search nil)
11423 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11424 (entries (or org-refile-targets '((nil . (:level . 1)))))
11425 targets tgs files desc descre)
11426 (message "Getting targets...")
11427 (with-current-buffer (or default-buffer (current-buffer))
11428 (dolist (entry entries)
11429 (setq files (car entry) desc (cdr entry))
11430 (cond
11431 ((null files) (setq files (list (current-buffer))))
11432 ((eq files 'org-agenda-files)
11433 (setq files (org-agenda-files 'unrestricted)))
11434 ((and (symbolp files) (fboundp files))
11435 (setq files (funcall files)))
11436 ((and (symbolp files) (boundp files))
11437 (setq files (symbol-value files))))
11438 (when (stringp files) (setq files (list files)))
11439 (cond
11440 ((eq (car desc) :tag)
11441 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11442 ((eq (car desc) :todo)
11443 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11444 ((eq (car desc) :regexp)
11445 (setq descre (cdr desc)))
11446 ((eq (car desc) :level)
11447 (setq descre (concat "^\\*\\{" (number-to-string
11448 (if org-odd-levels-only
11449 (1- (* 2 (cdr desc)))
11450 (cdr desc)))
11451 "\\}[ \t]")))
11452 ((eq (car desc) :maxlevel)
11453 (setq descre (concat "^\\*\\{1," (number-to-string
11454 (if org-odd-levels-only
11455 (1- (* 2 (cdr desc)))
11456 (cdr desc)))
11457 "\\}[ \t]")))
11458 (t (error "Bad refiling target description %s" desc)))
11459 (dolist (f files)
11460 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11462 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11463 (progn
11464 (when (bufferp f)
11465 (setq f (buffer-file-name (buffer-base-buffer f))))
11466 (setq f (and f (expand-file-name f)))
11467 (when (eq org-refile-use-outline-path 'file)
11468 (push (list (file-name-nondirectory f) f nil nil) tgs))
11469 (when (eq org-refile-use-outline-path 'buffer-name)
11470 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11471 (when (eq org-refile-use-outline-path 'full-file-path)
11472 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11473 (org-with-wide-buffer
11474 (goto-char (point-min))
11475 (setq org-outline-path-cache nil)
11476 (while (re-search-forward descre nil t)
11477 (beginning-of-line)
11478 (let ((case-fold-search nil))
11479 (looking-at org-complex-heading-regexp))
11480 (let ((begin (point))
11481 (heading (match-string-no-properties 4)))
11482 (unless (or (and
11483 org-refile-target-verify-function
11484 (not
11485 (funcall org-refile-target-verify-function)))
11486 (not heading))
11487 (let ((re (format org-complex-heading-regexp-format
11488 (regexp-quote heading)))
11489 (target
11490 (if (not org-refile-use-outline-path) heading
11491 (mapconcat
11492 #'identity
11493 (append
11494 (pcase org-refile-use-outline-path
11495 (`file (list (file-name-nondirectory
11496 (buffer-file-name
11497 (buffer-base-buffer)))))
11498 (`full-file-path
11499 (list (buffer-file-name
11500 (buffer-base-buffer))))
11501 (`buffer-name
11502 (list (buffer-name
11503 (buffer-base-buffer))))
11504 (_ nil))
11505 (mapcar (lambda (s) (replace-regexp-in-string
11506 "/" "\\/" s nil t))
11507 (org-get-outline-path t t)))
11508 "/"))))
11509 (push (list target f re (org-refile-marker (point)))
11510 tgs)))
11511 (when (= (point) begin)
11512 ;; Verification function has not moved point.
11513 (end-of-line)))))))
11514 (when org-refile-use-cache
11515 (org-refile-cache-put tgs (buffer-file-name) descre))
11516 (setq targets (append tgs targets))))))
11517 (message "Getting targets...done")
11518 (delete-dups (nreverse targets))))
11520 (defun org--get-outline-path-1 (&optional use-cache)
11521 "Return outline path to current headline.
11523 Outline path is a list of strings, in reverse order. When
11524 optional argument USE-CACHE is non-nil, make use of a cache. See
11525 `org-get-outline-path' for details.
11527 Assume buffer is widened and point is on a headline."
11528 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11529 (let ((p (point))
11530 (heading (let ((case-fold-search nil))
11531 (looking-at org-complex-heading-regexp)
11532 (if (not (match-end 4)) ""
11533 ;; Remove statistics cookies.
11534 (org-trim
11535 (org-link-display-format
11536 (replace-regexp-in-string
11537 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11538 (match-string-no-properties 4))))))))
11539 (if (org-up-heading-safe)
11540 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11541 (when use-cache
11542 (push (cons p path) org-outline-path-cache))
11543 path)
11544 ;; This is a new root node. Since we assume we are moving
11545 ;; forward, we can drop previous cache so as to limit number
11546 ;; of associations there.
11547 (let ((path (list heading)))
11548 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11549 path)))))
11551 (defun org-get-outline-path (&optional with-self use-cache)
11552 "Return the outline path to the current entry.
11554 An outline path is a list of ancestors for current headline, as
11555 a list of strings. Statistics cookies are removed and links are
11556 replaced with their description, if any, or their path otherwise.
11558 When optional argument WITH-SELF is non-nil, the path also
11559 includes the current headline.
11561 When optional argument USE-CACHE is non-nil, cache outline paths
11562 between calls to this function so as to avoid backtracking. This
11563 argument is useful when planning to find more than one outline
11564 path in the same document. In that case, there are two
11565 conditions to satisfy:
11566 - `org-outline-path-cache' is set to nil before starting the
11567 process;
11568 - outline paths are computed by increasing buffer positions."
11569 (org-with-wide-buffer
11570 (and (or (and with-self (org-back-to-heading t))
11571 (org-up-heading-safe))
11572 (reverse (org--get-outline-path-1 use-cache)))))
11574 (defun org-format-outline-path (path &optional width prefix separator)
11575 "Format the outline path PATH for display.
11576 WIDTH is the maximum number of characters that is available.
11577 PREFIX is a prefix to be included in the returned string,
11578 such as the file name.
11579 SEPARATOR is inserted between the different parts of the path,
11580 the default is \"/\"."
11581 (setq width (or width 79))
11582 (setq path (delq nil path))
11583 (unless (> width 0)
11584 (user-error "Argument `width' must be positive"))
11585 (setq separator (or separator "/"))
11586 (let* ((org-odd-levels-only nil)
11587 (fpath (concat
11588 prefix (and prefix path separator)
11589 (mapconcat
11590 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11591 (cl-loop for head in path
11592 for n from 0
11593 collect (org-add-props
11594 head nil 'face
11595 (nth (% n org-n-level-faces) org-level-faces)))
11596 separator))))
11597 (when (> (length fpath) width)
11598 (if (< width 7)
11599 ;; It's unlikely that `width' will be this small, but don't
11600 ;; waste characters by adding ".." if it is.
11601 (setq fpath (substring fpath 0 width))
11602 (setf (substring fpath (- width 2)) "..")))
11603 fpath))
11605 (defun org-display-outline-path (&optional file current separator just-return-string)
11606 "Display the current outline path in the echo area.
11608 If FILE is non-nil, prepend the output with the file name.
11609 If CURRENT is non-nil, append the current heading to the output.
11610 SEPARATOR is passed through to `org-format-outline-path'. It separates
11611 the different parts of the path and defaults to \"/\".
11612 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11613 (interactive "P")
11614 (let* (case-fold-search
11615 (bfn (buffer-file-name (buffer-base-buffer)))
11616 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11617 res)
11618 (when current (setq path (append path
11619 (save-excursion
11620 (org-back-to-heading t)
11621 (when (looking-at org-complex-heading-regexp)
11622 (list (match-string 4)))))))
11623 (setq res
11624 (org-format-outline-path
11625 path
11626 (1- (frame-width))
11627 (and file bfn (concat (file-name-nondirectory bfn) separator))
11628 separator))
11629 (if just-return-string
11630 (org-no-properties res)
11631 (org-unlogged-message "%s" res))))
11633 (defvar org-refile-history nil
11634 "History for refiling operations.")
11636 (defvar org-after-refile-insert-hook nil
11637 "Hook run after `org-refile' has inserted its stuff at the new location.
11638 Note that this is still *before* the stuff will be removed from
11639 the *old* location.")
11641 (defvar org-capture-last-stored-marker)
11642 (defvar org-refile-keep nil
11643 "Non-nil means `org-refile' will copy instead of refile.")
11645 (defun org-copy ()
11646 "Like `org-refile', but copy."
11647 (interactive)
11648 (let ((org-refile-keep t))
11649 (funcall 'org-refile nil nil nil "Copy")))
11651 (defun org-refile (&optional arg default-buffer rfloc msg)
11652 "Move the entry or entries at point to another heading.
11654 The list of target headings is compiled using the information in
11655 `org-refile-targets', which see.
11657 At the target location, the entry is filed as a subitem of the
11658 target heading. Depending on `org-reverse-note-order', the new
11659 subitem will either be the first or the last subitem.
11661 If there is an active region, all entries in that region will be
11662 refiled. However, the region must fulfill the requirement that
11663 the first heading sets the top-level of the moved text.
11665 With a `\\[universal-argument]' ARG, the command will only visit the target \
11666 location
11667 and not actually move anything.
11669 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11670 location where the last
11671 refiling operation has put the subtree.
11673 With a numeric prefix argument of `2', refile to the running clock.
11675 With a numeric prefix argument of `3', emulate `org-refile-keep'
11676 being set to t and copy to the target location, don't move it.
11677 Beware that keeping refiled entries may result in duplicated ID
11678 properties.
11680 RFLOC can be a refile location obtained in a different way.
11682 MSG is a string to replace \"Refile\" in the default prompt with
11683 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11685 See also `org-refile-use-outline-path'.
11687 If you are using target caching (see `org-refile-use-cache'), you
11688 have to clear the target cache in order to find new targets.
11689 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11690 prefix argument (`C-u C-u C-u C-c C-w')."
11691 (interactive "P")
11692 (if (member arg '(0 (64)))
11693 (org-refile-cache-clear)
11694 (let* ((actionmsg (cond (msg msg)
11695 ((equal arg 3) "Refile (and keep)")
11696 (t "Refile")))
11697 (regionp (org-region-active-p))
11698 (region-start (and regionp (region-beginning)))
11699 (region-end (and regionp (region-end)))
11700 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11701 pos it nbuf file level reversed)
11702 (setq last-command nil)
11703 (when regionp
11704 (goto-char region-start)
11705 (or (bolp) (goto-char (point-at-bol)))
11706 (setq region-start (point))
11707 (unless (or (org-kill-is-subtree-p
11708 (buffer-substring region-start region-end))
11709 (prog1 org-refile-active-region-within-subtree
11710 (let ((s (point-at-eol)))
11711 (org-toggle-heading)
11712 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11713 (user-error "The region is not a (sequence of) subtree(s)")))
11714 (if (equal arg '(16))
11715 (org-refile-goto-last-stored)
11716 (when (or
11717 (and (equal arg 2)
11718 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11719 (prog1
11720 (setq it (list (or org-clock-heading "running clock")
11721 (buffer-file-name
11722 (marker-buffer org-clock-hd-marker))
11724 (marker-position org-clock-hd-marker)))
11725 (setq arg nil)))
11726 (setq it
11727 (or rfloc
11728 (let (heading-text)
11729 (save-excursion
11730 (unless (and arg (listp arg))
11731 (org-back-to-heading t)
11732 (setq heading-text
11733 (replace-regexp-in-string
11734 org-bracket-link-regexp
11735 "\\3"
11736 (or (nth 4 (org-heading-components))
11737 ""))))
11738 (org-refile-get-location
11739 (cond ((and arg (listp arg)) "Goto")
11740 (regionp (concat actionmsg " region to"))
11741 (t (concat actionmsg " subtree \""
11742 heading-text "\" to")))
11743 default-buffer
11744 (and (not (equal '(4) arg))
11745 org-refile-allow-creating-parent-nodes)))))))
11746 (setq file (nth 1 it)
11747 pos (nth 3 it))
11748 (when (and (not arg)
11750 (equal (buffer-file-name) file)
11751 (if regionp
11752 (and (>= pos region-start)
11753 (<= pos region-end))
11754 (and (>= pos (point))
11755 (< pos (save-excursion
11756 (org-end-of-subtree t t))))))
11757 (error "Cannot refile to position inside the tree or region"))
11758 (setq nbuf (or (find-buffer-visiting file)
11759 (find-file-noselect file)))
11760 (if (and arg (not (equal arg 3)))
11761 (progn
11762 (pop-to-buffer-same-window nbuf)
11763 (goto-char (cond (pos)
11764 ((org-notes-order-reversed-p) (point-min))
11765 (t (point-max))))
11766 (org-show-context 'org-goto))
11767 (if regionp
11768 (progn
11769 (org-kill-new (buffer-substring region-start region-end))
11770 (org-save-markers-in-region region-start region-end))
11771 (org-copy-subtree 1 nil t))
11772 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11773 (find-file-noselect file)))
11774 (setq reversed (org-notes-order-reversed-p))
11775 (org-with-wide-buffer
11776 (if pos
11777 (progn
11778 (goto-char pos)
11779 (setq level (org-get-valid-level (funcall outline-level) 1))
11780 (goto-char
11781 (if reversed
11782 (or (outline-next-heading) (point-max))
11783 (or (save-excursion (org-get-next-sibling))
11784 (org-end-of-subtree t t)
11785 (point-max)))))
11786 (setq level 1)
11787 (if (not reversed)
11788 (goto-char (point-max))
11789 (goto-char (point-min))
11790 (or (outline-next-heading) (goto-char (point-max)))))
11791 (unless (bolp) (newline))
11792 (org-paste-subtree level nil nil t)
11793 (when org-log-refile
11794 (org-add-log-setup 'refile nil nil org-log-refile)
11795 (unless (eq org-log-refile 'note)
11796 (save-excursion (org-add-log-note))))
11797 (and org-auto-align-tags
11798 (let ((org-loop-over-headlines-in-active-region nil))
11799 (org-set-tags nil t)))
11800 (let ((bookmark-name (plist-get org-bookmark-names-plist
11801 :last-refile)))
11802 (when bookmark-name
11803 (with-demoted-errors
11804 (bookmark-set bookmark-name))))
11805 ;; If we are refiling for capture, make sure that the
11806 ;; last-capture pointers point here
11807 (when (bound-and-true-p org-capture-is-refiling)
11808 (let ((bookmark-name (plist-get org-bookmark-names-plist
11809 :last-capture-marker)))
11810 (when bookmark-name
11811 (with-demoted-errors
11812 (bookmark-set bookmark-name))))
11813 (move-marker org-capture-last-stored-marker (point)))
11814 (when (fboundp 'deactivate-mark) (deactivate-mark))
11815 (run-hooks 'org-after-refile-insert-hook)))
11816 (unless org-refile-keep
11817 (if regionp
11818 (delete-region (point) (+ (point) (- region-end region-start)))
11819 (delete-region
11820 (and (org-back-to-heading t) (point))
11821 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11822 (when (featurep 'org-inlinetask)
11823 (org-inlinetask-remove-END-maybe))
11824 (setq org-markers-to-move nil)
11825 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11827 (defun org-refile-goto-last-stored ()
11828 "Go to the location where the last refile was stored."
11829 (interactive)
11830 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11831 (message "This is the location of the last refile"))
11833 (defun org-refile--get-location (refloc tbl)
11834 "When user refile to REFLOC, find the associated target in TBL.
11835 Also check `org-refile-target-table'."
11836 (car (delq
11838 (mapcar
11839 (lambda (r) (or (assoc r tbl)
11840 (assoc r org-refile-target-table)))
11841 (list (replace-regexp-in-string "/$" "" refloc)
11842 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11844 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11845 "Prompt the user for a refile location, using PROMPT.
11846 PROMPT should not be suffixed with a colon and a space, because
11847 this function appends the default value from
11848 `org-refile-history' automatically, if that is not empty."
11849 (let ((org-refile-targets org-refile-targets)
11850 (org-refile-use-outline-path org-refile-use-outline-path))
11851 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11852 (unless org-refile-target-table
11853 (user-error "No refile targets"))
11854 (let* ((cbuf (current-buffer))
11855 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11856 (cfunc (if (and org-refile-use-outline-path
11857 org-outline-path-complete-in-steps)
11858 #'org-olpath-completing-read
11859 #'completing-read))
11860 (extra (if org-refile-use-outline-path "/" ""))
11861 (cbnex (concat (buffer-name) extra))
11862 (filename (and cfn (expand-file-name cfn)))
11863 (tbl (mapcar
11864 (lambda (x)
11865 (if (and (not (member org-refile-use-outline-path
11866 '(file full-file-path)))
11867 (not (equal filename (nth 1 x))))
11868 (cons (concat (car x) extra " ("
11869 (file-name-nondirectory (nth 1 x)) ")")
11870 (cdr x))
11871 (cons (concat (car x) extra) (cdr x))))
11872 org-refile-target-table))
11873 (completion-ignore-case t)
11874 cdef
11875 (prompt (concat prompt
11876 (or (and (car org-refile-history)
11877 (concat " (default " (car org-refile-history) ")"))
11878 (and (assoc cbnex tbl) (setq cdef cbnex)
11879 (concat " (default " cbnex ")"))) ": "))
11880 pa answ parent-target child parent old-hist)
11881 (setq old-hist org-refile-history)
11882 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11883 nil 'org-refile-history (or cdef (car org-refile-history))))
11884 (if (setq pa (org-refile--get-location answ tbl))
11885 (progn
11886 (org-refile-check-position pa)
11887 (when (or (not org-refile-history)
11888 (not (eq old-hist org-refile-history))
11889 (not (equal (car pa) (car org-refile-history))))
11890 (setq org-refile-history
11891 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11892 org-refile-history
11893 (cdr org-refile-history))))
11894 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11895 (pop org-refile-history)))
11897 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11898 (progn
11899 (setq parent (match-string 1 answ)
11900 child (match-string 2 answ))
11901 (setq parent-target (org-refile--get-location parent tbl))
11902 (when (and parent-target
11903 (or (eq new-nodes t)
11904 (and (eq new-nodes 'confirm)
11905 (y-or-n-p (format "Create new node \"%s\"? "
11906 child)))))
11907 (org-refile-new-child parent-target child)))
11908 (user-error "Invalid target location")))))
11910 (declare-function org-string-nw-p "org-macs" (s))
11911 (defun org-refile-check-position (refile-pointer)
11912 "Check if the refile pointer matches the headline to which it points."
11913 (let* ((file (nth 1 refile-pointer))
11914 (re (nth 2 refile-pointer))
11915 (pos (nth 3 refile-pointer))
11916 buffer)
11917 (if (and (not (markerp pos)) (not file))
11918 (user-error "Please indicate a target file in the refile path")
11919 (when (org-string-nw-p re)
11920 (setq buffer (if (markerp pos)
11921 (marker-buffer pos)
11922 (or (find-buffer-visiting file)
11923 (find-file-noselect file))))
11924 (with-current-buffer buffer
11925 (org-with-wide-buffer
11926 (goto-char pos)
11927 (beginning-of-line 1)
11928 (unless (looking-at-p re)
11929 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11931 (defun org-refile-new-child (parent-target child)
11932 "Use refile target PARENT-TARGET to add new CHILD below it."
11933 (unless parent-target
11934 (error "Cannot find parent for new node"))
11935 (let ((file (nth 1 parent-target))
11936 (pos (nth 3 parent-target))
11937 level)
11938 (with-current-buffer (or (find-buffer-visiting file)
11939 (find-file-noselect file))
11940 (org-with-wide-buffer
11941 (if pos
11942 (goto-char pos)
11943 (goto-char (point-max))
11944 (unless (bolp) (newline)))
11945 (when (looking-at org-outline-regexp)
11946 (setq level (funcall outline-level))
11947 (org-end-of-subtree t t))
11948 (org-back-over-empty-lines)
11949 (insert "\n" (make-string
11950 (if pos (org-get-valid-level level 1) 1) ?*)
11951 " " child "\n")
11952 (beginning-of-line 0)
11953 (list (concat (car parent-target) "/" child) file "" (point))))))
11955 (defun org-olpath-completing-read (prompt collection &rest args)
11956 "Read an outline path like a file name."
11957 (let ((thetable collection))
11958 (apply #'completing-read
11959 prompt
11960 (lambda (string predicate &optional flag)
11961 (cond
11962 ((eq flag nil) (try-completion string thetable))
11963 ((eq flag t)
11964 (let ((l (length string)))
11965 (mapcar (lambda (x)
11966 (let ((r (substring x l))
11967 (f (if (string-match " ([^)]*)$" x)
11968 (match-string 0 x)
11969 "")))
11970 (if (string-match "/" r)
11971 (concat string (substring r 0 (match-end 0)) f)
11972 x)))
11973 (all-completions string thetable predicate))))
11974 ;; Exact match?
11975 ((eq flag 'lambda) (assoc string thetable))))
11976 args)))
11978 ;;;; Dynamic blocks
11980 (defun org-find-dblock (name)
11981 "Find the first dynamic block with name NAME in the buffer.
11982 If not found, stay at current position and return nil."
11983 (let ((case-fold-search t) pos)
11984 (save-excursion
11985 (goto-char (point-min))
11986 (setq pos (and (re-search-forward
11987 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11988 (match-beginning 0))))
11989 (when pos (goto-char pos))
11990 pos))
11992 (defun org-create-dblock (plist)
11993 "Create a dynamic block section, with parameters taken from PLIST.
11994 PLIST must contain a :name entry which is used as the name of the block."
11995 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11996 (end-of-line 1)
11997 (newline))
11998 (let ((col (current-column))
11999 (name (plist-get plist :name)))
12000 (insert "#+BEGIN: " name)
12001 (while plist
12002 (if (eq (car plist) :name)
12003 (setq plist (cddr plist))
12004 (insert " " (prin1-to-string (pop plist)))))
12005 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12006 (beginning-of-line -2)))
12008 (defun org-prepare-dblock ()
12009 "Prepare dynamic block for refresh.
12010 This empties the block, puts the cursor at the insert position and returns
12011 the property list including an extra property :name with the block name."
12012 (unless (looking-at org-dblock-start-re)
12013 (user-error "Not at a dynamic block"))
12014 (let* ((begdel (1+ (match-end 0)))
12015 (name (org-no-properties (match-string 1)))
12016 (params (append (list :name name)
12017 (read (concat "(" (match-string 3) ")")))))
12018 (save-excursion
12019 (beginning-of-line 1)
12020 (skip-chars-forward " \t")
12021 (setq params (plist-put params :indentation-column (current-column))))
12022 (unless (re-search-forward org-dblock-end-re nil t)
12023 (error "Dynamic block not terminated"))
12024 (setq params
12025 (append params
12026 (list :content (buffer-substring
12027 begdel (match-beginning 0)))))
12028 (delete-region begdel (match-beginning 0))
12029 (goto-char begdel)
12030 (open-line 1)
12031 params))
12033 (defun org-map-dblocks (&optional command)
12034 "Apply COMMAND to all dynamic blocks in the current buffer.
12035 If COMMAND is not given, use `org-update-dblock'."
12036 (let ((cmd (or command 'org-update-dblock)))
12037 (save-excursion
12038 (goto-char (point-min))
12039 (while (re-search-forward org-dblock-start-re nil t)
12040 (goto-char (match-beginning 0))
12041 (save-excursion
12042 (condition-case nil
12043 (funcall cmd)
12044 (error (message "Error during update of dynamic block"))))
12045 (unless (re-search-forward org-dblock-end-re nil t)
12046 (error "Dynamic block not terminated"))))))
12048 (defun org-dblock-update (&optional arg)
12049 "User command for updating dynamic blocks.
12050 Update the dynamic block at point. With prefix ARG, update all dynamic
12051 blocks in the buffer."
12052 (interactive "P")
12053 (if arg
12054 (org-update-all-dblocks)
12055 (or (looking-at org-dblock-start-re)
12056 (org-beginning-of-dblock))
12057 (org-update-dblock)))
12059 (defun org-update-dblock ()
12060 "Update the dynamic block at point.
12061 This means to empty the block, parse for parameters and then call
12062 the correct writing function."
12063 (interactive)
12064 (save-excursion
12065 (let* ((win (selected-window))
12066 (pos (point))
12067 (line (org-current-line))
12068 (params (org-prepare-dblock))
12069 (name (plist-get params :name))
12070 (indent (plist-get params :indentation-column))
12071 (cmd (intern (concat "org-dblock-write:" name))))
12072 (message "Updating dynamic block `%s' at line %d..." name line)
12073 (funcall cmd params)
12074 (message "Updating dynamic block `%s' at line %d...done" name line)
12075 (goto-char pos)
12076 (when (and indent (> indent 0))
12077 (setq indent (make-string indent ?\ ))
12078 (save-excursion
12079 (select-window win)
12080 (org-beginning-of-dblock)
12081 (forward-line 1)
12082 (while (not (looking-at org-dblock-end-re))
12083 (insert indent)
12084 (beginning-of-line 2))
12085 (when (looking-at org-dblock-end-re)
12086 (and (looking-at "[ \t]+")
12087 (replace-match ""))
12088 (insert indent)))))))
12090 (defun org-beginning-of-dblock ()
12091 "Find the beginning of the dynamic block at point.
12092 Error if there is no such block at point."
12093 (let ((pos (point))
12094 beg)
12095 (end-of-line 1)
12096 (if (and (re-search-backward org-dblock-start-re nil t)
12097 (setq beg (match-beginning 0))
12098 (re-search-forward org-dblock-end-re nil t)
12099 (> (match-end 0) pos))
12100 (goto-char beg)
12101 (goto-char pos)
12102 (error "Not in a dynamic block"))))
12104 (defun org-update-all-dblocks ()
12105 "Update all dynamic blocks in the buffer.
12106 This function can be used in a hook."
12107 (interactive)
12108 (when (derived-mode-p 'org-mode)
12109 (org-map-dblocks 'org-update-dblock)))
12112 ;;;; Completion
12114 (declare-function org-export-backend-options "ox" (cl-x) t)
12115 (defun org-get-export-keywords ()
12116 "Return a list of all currently understood export keywords.
12117 Export keywords include options, block names, attributes and
12118 keywords relative to each registered export back-end."
12119 (let (keywords)
12120 (dolist (backend
12121 (bound-and-true-p org-export-registered-backends)
12122 (delq nil keywords))
12123 ;; Back-end name (for keywords, like #+LATEX:)
12124 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12125 (dolist (option-entry (org-export-backend-options backend))
12126 ;; Back-end options.
12127 (push (nth 1 option-entry) keywords)))))
12129 (defconst org-options-keywords
12130 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12131 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12132 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12133 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12134 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12136 (defcustom org-structure-template-alist
12137 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12138 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12139 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12140 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12141 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12142 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12143 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12144 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12145 ("L" "#+LaTeX: ")
12146 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12147 ("H" "#+HTML: ")
12148 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12149 ("A" "#+ASCII: ")
12150 ("i" "#+INDEX: ?")
12151 ("I" "#+INCLUDE: %file ?"))
12152 "Structure completion elements.
12153 This is a list of abbreviation keys and values. The value gets inserted
12154 if you type `<' followed by the key and then press the completion key,
12155 usually `TAB'. %file will be replaced by a file name after prompting
12156 for the file using completion. The cursor will be placed at the position
12157 of the `?' in the template.
12158 There are two templates for each key, the first uses the original Org syntax,
12159 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12160 the default when the /org-mtags.el/ module has been loaded. See also the
12161 variable `org-mtags-prefer-muse-templates'."
12162 :group 'org-completion
12163 :type '(repeat
12164 (list
12165 (string :tag "Key")
12166 (string :tag "Template")))
12167 :version "26.1"
12168 :package-version '(Org . "8.3"))
12170 (defun org-try-structure-completion ()
12171 "Try to complete a structure template before point.
12172 This looks for strings like \"<e\" on an otherwise empty line and
12173 expands them."
12174 (let ((l (buffer-substring (point-at-bol) (point)))
12176 (when (and (looking-at "[ \t]*$")
12177 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12178 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12179 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12180 (match-beginning 1)) a)
12181 t)))
12183 (defun org-complete-expand-structure-template (start cell)
12184 "Expand a structure template."
12185 (let ((rpl (nth 1 cell))
12186 (ind ""))
12187 (delete-region start (point))
12188 (when (string-match "\\`[ \t]*#\\+" rpl)
12189 (cond
12190 ((bolp))
12191 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12192 (setq ind (buffer-substring (point-at-bol) (point))))
12193 (t (newline))))
12194 (setq start (point))
12195 (when (string-match "%file" rpl)
12196 (setq rpl (replace-match
12197 (concat
12198 "\""
12199 (save-match-data
12200 (abbreviate-file-name (read-file-name "Include file: ")))
12201 "\"")
12202 t t rpl)))
12203 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12204 (concat "\n" ind)))
12205 (insert rpl)
12206 (when (re-search-backward "\\?" start t) (delete-char 1))))
12208 ;;;; TODO, DEADLINE, Comments
12210 (defun org-toggle-comment ()
12211 "Change the COMMENT state of an entry."
12212 (interactive)
12213 (save-excursion
12214 (org-back-to-heading)
12215 (let ((case-fold-search nil))
12216 (looking-at org-complex-heading-regexp))
12217 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12218 (skip-chars-forward " \t")
12219 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12220 (if (org-in-commented-heading-p t)
12221 (delete-region (point)
12222 (progn (search-forward " " (line-end-position) 'move)
12223 (skip-chars-forward " \t")
12224 (point)))
12225 (insert org-comment-string)
12226 (unless (eolp) (insert " ")))))
12228 (defvar org-last-todo-state-is-todo nil
12229 "This is non-nil when the last TODO state change led to a TODO state.
12230 If the last change removed the TODO tag or switched to DONE, then
12231 this is nil.")
12233 (defvar org-setting-tags nil) ; dynamically skipped
12235 (defvar org-todo-setup-filter-hook nil
12236 "Hook for functions that pre-filter todo specs.
12237 Each function takes a todo spec and returns either nil or the spec
12238 transformed into canonical form." )
12240 (defvar org-todo-get-default-hook nil
12241 "Hook for functions that get a default item for todo.
12242 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12243 nil or a string to be used for the todo mark." )
12245 (defvar org-agenda-headline-snapshot-before-repeat)
12247 (defun org-current-effective-time ()
12248 "Return current time adjusted for `org-extend-today-until' variable."
12249 (let* ((ct (org-current-time))
12250 (dct (decode-time ct))
12251 (ct1
12252 (cond
12253 (org-use-last-clock-out-time-as-effective-time
12254 (or (org-clock-get-last-clock-out-time) ct))
12255 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12256 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12257 (t ct))))
12258 ct1))
12260 (defun org-todo-yesterday (&optional arg)
12261 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12262 (interactive "P")
12263 (if (eq major-mode 'org-agenda-mode)
12264 (apply 'org-agenda-todo-yesterday arg)
12265 (let* ((org-use-effective-time t)
12266 (hour (nth 2 (decode-time (org-current-time))))
12267 (org-extend-today-until (1+ hour)))
12268 (org-todo arg))))
12270 (defvar org-block-entry-blocking ""
12271 "First entry preventing the TODO state change.")
12273 (defun org-cancel-repeater ()
12274 "Cancel a repeater by setting its numeric value to zero."
12275 (interactive)
12276 (save-excursion
12277 (org-back-to-heading t)
12278 (let ((bound1 (point))
12279 (bound0 (save-excursion (outline-next-heading) (point))))
12280 (when (and (re-search-forward
12281 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12282 org-deadline-time-regexp "\\)\\|\\("
12283 org-ts-regexp "\\)")
12284 bound0 t)
12285 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12286 bound1 t))
12287 (replace-match "0" t nil nil 1)))))
12289 (defvar org-state)
12290 (defvar org-blocked-by-checkboxes)
12291 (defun org-todo (&optional arg)
12292 "Change the TODO state of an item.
12294 The state of an item is given by a keyword at the start of the heading,
12295 like
12296 *** TODO Write paper
12297 *** DONE Call mom
12299 The different keywords are specified in the variable `org-todo-keywords'.
12300 By default the available states are \"TODO\" and \"DONE\". So, for this
12301 example: when the item starts with TODO, it is changed to DONE.
12302 When it starts with DONE, the DONE is removed. And when neither TODO nor
12303 DONE are present, add TODO at the beginning of the heading.
12305 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12306 state.
12307 With numeric prefix ARG, switch to that state.
12308 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12309 next set of TODO \
12310 keywords (nextset).
12311 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12312 prefix, circumvent any state blocking.
12313 With a numeric prefix arg of 0, inhibit note taking for the change.
12314 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12316 When called through ELisp, arg is also interpreted in the following way:
12317 `none' -> empty state
12318 \"\" -> switch to empty state
12319 `done' -> switch to DONE
12320 `nextset' -> switch to the next set of keywords
12321 `previousset' -> switch to the previous set of keywords
12322 \"WAITING\" -> switch to the specified keyword, but only if it
12323 really is a member of `org-todo-keywords'."
12324 (interactive "P")
12325 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12326 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12327 'region-start-level 'region))
12328 org-loop-over-headlines-in-active-region)
12329 (org-map-entries
12330 `(org-todo ,arg)
12331 org-loop-over-headlines-in-active-region
12332 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12333 (when (equal arg '(16)) (setq arg 'nextset))
12334 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12335 (let ((org-blocker-hook org-blocker-hook)
12336 commentp
12337 case-fold-search)
12338 (when (equal arg '(64))
12339 (setq arg nil org-blocker-hook nil))
12340 (when (and org-blocker-hook
12341 (or org-inhibit-blocking
12342 (org-entry-get nil "NOBLOCKING")))
12343 (setq org-blocker-hook nil))
12344 (save-excursion
12345 (catch 'exit
12346 (org-back-to-heading t)
12347 (when (org-in-commented-heading-p t)
12348 (org-toggle-comment)
12349 (setq commentp t))
12350 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12351 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12352 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12353 (let* ((match-data (match-data))
12354 (startpos (point-at-bol))
12355 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12356 (org-log-done org-log-done)
12357 (org-log-repeat org-log-repeat)
12358 (org-todo-log-states org-todo-log-states)
12359 (org-inhibit-logging
12360 (if (equal arg 0)
12361 (progn (setq arg nil) 'note) org-inhibit-logging))
12362 (this (match-string 1))
12363 (hl-pos (match-beginning 0))
12364 (head (org-get-todo-sequence-head this))
12365 (ass (assoc head org-todo-kwd-alist))
12366 (interpret (nth 1 ass))
12367 (done-word (nth 3 ass))
12368 (final-done-word (nth 4 ass))
12369 (org-last-state (or this ""))
12370 (completion-ignore-case t)
12371 (member (member this org-todo-keywords-1))
12372 (tail (cdr member))
12373 (org-state (cond
12374 ((and org-todo-key-trigger
12375 (or (and (equal arg '(4))
12376 (eq org-use-fast-todo-selection 'prefix))
12377 (and (not arg) org-use-fast-todo-selection
12378 (not (eq org-use-fast-todo-selection
12379 'prefix)))))
12380 ;; Use fast selection.
12381 (org-fast-todo-selection))
12382 ((and (equal arg '(4))
12383 (or (not org-use-fast-todo-selection)
12384 (not org-todo-key-trigger)))
12385 ;; Read a state with completion.
12386 (completing-read
12387 "State: " (mapcar #'list org-todo-keywords-1)
12388 nil t))
12389 ((eq arg 'right)
12390 (if this
12391 (if tail (car tail) nil)
12392 (car org-todo-keywords-1)))
12393 ((eq arg 'left)
12394 (unless (equal member org-todo-keywords-1)
12395 (if this
12396 (nth (- (length org-todo-keywords-1)
12397 (length tail) 2)
12398 org-todo-keywords-1)
12399 (org-last org-todo-keywords-1))))
12400 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12401 (setq arg nil))) ;hack to fall back to cycling
12402 (arg
12403 ;; User or caller requests a specific state.
12404 (cond
12405 ((equal arg "") nil)
12406 ((eq arg 'none) nil)
12407 ((eq arg 'done) (or done-word (car org-done-keywords)))
12408 ((eq arg 'nextset)
12409 (or (car (cdr (member head org-todo-heads)))
12410 (car org-todo-heads)))
12411 ((eq arg 'previousset)
12412 (let ((org-todo-heads (reverse org-todo-heads)))
12413 (or (car (cdr (member head org-todo-heads)))
12414 (car org-todo-heads))))
12415 ((car (member arg org-todo-keywords-1)))
12416 ((stringp arg)
12417 (user-error "State `%s' not valid in this file" arg))
12418 ((nth (1- (prefix-numeric-value arg))
12419 org-todo-keywords-1))))
12420 ((null member) (or head (car org-todo-keywords-1)))
12421 ((equal this final-done-word) nil) ;-> make empty
12422 ((null tail) nil) ;-> first entry
12423 ((memq interpret '(type priority))
12424 (if (eq this-command last-command)
12425 (car tail)
12426 (if (> (length tail) 0)
12427 (or done-word (car org-done-keywords))
12428 nil)))
12430 (car tail))))
12431 (org-state (or
12432 (run-hook-with-args-until-success
12433 'org-todo-get-default-hook org-state org-last-state)
12434 org-state))
12435 (next (if org-state (concat " " org-state " ") " "))
12436 (change-plist (list :type 'todo-state-change :from this :to org-state
12437 :position startpos))
12438 dolog now-done-p)
12439 (when org-blocker-hook
12440 (let (org-blocked-by-checkboxes block-reason)
12441 (setq org-last-todo-state-is-todo
12442 (not (member this org-done-keywords)))
12443 (unless (save-excursion
12444 (save-match-data
12445 (org-with-wide-buffer
12446 (run-hook-with-args-until-failure
12447 'org-blocker-hook change-plist))))
12448 (setq block-reason (if org-blocked-by-checkboxes
12449 "contained checkboxes"
12450 (format "\"%s\"" org-block-entry-blocking)))
12451 (if (called-interactively-p 'interactive)
12452 (user-error "TODO state change from %s to %s blocked (by %s)"
12453 this org-state block-reason)
12454 ;; Fail silently.
12455 (message "TODO state change from %s to %s blocked (by %s)"
12456 this org-state block-reason)
12457 (throw 'exit nil)))))
12458 (store-match-data match-data)
12459 (replace-match next t t)
12460 (cond ((equal this org-state)
12461 (message "TODO state was already %s" (org-trim next)))
12462 ((not (pos-visible-in-window-p hl-pos))
12463 (message "TODO state changed to %s" (org-trim next))))
12464 (unless head
12465 (setq head (org-get-todo-sequence-head org-state)
12466 ass (assoc head org-todo-kwd-alist)
12467 interpret (nth 1 ass)
12468 done-word (nth 3 ass)
12469 final-done-word (nth 4 ass)))
12470 (when (memq arg '(nextset previousset))
12471 (message "Keyword-Set %d/%d: %s"
12472 (- (length org-todo-sets) -1
12473 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12474 (length org-todo-sets)
12475 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12476 (setq org-last-todo-state-is-todo
12477 (not (member org-state org-done-keywords)))
12478 (setq now-done-p (and (member org-state org-done-keywords)
12479 (not (member this org-done-keywords))))
12480 (and logging (org-local-logging logging))
12481 (when (and (or org-todo-log-states org-log-done)
12482 (not (eq org-inhibit-logging t))
12483 (not (memq arg '(nextset previousset))))
12484 ;; We need to look at recording a time and note.
12485 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12486 (nth 2 (assoc this org-todo-log-states))))
12487 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12488 (setq dolog 'time))
12489 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12490 (and org-state
12491 (member org-state org-not-done-keywords)
12492 (not (member this org-not-done-keywords))))
12493 ;; This is now a todo state and was not one before
12494 ;; If there was a CLOSED time stamp, get rid of it.
12495 (org-add-planning-info nil nil 'closed))
12496 (when (and now-done-p org-log-done)
12497 ;; It is now done, and it was not done before.
12498 (org-add-planning-info 'closed (org-current-effective-time))
12499 (when (and (not dolog) (eq 'note org-log-done))
12500 (org-add-log-setup 'done org-state this 'note)))
12501 (when (and org-state dolog)
12502 ;; This is a non-nil state, and we need to log it.
12503 (org-add-log-setup 'state org-state this dolog)))
12504 ;; Fixup tag positioning.
12505 (org-todo-trigger-tag-changes org-state)
12506 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12507 (when org-provide-todo-statistics
12508 (org-update-parent-todo-statistics))
12509 (run-hooks 'org-after-todo-state-change-hook)
12510 (when (and arg (not (member org-state org-done-keywords)))
12511 (setq head (org-get-todo-sequence-head org-state)))
12512 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12513 ;; Do we need to trigger a repeat?
12514 (when now-done-p
12515 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12516 ;; This is for the agenda, take a snapshot of the headline.
12517 (save-match-data
12518 (setq org-agenda-headline-snapshot-before-repeat
12519 (org-get-heading))))
12520 (org-auto-repeat-maybe org-state))
12521 ;; Fixup cursor location if close to the keyword.
12522 (when (and (outline-on-heading-p)
12523 (not (bolp))
12524 (save-excursion (beginning-of-line 1)
12525 (looking-at org-todo-line-regexp))
12526 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12527 (goto-char (or (match-end 2) (match-end 1)))
12528 (and (looking-at " ") (just-one-space)))
12529 (when org-trigger-hook
12530 (save-excursion
12531 (run-hook-with-args 'org-trigger-hook change-plist)))
12532 (when commentp (org-toggle-comment))))))))
12534 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12535 "Block turning an entry into a TODO, using the hierarchy.
12536 This checks whether the current task should be blocked from state
12537 changes. Such blocking occurs when:
12539 1. The task has children which are not all in a completed state.
12541 2. A task has a parent with the property :ORDERED:, and there
12542 are siblings prior to the current task with incomplete
12543 status.
12545 3. The parent of the task is blocked because it has siblings that should
12546 be done first, or is child of a block grandparent TODO entry."
12548 (if (not org-enforce-todo-dependencies)
12549 t ; if locally turned off don't block
12550 (catch 'dont-block
12551 ;; If this is not a todo state change, or if this entry is already DONE,
12552 ;; do not block
12553 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12554 (member (plist-get change-plist :from)
12555 (cons 'done org-done-keywords))
12556 (member (plist-get change-plist :to)
12557 (cons 'todo org-not-done-keywords))
12558 (not (plist-get change-plist :to)))
12559 (throw 'dont-block t))
12560 ;; If this task has children, and any are undone, it's blocked
12561 (save-excursion
12562 (org-back-to-heading t)
12563 (let ((this-level (funcall outline-level)))
12564 (outline-next-heading)
12565 (let ((child-level (funcall outline-level)))
12566 (while (and (not (eobp))
12567 (> child-level this-level))
12568 ;; this todo has children, check whether they are all
12569 ;; completed
12570 (when (and (not (org-entry-is-done-p))
12571 (org-entry-is-todo-p))
12572 (setq org-block-entry-blocking (org-get-heading))
12573 (throw 'dont-block nil))
12574 (outline-next-heading)
12575 (setq child-level (funcall outline-level))))))
12576 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12577 ;; any previous siblings are undone, it's blocked
12578 (save-excursion
12579 (org-back-to-heading t)
12580 (let* ((pos (point))
12581 (parent-pos (and (org-up-heading-safe) (point)))
12582 (case-fold-search nil))
12583 (unless parent-pos (throw 'dont-block t)) ; no parent
12584 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12585 (forward-line 1)
12586 (re-search-forward org-not-done-heading-regexp pos t))
12587 (setq org-block-entry-blocking (match-string 0))
12588 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12589 ;; Search further up the hierarchy, to see if an ancestor is blocked
12590 (while t
12591 (goto-char parent-pos)
12592 (unless (looking-at org-not-done-heading-regexp)
12593 (throw 'dont-block t)) ; do not block, parent is not a TODO
12594 (setq pos (point))
12595 (setq parent-pos (and (org-up-heading-safe) (point)))
12596 (unless parent-pos (throw 'dont-block t)) ; no parent
12597 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12598 (forward-line 1)
12599 (re-search-forward org-not-done-heading-regexp pos t)
12600 (setq org-block-entry-blocking (org-get-heading)))
12601 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12603 (defcustom org-track-ordered-property-with-tag nil
12604 "Should the ORDERED property also be shown as a tag?
12605 The ORDERED property decides if an entry should require subtasks to be
12606 completed in sequence. Since a property is not very visible, setting
12607 this option means that toggling the ORDERED property with the command
12608 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12609 not relevant for the behavior, but it makes things more visible.
12611 Note that toggling the tag with tags commands will not change the property
12612 and therefore not influence behavior!
12614 This can be t, meaning the tag ORDERED should be used, It can also be a
12615 string to select a different tag for this task."
12616 :group 'org-todo
12617 :type '(choice
12618 (const :tag "No tracking" nil)
12619 (const :tag "Track with ORDERED tag" t)
12620 (string :tag "Use other tag")))
12622 (defun org-toggle-ordered-property ()
12623 "Toggle the ORDERED property of the current entry.
12624 For better visibility, you can track the value of this property with a tag.
12625 See variable `org-track-ordered-property-with-tag'."
12626 (interactive)
12627 (let* ((t1 org-track-ordered-property-with-tag)
12628 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12629 (save-excursion
12630 (org-back-to-heading)
12631 (if (org-entry-get nil "ORDERED")
12632 (progn
12633 (org-delete-property "ORDERED")
12634 (and tag (org-toggle-tag tag 'off))
12635 (message "Subtasks can be completed in arbitrary order"))
12636 (org-entry-put nil "ORDERED" "t")
12637 (and tag (org-toggle-tag tag 'on))
12638 (message "Subtasks must be completed in sequence")))))
12640 (defun org-block-todo-from-checkboxes (change-plist)
12641 "Block turning an entry into a TODO, using checkboxes.
12642 This checks whether the current task should be blocked from state
12643 changes because there are unchecked boxes in this entry."
12644 (if (not org-enforce-todo-checkbox-dependencies)
12645 t ; if locally turned off don't block
12646 (catch 'dont-block
12647 ;; If this is not a todo state change, or if this entry is already DONE,
12648 ;; do not block
12649 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12650 (member (plist-get change-plist :from)
12651 (cons 'done org-done-keywords))
12652 (member (plist-get change-plist :to)
12653 (cons 'todo org-not-done-keywords))
12654 (not (plist-get change-plist :to)))
12655 (throw 'dont-block t))
12656 ;; If this task has checkboxes that are not checked, it's blocked
12657 (save-excursion
12658 (org-back-to-heading t)
12659 (let ((beg (point)) end)
12660 (outline-next-heading)
12661 (setq end (point))
12662 (goto-char beg)
12663 (when (org-list-search-forward
12664 (concat (org-item-beginning-re)
12665 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12666 "\\[[- ]\\]")
12667 end t)
12668 (when (boundp 'org-blocked-by-checkboxes)
12669 (setq org-blocked-by-checkboxes t))
12670 (throw 'dont-block nil))))
12671 t))) ; do not block
12673 (defun org-entry-blocked-p ()
12674 "Non-nil if entry at point is blocked."
12675 (and (not (org-entry-get nil "NOBLOCKING"))
12676 (member (org-entry-get nil "TODO") org-not-done-keywords)
12677 (not (run-hook-with-args-until-failure
12678 'org-blocker-hook
12679 (list :type 'todo-state-change
12680 :position (point)
12681 :from 'todo
12682 :to 'done)))))
12684 (defun org-update-statistics-cookies (all)
12685 "Update the statistics cookie, either from TODO or from checkboxes.
12686 This should be called with the cursor in a line with a statistics
12687 cookie. When called with a \\[universal-argument] prefix, update
12688 all statistics cookies in the buffer."
12689 (interactive "P")
12690 (if all
12691 (progn
12692 (org-update-checkbox-count 'all)
12693 (org-map-entries 'org-update-parent-todo-statistics))
12694 (if (not (org-at-heading-p))
12695 (org-update-checkbox-count)
12696 (let ((pos (point-marker))
12697 end l1 l2)
12698 (ignore-errors (org-back-to-heading t))
12699 (if (not (org-at-heading-p))
12700 (org-update-checkbox-count)
12701 (setq l1 (org-outline-level))
12702 (setq end (save-excursion
12703 (outline-next-heading)
12704 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12705 (point)))
12706 (if (and (save-excursion
12707 (re-search-forward
12708 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12709 (not (save-excursion (re-search-forward
12710 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12711 (org-update-checkbox-count)
12712 (if (and l2 (> l2 l1))
12713 (progn
12714 (goto-char end)
12715 (org-update-parent-todo-statistics))
12716 (goto-char pos)
12717 (beginning-of-line 1)
12718 (while (re-search-forward
12719 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12720 (point-at-eol) t)
12721 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12722 (goto-char pos)
12723 (move-marker pos nil)))))
12725 (defvar org-entry-property-inherited-from) ;; defined below
12726 (defun org-update-parent-todo-statistics ()
12727 "Update any statistics cookie in the parent of the current headline.
12728 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12729 the entire subtree and this will travel up the hierarchy and update
12730 statistics everywhere."
12731 (let* ((prop (save-excursion (org-up-heading-safe)
12732 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12733 (recursive (or (not org-hierarchical-todo-statistics)
12734 (and prop (string-match "\\<recursive\\>" prop))))
12735 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12737 (first t)
12738 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12739 level ltoggle l1 new ndel
12740 (cnt-all 0) (cnt-done 0) is-percent kwd
12741 checkbox-beg cookie-present)
12742 (catch 'exit
12743 (save-excursion
12744 (beginning-of-line 1)
12745 (setq ltoggle (funcall outline-level))
12746 ;; Three situations are to consider:
12748 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12749 ;; to the top-level ancestor on the headline;
12751 ;; 2. If parent has "recursive" property, repeat up to the
12752 ;; headline setting that property, taking inheritance into
12753 ;; account;
12755 ;; 3. Else, move up to direct parent and proceed only once.
12756 (while (and (setq level (org-up-heading-safe))
12757 (or recursive first)
12758 (>= (point) lim))
12759 (setq first nil cookie-present nil)
12760 (unless (and level
12761 (not (string-match
12762 "\\<checkbox\\>"
12763 (downcase (or (org-entry-get nil "COOKIE_DATA")
12764 "")))))
12765 (throw 'exit nil))
12766 (while (re-search-forward box-re (point-at-eol) t)
12767 (setq cnt-all 0 cnt-done 0 cookie-present t)
12768 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12769 (save-match-data
12770 (unless (outline-next-heading) (throw 'exit nil))
12771 (while (and (looking-at org-complex-heading-regexp)
12772 (> (setq l1 (length (match-string 1))) level))
12773 (setq kwd (and (or recursive (= l1 ltoggle))
12774 (match-string 2)))
12775 (if (or (eq org-provide-todo-statistics 'all-headlines)
12776 (and (eq org-provide-todo-statistics t)
12777 (or (member kwd org-done-keywords)))
12778 (and (listp org-provide-todo-statistics)
12779 (stringp (car org-provide-todo-statistics))
12780 (or (member kwd org-provide-todo-statistics)
12781 (member kwd org-done-keywords)))
12782 (and (listp org-provide-todo-statistics)
12783 (listp (car org-provide-todo-statistics))
12784 (or (member kwd (car org-provide-todo-statistics))
12785 (and (member kwd org-done-keywords)
12786 (member kwd (cadr org-provide-todo-statistics))))))
12787 (setq cnt-all (1+ cnt-all))
12788 (and (eq org-provide-todo-statistics t)
12790 (setq cnt-all (1+ cnt-all))))
12791 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12792 (member kwd org-done-keywords))
12793 (and (listp org-provide-todo-statistics)
12794 (listp (car org-provide-todo-statistics))
12795 (member kwd org-done-keywords)
12796 (member kwd (cadr org-provide-todo-statistics)))
12797 (and (listp org-provide-todo-statistics)
12798 (stringp (car org-provide-todo-statistics))
12799 (member kwd org-done-keywords)))
12800 (setq cnt-done (1+ cnt-done)))
12801 (outline-next-heading)))
12802 (setq new
12803 (if is-percent
12804 (format "[%d%%]" (floor (* 100.0 cnt-done)
12805 (max 1 cnt-all)))
12806 (format "[%d/%d]" cnt-done cnt-all))
12807 ndel (- (match-end 0) checkbox-beg))
12808 (goto-char checkbox-beg)
12809 (insert new)
12810 (delete-region (point) (+ (point) ndel))
12811 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12812 (when cookie-present
12813 (run-hook-with-args 'org-after-todo-statistics-hook
12814 cnt-done (- cnt-all cnt-done))))))
12815 (run-hooks 'org-todo-statistics-hook)))
12817 (defvar org-after-todo-statistics-hook nil
12818 "Hook that is called after a TODO statistics cookie has been updated.
12819 Each function is called with two arguments: the number of not-done entries
12820 and the number of done entries.
12822 For example, the following function, when added to this hook, will switch
12823 an entry to DONE when all children are done, and back to TODO when new
12824 entries are set to a TODO status. Note that this hook is only called
12825 when there is a statistics cookie in the headline!
12827 (defun org-summary-todo (n-done n-not-done)
12828 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12829 (let (org-log-done org-log-states) ; turn off logging
12830 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12833 (defvar org-todo-statistics-hook nil
12834 "Hook that is run whenever Org thinks TODO statistics should be updated.
12835 This hook runs even if there is no statistics cookie present, in which case
12836 `org-after-todo-statistics-hook' would not run.")
12838 (defun org-todo-trigger-tag-changes (state)
12839 "Apply the changes defined in `org-todo-state-tags-triggers'."
12840 (let ((l org-todo-state-tags-triggers)
12841 changes)
12842 (when (or (not state) (equal state ""))
12843 (setq changes (append changes (cdr (assoc "" l)))))
12844 (when (and (stringp state) (> (length state) 0))
12845 (setq changes (append changes (cdr (assoc state l)))))
12846 (when (member state org-not-done-keywords)
12847 (setq changes (append changes (cdr (assq 'todo l)))))
12848 (when (member state org-done-keywords)
12849 (setq changes (append changes (cdr (assq 'done l)))))
12850 (dolist (c changes)
12851 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12853 (defun org-local-logging (value)
12854 "Get logging settings from a property VALUE."
12855 ;; Directly set the variables, they are already local.
12856 (setq org-log-done nil
12857 org-log-repeat nil
12858 org-todo-log-states nil)
12859 (dolist (w (split-string value))
12860 (let (a)
12861 (cond
12862 ((setq a (assoc w org-startup-options))
12863 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12864 (set (nth 1 a) (nth 2 a))))
12865 ((setq a (org-extract-log-state-settings w))
12866 (and (member (car a) org-todo-keywords-1)
12867 (push a org-todo-log-states)))))))
12869 (defun org-get-todo-sequence-head (kwd)
12870 "Return the head of the TODO sequence to which KWD belongs.
12871 If KWD is not set, check if there is a text property remembering the
12872 right sequence."
12873 (let (p)
12874 (cond
12875 ((not kwd)
12876 (or (get-text-property (point-at-bol) 'org-todo-head)
12877 (progn
12878 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12879 nil (point-at-eol)))
12880 (get-text-property p 'org-todo-head))))
12881 ((not (member kwd org-todo-keywords-1))
12882 (car org-todo-keywords-1))
12883 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12885 (defun org-fast-todo-selection ()
12886 "Fast TODO keyword selection with single keys.
12887 Returns the new TODO keyword, or nil if no state change should occur."
12888 (let* ((fulltable org-todo-key-alist)
12889 (done-keywords org-done-keywords) ;; needed for the faces.
12890 (maxlen (apply 'max (mapcar
12891 (lambda (x)
12892 (if (stringp (car x)) (string-width (car x)) 0))
12893 fulltable)))
12894 (expert nil)
12895 (fwidth (+ maxlen 3 1 3))
12896 (ncol (/ (- (window-width) 4) fwidth))
12897 tg cnt e c tbl
12898 groups ingroup)
12899 (save-excursion
12900 (save-window-excursion
12901 (if expert
12902 (set-buffer (get-buffer-create " *Org todo*"))
12903 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12904 (erase-buffer)
12905 (setq-local org-done-keywords done-keywords)
12906 (setq tbl fulltable cnt 0)
12907 (while (setq e (pop tbl))
12908 (cond
12909 ((equal e '(:startgroup))
12910 (push '() groups) (setq ingroup t)
12911 (unless (= cnt 0)
12912 (setq cnt 0)
12913 (insert "\n"))
12914 (insert "{ "))
12915 ((equal e '(:endgroup))
12916 (setq ingroup nil cnt 0)
12917 (insert "}\n"))
12918 ((equal e '(:newline))
12919 (unless (= cnt 0)
12920 (setq cnt 0)
12921 (insert "\n")
12922 (setq e (car tbl))
12923 (while (equal (car tbl) '(:newline))
12924 (insert "\n")
12925 (setq tbl (cdr tbl)))))
12927 (setq tg (car e) c (cdr e))
12928 (when ingroup (push tg (car groups)))
12929 (setq tg (org-add-props tg nil 'face
12930 (org-get-todo-face tg)))
12931 (when (and (= cnt 0) (not ingroup)) (insert " "))
12932 (insert "[" c "] " tg (make-string
12933 (- fwidth 4 (length tg)) ?\ ))
12934 (when (= (setq cnt (1+ cnt)) ncol)
12935 (insert "\n")
12936 (when ingroup (insert " "))
12937 (setq cnt 0)))))
12938 (insert "\n")
12939 (goto-char (point-min))
12940 (unless expert (org-fit-window-to-buffer))
12941 (message "[a-z..]:Set [SPC]:clear")
12942 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12943 (cond
12944 ((or (= c ?\C-g)
12945 (and (= c ?q) (not (rassoc c fulltable))))
12946 (setq quit-flag t))
12947 ((= c ?\ ) nil)
12948 ((setq e (rassoc c fulltable) tg (car e))
12950 (t (setq quit-flag t)))))))
12952 (defun org-entry-is-todo-p ()
12953 (member (org-get-todo-state) org-not-done-keywords))
12955 (defun org-entry-is-done-p ()
12956 (member (org-get-todo-state) org-done-keywords))
12958 (defun org-get-todo-state ()
12959 "Return the TODO keyword of the current subtree."
12960 (save-excursion
12961 (org-back-to-heading t)
12962 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12963 (match-end 2)
12964 (match-string 2))))
12966 (defun org-at-date-range-p (&optional inactive-ok)
12967 "Non-nil if point is inside a date range.
12969 When optional argument INACTIVE-OK is non-nil, also consider
12970 inactive time ranges.
12972 When this function returns a non-nil value, match data is set
12973 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12974 on INACTIVE-OK."
12975 (interactive)
12976 (save-excursion
12977 (catch 'exit
12978 (let ((pos (point)))
12979 (skip-chars-backward "^[<\r\n")
12980 (skip-chars-backward "<[")
12981 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12982 (>= (match-end 0) pos)
12983 (throw 'exit t))
12984 (skip-chars-backward "^<[\r\n")
12985 (skip-chars-backward "<[")
12986 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12987 (>= (match-end 0) pos)
12988 (throw 'exit t)))
12989 nil)))
12991 (defun org-get-repeat (&optional timestamp)
12992 "Check if there is a time-stamp with repeater in this entry.
12994 Return the repeater, as a string, or nil. Also return nil when
12995 this function is called before first heading.
12997 When optional argument TIMESTAMP is a string, extract the
12998 repeater from there instead."
12999 (save-match-data
13000 (cond (timestamp
13001 (and (string-match org-repeat-re timestamp)
13002 (match-string-no-properties 1 timestamp)))
13003 ((org-before-first-heading-p) nil)
13005 (save-excursion
13006 (org-back-to-heading t)
13007 (let ((end (org-entry-end-position)))
13008 (catch :repeat
13009 (while (re-search-forward org-repeat-re end t)
13010 (when (save-match-data (org-at-timestamp-p 'agenda))
13011 (throw :repeat (match-string-no-properties 1)))))))))))
13013 (defvar org-last-changed-timestamp)
13014 (defvar org-last-inserted-timestamp)
13015 (defvar org-log-post-message)
13016 (defvar org-log-note-purpose)
13017 (defvar org-log-note-how nil)
13018 (defvar org-log-note-extra)
13019 (defun org-auto-repeat-maybe (done-word)
13020 "Check if the current headline contains a repeated time-stamp.
13022 If yes, set TODO state back to what it was and change the base date
13023 of repeating deadline/scheduled time stamps to new date.
13025 This function is run automatically after each state change to a DONE state."
13026 (let* ((repeat (org-get-repeat))
13027 (aa (assoc org-last-state org-todo-kwd-alist))
13028 (interpret (nth 1 aa))
13029 (head (nth 2 aa))
13030 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13031 (msg "Entry repeats: ")
13032 (org-log-done nil)
13033 (org-todo-log-states nil)
13034 (end (copy-marker (org-entry-end-position))))
13035 (unwind-protect
13036 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13037 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13038 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13039 org-todo-repeat-to-state)))
13040 (org-todo (cond
13041 ((and to-state (member to-state org-todo-keywords-1))
13042 to-state)
13043 ((eq interpret 'type) org-last-state)
13044 (head)
13045 (t 'none))))
13046 (org-back-to-heading t)
13047 (org-add-planning-info nil nil 'closed)
13048 ;; When `org-log-repeat' is non-nil or entry contains
13049 ;; a clock, set LAST_REPEAT property.
13050 (when (or org-log-repeat
13051 (catch :clock
13052 (while (re-search-forward org-clock-line-re end t)
13053 (when (org-at-clock-log-p) (throw :clock t)))))
13054 (org-entry-put nil "LAST_REPEAT" (format-time-string
13055 (org-time-stamp-format t t)
13056 (current-time))))
13057 (when org-log-repeat
13058 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13059 (memq 'org-add-log-note post-command-hook))
13060 ;; We are already setup for some record.
13061 (when (eq org-log-repeat 'note)
13062 ;; Make sure we take a note, not only a time stamp.
13063 (setq org-log-note-how 'note))
13064 ;; Set up for taking a record.
13065 (org-add-log-setup 'state
13066 (or done-word (car org-done-keywords))
13067 org-last-state
13068 org-log-repeat)))
13069 (let ((planning-re (regexp-opt
13070 (list org-scheduled-string org-deadline-string))))
13071 (while (re-search-forward org-ts-regexp end t)
13072 (let* ((ts (match-string 0))
13073 (planning? (org-at-planning-p))
13074 (type (if (not planning?) "Plain:"
13075 (save-excursion
13076 (re-search-backward
13077 planning-re (line-beginning-position) t)
13078 (match-string 0)))))
13079 (cond
13080 ;; Ignore fake time-stamps (e.g., within comments).
13081 ((not (org-at-timestamp-p 'agenda)))
13082 ;; Time-stamps without a repeater are usually
13083 ;; skipped. However, a SCHEDULED time-stamp without
13084 ;; one is removed, as they are no longer relevant.
13085 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13086 ts))
13087 (when (equal type org-scheduled-string)
13088 (org-remove-timestamp-with-keyword type)))
13090 (let ((n (string-to-number (match-string 2 ts)))
13091 (what (match-string 3 ts)))
13092 (when (equal what "w") (setq n (* n 7) what "d"))
13093 (when (and (equal what "h")
13094 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13095 ts)))
13096 (user-error
13097 "Cannot repeat in Repeat in %d hour(s) because no hour \
13098 has been set"
13100 ;; Preparation, see if we need to modify the start
13101 ;; date for the change.
13102 (when (match-end 1)
13103 (let ((time (save-match-data
13104 (org-time-string-to-time ts))))
13105 (cond
13106 ((equal (match-string 1 ts) ".")
13107 ;; Shift starting date to today
13108 (org-timestamp-change
13109 (- (org-today) (time-to-days time))
13110 'day))
13111 ((equal (match-string 1 ts) "+")
13112 (let ((nshiftmax 10)
13113 (nshift 0))
13114 (while (or (= nshift 0)
13115 (not (time-less-p (current-time) time)))
13116 (when (= (cl-incf nshift) nshiftmax)
13117 (or (y-or-n-p
13118 (format "%d repeater intervals were not \
13119 enough to shift date past today. Continue? "
13120 nshift))
13121 (user-error "Abort")))
13122 (org-timestamp-change n (cdr (assoc what whata)))
13123 (org-in-regexp org-ts-regexp3)
13124 (setq ts (match-string 1))
13125 (setq time
13126 (save-match-data
13127 (org-time-string-to-time ts)))))
13128 (org-timestamp-change (- n) (cdr (assoc what whata)))
13129 ;; Rematch, so that we have everything in place
13130 ;; for the real shift.
13131 (org-in-regexp org-ts-regexp3)
13132 (setq ts (match-string 1))
13133 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13134 ts)))))
13135 (save-excursion
13136 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13137 (setq msg
13138 (concat
13139 msg type " " org-last-changed-timestamp " "))))))))
13140 (setq org-log-post-message msg)
13141 (message "%s" msg))
13142 (set-marker end nil))))
13144 (defun org-show-todo-tree (arg)
13145 "Make a compact tree which shows all headlines marked with TODO.
13146 The tree will show the lines where the regexp matches, and all higher
13147 headlines above the match.
13148 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13149 With a numeric prefix N, construct a sparse tree for the Nth element
13150 of `org-todo-keywords-1'."
13151 (interactive "P")
13152 (let ((case-fold-search nil)
13153 (kwd-re
13154 (cond ((null arg) org-not-done-regexp)
13155 ((equal arg '(4))
13156 (let ((kwd
13157 (completing-read "Keyword (or KWD1|KWD2|...): "
13158 (mapcar #'list org-todo-keywords-1))))
13159 (concat "\\("
13160 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13161 "\\)\\>")))
13162 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13163 (regexp-quote (nth (1- (prefix-numeric-value arg))
13164 org-todo-keywords-1)))
13165 (t (user-error "Invalid prefix argument: %s" arg)))))
13166 (message "%d TODO entries found"
13167 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13169 (defun org--deadline-or-schedule (arg type time)
13170 "Insert DEADLINE or SCHEDULE information in current entry.
13171 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13172 `org-schedule' for information about ARG and TIME arguments."
13173 (let* ((deadline? (eq type 'deadline))
13174 (keyword (if deadline? org-deadline-string org-scheduled-string))
13175 (log (if deadline? org-log-redeadline org-log-reschedule))
13176 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13177 (old-date-time (and old-date (org-time-string-to-time old-date)))
13178 ;; Save repeater cookie from either TIME or current scheduled
13179 ;; time stamp. We are going to insert it back at the end of
13180 ;; the process.
13181 (repeater (or (and (org-string-nw-p time)
13182 ;; We use `org-repeat-re' because we need
13183 ;; to tell the difference between a real
13184 ;; repeater and a time delta, e.g. "+2d".
13185 (string-match org-repeat-re time)
13186 (match-string 1 time))
13187 (and (org-string-nw-p old-date)
13188 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13189 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13190 old-date)
13191 (match-string 1 old-date)))))
13192 (pcase arg
13193 (`(4)
13194 (when (and old-date log)
13195 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13196 nil old-date log))
13197 (org-remove-timestamp-with-keyword keyword)
13198 (message (if deadline? "Item no longer has a deadline."
13199 "Item is no longer scheduled.")))
13200 (`(16)
13201 (save-excursion
13202 (org-back-to-heading t)
13203 (let ((regexp (if deadline? org-deadline-time-regexp
13204 org-scheduled-time-regexp)))
13205 (if (not (re-search-forward regexp (line-end-position 2) t))
13206 (user-error (if deadline? "No deadline information to update"
13207 "No scheduled information to update"))
13208 (let* ((rpl0 (match-string 1))
13209 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13210 (msg (if deadline? "Warn starting from" "Delay until")))
13211 (replace-match
13212 (concat keyword
13213 " <" rpl
13214 (format " -%dd"
13215 (abs (- (time-to-days
13216 (save-match-data
13217 (org-read-date
13218 nil t nil msg old-date-time)))
13219 (time-to-days old-date-time))))
13220 ">") t t))))))
13222 (org-add-planning-info type time 'closed)
13223 (when (and old-date
13225 (not (equal old-date org-last-inserted-timestamp)))
13226 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13227 org-last-inserted-timestamp
13228 old-date
13229 log))
13230 (when repeater
13231 (save-excursion
13232 (org-back-to-heading t)
13233 (when (re-search-forward
13234 (concat keyword " " org-last-inserted-timestamp)
13235 (line-end-position 2)
13237 (goto-char (1- (match-end 0)))
13238 (insert " " repeater)
13239 (setq org-last-inserted-timestamp
13240 (concat (substring org-last-inserted-timestamp 0 -1)
13241 " " repeater
13242 (substring org-last-inserted-timestamp -1))))))
13243 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13244 org-last-inserted-timestamp)))))
13246 (defun org-deadline (arg &optional time)
13247 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13248 With one universal prefix argument, remove any deadline from the item.
13249 With two universal prefix arguments, prompt for a warning delay.
13250 With argument TIME, set the deadline at the corresponding date. TIME
13251 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13252 (interactive "P")
13253 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13254 (org-map-entries
13255 (lambda () (org--deadline-or-schedule arg 'deadline time))
13257 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13258 'region-start-level
13259 'region)
13260 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13261 (org--deadline-or-schedule arg 'deadline time)))
13263 (defun org-schedule (arg &optional time)
13264 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13265 With one universal prefix argument, remove any scheduling date from the item.
13266 With two universal prefix arguments, prompt for a delay cookie.
13267 With argument TIME, scheduled at the corresponding date. TIME can
13268 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13269 (interactive "P")
13270 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13271 (org-map-entries
13272 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13274 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13275 'region-start-level
13276 'region)
13277 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13278 (org--deadline-or-schedule arg 'scheduled time)))
13280 (defun org-get-scheduled-time (pom &optional inherit)
13281 "Get the scheduled time as a time tuple, of a format suitable
13282 for calling org-schedule with, or if there is no scheduling,
13283 returns nil."
13284 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13285 (when time
13286 (apply 'encode-time (org-parse-time-string time)))))
13288 (defun org-get-deadline-time (pom &optional inherit)
13289 "Get the deadline as a time tuple, of a format suitable for
13290 calling org-deadline with, or if there is no scheduling, returns
13291 nil."
13292 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13293 (when time
13294 (apply 'encode-time (org-parse-time-string time)))))
13296 (defun org-remove-timestamp-with-keyword (keyword)
13297 "Remove all time stamps with KEYWORD in the current entry."
13298 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13299 beg)
13300 (save-excursion
13301 (org-back-to-heading t)
13302 (setq beg (point))
13303 (outline-next-heading)
13304 (while (re-search-backward re beg t)
13305 (replace-match "")
13306 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13307 (equal (char-before) ?\ ))
13308 (backward-delete-char 1)
13309 (when (string-match "^[ \t]*$" (buffer-substring
13310 (point-at-bol) (point-at-eol)))
13311 (delete-region (point-at-bol)
13312 (min (point-max) (1+ (point-at-eol))))))))))
13314 (defvar org-time-was-given) ; dynamically scoped parameter
13315 (defvar org-end-time-was-given) ; dynamically scoped parameter
13317 (defun org-at-planning-p ()
13318 "Non-nil when point is on a planning info line."
13319 ;; This is as accurate and faster than `org-element-at-point' since
13320 ;; planning info location is fixed in the section.
13321 (org-with-wide-buffer
13322 (beginning-of-line)
13323 (and (looking-at-p org-planning-line-re)
13324 (eq (point)
13325 (ignore-errors
13326 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13327 (org-back-to-heading t)
13328 (org-with-limited-levels (org-back-to-heading t)))
13329 (line-beginning-position 2))))))
13331 (defun org-add-planning-info (what &optional time &rest remove)
13332 "Insert new timestamp with keyword in the planning line.
13333 WHAT indicates what kind of time stamp to add. It is a symbol
13334 among `closed', `deadline', `scheduled' and nil. TIME indicates
13335 the time to use. If none is given, the user is prompted for
13336 a date. REMOVE indicates what kind of entries to remove. An old
13337 WHAT entry will also be removed."
13338 (let (org-time-was-given org-end-time-was-given default-time default-input)
13339 (catch 'exit
13340 (when (and (memq what '(scheduled deadline))
13341 (or (not time)
13342 (and (stringp time)
13343 (string-match "^[-+]+[0-9]" time))))
13344 ;; Try to get a default date/time from existing timestamp
13345 (save-excursion
13346 (org-back-to-heading t)
13347 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13348 (when (re-search-forward (if (eq what 'scheduled)
13349 org-scheduled-time-regexp
13350 org-deadline-time-regexp)
13351 end t)
13352 (setq ts (match-string 1)
13353 default-time (apply 'encode-time (org-parse-time-string ts))
13354 default-input (and ts (org-get-compact-tod ts)))))))
13355 (when what
13356 (setq time
13357 (if (stringp time)
13358 ;; This is a string (relative or absolute), set
13359 ;; proper date.
13360 (apply #'encode-time
13361 (org-read-date-analyze
13362 time default-time (decode-time default-time)))
13363 ;; If necessary, get the time from the user
13364 (or time (org-read-date nil 'to-time nil nil
13365 default-time default-input)))))
13367 (org-with-wide-buffer
13368 (org-back-to-heading t)
13369 (forward-line)
13370 (unless (bolp) (insert "\n"))
13371 (cond ((looking-at-p org-planning-line-re)
13372 ;; Move to current indentation.
13373 (skip-chars-forward " \t")
13374 ;; Check if we have to remove something.
13375 (dolist (type (if what (cons what remove) remove))
13376 (save-excursion
13377 (when (re-search-forward
13378 (cl-case type
13379 (closed org-closed-time-regexp)
13380 (deadline org-deadline-time-regexp)
13381 (scheduled org-scheduled-time-regexp)
13382 (otherwise
13383 (error "Invalid planning type: %s" type)))
13384 (line-end-position) t)
13385 ;; Delete until next keyword or end of line.
13386 (delete-region
13387 (match-beginning 0)
13388 (if (re-search-forward org-keyword-time-not-clock-regexp
13389 (line-end-position)
13391 (match-beginning 0)
13392 (line-end-position))))))
13393 ;; If there is nothing more to add and no more keyword
13394 ;; is left, remove the line completely.
13395 (if (and (looking-at-p "[ \t]*$") (not what))
13396 (delete-region (line-beginning-position)
13397 (line-beginning-position 2))
13398 ;; If we removed last keyword, do not leave trailing
13399 ;; white space at the end of line.
13400 (let ((p (point)))
13401 (save-excursion
13402 (end-of-line)
13403 (unless (= (skip-chars-backward " \t" p) 0)
13404 (delete-region (point) (line-end-position)))))))
13405 ((not what) (throw 'exit nil)) ; Nothing to do.
13406 (t (insert-before-markers "\n")
13407 (backward-char 1)
13408 (when org-adapt-indentation
13409 (indent-to-column (1+ (org-outline-level))))))
13410 (when what
13411 ;; Insert planning keyword.
13412 (insert (cl-case what
13413 (closed org-closed-string)
13414 (deadline org-deadline-string)
13415 (scheduled org-scheduled-string)
13416 (otherwise (error "Invalid planning type: %s" what)))
13417 " ")
13418 ;; Insert associated timestamp.
13419 (let ((ts (org-insert-time-stamp
13420 time
13421 (or org-time-was-given
13422 (and (eq what 'closed) org-log-done-with-time))
13423 (eq what 'closed)
13424 nil nil (list org-end-time-was-given))))
13425 (unless (eolp) (insert " "))
13426 ts))))))
13428 (defvar org-log-note-marker (make-marker)
13429 "Marker pointing at the entry where the note is to be inserted.")
13430 (defvar org-log-note-purpose nil)
13431 (defvar org-log-note-state nil)
13432 (defvar org-log-note-previous-state nil)
13433 (defvar org-log-note-extra nil)
13434 (defvar org-log-note-window-configuration nil)
13435 (defvar org-log-note-return-to (make-marker))
13436 (defvar org-log-note-effective-time nil
13437 "Remembered current time so that dynamically scoped
13438 `org-extend-today-until' affects timestamps in state change log")
13440 (defvar org-log-post-message nil
13441 "Message to be displayed after a log note has been stored.
13442 The auto-repeater uses this.")
13444 (defun org-add-note ()
13445 "Add a note to the current entry.
13446 This is done in the same way as adding a state change note."
13447 (interactive)
13448 (org-add-log-setup 'note))
13450 (defun org-log-beginning (&optional create)
13451 "Return expected start of log notes in current entry.
13452 When optional argument CREATE is non-nil, the function creates
13453 a drawer to store notes, if necessary. Returned position ignores
13454 narrowing."
13455 (org-with-wide-buffer
13456 (let ((drawer (org-log-into-drawer)))
13457 (cond
13458 (drawer
13459 (org-end-of-meta-data)
13460 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13461 (end (if (org-at-heading-p) (point)
13462 (save-excursion (outline-next-heading) (point))))
13463 (case-fold-search t))
13464 (catch 'exit
13465 ;; Try to find existing drawer.
13466 (while (re-search-forward regexp end t)
13467 (let ((element (org-element-at-point)))
13468 (when (eq (org-element-type element) 'drawer)
13469 (let ((cend (org-element-property :contents-end element)))
13470 (when (and (not org-log-states-order-reversed) cend)
13471 (goto-char cend)))
13472 (throw 'exit nil))))
13473 ;; No drawer found. Create one, if permitted.
13474 (when create
13475 (unless (bolp) (insert "\n"))
13476 (let ((beg (point)))
13477 (insert ":" drawer ":\n:END:\n")
13478 (org-indent-region beg (point)))
13479 (end-of-line -1)))))
13481 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13482 (skip-chars-forward " \t\n")
13483 (beginning-of-line)
13484 (unless org-log-states-order-reversed
13485 (org-skip-over-state-notes)
13486 (skip-chars-backward " \t\n")
13487 (forward-line)))))
13488 (if (bolp) (point) (line-beginning-position 2))))
13490 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13491 "Set up the post command hook to take a note.
13492 If this is about to TODO state change, the new state is expected in STATE.
13493 HOW is an indicator what kind of note should be created.
13494 EXTRA is additional text that will be inserted into the notes buffer."
13495 (move-marker org-log-note-marker (point))
13496 (setq org-log-note-purpose purpose
13497 org-log-note-state state
13498 org-log-note-previous-state prev-state
13499 org-log-note-how how
13500 org-log-note-extra extra
13501 org-log-note-effective-time (org-current-effective-time))
13502 (add-hook 'post-command-hook 'org-add-log-note 'append))
13504 (defun org-skip-over-state-notes ()
13505 "Skip past the list of State notes in an entry."
13506 (when (ignore-errors (goto-char (org-in-item-p)))
13507 (let* ((struct (org-list-struct))
13508 (prevs (org-list-prevs-alist struct))
13509 (regexp
13510 (concat "[ \t]*- +"
13511 (replace-regexp-in-string
13512 " +" " +"
13513 (org-replace-escapes
13514 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13515 `(("%d" . ,org-ts-regexp-inactive)
13516 ("%D" . ,org-ts-regexp)
13517 ("%s" . "\"\\S-+\"")
13518 ("%S" . "\"\\S-+\"")
13519 ("%t" . ,org-ts-regexp-inactive)
13520 ("%T" . ,org-ts-regexp)
13521 ("%u" . ".*?")
13522 ("%U" . ".*?")))))))
13523 (while (looking-at-p regexp)
13524 (goto-char (or (org-list-get-next-item (point) struct prevs)
13525 (org-list-get-item-end (point) struct)))))))
13527 (defun org-add-log-note (&optional _purpose)
13528 "Pop up a window for taking a note, and add this note later."
13529 (remove-hook 'post-command-hook 'org-add-log-note)
13530 (setq org-log-note-window-configuration (current-window-configuration))
13531 (delete-other-windows)
13532 (move-marker org-log-note-return-to (point))
13533 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13534 (goto-char org-log-note-marker)
13535 (org-switch-to-buffer-other-window "*Org Note*")
13536 (erase-buffer)
13537 (if (memq org-log-note-how '(time state))
13538 (org-store-log-note)
13539 (let ((org-inhibit-startup t)) (org-mode))
13540 (insert (format "# Insert note for %s.
13541 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13542 (cond
13543 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13544 ((eq org-log-note-purpose 'done) "closed todo item")
13545 ((eq org-log-note-purpose 'state)
13546 (format "state change from \"%s\" to \"%s\""
13547 (or org-log-note-previous-state "")
13548 (or org-log-note-state "")))
13549 ((eq org-log-note-purpose 'reschedule)
13550 "rescheduling")
13551 ((eq org-log-note-purpose 'delschedule)
13552 "no longer scheduled")
13553 ((eq org-log-note-purpose 'redeadline)
13554 "changing deadline")
13555 ((eq org-log-note-purpose 'deldeadline)
13556 "removing deadline")
13557 ((eq org-log-note-purpose 'refile)
13558 "refiling")
13559 ((eq org-log-note-purpose 'note)
13560 "this entry")
13561 (t (error "This should not happen")))))
13562 (when org-log-note-extra (insert org-log-note-extra))
13563 (setq-local org-finish-function 'org-store-log-note)
13564 (run-hooks 'org-log-buffer-setup-hook)))
13566 (defvar org-note-abort nil) ; dynamically scoped
13567 (defun org-store-log-note ()
13568 "Finish taking a log note, and insert it to where it belongs."
13569 (let ((txt (prog1 (buffer-string)
13570 (kill-buffer)))
13571 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13572 lines)
13573 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13574 (setq txt (replace-match "" t t txt)))
13575 (when (string-match "\\s-+\\'" txt)
13576 (setq txt (replace-match "" t t txt)))
13577 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13578 (when (org-string-nw-p note)
13579 (setq note
13580 (org-replace-escapes
13581 note
13582 (list (cons "%u" (user-login-name))
13583 (cons "%U" user-full-name)
13584 (cons "%t" (format-time-string
13585 (org-time-stamp-format 'long 'inactive)
13586 org-log-note-effective-time))
13587 (cons "%T" (format-time-string
13588 (org-time-stamp-format 'long nil)
13589 org-log-note-effective-time))
13590 (cons "%d" (format-time-string
13591 (org-time-stamp-format nil 'inactive)
13592 org-log-note-effective-time))
13593 (cons "%D" (format-time-string
13594 (org-time-stamp-format nil nil)
13595 org-log-note-effective-time))
13596 (cons "%s" (cond
13597 ((not org-log-note-state) "")
13598 ((string-match-p org-ts-regexp
13599 org-log-note-state)
13600 (format "\"[%s]\""
13601 (substring org-log-note-state 1 -1)))
13602 (t (format "\"%s\"" org-log-note-state))))
13603 (cons "%S"
13604 (cond
13605 ((not org-log-note-previous-state) "")
13606 ((string-match-p org-ts-regexp
13607 org-log-note-previous-state)
13608 (format "\"[%s]\""
13609 (substring
13610 org-log-note-previous-state 1 -1)))
13611 (t (format "\"%s\""
13612 org-log-note-previous-state)))))))
13613 (when lines (setq note (concat note " \\\\")))
13614 (push note lines))
13615 (when (and lines (not org-note-abort))
13616 (with-current-buffer (marker-buffer org-log-note-marker)
13617 (org-with-wide-buffer
13618 ;; Find location for the new note.
13619 (goto-char org-log-note-marker)
13620 (set-marker org-log-note-marker nil)
13621 ;; Note associated to a clock is to be located right after
13622 ;; the clock. Do not move point.
13623 (unless (eq org-log-note-purpose 'clock-out)
13624 (goto-char (org-log-beginning t)))
13625 ;; Make sure point is at the beginning of an empty line.
13626 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13627 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13628 ;; In an existing list, add a new item at the top level.
13629 ;; Otherwise, indent line like a regular one.
13630 (let ((itemp (org-in-item-p)))
13631 (if itemp
13632 (indent-line-to
13633 (let ((struct (save-excursion
13634 (goto-char itemp) (org-list-struct))))
13635 (org-list-get-ind (org-list-get-top-point struct) struct)))
13636 (org-indent-line)))
13637 (insert (org-list-bullet-string "-") (pop lines))
13638 (let ((ind (org-list-item-body-column (line-beginning-position))))
13639 (dolist (line lines)
13640 (insert "\n")
13641 (indent-line-to ind)
13642 (insert line)))
13643 (message "Note stored")
13644 (org-back-to-heading t)
13645 (org-cycle-hide-drawers 'children))
13646 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13647 ;; from within `org-add-log-note' because `buffer-undo-list'
13648 ;; is then modified outside of `org-with-remote-undo'.
13649 (when (eq this-command 'org-agenda-todo)
13650 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13651 ;; Don't add undo information when called from `org-agenda-todo'.
13652 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13653 (set-window-configuration org-log-note-window-configuration)
13654 (with-current-buffer (marker-buffer org-log-note-return-to)
13655 (goto-char org-log-note-return-to))
13656 (move-marker org-log-note-return-to nil)
13657 (when org-log-post-message (message "%s" org-log-post-message))))
13659 (defun org-remove-empty-drawer-at (pos)
13660 "Remove an empty drawer at position POS.
13661 POS may also be a marker."
13662 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13663 (org-with-wide-buffer
13664 (goto-char pos)
13665 (let ((drawer (org-element-at-point)))
13666 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13667 (not (org-element-property :contents-begin drawer)))
13668 (delete-region (org-element-property :begin drawer)
13669 (progn (goto-char (org-element-property :end drawer))
13670 (skip-chars-backward " \r\t\n")
13671 (forward-line)
13672 (point))))))))
13674 (defvar org-ts-type nil)
13675 (defun org-sparse-tree (&optional arg type)
13676 "Create a sparse tree, prompt for the details.
13677 This command can create sparse trees. You first need to select the type
13678 of match used to create the tree:
13680 t Show all TODO entries.
13681 T Show entries with a specific TODO keyword.
13682 m Show entries selected by a tags/property match.
13683 p Enter a property name and its value (both with completion on existing
13684 names/values) and show entries with that property.
13685 r Show entries matching a regular expression (`/' can be used as well).
13686 b Show deadlines and scheduled items before a date.
13687 a Show deadlines and scheduled items after a date.
13688 d Show deadlines due within `org-deadline-warning-days'.
13689 D Show deadlines and scheduled items between a date range."
13690 (interactive "P")
13691 (setq type (or type org-sparse-tree-default-date-type))
13692 (setq org-ts-type type)
13693 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13694 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13695 \[c]ycle through date types: %s"
13696 (cl-case type
13697 (all "all timestamps")
13698 (scheduled "only scheduled")
13699 (deadline "only deadline")
13700 (active "only active timestamps")
13701 (inactive "only inactive timestamps")
13702 (closed "with a closed time-stamp")
13703 (otherwise "scheduled/deadline")))
13704 (let ((answer (read-char-exclusive)))
13705 (cl-case answer
13707 (org-sparse-tree
13709 (cadr
13710 (memq type '(nil all scheduled deadline active inactive closed)))))
13711 (?d (call-interactively 'org-check-deadlines))
13712 (?b (call-interactively 'org-check-before-date))
13713 (?a (call-interactively 'org-check-after-date))
13714 (?D (call-interactively 'org-check-dates-range))
13715 (?t (call-interactively 'org-show-todo-tree))
13716 (?T (org-show-todo-tree '(4)))
13717 (?m (call-interactively 'org-match-sparse-tree))
13718 ((?p ?P)
13719 (let* ((kwd (completing-read
13720 "Property: " (mapcar #'list (org-buffer-property-keys))))
13721 (value (completing-read
13722 "Value: " (mapcar #'list (org-property-values kwd)))))
13723 (unless (string-match "\\`{.*}\\'" value)
13724 (setq value (concat "\"" value "\"")))
13725 (org-match-sparse-tree arg (concat kwd "=" value))))
13726 ((?r ?R ?/) (call-interactively 'org-occur))
13727 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13729 (defvar-local org-occur-highlights nil
13730 "List of overlays used for occur matches.")
13731 (defvar-local org-occur-parameters nil
13732 "Parameters of the active org-occur calls.
13733 This is a list, each call to org-occur pushes as cons cell,
13734 containing the regular expression and the callback, onto the list.
13735 The list can contain several entries if `org-occur' has been called
13736 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13737 will only contain one set of parameters. When the highlights are
13738 removed (for example with `C-c C-c', or with the next edit (depending
13739 on `org-remove-highlights-with-change'), this variable is emptied
13740 as well.")
13742 (defun org-occur (regexp &optional keep-previous callback)
13743 "Make a compact tree which shows all matches of REGEXP.
13745 The tree will show the lines where the regexp matches, and any other context
13746 defined in `org-show-context-detail', which see.
13748 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13749 done by a previous call to `org-occur' will be kept, to allow stacking of
13750 calls to this command.
13752 Optional argument CALLBACK can be a function of no argument. In this case,
13753 it is called with point at the end of the match, match data being set
13754 accordingly. Current match is shown only if the return value is non-nil.
13755 The function must neither move point nor alter narrowing."
13756 (interactive "sRegexp: \nP")
13757 (when (equal regexp "")
13758 (user-error "Regexp cannot be empty"))
13759 (unless keep-previous
13760 (org-remove-occur-highlights nil nil t))
13761 (push (cons regexp callback) org-occur-parameters)
13762 (let ((cnt 0))
13763 (save-excursion
13764 (goto-char (point-min))
13765 (when (or (not keep-previous) ; do not want to keep
13766 (not org-occur-highlights)) ; no previous matches
13767 ;; hide everything
13768 (org-overview))
13769 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13770 (isearch-no-upper-case-p regexp t)
13771 org-occur-case-fold-search)))
13772 (while (re-search-forward regexp nil t)
13773 (when (or (not callback)
13774 (save-match-data (funcall callback)))
13775 (setq cnt (1+ cnt))
13776 (when org-highlight-sparse-tree-matches
13777 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13778 (org-show-context 'occur-tree)))))
13779 (when org-remove-highlights-with-change
13780 (add-hook 'before-change-functions 'org-remove-occur-highlights
13781 nil 'local))
13782 (unless org-sparse-tree-open-archived-trees
13783 (org-hide-archived-subtrees (point-min) (point-max)))
13784 (run-hooks 'org-occur-hook)
13785 (when (called-interactively-p 'interactive)
13786 (message "%d match(es) for regexp %s" cnt regexp))
13787 cnt))
13789 (defun org-occur-next-match (&optional n _reset)
13790 "Function for `next-error-function' to find sparse tree matches.
13791 N is the number of matches to move, when negative move backwards.
13792 This function always goes back to the starting point when no
13793 match is found."
13794 (let* ((limit (if (< n 0) (point-min) (point-max)))
13795 (search-func (if (< n 0)
13796 'previous-single-char-property-change
13797 'next-single-char-property-change))
13798 (n (abs n))
13799 (pos (point))
13801 (catch 'exit
13802 (while (setq p1 (funcall search-func (point) 'org-type))
13803 (when (equal p1 limit)
13804 (goto-char pos)
13805 (user-error "No more matches"))
13806 (when (equal (get-char-property p1 'org-type) 'org-occur)
13807 (setq n (1- n))
13808 (when (= n 0)
13809 (goto-char p1)
13810 (throw 'exit (point))))
13811 (goto-char p1))
13812 (goto-char p1)
13813 (user-error "No more matches"))))
13815 (defun org-show-context (&optional key)
13816 "Make sure point and context are visible.
13817 Optional argument KEY, when non-nil, is a symbol. See
13818 `org-show-context-detail' for allowed values and how much is to
13819 be shown."
13820 (org-show-set-visibility
13821 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13822 ((cdr (assq key org-show-context-detail)))
13823 (t (cdr (assq 'default org-show-context-detail))))))
13825 (defun org-show-set-visibility (detail)
13826 "Set visibility around point according to DETAIL.
13827 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13828 `tree', `canonical' or t. See `org-show-context-detail' for more
13829 information."
13830 ;; Show current heading and possibly its entry, following headline
13831 ;; or all children.
13832 (if (and (org-at-heading-p) (not (eq detail 'local)))
13833 (org-flag-heading nil)
13834 (org-show-entry)
13835 ;; If point is hidden within a drawer or a block, make sure to
13836 ;; expose it.
13837 (dolist (o (overlays-at (point)))
13838 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13839 (delete-overlay o)))
13840 (unless (org-before-first-heading-p)
13841 (org-with-limited-levels
13842 (cl-case detail
13843 ((tree canonical t) (org-show-children))
13844 ((nil minimal ancestors))
13845 (t (save-excursion
13846 (outline-next-heading)
13847 (org-flag-heading nil)))))))
13848 ;; Show all siblings.
13849 (when (eq detail 'lineage) (org-show-siblings))
13850 ;; Show ancestors, possibly with their children.
13851 (when (memq detail '(ancestors lineage tree canonical t))
13852 (save-excursion
13853 (while (org-up-heading-safe)
13854 (org-flag-heading nil)
13855 (when (memq detail '(canonical t)) (org-show-entry))
13856 (when (memq detail '(tree canonical t)) (org-show-children))))))
13858 (defvar org-reveal-start-hook nil
13859 "Hook run before revealing a location.")
13861 (defun org-reveal (&optional siblings)
13862 "Show current entry, hierarchy above it, and the following headline.
13864 This can be used to show a consistent set of context around
13865 locations exposed with `org-show-context'.
13867 With optional argument SIBLINGS, on each level of the hierarchy all
13868 siblings are shown. This repairs the tree structure to what it would
13869 look like when opened with hierarchical calls to `org-cycle'.
13871 With a \\[universal-argument] \\[universal-argument] prefix, \
13872 go to the parent and show the entire tree."
13873 (interactive "P")
13874 (run-hooks 'org-reveal-start-hook)
13875 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13876 ((equal siblings '(16))
13877 (save-excursion
13878 (when (org-up-heading-safe)
13879 (org-show-subtree)
13880 (run-hook-with-args 'org-cycle-hook 'subtree))))
13881 (t (org-show-set-visibility 'lineage))))
13883 (defun org-highlight-new-match (beg end)
13884 "Highlight from BEG to END and mark the highlight is an occur headline."
13885 (let ((ov (make-overlay beg end)))
13886 (overlay-put ov 'face 'secondary-selection)
13887 (overlay-put ov 'org-type 'org-occur)
13888 (push ov org-occur-highlights)))
13890 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13891 "Remove the occur highlights from the buffer.
13892 BEG and END are ignored. If NOREMOVE is nil, remove this function
13893 from the `before-change-functions' in the current buffer."
13894 (interactive)
13895 (unless org-inhibit-highlight-removal
13896 (mapc #'delete-overlay org-occur-highlights)
13897 (setq org-occur-highlights nil)
13898 (setq org-occur-parameters nil)
13899 (unless noremove
13900 (remove-hook 'before-change-functions
13901 'org-remove-occur-highlights 'local))))
13903 ;;;; Priorities
13905 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13906 "Regular expression matching the priority indicator.")
13908 (defvar org-remove-priority-next-time nil)
13910 (defun org-priority-up ()
13911 "Increase the priority of the current item."
13912 (interactive)
13913 (org-priority 'up))
13915 (defun org-priority-down ()
13916 "Decrease the priority of the current item."
13917 (interactive)
13918 (org-priority 'down))
13920 (defun org-priority (&optional action _show)
13921 "Change the priority of an item.
13922 ACTION can be `set', `up', `down', or a character."
13923 (interactive "P")
13924 (if (equal action '(4))
13925 (org-show-priority)
13926 (unless org-enable-priority-commands
13927 (user-error "Priority commands are disabled"))
13928 (setq action (or action 'set))
13929 (let (current new news have remove)
13930 (save-excursion
13931 (org-back-to-heading t)
13932 (when (looking-at org-priority-regexp)
13933 (setq current (string-to-char (match-string 2))
13934 have t))
13935 (cond
13936 ((eq action 'remove)
13937 (setq remove t new ?\ ))
13938 ((or (eq action 'set)
13939 (integerp action))
13940 (if (not (eq action 'set))
13941 (setq new action)
13942 (message "Priority %c-%c, SPC to remove: "
13943 org-highest-priority org-lowest-priority)
13944 (save-match-data
13945 (setq new (read-char-exclusive))))
13946 (when (and (= (upcase org-highest-priority) org-highest-priority)
13947 (= (upcase org-lowest-priority) org-lowest-priority))
13948 (setq new (upcase new)))
13949 (cond ((equal new ?\ ) (setq remove t))
13950 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13951 (user-error "Priority must be between `%c' and `%c'"
13952 org-highest-priority org-lowest-priority))))
13953 ((eq action 'up)
13954 (setq new (if have
13955 (1- current) ; normal cycling
13956 ;; last priority was empty
13957 (if (eq last-command this-command)
13958 org-lowest-priority ; wrap around empty to lowest
13959 ;; default
13960 (if org-priority-start-cycle-with-default
13961 org-default-priority
13962 (1- org-default-priority))))))
13963 ((eq action 'down)
13964 (setq new (if have
13965 (1+ current) ; normal cycling
13966 ;; last priority was empty
13967 (if (eq last-command this-command)
13968 org-highest-priority ; wrap around empty to highest
13969 ;; default
13970 (if org-priority-start-cycle-with-default
13971 org-default-priority
13972 (1+ org-default-priority))))))
13973 (t (user-error "Invalid action")))
13974 (when (or (< (upcase new) org-highest-priority)
13975 (> (upcase new) org-lowest-priority))
13976 (if (and (memq action '(up down))
13977 (not have) (not (eq last-command this-command)))
13978 ;; `new' is from default priority
13979 (error
13980 "The default can not be set, see `org-default-priority' why")
13981 ;; normal cycling: `new' is beyond highest/lowest priority
13982 ;; and is wrapped around to the empty priority
13983 (setq remove t)))
13984 (setq news (format "%c" new))
13985 (if have
13986 (if remove
13987 (replace-match "" t t nil 1)
13988 (replace-match news t t nil 2))
13989 (if remove
13990 (user-error "No priority cookie found in line")
13991 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13992 (if (match-end 2)
13993 (progn
13994 (goto-char (match-end 2))
13995 (insert " [#" news "]"))
13996 (goto-char (match-beginning 3))
13997 (insert "[#" news "] "))))
13998 (org-set-tags nil 'align))
13999 (if remove
14000 (message "Priority removed")
14001 (message "Priority of current item set to %s" news)))))
14003 (defun org-show-priority ()
14004 "Show the priority of the current item.
14005 This priority is composed of the main priority given with the [#A] cookies,
14006 and by additional input from the age of a schedules or deadline entry."
14007 (interactive)
14008 (let ((pri (if (eq major-mode 'org-agenda-mode)
14009 (org-get-at-bol 'priority)
14010 (save-excursion
14011 (save-match-data
14012 (beginning-of-line)
14013 (and (looking-at org-heading-regexp)
14014 (org-get-priority (match-string 0))))))))
14015 (message "Priority is %d" (if pri pri -1000))))
14017 (defun org-get-priority (s)
14018 "Find priority cookie and return priority."
14019 (save-match-data
14020 (if (functionp org-get-priority-function)
14021 (funcall org-get-priority-function)
14022 (if (not (string-match org-priority-regexp s))
14023 (* 1000 (- org-lowest-priority org-default-priority))
14024 (* 1000 (- org-lowest-priority
14025 (string-to-char (match-string 2 s))))))))
14027 ;;;; Tags
14029 (defvar org-agenda-archives-mode)
14030 (defvar org-map-continue-from nil
14031 "Position from where mapping should continue.
14032 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14034 (defvar org-scanner-tags nil
14035 "The current tag list while the tags scanner is running.")
14037 (defvar org-trust-scanner-tags nil
14038 "Should `org-get-tags-at' use the tags for the scanner.
14039 This is for internal dynamical scoping only.
14040 When this is non-nil, the function `org-get-tags-at' will return the value
14041 of `org-scanner-tags' instead of building the list by itself. This
14042 can lead to large speed-ups when the tags scanner is used in a file with
14043 many entries, and when the list of tags is retrieved, for example to
14044 obtain a list of properties. Building the tags list for each entry in such
14045 a file becomes an N^2 operation - but with this variable set, it scales
14046 as N.")
14048 (defvar org--matcher-tags-todo-only nil)
14050 (defun org-scan-tags (action matcher todo-only &optional start-level)
14051 "Scan headline tags with inheritance and produce output ACTION.
14053 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14054 or `agenda' to produce an entry list for an agenda view. It can also be
14055 a Lisp form or a function that should be called at each matched headline, in
14056 this case the return value is a list of all return values from these calls.
14058 MATCHER is a function accepting three arguments, returning
14059 a non-nil value whenever a given set of tags qualifies a headline
14060 for inclusion. See `org-make-tags-matcher' for more information.
14061 As a special case, it can also be set to t (respectively nil) in
14062 order to match all (respectively none) headline.
14064 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14065 included in the output.
14067 START-LEVEL can be a string with asterisks, reducing the scope to
14068 headlines matching this string."
14069 (require 'org-agenda)
14070 (let* ((re (concat "^"
14071 (if start-level
14072 ;; Get the correct level to match
14073 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14074 org-outline-regexp)
14075 " *\\(\\<\\("
14076 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14077 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14078 (props (list 'face 'default
14079 'done-face 'org-agenda-done
14080 'undone-face 'default
14081 'mouse-face 'highlight
14082 'org-not-done-regexp org-not-done-regexp
14083 'org-todo-regexp org-todo-regexp
14084 'org-complex-heading-regexp org-complex-heading-regexp
14085 'help-echo
14086 (format "mouse-2 or RET jump to org file %s"
14087 (abbreviate-file-name
14088 (or (buffer-file-name (buffer-base-buffer))
14089 (buffer-name (buffer-base-buffer)))))))
14090 (org-map-continue-from nil)
14091 lspos tags tags-list
14092 (tags-alist (list (cons 0 org-file-tags)))
14093 (llast 0) rtn rtn1 level category i txt
14094 todo marker entry priority
14095 ts-date ts-date-type ts-date-pair)
14096 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14097 (setq action (list 'lambda nil action)))
14098 (save-excursion
14099 (goto-char (point-min))
14100 (when (eq action 'sparse-tree)
14101 (org-overview)
14102 (org-remove-occur-highlights))
14103 (while (let (case-fold-search)
14104 (re-search-forward re nil t))
14105 (setq org-map-continue-from nil)
14106 (catch :skip
14107 (setq todo
14108 ;; TODO: is the 1-2 difference a bug?
14109 (when (match-end 1) (match-string-no-properties 2))
14110 tags (when (match-end 4) (match-string-no-properties 4)))
14111 (goto-char (setq lspos (match-beginning 0)))
14112 (setq level (org-reduced-level (org-outline-level))
14113 category (org-get-category))
14114 (when (eq action 'agenda)
14115 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14116 ts-date (car ts-date-pair)
14117 ts-date-type (cdr ts-date-pair)))
14118 (setq i llast llast level)
14119 ;; remove tag lists from same and sublevels
14120 (while (>= i level)
14121 (when (setq entry (assoc i tags-alist))
14122 (setq tags-alist (delete entry tags-alist)))
14123 (setq i (1- i)))
14124 ;; add the next tags
14125 (when tags
14126 (setq tags (org-split-string tags ":")
14127 tags-alist
14128 (cons (cons level tags) tags-alist)))
14129 ;; compile tags for current headline
14130 (setq tags-list
14131 (if org-use-tag-inheritance
14132 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14133 tags)
14134 org-scanner-tags tags-list)
14135 (when org-use-tag-inheritance
14136 (setcdr (car tags-alist)
14137 (mapcar (lambda (x)
14138 (setq x (copy-sequence x))
14139 (org-add-prop-inherited x))
14140 (cdar tags-alist))))
14141 (when (and tags org-use-tag-inheritance
14142 (or (not (eq t org-use-tag-inheritance))
14143 org-tags-exclude-from-inheritance))
14144 ;; Selective inheritance, remove uninherited ones.
14145 (setcdr (car tags-alist)
14146 (org-remove-uninherited-tags (cdar tags-alist))))
14147 (when (and
14149 ;; eval matcher only when the todo condition is OK
14150 (and (or (not todo-only) (member todo org-todo-keywords-1))
14151 (if (functionp matcher)
14152 (let ((case-fold-search t) (org-trust-scanner-tags t))
14153 (funcall matcher todo tags-list level))
14154 matcher))
14156 ;; Call the skipper, but return t if it does not
14157 ;; skip, so that the `and' form continues evaluating.
14158 (progn
14159 (unless (eq action 'sparse-tree) (org-agenda-skip))
14162 ;; Check if timestamps are deselecting this entry
14163 (or (not todo-only)
14164 (and (member todo org-todo-keywords-1)
14165 (or (not org-agenda-tags-todo-honor-ignore-options)
14166 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14168 ;; select this headline
14169 (cond
14170 ((eq action 'sparse-tree)
14171 (and org-highlight-sparse-tree-matches
14172 (org-get-heading) (match-end 0)
14173 (org-highlight-new-match
14174 (match-beginning 1) (match-end 1)))
14175 (org-show-context 'tags-tree))
14176 ((eq action 'agenda)
14177 (setq txt (org-agenda-format-item
14179 (concat
14180 (if (eq org-tags-match-list-sublevels 'indented)
14181 (make-string (1- level) ?.) "")
14182 (org-get-heading))
14183 (make-string level ?\s)
14184 category
14185 tags-list)
14186 priority (org-get-priority txt))
14187 (goto-char lspos)
14188 (setq marker (org-agenda-new-marker))
14189 (org-add-props txt props
14190 'org-marker marker 'org-hd-marker marker 'org-category category
14191 'todo-state todo
14192 'ts-date ts-date
14193 'priority priority
14194 'type (concat "tagsmatch" ts-date-type))
14195 (push txt rtn))
14196 ((functionp action)
14197 (setq org-map-continue-from nil)
14198 (save-excursion
14199 (setq rtn1 (funcall action))
14200 (push rtn1 rtn)))
14201 (t (user-error "Invalid action")))
14203 ;; if we are to skip sublevels, jump to end of subtree
14204 (unless org-tags-match-list-sublevels
14205 (org-end-of-subtree t)
14206 (backward-char 1))))
14207 ;; Get the correct position from where to continue
14208 (if org-map-continue-from
14209 (goto-char org-map-continue-from)
14210 (and (= (point) lspos) (end-of-line 1)))))
14211 (when (and (eq action 'sparse-tree)
14212 (not org-sparse-tree-open-archived-trees))
14213 (org-hide-archived-subtrees (point-min) (point-max)))
14214 (nreverse rtn)))
14216 (defun org-remove-uninherited-tags (tags)
14217 "Remove all tags that are not inherited from the list TAGS."
14218 (cond
14219 ((eq org-use-tag-inheritance t)
14220 (if org-tags-exclude-from-inheritance
14221 (org-delete-all org-tags-exclude-from-inheritance tags)
14222 tags))
14223 ((not org-use-tag-inheritance) nil)
14224 ((stringp org-use-tag-inheritance)
14225 (delq nil (mapcar
14226 (lambda (x)
14227 (if (and (string-match org-use-tag-inheritance x)
14228 (not (member x org-tags-exclude-from-inheritance)))
14229 x nil))
14230 tags)))
14231 ((listp org-use-tag-inheritance)
14232 (delq nil (mapcar
14233 (lambda (x)
14234 (if (member x org-use-tag-inheritance) x nil))
14235 tags)))))
14237 (defun org-match-sparse-tree (&optional todo-only match)
14238 "Create a sparse tree according to tags string MATCH.
14240 MATCH is a string with match syntax. It can contain a selection
14241 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14242 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14243 those. See the manual for details.
14245 If optional argument TODO-ONLY is non-nil, only select lines that
14246 are also TODO tasks."
14247 (interactive "P")
14248 (org-agenda-prepare-buffers (list (current-buffer)))
14249 (let ((org--matcher-tags-todo-only todo-only))
14250 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14251 org--matcher-tags-todo-only)))
14253 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14255 (defvar org-cached-props nil)
14256 (defun org-cached-entry-get (pom property)
14257 (if (or (eq t org-use-property-inheritance)
14258 (and (stringp org-use-property-inheritance)
14259 (let ((case-fold-search t))
14260 (string-match-p org-use-property-inheritance property)))
14261 (and (listp org-use-property-inheritance)
14262 (member-ignore-case property org-use-property-inheritance)))
14263 ;; Caching is not possible, check it directly.
14264 (org-entry-get pom property 'inherit)
14265 ;; Get all properties, so we can do complicated checks easily.
14266 (cdr (assoc-string property
14267 (or org-cached-props
14268 (setq org-cached-props (org-entry-properties pom)))
14269 t))))
14271 (defun org-global-tags-completion-table (&optional files)
14272 "Return the list of all tags in all agenda buffer/files.
14273 Optional FILES argument is a list of files which can be used
14274 instead of the agenda files."
14275 (save-excursion
14276 (org-uniquify
14277 (delq nil
14278 (apply #'append
14279 (mapcar
14280 (lambda (file)
14281 (set-buffer (find-file-noselect file))
14282 (mapcar (lambda (x)
14283 (and (stringp (car-safe x))
14284 (list (car-safe x))))
14285 (or org-current-tag-alist (org-get-buffer-tags))))
14286 (if (car-safe files) files
14287 (org-agenda-files))))))))
14289 (defun org-make-tags-matcher (match)
14290 "Create the TAGS/TODO matcher form for the selection string MATCH.
14292 Returns a cons of the selection string MATCH and a function
14293 implementing the matcher.
14295 The matcher is to be called at an Org entry, with point on the
14296 headline, and returns non-nil if the entry matches the selection
14297 string MATCH. It must be called with three arguments: the TODO
14298 keyword at the entry (or nil if none), the list of all tags at
14299 the entry including inherited ones and the reduced level of the
14300 headline. Additionally, the category of the entry, if any, must
14301 be specified as the text property `org-category' on the headline.
14303 This function sets the variable `org--matcher-tags-todo-only' to
14304 a non-nil value if the matcher restricts matching to TODO
14305 entries, otherwise it is not touched.
14307 See also `org-scan-tags'."
14308 (unless match
14309 ;; Get a new match request, with completion against the global
14310 ;; tags table and the local tags in current buffer.
14311 (let ((org-last-tags-completion-table
14312 (org-uniquify
14313 (delq nil (append (org-get-buffer-tags)
14314 (org-global-tags-completion-table))))))
14315 (setq match
14316 (completing-read
14317 "Match: "
14318 'org-tags-completion-function nil nil nil 'org-tags-history))))
14320 (let ((match0 match)
14321 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14322 (start 0)
14323 tagsmatch todomatch tagsmatcher todomatcher)
14325 ;; Expand group tags.
14326 (setq match (org-tags-expand match))
14328 ;; Check if there is a TODO part of this match, which would be the
14329 ;; part after a "/". To make sure that this slash is not part of
14330 ;; a property value to be matched against, we also check that
14331 ;; there is no / after that slash. First, find the last slash.
14332 (let ((s 0))
14333 (while (string-match "/+" match s)
14334 (setq start (match-beginning 0))
14335 (setq s (match-end 0))))
14336 (if (and (string-match "/+" match start)
14337 (not (string-match-p "\"" match start)))
14338 ;; Match contains also a TODO-matching request.
14339 (progn
14340 (setq tagsmatch (substring match 0 (match-beginning 0)))
14341 (setq todomatch (substring match (match-end 0)))
14342 (when (string-prefix-p "!" todomatch)
14343 (setq org--matcher-tags-todo-only t)
14344 (setq todomatch (substring todomatch 1)))
14345 (when (string-match "\\`\\s-*\\'" todomatch)
14346 (setq todomatch nil)))
14347 ;; Only matching tags.
14348 (setq tagsmatch match)
14349 (setq todomatch nil))
14351 ;; Make the tags matcher.
14352 (when (org-string-nw-p tagsmatch)
14353 (let ((orlist nil)
14354 (orterms (org-split-string tagsmatch "|"))
14355 term)
14356 (while (setq term (pop orterms))
14357 (while (and (equal (substring term -1) "\\") orterms)
14358 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14359 (while (string-match re term)
14360 (let* ((rest (substring term (match-end 0)))
14361 (minus (and (match-end 1)
14362 (equal (match-string 1 term) "-")))
14363 (tag (save-match-data
14364 (replace-regexp-in-string
14365 "\\\\-" "-" (match-string 2 term))))
14366 (regexp (eq (string-to-char tag) ?{))
14367 (levelp (match-end 4))
14368 (propp (match-end 5))
14370 (cond
14371 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14372 (levelp
14373 `(,(org-op-to-function (match-string 3 term))
14374 level
14375 ,(string-to-number (match-string 4 term))))
14376 (propp
14377 (let* ((gv (pcase (upcase (match-string 5 term))
14378 ("CATEGORY"
14379 '(get-text-property (point) 'org-category))
14380 ("TODO" 'todo)
14381 (p `(org-cached-entry-get nil ,p))))
14382 (pv (match-string 7 term))
14383 (regexp (eq (string-to-char pv) ?{))
14384 (strp (eq (string-to-char pv) ?\"))
14385 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14386 (po (org-op-to-function (match-string 6 term)
14387 (if timep 'time strp))))
14388 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14389 (when timep (setq pv (org-matcher-time pv)))
14390 (cond ((and regexp (eq po 'org<>))
14391 `(not (string-match ,pv (or ,gv ""))))
14392 (regexp `(string-match ,pv (or ,gv "")))
14393 (strp `(,po (or ,gv "") ,pv))
14395 `(,po
14396 (string-to-number (or ,gv ""))
14397 ,(string-to-number pv))))))
14398 (t `(member ,tag tags-list)))))
14399 (push (if minus `(not ,mm) mm) tagsmatcher)
14400 (setq term rest)))
14401 (push `(and ,@tagsmatcher) orlist)
14402 (setq tagsmatcher nil))
14403 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14405 ;; Make the TODO matcher.
14406 (when (org-string-nw-p todomatch)
14407 (let ((orlist nil))
14408 (dolist (term (org-split-string todomatch "|"))
14409 (while (string-match re term)
14410 (let* ((minus (and (match-end 1)
14411 (equal (match-string 1 term) "-")))
14412 (kwd (match-string 2 term))
14413 (regexp (eq (string-to-char kwd) ?{))
14414 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14415 `(equal todo ,kwd))))
14416 (push (if minus `(not ,mm) mm) todomatcher))
14417 (setq term (substring term (match-end 0))))
14418 (push (if (> (length todomatcher) 1)
14419 (cons 'and todomatcher)
14420 (car todomatcher))
14421 orlist)
14422 (setq todomatcher nil))
14423 (setq todomatcher (cons 'or orlist))))
14425 ;; Return the string and function of the matcher. If no
14426 ;; tags-specific or todo-specific matcher exists, match
14427 ;; everything.
14428 (let ((matcher (if (and tagsmatcher todomatcher)
14429 `(and ,tagsmatcher ,todomatcher)
14430 (or tagsmatcher todomatcher t))))
14431 (when org--matcher-tags-todo-only
14432 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14433 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14435 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14436 "Expand group tags in MATCH.
14438 This replaces every group tag in MATCH with a regexp tag search.
14439 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14440 will be replaced like this:
14442 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14443 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14444 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14446 Replacing by a regexp preserves the structure of the match.
14447 E.g., this expansion
14449 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14451 will match anything tagged with \"Lab\" and \"Home\", or tagged
14452 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14454 A group tag in MATCH can contain regular expressions of its own.
14455 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14456 will be replaced like this:
14458 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14460 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14461 assumed to be a single group tag, and the function will return
14462 the list of tags in this group.
14464 When DOWNCASE is non-nil, expand downcased TAGS."
14465 (if org-group-tags
14466 (let* ((case-fold-search t)
14467 (stable org-mode-syntax-table)
14468 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14469 (taggroups (if downcased
14470 (mapcar (lambda (tg) (mapcar #'downcase tg))
14471 taggroups)
14472 taggroups))
14473 (taggroups-keys (mapcar #'car taggroups))
14474 (return-match (if downcased (downcase match) match))
14475 (count 0)
14476 (work-already-expanded tags-already-expanded)
14477 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14478 ;; @ and _ are allowed as word-components in tags.
14479 (modify-syntax-entry ?@ "w" stable)
14480 (modify-syntax-entry ?_ "w" stable)
14481 ;; Temporarily replace regexp-expressions in the match-expression.
14482 (while (string-match "{.+?}" return-match)
14483 (cl-incf count)
14484 (push (match-string 0 return-match) regexps-in-match)
14485 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14486 (while (and taggroups-keys
14487 (with-syntax-table stable
14488 (string-match
14489 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14490 (regexp-opt taggroups-keys) "\\>\\)")
14491 return-match)))
14492 (let* ((dir (match-string 1 return-match))
14493 (tag (match-string 2 return-match))
14494 (tag (if downcased (downcase tag) tag)))
14495 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14496 (member tag work-already-expanded))
14497 (setq tags-in-group (assoc tag taggroups))
14498 (push tag work-already-expanded)
14499 ;; Recursively expand each tag in the group, if the tag hasn't
14500 ;; already been expanded. Restore the match-data after all recursive calls.
14501 (save-match-data
14502 (let (tags-expanded)
14503 (dolist (x (cdr tags-in-group))
14504 (if (and (member x taggroups-keys)
14505 (not (member x work-already-expanded)))
14506 (setq tags-expanded
14507 (delete-dups
14508 (append
14509 (org-tags-expand x t downcased
14510 work-already-expanded)
14511 tags-expanded)))
14512 (setq tags-expanded
14513 (append (list x) tags-expanded)))
14514 (setq work-already-expanded
14515 (delete-dups
14516 (append tags-expanded
14517 work-already-expanded))))
14518 (setq tags-in-group
14519 (delete-dups (cons (car tags-in-group)
14520 tags-expanded)))))
14521 ;; Filter tag-regexps from tags.
14522 (setq regexp-in-group-escaped
14523 (delq nil (mapcar (lambda (x)
14524 (if (stringp x)
14525 (and (equal "{" (substring x 0 1))
14526 (equal "}" (substring x -1))
14529 tags-in-group))
14530 regexp-in-group
14531 (mapcar (lambda (x)
14532 (substring x 1 -1))
14533 regexp-in-group-escaped)
14534 tags-in-group
14535 (delq nil (mapcar (lambda (x)
14536 (if (stringp x)
14537 (and (not (equal "{" (substring x 0 1)))
14538 (not (equal "}" (substring x -1)))
14541 tags-in-group)))
14542 ;; If single-as-list, do no more in the while-loop.
14543 (if (not single-as-list)
14544 (progn
14545 (when regexp-in-group
14546 (setq regexp-in-group
14547 (concat "\\|"
14548 (mapconcat 'identity regexp-in-group
14549 "\\|"))))
14550 (setq tags-in-group
14551 (concat dir
14552 "{\\<"
14553 (regexp-opt tags-in-group)
14554 "\\>"
14555 regexp-in-group
14556 "}"))
14557 (when (stringp tags-in-group)
14558 (org-add-props tags-in-group '(grouptag t)))
14559 (setq return-match
14560 (replace-match tags-in-group t t return-match)))
14561 (setq tags-in-group
14562 (append regexp-in-group-escaped tags-in-group))))
14563 (setq taggroups-keys (delete tag taggroups-keys))))
14564 ;; Add the regular expressions back into the match-expression again.
14565 (while regexps-in-match
14566 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14567 (pop regexps-in-match)
14568 return-match t t))
14569 (cl-decf count))
14570 (if single-as-list
14571 (if tags-in-group tags-in-group (list return-match))
14572 return-match))
14573 (if single-as-list
14574 (list (if downcased (downcase match) match))
14575 match)))
14577 (defun org-op-to-function (op &optional stringp)
14578 "Turn an operator into the appropriate function."
14579 (setq op
14580 (cond
14581 ((equal op "<" ) '(< string< org-time<))
14582 ((equal op ">" ) '(> org-string> org-time>))
14583 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14584 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14585 ((member op '("=" "==")) '(= string= org-time=))
14586 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14587 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14589 (defun org<> (a b) (not (= a b)))
14590 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14591 (defun org-string>= (a b) (not (string< a b)))
14592 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14593 (defun org-string<> (a b) (not (string= a b)))
14594 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14595 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14596 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14597 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14598 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14599 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14600 (defun org-2ft (s)
14601 "Convert S to a floating point time.
14602 If S is already a number, just return it. If it is a string, parse
14603 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14604 (cond
14605 ((numberp s) s)
14606 ((stringp s)
14607 (condition-case nil
14608 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14609 (error 0.)))
14610 (t 0.)))
14612 (defun org-time-today ()
14613 "Time in seconds today at 0:00.
14614 Returns the float number of seconds since the beginning of the
14615 epoch to the beginning of today (00:00)."
14616 (float-time (apply 'encode-time
14617 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14619 (defun org-matcher-time (s)
14620 "Interpret a time comparison value."
14621 (save-match-data
14622 (cond
14623 ((string= s "<now>") (float-time))
14624 ((string= s "<today>") (org-time-today))
14625 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14626 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14627 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14628 (+ (org-time-today)
14629 (* (string-to-number (match-string 1 s))
14630 (cdr (assoc (match-string 2 s)
14631 '(("d" . 86400.0) ("w" . 604800.0)
14632 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14633 (t (org-2ft s)))))
14635 (defun org-match-any-p (re list)
14636 "Does re match any element of list?"
14637 (setq list (mapcar (lambda (x) (string-match re x)) list))
14638 (delq nil list))
14640 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14641 (defvar org-tags-overlay (make-overlay 1 1))
14642 (delete-overlay org-tags-overlay)
14644 (defun org-get-local-tags-at (&optional pos)
14645 "Get a list of tags defined in the current headline."
14646 (org-get-tags-at pos 'local))
14648 (defun org-get-local-tags ()
14649 "Get a list of tags defined in the current headline."
14650 (org-get-tags-at nil 'local))
14652 (defun org-get-tags-at (&optional pos local)
14653 "Get a list of all headline tags applicable at POS.
14654 POS defaults to point. If tags are inherited, the list contains
14655 the targets in the same sequence as the headlines appear, i.e.
14656 the tags of the current headline come last.
14657 When LOCAL is non-nil, only return tags from the current headline,
14658 ignore inherited ones."
14659 (interactive)
14660 (if (and org-trust-scanner-tags
14661 (or (not pos) (equal pos (point)))
14662 (not local))
14663 org-scanner-tags
14664 (let (tags ltags lastpos parent)
14665 (save-excursion
14666 (save-restriction
14667 (widen)
14668 (goto-char (or pos (point)))
14669 (save-match-data
14670 (catch 'done
14671 (condition-case nil
14672 (progn
14673 (org-back-to-heading t)
14674 (while (not (equal lastpos (point)))
14675 (setq lastpos (point))
14676 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14677 (setq ltags (org-split-string
14678 (match-string-no-properties 1) ":"))
14679 (when parent
14680 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14681 (setq tags (append
14682 (if parent
14683 (org-remove-uninherited-tags ltags)
14684 ltags)
14685 tags)))
14686 (or org-use-tag-inheritance (throw 'done t))
14687 (when local (throw 'done t))
14688 (or (org-up-heading-safe) (error nil))
14689 (setq parent t)))
14690 (error nil)))))
14691 (if local
14692 tags
14693 (reverse (delete-dups
14694 (reverse (append
14695 (org-remove-uninherited-tags
14696 org-file-tags)
14697 tags)))))))))
14699 (defun org-add-prop-inherited (s)
14700 (add-text-properties 0 (length s) '(inherited t) s)
14703 (defun org-toggle-tag (tag &optional onoff)
14704 "Toggle the tag TAG for the current line.
14705 If ONOFF is `on' or `off', don't toggle but set to this state."
14706 (save-excursion
14707 (org-back-to-heading t)
14708 (let ((current
14709 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14710 (line-end-position) t)
14711 (let ((tags (match-string 1)))
14712 ;; Clear current tags.
14713 (replace-match "")
14714 ;; Reverse the tags list so any new tag is appended to
14715 ;; the current list of tags.
14716 (nreverse (org-split-string tags ":")))))
14717 res)
14718 (pcase onoff
14719 (`off (setq current (delete tag current)))
14720 ((or `on (guard (not (member tag current))))
14721 (setq res t)
14722 (cl-pushnew tag current :test #'equal))
14723 (_ (setq current (delete tag current))))
14724 (end-of-line)
14725 (if current
14726 (progn
14727 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14728 (org-set-tags nil t))
14729 (delete-horizontal-space))
14730 (run-hooks 'org-after-tags-change-hook)
14731 res)))
14733 (defun org--align-tags-here (to-col)
14734 "Align tags on the current headline to TO-COL.
14735 Assume point is on a headline."
14736 (let ((pos (point)))
14737 (beginning-of-line)
14738 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14739 (>= pos (match-beginning 2)))
14740 ;; No tags or point within tags: do not align.
14741 (goto-char pos)
14742 (goto-char (match-beginning 1))
14743 (let ((shift (max (- (if (>= to-col 0) to-col
14744 (- (abs to-col) (string-width (match-string 2))))
14745 (current-column))
14746 1)))
14747 (replace-match (make-string shift ?\s) nil nil nil 1)
14748 ;; Preserve initial position, if possible. In any case, stop
14749 ;; before tags.
14750 (when (< pos (point)) (goto-char pos))))))
14752 (defun org-set-tags-command (&optional arg just-align)
14753 "Call the set-tags command for the current entry."
14754 (interactive "P")
14755 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14756 (org-set-tags arg just-align)
14757 (save-excursion
14758 (unless (and (org-region-active-p)
14759 org-loop-over-headlines-in-active-region)
14760 (org-back-to-heading t))
14761 (org-set-tags arg just-align))))
14763 (defun org-set-tags-to (data)
14764 "Set the tags of the current entry to DATA, replacing the current tags.
14765 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14766 If DATA is nil or the empty string, any tags will be removed."
14767 (interactive "sTags: ")
14768 (setq data
14769 (cond
14770 ((eq data nil) "")
14771 ((equal data "") "")
14772 ((stringp data)
14773 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14774 ":"))
14775 ((listp data)
14776 (concat ":" (mapconcat 'identity data ":") ":"))))
14777 (when data
14778 (save-excursion
14779 (org-back-to-heading t)
14780 (when (let ((case-fold-search nil))
14781 (looking-at org-complex-heading-regexp))
14782 (if (match-end 5)
14783 (progn
14784 (goto-char (match-beginning 5))
14785 (insert data)
14786 (delete-region (point) (point-at-eol))
14787 (org-set-tags nil 'align))
14788 (goto-char (point-at-eol))
14789 (insert " " data)
14790 (org-set-tags nil 'align)))
14791 (beginning-of-line 1)
14792 (when (looking-at ".*?\\([ \t]+\\)$")
14793 (delete-region (match-beginning 1) (match-end 1))))))
14795 (defun org-align-all-tags ()
14796 "Align the tags in all headings."
14797 (interactive)
14798 (save-excursion
14799 (or (ignore-errors (org-back-to-heading t))
14800 (outline-next-heading))
14801 (if (org-at-heading-p)
14802 (org-set-tags t)
14803 (message "No headings"))))
14805 (defvar org-indent-indentation-per-level)
14806 (defun org-set-tags (&optional arg just-align)
14807 "Set the tags for the current headline.
14808 With prefix ARG, realign all tags in headings in the current buffer.
14809 When JUST-ALIGN is non-nil, only align tags."
14810 (interactive "P")
14811 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14812 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14813 'region-start-level
14814 'region))
14815 org-loop-over-headlines-in-active-region)
14816 (org-map-entries
14817 ;; We don't use ARG and JUST-ALIGN here because these args
14818 ;; are not useful when looping over headlines.
14819 #'org-set-tags
14820 org-loop-over-headlines-in-active-region
14822 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14823 (let ((org-setting-tags t))
14824 (if arg
14825 (save-excursion
14826 (goto-char (point-min))
14827 (while (re-search-forward org-outline-regexp-bol nil t)
14828 (org-set-tags nil t)
14829 (end-of-line))
14830 (message "All tags realigned to column %d" org-tags-column))
14831 (let* ((current (org-get-tags-string))
14832 (tags
14833 (if just-align current
14834 ;; Get a new set of tags from the user.
14835 (save-excursion
14836 (let* ((seen)
14837 (table
14838 (setq
14839 org-last-tags-completion-table
14840 ;; Uniquify tags in alists, yet preserve
14841 ;; structure (i.e., keywords).
14842 (delq nil
14843 (mapcar
14844 (lambda (pair)
14845 (let ((head (car pair)))
14846 (cond ((symbolp head) pair)
14847 ((member head seen) nil)
14848 (t (push head seen)
14849 pair))))
14850 (append
14851 (or org-current-tag-alist
14852 (org-get-buffer-tags))
14853 (and
14854 org-complete-tags-always-offer-all-agenda-tags
14855 (org-global-tags-completion-table
14856 (org-agenda-files))))))))
14857 (current-tags (org-split-string current ":"))
14858 (inherited-tags
14859 (nreverse (nthcdr (length current-tags)
14860 (nreverse (org-get-tags-at))))))
14861 (replace-regexp-in-string
14862 "\\([-+&]+\\|,\\)"
14864 (if (or (eq t org-use-fast-tag-selection)
14865 (and org-use-fast-tag-selection
14866 (delq nil (mapcar #'cdr table))))
14867 (org-fast-tag-selection
14868 current-tags inherited-tags table
14869 (and org-fast-tag-selection-include-todo
14870 org-todo-key-alist))
14871 (let ((org-add-colon-after-tag-completion
14872 (< 1 (length table))))
14873 (org-trim
14874 (completing-read
14875 "Tags: "
14876 #'org-tags-completion-function
14877 nil nil current 'org-tags-history))))))))))
14879 (when org-tags-sort-function
14880 (setq tags
14881 (mapconcat
14882 #'identity
14883 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14884 org-tags-sort-function)
14885 ":")))
14887 (if (or (string= ":" tags)
14888 (string= "::" tags))
14889 (setq tags ""))
14890 (if (not (org-string-nw-p tags)) (setq tags "")
14891 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14892 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14894 ;; Insert new tags at the correct column.
14895 (unless (equal current tags)
14896 (save-excursion
14897 (beginning-of-line)
14898 (let ((case-fold-search nil))
14899 (looking-at org-complex-heading-regexp))
14900 ;; Remove current tags, if any.
14901 (when (match-end 5) (replace-match "" nil nil nil 5))
14902 ;; Insert new tags, if any. Otherwise, remove trailing
14903 ;; white spaces.
14904 (end-of-line)
14905 (if (not (equal tags ""))
14906 ;; When text is being inserted on an invisible
14907 ;; region boundary, it can be inadvertently sucked
14908 ;; into invisibility.
14909 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14910 (skip-chars-backward " \t")
14911 (delete-region (point) (line-end-position)))))
14912 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14913 ;; is on.
14914 (unless (equal tags "")
14915 (let* ((level (save-excursion
14916 (beginning-of-line)
14917 (skip-chars-forward "\\*")))
14918 (offset (if (bound-and-true-p org-indent-mode)
14919 (* (1- org-indent-indentation-per-level)
14920 (1- level))
14922 (tags-column
14923 (+ org-tags-column
14924 (if (> org-tags-column 0) (- offset) offset))))
14925 (org--align-tags-here tags-column))))
14926 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14928 (defun org-change-tag-in-region (beg end tag off)
14929 "Add or remove TAG for each entry in the region.
14930 This works in the agenda, and also in an Org buffer."
14931 (interactive
14932 (list (region-beginning) (region-end)
14933 (let ((org-last-tags-completion-table
14934 (if (derived-mode-p 'org-mode)
14935 (org-uniquify
14936 (delq nil (append (org-get-buffer-tags)
14937 (org-global-tags-completion-table))))
14938 (org-global-tags-completion-table))))
14939 (completing-read
14940 "Tag: " 'org-tags-completion-function nil nil nil
14941 'org-tags-history))
14942 (progn
14943 (message "[s]et or [r]emove? ")
14944 (equal (read-char-exclusive) ?r))))
14945 (when (fboundp 'deactivate-mark) (deactivate-mark))
14946 (let ((agendap (equal major-mode 'org-agenda-mode))
14947 l1 l2 m buf pos newhead (cnt 0))
14948 (goto-char end)
14949 (setq l2 (1- (org-current-line)))
14950 (goto-char beg)
14951 (setq l1 (org-current-line))
14952 (cl-loop for l from l1 to l2 do
14953 (org-goto-line l)
14954 (setq m (get-text-property (point) 'org-hd-marker))
14955 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14956 (and agendap m))
14957 (setq buf (if agendap (marker-buffer m) (current-buffer))
14958 pos (if agendap m (point)))
14959 (with-current-buffer buf
14960 (save-excursion
14961 (save-restriction
14962 (goto-char pos)
14963 (setq cnt (1+ cnt))
14964 (org-toggle-tag tag (if off 'off 'on))
14965 (setq newhead (org-get-heading)))))
14966 (and agendap (org-agenda-change-all-lines newhead m))))
14967 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14969 (defun org-tags-completion-function (string _predicate &optional flag)
14970 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14971 (confirm (lambda (x) (stringp (car x)))))
14972 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14973 (setq s1 (match-string 1 string)
14974 s2 (match-string 2 string))
14975 (setq s1 "" s2 string))
14976 (cond
14977 ((eq flag nil)
14978 ;; try completion
14979 (setq rtn (try-completion s2 ctable confirm))
14980 (when (stringp rtn)
14981 (setq rtn
14982 (concat s1 s2 (substring rtn (length s2))
14983 (if (and org-add-colon-after-tag-completion
14984 (assoc rtn ctable))
14985 ":" ""))))
14986 rtn)
14987 ((eq flag t)
14988 ;; all-completions
14989 (all-completions s2 ctable confirm))
14990 ((eq flag 'lambda)
14991 ;; exact match?
14992 (assoc s2 ctable)))))
14994 (defun org-fast-tag-insert (kwd tags face &optional end)
14995 "Insert KDW, and the TAGS, the latter with face FACE.
14996 Also insert END."
14997 (insert (format "%-12s" (concat kwd ":"))
14998 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14999 (or end "")))
15001 (defun org-fast-tag-show-exit (flag)
15002 (save-excursion
15003 (org-goto-line 3)
15004 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15005 (replace-match ""))
15006 (when flag
15007 (end-of-line 1)
15008 (org-move-to-column (- (window-width) 19) t)
15009 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15011 (defun org-set-current-tags-overlay (current prefix)
15012 "Add an overlay to CURRENT tag with PREFIX."
15013 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15014 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15015 (org-overlay-display org-tags-overlay (concat prefix s))))
15017 (defvar org-last-tag-selection-key nil)
15018 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15019 "Fast tag selection with single keys.
15020 CURRENT is the current list of tags in the headline, INHERITED is the
15021 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15022 possibly with grouping information. TODO-TABLE is a similar table with
15023 TODO keywords, should these have keys assigned to them.
15024 If the keys are nil, a-z are automatically assigned.
15025 Returns the new tags string, or nil to not change the current settings."
15026 (let* ((fulltable (append table todo-table))
15027 (maxlen (apply 'max (mapcar
15028 (lambda (x)
15029 (if (stringp (car x)) (string-width (car x)) 0))
15030 fulltable)))
15031 (buf (current-buffer))
15032 (expert (eq org-fast-tag-selection-single-key 'expert))
15033 (buffer-tags nil)
15034 (fwidth (+ maxlen 3 1 3))
15035 (ncol (/ (- (window-width) 4) fwidth))
15036 (i-face 'org-done)
15037 (c-face 'org-todo)
15038 tg cnt e c char c1 c2 ntable tbl rtn
15039 ov-start ov-end ov-prefix
15040 (exit-after-next org-fast-tag-selection-single-key)
15041 (done-keywords org-done-keywords)
15042 groups ingroup intaggroup)
15043 (save-excursion
15044 (beginning-of-line 1)
15045 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15046 (setq ov-start (match-beginning 1)
15047 ov-end (match-end 1)
15048 ov-prefix "")
15049 (setq ov-start (1- (point-at-eol))
15050 ov-end (1+ ov-start))
15051 (skip-chars-forward "^\n\r")
15052 (setq ov-prefix
15053 (concat
15054 (buffer-substring (1- (point)) (point))
15055 (if (> (current-column) org-tags-column)
15057 (make-string (- org-tags-column (current-column)) ?\ ))))))
15058 (move-overlay org-tags-overlay ov-start ov-end)
15059 (save-window-excursion
15060 (if expert
15061 (set-buffer (get-buffer-create " *Org tags*"))
15062 (delete-other-windows)
15063 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15064 (org-switch-to-buffer-other-window " *Org tags*"))
15065 (erase-buffer)
15066 (setq-local org-done-keywords done-keywords)
15067 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15068 (org-fast-tag-insert "Current" current c-face "\n\n")
15069 (org-fast-tag-show-exit exit-after-next)
15070 (org-set-current-tags-overlay current ov-prefix)
15071 (setq tbl fulltable char ?a cnt 0)
15072 (while (setq e (pop tbl))
15073 (cond
15074 ((eq (car e) :startgroup)
15075 (push '() groups) (setq ingroup t)
15076 (unless (zerop cnt)
15077 (setq cnt 0)
15078 (insert "\n"))
15079 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15080 ((eq (car e) :endgroup)
15081 (setq ingroup nil cnt 0)
15082 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15083 ((eq (car e) :startgrouptag)
15084 (setq intaggroup t)
15085 (unless (zerop cnt)
15086 (setq cnt 0)
15087 (insert "\n"))
15088 (insert "[ "))
15089 ((eq (car e) :endgrouptag)
15090 (setq intaggroup nil cnt 0)
15091 (insert "]\n"))
15092 ((equal e '(:newline))
15093 (unless (zerop cnt)
15094 (setq cnt 0)
15095 (insert "\n")
15096 (setq e (car tbl))
15097 (while (equal (car tbl) '(:newline))
15098 (insert "\n")
15099 (setq tbl (cdr tbl)))))
15100 ((equal e '(:grouptags)) (insert " : "))
15102 (setq tg (copy-sequence (car e)) c2 nil)
15103 (if (cdr e)
15104 (setq c (cdr e))
15105 ;; automatically assign a character.
15106 (setq c1 (string-to-char
15107 (downcase (substring
15108 tg (if (= (string-to-char tg) ?@) 1 0)))))
15109 (if (or (rassoc c1 ntable) (rassoc c1 table))
15110 (while (or (rassoc char ntable) (rassoc char table))
15111 (setq char (1+ char)))
15112 (setq c2 c1))
15113 (setq c (or c2 char)))
15114 (when ingroup (push tg (car groups)))
15115 (setq tg (org-add-props tg nil 'face
15116 (cond
15117 ((not (assoc tg table))
15118 (org-get-todo-face tg))
15119 ((member tg current) c-face)
15120 ((member tg inherited) i-face))))
15121 (when (equal (caar tbl) :grouptags)
15122 (org-add-props tg nil 'face 'org-tag-group))
15123 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15124 (insert "[" c "] " tg (make-string
15125 (- fwidth 4 (length tg)) ?\ ))
15126 (push (cons tg c) ntable)
15127 (when (= (cl-incf cnt) ncol)
15128 (insert "\n")
15129 (when (or ingroup intaggroup) (insert " "))
15130 (setq cnt 0)))))
15131 (setq ntable (nreverse ntable))
15132 (insert "\n")
15133 (goto-char (point-min))
15134 (unless expert (org-fit-window-to-buffer))
15135 (setq rtn
15136 (catch 'exit
15137 (while t
15138 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15139 (if (not groups) "no " "")
15140 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15141 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15142 (setq org-last-tag-selection-key c)
15143 (cond
15144 ((= c ?\r) (throw 'exit t))
15145 ((= c ?!)
15146 (setq groups (not groups))
15147 (goto-char (point-min))
15148 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15149 ((= c ?\C-c)
15150 (if (not expert)
15151 (org-fast-tag-show-exit
15152 (setq exit-after-next (not exit-after-next)))
15153 (setq expert nil)
15154 (delete-other-windows)
15155 (set-window-buffer (split-window-vertically) " *Org tags*")
15156 (org-switch-to-buffer-other-window " *Org tags*")
15157 (org-fit-window-to-buffer)))
15158 ((or (= c ?\C-g)
15159 (and (= c ?q) (not (rassoc c ntable))))
15160 (delete-overlay org-tags-overlay)
15161 (setq quit-flag t))
15162 ((= c ?\ )
15163 (setq current nil)
15164 (when exit-after-next (setq exit-after-next 'now)))
15165 ((= c ?\t)
15166 (condition-case nil
15167 (setq tg (completing-read
15168 "Tag: "
15169 (or buffer-tags
15170 (with-current-buffer buf
15171 (setq buffer-tags
15172 (org-get-buffer-tags))))))
15173 (quit (setq tg "")))
15174 (when (string-match "\\S-" tg)
15175 (cl-pushnew (list tg) buffer-tags :test #'equal)
15176 (if (member tg current)
15177 (setq current (delete tg current))
15178 (push tg current)))
15179 (when exit-after-next (setq exit-after-next 'now)))
15180 ((setq e (rassoc c todo-table) tg (car e))
15181 (with-current-buffer buf
15182 (save-excursion (org-todo tg)))
15183 (when exit-after-next (setq exit-after-next 'now)))
15184 ((setq e (rassoc c ntable) tg (car e))
15185 (if (member tg current)
15186 (setq current (delete tg current))
15187 (cl-loop for g in groups do
15188 (when (member tg g)
15189 (dolist (x g) (setq current (delete x current)))))
15190 (push tg current))
15191 (when exit-after-next (setq exit-after-next 'now))))
15193 ;; Create a sorted list
15194 (setq current
15195 (sort current
15196 (lambda (a b)
15197 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15198 (when (eq exit-after-next 'now) (throw 'exit t))
15199 (goto-char (point-min))
15200 (beginning-of-line 2)
15201 (delete-region (point) (point-at-eol))
15202 (org-fast-tag-insert "Current" current c-face)
15203 (org-set-current-tags-overlay current ov-prefix)
15204 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15205 (setq tg (match-string 1))
15206 (add-text-properties
15207 (match-beginning 1) (match-end 1)
15208 (list 'face
15209 (cond
15210 ((member tg current) c-face)
15211 ((member tg inherited) i-face)
15212 (t (get-text-property (match-beginning 1) 'face))))))
15213 (goto-char (point-min)))))
15214 (delete-overlay org-tags-overlay)
15215 (if rtn
15216 (mapconcat 'identity current ":")
15217 nil))))
15219 (defun org-get-tags-string ()
15220 "Get the TAGS string in the current headline."
15221 (unless (org-at-heading-p t)
15222 (user-error "Not on a heading"))
15223 (save-excursion
15224 (beginning-of-line 1)
15225 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15226 (match-string-no-properties 1)
15227 "")))
15229 (defun org-get-tags ()
15230 "Get the list of tags specified in the current headline."
15231 (org-split-string (org-get-tags-string) ":"))
15233 (defun org-get-buffer-tags ()
15234 "Get a table of all tags used in the buffer, for completion."
15235 (org-with-wide-buffer
15236 (goto-char (point-min))
15237 (let ((tag-re (concat org-outline-regexp-bol
15238 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15239 tags)
15240 (while (re-search-forward tag-re nil t)
15241 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15242 (push tag tags)))
15243 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15245 ;;;; The mapping API
15247 (defvar org-agenda-skip-comment-trees)
15248 (defvar org-agenda-skip-function)
15249 (defun org-map-entries (func &optional match scope &rest skip)
15250 "Call FUNC at each headline selected by MATCH in SCOPE.
15252 FUNC is a function or a lisp form. The function will be called without
15253 arguments, with the cursor positioned at the beginning of the headline.
15254 The return values of all calls to the function will be collected and
15255 returned as a list.
15257 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15258 does not need to preserve point. After evaluation, the cursor will be
15259 moved to the end of the line (presumably of the headline of the
15260 processed entry) and search continues from there. Under some
15261 circumstances, this may not produce the wanted results. For example,
15262 if you have removed (e.g. archived) the current (sub)tree it could
15263 mean that the next entry will be skipped entirely. In such cases, you
15264 can specify the position from where search should continue by making
15265 FUNC set the variable `org-map-continue-from' to the desired buffer
15266 position.
15268 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15269 Only headlines that are matched by this query will be considered during
15270 the iteration. When MATCH is nil or t, all headlines will be
15271 visited by the iteration.
15273 SCOPE determines the scope of this command. It can be any of:
15275 nil The current buffer, respecting the restriction if any
15276 tree The subtree started with the entry at point
15277 region The entries within the active region, if any
15278 region-start-level
15279 The entries within the active region, but only those at
15280 the same level than the first one.
15281 file The current buffer, without restriction
15282 file-with-archives
15283 The current buffer, and any archives associated with it
15284 agenda All agenda files
15285 agenda-with-archives
15286 All agenda files with any archive files associated with them
15287 \(file1 file2 ...)
15288 If this is a list, all files in the list will be scanned
15290 The remaining args are treated as settings for the skipping facilities of
15291 the scanner. The following items can be given here:
15293 archive skip trees with the archive tag
15294 comment skip trees with the COMMENT keyword
15295 function or Emacs Lisp form:
15296 will be used as value for `org-agenda-skip-function', so
15297 whenever the function returns a position, FUNC will not be
15298 called for that entry and search will continue from the
15299 position returned
15301 If your function needs to retrieve the tags including inherited tags
15302 at the *current* entry, you can use the value of the variable
15303 `org-scanner-tags' which will be much faster than getting the value
15304 with `org-get-tags-at'. If your function gets properties with
15305 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15306 to t around the call to `org-entry-properties' to get the same speedup.
15307 Note that if your function moves around to retrieve tags and properties at
15308 a *different* entry, you cannot use these techniques."
15309 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15310 (not (org-region-active-p)))
15311 (let* ((org-agenda-archives-mode nil) ; just to make sure
15312 (org-agenda-skip-archived-trees (memq 'archive skip))
15313 (org-agenda-skip-comment-trees (memq 'comment skip))
15314 (org-agenda-skip-function
15315 (car (org-delete-all '(comment archive) skip)))
15316 (org-tags-match-list-sublevels t)
15317 (start-level (eq scope 'region-start-level))
15318 matcher res
15319 org-todo-keywords-for-agenda
15320 org-done-keywords-for-agenda
15321 org-todo-keyword-alist-for-agenda
15322 org-tag-alist-for-agenda
15323 org--matcher-tags-todo-only)
15325 (cond
15326 ((eq match t) (setq matcher t))
15327 ((eq match nil) (setq matcher t))
15328 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15330 (save-excursion
15331 (save-restriction
15332 (cond ((eq scope 'tree)
15333 (org-back-to-heading t)
15334 (org-narrow-to-subtree)
15335 (setq scope nil))
15336 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15337 (org-region-active-p))
15338 ;; If needed, set start-level to a string like "2"
15339 (when start-level
15340 (save-excursion
15341 (goto-char (region-beginning))
15342 (unless (org-at-heading-p) (outline-next-heading))
15343 (setq start-level (org-current-level))))
15344 (narrow-to-region (region-beginning)
15345 (save-excursion
15346 (goto-char (region-end))
15347 (unless (and (bolp) (org-at-heading-p))
15348 (outline-next-heading))
15349 (point)))
15350 (setq scope nil)))
15352 (if (not scope)
15353 (progn
15354 (org-agenda-prepare-buffers
15355 (and buffer-file-name (list buffer-file-name)))
15356 (setq res
15357 (org-scan-tags
15358 func matcher org--matcher-tags-todo-only start-level)))
15359 ;; Get the right scope
15360 (cond
15361 ((and scope (listp scope) (symbolp (car scope)))
15362 (setq scope (eval scope)))
15363 ((eq scope 'agenda)
15364 (setq scope (org-agenda-files t)))
15365 ((eq scope 'agenda-with-archives)
15366 (setq scope (org-agenda-files t))
15367 (setq scope (org-add-archive-files scope)))
15368 ((eq scope 'file)
15369 (setq scope (and buffer-file-name (list buffer-file-name))))
15370 ((eq scope 'file-with-archives)
15371 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15372 (org-agenda-prepare-buffers scope)
15373 (dolist (file scope)
15374 (with-current-buffer (org-find-base-buffer-visiting file)
15375 (org-with-wide-buffer
15376 (goto-char (point-min))
15377 (setq res
15378 (append
15380 (org-scan-tags
15381 func matcher org--matcher-tags-todo-only)))))))))
15382 res)))
15384 ;;; Properties API
15386 (defconst org-special-properties
15387 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15388 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15389 "The special properties valid in Org mode.
15390 These are properties that are not defined in the property drawer,
15391 but in some other way.")
15393 (defconst org-default-properties
15394 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15395 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15396 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15397 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15398 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15399 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15400 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15401 "Some properties that are used by Org mode for various purposes.
15402 Being in this list makes sure that they are offered for completion.")
15404 (defun org--valid-property-p (property)
15405 "Non nil when string PROPERTY is a valid property name."
15406 (not
15407 (or (equal property "")
15408 (string-match-p "\\s-" property))))
15410 (defun org--update-property-plist (key val props)
15411 "Associate KEY to VAL in alist PROPS.
15412 Modifications are made by side-effect. Return new alist."
15413 (let* ((appending (string= (substring key -1) "+"))
15414 (key (if appending (substring key 0 -1) key))
15415 (old (assoc-string key props t)))
15416 (if (not old) (cons (cons key val) props)
15417 (setcdr old (if appending (concat (cdr old) " " val) val))
15418 props)))
15420 (defun org-get-property-block (&optional beg force)
15421 "Return the (beg . end) range of the body of the property drawer.
15422 BEG is the beginning of the current subtree, or of the part
15423 before the first headline. If it is not given, it will be found.
15424 If the drawer does not exist, create it if FORCE is non-nil, or
15425 return nil."
15426 (org-with-wide-buffer
15427 (when beg (goto-char beg))
15428 (unless (org-before-first-heading-p)
15429 (let ((beg (cond (beg)
15430 ((or (not (featurep 'org-inlinetask))
15431 (org-inlinetask-in-task-p))
15432 (org-back-to-heading t))
15433 (t (org-with-limited-levels (org-back-to-heading t))))))
15434 (forward-line)
15435 (when (looking-at-p org-planning-line-re) (forward-line))
15436 (cond ((looking-at org-property-drawer-re)
15437 (forward-line)
15438 (cons (point) (progn (goto-char (match-end 0))
15439 (line-beginning-position))))
15440 (force
15441 (goto-char beg)
15442 (org-insert-property-drawer)
15443 (let ((pos (save-excursion (search-forward ":END:")
15444 (line-beginning-position))))
15445 (cons pos pos))))))))
15447 (defun org-at-property-p ()
15448 "Non-nil when point is inside a property drawer.
15449 See `org-property-re' for match data, if applicable."
15450 (save-excursion
15451 (beginning-of-line)
15452 (and (looking-at org-property-re)
15453 (let ((property-drawer (save-match-data (org-get-property-block))))
15454 (and property-drawer
15455 (>= (point) (car property-drawer))
15456 (< (point) (cdr property-drawer)))))))
15458 (defun org-property-action ()
15459 "Do an action on properties."
15460 (interactive)
15461 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15462 (let ((c (read-char-exclusive)))
15463 (cl-case c
15464 (?s (call-interactively #'org-set-property))
15465 (?d (call-interactively #'org-delete-property))
15466 (?D (call-interactively #'org-delete-property-globally))
15467 (?c (call-interactively #'org-compute-property-at-point))
15468 (otherwise (user-error "No such property action %c" c)))))
15470 (defun org-inc-effort ()
15471 "Increment the value of the effort property in the current entry."
15472 (interactive)
15473 (org-set-effort nil t))
15475 (defvar org-clock-effort) ; Defined in org-clock.el.
15476 (defvar org-clock-current-task) ; Defined in org-clock.el.
15477 (defun org-set-effort (&optional value increment)
15478 "Set the effort property of the current entry.
15479 With numerical prefix arg, use the nth allowed value, 0 stands for the
15480 10th allowed value.
15482 When INCREMENT is non-nil, set the property to the next allowed value."
15483 (interactive "P")
15484 (when (equal value 0) (setq value 10))
15485 (let* ((completion-ignore-case t)
15486 (prop org-effort-property)
15487 (cur (org-entry-get nil prop))
15488 (allowed (org-property-get-allowed-values nil prop 'table))
15489 (existing (mapcar 'list (org-property-values prop)))
15490 (heading (nth 4 (org-heading-components)))
15492 (val (cond
15493 ((stringp value) value)
15494 ((and allowed (integerp value))
15495 (or (car (nth (1- value) allowed))
15496 (car (org-last allowed))))
15497 ((and allowed increment)
15498 (or (cl-caadr (member (list cur) allowed))
15499 (user-error "Allowed effort values are not set")))
15500 (allowed
15501 (message "Select 1-9,0, [RET%s]: %s"
15502 (if cur (concat "=" cur) "")
15503 (mapconcat 'car allowed " "))
15504 (setq rpl (read-char-exclusive))
15505 (if (equal rpl ?\r)
15507 (setq rpl (- rpl ?0))
15508 (when (equal rpl 0) (setq rpl 10))
15509 (if (and (> rpl 0) (<= rpl (length allowed)))
15510 (car (nth (1- rpl) allowed))
15511 (org-completing-read "Effort: " allowed nil))))
15513 (org-completing-read
15514 (concat "Effort" (and cur (string-match "\\S-" cur)
15515 (concat " [" cur "]"))
15516 ": ")
15517 existing nil nil "" nil cur)))))
15518 (unless (equal (org-entry-get nil prop) val)
15519 (org-entry-put nil prop val))
15520 (org-refresh-property
15521 '((effort . identity)
15522 (effort-minutes . org-duration-to-minutes))
15523 val)
15524 (when (equal heading (bound-and-true-p org-clock-current-task))
15525 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15526 (org-clock-update-mode-line))
15527 (message "%s is now %s" prop val)))
15529 (defun org-entry-properties (&optional pom which)
15530 "Get all properties of the current entry.
15532 When POM is a buffer position, get all properties from the entry
15533 there instead.
15535 This includes the TODO keyword, the tags, time strings for
15536 deadline, scheduled, and clocking, and any additional properties
15537 defined in the entry.
15539 If WHICH is nil or `all', get all properties. If WHICH is
15540 `special' or `standard', only get that subclass. If WHICH is
15541 a string, only get that property.
15543 Return value is an alist. Keys are properties, as upcased
15544 strings."
15545 (org-with-point-at pom
15546 (when (and (derived-mode-p 'org-mode)
15547 (ignore-errors (org-back-to-heading t)))
15548 (catch 'exit
15549 (let* ((beg (point))
15550 (specific (and (stringp which) (upcase which)))
15551 (which (cond ((not specific) which)
15552 ((member specific org-special-properties) 'special)
15553 (t 'standard)))
15554 props)
15555 ;; Get the special properties, like TODO and TAGS.
15556 (when (memq which '(nil all special))
15557 (when (or (not specific) (string= specific "CLOCKSUM"))
15558 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15559 (when clocksum
15560 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15561 props)))
15562 (when specific (throw 'exit props)))
15563 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15564 (let ((clocksumt (get-text-property (point)
15565 :org-clock-minutes-today)))
15566 (when clocksumt
15567 (push (cons "CLOCKSUM_T"
15568 (org-duration-from-minutes clocksumt))
15569 props)))
15570 (when specific (throw 'exit props)))
15571 (when (or (not specific) (string= specific "ITEM"))
15572 (let ((case-fold-search nil))
15573 (when (looking-at org-complex-heading-regexp)
15574 (push (cons "ITEM"
15575 (let ((title (match-string-no-properties 4)))
15576 (if (org-string-nw-p title)
15577 (org-remove-tabs title)
15578 "")))
15579 props)))
15580 (when specific (throw 'exit props)))
15581 (when (or (not specific) (string= specific "TODO"))
15582 (let ((case-fold-search nil))
15583 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15584 (push (cons "TODO" (match-string-no-properties 2)) props)))
15585 (when specific (throw 'exit props)))
15586 (when (or (not specific) (string= specific "PRIORITY"))
15587 (push (cons "PRIORITY"
15588 (if (looking-at org-priority-regexp)
15589 (match-string-no-properties 2)
15590 (char-to-string org-default-priority)))
15591 props)
15592 (when specific (throw 'exit props)))
15593 (when (or (not specific) (string= specific "FILE"))
15594 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15595 props)
15596 (when specific (throw 'exit props)))
15597 (when (or (not specific) (string= specific "TAGS"))
15598 (let ((value (org-string-nw-p (org-get-tags-string))))
15599 (when value (push (cons "TAGS" value) props)))
15600 (when specific (throw 'exit props)))
15601 (when (or (not specific) (string= specific "ALLTAGS"))
15602 (let ((value (org-get-tags-at)))
15603 (when value
15604 (push (cons "ALLTAGS"
15605 (format ":%s:" (mapconcat #'identity value ":")))
15606 props)))
15607 (when specific (throw 'exit props)))
15608 (when (or (not specific) (string= specific "BLOCKED"))
15609 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15610 (when specific (throw 'exit props)))
15611 (when (or (not specific)
15612 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15613 (forward-line)
15614 (when (looking-at-p org-planning-line-re)
15615 (end-of-line)
15616 (let ((bol (line-beginning-position))
15617 ;; Backward compatibility: time keywords used to
15618 ;; be configurable (before 8.3). Make sure we
15619 ;; get the correct keyword.
15620 (key-assoc `(("CLOSED" . ,org-closed-string)
15621 ("DEADLINE" . ,org-deadline-string)
15622 ("SCHEDULED" . ,org-scheduled-string))))
15623 (dolist (pair (if specific (list (assoc specific key-assoc))
15624 key-assoc))
15625 (save-excursion
15626 (when (search-backward (cdr pair) bol t)
15627 (goto-char (match-end 0))
15628 (skip-chars-forward " \t")
15629 (and (looking-at org-ts-regexp-both)
15630 (push (cons (car pair)
15631 (match-string-no-properties 0))
15632 props)))))))
15633 (when specific (throw 'exit props)))
15634 (when (or (not specific)
15635 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15636 (let ((find-ts
15637 (lambda (end ts)
15638 ;; Fix next time-stamp before END. TS is the
15639 ;; list of time-stamps found so far.
15640 (let ((ts ts)
15641 (regexp (cond
15642 ((string= specific "TIMESTAMP")
15643 org-ts-regexp)
15644 ((string= specific "TIMESTAMP_IA")
15645 org-ts-regexp-inactive)
15646 ((assoc "TIMESTAMP_IA" ts)
15647 org-ts-regexp)
15648 ((assoc "TIMESTAMP" ts)
15649 org-ts-regexp-inactive)
15650 (t org-ts-regexp-both))))
15651 (catch 'next
15652 (while (re-search-forward regexp end t)
15653 (backward-char)
15654 (let ((object (org-element-context)))
15655 ;; Accept to match timestamps in node
15656 ;; properties, too.
15657 (when (memq (org-element-type object)
15658 '(node-property timestamp))
15659 (let ((type
15660 (org-element-property :type object)))
15661 (cond
15662 ((and (memq type '(active active-range))
15663 (not (equal specific "TIMESTAMP_IA")))
15664 (unless (assoc "TIMESTAMP" ts)
15665 (push (cons "TIMESTAMP"
15666 (org-element-property
15667 :raw-value object))
15669 (when specific (throw 'exit ts))))
15670 ((and (memq type '(inactive inactive-range))
15671 (not (string= specific "TIMESTAMP")))
15672 (unless (assoc "TIMESTAMP_IA" ts)
15673 (push (cons "TIMESTAMP_IA"
15674 (org-element-property
15675 :raw-value object))
15677 (when specific (throw 'exit ts))))))
15678 ;; Both timestamp types are found,
15679 ;; move to next part.
15680 (when (= (length ts) 2) (throw 'next ts)))))
15681 ts)))))
15682 (goto-char beg)
15683 ;; First look for timestamps within headline.
15684 (let ((ts (funcall find-ts (line-end-position) nil)))
15685 (if (= (length ts) 2) (setq props (nconc ts props))
15686 ;; Then find timestamps in the section, skipping
15687 ;; planning line.
15688 (let ((end (save-excursion (outline-next-heading))))
15689 (forward-line)
15690 (when (looking-at-p org-planning-line-re) (forward-line))
15691 (setq props (nconc (funcall find-ts end ts) props))))))))
15692 ;; Get the standard properties, like :PROP:.
15693 (when (memq which '(nil all standard))
15694 ;; If we are looking after a specific property, delegate
15695 ;; to `org-entry-get', which is faster. However, make an
15696 ;; exception for "CATEGORY", since it can be also set
15697 ;; through keywords (i.e. #+CATEGORY).
15698 (if (and specific (not (equal specific "CATEGORY")))
15699 (let ((value (org-entry-get beg specific nil t)))
15700 (throw 'exit (and value (list (cons specific value)))))
15701 (let ((range (org-get-property-block beg)))
15702 (when range
15703 (let ((end (cdr range)) seen-base)
15704 (goto-char (car range))
15705 ;; Unlike to `org--update-property-plist', we
15706 ;; handle the case where base values is found
15707 ;; after its extension. We also forbid standard
15708 ;; properties to be named as special properties.
15709 (while (re-search-forward org-property-re end t)
15710 (let* ((key (upcase (match-string-no-properties 2)))
15711 (extendp (string-match-p "\\+\\'" key))
15712 (key-base (if extendp (substring key 0 -1) key))
15713 (value (match-string-no-properties 3)))
15714 (cond
15715 ((member-ignore-case key-base org-special-properties))
15716 (extendp
15717 (setq props
15718 (org--update-property-plist key value props)))
15719 ((member key seen-base))
15720 (t (push key seen-base)
15721 (let ((p (assoc-string key props t)))
15722 (if p (setcdr p (concat value " " (cdr p)))
15723 (push (cons key value) props))))))))))))
15724 (unless (assoc "CATEGORY" props)
15725 (push (cons "CATEGORY" (org-get-category beg)) props)
15726 (when (string= specific "CATEGORY") (throw 'exit props)))
15727 ;; Return value.
15728 props)))))
15730 (defun org--property-local-values (property literal-nil)
15731 "Return value for PROPERTY in current entry.
15732 Value is a list whose car is the base value for PROPERTY and cdr
15733 a list of accumulated values. Return nil if neither is found in
15734 the entry. Also return nil when PROPERTY is set to \"nil\",
15735 unless LITERAL-NIL is non-nil."
15736 (let ((range (org-get-property-block)))
15737 (when range
15738 (goto-char (car range))
15739 (let* ((case-fold-search t)
15740 (end (cdr range))
15741 (value
15742 ;; Base value.
15743 (save-excursion
15744 (let ((v (and (re-search-forward
15745 (org-re-property property nil t) end t)
15746 (match-string-no-properties 3))))
15747 (list (if literal-nil v (org-not-nil v)))))))
15748 ;; Find additional values.
15749 (let* ((property+ (org-re-property (concat property "+") nil t)))
15750 (while (re-search-forward property+ end t)
15751 (push (match-string-no-properties 3) value)))
15752 ;; Return final values.
15753 (and (not (equal value '(nil))) (nreverse value))))))
15755 (defun org--property-global-value (property literal-nil)
15756 "Return value for PROPERTY in current buffer.
15757 Return value is a string. Return nil if property is not set
15758 globally. Also return nil when PROPERTY is set to \"nil\",
15759 unless LITERAL-NIL is non-nil."
15760 (let ((global
15761 (cdr (or (assoc-string property org-file-properties t)
15762 (assoc-string property org-global-properties t)
15763 (assoc-string property org-global-properties-fixed t)))))
15764 (if literal-nil global (org-not-nil global))))
15766 (defun org-entry-get (pom property &optional inherit literal-nil)
15767 "Get value of PROPERTY for entry or content at point-or-marker POM.
15769 If INHERIT is non-nil and the entry does not have the property,
15770 then also check higher levels of the hierarchy. If INHERIT is
15771 the symbol `selective', use inheritance only if the setting in
15772 `org-use-property-inheritance' selects PROPERTY for inheritance.
15774 If the property is present but empty, the return value is the
15775 empty string. If the property is not present at all, nil is
15776 returned. In any other case, return the value as a string.
15777 Search is case-insensitive.
15779 If LITERAL-NIL is set, return the string value \"nil\" as
15780 a string, do not interpret it as the list atom nil. This is used
15781 for inheritance when a \"nil\" value can supersede a non-nil
15782 value higher up the hierarchy."
15783 (org-with-point-at pom
15784 (cond
15785 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15786 ;; We need a special property. Use `org-entry-properties' to
15787 ;; retrieve it, but specify the wanted property.
15788 (cdr (assoc-string property (org-entry-properties nil property))))
15789 ((and inherit
15790 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15791 (org-entry-get-with-inheritance property literal-nil))
15793 (let* ((local (org--property-local-values property literal-nil))
15794 (value (and local (mapconcat #'identity (delq nil local) " "))))
15795 (if literal-nil value (org-not-nil value)))))))
15797 (defun org-property-or-variable-value (var &optional inherit)
15798 "Check if there is a property fixing the value of VAR.
15799 If yes, return this value. If not, return the current value of the variable."
15800 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15801 (if (and prop (stringp prop) (string-match "\\S-" prop))
15802 (read prop)
15803 (symbol-value var))))
15805 (defun org-entry-delete (pom property)
15806 "Delete PROPERTY from entry at point-or-marker POM.
15807 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15808 non-nil when a property was removed."
15809 (org-with-point-at pom
15810 (pcase (org-get-property-block)
15811 (`(,begin . ,origin)
15812 (let* ((end (copy-marker origin))
15813 (re (org-re-property
15814 (concat (regexp-quote property) "\\+?") t t)))
15815 (goto-char begin)
15816 (while (re-search-forward re end t)
15817 (delete-region (match-beginning 0) (line-beginning-position 2)))
15818 ;; If drawer is empty, remove it altogether.
15819 (when (= begin end)
15820 (delete-region (line-beginning-position 0)
15821 (line-beginning-position 2)))
15822 ;; Return non-nil if some property was removed.
15823 (prog1 (/= end origin) (set-marker end nil))))
15824 (_ nil))))
15826 ;; Multi-values properties are properties that contain multiple values
15827 ;; These values are assumed to be single words, separated by whitespace.
15828 (defun org-entry-add-to-multivalued-property (pom property value)
15829 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15830 (let* ((old (org-entry-get pom property))
15831 (values (and old (split-string old))))
15832 (setq value (org-entry-protect-space value))
15833 (unless (member value values)
15834 (setq values (append values (list value)))
15835 (org-entry-put pom property (mapconcat #'identity values " ")))))
15837 (defun org-entry-remove-from-multivalued-property (pom property value)
15838 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15839 (let* ((old (org-entry-get pom property))
15840 (values (and old (split-string old))))
15841 (setq value (org-entry-protect-space value))
15842 (when (member value values)
15843 (setq values (delete value values))
15844 (org-entry-put pom property (mapconcat #'identity values " ")))))
15846 (defun org-entry-member-in-multivalued-property (pom property value)
15847 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15848 (let* ((old (org-entry-get pom property))
15849 (values (and old (split-string old))))
15850 (setq value (org-entry-protect-space value))
15851 (member value values)))
15853 (defun org-entry-get-multivalued-property (pom property)
15854 "Return a list of values in a multivalued property."
15855 (let* ((value (org-entry-get pom property))
15856 (values (and value (split-string value))))
15857 (mapcar #'org-entry-restore-space values)))
15859 (defun org-entry-put-multivalued-property (pom property &rest values)
15860 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15861 VALUES should be a list of strings. Spaces will be protected."
15862 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15863 (let* ((value (org-entry-get pom property))
15864 (values (and value (split-string value))))
15865 (mapcar #'org-entry-restore-space values)))
15867 (defun org-entry-protect-space (s)
15868 "Protect spaces and newline in string S."
15869 (while (string-match " " s)
15870 (setq s (replace-match "%20" t t s)))
15871 (while (string-match "\n" s)
15872 (setq s (replace-match "%0A" t t s)))
15875 (defun org-entry-restore-space (s)
15876 "Restore spaces and newline in string S."
15877 (while (string-match "%20" s)
15878 (setq s (replace-match " " t t s)))
15879 (while (string-match "%0A" s)
15880 (setq s (replace-match "\n" t t s)))
15883 (defvar org-entry-property-inherited-from (make-marker)
15884 "Marker pointing to the entry from where a property was inherited.
15885 Each call to `org-entry-get-with-inheritance' will set this marker to the
15886 location of the entry where the inheritance search matched. If there was
15887 no match, the marker will point nowhere.
15888 Note that also `org-entry-get' calls this function, if the INHERIT flag
15889 is set.")
15891 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15892 "Get PROPERTY of entry or content at point, search higher levels if needed.
15893 The search will stop at the first ancestor which has the property defined.
15894 If the value found is \"nil\", return nil to show that the property
15895 should be considered as undefined (this is the meaning of nil here).
15896 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15897 (move-marker org-entry-property-inherited-from nil)
15898 (org-with-wide-buffer
15899 (let (value)
15900 (catch 'exit
15901 (while t
15902 (let ((v (org--property-local-values property literal-nil)))
15903 (when v
15904 (setq value
15905 (concat (mapconcat #'identity (delq nil v) " ")
15906 (and value " ")
15907 value)))
15908 (cond
15909 ((car v)
15910 (org-back-to-heading t)
15911 (move-marker org-entry-property-inherited-from (point))
15912 (throw 'exit nil))
15913 ((org-up-heading-safe))
15915 (let ((global (org--property-global-value property literal-nil)))
15916 (cond ((not global))
15917 (value (setq value (concat global " " value)))
15918 (t (setq value global))))
15919 (throw 'exit nil))))))
15920 (if literal-nil value (org-not-nil value)))))
15922 (defvar org-property-changed-functions nil
15923 "Hook called when the value of a property has changed.
15924 Each hook function should accept two arguments, the name of the property
15925 and the new value.")
15927 (defun org-entry-put (pom property value)
15928 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15930 If the value is nil, it is converted to the empty string. If it
15931 is not a string, an error is raised. Also raise an error on
15932 invalid property names.
15934 PROPERTY can be any regular property (see
15935 `org-special-properties'). It can also be \"TODO\",
15936 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15938 For the last two properties, VALUE may have any of the special
15939 values \"earlier\" and \"later\". The function then increases or
15940 decreases scheduled or deadline date by one day."
15941 (cond ((null value) (setq value ""))
15942 ((not (stringp value)) (error "Properties values should be strings"))
15943 ((not (org--valid-property-p property))
15944 (user-error "Invalid property name: \"%s\"" property)))
15945 (org-with-point-at pom
15946 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15947 (org-back-to-heading t)
15948 (org-with-limited-levels (org-back-to-heading t)))
15949 (let ((beg (point)))
15950 (cond
15951 ((equal property "TODO")
15952 (cond ((not (org-string-nw-p value)) (setq value 'none))
15953 ((not (member value org-todo-keywords-1))
15954 (user-error "\"%s\" is not a valid TODO state" value)))
15955 (org-todo value)
15956 (org-set-tags nil 'align))
15957 ((equal property "PRIORITY")
15958 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15959 (org-set-tags nil 'align))
15960 ((equal property "SCHEDULED")
15961 (forward-line)
15962 (if (and (looking-at-p org-planning-line-re)
15963 (re-search-forward
15964 org-scheduled-time-regexp (line-end-position) t))
15965 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15966 ((string= value "later") (org-timestamp-change 1 'day))
15967 ((string= value "") (org-schedule '(4)))
15968 (t (org-schedule nil value)))
15969 (if (member value '("earlier" "later" ""))
15970 (call-interactively #'org-schedule)
15971 (org-schedule nil value))))
15972 ((equal property "DEADLINE")
15973 (forward-line)
15974 (if (and (looking-at-p org-planning-line-re)
15975 (re-search-forward
15976 org-deadline-time-regexp (line-end-position) t))
15977 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15978 ((string= value "later") (org-timestamp-change 1 'day))
15979 ((string= value "") (org-deadline '(4)))
15980 (t (org-deadline nil value)))
15981 (if (member value '("earlier" "later" ""))
15982 (call-interactively #'org-deadline)
15983 (org-deadline nil value))))
15984 ((member property org-special-properties)
15985 (error "The %s property cannot be set with `org-entry-put'" property))
15987 (let* ((range (org-get-property-block beg 'force))
15988 (end (cdr range))
15989 (case-fold-search t))
15990 (goto-char (car range))
15991 (if (re-search-forward (org-re-property property nil t) end t)
15992 (progn (delete-region (match-beginning 0) (match-end 0))
15993 (goto-char (match-beginning 0)))
15994 (goto-char end)
15995 (insert "\n")
15996 (backward-char))
15997 (insert ":" property ":")
15998 (when value (insert " " value))
15999 (org-indent-line)))))
16000 (run-hook-with-args 'org-property-changed-functions property value)))
16002 (defun org-buffer-property-keys
16003 (&optional specials defaults columns ignore-malformed)
16004 "Get all property keys in the current buffer.
16006 When SPECIALS is non-nil, also list the special properties that
16007 reflect things like tags and TODO state.
16009 When DEFAULTS is non-nil, also include properties that has
16010 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16011 DESCRIPTION, LOCATION, and LOGGING and others.
16013 When COLUMNS in non-nil, also include property names given in
16014 COLUMN formats in the current buffer.
16016 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16017 automatically performed, such drawers will be silently ignored."
16018 (let ((case-fold-search t)
16019 (props (append
16020 (and specials org-special-properties)
16021 (and defaults (cons org-effort-property org-default-properties))
16022 nil)))
16023 (org-with-wide-buffer
16024 (goto-char (point-min))
16025 (while (re-search-forward org-property-start-re nil t)
16026 (let ((range (org-get-property-block)))
16027 (catch 'skip
16028 (unless range
16029 (when (and (not ignore-malformed)
16030 (not (org-before-first-heading-p))
16031 (y-or-n-p (format "Malformed drawer at %d, repair?"
16032 (line-beginning-position))))
16033 (org-get-property-block nil t))
16034 (throw 'skip nil))
16035 (goto-char (car range))
16036 (let ((begin (car range))
16037 (end (cdr range)))
16038 ;; Make sure that found property block is not located
16039 ;; before current point, as it would generate an infloop.
16040 ;; It can happen, for example, in the following
16041 ;; situation:
16043 ;; * Headline
16044 ;; :PROPERTIES:
16045 ;; ...
16046 ;; :END:
16047 ;; *************** Inlinetask
16048 ;; #+BEGIN_EXAMPLE
16049 ;; :PROPERTIES:
16050 ;; #+END_EXAMPLE
16052 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16053 (while (< (point) end)
16054 (let ((p (progn (looking-at org-property-re)
16055 (match-string-no-properties 2))))
16056 ;; Only add true property name, not extension symbol.
16057 (push (if (not (string-match-p "\\+\\'" p)) p
16058 (substring p 0 -1))
16059 props))
16060 (forward-line))))
16061 (outline-next-heading)))
16062 (when columns
16063 (goto-char (point-min))
16064 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16065 (let ((element (org-element-at-point)))
16066 (when (memq (org-element-type element) '(keyword node-property))
16067 (let ((value (org-element-property :value element))
16068 (start 0))
16069 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16070 (setq start (match-end 0))
16071 (let ((p (match-string-no-properties 1 value)))
16072 (unless (member-ignore-case p org-special-properties)
16073 (push p props))))))))))
16074 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16076 (defun org-property-values (key)
16077 "List all non-nil values of property KEY in current buffer."
16078 (org-with-wide-buffer
16079 (goto-char (point-min))
16080 (let ((case-fold-search t)
16081 (re (org-re-property key))
16082 values)
16083 (while (re-search-forward re nil t)
16084 (push (org-entry-get (point) key) values))
16085 (delete-dups values))))
16087 (defun org-insert-property-drawer ()
16088 "Insert a property drawer into the current entry."
16089 (org-with-wide-buffer
16090 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16091 (org-back-to-heading t)
16092 (org-with-limited-levels (org-back-to-heading t)))
16093 (forward-line)
16094 (when (looking-at-p org-planning-line-re) (forward-line))
16095 (unless (looking-at-p org-property-drawer-re)
16096 ;; Make sure we start editing a line from current entry, not from
16097 ;; next one. It prevents extending text properties or overlays
16098 ;; belonging to the latter.
16099 (when (bolp) (backward-char))
16100 (let ((begin (1+ (point)))
16101 (inhibit-read-only t))
16102 (insert "\n:PROPERTIES:\n:END:")
16103 (when (eobp) (insert "\n"))
16104 (org-indent-region begin (point))))))
16106 (defun org-insert-drawer (&optional arg drawer)
16107 "Insert a drawer at point.
16109 When optional argument ARG is non-nil, insert a property drawer.
16111 Optional argument DRAWER, when non-nil, is a string representing
16112 drawer's name. Otherwise, the user is prompted for a name.
16114 If a region is active, insert the drawer around that region
16115 instead.
16117 Point is left between drawer's boundaries."
16118 (interactive "P")
16119 (let* ((drawer (if arg "PROPERTIES"
16120 (or drawer (read-from-minibuffer "Drawer: ")))))
16121 (cond
16122 ;; With C-u, fall back on `org-insert-property-drawer'
16123 (arg (org-insert-property-drawer))
16124 ;; Check validity of suggested drawer's name.
16125 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16126 (user-error "Invalid drawer name"))
16127 ;; With an active region, insert a drawer at point.
16128 ((not (org-region-active-p))
16129 (progn
16130 (unless (bolp) (insert "\n"))
16131 (insert (format ":%s:\n\n:END:\n" drawer))
16132 (forward-line -2)))
16133 ;; Otherwise, insert the drawer at point
16135 (let ((rbeg (region-beginning))
16136 (rend (copy-marker (region-end))))
16137 (unwind-protect
16138 (progn
16139 (goto-char rbeg)
16140 (beginning-of-line)
16141 (when (save-excursion
16142 (re-search-forward org-outline-regexp-bol rend t))
16143 (user-error "Drawers cannot contain headlines"))
16144 ;; Position point at the beginning of the first
16145 ;; non-blank line in region. Insert drawer's opening
16146 ;; there, then indent it.
16147 (org-skip-whitespace)
16148 (beginning-of-line)
16149 (insert ":" drawer ":\n")
16150 (forward-line -1)
16151 (indent-for-tab-command)
16152 ;; Move point to the beginning of the first blank line
16153 ;; after the last non-blank line in region. Insert
16154 ;; drawer's closing, then indent it.
16155 (goto-char rend)
16156 (skip-chars-backward " \r\t\n")
16157 (insert "\n:END:")
16158 (deactivate-mark t)
16159 (indent-for-tab-command)
16160 (unless (eolp) (insert "\n")))
16161 ;; Clear marker, whatever the outcome of insertion is.
16162 (set-marker rend nil)))))))
16164 (defvar org-property-set-functions-alist nil
16165 "Property set function alist.
16166 Each entry should have the following format:
16168 (PROPERTY . READ-FUNCTION)
16170 The read function will be called with the same argument as
16171 `org-completing-read'.")
16173 (defun org-set-property-function (property)
16174 "Get the function that should be used to set PROPERTY.
16175 This is computed according to `org-property-set-functions-alist'."
16176 (or (cdr (assoc property org-property-set-functions-alist))
16177 'org-completing-read))
16179 (defun org-read-property-value (property)
16180 "Read PROPERTY value from user."
16181 (let* ((completion-ignore-case t)
16182 (allowed (org-property-get-allowed-values nil property 'table))
16183 (cur (org-entry-get nil property))
16184 (prompt (concat property " value"
16185 (if (and cur (string-match "\\S-" cur))
16186 (concat " [" cur "]") "") ": "))
16187 (set-function (org-set-property-function property))
16188 (val (if allowed
16189 (funcall set-function prompt allowed nil
16190 (not (get-text-property 0 'org-unrestricted
16191 (caar allowed))))
16192 (funcall set-function prompt
16193 (mapcar 'list (org-property-values property))
16194 nil nil "" nil cur))))
16195 (org-trim val)))
16197 (defvar org-last-set-property nil)
16198 (defvar org-last-set-property-value nil)
16199 (defun org-read-property-name ()
16200 "Read a property name."
16201 (let ((completion-ignore-case t)
16202 (default-prop (or (and (org-at-property-p)
16203 (match-string-no-properties 2))
16204 org-last-set-property)))
16205 (org-completing-read
16206 (concat "Property"
16207 (if default-prop (concat " [" default-prop "]") "")
16208 ": ")
16209 (mapcar #'list (org-buffer-property-keys nil t t))
16210 nil nil nil nil default-prop)))
16212 (defun org-set-property-and-value (use-last)
16213 "Allow to set [PROPERTY]: [value] direction from prompt.
16214 When use-default, don't even ask, just use the last
16215 \"[PROPERTY]: [value]\" string from the history."
16216 (interactive "P")
16217 (let* ((completion-ignore-case t)
16218 (pv (or (and use-last org-last-set-property-value)
16219 (org-completing-read
16220 "Enter a \"[Property]: [value]\" pair: "
16221 nil nil nil nil nil
16222 org-last-set-property-value)))
16223 prop val)
16224 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16225 (setq prop (match-string 1 pv)
16226 val (match-string 2 pv))
16227 (org-set-property prop val))))
16229 (defun org-set-property (property value)
16230 "In the current entry, set PROPERTY to VALUE.
16232 When called interactively, this will prompt for a property name, offering
16233 completion on existing and default properties. And then it will prompt
16234 for a value, offering completion either on allowed values (via an inherited
16235 xxx_ALL property) or on existing values in other instances of this property
16236 in the current file.
16238 Throw an error when trying to set a property with an invalid name."
16239 (interactive (list nil nil))
16240 (let ((property (or property (org-read-property-name))))
16241 ;; `org-entry-put' also makes the following check, but this one
16242 ;; avoids polluting `org-last-set-property' and
16243 ;; `org-last-set-property-value' needlessly.
16244 (unless (org--valid-property-p property)
16245 (user-error "Invalid property name: \"%s\"" property))
16246 (let ((value (or value (org-read-property-value property)))
16247 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16248 (setq org-last-set-property property)
16249 (setq org-last-set-property-value (concat property ": " value))
16250 ;; Possibly postprocess the inserted value:
16251 (when fn (setq value (funcall fn value)))
16252 (unless (equal (org-entry-get nil property) value)
16253 (org-entry-put nil property value)))))
16255 (defun org-find-property (property &optional value)
16256 "Find first entry in buffer that sets PROPERTY.
16258 When optional argument VALUE is non-nil, only consider an entry
16259 if it contains PROPERTY set to this value. If PROPERTY should be
16260 explicitly set to nil, use string \"nil\" for VALUE.
16262 Return position where the entry begins, or nil if there is no
16263 such entry. If narrowing is in effect, only search the visible
16264 part of the buffer."
16265 (save-excursion
16266 (goto-char (point-min))
16267 (let ((case-fold-search t)
16268 (re (org-re-property property nil (not value) value)))
16269 (catch 'exit
16270 (while (re-search-forward re nil t)
16271 (when (if value (org-at-property-p)
16272 (org-entry-get (point) property nil t))
16273 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16275 (defun org-delete-property (property)
16276 "In the current entry, delete PROPERTY."
16277 (interactive
16278 (let* ((completion-ignore-case t)
16279 (cat (org-entry-get (point) "CATEGORY"))
16280 (props0 (org-entry-properties nil 'standard))
16281 (props (if cat props0
16282 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16283 (prop (if (< 1 (length props))
16284 (completing-read "Property: " props nil t)
16285 (caar props))))
16286 (list prop)))
16287 (if (not property)
16288 (message "No property to delete in this entry")
16289 (org-entry-delete nil property)
16290 (message "Property \"%s\" deleted" property)))
16292 (defun org-delete-property-globally (property)
16293 "Remove PROPERTY globally, from all entries.
16294 This function ignores narrowing, if any."
16295 (interactive
16296 (let* ((completion-ignore-case t)
16297 (prop (completing-read
16298 "Globally remove property: "
16299 (mapcar #'list (org-buffer-property-keys)))))
16300 (list prop)))
16301 (org-with-wide-buffer
16302 (goto-char (point-min))
16303 (let ((count 0)
16304 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16305 (while (re-search-forward re nil t)
16306 (when (org-entry-delete (point) property) (cl-incf count)))
16307 (message "Property \"%s\" removed from %d entries" property count))))
16309 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16311 (defun org-compute-property-at-point ()
16312 "Compute the property at point.
16313 This looks for an enclosing column format, extracts the operator and
16314 then applies it to the property in the column format's scope."
16315 (interactive)
16316 (unless (org-at-property-p)
16317 (user-error "Not at a property"))
16318 (let ((prop (match-string-no-properties 2)))
16319 (org-columns-get-format-and-top-level)
16320 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16321 (user-error "No operator defined for property %s" prop))
16322 (org-columns-compute prop)))
16324 (defvar org-property-allowed-value-functions nil
16325 "Hook for functions supplying allowed values for a specific property.
16326 The functions must take a single argument, the name of the property, and
16327 return a flat list of allowed values. If \":ETC\" is one of
16328 the values, this means that these values are intended as defaults for
16329 completion, but that other values should be allowed too.
16330 The functions must return nil if they are not responsible for this
16331 property.")
16333 (defun org-property-get-allowed-values (pom property &optional table)
16334 "Get allowed values for the property PROPERTY.
16335 When TABLE is non-nil, return an alist that can directly be used for
16336 completion."
16337 (let (vals)
16338 (cond
16339 ((equal property "TODO")
16340 (setq vals (org-with-point-at pom
16341 (append org-todo-keywords-1 '("")))))
16342 ((equal property "PRIORITY")
16343 (let ((n org-lowest-priority))
16344 (while (>= n org-highest-priority)
16345 (push (char-to-string n) vals)
16346 (setq n (1- n)))))
16347 ((equal property "CATEGORY"))
16348 ((member property org-special-properties))
16349 ((setq vals (run-hook-with-args-until-success
16350 'org-property-allowed-value-functions property)))
16352 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16353 (when (and vals (string-match "\\S-" vals))
16354 (setq vals (car (read-from-string (concat "(" vals ")"))))
16355 (setq vals (mapcar (lambda (x)
16356 (cond ((stringp x) x)
16357 ((numberp x) (number-to-string x))
16358 ((symbolp x) (symbol-name x))
16359 (t "???")))
16360 vals)))))
16361 (when (member ":ETC" vals)
16362 (setq vals (remove ":ETC" vals))
16363 (org-add-props (car vals) '(org-unrestricted t)))
16364 (if table (mapcar 'list vals) vals)))
16366 (defun org-property-previous-allowed-value (&optional _previous)
16367 "Switch to the next allowed value for this property."
16368 (interactive)
16369 (org-property-next-allowed-value t))
16371 (defun org-property-next-allowed-value (&optional previous)
16372 "Switch to the next allowed value for this property."
16373 (interactive)
16374 (unless (org-at-property-p)
16375 (user-error "Not at a property"))
16376 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16377 (key (match-string 2))
16378 (value (match-string 3))
16379 (allowed (or (org-property-get-allowed-values (point) key)
16380 (and (member value '("[ ]" "[-]" "[X]"))
16381 '("[ ]" "[X]"))))
16382 (heading (save-match-data (nth 4 (org-heading-components))))
16383 nval)
16384 (unless allowed
16385 (user-error "Allowed values for this property have not been defined"))
16386 (when previous (setq allowed (reverse allowed)))
16387 (when (member value allowed)
16388 (setq nval (car (cdr (member value allowed)))))
16389 (setq nval (or nval (car allowed)))
16390 (when (equal nval value)
16391 (user-error "Only one allowed value for this property"))
16392 (org-at-property-p)
16393 (replace-match (concat " :" key ": " nval) t t)
16394 (org-indent-line)
16395 (beginning-of-line 1)
16396 (skip-chars-forward " \t")
16397 (when (equal prop org-effort-property)
16398 (org-refresh-property
16399 '((effort . identity)
16400 (effort-minutes . org-duration-to-minutes))
16401 nval)
16402 (when (string= org-clock-current-task heading)
16403 (setq org-clock-effort nval)
16404 (org-clock-update-mode-line)))
16405 (run-hook-with-args 'org-property-changed-functions key nval)))
16407 (defun org-find-olp (path &optional this-buffer)
16408 "Return a marker pointing to the entry at outline path OLP.
16409 If anything goes wrong, throw an error.
16410 You can wrap this call to catch the error like this:
16412 (condition-case msg
16413 (org-mobile-locate-entry (match-string 4))
16414 (error (nth 1 msg)))
16416 The return value will then be either a string with the error message,
16417 or a marker if everything is OK.
16419 If THIS-BUFFER is set, the outline path does not contain a file,
16420 only headings."
16421 (let* ((file (if this-buffer buffer-file-name (pop path)))
16422 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16423 (level 1)
16424 (lmin 1)
16425 (lmax 1)
16426 end found flevel)
16427 (unless buffer (error "File not found :%s" file))
16428 (with-current-buffer buffer
16429 (unless (derived-mode-p 'org-mode)
16430 (error "Buffer %s needs to be in Org mode" buffer))
16431 (org-with-wide-buffer
16432 (goto-char (point-min))
16433 (dolist (heading path)
16434 (let ((re (format org-complex-heading-regexp-format
16435 (regexp-quote heading)))
16436 (cnt 0))
16437 (while (re-search-forward re end t)
16438 (setq level (- (match-end 1) (match-beginning 1)))
16439 (when (and (>= level lmin) (<= level lmax))
16440 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16441 (when (= cnt 0)
16442 (error "Heading not found on level %d: %s" lmax heading))
16443 (when (> cnt 1)
16444 (error "Heading not unique on level %d: %s" lmax heading))
16445 (goto-char found)
16446 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16447 (setq end (save-excursion (org-end-of-subtree t t)))))
16448 (when (org-at-heading-p)
16449 (point-marker))))))
16451 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16452 "Find node HEADING in BUFFER.
16453 Return a marker to the heading if it was found, or nil if not.
16454 If POS-ONLY is set, return just the position instead of a marker.
16456 The heading text must match exact, but it may have a TODO keyword,
16457 a priority cookie and tags in the standard locations."
16458 (with-current-buffer (or buffer (current-buffer))
16459 (org-with-wide-buffer
16460 (goto-char (point-min))
16461 (let (case-fold-search)
16462 (when (re-search-forward
16463 (format org-complex-heading-regexp-format
16464 (regexp-quote heading)) nil t)
16465 (if pos-only
16466 (match-beginning 0)
16467 (move-marker (make-marker) (match-beginning 0))))))))
16469 (defun org-find-exact-heading-in-directory (heading &optional dir)
16470 "Find Org node headline HEADING in all .org files in directory DIR.
16471 When the target headline is found, return a marker to this location."
16472 (let ((files (directory-files (or dir default-directory)
16473 t "\\`[^.#].*\\.org\\'"))
16474 visiting m buffer)
16475 (catch 'found
16476 (dolist (file files)
16477 (message "trying %s" file)
16478 (setq visiting (org-find-base-buffer-visiting file))
16479 (setq buffer (or visiting (find-file-noselect file)))
16480 (setq m (org-find-exact-headline-in-buffer
16481 heading buffer))
16482 (when (and (not m) (not visiting)) (kill-buffer buffer))
16483 (and m (throw 'found m))))))
16485 (defun org-find-entry-with-id (ident)
16486 "Locate the entry that contains the ID property with exact value IDENT.
16487 IDENT can be a string, a symbol or a number, this function will search for
16488 the string representation of it.
16489 Return the position where this entry starts, or nil if there is no such entry."
16490 (interactive "sID: ")
16491 (let ((id (cond
16492 ((stringp ident) ident)
16493 ((symbolp ident) (symbol-name ident))
16494 ((numberp ident) (number-to-string ident))
16495 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16496 (org-with-wide-buffer (org-find-property "ID" id))))
16498 ;;;; Timestamps
16500 (defvar org-last-changed-timestamp nil)
16501 (defvar org-last-inserted-timestamp nil
16502 "The last time stamp inserted with `org-insert-time-stamp'.")
16504 (defun org-time-stamp (arg &optional inactive)
16505 "Prompt for a date/time and insert a time stamp.
16507 If the user specifies a time like HH:MM or if this command is
16508 called with at least one prefix argument, the time stamp contains
16509 the date and the time. Otherwise, only the date is included.
16511 All parts of a date not specified by the user are filled in from
16512 the timestamp at point, if any, or the current date/time
16513 otherwise.
16515 If there is already a timestamp at the cursor, it is replaced.
16517 With two universal prefix arguments, insert an active timestamp
16518 with the current time without prompting the user.
16520 When called from lisp, the timestamp is inactive if INACTIVE is
16521 non-nil."
16522 (interactive "P")
16523 (let* ((ts (cond
16524 ((org-at-date-range-p t)
16525 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16526 ((org-at-timestamp-p 'lax) (match-string 0))))
16527 ;; Default time is either the timestamp at point or today.
16528 ;; When entering a range, only the range start is considered.
16529 (default-time (if (not ts) (current-time)
16530 (apply #'encode-time (org-parse-time-string ts))))
16531 (default-input (and ts (org-get-compact-tod ts)))
16532 (repeater (and ts
16533 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16534 (match-string 0 ts)))
16535 org-time-was-given
16536 org-end-time-was-given
16537 (time
16538 (and (if (equal arg '(16)) (current-time)
16539 ;; Preserve `this-command' and `last-command'.
16540 (let ((this-command this-command)
16541 (last-command last-command))
16542 (org-read-date
16543 arg 'totime nil nil default-time default-input
16544 inactive))))))
16545 (cond
16546 ((and ts
16547 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16548 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16549 (insert "--")
16550 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16552 ;; Make sure we're on a timestamp. When in the middle of a date
16553 ;; range, move arbitrarily to range end.
16554 (unless (org-at-timestamp-p 'lax)
16555 (skip-chars-forward "-")
16556 (org-at-timestamp-p 'lax))
16557 (replace-match "")
16558 (setq org-last-changed-timestamp
16559 (org-insert-time-stamp
16560 time (or org-time-was-given arg)
16561 inactive nil nil (list org-end-time-was-given)))
16562 (when repeater
16563 (backward-char)
16564 (insert " " repeater)
16565 (setq org-last-changed-timestamp
16566 (concat (substring org-last-inserted-timestamp 0 -1)
16567 " " repeater ">")))
16568 (message "Timestamp updated"))
16569 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16570 (t (org-insert-time-stamp
16571 time (or org-time-was-given arg) inactive nil nil
16572 (list org-end-time-was-given))))))
16574 ;; FIXME: can we use this for something else, like computing time differences?
16575 (defun org-get-compact-tod (s)
16576 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16577 (let* ((t1 (match-string 1 s))
16578 (h1 (string-to-number (match-string 2 s)))
16579 (m1 (string-to-number (match-string 3 s)))
16580 (t2 (and (match-end 4) (match-string 5 s)))
16581 (h2 (and t2 (string-to-number (match-string 6 s))))
16582 (m2 (and t2 (string-to-number (match-string 7 s))))
16583 dh dm)
16584 (if (not t2)
16586 (setq dh (- h2 h1) dm (- m2 m1))
16587 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16588 (concat t1 "+" (number-to-string dh)
16589 (and (/= 0 dm) (format ":%02d" dm)))))))
16591 (defun org-time-stamp-inactive (&optional arg)
16592 "Insert an inactive time stamp.
16593 An inactive time stamp is enclosed in square brackets instead of angle
16594 brackets. It is inactive in the sense that it does not trigger agenda entries,
16595 does not link to the calendar and cannot be changed with the S-cursor keys.
16596 So these are more for recording a certain time/date."
16597 (interactive "P")
16598 (org-time-stamp arg 'inactive))
16600 (defvar org-date-ovl (make-overlay 1 1))
16601 (overlay-put org-date-ovl 'face 'org-date-selected)
16602 (delete-overlay org-date-ovl)
16604 (defvar org-ans1) ; dynamically scoped parameter
16605 (defvar org-ans2) ; dynamically scoped parameter
16607 (defvar org-plain-time-of-day-regexp) ; defined below
16609 (defvar org-overriding-default-time nil) ; dynamically scoped
16610 (defvar org-read-date-overlay nil)
16611 (defvar org-dcst nil) ; dynamically scoped
16612 (defvar org-read-date-history nil)
16613 (defvar org-read-date-final-answer nil)
16614 (defvar org-read-date-analyze-futurep nil)
16615 (defvar org-read-date-analyze-forced-year nil)
16616 (defvar org-read-date-inactive)
16618 (defvar org-read-date-minibuffer-local-map
16619 (let* ((map (make-sparse-keymap)))
16620 (set-keymap-parent map minibuffer-local-map)
16621 (org-defkey map (kbd ".")
16622 (lambda () (interactive)
16623 ;; Are we at the beginning of the prompt?
16624 (if (looking-back "^[^:]+: "
16625 (let ((inhibit-field-text-motion t))
16626 (line-beginning-position)))
16627 (org-eval-in-calendar '(calendar-goto-today))
16628 (insert "."))))
16629 (org-defkey map (kbd "C-.")
16630 (lambda () (interactive)
16631 (org-eval-in-calendar '(calendar-goto-today))))
16632 (org-defkey map [(meta shift left)]
16633 (lambda () (interactive)
16634 (org-eval-in-calendar '(calendar-backward-month 1))))
16635 (org-defkey map [(meta shift right)]
16636 (lambda () (interactive)
16637 (org-eval-in-calendar '(calendar-forward-month 1))))
16638 (org-defkey map [(meta shift up)]
16639 (lambda () (interactive)
16640 (org-eval-in-calendar '(calendar-backward-year 1))))
16641 (org-defkey map [(meta shift down)]
16642 (lambda () (interactive)
16643 (org-eval-in-calendar '(calendar-forward-year 1))))
16644 (org-defkey map [?\e (shift left)]
16645 (lambda () (interactive)
16646 (org-eval-in-calendar '(calendar-backward-month 1))))
16647 (org-defkey map [?\e (shift right)]
16648 (lambda () (interactive)
16649 (org-eval-in-calendar '(calendar-forward-month 1))))
16650 (org-defkey map [?\e (shift up)]
16651 (lambda () (interactive)
16652 (org-eval-in-calendar '(calendar-backward-year 1))))
16653 (org-defkey map [?\e (shift down)]
16654 (lambda () (interactive)
16655 (org-eval-in-calendar '(calendar-forward-year 1))))
16656 (org-defkey map [(shift up)]
16657 (lambda () (interactive)
16658 (org-eval-in-calendar '(calendar-backward-week 1))))
16659 (org-defkey map [(shift down)]
16660 (lambda () (interactive)
16661 (org-eval-in-calendar '(calendar-forward-week 1))))
16662 (org-defkey map [(shift left)]
16663 (lambda () (interactive)
16664 (org-eval-in-calendar '(calendar-backward-day 1))))
16665 (org-defkey map [(shift right)]
16666 (lambda () (interactive)
16667 (org-eval-in-calendar '(calendar-forward-day 1))))
16668 (org-defkey map "!"
16669 (lambda () (interactive)
16670 (org-eval-in-calendar '(diary-view-entries))
16671 (message "")))
16672 (org-defkey map ">"
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-scroll-left 1))))
16675 (org-defkey map "<"
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(calendar-scroll-right 1))))
16678 (org-defkey map "\C-v"
16679 (lambda () (interactive)
16680 (org-eval-in-calendar
16681 '(calendar-scroll-left-three-months 1))))
16682 (org-defkey map "\M-v"
16683 (lambda () (interactive)
16684 (org-eval-in-calendar
16685 '(calendar-scroll-right-three-months 1))))
16686 map)
16687 "Keymap for minibuffer commands when using `org-read-date'.")
16689 (defvar org-def)
16690 (defvar org-defdecode)
16691 (defvar org-with-time)
16693 (defvar calendar-setup) ; Dynamically scoped.
16694 (defun org-read-date (&optional with-time to-time from-string prompt
16695 default-time default-input inactive)
16696 "Read a date, possibly a time, and make things smooth for the user.
16697 The prompt will suggest to enter an ISO date, but you can also enter anything
16698 which will at least partially be understood by `parse-time-string'.
16699 Unrecognized parts of the date will default to the current day, month, year,
16700 hour and minute. If this command is called to replace a timestamp at point,
16701 or to enter the second timestamp of a range, the default time is taken
16702 from the existing stamp. Furthermore, the command prefers the future,
16703 so if you are giving a date where the year is not given, and the day-month
16704 combination is already past in the current year, it will assume you
16705 mean next year. For details, see the manual. A few examples:
16707 3-2-5 --> 2003-02-05
16708 feb 15 --> currentyear-02-15
16709 2/15 --> currentyear-02-15
16710 sep 12 9 --> 2009-09-12
16711 12:45 --> today 12:45
16712 22 sept 0:34 --> currentyear-09-22 0:34
16713 12 --> currentyear-currentmonth-12
16714 Fri --> nearest Friday after today
16715 -Tue --> last Tuesday
16716 etc.
16718 Furthermore you can specify a relative date by giving, as the *first* thing
16719 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16720 change in days weeks, months, years.
16721 With a single plus or minus, the date is relative to today. With a double
16722 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16723 +4d --> four days from today
16724 +4 --> same as above
16725 +2w --> two weeks from today
16726 ++5 --> five days from default date
16728 The function understands only English month and weekday abbreviations.
16730 While prompting, a calendar is popped up - you can also select the
16731 date with the mouse (button 1). The calendar shows a period of three
16732 months. To scroll it to other months, use the keys `>' and `<'.
16733 If you don't like the calendar, turn it off with
16734 (setq org-read-date-popup-calendar nil)
16736 With optional argument TO-TIME, the date will immediately be converted
16737 to an internal time.
16738 With an optional argument WITH-TIME, the prompt will suggest to
16739 also insert a time. Note that when WITH-TIME is not set, you can
16740 still enter a time, and this function will inform the calling routine
16741 about this change. The calling routine may then choose to change the
16742 format used to insert the time stamp into the buffer to include the time.
16743 With optional argument FROM-STRING, read from this string instead from
16744 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16745 the time/date that is used for everything that is not specified by the
16746 user."
16747 (require 'parse-time)
16748 (let* ((org-with-time with-time)
16749 (org-time-stamp-rounding-minutes
16750 (if (equal org-with-time '(16))
16751 '(0 0)
16752 org-time-stamp-rounding-minutes))
16753 (org-dcst org-display-custom-times)
16754 (ct (org-current-time))
16755 (org-def (or org-overriding-default-time default-time ct))
16756 (org-defdecode (decode-time org-def))
16757 (cur-frame (selected-frame))
16758 (mouse-autoselect-window nil) ; Don't let the mouse jump
16759 (calendar-setup
16760 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16761 (calendar-move-hook nil)
16762 (calendar-view-diary-initially-flag nil)
16763 (calendar-view-holidays-initially-flag nil)
16764 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16765 ;; Rationalize `org-def' and `org-defdecode', if required.
16766 (when (< (nth 2 org-defdecode) org-extend-today-until)
16767 (setf (nth 2 org-defdecode) -1)
16768 (setf (nth 1 org-defdecode) 59)
16769 (setq org-def (apply #'encode-time org-defdecode))
16770 (setq org-defdecode (decode-time org-def)))
16771 (let* ((timestr (format-time-string
16772 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16773 org-def))
16774 (prompt (concat (if prompt (concat prompt " ") "")
16775 (format "Date+time [%s]: " timestr))))
16776 (cond
16777 (from-string (setq ans from-string))
16778 (org-read-date-popup-calendar
16779 (save-excursion
16780 (save-window-excursion
16781 (calendar)
16782 (when (eq calendar-setup 'calendar-only)
16783 (setq cal-frame
16784 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16785 (select-frame cal-frame))
16786 (org-eval-in-calendar '(setq cursor-type nil) t)
16787 (unwind-protect
16788 (progn
16789 (calendar-forward-day (- (time-to-days org-def)
16790 (calendar-absolute-from-gregorian
16791 (calendar-current-date))))
16792 (org-eval-in-calendar nil t)
16793 (let* ((old-map (current-local-map))
16794 (map (copy-keymap calendar-mode-map))
16795 (minibuffer-local-map
16796 (copy-keymap org-read-date-minibuffer-local-map)))
16797 (org-defkey map (kbd "RET") 'org-calendar-select)
16798 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16799 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16800 (unwind-protect
16801 (progn
16802 (use-local-map map)
16803 (setq org-read-date-inactive inactive)
16804 (add-hook 'post-command-hook 'org-read-date-display)
16805 (setq org-ans0
16806 (read-string prompt
16807 default-input
16808 'org-read-date-history
16809 nil))
16810 ;; org-ans0: from prompt
16811 ;; org-ans1: from mouse click
16812 ;; org-ans2: from calendar motion
16813 (setq ans
16814 (concat org-ans0 " " (or org-ans1 org-ans2))))
16815 (remove-hook 'post-command-hook 'org-read-date-display)
16816 (use-local-map old-map)
16817 (when org-read-date-overlay
16818 (delete-overlay org-read-date-overlay)
16819 (setq org-read-date-overlay nil)))))
16820 (bury-buffer "*Calendar*")
16821 (when cal-frame
16822 (delete-frame cal-frame)
16823 (select-frame-set-input-focus cur-frame))))))
16825 (t ; Naked prompt only
16826 (unwind-protect
16827 (setq ans (read-string prompt default-input
16828 'org-read-date-history timestr))
16829 (when org-read-date-overlay
16830 (delete-overlay org-read-date-overlay)
16831 (setq org-read-date-overlay nil))))))
16833 (setq final (org-read-date-analyze ans org-def org-defdecode))
16835 (when org-read-date-analyze-forced-year
16836 (message "Year was forced into %s"
16837 (if org-read-date-force-compatible-dates
16838 "compatible range (1970-2037)"
16839 "range representable on this machine"))
16840 (ding))
16842 ;; One round trip to get rid of 34th of August and stuff like that....
16843 (setq final (decode-time (apply 'encode-time final)))
16845 (setq org-read-date-final-answer ans)
16847 (if to-time
16848 (apply 'encode-time final)
16849 (if (and (boundp 'org-time-was-given) org-time-was-given)
16850 (format "%04d-%02d-%02d %02d:%02d"
16851 (nth 5 final) (nth 4 final) (nth 3 final)
16852 (nth 2 final) (nth 1 final))
16853 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16855 (defun org-read-date-display ()
16856 "Display the current date prompt interpretation in the minibuffer."
16857 (when org-read-date-display-live
16858 (when org-read-date-overlay
16859 (delete-overlay org-read-date-overlay))
16860 (when (minibufferp (current-buffer))
16861 (save-excursion
16862 (end-of-line 1)
16863 (while (not (equal (buffer-substring
16864 (max (point-min) (- (point) 4)) (point))
16865 " "))
16866 (insert " ")))
16867 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16868 " " (or org-ans1 org-ans2)))
16869 (org-end-time-was-given nil)
16870 (f (org-read-date-analyze ans org-def org-defdecode))
16871 (fmts (if org-dcst
16872 org-time-stamp-custom-formats
16873 org-time-stamp-formats))
16874 (fmt (if (or org-with-time
16875 (and (boundp 'org-time-was-given) org-time-was-given))
16876 (cdr fmts)
16877 (car fmts)))
16878 (txt (format-time-string fmt (apply 'encode-time f)))
16879 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16880 (txt (concat "=> " txt)))
16881 (when (and org-end-time-was-given
16882 (string-match org-plain-time-of-day-regexp txt))
16883 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16884 org-end-time-was-given
16885 (substring txt (match-end 0)))))
16886 (when org-read-date-analyze-futurep
16887 (setq txt (concat txt " (=>F)")))
16888 (setq org-read-date-overlay
16889 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16890 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16892 (defun org-read-date-analyze (ans def defdecode)
16893 "Analyze the combined answer of the date prompt."
16894 ;; FIXME: cleanup and comment
16895 ;; Pass `current-time' result to `decode-time' (instead of calling
16896 ;; without arguments) so that only `current-time' has to be
16897 ;; overridden in tests.
16898 (let ((org-def def)
16899 (org-defdecode defdecode)
16900 (nowdecode (decode-time (current-time)))
16901 delta deltan deltaw deltadef year month day
16902 hour minute second wday pm h2 m2 tl wday1
16903 iso-year iso-weekday iso-week iso-date futurep kill-year)
16904 (setq org-read-date-analyze-futurep nil
16905 org-read-date-analyze-forced-year nil)
16906 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16907 (setq ans "+0"))
16909 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16910 (setq ans (replace-match "" t t ans)
16911 deltan (car delta)
16912 deltaw (nth 1 delta)
16913 deltadef (nth 2 delta)))
16915 ;; Check if there is an iso week date in there. If yes, store the
16916 ;; info and postpone interpreting it until the rest of the parsing
16917 ;; is done.
16918 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16919 (setq iso-year (when (match-end 1)
16920 (org-small-year-to-year
16921 (string-to-number (match-string 1 ans))))
16922 iso-weekday (when (match-end 3)
16923 (string-to-number (match-string 3 ans)))
16924 iso-week (string-to-number (match-string 2 ans)))
16925 (setq ans (replace-match "" t t ans)))
16927 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16928 (when (string-match
16929 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16930 (setq year (if (match-end 2)
16931 (string-to-number (match-string 2 ans))
16932 (progn (setq kill-year t)
16933 (string-to-number (format-time-string "%Y"))))
16934 month (string-to-number (match-string 3 ans))
16935 day (string-to-number (match-string 4 ans)))
16936 (setq year (org-small-year-to-year year))
16937 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16938 t nil ans)))
16940 ;; Help matching dotted european dates
16941 (when (string-match
16942 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16943 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16944 (setq kill-year t)
16945 (string-to-number (format-time-string "%Y")))
16946 day (string-to-number (match-string 1 ans))
16947 month (string-to-number (match-string 2 ans))
16948 ans (replace-match (format "%04d-%02d-%02d" year month day)
16949 t nil ans)))
16951 ;; Help matching american dates, like 5/30 or 5/30/7
16952 (when (string-match
16953 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16954 (setq year (if (match-end 4)
16955 (string-to-number (match-string 4 ans))
16956 (progn (setq kill-year t)
16957 (string-to-number (format-time-string "%Y"))))
16958 month (string-to-number (match-string 1 ans))
16959 day (string-to-number (match-string 2 ans)))
16960 (setq year (org-small-year-to-year year))
16961 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16962 t nil ans)))
16963 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16964 ;; If there is a time with am/pm, and *no* time without it, we convert
16965 ;; so that matching will be successful.
16966 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16967 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16968 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16969 (setq hour (string-to-number (match-string 1 ans))
16970 minute (if (match-end 3)
16971 (string-to-number (match-string 3 ans))
16973 pm (equal ?p
16974 (string-to-char (downcase (match-string 4 ans)))))
16975 (if (and (= hour 12) (not pm))
16976 (setq hour 0)
16977 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16978 (setq ans (replace-match (format "%02d:%02d" hour minute)
16979 t t ans))))
16981 ;; Check if a time range is given as a duration
16982 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16983 (setq hour (string-to-number (match-string 1 ans))
16984 h2 (+ hour (string-to-number (match-string 3 ans)))
16985 minute (string-to-number (match-string 2 ans))
16986 m2 (+ minute (if (match-end 5) (string-to-number
16987 (match-string 5 ans))0)))
16988 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16989 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16990 t t ans)))
16992 ;; Check if there is a time range
16993 (when (boundp 'org-end-time-was-given)
16994 (setq org-time-was-given nil)
16995 (when (and (string-match org-plain-time-of-day-regexp ans)
16996 (match-end 8))
16997 (setq org-end-time-was-given (match-string 8 ans))
16998 (setq ans (concat (substring ans 0 (match-beginning 7))
16999 (substring ans (match-end 7))))))
17001 (setq tl (parse-time-string ans)
17002 day (or (nth 3 tl) (nth 3 org-defdecode))
17003 month
17004 (cond ((nth 4 tl))
17005 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17006 ;; Day was specified. Make sure DAY+MONTH
17007 ;; combination happens in the future.
17008 ((nth 3 tl)
17009 (setq futurep t)
17010 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17011 (nth 4 nowdecode)))
17012 (t (nth 4 org-defdecode)))
17013 year
17014 (cond ((and (not kill-year) (nth 5 tl)))
17015 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17016 ;; Month was guessed in the future and is at least
17017 ;; equal to NOWDECODE's. Fix year accordingly.
17018 (futurep
17019 (if (or (> month (nth 4 nowdecode))
17020 (>= day (nth 3 nowdecode)))
17021 (nth 5 nowdecode)
17022 (1+ (nth 5 nowdecode))))
17023 ;; Month was specified. Make sure MONTH+YEAR
17024 ;; combination happens in the future.
17025 ((nth 4 tl)
17026 (setq futurep t)
17027 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17028 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17029 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17030 (t (nth 5 nowdecode))))
17031 (t (nth 5 org-defdecode)))
17032 hour (or (nth 2 tl) (nth 2 org-defdecode))
17033 minute (or (nth 1 tl) (nth 1 org-defdecode))
17034 second (or (nth 0 tl) 0)
17035 wday (nth 6 tl))
17037 (when (and (eq org-read-date-prefer-future 'time)
17038 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17039 (equal day (nth 3 nowdecode))
17040 (equal month (nth 4 nowdecode))
17041 (equal year (nth 5 nowdecode))
17042 (nth 2 tl)
17043 (or (< (nth 2 tl) (nth 2 nowdecode))
17044 (and (= (nth 2 tl) (nth 2 nowdecode))
17045 (nth 1 tl)
17046 (< (nth 1 tl) (nth 1 nowdecode)))))
17047 (setq day (1+ day)
17048 futurep t))
17050 ;; Special date definitions below
17051 (cond
17052 (iso-week
17053 ;; There was an iso week
17054 (require 'cal-iso)
17055 (setq futurep nil)
17056 (setq year (or iso-year year)
17057 day (or iso-weekday wday 1)
17058 wday nil ; to make sure that the trigger below does not match
17059 iso-date (calendar-gregorian-from-absolute
17060 (calendar-iso-to-absolute
17061 (list iso-week day year))))
17062 ; FIXME: Should we also push ISO weeks into the future?
17063 ; (when (and org-read-date-prefer-future
17064 ; (not iso-year)
17065 ; (< (calendar-absolute-from-gregorian iso-date)
17066 ; (time-to-days (current-time))))
17067 ; (setq year (1+ year)
17068 ; iso-date (calendar-gregorian-from-absolute
17069 ; (calendar-iso-to-absolute
17070 ; (list iso-week day year)))))
17071 (setq month (car iso-date)
17072 year (nth 2 iso-date)
17073 day (nth 1 iso-date)))
17074 (deltan
17075 (setq futurep nil)
17076 (unless deltadef
17077 ;; Pass `current-time' result to `decode-time' (instead of
17078 ;; calling without arguments) so that only `current-time' has
17079 ;; to be overridden in tests.
17080 (let ((now (decode-time (current-time))))
17081 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17082 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17083 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17084 ((equal deltaw "m") (setq month (+ month deltan)))
17085 ((equal deltaw "y") (setq year (+ year deltan)))))
17086 ((and wday (not (nth 3 tl)))
17087 ;; Weekday was given, but no day, so pick that day in the week
17088 ;; on or after the derived date.
17089 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17090 (unless (equal wday wday1)
17091 (setq day (+ day (% (- wday wday1 -7) 7))))))
17092 (when (and (boundp 'org-time-was-given)
17093 (nth 2 tl))
17094 (setq org-time-was-given t))
17095 (when (< year 100) (setq year (+ 2000 year)))
17096 ;; Check of the date is representable
17097 (if org-read-date-force-compatible-dates
17098 (progn
17099 (when (< year 1970)
17100 (setq year 1970 org-read-date-analyze-forced-year t))
17101 (when (> year 2037)
17102 (setq year 2037 org-read-date-analyze-forced-year t)))
17103 (condition-case nil
17104 (ignore (encode-time second minute hour day month year))
17105 (error
17106 (setq year (nth 5 org-defdecode))
17107 (setq org-read-date-analyze-forced-year t))))
17108 (setq org-read-date-analyze-futurep futurep)
17109 (list second minute hour day month year)))
17111 (defvar parse-time-weekdays)
17112 (defun org-read-date-get-relative (s today default)
17113 "Check string S for special relative date string.
17114 TODAY and DEFAULT are internal times, for today and for a default.
17115 Return shift list (N what def-flag)
17116 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17117 N is the number of WHATs to shift.
17118 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17119 the DEFAULT date rather than TODAY."
17120 (require 'parse-time)
17121 (when (and
17122 (string-match
17123 (concat
17124 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17125 "\\([0-9]+\\)?"
17126 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17127 "\\([ \t]\\|$\\)") s)
17128 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17129 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17130 (string-to-char (substring (match-string 1 s) -1))
17131 ?+))
17132 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17133 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17134 (what (if (match-end 3) (match-string 3 s) "d"))
17135 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17136 (date (if rel default today))
17137 (wday (nth 6 (decode-time date)))
17138 delta)
17139 (if wday1
17140 (progn
17141 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17142 (when (= delta 0) (setq delta 7))
17143 (when (= dir ?-)
17144 (setq delta (- delta 7))
17145 (when (= delta 0) (setq delta -7)))
17146 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17147 (list delta "d" rel))
17148 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17150 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17151 "Turn a user-specified date into the internal representation.
17152 The internal representation needed by the calendar is (month day year).
17153 This is a wrapper to handle the brain-dead convention in calendar that
17154 user function argument order change dependent on argument order."
17155 (pcase calendar-date-style
17156 (`american (list arg1 arg2 arg3))
17157 (`european (list arg2 arg1 arg3))
17158 (`iso (list arg2 arg3 arg1))))
17160 (defun org-eval-in-calendar (form &optional keepdate)
17161 "Eval FORM in the calendar window and return to current window.
17162 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17163 (let ((sf (selected-frame))
17164 (sw (selected-window)))
17165 (select-window (get-buffer-window "*Calendar*" t))
17166 (eval form)
17167 (when (and (not keepdate) (calendar-cursor-to-date))
17168 (let* ((date (calendar-cursor-to-date))
17169 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17170 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17171 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17172 (select-window sw)
17173 (select-frame-set-input-focus sf)))
17175 (defun org-calendar-select ()
17176 "Return to `org-read-date' with the date currently selected.
17177 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17178 (interactive)
17179 (when (calendar-cursor-to-date)
17180 (let* ((date (calendar-cursor-to-date))
17181 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17182 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17183 (when (active-minibuffer-window) (exit-minibuffer))))
17185 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17186 "Insert a date stamp for the date given by the internal TIME.
17187 See `format-time-string' for the format of TIME.
17188 WITH-HM means use the stamp format that includes the time of the day.
17189 INACTIVE means use square brackets instead of angular ones, so that the
17190 stamp will not contribute to the agenda.
17191 PRE and POST are optional strings to be inserted before and after the
17192 stamp.
17193 The command returns the inserted time stamp."
17194 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17195 stamp)
17196 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17197 (insert-before-markers (or pre ""))
17198 (when (listp extra)
17199 (setq extra (car extra))
17200 (if (and (stringp extra)
17201 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17202 (setq extra (format "-%02d:%02d"
17203 (string-to-number (match-string 1 extra))
17204 (string-to-number (match-string 2 extra))))
17205 (setq extra nil)))
17206 (when extra
17207 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17208 (insert-before-markers (setq stamp (format-time-string fmt time)))
17209 (insert-before-markers (or post ""))
17210 (setq org-last-inserted-timestamp stamp)))
17212 (defun org-toggle-time-stamp-overlays ()
17213 "Toggle the use of custom time stamp formats."
17214 (interactive)
17215 (setq org-display-custom-times (not org-display-custom-times))
17216 (unless org-display-custom-times
17217 (let ((p (point-min)) (bmp (buffer-modified-p)))
17218 (while (setq p (next-single-property-change p 'display))
17219 (when (and (get-text-property p 'display)
17220 (eq (get-text-property p 'face) 'org-date))
17221 (remove-text-properties
17222 p (setq p (next-single-property-change p 'display))
17223 '(display t))))
17224 (set-buffer-modified-p bmp)))
17225 (org-restart-font-lock)
17226 (setq org-table-may-need-update t)
17227 (if org-display-custom-times
17228 (message "Time stamps are overlaid with custom format")
17229 (message "Time stamp overlays removed")))
17231 (defun org-display-custom-time (beg end)
17232 "Overlay modified time stamp format over timestamp between BEG and END."
17233 (let* ((ts (buffer-substring beg end))
17234 t1 with-hm tf time str (off 0))
17235 (save-match-data
17236 (setq t1 (org-parse-time-string ts t))
17237 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17238 (setq off (- (match-end 0) (match-beginning 0)))))
17239 (setq end (- end off))
17240 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17241 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17242 time (org-fix-decoded-time t1)
17243 str (org-add-props
17244 (format-time-string
17245 (substring tf 1 -1) (apply 'encode-time time))
17246 nil 'mouse-face 'highlight))
17247 (put-text-property beg end 'display str)))
17249 (defun org-fix-decoded-time (time)
17250 "Set 0 instead of nil for the first 6 elements of time.
17251 Don't touch the rest."
17252 (let ((n 0))
17253 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17255 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17256 "Difference between TIMESTAMP-STRING and now in days.
17257 If SECONDS is non-nil, return the difference in seconds."
17258 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17259 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17260 (funcall fdiff (current-time)))))
17262 (defun org-deadline-close-p (timestamp-string &optional ndays)
17263 "Is the time in TIMESTAMP-STRING close to the current date?"
17264 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17265 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17266 (not (org-entry-is-done-p))))
17268 (defun org-get-wdays (ts &optional delay zero-delay)
17269 "Get the deadline lead time appropriate for timestring TS.
17270 When DELAY is non-nil, get the delay time for scheduled items
17271 instead of the deadline lead time. When ZERO-DELAY is non-nil
17272 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17273 don't try to find the delay cookie in the scheduled timestamp."
17274 (let ((tv (if delay org-scheduled-delay-days
17275 org-deadline-warning-days)))
17276 (cond
17277 ((or (and delay (< tv 0))
17278 (and delay zero-delay (<= tv 0))
17279 (and (not delay) (<= tv 0)))
17280 ;; Enforce this value no matter what
17281 (- tv))
17282 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17283 ;; lead time is specified.
17284 (floor (* (string-to-number (match-string 1 ts))
17285 (cdr (assoc (match-string 2 ts)
17286 '(("d" . 1) ("w" . 7)
17287 ("m" . 30.4) ("y" . 365.25)
17288 ("h" . 0.041667)))))))
17289 ;; go for the default.
17290 (t tv))))
17292 (defun org-calendar-select-mouse (ev)
17293 "Return to `org-read-date' with the date currently selected.
17294 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17295 (interactive "e")
17296 (mouse-set-point ev)
17297 (when (calendar-cursor-to-date)
17298 (let* ((date (calendar-cursor-to-date))
17299 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17300 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17301 (when (active-minibuffer-window) (exit-minibuffer))))
17303 (defun org-check-deadlines (ndays)
17304 "Check if there are any deadlines due or past due.
17305 A deadline is considered due if it happens within `org-deadline-warning-days'
17306 days from today's date. If the deadline appears in an entry marked DONE,
17307 it is not shown. A numeric prefix argument NDAYS can be used to test that
17308 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17309 are shown."
17310 (interactive "P")
17311 (let* ((org-warn-days
17312 (cond
17313 ((equal ndays '(4)) 100000)
17314 (ndays (prefix-numeric-value ndays))
17315 (t (abs org-deadline-warning-days))))
17316 (case-fold-search nil)
17317 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17318 (callback
17319 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17320 (message "%d deadlines past-due or due within %d days"
17321 (org-occur regexp nil callback)
17322 org-warn-days)))
17324 (defsubst org-re-timestamp (type)
17325 "Return a regexp for timestamp TYPE.
17326 Allowed values for TYPE are:
17328 all: all timestamps
17329 active: only active timestamps (<...>)
17330 inactive: only inactive timestamps ([...])
17331 scheduled: only scheduled timestamps
17332 deadline: only deadline timestamps
17333 closed: only closed time-stamps
17335 When TYPE is nil, fall back on returning a regexp that matches
17336 both scheduled and deadline timestamps."
17337 (cl-case type
17338 (all org-ts-regexp-both)
17339 (active org-ts-regexp)
17340 (inactive org-ts-regexp-inactive)
17341 (scheduled org-scheduled-time-regexp)
17342 (deadline org-deadline-time-regexp)
17343 (closed org-closed-time-regexp)
17344 (otherwise
17345 (concat "\\<"
17346 (regexp-opt (list org-deadline-string org-scheduled-string))
17347 " *<\\([^>]+\\)>"))))
17349 (defun org-check-before-date (d)
17350 "Check if there are deadlines or scheduled entries before date D."
17351 (interactive (list (org-read-date)))
17352 (let* ((case-fold-search nil)
17353 (regexp (org-re-timestamp org-ts-type))
17354 (ts-type org-ts-type)
17355 (callback
17356 (lambda ()
17357 (let ((match (match-string 1)))
17358 (and (if (memq ts-type '(active inactive all))
17359 (eq (org-element-type (save-excursion
17360 (backward-char)
17361 (org-element-context)))
17362 'timestamp)
17363 (org-at-planning-p))
17364 (time-less-p
17365 (org-time-string-to-time match t)
17366 (org-time-string-to-time d t)))))))
17367 (message "%d entries before %s"
17368 (org-occur regexp nil callback)
17369 d)))
17371 (defun org-check-after-date (d)
17372 "Check if there are deadlines or scheduled entries after date D."
17373 (interactive (list (org-read-date)))
17374 (let* ((case-fold-search nil)
17375 (regexp (org-re-timestamp org-ts-type))
17376 (ts-type org-ts-type)
17377 (callback
17378 (lambda ()
17379 (let ((match (match-string 1)))
17380 (and (if (memq ts-type '(active inactive all))
17381 (eq (org-element-type (save-excursion
17382 (backward-char)
17383 (org-element-context)))
17384 'timestamp)
17385 (org-at-planning-p))
17386 (not (time-less-p
17387 (org-time-string-to-time match t)
17388 (org-time-string-to-time d t))))))))
17389 (message "%d entries after %s"
17390 (org-occur regexp nil callback)
17391 d)))
17393 (defun org-check-dates-range (start-date end-date)
17394 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17395 (interactive (list (org-read-date nil nil nil "Range starts")
17396 (org-read-date nil nil nil "Range end")))
17397 (let ((case-fold-search nil)
17398 (regexp (org-re-timestamp org-ts-type))
17399 (callback
17400 (let ((type org-ts-type))
17401 (lambda ()
17402 (let ((match (match-string 1)))
17403 (and
17404 (if (memq type '(active inactive all))
17405 (eq (org-element-type (save-excursion
17406 (backward-char)
17407 (org-element-context)))
17408 'timestamp)
17409 (org-at-planning-p))
17410 (not (time-less-p
17411 (org-time-string-to-time match t)
17412 (org-time-string-to-time start-date t)))
17413 (time-less-p
17414 (org-time-string-to-time match t)
17415 (org-time-string-to-time end-date t))))))))
17416 (message "%d entries between %s and %s"
17417 (org-occur regexp nil callback) start-date end-date)))
17419 (defun org-evaluate-time-range (&optional to-buffer)
17420 "Evaluate a time range by computing the difference between start and end.
17421 Normally the result is just printed in the echo area, but with prefix arg
17422 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17423 If the time range is actually in a table, the result is inserted into the
17424 next column.
17425 For time difference computation, a year is assumed to be exactly 365
17426 days in order to avoid rounding problems."
17427 (interactive "P")
17429 (org-clock-update-time-maybe)
17430 (save-excursion
17431 (unless (org-at-date-range-p t)
17432 (goto-char (point-at-bol))
17433 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17434 (unless (org-at-date-range-p t)
17435 (user-error "Not at a time-stamp range, and none found in current line")))
17436 (let* ((ts1 (match-string 1))
17437 (ts2 (match-string 2))
17438 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17439 (match-end (match-end 0))
17440 (time1 (org-time-string-to-time ts1))
17441 (time2 (org-time-string-to-time ts2))
17442 (t1 (float-time time1))
17443 (t2 (float-time time2))
17444 (diff (abs (- t2 t1)))
17445 (negative (< (- t2 t1) 0))
17446 ;; (ys (floor (* 365 24 60 60)))
17447 (ds (* 24 60 60))
17448 (hs (* 60 60))
17449 (fy "%dy %dd %02d:%02d")
17450 (fy1 "%dy %dd")
17451 (fd "%dd %02d:%02d")
17452 (fd1 "%dd")
17453 (fh "%02d:%02d")
17454 y d h m align)
17455 (if havetime
17456 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17458 d (floor (/ diff ds)) diff (mod diff ds)
17459 h (floor (/ diff hs)) diff (mod diff hs)
17460 m (floor (/ diff 60)))
17461 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17463 d (floor (+ (/ diff ds) 0.5))
17464 h 0 m 0))
17465 (if (not to-buffer)
17466 (message "%s" (org-make-tdiff-string y d h m))
17467 (if (org-at-table-p)
17468 (progn
17469 (goto-char match-end)
17470 (setq align t)
17471 (and (looking-at " *|") (goto-char (match-end 0))))
17472 (goto-char match-end))
17473 (when (looking-at
17474 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17475 (replace-match ""))
17476 (when negative (insert " -"))
17477 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17478 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17479 (insert " " (format fh h m))))
17480 (when align (org-table-align))
17481 (message "Time difference inserted")))))
17483 (defun org-make-tdiff-string (y d h m)
17484 (let ((fmt "")
17485 (l nil))
17486 (when (> y 0)
17487 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17488 (push y l))
17489 (when (> d 0)
17490 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17491 (push d l))
17492 (when (> h 0)
17493 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17494 (push h l))
17495 (when (> m 0)
17496 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17497 (push m l))
17498 (apply 'format fmt (nreverse l))))
17500 (defun org-time-string-to-time (s &optional zone)
17501 "Convert timestamp string S into internal time.
17502 The optional ZONE is omitted or nil for Emacs local time, t for
17503 Universal Time, ‘wall’ for system wall clock time, or a string as
17504 in the TZ environment variable."
17505 (apply #'encode-time (org-parse-time-string s nil zone)))
17507 (defun org-time-string-to-seconds (s &optional zone)
17508 "Convert a timestamp string S into a number of seconds.
17509 The optional ZONE is omitted or nil for Emacs local time, t for
17510 Universal Time, ‘wall’ for system wall clock time, or a string as
17511 in the TZ environment variable."
17512 (float-time (org-time-string-to-time s zone)))
17514 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17516 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17517 "Convert time stamp S to an absolute day number.
17519 If DAYNR in non-nil, and there is a specifier for a cyclic time
17520 stamp, get the closest date to DAYNR. If PREFER is
17521 `past' (respectively `future') return a date past (respectively
17522 after) or equal to DAYNR.
17524 POS is the location of time stamp S, as a buffer position in
17525 BUFFER.
17527 Diary sexp timestamps are matched against DAYNR, when non-nil.
17528 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17529 signaled."
17530 (cond
17531 ((string-match "\\`%%\\((.*)\\)" s)
17532 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17533 ;; only able to match individual dates. If it fails, raise an
17534 ;; error.
17535 (if (and daynr
17536 (org-diary-sexp-entry
17537 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17538 daynr
17539 (signal 'org-diary-sexp-no-match (list s))))
17540 (daynr (org-closest-date s daynr prefer))
17541 (t (time-to-days
17542 (condition-case errdata
17543 (apply #'encode-time (org-parse-time-string s))
17544 (error (error "Bad timestamp `%s'%s\nError was: %s"
17546 (if (not (and buffer pos)) ""
17547 (format-message " at %d in buffer `%s'" pos buffer))
17548 (cdr errdata))))))))
17550 (defun org-days-to-iso-week (days)
17551 "Return the iso week number."
17552 (require 'cal-iso)
17553 (car (calendar-iso-from-absolute days)))
17555 (defun org-small-year-to-year (year)
17556 "Convert 2-digit years into 4-digit years.
17557 YEAR is expanded into one of the 30 next years, if possible, or
17558 into a past one. Any year larger than 99 is returned unchanged."
17559 (if (>= year 100) year
17560 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17561 (century (/ current 100))
17562 (offset (- year (% current 100))))
17563 (cond ((> offset 30) (+ (* (1- century) 100) year))
17564 ((> offset -70) (+ (* century 100) year))
17565 (t (+ (* (1+ century) 100) year))))))
17567 (defun org-time-from-absolute (d)
17568 "Return the time corresponding to date D.
17569 D may be an absolute day number, or a calendar-type list (month day year)."
17570 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17571 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17573 (defvar org-agenda-current-date)
17574 (defun org-calendar-holiday ()
17575 "List of holidays, for Diary display in Org mode."
17576 (require 'holidays)
17577 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17578 (and hl (mapconcat #'identity hl "; "))))
17580 (defun org-diary-sexp-entry (sexp entry d)
17581 "Process a SEXP diary ENTRY for date D."
17582 (require 'diary-lib)
17583 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17584 ;; dynamically.
17585 (let* ((sexp `(let ((entry ,entry)
17586 (date ',d))
17587 ,(car (read-from-string sexp))))
17588 (result (if calendar-debug-sexp (eval sexp)
17589 (condition-case nil
17590 (eval sexp)
17591 (error
17592 (beep)
17593 (message "Bad sexp at line %d in %s: %s"
17594 (org-current-line)
17595 (buffer-file-name) sexp)
17596 (sleep-for 2))))))
17597 (cond ((stringp result) (split-string result "; "))
17598 ((and (consp result)
17599 (not (consp (cdr result)))
17600 (stringp (cdr result))) (cdr result))
17601 ((and (consp result)
17602 (stringp (car result))) result)
17603 (result entry))))
17605 (defun org-diary-to-ical-string (frombuf)
17606 "Get iCalendar entries from diary entries in buffer FROMBUF.
17607 This uses the icalendar.el library."
17608 (let* ((tmpdir temporary-file-directory)
17609 (tmpfile (make-temp-name
17610 (expand-file-name "orgics" tmpdir)))
17611 buf rtn b e)
17612 (with-current-buffer frombuf
17613 (icalendar-export-region (point-min) (point-max) tmpfile)
17614 (setq buf (find-buffer-visiting tmpfile))
17615 (set-buffer buf)
17616 (goto-char (point-min))
17617 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17618 (setq b (match-beginning 0)))
17619 (goto-char (point-max))
17620 (when (re-search-backward "^END:VEVENT" nil t)
17621 (setq e (match-end 0)))
17622 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17623 (kill-buffer buf)
17624 (delete-file tmpfile)
17625 rtn))
17627 (defun org-closest-date (start current prefer)
17628 "Return closest date to CURRENT starting from START.
17630 CURRENT and START are both time stamps.
17632 When PREFER is `past', return a date that is either CURRENT or
17633 past. When PREFER is `future', return a date that is either
17634 CURRENT or future.
17636 Only time stamps with a repeater are modified. Any other time
17637 stamp stay unchanged. In any case, return value is an absolute
17638 day number."
17639 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17640 ;; No repeater. Do not shift time stamp.
17641 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17642 (let ((value (string-to-number (match-string 1 start)))
17643 (type (match-string 2 start)))
17644 (if (= 0 value)
17645 ;; Repeater with a 0-value is considered as void.
17646 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17647 (let* ((base (org-date-to-gregorian start))
17648 (target (org-date-to-gregorian current))
17649 (sday (calendar-absolute-from-gregorian base))
17650 (cday (calendar-absolute-from-gregorian target))
17651 n1 n2)
17652 ;; If START is already past CURRENT, just return START.
17653 (if (<= cday sday) sday
17654 ;; Compute closest date before (N1) and closest date past
17655 ;; (N2) CURRENT.
17656 (pcase type
17657 ("h"
17658 (let ((missing-hours
17659 (mod (+ (- (* 24 (- cday sday))
17660 (nth 2 (org-parse-time-string start)))
17661 org-extend-today-until)
17662 value)))
17663 (setf n1 (if (= missing-hours 0) cday
17664 (- cday (1+ (/ missing-hours 24)))))
17665 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17666 ((or "d" "w")
17667 (let ((value (if (equal type "w") (* 7 value) value)))
17668 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17669 (setf n2 (+ n1 value))))
17670 ("m"
17671 (let* ((add-months
17672 (lambda (d n)
17673 ;; Add N months to gregorian date D, i.e.,
17674 ;; a list (MONTH DAY YEAR). Return a valid
17675 ;; gregorian date.
17676 (let ((m (+ (nth 0 d) n)))
17677 (list (mod m 12)
17678 (nth 1 d)
17679 (+ (/ m 12) (nth 2 d))))))
17680 (months ; Complete months to TARGET.
17681 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17682 (- (nth 0 target) (nth 0 base))
17683 ;; If START's day is greater than
17684 ;; TARGET's, remove incomplete month.
17685 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17686 value)
17687 value))
17688 (before (funcall add-months base months)))
17689 (setf n1 (calendar-absolute-from-gregorian before))
17690 (setf n2
17691 (calendar-absolute-from-gregorian
17692 (funcall add-months before value)))))
17694 (let* ((d (nth 1 base))
17695 (m (nth 0 base))
17696 (y (nth 2 base))
17697 (years ; Complete years to TARGET.
17698 (* (/ (- (nth 2 target)
17700 ;; If START's month and day are
17701 ;; greater than TARGET's, remove
17702 ;; incomplete year.
17703 (if (or (> (nth 0 target) m)
17704 (and (= (nth 0 target) m)
17705 (> (nth 1 target) d)))
17708 value)
17709 value))
17710 (before (list m d (+ y years))))
17711 (setf n1 (calendar-absolute-from-gregorian before))
17712 (setf n2 (calendar-absolute-from-gregorian
17713 (list m d (+ (nth 2 before) value)))))))
17714 ;; Handle PREFER parameter, if any.
17715 (cond
17716 ((eq prefer 'past) (if (= cday n2) n2 n1))
17717 ((eq prefer 'future) (if (= cday n1) n1 n2))
17718 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17720 (defun org-date-to-gregorian (d)
17721 "Turn any specification of date D into a Gregorian date for the calendar."
17722 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17723 ((and (listp d) (= (length d) 3)) d)
17724 ((stringp d)
17725 (let ((d (org-parse-time-string d)))
17726 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17727 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17729 (defun org-parse-time-string (s &optional nodefault zone)
17730 "Parse the standard Org time string.
17732 This should be a lot faster than the normal `parse-time-string'.
17734 If time is not given, defaults to 0:00. However, with optional
17735 NODEFAULT, hour and minute fields will be nil if not given.
17737 The optional ZONE is omitted or nil for Emacs local time, t for
17738 Universal Time, ‘wall’ for system wall clock time, or a string as
17739 in the TZ environment variable."
17740 (cond ((string-match org-ts-regexp0 s)
17741 (list 0
17742 (when (or (match-beginning 8) (not nodefault))
17743 (string-to-number (or (match-string 8 s) "0")))
17744 (when (or (match-beginning 7) (not nodefault))
17745 (string-to-number (or (match-string 7 s) "0")))
17746 (string-to-number (match-string 4 s))
17747 (string-to-number (match-string 3 s))
17748 (string-to-number (match-string 2 s))
17749 nil nil zone))
17750 ((string-match "^<[^>]+>$" s)
17751 ;; FIXME: `decode-time' needs to be called with ZONE as its
17752 ;; second argument. However, this requires at least Emacs
17753 ;; 25.1. We can do it when we switch to this version as our
17754 ;; minimal requirement.
17755 (decode-time (seconds-to-time (org-matcher-time s))))
17756 (t (error "Not a standard Org time string: %s" s))))
17758 (defun org-timestamp-up (&optional arg)
17759 "Increase the date item at the cursor by one.
17760 If the cursor is on the year, change the year. If it is on the month,
17761 the day or the time, change that.
17762 With prefix ARG, change by that many units."
17763 (interactive "p")
17764 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17766 (defun org-timestamp-down (&optional arg)
17767 "Decrease the date item at the cursor by one.
17768 If the cursor is on the year, change the year. If it is on the month,
17769 the day or the time, change that.
17770 With prefix ARG, change by that many units."
17771 (interactive "p")
17772 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17774 (defun org-timestamp-up-day (&optional arg)
17775 "Increase the date in the time stamp by one day.
17776 With prefix ARG, change that many days."
17777 (interactive "p")
17778 (if (and (not (org-at-timestamp-p 'lax))
17779 (org-at-heading-p))
17780 (org-todo 'up)
17781 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17783 (defun org-timestamp-down-day (&optional arg)
17784 "Decrease the date in the time stamp by one day.
17785 With prefix ARG, change that many days."
17786 (interactive "p")
17787 (if (and (not (org-at-timestamp-p 'lax))
17788 (org-at-heading-p))
17789 (org-todo 'down)
17790 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17792 (defun org-at-timestamp-p (&optional extended)
17793 "Non-nil if point is inside a timestamp.
17795 By default, the function only consider syntactically valid active
17796 timestamps. However, the caller may have a broader definition
17797 for timestamps. As a consequence, optional argument EXTENDED can
17798 be set to the following values
17800 `inactive'
17802 Include also syntactically valid inactive timestamps.
17804 `agenda'
17806 Include timestamps allowed in Agenda, i.e., those in
17807 properties drawers, planning lines and clock lines.
17809 `lax'
17811 Ignore context. The function matches any part of the
17812 document looking like a timestamp. This includes comments,
17813 example blocks...
17815 For backward-compatibility with Org 9.0, every other non-nil
17816 value is equivalent to `inactive'.
17818 When at a timestamp, return the position of the point as a symbol
17819 among `bracket', `after', `year', `month', `hour', `minute',
17820 `day' or a number of character from the last know part of the
17821 time stamp.
17823 When matching, the match groups are the following:
17824 group 1: year
17825 group 2: month
17826 group 3: day number
17827 group 4: day name
17828 group 5: hours, if any
17829 group 6: minutes, if any"
17830 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17831 (pos (point))
17832 (match?
17833 (let ((boundaries (org-in-regexp regexp)))
17834 (save-match-data
17835 (cond ((null boundaries) nil)
17836 ((eq extended 'lax) t)
17838 (or (and (eq extended 'agenda)
17839 (or (org-at-planning-p)
17840 (org-at-property-p)
17841 (and (bound-and-true-p
17842 org-agenda-include-inactive-timestamps)
17843 (org-at-clock-log-p))))
17844 (eq 'timestamp
17845 (save-excursion
17846 (when (= pos (cdr boundaries)) (forward-char -1))
17847 (org-element-type (org-element-context)))))))))))
17848 (cond
17849 ((not match?) nil)
17850 ((= pos (match-beginning 0)) 'bracket)
17851 ;; Distinguish location right before the closing bracket from
17852 ;; right after it.
17853 ((= pos (1- (match-end 0))) 'bracket)
17854 ((= pos (match-end 0)) 'after)
17855 ((org-pos-in-match-range pos 2) 'year)
17856 ((org-pos-in-match-range pos 3) 'month)
17857 ((org-pos-in-match-range pos 7) 'hour)
17858 ((org-pos-in-match-range pos 8) 'minute)
17859 ((or (org-pos-in-match-range pos 4)
17860 (org-pos-in-match-range pos 5)) 'day)
17861 ((and (> pos (or (match-end 8) (match-end 5)))
17862 (< pos (match-end 0)))
17863 (- pos (or (match-end 8) (match-end 5))))
17864 (t 'day))))
17866 (defun org-toggle-timestamp-type ()
17867 "Toggle the type (<active> or [inactive]) of a time stamp."
17868 (interactive)
17869 (when (org-at-timestamp-p 'lax)
17870 (let ((beg (match-beginning 0)) (end (match-end 0))
17871 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17872 (save-excursion
17873 (goto-char beg)
17874 (while (re-search-forward "[][<>]" end t)
17875 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17876 t t)))
17877 (message "Timestamp is now %sactive"
17878 (if (equal (char-after beg) ?<) "" "in")))))
17880 (defun org-at-clock-log-p ()
17881 "Non-nil if point is on a clock log line."
17882 (and (org-match-line org-clock-line-re)
17883 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17885 (defvar org-clock-history) ; defined in org-clock.el
17886 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17887 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17888 "Change the date in the time stamp at point.
17889 The date will be changed by N times WHAT. WHAT can be `day', `month',
17890 `year', `minute', `second'. If WHAT is not given, the cursor position
17891 in the timestamp determines what will be changed.
17892 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17893 (let ((origin (point))
17894 (timestamp? (org-at-timestamp-p 'lax))
17895 origin-cat
17896 with-hm inactive
17897 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17898 extra rem
17899 ts time time0 fixnext clrgx)
17900 (unless timestamp? (user-error "Not at a timestamp"))
17901 (if (and (not what) (eq timestamp? 'bracket))
17902 (org-toggle-timestamp-type)
17903 ;; Point isn't on brackets. Remember the part of the time-stamp
17904 ;; the point was in. Indeed, size of time-stamps may change,
17905 ;; but point must be kept in the same category nonetheless.
17906 (setq origin-cat timestamp?)
17907 (when (and (not what) (not (eq timestamp? 'day))
17908 org-display-custom-times
17909 (get-text-property (point) 'display)
17910 (not (get-text-property (1- (point)) 'display)))
17911 (setq timestamp? 'day))
17912 (setq timestamp? (or what timestamp?)
17913 inactive (= (char-after (match-beginning 0)) ?\[)
17914 ts (match-string 0))
17915 (replace-match "")
17916 (when (string-match
17917 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17919 (setq extra (match-string 1 ts))
17920 (when suppress-tmp-delay
17921 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17922 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17923 (setq with-hm t))
17924 (setq time0 (org-parse-time-string ts))
17925 (when (and updown
17926 (eq timestamp? 'minute)
17927 (not current-prefix-arg))
17928 ;; This looks like s-up and s-down. Change by one rounding step.
17929 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17930 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17931 (setcar (cdr time0) (+ (nth 1 time0)
17932 (if (> n 0) (- rem) (- dm rem))))))
17933 (setq time
17934 (apply #'encode-time
17935 (or (car time0) 0)
17936 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17937 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17938 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17939 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17940 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17941 (nthcdr 6 time0)))
17942 (when (and (memq timestamp? '(hour minute))
17943 extra
17944 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17945 (setq extra (org-modify-ts-extra
17946 extra
17947 (if (eq timestamp? 'hour) 2 5)
17948 n dm)))
17949 (when (integerp timestamp?)
17950 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17951 (when (eq what 'calendar)
17952 (let ((cal-date (org-get-date-from-calendar)))
17953 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17954 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17955 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17956 (setcar time0 (or (car time0) 0))
17957 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17958 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17959 (setq time (apply 'encode-time time0))))
17960 ;; Insert the new time-stamp, and ensure point stays in the same
17961 ;; category as before (i.e. not after the last position in that
17962 ;; category).
17963 (let ((pos (point)))
17964 ;; Stay before inserted string. `save-excursion' is of no use.
17965 (setq org-last-changed-timestamp
17966 (org-insert-time-stamp time with-hm inactive nil nil extra))
17967 (goto-char pos))
17968 (save-match-data
17969 (looking-at org-ts-regexp3)
17970 (goto-char
17971 (pcase origin-cat
17972 ;; `day' category ends before `hour' if any, or at the end
17973 ;; of the day name.
17974 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17975 (`hour (min (match-end 7) origin))
17976 (`minute (min (1- (match-end 8)) origin))
17977 ((pred integerp) (min (1- (match-end 0)) origin))
17978 ;; Point was right after the time-stamp. However, the
17979 ;; time-stamp length might have changed, so refer to
17980 ;; (match-end 0) instead.
17981 (`after (match-end 0))
17982 ;; `year' and `month' have both fixed size: point couldn't
17983 ;; have moved into another part.
17984 (_ origin))))
17985 ;; Update clock if on a CLOCK line.
17986 (org-clock-update-time-maybe)
17987 ;; Maybe adjust the closest clock in `org-clock-history'
17988 (when org-clock-adjust-closest
17989 (if (not (and (org-at-clock-log-p)
17990 (< 1 (length (delq nil (mapcar 'marker-position
17991 org-clock-history))))))
17992 (message "No clock to adjust")
17993 (cond ((save-excursion ; fix previous clock?
17994 (re-search-backward org-ts-regexp0 nil t)
17995 (looking-back (concat org-clock-string " \\[")
17996 (line-beginning-position)))
17997 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17998 ((save-excursion ; fix next clock?
17999 (re-search-backward org-ts-regexp0 nil t)
18000 (looking-at (concat org-ts-regexp0 "\\] =>")))
18001 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18002 (save-window-excursion
18003 ;; Find closest clock to point, adjust the previous/next one in history
18004 (let* ((p (save-excursion (org-back-to-heading t)))
18005 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18006 (clfixnth
18007 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18008 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18009 (if (not clfixpos)
18010 (message "No clock to adjust")
18011 (save-excursion
18012 (org-goto-marker-or-bmk clfixpos)
18013 (org-show-subtree)
18014 (when (re-search-forward clrgx nil t)
18015 (goto-char (match-beginning 1))
18016 (let (org-clock-adjust-closest)
18017 (org-timestamp-change n timestamp? updown))
18018 (message "Clock adjusted in %s for heading: %s"
18019 (file-name-nondirectory (buffer-file-name))
18020 (org-get-heading t t)))))))))
18021 ;; Try to recenter the calendar window, if any.
18022 (when (and org-calendar-follow-timestamp-change
18023 (get-buffer-window "*Calendar*" t)
18024 (memq timestamp? '(day month year)))
18025 (org-recenter-calendar (time-to-days time))))))
18027 (defun org-modify-ts-extra (s pos n dm)
18028 "Change the different parts of the lead-time and repeat fields in timestamp."
18029 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18030 ng h m new rem)
18031 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18032 (cond
18033 ((or (org-pos-in-match-range pos 2)
18034 (org-pos-in-match-range pos 3))
18035 (setq m (string-to-number (match-string 3 s))
18036 h (string-to-number (match-string 2 s)))
18037 (if (org-pos-in-match-range pos 2)
18038 (setq h (+ h n))
18039 (setq n (* dm (with-no-warnings (signum n))))
18040 (unless (= 0 (setq rem (% m dm)))
18041 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18042 (setq m (+ m n)))
18043 (when (< m 0) (setq m (+ m 60) h (1- h)))
18044 (when (> m 59) (setq m (- m 60) h (1+ h)))
18045 (setq h (mod h 24))
18046 (setq ng 1 new (format "-%02d:%02d" h m)))
18047 ((org-pos-in-match-range pos 6)
18048 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18049 ((org-pos-in-match-range pos 5)
18050 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18052 ((org-pos-in-match-range pos 9)
18053 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18054 ((org-pos-in-match-range pos 8)
18055 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18057 (when ng
18058 (setq s (concat
18059 (substring s 0 (match-beginning ng))
18061 (substring s (match-end ng))))))
18064 (defun org-recenter-calendar (d)
18065 "If the calendar is visible, recenter it to date D."
18066 (let ((cwin (get-buffer-window "*Calendar*" t)))
18067 (when cwin
18068 (let ((calendar-move-hook nil))
18069 (with-selected-window cwin
18070 (calendar-goto-date
18071 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18073 (defun org-goto-calendar (&optional arg)
18074 "Go to the Emacs calendar at the current date.
18075 If there is a time stamp in the current line, go to that date.
18076 A prefix ARG can be used to force the current date."
18077 (interactive "P")
18078 (let ((calendar-move-hook nil)
18079 (calendar-view-holidays-initially-flag nil)
18080 (calendar-view-diary-initially-flag nil)
18081 diff)
18082 (when (or (org-at-timestamp-p 'lax)
18083 (org-match-line (concat ".*" org-ts-regexp)))
18084 (let ((d1 (time-to-days (current-time)))
18085 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18086 (setq diff (- d2 d1))))
18087 (calendar)
18088 (calendar-goto-today)
18089 (when (and diff (not arg)) (calendar-forward-day diff))))
18091 (defun org-get-date-from-calendar ()
18092 "Return a list (month day year) of date at point in calendar."
18093 (with-current-buffer "*Calendar*"
18094 (save-match-data
18095 (calendar-cursor-to-date))))
18097 (defun org-date-from-calendar ()
18098 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18099 If there is already a time stamp at the cursor position, update it."
18100 (interactive)
18101 (if (org-at-timestamp-p 'lax)
18102 (org-timestamp-change 0 'calendar)
18103 (let ((cal-date (org-get-date-from-calendar)))
18104 (org-insert-time-stamp
18105 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18107 (defcustom org-effort-durations
18108 `(("min" . 1)
18109 ("h" . 60)
18110 ("d" . ,(* 60 8))
18111 ("w" . ,(* 60 8 5))
18112 ("m" . ,(* 60 8 5 4))
18113 ("y" . ,(* 60 8 5 40)))
18114 "Conversion factor to minutes for an effort modifier.
18116 Each entry has the form (MODIFIER . MINUTES).
18118 In an effort string, a number followed by MODIFIER is multiplied
18119 by the specified number of MINUTES to obtain an effort in
18120 minutes.
18122 For example, if the value of this variable is ((\"hours\" . 60)), then an
18123 effort string \"2hours\" is equivalent to 120 minutes."
18124 :group 'org-agenda
18125 :version "26.1"
18126 :package-version '(Org . "8.3")
18127 :type '(alist :key-type (string :tag "Modifier")
18128 :value-type (number :tag "Minutes")))
18130 (defcustom org-image-actual-width t
18131 "Should we use the actual width of images when inlining them?
18133 When set to t, always use the image width.
18135 When set to a number, use imagemagick (when available) to set
18136 the image's width to this value.
18138 When set to a number in a list, try to get the width from any
18139 #+ATTR.* keyword if it matches a width specification like
18141 #+ATTR_HTML: :width 300px
18143 and fall back on that number if none is found.
18145 When set to nil, try to get the width from an #+ATTR.* keyword
18146 and fall back on the original width if none is found.
18148 This requires Emacs >= 24.1, build with imagemagick support."
18149 :group 'org-appearance
18150 :version "24.4"
18151 :package-version '(Org . "8.0")
18152 :type '(choice
18153 (const :tag "Use the image width" t)
18154 (integer :tag "Use a number of pixels")
18155 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18156 (const :tag "Use #+ATTR* or don't resize" nil)))
18158 (defcustom org-agenda-inhibit-startup nil
18159 "Inhibit startup when preparing agenda buffers.
18160 When this variable is t, the initialization of the Org agenda
18161 buffers is inhibited: e.g. the visibility state is not set, the
18162 tables are not re-aligned, etc."
18163 :type 'boolean
18164 :version "24.3"
18165 :group 'org-agenda)
18167 (defcustom org-agenda-ignore-properties nil
18168 "Avoid updating text properties when building the agenda.
18169 Properties are used to prepare buffers for effort estimates,
18170 appointments, statistics and subtree-local categories.
18171 If you don't use these in the agenda, you can add them to this
18172 list and agenda building will be a bit faster.
18173 The value is a list, with zero or more of the symbols `effort', `appt',
18174 `stats' or `category'."
18175 :type '(set :greedy t
18176 (const effort)
18177 (const appt)
18178 (const stats)
18179 (const category))
18180 :version "26.1"
18181 :package-version '(Org . "8.3")
18182 :group 'org-agenda)
18184 ;;;; Files
18186 (defun org-save-all-org-buffers ()
18187 "Save all Org buffers without user confirmation."
18188 (interactive)
18189 (message "Saving all Org buffers...")
18190 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18191 (when (featurep 'org-id) (org-id-locations-save))
18192 (message "Saving all Org buffers... done"))
18194 (defun org-revert-all-org-buffers ()
18195 "Revert all Org buffers.
18196 Prompt for confirmation when there are unsaved changes.
18197 Be sure you know what you are doing before letting this function
18198 overwrite your changes.
18200 This function is useful in a setup where one tracks org files
18201 with a version control system, to revert on one machine after pulling
18202 changes from another. I believe the procedure must be like this:
18204 1. M-x org-save-all-org-buffers
18205 2. Pull changes from the other machine, resolve conflicts
18206 3. M-x org-revert-all-org-buffers"
18207 (interactive)
18208 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18209 (user-error "Abort"))
18210 (save-excursion
18211 (save-window-excursion
18212 (dolist (b (buffer-list))
18213 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18214 (with-current-buffer b buffer-file-name))
18215 (pop-to-buffer-same-window b)
18216 (revert-buffer t 'no-confirm)))
18217 (when (and (featurep 'org-id) org-id-track-globally)
18218 (org-id-locations-load)))))
18220 ;;;; Agenda files
18222 ;;;###autoload
18223 (defun org-switchb (&optional arg)
18224 "Switch between Org buffers.
18226 With `\\[universal-argument]' prefix, restrict available buffers to files.
18228 With `\\[universal-argument] \\[universal-argument]' \
18229 prefix, restrict available buffers to agenda files."
18230 (interactive "P")
18231 (let ((blist (org-buffer-list
18232 (cond ((equal arg '(4)) 'files)
18233 ((equal arg '(16)) 'agenda)))))
18234 (pop-to-buffer-same-window
18235 (completing-read "Org buffer: "
18236 (mapcar #'list (mapcar #'buffer-name blist))
18237 nil t))))
18239 (defun org-buffer-list (&optional predicate exclude-tmp)
18240 "Return a list of Org buffers.
18241 PREDICATE can be `export', `files' or `agenda'.
18243 export restrict the list to Export buffers.
18244 files restrict the list to buffers visiting Org files.
18245 agenda restrict the list to buffers visiting agenda files.
18247 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18248 (let* ((bfn nil)
18249 (agenda-files (and (eq predicate 'agenda)
18250 (mapcar 'file-truename (org-agenda-files t))))
18251 (filter
18252 (cond
18253 ((eq predicate 'files)
18254 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18255 ((eq predicate 'export)
18256 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18257 ((eq predicate 'agenda)
18258 (lambda (b)
18259 (with-current-buffer b
18260 (and (derived-mode-p 'org-mode)
18261 (setq bfn (buffer-file-name b))
18262 (member (file-truename bfn) agenda-files)))))
18263 (t (lambda (b) (with-current-buffer b
18264 (or (derived-mode-p 'org-mode)
18265 (string-match "\\*Org .*Export"
18266 (buffer-name b)))))))))
18267 (delq nil
18268 (mapcar
18269 (lambda(b)
18270 (if (and (funcall filter b)
18271 (or (not exclude-tmp)
18272 (not (string-match "tmp" (buffer-name b)))))
18274 nil))
18275 (buffer-list)))))
18277 (defun org-agenda-files (&optional unrestricted archives)
18278 "Get the list of agenda files.
18279 Optional UNRESTRICTED means return the full list even if a restriction
18280 is currently in place.
18281 When ARCHIVES is t, include all archive files that are really being
18282 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18283 `org-agenda-archives-mode' is t."
18284 (let ((files
18285 (cond
18286 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18287 ((stringp org-agenda-files) (org-read-agenda-file-list))
18288 ((listp org-agenda-files) org-agenda-files)
18289 (t (error "Invalid value of `org-agenda-files'")))))
18290 (setq files (apply 'append
18291 (mapcar (lambda (f)
18292 (if (file-directory-p f)
18293 (directory-files
18294 f t org-agenda-file-regexp)
18295 (list f)))
18296 files)))
18297 (when org-agenda-skip-unavailable-files
18298 (setq files (delq nil
18299 (mapcar (function
18300 (lambda (file)
18301 (and (file-readable-p file) file)))
18302 files))))
18303 (when (or (eq archives t)
18304 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18305 (setq files (org-add-archive-files files)))
18306 files))
18308 (defun org-agenda-file-p (&optional file)
18309 "Return non-nil, if FILE is an agenda file.
18310 If FILE is omitted, use the file associated with the current
18311 buffer."
18312 (let ((fname (or file (buffer-file-name))))
18313 (and fname
18314 (member (file-truename fname)
18315 (mapcar #'file-truename (org-agenda-files t))))))
18317 (defun org-edit-agenda-file-list ()
18318 "Edit the list of agenda files.
18319 Depending on setup, this either uses customize to edit the variable
18320 `org-agenda-files', or it visits the file that is holding the list. In the
18321 latter case, the buffer is set up in a way that saving it automatically kills
18322 the buffer and restores the previous window configuration."
18323 (interactive)
18324 (if (stringp org-agenda-files)
18325 (let ((cw (current-window-configuration)))
18326 (find-file org-agenda-files)
18327 (setq-local org-window-configuration cw)
18328 (add-hook 'after-save-hook
18329 (lambda ()
18330 (set-window-configuration
18331 (prog1 org-window-configuration
18332 (kill-buffer (current-buffer))))
18333 (org-install-agenda-files-menu)
18334 (message "New agenda file list installed"))
18335 nil 'local)
18336 (message "%s" (substitute-command-keys
18337 "Edit list and finish with \\[save-buffer]")))
18338 (customize-variable 'org-agenda-files)))
18340 (defun org-store-new-agenda-file-list (list)
18341 "Set new value for the agenda file list and save it correctly."
18342 (if (stringp org-agenda-files)
18343 (let ((fe (org-read-agenda-file-list t)) b u)
18344 (while (setq b (find-buffer-visiting org-agenda-files))
18345 (kill-buffer b))
18346 (with-temp-file org-agenda-files
18347 (insert
18348 (mapconcat
18349 (lambda (f) ;; Keep un-expanded entries.
18350 (if (setq u (assoc f fe))
18351 (cdr u)
18353 list "\n")
18354 "\n")))
18355 (let ((org-mode-hook nil) (org-inhibit-startup t)
18356 (org-insert-mode-line-in-empty-file nil))
18357 (setq org-agenda-files list)
18358 (customize-save-variable 'org-agenda-files org-agenda-files))))
18360 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18361 "Read the list of agenda files from a file.
18362 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18363 filenames, used by `org-store-new-agenda-file-list' to write back
18364 un-expanded file names."
18365 (when (file-directory-p org-agenda-files)
18366 (error "`org-agenda-files' cannot be a single directory"))
18367 (when (stringp org-agenda-files)
18368 (with-temp-buffer
18369 (insert-file-contents org-agenda-files)
18370 (mapcar
18371 (lambda (f)
18372 (let ((e (expand-file-name (substitute-in-file-name f)
18373 org-directory)))
18374 (if pair-with-expansion
18375 (cons e f)
18376 e)))
18377 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18379 ;;;###autoload
18380 (defun org-cycle-agenda-files ()
18381 "Cycle through the files in `org-agenda-files'.
18382 If the current buffer visits an agenda file, find the next one in the list.
18383 If the current buffer does not, find the first agenda file."
18384 (interactive)
18385 (let* ((fs (or (org-agenda-files t)
18386 (user-error "No agenda files")))
18387 (files (copy-sequence fs))
18388 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18389 file)
18390 (when tcf
18391 (while (and (setq file (pop files))
18392 (not (equal (file-truename file) tcf)))))
18393 (find-file (car (or files fs)))
18394 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18396 (defun org-agenda-file-to-front (&optional to-end)
18397 "Move/add the current file to the top of the agenda file list.
18398 If the file is not present in the list, it is added to the front. If it is
18399 present, it is moved there. With optional argument TO-END, add/move to the
18400 end of the list."
18401 (interactive "P")
18402 (let ((org-agenda-skip-unavailable-files nil)
18403 (file-alist (mapcar (lambda (x)
18404 (cons (file-truename x) x))
18405 (org-agenda-files t)))
18406 (ctf (file-truename
18407 (or buffer-file-name
18408 (user-error "Please save the current buffer to a file"))))
18409 x had)
18410 (setq x (assoc ctf file-alist) had x)
18412 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18413 (if to-end
18414 (setq file-alist (append (delq x file-alist) (list x)))
18415 (setq file-alist (cons x (delq x file-alist))))
18416 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18417 (org-install-agenda-files-menu)
18418 (message "File %s to %s of agenda file list"
18419 (if had "moved" "added") (if to-end "end" "front"))))
18421 (defun org-remove-file (&optional file)
18422 "Remove current file from the list of files in variable `org-agenda-files'.
18423 These are the files which are being checked for agenda entries.
18424 Optional argument FILE means use this file instead of the current."
18425 (interactive)
18426 (let* ((org-agenda-skip-unavailable-files nil)
18427 (file (or file buffer-file-name
18428 (user-error "Current buffer does not visit a file")))
18429 (true-file (file-truename file))
18430 (afile (abbreviate-file-name file))
18431 (files (delq nil (mapcar
18432 (lambda (x)
18433 (unless (equal true-file
18434 (file-truename x))
18436 (org-agenda-files t)))))
18437 (if (not (= (length files) (length (org-agenda-files t))))
18438 (progn
18439 (org-store-new-agenda-file-list files)
18440 (org-install-agenda-files-menu)
18441 (message "Removed from Org Agenda list: %s" afile))
18442 (message "File was not in list: %s (not removed)" afile))))
18444 (defun org-file-menu-entry (file)
18445 (vector file (list 'find-file file) t))
18447 (defun org-check-agenda-file (file)
18448 "Make sure FILE exists. If not, ask user what to do."
18449 (unless (file-exists-p file)
18450 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18451 (abbreviate-file-name file))
18452 (let ((r (downcase (read-char-exclusive))))
18453 (cond
18454 ((equal r ?r)
18455 (org-remove-file file)
18456 (throw 'nextfile t))
18457 (t (user-error "Abort"))))))
18459 (defun org-get-agenda-file-buffer (file)
18460 "Get an agenda buffer visiting FILE.
18461 If the buffer needs to be created, add it to the list of buffers
18462 which might be released later."
18463 (let ((buf (org-find-base-buffer-visiting file)))
18464 (if buf
18465 buf ; just return it
18466 ;; Make a new buffer and remember it
18467 (setq buf (find-file-noselect file))
18468 (when buf (push buf org-agenda-new-buffers))
18469 buf)))
18471 (defun org-release-buffers (blist)
18472 "Release all buffers in list, asking the user for confirmation when needed.
18473 When a buffer is unmodified, it is just killed. When modified, it is saved
18474 \(if the user agrees) and then killed."
18475 (let (file)
18476 (dolist (buf blist)
18477 (setq file (buffer-file-name buf))
18478 (when (and (buffer-modified-p buf)
18479 file
18480 (y-or-n-p (format "Save file %s? " file)))
18481 (with-current-buffer buf (save-buffer)))
18482 (kill-buffer buf))))
18484 (defun org-agenda-prepare-buffers (files)
18485 "Create buffers for all agenda files, protect archived trees and comments."
18486 (interactive)
18487 (let ((pa '(:org-archived t))
18488 (pc '(:org-comment t))
18489 (pall '(:org-archived t :org-comment t))
18490 (inhibit-read-only t)
18491 (org-inhibit-startup org-agenda-inhibit-startup)
18492 (rea (concat ":" org-archive-tag ":"))
18493 re pos)
18494 (setq org-tag-alist-for-agenda nil
18495 org-tag-groups-alist-for-agenda nil)
18496 (save-excursion
18497 (save-restriction
18498 (dolist (file files)
18499 (catch 'nextfile
18500 (if (bufferp file)
18501 (set-buffer file)
18502 (org-check-agenda-file file)
18503 (set-buffer (org-get-agenda-file-buffer file)))
18504 (widen)
18505 (org-set-regexps-and-options 'tags-only)
18506 (setq pos (point))
18507 (or (memq 'category org-agenda-ignore-properties)
18508 (org-refresh-category-properties))
18509 (or (memq 'stats org-agenda-ignore-properties)
18510 (org-refresh-stats-properties))
18511 (or (memq 'effort org-agenda-ignore-properties)
18512 (org-refresh-effort-properties))
18513 (or (memq 'appt org-agenda-ignore-properties)
18514 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18515 (setq org-todo-keywords-for-agenda
18516 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18517 (setq org-done-keywords-for-agenda
18518 (append org-done-keywords-for-agenda org-done-keywords))
18519 (setq org-todo-keyword-alist-for-agenda
18520 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18521 (setq org-tag-alist-for-agenda
18522 (org-uniquify
18523 (append org-tag-alist-for-agenda
18524 org-current-tag-alist)))
18525 ;; Merge current file's tag groups into global
18526 ;; `org-tag-groups-alist-for-agenda'.
18527 (when org-group-tags
18528 (dolist (alist org-tag-groups-alist)
18529 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18530 (if old
18531 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18532 (push alist org-tag-groups-alist-for-agenda)))))
18533 (org-with-silent-modifications
18534 (save-excursion
18535 (remove-text-properties (point-min) (point-max) pall)
18536 (when org-agenda-skip-archived-trees
18537 (goto-char (point-min))
18538 (while (re-search-forward rea nil t)
18539 (when (org-at-heading-p t)
18540 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18541 (goto-char (point-min))
18542 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18543 (while (re-search-forward re nil t)
18544 (when (save-match-data (org-in-commented-heading-p t))
18545 (add-text-properties
18546 (match-beginning 0) (org-end-of-subtree t) pc)))))
18547 (goto-char pos)))))
18548 (setq org-todo-keywords-for-agenda
18549 (org-uniquify org-todo-keywords-for-agenda))
18550 (setq org-todo-keyword-alist-for-agenda
18551 (org-uniquify org-todo-keyword-alist-for-agenda))))
18554 ;;;; CDLaTeX minor mode
18556 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18557 "Keymap for the minor `org-cdlatex-mode'.")
18559 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18560 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18561 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18562 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18563 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18565 (defvar org-cdlatex-texmathp-advice-is-done nil
18566 "Flag remembering if we have applied the advice to texmathp already.")
18568 (define-minor-mode org-cdlatex-mode
18569 "Toggle the minor `org-cdlatex-mode'.
18570 This mode supports entering LaTeX environment and math in LaTeX fragments
18571 in Org mode.
18572 \\{org-cdlatex-mode-map}"
18573 nil " OCDL" nil
18574 (when org-cdlatex-mode
18575 (require 'cdlatex)
18576 (run-hooks 'cdlatex-mode-hook)
18577 (cdlatex-compute-tables))
18578 (unless org-cdlatex-texmathp-advice-is-done
18579 (setq org-cdlatex-texmathp-advice-is-done t)
18580 (defadvice texmathp (around org-math-always-on activate)
18581 "Always return t in Org buffers.
18582 This is because we want to insert math symbols without dollars even outside
18583 the LaTeX math segments. If Org mode thinks that point is actually inside
18584 an embedded LaTeX fragment, let `texmathp' do its job.
18585 `\\[org-cdlatex-mode-map]'"
18586 (interactive)
18587 (let (p)
18588 (cond
18589 ((not (derived-mode-p 'org-mode)) ad-do-it)
18590 ((eq this-command 'cdlatex-math-symbol)
18591 (setq ad-return-value t
18592 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18594 (let ((p (org-inside-LaTeX-fragment-p)))
18595 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18596 (setq ad-return-value t
18597 texmathp-why '("Org mode embedded math" . 0))
18598 (when p ad-do-it)))))))))
18600 (defun turn-on-org-cdlatex ()
18601 "Unconditionally turn on `org-cdlatex-mode'."
18602 (org-cdlatex-mode 1))
18604 (defun org-try-cdlatex-tab ()
18605 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18606 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18607 - inside a LaTeX fragment, or
18608 - after the first word in a line, where an abbreviation expansion could
18609 insert a LaTeX environment."
18610 (when org-cdlatex-mode
18611 (cond
18612 ;; Before any word on the line: No expansion possible.
18613 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18614 ;; Just after first word on the line: Expand it. Make sure it
18615 ;; cannot happen on headlines, though.
18616 ((save-excursion
18617 (skip-chars-backward "a-zA-Z0-9*")
18618 (skip-chars-backward " \t")
18619 (and (bolp) (not (org-at-heading-p))))
18620 (cdlatex-tab) t)
18621 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18623 (defun org-cdlatex-underscore-caret (&optional _arg)
18624 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18625 Revert to the normal definition outside of these fragments."
18626 (interactive "P")
18627 (if (org-inside-LaTeX-fragment-p)
18628 (call-interactively 'cdlatex-sub-superscript)
18629 (let (org-cdlatex-mode)
18630 (call-interactively (key-binding (vector last-input-event))))))
18632 (defun org-cdlatex-math-modify (&optional _arg)
18633 "Execute `cdlatex-math-modify' in LaTeX fragments.
18634 Revert to the normal definition outside of these fragments."
18635 (interactive "P")
18636 (if (org-inside-LaTeX-fragment-p)
18637 (call-interactively 'cdlatex-math-modify)
18638 (let (org-cdlatex-mode)
18639 (call-interactively (key-binding (vector last-input-event))))))
18641 (defun org-cdlatex-environment-indent (&optional environment item)
18642 "Execute `cdlatex-environment' and indent the inserted environment.
18644 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18646 The inserted environment is indented to current indentation
18647 unless point is at the beginning of the line, in which the
18648 environment remains unintended."
18649 (interactive)
18650 ;; cdlatex-environment always return nil. Therefore, capture output
18651 ;; first and determine if an environment was selected.
18652 (let* ((beg (point-marker))
18653 (end (copy-marker (point) t))
18654 (inserted (progn
18655 (ignore-errors (cdlatex-environment environment item))
18656 (< beg end)))
18657 ;; Figure out how many lines to move forward after the
18658 ;; environment has been inserted.
18659 (lines (when inserted
18660 (save-excursion
18661 (- (cl-loop while (< beg (point))
18662 with x = 0
18663 do (forward-line -1)
18664 (cl-incf x)
18665 finally return x)
18666 (if (progn (goto-char beg)
18667 (and (progn (skip-chars-forward " \t") (eolp))
18668 (progn (skip-chars-backward " \t") (bolp))))
18669 1 0)))))
18670 (env (org-trim (delete-and-extract-region beg end))))
18671 (when inserted
18672 ;; Get indentation of next line unless at column 0.
18673 (let ((ind (if (bolp) 0
18674 (save-excursion
18675 (org-return-indent)
18676 (prog1 (org-get-indentation)
18677 (when (progn (skip-chars-forward " \t") (eolp))
18678 (delete-region beg (point)))))))
18679 (bol (progn (skip-chars-backward " \t") (bolp))))
18680 ;; Insert a newline before environment unless at column zero
18681 ;; to "escape" the current line. Insert a newline if
18682 ;; something is one the same line as \end{ENVIRONMENT}.
18683 (insert
18684 (concat (unless bol "\n") env
18685 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18686 (unless (zerop ind)
18687 (save-excursion
18688 (goto-char beg)
18689 (while (< (point) end)
18690 (unless (eolp) (indent-line-to ind))
18691 (forward-line))))
18692 (goto-char beg)
18693 (forward-line lines)
18694 (indent-line-to ind)))
18695 (set-marker beg nil)
18696 (set-marker end nil)))
18699 ;;;; LaTeX fragments
18701 (defun org-inside-LaTeX-fragment-p ()
18702 "Test if point is inside a LaTeX fragment.
18703 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18704 sequence appearing also before point.
18705 Even though the matchers for math are configurable, this function assumes
18706 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18707 delimiters are skipped when they have been removed by customization.
18708 The return value is nil, or a cons cell with the delimiter and the
18709 position of this delimiter.
18711 This function does a reasonably good job, but can locally be fooled by
18712 for example currency specifications. For example it will assume being in
18713 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18714 fragments that are properly closed, but during editing, we have to live
18715 with the uncertainty caused by missing closing delimiters. This function
18716 looks only before point, not after."
18717 (catch 'exit
18718 (let ((pos (point))
18719 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18720 (lim (save-excursion (org-backward-paragraph) (point)))
18721 dd-on str (start 0) m re)
18722 (goto-char pos)
18723 (when dodollar
18724 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18725 re (nth 1 (assoc "$" org-latex-regexps)))
18726 (while (string-match re str start)
18727 (cond
18728 ((= (match-end 0) (length str))
18729 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18730 ((= (match-end 0) (- (length str) 5))
18731 (throw 'exit nil))
18732 (t (setq start (match-end 0))))))
18733 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18734 (goto-char pos)
18735 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18736 (and (match-beginning 2) (throw 'exit nil))
18737 ;; count $$
18738 (while (re-search-backward "\\$\\$" lim t)
18739 (setq dd-on (not dd-on)))
18740 (goto-char pos)
18741 (when dd-on (cons "$$" m))))))
18743 (defun org-inside-latex-macro-p ()
18744 "Is point inside a LaTeX macro or its arguments?"
18745 (save-match-data
18746 (org-in-regexp
18747 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18749 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18750 "Build an overlay between BEG and END using IMAGE file.
18751 Argument IMAGETYPE is the extension of the displayed image,
18752 as a string. It defaults to \"png\"."
18753 (let ((ov (make-overlay beg end))
18754 (imagetype (or (intern imagetype) 'png)))
18755 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18756 (overlay-put ov 'evaporate t)
18757 (overlay-put ov
18758 'modification-hooks
18759 (list (lambda (o _flag _beg _end &optional _l)
18760 (delete-overlay o))))
18761 (overlay-put ov
18762 'display
18763 (list 'image :type imagetype :file image :ascent 'center))))
18765 (defun org--list-latex-overlays (&optional beg end)
18766 "List all Org LaTeX overlays in current buffer.
18767 Limit to overlays between BEG and END when those are provided."
18768 (cl-remove-if-not
18769 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18770 (overlays-in (or beg (point-min)) (or end (point-max)))))
18772 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18773 "Remove all overlays with LaTeX fragment images in current buffer.
18774 When optional arguments BEG and END are non-nil, remove all
18775 overlays between them instead. Return a non-nil value when some
18776 overlays were removed, nil otherwise."
18777 (let ((overlays (org--list-latex-overlays beg end)))
18778 (mapc #'delete-overlay overlays)
18779 overlays))
18781 (defun org-toggle-latex-fragment (&optional arg)
18782 "Preview the LaTeX fragment at point, or all locally or globally.
18784 If the cursor is on a LaTeX fragment, create the image and overlay
18785 it over the source code, if there is none. Remove it otherwise.
18786 If there is no fragment at point, display all fragments in the
18787 current section.
18789 With prefix ARG, preview or clear image for all fragments in the
18790 current subtree or in the whole buffer when used before the first
18791 headline. With a prefix ARG `\\[universal-argument] \
18792 \\[universal-argument]' preview or clear images
18793 for all fragments in the buffer."
18794 (interactive "P")
18795 (when (display-graphic-p)
18796 (catch 'exit
18797 (save-excursion
18798 (let (beg end msg)
18799 (cond
18800 ((or (equal arg '(16))
18801 (and (equal arg '(4))
18802 (org-with-limited-levels (org-before-first-heading-p))))
18803 (if (org-remove-latex-fragment-image-overlays)
18804 (progn (message "LaTeX fragments images removed from buffer")
18805 (throw 'exit nil))
18806 (setq msg "Creating images for buffer...")))
18807 ((equal arg '(4))
18808 (org-with-limited-levels (org-back-to-heading t))
18809 (setq beg (point))
18810 (setq end (progn (org-end-of-subtree t) (point)))
18811 (if (org-remove-latex-fragment-image-overlays beg end)
18812 (progn
18813 (message "LaTeX fragment images removed from subtree")
18814 (throw 'exit nil))
18815 (setq msg "Creating images for subtree...")))
18816 ((let ((datum (org-element-context)))
18817 (when (memq (org-element-type datum)
18818 '(latex-environment latex-fragment))
18819 (setq beg (org-element-property :begin datum))
18820 (setq end (org-element-property :end datum))
18821 (if (org-remove-latex-fragment-image-overlays beg end)
18822 (progn (message "LaTeX fragment image removed")
18823 (throw 'exit nil))
18824 (setq msg "Creating image...")))))
18826 (org-with-limited-levels
18827 (setq beg (if (org-at-heading-p) (line-beginning-position)
18828 (outline-previous-heading)
18829 (point)))
18830 (setq end (progn (outline-next-heading) (point)))
18831 (if (org-remove-latex-fragment-image-overlays beg end)
18832 (progn
18833 (message "LaTeX fragment images removed from section")
18834 (throw 'exit nil))
18835 (setq msg "Creating images for section...")))))
18836 (let ((file (buffer-file-name (buffer-base-buffer))))
18837 (org-format-latex
18838 (concat org-preview-latex-image-directory "org-ltximg")
18839 beg end
18840 ;; Emacs cannot overlay images from remote hosts. Create
18841 ;; it in `temporary-file-directory' instead.
18842 (if (or (not file) (file-remote-p file))
18843 temporary-file-directory
18844 default-directory)
18845 'overlays msg 'forbuffer org-preview-latex-default-process))
18846 (message (concat msg "done")))))))
18848 (defun org-format-latex
18849 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18850 "Replace LaTeX fragments with links to an image.
18852 The function takes care of creating the replacement image.
18854 Only consider fragments between BEG and END when those are
18855 provided.
18857 When optional argument OVERLAYS is non-nil, display the image on
18858 top of the fragment instead of replacing it.
18860 PROCESSING-TYPE is the conversion method to use, as a symbol.
18862 Some of the options can be changed using the variable
18863 `org-format-latex-options', which see."
18864 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18865 (unless (eq processing-type 'verbatim)
18866 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18867 (cnt 0)
18868 checkdir-flag)
18869 (goto-char (or beg (point-min)))
18870 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18871 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18872 (overlay-recenter (or end (point-max))))
18873 (while (re-search-forward math-regexp end t)
18874 (unless (and overlays
18875 (eq (get-char-property (point) 'org-overlay-type)
18876 'org-latex-overlay))
18877 (let* ((context (org-element-context))
18878 (type (org-element-type context)))
18879 (when (memq type '(latex-environment latex-fragment))
18880 (let ((block-type (eq type 'latex-environment))
18881 (value (org-element-property :value context))
18882 (beg (org-element-property :begin context))
18883 (end (save-excursion
18884 (goto-char (org-element-property :end context))
18885 (skip-chars-backward " \r\t\n")
18886 (point))))
18887 (cond
18888 ((eq processing-type 'mathjax)
18889 ;; Prepare for MathJax processing.
18890 (if (not (string-match "\\`\\$\\$?" value))
18891 (goto-char end)
18892 (delete-region beg end)
18893 (if (string= (match-string 0 value) "$$")
18894 (insert "\\[" (substring value 2 -2) "\\]")
18895 (insert "\\(" (substring value 1 -1) "\\)"))))
18896 ((assq processing-type org-preview-latex-process-alist)
18897 ;; Process to an image.
18898 (cl-incf cnt)
18899 (goto-char beg)
18900 (let* ((processing-info
18901 (cdr (assq processing-type org-preview-latex-process-alist)))
18902 (face (face-at-point))
18903 ;; Get the colors from the face at point.
18905 (let ((color (plist-get org-format-latex-options
18906 :foreground)))
18907 (if (and forbuffer (eq color 'auto))
18908 (face-attribute face :foreground nil 'default)
18909 color)))
18911 (let ((color (plist-get org-format-latex-options
18912 :background)))
18913 (if (and forbuffer (eq color 'auto))
18914 (face-attribute face :background nil 'default)
18915 color)))
18916 (hash (sha1 (prin1-to-string
18917 (list org-format-latex-header
18918 org-latex-default-packages-alist
18919 org-latex-packages-alist
18920 org-format-latex-options
18921 forbuffer value fg bg))))
18922 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18923 (absprefix (expand-file-name prefix dir))
18924 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18925 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18926 (sep (and block-type "\n\n"))
18927 (link (concat sep "[[file:" linkfile "]]" sep))
18928 (options
18929 (org-combine-plists
18930 org-format-latex-options
18931 `(:foreground ,fg :background ,bg))))
18932 (when msg (message msg cnt))
18933 (unless checkdir-flag ; Ensure the directory exists.
18934 (setq checkdir-flag t)
18935 (let ((todir (file-name-directory absprefix)))
18936 (unless (file-directory-p todir)
18937 (make-directory todir t))))
18938 (unless (file-exists-p movefile)
18939 (org-create-formula-image
18940 value movefile options forbuffer processing-type))
18941 (if overlays
18942 (progn
18943 (dolist (o (overlays-in beg end))
18944 (when (eq (overlay-get o 'org-overlay-type)
18945 'org-latex-overlay)
18946 (delete-overlay o)))
18947 (org--format-latex-make-overlay beg end movefile imagetype)
18948 (goto-char end))
18949 (delete-region beg end)
18950 (insert
18951 (org-add-props link
18952 (list 'org-latex-src
18953 (replace-regexp-in-string "\"" "" value)
18954 'org-latex-src-embed-type
18955 (if block-type 'paragraph 'character)))))))
18956 ((eq processing-type 'mathml)
18957 ;; Process to MathML.
18958 (unless (org-format-latex-mathml-available-p)
18959 (user-error "LaTeX to MathML converter not configured"))
18960 (cl-incf cnt)
18961 (when msg (message msg cnt))
18962 (goto-char beg)
18963 (delete-region beg end)
18964 (insert (org-format-latex-as-mathml
18965 value block-type prefix dir)))
18967 (error "Unknown conversion process %s for LaTeX fragments"
18968 processing-type)))))))))))
18970 (defun org-create-math-formula (latex-frag &optional mathml-file)
18971 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18972 Use `org-latex-to-mathml-convert-command'. If the conversion is
18973 sucessful, return the portion between \"<math...> </math>\"
18974 elements otherwise return nil. When MATHML-FILE is specified,
18975 write the results in to that file. When invoked as an
18976 interactive command, prompt for LATEX-FRAG, with initial value
18977 set to the current active region and echo the results for user
18978 inspection."
18979 (interactive (list (let ((frag (when (org-region-active-p)
18980 (buffer-substring-no-properties
18981 (region-beginning) (region-end)))))
18982 (read-string "LaTeX Fragment: " frag nil frag))))
18983 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18984 (let* ((tmp-in-file
18985 (let ((file (file-relative-name
18986 (make-temp-name (expand-file-name "ltxmathml-in")))))
18987 (write-region latex-frag nil file)
18988 file))
18989 (tmp-out-file (file-relative-name
18990 (make-temp-name (expand-file-name "ltxmathml-out"))))
18991 (cmd (format-spec
18992 org-latex-to-mathml-convert-command
18993 `((?j . ,(and org-latex-to-mathml-jar-file
18994 (shell-quote-argument
18995 (expand-file-name
18996 org-latex-to-mathml-jar-file))))
18997 (?I . ,(shell-quote-argument tmp-in-file))
18998 (?i . ,latex-frag)
18999 (?o . ,(shell-quote-argument tmp-out-file)))))
19000 mathml shell-command-output)
19001 (when (called-interactively-p 'any)
19002 (unless (org-format-latex-mathml-available-p)
19003 (user-error "LaTeX to MathML converter not configured")))
19004 (message "Running %s" cmd)
19005 (setq shell-command-output (shell-command-to-string cmd))
19006 (setq mathml
19007 (when (file-readable-p tmp-out-file)
19008 (with-current-buffer (find-file-noselect tmp-out-file t)
19009 (goto-char (point-min))
19010 (when (re-search-forward
19011 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19012 (regexp-quote
19013 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19014 nil t)
19015 (prog1 (match-string 0) (kill-buffer))))))
19016 (cond
19017 (mathml
19018 (setq mathml
19019 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19020 (when mathml-file
19021 (write-region mathml nil mathml-file))
19022 (when (called-interactively-p 'any)
19023 (message mathml)))
19024 ((message "LaTeX to MathML conversion failed")
19025 (message shell-command-output)))
19026 (delete-file tmp-in-file)
19027 (when (file-exists-p tmp-out-file)
19028 (delete-file tmp-out-file))
19029 mathml))
19031 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19032 prefix &optional dir)
19033 "Use `org-create-math-formula' but check local cache first."
19034 (let* ((absprefix (expand-file-name prefix dir))
19035 (print-length nil) (print-level nil)
19036 (formula-id (concat
19037 "formula-"
19038 (sha1
19039 (prin1-to-string
19040 (list latex-frag
19041 org-latex-to-mathml-convert-command)))))
19042 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19043 (formula-cache-dir (file-name-directory formula-cache)))
19045 (unless (file-directory-p formula-cache-dir)
19046 (make-directory formula-cache-dir t))
19048 (unless (file-exists-p formula-cache)
19049 (org-create-math-formula latex-frag formula-cache))
19051 (if (file-exists-p formula-cache)
19052 ;; Successful conversion. Return the link to MathML file.
19053 (org-add-props
19054 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19055 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19056 'org-latex-src-embed-type (if latex-frag-type
19057 'paragraph 'character)))
19058 ;; Failed conversion. Return the LaTeX fragment verbatim
19059 latex-frag)))
19061 (defun org--get-display-dpi ()
19062 "Get the DPI of the display.
19063 The function assumes that the display has the same pixel width in
19064 the horizontal and vertical directions."
19065 (if (display-graphic-p)
19066 (round (/ (display-pixel-height)
19067 (/ (display-mm-height) 25.4)))
19068 (error "Attempt to calculate the dpi of a non-graphic display")))
19070 (defun org-create-formula-image
19071 (string tofile options buffer &optional processing-type)
19072 "Create an image from LaTeX source using external processes.
19074 The LaTeX STRING is saved to a temporary LaTeX file, then
19075 converted to an image file by process PROCESSING-TYPE defined in
19076 `org-preview-latex-process-alist'. A nil value defaults to
19077 `org-preview-latex-default-process'.
19079 The generated image file is eventually moved to TOFILE.
19081 The OPTIONS argument controls the size, foreground color and
19082 background color of the generated image.
19084 When BUFFER non-nil, this function is used for LaTeX previewing.
19085 Otherwise, it is used to deal with LaTeX snippets showed in
19086 a HTML file."
19087 (let* ((processing-type (or processing-type
19088 org-preview-latex-default-process))
19089 (processing-info
19090 (cdr (assq processing-type org-preview-latex-process-alist)))
19091 (programs (plist-get processing-info :programs))
19092 (error-message (or (plist-get processing-info :message) ""))
19093 (use-xcolor (plist-get processing-info :use-xcolor))
19094 (image-input-type (plist-get processing-info :image-input-type))
19095 (image-output-type (plist-get processing-info :image-output-type))
19096 (post-clean (or (plist-get processing-info :post-clean)
19097 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19098 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19099 (latex-header
19100 (or (plist-get processing-info :latex-header)
19101 (org-latex-make-preamble
19102 (org-export-get-environment (org-export-get-backend 'latex))
19103 org-format-latex-header
19104 'snippet)))
19105 (latex-compiler (plist-get processing-info :latex-compiler))
19106 (image-converter (plist-get processing-info :image-converter))
19107 (tmpdir temporary-file-directory)
19108 (texfilebase (make-temp-name
19109 (expand-file-name "orgtex" tmpdir)))
19110 (texfile (concat texfilebase ".tex"))
19111 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19112 '(1.0 . 1.0)))
19113 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19114 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19115 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19116 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19117 "Black"))
19118 (bg (or (plist-get options (if buffer :background :html-background))
19119 "Transparent"))
19120 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19121 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19122 (dolist (program programs)
19123 (org-check-external-command program error-message))
19124 (if use-xcolor
19125 (progn (if (eq fg 'default)
19126 (setq fg (org-latex-color :foreground))
19127 (setq fg (org-latex-color-format fg)))
19128 (if (eq bg 'default)
19129 (setq bg (org-latex-color :background))
19130 (setq bg (org-latex-color-format
19131 (if (string= bg "Transparent") "white" bg))))
19132 (with-temp-file texfile
19133 (insert latex-header)
19134 (insert "\n\\begin{document}\n"
19135 "\\definecolor{fg}{rgb}{" fg "}\n"
19136 "\\definecolor{bg}{rgb}{" bg "}\n"
19137 "\n\\pagecolor{bg}\n"
19138 "\n{\\color{fg}\n"
19139 string
19140 "\n}\n"
19141 "\n\\end{document}\n")))
19142 (if (eq fg 'default)
19143 (setq fg (org-dvipng-color :foreground))
19144 (unless (string= fg "Transparent")
19145 (setq fg (org-dvipng-color-format fg))))
19146 (if (eq bg 'default)
19147 (setq bg (org-dvipng-color :background))
19148 (unless (string= bg "Transparent")
19149 (setq bg (org-dvipng-color-format bg))))
19150 (with-temp-file texfile
19151 (insert latex-header)
19152 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19154 (let* ((err-msg (format "Please adjust `%s' part of \
19155 `org-preview-latex-process-alist'."
19156 processing-type))
19157 (image-input-file
19158 (org-compile-file
19159 texfile latex-compiler image-input-type err-msg log-buf))
19160 (image-output-file
19161 (org-compile-file
19162 image-input-file image-converter image-output-type err-msg log-buf
19163 `((?F . ,(shell-quote-argument fg))
19164 (?B . ,(shell-quote-argument bg))
19165 (?D . ,(shell-quote-argument (format "%s" dpi)))
19166 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19167 (copy-file image-output-file tofile 'replace)
19168 (dolist (e post-clean)
19169 (when (file-exists-p (concat texfilebase e))
19170 (delete-file (concat texfilebase e))))
19171 image-output-file)))
19173 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19174 "Fill a LaTeX header template TPL.
19175 In the template, the following place holders will be recognized:
19177 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19178 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19179 [PACKAGES] \\usepackage statements for PKG
19180 [NO-PACKAGES] do not include PKG
19181 [EXTRA] the string EXTRA
19182 [NO-EXTRA] do not include EXTRA
19184 For backward compatibility, if both the positive and the negative place
19185 holder is missing, the positive one (without the \"NO-\") will be
19186 assumed to be present at the end of the template.
19187 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19188 EXTRA is a string.
19189 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19190 (let (rpl (end ""))
19191 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19192 (setq rpl (if (or (match-end 1) (not def-pkg))
19193 "" (org-latex-packages-to-string def-pkg snippets-p t))
19194 tpl (replace-match rpl t t tpl))
19195 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19197 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19198 (setq rpl (if (or (match-end 1) (not pkg))
19199 "" (org-latex-packages-to-string pkg snippets-p t))
19200 tpl (replace-match rpl t t tpl))
19201 (when pkg (setq end
19202 (concat end "\n"
19203 (org-latex-packages-to-string pkg snippets-p)))))
19205 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19206 (setq rpl (if (or (match-end 1) (not extra))
19207 "" (concat extra "\n"))
19208 tpl (replace-match rpl t t tpl))
19209 (when (and extra (string-match "\\S-" extra))
19210 (setq end (concat end "\n" extra))))
19212 (if (string-match "\\S-" end)
19213 (concat tpl "\n" end)
19214 tpl)))
19216 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19217 "Turn an alist of packages into a string with the \\usepackage macros."
19218 (setq pkg (mapconcat (lambda(p)
19219 (cond
19220 ((stringp p) p)
19221 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19222 (format "%% Package %s omitted" (cadr p)))
19223 ((equal "" (car p))
19224 (format "\\usepackage{%s}" (cadr p)))
19226 (format "\\usepackage[%s]{%s}"
19227 (car p) (cadr p)))))
19229 "\n"))
19230 (if newline (concat pkg "\n") pkg))
19232 (defun org-dvipng-color (attr)
19233 "Return a RGB color specification for dvipng."
19234 (org-dvipng-color-format (face-attribute 'default attr nil)))
19236 (defun org-dvipng-color-format (color-name)
19237 "Convert COLOR-NAME to a RGB color value for dvipng."
19238 (apply #'format "rgb %s %s %s"
19239 (mapcar 'org-normalize-color
19240 (color-values color-name))))
19242 (defun org-latex-color (attr)
19243 "Return a RGB color for the LaTeX color package."
19244 (org-latex-color-format (face-attribute 'default attr nil)))
19246 (defun org-latex-color-format (color-name)
19247 "Convert COLOR-NAME to a RGB color value."
19248 (apply #'format "%s,%s,%s"
19249 (mapcar 'org-normalize-color
19250 (color-values color-name))))
19252 (defun org-normalize-color (value)
19253 "Return string to be used as color value for an RGB component."
19254 (format "%g" (/ value 65535.0)))
19258 ;; Image display
19260 (defvar-local org-inline-image-overlays nil)
19262 (defun org-toggle-inline-images (&optional include-linked)
19263 "Toggle the display of inline images.
19264 INCLUDE-LINKED is passed to `org-display-inline-images'."
19265 (interactive "P")
19266 (if org-inline-image-overlays
19267 (progn
19268 (org-remove-inline-images)
19269 (when (called-interactively-p 'interactive)
19270 (message "Inline image display turned off")))
19271 (org-display-inline-images include-linked)
19272 (when (called-interactively-p 'interactive)
19273 (message (if org-inline-image-overlays
19274 (format "%d images displayed inline"
19275 (length org-inline-image-overlays))
19276 "No images to display inline")))))
19278 (defun org-redisplay-inline-images ()
19279 "Refresh the display of inline images."
19280 (interactive)
19281 (if (not org-inline-image-overlays)
19282 (org-toggle-inline-images)
19283 (org-toggle-inline-images)
19284 (org-toggle-inline-images)))
19286 (defun org-display-inline-images (&optional include-linked refresh beg end)
19287 "Display inline images.
19289 An inline image is a link which follows either of these
19290 conventions:
19292 1. Its path is a file with an extension matching return value
19293 from `image-file-name-regexp' and it has no contents.
19295 2. Its description consists in a single link of the previous
19296 type.
19298 When optional argument INCLUDE-LINKED is non-nil, also links with
19299 a text description part will be inlined. This can be nice for
19300 a quick look at those images, but it does not reflect what
19301 exported files will look like.
19303 When optional argument REFRESH is non-nil, refresh existing
19304 images between BEG and END. This will create new image displays
19305 only if necessary. BEG and END default to the buffer
19306 boundaries."
19307 (interactive "P")
19308 (when (display-graphic-p)
19309 (unless refresh
19310 (org-remove-inline-images)
19311 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19312 (org-with-wide-buffer
19313 (goto-char (or beg (point-min)))
19314 (let* ((case-fold-search t)
19315 (file-extension-re (image-file-name-regexp))
19316 (link-abbrevs (mapcar #'car
19317 (append org-link-abbrev-alist-local
19318 org-link-abbrev-alist)))
19319 ;; Check absolute, relative file names and explicit
19320 ;; "file:" links. Also check link abbreviations since
19321 ;; some might expand to "file" links.
19322 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19323 (and link-abbrevs
19324 (format "\\|\\(?:%s:\\)"
19325 (regexp-opt link-abbrevs))))))
19326 (while (re-search-forward file-types-re end t)
19327 (let ((link (save-match-data (org-element-context))))
19328 ;; Check if we're at an inline image, i.e., an image file
19329 ;; link without a description (unless INCLUDE-LINKED is
19330 ;; non-nil).
19331 (when (and (equal "file" (org-element-property :type link))
19332 (or include-linked
19333 (null (org-element-contents link)))
19334 (string-match-p file-extension-re
19335 (org-element-property :path link)))
19336 (let ((file (expand-file-name
19337 (org-link-unescape
19338 (org-element-property :path link)))))
19339 (when (file-exists-p file)
19340 (let ((width
19341 ;; Apply `org-image-actual-width' specifications.
19342 (cond
19343 ((not (image-type-available-p 'imagemagick)) nil)
19344 ((eq org-image-actual-width t) nil)
19345 ((listp org-image-actual-width)
19347 ;; First try to find a width among
19348 ;; attributes associated to the paragraph
19349 ;; containing link.
19350 (let ((paragraph
19351 (let ((e link))
19352 (while (and (setq e (org-element-property
19353 :parent e))
19354 (not (eq (org-element-type e)
19355 'paragraph))))
19356 e)))
19357 (when paragraph
19358 (save-excursion
19359 (goto-char (org-element-property :begin paragraph))
19360 (when
19361 (re-search-forward
19362 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19363 (org-element-property
19364 :post-affiliated paragraph)
19366 (string-to-number (match-string 1))))))
19367 ;; Otherwise, fall-back to provided number.
19368 (car org-image-actual-width)))
19369 ((numberp org-image-actual-width)
19370 org-image-actual-width)))
19371 (old (get-char-property-and-overlay
19372 (org-element-property :begin link)
19373 'org-image-overlay)))
19374 (if (and (car-safe old) refresh)
19375 (image-refresh (overlay-get (cdr old) 'display))
19376 (let ((image (create-image file
19377 (and width 'imagemagick)
19379 :width width)))
19380 (when image
19381 (let ((ov (make-overlay
19382 (org-element-property :begin link)
19383 (progn
19384 (goto-char
19385 (org-element-property :end link))
19386 (skip-chars-backward " \t")
19387 (point)))))
19388 (overlay-put ov 'display image)
19389 (overlay-put ov 'face 'default)
19390 (overlay-put ov 'org-image-overlay t)
19391 (overlay-put
19392 ov 'modification-hooks
19393 (list 'org-display-inline-remove-overlay))
19394 (push ov org-inline-image-overlays)))))))))))))))
19396 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19397 "Remove inline-display overlay if a corresponding region is modified."
19398 (let ((inhibit-modification-hooks t))
19399 (when (and ov after)
19400 (delete ov org-inline-image-overlays)
19401 (delete-overlay ov))))
19403 (defun org-remove-inline-images ()
19404 "Remove inline display of images."
19405 (interactive)
19406 (mapc #'delete-overlay org-inline-image-overlays)
19407 (setq org-inline-image-overlays nil))
19409 ;;;; Key bindings
19411 (defun org-remap (map &rest commands)
19412 "In MAP, remap the functions given in COMMANDS.
19413 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19414 (let (new old)
19415 (while commands
19416 (setq old (pop commands) new (pop commands))
19417 (org-defkey map (vector 'remap old) new))))
19419 ;; Outline functions from `outline-mode-prefix-map'
19420 ;; that can be remapped in Org:
19421 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19422 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19423 (define-key org-mode-map [remap outline-forward-same-level]
19424 'org-forward-heading-same-level)
19425 (define-key org-mode-map [remap outline-backward-same-level]
19426 'org-backward-heading-same-level)
19427 (define-key org-mode-map [remap outline-show-branches]
19428 'org-kill-note-or-show-branches)
19429 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19430 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19431 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19432 (define-key org-mode-map [remap outline-next-visible-heading]
19433 'org-next-visible-heading)
19434 (define-key org-mode-map [remap outline-previous-visible-heading]
19435 'org-previous-visible-heading)
19436 (define-key org-mode-map [remap show-children] 'org-show-children)
19438 ;; Outline functions from `outline-mode-prefix-map' that can not
19439 ;; be remapped in Org:
19441 ;; - the column "key binding" shows whether the Outline function is still
19442 ;; available in Org mode on the same key that it has been bound to in
19443 ;; Outline mode:
19444 ;; - "overridden": key used for a different functionality in Org mode
19445 ;; - else: key still bound to the same Outline function in Org mode
19447 ;; | Outline function | key binding | Org replacement |
19448 ;; |------------------------------------+-------------+--------------------------|
19449 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19450 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19451 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19452 ;; | `show-entry' | overridden | no replacement |
19453 ;; | `show-branches' | `C-c C-k' | still same function |
19454 ;; | `show-subtree' | overridden | visibility cycling |
19455 ;; | `show-all' | overridden | no replacement |
19456 ;; | `hide-subtree' | overridden | visibility cycling |
19457 ;; | `hide-body' | overridden | no replacement |
19458 ;; | `hide-entry' | overridden | visibility cycling |
19459 ;; | `hide-leaves' | overridden | no replacement |
19460 ;; | `hide-sublevels' | overridden | no replacement |
19461 ;; | `hide-other' | overridden | no replacement |
19463 ;; Make `C-c C-x' a prefix key
19464 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19466 ;; TAB key with modifiers
19467 (org-defkey org-mode-map "\C-i" 'org-cycle)
19468 (org-defkey org-mode-map [(tab)] 'org-cycle)
19469 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19470 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19472 ;; The following line is necessary under Suse GNU/Linux
19473 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19474 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19475 (define-key org-mode-map [backtab] 'org-shifttab)
19477 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19478 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19479 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19481 ;; Cursor keys with modifiers
19482 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19483 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19484 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19485 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19487 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19488 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19489 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19490 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19491 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19492 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19494 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19495 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19496 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19497 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19499 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19500 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19501 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19502 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19504 ;; Babel keys
19505 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19506 (dolist (pair org-babel-key-bindings)
19507 (define-key org-babel-map (car pair) (cdr pair)))
19509 ;;; Extra keys for tty access.
19510 ;; We only set them when really needed because otherwise the
19511 ;; menus don't show the simple keys
19513 (when (or org-use-extra-keys (not window-system))
19514 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19515 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19516 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19517 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19518 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19519 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19520 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19521 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19522 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19523 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19524 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19525 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19526 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19527 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19528 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19529 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19530 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19531 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19532 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19533 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19534 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19535 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19536 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19537 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19538 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19539 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19540 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19541 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19543 ;; All the other keys
19544 (org-remap org-mode-map
19545 'self-insert-command 'org-self-insert-command
19546 'delete-char 'org-delete-char
19547 'delete-backward-char 'org-delete-backward-char)
19548 (org-defkey org-mode-map "|" 'org-force-self-insert)
19550 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19551 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19552 (if (boundp 'narrow-map)
19553 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19554 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19555 (if (boundp 'narrow-map)
19556 (org-defkey narrow-map "b" 'org-narrow-to-block)
19557 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19558 (if (boundp 'narrow-map)
19559 (org-defkey narrow-map "e" 'org-narrow-to-element)
19560 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19561 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19562 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19563 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19564 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19565 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19566 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19567 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19568 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19569 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19570 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19571 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19572 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19573 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19574 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19575 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19576 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19577 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19578 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19579 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19580 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19581 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19582 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19583 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19584 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19585 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19586 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19587 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19588 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19589 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19590 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19591 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19592 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19593 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19594 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19595 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19596 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19597 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19598 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19599 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19600 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19601 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19602 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19603 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19604 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19605 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19606 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19607 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19608 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19609 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19610 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19611 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19612 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19613 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19614 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19615 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19616 (org-defkey org-mode-map "\C-c^" 'org-sort)
19617 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19618 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19619 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19620 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19621 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19622 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19623 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19624 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19625 (org-defkey org-mode-map "\C-m" 'org-return)
19626 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19627 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19628 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19629 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19630 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19631 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19632 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19633 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19634 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19635 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19636 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19637 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19638 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19639 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19640 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19641 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19642 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19643 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19644 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19645 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19646 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19647 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19648 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19649 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19650 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19652 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19653 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19654 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19656 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19657 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19658 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19659 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19660 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19661 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19662 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19663 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19664 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19665 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19666 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19667 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19668 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19669 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19670 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19671 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19672 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19673 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19674 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19675 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19676 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19677 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19679 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19680 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19681 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19682 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19683 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19685 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19687 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19689 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19690 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19692 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19695 (defconst org-speed-commands-default
19697 ("Outline Navigation")
19698 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19699 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19700 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19701 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19702 ("F" . org-next-block)
19703 ("B" . org-previous-block)
19704 ("u" . (org-speed-move-safe 'outline-up-heading))
19705 ("j" . org-goto)
19706 ("g" . (org-refile t))
19707 ("Outline Visibility")
19708 ("c" . org-cycle)
19709 ("C" . org-shifttab)
19710 (" " . org-display-outline-path)
19711 ("s" . org-narrow-to-subtree)
19712 ("=" . org-columns)
19713 ("Outline Structure Editing")
19714 ("U" . org-metaup)
19715 ("D" . org-metadown)
19716 ("r" . org-metaright)
19717 ("l" . org-metaleft)
19718 ("R" . org-shiftmetaright)
19719 ("L" . org-shiftmetaleft)
19720 ("i" . (progn (forward-char 1) (call-interactively
19721 'org-insert-heading-respect-content)))
19722 ("^" . org-sort)
19723 ("w" . org-refile)
19724 ("a" . org-archive-subtree-default-with-confirmation)
19725 ("@" . org-mark-subtree)
19726 ("#" . org-toggle-comment)
19727 ("Clock Commands")
19728 ("I" . org-clock-in)
19729 ("O" . org-clock-out)
19730 ("Meta Data Editing")
19731 ("t" . org-todo)
19732 ("," . (org-priority))
19733 ("0" . (org-priority ?\ ))
19734 ("1" . (org-priority ?A))
19735 ("2" . (org-priority ?B))
19736 ("3" . (org-priority ?C))
19737 (":" . org-set-tags-command)
19738 ("e" . org-set-effort)
19739 ("E" . org-inc-effort)
19740 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19741 (org-entry-put (point) "APPT_WARNTIME" m)))
19742 ("Agenda Views etc")
19743 ("v" . org-agenda)
19744 ("/" . org-sparse-tree)
19745 ("Misc")
19746 ("o" . org-open-at-point)
19747 ("?" . org-speed-command-help)
19748 ("<" . (org-agenda-set-restriction-lock 'subtree))
19749 (">" . (org-agenda-remove-restriction-lock))
19751 "The default speed commands.")
19753 (defun org-print-speed-command (e)
19754 (if (> (length (car e)) 1)
19755 (progn
19756 (princ "\n")
19757 (princ (car e))
19758 (princ "\n")
19759 (princ (make-string (length (car e)) ?-))
19760 (princ "\n"))
19761 (princ (car e))
19762 (princ " ")
19763 (if (symbolp (cdr e))
19764 (princ (symbol-name (cdr e)))
19765 (prin1 (cdr e)))
19766 (princ "\n")))
19768 (defun org-speed-command-help ()
19769 "Show the available speed commands."
19770 (interactive)
19771 (if (not org-use-speed-commands)
19772 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19773 (with-output-to-temp-buffer "*Help*"
19774 (princ "User-defined Speed commands\n===========================\n")
19775 (mapc #'org-print-speed-command org-speed-commands-user)
19776 (princ "\n")
19777 (princ "Built-in Speed commands\n=======================\n")
19778 (mapc #'org-print-speed-command org-speed-commands-default))
19779 (with-current-buffer "*Help*"
19780 (setq truncate-lines t))))
19782 (defun org-speed-move-safe (cmd)
19783 "Execute CMD, but make sure that the cursor always ends up in a headline.
19784 If not, return to the original position and throw an error."
19785 (interactive)
19786 (let ((pos (point)))
19787 (call-interactively cmd)
19788 (unless (and (bolp) (org-at-heading-p))
19789 (goto-char pos)
19790 (error "Boundary reached while executing %s" cmd))))
19792 (defvar org-self-insert-command-undo-counter 0)
19794 (defvar org-table-auto-blank-field) ; defined in org-table.el
19795 (defvar org-speed-command nil)
19797 (defun org-speed-command-activate (keys)
19798 "Hook for activating single-letter speed commands.
19799 `org-speed-commands-default' specifies a minimal command set.
19800 Use `org-speed-commands-user' for further customization."
19801 (when (or (and (bolp) (looking-at org-outline-regexp))
19802 (and (functionp org-use-speed-commands)
19803 (funcall org-use-speed-commands)))
19804 (cdr (assoc keys (append org-speed-commands-user
19805 org-speed-commands-default)))))
19807 (defun org-babel-speed-command-activate (keys)
19808 "Hook for activating single-letter code block commands."
19809 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19810 (cdr (assoc keys org-babel-key-bindings))))
19812 (defcustom org-speed-command-hook
19813 '(org-speed-command-activate org-babel-speed-command-activate)
19814 "Hook for activating speed commands at strategic locations.
19815 Hook functions are called in sequence until a valid handler is
19816 found.
19818 Each hook takes a single argument, a user-pressed command key
19819 which is also a `self-insert-command' from the global map.
19821 Within the hook, examine the cursor position and the command key
19822 and return nil or a valid handler as appropriate. Handler could
19823 be one of an interactive command, a function, or a form.
19825 Set `org-use-speed-commands' to non-nil value to enable this
19826 hook. The default setting is `org-speed-command-activate'."
19827 :group 'org-structure
19828 :version "24.1"
19829 :type 'hook)
19831 (defun org-self-insert-command (N)
19832 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19833 If the cursor is in a table looking at whitespace, the whitespace is
19834 overwritten, and the table is not marked as requiring realignment."
19835 (interactive "p")
19836 (org-check-before-invisible-edit 'insert)
19837 (cond
19838 ((and org-use-speed-commands
19839 (let ((kv (this-command-keys-vector)))
19840 (setq org-speed-command
19841 (run-hook-with-args-until-success
19842 'org-speed-command-hook
19843 (make-string 1 (aref kv (1- (length kv))))))))
19844 (cond
19845 ((commandp org-speed-command)
19846 (setq this-command org-speed-command)
19847 (call-interactively org-speed-command))
19848 ((functionp org-speed-command)
19849 (funcall org-speed-command))
19850 ((and org-speed-command (listp org-speed-command))
19851 (eval org-speed-command))
19852 (t (let (org-use-speed-commands)
19853 (call-interactively 'org-self-insert-command)))))
19854 ((and
19855 (org-at-table-p)
19856 (eq N 1)
19857 (not (org-region-active-p))
19858 (progn
19859 ;; Check if we blank the field, and if that triggers align.
19860 (and (featurep 'org-table) org-table-auto-blank-field
19861 (memq last-command
19862 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19863 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19864 ;; Got extra space, this field does not determine
19865 ;; column width.
19866 (let (org-table-may-need-update) (org-table-blank-field))
19867 ;; No extra space, this field may determine column
19868 ;; width.
19869 (org-table-blank-field)))
19871 (looking-at "[^|\n]* \\( \\)|"))
19872 ;; There is room for insertion without re-aligning the table.
19873 (delete-region (match-beginning 1) (match-end 1))
19874 (self-insert-command N))
19876 (setq org-table-may-need-update t)
19877 (self-insert-command N)
19878 (org-fix-tags-on-the-fly)
19879 (when org-self-insert-cluster-for-undo
19880 (if (not (eq last-command 'org-self-insert-command))
19881 (setq org-self-insert-command-undo-counter 1)
19882 (if (>= org-self-insert-command-undo-counter 20)
19883 (setq org-self-insert-command-undo-counter 1)
19884 (and (> org-self-insert-command-undo-counter 0)
19885 buffer-undo-list (listp buffer-undo-list)
19886 (not (cadr buffer-undo-list)) ; remove nil entry
19887 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19888 (setq org-self-insert-command-undo-counter
19889 (1+ org-self-insert-command-undo-counter))))))))
19891 (defun org-check-before-invisible-edit (kind)
19892 "Check is editing if kind KIND would be dangerous with invisible text around.
19893 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19894 ;; First, try to get out of here as quickly as possible, to reduce overhead
19895 (when (and org-catch-invisible-edits
19896 (or (not (boundp 'visible-mode)) (not visible-mode))
19897 (or (get-char-property (point) 'invisible)
19898 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19899 ;; OK, we need to take a closer look. Do not consider
19900 ;; invisibility obtained through text properties (e.g., link
19901 ;; fontification), as it cannot be toggled.
19902 (let* ((invisible-at-point
19903 (pcase (get-char-property-and-overlay (point) 'invisible)
19904 (`(,_ . ,(and (pred overlayp) o)) o)))
19905 ;; Assume that point cannot land in the middle of an
19906 ;; overlay, or between two overlays.
19907 (invisible-before-point
19908 (and (not invisible-at-point)
19909 (not (bobp))
19910 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19911 (`(,_ . ,(and (pred overlayp) o)) o))))
19912 (border-and-ok-direction
19914 ;; Check if we are acting predictably before invisible
19915 ;; text.
19916 (and invisible-at-point
19917 (memq kind '(insert delete-backward)))
19918 ;; Check if we are acting predictably after invisible text
19919 ;; This works not well, and I have turned it off. It seems
19920 ;; better to always show and stop after invisible text.
19921 ;; (and (not invisible-at-point) invisible-before-point
19922 ;; (memq kind '(insert delete)))
19924 (when (or invisible-at-point invisible-before-point)
19925 (when (eq org-catch-invisible-edits 'error)
19926 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19927 (if (and org-custom-properties-overlays
19928 (y-or-n-p "Display invisible properties in this buffer? "))
19929 (org-toggle-custom-properties-visibility)
19930 ;; Make the area visible
19931 (save-excursion
19932 (when invisible-before-point
19933 (goto-char
19934 (previous-single-char-property-change (point) 'invisible)))
19935 ;; Remove whatever overlay is currently making yet-to-be
19936 ;; edited text invisible. Also remove nested invisibility
19937 ;; related overlays.
19938 (delete-overlay (or invisible-at-point invisible-before-point))
19939 (let ((origin (if invisible-at-point (point) (1- (point)))))
19940 (while (pcase (get-char-property-and-overlay origin 'invisible)
19941 (`(,_ . ,(and (pred overlayp) o))
19942 (delete-overlay o)
19943 t)))))
19944 (cond
19945 ((eq org-catch-invisible-edits 'show)
19946 ;; That's it, we do the edit after showing
19947 (message
19948 "Unfolding invisible region around point before editing")
19949 (sit-for 1))
19950 ((and (eq org-catch-invisible-edits 'smart)
19951 border-and-ok-direction)
19952 (message "Unfolding invisible region around point before editing"))
19954 ;; Don't do the edit, make the user repeat it in full visibility
19955 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19957 (defun org-fix-tags-on-the-fly ()
19958 "Align tags in headline at point.
19959 Unlike to `org-set-tags', it ignores region and sorting."
19960 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19961 (org-at-heading-p))
19962 (let ((org-ignore-region t)
19963 (org-tags-sort-function nil))
19964 (org-set-tags nil t))))
19966 (defun org-delete-backward-char (N)
19967 "Like `delete-backward-char', insert whitespace at field end in tables.
19968 When deleting backwards, in tables this function will insert whitespace in
19969 front of the next \"|\" separator, to keep the table aligned. The table will
19970 still be marked for re-alignment if the field did fill the entire column,
19971 because, in this case the deletion might narrow the column."
19972 (interactive "p")
19973 (save-match-data
19974 (org-check-before-invisible-edit 'delete-backward)
19975 (if (and (org-at-table-p)
19976 (eq N 1)
19977 (not (org-region-active-p))
19978 (string-match "|" (buffer-substring (point-at-bol) (point)))
19979 (looking-at ".*?|"))
19980 (let ((pos (point))
19981 (noalign (looking-at "[^|\n\r]* |"))
19982 (c org-table-may-need-update))
19983 (backward-delete-char N)
19984 (unless overwrite-mode
19985 (skip-chars-forward "^|")
19986 (insert " ")
19987 (goto-char (1- pos)))
19988 ;; noalign: if there were two spaces at the end, this field
19989 ;; does not determine the width of the column.
19990 (when noalign (setq org-table-may-need-update c)))
19991 (backward-delete-char N)
19992 (org-fix-tags-on-the-fly))))
19994 (defun org-delete-char (N)
19995 "Like `delete-char', but insert whitespace at field end in tables.
19996 When deleting characters, in tables this function will insert whitespace in
19997 front of the next \"|\" separator, to keep the table aligned. The table will
19998 still be marked for re-alignment if the field did fill the entire column,
19999 because, in this case the deletion might narrow the column."
20000 (interactive "p")
20001 (save-match-data
20002 (org-check-before-invisible-edit 'delete)
20003 (if (and (org-at-table-p)
20004 (not (bolp))
20005 (not (= (char-after) ?|))
20006 (eq N 1))
20007 (if (looking-at ".*?|")
20008 (let ((pos (point))
20009 (noalign (looking-at "[^|\n\r]* |"))
20010 (c org-table-may-need-update))
20011 (replace-match
20012 (concat (substring (match-string 0) 1 -1) " |") nil t)
20013 (goto-char pos)
20014 ;; noalign: if there were two spaces at the end, this field
20015 ;; does not determine the width of the column.
20016 (when noalign (setq org-table-may-need-update c)))
20017 (delete-char N))
20018 (delete-char N)
20019 (org-fix-tags-on-the-fly))))
20021 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20022 (put 'org-self-insert-command 'delete-selection
20023 (lambda ()
20024 (not (run-hook-with-args-until-success
20025 'self-insert-uses-region-functions))))
20026 (put 'orgtbl-self-insert-command 'delete-selection
20027 (lambda ()
20028 (not (run-hook-with-args-until-success
20029 'self-insert-uses-region-functions))))
20030 (put 'org-delete-char 'delete-selection 'supersede)
20031 (put 'org-delete-backward-char 'delete-selection 'supersede)
20032 (put 'org-yank 'delete-selection 'yank)
20034 ;; Make `flyspell-mode' delay after some commands
20035 (put 'org-self-insert-command 'flyspell-delayed t)
20036 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20037 (put 'org-delete-char 'flyspell-delayed t)
20038 (put 'org-delete-backward-char 'flyspell-delayed t)
20040 ;; Make pabbrev-mode expand after Org mode commands
20041 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20042 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20044 (defun org-transpose-words ()
20045 "Transpose words for Org.
20046 This uses the `org-mode-transpose-word-syntax-table' syntax
20047 table, which interprets characters in `org-emphasis-alist' as
20048 word constituents."
20049 (interactive)
20050 (with-syntax-table org-mode-transpose-word-syntax-table
20051 (call-interactively 'transpose-words)))
20052 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20054 (defvar org-ctrl-c-ctrl-c-hook nil
20055 "Hook for functions attaching themselves to `C-c C-c'.
20057 This can be used to add additional functionality to the C-c C-c
20058 key which executes context-dependent commands. This hook is run
20059 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20060 run after the last test.
20062 Each function will be called with no arguments. The function
20063 must check if the context is appropriate for it to act. If yes,
20064 it should do its thing and then return a non-nil value. If the
20065 context is wrong, just do nothing and return nil.")
20067 (defvar org-ctrl-c-ctrl-c-final-hook nil
20068 "Hook for functions attaching themselves to `C-c C-c'.
20070 This can be used to add additional functionality to the C-c C-c
20071 key which executes context-dependent commands. This hook is run
20072 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20073 before the first test.
20075 Each function will be called with no arguments. The function
20076 must check if the context is appropriate for it to act. If yes,
20077 it should do its thing and then return a non-nil value. If the
20078 context is wrong, just do nothing and return nil.")
20080 (defvar org-tab-first-hook nil
20081 "Hook for functions to attach themselves to TAB.
20082 See `org-ctrl-c-ctrl-c-hook' for more information.
20083 This hook runs as the first action when TAB is pressed, even before
20084 `org-cycle' messes around with the `outline-regexp' to cater for
20085 inline tasks and plain list item folding.
20086 If any function in this hook returns t, any other actions that
20087 would have been caused by TAB (such as table field motion or visibility
20088 cycling) will not occur.")
20090 (defvar org-tab-after-check-for-table-hook nil
20091 "Hook for functions to attach themselves to TAB.
20092 See `org-ctrl-c-ctrl-c-hook' for more information.
20093 This hook runs after it has been established that the cursor is not in a
20094 table, but before checking if the cursor is in a headline or if global cycling
20095 should be done.
20096 If any function in this hook returns t, not other actions like visibility
20097 cycling will be done.")
20099 (defvar org-tab-after-check-for-cycling-hook nil
20100 "Hook for functions to attach themselves to TAB.
20101 See `org-ctrl-c-ctrl-c-hook' for more information.
20102 This hook runs after it has been established that not table field motion and
20103 not visibility should be done because of current context. This is probably
20104 the place where a package like yasnippets can hook in.")
20106 (defvar org-tab-before-tab-emulation-hook nil
20107 "Hook for functions to attach themselves to TAB.
20108 See `org-ctrl-c-ctrl-c-hook' for more information.
20109 This hook runs after every other options for TAB have been exhausted, but
20110 before indentation and \t insertion takes place.")
20112 (defvar org-metaleft-hook nil
20113 "Hook for functions attaching themselves to `M-left'.
20114 See `org-ctrl-c-ctrl-c-hook' for more information.")
20115 (defvar org-metaright-hook nil
20116 "Hook for functions attaching themselves to `M-right'.
20117 See `org-ctrl-c-ctrl-c-hook' for more information.")
20118 (defvar org-metaup-hook nil
20119 "Hook for functions attaching themselves to `M-up'.
20120 See `org-ctrl-c-ctrl-c-hook' for more information.")
20121 (defvar org-metadown-hook nil
20122 "Hook for functions attaching themselves to `M-down'.
20123 See `org-ctrl-c-ctrl-c-hook' for more information.")
20124 (defvar org-shiftmetaleft-hook nil
20125 "Hook for functions attaching themselves to `M-S-left'.
20126 See `org-ctrl-c-ctrl-c-hook' for more information.")
20127 (defvar org-shiftmetaright-hook nil
20128 "Hook for functions attaching themselves to `M-S-right'.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.")
20130 (defvar org-shiftmetaup-hook nil
20131 "Hook for functions attaching themselves to `M-S-up'.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-shiftmetadown-hook nil
20134 "Hook for functions attaching themselves to `M-S-down'.
20135 See `org-ctrl-c-ctrl-c-hook' for more information.")
20136 (defvar org-metareturn-hook nil
20137 "Hook for functions attaching themselves to `M-RET'.
20138 See `org-ctrl-c-ctrl-c-hook' for more information.")
20139 (defvar org-shiftup-hook nil
20140 "Hook for functions attaching themselves to `S-up'.
20141 See `org-ctrl-c-ctrl-c-hook' for more information.")
20142 (defvar org-shiftup-final-hook nil
20143 "Hook for functions attaching themselves to `S-up'.
20144 This one runs after all other options except shift-select have been excluded.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.")
20146 (defvar org-shiftdown-hook nil
20147 "Hook for functions attaching themselves to `S-down'.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.")
20149 (defvar org-shiftdown-final-hook nil
20150 "Hook for functions attaching themselves to `S-down'.
20151 This one runs after all other options except shift-select have been excluded.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.")
20153 (defvar org-shiftleft-hook nil
20154 "Hook for functions attaching themselves to `S-left'.
20155 See `org-ctrl-c-ctrl-c-hook' for more information.")
20156 (defvar org-shiftleft-final-hook nil
20157 "Hook for functions attaching themselves to `S-left'.
20158 This one runs after all other options except shift-select have been excluded.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.")
20160 (defvar org-shiftright-hook nil
20161 "Hook for functions attaching themselves to `S-right'.
20162 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defvar org-shiftright-final-hook nil
20164 "Hook for functions attaching themselves to `S-right'.
20165 This one runs after all other options except shift-select have been excluded.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defun org-modifier-cursor-error ()
20169 "Throw an error, a modified cursor command was applied in wrong context."
20170 (user-error "This command is active in special context like tables, headlines or items"))
20172 (defun org-shiftselect-error ()
20173 "Throw an error because Shift-Cursor command was applied in wrong context."
20174 (if (and (boundp 'shift-select-mode) shift-select-mode)
20175 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20176 (user-error "This command works only in special context like headlines or timestamps")))
20178 (defun org-call-for-shift-select (cmd)
20179 (let ((this-command-keys-shift-translated t))
20180 (call-interactively cmd)))
20182 (defun org-shifttab (&optional arg)
20183 "Global visibility cycling or move to previous table field.
20184 Call `org-table-previous-field' within a table.
20185 When ARG is nil, cycle globally through visibility states.
20186 When ARG is a numeric prefix, show contents of this level."
20187 (interactive "P")
20188 (cond
20189 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20190 ((integerp arg)
20191 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20192 (message "Content view to level: %d" arg)
20193 (org-content (prefix-numeric-value arg2))
20194 (org-cycle-show-empty-lines t)
20195 (setq org-cycle-global-status 'overview)))
20196 (t (call-interactively 'org-global-cycle))))
20198 (defun org-shiftmetaleft ()
20199 "Promote subtree or delete table column.
20200 Calls `org-promote-subtree', `org-outdent-item-tree', or
20201 `org-table-delete-column', depending on context. See the
20202 individual commands for more information."
20203 (interactive)
20204 (cond
20205 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20206 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20207 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20208 ((if (not (org-region-active-p)) (org-at-item-p)
20209 (save-excursion (goto-char (region-beginning))
20210 (org-at-item-p)))
20211 (call-interactively 'org-outdent-item-tree))
20212 (t (org-modifier-cursor-error))))
20214 (defun org-shiftmetaright ()
20215 "Demote subtree or insert table column.
20216 Calls `org-demote-subtree', `org-indent-item-tree', or
20217 `org-table-insert-column', depending on context. See the
20218 individual commands for more information."
20219 (interactive)
20220 (cond
20221 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20222 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20223 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20224 ((if (not (org-region-active-p)) (org-at-item-p)
20225 (save-excursion (goto-char (region-beginning))
20226 (org-at-item-p)))
20227 (call-interactively 'org-indent-item-tree))
20228 (t (org-modifier-cursor-error))))
20230 (defun org-shiftmetaup (&optional _arg)
20231 "Drag the line at point up.
20232 In a table, kill the current row.
20233 On a clock timestamp, update the value of the timestamp like `S-<up>'
20234 but also adjust the previous clocked item in the clock history.
20235 Everywhere else, drag the line at point up."
20236 (interactive "P")
20237 (cond
20238 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20239 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20240 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20241 (call-interactively 'org-timestamp-up)))
20242 (t (call-interactively 'org-drag-line-backward))))
20244 (defun org-shiftmetadown (&optional _arg)
20245 "Drag the line at point down.
20246 In a table, insert an empty row at the current line.
20247 On a clock timestamp, update the value of the timestamp like `S-<down>'
20248 but also adjust the previous clocked item in the clock history.
20249 Everywhere else, drag the line at point down."
20250 (interactive "P")
20251 (cond
20252 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20253 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20254 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20255 (call-interactively 'org-timestamp-down)))
20256 (t (call-interactively 'org-drag-line-forward))))
20258 (defsubst org-hidden-tree-error ()
20259 (user-error
20260 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20262 (defun org-metaleft (&optional _arg)
20263 "Promote heading, list item at point or move table column left.
20265 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20266 depending on context. With no specific context, calls the Emacs
20267 default `backward-word'. See the individual commands for more
20268 information.
20270 This function runs the hook `org-metaleft-hook' as a first step,
20271 and returns at first non-nil value."
20272 (interactive "P")
20273 (cond
20274 ((run-hook-with-args-until-success 'org-metaleft-hook))
20275 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20276 ((org-with-limited-levels
20277 (or (org-at-heading-p)
20278 (and (org-region-active-p)
20279 (save-excursion
20280 (goto-char (region-beginning))
20281 (org-at-heading-p)))))
20282 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20283 (call-interactively 'org-do-promote))
20284 ;; At an inline task.
20285 ((org-at-heading-p)
20286 (call-interactively 'org-inlinetask-promote))
20287 ((or (org-at-item-p)
20288 (and (org-region-active-p)
20289 (save-excursion
20290 (goto-char (region-beginning))
20291 (org-at-item-p))))
20292 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20293 (call-interactively 'org-outdent-item))
20294 (t (call-interactively 'backward-word))))
20296 (defun org-metaright (&optional _arg)
20297 "Demote heading, list item at point or move table column right.
20299 In front of a drawer or a block keyword, indent it correctly.
20301 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20302 `org-indent-drawer' or `org-indent-block' depending on context.
20303 With no specific context, calls the Emacs default `forward-word'.
20304 See the individual commands for more information.
20306 This function runs the hook `org-metaright-hook' as a first step,
20307 and returns at first non-nil value."
20308 (interactive "P")
20309 (cond
20310 ((run-hook-with-args-until-success 'org-metaright-hook))
20311 ((org-at-table-p) (call-interactively 'org-table-move-column))
20312 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20313 ((org-at-block-p) (call-interactively 'org-indent-block))
20314 ((org-with-limited-levels
20315 (or (org-at-heading-p)
20316 (and (org-region-active-p)
20317 (save-excursion
20318 (goto-char (region-beginning))
20319 (org-at-heading-p)))))
20320 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20321 (call-interactively 'org-do-demote))
20322 ;; At an inline task.
20323 ((org-at-heading-p)
20324 (call-interactively 'org-inlinetask-demote))
20325 ((or (org-at-item-p)
20326 (and (org-region-active-p)
20327 (save-excursion
20328 (goto-char (region-beginning))
20329 (org-at-item-p))))
20330 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20331 (call-interactively 'org-indent-item))
20332 (t (call-interactively 'forward-word))))
20334 (defun org-check-for-hidden (what)
20335 "Check if there are hidden headlines/items in the current visual line.
20336 WHAT can be either `headlines' or `items'. If the current line is
20337 an outline or item heading and it has a folded subtree below it,
20338 this function returns t, nil otherwise."
20339 (let ((re (cond
20340 ((eq what 'headlines) org-outline-regexp-bol)
20341 ((eq what 'items) (org-item-beginning-re))
20342 (t (error "This should not happen"))))
20343 beg end)
20344 (save-excursion
20345 (catch 'exit
20346 (unless (org-region-active-p)
20347 (setq beg (point-at-bol))
20348 (beginning-of-line 2)
20349 (while (and (not (eobp)) ;; this is like `next-line'
20350 (get-char-property (1- (point)) 'invisible))
20351 (beginning-of-line 2))
20352 (setq end (point))
20353 (goto-char beg)
20354 (goto-char (point-at-eol))
20355 (setq end (max end (point)))
20356 (while (re-search-forward re end t)
20357 (when (get-char-property (match-beginning 0) 'invisible)
20358 (throw 'exit t))))
20359 nil))))
20361 (defun org-metaup (&optional _arg)
20362 "Move subtree up or move table row up.
20363 Calls `org-move-subtree-up' or `org-table-move-row' or
20364 `org-move-item-up', depending on context. See the individual commands
20365 for more information."
20366 (interactive "P")
20367 (cond
20368 ((run-hook-with-args-until-success 'org-metaup-hook))
20369 ((org-region-active-p)
20370 (let* ((a (min (region-beginning) (region-end)))
20371 (b (1- (max (region-beginning) (region-end))))
20372 (c (save-excursion (goto-char a)
20373 (move-beginning-of-line 0)))
20374 (d (save-excursion (goto-char a)
20375 (move-end-of-line 0) (point))))
20376 (transpose-regions a b c d)
20377 (goto-char c)))
20378 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20379 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20380 ((org-at-item-p) (call-interactively 'org-move-item-up))
20381 (t (org-drag-element-backward))))
20383 (defun org-metadown (&optional _arg)
20384 "Move subtree down or move table row down.
20385 Calls `org-move-subtree-down' or `org-table-move-row' or
20386 `org-move-item-down', depending on context. See the individual
20387 commands for more information."
20388 (interactive "P")
20389 (cond
20390 ((run-hook-with-args-until-success 'org-metadown-hook))
20391 ((org-region-active-p)
20392 (let* ((a (min (region-beginning) (region-end)))
20393 (b (max (region-beginning) (region-end)))
20394 (c (save-excursion (goto-char b)
20395 (move-beginning-of-line 1)))
20396 (d (save-excursion (goto-char b)
20397 (move-end-of-line 1) (1+ (point)))))
20398 (transpose-regions a b c d)
20399 (goto-char d)))
20400 ((org-at-table-p) (call-interactively 'org-table-move-row))
20401 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20402 ((org-at-item-p) (call-interactively 'org-move-item-down))
20403 (t (org-drag-element-forward))))
20405 (defun org-shiftup (&optional arg)
20406 "Increase item in timestamp or increase priority of current headline.
20407 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20408 depending on context. See the individual commands for more information."
20409 (interactive "P")
20410 (cond
20411 ((run-hook-with-args-until-success 'org-shiftup-hook))
20412 ((and org-support-shift-select (org-region-active-p))
20413 (org-call-for-shift-select 'previous-line))
20414 ((org-at-timestamp-p 'lax)
20415 (call-interactively (if org-edit-timestamp-down-means-later
20416 'org-timestamp-down 'org-timestamp-up)))
20417 ((and (not (eq org-support-shift-select 'always))
20418 org-enable-priority-commands
20419 (org-at-heading-p))
20420 (call-interactively 'org-priority-up))
20421 ((and (not org-support-shift-select) (org-at-item-p))
20422 (call-interactively 'org-previous-item))
20423 ((org-clocktable-try-shift 'up arg))
20424 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20425 (org-support-shift-select
20426 (org-call-for-shift-select 'previous-line))
20427 (t (org-shiftselect-error))))
20429 (defun org-shiftdown (&optional arg)
20430 "Decrease item in timestamp or decrease priority of current headline.
20431 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20432 depending on context. See the individual commands for more information."
20433 (interactive "P")
20434 (cond
20435 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20436 ((and org-support-shift-select (org-region-active-p))
20437 (org-call-for-shift-select 'next-line))
20438 ((org-at-timestamp-p 'lax)
20439 (call-interactively (if org-edit-timestamp-down-means-later
20440 'org-timestamp-up 'org-timestamp-down)))
20441 ((and (not (eq org-support-shift-select 'always))
20442 org-enable-priority-commands
20443 (org-at-heading-p))
20444 (call-interactively 'org-priority-down))
20445 ((and (not org-support-shift-select) (org-at-item-p))
20446 (call-interactively 'org-next-item))
20447 ((org-clocktable-try-shift 'down arg))
20448 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20449 (org-support-shift-select
20450 (org-call-for-shift-select 'next-line))
20451 (t (org-shiftselect-error))))
20453 (defun org-shiftright (&optional arg)
20454 "Cycle the thing at point or in the current line, depending on context.
20455 Depending on context, this does one of the following:
20457 - switch a timestamp at point one day into the future
20458 - on a headline, switch to the next TODO keyword.
20459 - on an item, switch entire list to the next bullet type
20460 - on a property line, switch to the next allowed value
20461 - on a clocktable definition line, move time block into the future"
20462 (interactive "P")
20463 (cond
20464 ((run-hook-with-args-until-success 'org-shiftright-hook))
20465 ((and org-support-shift-select (org-region-active-p))
20466 (org-call-for-shift-select 'forward-char))
20467 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20468 ((and (not (eq org-support-shift-select 'always))
20469 (org-at-heading-p))
20470 (let ((org-inhibit-logging
20471 (not org-treat-S-cursor-todo-selection-as-state-change))
20472 (org-inhibit-blocking
20473 (not org-treat-S-cursor-todo-selection-as-state-change)))
20474 (org-call-with-arg 'org-todo 'right)))
20475 ((or (and org-support-shift-select
20476 (not (eq org-support-shift-select 'always))
20477 (org-at-item-bullet-p))
20478 (and (not org-support-shift-select) (org-at-item-p)))
20479 (org-call-with-arg 'org-cycle-list-bullet nil))
20480 ((and (not (eq org-support-shift-select 'always))
20481 (org-at-property-p))
20482 (call-interactively 'org-property-next-allowed-value))
20483 ((org-clocktable-try-shift 'right arg))
20484 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20485 (org-support-shift-select
20486 (org-call-for-shift-select 'forward-char))
20487 (t (org-shiftselect-error))))
20489 (defun org-shiftleft (&optional arg)
20490 "Cycle the thing at point or in the current line, depending on context.
20491 Depending on context, this does one of the following:
20493 - switch a timestamp at point one day into the past
20494 - on a headline, switch to the previous TODO keyword.
20495 - on an item, switch entire list to the previous bullet type
20496 - on a property line, switch to the previous allowed value
20497 - on a clocktable definition line, move time block into the past"
20498 (interactive "P")
20499 (cond
20500 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20501 ((and org-support-shift-select (org-region-active-p))
20502 (org-call-for-shift-select 'backward-char))
20503 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20504 ((and (not (eq org-support-shift-select 'always))
20505 (org-at-heading-p))
20506 (let ((org-inhibit-logging
20507 (not org-treat-S-cursor-todo-selection-as-state-change))
20508 (org-inhibit-blocking
20509 (not org-treat-S-cursor-todo-selection-as-state-change)))
20510 (org-call-with-arg 'org-todo 'left)))
20511 ((or (and org-support-shift-select
20512 (not (eq org-support-shift-select 'always))
20513 (org-at-item-bullet-p))
20514 (and (not org-support-shift-select) (org-at-item-p)))
20515 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20516 ((and (not (eq org-support-shift-select 'always))
20517 (org-at-property-p))
20518 (call-interactively 'org-property-previous-allowed-value))
20519 ((org-clocktable-try-shift 'left arg))
20520 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20521 (org-support-shift-select
20522 (org-call-for-shift-select 'backward-char))
20523 (t (org-shiftselect-error))))
20525 (defun org-shiftcontrolright ()
20526 "Switch to next TODO set."
20527 (interactive)
20528 (cond
20529 ((and org-support-shift-select (org-region-active-p))
20530 (org-call-for-shift-select 'forward-word))
20531 ((and (not (eq org-support-shift-select 'always))
20532 (org-at-heading-p))
20533 (org-call-with-arg 'org-todo 'nextset))
20534 (org-support-shift-select
20535 (org-call-for-shift-select 'forward-word))
20536 (t (org-shiftselect-error))))
20538 (defun org-shiftcontrolleft ()
20539 "Switch to previous TODO set."
20540 (interactive)
20541 (cond
20542 ((and org-support-shift-select (org-region-active-p))
20543 (org-call-for-shift-select 'backward-word))
20544 ((and (not (eq org-support-shift-select 'always))
20545 (org-at-heading-p))
20546 (org-call-with-arg 'org-todo 'previousset))
20547 (org-support-shift-select
20548 (org-call-for-shift-select 'backward-word))
20549 (t (org-shiftselect-error))))
20551 (defun org-shiftcontrolup (&optional n)
20552 "Change timestamps synchronously up in CLOCK log lines.
20553 Optional argument N tells to change by that many units."
20554 (interactive "P")
20555 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20556 (let (org-support-shift-select)
20557 (org-clock-timestamps-up n))
20558 (user-error "Not at a clock log")))
20560 (defun org-shiftcontroldown (&optional n)
20561 "Change timestamps synchronously down in CLOCK log lines.
20562 Optional argument N tells to change by that many units."
20563 (interactive "P")
20564 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20565 (let (org-support-shift-select)
20566 (org-clock-timestamps-down n))
20567 (user-error "Not at a clock log")))
20569 (defun org-increase-number-at-point (&optional inc)
20570 "Increment the number at point.
20571 With an optional prefix numeric argument INC, increment using
20572 this numeric value."
20573 (interactive "p")
20574 (if (not (number-at-point))
20575 (user-error "Not on a number")
20576 (unless inc (setq inc 1))
20577 (let ((pos (point))
20578 (beg (skip-chars-backward "-+^/*0-9eE."))
20579 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20580 (setq nap (buffer-substring-no-properties
20581 (+ pos beg) (+ pos beg end)))
20582 (delete-region (+ pos beg) (+ pos beg end))
20583 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20584 (when (org-at-table-p)
20585 (org-table-align)
20586 (org-table-end-of-field 1))))
20588 (defun org-decrease-number-at-point (&optional inc)
20589 "Decrement the number at point.
20590 With an optional prefix numeric argument INC, decrement using
20591 this numeric value."
20592 (interactive "p")
20593 (org-increase-number-at-point (- (or inc 1))))
20595 (defun org-ctrl-c-ret ()
20596 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20597 (interactive)
20598 (cond
20599 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20600 (t (call-interactively 'org-insert-heading))))
20602 (defun org-find-visible ()
20603 (let ((s (point)))
20604 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20605 (get-char-property s 'invisible)))
20607 (defun org-find-invisible ()
20608 (let ((s (point)))
20609 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20610 (not (get-char-property s 'invisible))))
20613 (defun org-copy-visible (beg end)
20614 "Copy the visible parts of the region."
20615 (interactive "r")
20616 (let ((result ""))
20617 (while (/= beg end)
20618 (when (get-char-property beg 'invisible)
20619 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20620 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20621 (setq result (concat result (buffer-substring beg next)))
20622 (setq beg next)))
20623 (kill-new result)))
20625 (defun org-copy-special ()
20626 "Copy region in table or copy current subtree.
20627 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20628 context. See the individual commands for more information."
20629 (interactive)
20630 (call-interactively
20631 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20633 (defun org-cut-special ()
20634 "Cut region in table or cut current subtree.
20635 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20636 context. See the individual commands for more information."
20637 (interactive)
20638 (call-interactively
20639 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20641 (defun org-paste-special (arg)
20642 "Paste rectangular region into table, or past subtree relative to level.
20643 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20644 See the individual commands for more information."
20645 (interactive "P")
20646 (if (org-at-table-p)
20647 (org-table-paste-rectangle)
20648 (org-paste-subtree arg)))
20650 (defun org-edit-special (&optional arg)
20651 "Call a special editor for the element at point.
20652 When at a table, call the formula editor with `org-table-edit-formulas'.
20653 When in a source code block, call `org-edit-src-code'.
20654 When in a fixed-width region, call `org-edit-fixed-width-region'.
20655 When in an export block, call `org-edit-export-block'.
20656 When in a LaTeX environment, call `org-edit-latex-environment'.
20657 When at an #+INCLUDE keyword, visit the included file.
20658 When at a footnote reference, call `org-edit-footnote-reference'
20659 On a link, call `ffap' to visit the link at point.
20660 Otherwise, return a user error."
20661 (interactive "P")
20662 (let ((element (org-element-at-point)))
20663 (barf-if-buffer-read-only)
20664 (pcase (org-element-type element)
20665 (`src-block
20666 (if (not arg) (org-edit-src-code)
20667 (let* ((info (org-babel-get-src-block-info))
20668 (lang (nth 0 info))
20669 (params (nth 2 info))
20670 (session (cdr (assq :session params))))
20671 (if (not session) (org-edit-src-code)
20672 ;; At a src-block with a session and function called with
20673 ;; an ARG: switch to the buffer related to the inferior
20674 ;; process.
20675 (switch-to-buffer
20676 (funcall (intern (concat "org-babel-prep-session:" lang))
20677 session params))))))
20678 (`keyword
20679 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20680 (org-open-link-from-string
20681 (format "[[%s]]"
20682 (expand-file-name
20683 (let ((value (org-element-property :value element)))
20684 (cond ((org-file-url-p value)
20685 (user-error "The file is specified as a URL, cannot be edited"))
20686 ((not (org-string-nw-p value))
20687 (user-error "No file to edit"))
20688 ((string-match "\\`\"\\(.*?\\)\"" value)
20689 (match-string 1 value))
20690 ((string-match "\\`[^ \t\"]\\S-*" value)
20691 (match-string 0 value))
20692 (t (user-error "No valid file specified")))))))
20693 (user-error "No special environment to edit here")))
20694 (`table
20695 (if (eq (org-element-property :type element) 'table.el)
20696 (org-edit-table.el)
20697 (call-interactively 'org-table-edit-formulas)))
20698 ;; Only Org tables contain `table-row' type elements.
20699 (`table-row (call-interactively 'org-table-edit-formulas))
20700 (`example-block (org-edit-src-code))
20701 (`export-block (org-edit-export-block))
20702 (`fixed-width (org-edit-fixed-width-region))
20703 (`latex-environment (org-edit-latex-environment))
20705 ;; No notable element at point. Though, we may be at a link or
20706 ;; a footnote reference, which are objects. Thus, scan deeper.
20707 (let ((context (org-element-context element)))
20708 (pcase (org-element-type context)
20709 (`footnote-reference (org-edit-footnote-reference))
20710 (`inline-src-block (org-edit-inline-src-code))
20711 (`link (call-interactively #'ffap))
20712 (_ (user-error "No special environment to edit here"))))))))
20714 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20715 (defun org-ctrl-c-ctrl-c (&optional arg)
20716 "Set tags in headline, or update according to changed information at point.
20718 This command does many different things, depending on context:
20720 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20721 this is what we do.
20723 - If the cursor is on a statistics cookie, update it.
20725 - If the cursor is in a headline, prompt for tags and insert them
20726 into the current line, aligned to `org-tags-column'. When called
20727 with prefix arg, realign all tags in the current buffer.
20729 - If the cursor is in one of the special #+KEYWORD lines, this
20730 triggers scanning the buffer for these lines and updating the
20731 information.
20733 - If the cursor is inside a table, realign the table. This command
20734 works even if the automatic table editor has been turned off.
20736 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20737 the entire table.
20739 - If the cursor is at a footnote reference or definition, jump to
20740 the corresponding definition or references, respectively.
20742 - If the cursor is a the beginning of a dynamic block, update it.
20744 - If the current buffer is a capture buffer, close note and file it.
20746 - If the cursor is on a <<<target>>>, update radio targets and
20747 corresponding links in this buffer.
20749 - If the cursor is on a numbered item in a plain list, renumber the
20750 ordered list.
20752 - If the cursor is on a checkbox, toggle it.
20754 - If the cursor is on a code block, evaluate it. The variable
20755 `org-confirm-babel-evaluate' can be used to control prompting
20756 before code block evaluation, by default every code block
20757 evaluation requires confirmation. Code block evaluation can be
20758 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20759 (interactive "P")
20760 (cond
20761 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20762 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20763 (org-remove-occur-highlights)
20764 (message "Temporary highlights/overlays removed from current buffer"))
20765 ((and (local-variable-p 'org-finish-function)
20766 (fboundp org-finish-function))
20767 (funcall org-finish-function))
20768 ((org-babel-hash-at-point))
20769 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20771 (let* ((context
20772 (org-element-lineage
20773 (org-element-context)
20774 ;; Limit to supported contexts.
20775 '(babel-call clock dynamic-block footnote-definition
20776 footnote-reference inline-babel-call inline-src-block
20777 inlinetask item keyword node-property paragraph
20778 plain-list property-drawer radio-target src-block
20779 statistics-cookie table table-cell table-row
20780 timestamp)
20782 (type (org-element-type context)))
20783 ;; For convenience: at the first line of a paragraph on the same
20784 ;; line as an item, apply function on that item instead.
20785 (when (eq type 'paragraph)
20786 (let ((parent (org-element-property :parent context)))
20787 (when (and (eq (org-element-type parent) 'item)
20788 (= (line-beginning-position)
20789 (org-element-property :begin parent)))
20790 (setq context parent)
20791 (setq type 'item))))
20792 ;; Act according to type of element or object at point.
20794 ;; Do nothing on a blank line, except if it is contained in
20795 ;; a src block. Hence, we first check if point is in such
20796 ;; a block and then if it is at a blank line.
20797 (pcase type
20798 ((or `inline-src-block `src-block)
20799 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20800 (org-babel-eval-wipe-error-buffer)
20801 (org-babel-execute-src-block
20802 current-prefix-arg (org-babel-get-src-block-info nil context))))
20803 ((guard (org-match-line "[ \t]*$"))
20804 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20805 (user-error
20806 (substitute-command-keys
20807 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20808 ((or `babel-call `inline-babel-call)
20809 (let ((info (org-babel-lob-get-info context)))
20810 (when info (org-babel-execute-src-block nil info))))
20811 (`clock (org-clock-update-time-maybe))
20812 (`dynamic-block
20813 (save-excursion
20814 (goto-char (org-element-property :post-affiliated context))
20815 (org-update-dblock)))
20816 (`footnote-definition
20817 (goto-char (org-element-property :post-affiliated context))
20818 (call-interactively 'org-footnote-action))
20819 (`footnote-reference (call-interactively #'org-footnote-action))
20820 ((or `headline `inlinetask)
20821 (save-excursion (goto-char (org-element-property :begin context))
20822 (call-interactively #'org-set-tags)))
20823 (`item
20824 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20825 ;; unconditionally, whereas `C-u' will toggle its presence.
20826 ;; Without a universal argument, if the item has a checkbox,
20827 ;; toggle it. Otherwise repair the list.
20828 (let* ((box (org-element-property :checkbox context))
20829 (struct (org-element-property :structure context))
20830 (old-struct (copy-tree struct))
20831 (parents (org-list-parents-alist struct))
20832 (prevs (org-list-prevs-alist struct))
20833 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20834 (org-list-set-checkbox
20835 (org-element-property :begin context) struct
20836 (cond ((equal arg '(16)) "[-]")
20837 ((and (not box) (equal arg '(4))) "[ ]")
20838 ((or (not box) (equal arg '(4))) nil)
20839 ((eq box 'on) "[ ]")
20840 (t "[X]")))
20841 ;; Mimic `org-list-write-struct' but with grabbing a return
20842 ;; value from `org-list-struct-fix-box'.
20843 (org-list-struct-fix-ind struct parents 2)
20844 (org-list-struct-fix-item-end struct)
20845 (org-list-struct-fix-bul struct prevs)
20846 (org-list-struct-fix-ind struct parents)
20847 (let ((block-item
20848 (org-list-struct-fix-box struct parents prevs orderedp)))
20849 (if (and box (equal struct old-struct))
20850 (if (equal arg '(16))
20851 (message "Checkboxes already reset")
20852 (user-error "Cannot toggle this checkbox: %s"
20853 (if (eq box 'on)
20854 "all subitems checked"
20855 "unchecked subitems")))
20856 (org-list-struct-apply-struct struct old-struct)
20857 (org-update-checkbox-count-maybe))
20858 (when block-item
20859 (message "Checkboxes were removed due to empty box at line %d"
20860 (org-current-line block-item))))))
20861 (`keyword
20862 (let ((org-inhibit-startup-visibility-stuff t)
20863 (org-startup-align-all-tables nil))
20864 (when (boundp 'org-table-coordinate-overlays)
20865 (mapc #'delete-overlay org-table-coordinate-overlays)
20866 (setq org-table-coordinate-overlays nil))
20867 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20868 (message "Local setup has been refreshed"))
20869 (`plain-list
20870 ;; At a plain list, with a double C-u argument, set
20871 ;; checkboxes of each item to "[-]", whereas a single one
20872 ;; will toggle their presence according to the state of the
20873 ;; first item in the list. Without an argument, repair the
20874 ;; list.
20875 (let* ((begin (org-element-property :contents-begin context))
20876 (beginm (move-marker (make-marker) begin))
20877 (struct (org-element-property :structure context))
20878 (old-struct (copy-tree struct))
20879 (first-box (save-excursion
20880 (goto-char begin)
20881 (looking-at org-list-full-item-re)
20882 (match-string-no-properties 3)))
20883 (new-box (cond ((equal arg '(16)) "[-]")
20884 ((equal arg '(4)) (unless first-box "[ ]"))
20885 ((equal first-box "[X]") "[ ]")
20886 (t "[X]"))))
20887 (cond
20888 (arg
20889 (dolist (pos
20890 (org-list-get-all-items
20891 begin struct (org-list-prevs-alist struct)))
20892 (org-list-set-checkbox pos struct new-box)))
20893 ((and first-box (eq (point) begin))
20894 ;; For convenience, when point is at bol on the first
20895 ;; item of the list and no argument is provided, simply
20896 ;; toggle checkbox of that item, if any.
20897 (org-list-set-checkbox begin struct new-box)))
20898 (org-list-write-struct
20899 struct (org-list-parents-alist struct) old-struct)
20900 (org-update-checkbox-count-maybe)
20901 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20902 ((or `property-drawer `node-property)
20903 (call-interactively #'org-property-action))
20904 (`radio-target
20905 (call-interactively #'org-update-radio-target-regexp))
20906 (`statistics-cookie
20907 (call-interactively #'org-update-statistics-cookies))
20908 ((or `table `table-cell `table-row)
20909 ;; At a table, recalculate every field and align it. Also
20910 ;; send the table if necessary. If the table has
20911 ;; a `table.el' type, just give up. At a table row or cell,
20912 ;; maybe recalculate line but always align table.
20913 (if (eq (org-element-property :type context) 'table.el)
20914 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20915 Use `\\[org-edit-special]' to edit table.el tables"))
20916 (if (or (eq type 'table)
20917 ;; Check if point is at a TBLFM line.
20918 (and (eq type 'table-row)
20919 (= (point) (org-element-property :end context))))
20920 (save-excursion
20921 (if (org-at-TBLFM-p)
20922 (progn (require 'org-table)
20923 (org-table-calc-current-TBLFM))
20924 (goto-char (org-element-property :contents-begin context))
20925 (org-call-with-arg 'org-table-recalculate (or arg t))
20926 (orgtbl-send-table 'maybe)))
20927 (org-table-maybe-eval-formula)
20928 (cond (arg (call-interactively #'org-table-recalculate))
20929 ((org-table-maybe-recalculate-line))
20930 (t (org-table-align))))))
20931 (`timestamp (org-timestamp-change 0 'day))
20932 ((and `nil (guard (org-at-heading-p)))
20933 ;; When point is on an unsupported object type, we can miss
20934 ;; the fact that it also is at a heading. Handle it here.
20935 (call-interactively #'org-set-tags))
20936 ((guard
20937 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20939 (user-error
20940 (substitute-command-keys
20941 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20943 (defun org-mode-restart ()
20944 (interactive)
20945 (let ((indent-status (bound-and-true-p org-indent-mode)))
20946 (funcall major-mode)
20947 (hack-local-variables)
20948 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20949 (org-indent-mode -1))
20950 (org-reset-file-cache))
20951 (message "%s restarted" major-mode))
20953 (defun org-kill-note-or-show-branches ()
20954 "Abort storing current note, or call `outline-show-branches'."
20955 (interactive)
20956 (if (not org-finish-function)
20957 (progn
20958 (outline-hide-subtree)
20959 (call-interactively 'outline-show-branches))
20960 (let ((org-note-abort t))
20961 (funcall org-finish-function))))
20963 (defun org-delete-indentation (&optional arg)
20964 "Join current line to previous and fix whitespace at join.
20966 If previous line is a headline add to headline title. Otherwise
20967 the function calls `delete-indentation'.
20969 With a non-nil optional argument, join it to the following one."
20970 (interactive "*P")
20971 (if (save-excursion
20972 (beginning-of-line (if arg 1 0))
20973 (let ((case-fold-search nil))
20974 (looking-at org-complex-heading-regexp)))
20975 ;; At headline.
20976 (let ((tags-column (when (match-beginning 5)
20977 (save-excursion (goto-char (match-beginning 5))
20978 (current-column))))
20979 (string (concat " " (progn (when arg (forward-line 1))
20980 (org-trim (delete-and-extract-region
20981 (line-beginning-position)
20982 (line-end-position)))))))
20983 (unless (bobp) (delete-region (point) (1- (point))))
20984 (goto-char (or (match-end 4)
20985 (match-beginning 5)
20986 (match-end 0)))
20987 (skip-chars-backward " \t")
20988 (save-excursion (insert string))
20989 ;; Adjust alignment of tags.
20990 (cond
20991 ((not tags-column)) ;no tags
20992 (org-auto-align-tags (org-set-tags nil t))
20993 (t (org--align-tags-here tags-column)))) ;preserve tags column
20994 (delete-indentation arg)))
20996 (defun org-open-line (n)
20997 "Insert a new row in tables, call `open-line' elsewhere.
20998 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20999 As a special case, when a document starts with a table, allow to
21000 call `open-line' on the very first character."
21001 (interactive "*p")
21002 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21003 (org-table-insert-row)
21004 (open-line n)))
21006 (defun org-return (&optional indent)
21007 "Goto next table row or insert a newline.
21009 Calls `org-table-next-row' or `newline', depending on context.
21011 When optional INDENT argument is non-nil, call
21012 `newline-and-indent' instead of `newline'.
21014 When `org-return-follows-link' is non-nil and point is on
21015 a timestamp or a link, call `org-open-at-point'. However, it
21016 will not happen if point is in a table or on a \"dead\"
21017 object (e.g., within a comment). In these case, you need to use
21018 `org-open-at-point' directly."
21019 (interactive)
21020 (let ((context (if org-return-follows-link (org-element-context)
21021 (org-element-at-point))))
21022 (cond
21023 ;; In a table, call `org-table-next-row'.
21024 ((or (and (eq (org-element-type context) 'table)
21025 (>= (point) (org-element-property :contents-begin context))
21026 (< (point) (org-element-property :contents-end context)))
21027 (org-element-lineage context '(table-row table-cell) t))
21028 (org-table-justify-field-maybe)
21029 (call-interactively #'org-table-next-row))
21030 ;; On a link or a timestamp, call `org-open-at-point' if
21031 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21032 ;; locations, e.g., in a comment, as `org-open-at-point'.
21033 ((and org-return-follows-link
21034 (or (org-in-regexp org-ts-regexp-both nil t)
21035 (org-in-regexp org-tsr-regexp-both nil t)
21036 (org-in-regexp org-any-link-re nil t)))
21037 (call-interactively #'org-open-at-point))
21038 ;; Insert newline in heading, but preserve tags.
21039 ((and (not (bolp))
21040 (save-excursion (beginning-of-line)
21041 (let ((case-fold-search nil))
21042 (looking-at org-complex-heading-regexp))))
21043 ;; At headline. Split line. However, if point is on keyword,
21044 ;; priority cookie or tags, do not break any of them: add
21045 ;; a newline after the headline instead.
21046 (let ((tags-column (and (match-beginning 5)
21047 (save-excursion (goto-char (match-beginning 5))
21048 (current-column))))
21049 (string
21050 (when (and (match-end 4) (org-point-in-group (point) 4))
21051 (delete-and-extract-region (point) (match-end 4)))))
21052 ;; Adjust tag alignment.
21053 (cond
21054 ((not (and tags-column string)))
21055 (org-auto-align-tags (org-set-tags nil t))
21056 (t (org--align-tags-here tags-column))) ;preserve tags column
21057 (end-of-line)
21058 (org-show-entry)
21059 (if indent (newline-and-indent) (newline))
21060 (when string (save-excursion (insert (org-trim string))))))
21061 ;; In a list, make sure indenting keeps trailing text within.
21062 ((and indent
21063 (not (eolp))
21064 (org-element-lineage context '(item)))
21065 (let ((trailing-data
21066 (delete-and-extract-region (point) (line-end-position))))
21067 (newline-and-indent)
21068 (save-excursion (insert trailing-data))))
21069 (t (if indent (newline-and-indent) (newline))))))
21071 (defun org-return-indent ()
21072 "Goto next table row or insert a newline and indent.
21073 Calls `org-table-next-row' or `newline-and-indent', depending on
21074 context. See the individual commands for more information."
21075 (interactive)
21076 (org-return t))
21078 (defun org-ctrl-c-star ()
21079 "Compute table, or change heading status of lines.
21080 Calls `org-table-recalculate' or `org-toggle-heading',
21081 depending on context."
21082 (interactive)
21083 (cond
21084 ((org-at-table-p)
21085 (call-interactively 'org-table-recalculate))
21087 ;; Convert all lines in region to list items
21088 (call-interactively 'org-toggle-heading))))
21090 (defun org-ctrl-c-minus ()
21091 "Insert separator line in table or modify bullet status of line.
21092 Also turns a plain line or a region of lines into list items.
21093 Calls `org-table-insert-hline', `org-toggle-item', or
21094 `org-cycle-list-bullet', depending on context."
21095 (interactive)
21096 (cond
21097 ((org-at-table-p)
21098 (call-interactively 'org-table-insert-hline))
21099 ((org-region-active-p)
21100 (call-interactively 'org-toggle-item))
21101 ((org-in-item-p)
21102 (call-interactively 'org-cycle-list-bullet))
21104 (call-interactively 'org-toggle-item))))
21106 (defun org-toggle-heading (&optional nstars)
21107 "Convert headings to normal text, or items or text to headings.
21108 If there is no active region, only convert the current line.
21110 With a `\\[universal-argument]' prefix, convert the whole list at
21111 point into heading.
21113 In a region:
21115 - If the first non blank line is a headline, remove the stars
21116 from all headlines in the region.
21118 - If it is a normal line, turn each and every normal line (i.e.,
21119 not an heading or an item) in the region into headings. If you
21120 want to convert only the first line of this region, use one
21121 universal prefix argument.
21123 - If it is a plain list item, turn all plain list items into headings.
21125 When converting a line into a heading, the number of stars is chosen
21126 such that the lines become children of the current entry. However,
21127 when a numeric prefix argument is given, its value determines the
21128 number of stars to add."
21129 (interactive "P")
21130 (let ((skip-blanks
21131 (function
21132 ;; Return beginning of first non-blank line, starting from
21133 ;; line at POS.
21134 (lambda (pos)
21135 (save-excursion
21136 (goto-char pos)
21137 (while (org-at-comment-p) (forward-line))
21138 (skip-chars-forward " \r\t\n")
21139 (point-at-bol)))))
21140 beg end toggled)
21141 ;; Determine boundaries of changes. If a universal prefix has
21142 ;; been given, put the list in a region. If region ends at a bol,
21143 ;; do not consider the last line to be in the region.
21145 (when (and current-prefix-arg (org-at-item-p))
21146 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21147 (org-mark-element))
21149 (if (org-region-active-p)
21150 (setq beg (funcall skip-blanks (region-beginning))
21151 end (copy-marker (save-excursion
21152 (goto-char (region-end))
21153 (if (bolp) (point) (point-at-eol)))))
21154 (setq beg (funcall skip-blanks (point-at-bol))
21155 end (copy-marker (point-at-eol))))
21156 ;; Ensure inline tasks don't count as headings.
21157 (org-with-limited-levels
21158 (save-excursion
21159 (goto-char beg)
21160 (cond
21161 ;; Case 1. Started at an heading: de-star headings.
21162 ((org-at-heading-p)
21163 (while (< (point) end)
21164 (when (org-at-heading-p t)
21165 (looking-at org-outline-regexp) (replace-match "")
21166 (setq toggled t))
21167 (forward-line)))
21168 ;; Case 2. Started at an item: change items into headlines.
21169 ;; One star will be added by `org-list-to-subtree'.
21170 ((org-at-item-p)
21171 (while (< (point) end)
21172 (when (org-at-item-p)
21173 ;; Pay attention to cases when region ends before list.
21174 (let* ((struct (org-list-struct))
21175 (list-end
21176 (min (org-list-get-bottom-point struct) (1+ end))))
21177 (save-restriction
21178 (narrow-to-region (point) list-end)
21179 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21180 (setq toggled t))
21181 (forward-line)))
21182 ;; Case 3. Started at normal text: make every line an heading,
21183 ;; skipping headlines and items.
21184 (t (let* ((stars
21185 (make-string
21186 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21187 (add-stars
21188 (cond (nstars "") ; stars from prefix only
21189 ((equal stars "") "*") ; before first heading
21190 (org-odd-levels-only "**") ; inside heading, odd
21191 (t "*"))) ; inside heading, oddeven
21192 (rpl (concat stars add-stars " "))
21193 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21194 (while (< (point) (if (equal nstars '(4)) lend end))
21195 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21196 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21197 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21198 (forward-line)))))))
21199 (unless toggled (message "Cannot toggle heading from here"))))
21201 (defun org-meta-return (&optional arg)
21202 "Insert a new heading or wrap a region in a table.
21203 Calls `org-insert-heading', `org-insert-item' or
21204 `org-table-wrap-region', depending on context. When called with
21205 an argument, unconditionally call `org-insert-heading'."
21206 (interactive "P")
21207 (org-check-before-invisible-edit 'insert)
21208 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21209 (call-interactively (cond (arg #'org-insert-heading)
21210 ((org-at-table-p) #'org-table-wrap-region)
21211 ((org-in-item-p) #'org-insert-item)
21212 (t #'org-insert-heading)))))
21214 ;;; Menu entries
21216 (defsubst org-in-subtree-not-table-p ()
21217 "Are we in a subtree and not in a table?"
21218 (and (not (org-before-first-heading-p))
21219 (not (org-at-table-p))))
21221 ;; Define the Org mode menus
21222 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21223 '("Tbl"
21224 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21225 ["Next Field" org-cycle (org-at-table-p)]
21226 ["Previous Field" org-shifttab (org-at-table-p)]
21227 ["Next Row" org-return (org-at-table-p)]
21228 "--"
21229 ["Blank Field" org-table-blank-field (org-at-table-p)]
21230 ["Edit Field" org-table-edit-field (org-at-table-p)]
21231 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21232 "--"
21233 ("Column"
21234 ["Move Column Left" org-metaleft (org-at-table-p)]
21235 ["Move Column Right" org-metaright (org-at-table-p)]
21236 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21237 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21238 ("Row"
21239 ["Move Row Up" org-metaup (org-at-table-p)]
21240 ["Move Row Down" org-metadown (org-at-table-p)]
21241 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21242 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21243 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21244 "--"
21245 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21246 ("Rectangle"
21247 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21248 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21249 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21250 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21251 "--"
21252 ("Calculate"
21253 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21254 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21255 ["Edit Formulas" org-edit-special (org-at-table-p)]
21256 "--"
21257 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21258 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21259 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21260 "--"
21261 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21262 "--"
21263 ["Sum Column/Rectangle" org-table-sum
21264 (or (org-at-table-p) (org-region-active-p))]
21265 ["Which Column?" org-table-current-column (org-at-table-p)])
21266 ["Debug Formulas"
21267 org-table-toggle-formula-debugger
21268 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21269 ["Show Col/Row Numbers"
21270 org-table-toggle-coordinate-overlays
21271 :style toggle
21272 :selected (bound-and-true-p org-table-overlay-coordinates)]
21273 "--"
21274 ["Create" org-table-create (not (org-at-table-p))]
21275 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21276 ["Import from File" org-table-import (not (org-at-table-p))]
21277 ["Export to File" org-table-export (org-at-table-p)]
21278 "--"
21279 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21280 "--"
21281 ("Plot"
21282 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21283 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21285 (easy-menu-define org-org-menu org-mode-map "Org menu"
21286 '("Org"
21287 ("Show/Hide"
21288 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21289 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21290 ["Sparse Tree..." org-sparse-tree t]
21291 ["Reveal Context" org-reveal t]
21292 ["Show All" outline-show-all t]
21293 "--"
21294 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21295 "--"
21296 ["New Heading" org-insert-heading t]
21297 ("Navigate Headings"
21298 ["Up" outline-up-heading t]
21299 ["Next" outline-next-visible-heading t]
21300 ["Previous" outline-previous-visible-heading t]
21301 ["Next Same Level" outline-forward-same-level t]
21302 ["Previous Same Level" outline-backward-same-level t]
21303 "--"
21304 ["Jump" org-goto t])
21305 ("Edit Structure"
21306 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21307 "--"
21308 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21309 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21310 "--"
21311 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21312 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21313 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21314 "--"
21315 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21316 "--"
21317 ["Copy visible text" org-copy-visible t]
21318 "--"
21319 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21320 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21321 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21322 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21323 "--"
21324 ["Sort Region/Children" org-sort t]
21325 "--"
21326 ["Convert to odd levels" org-convert-to-odd-levels t]
21327 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21328 ("Editing"
21329 ["Emphasis..." org-emphasize t]
21330 ["Edit Source Example" org-edit-special t]
21331 "--"
21332 ["Footnote new/jump" org-footnote-action t]
21333 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21334 ("Archive"
21335 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21336 "--"
21337 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21338 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21339 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21341 "--"
21342 ("Hyperlinks"
21343 ["Store Link (Global)" org-store-link t]
21344 ["Find existing link to here" org-occur-link-in-agenda-files t]
21345 ["Insert Link" org-insert-link t]
21346 ["Follow Link" org-open-at-point t]
21347 "--"
21348 ["Next link" org-next-link t]
21349 ["Previous link" org-previous-link t]
21350 "--"
21351 ["Descriptive Links"
21352 org-toggle-link-display
21353 :style radio
21354 :selected org-descriptive-links
21356 ["Literal Links"
21357 org-toggle-link-display
21358 :style radio
21359 :selected (not org-descriptive-links)])
21360 "--"
21361 ("TODO Lists"
21362 ["TODO/DONE/-" org-todo t]
21363 ("Select keyword"
21364 ["Next keyword" org-shiftright (org-at-heading-p)]
21365 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21366 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21367 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21368 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21369 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21370 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21371 "--"
21372 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21373 :selected org-enforce-todo-dependencies :style toggle :active t]
21374 "Settings for tree at point"
21375 ["Do Children sequentially" org-toggle-ordered-property :style radio
21376 :selected (org-entry-get nil "ORDERED")
21377 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21378 ["Do Children parallel" org-toggle-ordered-property :style radio
21379 :selected (not (org-entry-get nil "ORDERED"))
21380 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21381 "--"
21382 ["Set Priority" org-priority t]
21383 ["Priority Up" org-shiftup t]
21384 ["Priority Down" org-shiftdown t]
21385 "--"
21386 ["Get news from all feeds" org-feed-update-all t]
21387 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21388 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21389 ("TAGS and Properties"
21390 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21391 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21392 "--"
21393 ["Set property" org-set-property (not (org-before-first-heading-p))]
21394 ["Column view of properties" org-columns t]
21395 ["Insert Column View DBlock" org-columns-insert-dblock t])
21396 ("Dates and Scheduling"
21397 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21398 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21399 ("Change Date"
21400 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21401 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21402 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21403 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21404 ["Compute Time Range" org-evaluate-time-range t]
21405 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21406 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21407 "--"
21408 ["Custom time format" org-toggle-time-stamp-overlays
21409 :style radio :selected org-display-custom-times]
21410 "--"
21411 ["Goto Calendar" org-goto-calendar t]
21412 ["Date from Calendar" org-date-from-calendar t]
21413 "--"
21414 ["Start/Restart Timer" org-timer-start t]
21415 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21416 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21417 ["Insert Timer String" org-timer t]
21418 ["Insert Timer Item" org-timer-item t])
21419 ("Logging work"
21420 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21421 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21422 ["Clock out" org-clock-out t]
21423 ["Clock cancel" org-clock-cancel t]
21424 "--"
21425 ["Mark as default task" org-clock-mark-default-task t]
21426 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21427 ["Goto running clock" org-clock-goto t]
21428 "--"
21429 ["Display times" org-clock-display t]
21430 ["Create clock table" org-clock-report t]
21431 "--"
21432 ["Record DONE time"
21433 (progn (setq org-log-done (not org-log-done))
21434 (message "Switching to %s will %s record a timestamp"
21435 (car org-done-keywords)
21436 (if org-log-done "automatically" "not")))
21437 :style toggle :selected org-log-done])
21438 "--"
21439 ["Agenda Command..." org-agenda t]
21440 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21441 ("File List for Agenda")
21442 ("Special views current file"
21443 ["TODO Tree" org-show-todo-tree t]
21444 ["Check Deadlines" org-check-deadlines t]
21445 ["Tags/Property tree" org-match-sparse-tree t])
21446 "--"
21447 ["Export/Publish..." org-export-dispatch t]
21448 ("LaTeX"
21449 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21450 :selected org-cdlatex-mode]
21451 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21452 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21453 ["Modify math symbol" org-cdlatex-math-modify
21454 (org-inside-LaTeX-fragment-p)]
21455 ["Insert citation" org-reftex-citation t])
21456 "--"
21457 ("MobileOrg"
21458 ["Push Files and Views" org-mobile-push t]
21459 ["Get Captured and Flagged" org-mobile-pull t]
21460 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21461 "--"
21462 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21463 "--"
21464 ("Documentation"
21465 ["Show Version" org-version t]
21466 ["Info Documentation" org-info t])
21467 ("Customize"
21468 ["Browse Org Group" org-customize t]
21469 "--"
21470 ["Expand This Menu" org-create-customize-menu
21471 (fboundp 'customize-menu-create)])
21472 ["Send bug report" org-submit-bug-report t]
21473 "--"
21474 ("Refresh/Reload"
21475 ["Refresh setup current buffer" org-mode-restart t]
21476 ["Reload Org (after update)" org-reload t]
21477 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21480 (defun org-info (&optional node)
21481 "Read documentation for Org in the info system.
21482 With optional NODE, go directly to that node."
21483 (interactive)
21484 (info (format "(org)%s" (or node ""))))
21486 ;;;###autoload
21487 (defun org-submit-bug-report ()
21488 "Submit a bug report on Org via mail.
21490 Don't hesitate to report any problems or inaccurate documentation.
21492 If you don't have setup sending mail from (X)Emacs, please copy the
21493 output buffer into your mail program, as it gives us important
21494 information about your Org version and configuration."
21495 (interactive)
21496 (require 'reporter)
21497 (defvar reporter-prompt-for-summary-p)
21498 (org-load-modules-maybe)
21499 (org-require-autoloaded-modules)
21500 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21501 (reporter-submit-bug-report
21502 "emacs-orgmode@gnu.org"
21503 (org-version nil 'full)
21504 (let (list)
21505 (save-window-excursion
21506 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21507 (delete-other-windows)
21508 (erase-buffer)
21509 (insert "You are about to submit a bug report to the Org mailing list.
21511 We would like to add your full Org and Outline configuration to the
21512 bug report. This greatly simplifies the work of the maintainer and
21513 other experts on the mailing list.
21515 HOWEVER, some variables you have customized may contain private
21516 information. The names of customers, colleagues, or friends, might
21517 appear in the form of file names, tags, todo states, or search strings.
21518 If you answer yes to the prompt, you might want to check and remove
21519 such private information before sending the email.")
21520 (add-text-properties (point-min) (point-max) '(face org-warning))
21521 (when (yes-or-no-p "Include your Org configuration ")
21522 (mapatoms
21523 (lambda (v)
21524 (and (boundp v)
21525 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21526 (or (and (symbol-value v)
21527 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21528 (and
21529 (get v 'custom-type) (get v 'standard-value)
21530 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21531 (push v list)))))
21532 (kill-buffer (get-buffer "*Warn about privacy*"))
21533 list))
21534 nil nil
21535 "Remember to cover the basics, that is, what you expected to happen and
21536 what in fact did happen. You don't know how to make a good report? See
21538 http://orgmode.org/manual/Feedback.html#Feedback
21540 Your bug report will be posted to the Org mailing list.
21541 ------------------------------------------------------------------------")
21542 (save-excursion
21543 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21544 (replace-match "\\1Bug: \\3 [\\2]")))))
21547 (defun org-install-agenda-files-menu ()
21548 (let ((bl (buffer-list)))
21549 (save-excursion
21550 (while bl
21551 (set-buffer (pop bl))
21552 (when (derived-mode-p 'org-mode) (setq bl nil)))
21553 (when (derived-mode-p 'org-mode)
21554 (easy-menu-change
21555 '("Org") "File List for Agenda"
21556 (append
21557 (list
21558 ["Edit File List" (org-edit-agenda-file-list) t]
21559 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21560 ["Remove Current File from List" org-remove-file t]
21561 ["Cycle through agenda files" org-cycle-agenda-files t]
21562 ["Occur in all agenda files" org-occur-in-agenda-files t]
21563 "--")
21564 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21566 ;;;; Documentation
21568 (defun org-require-autoloaded-modules ()
21569 (interactive)
21570 (mapc #'require
21571 '(org-agenda org-archive org-attach org-clock org-colview org-id
21572 org-table org-timer)))
21574 ;;;###autoload
21575 (defun org-reload (&optional uncompiled)
21576 "Reload all org lisp files.
21577 With prefix arg UNCOMPILED, load the uncompiled versions."
21578 (interactive "P")
21579 (require 'loadhist)
21580 (let* ((org-dir (org-find-library-dir "org"))
21581 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21582 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21583 (remove-re (format "\\`%s\\'"
21584 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21585 (feats (delete-dups
21586 (mapcar 'file-name-sans-extension
21587 (mapcar 'file-name-nondirectory
21588 (delq nil
21589 (mapcar 'feature-file
21590 features))))))
21591 (lfeat (append
21592 (sort
21593 (setq feats
21594 (delq nil (mapcar
21595 (lambda (f)
21596 (if (and (string-match feature-re f)
21597 (not (string-match remove-re f)))
21598 f nil))
21599 feats)))
21600 'string-lessp)
21601 (list "org-version" "org")))
21602 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21603 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21604 load-uncore load-misses)
21605 (setq load-misses
21606 (delq 't
21607 (mapcar (lambda (f)
21608 (or (org-load-noerror-mustsuffix (concat org-dir f))
21609 (and (string= org-dir contrib-dir)
21610 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21611 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21612 (add-to-list 'load-uncore f 'append)
21615 lfeat)))
21616 (when load-uncore
21617 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21618 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21619 (if load-misses
21620 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21621 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21622 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21624 ;;;###autoload
21625 (defun org-customize ()
21626 "Call the customize function with org as argument."
21627 (interactive)
21628 (org-load-modules-maybe)
21629 (org-require-autoloaded-modules)
21630 (customize-browse 'org))
21632 (defun org-create-customize-menu ()
21633 "Create a full customization menu for Org mode, insert it into the menu."
21634 (interactive)
21635 (org-load-modules-maybe)
21636 (org-require-autoloaded-modules)
21637 (if (fboundp 'customize-menu-create)
21638 (progn
21639 (easy-menu-change
21640 '("Org") "Customize"
21641 `(["Browse Org group" org-customize t]
21642 "--"
21643 ,(customize-menu-create 'org)
21644 ["Set" Custom-set t]
21645 ["Save" Custom-save t]
21646 ["Reset to Current" Custom-reset-current t]
21647 ["Reset to Saved" Custom-reset-saved t]
21648 ["Reset to Standard Settings" Custom-reset-standard t]))
21649 (message "\"Org\"-menu now contains full customization menu"))
21650 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21652 ;;;; Miscellaneous stuff
21654 ;;; Generally useful functions
21656 (defun org-get-at-eol (property n)
21657 "Get text property PROPERTY at the end of line less N characters."
21658 (get-text-property (- (point-at-eol) n) property))
21660 (defun org-find-text-property-in-string (prop s)
21661 "Return the first non-nil value of property PROP in string S."
21662 (or (get-text-property 0 prop s)
21663 (get-text-property (or (next-single-property-change 0 prop s) 0)
21664 prop s)))
21666 (defun org-display-warning (message)
21667 "Display the given MESSAGE as a warning."
21668 (display-warning 'org message :warning))
21670 (defun org-eval (form)
21671 "Eval FORM and return result."
21672 (condition-case error
21673 (eval form)
21674 (error (format "%%![Error: %s]" error))))
21676 (defun org-in-clocktable-p ()
21677 "Check if the cursor is in a clocktable."
21678 (let ((pos (point)) start)
21679 (save-excursion
21680 (end-of-line 1)
21681 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21682 (setq start (match-beginning 0))
21683 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21684 (>= (match-end 0) pos)
21685 start))))
21687 (defun org-in-verbatim-emphasis ()
21688 (save-match-data
21689 (and (org-in-regexp org-verbatim-re 2)
21690 (>= (point) (match-beginning 3))
21691 (<= (point) (match-end 4)))))
21693 (defun org-overlay-display (ovl text &optional face evap)
21694 "Make overlay OVL display TEXT with face FACE."
21695 (overlay-put ovl 'display text)
21696 (if face (overlay-put ovl 'face face))
21697 (if evap (overlay-put ovl 'evaporate t)))
21699 (defun org-overlay-before-string (ovl text &optional face evap)
21700 "Make overlay OVL display TEXT with face FACE."
21701 (if face (org-add-props text nil 'face face))
21702 (overlay-put ovl 'before-string text)
21703 (if evap (overlay-put ovl 'evaporate t)))
21705 (defun org-find-overlays (prop &optional pos delete)
21706 "Find all overlays specifying PROP at POS or point.
21707 If DELETE is non-nil, delete all those overlays."
21708 (let (found)
21709 (dolist (ov (overlays-at (or pos (point))) found)
21710 (cond ((not (overlay-get ov prop)))
21711 (delete (delete-overlay ov))
21712 (t (push ov found))))))
21714 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21715 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21716 (if (and marker (marker-buffer marker)
21717 (buffer-live-p (marker-buffer marker)))
21718 (progn
21719 (pop-to-buffer-same-window (marker-buffer marker))
21720 (when (or (> marker (point-max)) (< marker (point-min)))
21721 (widen))
21722 (goto-char marker)
21723 (org-show-context 'org-goto))
21724 (if bookmark
21725 (bookmark-jump bookmark)
21726 (error "Cannot find location"))))
21728 (defun org-quote-csv-field (s)
21729 "Quote field for inclusion in CSV material."
21730 (if (string-match "[\",]" s)
21731 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21734 (defun org-force-self-insert (N)
21735 "Needed to enforce self-insert under remapping."
21736 (interactive "p")
21737 (self-insert-command N))
21739 (defun org-shorten-string (s maxlength)
21740 "Shorten string S so that it is no longer than MAXLENGTH characters.
21741 If the string is shorter or has length MAXLENGTH, just return the
21742 original string. If it is longer, the functions finds a space in the
21743 string, breaks this string off at that locations and adds three dots
21744 as ellipsis. Including the ellipsis, the string will not be longer
21745 than MAXLENGTH. If finding a good breaking point in the string does
21746 not work, the string is just chopped off in the middle of a word
21747 if necessary."
21748 (if (<= (length s) maxlength)
21750 (let* ((n (max (- maxlength 4) 1))
21751 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21752 (if (string-match re s)
21753 (concat (match-string 1 s) "...")
21754 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21756 (defun org-get-indentation (&optional line)
21757 "Get the indentation of the current line, interpreting tabs.
21758 When LINE is given, assume it represents a line and compute its indentation."
21759 (if line
21760 (when (string-match "^ *" (org-remove-tabs line))
21761 (match-end 0))
21762 (save-excursion
21763 (beginning-of-line 1)
21764 (skip-chars-forward " \t")
21765 (current-column))))
21767 (defun org-get-string-indentation (s)
21768 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21769 (let ((n -1) (i 0) (w tab-width) c)
21770 (catch 'exit
21771 (while (< (setq n (1+ n)) (length s))
21772 (setq c (aref s n))
21773 (cond ((= c ?\ ) (setq i (1+ i)))
21774 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21775 (t (throw 'exit t)))))
21778 (defun org-remove-tabs (s &optional width)
21779 "Replace tabulators in S with spaces.
21780 Assumes that s is a single line, starting in column 0."
21781 (setq width (or width tab-width))
21782 (while (string-match "\t" s)
21783 (setq s (replace-match
21784 (make-string
21785 (- (* width (/ (+ (match-beginning 0) width) width))
21786 (match-beginning 0)) ?\ )
21787 t t s)))
21790 (defun org-fix-indentation (line ind)
21791 "Fix indentation in LINE.
21792 IND is a cons cell with target and minimum indentation.
21793 If the current indentation in LINE is smaller than the minimum,
21794 leave it alone. If it is larger than ind, set it to the target."
21795 (let* ((l (org-remove-tabs line))
21796 (i (org-get-indentation l))
21797 (i1 (car ind)) (i2 (cdr ind)))
21798 (when (>= i i2) (setq l (substring line i2)))
21799 (if (> i1 0)
21800 (concat (make-string i1 ?\ ) l)
21801 l)))
21803 (defun org-remove-indentation (code &optional n)
21804 "Remove maximum common indentation in string CODE and return it.
21805 N may optionally be the number of columns to remove. Return CODE
21806 as-is if removal failed."
21807 (with-temp-buffer
21808 (insert code)
21809 (if (org-do-remove-indentation n) (buffer-string) code)))
21811 (defun org-do-remove-indentation (&optional n)
21812 "Remove the maximum common indentation from the buffer.
21813 When optional argument N is a positive integer, remove exactly
21814 that much characters from indentation, if possible. Return nil
21815 if it fails."
21816 (catch :exit
21817 (goto-char (point-min))
21818 ;; Find maximum common indentation, if not specified.
21819 (let ((n (or n
21820 (let ((min-ind (point-max)))
21821 (save-excursion
21822 (while (re-search-forward "^[ \t]*\\S-" nil t)
21823 (let ((ind (1- (current-column))))
21824 (if (zerop ind) (throw :exit nil)
21825 (setq min-ind (min min-ind ind))))))
21826 min-ind))))
21827 (if (zerop n) (throw :exit nil)
21828 ;; Remove exactly N indentation, but give up if not possible.
21829 (while (not (eobp))
21830 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21831 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21832 ((< ind n) (throw :exit nil))
21833 (t (indent-line-to (- ind n))))
21834 (forward-line)))
21835 ;; Signal success.
21836 t))))
21838 (defun org-fill-template (template alist)
21839 "Find each %key of ALIST in TEMPLATE and replace it."
21840 (let ((case-fold-search nil))
21841 (dolist (entry (sort (copy-sequence alist)
21842 (lambda (a b) (< (length (car a)) (length (car b))))))
21843 (setq template
21844 (replace-regexp-in-string
21845 (concat "%" (regexp-quote (car entry)))
21846 (or (cdr entry) "") template t t)))
21847 template))
21849 (defun org-base-buffer (buffer)
21850 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21851 (if (not buffer)
21852 buffer
21853 (or (buffer-base-buffer buffer)
21854 buffer)))
21856 (defun org-wrap (string &optional width lines)
21857 "Wrap string to either a number of lines, or a width in characters.
21858 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21859 that costs. If there is a word longer than WIDTH, the text is actually
21860 wrapped to the length of that word.
21861 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21862 many lines, whatever width that takes.
21863 The return value is a list of lines, without newlines at the end."
21864 (let* ((words (split-string string))
21865 (maxword (apply 'max (mapcar 'org-string-width words)))
21866 w ll)
21867 (cond (width
21868 (org-do-wrap words (max maxword width)))
21869 (lines
21870 (setq w maxword)
21871 (setq ll (org-do-wrap words maxword))
21872 (if (<= (length ll) lines)
21874 (setq ll words)
21875 (while (> (length ll) lines)
21876 (setq w (1+ w))
21877 (setq ll (org-do-wrap words w)))
21878 ll))
21879 (t (error "Cannot wrap this")))))
21881 (defun org-do-wrap (words width)
21882 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21883 (let (lines line)
21884 (while words
21885 (setq line (pop words))
21886 (while (and words (< (+ (length line) (length (car words))) width))
21887 (setq line (concat line " " (pop words))))
21888 (setq lines (push line lines)))
21889 (nreverse lines)))
21891 (defun org-quote-vert (s)
21892 "Replace \"|\" with \"\\vert\"."
21893 (while (string-match "|" s)
21894 (setq s (replace-match "\\vert" t t s)))
21897 (defun org-uuidgen-p (s)
21898 "Is S an ID created by UUIDGEN?"
21899 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21901 (defun org-in-src-block-p (&optional inside)
21902 "Whether point is in a code source block.
21903 When INSIDE is non-nil, don't consider we are within a src block
21904 when point is at #+BEGIN_SRC or #+END_SRC."
21905 (let ((case-fold-search t))
21906 (or (and (eq (get-char-property (point) 'src-block) t))
21907 (and (not inside)
21908 (save-match-data
21909 (save-excursion
21910 (beginning-of-line)
21911 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21913 (defun org-context ()
21914 "Return a list of contexts of the current cursor position.
21915 If several contexts apply, all are returned.
21916 Each context entry is a list with a symbol naming the context, and
21917 two positions indicating start and end of the context. Possible
21918 contexts are:
21920 :headline anywhere in a headline
21921 :headline-stars on the leading stars in a headline
21922 :todo-keyword on a TODO keyword (including DONE) in a headline
21923 :tags on the TAGS in a headline
21924 :priority on the priority cookie in a headline
21925 :item on the first line of a plain list item
21926 :item-bullet on the bullet/number of a plain list item
21927 :checkbox on the checkbox in a plain list item
21928 :table in an Org table
21929 :table-special on a special filed in a table
21930 :table-table in a table.el table
21931 :clocktable in a clocktable
21932 :src-block in a source block
21933 :link on a hyperlink
21934 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21935 :target on a <<target>>
21936 :radio-target on a <<<radio-target>>>
21937 :latex-fragment on a LaTeX fragment
21938 :latex-preview on a LaTeX fragment with overlaid preview image
21940 This function expects the position to be visible because it uses font-lock
21941 faces as a help to recognize the following contexts: :table-special, :link,
21942 and :keyword."
21943 (let* ((f (get-text-property (point) 'face))
21944 (faces (if (listp f) f (list f)))
21945 (case-fold-search t)
21946 (p (point)) clist o)
21947 ;; First the large context
21948 (cond
21949 ((org-at-heading-p t)
21950 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21951 (when (progn
21952 (beginning-of-line 1)
21953 (looking-at org-todo-line-tags-regexp))
21954 (push (org-point-in-group p 1 :headline-stars) clist)
21955 (push (org-point-in-group p 2 :todo-keyword) clist)
21956 (push (org-point-in-group p 4 :tags) clist))
21957 (goto-char p)
21958 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21959 (when (looking-at "\\[#[A-Z0-9]\\]")
21960 (push (org-point-in-group p 0 :priority) clist)))
21962 ((org-at-item-p)
21963 (push (org-point-in-group p 2 :item-bullet) clist)
21964 (push (list :item (point-at-bol)
21965 (save-excursion (org-end-of-item) (point)))
21966 clist)
21967 (and (org-at-item-checkbox-p)
21968 (push (org-point-in-group p 0 :checkbox) clist)))
21970 ((org-at-table-p)
21971 (push (list :table (org-table-begin) (org-table-end)) clist)
21972 (when (memq 'org-formula faces)
21973 (push (list :table-special
21974 (previous-single-property-change p 'face)
21975 (next-single-property-change p 'face)) clist)))
21976 ((org-at-table-p 'any)
21977 (push (list :table-table) clist)))
21978 (goto-char p)
21980 (let ((case-fold-search t))
21981 ;; New the "medium" contexts: clocktables, source blocks
21982 (cond ((org-in-clocktable-p)
21983 (push (list :clocktable
21984 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21985 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21986 (match-beginning 1))
21987 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21988 (match-end 0))) clist))
21989 ((org-in-src-block-p)
21990 (push (list :src-block
21991 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21992 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21993 (match-beginning 1))
21994 (and (search-forward "#+END_SRC" nil t)
21995 (match-beginning 0))) clist))))
21996 (goto-char p)
21998 ;; Now the small context
21999 (cond
22000 ((org-at-timestamp-p)
22001 (push (org-point-in-group p 0 :timestamp) clist))
22002 ((memq 'org-link faces)
22003 (push (list :link
22004 (previous-single-property-change p 'face)
22005 (next-single-property-change p 'face)) clist))
22006 ((memq 'org-special-keyword faces)
22007 (push (list :keyword
22008 (previous-single-property-change p 'face)
22009 (next-single-property-change p 'face)) clist))
22010 ((org-at-target-p)
22011 (push (org-point-in-group p 0 :target) clist)
22012 (goto-char (1- (match-beginning 0)))
22013 (when (looking-at org-radio-target-regexp)
22014 (push (org-point-in-group p 0 :radio-target) clist))
22015 (goto-char p))
22016 ((setq o (cl-some
22017 (lambda (o)
22018 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22020 (overlays-at (point))))
22021 (push (list :latex-fragment
22022 (overlay-start o) (overlay-end o)) clist)
22023 (push (list :latex-preview
22024 (overlay-start o) (overlay-end o)) clist))
22025 ((org-inside-LaTeX-fragment-p)
22026 ;; FIXME: positions wrong.
22027 (push (list :latex-fragment (point) (point)) clist)))
22029 (setq clist (nreverse (delq nil clist)))
22030 clist))
22032 (defun org-in-regexp (regexp &optional nlines visually)
22033 "Check if point is inside a match of REGEXP.
22035 Normally only the current line is checked, but you can include
22036 NLINES extra lines around point into the search. If VISUALLY is
22037 set, require that the cursor is not after the match but really
22038 on, so that the block visually is on the match.
22040 Return nil or a cons cell (BEG . END) where BEG and END are,
22041 respectively, the positions at the beginning and the end of the
22042 match."
22043 (catch :exit
22044 (let ((pos (point))
22045 (eol (line-end-position (if nlines (1+ nlines) 1))))
22046 (save-excursion
22047 (beginning-of-line (- 1 (or nlines 0)))
22048 (while (and (re-search-forward regexp eol t)
22049 (<= (match-beginning 0) pos))
22050 (let ((end (match-end 0)))
22051 (when (or (> end pos) (and (= end pos) (not visually)))
22052 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22054 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22055 "Non-nil when point is between matches of START-RE and END-RE.
22057 Also return a non-nil value when point is on one of the matches.
22059 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22060 buffer positions. Default values are the positions of headlines
22061 surrounding the point.
22063 The functions returns a cons cell whose car (resp. cdr) is the
22064 position before START-RE (resp. after END-RE)."
22065 (save-match-data
22066 (let ((pos (point))
22067 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22068 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22069 beg end)
22070 (save-excursion
22071 ;; Point is on a block when on START-RE or if START-RE can be
22072 ;; found before it...
22073 (and (or (org-in-regexp start-re)
22074 (re-search-backward start-re limit-up t))
22075 (setq beg (match-beginning 0))
22076 ;; ... and END-RE after it...
22077 (goto-char (match-end 0))
22078 (re-search-forward end-re limit-down t)
22079 (> (setq end (match-end 0)) pos)
22080 ;; ... without another START-RE in-between.
22081 (goto-char (match-beginning 0))
22082 (not (re-search-backward start-re (1+ beg) t))
22083 ;; Return value.
22084 (cons beg end))))))
22086 (defun org-in-block-p (names)
22087 "Non-nil when point belongs to a block whose name belongs to NAMES.
22089 NAMES is a list of strings containing names of blocks.
22091 Return first block name matched, or nil. Beware that in case of
22092 nested blocks, the returned name may not belong to the closest
22093 block from point."
22094 (save-match-data
22095 (catch 'exit
22096 (let ((case-fold-search t)
22097 (lim-up (save-excursion (outline-previous-heading)))
22098 (lim-down (save-excursion (outline-next-heading))))
22099 (dolist (name names)
22100 (let ((n (regexp-quote name)))
22101 (when (org-between-regexps-p
22102 (concat "^[ \t]*#\\+begin_" n)
22103 (concat "^[ \t]*#\\+end_" n)
22104 lim-up lim-down)
22105 (throw 'exit n)))))
22106 nil)))
22108 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22109 "Call `multi-occur' with buffers for all agenda files."
22110 (interactive "sOrg-files matching: ")
22111 (let* ((files (org-agenda-files))
22112 (tnames (mapcar #'file-truename files))
22113 (extra org-agenda-text-search-extra-files))
22114 (when (eq (car extra) 'agenda-archives)
22115 (setq extra (cdr extra))
22116 (setq files (org-add-archive-files files)))
22117 (dolist (f extra)
22118 (unless (member (file-truename f) tnames)
22119 (unless (member f files) (setq files (append files (list f))))
22120 (setq tnames (append tnames (list (file-truename f))))))
22121 (multi-occur
22122 (mapcar (lambda (x)
22123 (with-current-buffer
22124 ;; FIXME: Why not just (find-file-noselect x)?
22125 ;; Is it to avoid the "revert buffer" prompt?
22126 (or (get-file-buffer x) (find-file-noselect x))
22127 (widen)
22128 (current-buffer)))
22129 files)
22130 regexp)))
22132 (add-hook 'occur-mode-find-occurrence-hook
22133 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22135 (defun org-occur-link-in-agenda-files ()
22136 "Create a link and search for it in the agendas.
22137 The link is not stored in `org-stored-links', it is just created
22138 for the search purpose."
22139 (interactive)
22140 (let ((link (condition-case nil
22141 (org-store-link nil)
22142 (error "Unable to create a link to here"))))
22143 (org-occur-in-agenda-files (regexp-quote link))))
22145 (defun org-reverse-string (string)
22146 "Return the reverse of STRING."
22147 (apply 'string (reverse (string-to-list string))))
22149 ;; defsubst org-uniquify must be defined before first use
22151 (defun org-uniquify-alist (alist)
22152 "Merge elements of ALIST with the same key.
22154 For example, in this alist:
22156 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22157 => \\='((a 1 3) (b 2))
22159 merge (a 1) and (a 3) into (a 1 3).
22161 The function returns the new ALIST."
22162 (let (rtn)
22163 (dolist (e alist rtn)
22164 (let (n)
22165 (if (not (assoc (car e) rtn))
22166 (push e rtn)
22167 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22168 (setq rtn (assq-delete-all (car e) rtn))
22169 (push n rtn))))))
22171 (defun org-delete-all (elts list)
22172 "Remove all elements in ELTS from LIST.
22173 Comparison is done with `equal'. It is a destructive operation
22174 that may remove elements by altering the list structure."
22175 (while elts
22176 (setq list (delete (pop elts) list)))
22177 list)
22179 (defun org-back-over-empty-lines ()
22180 "Move backwards over whitespace, to the beginning of the first empty line.
22181 Returns the number of empty lines passed."
22182 (let ((pos (point)))
22183 (if (cdr (assq 'heading org-blank-before-new-entry))
22184 (skip-chars-backward " \t\n\r")
22185 (unless (eobp)
22186 (forward-line -1)))
22187 (beginning-of-line 2)
22188 (goto-char (min (point) pos))
22189 (count-lines (point) pos)))
22191 (defun org-skip-whitespace ()
22192 (skip-chars-forward " \t\n\r"))
22194 (defun org-point-in-group (point group &optional context)
22195 "Check if POINT is in match-group GROUP.
22196 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22197 match. If the match group does not exist or point is not inside it,
22198 return nil."
22199 (and (match-beginning group)
22200 (>= point (match-beginning group))
22201 (<= point (match-end group))
22202 (if context
22203 (list context (match-beginning group) (match-end group))
22204 t)))
22206 (defun org-switch-to-buffer-other-window (&rest args)
22207 "Switch to buffer in a second window on the current frame.
22208 In particular, do not allow pop-up frames.
22209 Returns the newly created buffer."
22210 (org-no-popups
22211 (apply 'switch-to-buffer-other-window args)))
22213 (defun org-combine-plists (&rest plists)
22214 "Create a single property list from all plists in PLISTS.
22215 The process starts by copying the first list, and then setting properties
22216 from the other lists. Settings in the last list are the most significant
22217 ones and overrule settings in the other lists."
22218 (let ((rtn (copy-sequence (pop plists)))
22219 p v ls)
22220 (while plists
22221 (setq ls (pop plists))
22222 (while ls
22223 (setq p (pop ls) v (pop ls))
22224 (setq rtn (plist-put rtn p v))))
22225 rtn))
22227 (defun org-replace-escapes (string table)
22228 "Replace %-escapes in STRING with values in TABLE.
22229 TABLE is an association list with keys like \"%a\" and string values.
22230 The sequences in STRING may contain normal field width and padding information,
22231 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22232 so values can contain further %-escapes if they are define later in TABLE."
22233 (let ((tbl (copy-alist table))
22234 (case-fold-search nil)
22235 (pchg 0)
22236 re rpl)
22237 (dolist (e tbl)
22238 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22239 (when (and (cdr e) (string-match re (cdr e)))
22240 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22241 (safe "SREF"))
22242 (add-text-properties 0 3 (list 'sref sref) safe)
22243 (setcdr e (replace-match safe t t (cdr e)))))
22244 (while (string-match re string)
22245 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22246 (cdr e)))
22247 (setq string (replace-match rpl t t string))))
22248 (while (setq pchg (next-property-change pchg string))
22249 (let ((sref (get-text-property pchg 'sref string)))
22250 (when (and sref (string-match "SREF" string pchg))
22251 (setq string (replace-match sref t t string)))))
22252 string))
22254 (defun org-find-base-buffer-visiting (file)
22255 "Like `find-buffer-visiting' but always return the base buffer and
22256 not an indirect buffer."
22257 (let ((buf (or (get-file-buffer file)
22258 (find-buffer-visiting file))))
22259 (if buf
22260 (or (buffer-base-buffer buf) buf)
22261 nil)))
22263 ;;; TODO: Only called once, from ox-odt which should probably use
22264 ;;; org-export-inline-image-p or something.
22265 (defun org-file-image-p (file)
22266 "Return non-nil if FILE is an image."
22267 (save-match-data
22268 (string-match (image-file-name-regexp) file)))
22270 (defun org-get-cursor-date (&optional with-time)
22271 "Return the date at cursor in as a time.
22272 This works in the calendar and in the agenda, anywhere else it just
22273 returns the current time.
22274 If WITH-TIME is non-nil, returns the time of the event at point (in
22275 the agenda) or the current time of the day."
22276 (let (date day defd tp hod mod)
22277 (when with-time
22278 (setq tp (get-text-property (point) 'time))
22279 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22280 (setq hod (string-to-number (match-string 1 tp))
22281 mod (string-to-number (match-string 2 tp))))
22282 (or tp (let ((now (decode-time)))
22283 (setq hod (nth 2 now)
22284 mod (nth 1 now)))))
22285 (cond
22286 ((eq major-mode 'calendar-mode)
22287 (setq date (calendar-cursor-to-date)
22288 defd (encode-time 0 (or mod 0) (or hod 0)
22289 (nth 1 date) (nth 0 date) (nth 2 date))))
22290 ((eq major-mode 'org-agenda-mode)
22291 (setq day (get-text-property (point) 'day))
22292 (when day
22293 (setq date (calendar-gregorian-from-absolute day)
22294 defd (encode-time 0 (or mod 0) (or hod 0)
22295 (nth 1 date) (nth 0 date) (nth 2 date))))))
22296 (or defd (current-time))))
22298 (defun org-mark-subtree (&optional up)
22299 "Mark the current subtree.
22300 This puts point at the start of the current subtree, and mark at
22301 the end. If a numeric prefix UP is given, move up into the
22302 hierarchy of headlines by UP levels before marking the subtree."
22303 (interactive "P")
22304 (org-with-limited-levels
22305 (cond ((org-at-heading-p) (beginning-of-line))
22306 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22307 (t (outline-previous-visible-heading 1))))
22308 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22309 (if (called-interactively-p 'any)
22310 (call-interactively 'org-mark-element)
22311 (org-mark-element)))
22313 (defun org-file-newer-than-p (file time)
22314 "Non-nil if FILE is newer than TIME.
22315 FILE is a filename, as a string, TIME is a list of integers, as
22316 returned by, e.g., `current-time'."
22317 (and (file-exists-p file)
22318 ;; Only compare times up to whole seconds as some file-systems
22319 ;; (e.g. HFS+) do not retain any finer granularity. As
22320 ;; a consequence, make sure we return non-nil when the two
22321 ;; times are equal.
22322 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22323 (cl-subseq time 0 2)))))
22325 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22326 "Compile a SOURCE file using PROCESS.
22328 PROCESS is either a function or a list of shell commands, as
22329 strings. EXT is a file extension, without the leading dot, as
22330 a string. It is used to check if the process actually succeeded.
22332 PROCESS must create a file with the same base name and directory
22333 as SOURCE, but ending with EXT. The function then returns its
22334 filename. Otherwise, it raises an error. The error message can
22335 then be refined by providing string ERR-MSG, which is appended to
22336 the standard message.
22338 If PROCESS is a function, it is called with a single argument:
22339 the SOURCE file.
22341 If it is a list of commands, each of them is called using
22342 `shell-command'. By default, in each command, %b, %f, %F, %o and
22343 %O are replaced with, respectively, SOURCE base name, name, full
22344 name, directory and absolute output file name. It is possible,
22345 however, to use more place-holders by specifying them in optional
22346 argument SPEC, as an alist following the pattern
22348 (CHARACTER . REPLACEMENT-STRING).
22350 When PROCESS is a list of commands, optional argument LOG-BUF can
22351 be set to a buffer or a buffer name. `shell-command' then uses
22352 it for output."
22353 (let* ((base-name (file-name-base source))
22354 (full-name (file-truename source))
22355 (out-dir (or (file-name-directory source) "./"))
22356 (output (expand-file-name (concat base-name "." ext) out-dir))
22357 (time (current-time))
22358 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22359 (save-window-excursion
22360 (pcase process
22361 ((pred functionp) (funcall process (shell-quote-argument source)))
22362 ((pred consp)
22363 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22364 (spec (append spec
22365 `((?b . ,(shell-quote-argument base-name))
22366 (?f . ,(shell-quote-argument source))
22367 (?F . ,(shell-quote-argument full-name))
22368 (?o . ,(shell-quote-argument out-dir))
22369 (?O . ,(shell-quote-argument output))))))
22370 (dolist (command process)
22371 (shell-command (format-spec command spec) log-buf))
22372 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22373 (_ (error "No valid command to process %S%s" source err-msg))))
22374 ;; Check for process failure. Output file is expected to be
22375 ;; located in the same directory as SOURCE.
22376 (unless (org-file-newer-than-p output time)
22377 (error (format "File %S wasn't produced%s" output err-msg)))
22378 output))
22380 ;;; Indentation
22382 (defvar org-element-greater-elements)
22383 (defun org--get-expected-indentation (element contentsp)
22384 "Expected indentation column for current line, according to ELEMENT.
22385 ELEMENT is an element containing point. CONTENTSP is non-nil
22386 when indentation is to be computed according to contents of
22387 ELEMENT."
22388 (let ((type (org-element-type element))
22389 (start (org-element-property :begin element))
22390 (post-affiliated (org-element-property :post-affiliated element)))
22391 (org-with-wide-buffer
22392 (cond
22393 (contentsp
22394 (cl-case type
22395 ((diary-sexp footnote-definition) 0)
22396 ((headline inlinetask nil)
22397 (if (not org-adapt-indentation) 0
22398 (let ((level (org-current-level)))
22399 (if level (1+ level) 0))))
22400 ((item plain-list) (org-list-item-body-column post-affiliated))
22402 (goto-char start)
22403 (org-get-indentation))))
22404 ((memq type '(headline inlinetask nil))
22405 (if (org-match-line "[ \t]*$")
22406 (org--get-expected-indentation element t)
22408 ((memq type '(diary-sexp footnote-definition)) 0)
22409 ;; First paragraph of a footnote definition or an item.
22410 ;; Indent like parent.
22411 ((< (line-beginning-position) start)
22412 (org--get-expected-indentation
22413 (org-element-property :parent element) t))
22414 ;; At first line: indent according to previous sibling, if any,
22415 ;; ignoring footnote definitions and inline tasks, or parent's
22416 ;; contents.
22417 ((= (line-beginning-position) start)
22418 (catch 'exit
22419 (while t
22420 (if (= (point-min) start) (throw 'exit 0)
22421 (goto-char (1- start))
22422 (let* ((previous (org-element-at-point))
22423 (parent previous))
22424 (while (and parent (<= (org-element-property :end parent) start))
22425 (setq previous parent
22426 parent (org-element-property :parent parent)))
22427 (cond
22428 ((not previous) (throw 'exit 0))
22429 ((> (org-element-property :end previous) start)
22430 (throw 'exit (org--get-expected-indentation previous t)))
22431 ((memq (org-element-type previous)
22432 '(footnote-definition inlinetask))
22433 (setq start (org-element-property :begin previous)))
22434 (t (goto-char (org-element-property :begin previous))
22435 (throw 'exit
22436 (if (bolp) (org-get-indentation)
22437 ;; At first paragraph in an item or
22438 ;; a footnote definition.
22439 (org--get-expected-indentation
22440 (org-element-property :parent previous) t))))))))))
22441 ;; Otherwise, move to the first non-blank line above.
22443 (beginning-of-line)
22444 (let ((pos (point)))
22445 (skip-chars-backward " \r\t\n")
22446 (cond
22447 ;; Two blank lines end a footnote definition or a plain
22448 ;; list. When we indent an empty line after them, the
22449 ;; containing list or footnote definition is over, so it
22450 ;; qualifies as a previous sibling. Therefore, we indent
22451 ;; like its first line.
22452 ((and (memq type '(footnote-definition plain-list))
22453 (> (count-lines (point) pos) 2))
22454 (goto-char start)
22455 (org-get-indentation))
22456 ;; Line above is the first one of a paragraph at the
22457 ;; beginning of an item or a footnote definition. Indent
22458 ;; like parent.
22459 ((< (line-beginning-position) start)
22460 (org--get-expected-indentation
22461 (org-element-property :parent element) t))
22462 ;; Line above is the beginning of an element, i.e., point
22463 ;; was originally on the blank lines between element's start
22464 ;; and contents.
22465 ((= (line-beginning-position) post-affiliated)
22466 (org--get-expected-indentation element t))
22467 ;; POS is after contents in a greater element. Indent like
22468 ;; the beginning of the element.
22469 ((and (memq type org-element-greater-elements)
22470 (let ((cend (org-element-property :contents-end element)))
22471 (and cend (<= cend pos))))
22472 ;; As a special case, if point is at the end of a footnote
22473 ;; definition or an item, indent like the very last element
22474 ;; within. If that last element is an item, indent like
22475 ;; its contents.
22476 (if (memq type '(footnote-definition item plain-list))
22477 (let ((last (org-element-at-point)))
22478 (goto-char pos)
22479 (org--get-expected-indentation
22480 last (eq (org-element-type last) 'item)))
22481 (goto-char start)
22482 (org-get-indentation)))
22483 ;; In any other case, indent like the current line.
22484 (t (org-get-indentation)))))))))
22486 (defun org--align-node-property ()
22487 "Align node property at point.
22488 Alignment is done according to `org-property-format', which see."
22489 (when (save-excursion
22490 (beginning-of-line)
22491 (looking-at org-property-re))
22492 (replace-match
22493 (concat (match-string 4)
22494 (org-trim
22495 (format org-property-format (match-string 1) (match-string 3))))
22496 t t)))
22498 (defun org-indent-line ()
22499 "Indent line depending on context.
22501 Indentation is done according to the following rules:
22503 - Footnote definitions, diary sexps, headlines and inline tasks
22504 have to start at column 0.
22506 - On the very first line of an element, consider, in order, the
22507 next rules until one matches:
22509 1. If there's a sibling element before, ignoring footnote
22510 definitions and inline tasks, indent like its first line.
22512 2. If element has a parent, indent like its contents. More
22513 precisely, if parent is an item, indent after the
22514 description part, if any, or the bullet (see
22515 `org-list-description-max-indent'). Else, indent like
22516 parent's first line.
22518 3. Otherwise, indent relatively to current level, if
22519 `org-adapt-indentation' is non-nil, or to left margin.
22521 - On a blank line at the end of an element, indent according to
22522 the type of the element. More precisely
22524 1. If element is a plain list, an item, or a footnote
22525 definition, indent like the very last element within.
22527 2. If element is a paragraph, indent like its last non blank
22528 line.
22530 3. Otherwise, indent like its very first line.
22532 - In the code part of a source block, use language major mode
22533 to indent current line if `org-src-tab-acts-natively' is
22534 non-nil. If it is nil, do nothing.
22536 - Otherwise, indent like the first non-blank line above.
22538 The function doesn't indent an item as it could break the whole
22539 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22540 `\\[org-shiftmetaright]'.
22542 Also align node properties according to `org-property-format'."
22543 (interactive)
22544 (cond
22545 (orgstruct-is-++
22546 (let ((indent-line-function
22547 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22548 (indent-according-to-mode)))
22549 ((org-at-heading-p) 'noindent)
22551 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22552 (type (org-element-type element)))
22553 (cond ((and (memq type '(plain-list item))
22554 (= (line-beginning-position)
22555 (org-element-property :post-affiliated element)))
22556 'noindent)
22557 ((and (eq type 'latex-environment)
22558 (>= (point) (org-element-property :post-affiliated element))
22559 (< (point) (org-with-wide-buffer
22560 (goto-char (org-element-property :end element))
22561 (skip-chars-backward " \r\t\n")
22562 (line-beginning-position 2))))
22563 'noindent)
22564 ((and (eq type 'src-block)
22565 org-src-tab-acts-natively
22566 (> (line-beginning-position)
22567 (org-element-property :post-affiliated element))
22568 (< (line-beginning-position)
22569 (org-with-wide-buffer
22570 (goto-char (org-element-property :end element))
22571 (skip-chars-backward " \r\t\n")
22572 (line-beginning-position))))
22573 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22575 (let ((column (org--get-expected-indentation element nil)))
22576 ;; Preserve current column.
22577 (if (<= (current-column) (current-indentation))
22578 (indent-line-to column)
22579 (save-excursion (indent-line-to column))))
22580 ;; Align node property. Also preserve current column.
22581 (when (eq type 'node-property)
22582 (let ((column (current-column)))
22583 (org--align-node-property)
22584 (org-move-to-column column)))))))))
22586 (defun org-indent-region (start end)
22587 "Indent each non-blank line in the region.
22588 Called from a program, START and END specify the region to
22589 indent. The function will not indent contents of example blocks,
22590 verse blocks and export blocks as leading white spaces are
22591 assumed to be significant there."
22592 (interactive "r")
22593 (save-excursion
22594 (goto-char start)
22595 (skip-chars-forward " \r\t\n")
22596 (unless (eobp) (beginning-of-line))
22597 (let ((indent-to
22598 (lambda (ind pos)
22599 ;; Set IND as indentation for all lines between point and
22600 ;; POS. Blank lines are ignored. Leave point after POS
22601 ;; once done.
22602 (let ((limit (copy-marker pos)))
22603 (while (< (point) limit)
22604 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22605 (forward-line))
22606 (set-marker limit nil))))
22607 (end (copy-marker end)))
22608 (while (< (point) end)
22609 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22610 (let* ((element (org-element-at-point))
22611 (type (org-element-type element))
22612 (element-end (copy-marker (org-element-property :end element)))
22613 (ind (org--get-expected-indentation element nil)))
22614 (cond
22615 ;; Element indented as a single block. Example blocks
22616 ;; preserving indentation are a special case since the
22617 ;; "contents" must not be indented whereas the block
22618 ;; boundaries can.
22619 ((or (memq type '(export-block latex-environment))
22620 (and (eq type 'example-block)
22621 (not
22622 (or org-src-preserve-indentation
22623 (org-element-property :preserve-indent element)))))
22624 (let ((offset (- ind (org-get-indentation))))
22625 (unless (zerop offset)
22626 (indent-rigidly (org-element-property :begin element)
22627 (org-element-property :end element)
22628 offset)))
22629 (goto-char element-end))
22630 ;; Elements indented line wise. Be sure to exclude
22631 ;; example blocks (preserving indentation) and source
22632 ;; blocks from this category as they are treated
22633 ;; specially later.
22634 ((or (memq type '(paragraph table table-row))
22635 (not (or (org-element-property :contents-begin element)
22636 (memq type '(example-block src-block)))))
22637 (when (eq type 'node-property)
22638 (org--align-node-property)
22639 (beginning-of-line))
22640 (funcall indent-to ind (min element-end end)))
22641 ;; Elements consisting of three parts: before the
22642 ;; contents, the contents, and after the contents. The
22643 ;; contents are treated specially, according to the
22644 ;; element type, or not indented at all. Other parts are
22645 ;; indented as a single block.
22647 (let* ((post (copy-marker
22648 (org-element-property :post-affiliated element)))
22649 (cbeg
22650 (copy-marker
22651 (cond
22652 ((not (org-element-property :contents-begin element))
22653 ;; Fake contents for source blocks.
22654 (org-with-wide-buffer
22655 (goto-char post)
22656 (line-beginning-position 2)))
22657 ((memq type '(footnote-definition item plain-list))
22658 ;; Contents in these elements could start on
22659 ;; the same line as the beginning of the
22660 ;; element. Make sure we start indenting
22661 ;; from the second line.
22662 (org-with-wide-buffer
22663 (goto-char post)
22664 (end-of-line)
22665 (skip-chars-forward " \r\t\n")
22666 (if (eobp) (point) (line-beginning-position))))
22667 (t (org-element-property :contents-begin element)))))
22668 (cend (copy-marker
22669 (or (org-element-property :contents-end element)
22670 ;; Fake contents for source blocks.
22671 (org-with-wide-buffer
22672 (goto-char element-end)
22673 (skip-chars-backward " \r\t\n")
22674 (line-beginning-position)))
22675 t)))
22676 ;; Do not change items indentation individually as it
22677 ;; might break the list as a whole. On the other
22678 ;; hand, when at a plain list, indent it as a whole.
22679 (cond ((eq type 'plain-list)
22680 (let ((offset (- ind (org-get-indentation))))
22681 (unless (zerop offset)
22682 (indent-rigidly (org-element-property :begin element)
22683 (org-element-property :end element)
22684 offset))
22685 (goto-char cbeg)))
22686 ((eq type 'item) (goto-char cbeg))
22687 (t (funcall indent-to ind (min cbeg end))))
22688 (when (< (point) end)
22689 (cl-case type
22690 ((example-block verse-block))
22691 (src-block
22692 ;; In a source block, indent source code
22693 ;; according to language major mode, but only if
22694 ;; `org-src-tab-acts-natively' is non-nil.
22695 (when (and (< (point) end) org-src-tab-acts-natively)
22696 (ignore-errors
22697 (org-babel-do-in-edit-buffer
22698 (indent-region (point-min) (point-max))))))
22699 (t (org-indent-region (point) (min cend end))))
22700 (goto-char (min cend end))
22701 (when (< (point) end)
22702 (funcall indent-to ind (min element-end end))))
22703 (set-marker post nil)
22704 (set-marker cbeg nil)
22705 (set-marker cend nil))))
22706 (set-marker element-end nil))))
22707 (set-marker end nil))))
22709 (defun org-indent-drawer ()
22710 "Indent the drawer at point."
22711 (interactive)
22712 (unless (save-excursion
22713 (beginning-of-line)
22714 (looking-at-p org-drawer-regexp))
22715 (user-error "Not at a drawer"))
22716 (let ((element (org-element-at-point)))
22717 (unless (memq (org-element-type element) '(drawer property-drawer))
22718 (user-error "Not at a drawer"))
22719 (org-with-wide-buffer
22720 (org-indent-region (org-element-property :begin element)
22721 (org-element-property :end element))))
22722 (message "Drawer at point indented"))
22724 (defun org-indent-block ()
22725 "Indent the block at point."
22726 (interactive)
22727 (unless (save-excursion
22728 (beginning-of-line)
22729 (let ((case-fold-search t))
22730 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22731 (user-error "Not at a block"))
22732 (let ((element (org-element-at-point)))
22733 (unless (memq (org-element-type element)
22734 '(comment-block center-block dynamic-block example-block
22735 export-block quote-block special-block
22736 src-block verse-block))
22737 (user-error "Not at a block"))
22738 (org-with-wide-buffer
22739 (org-indent-region (org-element-property :begin element)
22740 (org-element-property :end element))))
22741 (message "Block at point indented"))
22744 ;;; Filling
22746 ;; We use our own fill-paragraph and auto-fill functions.
22748 ;; `org-fill-paragraph' relies on adaptive filling and context
22749 ;; checking. Appropriate `fill-prefix' is computed with
22750 ;; `org-adaptive-fill-function'.
22752 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22753 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22754 ;; `org-adaptive-fill-function' value. Internally,
22755 ;; `org-comment-line-break-function' breaks the line.
22757 ;; `org-setup-filling' installs filling and auto-filling related
22758 ;; variables during `org-mode' initialization.
22760 (defvar org-element-paragraph-separate) ; org-element.el
22761 (defun org-setup-filling ()
22762 (require 'org-element)
22763 ;; Prevent auto-fill from inserting unwanted new items.
22764 (when (boundp 'fill-nobreak-predicate)
22765 (setq-local
22766 fill-nobreak-predicate
22767 (org-uniquify
22768 (append fill-nobreak-predicate
22769 '(org-fill-line-break-nobreak-p
22770 org-fill-n-macro-as-item-nobreak-p
22771 org-fill-paragraph-with-timestamp-nobreak-p)))))
22772 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22773 (setq-local paragraph-start paragraph-ending)
22774 (setq-local paragraph-separate paragraph-ending))
22775 (setq-local fill-paragraph-function 'org-fill-paragraph)
22776 (setq-local auto-fill-inhibit-regexp nil)
22777 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22778 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22779 (setq-local comment-line-break-function 'org-comment-line-break-function))
22781 (defun org-fill-line-break-nobreak-p ()
22782 "Non-nil when a new line at point would create an Org line break."
22783 (save-excursion
22784 (skip-chars-backward "[ \t]")
22785 (skip-chars-backward "\\\\")
22786 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22788 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22789 "Non-nil when a new line at point would split a timestamp."
22790 (and (org-at-timestamp-p 'lax)
22791 (not (looking-at org-ts-regexp-both))))
22793 (defun org-fill-n-macro-as-item-nobreak-p ()
22794 "Non-nil when a new line at point would create a new list."
22795 ;; During export, a "n" macro followed by a dot or a closing
22796 ;; parenthesis can end up being parsed as a new list item.
22797 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22799 (declare-function message-in-body-p "message" ())
22800 (defvar orgtbl-line-start-regexp) ; From org-table.el
22801 (defun org-adaptive-fill-function ()
22802 "Compute a fill prefix for the current line.
22803 Return fill prefix, as a string, or nil if current line isn't
22804 meant to be filled. For convenience, if `adaptive-fill-regexp'
22805 matches in paragraphs or comments, use it."
22806 (catch 'exit
22807 (when (derived-mode-p 'message-mode)
22808 (save-excursion
22809 (beginning-of-line)
22810 (cond ((not (message-in-body-p)) (throw 'exit nil))
22811 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22812 ((looking-at message-cite-prefix-regexp)
22813 (throw 'exit (match-string-no-properties 0)))
22814 ((looking-at org-outline-regexp)
22815 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22816 (org-with-wide-buffer
22817 (unless (org-at-heading-p)
22818 (let* ((p (line-beginning-position))
22819 (element (save-excursion
22820 (beginning-of-line)
22821 (org-element-at-point)))
22822 (type (org-element-type element))
22823 (post-affiliated (org-element-property :post-affiliated element)))
22824 (unless (< p post-affiliated)
22825 (cl-case type
22826 (comment
22827 (save-excursion
22828 (beginning-of-line)
22829 (looking-at "[ \t]*")
22830 (concat (match-string 0) "# ")))
22831 (footnote-definition "")
22832 ((item plain-list)
22833 (make-string (org-list-item-body-column post-affiliated) ?\s))
22834 (paragraph
22835 ;; Fill prefix is usually the same as the current line,
22836 ;; unless the paragraph is at the beginning of an item.
22837 (let ((parent (org-element-property :parent element)))
22838 (save-excursion
22839 (beginning-of-line)
22840 (cond ((eq (org-element-type parent) 'item)
22841 (make-string (org-list-item-body-column
22842 (org-element-property :begin parent))
22843 ?\s))
22844 ((and adaptive-fill-regexp
22845 ;; Locally disable
22846 ;; `adaptive-fill-function' to let
22847 ;; `fill-context-prefix' handle
22848 ;; `adaptive-fill-regexp' variable.
22849 (let (adaptive-fill-function)
22850 (fill-context-prefix
22851 post-affiliated
22852 (org-element-property :end element)))))
22853 ((looking-at "[ \t]+") (match-string 0))
22854 (t "")))))
22855 (comment-block
22856 ;; Only fill contents if P is within block boundaries.
22857 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22858 (forward-line)
22859 (point)))
22860 (cend (save-excursion
22861 (goto-char (org-element-property :end element))
22862 (skip-chars-backward " \r\t\n")
22863 (line-beginning-position))))
22864 (when (and (>= p cbeg) (< p cend))
22865 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22866 (match-string 0)
22867 "")))))))))))
22869 (declare-function message-goto-body "message" ())
22870 (defvar message-cite-prefix-regexp) ; From message.el
22872 (defun org-fill-element (&optional justify)
22873 "Fill element at point, when applicable.
22875 This function only applies to comment blocks, comments, example
22876 blocks and paragraphs. Also, as a special case, re-align table
22877 when point is at one.
22879 If JUSTIFY is non-nil (interactively, with prefix argument),
22880 justify as well. If `sentence-end-double-space' is non-nil, then
22881 period followed by one space does not end a sentence, so don't
22882 break a line there. The variable `fill-column' controls the
22883 width for filling.
22885 For convenience, when point is at a plain list, an item or
22886 a footnote definition, try to fill the first paragraph within."
22887 (with-syntax-table org-mode-transpose-word-syntax-table
22888 ;; Move to end of line in order to get the first paragraph within
22889 ;; a plain list or a footnote definition.
22890 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22891 ;; First check if point is in a blank line at the beginning of
22892 ;; the buffer. In that case, ignore filling.
22893 (cl-case (org-element-type element)
22894 ;; Use major mode filling function is src blocks.
22895 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22896 ;; Align Org tables, leave table.el tables as-is.
22897 (table-row (org-table-align) t)
22898 (table
22899 (when (eq (org-element-property :type element) 'org)
22900 (save-excursion
22901 (goto-char (org-element-property :post-affiliated element))
22902 (org-table-align)))
22904 (paragraph
22905 ;; Paragraphs may contain `line-break' type objects.
22906 (let ((beg (max (point-min)
22907 (org-element-property :contents-begin element)))
22908 (end (min (point-max)
22909 (org-element-property :contents-end element))))
22910 ;; Do nothing if point is at an affiliated keyword.
22911 (if (< (line-end-position) beg) t
22912 (when (derived-mode-p 'message-mode)
22913 ;; In `message-mode', do not fill following citation
22914 ;; in current paragraph nor text before message body.
22915 (let ((body-start (save-excursion (message-goto-body))))
22916 (when body-start (setq beg (max body-start beg))))
22917 (when (save-excursion
22918 (re-search-forward
22919 (concat "^" message-cite-prefix-regexp) end t))
22920 (setq end (match-beginning 0))))
22921 ;; Fill paragraph, taking line breaks into account.
22922 (save-excursion
22923 (goto-char beg)
22924 (let ((cuts (list beg)))
22925 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22926 (when (eq 'line-break
22927 (org-element-type
22928 (save-excursion (backward-char)
22929 (org-element-context))))
22930 (push (point) cuts)))
22931 (dolist (c (delq end cuts))
22932 (fill-region-as-paragraph c end justify)
22933 (setq end c))))
22934 t)))
22935 ;; Contents of `comment-block' type elements should be
22936 ;; filled as plain text, but only if point is within block
22937 ;; markers.
22938 (comment-block
22939 (let* ((case-fold-search t)
22940 (beg (save-excursion
22941 (goto-char (org-element-property :begin element))
22942 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22943 (forward-line)
22944 (point)))
22945 (end (save-excursion
22946 (goto-char (org-element-property :end element))
22947 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22948 (line-beginning-position))))
22949 (if (or (< (point) beg) (> (point) end)) t
22950 (fill-region-as-paragraph
22951 (save-excursion (end-of-line)
22952 (re-search-backward "^[ \t]*$" beg 'move)
22953 (line-beginning-position))
22954 (save-excursion (beginning-of-line)
22955 (re-search-forward "^[ \t]*$" end 'move)
22956 (line-beginning-position))
22957 justify))))
22958 ;; Fill comments.
22959 (comment
22960 (let ((begin (org-element-property :post-affiliated element))
22961 (end (org-element-property :end element)))
22962 (when (and (>= (point) begin) (<= (point) end))
22963 (let ((begin (save-excursion
22964 (end-of-line)
22965 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22966 (progn (forward-line) (point))
22967 begin)))
22968 (end (save-excursion
22969 (end-of-line)
22970 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22971 (1- (line-beginning-position))
22972 (skip-chars-backward " \r\t\n")
22973 (line-end-position)))))
22974 ;; Do not fill comments when at a blank line.
22975 (when (> end begin)
22976 (let ((fill-prefix
22977 (save-excursion
22978 (beginning-of-line)
22979 (looking-at "[ \t]*#")
22980 (let ((comment-prefix (match-string 0)))
22981 (goto-char (match-end 0))
22982 (if (looking-at adaptive-fill-regexp)
22983 (concat comment-prefix (match-string 0))
22984 (concat comment-prefix " "))))))
22985 (save-excursion
22986 (fill-region-as-paragraph begin end justify))))))
22988 ;; Ignore every other element.
22989 (otherwise t)))))
22991 (defun org-fill-paragraph (&optional justify region)
22992 "Fill element at point, when applicable.
22994 This function only applies to comment blocks, comments, example
22995 blocks and paragraphs. Also, as a special case, re-align table
22996 when point is at one.
22998 For convenience, when point is at a plain list, an item or
22999 a footnote definition, try to fill the first paragraph within.
23001 If JUSTIFY is non-nil (interactively, with prefix argument),
23002 justify as well. If `sentence-end-double-space' is non-nil, then
23003 period followed by one space does not end a sentence, so don't
23004 break a line there. The variable `fill-column' controls the
23005 width for filling.
23007 The REGION argument is non-nil if called interactively; in that
23008 case, if Transient Mark mode is enabled and the mark is active,
23009 fill each of the elements in the active region, instead of just
23010 filling the current element."
23011 (interactive (progn
23012 (barf-if-buffer-read-only)
23013 (list (if current-prefix-arg 'full) t)))
23014 (cond
23015 ((and (derived-mode-p 'message-mode)
23016 (or (not (message-in-body-p))
23017 (save-excursion (move-beginning-of-line 1)
23018 (looking-at message-cite-prefix-regexp))))
23019 ;; First ensure filling is correct in message-mode.
23020 (let ((fill-paragraph-function
23021 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23022 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23023 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23024 (paragraph-separate
23025 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23026 (fill-paragraph nil)))
23027 ((and region transient-mark-mode mark-active
23028 (not (eq (region-beginning) (region-end))))
23029 (let ((origin (point-marker))
23030 (start (region-beginning)))
23031 (unwind-protect
23032 (progn
23033 (goto-char (region-end))
23034 (while (> (point) start)
23035 (org-backward-paragraph)
23036 (org-fill-element justify)))
23037 (goto-char origin)
23038 (set-marker origin nil))))
23039 (t (org-fill-element justify))))
23040 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23042 (defun org-auto-fill-function ()
23043 "Auto-fill function."
23044 ;; Check if auto-filling is meaningful.
23045 (let ((fc (current-fill-column)))
23046 (when (and fc (> (current-column) fc))
23047 (let* ((fill-prefix (org-adaptive-fill-function))
23048 ;; Enforce empty fill prefix, if required. Otherwise, it
23049 ;; will be computed again.
23050 (adaptive-fill-mode (not (equal fill-prefix ""))))
23051 (when fill-prefix (do-auto-fill))))))
23053 (defun org-comment-line-break-function (&optional soft)
23054 "Break line at point and indent, continuing comment if within one.
23055 The inserted newline is marked hard if variable
23056 `use-hard-newlines' is true, unless optional argument SOFT is
23057 non-nil."
23058 (if soft (insert-and-inherit ?\n) (newline 1))
23059 (save-excursion (forward-char -1) (delete-horizontal-space))
23060 (delete-horizontal-space)
23061 (indent-to-left-margin)
23062 (insert-before-markers-and-inherit fill-prefix))
23065 ;;; Fixed Width Areas
23067 (defun org-toggle-fixed-width ()
23068 "Toggle fixed-width markup.
23070 Add or remove fixed-width markup on current line, whenever it
23071 makes sense. Return an error otherwise.
23073 If a region is active and if it contains only fixed-width areas
23074 or blank lines, remove all fixed-width markup in it. If the
23075 region contains anything else, convert all non-fixed-width lines
23076 to fixed-width ones.
23078 Blank lines at the end of the region are ignored unless the
23079 region only contains such lines."
23080 (interactive)
23081 (if (not (org-region-active-p))
23082 ;; No region:
23084 ;; Remove fixed width marker only in a fixed-with element.
23086 ;; Add fixed width maker in paragraphs, in blank lines after
23087 ;; elements or at the beginning of a headline or an inlinetask,
23088 ;; and before any one-line elements (e.g., a clock).
23089 (progn
23090 (beginning-of-line)
23091 (let* ((element (org-element-at-point))
23092 (type (org-element-type element)))
23093 (cond
23094 ((and (eq type 'fixed-width)
23095 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23096 (replace-match
23097 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23098 ((and (memq type '(babel-call clock comment diary-sexp headline
23099 horizontal-rule keyword paragraph
23100 planning))
23101 (<= (org-element-property :post-affiliated element) (point)))
23102 (skip-chars-forward " \t")
23103 (insert ": "))
23104 ((and (looking-at-p "[ \t]*$")
23105 (or (eq type 'inlinetask)
23106 (save-excursion
23107 (skip-chars-forward " \r\t\n")
23108 (<= (org-element-property :end element) (point)))))
23109 (delete-region (point) (line-end-position))
23110 (org-indent-line)
23111 (insert ": "))
23112 (t (user-error "Cannot insert a fixed-width line here")))))
23113 ;; Region active.
23114 (let* ((begin (save-excursion
23115 (goto-char (region-beginning))
23116 (line-beginning-position)))
23117 (end (copy-marker
23118 (save-excursion
23119 (goto-char (region-end))
23120 (unless (eolp) (beginning-of-line))
23121 (if (save-excursion (re-search-backward "\\S-" begin t))
23122 (progn (skip-chars-backward " \r\t\n") (point))
23123 (point)))))
23124 (all-fixed-width-p
23125 (catch 'not-all-p
23126 (save-excursion
23127 (goto-char begin)
23128 (skip-chars-forward " \r\t\n")
23129 (when (eobp) (throw 'not-all-p nil))
23130 (while (< (point) end)
23131 (let ((element (org-element-at-point)))
23132 (if (eq (org-element-type element) 'fixed-width)
23133 (goto-char (org-element-property :end element))
23134 (throw 'not-all-p nil))))
23135 t))))
23136 (if all-fixed-width-p
23137 (save-excursion
23138 (goto-char begin)
23139 (while (< (point) end)
23140 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23141 (replace-match
23142 "" nil nil nil
23143 (if (= (line-end-position) (match-end 0)) 0 1)))
23144 (forward-line)))
23145 (let ((min-ind (point-max)))
23146 ;; Find minimum indentation across all lines.
23147 (save-excursion
23148 (goto-char begin)
23149 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23150 (setq min-ind 0)
23151 (catch 'zerop
23152 (while (< (point) end)
23153 (unless (looking-at-p "[ \t]*$")
23154 (let ((ind (org-get-indentation)))
23155 (setq min-ind (min min-ind ind))
23156 (when (zerop ind) (throw 'zerop t))))
23157 (forward-line)))))
23158 ;; Loop over all lines and add fixed-width markup everywhere
23159 ;; but in fixed-width lines.
23160 (save-excursion
23161 (goto-char begin)
23162 (while (< (point) end)
23163 (cond
23164 ((org-at-heading-p)
23165 (insert ": ")
23166 (forward-line)
23167 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23168 (insert ":")
23169 (forward-line)))
23170 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23171 (let* ((element (org-element-at-point))
23172 (element-end (org-element-property :end element)))
23173 (if (eq (org-element-type element) 'fixed-width)
23174 (progn (goto-char element-end)
23175 (skip-chars-backward " \r\t\n")
23176 (forward-line))
23177 (let ((limit (min end element-end)))
23178 (while (< (point) limit)
23179 (org-move-to-column min-ind t)
23180 (insert ": ")
23181 (forward-line))))))
23183 (org-move-to-column min-ind t)
23184 (insert ": ")
23185 (forward-line)))))))
23186 (set-marker end nil))))
23189 ;;; Comments
23191 ;; Org comments syntax is quite complex. It requires the entire line
23192 ;; to be just a comment. Also, even with the right syntax at the
23193 ;; beginning of line, some elements (e.g., verse-block or
23194 ;; example-block) don't accept comments. Usual Emacs comment commands
23195 ;; cannot cope with those requirements. Therefore, Org replaces them.
23197 ;; Org still relies on `comment-dwim', but cannot trust
23198 ;; `comment-only-p'. So, `comment-region-function' and
23199 ;; `uncomment-region-function' both point
23200 ;; to`org-comment-or-uncomment-region'. Eventually,
23201 ;; `org-insert-comment' takes care of insertion of comments at the
23202 ;; beginning of line.
23204 ;; `org-setup-comments-handling' install comments related variables
23205 ;; during `org-mode' initialization.
23207 (defun org-setup-comments-handling ()
23208 (interactive)
23209 (setq-local comment-use-syntax nil)
23210 (setq-local comment-start "# ")
23211 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23212 (setq-local comment-insert-comment-function 'org-insert-comment)
23213 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23214 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23216 (defun org-insert-comment ()
23217 "Insert an empty comment above current line.
23218 If the line is empty, insert comment at its beginning. When
23219 point is within a source block, comment according to the related
23220 major mode."
23221 (if (let ((element (org-element-at-point)))
23222 (and (eq (org-element-type element) 'src-block)
23223 (< (save-excursion
23224 (goto-char (org-element-property :post-affiliated element))
23225 (line-end-position))
23226 (point))
23227 (> (save-excursion
23228 (goto-char (org-element-property :end element))
23229 (skip-chars-backward " \r\t\n")
23230 (line-beginning-position))
23231 (point))))
23232 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23233 (beginning-of-line)
23234 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23235 (open-line 1))
23236 (org-indent-line)
23237 (insert "# ")))
23239 (defvar comment-empty-lines) ; From newcomment.el.
23240 (defun org-comment-or-uncomment-region (beg end &rest _)
23241 "Comment or uncomment each non-blank line in the region.
23242 Uncomment each non-blank line between BEG and END if it only
23243 contains commented lines. Otherwise, comment them. If region is
23244 strictly within a source block, use appropriate comment syntax."
23245 (if (let ((element (org-element-at-point)))
23246 (and (eq (org-element-type element) 'src-block)
23247 (< (save-excursion
23248 (goto-char (org-element-property :post-affiliated element))
23249 (line-end-position))
23250 beg)
23251 (>= (save-excursion
23252 (goto-char (org-element-property :end element))
23253 (skip-chars-backward " \r\t\n")
23254 (line-beginning-position))
23255 end)))
23256 ;; Translate region boundaries for the Org buffer to the source
23257 ;; buffer.
23258 (let ((offset (- end beg)))
23259 (save-excursion
23260 (goto-char beg)
23261 (org-babel-do-in-edit-buffer
23262 (comment-or-uncomment-region (point) (+ offset (point))))))
23263 (save-restriction
23264 ;; Restrict region
23265 (narrow-to-region (save-excursion (goto-char beg)
23266 (skip-chars-forward " \r\t\n" end)
23267 (line-beginning-position))
23268 (save-excursion (goto-char end)
23269 (skip-chars-backward " \r\t\n" beg)
23270 (line-end-position)))
23271 (let ((uncommentp
23272 ;; UNCOMMENTP is non-nil when every non blank line between
23273 ;; BEG and END is a comment.
23274 (save-excursion
23275 (goto-char (point-min))
23276 (while (and (not (eobp))
23277 (let ((element (org-element-at-point)))
23278 (and (eq (org-element-type element) 'comment)
23279 (goto-char (min (point-max)
23280 (org-element-property
23281 :end element)))))))
23282 (eobp))))
23283 (if uncommentp
23284 ;; Only blank lines and comments in region: uncomment it.
23285 (save-excursion
23286 (goto-char (point-min))
23287 (while (not (eobp))
23288 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23289 (replace-match "" nil nil nil 1))
23290 (forward-line)))
23291 ;; Comment each line in region.
23292 (let ((min-indent (point-max)))
23293 ;; First find the minimum indentation across all lines.
23294 (save-excursion
23295 (goto-char (point-min))
23296 (while (and (not (eobp)) (not (zerop min-indent)))
23297 (unless (looking-at "[ \t]*$")
23298 (setq min-indent (min min-indent (current-indentation))))
23299 (forward-line)))
23300 ;; Then loop over all lines.
23301 (save-excursion
23302 (goto-char (point-min))
23303 (while (not (eobp))
23304 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23305 ;; Don't get fooled by invisible text (e.g. link path)
23306 ;; when moving to column MIN-INDENT.
23307 (let ((buffer-invisibility-spec nil))
23308 (org-move-to-column min-indent t))
23309 (insert comment-start))
23310 (forward-line)))))))))
23312 (defun org-comment-dwim (_arg)
23313 "Call `comment-dwim' within a source edit buffer if needed."
23314 (interactive "*P")
23315 (if (org-in-src-block-p)
23316 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23317 (call-interactively 'comment-dwim)))
23320 ;;; Timestamps API
23322 ;; This section contains tools to operate on timestamp objects, as
23323 ;; returned by, e.g. `org-element-context'.
23325 (defun org-timestamp--to-internal-time (timestamp &optional end)
23326 "Encode TIMESTAMP object into Emacs internal time.
23327 Use end of date range or time range when END is non-nil."
23328 (apply #'encode-time
23329 (cons 0
23330 (mapcar
23331 (lambda (prop) (or (org-element-property prop timestamp) 0))
23332 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23333 '(:minute-start :hour-start :day-start :month-start
23334 :year-start))))))
23336 (defun org-timestamp-has-time-p (timestamp)
23337 "Non-nil when TIMESTAMP has a time specified."
23338 (org-element-property :hour-start timestamp))
23340 (defun org-timestamp-format (timestamp format &optional end utc)
23341 "Format a TIMESTAMP object into a string.
23343 FORMAT is a format specifier to be passed to
23344 `format-time-string'.
23346 When optional argument END is non-nil, use end of date-range or
23347 time-range, if possible.
23349 When optional argument UTC is non-nil, time will be expressed as
23350 Universal Time."
23351 (format-time-string
23352 format (org-timestamp--to-internal-time timestamp end)
23353 (and utc t)))
23355 (defun org-timestamp-split-range (timestamp &optional end)
23356 "Extract a TIMESTAMP object from a date or time range.
23358 END, when non-nil, means extract the end of the range.
23359 Otherwise, extract its start.
23361 Return a new timestamp object."
23362 (let ((type (org-element-property :type timestamp)))
23363 (if (memq type '(active inactive diary)) timestamp
23364 (let ((split-ts (org-element-copy timestamp)))
23365 ;; Set new type.
23366 (org-element-put-property
23367 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23368 ;; Copy start properties over end properties if END is
23369 ;; non-nil. Otherwise, copy end properties over `start' ones.
23370 (let ((p-alist '((:minute-start . :minute-end)
23371 (:hour-start . :hour-end)
23372 (:day-start . :day-end)
23373 (:month-start . :month-end)
23374 (:year-start . :year-end))))
23375 (dolist (p-cell p-alist)
23376 (org-element-put-property
23377 split-ts
23378 (funcall (if end #'car #'cdr) p-cell)
23379 (org-element-property
23380 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23381 ;; Eventually refresh `:raw-value'.
23382 (org-element-put-property split-ts :raw-value nil)
23383 (org-element-put-property
23384 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23386 (defun org-timestamp-translate (timestamp &optional boundary)
23387 "Translate TIMESTAMP object to custom format.
23389 Format string is defined in `org-time-stamp-custom-formats',
23390 which see.
23392 When optional argument BOUNDARY is non-nil, it is either the
23393 symbol `start' or `end'. In this case, only translate the
23394 starting or ending part of TIMESTAMP if it is a date or time
23395 range. Otherwise, translate both parts.
23397 Return timestamp as-is if `org-display-custom-times' is nil or if
23398 it has a `diary' type."
23399 (let ((type (org-element-property :type timestamp)))
23400 (if (or (not org-display-custom-times) (eq type 'diary))
23401 (org-element-interpret-data timestamp)
23402 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23403 org-time-stamp-custom-formats)))
23404 (if (and (not boundary) (memq type '(active-range inactive-range)))
23405 (concat (org-timestamp-format timestamp fmt)
23406 "--"
23407 (org-timestamp-format timestamp fmt t))
23408 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23412 ;;; Other stuff.
23414 (defvar reftex-docstruct-symbol)
23415 (defvar org--rds)
23417 (defun org-reftex-citation ()
23418 "Use reftex-citation to insert a citation into the buffer.
23419 This looks for a line like
23421 #+BIBLIOGRAPHY: foo plain option:-d
23423 and derives from it that foo.bib is the bibliography file relevant
23424 for this document. It then installs the necessary environment for RefTeX
23425 to work in this buffer and calls `reftex-citation' to insert a citation
23426 into the buffer.
23428 Export of such citations to both LaTeX and HTML is handled by the contributed
23429 package ox-bibtex by Taru Karttunen."
23430 (interactive)
23431 (let ((reftex-docstruct-symbol 'org--rds)
23432 org--rds bib)
23433 (org-with-wide-buffer
23434 (let ((case-fold-search t)
23435 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23436 (if (not (save-excursion
23437 (or (re-search-forward re nil t)
23438 (re-search-backward re nil t))))
23439 (user-error "No bibliography defined in file")
23440 (setq bib (concat (match-string 1) ".bib")
23441 org--rds (list (list 'bib bib))))))
23442 (call-interactively 'reftex-citation)))
23444 ;;;; Functions extending outline functionality
23446 (defun org-beginning-of-line (&optional n)
23447 "Go to the beginning of the current visible line.
23449 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23450 tags on the first attempt, and only move to after the tags when
23451 the cursor is already beyond the end of the headline.
23453 With argument N not nil or 1, move forward N - 1 lines first."
23454 (interactive "^p")
23455 (let ((origin (point))
23456 (special (pcase org-special-ctrl-a/e
23457 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23458 deactivate-mark)
23459 ;; First move to a visible line.
23460 (if (bound-and-true-p visual-line-mode)
23461 (beginning-of-visual-line n)
23462 (move-beginning-of-line n)
23463 ;; `move-beginning-of-line' may leave point after invisible
23464 ;; characters if line starts with such of these (e.g., with
23465 ;; a link at column 0). Really move to the beginning of the
23466 ;; current visible line.
23467 (beginning-of-line))
23468 (cond
23469 ;; No special behavior. Point is already at the beginning of
23470 ;; a line, logical or visual.
23471 ((not special))
23472 ;; `beginning-of-visual-line' left point before logical beginning
23473 ;; of line: point is at the beginning of a visual line. Bail
23474 ;; out.
23475 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23476 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23477 ;; At a headline, special position is before the title, but
23478 ;; after any TODO keyword or priority cookie.
23479 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23480 (line-end-position)))
23481 (bol (point)))
23482 (if (eq special 'reversed)
23483 (when (and (= origin bol) (eq last-command this-command))
23484 (goto-char refpos))
23485 (when (or (> origin refpos) (= origin bol))
23486 (goto-char refpos)))))
23487 ((and (looking-at org-list-full-item-re)
23488 (memq (org-element-type (save-match-data (org-element-at-point)))
23489 '(item plain-list)))
23490 ;; Set special position at first white space character after
23491 ;; bullet, and check-box, if any.
23492 (let ((after-bullet
23493 (let ((box (match-end 3)))
23494 (cond ((not box) (match-end 1))
23495 ((eq (char-after box) ?\s) (1+ box))
23496 (t box)))))
23497 (if (eq special 'reversed)
23498 (when (and (= (point) origin) (eq last-command this-command))
23499 (goto-char after-bullet))
23500 (when (or (> origin after-bullet) (= (point) origin))
23501 (goto-char after-bullet)))))
23502 ;; No special context. Point is already at beginning of line.
23503 (t nil))))
23505 (defun org-end-of-line (&optional n)
23506 "Go to the end of the line, but before ellipsis, if any.
23508 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23509 tags on the first attempt, and only move to after the tags when
23510 the cursor is already beyond the end of the headline.
23512 With argument N not nil or 1, move forward N - 1 lines first."
23513 (interactive "^p")
23514 (let ((origin (point))
23515 (special (pcase org-special-ctrl-a/e
23516 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23517 deactivate-mark)
23518 ;; First move to a visible line.
23519 (if (bound-and-true-p visual-line-mode)
23520 (beginning-of-visual-line n)
23521 (move-beginning-of-line n))
23522 (cond
23523 ;; At a headline, with tags.
23524 ((and special
23525 (save-excursion
23526 (beginning-of-line)
23527 (let ((case-fold-search nil))
23528 (looking-at org-complex-heading-regexp)))
23529 (match-end 5))
23530 (let ((tags (save-excursion
23531 (goto-char (match-beginning 5))
23532 (skip-chars-backward " \t")
23533 (point)))
23534 (visual-end (and (bound-and-true-p visual-line-mode)
23535 (save-excursion
23536 (end-of-visual-line)
23537 (point)))))
23538 ;; If `end-of-visual-line' brings us before end of line or
23539 ;; even tags, i.e., the headline spans over multiple visual
23540 ;; lines, move there.
23541 (cond ((and visual-end
23542 (< visual-end tags)
23543 (<= origin visual-end))
23544 (goto-char visual-end))
23545 ((eq special 'reversed)
23546 (if (and (= origin (line-end-position))
23547 (eq this-command last-command))
23548 (goto-char tags)
23549 (end-of-line)))
23551 (if (or (< origin tags) (= origin (line-end-position)))
23552 (goto-char tags)
23553 (end-of-line))))))
23554 ((bound-and-true-p visual-line-mode)
23555 (let ((bol (line-beginning-position)))
23556 (end-of-visual-line)
23557 ;; If `end-of-visual-line' gets us past the ellipsis at the
23558 ;; end of a line, backtrack and use `end-of-line' instead.
23559 (when (/= bol (line-beginning-position))
23560 (goto-char bol)
23561 (end-of-line))))
23562 (t (end-of-line)))))
23564 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23565 (define-key org-mode-map "\C-e" 'org-end-of-line)
23567 (defun org-backward-sentence (&optional _arg)
23568 "Go to beginning of sentence, or beginning of table field.
23569 This will call `backward-sentence' or `org-table-beginning-of-field',
23570 depending on context."
23571 (interactive)
23572 (let* ((element (org-element-at-point))
23573 (contents-begin (org-element-property :contents-begin element))
23574 (table (org-element-lineage element '(table) t)))
23575 (if (and table
23576 (> (point) contents-begin)
23577 (<= (point) (org-element-property :contents-end table)))
23578 (call-interactively #'org-table-beginning-of-field)
23579 (save-restriction
23580 (when (and contents-begin
23581 (< (point-min) contents-begin)
23582 (> (point) contents-begin))
23583 (narrow-to-region contents-begin
23584 (org-element-property :contents-end element)))
23585 (call-interactively #'backward-sentence)))))
23587 (defun org-forward-sentence (&optional _arg)
23588 "Go to end of sentence, or end of table field.
23589 This will call `forward-sentence' or `org-table-end-of-field',
23590 depending on context."
23591 (interactive)
23592 (let* ((element (org-element-at-point))
23593 (contents-end (org-element-property :contents-end element))
23594 (table (org-element-lineage element '(table) t)))
23595 (if (and table
23596 (>= (point) (org-element-property :contents-begin table))
23597 (< (point) contents-end))
23598 (call-interactively #'org-table-end-of-field)
23599 (save-restriction
23600 (when (and contents-end
23601 (> (point-max) contents-end)
23602 ;; Skip blank lines between elements.
23603 (< (org-element-property :end element)
23604 (save-excursion (goto-char contents-end)
23605 (skip-chars-forward " \r\t\n"))))
23606 (narrow-to-region (org-element-property :contents-begin element)
23607 contents-end))
23608 (call-interactively #'forward-sentence)))))
23610 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23611 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23613 (defun org-kill-line (&optional _arg)
23614 "Kill line, to tags or end of line."
23615 (interactive)
23616 (cond
23617 ((or (not org-special-ctrl-k)
23618 (bolp)
23619 (not (org-at-heading-p)))
23620 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23621 org-ctrl-k-protect-subtree
23622 (or (eq org-ctrl-k-protect-subtree 'error)
23623 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23624 (user-error "C-k aborted as it would kill a hidden subtree"))
23625 (call-interactively
23626 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23627 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23628 (kill-region (point) (match-beginning 1))
23629 (org-set-tags nil t))
23630 (t (kill-region (point) (point-at-eol)))))
23632 (define-key org-mode-map "\C-k" 'org-kill-line)
23634 (defun org-yank (&optional arg)
23635 "Yank. If the kill is a subtree, treat it specially.
23636 This command will look at the current kill and check if is a single
23637 subtree, or a series of subtrees[1]. If it passes the test, and if the
23638 cursor is at the beginning of a line or after the stars of a currently
23639 empty headline, then the yank is handled specially. How exactly depends
23640 on the value of the following variables.
23642 `org-yank-folded-subtrees'
23643 By default, this variable is non-nil, which results in
23644 subtree(s) being folded after insertion, except if doing so
23645 would swallow text after the yanked text.
23647 `org-yank-adjusted-subtrees'
23648 When non-nil (the default value is nil), the subtree will be
23649 promoted or demoted in order to fit into the local outline tree
23650 structure, which means that the level will be adjusted so that it
23651 becomes the smaller one of the two *visible* surrounding headings.
23653 Any prefix to this command will cause `yank' to be called directly with
23654 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23655 will just
23656 plainly yank the text as it is.
23658 \[1] The test checks if the first non-white line is a heading
23659 and if there are no other headings with fewer stars."
23660 (interactive "P")
23661 (org-yank-generic 'yank arg))
23663 (defun org-yank-generic (command arg)
23664 "Perform some yank-like command.
23666 This function implements the behavior described in the `org-yank'
23667 documentation. However, it has been generalized to work for any
23668 interactive command with similar behavior."
23670 ;; pretend to be command COMMAND
23671 (setq this-command command)
23673 (if arg
23674 (call-interactively command)
23676 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23677 (and (org-kill-is-subtree-p)
23678 (or (bolp)
23679 (and (looking-at "[ \t]*$")
23680 (string-match
23681 "\\`\\*+\\'"
23682 (buffer-substring (point-at-bol) (point)))))))
23683 swallowp)
23684 (cond
23685 ((and subtreep org-yank-folded-subtrees)
23686 (let ((beg (point))
23687 end)
23688 (if (and subtreep org-yank-adjusted-subtrees)
23689 (org-paste-subtree nil nil 'for-yank)
23690 (call-interactively command))
23692 (setq end (point))
23693 (goto-char beg)
23694 (when (and (bolp) subtreep
23695 (not (setq swallowp
23696 (org-yank-folding-would-swallow-text beg end))))
23697 (org-with-limited-levels
23698 (or (looking-at org-outline-regexp)
23699 (re-search-forward org-outline-regexp-bol end t))
23700 (while (and (< (point) end) (looking-at org-outline-regexp))
23701 (outline-hide-subtree)
23702 (org-cycle-show-empty-lines 'folded)
23703 (condition-case nil
23704 (outline-forward-same-level 1)
23705 (error (goto-char end))))))
23706 (when swallowp
23707 (message
23708 "Inserted text not folded because that would swallow text"))
23710 (goto-char end)
23711 (skip-chars-forward " \t\n\r")
23712 (beginning-of-line 1)
23713 (push-mark beg 'nomsg)))
23714 ((and subtreep org-yank-adjusted-subtrees)
23715 (let ((beg (point-at-bol)))
23716 (org-paste-subtree nil nil 'for-yank)
23717 (push-mark beg 'nomsg)))
23719 (call-interactively command))))))
23721 (defun org-yank-folding-would-swallow-text (beg end)
23722 "Would hide-subtree at BEG swallow any text after END?"
23723 (let (level)
23724 (org-with-limited-levels
23725 (save-excursion
23726 (goto-char beg)
23727 (when (or (looking-at org-outline-regexp)
23728 (re-search-forward org-outline-regexp-bol end t))
23729 (setq level (org-outline-level)))
23730 (goto-char end)
23731 (skip-chars-forward " \t\r\n\v\f")
23732 (not (or (eobp)
23733 (and (bolp) (looking-at-p org-outline-regexp)
23734 (<= (org-outline-level) level))))))))
23736 (define-key org-mode-map "\C-y" 'org-yank)
23738 (defun org-truely-invisible-p ()
23739 "Check if point is at a character currently not visible.
23740 This version does not only check the character property, but also
23741 `visible-mode'."
23742 (unless (bound-and-true-p visible-mode)
23743 (org-invisible-p)))
23745 (defun org-invisible-p2 ()
23746 "Check if point is at a character currently not visible.
23748 If the point is at EOL (and not at the beginning of a buffer too),
23749 move it back by one char before doing this check."
23750 (save-excursion
23751 (when (and (eolp) (not (bobp)))
23752 (backward-char 1))
23753 (org-invisible-p)))
23755 (defun org-back-to-heading (&optional invisible-ok)
23756 "Call `outline-back-to-heading', but provide a better error message."
23757 (condition-case nil
23758 (outline-back-to-heading invisible-ok)
23759 (error (error "Before first headline at position %d in buffer %s"
23760 (point) (current-buffer)))))
23762 (defun org-before-first-heading-p ()
23763 "Before first heading?"
23764 (save-excursion
23765 (end-of-line)
23766 (null (re-search-backward org-outline-regexp-bol nil t))))
23768 (defun org-at-heading-p (&optional ignored)
23769 (outline-on-heading-p t))
23771 (defun org-in-commented-heading-p (&optional no-inheritance)
23772 "Non-nil if point is under a commented heading.
23773 This function also checks ancestors of the current headline,
23774 unless optional argument NO-INHERITANCE is non-nil."
23775 (cond
23776 ((org-before-first-heading-p) nil)
23777 ((let ((headline (nth 4 (org-heading-components))))
23778 (and headline
23779 (let ((case-fold-search nil))
23780 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23781 headline)))))
23782 (no-inheritance nil)
23784 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23786 (defun org-at-comment-p nil
23787 "Is cursor in a commented line?"
23788 (save-excursion
23789 (save-match-data
23790 (beginning-of-line)
23791 (looking-at "^[ \t]*# "))))
23793 (defun org-at-drawer-p nil
23794 "Is cursor at a drawer keyword?"
23795 (save-excursion
23796 (move-beginning-of-line 1)
23797 (looking-at org-drawer-regexp)))
23799 (defun org-at-block-p nil
23800 "Is cursor at a block keyword?"
23801 (save-excursion
23802 (move-beginning-of-line 1)
23803 (looking-at org-block-regexp)))
23805 (defun org-point-at-end-of-empty-headline ()
23806 "If point is at the end of an empty headline, return t, else nil.
23807 If the heading only contains a TODO keyword, it is still still considered
23808 empty."
23809 (let ((case-fold-search nil))
23810 (and (looking-at "[ \t]*$")
23811 org-todo-line-regexp
23812 (save-excursion
23813 (beginning-of-line)
23814 (looking-at org-todo-line-regexp)
23815 (string= (match-string 3) "")))))
23817 (defun org-at-heading-or-item-p ()
23818 (or (org-at-heading-p) (org-at-item-p)))
23820 (defun org-at-target-p ()
23821 (or (org-in-regexp org-radio-target-regexp)
23822 (org-in-regexp org-target-regexp)))
23823 ;; Compatibility alias with Org versions < 7.8.03
23824 (defalias 'org-on-target-p 'org-at-target-p)
23826 (defun org-up-heading-all (arg)
23827 "Move to the heading line of which the present line is a subheading.
23828 This function considers both visible and invisible heading lines.
23829 With argument, move up ARG levels."
23830 (outline-up-heading arg t))
23832 (defun org-up-heading-safe ()
23833 "Move to the heading line of which the present line is a subheading.
23834 This version will not throw an error. It will return the level of the
23835 headline found, or nil if no higher level is found.
23837 Also, this function will be a lot faster than `outline-up-heading',
23838 because it relies on stars being the outline starters. This can really
23839 make a significant difference in outlines with very many siblings."
23840 (when (ignore-errors (org-back-to-heading t))
23841 (let ((level-up (1- (funcall outline-level))))
23842 (and (> level-up 0)
23843 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23844 (funcall outline-level)))))
23846 (defun org-first-sibling-p ()
23847 "Is this heading the first child of its parents?"
23848 (interactive)
23849 (let ((re org-outline-regexp-bol)
23850 level l)
23851 (unless (org-at-heading-p t)
23852 (user-error "Not at a heading"))
23853 (setq level (funcall outline-level))
23854 (save-excursion
23855 (if (not (re-search-backward re nil t))
23857 (setq l (funcall outline-level))
23858 (< l level)))))
23860 (defun org-goto-sibling (&optional previous)
23861 "Goto the next sibling, even if it is invisible.
23862 When PREVIOUS is set, go to the previous sibling instead. Returns t
23863 when a sibling was found. When none is found, return nil and don't
23864 move point."
23865 (let ((fun (if previous 're-search-backward 're-search-forward))
23866 (pos (point))
23867 (re org-outline-regexp-bol)
23868 level l)
23869 (when (ignore-errors (org-back-to-heading t))
23870 (setq level (funcall outline-level))
23871 (catch 'exit
23872 (or previous (forward-char 1))
23873 (while (funcall fun re nil t)
23874 (setq l (funcall outline-level))
23875 (when (< l level) (goto-char pos) (throw 'exit nil))
23876 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23877 (goto-char pos)
23878 nil))))
23880 (defun org-show-siblings ()
23881 "Show all siblings of the current headline."
23882 (save-excursion
23883 (while (org-goto-sibling) (org-flag-heading nil)))
23884 (save-excursion
23885 (while (org-goto-sibling 'previous)
23886 (org-flag-heading nil))))
23888 (defun org-goto-first-child ()
23889 "Goto the first child, even if it is invisible.
23890 Return t when a child was found. Otherwise don't move point and
23891 return nil."
23892 (let (level (pos (point)) (re org-outline-regexp-bol))
23893 (when (ignore-errors (org-back-to-heading t))
23894 (setq level (outline-level))
23895 (forward-char 1)
23896 (if (and (re-search-forward re nil t) (> (outline-level) level))
23897 (progn (goto-char (match-beginning 0)) t)
23898 (goto-char pos) nil))))
23900 (defun org-show-hidden-entry ()
23901 "Show an entry where even the heading is hidden."
23902 (save-excursion
23903 (org-show-entry)))
23905 (defun org-flag-heading (flag &optional entry)
23906 "Flag the current heading. FLAG non-nil means make invisible.
23907 When ENTRY is non-nil, show the entire entry."
23908 (save-excursion
23909 (org-back-to-heading t)
23910 ;; Check if we should show the entire entry
23911 (if entry
23912 (progn
23913 (org-show-entry)
23914 (save-excursion
23915 (and (outline-next-heading)
23916 (org-flag-heading nil))))
23917 (outline-flag-region (max (point-min) (1- (point)))
23918 (save-excursion (outline-end-of-heading) (point))
23919 flag))))
23921 (defun org-get-next-sibling ()
23922 "Move to next heading of the same level, and return point.
23923 If there is no such heading, return nil.
23924 This is like outline-next-sibling, but invisible headings are ok."
23925 (let ((level (funcall outline-level)))
23926 (outline-next-heading)
23927 (while (and (not (eobp)) (> (funcall outline-level) level))
23928 (outline-next-heading))
23929 (unless (or (eobp) (< (funcall outline-level) level))
23930 (point))))
23932 (defun org-get-last-sibling ()
23933 "Move to previous heading of the same level, and return point.
23934 If there is no such heading, return nil."
23935 (let ((opoint (point))
23936 (level (funcall outline-level)))
23937 (outline-previous-heading)
23938 (when (and (/= (point) opoint) (outline-on-heading-p t))
23939 (while (and (> (funcall outline-level) level)
23940 (not (bobp)))
23941 (outline-previous-heading))
23942 (unless (< (funcall outline-level) level)
23943 (point)))))
23945 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23946 "Goto to the end of a subtree."
23947 ;; This contains an exact copy of the original function, but it uses
23948 ;; `org-back-to-heading', to make it work also in invisible
23949 ;; trees. And is uses an invisible-ok argument.
23950 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23951 ;; Furthermore, when used inside Org, finding the end of a large subtree
23952 ;; with many children and grandchildren etc, this can be much faster
23953 ;; than the outline version.
23954 (org-back-to-heading invisible-ok)
23955 (let ((first t)
23956 (level (funcall outline-level)))
23957 (if (and (derived-mode-p 'org-mode) (< level 1000))
23958 ;; A true heading (not a plain list item), in Org
23959 ;; This means we can easily find the end by looking
23960 ;; only for the right number of stars. Using a regexp to do
23961 ;; this is so much faster than using a Lisp loop.
23962 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23963 (forward-char 1)
23964 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23965 ;; something else, do it the slow way
23966 (while (and (not (eobp))
23967 (or first (> (funcall outline-level) level)))
23968 (setq first nil)
23969 (outline-next-heading)))
23970 (unless to-heading
23971 (when (memq (preceding-char) '(?\n ?\^M))
23972 ;; Go to end of line before heading
23973 (forward-char -1)
23974 (when (memq (preceding-char) '(?\n ?\^M))
23975 ;; leave blank line before heading
23976 (forward-char -1)))))
23977 (point))
23979 (defun org-end-of-meta-data (&optional full)
23980 "Skip planning line and properties drawer in current entry.
23981 When optional argument FULL is non-nil, also skip empty lines,
23982 clocking lines and regular drawers at the beginning of the
23983 entry."
23984 (org-back-to-heading t)
23985 (forward-line)
23986 (when (looking-at-p org-planning-line-re) (forward-line))
23987 (when (looking-at org-property-drawer-re)
23988 (goto-char (match-end 0))
23989 (forward-line))
23990 (when (and full (not (org-at-heading-p)))
23991 (catch 'exit
23992 (let ((end (save-excursion (outline-next-heading) (point)))
23993 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23994 (while (not (eobp))
23995 (cond ((looking-at-p org-drawer-regexp)
23996 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23997 (forward-line)
23998 (throw 'exit t)))
23999 ((looking-at-p re) (forward-line))
24000 (t (throw 'exit t))))))))
24002 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24003 "Move forward to the ARG'th subheading at same level as this one.
24004 Stop at the first and last subheadings of a superior heading.
24005 Normally this only looks at visible headings, but when INVISIBLE-OK is
24006 non-nil it will also look at invisible ones."
24007 (interactive "p")
24008 (let ((backward? (and arg (< arg 0))))
24009 (if (org-before-first-heading-p)
24010 (if backward? (goto-char (point-min)) (outline-next-heading))
24011 (org-back-to-heading invisible-ok)
24012 (unless backward? (end-of-line)) ;do not match current headline
24013 (let ((level (- (match-end 0) (match-beginning 0) 1))
24014 (f (if backward? #'re-search-backward #'re-search-forward))
24015 (count (if arg (abs arg) 1))
24016 (result (point)))
24017 (while (and (> count 0)
24018 (funcall f org-outline-regexp-bol nil 'move))
24019 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24020 (cond ((< l level) (setq count 0))
24021 ((and (= l level)
24022 (or invisible-ok
24023 (not (org-invisible-p
24024 (line-beginning-position)))))
24025 (cl-decf count)
24026 (when (= l level) (setq result (point)))))))
24027 (goto-char result))
24028 (beginning-of-line))))
24030 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24031 "Move backward to the ARG'th subheading at same level as this one.
24032 Stop at the first and last subheadings of a superior heading."
24033 (interactive "p")
24034 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24036 (defun org-next-visible-heading (arg)
24037 "Move to the next visible heading.
24039 This function wraps `outline-next-visible-heading' with
24040 `org-with-limited-levels' in order to skip over inline tasks and
24041 respect customization of `org-odd-levels-only'."
24042 (interactive "p")
24043 (org-with-limited-levels
24044 (outline-next-visible-heading arg)))
24046 (defun org-previous-visible-heading (arg)
24047 "Move to the previous visible heading.
24049 This function wraps `outline-previous-visible-heading' with
24050 `org-with-limited-levels' in order to skip over inline tasks and
24051 respect customization of `org-odd-levels-only'."
24052 (interactive "p")
24053 (org-with-limited-levels
24054 (outline-previous-visible-heading arg)))
24056 (defun org-next-block (arg &optional backward block-regexp)
24057 "Jump to the next block.
24059 With a prefix argument ARG, jump forward ARG many blocks.
24061 When BACKWARD is non-nil, jump to the previous block.
24063 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24064 Match data is set according to this regexp when the function
24065 returns.
24067 Return point at beginning of the opening line of found block.
24068 Throw an error if no block is found."
24069 (interactive "p")
24070 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24071 (case-fold-search t)
24072 (search-fn (if backward #'re-search-backward #'re-search-forward))
24073 (count (or arg 1))
24074 (origin (point))
24075 last-element)
24076 (if backward (beginning-of-line) (end-of-line))
24077 (while (and (> count 0) (funcall search-fn re nil t))
24078 (let ((element (save-excursion
24079 (goto-char (match-beginning 0))
24080 (save-match-data (org-element-at-point)))))
24081 (when (and (memq (org-element-type element)
24082 '(center-block comment-block dynamic-block
24083 example-block export-block quote-block
24084 special-block src-block verse-block))
24085 (<= (match-beginning 0)
24086 (org-element-property :post-affiliated element)))
24087 (setq last-element element)
24088 (cl-decf count))))
24089 (if (= count 0)
24090 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24091 (save-match-data (org-show-context)))
24092 (goto-char origin)
24093 (user-error "No %s code blocks" (if backward "previous" "further")))))
24095 (defun org-previous-block (arg &optional block-regexp)
24096 "Jump to the previous block.
24097 With a prefix argument ARG, jump backward ARG many source blocks.
24098 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24099 (interactive "p")
24100 (org-next-block arg t block-regexp))
24102 (defun org-forward-paragraph ()
24103 "Move forward to beginning of next paragraph or equivalent.
24105 The function moves point to the beginning of the next visible
24106 structural element, which can be a paragraph, a table, a list
24107 item, etc. It also provides some special moves for convenience:
24109 - On an affiliated keyword, jump to the beginning of the
24110 relative element.
24111 - On an item or a footnote definition, move to the second
24112 element inside, if any.
24113 - On a table or a property drawer, jump after it.
24114 - On a verse or source block, stop after blank lines."
24115 (interactive)
24116 (unless (eobp)
24117 (let* ((deactivate-mark nil)
24118 (element (org-element-at-point))
24119 (type (org-element-type element))
24120 (post-affiliated (org-element-property :post-affiliated element))
24121 (contents-begin (org-element-property :contents-begin element))
24122 (contents-end (org-element-property :contents-end element))
24123 (end (let ((end (org-element-property :end element)) (parent element))
24124 (while (and (setq parent (org-element-property :parent parent))
24125 (= (org-element-property :contents-end parent) end))
24126 (setq end (org-element-property :end parent)))
24127 end)))
24128 (cond ((not element)
24129 (skip-chars-forward " \r\t\n")
24130 (or (eobp) (beginning-of-line)))
24131 ;; On affiliated keywords, move to element's beginning.
24132 ((< (point) post-affiliated)
24133 (goto-char post-affiliated))
24134 ;; At a table row, move to the end of the table. Similarly,
24135 ;; at a node property, move to the end of the property
24136 ;; drawer.
24137 ((memq type '(node-property table-row))
24138 (goto-char (org-element-property
24139 :end (org-element-property :parent element))))
24140 ((memq type '(property-drawer table)) (goto-char end))
24141 ;; Consider blank lines as separators in verse and source
24142 ;; blocks to ease editing.
24143 ((memq type '(src-block verse-block))
24144 (when (eq type 'src-block)
24145 (setq contents-end
24146 (save-excursion (goto-char end)
24147 (skip-chars-backward " \r\t\n")
24148 (line-beginning-position))))
24149 (beginning-of-line)
24150 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24151 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24152 (goto-char end)
24153 (skip-chars-forward " \r\t\n")
24154 (if (= (point) contents-end) (goto-char end)
24155 (beginning-of-line))))
24156 ;; With no contents, just skip element.
24157 ((not contents-begin) (goto-char end))
24158 ;; If contents are invisible, skip the element altogether.
24159 ((org-invisible-p (line-end-position))
24160 (cl-case type
24161 (headline
24162 (org-with-limited-levels (outline-next-visible-heading 1)))
24163 ;; At a plain list, make sure we move to the next item
24164 ;; instead of skipping the whole list.
24165 (plain-list (forward-char)
24166 (org-forward-paragraph))
24167 (otherwise (goto-char end))))
24168 ((>= (point) contents-end) (goto-char end))
24169 ((>= (point) contents-begin)
24170 ;; This can only happen on paragraphs and plain lists.
24171 (cl-case type
24172 (paragraph (goto-char end))
24173 ;; At a plain list, try to move to second element in
24174 ;; first item, if possible.
24175 (plain-list (end-of-line)
24176 (org-forward-paragraph))))
24177 ;; When contents start on the middle of a line (e.g. in
24178 ;; items and footnote definitions), try to reach first
24179 ;; element starting after current line.
24180 ((> (line-end-position) contents-begin)
24181 (end-of-line)
24182 (org-forward-paragraph))
24183 (t (goto-char contents-begin))))))
24185 (defun org-backward-paragraph ()
24186 "Move backward to start of previous paragraph or equivalent.
24188 The function moves point to the beginning of the current
24189 structural element, which can be a paragraph, a table, a list
24190 item, etc., or to the beginning of the previous visible one if
24191 point is already there. It also provides some special moves for
24192 convenience:
24194 - On an affiliated keyword, jump to the first one.
24195 - On a table or a property drawer, move to its beginning.
24196 - On a verse or source block, stop before blank lines."
24197 (interactive)
24198 (unless (bobp)
24199 (let* ((deactivate-mark nil)
24200 (element (org-element-at-point))
24201 (type (org-element-type element))
24202 (contents-begin (org-element-property :contents-begin element))
24203 (contents-end (org-element-property :contents-end element))
24204 (post-affiliated (org-element-property :post-affiliated element))
24205 (begin (org-element-property :begin element)))
24206 (cond
24207 ((not element) (goto-char (point-min)))
24208 ((= (point) begin)
24209 (backward-char)
24210 (org-backward-paragraph))
24211 ((<= (point) post-affiliated) (goto-char begin))
24212 ((memq type '(node-property table-row))
24213 (goto-char (org-element-property
24214 :post-affiliated (org-element-property :parent element))))
24215 ((memq type '(property-drawer table)) (goto-char begin))
24216 ((memq type '(src-block verse-block))
24217 (when (eq type 'src-block)
24218 (setq contents-begin
24219 (save-excursion (goto-char begin) (forward-line) (point))))
24220 (if (= (point) contents-begin) (goto-char post-affiliated)
24221 ;; Inside a verse block, see blank lines as paragraph
24222 ;; separators.
24223 (let ((origin (point)))
24224 (skip-chars-backward " \r\t\n" contents-begin)
24225 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24226 (skip-chars-forward " \r\t\n" origin)
24227 (if (= (point) origin) (goto-char contents-begin)
24228 (beginning-of-line))))))
24229 ((not contents-begin) (goto-char (or post-affiliated begin)))
24230 ((eq type 'paragraph)
24231 (goto-char contents-begin)
24232 ;; When at first paragraph in an item or a footnote definition,
24233 ;; move directly to beginning of line.
24234 (let ((parent-contents
24235 (org-element-property
24236 :contents-begin (org-element-property :parent element))))
24237 (when (and parent-contents (= parent-contents contents-begin))
24238 (beginning-of-line))))
24239 ;; At the end of a greater element, move to the beginning of the
24240 ;; last element within.
24241 ((>= (point) contents-end)
24242 (goto-char (1- contents-end))
24243 (org-backward-paragraph))
24244 (t (goto-char (or post-affiliated begin))))
24245 ;; Ensure we never leave point invisible.
24246 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24248 (defun org-forward-element ()
24249 "Move forward by one element.
24250 Move to the next element at the same level, when possible."
24251 (interactive)
24252 (cond ((eobp) (user-error "Cannot move further down"))
24253 ((org-with-limited-levels (org-at-heading-p))
24254 (let ((origin (point)))
24255 (goto-char (org-end-of-subtree nil t))
24256 (unless (org-with-limited-levels (org-at-heading-p))
24257 (goto-char origin)
24258 (user-error "Cannot move further down"))))
24260 (let* ((elem (org-element-at-point))
24261 (end (org-element-property :end elem))
24262 (parent (org-element-property :parent elem)))
24263 (cond ((and parent (= (org-element-property :contents-end parent) end))
24264 (goto-char (org-element-property :end parent)))
24265 ((integer-or-marker-p end) (goto-char end))
24266 (t (message "No element at point")))))))
24268 (defun org-backward-element ()
24269 "Move backward by one element.
24270 Move to the previous element at the same level, when possible."
24271 (interactive)
24272 (cond ((bobp) (user-error "Cannot move further up"))
24273 ((org-with-limited-levels (org-at-heading-p))
24274 ;; At a headline, move to the previous one, if any, or stay
24275 ;; here.
24276 (let ((origin (point)))
24277 (org-with-limited-levels (org-backward-heading-same-level 1))
24278 ;; When current headline has no sibling above, move to its
24279 ;; parent.
24280 (when (= (point) origin)
24281 (or (org-with-limited-levels (org-up-heading-safe))
24282 (progn (goto-char origin)
24283 (user-error "Cannot move further up"))))))
24285 (let* ((elem (org-element-at-point))
24286 (beg (org-element-property :begin elem)))
24287 (cond
24288 ;; Move to beginning of current element if point isn't
24289 ;; there already.
24290 ((null beg) (message "No element at point"))
24291 ((/= (point) beg) (goto-char beg))
24292 (t (goto-char beg)
24293 (skip-chars-backward " \r\t\n")
24294 (unless (bobp)
24295 (let ((prev (org-element-at-point)))
24296 (goto-char (org-element-property :begin prev))
24297 (while (and (setq prev (org-element-property :parent prev))
24298 (<= (org-element-property :end prev) beg))
24299 (goto-char (org-element-property :begin prev)))))))))))
24301 (defun org-up-element ()
24302 "Move to upper element."
24303 (interactive)
24304 (if (org-with-limited-levels (org-at-heading-p))
24305 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24306 (let* ((elem (org-element-at-point))
24307 (parent (org-element-property :parent elem)))
24308 (if parent (goto-char (org-element-property :begin parent))
24309 (if (org-with-limited-levels (org-before-first-heading-p))
24310 (user-error "No surrounding element")
24311 (org-with-limited-levels (org-back-to-heading)))))))
24313 (defun org-down-element ()
24314 "Move to inner element."
24315 (interactive)
24316 (let ((element (org-element-at-point)))
24317 (cond
24318 ((memq (org-element-type element) '(plain-list table))
24319 (goto-char (org-element-property :contents-begin element))
24320 (forward-char))
24321 ((memq (org-element-type element) org-element-greater-elements)
24322 ;; If contents are hidden, first disclose them.
24323 (when (org-invisible-p (line-end-position)) (org-cycle))
24324 (goto-char (or (org-element-property :contents-begin element)
24325 (user-error "No content for this element"))))
24326 (t (user-error "No inner element")))))
24328 (defun org-drag-element-backward ()
24329 "Move backward element at point."
24330 (interactive)
24331 (let ((elem (or (org-element-at-point)
24332 (user-error "No element at point"))))
24333 (if (eq (org-element-type elem) 'headline)
24334 ;; Preserve point when moving a whole tree, even if point was
24335 ;; on blank lines below the headline.
24336 (let ((offset (skip-chars-backward " \t\n")))
24337 (unwind-protect (org-move-subtree-up)
24338 (forward-char (- offset))))
24339 (let ((prev-elem
24340 (save-excursion
24341 (goto-char (org-element-property :begin elem))
24342 (skip-chars-backward " \r\t\n")
24343 (unless (bobp)
24344 (let* ((beg (org-element-property :begin elem))
24345 (prev (org-element-at-point))
24346 (up prev))
24347 (while (and (setq up (org-element-property :parent up))
24348 (<= (org-element-property :end up) beg))
24349 (setq prev up))
24350 prev)))))
24351 ;; Error out if no previous element or previous element is
24352 ;; a parent of the current one.
24353 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24354 (user-error "Cannot drag element backward")
24355 (let ((pos (point)))
24356 (org-element-swap-A-B prev-elem elem)
24357 (goto-char (+ (org-element-property :begin prev-elem)
24358 (- pos (org-element-property :begin elem))))))))))
24360 (defun org-drag-element-forward ()
24361 "Move forward element at point."
24362 (interactive)
24363 (let* ((pos (point))
24364 (elem (or (org-element-at-point)
24365 (user-error "No element at point"))))
24366 (when (= (point-max) (org-element-property :end elem))
24367 (user-error "Cannot drag element forward"))
24368 (goto-char (org-element-property :end elem))
24369 (let ((next-elem (org-element-at-point)))
24370 (when (or (org-element-nested-p elem next-elem)
24371 (and (eq (org-element-type next-elem) 'headline)
24372 (not (eq (org-element-type elem) 'headline))))
24373 (goto-char pos)
24374 (user-error "Cannot drag element forward"))
24375 ;; Compute new position of point: it's shifted by NEXT-ELEM
24376 ;; body's length (without final blanks) and by the length of
24377 ;; blanks between ELEM and NEXT-ELEM.
24378 (let ((size-next (- (save-excursion
24379 (goto-char (org-element-property :end next-elem))
24380 (skip-chars-backward " \r\t\n")
24381 (forward-line)
24382 ;; Small correction if buffer doesn't end
24383 ;; with a newline character.
24384 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24385 (org-element-property :begin next-elem)))
24386 (size-blank (- (org-element-property :end elem)
24387 (save-excursion
24388 (goto-char (org-element-property :end elem))
24389 (skip-chars-backward " \r\t\n")
24390 (forward-line)
24391 (point)))))
24392 (org-element-swap-A-B elem next-elem)
24393 (goto-char (+ pos size-next size-blank))))))
24395 (defun org-drag-line-forward (arg)
24396 "Drag the line at point ARG lines forward."
24397 (interactive "p")
24398 (dotimes (_ (abs arg))
24399 (let ((c (current-column)))
24400 (if (< 0 arg)
24401 (progn
24402 (beginning-of-line 2)
24403 (transpose-lines 1)
24404 (beginning-of-line 0))
24405 (transpose-lines 1)
24406 (beginning-of-line -1))
24407 (org-move-to-column c))))
24409 (defun org-drag-line-backward (arg)
24410 "Drag the line at point ARG lines backward."
24411 (interactive "p")
24412 (org-drag-line-forward (- arg)))
24414 (defun org-mark-element ()
24415 "Put point at beginning of this element, mark at end.
24417 Interactively, if this command is repeated or (in Transient Mark
24418 mode) if the mark is active, it marks the next element after the
24419 ones already marked."
24420 (interactive)
24421 (let (deactivate-mark)
24422 (if (and (called-interactively-p 'any)
24423 (or (and (eq last-command this-command) (mark t))
24424 (and transient-mark-mode mark-active)))
24425 (set-mark
24426 (save-excursion
24427 (goto-char (mark))
24428 (goto-char (org-element-property :end (org-element-at-point)))))
24429 (let ((element (org-element-at-point)))
24430 (end-of-line)
24431 (push-mark (org-element-property :end element) t t)
24432 (goto-char (org-element-property :begin element))))))
24434 (defun org-narrow-to-element ()
24435 "Narrow buffer to current element."
24436 (interactive)
24437 (let ((elem (org-element-at-point)))
24438 (cond
24439 ((eq (car elem) 'headline)
24440 (narrow-to-region
24441 (org-element-property :begin elem)
24442 (org-element-property :end elem)))
24443 ((memq (car elem) org-element-greater-elements)
24444 (narrow-to-region
24445 (org-element-property :contents-begin elem)
24446 (org-element-property :contents-end elem)))
24448 (narrow-to-region
24449 (org-element-property :begin elem)
24450 (org-element-property :end elem))))))
24452 (defun org-transpose-element ()
24453 "Transpose current and previous elements, keeping blank lines between.
24454 Point is moved after both elements."
24455 (interactive)
24456 (org-skip-whitespace)
24457 (let ((end (org-element-property :end (org-element-at-point))))
24458 (org-drag-element-backward)
24459 (goto-char end)))
24461 (defun org-unindent-buffer ()
24462 "Un-indent the visible part of the buffer.
24463 Relative indentation (between items, inside blocks, etc.) isn't
24464 modified."
24465 (interactive)
24466 (unless (eq major-mode 'org-mode)
24467 (user-error "Cannot un-indent a buffer not in Org mode"))
24468 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24469 (unindent-tree
24470 (lambda (contents)
24471 (dolist (element (reverse contents))
24472 (if (memq (org-element-type element) '(headline section))
24473 (funcall unindent-tree (org-element-contents element))
24474 (save-excursion
24475 (save-restriction
24476 (narrow-to-region
24477 (org-element-property :begin element)
24478 (org-element-property :end element))
24479 (org-do-remove-indentation))))))))
24480 (funcall unindent-tree (org-element-contents parse-tree))))
24482 (defun org-show-children (&optional level)
24483 "Show all direct subheadings of this heading.
24484 Prefix arg LEVEL is how many levels below the current level
24485 should be shown. Default is enough to cause the following
24486 heading to appear."
24487 (interactive "p")
24488 ;; If `orgstruct-mode' is active, use the slower version.
24489 (if orgstruct-mode (call-interactively #'outline-show-children)
24490 (save-excursion
24491 (org-back-to-heading t)
24492 (let* ((current-level (funcall outline-level))
24493 (max-level (org-get-valid-level
24494 current-level
24495 (if level (prefix-numeric-value level) 1)))
24496 (end (save-excursion (org-end-of-subtree t t)))
24497 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24498 (past-first-child nil)
24499 ;; Make sure to skip inlinetasks.
24500 (re (format regexp-fmt
24501 current-level
24502 (cond
24503 ((not (featurep 'org-inlinetask)) "")
24504 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24506 (t (1- org-inlinetask-min-level))))))
24507 ;; Display parent heading.
24508 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24509 (forward-line)
24510 ;; Display children. First child may be deeper than expected
24511 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24512 ;; MAX-LEVEL accordingly.
24513 (while (re-search-forward re end t)
24514 (unless past-first-child
24515 (setq re (format regexp-fmt
24516 current-level
24517 (max (funcall outline-level) max-level)))
24518 (setq past-first-child t))
24519 (outline-flag-region
24520 (line-end-position 0) (line-end-position) nil))))))
24522 (defun org-show-subtree ()
24523 "Show everything after this heading at deeper levels."
24524 (interactive)
24525 (outline-flag-region
24526 (point)
24527 (save-excursion
24528 (org-end-of-subtree t t))
24529 nil))
24531 (defun org-show-entry ()
24532 "Show the body directly following this heading.
24533 Show the heading too, if it is currently invisible."
24534 (interactive)
24535 (save-excursion
24536 (ignore-errors
24537 (org-back-to-heading t)
24538 (outline-flag-region
24539 (max (point-min) (1- (point)))
24540 (save-excursion
24541 (if (re-search-forward
24542 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24543 (match-beginning 1)
24544 (point-max)))
24545 nil)
24546 (org-cycle-hide-drawers 'children))))
24548 (defun org-make-options-regexp (kwds &optional extra)
24549 "Make a regular expression for keyword lines.
24550 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24551 when non-nil, is a regexp matching keywords names."
24552 (concat "^[ \t]*#\\+\\("
24553 (regexp-opt kwds)
24554 (and extra (concat (and kwds "\\|") extra))
24555 "\\):[ \t]*\\(.*\\)"))
24557 ;;;; Integration with and fixes for other packages
24559 ;;; Imenu support
24561 (defvar-local org-imenu-markers nil
24562 "All markers currently used by Imenu.")
24564 (defun org-imenu-new-marker (&optional pos)
24565 "Return a new marker for use by Imenu, and remember the marker."
24566 (let ((m (make-marker)))
24567 (move-marker m (or pos (point)))
24568 (push m org-imenu-markers)
24571 (defun org-imenu-get-tree ()
24572 "Produce the index for Imenu."
24573 (dolist (x org-imenu-markers) (move-marker x nil))
24574 (setq org-imenu-markers nil)
24575 (let* ((case-fold-search nil)
24576 (n org-imenu-depth)
24577 (re (concat "^" (org-get-limited-outline-regexp)))
24578 (subs (make-vector (1+ n) nil))
24579 (last-level 0)
24580 m level head0 head)
24581 (org-with-wide-buffer
24582 (goto-char (point-max))
24583 (while (re-search-backward re nil t)
24584 (setq level (org-reduced-level (funcall outline-level)))
24585 (when (and (<= level n)
24586 (looking-at org-complex-heading-regexp)
24587 (setq head0 (match-string-no-properties 4)))
24588 (setq head (org-link-display-format head0)
24589 m (org-imenu-new-marker))
24590 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24591 (if (>= level last-level)
24592 (push (cons head m) (aref subs level))
24593 (push (cons head (aref subs (1+ level))) (aref subs level))
24594 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24595 (setq last-level level))))
24596 (aref subs 1)))
24598 (eval-after-load "imenu"
24599 '(progn
24600 (add-hook 'imenu-after-jump-hook
24601 (lambda ()
24602 (when (derived-mode-p 'org-mode)
24603 (org-show-context 'org-goto))))))
24605 (defun org-link-display-format (s)
24606 "Replace links in string S with their description.
24607 If there is no description, use the link target."
24608 (save-match-data
24609 (replace-regexp-in-string
24610 org-bracket-link-analytic-regexp
24611 (lambda (m)
24612 (if (match-end 5) (match-string 5 m)
24613 (concat (match-string 1 m) (match-string 3 m))))
24614 s nil t)))
24616 (defun org-toggle-link-display ()
24617 "Toggle the literal or descriptive display of links."
24618 (interactive)
24619 (if org-descriptive-links
24620 (progn (org-remove-from-invisibility-spec '(org-link))
24621 (org-restart-font-lock)
24622 (setq org-descriptive-links nil))
24623 (progn (add-to-invisibility-spec '(org-link))
24624 (org-restart-font-lock)
24625 (setq org-descriptive-links t))))
24627 ;; Speedbar support
24629 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24630 "Overlay marking the agenda restriction line in speedbar.")
24631 (overlay-put org-speedbar-restriction-lock-overlay
24632 'face 'org-agenda-restriction-lock)
24633 (overlay-put org-speedbar-restriction-lock-overlay
24634 'help-echo "Agendas are currently limited to this item.")
24635 (delete-overlay org-speedbar-restriction-lock-overlay)
24637 (defun org-speedbar-set-agenda-restriction ()
24638 "Restrict future agenda commands to the location at point in speedbar.
24639 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24640 (interactive)
24641 (require 'org-agenda)
24642 (let (p m tp np dir txt)
24643 (cond
24644 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24645 'org-imenu t))
24646 (setq m (get-text-property p 'org-imenu-marker))
24647 (with-current-buffer (marker-buffer m)
24648 (goto-char m)
24649 (org-agenda-set-restriction-lock 'subtree)))
24650 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24651 'speedbar-function 'speedbar-find-file))
24652 (setq tp (previous-single-property-change
24653 (1+ p) 'speedbar-function)
24654 np (next-single-property-change
24655 tp 'speedbar-function)
24656 dir (speedbar-line-directory)
24657 txt (buffer-substring-no-properties (or tp (point-min))
24658 (or np (point-max))))
24659 (with-current-buffer (find-file-noselect
24660 (let ((default-directory dir))
24661 (expand-file-name txt)))
24662 (unless (derived-mode-p 'org-mode)
24663 (user-error "Cannot restrict to non-Org mode file"))
24664 (org-agenda-set-restriction-lock 'file)))
24665 (t (user-error "Don't know how to restrict Org mode agenda")))
24666 (move-overlay org-speedbar-restriction-lock-overlay
24667 (point-at-bol) (point-at-eol))
24668 (setq current-prefix-arg nil)
24669 (org-agenda-maybe-redo)))
24671 (defvar speedbar-file-key-map)
24672 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24673 (eval-after-load "speedbar"
24674 '(progn
24675 (speedbar-add-supported-extension ".org")
24676 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24677 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24678 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24679 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24680 (add-hook 'speedbar-visiting-tag-hook
24681 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24683 ;;; Fixes and Hacks for problems with other packages
24685 (defun org--flyspell-object-check-p (element)
24686 "Non-nil when Flyspell can check object at point.
24687 ELEMENT is the element at point."
24688 (let ((object (save-excursion
24689 (when (looking-at-p "\\>") (backward-char))
24690 (org-element-context element))))
24691 (cl-case (org-element-type object)
24692 ;; Prevent checks in links due to keybinding conflict with
24693 ;; Flyspell.
24694 ((code entity export-snippet inline-babel-call
24695 inline-src-block line-break latex-fragment link macro
24696 statistics-cookie target timestamp verbatim)
24697 nil)
24698 (footnote-reference
24699 ;; Only in inline footnotes, within the definition.
24700 (and (eq (org-element-property :type object) 'inline)
24701 (< (save-excursion
24702 (goto-char (org-element-property :begin object))
24703 (search-forward ":" nil t 2))
24704 (point))))
24705 (otherwise t))))
24707 (defun org-mode-flyspell-verify ()
24708 "Function used for `flyspell-generic-check-word-predicate'."
24709 (if (org-at-heading-p)
24710 ;; At a headline or an inlinetask, check title only. This is
24711 ;; faster than relying on `org-element-at-point'.
24712 (and (save-excursion (beginning-of-line)
24713 (and (let ((case-fold-search t))
24714 (not (looking-at-p "\\*+ END[ \t]*$")))
24715 (let ((case-fold-search nil))
24716 (looking-at org-complex-heading-regexp))))
24717 (match-beginning 4)
24718 (>= (point) (match-beginning 4))
24719 (or (not (match-beginning 5))
24720 (< (point) (match-beginning 5))))
24721 (let* ((element (org-element-at-point))
24722 (post-affiliated (org-element-property :post-affiliated element)))
24723 (cond
24724 ;; Ignore checks in all affiliated keywords but captions.
24725 ((< (point) post-affiliated)
24726 (and (save-excursion
24727 (beginning-of-line)
24728 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24729 (> (point) (match-end 0))
24730 (org--flyspell-object-check-p element)))
24731 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24732 ((let ((log (org-log-into-drawer)))
24733 (and log
24734 (let ((drawer (org-element-lineage element '(drawer))))
24735 (and drawer
24736 (eq (compare-strings
24737 log nil nil
24738 (org-element-property :drawer-name drawer) nil nil t)
24739 t)))))
24740 nil)
24742 (cl-case (org-element-type element)
24743 ((comment quote-section) t)
24744 (comment-block
24745 ;; Allow checks between block markers, not on them.
24746 (and (> (line-beginning-position) post-affiliated)
24747 (save-excursion
24748 (end-of-line)
24749 (skip-chars-forward " \r\t\n")
24750 (< (point) (org-element-property :end element)))))
24751 ;; Arbitrary list of keywords where checks are meaningful.
24752 ;; Make sure point is on the value part of the element.
24753 (keyword
24754 (and (member (org-element-property :key element)
24755 '("DESCRIPTION" "TITLE"))
24756 (save-excursion
24757 (search-backward ":" (line-beginning-position) t))))
24758 ;; Check is globally allowed in paragraphs verse blocks and
24759 ;; table rows (after affiliated keywords) but some objects
24760 ;; must not be affected.
24761 ((paragraph table-row verse-block)
24762 (let ((cbeg (org-element-property :contents-begin element))
24763 (cend (org-element-property :contents-end element)))
24764 (and cbeg (>= (point) cbeg) (< (point) cend)
24765 (org--flyspell-object-check-p element))))))))))
24766 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24768 (defun org-remove-flyspell-overlays-in (beg end)
24769 "Remove flyspell overlays in region."
24770 (and (bound-and-true-p flyspell-mode)
24771 (fboundp 'flyspell-delete-region-overlays)
24772 (flyspell-delete-region-overlays beg end)))
24774 (defvar flyspell-delayed-commands)
24775 (eval-after-load "flyspell"
24776 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24778 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24779 (eval-after-load "bookmark"
24780 '(if (boundp 'bookmark-after-jump-hook)
24781 ;; We can use the hook
24782 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24783 ;; Hook not available, use advice
24784 (defadvice bookmark-jump (after org-make-visible activate)
24785 "Make the position visible."
24786 (org-bookmark-jump-unhide))))
24788 ;; Make sure saveplace shows the location if it was hidden
24789 (eval-after-load "saveplace"
24790 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24791 "Make the position visible."
24792 (org-bookmark-jump-unhide)))
24794 ;; Make sure ecb shows the location if it was hidden
24795 (eval-after-load "ecb"
24796 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24797 "Make hierarchy visible when jumping into location from ECB tree buffer."
24798 (when (derived-mode-p 'org-mode)
24799 (org-show-context))))
24801 (defun org-bookmark-jump-unhide ()
24802 "Unhide the current position, to show the bookmark location."
24803 (and (derived-mode-p 'org-mode)
24804 (or (org-invisible-p)
24805 (save-excursion (goto-char (max (point-min) (1- (point))))
24806 (org-invisible-p)))
24807 (org-show-context 'bookmark-jump)))
24809 (defun org-mark-jump-unhide ()
24810 "Make the point visible with `org-show-context' after jumping to the mark."
24811 (when (and (derived-mode-p 'org-mode)
24812 (org-invisible-p))
24813 (org-show-context 'mark-goto)))
24815 (eval-after-load "simple"
24816 '(defadvice pop-to-mark-command (after org-make-visible activate)
24817 "Make the point visible with `org-show-context'."
24818 (org-mark-jump-unhide)))
24820 (eval-after-load "simple"
24821 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24822 "Make the point visible with `org-show-context'."
24823 (org-mark-jump-unhide)))
24825 (eval-after-load "simple"
24826 '(defadvice pop-global-mark (after org-make-visible activate)
24827 "Make the point visible with `org-show-context'."
24828 (org-mark-jump-unhide)))
24830 ;; Make session.el ignore our circular variable
24831 (defvar session-globals-exclude)
24832 (eval-after-load "session"
24833 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24835 ;;;; Finish up
24837 (provide 'org)
24839 (run-hooks 'org-load-hook)
24841 ;;; org.el ends here