org-table: Obey <c> cookie when aligning a table
[org-mode.git] / lisp / org.el
bloba644a572a91f3cb7f88aabf9d1ac36c8b50b5158
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 can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: align
1034 #+STARTUP: noalign"
1035 :group 'org-startup
1036 :type 'boolean)
1038 (defcustom org-startup-shrink-all-tables nil
1039 "Non-nil means shrink all table columns with a width cookie.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: shrink"
1043 :group 'org-startup
1044 :type 'boolean
1045 :version "26.1"
1046 :package-version '(Org . "9.1")
1047 :safe #'booleanp)
1049 (defcustom org-startup-with-inline-images nil
1050 "Non-nil means show inline images when loading a new Org file.
1051 This can also be configured on a per-file basis by adding one of
1052 the following lines anywhere in the buffer:
1053 #+STARTUP: inlineimages
1054 #+STARTUP: noinlineimages"
1055 :group 'org-startup
1056 :version "24.1"
1057 :type 'boolean)
1059 (defcustom org-startup-with-latex-preview nil
1060 "Non-nil means preview LaTeX fragments when loading a new Org file.
1062 This can also be configured on a per-file basis by adding one of
1063 the following lines anywhere in the buffer:
1064 #+STARTUP: latexpreview
1065 #+STARTUP: nolatexpreview"
1066 :group 'org-startup
1067 :version "24.4"
1068 :package-version '(Org . "8.0")
1069 :type 'boolean)
1071 (defcustom org-insert-mode-line-in-empty-file nil
1072 "Non-nil means insert the first line setting Org mode in empty files.
1073 When the function `org-mode' is called interactively in an empty file, this
1074 normally means that the file name does not automatically trigger Org mode.
1075 To ensure that the file will always be in Org mode in the future, a
1076 line enforcing Org mode will be inserted into the buffer, if this option
1077 has been set."
1078 :group 'org-startup
1079 :type 'boolean)
1081 (defcustom org-replace-disputed-keys nil
1082 "Non-nil means use alternative key bindings for some keys.
1083 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1084 These keys are also used by other packages like shift-selection-mode'
1085 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1086 If you want to use Org mode together with one of these other modes,
1087 or more generally if you would like to move some Org mode commands to
1088 other keys, set this variable and configure the keys with the variable
1089 `org-disputed-keys'.
1091 This option is only relevant at load-time of Org mode, and must be set
1092 *before* org.el is loaded. Changing it requires a restart of Emacs to
1093 become effective."
1094 :group 'org-startup
1095 :type 'boolean)
1097 (defcustom org-use-extra-keys nil
1098 "Non-nil means use extra key sequence definitions for certain commands.
1099 This happens automatically if `window-system' is nil. This
1100 variable lets you do the same manually. You must set it before
1101 loading Org."
1102 :group 'org-startup
1103 :type 'boolean)
1105 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1107 (defcustom org-disputed-keys
1108 '(([(shift up)] . [(meta p)])
1109 ([(shift down)] . [(meta n)])
1110 ([(shift left)] . [(meta -)])
1111 ([(shift right)] . [(meta +)])
1112 ([(control shift right)] . [(meta shift +)])
1113 ([(control shift left)] . [(meta shift -)]))
1114 "Keys for which Org mode and other modes compete.
1115 This is an alist, cars are the default keys, second element specifies
1116 the alternative to use when `org-replace-disputed-keys' is t.
1118 Keys can be specified in any syntax supported by `define-key'.
1119 The value of this option takes effect only at Org mode startup,
1120 therefore you'll have to restart Emacs to apply it after changing."
1121 :group 'org-startup
1122 :type 'alist)
1124 (defun org-key (key)
1125 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1126 Or return the original if not disputed."
1127 (when org-replace-disputed-keys
1128 (let* ((nkey (key-description key))
1129 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1130 org-disputed-keys)))
1131 (setq key (if x (cdr x) key))))
1132 key)
1134 (defun org-defkey (keymap key def)
1135 "Define a key, possibly translated, as returned by `org-key'."
1136 (define-key keymap (org-key key) def))
1138 (defcustom org-ellipsis nil
1139 "The ellipsis to use in the Org mode outline.
1141 When nil, just use the standard three dots. When a non-empty string,
1142 use that string instead.
1144 The change affects only Org mode (which will then use its own display table).
1145 Changing this requires executing `\\[org-mode]' in a buffer to become
1146 effective."
1147 :group 'org-startup
1148 :type '(choice (const :tag "Default" nil)
1149 (string :tag "String" :value "...#"))
1150 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1152 (defvar org-display-table nil
1153 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1155 (defgroup org-keywords nil
1156 "Keywords in Org mode."
1157 :tag "Org Keywords"
1158 :group 'org)
1160 (defcustom org-closed-keep-when-no-todo nil
1161 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1162 :group 'org-todo
1163 :group 'org-keywords
1164 :version "24.4"
1165 :package-version '(Org . "8.0")
1166 :type 'boolean)
1168 (defgroup org-structure nil
1169 "Options concerning the general structure of Org files."
1170 :tag "Org Structure"
1171 :group 'org)
1173 (defgroup org-reveal-location nil
1174 "Options about how to make context of a location visible."
1175 :tag "Org Reveal Location"
1176 :group 'org-structure)
1178 (defcustom org-show-context-detail '((agenda . local)
1179 (bookmark-jump . lineage)
1180 (isearch . lineage)
1181 (default . ancestors))
1182 "Alist between context and visibility span when revealing a location.
1184 \\<org-mode-map>Some actions may move point into invisible
1185 locations. As a consequence, Org always expose a neighborhood
1186 around point. How much is shown depends on the initial action,
1187 or context. Valid contexts are
1189 agenda when exposing an entry from the agenda
1190 org-goto when using the command `org-goto' (`\\[org-goto]')
1191 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1192 tags-tree when constructing a sparse tree based on tags matches
1193 link-search when exposing search matches associated with a link
1194 mark-goto when exposing the jump goal of a mark
1195 bookmark-jump when exposing a bookmark location
1196 isearch when exiting from an incremental search
1197 default default for all contexts not set explicitly
1199 Allowed visibility spans are
1201 minimal show current headline; if point is not on headline,
1202 also show entry
1204 local show current headline, entry and next headline
1206 ancestors show current headline and its direct ancestors; if
1207 point is not on headline, also show entry
1209 lineage show current headline, its direct ancestors and all
1210 their children; if point is not on headline, also show
1211 entry and first child
1213 tree show current headline, its direct ancestors and all
1214 their children; if point is not on headline, also show
1215 entry and all children
1217 canonical show current headline, its direct ancestors along with
1218 their entries and children; if point is not located on
1219 the headline, also show current entry and all children
1221 As special cases, a nil or t value means show all contexts in
1222 `minimal' or `canonical' view, respectively.
1224 Some views can make displayed information very compact, but also
1225 make it harder to edit the location of the match. In such
1226 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1227 more context."
1228 :group 'org-reveal-location
1229 :version "26.1"
1230 :package-version '(Org . "9.0")
1231 :type '(choice
1232 (const :tag "Canonical" t)
1233 (const :tag "Minimal" nil)
1234 (repeat :greedy t :tag "Individual contexts"
1235 (cons
1236 (choice :tag "Context"
1237 (const agenda)
1238 (const org-goto)
1239 (const occur-tree)
1240 (const tags-tree)
1241 (const link-search)
1242 (const mark-goto)
1243 (const bookmark-jump)
1244 (const isearch)
1245 (const default))
1246 (choice :tag "Detail level"
1247 (const minimal)
1248 (const local)
1249 (const ancestors)
1250 (const lineage)
1251 (const tree)
1252 (const canonical))))))
1254 (defcustom org-indirect-buffer-display 'other-window
1255 "How should indirect tree buffers be displayed?
1257 This applies to indirect buffers created with the commands
1258 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1260 Valid values are:
1261 current-window Display in the current window
1262 other-window Just display in another window.
1263 dedicated-frame Create one new frame, and re-use it each time.
1264 new-frame Make a new frame each time. Note that in this case
1265 previously-made indirect buffers are kept, and you need to
1266 kill these buffers yourself."
1267 :group 'org-structure
1268 :group 'org-agenda-windows
1269 :type '(choice
1270 (const :tag "In current window" current-window)
1271 (const :tag "In current frame, other window" other-window)
1272 (const :tag "Each time a new frame" new-frame)
1273 (const :tag "One dedicated frame" dedicated-frame)))
1275 (defcustom org-use-speed-commands nil
1276 "Non-nil means activate single letter commands at beginning of a headline.
1277 This may also be a function to test for appropriate locations where speed
1278 commands should be active.
1280 For example, to activate speed commands when the point is on any
1281 star at the beginning of the headline, you can do this:
1283 (setq org-use-speed-commands
1284 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1285 :group 'org-structure
1286 :type '(choice
1287 (const :tag "Never" nil)
1288 (const :tag "At beginning of headline stars" t)
1289 (function)))
1291 (defcustom org-speed-commands-user nil
1292 "Alist of additional speed commands.
1293 This list will be checked before `org-speed-commands-default'
1294 when the variable `org-use-speed-commands' is non-nil
1295 and when the cursor is at the beginning of a headline.
1296 The car if each entry is a string with a single letter, which must
1297 be assigned to `self-insert-command' in the global map.
1298 The cdr is either a command to be called interactively, a function
1299 to be called, or a form to be evaluated.
1300 An entry that is just a list with a single string will be interpreted
1301 as a descriptive headline that will be added when listing the speed
1302 commands in the Help buffer using the `?' speed command."
1303 :group 'org-structure
1304 :type '(repeat :value ("k" . ignore)
1305 (choice :value ("k" . ignore)
1306 (list :tag "Descriptive Headline" (string :tag "Headline"))
1307 (cons :tag "Letter and Command"
1308 (string :tag "Command letter")
1309 (choice
1310 (function)
1311 (sexp))))))
1313 (defcustom org-bookmark-names-plist
1314 '(:last-capture "org-capture-last-stored"
1315 :last-refile "org-refile-last-stored"
1316 :last-capture-marker "org-capture-last-stored-marker")
1317 "Names for bookmarks automatically set by some Org commands.
1318 This can provide strings as names for a number of bookmarks Org sets
1319 automatically. The following keys are currently implemented:
1320 :last-capture
1321 :last-capture-marker
1322 :last-refile
1323 When a key does not show up in the property list, the corresponding bookmark
1324 is not set."
1325 :group 'org-structure
1326 :type 'plist)
1328 (defgroup org-cycle nil
1329 "Options concerning visibility cycling in Org mode."
1330 :tag "Org Cycle"
1331 :group 'org-structure)
1333 (defcustom org-cycle-skip-children-state-if-no-children t
1334 "Non-nil means skip CHILDREN state in entries that don't have any."
1335 :group 'org-cycle
1336 :type 'boolean)
1338 (defcustom org-cycle-max-level nil
1339 "Maximum level which should still be subject to visibility cycling.
1340 Levels higher than this will, for cycling, be treated as text, not a headline.
1341 When `org-odd-levels-only' is set, a value of N in this variable actually
1342 means 2N-1 stars as the limiting headline.
1343 When nil, cycle all levels.
1344 Note that the limiting level of cycling is also influenced by
1345 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1346 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1347 than its value."
1348 :group 'org-cycle
1349 :type '(choice
1350 (const :tag "No limit" nil)
1351 (integer :tag "Maximum level")))
1353 (defcustom org-hide-block-startup nil
1354 "Non-nil means entering Org mode will fold all blocks.
1355 This can also be set in on a per-file basis with
1357 #+STARTUP: hideblocks
1358 #+STARTUP: showblocks"
1359 :group 'org-startup
1360 :group 'org-cycle
1361 :type 'boolean)
1363 (defcustom org-cycle-global-at-bob nil
1364 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1366 This makes it possible to do global cycling without having to use `S-TAB'
1367 or `\\[universal-argument] TAB'. For this special case to work, the first \
1368 line of the buffer
1369 must not be a headline -- it may be empty or some other text.
1371 When used in this way, `org-cycle-hook' is disabled temporarily to make
1372 sure the cursor stays at the beginning of the buffer.
1374 When this option is nil, don't do anything special at the beginning of
1375 the buffer."
1376 :group 'org-cycle
1377 :type 'boolean)
1379 (defcustom org-cycle-level-after-item/entry-creation t
1380 "Non-nil means cycle entry level or item indentation in new empty entries.
1382 When the cursor is at the end of an empty headline, i.e., with only stars
1383 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1384 and then all possible ancestor states, before returning to the original state.
1385 This makes data entry extremely fast: M-RET to create a new headline,
1386 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1388 When the cursor is at the end of an empty plain list item, one TAB will
1389 make it a subitem, two or more tabs will back up to make this an item
1390 higher up in the item hierarchy."
1391 :group 'org-cycle
1392 :type 'boolean)
1394 (defcustom org-cycle-emulate-tab t
1395 "Where should `org-cycle' emulate TAB.
1396 nil Never
1397 white Only in completely white lines
1398 whitestart Only at the beginning of lines, before the first non-white char
1399 t Everywhere except in headlines
1400 exc-hl-bol Everywhere except at the start of a headline
1401 If TAB is used in a place where it does not emulate TAB, the current subtree
1402 visibility is cycled."
1403 :group 'org-cycle
1404 :type '(choice (const :tag "Never" nil)
1405 (const :tag "Only in completely white lines" white)
1406 (const :tag "Before first char in a line" whitestart)
1407 (const :tag "Everywhere except in headlines" t)
1408 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1410 (defcustom org-cycle-separator-lines 2
1411 "Number of empty lines needed to keep an empty line between collapsed trees.
1412 If you leave an empty line between the end of a subtree and the following
1413 headline, this empty line is hidden when the subtree is folded.
1414 Org mode will leave (exactly) one empty line visible if the number of
1415 empty lines is equal or larger to the number given in this variable.
1416 So the default 2 means at least 2 empty lines after the end of a subtree
1417 are needed to produce free space between a collapsed subtree and the
1418 following headline.
1420 If the number is negative, and the number of empty lines is at least -N,
1421 all empty lines are shown.
1423 Special case: when 0, never leave empty lines in collapsed view."
1424 :group 'org-cycle
1425 :type 'integer)
1426 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1428 (defcustom org-pre-cycle-hook nil
1429 "Hook that is run before visibility cycling is happening.
1430 The function(s) in this hook must accept a single argument which indicates
1431 the new state that will be set right after running this hook. The
1432 argument is a symbol. Before a global state change, it can have the values
1433 `overview', `content', or `all'. Before a local state change, it can have
1434 the values `folded', `children', or `subtree'."
1435 :group 'org-cycle
1436 :type 'hook)
1438 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1439 org-cycle-hide-drawers
1440 org-cycle-show-empty-lines
1441 org-optimize-window-after-visibility-change)
1442 "Hook that is run after `org-cycle' has changed the buffer visibility.
1443 The function(s) in this hook must accept a single argument which indicates
1444 the new state that was set by the most recent `org-cycle' command. The
1445 argument is a symbol. After a global state change, it can have the values
1446 `overview', `contents', or `all'. After a local state change, it can have
1447 the values `folded', `children', or `subtree'."
1448 :group 'org-cycle
1449 :type 'hook
1450 :version "26.1"
1451 :package-version '(Org . "8.3"))
1453 (defgroup org-edit-structure nil
1454 "Options concerning structure editing in Org mode."
1455 :tag "Org Edit Structure"
1456 :group 'org-structure)
1458 (defcustom org-odd-levels-only nil
1459 "Non-nil means skip even levels and only use odd levels for the outline.
1460 This has the effect that two stars are being added/taken away in
1461 promotion/demotion commands. It also influences how levels are
1462 handled by the exporters.
1463 Changing it requires restart of `font-lock-mode' to become effective
1464 for fontification also in regions already fontified.
1465 You may also set this on a per-file basis by adding one of the following
1466 lines to the buffer:
1468 #+STARTUP: odd
1469 #+STARTUP: oddeven"
1470 :group 'org-edit-structure
1471 :group 'org-appearance
1472 :type 'boolean)
1474 (defcustom org-adapt-indentation t
1475 "Non-nil means adapt indentation to outline node level.
1477 When this variable is set, Org assumes that you write outlines by
1478 indenting text in each node to align with the headline (after the
1479 stars). The following issues are influenced by this variable:
1481 - The indentation is increased by one space in a demotion
1482 command, and decreased by one in a promotion command. However,
1483 in the latter case, if shifting some line in the entry body
1484 would alter document structure (e.g., insert a new headline),
1485 indentation is not changed at all.
1487 - Property drawers and planning information is inserted indented
1488 when this variable is set. When nil, they will not be indented.
1490 - TAB indents a line relative to current level. The lines below
1491 a headline will be indented when this variable is set.
1493 Note that this is all about true indentation, by adding and
1494 removing space characters. See also `org-indent.el' which does
1495 level-dependent indentation in a virtual way, i.e. at display
1496 time in Emacs."
1497 :group 'org-edit-structure
1498 :type 'boolean)
1500 (defcustom org-special-ctrl-a/e nil
1501 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1503 When t, `C-a' will bring back the cursor to the beginning of the
1504 headline text, i.e. after the stars and after a possible TODO
1505 keyword. In an item, this will be the position after bullet and
1506 check-box, if any. When the cursor is already at that position,
1507 another `C-a' will bring it to the beginning of the line.
1509 `C-e' will jump to the end of the headline, ignoring the presence
1510 of tags in the headline. A second `C-e' will then jump to the
1511 true end of the line, after any tags. This also means that, when
1512 this variable is non-nil, `C-e' also will never jump beyond the
1513 end of the heading of a folded section, i.e. not after the
1514 ellipses.
1516 When set to the symbol `reversed', the first `C-a' or `C-e' works
1517 normally, going to the true line boundary first. Only a directly
1518 following, identical keypress will bring the cursor to the
1519 special positions.
1521 This may also be a cons cell where the behavior for `C-a' and
1522 `C-e' is set separately."
1523 :group 'org-edit-structure
1524 :type '(choice
1525 (const :tag "off" nil)
1526 (const :tag "on: after stars/bullet and before tags first" t)
1527 (const :tag "reversed: true line boundary first" reversed)
1528 (cons :tag "Set C-a and C-e separately"
1529 (choice :tag "Special C-a"
1530 (const :tag "off" nil)
1531 (const :tag "on: after stars/bullet first" t)
1532 (const :tag "reversed: before stars/bullet first" reversed))
1533 (choice :tag "Special C-e"
1534 (const :tag "off" nil)
1535 (const :tag "on: before tags first" t)
1536 (const :tag "reversed: after tags first" reversed)))))
1537 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1539 (defcustom org-special-ctrl-k nil
1540 "Non-nil means `C-k' will behave specially in headlines.
1541 When nil, `C-k' will call the default `kill-line' command.
1542 When t, the following will happen while the cursor is in the headline:
1544 - When the cursor is at the beginning of a headline, kill the entire
1545 line and possible the folded subtree below the line.
1546 - When in the middle of the headline text, kill the headline up to the tags.
1547 - When after the headline text, kill the tags."
1548 :group 'org-edit-structure
1549 :type 'boolean)
1551 (defcustom org-ctrl-k-protect-subtree nil
1552 "Non-nil means, do not delete a hidden subtree with C-k.
1553 When set to the symbol `error', simply throw an error when C-k is
1554 used to kill (part-of) a headline that has hidden text behind it.
1555 Any other non-nil value will result in a query to the user, if it is
1556 OK to kill that hidden subtree. When nil, kill without remorse."
1557 :group 'org-edit-structure
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Do not protect hidden subtrees" nil)
1561 (const :tag "Protect hidden subtrees with a security query" t)
1562 (const :tag "Never kill a hidden subtree with C-k" error)))
1564 (defcustom org-special-ctrl-o t
1565 "Non-nil means, make `C-o' insert a row in tables."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-catch-invisible-edits nil
1570 "Check if in invisible region before inserting or deleting a character.
1571 Valid values are:
1573 nil Do not check, so just do invisible edits.
1574 error Throw an error and do nothing.
1575 show Make point visible, and do the requested edit.
1576 show-and-error Make point visible, then throw an error and abort the edit.
1577 smart Make point visible, and do insertion/deletion if it is
1578 adjacent to visible text and the change feels predictable.
1579 Never delete a previously invisible character or add in the
1580 middle or right after an invisible region. Basically, this
1581 allows insertion and backward-delete right before ellipses.
1582 FIXME: maybe in this case we should not even show?"
1583 :group 'org-edit-structure
1584 :version "24.1"
1585 :type '(choice
1586 (const :tag "Do not check" nil)
1587 (const :tag "Throw error when trying to edit" error)
1588 (const :tag "Unhide, but do not do the edit" show-and-error)
1589 (const :tag "Show invisible part and do the edit" show)
1590 (const :tag "Be smart and do the right thing" smart)))
1592 (defcustom org-yank-folded-subtrees t
1593 "Non-nil means when yanking subtrees, fold them.
1594 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1595 it starts with a heading and all other headings in it are either children
1596 or siblings, then fold all the subtrees. However, do this only if no
1597 text after the yank would be swallowed into a folded tree by this action."
1598 :group 'org-edit-structure
1599 :type 'boolean)
1601 (defcustom org-yank-adjusted-subtrees nil
1602 "Non-nil means when yanking subtrees, adjust the level.
1603 With this setting, `org-paste-subtree' is used to insert the subtree, see
1604 this function for details."
1605 :group 'org-edit-structure
1606 :type 'boolean)
1608 (defcustom org-M-RET-may-split-line '((default . t))
1609 "Non-nil means M-RET will split the line at the cursor position.
1610 When nil, it will go to the end of the line before making a
1611 new line.
1612 You may also set this option in a different way for different
1613 contexts. Valid contexts are:
1615 headline when creating a new headline
1616 item when creating a new item
1617 table in a table field
1618 default the value to be used for all contexts not explicitly
1619 customized"
1620 :group 'org-structure
1621 :group 'org-table
1622 :type '(choice
1623 (const :tag "Always" t)
1624 (const :tag "Never" nil)
1625 (repeat :greedy t :tag "Individual contexts"
1626 (cons
1627 (choice :tag "Context"
1628 (const headline)
1629 (const item)
1630 (const table)
1631 (const default))
1632 (boolean)))))
1635 (defcustom org-insert-heading-respect-content nil
1636 "Non-nil means insert new headings after the current subtree.
1637 \\<org-mode-map>
1638 When nil, the new heading is created directly after the current line.
1639 The commands `\\[org-insert-heading-respect-content]' and \
1640 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1641 for the duration of the command."
1642 :group 'org-structure
1643 :type 'boolean)
1645 (defcustom org-blank-before-new-entry '((heading . auto)
1646 (plain-list-item . auto))
1647 "Should `org-insert-heading' leave a blank line before new heading/item?
1648 The value is an alist, with `heading' and `plain-list-item' as CAR,
1649 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1650 which case Org will look at the surrounding headings/items and try to
1651 make an intelligent decision whether to insert a blank line or not."
1652 :group 'org-edit-structure
1653 :type '(list
1654 (cons (const heading)
1655 (choice (const :tag "Never" nil)
1656 (const :tag "Always" t)
1657 (const :tag "Auto" auto)))
1658 (cons (const plain-list-item)
1659 (choice (const :tag "Never" nil)
1660 (const :tag "Always" t)
1661 (const :tag "Auto" auto)))))
1663 (defcustom org-insert-heading-hook nil
1664 "Hook being run after inserting a new heading."
1665 :group 'org-edit-structure
1666 :type 'hook)
1668 (defcustom org-enable-fixed-width-editor t
1669 "Non-nil means lines starting with \":\" are treated as fixed-width.
1670 This currently only means they are never auto-wrapped.
1671 When nil, such lines will be treated like ordinary lines."
1672 :group 'org-edit-structure
1673 :type 'boolean)
1675 (defcustom org-goto-auto-isearch t
1676 "Non-nil means typing characters in `org-goto' starts incremental search.
1677 When nil, you can use these keybindings to navigate the buffer:
1679 q Quit the org-goto interface
1680 n Go to the next visible heading
1681 p Go to the previous visible heading
1682 f Go one heading forward on same level
1683 b Go one heading backward on same level
1684 u Go one heading up"
1685 :group 'org-edit-structure
1686 :type 'boolean)
1688 (defgroup org-sparse-trees nil
1689 "Options concerning sparse trees in Org mode."
1690 :tag "Org Sparse Trees"
1691 :group 'org-structure)
1693 (defcustom org-highlight-sparse-tree-matches t
1694 "Non-nil means highlight all matches that define a sparse tree.
1695 The highlights will automatically disappear the next time the buffer is
1696 changed by an edit command."
1697 :group 'org-sparse-trees
1698 :type 'boolean)
1700 (defcustom org-remove-highlights-with-change t
1701 "Non-nil means any change to the buffer will remove temporary highlights.
1702 \\<org-mode-map>\
1703 Such highlights are created by `org-occur' and `org-clock-display'.
1704 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1705 to get rid of the highlights.
1706 The highlights created by `org-toggle-latex-fragment' always need
1707 `\\[org-toggle-latex-fragment]' to be removed."
1708 :group 'org-sparse-trees
1709 :group 'org-time
1710 :type 'boolean)
1712 (defcustom org-occur-case-fold-search t
1713 "Non-nil means `org-occur' should be case-insensitive.
1714 If set to `smart' the search will be case-insensitive only if it
1715 doesn't specify any upper case character."
1716 :group 'org-sparse-trees
1717 :version "26.1"
1718 :type '(choice
1719 (const :tag "Case-sensitive" nil)
1720 (const :tag "Case-insensitive" t)
1721 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1723 (defcustom org-occur-hook '(org-first-headline-recenter)
1724 "Hook that is run after `org-occur' has constructed a sparse tree.
1725 This can be used to recenter the window to show as much of the structure
1726 as possible."
1727 :group 'org-sparse-trees
1728 :type 'hook)
1730 (defgroup org-imenu-and-speedbar nil
1731 "Options concerning imenu and speedbar in Org mode."
1732 :tag "Org Imenu and Speedbar"
1733 :group 'org-structure)
1735 (defcustom org-imenu-depth 2
1736 "The maximum level for Imenu access to Org headlines.
1737 This also applied for speedbar access."
1738 :group 'org-imenu-and-speedbar
1739 :type 'integer)
1741 (defgroup org-table nil
1742 "Options concerning tables in Org mode."
1743 :tag "Org Table"
1744 :group 'org)
1746 (defcustom org-self-insert-cluster-for-undo nil
1747 "Non-nil means cluster self-insert commands for undo when possible.
1748 If this is set, then, like in the Emacs command loop, 20 consecutive
1749 characters will be undone together.
1750 This is configurable, because there is some impact on typing performance."
1751 :group 'org-table
1752 :type 'boolean)
1754 (defcustom org-table-tab-recognizes-table.el t
1755 "Non-nil means TAB will automatically notice a table.el table.
1756 When it sees such a table, it moves point into it and - if necessary -
1757 calls `table-recognize-table'."
1758 :group 'org-table-editing
1759 :type 'boolean)
1761 (defgroup org-link nil
1762 "Options concerning links in Org mode."
1763 :tag "Org Link"
1764 :group 'org)
1766 (defvar-local org-link-abbrev-alist-local nil
1767 "Buffer-local version of `org-link-abbrev-alist', which see.
1768 The value of this is taken from the #+LINK lines.")
1770 (defcustom org-link-parameters
1771 '(("doi" :follow org--open-doi-link)
1772 ("elisp" :follow org--open-elisp-link)
1773 ("file" :complete org-file-complete-link)
1774 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1775 ("help" :follow org--open-help-link)
1776 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1777 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1778 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1779 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1780 ("shell" :follow org--open-shell-link))
1781 "An alist of properties that defines all the links in Org mode.
1782 The key in each association is a string of the link type.
1783 Subsequent optional elements make up a p-list of link properties.
1785 :follow - A function that takes the link path as an argument.
1787 :export - A function that takes the link path, description and
1788 export-backend as arguments.
1790 :store - A function responsible for storing the link. See the
1791 function `org-store-link-functions'.
1793 :complete - A function that inserts a link with completion. The
1794 function takes one optional prefix arg.
1796 :face - A face for the link, or a function that returns a face.
1797 The function takes one argument which is the link path. The
1798 default face is `org-link'.
1800 :mouse-face - The mouse-face. The default is `highlight'.
1802 :display - `full' will not fold the link in descriptive
1803 display. Default is `org-link'.
1805 :help-echo - A string or function that takes (window object position)
1806 as arguments and returns a string.
1808 :keymap - A keymap that is active on the link. The default is
1809 `org-mouse-map'.
1811 :htmlize-link - A function for the htmlize-link. Defaults
1812 to (list :uri \"type:path\")
1814 :activate-func - A function to run at the end of font-lock
1815 activation. The function must accept (link-start link-end path bracketp)
1816 as arguments."
1817 :group 'org-link
1818 :type '(alist :tag "Link display parameters"
1819 :value-type plist)
1820 :version "26.1"
1821 :package-version '(Org . "9.1"))
1823 (defun org-link-get-parameter (type key)
1824 "Get TYPE link property for KEY.
1825 TYPE is a string and KEY is a plist keyword."
1826 (plist-get
1827 (cdr (assoc type org-link-parameters))
1828 key))
1830 (defun org-link-set-parameters (type &rest parameters)
1831 "Set link TYPE properties to PARAMETERS.
1832 PARAMETERS should be :key val pairs."
1833 (let ((data (assoc type org-link-parameters)))
1834 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1835 (push (cons type parameters) org-link-parameters)
1836 (org-make-link-regexps)
1837 (org-element-update-syntax))))
1839 (defun org-link-types ()
1840 "Return a list of known link types."
1841 (mapcar #'car org-link-parameters))
1843 (defcustom org-link-abbrev-alist nil
1844 "Alist of link abbreviations.
1845 The car of each element is a string, to be replaced at the start of a link.
1846 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1847 links in Org buffers can have an optional tag after a double colon, e.g.,
1849 [[linkkey:tag][description]]
1851 The `linkkey' must be a single word, starting with a letter, followed
1852 by letters, numbers, `-' or `_'.
1854 If REPLACE is a string, the tag will simply be appended to create the link.
1855 If the string contains \"%s\", the tag will be inserted there. If the string
1856 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1857 at that point (see the function `url-hexify-string'). If the string contains
1858 the specifier \"%(my-function)\", then the custom function `my-function' will
1859 be invoked: this function takes the tag as its only argument and must return
1860 a string.
1862 REPLACE may also be a function that will be called with the tag as the
1863 only argument to create the link, which should be returned as a string.
1865 See the manual for examples."
1866 :group 'org-link
1867 :type '(repeat
1868 (cons
1869 (string :tag "Protocol")
1870 (choice
1871 (string :tag "Format")
1872 (function)))))
1874 (defcustom org-descriptive-links t
1875 "Non-nil means Org will display descriptive links.
1876 E.g. [[http://orgmode.org][Org website]] will be displayed as
1877 \"Org Website\", hiding the link itself and just displaying its
1878 description. When set to nil, Org will display the full links
1879 literally.
1881 You can interactively set the value of this variable by calling
1882 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1883 :group 'org-link
1884 :type 'boolean)
1886 (defcustom org-link-file-path-type 'adaptive
1887 "How the path name in file links should be stored.
1888 Valid values are:
1890 relative Relative to the current directory, i.e. the directory of the file
1891 into which the link is being inserted.
1892 absolute Absolute path, if possible with ~ for home directory.
1893 noabbrev Absolute path, no abbreviation of home directory.
1894 adaptive Use relative path for files in the current directory and sub-
1895 directories of it. For other files, use an absolute path."
1896 :group 'org-link
1897 :type '(choice
1898 (const relative)
1899 (const absolute)
1900 (const noabbrev)
1901 (const adaptive)))
1903 (defvaralias 'org-activate-links 'org-highlight-links)
1904 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1905 "Types of links that should be highlighted in Org files.
1907 This is a list of symbols, each one of them leading to the
1908 highlighting of a certain link type.
1910 You can still open links that are not highlighted.
1912 In principle, it does not hurt to turn on highlighting for all
1913 link types. There may be a small gain when turning off unused
1914 link types. The types are:
1916 bracket The recommended [[link][description]] or [[link]] links with hiding.
1917 angle Links in angular brackets that may contain whitespace like
1918 <bbdb:Carsten Dominik>.
1919 plain Plain links in normal text, no whitespace, like http://google.com.
1920 radio Text that is matched by a radio target, see manual for details.
1921 tag Tag settings in a headline (link to tag search).
1922 date Time stamps (link to calendar).
1923 footnote Footnote labels.
1925 If you set this variable during an Emacs session, use `org-mode-restart'
1926 in the Org buffer so that the change takes effect."
1927 :group 'org-link
1928 :group 'org-appearance
1929 :type '(set :greedy t
1930 (const :tag "Double bracket links" bracket)
1931 (const :tag "Angular bracket links" angle)
1932 (const :tag "Plain text links" plain)
1933 (const :tag "Radio target matches" radio)
1934 (const :tag "Tags" tag)
1935 (const :tag "Timestamps" date)
1936 (const :tag "Footnotes" footnote)))
1938 (defcustom org-make-link-description-function nil
1939 "Function to use for generating link descriptions from links.
1940 When nil, the link location will be used. This function must take
1941 two parameters: the first one is the link, the second one is the
1942 description generated by `org-insert-link'. The function should
1943 return the description to use."
1944 :group 'org-link
1945 :type '(choice (const nil) (function)))
1947 (defgroup org-link-store nil
1948 "Options concerning storing links in Org mode."
1949 :tag "Org Store Link"
1950 :group 'org-link)
1952 (defcustom org-url-hexify-p t
1953 "When non-nil, hexify URL when creating a link."
1954 :type 'boolean
1955 :version "24.3"
1956 :group 'org-link-store)
1958 (defcustom org-email-link-description-format "Email %c: %.30s"
1959 "Format of the description part of a link to an email or usenet message.
1960 The following %-escapes will be replaced by corresponding information:
1962 %F full \"From\" field
1963 %f name, taken from \"From\" field, address if no name
1964 %T full \"To\" field
1965 %t first name in \"To\" field, address if no name
1966 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1967 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1968 %s subject
1969 %d date
1970 %m message-id.
1972 You may use normal field width specification between the % and the letter.
1973 This is for example useful to limit the length of the subject.
1975 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1976 :group 'org-link-store
1977 :type 'string)
1979 (defcustom org-from-is-user-regexp
1980 (let (r1 r2)
1981 (when (and user-mail-address (not (string= user-mail-address "")))
1982 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1983 (when (and user-full-name (not (string= user-full-name "")))
1984 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1985 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1986 "Regexp matched against the \"From:\" header of an email or usenet message.
1987 It should match if the message is from the user him/herself."
1988 :group 'org-link-store
1989 :type 'regexp)
1991 (defcustom org-context-in-file-links t
1992 "Non-nil means file links from `org-store-link' contain context.
1993 \\<org-mode-map>
1994 A search string will be added to the file name with :: as separator
1995 and used to find the context when the link is activated by the command
1996 `org-open-at-point'. When this option is t, the entire active region
1997 will be placed in the search string of the file link. If set to a
1998 positive integer, only the first n lines of context will be stored.
2000 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2001 \\[org-store-link]')
2002 negates this setting for the duration of the command."
2003 :group 'org-link-store
2004 :type '(choice boolean integer))
2006 (defcustom org-keep-stored-link-after-insertion nil
2007 "Non-nil means keep link in list for entire session.
2008 \\<org-mode-map>
2009 The command `org-store-link' adds a link pointing to the current
2010 location to an internal list. These links accumulate during a session.
2011 The command `org-insert-link' can be used to insert links into any
2012 Org file (offering completion for all stored links).
2014 When this option is nil, every link which has been inserted once using
2015 `\\[org-insert-link]' will be removed from the list, to make completing the \
2016 unused
2017 links more efficient."
2018 :group 'org-link-store
2019 :type 'boolean)
2021 (defgroup org-link-follow nil
2022 "Options concerning following links in Org mode."
2023 :tag "Org Follow Link"
2024 :group 'org-link)
2026 (defcustom org-link-translation-function nil
2027 "Function to translate links with different syntax to Org syntax.
2028 This can be used to translate links created for example by the Planner
2029 or emacs-wiki packages to Org syntax.
2030 The function must accept two parameters, a TYPE containing the link
2031 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2032 which is everything after the link protocol. It should return a cons
2033 with possibly modified values of type and path.
2034 Org contains a function for this, so if you set this variable to
2035 `org-translate-link-from-planner', you should be able follow many
2036 links created by planner."
2037 :group 'org-link-follow
2038 :type '(choice (const nil) (function)))
2040 (defcustom org-follow-link-hook nil
2041 "Hook that is run after a link has been followed."
2042 :group 'org-link-follow
2043 :type 'hook)
2045 (defcustom org-tab-follows-link nil
2046 "Non-nil means on links TAB will follow the link.
2047 Needs to be set before org.el is loaded.
2048 This really should not be used, it does not make sense, and the
2049 implementation is bad."
2050 :group 'org-link-follow
2051 :type 'boolean)
2053 (defcustom org-return-follows-link nil
2054 "Non-nil means on links RET will follow the link.
2055 In tables, the special behavior of RET has precedence."
2056 :group 'org-link-follow
2057 :type 'boolean)
2059 (defcustom org-mouse-1-follows-link
2060 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2061 "Non-nil means mouse-1 on a link will follow the link.
2062 A longer mouse click will still set point. Needs to be set
2063 before org.el is loaded."
2064 :group 'org-link-follow
2065 :version "24.4"
2066 :package-version '(Org . "8.3")
2067 :type '(choice
2068 (const :tag "A double click follows the link" double)
2069 (const :tag "Unconditionally follow the link with mouse-1" t)
2070 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2072 (defcustom org-mark-ring-length 4
2073 "Number of different positions to be recorded in the ring.
2074 Changing this requires a restart of Emacs to work correctly."
2075 :group 'org-link-follow
2076 :type 'integer)
2078 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2079 "Non-nil means internal fuzzy links can only match headlines.
2081 When nil, the a fuzzy link may point to a target or a named
2082 construct in the document. When set to the special value
2083 `query-to-create', offer to create a new headline when none
2084 matched.
2086 Spaces and statistics cookies are ignored during heading searches."
2087 :group 'org-link-follow
2088 :version "24.1"
2089 :type '(choice
2090 (const :tag "Use fuzzy text search" nil)
2091 (const :tag "Match only exact headline" t)
2092 (const :tag "Match exact headline or query to create it"
2093 query-to-create))
2094 :safe #'symbolp)
2096 (defcustom org-link-frame-setup
2097 '((vm . vm-visit-folder-other-frame)
2098 (vm-imap . vm-visit-imap-folder-other-frame)
2099 (gnus . org-gnus-no-new-news)
2100 (file . find-file-other-window)
2101 (wl . wl-other-frame))
2102 "Setup the frame configuration for following links.
2103 When following a link with Emacs, it may often be useful to display
2104 this link in another window or frame. This variable can be used to
2105 set this up for the different types of links.
2106 For VM, use any of
2107 `vm-visit-folder'
2108 `vm-visit-folder-other-window'
2109 `vm-visit-folder-other-frame'
2110 For Gnus, use any of
2111 `gnus'
2112 `gnus-other-frame'
2113 `org-gnus-no-new-news'
2114 For FILE, use any of
2115 `find-file'
2116 `find-file-other-window'
2117 `find-file-other-frame'
2118 For Wanderlust use any of
2119 `wl'
2120 `wl-other-frame'
2121 For the calendar, use the variable `calendar-setup'.
2122 For BBDB, it is currently only possible to display the matches in
2123 another window."
2124 :group 'org-link-follow
2125 :type '(list
2126 (cons (const vm)
2127 (choice
2128 (const vm-visit-folder)
2129 (const vm-visit-folder-other-window)
2130 (const vm-visit-folder-other-frame)))
2131 (cons (const vm-imap)
2132 (choice
2133 (const vm-visit-imap-folder)
2134 (const vm-visit-imap-folder-other-window)
2135 (const vm-visit-imap-folder-other-frame)))
2136 (cons (const gnus)
2137 (choice
2138 (const gnus)
2139 (const gnus-other-frame)
2140 (const org-gnus-no-new-news)))
2141 (cons (const file)
2142 (choice
2143 (const find-file)
2144 (const find-file-other-window)
2145 (const find-file-other-frame)))
2146 (cons (const wl)
2147 (choice
2148 (const wl)
2149 (const wl-other-frame)))))
2151 (defcustom org-display-internal-link-with-indirect-buffer nil
2152 "Non-nil means use indirect buffer to display infile links.
2153 Activating internal links (from one location in a file to another location
2154 in the same file) normally just jumps to the location. When the link is
2155 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2156 is displayed in
2157 another window. When this option is set, the other window actually displays
2158 an indirect buffer clone of the current buffer, to avoid any visibility
2159 changes to the current buffer."
2160 :group 'org-link-follow
2161 :type 'boolean)
2163 (defcustom org-open-non-existing-files nil
2164 "Non-nil means `org-open-file' will open non-existing files.
2165 When nil, an error will be generated.
2166 This variable applies only to external applications because they
2167 might choke on non-existing files. If the link is to a file that
2168 will be opened in Emacs, the variable is ignored."
2169 :group 'org-link-follow
2170 :type 'boolean)
2172 (defcustom org-open-directory-means-index-dot-org nil
2173 "Non-nil means a link to a directory really means to index.org.
2174 When nil, following a directory link will run dired or open a finder/explorer
2175 window on that directory."
2176 :group 'org-link-follow
2177 :type 'boolean)
2179 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2180 "Non-nil means ask for confirmation before executing shell links.
2181 Shell links can be dangerous: just think about a link
2183 [[shell:rm -rf ~/*][Google Search]]
2185 This link would show up in your Org document as \"Google Search\",
2186 but really it would remove your entire home directory.
2187 Therefore we advise against setting this variable to nil.
2188 Just change it to `y-or-n-p' if you want to confirm with a
2189 single keystroke rather than having to type \"yes\"."
2190 :group 'org-link-follow
2191 :type '(choice
2192 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2193 (const :tag "with y-or-n (faster)" y-or-n-p)
2194 (const :tag "no confirmation (dangerous)" nil)))
2195 (put 'org-confirm-shell-link-function
2196 'safe-local-variable
2197 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2199 (defcustom org-confirm-shell-link-not-regexp ""
2200 "A regexp to skip confirmation for shell links."
2201 :group 'org-link-follow
2202 :version "24.1"
2203 :type 'regexp)
2205 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2206 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2207 Elisp links can be dangerous: just think about a link
2209 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2211 This link would show up in your Org document as \"Google Search\",
2212 but really it would remove your entire home directory.
2213 Therefore we advise against setting this variable to nil.
2214 Just change it to `y-or-n-p' if you want to confirm with a
2215 single keystroke rather than having to type \"yes\"."
2216 :group 'org-link-follow
2217 :type '(choice
2218 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2219 (const :tag "with y-or-n (faster)" y-or-n-p)
2220 (const :tag "no confirmation (dangerous)" nil)))
2221 (put 'org-confirm-shell-link-function
2222 'safe-local-variable
2223 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2225 (defcustom org-confirm-elisp-link-not-regexp ""
2226 "A regexp to skip confirmation for Elisp links."
2227 :group 'org-link-follow
2228 :version "24.1"
2229 :type 'regexp)
2231 (defconst org-file-apps-defaults-gnu
2232 '((remote . emacs)
2233 (system . mailcap)
2234 (t . mailcap))
2235 "Default file applications on a UNIX or GNU/Linux system.
2236 See `org-file-apps'.")
2238 (defconst org-file-apps-defaults-macosx
2239 '((remote . emacs)
2240 (system . "open %s")
2241 ("ps.gz" . "gv %s")
2242 ("eps.gz" . "gv %s")
2243 ("dvi" . "xdvi %s")
2244 ("fig" . "xfig %s")
2245 (t . "open %s"))
2246 "Default file applications on a macOS system.
2247 The system \"open\" is known as a default, but we use X11 applications
2248 for some files for which the OS does not have a good default.
2249 See `org-file-apps'.")
2251 (defconst org-file-apps-defaults-windowsnt
2252 (list '(remote . emacs)
2253 (cons 'system (lambda (file _path)
2254 (with-no-warnings (w32-shell-execute "open" file))))
2255 (cons t (lambda (file _path)
2256 (with-no-warnings (w32-shell-execute "open" file)))))
2257 "Default file applications on a Windows NT system.
2258 The system \"open\" is used for most files.
2259 See `org-file-apps'.")
2261 (defcustom org-file-apps
2262 '((auto-mode . emacs)
2263 ("\\.mm\\'" . default)
2264 ("\\.x?html?\\'" . default)
2265 ("\\.pdf\\'" . default))
2266 "External applications for opening `file:path' items in a document.
2267 \\<org-mode-map>\
2269 Org mode uses system defaults for different file types, but
2270 you can use this variable to set the application for a given file
2271 extension. The entries in this list are cons cells where the car identifies
2272 files and the cdr the corresponding command.
2274 Possible values for the file identifier are:
2276 \"string\" A string as a file identifier can be interpreted in different
2277 ways, depending on its contents:
2279 - Alphanumeric characters only:
2280 Match links with this file extension.
2281 Example: (\"pdf\" . \"evince %s\")
2282 to open PDFs with evince.
2284 - Regular expression: Match links where the
2285 filename matches the regexp. If you want to
2286 use groups here, use shy groups.
2288 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2289 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2290 to open *.html and *.xhtml with firefox.
2292 - Regular expression which contains (non-shy) groups:
2293 Match links where the whole link, including \"::\", and
2294 anything after that, matches the regexp.
2295 In a custom command string, %1, %2, etc. are replaced with
2296 the parts of the link that were matched by the groups.
2297 For backwards compatibility, if a command string is given
2298 that does not use any of the group matches, this case is
2299 handled identically to the second one (i.e. match against
2300 file name only).
2301 In a custom function, you can access the group matches with
2302 (match-string n link).
2304 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2305 \"evince -p %1 %s\")
2306 to open [[file:document.pdf::5]] with evince at page 5.
2308 `directory' Matches a directory
2309 `remote' Matches a remote file, accessible through tramp or efs.
2310 Remote files most likely should be visited through Emacs
2311 because external applications cannot handle such paths.
2312 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2313 so all files Emacs knows how to handle. Using this with
2314 command `emacs' will open most files in Emacs. Beware that this
2315 will also open html files inside Emacs, unless you add
2316 (\"html\" . default) to the list as well.
2317 `system' The system command to open files, like `open' on Windows
2318 and macOS, and mailcap under GNU/Linux. This is the command
2319 that will be selected if you call `org-open-at-point' with a
2320 double prefix argument (`\\[universal-argument] \
2321 \\[universal-argument] \\[org-open-at-point]').
2322 t Default for files not matched by any of the other options.
2324 Possible values for the command are:
2326 `emacs' The file will be visited by the current Emacs process.
2327 `default' Use the default application for this file type, which is the
2328 association for t in the list, most likely in the system-specific
2329 part. This can be used to overrule an unwanted setting in the
2330 system-specific variable.
2331 `system' Use the system command for opening files, like \"open\".
2332 This command is specified by the entry whose car is `system'.
2333 Most likely, the system-specific version of this variable
2334 does define this command, but you can overrule/replace it
2335 here.
2336 `mailcap' Use command specified in the mailcaps.
2337 string A command to be executed by a shell; %s will be replaced
2338 by the path to the file.
2339 function A Lisp function, which will be called with two arguments:
2340 the file path and the original link string, without the
2341 \"file:\" prefix.
2343 For more examples, see the system specific constants
2344 `org-file-apps-defaults-macosx'
2345 `org-file-apps-defaults-windowsnt'
2346 `org-file-apps-defaults-gnu'."
2347 :group 'org-link-follow
2348 :type '(repeat
2349 (cons (choice :value ""
2350 (string :tag "Extension")
2351 (const :tag "System command to open files" system)
2352 (const :tag "Default for unrecognized files" t)
2353 (const :tag "Remote file" remote)
2354 (const :tag "Links to a directory" directory)
2355 (const :tag "Any files that have Emacs modes"
2356 auto-mode))
2357 (choice :value ""
2358 (const :tag "Visit with Emacs" emacs)
2359 (const :tag "Use default" default)
2360 (const :tag "Use the system command" system)
2361 (string :tag "Command")
2362 (function :tag "Function")))))
2364 (defcustom org-doi-server-url "http://dx.doi.org/"
2365 "The URL of the DOI server."
2366 :type 'string
2367 :version "24.3"
2368 :group 'org-link-follow)
2370 (defgroup org-refile nil
2371 "Options concerning refiling entries in Org mode."
2372 :tag "Org Refile"
2373 :group 'org)
2375 (defcustom org-directory "~/org"
2376 "Directory with Org files.
2377 This is just a default location to look for Org files. There is no need
2378 at all to put your files into this directory. It is used in the
2379 following situations:
2381 1. When a capture template specifies a target file that is not an
2382 absolute path. The path will then be interpreted relative to
2383 `org-directory'
2384 2. When the value of variable `org-agenda-files' is a single file, any
2385 relative paths in this file will be taken as relative to
2386 `org-directory'."
2387 :group 'org-refile
2388 :group 'org-capture
2389 :type 'directory)
2391 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2392 "Default target for storing notes.
2393 Used as a fall back file for org-capture.el, for templates that
2394 do not specify a target file."
2395 :group 'org-refile
2396 :group 'org-capture
2397 :type 'file)
2399 (defcustom org-goto-interface 'outline
2400 "The default interface to be used for `org-goto'.
2401 Allowed values are:
2402 outline The interface shows an outline of the relevant file
2403 and the correct heading is found by moving through
2404 the outline or by searching with incremental search.
2405 outline-path-completion Headlines in the current buffer are offered via
2406 completion. This is the interface also used by
2407 the refile command."
2408 :group 'org-refile
2409 :type '(choice
2410 (const :tag "Outline" outline)
2411 (const :tag "Outline-path-completion" outline-path-completion)))
2413 (defcustom org-goto-max-level 5
2414 "Maximum target level when running `org-goto' with refile interface."
2415 :group 'org-refile
2416 :type 'integer)
2418 (defcustom org-reverse-note-order nil
2419 "Non-nil means store new notes at the beginning of a file or entry.
2420 When nil, new notes will be filed to the end of a file or entry.
2421 This can also be a list with cons cells of regular expressions that
2422 are matched against file names, and values."
2423 :group 'org-capture
2424 :group 'org-refile
2425 :type '(choice
2426 (const :tag "Reverse always" t)
2427 (const :tag "Reverse never" nil)
2428 (repeat :tag "By file name regexp"
2429 (cons regexp boolean))))
2431 (defcustom org-log-refile nil
2432 "Information to record when a task is refiled.
2434 Possible values are:
2436 nil Don't add anything
2437 time Add a time stamp to the task
2438 note Prompt for a note and add it with template `org-log-note-headings'
2440 This option can also be set with on a per-file-basis with
2442 #+STARTUP: nologrefile
2443 #+STARTUP: logrefile
2444 #+STARTUP: lognoterefile
2446 You can have local logging settings for a subtree by setting the LOGGING
2447 property to one or more of these keywords.
2449 When bulk-refiling from the agenda, the value `note' is forbidden and
2450 will temporarily be changed to `time'."
2451 :group 'org-refile
2452 :group 'org-progress
2453 :version "24.1"
2454 :type '(choice
2455 (const :tag "No logging" nil)
2456 (const :tag "Record timestamp" time)
2457 (const :tag "Record timestamp with note." note)))
2459 (defcustom org-refile-targets nil
2460 "Targets for refiling entries with `\\[org-refile]'.
2461 This is a list of cons cells. Each cell contains:
2462 - a specification of the files to be considered, either a list of files,
2463 or a symbol whose function or variable value will be used to retrieve
2464 a file name or a list of file names. If you use `org-agenda-files' for
2465 that, all agenda files will be scanned for targets. Nil means consider
2466 headings in the current buffer.
2467 - A specification of how to find candidate refile targets. This may be
2468 any of:
2469 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2470 This tag has to be present in all target headlines, inheritance will
2471 not be considered.
2472 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2473 todo keyword.
2474 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2475 headlines that are refiling targets.
2476 - a cons cell (:level . N). Any headline of level N is considered a target.
2477 Note that, when `org-odd-levels-only' is set, level corresponds to
2478 order in hierarchy, not to the number of stars.
2479 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2480 Note that, when `org-odd-levels-only' is set, level corresponds to
2481 order in hierarchy, not to the number of stars.
2483 Each element of this list generates a set of possible targets.
2484 The union of these sets is presented (with completion) to
2485 the user by `org-refile'.
2487 You can set the variable `org-refile-target-verify-function' to a function
2488 to verify each headline found by the simple criteria above.
2490 When this variable is nil, all top-level headlines in the current buffer
2491 are used, equivalent to the value `((nil . (:level . 1))'."
2492 :group 'org-refile
2493 :type '(repeat
2494 (cons
2495 (choice :value org-agenda-files
2496 (const :tag "All agenda files" org-agenda-files)
2497 (const :tag "Current buffer" nil)
2498 (function) (variable) (file))
2499 (choice :tag "Identify target headline by"
2500 (cons :tag "Specific tag" (const :value :tag) (string))
2501 (cons :tag "TODO keyword" (const :value :todo) (string))
2502 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2503 (cons :tag "Level number" (const :value :level) (integer))
2504 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2506 (defcustom org-refile-target-verify-function nil
2507 "Function to verify if the headline at point should be a refile target.
2508 The function will be called without arguments, with point at the
2509 beginning of the headline. It should return t and leave point
2510 where it is if the headline is a valid target for refiling.
2512 If the target should not be selected, the function must return nil.
2513 In addition to this, it may move point to a place from where the search
2514 should be continued. For example, the function may decide that the entire
2515 subtree of the current entry should be excluded and move point to the end
2516 of the subtree."
2517 :group 'org-refile
2518 :type '(choice
2519 (const nil)
2520 (function)))
2522 (defcustom org-refile-use-cache nil
2523 "Non-nil means cache refile targets to speed up the process.
2524 \\<org-mode-map>\
2525 The cache for a particular file will be updated automatically when
2526 the buffer has been killed, or when any of the marker used for flagging
2527 refile targets no longer points at a live buffer.
2528 If you have added new entries to a buffer that might themselves be targets,
2529 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2530 if you find that easier, \
2531 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2532 \\[org-refile]'."
2533 :group 'org-refile
2534 :version "24.1"
2535 :type 'boolean)
2537 (defcustom org-refile-use-outline-path nil
2538 "Non-nil means provide refile targets as paths.
2539 So a level 3 headline will be available as level1/level2/level3.
2541 When the value is `file', also include the file name (without directory)
2542 into the path. In this case, you can also stop the completion after
2543 the file name, to get entries inserted as top level in the file.
2545 When `full-file-path', include the full file path.
2547 When `buffer-name', use the buffer name."
2548 :group 'org-refile
2549 :type '(choice
2550 (const :tag "Not" nil)
2551 (const :tag "Yes" t)
2552 (const :tag "Start with file name" file)
2553 (const :tag "Start with full file path" full-file-path)
2554 (const :tag "Start with buffer name" buffer-name)))
2556 (defcustom org-outline-path-complete-in-steps t
2557 "Non-nil means complete the outline path in hierarchical steps.
2558 When Org uses the refile interface to select an outline path (see
2559 `org-refile-use-outline-path'), the completion of the path can be
2560 done in a single go, or it can be done in steps down the headline
2561 hierarchy. Going in steps is probably the best if you do not use
2562 a special completion package like `ido' or `icicles'. However,
2563 when using these packages, going in one step can be very fast,
2564 while still showing the whole path to the entry."
2565 :group 'org-refile
2566 :type 'boolean)
2568 (defcustom org-refile-allow-creating-parent-nodes nil
2569 "Non-nil means allow the creation of new nodes as refile targets.
2570 New nodes are then created by adding \"/new node name\" to the completion
2571 of an existing node. When the value of this variable is `confirm',
2572 new node creation must be confirmed by the user (recommended).
2573 When nil, the completion must match an existing entry.
2575 Note that, if the new heading is not seen by the criteria
2576 listed in `org-refile-targets', multiple instances of the same
2577 heading would be created by trying again to file under the new
2578 heading."
2579 :group 'org-refile
2580 :type '(choice
2581 (const :tag "Never" nil)
2582 (const :tag "Always" t)
2583 (const :tag "Prompt for confirmation" confirm)))
2585 (defcustom org-refile-active-region-within-subtree nil
2586 "Non-nil means also refile active region within a subtree.
2588 By default `org-refile' doesn't allow refiling regions if they
2589 don't contain a set of subtrees, but it might be convenient to
2590 do so sometimes: in that case, the first line of the region is
2591 converted to a headline before refiling."
2592 :group 'org-refile
2593 :version "24.1"
2594 :type 'boolean)
2596 (defgroup org-todo nil
2597 "Options concerning TODO items in Org mode."
2598 :tag "Org TODO"
2599 :group 'org)
2601 (defgroup org-progress nil
2602 "Options concerning Progress logging in Org mode."
2603 :tag "Org Progress"
2604 :group 'org-time)
2606 (defvar org-todo-interpretation-widgets
2607 '((:tag "Sequence (cycling hits every state)" sequence)
2608 (:tag "Type (cycling directly to DONE)" type))
2609 "The available interpretation symbols for customizing `org-todo-keywords'.
2610 Interested libraries should add to this list.")
2612 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2613 "List of TODO entry keyword sequences and their interpretation.
2614 \\<org-mode-map>This is a list of sequences.
2616 Each sequence starts with a symbol, either `sequence' or `type',
2617 indicating if the keywords should be interpreted as a sequence of
2618 action steps, or as different types of TODO items. The first
2619 keywords are states requiring action - these states will select a headline
2620 for inclusion into the global TODO list Org produces. If one of the
2621 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2622 signify that no further action is necessary. If \"|\" is not found,
2623 the last keyword is treated as the only DONE state of the sequence.
2625 The command `\\[org-todo]' cycles an entry through these states, and one
2626 additional state where no keyword is present. For details about this
2627 cycling, see the manual.
2629 TODO keywords and interpretation can also be set on a per-file basis with
2630 the special #+SEQ_TODO and #+TYP_TODO lines.
2632 Each keyword can optionally specify a character for fast state selection
2633 \(in combination with the variable `org-use-fast-todo-selection')
2634 and specifiers for state change logging, using the same syntax that
2635 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2636 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2637 indicates to record a time stamp each time this state is selected.
2639 Each keyword may also specify if a timestamp or a note should be
2640 recorded when entering or leaving the state, by adding additional
2641 characters in the parenthesis after the keyword. This looks like this:
2642 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2643 record only the time of the state change. With X and Y being either
2644 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2645 Y when leaving the state if and only if the *target* state does not
2646 define X. You may omit any of the fast-selection key or X or /Y,
2647 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2649 For backward compatibility, this variable may also be just a list
2650 of keywords. In this case the interpretation (sequence or type) will be
2651 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2652 :group 'org-todo
2653 :group 'org-keywords
2654 :type '(choice
2655 (repeat :tag "Old syntax, just keywords"
2656 (string :tag "Keyword"))
2657 (repeat :tag "New syntax"
2658 (cons
2659 (choice
2660 :tag "Interpretation"
2661 ;;Quick and dirty way to see
2662 ;;`org-todo-interpretations'. This takes the
2663 ;;place of item arguments
2664 :convert-widget
2665 (lambda (widget)
2666 (widget-put widget
2667 :args (mapcar
2668 (lambda (x)
2669 (widget-convert
2670 (cons 'const x)))
2671 org-todo-interpretation-widgets))
2672 widget))
2673 (repeat
2674 (string :tag "Keyword"))))))
2676 (defvar-local org-todo-keywords-1 nil
2677 "All TODO and DONE keywords active in a buffer.")
2678 (defvar org-todo-keywords-for-agenda nil)
2679 (defvar org-done-keywords-for-agenda nil)
2680 (defvar org-todo-keyword-alist-for-agenda nil)
2681 (defvar org-tag-alist-for-agenda nil
2682 "Alist of all tags from all agenda files.")
2683 (defvar org-tag-groups-alist-for-agenda nil
2684 "Alist of all groups tags from all current agenda files.")
2685 (defvar-local org-tag-groups-alist nil)
2686 (defvar org-agenda-contributing-files nil)
2687 (defvar-local org-current-tag-alist nil
2688 "Alist of all tag groups in current buffer.
2689 This variable takes into consideration `org-tag-alist',
2690 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2691 (defvar-local org-not-done-keywords nil)
2692 (defvar-local org-done-keywords nil)
2693 (defvar-local org-todo-heads nil)
2694 (defvar-local org-todo-sets nil)
2695 (defvar-local org-todo-log-states nil)
2696 (defvar-local org-todo-kwd-alist nil)
2697 (defvar-local org-todo-key-alist nil)
2698 (defvar-local org-todo-key-trigger nil)
2700 (defcustom org-todo-interpretation 'sequence
2701 "Controls how TODO keywords are interpreted.
2702 This variable is in principle obsolete and is only used for
2703 backward compatibility, if the interpretation of todo keywords is
2704 not given already in `org-todo-keywords'. See that variable for
2705 more information."
2706 :group 'org-todo
2707 :group 'org-keywords
2708 :type '(choice (const sequence)
2709 (const type)))
2711 (defcustom org-use-fast-todo-selection t
2712 "\\<org-mode-map>\
2713 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2714 This variable describes if and under what circumstances the cycling
2715 mechanism for TODO keywords will be replaced by a single-key, direct
2716 selection scheme.
2718 When nil, fast selection is never used.
2720 When the symbol `prefix', it will be used when `org-todo' is called
2721 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2722 in an Org buffer, and
2723 `\\[universal-argument] t' in an agenda buffer.
2725 When t, fast selection is used by default. In this case, the prefix
2726 argument forces cycling instead.
2728 In all cases, the special interface is only used if access keys have
2729 actually been assigned by the user, i.e. if keywords in the configuration
2730 are followed by a letter in parenthesis, like TODO(t)."
2731 :group 'org-todo
2732 :type '(choice
2733 (const :tag "Never" nil)
2734 (const :tag "By default" t)
2735 (const :tag "Only with C-u C-c C-t" prefix)))
2737 (defcustom org-provide-todo-statistics t
2738 "Non-nil means update todo statistics after insert and toggle.
2739 ALL-HEADLINES means update todo statistics by including headlines
2740 with no TODO keyword as well, counting them as not done.
2741 A list of TODO keywords means the same, but skip keywords that are
2742 not in this list.
2743 When set to a list of two lists, the first list contains keywords
2744 to consider as TODO keywords, the second list contains keywords
2745 to consider as DONE keywords.
2747 When this is set, todo statistics is updated in the parent of the
2748 current entry each time a todo state is changed."
2749 :group 'org-todo
2750 :type '(choice
2751 (const :tag "Yes, only for TODO entries" t)
2752 (const :tag "Yes, including all entries" all-headlines)
2753 (repeat :tag "Yes, for TODOs in this list"
2754 (string :tag "TODO keyword"))
2755 (list :tag "Yes, for TODOs and DONEs in these lists"
2756 (repeat (string :tag "TODO keyword"))
2757 (repeat (string :tag "DONE keyword")))
2758 (other :tag "No TODO statistics" nil)))
2760 (defcustom org-hierarchical-todo-statistics t
2761 "Non-nil means TODO statistics covers just direct children.
2762 When nil, all entries in the subtree are considered.
2763 This has only an effect if `org-provide-todo-statistics' is set.
2764 To set this to nil for only a single subtree, use a COOKIE_DATA
2765 property and include the word \"recursive\" into the value."
2766 :group 'org-todo
2767 :type 'boolean)
2769 (defcustom org-after-todo-state-change-hook nil
2770 "Hook which is run after the state of a TODO item was changed.
2771 The new state (a string with a TODO keyword, or nil) is available in the
2772 Lisp variable `org-state'."
2773 :group 'org-todo
2774 :type 'hook)
2776 (defvar org-blocker-hook nil
2777 "Hook for functions that are allowed to block a state change.
2779 Functions in this hook should not modify the buffer.
2780 Each function gets as its single argument a property list,
2781 see `org-trigger-hook' for more information about this list.
2783 If any of the functions in this hook returns nil, the state change
2784 is blocked.")
2786 (defvar org-trigger-hook nil
2787 "Hook for functions that are triggered by a state change.
2789 Each function gets as its single argument a property list with at
2790 least the following elements:
2792 (:type type-of-change :position pos-at-entry-start
2793 :from old-state :to new-state)
2795 Depending on the type, more properties may be present.
2797 This mechanism is currently implemented for:
2799 TODO state changes
2800 ------------------
2801 :type todo-state-change
2802 :from previous state (keyword as a string), or nil, or a symbol
2803 `todo' or `done', to indicate the general type of state.
2804 :to new state, like in :from")
2806 (defcustom org-enforce-todo-dependencies nil
2807 "Non-nil means undone TODO entries will block switching the parent to DONE.
2808 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2809 be blocked if any prior sibling is not yet done.
2810 Finally, if the parent is blocked because of ordered siblings of its own,
2811 the child will also be blocked."
2812 :set (lambda (var val)
2813 (set var val)
2814 (if val
2815 (add-hook 'org-blocker-hook
2816 'org-block-todo-from-children-or-siblings-or-parent)
2817 (remove-hook 'org-blocker-hook
2818 'org-block-todo-from-children-or-siblings-or-parent)))
2819 :group 'org-todo
2820 :type 'boolean)
2822 (defcustom org-enforce-todo-checkbox-dependencies nil
2823 "Non-nil means unchecked boxes will block switching the parent to DONE.
2824 When this is nil, checkboxes have no influence on switching TODO states.
2825 When non-nil, you first need to check off all check boxes before the TODO
2826 entry can be switched to DONE.
2827 This variable needs to be set before org.el is loaded, and you need to
2828 restart Emacs after a change to make the change effective. The only way
2829 to change is while Emacs is running is through the customize interface."
2830 :set (lambda (var val)
2831 (set var val)
2832 (if val
2833 (add-hook 'org-blocker-hook
2834 'org-block-todo-from-checkboxes)
2835 (remove-hook 'org-blocker-hook
2836 'org-block-todo-from-checkboxes)))
2837 :group 'org-todo
2838 :type 'boolean)
2840 (defcustom org-treat-insert-todo-heading-as-state-change nil
2841 "Non-nil means inserting a TODO heading is treated as state change.
2842 So when the command `\\[org-insert-todo-heading]' is used, state change
2843 logging will apply if appropriate. When nil, the new TODO item will
2844 be inserted directly, and no logging will take place."
2845 :group 'org-todo
2846 :type 'boolean)
2848 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2849 "Non-nil means switching TODO states with S-cursor counts as state change.
2850 This is the default behavior. However, setting this to nil allows a
2851 convenient way to select a TODO state and bypass any logging associated
2852 with that."
2853 :group 'org-todo
2854 :type 'boolean)
2856 (defcustom org-todo-state-tags-triggers nil
2857 "Tag changes that should be triggered by TODO state changes.
2858 This is a list. Each entry is
2860 (state-change (tag . flag) .......)
2862 State-change can be a string with a state, and empty string to indicate the
2863 state that has no TODO keyword, or it can be one of the symbols `todo'
2864 or `done', meaning any not-done or done state, respectively."
2865 :group 'org-todo
2866 :group 'org-tags
2867 :type '(repeat
2868 (cons (choice :tag "When changing to"
2869 (const :tag "Not-done state" todo)
2870 (const :tag "Done state" done)
2871 (string :tag "State"))
2872 (repeat
2873 (cons :tag "Tag action"
2874 (string :tag "Tag")
2875 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2877 (defcustom org-log-done nil
2878 "Information to record when a task moves to the DONE state.
2880 Possible values are:
2882 nil Don't add anything, just change the keyword
2883 time Add a time stamp to the task
2884 note Prompt for a note and add it with template `org-log-note-headings'
2886 This option can also be set with on a per-file-basis with
2888 #+STARTUP: nologdone
2889 #+STARTUP: logdone
2890 #+STARTUP: lognotedone
2892 You can have local logging settings for a subtree by setting the LOGGING
2893 property to one or more of these keywords."
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type '(choice
2897 (const :tag "No logging" nil)
2898 (const :tag "Record CLOSED timestamp" time)
2899 (const :tag "Record CLOSED timestamp with note." note)))
2901 ;; Normalize old uses of org-log-done.
2902 (cond
2903 ((eq org-log-done t) (setq org-log-done 'time))
2904 ((and (listp org-log-done) (memq 'done org-log-done))
2905 (setq org-log-done 'note)))
2907 (defcustom org-log-reschedule nil
2908 "Information to record when the scheduling date of a tasks is modified.
2910 Possible values are:
2912 nil Don't add anything, just change the date
2913 time Add a time stamp to the task
2914 note Prompt for a note and add it with template `org-log-note-headings'
2916 This option can also be set with on a per-file-basis with
2918 #+STARTUP: nologreschedule
2919 #+STARTUP: logreschedule
2920 #+STARTUP: lognotereschedule"
2921 :group 'org-todo
2922 :group 'org-progress
2923 :type '(choice
2924 (const :tag "No logging" nil)
2925 (const :tag "Record timestamp" time)
2926 (const :tag "Record timestamp with note." note)))
2928 (defcustom org-log-redeadline nil
2929 "Information to record when the deadline date of a tasks is modified.
2931 Possible values are:
2933 nil Don't add anything, just change the date
2934 time Add a time stamp to the task
2935 note Prompt for a note and add it with template `org-log-note-headings'
2937 This option can also be set with on a per-file-basis with
2939 #+STARTUP: nologredeadline
2940 #+STARTUP: logredeadline
2941 #+STARTUP: lognoteredeadline
2943 You can have local logging settings for a subtree by setting the LOGGING
2944 property to one or more of these keywords."
2945 :group 'org-todo
2946 :group 'org-progress
2947 :type '(choice
2948 (const :tag "No logging" nil)
2949 (const :tag "Record timestamp" time)
2950 (const :tag "Record timestamp with note." note)))
2952 (defcustom org-log-note-clock-out nil
2953 "Non-nil means record a note when clocking out of an item.
2954 This can also be configured on a per-file basis by adding one of
2955 the following lines anywhere in the buffer:
2957 #+STARTUP: lognoteclock-out
2958 #+STARTUP: nolognoteclock-out"
2959 :group 'org-todo
2960 :group 'org-progress
2961 :type 'boolean)
2963 (defcustom org-log-done-with-time t
2964 "Non-nil means the CLOSED time stamp will contain date and time.
2965 When nil, only the date will be recorded."
2966 :group 'org-progress
2967 :type 'boolean)
2969 (defcustom org-log-note-headings
2970 '((done . "CLOSING NOTE %t")
2971 (state . "State %-12s from %-12S %t")
2972 (note . "Note taken on %t")
2973 (reschedule . "Rescheduled from %S on %t")
2974 (delschedule . "Not scheduled, was %S on %t")
2975 (redeadline . "New deadline from %S on %t")
2976 (deldeadline . "Removed deadline, was %S on %t")
2977 (refile . "Refiled on %t")
2978 (clock-out . ""))
2979 "Headings for notes added to entries.
2981 The value is an alist, with the car being a symbol indicating the
2982 note context, and the cdr is the heading to be used. The heading
2983 may also be the empty string. The following placeholders can be
2984 used:
2986 %t a time stamp.
2987 %T an active time stamp instead the default inactive one
2988 %d a short-format time stamp.
2989 %D an active short-format time stamp.
2990 %s the new TODO state or time stamp (inactive), in double quotes.
2991 %S the old TODO state or time stamp (inactive), in double quotes.
2992 %u the user name.
2993 %U full user name.
2995 In fact, it is not a good idea to change the `state' entry,
2996 because Agenda Log mode depends on the format of these entries."
2997 :group 'org-todo
2998 :group 'org-progress
2999 :type '(list :greedy t
3000 (cons (const :tag "Heading when closing an item" done) string)
3001 (cons (const :tag
3002 "Heading when changing todo state (todo sequence only)"
3003 state) string)
3004 (cons (const :tag "Heading when just taking a note" note) string)
3005 (cons (const :tag "Heading when rescheduling" reschedule) string)
3006 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3007 (cons (const :tag "Heading when changing deadline" redeadline) string)
3008 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3009 (cons (const :tag "Heading when refiling" refile) string)
3010 (cons (const :tag "Heading when clocking out" clock-out) string)))
3012 (unless (assq 'note org-log-note-headings)
3013 (push '(note . "%t") org-log-note-headings))
3015 (defcustom org-log-into-drawer nil
3016 "Non-nil means insert state change notes and time stamps into a drawer.
3017 When nil, state changes notes will be inserted after the headline and
3018 any scheduling and clock lines, but not inside a drawer.
3020 The value of this variable should be the name of the drawer to use.
3021 LOGBOOK is proposed as the default drawer for this purpose, you can
3022 also set this to a string to define the drawer of your choice.
3024 A value of t is also allowed, representing \"LOGBOOK\".
3026 A value of t or nil can also be set with on a per-file-basis with
3028 #+STARTUP: logdrawer
3029 #+STARTUP: nologdrawer
3031 If this variable is set, `org-log-state-notes-insert-after-drawers'
3032 will be ignored.
3034 You can set the property LOG_INTO_DRAWER to overrule this setting for
3035 a subtree.
3037 Do not check directly this variable in a Lisp program. Call
3038 function `org-log-into-drawer' instead."
3039 :group 'org-todo
3040 :group 'org-progress
3041 :type '(choice
3042 (const :tag "Not into a drawer" nil)
3043 (const :tag "LOGBOOK" t)
3044 (string :tag "Other")))
3046 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3048 (defun org-log-into-drawer ()
3049 "Name of the log drawer, as a string, or nil.
3050 This is the value of `org-log-into-drawer'. However, if the
3051 current entry has or inherits a LOG_INTO_DRAWER property, it will
3052 be used instead of the default value."
3053 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3054 (cond ((equal p "nil") nil)
3055 ((equal p "t") "LOGBOOK")
3056 ((stringp p) p)
3057 (p "LOGBOOK")
3058 ((stringp org-log-into-drawer) org-log-into-drawer)
3059 (org-log-into-drawer "LOGBOOK"))))
3061 (defcustom org-log-state-notes-insert-after-drawers nil
3062 "Non-nil means insert state change notes after any drawers in entry.
3063 Only the drawers that *immediately* follow the headline and the
3064 deadline/scheduled line are skipped.
3065 When nil, insert notes right after the heading and perhaps the line
3066 with deadline/scheduling if present.
3068 This variable will have no effect if `org-log-into-drawer' is
3069 set."
3070 :group 'org-todo
3071 :group 'org-progress
3072 :type 'boolean)
3074 (defcustom org-log-states-order-reversed t
3075 "Non-nil means the latest state note will be directly after heading.
3076 When nil, the state change notes will be ordered according to time.
3078 This option can also be set with on a per-file-basis with
3080 #+STARTUP: logstatesreversed
3081 #+STARTUP: nologstatesreversed"
3082 :group 'org-todo
3083 :group 'org-progress
3084 :type 'boolean)
3086 (defcustom org-todo-repeat-to-state nil
3087 "The TODO state to which a repeater should return the repeating task.
3088 By default this is the first task in a TODO sequence, or the previous state
3089 in a TODO_TYP set. But you can specify another task here.
3090 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3091 :group 'org-todo
3092 :version "24.1"
3093 :type '(choice (const :tag "Head of sequence" nil)
3094 (string :tag "Specific state")))
3096 (defcustom org-log-repeat 'time
3097 "Non-nil means record moving through the DONE state when triggering repeat.
3098 An auto-repeating task is immediately switched back to TODO when
3099 marked DONE. If you are not logging state changes (by adding \"@\"
3100 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3101 record a closing note, there will be no record of the task moving
3102 through DONE. This variable forces taking a note anyway.
3104 nil Don't force a record
3105 time Record a time stamp
3106 note Prompt for a note and add it with template `org-log-note-headings'
3108 This option can also be set with on a per-file-basis with
3110 #+STARTUP: nologrepeat
3111 #+STARTUP: logrepeat
3112 #+STARTUP: lognoterepeat
3114 You can have local logging settings for a subtree by setting the LOGGING
3115 property to one or more of these keywords."
3116 :group 'org-todo
3117 :group 'org-progress
3118 :type '(choice
3119 (const :tag "Don't force a record" nil)
3120 (const :tag "Force recording the DONE state" time)
3121 (const :tag "Force recording a note with the DONE state" note)))
3124 (defgroup org-priorities nil
3125 "Priorities in Org mode."
3126 :tag "Org Priorities"
3127 :group 'org-todo)
3129 (defcustom org-enable-priority-commands t
3130 "Non-nil means priority commands are active.
3131 When nil, these commands will be disabled, so that you never accidentally
3132 set a priority."
3133 :group 'org-priorities
3134 :type 'boolean)
3136 (defcustom org-highest-priority ?A
3137 "The highest priority of TODO items. A character like ?A, ?B etc.
3138 Must have a smaller ASCII number than `org-lowest-priority'."
3139 :group 'org-priorities
3140 :type 'character)
3142 (defcustom org-lowest-priority ?C
3143 "The lowest priority of TODO items. A character like ?A, ?B etc.
3144 Must have a larger ASCII number than `org-highest-priority'."
3145 :group 'org-priorities
3146 :type 'character)
3148 (defcustom org-default-priority ?B
3149 "The default priority of TODO items.
3150 This is the priority an item gets if no explicit priority is given.
3151 When starting to cycle on an empty priority the first step in the cycle
3152 depends on `org-priority-start-cycle-with-default'. The resulting first
3153 step priority must not exceed the range from `org-highest-priority' to
3154 `org-lowest-priority' which means that `org-default-priority' has to be
3155 in this range exclusive or inclusive the range boundaries. Else the
3156 first step refuses to set the default and the second will fall back
3157 to (depending on the command used) the highest or lowest priority."
3158 :group 'org-priorities
3159 :type 'character)
3161 (defcustom org-priority-start-cycle-with-default t
3162 "Non-nil means start with default priority when starting to cycle.
3163 When this is nil, the first step in the cycle will be (depending on the
3164 command used) one higher or lower than the default priority.
3165 See also `org-default-priority'."
3166 :group 'org-priorities
3167 :type 'boolean)
3169 (defcustom org-get-priority-function nil
3170 "Function to extract the priority from a string.
3171 The string is normally the headline. If this is nil Org computes the
3172 priority from the priority cookie like [#A] in the headline. It returns
3173 an integer, increasing by 1000 for each priority level.
3174 The user can set a different function here, which should take a string
3175 as an argument and return the numeric priority."
3176 :group 'org-priorities
3177 :version "24.1"
3178 :type '(choice
3179 (const nil)
3180 (function)))
3182 (defgroup org-time nil
3183 "Options concerning time stamps and deadlines in Org mode."
3184 :tag "Org Time"
3185 :group 'org)
3187 (defcustom org-time-stamp-rounding-minutes '(0 5)
3188 "Number of minutes to round time stamps to.
3189 \\<org-mode-map>\
3190 These are two values, the first applies when first creating a time stamp.
3191 The second applies when changing it with the commands `S-up' and `S-down'.
3192 When changing the time stamp, this means that it will change in steps
3193 of N minutes, as given by the second value.
3195 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3196 numbers should be factors of 60, so for example 5, 10, 15.
3198 When this is larger than 1, you can still force an exact time stamp by using
3199 a double prefix argument to a time stamp command like \
3200 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3201 and by using a prefix arg to `S-up/down' to specify the exact number
3202 of minutes to shift."
3203 :group 'org-time
3204 :get (lambda (var) ; Make sure both elements are there
3205 (if (integerp (default-value var))
3206 (list (default-value var) 5)
3207 (default-value var)))
3208 :type '(list
3209 (integer :tag "when inserting times")
3210 (integer :tag "when modifying times")))
3212 ;; Normalize old customizations of this variable.
3213 (when (integerp org-time-stamp-rounding-minutes)
3214 (setq org-time-stamp-rounding-minutes
3215 (list org-time-stamp-rounding-minutes
3216 org-time-stamp-rounding-minutes)))
3218 (defcustom org-display-custom-times nil
3219 "Non-nil means overlay custom formats over all time stamps.
3220 The formats are defined through the variable `org-time-stamp-custom-formats'.
3221 To turn this on on a per-file basis, insert anywhere in the file:
3222 #+STARTUP: customtime"
3223 :group 'org-time
3224 :set 'set-default
3225 :type 'sexp)
3226 (make-variable-buffer-local 'org-display-custom-times)
3228 (defcustom org-time-stamp-custom-formats
3229 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3230 "Custom formats for time stamps. See `format-time-string' for the syntax.
3231 These are overlaid over the default ISO format if the variable
3232 `org-display-custom-times' is set. Time like %H:%M should be at the
3233 end of the second format. The custom formats are also honored by export
3234 commands, if custom time display is turned on at the time of export."
3235 :group 'org-time
3236 :type 'sexp)
3238 (defun org-time-stamp-format (&optional long inactive)
3239 "Get the right format for a time string."
3240 (let ((f (if long (cdr org-time-stamp-formats)
3241 (car org-time-stamp-formats))))
3242 (if inactive
3243 (concat "[" (substring f 1 -1) "]")
3244 f)))
3246 (defcustom org-deadline-warning-days 14
3247 "Number of days before expiration during which a deadline becomes active.
3248 This variable governs the display in sparse trees and in the agenda.
3249 When 0 or negative, it means use this number (the absolute value of it)
3250 even if a deadline has a different individual lead time specified.
3252 Custom commands can set this variable in the options section."
3253 :group 'org-time
3254 :group 'org-agenda-daily/weekly
3255 :type 'integer)
3257 (defcustom org-scheduled-delay-days 0
3258 "Number of days before a scheduled item becomes active.
3259 This variable governs the display in sparse trees and in the agenda.
3260 The default value (i.e. 0) means: don't delay scheduled item.
3261 When negative, it means use this number (the absolute value of it)
3262 even if a scheduled item has a different individual delay time
3263 specified.
3265 Custom commands can set this variable in the options section."
3266 :group 'org-time
3267 :group 'org-agenda-daily/weekly
3268 :version "24.4"
3269 :package-version '(Org . "8.0")
3270 :type 'integer)
3272 (defcustom org-read-date-prefer-future t
3273 "Non-nil means assume future for incomplete date input from user.
3274 This affects the following situations:
3275 1. The user gives a month but not a year.
3276 For example, if it is April and you enter \"feb 2\", this will be read
3277 as Feb 2, *next* year. \"May 5\", however, will be this year.
3278 2. The user gives a day, but no month.
3279 For example, if today is the 15th, and you enter \"3\", Org will read
3280 this as the third of *next* month. However, if you enter \"17\",
3281 it will be considered as *this* month.
3283 If you set this variable to the symbol `time', then also the following
3284 will work:
3286 3. If the user gives a time.
3287 If the time is before now, it will be interpreted as tomorrow.
3289 Currently none of this works for ISO week specifications.
3291 When this option is nil, the current day, month and year will always be
3292 used as defaults.
3294 See also `org-agenda-jump-prefer-future'."
3295 :group 'org-time
3296 :type '(choice
3297 (const :tag "Never" nil)
3298 (const :tag "Check month and day" t)
3299 (const :tag "Check month, day, and time" time)))
3301 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3302 "Should the agenda jump command prefer the future for incomplete dates?
3303 The default is to do the same as configured in `org-read-date-prefer-future'.
3304 But you can also set a deviating value here.
3305 This may t or nil, or the symbol `org-read-date-prefer-future'."
3306 :group 'org-agenda
3307 :group 'org-time
3308 :version "24.1"
3309 :type '(choice
3310 (const :tag "Use org-read-date-prefer-future"
3311 org-read-date-prefer-future)
3312 (const :tag "Never" nil)
3313 (const :tag "Always" t)))
3315 (defcustom org-read-date-force-compatible-dates t
3316 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3318 Depending on the system Emacs is running on, certain dates cannot
3319 be represented with the type used internally to represent time.
3320 Dates between 1970-1-1 and 2038-1-1 can always be represented
3321 correctly. Some systems allow for earlier dates, some for later,
3322 some for both. One way to find out it to insert any date into an
3323 Org buffer, putting the cursor on the year and hitting S-up and
3324 S-down to test the range.
3326 When this variable is set to t, the date/time prompt will not let
3327 you specify dates outside the 1970-2037 range, so it is certain that
3328 these dates will work in whatever version of Emacs you are
3329 running, and also that you can move a file from one Emacs implementation
3330 to another. WHenever Org is forcing the year for you, it will display
3331 a message and beep.
3333 When this variable is nil, Org will check if the date is
3334 representable in the specific Emacs implementation you are using.
3335 If not, it will force a year, usually the current year, and beep
3336 to remind you. Currently this setting is not recommended because
3337 the likelihood that you will open your Org files in an Emacs that
3338 has limited date range is not negligible.
3340 A workaround for this problem is to use diary sexp dates for time
3341 stamps outside of this range."
3342 :group 'org-time
3343 :version "24.1"
3344 :type 'boolean)
3346 (defcustom org-read-date-display-live t
3347 "Non-nil means display current interpretation of date prompt live.
3348 This display will be in an overlay, in the minibuffer."
3349 :group 'org-time
3350 :type 'boolean)
3352 (defcustom org-read-date-popup-calendar t
3353 "Non-nil means pop up a calendar when prompting for a date.
3354 In the calendar, the date can be selected with mouse-1. However, the
3355 minibuffer will also be active, and you can simply enter the date as well.
3356 When nil, only the minibuffer will be available."
3357 :group 'org-time
3358 :type 'boolean)
3359 (defvaralias 'org-popup-calendar-for-date-prompt
3360 'org-read-date-popup-calendar)
3362 (defcustom org-extend-today-until 0
3363 "The hour when your day really ends. Must be an integer.
3364 This has influence for the following applications:
3365 - When switching the agenda to \"today\". It it is still earlier than
3366 the time given here, the day recognized as TODAY is actually yesterday.
3367 - When a date is read from the user and it is still before the time given
3368 here, the current date and time will be assumed to be yesterday, 23:59.
3369 Also, timestamps inserted in capture templates follow this rule.
3371 IMPORTANT: This is a feature whose implementation is and likely will
3372 remain incomplete. Really, it is only here because past midnight seems to
3373 be the favorite working time of John Wiegley :-)"
3374 :group 'org-time
3375 :type 'integer)
3377 (defcustom org-use-effective-time nil
3378 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3379 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3380 \"effective time\" of any timestamps between midnight and 8am will be
3381 23:59 of the previous day."
3382 :group 'org-time
3383 :version "24.1"
3384 :type 'boolean)
3386 (defcustom org-use-last-clock-out-time-as-effective-time nil
3387 "When non-nil, use the last clock out time for `org-todo'.
3388 Note that this option has precedence over the combined use of
3389 `org-use-effective-time' and `org-extend-today-until'."
3390 :group 'org-time
3391 :version "24.4"
3392 :package-version '(Org . "8.0")
3393 :type 'boolean)
3395 (defcustom org-edit-timestamp-down-means-later nil
3396 "Non-nil means S-down will increase the time in a time stamp.
3397 When nil, S-up will increase."
3398 :group 'org-time
3399 :type 'boolean)
3401 (defcustom org-calendar-follow-timestamp-change t
3402 "Non-nil means make the calendar window follow timestamp changes.
3403 When a timestamp is modified and the calendar window is visible, it will be
3404 moved to the new date."
3405 :group 'org-time
3406 :type 'boolean)
3408 (defgroup org-tags nil
3409 "Options concerning tags in Org mode."
3410 :tag "Org Tags"
3411 :group 'org)
3413 (defcustom org-tag-alist nil
3414 "Default tags available in Org files.
3416 The value of this variable is an alist. Associations either:
3418 (TAG)
3419 (TAG . SELECT)
3420 (SPECIAL)
3422 where TAG is a tag as a string, SELECT is character, used to
3423 select that tag through the fast tag selection interface, and
3424 SPECIAL is one of the following keywords: `:startgroup',
3425 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3426 `:newline'. These keywords are used to define a hierarchy of
3427 tags. See manual for details.
3429 When this variable is nil, Org mode bases tag input on what is
3430 already in the buffer. The value can be overridden locally by
3431 using a TAGS keyword, e.g.,
3433 #+TAGS: tag1 tag2
3435 See also `org-tag-persistent-alist' to sidestep this behavior."
3436 :group 'org-tags
3437 :type '(repeat
3438 (choice
3439 (cons :tag "Tag with key"
3440 (string :tag "Tag name")
3441 (character :tag "Access char"))
3442 (list :tag "Tag" (string :tag "Tag name"))
3443 (const :tag "Start radio group" (:startgroup))
3444 (const :tag "Start tag group, non distinct" (:startgrouptag))
3445 (const :tag "Group tags delimiter" (:grouptags))
3446 (const :tag "End radio group" (:endgroup))
3447 (const :tag "End tag group, non distinct" (:endgrouptag))
3448 (const :tag "New line" (:newline)))))
3450 (defcustom org-tag-persistent-alist nil
3451 "Tags always available in Org files.
3453 The value of this variable is an alist. Associations either:
3455 (TAG)
3456 (TAG . SELECT)
3457 (SPECIAL)
3459 where TAG is a tag as a string, SELECT is a character, used to
3460 select that tag through the fast tag selection interface, and
3461 SPECIAL is one of the following keywords: `:startgroup',
3462 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3463 `:newline'. These keywords are used to define a hierarchy of
3464 tags. See manual for details.
3466 Unlike to `org-tag-alist', tags defined in this variable do not
3467 depend on a local TAGS keyword. Instead, to disable these tags
3468 on a per-file basis, insert anywhere in the file:
3470 #+STARTUP: noptag"
3471 :group 'org-tags
3472 :type '(repeat
3473 (choice
3474 (cons :tag "Tag with key"
3475 (string :tag "Tag name")
3476 (character :tag "Access char"))
3477 (list :tag "Tag" (string :tag "Tag name"))
3478 (const :tag "Start radio group" (:startgroup))
3479 (const :tag "Start tag group, non distinct" (:startgrouptag))
3480 (const :tag "Group tags delimiter" (:grouptags))
3481 (const :tag "End radio group" (:endgroup))
3482 (const :tag "End tag group, non distinct" (:endgrouptag))
3483 (const :tag "New line" (:newline)))))
3485 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3486 "If non-nil, always offer completion for all tags of all agenda files.
3487 Instead of customizing this variable directly, you might want to
3488 set it locally for capture buffers, because there no list of
3489 tags in that file can be created dynamically (there are none).
3491 (add-hook \\='org-capture-mode-hook
3492 (lambda ()
3493 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3494 :group 'org-tags
3495 :version "24.1"
3496 :type 'boolean)
3498 (defvar org-file-tags nil
3499 "List of tags that can be inherited by all entries in the file.
3500 The tags will be inherited if the variable `org-use-tag-inheritance'
3501 says they should be.
3502 This variable is populated from #+FILETAGS lines.")
3504 (defcustom org-use-fast-tag-selection 'auto
3505 "Non-nil means use fast tag selection scheme.
3506 This is a special interface to select and deselect tags with single keys.
3507 When nil, fast selection is never used.
3508 When the symbol `auto', fast selection is used if and only if selection
3509 characters for tags have been configured, either through the variable
3510 `org-tag-alist' or through a #+TAGS line in the buffer.
3511 When t, fast selection is always used and selection keys are assigned
3512 automatically if necessary."
3513 :group 'org-tags
3514 :type '(choice
3515 (const :tag "Always" t)
3516 (const :tag "Never" nil)
3517 (const :tag "When selection characters are configured" auto)))
3519 (defcustom org-fast-tag-selection-single-key nil
3520 "Non-nil means fast tag selection exits after first change.
3521 When nil, you have to press RET to exit it.
3522 During fast tag selection, you can toggle this flag with `C-c'.
3523 This variable can also have the value `expert'. In this case, the window
3524 displaying the tags menu is not even shown, until you press C-c again."
3525 :group 'org-tags
3526 :type '(choice
3527 (const :tag "No" nil)
3528 (const :tag "Yes" t)
3529 (const :tag "Expert" expert)))
3531 (defvar org-fast-tag-selection-include-todo nil
3532 "Non-nil means fast tags selection interface will also offer TODO states.
3533 This is an undocumented feature, you should not rely on it.")
3535 (defcustom org-tags-column -77
3536 "The column to which tags should be indented in a headline.
3537 If this number is positive, it specifies the column. If it is negative,
3538 it means that the tags should be flushright to that column. For example,
3539 -80 works well for a normal 80 character screen.
3540 When 0, place tags directly after headline text, with only one space in
3541 between."
3542 :group 'org-tags
3543 :type 'integer)
3545 (defcustom org-auto-align-tags t
3546 "Non-nil keeps tags aligned when modifying headlines.
3547 Some operations (i.e. demoting) change the length of a headline and
3548 therefore shift the tags around. With this option turned on, after
3549 each such operation the tags are again aligned to `org-tags-column'."
3550 :group 'org-tags
3551 :type 'boolean)
3553 (defcustom org-use-tag-inheritance t
3554 "Non-nil means tags in levels apply also for sublevels.
3555 When nil, only the tags directly given in a specific line apply there.
3556 This may also be a list of tags that should be inherited, or a regexp that
3557 matches tags that should be inherited. Additional control is possible
3558 with the variable `org-tags-exclude-from-inheritance' which gives an
3559 explicit list of tags to be excluded from inheritance, even if the value of
3560 `org-use-tag-inheritance' would select it for inheritance.
3562 If this option is t, a match early-on in a tree can lead to a large
3563 number of matches in the subtree when constructing the agenda or creating
3564 a sparse tree. If you only want to see the first match in a tree during
3565 a search, check out the variable `org-tags-match-list-sublevels'."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "Not" nil)
3569 (const :tag "Always" t)
3570 (repeat :tag "Specific tags" (string :tag "Tag"))
3571 (regexp :tag "Tags matched by regexp")))
3573 (defcustom org-tags-exclude-from-inheritance nil
3574 "List of tags that should never be inherited.
3575 This is a way to exclude a few tags from inheritance. For way to do
3576 the opposite, to actively allow inheritance for selected tags,
3577 see the variable `org-use-tag-inheritance'."
3578 :group 'org-tags
3579 :type '(repeat (string :tag "Tag")))
3581 (defun org-tag-inherit-p (tag)
3582 "Check if TAG is one that should be inherited."
3583 (cond
3584 ((member tag org-tags-exclude-from-inheritance) nil)
3585 ((eq org-use-tag-inheritance t) t)
3586 ((not org-use-tag-inheritance) nil)
3587 ((stringp org-use-tag-inheritance)
3588 (string-match org-use-tag-inheritance tag))
3589 ((listp org-use-tag-inheritance)
3590 (member tag org-use-tag-inheritance))
3591 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3593 (defcustom org-tags-match-list-sublevels t
3594 "Non-nil means list also sublevels of headlines matching a search.
3595 This variable applies to tags/property searches, and also to stuck
3596 projects because this search is based on a tags match as well.
3598 When set to the symbol `indented', sublevels are indented with
3599 leading dots.
3601 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3602 the sublevels of a headline matching a tag search often also match
3603 the same search. Listing all of them can create very long lists.
3604 Setting this variable to nil causes subtrees of a match to be skipped.
3606 This variable is semi-obsolete and probably should always be true. It
3607 is better to limit inheritance to certain tags using the variables
3608 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3609 :group 'org-tags
3610 :type '(choice
3611 (const :tag "No, don't list them" nil)
3612 (const :tag "Yes, do list them" t)
3613 (const :tag "List them, indented with leading dots" indented)))
3615 (defcustom org-tags-sort-function nil
3616 "When set, tags are sorted using this function as a comparator."
3617 :group 'org-tags
3618 :type '(choice
3619 (const :tag "No sorting" nil)
3620 (const :tag "Alphabetical" string<)
3621 (const :tag "Reverse alphabetical" string>)
3622 (function :tag "Custom function" nil)))
3624 (defvar org-tags-history nil
3625 "History of minibuffer reads for tags.")
3626 (defvar org-last-tags-completion-table nil
3627 "The last used completion table for tags.")
3628 (defvar org-after-tags-change-hook nil
3629 "Hook that is run after the tags in a line have changed.")
3631 (defgroup org-properties nil
3632 "Options concerning properties in Org mode."
3633 :tag "Org Properties"
3634 :group 'org)
3636 (defcustom org-property-format "%-10s %s"
3637 "How property key/value pairs should be formatted by `indent-line'.
3638 When `indent-line' hits a property definition, it will format the line
3639 according to this format, mainly to make sure that the values are
3640 lined-up with respect to each other."
3641 :group 'org-properties
3642 :type 'string)
3644 (defcustom org-properties-postprocess-alist nil
3645 "Alist of properties and functions to adjust inserted values.
3646 Elements of this alist must be of the form
3648 ([string] [function])
3650 where [string] must be a property name and [function] must be a
3651 lambda expression: this lambda expression must take one argument,
3652 the value to adjust, and return the new value as a string.
3654 For example, this element will allow the property \"Remaining\"
3655 to be updated wrt the relation between the \"Effort\" property
3656 and the clock summary:
3658 ((\"Remaining\" (lambda(value)
3659 (let ((clocksum (org-clock-sum-current-item))
3660 (effort (org-duration-to-minutes
3661 (org-entry-get (point) \"Effort\"))))
3662 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3663 :group 'org-properties
3664 :version "24.1"
3665 :type '(alist :key-type (string :tag "Property")
3666 :value-type (function :tag "Function")))
3668 (defcustom org-use-property-inheritance nil
3669 "Non-nil means properties apply also for sublevels.
3671 This setting is chiefly used during property searches. Turning it on can
3672 cause significant overhead when doing a search, which is why it is not
3673 on by default.
3675 When nil, only the properties directly given in the current entry count.
3676 When t, every property is inherited. The value may also be a list of
3677 properties that should have inheritance, or a regular expression matching
3678 properties that should be inherited.
3680 However, note that some special properties use inheritance under special
3681 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3682 and the properties ending in \"_ALL\" when they are used as descriptor
3683 for valid values of a property.
3685 Note for programmers:
3686 When querying an entry with `org-entry-get', you can control if inheritance
3687 should be used. By default, `org-entry-get' looks only at the local
3688 properties. You can request inheritance by setting the inherit argument
3689 to t (to force inheritance) or to `selective' (to respect the setting
3690 in this variable)."
3691 :group 'org-properties
3692 :type '(choice
3693 (const :tag "Not" nil)
3694 (const :tag "Always" t)
3695 (repeat :tag "Specific properties" (string :tag "Property"))
3696 (regexp :tag "Properties matched by regexp")))
3698 (defun org-property-inherit-p (property)
3699 "Return a non-nil value if PROPERTY should be inherited."
3700 (cond
3701 ((eq org-use-property-inheritance t) t)
3702 ((not org-use-property-inheritance) nil)
3703 ((stringp org-use-property-inheritance)
3704 (string-match org-use-property-inheritance property))
3705 ((listp org-use-property-inheritance)
3706 (member-ignore-case property org-use-property-inheritance))
3707 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3709 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3710 "The default column format, if no other format has been defined.
3711 This variable can be set on the per-file basis by inserting a line
3713 #+COLUMNS: %25ITEM ....."
3714 :group 'org-properties
3715 :type 'string)
3717 (defcustom org-columns-ellipses ".."
3718 "The ellipses to be used when a field in column view is truncated.
3719 When this is the empty string, as many characters as possible are shown,
3720 but then there will be no visual indication that the field has been truncated.
3721 When this is a string of length N, the last N characters of a truncated
3722 field are replaced by this string. If the column is narrower than the
3723 ellipses string, only part of the ellipses string will be shown."
3724 :group 'org-properties
3725 :type 'string)
3727 (defconst org-global-properties-fixed
3728 '(("VISIBILITY_ALL" . "folded children content all")
3729 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3730 "List of property/value pairs that can be inherited by any entry.
3732 These are fixed values, for the preset properties. The user variable
3733 that can be used to add to this list is `org-global-properties'.
3735 The entries in this list are cons cells where the car is a property
3736 name and cdr is a string with the value. If the value represents
3737 multiple items like an \"_ALL\" property, separate the items by
3738 spaces.")
3740 (defcustom org-global-properties nil
3741 "List of property/value pairs that can be inherited by any entry.
3743 This list will be combined with the constant `org-global-properties-fixed'.
3745 The entries in this list are cons cells where the car is a property
3746 name and cdr is a string with the value.
3748 You can set buffer-local values for the same purpose in the variable
3749 `org-file-properties' this by adding lines like
3751 #+PROPERTY: NAME VALUE"
3752 :group 'org-properties
3753 :type '(repeat
3754 (cons (string :tag "Property")
3755 (string :tag "Value"))))
3757 (defvar-local org-file-properties nil
3758 "List of property/value pairs that can be inherited by any entry.
3759 Valid for the current buffer.
3760 This variable is populated from #+PROPERTY lines.")
3762 (defgroup org-agenda nil
3763 "Options concerning agenda views in Org mode."
3764 :tag "Org Agenda"
3765 :group 'org)
3767 (defvar-local org-category nil
3768 "Variable used by org files to set a category for agenda display.
3769 Such files should use a file variable to set it, for example
3771 # -*- mode: org; org-category: \"ELisp\"
3773 or contain a special line
3775 #+CATEGORY: ELisp
3777 If the file does not specify a category, then file's base name
3778 is used instead.")
3779 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3781 (defcustom org-agenda-files nil
3782 "The files to be used for agenda display.
3784 If an entry is a directory, all files in that directory that are matched
3785 by `org-agenda-file-regexp' will be part of the file list.
3787 If the value of the variable is not a list but a single file name, then
3788 the list of agenda files is actually stored and maintained in that file,
3789 one agenda file per line. In this file paths can be given relative to
3790 `org-directory'. Tilde expansion and environment variable substitution
3791 are also made.
3793 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3794 and removed with `\\[org-remove-file]'."
3795 :group 'org-agenda
3796 :type '(choice
3797 (repeat :tag "List of files and directories" file)
3798 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3800 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3801 "Regular expression to match files for `org-agenda-files'.
3802 If any element in the list in that variable contains a directory instead
3803 of a normal file, all files in that directory that are matched by this
3804 regular expression will be included."
3805 :group 'org-agenda
3806 :type 'regexp)
3808 (defcustom org-agenda-text-search-extra-files nil
3809 "List of extra files to be searched by text search commands.
3810 These files will be searched in addition to the agenda files by the
3811 commands `org-search-view' (`\\[org-agenda] s') \
3812 and `org-occur-in-agenda-files'.
3813 Note that these files will only be searched for text search commands,
3814 not for the other agenda views like todo lists, tag searches or the weekly
3815 agenda. This variable is intended to list notes and possibly archive files
3816 that should also be searched by these two commands.
3817 In fact, if the first element in the list is the symbol `agenda-archives',
3818 then all archive files of all agenda files will be added to the search
3819 scope."
3820 :group 'org-agenda
3821 :type '(set :greedy t
3822 (const :tag "Agenda Archives" agenda-archives)
3823 (repeat :inline t (file))))
3825 (defvaralias 'org-agenda-multi-occur-extra-files
3826 'org-agenda-text-search-extra-files)
3828 (defcustom org-agenda-skip-unavailable-files nil
3829 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3830 A nil value means to remove them, after a query, from the list."
3831 :group 'org-agenda
3832 :type 'boolean)
3834 (defcustom org-calendar-to-agenda-key [?c]
3835 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3836 The command `org-calendar-goto-agenda' will be bound to this key. The
3837 default is the character `c' because then `c' can be used to switch back and
3838 forth between agenda and calendar."
3839 :group 'org-agenda
3840 :type 'sexp)
3842 (defcustom org-calendar-insert-diary-entry-key [?i]
3843 "The key to be installed in `calendar-mode-map' for adding diary entries.
3844 This option is irrelevant until `org-agenda-diary-file' has been configured
3845 to point to an Org file. When that is the case, the command
3846 `org-agenda-diary-entry' will be bound to the key given here, by default
3847 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3848 if you want to continue doing this, you need to change this to a different
3849 key."
3850 :group 'org-agenda
3851 :type 'sexp)
3853 (defcustom org-agenda-diary-file 'diary-file
3854 "File to which to add new entries with the `i' key in agenda and calendar.
3855 When this is the symbol `diary-file', the functionality in the Emacs
3856 calendar will be used to add entries to the `diary-file'. But when this
3857 points to a file, `org-agenda-diary-entry' will be used instead."
3858 :group 'org-agenda
3859 :type '(choice
3860 (const :tag "The standard Emacs diary file" diary-file)
3861 (file :tag "Special Org file diary entries")))
3863 (eval-after-load "calendar"
3864 '(progn
3865 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3866 'org-calendar-goto-agenda)
3867 (add-hook 'calendar-mode-hook
3868 (lambda ()
3869 (unless (eq org-agenda-diary-file 'diary-file)
3870 (define-key calendar-mode-map
3871 org-calendar-insert-diary-entry-key
3872 'org-agenda-diary-entry))))))
3874 (defgroup org-latex nil
3875 "Options for embedding LaTeX code into Org mode."
3876 :tag "Org LaTeX"
3877 :group 'org)
3879 (defcustom org-format-latex-options
3880 '(:foreground default :background default :scale 1.0
3881 :html-foreground "Black" :html-background "Transparent"
3882 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3883 "Options for creating images from LaTeX fragments.
3884 This is a property list with the following properties:
3885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3886 `default' means use the foreground of the default face.
3887 `auto' means use the foreground from the text face.
3888 :background the background color, or \"Transparent\".
3889 `default' means use the background of the default face.
3890 `auto' means use the background from the text face.
3891 :scale a scaling factor for the size of the images, to get more pixels
3892 :html-foreground, :html-background, :html-scale
3893 the same numbers for HTML export.
3894 :matchers a list indicating which matchers should be used to
3895 find LaTeX fragments. Valid members of this list are:
3896 \"begin\" find environments
3897 \"$1\" find single characters surrounded by $.$
3898 \"$\" find math expressions surrounded by $...$
3899 \"$$\" find math expressions surrounded by $$....$$
3900 \"\\(\" find math expressions surrounded by \\(...\\)
3901 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3902 :group 'org-latex
3903 :type 'plist)
3905 (defcustom org-format-latex-signal-error t
3906 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3907 When nil, just push out a message."
3908 :group 'org-latex
3909 :version "24.1"
3910 :type 'boolean)
3912 (defcustom org-latex-to-mathml-jar-file nil
3913 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3914 Use this to specify additional executable file say a jar file.
3916 When using MathToWeb as the converter, specify the full-path to
3917 your mathtoweb.jar file."
3918 :group 'org-latex
3919 :version "24.1"
3920 :type '(choice
3921 (const :tag "None" nil)
3922 (file :tag "JAR file" :must-match t)))
3924 (defcustom org-latex-to-mathml-convert-command nil
3925 "Command to convert LaTeX fragments to MathML.
3926 Replace format-specifiers in the command as noted below and use
3927 `shell-command' to convert LaTeX to MathML.
3928 %j: Executable file in fully expanded form as specified by
3929 `org-latex-to-mathml-jar-file'.
3930 %I: Input LaTeX file in fully expanded form.
3931 %i: The latex fragment to be converted.
3932 %o: Output MathML file.
3934 This command is used by `org-create-math-formula'.
3936 When using MathToWeb as the converter, set this option to
3937 \"java -jar %j -unicode -force -df %o %I\".
3939 When using LaTeXML set this option to
3940 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3941 :group 'org-latex
3942 :version "24.1"
3943 :type '(choice
3944 (const :tag "None" nil)
3945 (string :tag "\nShell command")))
3947 (defcustom org-preview-latex-default-process 'dvipng
3948 "The default process to convert LaTeX fragments to image files.
3949 All available processes and theirs documents can be found in
3950 `org-preview-latex-process-alist', which see."
3951 :group 'org-latex
3952 :version "26.1"
3953 :package-version '(Org . "9.0")
3954 :type 'symbol)
3956 (defcustom org-preview-latex-process-alist
3957 '((dvipng
3958 :programs ("latex" "dvipng")
3959 :description "dvi > png"
3960 :message "you need to install the programs: latex and dvipng."
3961 :image-input-type "dvi"
3962 :image-output-type "png"
3963 :image-size-adjust (1.0 . 1.0)
3964 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3965 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3966 (dvisvgm
3967 :programs ("latex" "dvisvgm")
3968 :description "dvi > svg"
3969 :message "you need to install the programs: latex and dvisvgm."
3970 :use-xcolor t
3971 :image-input-type "dvi"
3972 :image-output-type "svg"
3973 :image-size-adjust (1.7 . 1.5)
3974 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3975 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3976 (imagemagick
3977 :programs ("latex" "convert")
3978 :description "pdf > png"
3979 :message "you need to install the programs: latex and imagemagick."
3980 :use-xcolor t
3981 :image-input-type "pdf"
3982 :image-output-type "png"
3983 :image-size-adjust (1.0 . 1.0)
3984 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3985 :image-converter
3986 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3987 "Definitions of external processes for LaTeX previewing.
3988 Org mode can use some external commands to generate TeX snippet's images for
3989 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3990 `org-create-formula-image' how to call them.
3992 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3993 PROPERTIES accepts the following attributes:
3995 :programs list of strings, required programs.
3996 :description string, describe the process.
3997 :message string, message it when required programs cannot be found.
3998 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3999 :image-output-type string, output file type of image converter (e.g., \"png\").
4000 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4001 deal with background and foreground color of image.
4002 Otherwise, dvipng style background and foreground color
4003 format are generated. You may then refer to them in
4004 command options with \"%F\" and \"%B\".
4005 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4006 image size showed in buffer and the cdr element is for
4007 HTML file. This option is only useful for process
4008 developers, users should use variable
4009 `org-format-latex-options' instead.
4010 :post-clean list of strings, files matched are to be cleaned up once
4011 the image is generated. When nil, the files with \".dvi\",
4012 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4013 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4014 be cleaned up.
4015 :latex-header list of strings, the LaTeX header of the snippet file.
4016 When nil, the fallback value is used instead, which is
4017 controlled by `org-format-latex-header',
4018 `org-latex-default-packages-alist' and
4019 `org-latex-packages-alist', which see.
4020 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4021 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4022 replaced with values defined below.
4023 :image-converter list of image converter commands strings. Each of them is
4024 given to the shell and supports any of the following
4025 place-holders defined below.
4027 Place-holders used by `:image-converter' and `:latex-compiler':
4029 %f input file name
4030 %b base name of input file
4031 %o base directory of input file
4032 %O absolute output file name
4034 Place-holders only used by `:image-converter':
4036 %F foreground of image
4037 %B background of image
4038 %D dpi, which is used to adjust image size by some processing commands.
4039 %S the image size scale ratio, which is used to adjust image size by some
4040 processing commands."
4041 :group 'org-latex
4042 :version "26.1"
4043 :package-version '(Org . "9.0")
4044 :type '(alist :tag "LaTeX to image backends"
4045 :value-type (plist)))
4047 (defcustom org-preview-latex-image-directory "ltximg/"
4048 "Path to store latex preview images.
4049 A relative path here creates many directories relative to the
4050 processed org files paths. An absolute path puts all preview
4051 images at the same place."
4052 :group 'org-latex
4053 :version "26.1"
4054 :package-version '(Org . "9.0")
4055 :type 'string)
4057 (defun org-format-latex-mathml-available-p ()
4058 "Return t if `org-latex-to-mathml-convert-command' is usable."
4059 (save-match-data
4060 (when (and (boundp 'org-latex-to-mathml-convert-command)
4061 org-latex-to-mathml-convert-command)
4062 (let ((executable (car (split-string
4063 org-latex-to-mathml-convert-command))))
4064 (when (executable-find executable)
4065 (if (string-match
4066 "%j" org-latex-to-mathml-convert-command)
4067 (file-readable-p org-latex-to-mathml-jar-file)
4068 t))))))
4070 (defcustom org-format-latex-header "\\documentclass{article}
4071 \\usepackage[usenames]{color}
4072 \[PACKAGES]
4073 \[DEFAULT-PACKAGES]
4074 \\pagestyle{empty} % do not remove
4075 % The settings below are copied from fullpage.sty
4076 \\setlength{\\textwidth}{\\paperwidth}
4077 \\addtolength{\\textwidth}{-3cm}
4078 \\setlength{\\oddsidemargin}{1.5cm}
4079 \\addtolength{\\oddsidemargin}{-2.54cm}
4080 \\setlength{\\evensidemargin}{\\oddsidemargin}
4081 \\setlength{\\textheight}{\\paperheight}
4082 \\addtolength{\\textheight}{-\\headheight}
4083 \\addtolength{\\textheight}{-\\headsep}
4084 \\addtolength{\\textheight}{-\\footskip}
4085 \\addtolength{\\textheight}{-3cm}
4086 \\setlength{\\topmargin}{1.5cm}
4087 \\addtolength{\\topmargin}{-2.54cm}"
4088 "The document header used for processing LaTeX fragments.
4089 It is imperative that this header make sure that no page number
4090 appears on the page. The package defined in the variables
4091 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4092 will either replace the placeholder \"[PACKAGES]\" in this
4093 header, or they will be appended."
4094 :group 'org-latex
4095 :type 'string)
4097 (defun org-set-packages-alist (var val)
4098 "Set the packages alist and make sure it has 3 elements per entry."
4099 (set var (mapcar (lambda (x)
4100 (if (and (consp x) (= (length x) 2))
4101 (list (car x) (nth 1 x) t)
4103 val)))
4105 (defun org-get-packages-alist (var)
4106 "Get the packages alist and make sure it has 3 elements per entry."
4107 (mapcar (lambda (x)
4108 (if (and (consp x) (= (length x) 2))
4109 (list (car x) (nth 1 x) t)
4111 (default-value var)))
4113 (defcustom org-latex-default-packages-alist
4114 '(("AUTO" "inputenc" t ("pdflatex"))
4115 ("T1" "fontenc" t ("pdflatex"))
4116 ("" "graphicx" t)
4117 ("" "grffile" t)
4118 ("" "longtable" nil)
4119 ("" "wrapfig" nil)
4120 ("" "rotating" nil)
4121 ("normalem" "ulem" t)
4122 ("" "amsmath" t)
4123 ("" "textcomp" t)
4124 ("" "amssymb" t)
4125 ("" "capt-of" nil)
4126 ("" "hyperref" nil))
4127 "Alist of default packages to be inserted in the header.
4129 Change this only if one of the packages here causes an
4130 incompatibility with another package you are using.
4132 The packages in this list are needed by one part or another of
4133 Org mode to function properly:
4135 - inputenc, fontenc: for basic font and character selection
4136 - graphicx: for including images
4137 - grffile: allow periods and spaces in graphics file names
4138 - longtable: For multipage tables
4139 - wrapfig: for figure placement
4140 - rotating: for sideways figures and tables
4141 - ulem: for underline and strike-through
4142 - amsmath: for subscript and superscript and math environments
4143 - textcomp, amssymb: for various symbols used
4144 for interpreting the entities in `org-entities'. You can skip
4145 some of these packages if you don't use any of their symbols.
4146 - capt-of: for captions outside of floats
4147 - hyperref: for cross references
4149 Therefore you should not modify this variable unless you know
4150 what you are doing. The one reason to change it anyway is that
4151 you might be loading some other package that conflicts with one
4152 of the default packages. Each element is either a cell or
4153 a string.
4155 A cell is of the format
4157 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4159 If SNIPPET-FLAG is non-nil, the package also needs to be included
4160 when compiling LaTeX snippets into images for inclusion into
4161 non-LaTeX output. COMPILERS is a list of compilers that should
4162 include the package, see `org-latex-compiler'. If the document
4163 compiler is not in the list, and the list is non-nil, the package
4164 will not be inserted in the final document.
4166 A string will be inserted as-is in the header of the document."
4167 :group 'org-latex
4168 :group 'org-export-latex
4169 :set 'org-set-packages-alist
4170 :get 'org-get-packages-alist
4171 :version "26.1"
4172 :package-version '(Org . "8.3")
4173 :type '(repeat
4174 (choice
4175 (list :tag "options/package pair"
4176 (string :tag "options")
4177 (string :tag "package")
4178 (boolean :tag "Snippet"))
4179 (string :tag "A line of LaTeX"))))
4181 (defcustom org-latex-packages-alist nil
4182 "Alist of packages to be inserted in every LaTeX header.
4184 These will be inserted after `org-latex-default-packages-alist'.
4185 Each element is either a cell or a string.
4187 A cell is of the format:
4189 (\"options\" \"package\" SNIPPET-FLAG)
4191 SNIPPET-FLAG, when non-nil, indicates that this package is also
4192 needed when turning LaTeX snippets into images for inclusion into
4193 non-LaTeX output.
4195 A string will be inserted as-is in the header of the document.
4197 Make sure that you only list packages here which:
4199 - you want in every file;
4200 - do not conflict with the setup in `org-format-latex-header';
4201 - do not conflict with the default packages in
4202 `org-latex-default-packages-alist'."
4203 :group 'org-latex
4204 :group 'org-export-latex
4205 :set 'org-set-packages-alist
4206 :get 'org-get-packages-alist
4207 :type '(repeat
4208 (choice
4209 (list :tag "options/package pair"
4210 (string :tag "options")
4211 (string :tag "package")
4212 (boolean :tag "Snippet"))
4213 (string :tag "A line of LaTeX"))))
4215 (defgroup org-appearance nil
4216 "Settings for Org mode appearance."
4217 :tag "Org Appearance"
4218 :group 'org)
4220 (defcustom org-level-color-stars-only nil
4221 "Non-nil means fontify only the stars in each headline.
4222 When nil, the entire headline is fontified.
4223 Changing it requires restart of `font-lock-mode' to become effective
4224 also in regions already fontified."
4225 :group 'org-appearance
4226 :type 'boolean)
4228 (defcustom org-hide-leading-stars nil
4229 "Non-nil means hide the first N-1 stars in a headline.
4230 This works by using the face `org-hide' for these stars. This
4231 face is white for a light background, and black for a dark
4232 background. You may have to customize the face `org-hide' to
4233 make this work.
4234 Changing it requires restart of `font-lock-mode' to become effective
4235 also in regions already fontified.
4236 You may also set this on a per-file basis by adding one of the following
4237 lines to the buffer:
4239 #+STARTUP: hidestars
4240 #+STARTUP: showstars"
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hidden-keywords nil
4245 "List of symbols corresponding to keywords to be hidden the org buffer.
4246 For example, a value \\='(title) for this list will make the document's title
4247 appear in the buffer without the initial #+TITLE: keyword."
4248 :group 'org-appearance
4249 :version "24.1"
4250 :type '(set (const :tag "#+AUTHOR" author)
4251 (const :tag "#+DATE" date)
4252 (const :tag "#+EMAIL" email)
4253 (const :tag "#+TITLE" title)))
4255 (defcustom org-custom-properties nil
4256 "List of properties (as strings) with a special meaning.
4257 The default use of these custom properties is to let the user
4258 hide them with `org-toggle-custom-properties-visibility'."
4259 :group 'org-properties
4260 :group 'org-appearance
4261 :version "24.3"
4262 :type '(repeat (string :tag "Property Name")))
4264 (defcustom org-fontify-done-headline nil
4265 "Non-nil means change the face of a headline if it is marked DONE.
4266 Normally, only the TODO/DONE keyword indicates the state of a headline.
4267 When this is non-nil, the headline after the keyword is set to the
4268 `org-headline-done' as an additional indication."
4269 :group 'org-appearance
4270 :type 'boolean)
4272 (defcustom org-fontify-emphasized-text t
4273 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4274 Changing this variable requires a restart of Emacs to take effect."
4275 :group 'org-appearance
4276 :type 'boolean)
4278 (defcustom org-fontify-whole-heading-line nil
4279 "Non-nil means fontify the whole line for headings.
4280 This is useful when setting a background color for the
4281 org-level-* faces."
4282 :group 'org-appearance
4283 :type 'boolean)
4285 (defcustom org-highlight-latex-and-related nil
4286 "Non-nil means highlight LaTeX related syntax in the buffer.
4287 When non nil, the value should be a list containing any of the
4288 following symbols:
4289 `latex' Highlight LaTeX snippets and environments.
4290 `script' Highlight subscript and superscript.
4291 `entities' Highlight entities."
4292 :group 'org-appearance
4293 :version "24.4"
4294 :package-version '(Org . "8.0")
4295 :type '(choice
4296 (const :tag "No highlighting" nil)
4297 (set :greedy t :tag "Highlight"
4298 (const :tag "LaTeX snippets and environments" latex)
4299 (const :tag "Subscript and superscript" script)
4300 (const :tag "Entities" entities))))
4302 (defcustom org-hide-emphasis-markers nil
4303 "Non-nil mean font-lock should hide the emphasis marker characters."
4304 :group 'org-appearance
4305 :type 'boolean)
4307 (defcustom org-hide-macro-markers nil
4308 "Non-nil mean font-lock should hide the brackets marking macro calls."
4309 :group 'org-appearance
4310 :type 'boolean)
4312 (defcustom org-pretty-entities nil
4313 "Non-nil means show entities as UTF8 characters.
4314 When nil, the \\name form remains in the buffer."
4315 :group 'org-appearance
4316 :version "24.1"
4317 :type 'boolean)
4319 (defcustom org-pretty-entities-include-sub-superscripts t
4320 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4321 :group 'org-appearance
4322 :version "24.1"
4323 :type 'boolean)
4325 (defvar org-emph-re nil
4326 "Regular expression for matching emphasis.
4327 After a match, the match groups contain these elements:
4328 0 The match of the full regular expression, including the characters
4329 before and after the proper match
4330 1 The character before the proper match, or empty at beginning of line
4331 2 The proper match, including the leading and trailing markers
4332 3 The leading marker like * or /, indicating the type of highlighting
4333 4 The text between the emphasis markers, not including the markers
4334 5 The character after the match, empty at the end of a line")
4336 (defvar org-verbatim-re nil
4337 "Regular expression for matching verbatim text.")
4339 (defvar org-emphasis-regexp-components) ; defined just below
4340 (defvar org-emphasis-alist) ; defined just below
4341 (defun org-set-emph-re (var val)
4342 "Set variable and compute the emphasis regular expression."
4343 (set var val)
4344 (when (and (boundp 'org-emphasis-alist)
4345 (boundp 'org-emphasis-regexp-components)
4346 org-emphasis-alist org-emphasis-regexp-components)
4347 (pcase-let*
4348 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4349 (body (if (<= nl 0) body
4350 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4351 (template
4352 (format (concat "\\([%s]\\|^\\)" ;before markers
4353 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4354 "\\([%s]\\|$\\)") ;after markers
4355 pre border border body border post)))
4356 (setq org-emph-re (format template "*/_+"))
4357 (setq org-verbatim-re (format template "=~")))))
4359 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4360 ;; set this option proved cumbersome. See this message/thread:
4361 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4362 (defvar org-emphasis-regexp-components
4363 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4364 "Components used to build the regular expression for emphasis.
4365 This is a list with five entries. Terminology: In an emphasis string
4366 like \" *strong word* \", we call the initial space PREMATCH, the final
4367 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4368 and \"trong wor\" is the body. The different components in this variable
4369 specify what is allowed/forbidden in each part:
4371 pre Chars allowed as prematch. Beginning of line will be allowed too.
4372 post Chars allowed as postmatch. End of line will be allowed too.
4373 border The chars *forbidden* as border characters.
4374 body-regexp A regexp like \".\" to match a body character. Don't use
4375 non-shy groups here, and don't allow newline here.
4376 newline The maximum number of newlines allowed in an emphasis exp.
4378 You need to reload Org or to restart Emacs after customizing this.")
4380 (defcustom org-emphasis-alist
4381 '(("*" bold)
4382 ("/" italic)
4383 ("_" underline)
4384 ("=" org-verbatim verbatim)
4385 ("~" org-code verbatim)
4386 ("+" (:strike-through t)))
4387 "Alist of characters and faces to emphasize text.
4388 Text starting and ending with a special character will be emphasized,
4389 for example *bold*, _underlined_ and /italic/. This variable sets the
4390 marker characters and the face to be used by font-lock for highlighting
4391 in Org buffers.
4393 You need to reload Org or to restart Emacs after customizing this."
4394 :group 'org-appearance
4395 :set 'org-set-emph-re
4396 :version "24.4"
4397 :package-version '(Org . "8.0")
4398 :type '(repeat
4399 (list
4400 (string :tag "Marker character")
4401 (choice
4402 (face :tag "Font-lock-face")
4403 (plist :tag "Face property list"))
4404 (option (const verbatim)))))
4406 (defvar org-protecting-blocks '("src" "example" "export")
4407 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4408 This is needed for font-lock setup.")
4410 ;;; Functions and variables from their packages
4411 ;; Declared here to avoid compiler warnings
4412 (defvar mark-active)
4414 ;; Various packages
4415 (declare-function calc-eval "calc" (str &optional separator &rest args))
4416 (declare-function calendar-forward-day "cal-move" (arg))
4417 (declare-function calendar-goto-date "cal-move" (date))
4418 (declare-function calendar-goto-today "cal-move" ())
4419 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4420 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4421 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4422 (declare-function cdlatex-tab "ext:cdlatex" ())
4423 (declare-function dired-get-filename
4424 "dired"
4425 (&optional localp no-error-if-not-filep))
4426 (declare-function iswitchb-read-buffer
4427 "iswitchb"
4428 (prompt &optional
4429 default require-match _predicate start matches-set))
4430 (declare-function org-agenda-change-all-lines
4431 "org-agenda"
4432 (newhead hdmarker &optional fixface just-this))
4433 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4434 "org-agenda"
4435 (&optional end))
4436 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4437 (declare-function org-agenda-format-item
4438 "org-agenda"
4439 (extra txt &optional level category tags dotime
4440 remove-re habitp))
4441 (declare-function org-agenda-maybe-redo "org-agenda" ())
4442 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4443 (declare-function org-agenda-save-markers-for-cut-and-paste
4444 "org-agenda"
4445 (beg end))
4446 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4447 (declare-function org-agenda-skip "org-agenda" ())
4448 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4449 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4450 (declare-function org-indent-mode "org-indent" (&optional arg))
4451 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4452 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4453 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4454 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4455 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4456 (declare-function parse-time-string "parse-time" (string))
4457 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4459 (defvar align-mode-rules-list)
4460 (defvar calc-embedded-close-formula)
4461 (defvar calc-embedded-open-formula)
4462 (defvar calc-embedded-open-mode)
4463 (defvar font-lock-unfontify-region-function)
4464 (defvar iswitchb-temp-buflist)
4465 (defvar org-agenda-tags-todo-honor-ignore-options)
4466 (defvar remember-data-file)
4467 (defvar texmathp-why)
4469 ;;;###autoload
4470 (defun turn-on-orgtbl ()
4471 "Unconditionally turn on `orgtbl-mode'."
4472 (require 'org-table)
4473 (orgtbl-mode 1))
4475 (defun org-at-table-p (&optional table-type)
4476 "Non-nil if the cursor is inside an Org table.
4477 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4478 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4479 (or (not (derived-mode-p 'org-mode))
4480 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4481 (and e (or table-type
4482 (eq 'org (org-element-property :type e))))))))
4484 (defun org-at-table.el-p ()
4485 "Non-nil when point is at a table.el table."
4486 (and (org-match-line "[ \t]*[|+]")
4487 (let ((element (org-element-at-point)))
4488 (and (eq (org-element-type element) 'table)
4489 (eq (org-element-property :type element) 'table.el)))))
4491 (defun org-at-table-hline-p ()
4492 "Non-nil when point is inside a hline in a table.
4493 Assume point is already in a table."
4494 (org-match-line org-table-hline-regexp))
4496 (defun org-table-map-tables (function &optional quietly)
4497 "Apply FUNCTION to the start of all tables in the buffer."
4498 (org-with-wide-buffer
4499 (goto-char (point-min))
4500 (while (re-search-forward org-table-any-line-regexp nil t)
4501 (unless quietly
4502 (message "Mapping tables: %d%%"
4503 (floor (* 100.0 (point)) (buffer-size))))
4504 (beginning-of-line 1)
4505 (when (and (looking-at org-table-line-regexp)
4506 ;; Exclude tables in src/example/verbatim/clocktable blocks
4507 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4508 (save-excursion (funcall function))
4509 (or (looking-at org-table-line-regexp)
4510 (forward-char 1)))
4511 (re-search-forward org-table-any-border-regexp nil 1)))
4512 (unless quietly (message "Mapping tables: done")))
4514 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4515 (declare-function org-clock-update-mode-line "org-clock" ())
4516 (declare-function org-resolve-clocks "org-clock"
4517 (&optional also-non-dangling-p prompt last-valid))
4519 (defun org-at-TBLFM-p (&optional pos)
4520 "Non-nil when point (or POS) is in #+TBLFM line."
4521 (save-excursion
4522 (goto-char (or pos (point)))
4523 (beginning-of-line)
4524 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4525 (eq (org-element-type (org-element-at-point)) 'table))))
4527 (defvar org-clock-start-time)
4528 (defvar org-clock-marker (make-marker)
4529 "Marker recording the last clock-in.")
4530 (defvar org-clock-hd-marker (make-marker)
4531 "Marker recording the last clock-in, but the headline position.")
4532 (defvar org-clock-heading ""
4533 "The heading of the current clock entry.")
4534 (defun org-clock-is-active ()
4535 "Return the buffer where the clock is currently running.
4536 Return nil if no clock is running."
4537 (marker-buffer org-clock-marker))
4539 (defun org-check-running-clock ()
4540 "Check if the current buffer contains the running clock.
4541 If yes, offer to stop it and to save the buffer with the changes."
4542 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4543 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4544 (buffer-name))))
4545 (org-clock-out)
4546 (when (y-or-n-p "Save changed buffer?")
4547 (save-buffer))))
4549 (defun org-clocktable-try-shift (dir n)
4550 "Check if this line starts a clock table, if yes, shift the time block."
4551 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4552 (org-clocktable-shift dir n)))
4554 ;;;###autoload
4555 (defun org-clock-persistence-insinuate ()
4556 "Set up hooks for clock persistence."
4557 (require 'org-clock)
4558 (add-hook 'org-mode-hook 'org-clock-load)
4559 (add-hook 'kill-emacs-hook 'org-clock-save))
4561 (defgroup org-archive nil
4562 "Options concerning archiving in Org mode."
4563 :tag "Org Archive"
4564 :group 'org-structure)
4566 (defcustom org-archive-location "%s_archive::"
4567 "The location where subtrees should be archived.
4569 The value of this variable is a string, consisting of two parts,
4570 separated by a double-colon. The first part is a filename and
4571 the second part is a headline.
4573 When the filename is omitted, archiving happens in the same file.
4574 %s in the filename will be replaced by the current file
4575 name (without the directory part). Archiving to a different file
4576 is useful to keep archived entries from contributing to the
4577 Org Agenda.
4579 The archived entries will be filed as subtrees of the specified
4580 headline. When the headline is omitted, the subtrees are simply
4581 filed away at the end of the file, as top-level entries. Also in
4582 the heading you can use %s to represent the file name, this can be
4583 useful when using the same archive for a number of different files.
4585 Here are a few examples:
4586 \"%s_archive::\"
4587 If the current file is Projects.org, archive in file
4588 Projects.org_archive, as top-level trees. This is the default.
4590 \"::* Archived Tasks\"
4591 Archive in the current file, under the top-level headline
4592 \"* Archived Tasks\".
4594 \"~/org/archive.org::\"
4595 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4597 \"~/org/archive.org::* From %s\"
4598 Archive in file ~/org/archive.org (absolute path), under headlines
4599 \"From FILENAME\" where file name is the current file name.
4601 \"~/org/datetree.org::datetree/* Finished Tasks\"
4602 The \"datetree/\" string is special, signifying to archive
4603 items to the datetree. Items are placed in either the CLOSED
4604 date of the item, or the current date if there is no CLOSED date.
4605 The heading will be a subentry to the current date. There doesn't
4606 need to be a heading, but there always needs to be a slash after
4607 datetree. For example, to store archived items directly in the
4608 datetree, use \"~/org/datetree.org::datetree/\".
4610 \"basement::** Finished Tasks\"
4611 Archive in file ./basement (relative path), as level 3 trees
4612 below the level 2 heading \"** Finished Tasks\".
4614 You may set this option on a per-file basis by adding to the buffer a
4615 line like
4617 #+ARCHIVE: basement::** Finished Tasks
4619 You may also define it locally for a subtree by setting an ARCHIVE property
4620 in the entry. If such a property is found in an entry, or anywhere up
4621 the hierarchy, it will be used."
4622 :group 'org-archive
4623 :type 'string)
4625 (defcustom org-agenda-skip-archived-trees t
4626 "Non-nil means the agenda will skip any items located in archived trees.
4627 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4628 variable is no longer recommended, you should leave it at the value t.
4629 Instead, use the key `v' to cycle the archives-mode in the agenda."
4630 :group 'org-archive
4631 :group 'org-agenda-skip
4632 :type 'boolean)
4634 (defcustom org-columns-skip-archived-trees t
4635 "Non-nil means ignore archived trees when creating column view."
4636 :group 'org-archive
4637 :group 'org-properties
4638 :type 'boolean)
4640 (defcustom org-cycle-open-archived-trees nil
4641 "Non-nil means `org-cycle' will open archived trees.
4642 An archived tree is a tree marked with the tag ARCHIVE.
4643 When nil, archived trees will stay folded. You can still open them with
4644 normal outline commands like `show-all', but not with the cycling commands."
4645 :group 'org-archive
4646 :group 'org-cycle
4647 :type 'boolean)
4649 (defcustom org-sparse-tree-open-archived-trees nil
4650 "Non-nil means sparse tree construction shows matches in archived trees.
4651 When nil, matches in these trees are highlighted, but the trees are kept in
4652 collapsed state."
4653 :group 'org-archive
4654 :group 'org-sparse-trees
4655 :type 'boolean)
4657 (defcustom org-sparse-tree-default-date-type nil
4658 "The default date type when building a sparse tree.
4659 When this is nil, a date is a scheduled or a deadline timestamp.
4660 Otherwise, these types are allowed:
4662 all: all timestamps
4663 active: only active timestamps (<...>)
4664 inactive: only inactive timestamps ([...])
4665 scheduled: only scheduled timestamps
4666 deadline: only deadline timestamps"
4667 :type '(choice (const :tag "Scheduled or deadline" nil)
4668 (const :tag "All timestamps" all)
4669 (const :tag "Only active timestamps" active)
4670 (const :tag "Only inactive timestamps" inactive)
4671 (const :tag "Only scheduled timestamps" scheduled)
4672 (const :tag "Only deadline timestamps" deadline)
4673 (const :tag "Only closed timestamps" closed))
4674 :version "26.1"
4675 :package-version '(Org . "8.3")
4676 :group 'org-sparse-trees)
4678 (defun org-cycle-hide-archived-subtrees (state)
4679 "Re-hide all archived subtrees after a visibility state change.
4680 STATE should be one of the symbols listed in the docstring of
4681 `org-cycle-hook'."
4682 (when (and (not org-cycle-open-archived-trees)
4683 (not (memq state '(overview folded))))
4684 (save-excursion
4685 (let* ((globalp (memq state '(contents all)))
4686 (beg (if globalp (point-min) (point)))
4687 (end (if globalp (point-max) (org-end-of-subtree t))))
4688 (org-hide-archived-subtrees beg end)
4689 (goto-char beg)
4690 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4691 (message "%s" (substitute-command-keys
4692 "Subtree is archived and stays closed. Use \
4693 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4695 (defun org-force-cycle-archived ()
4696 "Cycle subtree even if it is archived."
4697 (interactive)
4698 (setq this-command 'org-cycle)
4699 (let ((org-cycle-open-archived-trees t))
4700 (call-interactively 'org-cycle)))
4702 (defun org-hide-archived-subtrees (beg end)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (org-with-wide-buffer
4705 (let ((case-fold-search nil)
4706 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4707 (goto-char beg)
4708 ;; Include headline point is currently on.
4709 (beginning-of-line)
4710 (while (and (< (point) end) (re-search-forward re end t))
4711 (when (member org-archive-tag (org-get-tags))
4712 (org-flag-subtree t)
4713 (org-end-of-subtree t))))))
4715 (declare-function outline-end-of-heading "outline" ())
4716 (declare-function outline-flag-region "outline" (from to flag))
4717 (defun org-flag-subtree (flag)
4718 (save-excursion
4719 (org-back-to-heading t)
4720 (outline-end-of-heading)
4721 (outline-flag-region (point)
4722 (progn (org-end-of-subtree t) (point))
4723 flag)))
4725 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4727 ;; Declare Column View Code
4729 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4730 (declare-function org-columns-compute "org-colview" (property))
4732 ;; Declare ID code
4734 (declare-function org-id-store-link "org-id")
4735 (declare-function org-id-locations-load "org-id")
4736 (declare-function org-id-locations-save "org-id")
4737 (defvar org-id-track-globally)
4739 ;;; Variables for pre-computed regular expressions, all buffer local
4741 (defvar-local org-todo-regexp nil
4742 "Matches any of the TODO state keywords.
4743 Since TODO keywords are case-sensitive, `case-fold-search' is
4744 expected to be bound to nil when matching against this regexp.")
4746 (defvar-local org-not-done-regexp nil
4747 "Matches any of the TODO state keywords except the last one.
4748 Since TODO keywords are case-sensitive, `case-fold-search' is
4749 expected to be bound to nil when matching against this regexp.")
4751 (defvar-local org-not-done-heading-regexp nil
4752 "Matches a TODO headline that is not done.
4753 Since TODO keywords are case-sensitive, `case-fold-search' is
4754 expected to be bound to nil when matching against this regexp.")
4756 (defvar-local org-todo-line-regexp nil
4757 "Matches a headline and puts TODO state into group 2 if present.
4758 Since TODO keywords are case-sensitive, `case-fold-search' is
4759 expected to be bound to nil when matching against this regexp.")
4761 (defvar-local org-complex-heading-regexp nil
4762 "Matches a headline and puts everything into groups:
4764 group 1: Stars
4765 group 2: The TODO keyword, maybe
4766 group 3: Priority cookie
4767 group 4: True headline
4768 group 5: Tags
4770 Since TODO keywords are case-sensitive, `case-fold-search' is
4771 expected to be bound to nil when matching against this regexp.")
4773 (defvar-local org-complex-heading-regexp-format nil
4774 "Printf format to make regexp to match an exact headline.
4775 This regexp will match the headline of any node which has the
4776 exact headline text that is put into the format, but may have any
4777 TODO state, priority and tags.")
4779 (defvar-local org-todo-line-tags-regexp nil
4780 "Matches a headline and puts TODO state into group 2 if present.
4781 Also put tags into group 4 if tags are present.")
4783 (defconst org-plain-time-of-day-regexp
4784 (concat
4785 "\\(\\<[012]?[0-9]"
4786 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4787 "\\(--?"
4788 "\\(\\<[012]?[0-9]"
4789 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4790 "\\)?")
4791 "Regular expression to match a plain time or time range.
4792 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4793 groups carry important information:
4794 0 the full match
4795 1 the first time, range or not
4796 8 the second time, if it is a range.")
4798 (defconst org-plain-time-extension-regexp
4799 (concat
4800 "\\(\\<[012]?[0-9]"
4801 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4802 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4803 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4804 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4805 groups carry important information:
4806 0 the full match
4807 7 hours of duration
4808 9 minutes of duration")
4810 (defconst org-stamp-time-of-day-regexp
4811 (concat
4812 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4813 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4814 "\\(--?"
4815 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4816 "Regular expression to match a timestamp time or time range.
4817 After a match, the following groups carry important information:
4818 0 the full match
4819 1 date plus weekday, for back referencing to make sure both times are on the same day
4820 2 the first time, range or not
4821 4 the second time, if it is a range.")
4823 (defconst org-startup-options
4824 '(("fold" org-startup-folded t)
4825 ("overview" org-startup-folded t)
4826 ("nofold" org-startup-folded nil)
4827 ("showall" org-startup-folded nil)
4828 ("showeverything" org-startup-folded showeverything)
4829 ("content" org-startup-folded content)
4830 ("indent" org-startup-indented t)
4831 ("noindent" org-startup-indented nil)
4832 ("hidestars" org-hide-leading-stars t)
4833 ("showstars" org-hide-leading-stars nil)
4834 ("odd" org-odd-levels-only t)
4835 ("oddeven" org-odd-levels-only nil)
4836 ("align" org-startup-align-all-tables t)
4837 ("noalign" org-startup-align-all-tables nil)
4838 ("shrink" org-startup-shrink-all-tables t)
4839 ("inlineimages" org-startup-with-inline-images t)
4840 ("noinlineimages" org-startup-with-inline-images nil)
4841 ("latexpreview" org-startup-with-latex-preview t)
4842 ("nolatexpreview" org-startup-with-latex-preview nil)
4843 ("customtime" org-display-custom-times t)
4844 ("logdone" org-log-done time)
4845 ("lognotedone" org-log-done note)
4846 ("nologdone" org-log-done nil)
4847 ("lognoteclock-out" org-log-note-clock-out t)
4848 ("nolognoteclock-out" org-log-note-clock-out nil)
4849 ("logrepeat" org-log-repeat state)
4850 ("lognoterepeat" org-log-repeat note)
4851 ("logdrawer" org-log-into-drawer t)
4852 ("nologdrawer" org-log-into-drawer nil)
4853 ("logstatesreversed" org-log-states-order-reversed t)
4854 ("nologstatesreversed" org-log-states-order-reversed nil)
4855 ("nologrepeat" org-log-repeat nil)
4856 ("logreschedule" org-log-reschedule time)
4857 ("lognotereschedule" org-log-reschedule note)
4858 ("nologreschedule" org-log-reschedule nil)
4859 ("logredeadline" org-log-redeadline time)
4860 ("lognoteredeadline" org-log-redeadline note)
4861 ("nologredeadline" org-log-redeadline nil)
4862 ("logrefile" org-log-refile time)
4863 ("lognoterefile" org-log-refile note)
4864 ("nologrefile" org-log-refile nil)
4865 ("fninline" org-footnote-define-inline t)
4866 ("nofninline" org-footnote-define-inline nil)
4867 ("fnlocal" org-footnote-section nil)
4868 ("fnauto" org-footnote-auto-label t)
4869 ("fnprompt" org-footnote-auto-label nil)
4870 ("fnconfirm" org-footnote-auto-label confirm)
4871 ("fnplain" org-footnote-auto-label plain)
4872 ("fnadjust" org-footnote-auto-adjust t)
4873 ("nofnadjust" org-footnote-auto-adjust nil)
4874 ("constcgs" constants-unit-system cgs)
4875 ("constSI" constants-unit-system SI)
4876 ("noptag" org-tag-persistent-alist nil)
4877 ("hideblocks" org-hide-block-startup t)
4878 ("nohideblocks" org-hide-block-startup nil)
4879 ("beamer" org-startup-with-beamer-mode t)
4880 ("entitiespretty" org-pretty-entities t)
4881 ("entitiesplain" org-pretty-entities nil))
4882 "Variable associated with STARTUP options for org-mode.
4883 Each element is a list of three items: the startup options (as written
4884 in the #+STARTUP line), the corresponding variable, and the value to set
4885 this variable to if the option is found. An optional forth element PUSH
4886 means to push this value onto the list in the variable.")
4888 (defcustom org-group-tags t
4889 "When non-nil (the default), use group tags.
4890 This can be turned on/off through `org-toggle-tags-groups'."
4891 :group 'org-tags
4892 :group 'org-startup
4893 :type 'boolean)
4895 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4897 (defun org-toggle-tags-groups ()
4898 "Toggle support for group tags.
4899 Support for group tags is controlled by the option
4900 `org-group-tags', which is non-nil by default."
4901 (interactive)
4902 (setq org-group-tags (not org-group-tags))
4903 (cond ((and (derived-mode-p 'org-agenda-mode)
4904 org-group-tags)
4905 (org-agenda-redo))
4906 ((derived-mode-p 'org-mode)
4907 (let ((org-inhibit-startup t)) (org-mode))))
4908 (message "Groups tags support has been turned %s"
4909 (if org-group-tags "on" "off")))
4911 (defun org-set-regexps-and-options (&optional tags-only)
4912 "Precompute regular expressions used in the current buffer.
4913 When optional argument TAGS-ONLY is non-nil, only compute tags
4914 related expressions."
4915 (when (derived-mode-p 'org-mode)
4916 (let ((alist (org--setup-collect-keywords
4917 (org-make-options-regexp
4918 (append '("FILETAGS" "TAGS" "SETUPFILE")
4919 (and (not tags-only)
4920 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4921 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4922 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4923 ;; Startup options. Get this early since it does change
4924 ;; behavior for other options (e.g., tags).
4925 (let ((startup (cdr (assq 'startup alist))))
4926 (dolist (option startup)
4927 (let ((entry (assoc-string option org-startup-options t)))
4928 (when entry
4929 (let ((var (nth 1 entry))
4930 (val (nth 2 entry)))
4931 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4932 (unless (listp (symbol-value var))
4933 (set (make-local-variable var) nil))
4934 (add-to-list var val)))))))
4935 (setq-local org-file-tags
4936 (mapcar #'org-add-prop-inherited
4937 (cdr (assq 'filetags alist))))
4938 (setq org-current-tag-alist
4939 (append org-tag-persistent-alist
4940 (let ((tags (cdr (assq 'tags alist))))
4941 (if tags (org-tag-string-to-alist tags)
4942 org-tag-alist))))
4943 (setq org-tag-groups-alist
4944 (org-tag-alist-to-groups org-current-tag-alist))
4945 (unless tags-only
4946 ;; File properties.
4947 (setq-local org-file-properties (cdr (assq 'property alist)))
4948 ;; Archive location.
4949 (let ((archive (cdr (assq 'archive alist))))
4950 (when archive (setq-local org-archive-location archive)))
4951 ;; Category.
4952 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4953 (when cat
4954 (setq-local org-category (intern cat))
4955 (setq-local org-file-properties
4956 (org--update-property-plist
4957 "CATEGORY" cat org-file-properties))))
4958 ;; Columns.
4959 (let ((column (cdr (assq 'columns alist))))
4960 (when column (setq-local org-columns-default-format column)))
4961 ;; Constants.
4962 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4963 ;; Link abbreviations.
4964 (let ((links (cdr (assq 'link alist))))
4965 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4966 ;; Priorities.
4967 (let ((priorities (cdr (assq 'priorities alist))))
4968 (when priorities
4969 (setq-local org-highest-priority (nth 0 priorities))
4970 (setq-local org-lowest-priority (nth 1 priorities))
4971 (setq-local org-default-priority (nth 2 priorities))))
4972 ;; Scripts.
4973 (let ((scripts (assq 'scripts alist)))
4974 (when scripts
4975 (setq-local org-use-sub-superscripts (cdr scripts))))
4976 ;; TODO keywords.
4977 (setq-local org-todo-kwd-alist nil)
4978 (setq-local org-todo-key-alist nil)
4979 (setq-local org-todo-key-trigger nil)
4980 (setq-local org-todo-keywords-1 nil)
4981 (setq-local org-done-keywords nil)
4982 (setq-local org-todo-heads nil)
4983 (setq-local org-todo-sets nil)
4984 (setq-local org-todo-log-states nil)
4985 (let ((todo-sequences
4986 (or (nreverse (cdr (assq 'todo alist)))
4987 (let ((d (default-value 'org-todo-keywords)))
4988 (if (not (stringp (car d))) d
4989 ;; XXX: Backward compatibility code.
4990 (list (cons org-todo-interpretation d)))))))
4991 (dolist (sequence todo-sequences)
4992 (let* ((sequence (or (run-hook-with-args-until-success
4993 'org-todo-setup-filter-hook sequence)
4994 sequence))
4995 (sequence-type (car sequence))
4996 (keywords (cdr sequence))
4997 (sep (member "|" keywords))
4998 names alist)
4999 (dolist (k (remove "|" keywords))
5000 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5002 (error "Invalid TODO keyword %s" k))
5003 (let ((name (match-string 1 k))
5004 (key (match-string 2 k))
5005 (log (org-extract-log-state-settings k)))
5006 (push name names)
5007 (push (cons name (and key (string-to-char key))) alist)
5008 (when log (push log org-todo-log-states))))
5009 (let* ((names (nreverse names))
5010 (done (if sep (org-remove-keyword-keys (cdr sep))
5011 (last names)))
5012 (head (car names))
5013 (tail (list sequence-type head (car done) (org-last done))))
5014 (add-to-list 'org-todo-heads head 'append)
5015 (push names org-todo-sets)
5016 (setq org-done-keywords (append org-done-keywords done nil))
5017 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5018 (setq org-todo-key-alist
5019 (append org-todo-key-alist
5020 (and alist
5021 (append '((:startgroup))
5022 (nreverse alist)
5023 '((:endgroup))))))
5024 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5025 (setq org-todo-sets (nreverse org-todo-sets)
5026 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5027 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5028 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5029 ;; Compute the regular expressions and other local variables.
5030 ;; Using `org-outline-regexp-bol' would complicate them much,
5031 ;; because of the fixed white space at the end of that string.
5032 (unless org-done-keywords
5033 (setq org-done-keywords
5034 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5035 (setq org-not-done-keywords
5036 (org-delete-all org-done-keywords
5037 (copy-sequence org-todo-keywords-1))
5038 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5039 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5040 org-not-done-heading-regexp
5041 (format org-heading-keyword-regexp-format org-not-done-regexp)
5042 org-todo-line-regexp
5043 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5044 org-complex-heading-regexp
5045 (concat "^\\(\\*+\\)"
5046 "\\(?: +" org-todo-regexp "\\)?"
5047 "\\(?: +\\(\\[#.\\]\\)\\)?"
5048 "\\(?: +\\(.*?\\)\\)??"
5049 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5050 "[ \t]*$")
5051 org-complex-heading-regexp-format
5052 (concat "^\\(\\*+\\)"
5053 "\\(?: +" org-todo-regexp "\\)?"
5054 "\\(?: +\\(\\[#.\\]\\)\\)?"
5055 "\\(?: +"
5056 ;; Stats cookies can be stuck to body.
5057 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5058 "\\(%s\\)"
5059 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5060 "\\)"
5061 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5062 "[ \t]*$")
5063 org-todo-line-tags-regexp
5064 (concat "^\\(\\*+\\)"
5065 "\\(?: +" org-todo-regexp "\\)?"
5066 "\\(?: +\\(.*?\\)\\)??"
5067 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5068 "[ \t]*$"))
5069 (org-compute-latex-and-related-regexp)))))
5071 (defun org--setup-collect-keywords (regexp &optional files alist)
5072 "Return setup keywords values as an alist.
5074 REGEXP matches a subset of setup keywords. FILES is a list of
5075 file names already visited. It is used to avoid circular setup
5076 files. ALIST, when non-nil, is the alist computed so far.
5078 Return value contains the following keys: `archive', `category',
5079 `columns', `constants', `filetags', `link', `priorities',
5080 `property', `scripts', `startup', `tags' and `todo'."
5081 (org-with-wide-buffer
5082 (goto-char (point-min))
5083 (let ((case-fold-search t))
5084 (while (re-search-forward regexp nil t)
5085 (let ((element (org-element-at-point)))
5086 (when (eq (org-element-type element) 'keyword)
5087 (let ((key (org-element-property :key element))
5088 (value (org-element-property :value element)))
5089 (cond
5090 ((equal key "ARCHIVE")
5091 (when (org-string-nw-p value)
5092 (push (cons 'archive value) alist)))
5093 ((equal key "CATEGORY") (push (cons 'category value) alist))
5094 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5095 ((equal key "CONSTANTS")
5096 (let* ((constants (assq 'constants alist))
5097 (store (cdr constants)))
5098 (dolist (pair (org-split-string value))
5099 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5100 pair)
5101 (let* ((name (match-string 1 pair))
5102 (value (match-string 2 pair))
5103 (old (assoc name store)))
5104 (if old (setcdr old value)
5105 (push (cons name value) store)))))
5106 (if constants (setcdr constants store)
5107 (push (cons 'constants store) alist))))
5108 ((equal key "FILETAGS")
5109 (when (org-string-nw-p value)
5110 (let ((old (assq 'filetags alist))
5111 (new (apply #'nconc
5112 (mapcar (lambda (x) (org-split-string x ":"))
5113 (org-split-string value)))))
5114 (if old (setcdr old (append new (cdr old)))
5115 (push (cons 'filetags new) alist)))))
5116 ((equal key "LINK")
5117 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5118 (let ((links (assq 'link alist))
5119 (pair (cons (match-string-no-properties 1 value)
5120 (match-string-no-properties 2 value))))
5121 (if links (push pair (cdr links))
5122 (push (list 'link pair) alist)))))
5123 ((equal key "OPTIONS")
5124 (when (and (org-string-nw-p value)
5125 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5126 (push (cons 'scripts (read (match-string 1 value))) alist)))
5127 ((equal key "PRIORITIES")
5128 (push (cons 'priorities
5129 (let ((prio (org-split-string value)))
5130 (if (< (length prio) 3) '(?A ?C ?B)
5131 (mapcar #'string-to-char prio))))
5132 alist))
5133 ((equal key "PROPERTY")
5134 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5135 (let* ((property (assq 'property alist))
5136 (value (org--update-property-plist
5137 (match-string-no-properties 1 value)
5138 (match-string-no-properties 2 value)
5139 (cdr property))))
5140 (if property (setcdr property value)
5141 (push (cons 'property value) alist)))))
5142 ((equal key "STARTUP")
5143 (let ((startup (assq 'startup alist)))
5144 (if startup
5145 (setcdr startup
5146 (append (cdr startup) (org-split-string value)))
5147 (push (cons 'startup (org-split-string value)) alist))))
5148 ((equal key "TAGS")
5149 (let ((tag-cell (assq 'tags alist)))
5150 (if tag-cell
5151 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5152 (push (cons 'tags value) alist))))
5153 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5154 (let ((todo (assq 'todo alist))
5155 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5156 (org-split-string value))))
5157 (if todo (push value (cdr todo))
5158 (push (list 'todo value) alist))))
5159 ((equal key "SETUPFILE")
5160 (unless buffer-read-only ; Do not check in Gnus messages.
5161 (let ((f (and (org-string-nw-p value)
5162 (expand-file-name
5163 (org-unbracket-string "\"" "\"" value)))))
5164 (when (and f (file-readable-p f) (not (member f files)))
5165 (with-temp-buffer
5166 (setq default-directory (file-name-directory f))
5167 (insert-file-contents f)
5168 (setq alist
5169 ;; Fake Org mode to benefit from cache
5170 ;; without recurring needlessly.
5171 (let ((major-mode 'org-mode))
5172 (org--setup-collect-keywords
5173 regexp (cons f files) alist)))))))))))))))
5174 alist)
5176 (defun org-tag-string-to-alist (s)
5177 "Return tag alist associated to string S.
5178 S is a value for TAGS keyword or produced with
5179 `org-tag-alist-to-string'. Return value is an alist suitable for
5180 `org-tag-alist' or `org-tag-persistent-alist'."
5181 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5182 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5183 "\\|{.+?}\\)" ; regular expression
5184 "\\(?:(\\(.\\))\\)?\\'"))
5185 alist group-flag)
5186 (dolist (tokens lines (cdr (nreverse alist)))
5187 (push '(:newline) alist)
5188 (while tokens
5189 (let ((token (pop tokens)))
5190 (pcase token
5191 ("{"
5192 (push '(:startgroup) alist)
5193 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5194 ("}"
5195 (push '(:endgroup) alist)
5196 (setq group-flag nil))
5197 ("["
5198 (push '(:startgrouptag) alist)
5199 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5200 ("]"
5201 (push '(:endgrouptag) alist)
5202 (setq group-flag nil))
5203 (":"
5204 (push '(:grouptags) alist))
5205 ((guard (string-match tag-re token))
5206 (let ((tag (match-string 1 token))
5207 (key (and (match-beginning 2)
5208 (string-to-char (match-string 2 token)))))
5209 ;; Push all tags in groups, no matter if they already
5210 ;; appear somewhere else in the list.
5211 (when (or group-flag (not (assoc tag alist)))
5212 (push (cons tag key) alist))))))))))
5214 (defun org-tag-alist-to-string (alist &optional skip-key)
5215 "Return tag string associated to ALIST.
5217 ALIST is an alist, as defined in `org-tag-alist' or
5218 `org-tag-persistent-alist', or produced with
5219 `org-tag-string-to-alist'.
5221 Return value is a string suitable as a value for \"TAGS\"
5222 keyword.
5224 When optional argument SKIP-KEY is non-nil, skip selection keys
5225 next to tags."
5226 (mapconcat (lambda (token)
5227 (pcase token
5228 (`(:startgroup) "{")
5229 (`(:endgroup) "}")
5230 (`(:startgrouptag) "[")
5231 (`(:endgrouptag) "]")
5232 (`(:grouptags) ":")
5233 (`(:newline) "\\n")
5234 ((and
5235 (guard (not skip-key))
5236 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5237 (format "%s(%c)" tag key))
5238 (`(,(and tag (pred stringp)) . ,_) tag)
5239 (_ (user-error "Invalid tag token: %S" token))))
5240 alist
5241 " "))
5243 (defun org-tag-alist-to-groups (alist)
5244 "Return group alist from tag ALIST.
5245 ALIST is an alist, as defined in `org-tag-alist' or
5246 `org-tag-persistent-alist', or produced with
5247 `org-tag-string-to-alist'. Return value is an alist following
5248 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5249 a string, summarizing TAGS, as a list of strings."
5250 (let (groups group-status current-group)
5251 (dolist (token alist (nreverse groups))
5252 (pcase token
5253 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5254 (`(,(or :endgroup :endgrouptag))
5255 (when (eq group-status 'append)
5256 (push (nreverse current-group) groups))
5257 (setq group-status nil))
5258 (`(:grouptags) (setq group-status 'append))
5259 ((and `(,tag . ,_) (guard group-status))
5260 (if (eq group-status 'append) (push tag current-group)
5261 (setq current-group (list tag))))
5262 (_ nil)))))
5264 (defvar org--file-cache (make-hash-table :test #'equal)
5265 "Hash table to store contents of files referenced via a URL.
5266 This is the cache of file URLs read using `org-file-contents'.")
5268 (defun org-reset-file-cache ()
5269 "Reset the cache of files downloaded by `org-file-contents'."
5270 (clrhash org--file-cache))
5272 (defun org-file-url-p (file)
5273 "Non-nil if FILE is a URL."
5274 (require 'ffap)
5275 (string-match-p ffap-url-regexp file))
5277 (defun org-file-contents (file &optional noerror nocache)
5278 "Return the contents of FILE, as a string.
5280 FILE can be a file name or URL.
5282 If FILE is a URL, download the contents. If the URL contents are
5283 already cached in the `org--file-cache' hash table, the download step
5284 is skipped.
5286 If NOERROR is non-nil, ignore the error when unable to read the FILE
5287 from file or URL.
5289 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5290 is available. This option applies only if FILE is a URL."
5291 (let* ((is-url (org-file-url-p file))
5292 (cache (and is-url
5293 (not nocache)
5294 (gethash file org--file-cache))))
5295 (cond
5296 (cache)
5297 (is-url
5298 (with-current-buffer (url-retrieve-synchronously file)
5299 (goto-char (point-min))
5300 ;; Move point to after the url-retrieve header.
5301 (search-forward "\n\n" nil :move)
5302 ;; Search for the success code only in the url-retrieve header.
5303 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5304 ;; Update the cache `org--file-cache' and return contents.
5305 (puthash file
5306 (buffer-substring-no-properties (point) (point-max))
5307 org--file-cache)
5308 (funcall (if noerror #'message #'user-error)
5309 "Unable to fetch file from %S"
5310 file))))
5312 (with-temp-buffer
5313 (condition-case err
5314 (progn
5315 (insert-file-contents file)
5316 (buffer-string))
5317 (file-error
5318 (funcall (if noerror #'message #'user-error)
5319 (error-message-string err)))))))))
5321 (defun org-extract-log-state-settings (x)
5322 "Extract the log state setting from a TODO keyword string.
5323 This will extract info from a string like \"WAIT(w@/!)\"."
5324 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5325 (let ((kw (match-string 1 x))
5326 (log1 (and (match-end 3) (match-string 3 x)))
5327 (log2 (and (match-end 4) (match-string 4 x))))
5328 (and (or log1 log2)
5329 (list kw
5330 (and log1 (if (equal log1 "!") 'time 'note))
5331 (and log2 (if (equal log2 "!") 'time 'note)))))))
5333 (defun org-remove-keyword-keys (list)
5334 "Remove a pair of parenthesis at the end of each string in LIST."
5335 (mapcar (lambda (x)
5336 (if (string-match "(.*)$" x)
5337 (substring x 0 (match-beginning 0))
5339 list))
5341 (defun org-assign-fast-keys (alist)
5342 "Assign fast keys to a keyword-key alist.
5343 Respect keys that are already there."
5344 (let (new e (alt ?0))
5345 (while (setq e (pop alist))
5346 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5347 (cdr e)) ;; Key already assigned.
5348 (push e new)
5349 (let ((clist (string-to-list (downcase (car e))))
5350 (used (append new alist)))
5351 (when (= (car clist) ?@)
5352 (pop clist))
5353 (while (and clist (rassoc (car clist) used))
5354 (pop clist))
5355 (unless clist
5356 (while (rassoc alt used)
5357 (cl-incf alt)))
5358 (push (cons (car e) (or (car clist) alt)) new))))
5359 (nreverse new)))
5361 ;;; Some variables used in various places
5363 (defvar org-window-configuration nil
5364 "Used in various places to store a window configuration.")
5365 (defvar org-selected-window nil
5366 "Used in various places to store a window configuration.")
5367 (defvar org-finish-function nil
5368 "Function to be called when `C-c C-c' is used.
5369 This is for getting out of special buffers like capture.")
5370 (defvar org-last-state)
5372 ;; Defined somewhere in this file, but used before definition.
5373 (defvar org-entities) ;; defined in org-entities.el
5374 (defvar org-struct-menu)
5375 (defvar org-org-menu)
5376 (defvar org-tbl-menu)
5378 ;;;; Define the Org mode
5380 ;; We use a before-change function to check if a table might need
5381 ;; an update.
5382 (defvar org-table-may-need-update t
5383 "Indicates that a table might need an update.
5384 This variable is set by `org-before-change-function'.
5385 `org-table-align' sets it back to nil.")
5386 (defun org-before-change-function (_beg _end)
5387 "Every change indicates that a table might need an update."
5388 (setq org-table-may-need-update t))
5389 (defvar org-mode-map)
5390 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5391 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5392 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5393 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5394 (defvar org-table-buffer-is-an nil)
5396 (defvar bidi-paragraph-direction)
5397 (defvar buffer-face-mode-face)
5399 (require 'outline)
5401 ;; Other stuff we need.
5402 (require 'time-date)
5403 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5404 (require 'easymenu)
5405 (autoload 'easy-menu-add "easymenu")
5406 (require 'overlay)
5408 ;; (require 'org-macs) moved higher up in the file before it is first used
5409 (require 'org-entities)
5410 ;; (require 'org-compat) moved higher up in the file before it is first used
5411 (require 'org-faces)
5412 (require 'org-list)
5413 (require 'org-pcomplete)
5414 (require 'org-src)
5415 (require 'org-footnote)
5416 (require 'org-macro)
5418 ;; babel
5419 (require 'ob)
5421 ;;;###autoload
5422 (define-derived-mode org-mode outline-mode "Org"
5423 "Outline-based notes management and organizer, alias
5424 \"Carsten's outline-mode for keeping track of everything.\"
5426 Org mode develops organizational tasks around a NOTES file which
5427 contains information about projects as plain text. Org mode is
5428 implemented on top of Outline mode, which is ideal to keep the content
5429 of large files well structured. It supports ToDo items, deadlines and
5430 time stamps, which magically appear in the diary listing of the Emacs
5431 calendar. Tables are easily created with a built-in table editor.
5432 Plain text URL-like links connect to websites, emails (VM), Usenet
5433 messages (Gnus), BBDB entries, and any files related to the project.
5434 For printing and sharing of notes, an Org file (or a part of it)
5435 can be exported as a structured ASCII or HTML file.
5437 The following commands are available:
5439 \\{org-mode-map}"
5441 ;; Get rid of Outline menus, they are not needed
5442 ;; Need to do this here because define-derived-mode sets up
5443 ;; the keymap so late. Still, it is a waste to call this each time
5444 ;; we switch another buffer into Org mode.
5445 (define-key org-mode-map [menu-bar headings] 'undefined)
5446 (define-key org-mode-map [menu-bar hide] 'undefined)
5447 (define-key org-mode-map [menu-bar show] 'undefined)
5449 (org-load-modules-maybe)
5450 (org-install-agenda-files-menu)
5451 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5452 (add-to-invisibility-spec '(org-hide-block . t))
5453 (setq-local outline-regexp org-outline-regexp)
5454 (setq-local outline-level 'org-outline-level)
5455 (setq bidi-paragraph-direction 'left-to-right)
5456 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5457 (unless org-display-table
5458 (setq org-display-table (make-display-table)))
5459 (set-display-table-slot
5460 org-display-table 4
5461 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5462 org-ellipsis)))
5463 (setq buffer-display-table org-display-table))
5464 (org-set-regexps-and-options)
5465 (org-set-font-lock-defaults)
5466 (when (and org-tag-faces (not org-tags-special-faces-re))
5467 ;; tag faces set outside customize.... force initialization.
5468 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5469 ;; Calc embedded
5470 (setq-local calc-embedded-open-mode "# ")
5471 ;; Modify a few syntax entries
5472 (modify-syntax-entry ?@ "w")
5473 (modify-syntax-entry ?\" "\"")
5474 (modify-syntax-entry ?\\ "_")
5475 (modify-syntax-entry ?~ "_")
5476 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5477 ;; Activate before-change-function
5478 (setq-local org-table-may-need-update t)
5479 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5480 ;; Check for running clock before killing a buffer
5481 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5482 ;; Initialize macros templates.
5483 (org-macro-initialize-templates)
5484 ;; Initialize radio targets.
5485 (org-update-radio-target-regexp)
5486 ;; Indentation.
5487 (setq-local indent-line-function 'org-indent-line)
5488 (setq-local indent-region-function 'org-indent-region)
5489 ;; Filling and auto-filling.
5490 (org-setup-filling)
5491 ;; Comments.
5492 (org-setup-comments-handling)
5493 ;; Initialize cache.
5494 (org-element-cache-reset)
5495 ;; Beginning/end of defun
5496 (setq-local beginning-of-defun-function 'org-backward-element)
5497 (setq-local end-of-defun-function
5498 (lambda ()
5499 (if (not (org-at-heading-p))
5500 (org-forward-element)
5501 (org-forward-element)
5502 (forward-char -1))))
5503 ;; Next error for sparse trees
5504 (setq-local next-error-function 'org-occur-next-match)
5505 ;; Make sure dependence stuff works reliably, even for users who set it
5506 ;; too late :-(
5507 (if org-enforce-todo-dependencies
5508 (add-hook 'org-blocker-hook
5509 'org-block-todo-from-children-or-siblings-or-parent)
5510 (remove-hook 'org-blocker-hook
5511 'org-block-todo-from-children-or-siblings-or-parent))
5512 (if org-enforce-todo-checkbox-dependencies
5513 (add-hook 'org-blocker-hook
5514 'org-block-todo-from-checkboxes)
5515 (remove-hook 'org-blocker-hook
5516 'org-block-todo-from-checkboxes))
5518 ;; Align options lines
5519 (setq-local
5520 align-mode-rules-list
5521 '((org-in-buffer-settings
5522 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5523 (modes . '(org-mode)))))
5525 ;; Imenu
5526 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5528 ;; Make isearch reveal context
5529 (setq-local outline-isearch-open-invisible-function
5530 (lambda (&rest _) (org-show-context 'isearch)))
5532 ;; Setup the pcomplete hooks
5533 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5534 (setq-local pcomplete-command-name-function 'org-command-at-point)
5535 (setq-local pcomplete-default-completion-function 'ignore)
5536 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5537 (setq-local pcomplete-termination-string "")
5538 (setq-local buffer-face-mode-face 'org-default)
5540 ;; If empty file that did not turn on Org mode automatically, make
5541 ;; it to.
5542 (when (and org-insert-mode-line-in-empty-file
5543 (called-interactively-p 'any)
5544 (= (point-min) (point-max)))
5545 (insert "# -*- mode: org -*-\n\n"))
5546 (unless org-inhibit-startup
5547 (org-unmodified
5548 (when org-startup-with-beamer-mode (org-beamer-mode))
5549 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5550 (org-table-map-tables
5551 (cond ((and org-startup-align-all-tables
5552 org-startup-shrink-all-tables)
5553 (lambda () (org-table-align) (org-table-shrink)))
5554 (org-startup-align-all-tables #'org-table-align)
5555 (t #'org-table-shrink))
5557 (when org-startup-with-inline-images (org-display-inline-images))
5558 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5559 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5560 (when org-startup-truncated (setq truncate-lines t))
5561 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5562 (org-refresh-effort-properties)))
5563 ;; Try to set `org-hide' face correctly.
5564 (let ((foreground (org-find-invisible-foreground)))
5565 (when foreground
5566 (set-face-foreground 'org-hide foreground))))
5568 ;; Update `customize-package-emacs-version-alist'
5569 (add-to-list 'customize-package-emacs-version-alist
5570 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5571 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5572 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5573 ("9.0" . "26.1")))
5575 (defvar org-mode-transpose-word-syntax-table
5576 (let ((st (make-syntax-table text-mode-syntax-table)))
5577 (dolist (c org-emphasis-alist st)
5578 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5580 (when (fboundp 'abbrev-table-put)
5581 (abbrev-table-put org-mode-abbrev-table
5582 :parents (list text-mode-abbrev-table)))
5584 (defun org-find-invisible-foreground ()
5585 (let ((candidates (remove
5586 "unspecified-bg"
5587 (nconc
5588 (list (face-background 'default)
5589 (face-background 'org-default))
5590 (mapcar
5591 (lambda (alist)
5592 (when (boundp alist)
5593 (cdr (assq 'background-color (symbol-value alist)))))
5594 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5595 (list (face-foreground 'org-hide))))))
5596 (car (remove nil candidates))))
5598 (defun org-current-time (&optional rounding-minutes past)
5599 "Current time, possibly rounded to ROUNDING-MINUTES.
5600 When ROUNDING-MINUTES is not an integer, fall back on the car of
5601 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5602 the rounding returns a past time."
5603 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5604 (car org-time-stamp-rounding-minutes)))
5605 (time (decode-time)) res)
5606 (if (< r 1)
5607 (current-time)
5608 (setq res
5609 (apply 'encode-time
5610 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5611 (nthcdr 2 time))))
5612 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5613 (seconds-to-time (- (float-time res) (* r 60)))
5614 res))))
5616 (defun org-today ()
5617 "Return today date, considering `org-extend-today-until'."
5618 (time-to-days
5619 (time-subtract (current-time)
5620 (list 0 (* 3600 org-extend-today-until) 0))))
5622 ;;;; Font-Lock stuff, including the activators
5624 (defvar org-mouse-map (make-sparse-keymap))
5625 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5626 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5627 (when org-mouse-1-follows-link
5628 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5629 (when org-tab-follows-link
5630 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5631 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5633 (require 'font-lock)
5635 (defconst org-non-link-chars "]\t\n\r<>")
5636 (defvar org-link-types-re nil
5637 "Matches a link that has a url-like prefix like \"http:\"")
5638 (defvar org-link-re-with-space nil
5639 "Matches a link with spaces, optional angular brackets around it.")
5640 (defvar org-link-re-with-space2 nil
5641 "Matches a link with spaces, optional angular brackets around it.")
5642 (defvar org-link-re-with-space3 nil
5643 "Matches a link with spaces, only for internal part in bracket links.")
5644 (defvar org-angle-link-re nil
5645 "Matches link with angular brackets, spaces are allowed.")
5646 (defvar org-plain-link-re nil
5647 "Matches plain link, without spaces.")
5648 (defvar org-bracket-link-regexp nil
5649 "Matches a link in double brackets.")
5650 (defvar org-bracket-link-analytic-regexp nil
5651 "Regular expression used to analyze links.
5652 Here is what the match groups contain after a match:
5653 1: http:
5654 2: http
5655 3: path
5656 4: [desc]
5657 5: desc")
5658 (defvar org-bracket-link-analytic-regexp++ nil
5659 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5660 (defvar org-any-link-re nil
5661 "Regular expression matching any link.")
5663 (defconst org-match-sexp-depth 3
5664 "Number of stacked braces for sub/superscript matching.")
5666 (defun org-create-multibrace-regexp (left right n)
5667 "Create a regular expression which will match a balanced sexp.
5668 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5669 as single character strings.
5670 The regexp returned will match the entire expression including the
5671 delimiters. It will also define a single group which contains the
5672 match except for the outermost delimiters. The maximum depth of
5673 stacked delimiters is N. Escaping delimiters is not possible."
5674 (let* ((nothing (concat "[^" left right "]*?"))
5675 (or "\\|")
5676 (re nothing)
5677 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5678 (while (> n 1)
5679 (setq n (1- n)
5680 re (concat re or next)
5681 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5682 (concat left "\\(" re "\\)" right)))
5684 (defconst org-match-substring-regexp
5685 (concat
5686 "\\(\\S-\\)\\([_^]\\)\\("
5687 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5688 "\\|"
5689 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5690 "\\|"
5691 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5692 "The regular expression matching a sub- or superscript.")
5694 (defconst org-match-substring-with-braces-regexp
5695 (concat
5696 "\\(\\S-\\)\\([_^]\\)"
5697 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5698 "The regular expression matching a sub- or superscript, forcing braces.")
5700 (defun org-make-link-regexps ()
5701 "Update the link regular expressions.
5702 This should be called after the variable `org-link-parameters' has changed."
5703 (let ((types-re (regexp-opt (org-link-types) t)))
5704 (setq org-link-types-re
5705 (concat "\\`" types-re ":")
5706 org-link-re-with-space
5707 (concat "<?" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^" org-non-link-chars "]*"
5710 "[^" org-non-link-chars " ]\\)>?")
5711 org-link-re-with-space2
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^\t\n\r]*"
5715 "[^" org-non-link-chars " ]\\)>?")
5716 org-link-re-with-space3
5717 (concat "<?" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^\t\n\r]*\\)")
5720 org-angle-link-re
5721 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5722 types-re)
5723 org-plain-link-re
5724 (concat
5725 "\\<" types-re ":"
5726 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5727 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5728 org-bracket-link-regexp
5729 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5730 org-bracket-link-analytic-regexp
5731 (concat
5732 "\\[\\["
5733 "\\(" types-re ":\\)?"
5734 "\\([^]]+\\)"
5735 "\\]"
5736 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5737 "\\]")
5738 org-bracket-link-analytic-regexp++
5739 (concat
5740 "\\[\\["
5741 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5742 "\\([^]]+\\)"
5743 "\\]"
5744 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5745 "\\]")
5746 org-any-link-re
5747 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5748 org-angle-link-re "\\)\\|\\("
5749 org-plain-link-re "\\)"))))
5751 (org-make-link-regexps)
5753 (defvar org-emph-face nil)
5755 (defun org-do-emphasis-faces (limit)
5756 "Run through the buffer and emphasize strings."
5757 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5758 (car org-emphasis-regexp-components))))
5759 (catch :exit
5760 (while (re-search-forward quick-re limit t)
5761 (let* ((marker (match-string 2))
5762 (verbatim? (member marker '("~" "="))))
5763 (when (save-excursion
5764 (goto-char (match-beginning 0))
5765 ;; Do not match headline stars. Do not consider
5766 ;; stars of a headline as closing marker for bold
5767 ;; markup either. Do not match table hlines.
5768 (and
5769 (not (looking-at-p org-outline-regexp-bol))
5770 (not (and (equal marker "+")
5771 (org-match-line
5772 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5773 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5774 (not (string-match-p
5775 (concat org-outline-regexp-bol "\\'")
5776 (match-string 0)))))
5777 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5778 (font-lock-prepend-text-property
5779 (match-beginning 2) (match-end 2) 'face face)
5780 (when verbatim?
5781 (org-remove-flyspell-overlays-in
5782 (match-beginning 0) (match-end 0)))
5783 (add-text-properties (match-beginning 2) (match-end 2)
5784 '(font-lock-multiline t org-emphasis t))
5785 (when org-hide-emphasis-markers
5786 (add-text-properties (match-end 4) (match-beginning 5)
5787 '(invisible org-link))
5788 (add-text-properties (match-beginning 3) (match-end 3)
5789 '(invisible org-link)))
5790 (throw :exit t))))))))
5792 (defun org-emphasize (&optional char)
5793 "Insert or change an emphasis, i.e. a font like bold or italic.
5794 If there is an active region, change that region to a new emphasis.
5795 If there is no region, just insert the marker characters and position
5796 the cursor between them.
5797 CHAR should be the marker character. If it is a space, it means to
5798 remove the emphasis of the selected region.
5799 If CHAR is not given (for example in an interactive call) it will be
5800 prompted for."
5801 (interactive)
5802 (let ((erc org-emphasis-regexp-components)
5803 (string "") beg end move s)
5804 (if (org-region-active-p)
5805 (setq beg (region-beginning)
5806 end (region-end)
5807 string (buffer-substring beg end))
5808 (setq move t))
5810 (unless char
5811 (message "Emphasis marker or tag: [%s]"
5812 (mapconcat #'car org-emphasis-alist ""))
5813 (setq char (read-char-exclusive)))
5814 (if (equal char ?\s)
5815 (setq s ""
5816 move nil)
5817 (unless (assoc (char-to-string char) org-emphasis-alist)
5818 (user-error "No such emphasis marker: \"%c\"" char))
5819 (setq s (char-to-string char)))
5820 (while (and (> (length string) 1)
5821 (equal (substring string 0 1) (substring string -1))
5822 (assoc (substring string 0 1) org-emphasis-alist))
5823 (setq string (substring string 1 -1)))
5824 (setq string (concat s string s))
5825 (when beg (delete-region beg end))
5826 (unless (or (bolp)
5827 (string-match (concat "[" (nth 0 erc) "\n]")
5828 (char-to-string (char-before (point)))))
5829 (insert " "))
5830 (unless (or (eobp)
5831 (string-match (concat "[" (nth 1 erc) "\n]")
5832 (char-to-string (char-after (point)))))
5833 (insert " ") (backward-char 1))
5834 (insert string)
5835 (and move (backward-char 1))))
5837 (defconst org-nonsticky-props
5838 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5840 (defsubst org-rear-nonsticky-at (pos)
5841 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5843 (defun org-activate-links (limit)
5844 "Add link properties to links.
5845 This includes angle, plain, and bracket links."
5846 (catch :exit
5847 (while (re-search-forward org-any-link-re limit t)
5848 (let* ((start (match-beginning 0))
5849 (end (match-end 0))
5850 (style (cond ((eq ?< (char-after start)) 'angle)
5851 ((eq ?\[ (char-after (1+ start))) 'bracket)
5852 (t 'plain))))
5853 (when (and (memq style org-highlight-links)
5854 ;; Do not confuse plain links with tags.
5855 (not (and (eq style 'plain)
5856 (let ((face (get-text-property
5857 (max (1- start) (point-min)) 'face)))
5858 (if (consp face) (memq 'org-tag face)
5859 (eq 'org-tag face))))))
5860 (let* ((link-object (save-excursion
5861 (goto-char start)
5862 (save-match-data (org-element-link-parser))))
5863 (link (org-element-property :raw-link link-object))
5864 (type (org-element-property :type link-object))
5865 (path (org-element-property :path link-object))
5866 (properties ;for link's visible part
5867 (list
5868 'face (pcase (org-link-get-parameter type :face)
5869 ((and (pred functionp) face) (funcall face path))
5870 ((and (pred facep) face) face)
5871 ((and (pred consp) face) face) ;anonymous
5872 (_ 'org-link))
5873 'mouse-face (or (org-link-get-parameter type :mouse-face)
5874 'highlight)
5875 'keymap (or (org-link-get-parameter type :keymap)
5876 org-mouse-map)
5877 'help-echo (pcase (org-link-get-parameter type :help-echo)
5878 ((and (pred stringp) echo) echo)
5879 ((and (pred functionp) echo) echo)
5880 (_ (concat "LINK: " link)))
5881 'htmlize-link (pcase (org-link-get-parameter type
5882 :htmlize-link)
5883 ((and (pred functionp) f) (funcall f))
5884 (_ `(:uri ,link)))
5885 'font-lock-multiline t)))
5886 (org-remove-flyspell-overlays-in start end)
5887 (org-rear-nonsticky-at end)
5888 (if (not (eq 'bracket style))
5889 (add-text-properties start end properties)
5890 ;; Handle invisible parts in bracket links.
5891 (remove-text-properties start end '(invisible nil))
5892 (let ((hidden
5893 (append `(invisible
5894 ,(or (org-link-get-parameter type :display)
5895 'org-link))
5896 properties))
5897 (visible-start (or (match-beginning 4) (match-beginning 2)))
5898 (visible-end (or (match-end 4) (match-end 2))))
5899 (add-text-properties start visible-start hidden)
5900 (add-text-properties visible-start visible-end properties)
5901 (add-text-properties visible-end end hidden)
5902 (org-rear-nonsticky-at visible-start)
5903 (org-rear-nonsticky-at visible-end)))
5904 (let ((f (org-link-get-parameter type :activate-func)))
5905 (when (functionp f)
5906 (funcall f start end path (eq style 'bracket))))
5907 (throw :exit t))))) ;signal success
5908 nil))
5910 (defun org-activate-code (limit)
5911 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5912 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5913 (remove-text-properties (match-beginning 0) (match-end 0)
5914 '(display t invisible t intangible t))
5917 (defcustom org-src-fontify-natively t
5918 "When non-nil, fontify code in code blocks.
5919 See also the `org-block' face."
5920 :type 'boolean
5921 :version "24.4"
5922 :package-version '(Org . "8.3")
5923 :group 'org-appearance
5924 :group 'org-babel)
5926 (defcustom org-allow-promoting-top-level-subtree nil
5927 "When non-nil, allow promoting a top level subtree.
5928 The leading star of the top level headline will be replaced
5929 by a #."
5930 :type 'boolean
5931 :version "24.1"
5932 :group 'org-appearance)
5934 (defun org-fontify-meta-lines-and-blocks (limit)
5935 (condition-case nil
5936 (org-fontify-meta-lines-and-blocks-1 limit)
5937 (error (message "org-mode fontification error in %S at %d"
5938 (current-buffer)
5939 (line-number-at-pos)))))
5941 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5942 "Fontify #+ lines and blocks."
5943 (let ((case-fold-search t))
5944 (when (re-search-forward
5945 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5946 limit t)
5947 (let ((beg (match-beginning 0))
5948 (block-start (match-end 0))
5949 (block-end nil)
5950 (lang (match-string 7))
5951 (beg1 (line-beginning-position 2))
5952 (dc1 (downcase (match-string 2)))
5953 (dc3 (downcase (match-string 3)))
5954 end end1 quoting block-type)
5955 (cond
5956 ((and (match-end 4) (equal dc3 "+begin"))
5957 ;; Truly a block
5958 (setq block-type (downcase (match-string 5))
5959 quoting (member block-type org-protecting-blocks))
5960 (when (re-search-forward
5961 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5962 nil t) ;; on purpose, we look further than LIMIT
5963 (setq end (min (point-max) (match-end 0))
5964 end1 (min (point-max) (1- (match-beginning 0))))
5965 (setq block-end (match-beginning 0))
5966 (when quoting
5967 (org-remove-flyspell-overlays-in beg1 end1)
5968 (remove-text-properties beg end
5969 '(display t invisible t intangible t)))
5970 (add-text-properties
5971 beg end '(font-lock-fontified t font-lock-multiline t))
5972 (add-text-properties beg beg1 '(face org-meta-line))
5973 (org-remove-flyspell-overlays-in beg beg1)
5974 (add-text-properties ; For end_src
5975 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5976 (org-remove-flyspell-overlays-in end1 end)
5977 (cond
5978 ((and lang (not (string= lang "")) org-src-fontify-natively)
5979 (org-src-font-lock-fontify-block lang block-start block-end)
5980 (add-text-properties beg1 block-end '(src-block t)))
5981 (quoting
5982 (add-text-properties beg1 (min (point-max) (1+ end1))
5983 (list 'face
5984 (list :inherit
5985 (let ((face-name
5986 (intern (format "org-block-%s" lang))))
5987 (append (and (facep face-name) (list face-name))
5988 '(org-block))))))) ; end of source block
5989 ((not org-fontify-quote-and-verse-blocks))
5990 ((string= block-type "quote")
5991 (add-face-text-property
5992 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5993 ((string= block-type "verse")
5994 (add-face-text-property
5995 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5996 (add-text-properties beg beg1 '(face org-block-begin-line))
5997 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5998 '(face org-block-end-line))
6000 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6001 (org-remove-flyspell-overlays-in
6002 (match-beginning 0)
6003 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6004 (add-text-properties
6005 beg (match-end 3)
6006 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6007 '(font-lock-fontified t invisible t)
6008 '(font-lock-fontified t face org-document-info-keyword)))
6009 (add-text-properties
6010 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6011 (if (string-equal dc1 "+title:")
6012 '(font-lock-fontified t face org-document-title)
6013 '(font-lock-fontified t face org-document-info))))
6014 ((string-prefix-p "+caption" dc1)
6015 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6016 (remove-text-properties (match-beginning 0) (match-end 0)
6017 '(display t invisible t intangible t))
6018 ;; Handle short captions.
6019 (save-excursion
6020 (beginning-of-line)
6021 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6022 (add-text-properties (line-beginning-position) (match-end 1)
6023 '(font-lock-fontified t face org-meta-line))
6024 (add-text-properties (match-end 0) (line-end-position)
6025 '(font-lock-fontified t face org-block))
6027 ((member dc3 '(" " ""))
6028 (org-remove-flyspell-overlays-in beg (match-end 0))
6029 (add-text-properties
6030 beg (match-end 0)
6031 '(font-lock-fontified t face font-lock-comment-face)))
6032 (t ;; just any other in-buffer setting, but not indented
6033 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (remove-text-properties (match-beginning 0) (match-end 0)
6035 '(display t invisible t intangible t))
6036 (add-text-properties beg (match-end 0)
6037 '(font-lock-fontified t face org-meta-line))
6038 t))))))
6040 (defun org-fontify-drawers (limit)
6041 "Fontify drawers."
6042 (when (re-search-forward org-drawer-regexp limit t)
6043 (add-text-properties
6044 (match-beginning 0) (match-end 0)
6045 '(font-lock-fontified t face org-special-keyword))
6046 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6049 (defun org-fontify-macros (limit)
6050 "Fontify macros."
6051 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6052 (add-text-properties
6053 (match-beginning 0) (match-end 0)
6054 '(font-lock-fontified t face org-macro))
6055 (when org-hide-macro-markers
6056 (add-text-properties (match-end 2) (match-beginning 2)
6057 '(invisible t))
6058 (add-text-properties (match-beginning 1) (match-end 1)
6059 '(invisible t)))
6060 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6063 (defun org-activate-footnote-links (limit)
6064 "Add text properties for footnotes."
6065 (let ((fn (org-footnote-next-reference-or-definition limit)))
6066 (when fn
6067 (let* ((beg (nth 1 fn))
6068 (end (nth 2 fn))
6069 (label (car fn))
6070 (referencep (/= (line-beginning-position) beg)))
6071 (when (and referencep (nth 3 fn))
6072 (save-excursion
6073 (goto-char beg)
6074 (search-forward (or label "fn:"))
6075 (org-remove-flyspell-overlays-in beg (match-end 0))))
6076 (add-text-properties beg end
6077 (list 'mouse-face 'highlight
6078 'keymap org-mouse-map
6079 'help-echo
6080 (if referencep "Footnote reference"
6081 "Footnote definition")
6082 'font-lock-fontified t
6083 'font-lock-multiline t
6084 'face 'org-footnote))))))
6086 (defun org-activate-dates (limit)
6087 "Add text properties for dates."
6088 (when (and (re-search-forward org-tsr-regexp-both limit t)
6089 (not (equal (char-before (match-beginning 0)) 91)))
6090 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6091 (add-text-properties (match-beginning 0) (match-end 0)
6092 (list 'mouse-face 'highlight
6093 'keymap org-mouse-map))
6094 (org-rear-nonsticky-at (match-end 0))
6095 (when org-display-custom-times
6096 ;; If it's a date range, activate custom time for second date.
6097 (when (match-end 3)
6098 (org-display-custom-time (match-beginning 3) (match-end 3)))
6099 (org-display-custom-time (match-beginning 1) (match-end 1)))
6102 (defvar-local org-target-link-regexp nil
6103 "Regular expression matching radio targets in plain text.")
6105 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6106 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6107 border border border))
6108 "Regular expression matching a link target.")
6110 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6111 "Regular expression matching a radio target.")
6113 (defconst org-any-target-regexp
6114 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6115 "Regular expression matching any target.")
6117 (defun org-activate-target-links (limit)
6118 "Add text properties for target matches."
6119 (when org-target-link-regexp
6120 (let ((case-fold-search t))
6121 (when (re-search-forward org-target-link-regexp limit t)
6122 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6123 (add-text-properties (match-beginning 1) (match-end 1)
6124 (list 'mouse-face 'highlight
6125 'keymap org-mouse-map
6126 'help-echo "Radio target link"
6127 'org-linked-text t))
6128 (org-rear-nonsticky-at (match-end 1))
6129 t))))
6131 (defun org-update-radio-target-regexp ()
6132 "Find all radio targets in this file and update the regular expression.
6133 Also refresh fontification if needed."
6134 (interactive)
6135 (let ((old-regexp org-target-link-regexp)
6136 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6137 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6138 (targets
6139 (org-with-wide-buffer
6140 (goto-char (point-min))
6141 (let (rtn)
6142 (while (re-search-forward org-radio-target-regexp nil t)
6143 ;; Make sure point is really within the object.
6144 (backward-char)
6145 (let ((obj (org-element-context)))
6146 (when (eq (org-element-type obj) 'radio-target)
6147 (cl-pushnew (org-element-property :value obj) rtn
6148 :test #'equal))))
6149 rtn))))
6150 (setq org-target-link-regexp
6151 (and targets
6152 (concat before-re
6153 (mapconcat
6154 (lambda (x)
6155 (replace-regexp-in-string
6156 " +" "\\s-+" (regexp-quote x) t t))
6157 targets
6158 "\\|")
6159 after-re)))
6160 (unless (equal old-regexp org-target-link-regexp)
6161 ;; Clean-up cache.
6162 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6163 ((not org-target-link-regexp) old-regexp)
6165 (concat before-re
6166 (mapconcat
6167 (lambda (re)
6168 (substring re (length before-re)
6169 (- (length after-re))))
6170 (list old-regexp org-target-link-regexp)
6171 "\\|")
6172 after-re)))))
6173 (org-with-wide-buffer
6174 (goto-char (point-min))
6175 (while (re-search-forward regexp nil t)
6176 (org-element-cache-refresh (match-beginning 1)))))
6177 ;; Re fontify buffer.
6178 (when (memq 'radio org-highlight-links)
6179 (org-restart-font-lock)))))
6181 (defvar org-latex-and-related-regexp nil
6182 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6184 (defun org-compute-latex-and-related-regexp ()
6185 "Compute regular expression for LaTeX, entities and sub/superscript.
6186 Result depends on variable `org-highlight-latex-and-related'."
6187 (setq-local
6188 org-latex-and-related-regexp
6189 (let* ((re-sub
6190 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6191 ((eq org-use-sub-superscripts '{})
6192 (list org-match-substring-with-braces-regexp))
6193 (org-use-sub-superscripts (list org-match-substring-regexp))))
6194 (re-latex
6195 (when (memq 'latex org-highlight-latex-and-related)
6196 (let ((matchers (plist-get org-format-latex-options :matchers)))
6197 (delq nil
6198 (mapcar (lambda (x)
6199 (and (member (car x) matchers) (nth 1 x)))
6200 org-latex-regexps)))))
6201 (re-entities
6202 (when (memq 'entities org-highlight-latex-and-related)
6203 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6204 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6206 (defun org-do-latex-and-related (limit)
6207 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6208 LIMIT bounds the search for syntax to highlight. Stop at first
6209 highlighted object, if any. Return t if some highlighting was
6210 done, nil otherwise."
6211 (when (org-string-nw-p org-latex-and-related-regexp)
6212 (catch 'found
6213 (while (re-search-forward org-latex-and-related-regexp limit t)
6214 (unless
6215 (cl-some
6216 (lambda (f)
6217 (memq f '(org-code org-verbatim underline org-special-keyword)))
6218 (save-excursion
6219 (goto-char (1+ (match-beginning 0)))
6220 (face-at-point nil t)))
6221 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6222 '(?_ ?^))
6224 0)))
6225 (font-lock-prepend-text-property
6226 (+ offset (match-beginning 0)) (match-end 0)
6227 'face 'org-latex-and-related)
6228 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6229 '(font-lock-multiline t)))
6230 (throw 'found t)))
6231 nil)))
6233 (defun org-restart-font-lock ()
6234 "Restart `font-lock-mode', to force refontification."
6235 (when (and (boundp 'font-lock-mode) font-lock-mode)
6236 (font-lock-mode -1)
6237 (font-lock-mode 1)))
6239 (defun org-activate-tags (limit)
6240 (when (re-search-forward
6241 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6242 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6243 (add-text-properties (match-beginning 1) (match-end 1)
6244 (list 'mouse-face 'highlight
6245 'keymap org-mouse-map))
6246 (org-rear-nonsticky-at (match-end 1))
6249 (defun org-outline-level ()
6250 "Compute the outline level of the heading at point.
6252 If this is called at a normal headline, the level is the number
6253 of stars. Use `org-reduced-level' to remove the effect of
6254 `org-odd-levels'. Unlike to `org-current-level', this function
6255 takes into consideration inlinetasks."
6256 (org-with-wide-buffer
6257 (end-of-line)
6258 (if (re-search-backward org-outline-regexp-bol nil t)
6259 (1- (- (match-end 0) (match-beginning 0)))
6260 0)))
6262 (defvar org-font-lock-keywords nil)
6264 (defsubst org-re-property (property &optional literal allow-null value)
6265 "Return a regexp matching a PROPERTY line.
6267 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6268 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6269 non-nil, match properties even without a value.
6271 Match group 3 is set to the value when it exists. If there is no
6272 value and ALLOW-NULL is non-nil, it is set to the empty string.
6274 With optional argument VALUE, match only property lines with
6275 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6276 unless LITERAL is non-nil."
6277 (concat
6278 "^\\(?4:[ \t]*\\)"
6279 (format "\\(?1::\\(?2:%s\\):\\)"
6280 (if literal property (regexp-quote property)))
6281 (cond (value
6282 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6283 (if literal value (regexp-quote value))))
6284 (allow-null
6285 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6287 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6289 (defconst org-property-re
6290 (org-re-property "\\S-+" 'literal t)
6291 "Regular expression matching a property line.
6292 There are four matching groups:
6293 1: :PROPKEY: including the leading and trailing colon,
6294 2: PROPKEY without the leading and trailing colon,
6295 3: PROPVAL without leading or trailing spaces,
6296 4: the indentation of the current line,
6297 5: trailing whitespace.")
6299 (defvar org-font-lock-hook nil
6300 "Functions to be called for special font lock stuff.")
6302 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6304 (defvar org-font-lock-set-keywords-hook nil
6305 "Functions that can manipulate `org-font-lock-extra-keywords'.
6306 This is called after `org-font-lock-extra-keywords' is defined, but before
6307 it is installed to be used by font lock. This can be useful if something
6308 needs to be inserted at a specific position in the font-lock sequence.")
6310 (defun org-font-lock-hook (limit)
6311 "Run `org-font-lock-hook' within LIMIT."
6312 (run-hook-with-args 'org-font-lock-hook limit))
6314 (defun org-set-font-lock-defaults ()
6315 "Set font lock defaults for the current buffer."
6316 (let* ((em org-fontify-emphasized-text)
6317 (lk org-highlight-links)
6318 (org-font-lock-extra-keywords
6319 (list
6320 ;; Call the hook
6321 '(org-font-lock-hook)
6322 ;; Headlines
6323 `(,(if org-fontify-whole-heading-line
6324 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6325 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6326 (1 (org-get-level-face 1))
6327 (2 (org-get-level-face 2))
6328 (3 (org-get-level-face 3)))
6329 ;; Table lines
6330 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6331 (1 'org-table t))
6332 ;; Table internals
6333 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6334 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6335 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6336 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6337 ;; Drawers
6338 '(org-fontify-drawers)
6339 ;; Properties
6340 (list org-property-re
6341 '(1 'org-special-keyword t)
6342 '(3 'org-property-value t))
6343 ;; Link related fontification.
6344 '(org-activate-links)
6345 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6346 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6347 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6348 (when (memq 'footnote lk) '(org-activate-footnote-links))
6349 ;; Targets.
6350 (list org-any-target-regexp '(0 'org-target t))
6351 ;; Diary sexps.
6352 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6353 ;; Macro
6354 '(org-fontify-macros)
6355 ;; TODO keyword
6356 (list (format org-heading-keyword-regexp-format
6357 org-todo-regexp)
6358 '(2 (org-get-todo-face 2) t))
6359 ;; DONE
6360 (if org-fontify-done-headline
6361 (list (format org-heading-keyword-regexp-format
6362 (concat
6363 "\\(?:"
6364 (mapconcat 'regexp-quote org-done-keywords "\\|")
6365 "\\)"))
6366 '(2 'org-headline-done t))
6367 nil)
6368 ;; Priorities
6369 '(org-font-lock-add-priority-faces)
6370 ;; Tags
6371 '(org-font-lock-add-tag-faces)
6372 ;; Tags groups
6373 (when (and org-group-tags org-tag-groups-alist)
6374 (list (concat org-outline-regexp-bol ".+\\(:"
6375 (regexp-opt (mapcar 'car org-tag-groups-alist))
6376 ":\\).*$")
6377 '(1 'org-tag-group prepend)))
6378 ;; Special keywords
6379 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6380 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6381 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6382 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6383 ;; Emphasis
6384 (when em '(org-do-emphasis-faces))
6385 ;; Checkboxes
6386 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6387 1 'org-checkbox prepend)
6388 (when (cdr (assq 'checkbox org-list-automatic-rules))
6389 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6390 (0 (org-get-checkbox-statistics-face) t)))
6391 ;; Description list items
6392 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6393 1 'org-list-dt prepend)
6394 ;; ARCHIVEd headings
6395 (list (concat
6396 org-outline-regexp-bol
6397 "\\(.*:" org-archive-tag ":.*\\)")
6398 '(1 'org-archived prepend))
6399 ;; Specials
6400 '(org-do-latex-and-related)
6401 '(org-fontify-entities)
6402 '(org-raise-scripts)
6403 ;; Code
6404 '(org-activate-code (1 'org-code t))
6405 ;; COMMENT
6406 (list (format
6407 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6408 org-todo-regexp
6409 org-comment-string)
6410 '(9 'org-special-keyword t))
6411 ;; Blocks and meta lines
6412 '(org-fontify-meta-lines-and-blocks))))
6413 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6414 (run-hooks 'org-font-lock-set-keywords-hook)
6415 ;; Now set the full font-lock-keywords
6416 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6417 (setq-local font-lock-defaults
6418 '(org-font-lock-keywords t nil nil backward-paragraph))
6419 (kill-local-variable 'font-lock-keywords)
6420 nil))
6422 (defun org-toggle-pretty-entities ()
6423 "Toggle the composition display of entities as UTF8 characters."
6424 (interactive)
6425 (setq-local org-pretty-entities (not org-pretty-entities))
6426 (org-restart-font-lock)
6427 (if org-pretty-entities
6428 (message "Entities are now displayed as UTF8 characters")
6429 (save-restriction
6430 (widen)
6431 (decompose-region (point-min) (point-max))
6432 (message "Entities are now displayed as plain text"))))
6434 (defvar-local org-custom-properties-overlays nil
6435 "List of overlays used for custom properties.")
6437 (defun org-toggle-custom-properties-visibility ()
6438 "Display or hide properties in `org-custom-properties'."
6439 (interactive)
6440 (if org-custom-properties-overlays
6441 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6442 (setq org-custom-properties-overlays nil))
6443 (when org-custom-properties
6444 (org-with-wide-buffer
6445 (goto-char (point-min))
6446 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6447 (while (re-search-forward regexp nil t)
6448 (let ((end (cdr (save-match-data (org-get-property-block)))))
6449 (when (and end (< (point) end))
6450 ;; Hide first custom property in current drawer.
6451 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6452 (overlay-put o 'invisible t)
6453 (overlay-put o 'org-custom-property t)
6454 (push o org-custom-properties-overlays))
6455 ;; Hide additional custom properties in the same drawer.
6456 (while (re-search-forward regexp end t)
6457 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6458 (overlay-put o 'invisible t)
6459 (overlay-put o 'org-custom-property t)
6460 (push o org-custom-properties-overlays)))))
6461 ;; Each entry is limited to a single property drawer.
6462 (outline-next-heading)))))))
6464 (defun org-fontify-entities (limit)
6465 "Find an entity to fontify."
6466 (let (ee)
6467 (when org-pretty-entities
6468 (catch 'match
6469 ;; "\_ "-family is left out on purpose. Only the first one,
6470 ;; i.e., "\_ ", could be fontified anyway, and it would be
6471 ;; confusing when adding a second white space character.
6472 (while (re-search-forward
6473 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6474 limit t)
6475 (when (and (not (org-at-comment-p))
6476 (setq ee (org-entity-get (match-string 1)))
6477 (= (length (nth 6 ee)) 1))
6478 (let* ((end (if (equal (match-string 2) "{}")
6479 (match-end 2)
6480 (match-end 1))))
6481 (add-text-properties
6482 (match-beginning 0) end
6483 (list 'font-lock-fontified t))
6484 (compose-region (match-beginning 0) end
6485 (nth 6 ee) nil)
6486 (backward-char 1)
6487 (throw 'match t))))
6488 nil))))
6490 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6491 "Fontify string S like in Org mode."
6492 (with-temp-buffer
6493 (insert s)
6494 (let ((org-odd-levels-only odd-levels))
6495 (org-mode)
6496 (org-font-lock-ensure)
6497 (buffer-string))))
6499 (defvar org-m nil)
6500 (defvar org-l nil)
6501 (defvar org-f nil)
6502 (defun org-get-level-face (n)
6503 "Get the right face for match N in font-lock matching of headlines."
6504 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6505 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6506 (if org-cycle-level-faces
6507 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6508 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6509 (cond
6510 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6511 ((eq n 2) org-f)
6512 (t (unless org-level-color-stars-only org-f))))
6514 (defun org-face-from-face-or-color (context inherit face-or-color)
6515 "Create a face list that inherits INHERIT, but sets the foreground color.
6516 When FACE-OR-COLOR is not a string, just return it."
6517 (if (stringp face-or-color)
6518 (list :inherit inherit
6519 (cdr (assoc context org-faces-easy-properties))
6520 face-or-color)
6521 face-or-color))
6523 (defun org-get-todo-face (kwd)
6524 "Get the right face for a TODO keyword KWD.
6525 If KWD is a number, get the corresponding match group."
6526 (when (numberp kwd) (setq kwd (match-string kwd)))
6527 (or (org-face-from-face-or-color
6528 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6529 (and (member kwd org-done-keywords) 'org-done)
6530 'org-todo))
6532 (defun org-get-priority-face (priority)
6533 "Get the right face for PRIORITY.
6534 PRIORITY is a character."
6535 (or (org-face-from-face-or-color
6536 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6537 'org-priority))
6539 (defun org-get-tag-face (tag)
6540 "Get the right face for TAG.
6541 If TAG is a number, get the corresponding match group."
6542 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6543 (or (org-face-from-face-or-color
6544 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6545 'org-tag)))
6547 (defun org-font-lock-add-priority-faces (limit)
6548 "Add the special priority faces."
6549 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6550 (add-text-properties
6551 (match-beginning 1) (match-end 1)
6552 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6553 'font-lock-fontified t))))
6555 (defun org-font-lock-add-tag-faces (limit)
6556 "Add the special tag faces."
6557 (when (and org-tag-faces org-tags-special-faces-re)
6558 (while (re-search-forward org-tags-special-faces-re limit t)
6559 (add-text-properties (match-beginning 1) (match-end 1)
6560 (list 'face (org-get-tag-face 1)
6561 'font-lock-fontified t))
6562 (backward-char 1))))
6564 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6565 "Remove fontification and activation overlays from links."
6566 (font-lock-default-unfontify-region beg end)
6567 (let* ((buffer-undo-list t)
6568 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6569 (inhibit-modification-hooks t)
6570 deactivate-mark buffer-file-name buffer-file-truename)
6571 (decompose-region beg end)
6572 (remove-text-properties beg end
6573 '(mouse-face t keymap t org-linked-text t
6574 invisible t intangible t
6575 org-emphasis t))
6576 (org-remove-font-lock-display-properties beg end)))
6578 (defconst org-script-display '(((raise -0.3) (height 0.7))
6579 ((raise 0.3) (height 0.7))
6580 ((raise -0.5))
6581 ((raise 0.5)))
6582 "Display properties for showing superscripts and subscripts.")
6584 (defun org-remove-font-lock-display-properties (beg end)
6585 "Remove specific display properties that have been added by font lock.
6586 The will remove the raise properties that are used to show superscripts
6587 and subscripts."
6588 (let (next prop)
6589 (while (< beg end)
6590 (setq next (next-single-property-change beg 'display nil end)
6591 prop (get-text-property beg 'display))
6592 (when (member prop org-script-display)
6593 (put-text-property beg next 'display nil))
6594 (setq beg next))))
6596 (defun org-raise-scripts (limit)
6597 "Add raise properties to sub/superscripts."
6598 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6599 (re-search-forward
6600 (if (eq org-use-sub-superscripts t)
6601 org-match-substring-regexp
6602 org-match-substring-with-braces-regexp)
6603 limit t))
6604 (let* ((pos (point)) table-p comment-p
6605 (mpos (match-beginning 3))
6606 (emph-p (get-text-property mpos 'org-emphasis))
6607 (link-p (get-text-property mpos 'mouse-face))
6608 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6609 (goto-char (point-at-bol))
6610 (setq table-p (looking-at-p org-table-dataline-regexp)
6611 comment-p (looking-at-p "^[ \t]*#[ +]"))
6612 (goto-char pos)
6613 ;; Handle a_b^c
6614 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6615 (unless (or comment-p emph-p link-p keyw-p)
6616 (put-text-property (match-beginning 3) (match-end 0)
6617 'display
6618 (if (equal (char-after (match-beginning 2)) ?^)
6619 (nth (if table-p 3 1) org-script-display)
6620 (nth (if table-p 2 0) org-script-display)))
6621 (add-text-properties (match-beginning 2) (match-end 2)
6622 (list 'invisible t))
6623 (when (and (eq (char-after (match-beginning 3)) ?{)
6624 (eq (char-before (match-end 3)) ?}))
6625 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6626 (list 'invisible t))
6627 (add-text-properties (1- (match-end 3)) (match-end 3)
6628 (list 'invisible t))))
6629 t)))
6631 ;;;; Visibility cycling, including org-goto and indirect buffer
6633 ;;; Cycling
6635 (defvar-local org-cycle-global-status nil)
6636 (put 'org-cycle-global-status 'org-state t)
6637 (defvar-local org-cycle-subtree-status nil)
6638 (put 'org-cycle-subtree-status 'org-state t)
6640 (defvar org-inlinetask-min-level)
6642 (defun org-unlogged-message (&rest args)
6643 "Display a message, but avoid logging it in the *Messages* buffer."
6644 (let ((message-log-max nil))
6645 (apply 'message args)))
6647 ;;;###autoload
6648 (defun org-cycle (&optional arg)
6649 "TAB-action and visibility cycling for Org mode.
6651 This is the command invoked in Org mode by the `TAB' key. Its main
6652 purpose is outline visibility cycling, but it also invokes other actions
6653 in special contexts.
6655 When this function is called with a `\\[universal-argument]' prefix, rotate \
6656 the entire
6657 buffer through 3 states (global cycling)
6658 1. OVERVIEW: Show only top-level headlines.
6659 2. CONTENTS: Show all headlines of all levels, but no body text.
6660 3. SHOW ALL: Show everything.
6662 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6663 switch to the startup visibility,
6664 determined by the variable `org-startup-folded', and by any VISIBILITY
6665 properties in the buffer.
6667 With a `\\[universal-argument] \\[universal-argument] \
6668 \\[universal-argument]' prefix argument, show the entire buffer, including
6669 any drawers.
6671 When inside a table, re-align the table and move to the next field.
6673 When point is at the beginning of a headline, rotate the subtree started
6674 by this line through 3 different states (local cycling)
6675 1. FOLDED: Only the main headline is shown.
6676 2. CHILDREN: The main headline and the direct children are shown.
6677 From this state, you can move to one of the children
6678 and zoom in further.
6679 3. SUBTREE: Show the entire subtree, including body text.
6680 If there is no subtree, switch directly from CHILDREN to FOLDED.
6682 When point is at the beginning of an empty headline and the variable
6683 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6684 of the headline by demoting and promoting it to likely levels. This
6685 speeds up creation document structure by pressing `TAB' once or several
6686 times right after creating a new headline.
6688 When there is a numeric prefix, go up to a heading with level ARG, do
6689 a `show-subtree' and return to the previous cursor position. If ARG
6690 is negative, go up that many levels.
6692 When point is not at the beginning of a headline, execute the global
6693 binding for `TAB', which is re-indenting the line. See the option
6694 `org-cycle-emulate-tab' for details.
6696 As a special case, if point is at the beginning of the buffer and there is
6697 no headline in line 1, this function will act as if called with prefix arg
6698 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6699 prefix arg, but only
6700 if the variable `org-cycle-global-at-bob' is t."
6701 (interactive "P")
6702 (org-load-modules-maybe)
6703 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6704 (and org-cycle-level-after-item/entry-creation
6705 (or (org-cycle-level)
6706 (org-cycle-item-indentation))))
6707 (let* ((limit-level
6708 (or org-cycle-max-level
6709 (and (boundp 'org-inlinetask-min-level)
6710 org-inlinetask-min-level
6711 (1- org-inlinetask-min-level))))
6712 (nstars (and limit-level
6713 (if org-odd-levels-only
6714 (and limit-level (1- (* limit-level 2)))
6715 limit-level)))
6716 (org-outline-regexp
6717 (if (not (derived-mode-p 'org-mode))
6718 outline-regexp
6719 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6720 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6721 (not (looking-at org-outline-regexp))))
6722 (org-cycle-hook
6723 (if bob-special
6724 (delq 'org-optimize-window-after-visibility-change
6725 (copy-sequence org-cycle-hook))
6726 org-cycle-hook))
6727 (pos (point)))
6729 (cond
6731 ((equal arg '(16))
6732 (setq last-command 'dummy)
6733 (org-set-startup-visibility)
6734 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6736 ((equal arg '(64))
6737 (outline-show-all)
6738 (org-unlogged-message "Entire buffer visible, including drawers"))
6740 ((equal arg '(4)) (org-cycle-internal-global))
6742 ;; Try hiding block at point.
6743 ((org-hide-block-toggle-maybe))
6745 ;; Try cdlatex TAB completion
6746 ((org-try-cdlatex-tab))
6748 ;; Table: enter it or move to the next field.
6749 ((org-at-table-p 'any)
6750 (if (org-at-table.el-p)
6751 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6752 Use `\\[org-edit-special]' to edit table.el tables"))
6753 (if arg (org-table-edit-field t)
6754 (org-table-justify-field-maybe)
6755 (call-interactively 'org-table-next-field))))
6757 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6759 ;; Global cycling: delegate to `org-cycle-internal-global'.
6760 (bob-special (org-cycle-internal-global))
6762 ;; Drawers: delegate to `org-flag-drawer'.
6763 ((save-excursion
6764 (beginning-of-line 1)
6765 (looking-at org-drawer-regexp))
6766 (org-flag-drawer ; toggle block visibility
6767 (not (get-char-property (match-end 0) 'invisible))))
6769 ;; Show-subtree, ARG levels up from here.
6770 ((integerp arg)
6771 (save-excursion
6772 (org-back-to-heading)
6773 (outline-up-heading (if (< arg 0) (- arg)
6774 (- (funcall outline-level) arg)))
6775 (org-show-subtree)))
6777 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6778 ((and (featurep 'org-inlinetask)
6779 (org-inlinetask-at-task-p)
6780 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6781 (org-inlinetask-toggle-visibility))
6783 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6784 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6785 (save-excursion (move-beginning-of-line 1)
6786 (looking-at org-outline-regexp)))
6787 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6788 (org-cycle-internal-local))
6790 ;; From there: TAB emulation and template completion.
6791 (buffer-read-only (org-back-to-heading))
6793 ((run-hook-with-args-until-success
6794 'org-tab-after-check-for-cycling-hook))
6796 ((org-try-structure-completion))
6798 ((run-hook-with-args-until-success
6799 'org-tab-before-tab-emulation-hook))
6801 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6802 (or (not (bolp))
6803 (not (looking-at org-outline-regexp))))
6804 (call-interactively (global-key-binding "\t")))
6806 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6807 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6808 (or (and (eq org-cycle-emulate-tab 'white)
6809 (= (match-end 0) (point-at-eol)))
6810 (and (eq org-cycle-emulate-tab 'whitestart)
6811 (>= (match-end 0) pos))))
6813 (eq org-cycle-emulate-tab t))
6814 (call-interactively (global-key-binding "\t")))
6816 (t (save-excursion
6817 (org-back-to-heading)
6818 (org-cycle)))))))
6820 (defun org-cycle-internal-global ()
6821 "Do the global cycling action."
6822 ;; Hack to avoid display of messages for .org attachments in Gnus
6823 (let ((ga (string-match "\\*fontification" (buffer-name))))
6824 (cond
6825 ((and (eq last-command this-command)
6826 (eq org-cycle-global-status 'overview))
6827 ;; We just created the overview - now do table of contents
6828 ;; This can be slow in very large buffers, so indicate action
6829 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6830 (unless ga (org-unlogged-message "CONTENTS..."))
6831 (org-content)
6832 (unless ga (org-unlogged-message "CONTENTS...done"))
6833 (setq org-cycle-global-status 'contents)
6834 (run-hook-with-args 'org-cycle-hook 'contents))
6836 ((and (eq last-command this-command)
6837 (eq org-cycle-global-status 'contents))
6838 ;; We just showed the table of contents - now show everything
6839 (run-hook-with-args 'org-pre-cycle-hook 'all)
6840 (outline-show-all)
6841 (unless ga (org-unlogged-message "SHOW ALL"))
6842 (setq org-cycle-global-status 'all)
6843 (run-hook-with-args 'org-cycle-hook 'all))
6846 ;; Default action: go to overview
6847 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6848 (org-overview)
6849 (unless ga (org-unlogged-message "OVERVIEW"))
6850 (setq org-cycle-global-status 'overview)
6851 (run-hook-with-args 'org-cycle-hook 'overview)))))
6853 (defvar org-called-with-limited-levels nil
6854 "Non-nil when `org-with-limited-levels' is currently active.")
6856 (defun org-invisible-p (&optional pos)
6857 "Non-nil if the character after POS is invisible.
6858 If POS is nil, use `point' instead."
6859 (get-char-property (or pos (point)) 'invisible))
6861 (defun org-cycle-internal-local ()
6862 "Do the local cycling action."
6863 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6864 ;; First, determine end of headline (EOH), end of subtree or item
6865 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6866 (save-excursion
6867 (if (org-at-item-p)
6868 (progn
6869 (beginning-of-line)
6870 (setq struct (org-list-struct))
6871 (setq eoh (point-at-eol))
6872 (setq eos (org-list-get-item-end-before-blank (point) struct))
6873 (setq has-children (org-list-has-child-p (point) struct)))
6874 (org-back-to-heading)
6875 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6876 (setq eos (save-excursion (org-end-of-subtree t t)
6877 (when (bolp) (backward-char)) (point)))
6878 (setq has-children
6879 (or (save-excursion
6880 (let ((level (funcall outline-level)))
6881 (outline-next-heading)
6882 (and (org-at-heading-p t)
6883 (> (funcall outline-level) level))))
6884 (save-excursion
6885 (org-list-search-forward (org-item-beginning-re) eos t)))))
6886 ;; Determine end invisible part of buffer (EOL)
6887 (beginning-of-line 2)
6888 (while (and (not (eobp)) ;This is like `next-line'.
6889 (get-char-property (1- (point)) 'invisible))
6890 (goto-char (next-single-char-property-change (point) 'invisible))
6891 (and (eolp) (beginning-of-line 2)))
6892 (setq eol (point)))
6893 ;; Find out what to do next and set `this-command'
6894 (cond
6895 ((= eos eoh)
6896 ;; Nothing is hidden behind this heading
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6899 (org-unlogged-message "EMPTY ENTRY")
6900 (setq org-cycle-subtree-status nil)
6901 (save-excursion
6902 (goto-char eos)
6903 (outline-next-heading)
6904 (when (org-invisible-p) (org-flag-heading nil))))
6905 ((and (or (>= eol eos)
6906 (not (string-match "\\S-" (buffer-substring eol eos))))
6907 (or has-children
6908 (not (setq children-skipped
6909 org-cycle-skip-children-state-if-no-children))))
6910 ;; Entire subtree is hidden in one line: children view
6911 (unless (org-before-first-heading-p)
6912 (run-hook-with-args 'org-pre-cycle-hook 'children))
6913 (if (org-at-item-p)
6914 (org-list-set-item-visibility (point-at-bol) struct 'children)
6915 (org-show-entry)
6916 (org-with-limited-levels (org-show-children))
6917 ;; FIXME: This slows down the func way too much.
6918 ;; How keep drawers hidden in subtree anyway?
6919 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6920 ;; (org-cycle-hide-drawers 'subtree))
6922 ;; Fold every list in subtree to top-level items.
6923 (when (eq org-cycle-include-plain-lists 'integrate)
6924 (save-excursion
6925 (org-back-to-heading)
6926 (while (org-list-search-forward (org-item-beginning-re) eos t)
6927 (beginning-of-line 1)
6928 (let* ((struct (org-list-struct))
6929 (prevs (org-list-prevs-alist struct))
6930 (end (org-list-get-bottom-point struct)))
6931 (dolist (e (org-list-get-all-items (point) struct prevs))
6932 (org-list-set-item-visibility e struct 'folded))
6933 (goto-char (if (< end eos) end eos)))))))
6934 (org-unlogged-message "CHILDREN")
6935 (save-excursion
6936 (goto-char eos)
6937 (outline-next-heading)
6938 (when (org-invisible-p) (org-flag-heading nil)))
6939 (setq org-cycle-subtree-status 'children)
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-cycle-hook 'children)))
6942 ((or children-skipped
6943 (and (eq last-command this-command)
6944 (eq org-cycle-subtree-status 'children)))
6945 ;; We just showed the children, or no children are there,
6946 ;; now show everything.
6947 (unless (org-before-first-heading-p)
6948 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6949 (outline-flag-region eoh eos nil)
6950 (org-unlogged-message
6951 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6952 (setq org-cycle-subtree-status 'subtree)
6953 (unless (org-before-first-heading-p)
6954 (run-hook-with-args 'org-cycle-hook 'subtree)))
6956 ;; Default action: hide the subtree.
6957 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6958 (outline-flag-region eoh eos t)
6959 (org-unlogged-message "FOLDED")
6960 (setq org-cycle-subtree-status 'folded)
6961 (unless (org-before-first-heading-p)
6962 (run-hook-with-args 'org-cycle-hook 'folded))))))
6964 ;;;###autoload
6965 (defun org-global-cycle (&optional arg)
6966 "Cycle the global visibility. For details see `org-cycle'.
6967 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6968 With a numeric prefix, show all headlines up to that level."
6969 (interactive "P")
6970 (let ((org-cycle-include-plain-lists
6971 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6972 (cond
6973 ((integerp arg)
6974 (outline-show-all)
6975 (outline-hide-sublevels arg)
6976 (setq org-cycle-global-status 'contents))
6977 ((equal arg '(4))
6978 (org-set-startup-visibility)
6979 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6981 (org-cycle '(4))))))
6983 (defun org-set-startup-visibility ()
6984 "Set the visibility required by startup options and properties."
6985 (cond
6986 ((eq org-startup-folded t)
6987 (org-overview))
6988 ((eq org-startup-folded 'content)
6989 (org-content))
6990 ((or (eq org-startup-folded 'showeverything)
6991 (eq org-startup-folded nil))
6992 (outline-show-all)))
6993 (unless (eq org-startup-folded 'showeverything)
6994 (when org-hide-block-startup (org-hide-block-all))
6995 (org-set-visibility-according-to-property 'no-cleanup)
6996 (org-cycle-hide-archived-subtrees 'all)
6997 (org-cycle-hide-drawers 'all)
6998 (org-cycle-show-empty-lines t)))
7000 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7001 "Switch subtree visibilities according to :VISIBILITY: property."
7002 (interactive)
7003 (org-with-wide-buffer
7004 (goto-char (point-min))
7005 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7006 (if (not (org-at-property-p)) (outline-next-heading)
7007 (let ((state (match-string 3)))
7008 (save-excursion
7009 (org-back-to-heading t)
7010 (outline-hide-subtree)
7011 (org-reveal)
7012 (cond
7013 ((equal state "folded")
7014 (outline-hide-subtree))
7015 ((equal state "children")
7016 (org-show-hidden-entry)
7017 (org-show-children))
7018 ((equal state "content")
7019 (save-excursion
7020 (save-restriction
7021 (org-narrow-to-subtree)
7022 (org-content))))
7023 ((member state '("all" "showall"))
7024 (outline-show-subtree)))))))
7025 (unless no-cleanup
7026 (org-cycle-hide-archived-subtrees 'all)
7027 (org-cycle-hide-drawers 'all)
7028 (org-cycle-show-empty-lines 'all))))
7030 ;; This function uses outline-regexp instead of the more fundamental
7031 ;; org-outline-regexp so that org-cycle-global works outside of Org
7032 ;; buffers, where outline-regexp is needed.
7033 (defun org-overview ()
7034 "Switch to overview mode, showing only top-level headlines.
7035 This shows all headlines with a level equal or greater than the level
7036 of the first headline in the buffer. This is important, because if the
7037 first headline is not level one, then (hide-sublevels 1) gives confusing
7038 results."
7039 (interactive)
7040 (save-excursion
7041 (let ((level
7042 (save-excursion
7043 (goto-char (point-min))
7044 (when (re-search-forward (concat "^" outline-regexp) nil t)
7045 (goto-char (match-beginning 0))
7046 (funcall outline-level)))))
7047 (and level (outline-hide-sublevels level)))))
7049 (defun org-content (&optional arg)
7050 "Show all headlines in the buffer, like a table of contents.
7051 With numerical argument N, show content up to level N."
7052 (interactive "P")
7053 (org-overview)
7054 (save-excursion
7055 ;; Visit all headings and show their offspring
7056 (and (integerp arg) (org-overview))
7057 (goto-char (point-max))
7058 (catch 'exit
7059 (while (and (progn (condition-case nil
7060 (outline-previous-visible-heading 1)
7061 (error (goto-char (point-min))))
7063 (looking-at org-outline-regexp))
7064 (if (integerp arg)
7065 (org-show-children (1- arg))
7066 (outline-show-branches))
7067 (when (bobp) (throw 'exit nil))))))
7069 (defun org-optimize-window-after-visibility-change (state)
7070 "Adjust the window after a change in outline visibility.
7071 This function is the default value of the hook `org-cycle-hook'."
7072 (when (get-buffer-window (current-buffer))
7073 (cond
7074 ((eq state 'content) nil)
7075 ((eq state 'all) nil)
7076 ((eq state 'folded) nil)
7077 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7078 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7080 (defun org-remove-empty-overlays-at (pos)
7081 "Remove outline overlays that do not contain non-white stuff."
7082 (dolist (o (overlays-at pos))
7083 (and (eq 'outline (overlay-get o 'invisible))
7084 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7085 (overlay-end o))))
7086 (delete-overlay o))))
7088 (defun org-clean-visibility-after-subtree-move ()
7089 "Fix visibility issues after moving a subtree."
7090 ;; First, find a reasonable region to look at:
7091 ;; Start two siblings above, end three below
7092 (let* ((beg (save-excursion
7093 (and (org-get-last-sibling)
7094 (org-get-last-sibling))
7095 (point)))
7096 (end (save-excursion
7097 (and (org-get-next-sibling)
7098 (org-get-next-sibling)
7099 (org-get-next-sibling))
7100 (if (org-at-heading-p)
7101 (point-at-eol)
7102 (point))))
7103 (level (looking-at "\\*+"))
7104 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7105 (save-excursion
7106 (save-restriction
7107 (narrow-to-region beg end)
7108 (when re
7109 ;; Properly fold already folded siblings
7110 (goto-char (point-min))
7111 (while (re-search-forward re nil t)
7112 (when (and (not (org-invisible-p))
7113 (save-excursion
7114 (goto-char (point-at-eol)) (org-invisible-p)))
7115 (outline-hide-entry))))
7116 (org-cycle-show-empty-lines 'overview)
7117 (org-cycle-hide-drawers 'overview)))))
7119 (defun org-cycle-show-empty-lines (state)
7120 "Show empty lines above all visible headlines.
7121 The region to be covered depends on STATE when called through
7122 `org-cycle-hook'. Lisp program can use t for STATE to get the
7123 entire buffer covered. Note that an empty line is only shown if there
7124 are at least `org-cycle-separator-lines' empty lines before the headline."
7125 (when (/= org-cycle-separator-lines 0)
7126 (save-excursion
7127 (let* ((n (abs org-cycle-separator-lines))
7128 (re (cond
7129 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7130 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7131 (t (let ((ns (number-to-string (- n 2))))
7132 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7133 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7134 beg end)
7135 (cond
7136 ((memq state '(overview contents t))
7137 (setq beg (point-min) end (point-max)))
7138 ((memq state '(children folded))
7139 (setq beg (point)
7140 end (progn (org-end-of-subtree t t)
7141 (line-beginning-position 2)))))
7142 (when beg
7143 (goto-char beg)
7144 (while (re-search-forward re end t)
7145 (unless (get-char-property (match-end 1) 'invisible)
7146 (let ((e (match-end 1))
7147 (b (if (>= org-cycle-separator-lines 0)
7148 (match-beginning 1)
7149 (save-excursion
7150 (goto-char (match-beginning 0))
7151 (skip-chars-backward " \t\n")
7152 (line-end-position)))))
7153 (outline-flag-region b e nil))))))))
7154 ;; Never hide empty lines at the end of the file.
7155 (save-excursion
7156 (goto-char (point-max))
7157 (outline-previous-heading)
7158 (outline-end-of-heading)
7159 (when (and (looking-at "[ \t\n]+")
7160 (= (match-end 0) (point-max)))
7161 (outline-flag-region (point) (match-end 0) nil))))
7163 (defun org-show-empty-lines-in-parent ()
7164 "Move to the parent and re-show empty lines before visible headlines."
7165 (save-excursion
7166 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7167 (org-cycle-show-empty-lines context))))
7169 (defun org-files-list ()
7170 "Return `org-agenda-files' list, plus all open Org files.
7171 This is useful for operations that need to scan all of a user's
7172 open and agenda-wise Org files."
7173 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7174 (dolist (buf (buffer-list))
7175 (with-current-buffer buf
7176 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7177 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7178 files))
7180 (defsubst org-entry-beginning-position ()
7181 "Return the beginning position of the current entry."
7182 (save-excursion (org-back-to-heading t) (point)))
7184 (defsubst org-entry-end-position ()
7185 "Return the end position of the current entry."
7186 (save-excursion (outline-next-heading) (point)))
7188 (defun org-cycle-hide-drawers (state &optional exceptions)
7189 "Re-hide all drawers after a visibility state change.
7190 STATE should be one of the symbols listed in the docstring of
7191 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7192 a list of strings specifying which drawers should not be hidden."
7193 (when (and (derived-mode-p 'org-mode)
7194 (not (memq state '(overview folded contents))))
7195 (save-excursion
7196 (let* ((globalp (eq state 'all))
7197 (beg (if globalp (point-min) (point)))
7198 (end (if globalp (point-max)
7199 (if (eq state 'children)
7200 (save-excursion (outline-next-heading) (point))
7201 (org-end-of-subtree t)))))
7202 (goto-char beg)
7203 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7204 (unless (member-ignore-case (match-string 1) exceptions)
7205 (let ((drawer (org-element-at-point)))
7206 (when (memq (org-element-type drawer) '(drawer property-drawer))
7207 (org-flag-drawer t drawer)
7208 ;; Make sure to skip drawer entirely or we might flag
7209 ;; it another time when matching its ending line with
7210 ;; `org-drawer-regexp'.
7211 (goto-char (org-element-property :end drawer))))))))))
7213 (defun org-flag-drawer (flag &optional element)
7214 "When FLAG is non-nil, hide the drawer we are at.
7215 Otherwise make it visible. When optional argument ELEMENT is
7216 a parsed drawer, as returned by `org-element-at-point', hide or
7217 show that drawer instead."
7218 (let ((drawer (or element
7219 (and (save-excursion
7220 (beginning-of-line)
7221 (looking-at-p org-drawer-regexp))
7222 (org-element-at-point)))))
7223 (when (memq (org-element-type drawer) '(drawer property-drawer))
7224 (let ((post (org-element-property :post-affiliated drawer)))
7225 (save-excursion
7226 (outline-flag-region
7227 (progn (goto-char post) (line-end-position))
7228 (progn (goto-char (org-element-property :end drawer))
7229 (skip-chars-backward " \r\t\n")
7230 (line-end-position))
7231 flag))
7232 ;; When the drawer is hidden away, make sure point lies in
7233 ;; a visible part of the buffer.
7234 (when (and flag (> (line-beginning-position) post))
7235 (goto-char post))))))
7237 (defun org-subtree-end-visible-p ()
7238 "Is the end of the current subtree visible?"
7239 (pos-visible-in-window-p
7240 (save-excursion (org-end-of-subtree t) (point))))
7242 (defun org-first-headline-recenter ()
7243 "Move cursor to the first headline and recenter the headline."
7244 (let ((window (get-buffer-window)))
7245 (when window
7246 (goto-char (point-min))
7247 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7248 (set-window-start window (line-beginning-position))))))
7250 ;;; Saving and restoring visibility
7252 (defun org-outline-overlay-data (&optional use-markers)
7253 "Return a list of the locations of all outline overlays.
7254 These are overlays with the `invisible' property value `outline'.
7255 The return value is a list of cons cells, with start and stop
7256 positions for each overlay.
7257 If USE-MARKERS is set, return the positions as markers."
7258 (let (beg end)
7259 (org-with-wide-buffer
7260 (delq nil
7261 (mapcar (lambda (o)
7262 (when (eq (overlay-get o 'invisible) 'outline)
7263 (setq beg (overlay-start o)
7264 end (overlay-end o))
7265 (and beg end (> end beg)
7266 (if use-markers
7267 (cons (copy-marker beg)
7268 (copy-marker end t))
7269 (cons beg end)))))
7270 (overlays-in (point-min) (point-max)))))))
7272 (defun org-set-outline-overlay-data (data)
7273 "Create visibility overlays for all positions in DATA.
7274 DATA should have been made by `org-outline-overlay-data'."
7275 (org-with-wide-buffer
7276 (outline-show-all)
7277 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7279 ;;; Folding of blocks
7281 (defvar-local org-hide-block-overlays nil
7282 "Overlays hiding blocks.")
7284 (defun org-block-map (function &optional start end)
7285 "Call FUNCTION at the head of all source blocks in the current buffer.
7286 Optional arguments START and END can be used to limit the range."
7287 (let ((start (or start (point-min)))
7288 (end (or end (point-max))))
7289 (save-excursion
7290 (goto-char start)
7291 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7292 (save-excursion
7293 (save-match-data
7294 (goto-char (match-beginning 0))
7295 (funcall function)))))))
7297 (defun org-hide-block-toggle-all ()
7298 "Toggle the visibility of all blocks in the current buffer."
7299 (org-block-map 'org-hide-block-toggle))
7301 (defun org-hide-block-all ()
7302 "Fold all blocks in the current buffer."
7303 (interactive)
7304 (org-show-block-all)
7305 (org-block-map 'org-hide-block-toggle-maybe))
7307 (defun org-show-block-all ()
7308 "Unfold all blocks in the current buffer."
7309 (interactive)
7310 (mapc #'delete-overlay org-hide-block-overlays)
7311 (setq org-hide-block-overlays nil))
7313 (defun org-hide-block-toggle-maybe ()
7314 "Toggle visibility of block at point.
7315 Unlike to `org-hide-block-toggle', this function does not throw
7316 an error. Return a non-nil value when toggling is successful."
7317 (interactive)
7318 (ignore-errors (org-hide-block-toggle)))
7320 (defun org-hide-block-toggle (&optional force)
7321 "Toggle the visibility of the current block.
7322 When optional argument FORCE is `off', make block visible. If it
7323 is non-nil, hide it unconditionally. Throw an error when not at
7324 a block. Return a non-nil value when toggling is successful."
7325 (interactive)
7326 (let ((element (org-element-at-point)))
7327 (unless (memq (org-element-type element)
7328 '(center-block comment-block dynamic-block example-block
7329 export-block quote-block special-block
7330 src-block verse-block))
7331 (user-error "Not at a block"))
7332 (let* ((start (save-excursion
7333 (goto-char (org-element-property :post-affiliated element))
7334 (line-end-position)))
7335 (end (save-excursion
7336 (goto-char (org-element-property :end element))
7337 (skip-chars-backward " \r\t\n")
7338 (line-end-position)))
7339 (overlays (overlays-at start)))
7340 (cond
7341 ;; Do nothing when not before or at the block opening line or
7342 ;; at the block closing line.
7343 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7344 ((and (not (eq force 'off))
7345 (not (memq t (mapcar
7346 (lambda (o)
7347 (eq (overlay-get o 'invisible) 'org-hide-block))
7348 overlays))))
7349 (let ((ov (make-overlay start end)))
7350 (overlay-put ov 'invisible 'org-hide-block)
7351 ;; Make the block accessible to `isearch'.
7352 (overlay-put
7353 ov 'isearch-open-invisible
7354 (lambda (ov)
7355 (when (memq ov org-hide-block-overlays)
7356 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7357 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7358 (delete-overlay ov))))
7359 (push ov org-hide-block-overlays)
7360 ;; When the block is hidden away, make sure point is left in
7361 ;; a visible part of the buffer.
7362 (when (> (line-beginning-position) start)
7363 (goto-char start)
7364 (beginning-of-line))
7365 ;; Signal successful toggling.
7367 ((or (not force) (eq force 'off))
7368 (dolist (ov overlays t)
7369 (when (memq ov org-hide-block-overlays)
7370 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7371 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7372 (delete-overlay ov))))))))
7374 ;; Remove overlays when changing major mode
7375 (add-hook 'org-mode-hook
7376 (lambda () (add-hook 'change-major-mode-hook
7377 'org-show-block-all 'append 'local)))
7379 ;;; Org-goto
7381 (defvar org-goto-window-configuration nil)
7382 (defvar org-goto-marker nil)
7383 (defvar org-goto-map)
7384 (defun org-goto-map ()
7385 "Set the keymap `org-goto'."
7386 (setq org-goto-map
7387 (let ((map (make-sparse-keymap)))
7388 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7389 mouse-drag-region universal-argument org-occur)))
7390 (dolist (cmd cmds)
7391 (substitute-key-definition cmd cmd map global-map)))
7392 (suppress-keymap map)
7393 (org-defkey map "\C-m" 'org-goto-ret)
7394 (org-defkey map [(return)] 'org-goto-ret)
7395 (org-defkey map [(left)] 'org-goto-left)
7396 (org-defkey map [(right)] 'org-goto-right)
7397 (org-defkey map [(control ?g)] 'org-goto-quit)
7398 (org-defkey map "\C-i" 'org-cycle)
7399 (org-defkey map [(tab)] 'org-cycle)
7400 (org-defkey map [(down)] 'outline-next-visible-heading)
7401 (org-defkey map [(up)] 'outline-previous-visible-heading)
7402 (if org-goto-auto-isearch
7403 (if (fboundp 'define-key-after)
7404 (define-key-after map [t] 'org-goto-local-auto-isearch)
7405 nil)
7406 (org-defkey map "q" 'org-goto-quit)
7407 (org-defkey map "n" 'outline-next-visible-heading)
7408 (org-defkey map "p" 'outline-previous-visible-heading)
7409 (org-defkey map "f" 'outline-forward-same-level)
7410 (org-defkey map "b" 'outline-backward-same-level)
7411 (org-defkey map "u" 'outline-up-heading))
7412 (org-defkey map "/" 'org-occur)
7413 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7414 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7415 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7416 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7417 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7418 map)))
7420 (defconst org-goto-help
7421 "Browse buffer copy, to find location or copy text.%s
7422 RET=jump to location C-g=quit and return to previous location
7423 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7425 (defvar org-goto-start-pos) ; dynamically scoped parameter
7427 (defun org-goto (&optional alternative-interface)
7428 "Look up a different location in the current file, keeping current visibility.
7430 When you want look-up or go to a different location in a
7431 document, the fastest way is often to fold the entire buffer and
7432 then dive into the tree. This method has the disadvantage, that
7433 the previous location will be folded, which may not be what you
7434 want.
7436 This command works around this by showing a copy of the current
7437 buffer in an indirect buffer, in overview mode. You can dive
7438 into the tree in that copy, use org-occur and incremental search
7439 to find a location. When pressing RET or `Q', the command
7440 returns to the original buffer in which the visibility is still
7441 unchanged. After RET it will also jump to the location selected
7442 in the indirect buffer and expose the headline hierarchy above.
7444 With a prefix argument, use the alternative interface: e.g., if
7445 `org-goto-interface' is `outline' use `outline-path-completion'."
7446 (interactive "P")
7447 (org-goto-map)
7448 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7449 (org-refile-use-outline-path t)
7450 (org-refile-target-verify-function nil)
7451 (interface
7452 (if (not alternative-interface)
7453 org-goto-interface
7454 (if (eq org-goto-interface 'outline)
7455 'outline-path-completion
7456 'outline)))
7457 (org-goto-start-pos (point))
7458 (selected-point
7459 (if (eq interface 'outline)
7460 (car (org-get-location (current-buffer) org-goto-help))
7461 (let ((pa (org-refile-get-location "Goto")))
7462 (org-refile-check-position pa)
7463 (nth 3 pa)))))
7464 (if selected-point
7465 (progn
7466 (org-mark-ring-push org-goto-start-pos)
7467 (goto-char selected-point)
7468 (when (or (org-invisible-p) (org-invisible-p2))
7469 (org-show-context 'org-goto)))
7470 (message "Quit"))))
7472 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7473 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7474 (defvar org-goto-local-auto-isearch-map) ; defined below
7476 (defun org-get-location (_buf help)
7477 "Let the user select a location in current buffer.
7478 This function uses a recursive edit. It returns the selected position
7479 or nil."
7480 (org-no-popups
7481 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7482 (isearch-hide-immediately nil)
7483 (isearch-search-fun-function
7484 (lambda () 'org-goto-local-search-headings))
7485 (org-goto-selected-point org-goto-exit-command))
7486 (save-excursion
7487 (save-window-excursion
7488 (delete-other-windows)
7489 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7490 (pop-to-buffer-same-window
7491 (condition-case nil
7492 (make-indirect-buffer (current-buffer) "*org-goto*")
7493 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7494 (with-output-to-temp-buffer "*Org Help*"
7495 (princ (format help (if org-goto-auto-isearch
7496 " Just type for auto-isearch."
7497 " n/p/f/b/u to navigate, q to quit."))))
7498 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7499 (setq buffer-read-only nil)
7500 (let ((org-startup-truncated t)
7501 (org-startup-folded nil)
7502 (org-startup-align-all-tables nil))
7503 (org-mode)
7504 (org-overview))
7505 (setq buffer-read-only t)
7506 (if (and (boundp 'org-goto-start-pos)
7507 (integer-or-marker-p org-goto-start-pos))
7508 (progn (goto-char org-goto-start-pos)
7509 (when (org-invisible-p)
7510 (org-show-set-visibility 'lineage)))
7511 (goto-char (point-min)))
7512 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7513 (message "Select location and press RET")
7514 (use-local-map org-goto-map)
7515 (recursive-edit)))
7516 (kill-buffer "*org-goto*")
7517 (cons org-goto-selected-point org-goto-exit-command))))
7519 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7520 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7521 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7522 (if (fboundp 'isearch-other-control-char)
7523 (progn
7524 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7525 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7526 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7527 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7528 (define-key org-goto-local-auto-isearch-map [return] nil))
7530 (defun org-goto-local-search-headings (string bound noerror)
7531 "Search and make sure that any matches are in headlines."
7532 (catch 'return
7533 (while (if isearch-forward
7534 (search-forward string bound noerror)
7535 (search-backward string bound noerror))
7536 (when (save-match-data
7537 (and (save-excursion
7538 (beginning-of-line)
7539 (looking-at org-complex-heading-regexp))
7540 (or (not (match-beginning 5))
7541 (< (point) (match-beginning 5)))))
7542 (throw 'return (point))))))
7544 (defun org-goto-local-auto-isearch ()
7545 "Start isearch."
7546 (interactive)
7547 (goto-char (point-min))
7548 (let ((keys (this-command-keys)))
7549 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7550 (isearch-mode t)
7551 (isearch-process-search-char (string-to-char keys)))))
7553 (defun org-goto-ret (&optional _arg)
7554 "Finish `org-goto' by going to the new location."
7555 (interactive "P")
7556 (setq org-goto-selected-point (point))
7557 (setq org-goto-exit-command 'return)
7558 (throw 'exit nil))
7560 (defun org-goto-left ()
7561 "Finish `org-goto' by going to the new location."
7562 (interactive)
7563 (if (org-at-heading-p)
7564 (progn
7565 (beginning-of-line 1)
7566 (setq org-goto-selected-point (point)
7567 org-goto-exit-command 'left)
7568 (throw 'exit nil))
7569 (user-error "Not on a heading")))
7571 (defun org-goto-right ()
7572 "Finish `org-goto' by going to the new location."
7573 (interactive)
7574 (if (org-at-heading-p)
7575 (progn
7576 (setq org-goto-selected-point (point)
7577 org-goto-exit-command 'right)
7578 (throw 'exit nil))
7579 (user-error "Not on a heading")))
7581 (defun org-goto-quit ()
7582 "Finish `org-goto' without cursor motion."
7583 (interactive)
7584 (setq org-goto-selected-point nil)
7585 (setq org-goto-exit-command 'quit)
7586 (throw 'exit nil))
7588 ;;; Indirect buffer display of subtrees
7590 (defvar org-indirect-dedicated-frame nil
7591 "This is the frame being used for indirect tree display.")
7592 (defvar org-last-indirect-buffer nil)
7594 (defun org-tree-to-indirect-buffer (&optional arg)
7595 "Create indirect buffer and narrow it to current subtree.
7597 With a numerical prefix ARG, go up to this level and then take that tree.
7598 If ARG is negative, go up that many levels.
7600 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7601 indirect buffer previously made with this command, to avoid proliferation of
7602 indirect buffers. However, when you call the command with a \
7603 `\\[universal-argument]' prefix, or
7604 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7605 so that you can work with several indirect buffers at the same time. If
7606 `org-indirect-buffer-display' is `dedicated-frame', the \
7607 `\\[universal-argument]' prefix also
7608 requests that a new frame be made for the new buffer, so that the dedicated
7609 frame is not changed."
7610 (interactive "P")
7611 (let ((cbuf (current-buffer))
7612 (cwin (selected-window))
7613 (pos (point))
7614 beg end level heading ibuf)
7615 (save-excursion
7616 (org-back-to-heading t)
7617 (when (numberp arg)
7618 (setq level (org-outline-level))
7619 (when (< arg 0) (setq arg (+ level arg)))
7620 (while (> (setq level (org-outline-level)) arg)
7621 (org-up-heading-safe)))
7622 (setq beg (point)
7623 heading (org-get-heading 'no-tags))
7624 (org-end-of-subtree t t)
7625 (when (org-at-heading-p) (backward-char 1))
7626 (setq end (point)))
7627 (when (and (buffer-live-p org-last-indirect-buffer)
7628 (not (eq org-indirect-buffer-display 'new-frame))
7629 (not arg))
7630 (kill-buffer org-last-indirect-buffer))
7631 (setq ibuf (org-get-indirect-buffer cbuf heading)
7632 org-last-indirect-buffer ibuf)
7633 (cond
7634 ((or (eq org-indirect-buffer-display 'new-frame)
7635 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7636 (select-frame (make-frame))
7637 (delete-other-windows)
7638 (pop-to-buffer-same-window ibuf)
7639 (org-set-frame-title heading))
7640 ((eq org-indirect-buffer-display 'dedicated-frame)
7641 (raise-frame
7642 (select-frame (or (and org-indirect-dedicated-frame
7643 (frame-live-p org-indirect-dedicated-frame)
7644 org-indirect-dedicated-frame)
7645 (setq org-indirect-dedicated-frame (make-frame)))))
7646 (delete-other-windows)
7647 (pop-to-buffer-same-window ibuf)
7648 (org-set-frame-title (concat "Indirect: " heading)))
7649 ((eq org-indirect-buffer-display 'current-window)
7650 (pop-to-buffer-same-window ibuf))
7651 ((eq org-indirect-buffer-display 'other-window)
7652 (pop-to-buffer ibuf))
7653 (t (error "Invalid value")))
7654 (narrow-to-region beg end)
7655 (outline-show-all)
7656 (goto-char pos)
7657 (run-hook-with-args 'org-cycle-hook 'all)
7658 (and (window-live-p cwin) (select-window cwin))))
7660 (defun org-get-indirect-buffer (&optional buffer heading)
7661 (setq buffer (or buffer (current-buffer)))
7662 (let ((n 1) (base (buffer-name buffer)) bname)
7663 (while (buffer-live-p
7664 (get-buffer
7665 (setq bname
7666 (concat base "-"
7667 (if heading (concat heading "-" (number-to-string n))
7668 (number-to-string n))))))
7669 (setq n (1+ n)))
7670 (condition-case nil
7671 (make-indirect-buffer buffer bname 'clone)
7672 (error (make-indirect-buffer buffer bname)))))
7674 (defun org-set-frame-title (title)
7675 "Set the title of the current frame to the string TITLE."
7676 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7678 ;;;; Structure editing
7680 ;;; Inserting headlines
7682 (defun org--line-empty-p (n)
7683 "Is the Nth next line empty?
7685 Counts the current line as N = 1 and the previous line as N = 0;
7686 see `beginning-of-line'."
7687 (save-excursion
7688 (and (not (bobp))
7689 (or (beginning-of-line n) t)
7690 (save-match-data
7691 (looking-at "[ \t]*$")))))
7693 (defun org-previous-line-empty-p ()
7694 "Is the previous line a blank line?
7695 When NEXT is non-nil, check the next line instead."
7696 (org--line-empty-p 0))
7698 (defun org-next-line-empty-p ()
7699 "Is the previous line a blank line?
7700 When NEXT is non-nil, check the next line instead."
7701 (org--line-empty-p 2))
7703 (defun org--blank-before-heading-p (&optional parent)
7704 "Non-nil when an empty line should precede a new heading here.
7705 When optional argument PARENT is non-nil, consider parent
7706 headline instead of current one."
7707 (pcase (assq 'heading org-blank-before-new-entry)
7708 (`(heading . auto)
7709 (save-excursion
7710 (org-with-limited-levels
7711 (unless (and (org-before-first-heading-p)
7712 (not (outline-next-heading)))
7713 (org-back-to-heading t)
7714 (when parent (org-up-heading-safe))
7715 (cond ((not (bobp))
7716 (org-previous-line-empty-p))
7717 ((outline-next-heading)
7718 (org-previous-line-empty-p))
7719 ;; Ignore trailing spaces on last buffer line.
7720 ((progn (skip-chars-backward " \t") (bolp))
7721 (org-previous-line-empty-p))
7722 (t nil))))))
7723 (`(heading . ,value) value)
7724 (_ nil)))
7726 (defun org-insert-heading (&optional arg invisible-ok top)
7727 "Insert a new heading or an item with the same depth at point.
7729 If point is at the beginning of a heading, insert a new heading
7730 or a new headline above the current one. When at the beginning
7731 of a regular line of text, turn it into a heading.
7733 If point is in the middle of a line, split it and create a new
7734 headline with the text in the current line after point (see
7735 `org-M-RET-may-split-line' on how to modify this behavior). As
7736 a special case, on a headline, splitting can only happen on the
7737 title itself. E.g., this excludes breaking stars or tags.
7739 With a `\\[universal-argument]' prefix, set \
7740 `org-insert-heading-respect-content' to
7741 a non-nil value for the duration of the command. This forces the
7742 insertion of a heading after the current subtree, independently
7743 on the location of point.
7745 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7746 insert the heading at the end of the tree
7747 above the current heading. For example, if point is within a
7748 2nd-level heading, then it will insert a 2nd-level heading at
7749 the end of the 1st-level parent subtree.
7751 When INVISIBLE-OK is set, stop at invisible headlines when going
7752 back. This is important for non-interactive uses of the
7753 command.
7755 When optional argument TOP is non-nil, insert a level 1 heading,
7756 unconditionally."
7757 (interactive "P")
7758 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7759 (level (org-current-level))
7760 (stars (make-string (if (and level (not top)) level 1) ?*)))
7761 (cond
7762 ((or org-insert-heading-respect-content
7763 (member arg '((4) (16)))
7764 (and (not invisible-ok)
7765 (invisible-p (max (1- (point)) (point-min)))))
7766 ;; Position point at the location of insertion.
7767 (if (not level) ;before first headline
7768 (org-with-limited-levels (outline-next-heading))
7769 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7770 ;; is nil.
7771 (org-with-limited-levels (org-back-to-heading invisible-ok))
7772 (cond ((equal arg '(16))
7773 (org-up-heading-safe)
7774 (org-end-of-subtree t t))
7776 (org-end-of-subtree t t))))
7777 (unless (bolp) (insert "\n")) ;ensure final newline
7778 (unless (and blank? (org-previous-line-empty-p))
7779 (org-N-empty-lines-before-current (if blank? 1 0)))
7780 (insert stars " \n")
7781 (forward-char -1))
7782 ;; At a headline...
7783 ((org-at-heading-p)
7784 (cond ((bolp)
7785 (when blank? (save-excursion (insert "\n")))
7786 (save-excursion (insert stars " \n"))
7787 (unless (and blank? (org-previous-line-empty-p))
7788 (org-N-empty-lines-before-current (if blank? 1 0)))
7789 (end-of-line))
7790 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7791 (org-match-line org-complex-heading-regexp)
7792 (org-pos-in-match-range (point) 4))
7793 ;; Grab the text that should moved to the new headline.
7794 ;; Preserve tags.
7795 (let ((split (delete-and-extract-region (point) (match-end 4))))
7796 (if (looking-at "[ \t]*$") (replace-match "")
7797 (org-set-tags nil t))
7798 (end-of-line)
7799 (when blank? (insert "\n"))
7800 (insert "\n" stars " ")
7801 (when (org-string-nw-p split) (insert split))
7802 (when (eobp) (save-excursion (insert "\n")))))
7804 (end-of-line)
7805 (when blank? (insert "\n"))
7806 (insert "\n" stars " ")
7807 (when (eobp) (save-excursion (insert "\n"))))))
7808 ;; On regular text, turn line into a headline or split, if
7809 ;; appropriate.
7810 ((bolp)
7811 (insert stars " ")
7812 (unless (and blank? (org-previous-line-empty-p))
7813 (org-N-empty-lines-before-current (if blank? 1 0))))
7815 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7816 (end-of-line))
7817 (insert "\n" stars " ")
7818 (unless (and blank? (org-previous-line-empty-p))
7819 (org-N-empty-lines-before-current (if blank? 1 0))))))
7820 (run-hooks 'org-insert-heading-hook))
7822 (defun org-N-empty-lines-before-current (n)
7823 "Make the number of empty lines before current exactly N.
7824 So this will delete or add empty lines."
7825 (let ((column (current-column)))
7826 (beginning-of-line)
7827 (unless (bobp)
7828 (let ((start (save-excursion
7829 (skip-chars-backward " \r\t\n")
7830 (line-end-position))))
7831 (delete-region start (line-end-position 0))))
7832 (insert (make-string n ?\n))
7833 (move-to-column column)))
7835 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7836 "Return the heading of the current entry, without the stars.
7837 When NO-TAGS is non-nil, don't include tags.
7838 When NO-TODO is non-nil, don't include TODO keywords.
7839 When NO-PRIORITY is non-nil, don't include priority cookie.
7840 When NO-COMMENT is non-nil, don't include COMMENT string."
7841 (save-excursion
7842 (org-back-to-heading t)
7843 (let ((case-fold-search nil))
7844 (looking-at org-complex-heading-regexp)
7845 (let ((todo (and (not no-todo) (match-string 2)))
7846 (priority (and (not no-priority) (match-string 3)))
7847 (headline (pcase (match-string 4)
7848 (`nil "")
7849 ((and (guard no-comment) h)
7850 (replace-regexp-in-string
7851 (eval-when-compile
7852 (format "\\`%s[ \t]+" org-comment-string))
7853 "" h))
7854 (h h)))
7855 (tags (and (not no-tags) (match-string 5))))
7856 (mapconcat #'identity
7857 (delq nil (list todo priority headline tags))
7858 " ")))))
7860 (defvar orgstruct-mode) ; defined below
7862 (defun org-heading-components ()
7863 "Return the components of the current heading.
7864 This is a list with the following elements:
7865 - the level as an integer
7866 - the reduced level, different if `org-odd-levels-only' is set.
7867 - the TODO keyword, or nil
7868 - the priority character, like ?A, or nil if no priority is given
7869 - the headline text itself, or the tags string if no headline text
7870 - the tags string, or nil."
7871 (save-excursion
7872 (org-back-to-heading t)
7873 (when (let (case-fold-search)
7874 (looking-at
7875 (if orgstruct-mode
7876 org-heading-regexp
7877 org-complex-heading-regexp)))
7878 (if orgstruct-mode
7879 (list (length (match-string 1))
7880 (org-reduced-level (length (match-string 1)))
7883 (match-string 2)
7884 nil)
7885 (list (length (match-string 1))
7886 (org-reduced-level (length (match-string 1)))
7887 (match-string-no-properties 2)
7888 (and (match-end 3) (aref (match-string 3) 2))
7889 (match-string-no-properties 4)
7890 (match-string-no-properties 5))))))
7892 (defun org-get-entry ()
7893 "Get the entry text, after heading, entire subtree."
7894 (save-excursion
7895 (org-back-to-heading t)
7896 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7898 (defun org-edit-headline (&optional heading)
7899 "Edit the current headline.
7900 Set it to HEADING when provided."
7901 (interactive)
7902 (org-with-wide-buffer
7903 (org-back-to-heading t)
7904 (let ((case-fold-search nil))
7905 (when (looking-at org-complex-heading-regexp)
7906 (let* ((old (match-string-no-properties 4))
7907 (new (save-match-data
7908 (org-trim (or heading (read-string "Edit: " old))))))
7909 (unless (equal old new)
7910 (if old (replace-match new t t nil 4)
7911 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7912 (insert " " new))
7913 (org-set-tags nil t)
7914 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7916 (defun org-insert-heading-after-current ()
7917 "Insert a new heading with same level as current, after current subtree."
7918 (interactive)
7919 (org-back-to-heading)
7920 (org-insert-heading)
7921 (org-move-subtree-down)
7922 (end-of-line 1))
7924 (defun org-insert-heading-respect-content (&optional invisible-ok)
7925 "Insert heading with `org-insert-heading-respect-content' set to t."
7926 (interactive)
7927 (org-insert-heading '(4) invisible-ok))
7929 (defun org-insert-todo-heading-respect-content (&optional force-state)
7930 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7931 (interactive)
7932 (org-insert-todo-heading force-state '(4)))
7934 (defun org-insert-todo-heading (arg &optional force-heading)
7935 "Insert a new heading with the same level and TODO state as current heading.
7937 If the heading has no TODO state, or if the state is DONE, use
7938 the first state (TODO by default). Also with one prefix arg,
7939 force first state. With two prefix args, force inserting at the
7940 end of the parent subtree.
7942 When called at a plain list item, insert a new item with an
7943 unchecked check box."
7944 (interactive "P")
7945 (when (or force-heading (not (org-insert-item 'checkbox)))
7946 (org-insert-heading (or (and (equal arg '(16)) '(16))
7947 force-heading))
7948 (save-excursion
7949 (org-back-to-heading)
7950 (outline-previous-heading)
7951 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7952 (let* ((new-mark-x
7953 (if (or (equal arg '(4))
7954 (not (match-beginning 2))
7955 (member (match-string 2) org-done-keywords))
7956 (car org-todo-keywords-1)
7957 (match-string 2)))
7958 (new-mark
7960 (run-hook-with-args-until-success
7961 'org-todo-get-default-hook new-mark-x nil)
7962 new-mark-x)))
7963 (beginning-of-line 1)
7964 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7965 (if org-treat-insert-todo-heading-as-state-change
7966 (org-todo new-mark)
7967 (insert new-mark " "))))
7968 (when org-provide-todo-statistics
7969 (org-update-parent-todo-statistics))))
7971 (defun org-insert-subheading (arg)
7972 "Insert a new subheading and demote it.
7973 Works for outline headings and for plain lists alike."
7974 (interactive "P")
7975 (org-insert-heading arg)
7976 (cond
7977 ((org-at-heading-p) (org-do-demote))
7978 ((org-at-item-p) (org-indent-item))))
7980 (defun org-insert-todo-subheading (arg)
7981 "Insert a new subheading with TODO keyword or checkbox and demote it.
7982 Works for outline headings and for plain lists alike."
7983 (interactive "P")
7984 (org-insert-todo-heading arg)
7985 (cond
7986 ((org-at-heading-p) (org-do-demote))
7987 ((org-at-item-p) (org-indent-item))))
7989 ;;; Promotion and Demotion
7991 (defvar org-after-demote-entry-hook nil
7992 "Hook run after an entry has been demoted.
7993 The cursor will be at the beginning of the entry.
7994 When a subtree is being demoted, the hook will be called for each node.")
7996 (defvar org-after-promote-entry-hook nil
7997 "Hook run after an entry has been promoted.
7998 The cursor will be at the beginning of the entry.
7999 When a subtree is being promoted, the hook will be called for each node.")
8001 (defun org-promote-subtree ()
8002 "Promote the entire subtree.
8003 See also `org-promote'."
8004 (interactive)
8005 (save-excursion
8006 (org-with-limited-levels (org-map-tree 'org-promote)))
8007 (org-fix-position-after-promote))
8009 (defun org-demote-subtree ()
8010 "Demote the entire subtree.
8011 See `org-demote' and `org-promote'."
8012 (interactive)
8013 (save-excursion
8014 (org-with-limited-levels (org-map-tree 'org-demote)))
8015 (org-fix-position-after-promote))
8017 (defun org-do-promote ()
8018 "Promote the current heading higher up the tree.
8019 If the region is active in `transient-mark-mode', promote all
8020 headings in the region."
8021 (interactive)
8022 (save-excursion
8023 (if (org-region-active-p)
8024 (org-map-region 'org-promote (region-beginning) (region-end))
8025 (org-promote)))
8026 (org-fix-position-after-promote))
8028 (defun org-do-demote ()
8029 "Demote the current heading lower down the tree.
8030 If the region is active in `transient-mark-mode', demote all
8031 headings in the region."
8032 (interactive)
8033 (save-excursion
8034 (if (org-region-active-p)
8035 (org-map-region 'org-demote (region-beginning) (region-end))
8036 (org-demote)))
8037 (org-fix-position-after-promote))
8039 (defun org-fix-position-after-promote ()
8040 "Fix cursor position and indentation after demoting/promoting."
8041 (let ((pos (point)))
8042 (when (save-excursion
8043 (beginning-of-line)
8044 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8045 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8046 (cond ((eobp) (insert " "))
8047 ((eolp) (insert " "))
8048 ((equal (char-after) ?\s) (forward-char 1))))))
8050 (defun org-current-level ()
8051 "Return the level of the current entry, or nil if before the first headline.
8052 The level is the number of stars at the beginning of the
8053 headline. Use `org-reduced-level' to remove the effect of
8054 `org-odd-levels'. Unlike to `org-outline-level', this function
8055 ignores inlinetasks."
8056 (let ((level (org-with-limited-levels (org-outline-level))))
8057 (and (> level 0) level)))
8059 (defun org-get-previous-line-level ()
8060 "Return the outline depth of the last headline before the current line.
8061 Returns 0 for the first headline in the buffer, and nil if before the
8062 first headline."
8063 (and (org-current-level)
8064 (or (and (/= (line-beginning-position) (point-min))
8065 (save-excursion (beginning-of-line 0) (org-current-level)))
8066 0)))
8068 (defun org-reduced-level (l)
8069 "Compute the effective level of a heading.
8070 This takes into account the setting of `org-odd-levels-only'."
8071 (cond
8072 ((zerop l) 0)
8073 (org-odd-levels-only (1+ (floor (/ l 2))))
8074 (t l)))
8076 (defun org-level-increment ()
8077 "Return the number of stars that will be added or removed at a
8078 time to headlines when structure editing, based on the value of
8079 `org-odd-levels-only'."
8080 (if org-odd-levels-only 2 1))
8082 (defun org-get-valid-level (level &optional change)
8083 "Rectify a level change under the influence of `org-odd-levels-only'.
8084 LEVEL is a current level, CHANGE is by how much the level should
8085 be modified. Even if CHANGE is nil, LEVEL may be returned
8086 modified because even level numbers will become the next higher
8087 odd number. Returns values greater than 0."
8088 (if org-odd-levels-only
8089 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8090 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8091 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8092 (max 1 (+ level (or change 0)))))
8094 (defun org-promote ()
8095 "Promote the current heading higher up the tree."
8096 (org-with-wide-buffer
8097 (org-back-to-heading t)
8098 (let* ((after-change-functions (remq 'flyspell-after-change-function
8099 after-change-functions))
8100 (level (save-match-data (funcall outline-level)))
8101 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8102 (diff (abs (- level (length up-head) -1))))
8103 (cond
8104 ((and (= level 1) org-allow-promoting-top-level-subtree)
8105 (replace-match "# " nil t))
8106 ((= level 1)
8107 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8108 (t (replace-match up-head nil t)))
8109 (unless (= level 1)
8110 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8111 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8112 (run-hooks 'org-after-promote-entry-hook))))
8114 (defun org-demote ()
8115 "Demote the current heading lower down the tree."
8116 (org-with-wide-buffer
8117 (org-back-to-heading t)
8118 (let* ((after-change-functions (remq 'flyspell-after-change-function
8119 after-change-functions))
8120 (level (save-match-data (funcall outline-level)))
8121 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8122 (diff (abs (- level (length down-head) -1))))
8123 (replace-match down-head nil t)
8124 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8125 (when org-adapt-indentation (org-fixup-indentation diff))
8126 (run-hooks 'org-after-demote-entry-hook))))
8128 (defun org-cycle-level ()
8129 "Cycle the level of an empty headline through possible states.
8130 This goes first to child, then to parent, level, then up the hierarchy.
8131 After top level, it switches back to sibling level."
8132 (interactive)
8133 (let ((org-adapt-indentation nil))
8134 (when (org-point-at-end-of-empty-headline)
8135 (setq this-command 'org-cycle-level) ; Only needed for caching
8136 (let ((cur-level (org-current-level))
8137 (prev-level (org-get-previous-line-level)))
8138 (cond
8139 ;; If first headline in file, promote to top-level.
8140 ((= prev-level 0)
8141 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8142 do (org-do-promote)))
8143 ;; If same level as prev, demote one.
8144 ((= prev-level cur-level)
8145 (org-do-demote))
8146 ;; If parent is top-level, promote to top level if not already.
8147 ((= prev-level 1)
8148 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8149 do (org-do-promote)))
8150 ;; If top-level, return to prev-level.
8151 ((= cur-level 1)
8152 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8153 do (org-do-demote)))
8154 ;; If less than prev-level, promote one.
8155 ((< cur-level prev-level)
8156 (org-do-promote))
8157 ;; If deeper than prev-level, promote until higher than
8158 ;; prev-level.
8159 ((> cur-level prev-level)
8160 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8161 do (org-do-promote))))
8162 t))))
8164 (defun org-map-tree (fun)
8165 "Call FUN for every heading underneath the current one."
8166 (org-back-to-heading t)
8167 (let ((level (funcall outline-level)))
8168 (save-excursion
8169 (funcall fun)
8170 (while (and (progn
8171 (outline-next-heading)
8172 (> (funcall outline-level) level))
8173 (not (eobp)))
8174 (funcall fun)))))
8176 (defun org-map-region (fun beg end)
8177 "Call FUN for every heading between BEG and END."
8178 (let ((org-ignore-region t))
8179 (save-excursion
8180 (setq end (copy-marker end))
8181 (goto-char beg)
8182 (when (and (re-search-forward org-outline-regexp-bol nil t)
8183 (< (point) end))
8184 (funcall fun))
8185 (while (and (progn
8186 (outline-next-heading)
8187 (< (point) end))
8188 (not (eobp)))
8189 (funcall fun)))))
8191 (defun org-fixup-indentation (diff)
8192 "Change the indentation in the current entry by DIFF.
8194 DIFF is an integer. Indentation is done according to the
8195 following rules:
8197 - Planning information and property drawers are always indented
8198 according to the new level of the headline;
8200 - Footnote definitions and their contents are ignored;
8202 - Inlinetasks' boundaries are not shifted;
8204 - Empty lines are ignored;
8206 - Other lines' indentation are shifted by DIFF columns, unless
8207 it would introduce a structural change in the document, in
8208 which case no shifting is done at all.
8210 Assume point is at a heading or an inlinetask beginning."
8211 (org-with-wide-buffer
8212 (narrow-to-region (line-beginning-position)
8213 (save-excursion
8214 (if (org-with-limited-levels (org-at-heading-p))
8215 (org-with-limited-levels (outline-next-heading))
8216 (org-inlinetask-goto-end))
8217 (point)))
8218 (forward-line)
8219 ;; Indent properly planning info and property drawer.
8220 (when (looking-at-p org-planning-line-re)
8221 (org-indent-line)
8222 (forward-line))
8223 (when (looking-at org-property-drawer-re)
8224 (goto-char (match-end 0))
8225 (forward-line)
8226 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8227 (catch 'no-shift
8228 (when (zerop diff) (throw 'no-shift nil))
8229 ;; If DIFF is negative, first check if a shift is possible at all
8230 ;; (e.g., it doesn't break structure). This can only happen if
8231 ;; some contents are not properly indented.
8232 (let ((case-fold-search t))
8233 (when (< diff 0)
8234 (let ((diff (- diff))
8235 (forbidden-re (concat org-outline-regexp
8236 "\\|"
8237 (substring org-footnote-definition-re 1))))
8238 (save-excursion
8239 (while (not (eobp))
8240 (cond
8241 ((looking-at-p "[ \t]*$") (forward-line))
8242 ((and (looking-at-p org-footnote-definition-re)
8243 (let ((e (org-element-at-point)))
8244 (and (eq (org-element-type e) 'footnote-definition)
8245 (goto-char (org-element-property :end e))))))
8246 ((looking-at-p org-outline-regexp) (forward-line))
8247 ;; Give up if shifting would move before column 0 or
8248 ;; if it would introduce a headline or a footnote
8249 ;; definition.
8251 (skip-chars-forward " \t")
8252 (let ((ind (current-column)))
8253 (when (or (< ind diff)
8254 (and (= ind diff) (looking-at-p forbidden-re)))
8255 (throw 'no-shift nil)))
8256 ;; Ignore contents of example blocks and source
8257 ;; blocks if their indentation is meant to be
8258 ;; preserved. Jump to block's closing line.
8259 (beginning-of-line)
8260 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8261 (let ((e (org-element-at-point)))
8262 (and (memq (org-element-type e)
8263 '(example-block src-block))
8264 (or org-src-preserve-indentation
8265 (org-element-property :preserve-indent e))
8266 (goto-char (org-element-property :end e))
8267 (progn (skip-chars-backward " \r\t\n")
8268 (beginning-of-line)
8269 t))))
8270 (forward-line))))))))
8271 ;; Shift lines but footnote definitions, inlinetasks boundaries
8272 ;; by DIFF. Also skip contents of source or example blocks
8273 ;; when indentation is meant to be preserved.
8274 (while (not (eobp))
8275 (cond
8276 ((and (looking-at-p org-footnote-definition-re)
8277 (let ((e (org-element-at-point)))
8278 (and (eq (org-element-type e) 'footnote-definition)
8279 (goto-char (org-element-property :end e))))))
8280 ((looking-at-p org-outline-regexp) (forward-line))
8281 ((looking-at-p "[ \t]*$") (forward-line))
8283 (indent-line-to (+ (org-get-indentation) diff))
8284 (beginning-of-line)
8285 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8286 (let ((e (org-element-at-point)))
8287 (and (memq (org-element-type e)
8288 '(example-block src-block))
8289 (or org-src-preserve-indentation
8290 (org-element-property :preserve-indent e))
8291 (goto-char (org-element-property :end e))
8292 (progn (skip-chars-backward " \r\t\n")
8293 (beginning-of-line)
8294 t))))
8295 (forward-line)))))))))
8297 (defun org-convert-to-odd-levels ()
8298 "Convert an Org file with all levels allowed to one with odd levels.
8299 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8300 level 5 etc."
8301 (interactive)
8302 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8303 (let ((outline-level 'org-outline-level)
8304 (org-odd-levels-only nil) n)
8305 (save-excursion
8306 (goto-char (point-min))
8307 (while (re-search-forward "^\\*\\*+ " nil t)
8308 (setq n (- (length (match-string 0)) 2))
8309 (while (>= (setq n (1- n)) 0)
8310 (org-demote))
8311 (end-of-line 1))))))
8313 (defun org-convert-to-oddeven-levels ()
8314 "Convert an Org file with only odd levels to one with odd/even levels.
8315 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8316 file contains a section with an even level, conversion would
8317 destroy the structure of the file. An error is signaled in this
8318 case."
8319 (interactive)
8320 (goto-char (point-min))
8321 ;; First check if there are no even levels
8322 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8323 (org-show-set-visibility 'canonical)
8324 (error "Not all levels are odd in this file. Conversion not possible"))
8325 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8326 (let ((outline-regexp org-outline-regexp)
8327 (outline-level 'org-outline-level)
8328 (org-odd-levels-only nil) n)
8329 (save-excursion
8330 (goto-char (point-min))
8331 (while (re-search-forward "^\\*\\*+ " nil t)
8332 (setq n (/ (1- (length (match-string 0))) 2))
8333 (while (>= (setq n (1- n)) 0)
8334 (org-promote))
8335 (end-of-line 1))))))
8337 (defun org-tr-level (n)
8338 "Make N odd if required."
8339 (if org-odd-levels-only (1+ (/ n 2)) n))
8341 ;;; Vertical tree motion, cutting and pasting of subtrees
8343 (defun org-move-subtree-up (&optional arg)
8344 "Move the current subtree up past ARG headlines of the same level."
8345 (interactive "p")
8346 (org-move-subtree-down (- (prefix-numeric-value arg))))
8348 (defun org-move-subtree-down (&optional arg)
8349 "Move the current subtree down past ARG headlines of the same level."
8350 (interactive "p")
8351 (setq arg (prefix-numeric-value arg))
8352 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8353 'org-get-last-sibling))
8354 (ins-point (make-marker))
8355 (cnt (abs arg))
8356 (col (current-column))
8357 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8358 ;; Select the tree
8359 (org-back-to-heading)
8360 (setq beg0 (point))
8361 (save-excursion
8362 (setq ne-beg (org-back-over-empty-lines))
8363 (setq beg (point)))
8364 (save-match-data
8365 (save-excursion (outline-end-of-heading)
8366 (setq folded (org-invisible-p)))
8367 (progn (org-end-of-subtree nil t)
8368 (unless (eobp) (backward-char))))
8369 (outline-next-heading)
8370 (setq ne-end (org-back-over-empty-lines))
8371 (setq end (point))
8372 (goto-char beg0)
8373 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8374 ;; include less whitespace
8375 (save-excursion
8376 (goto-char beg)
8377 (forward-line (- ne-beg ne-end))
8378 (setq beg (point))))
8379 ;; Find insertion point, with error handling
8380 (while (> cnt 0)
8381 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8382 (progn (goto-char beg0)
8383 (user-error "Cannot move past superior level or buffer limit")))
8384 (setq cnt (1- cnt)))
8385 (when (> arg 0)
8386 ;; Moving forward - still need to move over subtree
8387 (org-end-of-subtree t t)
8388 (save-excursion
8389 (org-back-over-empty-lines)
8390 (or (bolp) (newline))))
8391 (setq ne-ins (org-back-over-empty-lines))
8392 (move-marker ins-point (point))
8393 (setq txt (buffer-substring beg end))
8394 (org-save-markers-in-region beg end)
8395 (delete-region beg end)
8396 (org-remove-empty-overlays-at beg)
8397 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8398 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8399 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8400 (let ((bbb (point)))
8401 (insert-before-markers txt)
8402 (org-reinstall-markers-in-region bbb)
8403 (move-marker ins-point bbb))
8404 (or (bolp) (insert "\n"))
8405 (setq ins-end (point))
8406 (goto-char ins-point)
8407 (org-skip-whitespace)
8408 (when (and (< arg 0)
8409 (org-first-sibling-p)
8410 (> ne-ins ne-beg))
8411 ;; Move whitespace back to beginning
8412 (save-excursion
8413 (goto-char ins-end)
8414 (let ((kill-whole-line t))
8415 (kill-line (- ne-ins ne-beg)) (point)))
8416 (insert (make-string (- ne-ins ne-beg) ?\n)))
8417 (move-marker ins-point nil)
8418 (if folded
8419 (outline-hide-subtree)
8420 (org-show-entry)
8421 (org-show-children)
8422 (org-cycle-hide-drawers 'children))
8423 (org-clean-visibility-after-subtree-move)
8424 ;; move back to the initial column we were at
8425 (move-to-column col)))
8427 (defvar org-subtree-clip ""
8428 "Clipboard for cut and paste of subtrees.
8429 This is actually only a copy of the kill, because we use the normal kill
8430 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8432 (defvar org-subtree-clip-folded nil
8433 "Was the last copied subtree folded?
8434 This is used to fold the tree back after pasting.")
8436 (defun org-cut-subtree (&optional n)
8437 "Cut the current subtree into the clipboard.
8438 With prefix arg N, cut this many sequential subtrees.
8439 This is a short-hand for marking the subtree and then cutting it."
8440 (interactive "p")
8441 (org-copy-subtree n 'cut))
8443 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8444 "Copy the current subtree it in the clipboard.
8445 With prefix arg N, copy this many sequential subtrees.
8446 This is a short-hand for marking the subtree and then copying it.
8447 If CUT is non-nil, actually cut the subtree.
8448 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8449 of some markers in the region, even if CUT is non-nil. This is
8450 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8451 (interactive "p")
8452 (let (beg end folded (beg0 (point)))
8453 (if (called-interactively-p 'any)
8454 (org-back-to-heading nil) ; take what looks like a subtree
8455 (org-back-to-heading t)) ; take what is really there
8456 (setq beg (point))
8457 (skip-chars-forward " \t\r\n")
8458 (save-match-data
8459 (if nosubtrees
8460 (outline-next-heading)
8461 (save-excursion (outline-end-of-heading)
8462 (setq folded (org-invisible-p)))
8463 (ignore-errors (org-forward-heading-same-level (1- n) t))
8464 (org-end-of-subtree t t)))
8465 ;; Include the end of an inlinetask
8466 (when (and (featurep 'org-inlinetask)
8467 (looking-at-p (concat (org-inlinetask-outline-regexp)
8468 "END[ \t]*$")))
8469 (end-of-line))
8470 (setq end (point))
8471 (goto-char beg0)
8472 (when (> end beg)
8473 (setq org-subtree-clip-folded folded)
8474 (when (or cut force-store-markers)
8475 (org-save-markers-in-region beg end))
8476 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8477 (setq org-subtree-clip (current-kill 0))
8478 (message "%s: Subtree(s) with %d characters"
8479 (if cut "Cut" "Copied")
8480 (length org-subtree-clip)))))
8482 (defun org-paste-subtree (&optional level tree for-yank remove)
8483 "Paste the clipboard as a subtree, with modification of headline level.
8484 The entire subtree is promoted or demoted in order to match a new headline
8485 level.
8487 If the cursor is at the beginning of a headline, the same level as
8488 that headline is used to paste the tree.
8490 If not, the new level is derived from the *visible* headings
8491 before and after the insertion point, and taken to be the inferior headline
8492 level of the two. So if the previous visible heading is level 3 and the
8493 next is level 4 (or vice versa), level 4 will be used for insertion.
8494 This makes sure that the subtree remains an independent subtree and does
8495 not swallow low level entries.
8497 You can also force a different level, either by using a numeric prefix
8498 argument, or by inserting the heading marker by hand. For example, if the
8499 cursor is after \"*****\", then the tree will be shifted to level 5.
8501 If optional TREE is given, use this text instead of the kill ring.
8503 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8504 move back over whitespace before inserting, and move point to the end of
8505 the inserted text when done.
8507 When REMOVE is non-nil, remove the subtree from the clipboard."
8508 (interactive "P")
8509 (setq tree (or tree (and kill-ring (current-kill 0))))
8510 (unless (org-kill-is-subtree-p tree)
8511 (user-error "%s"
8512 (substitute-command-keys
8513 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8514 (org-with-limited-levels
8515 (let* ((visp (not (org-invisible-p)))
8516 (txt tree)
8517 (^re_ "\\(\\*+\\)[ \t]*")
8518 (old-level (if (string-match org-outline-regexp-bol txt)
8519 (- (match-end 0) (match-beginning 0) 1)
8520 -1))
8521 (force-level (cond (level (prefix-numeric-value level))
8522 ((and (looking-at "[ \t]*$")
8523 (string-match
8524 "^\\*+$" (buffer-substring
8525 (point-at-bol) (point))))
8526 (- (match-end 0) (match-beginning 0)))
8527 ((and (bolp)
8528 (looking-at org-outline-regexp))
8529 (- (match-end 0) (point) 1))))
8530 (previous-level (save-excursion
8531 (condition-case nil
8532 (progn
8533 (outline-previous-visible-heading 1)
8534 (if (looking-at ^re_)
8535 (- (match-end 0) (match-beginning 0) 1)
8537 (error 1))))
8538 (next-level (save-excursion
8539 (condition-case nil
8540 (progn
8541 (or (looking-at org-outline-regexp)
8542 (outline-next-visible-heading 1))
8543 (if (looking-at ^re_)
8544 (- (match-end 0) (match-beginning 0) 1)
8546 (error 1))))
8547 (new-level (or force-level (max previous-level next-level)))
8548 (shift (if (or (= old-level -1)
8549 (= new-level -1)
8550 (= old-level new-level))
8552 (- new-level old-level)))
8553 (delta (if (> shift 0) -1 1))
8554 (func (if (> shift 0) 'org-demote 'org-promote))
8555 (org-odd-levels-only nil)
8556 beg end newend)
8557 ;; Remove the forced level indicator
8558 (when force-level
8559 (delete-region (point-at-bol) (point)))
8560 ;; Paste
8561 (beginning-of-line (if (bolp) 1 2))
8562 (setq beg (point))
8563 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8564 (insert-before-markers txt)
8565 (unless (string-suffix-p "\n" txt) (insert "\n"))
8566 (setq newend (point))
8567 (org-reinstall-markers-in-region beg)
8568 (setq end (point))
8569 (goto-char beg)
8570 (skip-chars-forward " \t\n\r")
8571 (setq beg (point))
8572 (when (and (org-invisible-p) visp)
8573 (save-excursion (outline-show-heading)))
8574 ;; Shift if necessary
8575 (unless (= shift 0)
8576 (save-restriction
8577 (narrow-to-region beg end)
8578 (while (not (= shift 0))
8579 (org-map-region func (point-min) (point-max))
8580 (setq shift (+ delta shift)))
8581 (goto-char (point-min))
8582 (setq newend (point-max))))
8583 (when (or (called-interactively-p 'interactive) for-yank)
8584 (message "Clipboard pasted as level %d subtree" new-level))
8585 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8586 kill-ring
8587 (eq org-subtree-clip (current-kill 0))
8588 org-subtree-clip-folded)
8589 ;; The tree was folded before it was killed/copied
8590 (outline-hide-subtree))
8591 (and for-yank (goto-char newend))
8592 (and remove (setq kill-ring (cdr kill-ring))))))
8594 (defun org-kill-is-subtree-p (&optional txt)
8595 "Check if the current kill is an outline subtree, or a set of trees.
8596 Returns nil if kill does not start with a headline, or if the first
8597 headline level is not the largest headline level in the tree.
8598 So this will actually accept several entries of equal levels as well,
8599 which is OK for `org-paste-subtree'.
8600 If optional TXT is given, check this string instead of the current kill."
8601 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8602 (re (org-get-limited-outline-regexp))
8603 (^re (concat "^" re))
8604 (start-level (and kill
8605 (string-match
8606 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8607 kill)
8608 (- (match-end 2) (match-beginning 2) 1)))
8609 (start (1+ (or (match-beginning 2) -1))))
8610 (if (not start-level)
8611 (progn
8612 nil) ;; does not even start with a heading
8613 (catch 'exit
8614 (while (setq start (string-match ^re kill (1+ start)))
8615 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8616 (throw 'exit nil)))
8617 t))))
8619 (defvar org-markers-to-move nil
8620 "Markers that should be moved with a cut-and-paste operation.
8621 Those markers are stored together with their positions relative to
8622 the start of the region.")
8624 (defun org-save-markers-in-region (beg end)
8625 "Check markers in region.
8626 If these markers are between BEG and END, record their position relative
8627 to BEG, so that after moving the block of text, we can put the markers back
8628 into place.
8629 This function gets called just before an entry or tree gets cut from the
8630 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8631 called immediately, to move the markers with the entries."
8632 (setq org-markers-to-move nil)
8633 (when (featurep 'org-clock)
8634 (org-clock-save-markers-for-cut-and-paste beg end))
8635 (when (featurep 'org-agenda)
8636 (org-agenda-save-markers-for-cut-and-paste beg end)))
8638 (defun org-check-and-save-marker (marker beg end)
8639 "Check if MARKER is between BEG and END.
8640 If yes, remember the marker and the distance to BEG."
8641 (when (and (marker-buffer marker)
8642 (equal (marker-buffer marker) (current-buffer))
8643 (>= marker beg) (< marker end))
8644 (push (cons marker (- marker beg)) org-markers-to-move)))
8646 (defun org-reinstall-markers-in-region (beg)
8647 "Move all remembered markers to their position relative to BEG."
8648 (dolist (x org-markers-to-move)
8649 (move-marker (car x) (+ beg (cdr x))))
8650 (setq org-markers-to-move nil))
8652 (defun org-narrow-to-subtree ()
8653 "Narrow buffer to the current subtree."
8654 (interactive)
8655 (save-excursion
8656 (save-match-data
8657 (org-with-limited-levels
8658 (narrow-to-region
8659 (progn (org-back-to-heading t) (point))
8660 (progn (org-end-of-subtree t t)
8661 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8662 (point)))))))
8664 (defun org-narrow-to-block ()
8665 "Narrow buffer to the current block."
8666 (interactive)
8667 (let* ((case-fold-search t)
8668 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8669 "^[ \t]*#\\+end_.*")))
8670 (if blockp
8671 (narrow-to-region (car blockp) (cdr blockp))
8672 (user-error "Not in a block"))))
8674 (defun org-clone-subtree-with-time-shift (n &optional shift)
8675 "Clone the task (subtree) at point N times.
8676 The clones will be inserted as siblings.
8678 In interactive use, the user will be prompted for the number of
8679 clones to be produced. If the entry has a timestamp, the user
8680 will also be prompted for a time shift, which may be a repeater
8681 as used in time stamps, for example `+3d'. To disable this,
8682 you can call the function with a universal prefix argument.
8684 When a valid repeater is given and the entry contains any time
8685 stamps, the clones will become a sequence in time, with time
8686 stamps in the subtree shifted for each clone produced. If SHIFT
8687 is nil or the empty string, time stamps will be left alone. The
8688 ID property of the original subtree is removed.
8690 In each clone, all the CLOCK entries will be removed. This
8691 prevents Org from considering that the clocked times overlap.
8693 If the original subtree did contain time stamps with a repeater,
8694 the following will happen:
8695 - the repeater will be removed in each clone
8696 - an additional clone will be produced, with the current, unshifted
8697 date(s) in the entry.
8698 - the original entry will be placed *after* all the clones, with
8699 repeater intact.
8700 - the start days in the repeater in the original entry will be shifted
8701 to past the last clone.
8702 In this way you can spell out a number of instances of a repeating task,
8703 and still retain the repeater to cover future instances of the task.
8705 As described above, N+1 clones are produced when the original
8706 subtree has a repeater. Setting N to 0, then, can be used to
8707 remove the repeater from a subtree and create a shifted clone
8708 with the original repeater."
8709 (interactive "nNumber of clones to produce: ")
8710 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8711 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8712 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8713 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8714 (shift
8715 (or shift
8716 (if (and (not (equal current-prefix-arg '(4)))
8717 (save-excursion
8718 (goto-char beg)
8719 (re-search-forward org-ts-regexp-both end-of-tree t)))
8720 (read-from-minibuffer
8721 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8722 ""))) ;No time shift
8723 (doshift
8724 (and (org-string-nw-p shift)
8725 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8726 shift)
8727 (user-error "Invalid shift specification %s" shift)))))
8728 (goto-char end-of-tree)
8729 (unless (bolp) (insert "\n"))
8730 (let* ((end (point))
8731 (template (buffer-substring beg end))
8732 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8733 (shift-what (pcase (and doshift (match-string 2 shift))
8734 (`nil nil)
8735 ("d" 'day)
8736 ("w" (setq shift-n (* 7 shift-n)) 'day)
8737 ("m" 'month)
8738 ("y" 'year)
8739 (_ (error "Unsupported time unit"))))
8740 (nmin 1)
8741 (nmax n)
8742 (n-no-remove -1)
8743 (idprop (org-entry-get nil "ID")))
8744 (when (and doshift
8745 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8746 template))
8747 (delete-region beg end)
8748 (setq end beg)
8749 (setq nmin 0)
8750 (setq nmax (1+ nmax))
8751 (setq n-no-remove nmax))
8752 (goto-char end)
8753 (cl-loop for n from nmin to nmax do
8754 (insert
8755 ;; Prepare clone.
8756 (with-temp-buffer
8757 (insert template)
8758 (org-mode)
8759 (goto-char (point-min))
8760 (org-show-subtree)
8761 (and idprop (if org-clone-delete-id
8762 (org-entry-delete nil "ID")
8763 (org-id-get-create t)))
8764 (unless (= n 0)
8765 (while (re-search-forward org-clock-line-re nil t)
8766 (delete-region (line-beginning-position)
8767 (line-beginning-position 2)))
8768 (goto-char (point-min))
8769 (while (re-search-forward org-drawer-regexp nil t)
8770 (org-remove-empty-drawer-at (point))))
8771 (goto-char (point-min))
8772 (when doshift
8773 (while (re-search-forward org-ts-regexp-both nil t)
8774 (org-timestamp-change (* n shift-n) shift-what))
8775 (unless (= n n-no-remove)
8776 (goto-char (point-min))
8777 (while (re-search-forward org-ts-regexp nil t)
8778 (save-excursion
8779 (goto-char (match-beginning 0))
8780 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8781 (delete-region (match-beginning 1) (match-end 1)))))))
8782 (buffer-string)))))
8783 (goto-char beg)))
8785 ;;; Outline Sorting
8787 (defun org-sort (&optional with-case)
8788 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8789 Optional argument WITH-CASE means sort case-sensitively."
8790 (interactive "P")
8791 (org-call-with-arg
8792 (cond ((org-at-table-p) #'org-table-sort-lines)
8793 ((org-at-item-p) #'org-sort-list)
8794 (t #'org-sort-entries))
8795 with-case))
8797 (defun org-sort-remove-invisible (s)
8798 "Remove invisible part of links and emphasis markers from string S."
8799 (remove-text-properties 0 (length s) org-rm-props s)
8800 (replace-regexp-in-string
8801 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8802 (replace-regexp-in-string
8803 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8804 (org-link-display-format s)
8805 t t) t t))
8807 (defvar org-priority-regexp) ; defined later in the file
8809 (defvar org-after-sorting-entries-or-items-hook nil
8810 "Hook that is run after a bunch of entries or items have been sorted.
8811 When children are sorted, the cursor is in the parent line when this
8812 hook gets called. When a region or a plain list is sorted, the cursor
8813 will be in the first entry of the sorted region/list.")
8815 (defun org-sort-entries
8816 (&optional with-case sorting-type getkey-func compare-func property
8817 interactive?)
8818 "Sort entries on a certain level of an outline tree.
8819 If there is an active region, the entries in the region are sorted.
8820 Else, if the cursor is before the first entry, sort the top-level items.
8821 Else, the children of the entry at point are sorted.
8823 Sorting can be alphabetically, numerically, by date/time as given by
8824 a time stamp, by a property, by priority order, or by a custom function.
8826 The command prompts for the sorting type unless it has been given to the
8827 function through the SORTING-TYPE argument, which needs to be a character,
8828 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8829 the precise meaning of each character:
8831 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8832 c By creation time, which is assumed to be the first inactive time stamp
8833 at the beginning of a line.
8834 d By deadline date/time.
8835 k By clocking time.
8836 n Numerically, by converting the beginning of the entry/item to a number.
8837 o By order of TODO keywords.
8838 p By priority according to the cookie.
8839 r By the value of a property.
8840 s By scheduled date/time.
8841 t By date/time, either the first active time stamp in the entry, or, if
8842 none exist, by the first inactive one.
8844 Capital letters will reverse the sort order.
8846 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8847 called with point at the beginning of the record. It must return a
8848 value that is compatible with COMPARE-FUNC, the function used to
8849 compare entries.
8851 Comparing entries ignores case by default. However, with an optional argument
8852 WITH-CASE, the sorting considers case as well.
8854 Sorting is done against the visible part of the headlines, it ignores hidden
8855 links.
8857 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8859 A non-nil value for INTERACTIVE? is used to signal that this
8860 function is being called interactively."
8861 (interactive (list current-prefix-arg nil nil nil nil t))
8862 (let ((case-func (if with-case 'identity 'downcase))
8863 start beg end stars re re2
8864 txt what tmp)
8865 ;; Find beginning and end of region to sort
8866 (cond
8867 ((org-region-active-p)
8868 ;; we will sort the region
8869 (setq end (region-end)
8870 what "region")
8871 (goto-char (region-beginning))
8872 (unless (org-at-heading-p) (outline-next-heading))
8873 (setq start (point)))
8874 ((or (org-at-heading-p)
8875 (ignore-errors (progn (org-back-to-heading) t)))
8876 ;; we will sort the children of the current headline
8877 (org-back-to-heading)
8878 (setq start (point)
8879 end (progn (org-end-of-subtree t t)
8880 (or (bolp) (insert "\n"))
8881 (when (>= (org-back-over-empty-lines) 1)
8882 (forward-line 1))
8883 (point))
8884 what "children")
8885 (goto-char start)
8886 (outline-show-subtree)
8887 (outline-next-heading))
8889 ;; we will sort the top-level entries in this file
8890 (goto-char (point-min))
8891 (or (org-at-heading-p) (outline-next-heading))
8892 (setq start (point))
8893 (goto-char (point-max))
8894 (beginning-of-line 1)
8895 (when (looking-at ".*?\\S-")
8896 ;; File ends in a non-white line
8897 (end-of-line 1)
8898 (insert "\n"))
8899 (setq end (point-max))
8900 (setq what "top-level")
8901 (goto-char start)
8902 (outline-show-all)))
8904 (setq beg (point))
8905 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8907 (looking-at "\\(\\*+\\)")
8908 (setq stars (match-string 1)
8909 re (concat "^" (regexp-quote stars) " +")
8910 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8911 txt (buffer-substring beg end))
8912 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8913 (when (and (not (equal stars "*")) (string-match re2 txt))
8914 (user-error "Region to sort contains a level above the first entry"))
8916 (unless sorting-type
8917 (message
8918 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8919 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8920 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8921 what)
8922 (setq sorting-type (read-char-exclusive)))
8924 (unless getkey-func
8925 (and (= (downcase sorting-type) ?f)
8926 (setq getkey-func
8927 (or (and interactive?
8928 (org-read-function
8929 "Function for extracting keys: "))
8930 (error "Missing key extractor")))))
8932 (and (= (downcase sorting-type) ?r)
8933 (not property)
8934 (setq property
8935 (completing-read "Property: "
8936 (mapcar #'list (org-buffer-property-keys t))
8937 nil t)))
8939 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8940 (message "Sorting entries...")
8942 (save-restriction
8943 (narrow-to-region start end)
8944 (let ((restore-clock?
8945 ;; The clock marker is lost when using `sort-subr'; mark
8946 ;; the clock with temporary `:org-clock-marker-backup'
8947 ;; text property.
8948 (when (and (eq (org-clock-is-active) (current-buffer))
8949 (<= start (marker-position org-clock-marker))
8950 (>= end (marker-position org-clock-marker)))
8951 (org-with-silent-modifications
8952 (put-text-property (1- org-clock-marker) org-clock-marker
8953 :org-clock-marker-backup t))
8955 (dcst (downcase sorting-type))
8956 (case-fold-search nil)
8957 (now (current-time)))
8958 (sort-subr
8959 (/= dcst sorting-type)
8960 ;; This function moves to the beginning character of the "record" to
8961 ;; be sorted.
8962 (lambda nil
8963 (if (re-search-forward re nil t)
8964 (goto-char (match-beginning 0))
8965 (goto-char (point-max))))
8966 ;; This function moves to the last character of the "record" being
8967 ;; sorted.
8968 (lambda nil
8969 (save-match-data
8970 (condition-case nil
8971 (outline-forward-same-level 1)
8972 (error
8973 (goto-char (point-max))))))
8974 ;; This function returns the value that gets sorted against.
8975 (lambda nil
8976 (cond
8977 ((= dcst ?n)
8978 (if (looking-at org-complex-heading-regexp)
8979 (string-to-number (org-sort-remove-invisible (match-string 4)))
8980 nil))
8981 ((= dcst ?a)
8982 (if (looking-at org-complex-heading-regexp)
8983 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8984 nil))
8985 ((= dcst ?k)
8986 (or (get-text-property (point) :org-clock-minutes) 0))
8987 ((= dcst ?t)
8988 (let ((end (save-excursion (outline-next-heading) (point))))
8989 (if (or (re-search-forward org-ts-regexp end t)
8990 (re-search-forward org-ts-regexp-both end t))
8991 (org-time-string-to-seconds (match-string 0))
8992 (float-time now))))
8993 ((= dcst ?c)
8994 (let ((end (save-excursion (outline-next-heading) (point))))
8995 (if (re-search-forward
8996 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8997 end t)
8998 (org-time-string-to-seconds (match-string 0))
8999 (float-time now))))
9000 ((= dcst ?s)
9001 (let ((end (save-excursion (outline-next-heading) (point))))
9002 (if (re-search-forward org-scheduled-time-regexp end t)
9003 (org-time-string-to-seconds (match-string 1))
9004 (float-time now))))
9005 ((= dcst ?d)
9006 (let ((end (save-excursion (outline-next-heading) (point))))
9007 (if (re-search-forward org-deadline-time-regexp end t)
9008 (org-time-string-to-seconds (match-string 1))
9009 (float-time now))))
9010 ((= dcst ?p)
9011 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9012 (string-to-char (match-string 2))
9013 org-default-priority))
9014 ((= dcst ?r)
9015 (or (org-entry-get nil property) ""))
9016 ((= dcst ?o)
9017 (when (looking-at org-complex-heading-regexp)
9018 (let* ((m (match-string 2))
9019 (s (if (member m org-done-keywords) '- '+)))
9020 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9021 ((= dcst ?f)
9022 (if getkey-func
9023 (progn
9024 (setq tmp (funcall getkey-func))
9025 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9026 tmp)
9027 (error "Invalid key function `%s'" getkey-func)))
9028 (t (error "Invalid sorting type `%c'" sorting-type))))
9030 (cond
9031 ((= dcst ?a) 'string<)
9032 ((= dcst ?f)
9033 (or compare-func
9034 (and interactive?
9035 (org-read-function
9036 (concat "Function for comparing keys "
9037 "(empty for default `sort-subr' predicate): ")
9038 'allow-empty))))
9039 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9040 (when restore-clock?
9041 (move-marker org-clock-marker
9042 (1+ (next-single-property-change
9043 start :org-clock-marker-backup)))
9044 (remove-text-properties (1- org-clock-marker) org-clock-marker
9045 '(:org-clock-marker-backup t)))))
9046 (run-hooks 'org-after-sorting-entries-or-items-hook)
9047 (message "Sorting entries...done")))
9049 ;;; The orgstruct minor mode
9051 ;; Define a minor mode which can be used in other modes in order to
9052 ;; integrate the Org mode structure editing commands.
9054 ;; This is really a hack, because the Org mode structure commands use
9055 ;; keys which normally belong to the major mode. Here is how it
9056 ;; works: The minor mode defines all the keys necessary to operate the
9057 ;; structure commands, but wraps the commands into a function which
9058 ;; tests if the cursor is currently at a headline or a plain list
9059 ;; item. If that is the case, the structure command is used,
9060 ;; temporarily setting many Org mode variables like regular
9061 ;; expressions for filling etc. However, when any of those keys is
9062 ;; used at a different location, function uses `key-binding' to look
9063 ;; up if the key has an associated command in another currently active
9064 ;; keymap (minor modes, major mode, global), and executes that
9065 ;; command. There might be problems if any of the keys is otherwise
9066 ;; used as a prefix key.
9068 (defcustom orgstruct-heading-prefix-regexp ""
9069 "Regexp that matches the custom prefix of Org headlines in
9070 orgstruct(++)-mode."
9071 :group 'org
9072 :version "24.4"
9073 :package-version '(Org . "8.3")
9074 :type 'regexp)
9075 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9077 (defcustom orgstruct-setup-hook nil
9078 "Hook run after orgstruct-mode-map is filled."
9079 :group 'org
9080 :version "24.4"
9081 :package-version '(Org . "8.0")
9082 :type 'hook)
9084 (defvar orgstruct-initialized nil)
9086 (defvar org-local-vars nil
9087 "List of local variables, for use by `orgstruct-mode'.")
9089 ;;;###autoload
9090 (define-minor-mode orgstruct-mode
9091 "Toggle the minor mode `orgstruct-mode'.
9092 This mode is for using Org mode structure commands in other
9093 modes. The following keys behave as if Org mode were active, if
9094 the cursor is on a headline, or on a plain list item (both as
9095 defined by Org mode)."
9096 nil " OrgStruct" (make-sparse-keymap)
9097 (funcall (if orgstruct-mode
9098 'add-to-invisibility-spec
9099 'remove-from-invisibility-spec)
9100 '(outline . t))
9101 (when orgstruct-mode
9102 (org-load-modules-maybe)
9103 (unless orgstruct-initialized
9104 (orgstruct-setup)
9105 (setq orgstruct-initialized t))))
9107 ;;;###autoload
9108 (defun turn-on-orgstruct ()
9109 "Unconditionally turn on `orgstruct-mode'."
9110 (orgstruct-mode 1))
9112 (defvar-local orgstruct-is-++ nil
9113 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9114 (defvar-local org-fb-vars nil)
9115 (defun orgstruct++-mode (&optional arg)
9116 "Toggle `orgstruct-mode', the enhanced version of it.
9117 In addition to setting orgstruct-mode, this also exports all
9118 indentation and autofilling variables from Org mode into the
9119 buffer. It will also recognize item context in multiline items."
9120 (interactive "P")
9121 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9122 (if (< arg 1)
9123 (progn (orgstruct-mode -1)
9124 (dolist (v org-fb-vars)
9125 (set (make-local-variable (car v))
9126 (if (eq (car-safe (cadr v)) 'quote)
9127 (cl-cadadr v)
9128 (nth 1 v)))))
9129 (orgstruct-mode 1)
9130 (setq org-fb-vars nil)
9131 (unless org-local-vars
9132 (setq org-local-vars (org-get-local-variables)))
9133 (let (var val)
9134 (dolist (x org-local-vars)
9135 (when (string-match
9136 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9137 \\|fill-prefix\\|indent-\\)"
9138 (symbol-name (car x)))
9139 (setq var (car x) val (nth 1 x))
9140 (push (list var `(quote ,(eval var))) org-fb-vars)
9141 (set (make-local-variable var)
9142 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9143 (setq-local orgstruct-is-++ t))))
9145 ;;;###autoload
9146 (defun turn-on-orgstruct++ ()
9147 "Unconditionally turn on `orgstruct++-mode'."
9148 (orgstruct++-mode 1))
9150 (defun orgstruct-error ()
9151 "Error when there is no default binding for a structure key."
9152 (interactive)
9153 (funcall (if (fboundp 'user-error)
9154 'user-error
9155 'error)
9156 "This key has no function outside structure elements"))
9158 (defun orgstruct-setup ()
9159 "Setup orgstruct keymap."
9160 (dolist (cell '((org-demote . t)
9161 (org-metaleft . t)
9162 (org-metaright . t)
9163 (org-promote . t)
9164 (org-shiftmetaleft . t)
9165 (org-shiftmetaright . t)
9166 org-backward-element
9167 org-backward-heading-same-level
9168 org-ctrl-c-ret
9169 org-ctrl-c-minus
9170 org-ctrl-c-star
9171 org-cycle
9172 org-force-cycle-archived
9173 org-forward-heading-same-level
9174 org-insert-heading
9175 org-insert-heading-respect-content
9176 org-kill-note-or-show-branches
9177 org-mark-subtree
9178 org-meta-return
9179 org-metadown
9180 org-metaup
9181 org-narrow-to-subtree
9182 org-promote-subtree
9183 org-reveal
9184 org-shiftdown
9185 org-shiftleft
9186 org-shiftmetadown
9187 org-shiftmetaup
9188 org-shiftright
9189 org-shifttab
9190 org-shifttab
9191 org-shiftup
9192 org-show-children
9193 org-show-subtree
9194 org-sort
9195 org-up-element
9196 outline-demote
9197 outline-next-visible-heading
9198 outline-previous-visible-heading
9199 outline-promote
9200 outline-up-heading))
9201 (let ((f (or (car-safe cell) cell))
9202 (disable-when-heading-prefix (cdr-safe cell)))
9203 (when (fboundp f)
9204 (let ((new-bindings))
9205 (dolist (binding (nconc (where-is-internal f org-mode-map)
9206 (where-is-internal f outline-mode-map)))
9207 (push binding new-bindings)
9208 ;; TODO use local-function-key-map
9209 (dolist (rep '(("<tab>" . "TAB")
9210 ("<return>" . "RET")
9211 ("<escape>" . "ESC")
9212 ("<delete>" . "DEL")))
9213 (setq binding (read-kbd-macro
9214 (let ((case-fold-search))
9215 (replace-regexp-in-string
9216 (regexp-quote (cdr rep))
9217 (car rep)
9218 (key-description binding)))))
9219 (cl-pushnew binding new-bindings :test 'equal)))
9220 (dolist (binding new-bindings)
9221 (let ((key (lookup-key orgstruct-mode-map binding)))
9222 (when (or (not key) (numberp key))
9223 (ignore-errors
9224 (org-defkey orgstruct-mode-map
9225 binding
9226 (orgstruct-make-binding
9227 f binding disable-when-heading-prefix))))))))))
9228 (run-hooks 'orgstruct-setup-hook))
9230 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9231 "Create a function for binding in the structure minor mode.
9232 FUN is the command to call inside a table. KEY is the key that
9233 should be checked in for a command to execute outside of tables.
9234 Non-nil `disable-when-heading-prefix' means to disable the command
9235 if `orgstruct-heading-prefix-regexp' is not empty."
9236 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9237 (let ((nname name)
9238 (i 0))
9239 (while (fboundp (intern nname))
9240 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9241 (setq name (intern nname)))
9242 (eval
9243 (let ((bindings '((org-heading-regexp
9244 (concat "^"
9245 orgstruct-heading-prefix-regexp
9246 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9247 (org-outline-regexp
9248 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9249 (org-outline-regexp-bol
9250 (concat "^" org-outline-regexp))
9251 (outline-regexp org-outline-regexp)
9252 (outline-heading-end-regexp "\n")
9253 (outline-level 'org-outline-level)
9254 (outline-heading-alist))))
9255 `(defun ,name (arg)
9256 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9257 "Outside of structure, run the binding of `"
9258 (key-description key) "'."
9259 (when disable-when-heading-prefix
9260 (concat
9261 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9262 "back to the default binding due to limitations of Org's implementation of\n"
9263 "`" (symbol-name fun) "'.")))
9264 (interactive "p")
9265 (let* ((disable
9266 ,(and disable-when-heading-prefix
9267 '(not (string= orgstruct-heading-prefix-regexp ""))))
9268 (fallback
9269 (or disable
9270 (not
9271 (let* ,bindings
9272 (org-context-p 'headline 'item
9273 ,(when (memq fun
9274 '(org-insert-heading
9275 org-insert-heading-respect-content
9276 org-meta-return))
9277 '(when orgstruct-is-++
9278 'item-body))))))))
9279 (if fallback
9280 (let* ((orgstruct-mode)
9281 (binding
9282 (let ((key ,key))
9283 (catch 'exit
9284 (dolist
9285 (rep
9286 '(nil
9287 ("<\\([^>]*\\)tab>" . "\\1TAB")
9288 ("<\\([^>]*\\)return>" . "\\1RET")
9289 ("<\\([^>]*\\)escape>" . "\\1ESC")
9290 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9291 nil)
9292 (when rep
9293 (setq key (read-kbd-macro
9294 (let ((case-fold-search))
9295 (replace-regexp-in-string
9296 (car rep)
9297 (cdr rep)
9298 (key-description key))))))
9299 (when (key-binding key)
9300 (throw 'exit (key-binding key))))))))
9301 (if (keymapp binding)
9302 (org-set-transient-map binding)
9303 (let ((func (or binding
9304 (unless disable
9305 'orgstruct-error))))
9306 (when func
9307 (call-interactively func)))))
9308 (org-run-like-in-org-mode
9309 (lambda ()
9310 (interactive)
9311 (let* ,bindings
9312 (call-interactively ',fun)))))))))
9313 name))
9315 (defun org-contextualize-keys (alist contexts)
9316 "Return valid elements in ALIST depending on CONTEXTS.
9318 `org-agenda-custom-commands' or `org-capture-templates' are the
9319 values used for ALIST, and `org-agenda-custom-commands-contexts'
9320 or `org-capture-templates-contexts' are the associated contexts
9321 definitions."
9322 (let ((contexts
9323 ;; normalize contexts
9324 (mapcar
9325 (lambda(c) (cond ((listp (cadr c))
9326 (list (car c) (car c) (nth 1 c)))
9327 ((string= "" (cadr c))
9328 (list (car c) (car c) (nth 2 c)))
9329 (t c)))
9330 contexts))
9331 (a alist) r s)
9332 ;; loop over all commands or templates
9333 (dolist (c a)
9334 (let (vrules repl)
9335 (cond
9336 ((not (assoc (car c) contexts))
9337 (push c r))
9338 ((and (assoc (car c) contexts)
9339 (setq vrules (org-contextualize-validate-key
9340 (car c) contexts)))
9341 (mapc (lambda (vr)
9342 (unless (equal (car vr) (cadr vr))
9343 (setq repl vr)))
9344 vrules)
9345 (if (not repl) (push c r)
9346 (push (cadr repl) s)
9347 (push
9348 (cons (car c)
9349 (cdr (or (assoc (cadr repl) alist)
9350 (error "Undefined key `%s' as contextual replacement for `%s'"
9351 (cadr repl) (car c)))))
9352 r))))))
9353 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9354 (delq
9356 (delete-dups
9357 (mapcar (lambda (x)
9358 (let ((tpl (car x)))
9359 (unless (delq
9361 (mapcar (lambda (y)
9362 (equal y tpl))
9364 x)))
9365 (reverse r))))))
9367 (defun org-contextualize-validate-key (key contexts)
9368 "Check CONTEXTS for agenda or capture KEY."
9369 (let (res)
9370 (dolist (r contexts)
9371 (dolist (rr (car (last r)))
9372 (when
9373 (and (equal key (car r))
9374 (if (functionp rr) (funcall rr)
9375 (or (and (eq (car rr) 'in-file)
9376 (buffer-file-name)
9377 (string-match (cdr rr) (buffer-file-name)))
9378 (and (eq (car rr) 'in-mode)
9379 (string-match (cdr rr) (symbol-name major-mode)))
9380 (and (eq (car rr) 'in-buffer)
9381 (string-match (cdr rr) (buffer-name)))
9382 (when (and (eq (car rr) 'not-in-file)
9383 (buffer-file-name))
9384 (not (string-match (cdr rr) (buffer-file-name))))
9385 (when (eq (car rr) 'not-in-mode)
9386 (not (string-match (cdr rr) (symbol-name major-mode))))
9387 (when (eq (car rr) 'not-in-buffer)
9388 (not (string-match (cdr rr) (buffer-name)))))))
9389 (push r res))))
9390 (delete-dups (delq nil res))))
9392 (defun org-context-p (&rest contexts)
9393 "Check if local context is any of CONTEXTS.
9394 Possible values in the list of contexts are `table', `headline', and `item'."
9395 (let ((pos (point)))
9396 (goto-char (point-at-bol))
9397 (prog1 (or (and (memq 'table contexts)
9398 (looking-at "[ \t]*|"))
9399 (and (memq 'headline contexts)
9400 (looking-at org-outline-regexp))
9401 (and (memq 'item contexts)
9402 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9403 (and (memq 'item-body contexts)
9404 (org-in-item-p)))
9405 (goto-char pos))))
9407 ;;;###autoload
9408 (defun org-run-like-in-org-mode (cmd)
9409 "Run a command, pretending that the current buffer is in Org mode.
9410 This will temporarily bind local variables that are typically bound in
9411 Org mode to the values they have in Org mode, and then interactively
9412 call CMD."
9413 (org-load-modules-maybe)
9414 (unless org-local-vars
9415 (setq org-local-vars (org-get-local-variables)))
9416 (let (binds)
9417 (dolist (var org-local-vars)
9418 (when (or (not (boundp (car var)))
9419 (eq (symbol-value (car var))
9420 (default-value (car var))))
9421 (push (list (car var) `(quote ,(cadr var))) binds)))
9422 (eval `(let ,binds
9423 (call-interactively (quote ,cmd))))))
9425 (defun org-get-category (&optional pos force-refresh)
9426 "Get the category applying to position POS."
9427 (save-match-data
9428 (when force-refresh (org-refresh-category-properties))
9429 (let ((pos (or pos (point))))
9430 (or (get-text-property pos 'org-category)
9431 (progn (org-refresh-category-properties)
9432 (get-text-property pos 'org-category))))))
9434 ;;; Refresh properties
9436 (defun org-refresh-properties (dprop tprop)
9437 "Refresh buffer text properties.
9438 DPROP is the drawer property and TPROP is either the
9439 corresponding text property to set, or an alist with each element
9440 being a text property (as a symbol) and a function to apply to
9441 the value of the drawer property."
9442 (let* ((case-fold-search t)
9443 (inhibit-read-only t)
9444 (inherit? (org-property-inherit-p dprop))
9445 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9446 (global (and inherit? (org--property-global-value dprop nil))))
9447 (org-with-silent-modifications
9448 (org-with-point-at 1
9449 ;; Set global values (e.g., values defined through
9450 ;; "#+PROPERTY:" keywords) to the whole buffer.
9451 (when global (put-text-property (point-min) (point-max) tprop global))
9452 ;; Set local values.
9453 (while (re-search-forward property-re nil t)
9454 (when (org-at-property-p)
9455 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9456 (outline-next-heading))))))
9458 (defun org-refresh-property (tprop p &optional inherit)
9459 "Refresh the buffer text property TPROP from the drawer property P.
9460 The refresh happens only for the current headline, or the whole
9461 sub-tree if optional argument INHERIT is non-nil."
9462 (unless (org-before-first-heading-p)
9463 (save-excursion
9464 (org-back-to-heading t)
9465 (let ((start (point))
9466 (end (save-excursion
9467 (if inherit (org-end-of-subtree t t)
9468 (or (outline-next-heading) (point-max))))))
9469 (if (symbolp tprop)
9470 ;; TPROP is a text property symbol.
9471 (put-text-property start end tprop p)
9472 ;; TPROP is an alist with (property . function) elements.
9473 (pcase-dolist (`(,prop . ,f) tprop)
9474 (put-text-property start end prop (funcall f p))))))))
9476 (defun org-refresh-category-properties ()
9477 "Refresh category text properties in the buffer."
9478 (let ((case-fold-search t)
9479 (inhibit-read-only t)
9480 (default-category
9481 (cond ((null org-category)
9482 (if buffer-file-name
9483 (file-name-sans-extension
9484 (file-name-nondirectory buffer-file-name))
9485 "???"))
9486 ((symbolp org-category) (symbol-name org-category))
9487 (t org-category))))
9488 (org-with-silent-modifications
9489 (org-with-wide-buffer
9490 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9491 ;; This is the default category for the buffer. If none is
9492 ;; found, fall-back to `org-category' or buffer file name.
9493 (put-text-property
9494 (point-min) (point-max)
9495 'org-category
9496 (catch 'buffer-category
9497 (goto-char (point-max))
9498 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9499 (let ((element (org-element-at-point)))
9500 (when (eq (org-element-type element) 'keyword)
9501 (throw 'buffer-category
9502 (org-element-property :value element)))))
9503 default-category))
9504 ;; Set sub-tree specific categories.
9505 (goto-char (point-min))
9506 (let ((regexp (org-re-property "CATEGORY")))
9507 (while (re-search-forward regexp nil t)
9508 (let ((value (match-string-no-properties 3)))
9509 (when (org-at-property-p)
9510 (put-text-property
9511 (save-excursion (org-back-to-heading t) (point))
9512 (save-excursion (org-end-of-subtree t t) (point))
9513 'org-category
9514 value)))))))))
9516 (defun org-refresh-stats-properties ()
9517 "Refresh stats text properties in the buffer."
9518 (org-with-silent-modifications
9519 (org-with-point-at 1
9520 (let ((regexp (concat org-outline-regexp-bol
9521 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9522 (while (re-search-forward regexp nil t)
9523 (let* ((numerator (string-to-number (match-string 1)))
9524 (denominator (and (match-end 2)
9525 (string-to-number (match-string 2))))
9526 (stats (cond ((not denominator) numerator) ;percent
9527 ((= denominator 0) 0)
9528 (t (/ (* numerator 100) denominator)))))
9529 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9530 'org-stats stats)))))))
9532 (defun org-refresh-effort-properties ()
9533 "Refresh effort properties"
9534 (org-refresh-properties
9535 org-effort-property
9536 '((effort . identity)
9537 (effort-minutes . org-duration-to-minutes))))
9539 ;;;; Link Stuff
9541 ;;; Link abbreviations
9543 (defun org-link-expand-abbrev (link)
9544 "Apply replacements as defined in `org-link-abbrev-alist'."
9545 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9546 (let* ((key (match-string 1 link))
9547 (as (or (assoc key org-link-abbrev-alist-local)
9548 (assoc key org-link-abbrev-alist)))
9549 (tag (and (match-end 2) (match-string 3 link)))
9550 rpl)
9551 (if (not as)
9552 link
9553 (setq rpl (cdr as))
9554 (cond
9555 ((symbolp rpl) (funcall rpl tag))
9556 ((string-match "%(\\([^)]+\\))" rpl)
9557 (replace-match
9558 (save-match-data
9559 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9560 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9561 ((string-match "%h" rpl)
9562 (replace-match (url-hexify-string (or tag "")) t t rpl))
9563 (t (concat rpl tag)))))
9564 link))
9566 ;;; Storing and inserting links
9568 (defvar org-insert-link-history nil
9569 "Minibuffer history for links inserted with `org-insert-link'.")
9571 (defvar org-stored-links nil
9572 "Contains the links stored with `org-store-link'.")
9574 (defvar org-store-link-plist nil
9575 "Plist with info about the most recently link created with `org-store-link'.")
9577 (defun org-store-link-functions ()
9578 "Return a list of functions that are called to create and store a link.
9579 The functions defined in the :store property of
9580 `org-link-parameters'.
9582 Each function will be called in turn until one returns a non-nil
9583 value. Each function should check if it is responsible for
9584 creating this link (for example by looking at the major mode).
9585 If not, it must exit and return nil. If yes, it should return
9586 a non-nil value after calling `org-store-link-props' with a list
9587 of properties and values. Special properties are:
9589 :type The link prefix, like \"http\". This must be given.
9590 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9591 This is obligatory as well.
9592 :description Optional default description for the second pair
9593 of brackets in an Org mode link. The user can still change
9594 this when inserting this link into an Org mode buffer.
9596 In addition to these, any additional properties can be specified
9597 and then used in capture templates."
9598 (cl-loop for link in org-link-parameters
9599 with store-func
9600 do (setq store-func (org-link-get-parameter (car link) :store))
9601 if store-func
9602 collect store-func))
9604 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9605 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9607 ;;;###autoload
9608 (defun org-store-link (arg)
9609 "Store an org-link to the current location.
9610 \\<org-mode-map>
9611 This link is added to `org-stored-links' and can later be inserted
9612 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9614 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9615 A single
9616 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9617 `org-gnus-prefer-web-links' for links to Usenet articles.
9619 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9620 skipping storing functions that are not
9621 part of Org core.
9623 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9624 prefix ARG forces storing a link for each line in the
9625 active region."
9626 (interactive "P")
9627 (org-load-modules-maybe)
9628 (if (and (equal arg '(64)) (org-region-active-p))
9629 (save-excursion
9630 (let ((end (region-end)))
9631 (goto-char (region-beginning))
9632 (set-mark (point))
9633 (while (< (point-at-eol) end)
9634 (move-end-of-line 1) (activate-mark)
9635 (let (current-prefix-arg)
9636 (call-interactively 'org-store-link))
9637 (move-beginning-of-line 2)
9638 (set-mark (point)))))
9639 (setq org-store-link-plist nil)
9640 (let (link cpltxt desc description search
9641 txt custom-id agenda-link sfuns sfunsn)
9642 (cond
9644 ;; Store a link using an external link type
9645 ((and (not (equal arg '(16)))
9646 (setq sfuns
9647 (delq
9648 nil (mapcar (lambda (f)
9649 (let (fs) (if (funcall f) (push f fs))))
9650 (org-store-link-functions)))
9651 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9652 (or (and (cdr sfuns)
9653 (funcall (intern
9654 (completing-read
9655 "Which function for creating the link? "
9656 sfunsn nil t (car sfunsn)))))
9657 (funcall (caar sfuns)))
9658 (setq link (plist-get org-store-link-plist :link)
9659 desc (or (plist-get org-store-link-plist
9660 :description)
9661 link))))
9663 ;; Store a link from a source code buffer.
9664 ((org-src-edit-buffer-p)
9665 (let ((coderef-format (org-src-coderef-format)))
9666 (cond ((save-excursion
9667 (beginning-of-line)
9668 (looking-at (org-src-coderef-regexp coderef-format)))
9669 (setq link (format "(%s)" (match-string-no-properties 3))))
9670 ((called-interactively-p 'any)
9671 (let ((label (read-string "Code line label: ")))
9672 (end-of-line)
9673 (setq link (format coderef-format label))
9674 (let ((gc (- 79 (length link))))
9675 (if (< (current-column) gc)
9676 (org-move-to-column gc t)
9677 (insert " ")))
9678 (insert link)
9679 (setq link (concat "(" label ")"))
9680 (setq desc nil)))
9681 (t (setq link nil)))))
9683 ;; We are in the agenda, link to referenced location
9684 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9685 (let ((m (or (get-text-property (point) 'org-hd-marker)
9686 (get-text-property (point) 'org-marker))))
9687 (when m
9688 (org-with-point-at m
9689 (setq agenda-link
9690 (if (called-interactively-p 'any)
9691 (call-interactively 'org-store-link)
9692 (org-store-link nil)))))))
9694 ((eq major-mode 'calendar-mode)
9695 (let ((cd (calendar-cursor-to-date)))
9696 (setq link
9697 (format-time-string
9698 (car org-time-stamp-formats)
9699 (apply 'encode-time
9700 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9701 nil nil nil))))
9702 (org-store-link-props :type "calendar" :date cd)))
9704 ((eq major-mode 'help-mode)
9705 (setq link (concat "help:" (save-excursion
9706 (goto-char (point-min))
9707 (looking-at "^[^ ]+")
9708 (match-string 0))))
9709 (org-store-link-props :type "help"))
9711 ((eq major-mode 'w3-mode)
9712 (setq cpltxt (if (and (buffer-name)
9713 (not (string-match "Untitled" (buffer-name))))
9714 (buffer-name)
9715 (url-view-url t))
9716 link (url-view-url t))
9717 (org-store-link-props :type "w3" :url (url-view-url t)))
9719 ((eq major-mode 'image-mode)
9720 (setq cpltxt (concat "file:"
9721 (abbreviate-file-name buffer-file-name))
9722 link cpltxt)
9723 (org-store-link-props :type "image" :file buffer-file-name))
9725 ;; In dired, store a link to the file of the current line
9726 ((derived-mode-p 'dired-mode)
9727 (let ((file (dired-get-filename nil t)))
9728 (setq file (if file
9729 (abbreviate-file-name
9730 (expand-file-name (dired-get-filename nil t)))
9731 ;; otherwise, no file so use current directory.
9732 default-directory))
9733 (setq cpltxt (concat "file:" file)
9734 link cpltxt)))
9736 ((setq search (run-hook-with-args-until-success
9737 'org-create-file-search-functions))
9738 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9739 "::" search))
9740 (setq cpltxt (or description link)))
9742 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9743 (org-with-limited-levels
9744 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9745 (cond
9746 ;; Store a link using the target at point
9747 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9748 (setq cpltxt
9749 (concat "file:"
9750 (abbreviate-file-name
9751 (buffer-file-name (buffer-base-buffer)))
9752 "::" (match-string 1))
9753 link cpltxt))
9754 ((and (featurep 'org-id)
9755 (or (eq org-id-link-to-org-use-id t)
9756 (and (called-interactively-p 'any)
9757 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9758 (and (eq org-id-link-to-org-use-id
9759 'create-if-interactive-and-no-custom-id)
9760 (not custom-id))))
9761 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9762 ;; Store a link using the ID at point
9763 (setq link (condition-case nil
9764 (prog1 (org-id-store-link)
9765 (setq desc (or (plist-get org-store-link-plist
9766 :description)
9767 "")))
9768 (error
9769 ;; Probably before first headline, link only to file
9770 (concat "file:"
9771 (abbreviate-file-name
9772 (buffer-file-name (buffer-base-buffer))))))))
9774 ;; Just link to current headline
9775 (setq cpltxt (concat "file:"
9776 (abbreviate-file-name
9777 (buffer-file-name (buffer-base-buffer)))))
9778 ;; Add a context search string
9779 (when (org-xor org-context-in-file-links
9780 (equal arg '(4)))
9781 (let* ((element (org-element-at-point))
9782 (name (org-element-property :name element)))
9783 (setq txt (cond
9784 ((org-at-heading-p) nil)
9785 (name)
9786 ((org-region-active-p)
9787 (buffer-substring (region-beginning) (region-end)))))
9788 (when (or (null txt) (string-match "\\S-" txt))
9789 (setq cpltxt
9790 (concat cpltxt "::"
9791 (condition-case nil
9792 (org-make-org-heading-search-string txt)
9793 (error "")))
9794 desc (or name
9795 (nth 4 (ignore-errors (org-heading-components)))
9796 "NONE")))))
9797 (when (string-match "::\\'" cpltxt)
9798 (setq cpltxt (substring cpltxt 0 -2)))
9799 (setq link cpltxt)))))
9801 ((buffer-file-name (buffer-base-buffer))
9802 ;; Just link to this file here.
9803 (setq cpltxt (concat "file:"
9804 (abbreviate-file-name
9805 (buffer-file-name (buffer-base-buffer)))))
9806 ;; Add a context string.
9807 (when (org-xor org-context-in-file-links
9808 (equal arg '(4)))
9809 (setq txt (if (org-region-active-p)
9810 (buffer-substring (region-beginning) (region-end))
9811 (buffer-substring (point-at-bol) (point-at-eol))))
9812 ;; Only use search option if there is some text.
9813 (when (string-match "\\S-" txt)
9814 (setq cpltxt
9815 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9816 desc "NONE")))
9817 (setq link cpltxt))
9819 ((called-interactively-p 'interactive)
9820 (user-error "No method for storing a link from this buffer"))
9822 (t (setq link nil)))
9824 ;; We're done setting link and desc, clean up
9825 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9826 (setq link (or link cpltxt)
9827 desc (or desc cpltxt))
9828 (cond ((not desc))
9829 ((equal desc "NONE") (setq desc nil))
9830 (t (setq desc
9831 (replace-regexp-in-string
9832 org-bracket-link-analytic-regexp
9833 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9834 desc))))
9835 ;; Return the link
9836 (if (not (and (or (called-interactively-p 'any)
9837 executing-kbd-macro)
9838 link))
9839 (or agenda-link (and link (org-make-link-string link desc)))
9840 (push (list link desc) org-stored-links)
9841 (message "Stored: %s" (or desc link))
9842 (when custom-id
9843 (setq link (concat "file:" (abbreviate-file-name
9844 (buffer-file-name)) "::#" custom-id))
9845 (push (list link desc) org-stored-links))
9846 (car org-stored-links)))))
9848 (defun org-store-link-props (&rest plist)
9849 "Store link properties, extract names, addresses and dates."
9850 (let ((x (plist-get plist :from)))
9851 (when x
9852 (let ((adr (mail-extract-address-components x)))
9853 (setq plist (plist-put plist :fromname (car adr)))
9854 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9855 (let ((x (plist-get plist :to)))
9856 (when x
9857 (let ((adr (mail-extract-address-components x)))
9858 (setq plist (plist-put plist :toname (car adr)))
9859 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9860 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9861 (when x
9862 (setq plist (plist-put plist :date-timestamp
9863 (format-time-string
9864 (org-time-stamp-format t) x)))
9865 (setq plist (plist-put plist :date-timestamp-inactive
9866 (format-time-string
9867 (org-time-stamp-format t t) x)))))
9868 (let ((from (plist-get plist :from))
9869 (to (plist-get plist :to)))
9870 (when (and from to org-from-is-user-regexp)
9871 (setq plist
9872 (plist-put plist :fromto
9873 (if (string-match org-from-is-user-regexp from)
9874 (concat "to %t")
9875 (concat "from %f"))))))
9876 (setq org-store-link-plist plist))
9878 (defun org-add-link-props (&rest plist)
9879 "Add these properties to the link property list."
9880 (let (key value)
9881 (while plist
9882 (setq key (pop plist) value (pop plist))
9883 (setq org-store-link-plist
9884 (plist-put org-store-link-plist key value)))))
9886 (defun org-email-link-description (&optional fmt)
9887 "Return the description part of an email link.
9888 This takes information from `org-store-link-plist' and formats it
9889 according to FMT (default from `org-email-link-description-format')."
9890 (setq fmt (or fmt org-email-link-description-format))
9891 (let* ((p org-store-link-plist)
9892 (to (plist-get p :toaddress))
9893 (from (plist-get p :fromaddress))
9894 (table
9895 (list
9896 (cons "%c" (plist-get p :fromto))
9897 (cons "%F" (plist-get p :from))
9898 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9899 (cons "%T" (plist-get p :to))
9900 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9901 (cons "%s" (plist-get p :subject))
9902 (cons "%d" (plist-get p :date))
9903 (cons "%m" (plist-get p :message-id)))))
9904 (when (string-match "%c" fmt)
9905 ;; Check if the user wrote this message
9906 (if (and org-from-is-user-regexp from to
9907 (save-match-data (string-match org-from-is-user-regexp from)))
9908 (setq fmt (replace-match "to %t" t t fmt))
9909 (setq fmt (replace-match "from %f" t t fmt))))
9910 (org-replace-escapes fmt table)))
9912 (defun org-make-org-heading-search-string (&optional string)
9913 "Make search string for the current headline or STRING."
9914 (let ((s (or string
9915 (and (derived-mode-p 'org-mode)
9916 (save-excursion
9917 (org-back-to-heading t)
9918 (org-element-property :raw-value (org-element-at-point))))))
9919 (lines org-context-in-file-links))
9920 (or string (setq s (concat "*" s))) ; Add * for headlines
9921 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9922 (when (and string (integerp lines) (> lines 0))
9923 (let ((slines (org-split-string s "\n")))
9924 (when (< lines (length slines))
9925 (setq s (mapconcat
9926 'identity
9927 (reverse (nthcdr (- (length slines) lines)
9928 (reverse slines))) "\n")))))
9929 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9931 (defun org-make-link-string (link &optional description)
9932 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9933 (unless (org-string-nw-p link) (error "Empty link"))
9934 (let ((uri (cond ((string-match org-link-types-re link)
9935 (concat (match-string 1 link)
9936 (org-link-escape (substring link (match-end 1)))))
9937 ;; For readability, url-encode internal links only
9938 ;; when absolutely needed (i.e, when they contain
9939 ;; square brackets). File links however, are
9940 ;; encoded since, e.g., spaces are significant.
9941 ((or (file-name-absolute-p link)
9942 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9943 (org-link-escape link))
9944 (t link)))
9945 (description
9946 (and (org-string-nw-p description)
9947 ;; Remove brackets from description, as they are fatal.
9948 (replace-regexp-in-string
9949 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9950 (org-trim description)))))
9951 (format "[[%s]%s]"
9953 (if description (format "[%s]" description) ""))))
9955 (defconst org-link-escape-chars
9956 ;;%20 %5B %5D %25
9957 '(?\s ?\[ ?\] ?%)
9958 "List of characters that should be escaped in a link when stored to Org.
9959 This is the list that is used for internal purposes.")
9961 (defun org-link-escape (text &optional table merge)
9962 "Return percent escaped representation of TEXT.
9963 TEXT is a string with the text to escape.
9964 Optional argument TABLE is a list with characters that should be
9965 escaped. When nil, `org-link-escape-chars' is used.
9966 If optional argument MERGE is set, merge TABLE into
9967 `org-link-escape-chars'."
9968 (let ((characters-to-encode
9969 (cond ((null table) org-link-escape-chars)
9970 (merge (append org-link-escape-chars table))
9971 (t table))))
9972 (mapconcat
9973 (lambda (c)
9974 (if (or (memq c characters-to-encode)
9975 (and org-url-hexify-p (or (< c 32) (> c 126))))
9976 (mapconcat (lambda (e) (format "%%%.2X" e))
9977 (or (encode-coding-char c 'utf-8)
9978 (error "Unable to percent escape character: %c" c))
9980 (char-to-string c)))
9981 text "")))
9983 (defun org-link-unescape (str)
9984 "Unhex hexified Unicode parts in string STR.
9985 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9986 reciprocal of `org-link-escape', which see."
9987 (if (org-string-nw-p str)
9988 (replace-regexp-in-string
9989 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9990 str))
9992 (defun org-link-unescape-compound (hex)
9993 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9994 Note: this function also decodes single byte encodings like
9995 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9996 (save-match-data
9997 (let* ((bytes (cdr (split-string hex "%")))
9998 (ret "")
9999 (eat 0)
10000 (sum 0))
10001 (while bytes
10002 (let* ((val (string-to-number (pop bytes) 16))
10003 (shift-xor
10004 (if (= 0 eat)
10005 (cond
10006 ((>= val 252) (cons 6 252))
10007 ((>= val 248) (cons 5 248))
10008 ((>= val 240) (cons 4 240))
10009 ((>= val 224) (cons 3 224))
10010 ((>= val 192) (cons 2 192))
10011 (t (cons 0 0)))
10012 (cons 6 128))))
10013 (when (>= val 192) (setq eat (car shift-xor)))
10014 (setq val (logxor val (cdr shift-xor)))
10015 (setq sum (+ (lsh sum (car shift-xor)) val))
10016 (when (> eat 0) (setq eat (- eat 1)))
10017 (cond
10018 ((= 0 eat) ;multi byte
10019 (setq ret (concat ret (char-to-string sum)))
10020 (setq sum 0))
10021 ((not bytes) ; single byte(s)
10022 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10023 ret)))
10025 (defun org-link-unescape-single-byte-sequence (hex)
10026 "Unhexify hex-encoded single byte character sequences."
10027 (mapconcat (lambda (byte)
10028 (char-to-string (string-to-number byte 16)))
10029 (cdr (split-string hex "%")) ""))
10031 (defun org-xor (a b)
10032 "Exclusive or."
10033 (if a (not b) b))
10035 (defun org-fixup-message-id-for-http (s)
10036 "Replace special characters in a message id, so it can be used in an http query."
10037 (when (string-match "%" s)
10038 (setq s (mapconcat (lambda (c)
10039 (if (eq c ?%)
10040 "%25"
10041 (char-to-string c)))
10042 s "")))
10043 (while (string-match "<" s)
10044 (setq s (replace-match "%3C" t t s)))
10045 (while (string-match ">" s)
10046 (setq s (replace-match "%3E" t t s)))
10047 (while (string-match "@" s)
10048 (setq s (replace-match "%40" t t s)))
10051 (defun org-link-prettify (link)
10052 "Return a human-readable representation of LINK.
10053 The car of LINK must be a raw link.
10054 The cdr of LINK must be either a link description or nil."
10055 (let ((desc (or (cadr link) "<no description>")))
10056 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10057 "<" (car link) ">")))
10059 ;;;###autoload
10060 (defun org-insert-link-global ()
10061 "Insert a link like Org mode does.
10062 This command can be called in any mode to insert a link in Org syntax."
10063 (interactive)
10064 (org-load-modules-maybe)
10065 (org-run-like-in-org-mode 'org-insert-link))
10067 (defun org-insert-all-links (arg &optional pre post)
10068 "Insert all links in `org-stored-links'.
10069 When a universal prefix, do not delete the links from `org-stored-links'.
10070 When `ARG' is a number, insert the last N link(s).
10071 `PRE' and `POST' are optional arguments to define a string to
10072 prepend or to append."
10073 (interactive "P")
10074 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10075 (links (copy-sequence org-stored-links))
10076 (pr (or pre "- "))
10077 (po (or post "\n"))
10078 (cnt 1) l)
10079 (if (null org-stored-links)
10080 (message "No link to insert")
10081 (while (and (or (listp arg) (>= arg cnt))
10082 (setq l (if (listp arg)
10083 (pop links)
10084 (pop org-stored-links))))
10085 (setq cnt (1+ cnt))
10086 (insert pr)
10087 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10088 (insert po)))))
10090 (defun org-insert-last-stored-link (arg)
10091 "Insert the last link stored in `org-stored-links'."
10092 (interactive "p")
10093 (org-insert-all-links arg "" "\n"))
10095 (defun org-link-fontify-links-to-this-file ()
10096 "Fontify links to the current file in `org-stored-links'."
10097 (let ((f (buffer-file-name)) a b)
10098 (setq a (mapcar (lambda(l)
10099 (let ((ll (car l)))
10100 (when (and (string-match "^file:\\(.+\\)::" ll)
10101 (equal f (expand-file-name (match-string 1 ll))))
10102 ll)))
10103 org-stored-links))
10104 (when (featurep 'org-id)
10105 (setq b (mapcar (lambda(l)
10106 (let ((ll (car l)))
10107 (when (and (string-match "^id:\\(.+\\)$" ll)
10108 (equal f (expand-file-name
10109 (or (org-id-find-id-file
10110 (match-string 1 ll)) ""))))
10111 ll)))
10112 org-stored-links)))
10113 (mapcar (lambda(l)
10114 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10115 (delq nil (append a b)))))
10117 (defvar org--links-history nil)
10118 (defun org-insert-link (&optional complete-file link-location default-description)
10119 "Insert a link. At the prompt, enter the link.
10121 Completion can be used to insert any of the link protocol prefixes in use.
10123 The history can be used to select a link previously stored with
10124 `org-store-link'. When the empty string is entered (i.e. if you just
10125 press `RET' at the prompt), the link defaults to the most recently
10126 stored link. As `SPC' triggers completion in the minibuffer, you need to
10127 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10129 You will also be prompted for a description, and if one is given, it will
10130 be displayed in the buffer instead of the link.
10132 If there is already a link at point, this command will allow you to edit
10133 link and description parts.
10135 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10136 file name can be
10137 selected using completion. The path to the file will be relative to the
10138 current directory if the file is in the current directory or a subdirectory.
10139 Otherwise, the link will be the absolute path as completed in the minibuffer
10140 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10141 option `org-link-file-path-type'.
10143 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10144 absolute path even if the file is in
10145 the current directory or below.
10147 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10148 prefix negates `org-keep-stored-link-after-insertion'.
10150 If `org-make-link-description-function' is non-nil, this function will be
10151 called with the link target, and the result will be the default
10152 link description.
10154 If the LINK-LOCATION parameter is non-nil, this value will be used as
10155 the link location instead of reading one interactively.
10157 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10158 as the default description."
10159 (interactive "P")
10160 (let* ((wcf (current-window-configuration))
10161 (origbuf (current-buffer))
10162 (region (when (org-region-active-p)
10163 (buffer-substring (region-beginning) (region-end))))
10164 (remove (and region (list (region-beginning) (region-end))))
10165 (desc region)
10166 (link link-location)
10167 (abbrevs org-link-abbrev-alist-local)
10168 entry all-prefixes auto-desc)
10169 (cond
10170 (link-location) ; specified by arg, just use it.
10171 ((org-in-regexp org-bracket-link-regexp 1)
10172 ;; We do have a link at point, and we are going to edit it.
10173 (setq remove (list (match-beginning 0) (match-end 0)))
10174 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10175 (setq link (read-string "Link: "
10176 (org-link-unescape
10177 (match-string-no-properties 1)))))
10178 ((or (org-in-regexp org-angle-link-re)
10179 (org-in-regexp org-plain-link-re))
10180 ;; Convert to bracket link
10181 (setq remove (list (match-beginning 0) (match-end 0))
10182 link (read-string "Link: "
10183 (org-unbracket-string "<" ">" (match-string 0)))))
10184 ((member complete-file '((4) (16)))
10185 ;; Completing read for file names.
10186 (setq link (org-file-complete-link complete-file)))
10188 ;; Read link, with completion for stored links.
10189 (org-link-fontify-links-to-this-file)
10190 (org-switch-to-buffer-other-window "*Org Links*")
10191 (with-current-buffer "*Org Links*"
10192 (erase-buffer)
10193 (insert "Insert a link.
10194 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10195 (when org-stored-links
10196 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10197 (insert (mapconcat 'org-link-prettify
10198 (reverse org-stored-links) "\n")))
10199 (goto-char (point-min)))
10200 (let ((cw (selected-window)))
10201 (select-window (get-buffer-window "*Org Links*" 'visible))
10202 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10203 (unless (pos-visible-in-window-p (point-max))
10204 (org-fit-window-to-buffer))
10205 (and (window-live-p cw) (select-window cw)))
10206 (setq all-prefixes (append (mapcar 'car abbrevs)
10207 (mapcar 'car org-link-abbrev-alist)
10208 (org-link-types)))
10209 (unwind-protect
10210 ;; Fake a link history, containing the stored links.
10211 (let ((org--links-history
10212 (append (mapcar #'car org-stored-links)
10213 org-insert-link-history)))
10214 (setq link
10215 (org-completing-read
10216 "Link: "
10217 (append
10218 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10219 (mapcar #'car org-stored-links))
10220 nil nil nil
10221 'org--links-history
10222 (caar org-stored-links)))
10223 (unless (org-string-nw-p link) (user-error "No link selected"))
10224 (dolist (l org-stored-links)
10225 (when (equal link (cadr l))
10226 (setq link (car l))
10227 (setq auto-desc t)))
10228 (when (or (member link all-prefixes)
10229 (and (equal ":" (substring link -1))
10230 (member (substring link 0 -1) all-prefixes)
10231 (setq link (substring link 0 -1))))
10232 (setq link (with-current-buffer origbuf
10233 (org-link-try-special-completion link)))))
10234 (set-window-configuration wcf)
10235 (kill-buffer "*Org Links*"))
10236 (setq entry (assoc link org-stored-links))
10237 (or entry (push link org-insert-link-history))
10238 (setq desc (or desc (nth 1 entry)))))
10240 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10241 (not org-keep-stored-link-after-insertion))
10242 (setq org-stored-links (delq (assoc link org-stored-links)
10243 org-stored-links)))
10245 (when (and (string-match org-plain-link-re link)
10246 (not (string-match org-ts-regexp link)))
10247 ;; URL-like link, normalize the use of angular brackets.
10248 (setq link (org-unbracket-string "<" ">" link)))
10250 ;; Check if we are linking to the current file with a search
10251 ;; option If yes, simplify the link by using only the search
10252 ;; option.
10253 (when (and buffer-file-name
10254 (let ((case-fold-search nil))
10255 (string-match "\\`file:\\(.+?\\)::" link)))
10256 (let ((path (match-string-no-properties 1 link))
10257 (search (substring-no-properties link (match-end 0))))
10258 (save-match-data
10259 (when (equal (file-truename buffer-file-name) (file-truename path))
10260 ;; We are linking to this same file, with a search option
10261 (setq link search)))))
10263 ;; Check if we can/should use a relative path. If yes, simplify the link
10264 (let ((case-fold-search nil))
10265 (when (string-match "\\`\\(file\\|docview\\):" link)
10266 (let* ((type (match-string-no-properties 0 link))
10267 (path (substring-no-properties link (match-end 0)))
10268 (origpath path))
10269 (cond
10270 ((or (eq org-link-file-path-type 'absolute)
10271 (equal complete-file '(16)))
10272 (setq path (abbreviate-file-name (expand-file-name path))))
10273 ((eq org-link-file-path-type 'noabbrev)
10274 (setq path (expand-file-name path)))
10275 ((eq org-link-file-path-type 'relative)
10276 (setq path (file-relative-name path)))
10278 (save-match-data
10279 (if (string-match (concat "^" (regexp-quote
10280 (expand-file-name
10281 (file-name-as-directory
10282 default-directory))))
10283 (expand-file-name path))
10284 ;; We are linking a file with relative path name.
10285 (setq path (substring (expand-file-name path)
10286 (match-end 0)))
10287 (setq path (abbreviate-file-name (expand-file-name path)))))))
10288 (setq link (concat type path))
10289 (when (equal desc origpath)
10290 (setq desc path)))))
10292 (if org-make-link-description-function
10293 (setq desc
10294 (or (condition-case nil
10295 (funcall org-make-link-description-function link desc)
10296 (error (progn (message "Can't get link description from `%s'"
10297 (symbol-name org-make-link-description-function))
10298 (sit-for 2) nil)))
10299 (read-string "Description: " default-description)))
10300 (if default-description (setq desc default-description)
10301 (setq desc (or (and auto-desc desc)
10302 (read-string "Description: " desc)))))
10304 (unless (string-match "\\S-" desc) (setq desc nil))
10305 (when remove (apply 'delete-region remove))
10306 (insert (org-make-link-string link desc))
10307 ;; Redisplay so as the new link has proper invisible characters.
10308 (sit-for 0)))
10310 (defun org-link-try-special-completion (type)
10311 "If there is completion support for link type TYPE, offer it."
10312 (let ((fun (org-link-get-parameter type :complete)))
10313 (if (functionp fun)
10314 (funcall fun)
10315 (read-string "Link (no completion support): " (concat type ":")))))
10317 (defun org-file-complete-link (&optional arg)
10318 "Create a file link using completion."
10319 (let ((file (read-file-name "File: "))
10320 (pwd (file-name-as-directory (expand-file-name ".")))
10321 (pwd1 (file-name-as-directory (abbreviate-file-name
10322 (expand-file-name ".")))))
10323 (cond ((equal arg '(16))
10324 (concat "file:"
10325 (abbreviate-file-name (expand-file-name file))))
10326 ((string-match
10327 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10328 (concat "file:" (match-string 1 file)))
10329 ((string-match
10330 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10331 (expand-file-name file))
10332 (concat "file:"
10333 (match-string 1 (expand-file-name file))))
10334 (t (concat "file:" file)))))
10336 (defun org-completing-read (&rest args)
10337 "Completing-read with SPACE being a normal character."
10338 (let ((enable-recursive-minibuffers t)
10339 (minibuffer-local-completion-map
10340 (copy-keymap minibuffer-local-completion-map)))
10341 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10342 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10343 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10344 'org-time-stamp-inactive)
10345 (apply #'completing-read args)))
10347 ;;; Opening/following a link
10349 (defvar org-link-search-failed nil)
10351 (defvar org-open-link-functions nil
10352 "Hook for functions finding a plain text link.
10353 These functions must take a single argument, the link content.
10354 They will be called for links that look like [[link text][description]]
10355 when LINK TEXT does not have a protocol like \"http:\" and does not look
10356 like a filename (e.g. \"./blue.png\").
10358 These functions will be called *before* Org attempts to resolve the
10359 link by doing text searches in the current buffer - so if you want a
10360 link \"[[target]]\" to still find \"<<target>>\", your function should
10361 handle this as a special case.
10363 When the function does handle the link, it must return a non-nil value.
10364 If it decides that it is not responsible for this link, it must return
10365 nil to indicate that that Org can continue with other options like
10366 exact and fuzzy text search.")
10368 (defun org-next-link (&optional search-backward)
10369 "Move forward to the next link.
10370 If the link is in hidden text, expose it."
10371 (interactive "P")
10372 (when (and org-link-search-failed (eq this-command last-command))
10373 (goto-char (point-min))
10374 (message "Link search wrapped back to beginning of buffer"))
10375 (setq org-link-search-failed nil)
10376 (let* ((pos (point))
10377 (ct (org-context))
10378 (a (assq :link ct))
10379 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10380 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10381 ((looking-at org-any-link-re)
10382 ;; Don't stay stuck at link without an org-link face
10383 (forward-char (if search-backward -1 1))))
10384 (if (funcall srch-fun org-any-link-re nil t)
10385 (progn
10386 (goto-char (match-beginning 0))
10387 (when (org-invisible-p) (org-show-context)))
10388 (goto-char pos)
10389 (setq org-link-search-failed t)
10390 (message "No further link found"))))
10392 (defun org-previous-link ()
10393 "Move backward to the previous link.
10394 If the link is in hidden text, expose it."
10395 (interactive)
10396 (funcall 'org-next-link t))
10398 (defun org-translate-link (s)
10399 "Translate a link string if a translation function has been defined."
10400 (with-temp-buffer
10401 (insert (org-trim s))
10402 (org-trim (org-element-interpret-data (org-element-context)))))
10404 (defun org-translate-link-from-planner (type path)
10405 "Translate a link from Emacs Planner syntax so that Org can follow it.
10406 This is still an experimental function, your mileage may vary."
10407 (cond
10408 ((member type '("http" "https" "news" "ftp"))
10409 ;; standard Internet links are the same.
10410 nil)
10411 ((and (equal type "irc") (string-match "^//" path))
10412 ;; Planner has two / at the beginning of an irc link, we have 1.
10413 ;; We should have zero, actually....
10414 (setq path (substring path 1)))
10415 ((and (equal type "lisp") (string-match "^/" path))
10416 ;; Planner has a slash, we do not.
10417 (setq type "elisp" path (substring path 1)))
10418 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10419 ;; A typical message link. Planner has the id after the final slash,
10420 ;; we separate it with a hash mark
10421 (setq path (concat (match-string 1 path) "#"
10422 (org-unbracket-string "<" ">" (match-string 2 path))))))
10423 (cons type path))
10425 (defun org-find-file-at-mouse (ev)
10426 "Open file link or URL at mouse."
10427 (interactive "e")
10428 (mouse-set-point ev)
10429 (org-open-at-point 'in-emacs))
10431 (defun org-open-at-mouse (ev)
10432 "Open file link or URL at mouse.
10433 See the docstring of `org-open-file' for details."
10434 (interactive "e")
10435 (mouse-set-point ev)
10436 (when (eq major-mode 'org-agenda-mode)
10437 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10438 (org-open-at-point))
10440 (defvar org-window-config-before-follow-link nil
10441 "The window configuration before following a link.
10442 This is saved in case the need arises to restore it.")
10444 ;;;###autoload
10445 (defun org-open-at-point-global ()
10446 "Follow a link or time-stamp like Org mode does.
10447 This command can be called in any mode to follow an external link
10448 or a time-stamp that has Org mode syntax. Its behavior is
10449 undefined when called on internal links (e.g., fuzzy links).
10450 Raise an error when there is nothing to follow. "
10451 (interactive)
10452 (cond ((org-in-regexp org-any-link-re)
10453 (org-open-link-from-string (match-string-no-properties 0)))
10454 ((or (org-in-regexp org-ts-regexp-both nil t)
10455 (org-in-regexp org-tsr-regexp-both nil t))
10456 (org-follow-timestamp-link))
10457 (t (user-error "No link found"))))
10459 ;;;###autoload
10460 (defun org-open-link-from-string (s &optional arg reference-buffer)
10461 "Open a link in the string S, as if it was in Org mode."
10462 (interactive "sLink: \nP")
10463 (let ((reference-buffer (or reference-buffer (current-buffer))))
10464 (with-temp-buffer
10465 (let ((org-inhibit-startup (not reference-buffer)))
10466 (org-mode)
10467 (insert s)
10468 (goto-char (point-min))
10469 (when reference-buffer
10470 (setq org-link-abbrev-alist-local
10471 (with-current-buffer reference-buffer
10472 org-link-abbrev-alist-local)))
10473 (org-open-at-point arg reference-buffer)))))
10475 (defvar org-open-at-point-functions nil
10476 "Hook that is run when following a link at point.
10478 Functions in this hook must return t if they identify and follow
10479 a link at point. If they don't find anything interesting at point,
10480 they must return nil.")
10482 (defvar org-link-search-inhibit-query nil)
10483 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10484 (defun org--open-doi-link (path)
10485 "Open a \"doi\" type link.
10486 PATH is a the path to search for, as a string."
10487 (browse-url (url-encode-url (concat org-doi-server-url path))))
10489 (defun org--open-elisp-link (path)
10490 "Open a \"elisp\" type link.
10491 PATH is the sexp to evaluate, as a string."
10492 (let ((cmd path))
10493 (if (or (and (org-string-nw-p
10494 org-confirm-elisp-link-not-regexp)
10495 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10496 (not org-confirm-elisp-link-function)
10497 (funcall org-confirm-elisp-link-function
10498 (format "Execute \"%s\" as elisp? "
10499 (org-add-props cmd nil 'face 'org-warning))))
10500 (message "%s => %s" cmd
10501 (if (eq (string-to-char cmd) ?\()
10502 (eval (read cmd))
10503 (call-interactively (read cmd))))
10504 (user-error "Abort"))))
10506 (defun org--open-help-link (path)
10507 "Open a \"help\" type link.
10508 PATH is a symbol name, as a string."
10509 (pcase (intern path)
10510 ((and (pred fboundp) variable) (describe-function variable))
10511 ((and (pred boundp) function) (describe-variable function))
10512 (name (user-error "Unknown function or variable: %s" name))))
10514 (defun org--open-shell-link (path)
10515 "Open a \"shell\" type link.
10516 PATH is the command to execute, as a string."
10517 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10518 (cmd path))
10519 (if (or (and (org-string-nw-p
10520 org-confirm-shell-link-not-regexp)
10521 (string-match
10522 org-confirm-shell-link-not-regexp cmd))
10523 (not org-confirm-shell-link-function)
10524 (funcall org-confirm-shell-link-function
10525 (format "Execute \"%s\" in shell? "
10526 (org-add-props cmd nil
10527 'face 'org-warning))))
10528 (progn
10529 (message "Executing %s" cmd)
10530 (shell-command cmd buf)
10531 (when (featurep 'midnight)
10532 (setq clean-buffer-list-kill-buffer-names
10533 (cons (buffer-name buf)
10534 clean-buffer-list-kill-buffer-names))))
10535 (user-error "Abort"))))
10537 (defun org-open-at-point (&optional arg reference-buffer)
10538 "Open link, timestamp, footnote or tags at point.
10540 When point is on a link, follow it. Normally, files will be
10541 opened by an appropriate application. If the optional prefix
10542 argument ARG is non-nil, Emacs will visit the file. With
10543 a double prefix argument, try to open outside of Emacs, in the
10544 application the system uses for this file type.
10546 When point is on a timestamp, open the agenda at the day
10547 specified.
10549 When point is a footnote definition, move to the first reference
10550 found. If it is on a reference, move to the associated
10551 definition.
10553 When point is on a headline, display a list of every link in the
10554 entry, so it is possible to pick one, or all, of them. If point
10555 is on a tag, call `org-tags-view' instead.
10557 When optional argument REFERENCE-BUFFER is non-nil, it should
10558 specify a buffer from where the link search should happen. This
10559 is used internally by `org-open-link-from-string'.
10561 On top of syntactically correct links, this function will also
10562 try to open links and time-stamps in comments, example
10563 blocks... i.e., whenever point is on something looking like
10564 a timestamp or a link."
10565 (interactive "P")
10566 ;; On a code block, open block's results.
10567 (unless (call-interactively 'org-babel-open-src-block-result)
10568 (org-load-modules-maybe)
10569 (setq org-window-config-before-follow-link (current-window-configuration))
10570 (org-remove-occur-highlights nil nil t)
10571 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10572 (let* ((context
10573 ;; Only consider supported types, even if they are not
10574 ;; the closest one.
10575 (org-element-lineage
10576 (org-element-context)
10577 '(clock footnote-definition footnote-reference headline
10578 inlinetask link timestamp)
10580 (type (org-element-type context))
10581 (value (org-element-property :value context)))
10582 (cond
10583 ;; On a headline or an inlinetask, but not on a timestamp,
10584 ;; a link, a footnote reference.
10585 ((memq type '(headline inlinetask))
10586 (org-match-line org-complex-heading-regexp)
10587 (if (and (match-beginning 5)
10588 (>= (point) (match-beginning 5))
10589 (< (point) (match-end 5)))
10590 ;; On tags.
10591 (org-tags-view arg (substring (match-string 5) 0 -1))
10592 ;; Not on tags.
10593 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10594 (`(nil . ,_)
10595 (require 'org-attach)
10596 (org-attach-reveal 'if-exists))
10597 (`(,links . ,links-end)
10598 (dolist (link (if (stringp links) (list links) links))
10599 (search-forward link nil links-end)
10600 (goto-char (match-beginning 0))
10601 (org-open-at-point))))))
10602 ;; On a footnote reference or at definition's label.
10603 ((or (eq type 'footnote-reference)
10604 (and (eq type 'footnote-definition)
10605 (save-excursion
10606 ;; Do not validate action when point is on the
10607 ;; spaces right after the footnote label, in
10608 ;; order to be on par with behaviour on links.
10609 (skip-chars-forward " \t")
10610 (let ((begin
10611 (org-element-property :contents-begin context)))
10612 (if begin (< (point) begin)
10613 (= (org-element-property :post-affiliated context)
10614 (line-beginning-position)))))))
10615 (org-footnote-action))
10616 ;; No valid context. Ignore catch-all types like `headline'.
10617 ;; If point is on something looking like a link or
10618 ;; a time-stamp, try opening it. It may be useful in
10619 ;; comments, example blocks...
10620 ((memq type '(footnote-definition headline inlinetask nil))
10621 (call-interactively #'org-open-at-point-global))
10622 ;; On a clock line, make sure point is on the timestamp
10623 ;; before opening it.
10624 ((and (eq type 'clock)
10625 value
10626 (>= (point) (org-element-property :begin value))
10627 (<= (point) (org-element-property :end value)))
10628 (org-follow-timestamp-link))
10629 ;; Do nothing on white spaces after an object.
10630 ((>= (point)
10631 (save-excursion
10632 (goto-char (org-element-property :end context))
10633 (skip-chars-backward " \t")
10634 (point)))
10635 (user-error "No link found"))
10636 ((eq type 'timestamp) (org-follow-timestamp-link))
10637 ((eq type 'link)
10638 (let ((type (org-element-property :type context))
10639 (path (org-link-unescape (org-element-property :path context))))
10640 ;; Switch back to REFERENCE-BUFFER needed when called in
10641 ;; a temporary buffer through `org-open-link-from-string'.
10642 (with-current-buffer (or reference-buffer (current-buffer))
10643 (cond
10644 ((equal type "file")
10645 (if (string-match "[*?{]" (file-name-nondirectory path))
10646 (dired path)
10647 ;; Look into `org-link-parameters' in order to find
10648 ;; a DEDICATED-FUNCTION to open file. The function
10649 ;; will be applied on raw link instead of parsed
10650 ;; link due to the limitation in `org-add-link-type'
10651 ;; ("open" function called with a single argument).
10652 ;; If no such function is found, fallback to
10653 ;; `org-open-file'.
10654 (let* ((option (org-element-property :search-option context))
10655 (app (org-element-property :application context))
10656 (dedicated-function
10657 (org-link-get-parameter
10658 (if app (concat type "+" app) type)
10659 :follow)))
10660 (if dedicated-function
10661 (funcall dedicated-function
10662 (concat path
10663 (and option (concat "::" option))))
10664 (apply #'org-open-file
10665 path
10666 (cond (arg)
10667 ((equal app "emacs") 'emacs)
10668 ((equal app "sys") 'system))
10669 (cond ((not option) nil)
10670 ((string-match-p "\\`[0-9]+\\'" option)
10671 (list (string-to-number option)))
10672 (t (list nil
10673 (org-link-unescape option)))))))))
10674 ((functionp (org-link-get-parameter type :follow))
10675 (funcall (org-link-get-parameter type :follow) path))
10676 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10677 (unless (run-hook-with-args-until-success
10678 'org-open-link-functions path)
10679 (if (not arg) (org-mark-ring-push)
10680 (switch-to-buffer-other-window
10681 (org-get-buffer-for-internal-link (current-buffer))))
10682 (let ((destination
10683 (org-with-wide-buffer
10684 (if (equal type "radio")
10685 (org-search-radio-target
10686 (org-element-property :path context))
10687 (org-link-search
10688 (if (member type '("custom-id" "coderef"))
10689 (org-element-property :raw-link context)
10690 path)
10691 ;; Prevent fuzzy links from matching
10692 ;; themselves.
10693 (and (equal type "fuzzy")
10694 (+ 2 (org-element-property :begin context)))))
10695 (point))))
10696 (unless (and (<= (point-min) destination)
10697 (>= (point-max) destination))
10698 (widen))
10699 (goto-char destination))))
10700 (t (browse-url-at-point))))))
10701 (t (user-error "No link found")))))
10702 (run-hook-with-args 'org-follow-link-hook)))
10704 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10705 "Offer links in the current entry and return the selected link.
10706 If there is only one link, return it.
10707 If NTH is an integer, return the NTH link found.
10708 If ZERO is a string, check also this string for a link, and if
10709 there is one, return it."
10710 (with-current-buffer buffer
10711 (org-with-wide-buffer
10712 (goto-char marker)
10713 (let ((cnt ?0)
10714 have-zero end links link c)
10715 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10716 (push (match-string 0 zero) links)
10717 (setq cnt (1- cnt) have-zero t))
10718 (save-excursion
10719 (org-back-to-heading t)
10720 (setq end (save-excursion (outline-next-heading) (point)))
10721 (while (re-search-forward org-any-link-re end t)
10722 (push (match-string 0) links))
10723 (setq links (org-uniquify (reverse links))))
10724 (cond
10725 ((null links)
10726 (message "No links"))
10727 ((equal (length links) 1)
10728 (setq link (car links)))
10729 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10730 (setq link (nth (if have-zero nth (1- nth)) links)))
10731 (t ; we have to select a link
10732 (save-excursion
10733 (save-window-excursion
10734 (delete-other-windows)
10735 (with-output-to-temp-buffer "*Select Link*"
10736 (dolist (l links)
10737 (cond
10738 ((not (string-match org-bracket-link-regexp l))
10739 (princ (format "[%c] %s\n" (cl-incf cnt)
10740 (org-unbracket-string "<" ">" l))))
10741 ((match-end 3)
10742 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10743 (match-string 3 l) (match-string 1 l))))
10744 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10745 (match-string 1 l)))))))
10746 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10747 (message "Select link to open, RET to open all:")
10748 (setq c (read-char-exclusive))
10749 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10750 (when (equal c ?q) (user-error "Abort"))
10751 (if (equal c ?\C-m)
10752 (setq link links)
10753 (setq nth (- c ?0))
10754 (when have-zero (setq nth (1+ nth)))
10755 (unless (and (integerp nth) (>= (length links) nth))
10756 (user-error "Invalid link selection"))
10757 (setq link (nth (1- nth) links)))))
10758 (cons link end)))))
10760 ;; TODO: These functions are deprecated since `org-open-at-point'
10761 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10762 (defun org-open-file-with-system (path)
10763 "Open file at PATH using the system way of opening it."
10764 (org-open-file path 'system))
10765 (defun org-open-file-with-emacs (path)
10766 "Open file at PATH in Emacs."
10767 (org-open-file path 'emacs))
10770 ;;; File search
10772 (defvar org-create-file-search-functions nil
10773 "List of functions to construct the right search string for a file link.
10774 These functions are called in turn with point at the location to
10775 which the link should point.
10777 A function in the hook should first test if it would like to
10778 handle this file type, for example by checking the `major-mode'
10779 or the file extension. If it decides not to handle this file, it
10780 should just return nil to give other functions a chance. If it
10781 does handle the file, it must return the search string to be used
10782 when following the link. The search string will be part of the
10783 file link, given after a double colon, and `org-open-at-point'
10784 will automatically search for it. If special measures must be
10785 taken to make the search successful, another function should be
10786 added to the companion hook `org-execute-file-search-functions',
10787 which see.
10789 A function in this hook may also use `setq' to set the variable
10790 `description' to provide a suggestion for the descriptive text to
10791 be used for this link when it gets inserted into an Org buffer
10792 with \\[org-insert-link].")
10794 (defvar org-execute-file-search-functions nil
10795 "List of functions to execute a file search triggered by a link.
10797 Functions added to this hook must accept a single argument, the
10798 search string that was part of the file link, the part after the
10799 double colon. The function must first check if it would like to
10800 handle this search, for example by checking the `major-mode' or
10801 the file extension. If it decides not to handle this search, it
10802 should just return nil to give other functions a chance. If it
10803 does handle the search, it must return a non-nil value to keep
10804 other functions from trying.
10806 Each function can access the current prefix argument through the
10807 variable `current-prefix-arg'. Note that a single prefix is used
10808 to force opening a link in Emacs, so it may be good to only use a
10809 numeric or double prefix to guide the search function.
10811 In case this is needed, a function in this hook can also restore
10812 the window configuration before `org-open-at-point' was called using:
10814 (set-window-configuration org-window-config-before-follow-link)")
10816 (defun org-search-radio-target (target)
10817 "Search a radio target matching TARGET in current buffer.
10818 White spaces are not significant."
10819 (let ((re (format "<<<%s>>>"
10820 (mapconcat #'regexp-quote
10821 (org-split-string target "[ \t\n]+")
10822 "[ \t]+\\(?:\n[ \t]*\\)?")))
10823 (origin (point)))
10824 (goto-char (point-min))
10825 (catch :radio-match
10826 (while (re-search-forward re nil t)
10827 (backward-char)
10828 (let ((object (org-element-context)))
10829 (when (eq (org-element-type object) 'radio-target)
10830 (goto-char (org-element-property :begin object))
10831 (org-show-context 'link-search)
10832 (throw :radio-match nil))))
10833 (goto-char origin)
10834 (user-error "No match for radio target: %s" target))))
10836 (defun org-link-search (s &optional avoid-pos stealth)
10837 "Search for a search string S.
10839 If S starts with \"#\", it triggers a custom ID search.
10841 If S is enclosed within parenthesis, it initiates a coderef
10842 search.
10844 If S is surrounded by forward slashes, it is interpreted as
10845 a regular expression. In Org mode files, this will create an
10846 `org-occur' sparse tree. In ordinary files, `occur' will be used
10847 to list matches. If the current buffer is in `dired-mode', grep
10848 will be used to search in all files.
10850 When AVOID-POS is given, ignore matches near that position.
10852 When optional argument STEALTH is non-nil, do not modify
10853 visibility around point, thus ignoring `org-show-context-detail'
10854 variable.
10856 Search is case-insensitive and ignores white spaces. Return type
10857 of matched result, which is either `dedicated' or `fuzzy'."
10858 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10859 (let* ((case-fold-search t)
10860 (origin (point))
10861 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10862 (starred (eq (string-to-char normalized) ?*))
10863 (words (split-string (if starred (substring s 1) s)))
10864 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10865 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10866 type)
10867 (cond
10868 ;; Check if there are any special search functions.
10869 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10870 ((eq (string-to-char s) ?#)
10871 ;; Look for a custom ID S if S starts with "#".
10872 (let* ((id (substring normalized 1))
10873 (match (org-find-property "CUSTOM_ID" id)))
10874 (if match (progn (goto-char match) (setf type 'dedicated))
10875 (error "No match for custom ID: %s" id))))
10876 ((string-match "\\`(\\(.*\\))\\'" normalized)
10877 ;; Look for coderef targets if S is enclosed within parenthesis.
10878 (let ((coderef (match-string-no-properties 1 normalized))
10879 (re (substring s-single-re 1 -1)))
10880 (goto-char (point-min))
10881 (catch :coderef-match
10882 (while (re-search-forward re nil t)
10883 (let ((element (org-element-at-point)))
10884 (when (and (memq (org-element-type element)
10885 '(example-block src-block))
10886 ;; Build proper regexp according to current
10887 ;; block's label format.
10888 (let ((label-fmt
10889 (regexp-quote
10890 (or (org-element-property :label-fmt element)
10891 org-coderef-label-format))))
10892 (save-excursion
10893 (beginning-of-line)
10894 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10895 (format label-fmt coderef))))))
10896 (setq type 'dedicated)
10897 (goto-char (match-beginning 1))
10898 (throw :coderef-match nil))))
10899 (goto-char origin)
10900 (error "No match for coderef: %s" coderef))))
10901 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10902 ;; Look for a regular expression.
10903 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10904 (match-string 1 s)))
10905 ;; From here, we handle fuzzy links.
10907 ;; Look for targets, only if not in a headline search.
10908 ((and (not starred)
10909 (let ((target (format "<<%s>>" s-multi-re)))
10910 (catch :target-match
10911 (goto-char (point-min))
10912 (while (re-search-forward target nil t)
10913 (backward-char)
10914 (let ((context (org-element-context)))
10915 (when (eq (org-element-type context) 'target)
10916 (setq type 'dedicated)
10917 (goto-char (org-element-property :begin context))
10918 (throw :target-match t))))
10919 nil))))
10920 ;; Look for elements named after S, only if not in a headline
10921 ;; search.
10922 ((and (not starred)
10923 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10924 (catch :name-match
10925 (goto-char (point-min))
10926 (while (re-search-forward name nil t)
10927 (let ((element (org-element-at-point)))
10928 (when (equal words
10929 (split-string
10930 (org-element-property :name element)))
10931 (setq type 'dedicated)
10932 (beginning-of-line)
10933 (throw :name-match t))))
10934 nil))))
10935 ;; Regular text search. Prefer headlines in Org mode buffers.
10936 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10937 ;; statistics cookies and tags.
10938 ((and (derived-mode-p 'org-mode)
10939 (let ((title-re
10940 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10941 org-outline-regexp-bol
10942 org-comment-string
10943 (mapconcat #'regexp-quote words ".+")))
10944 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10945 (comment-re (eval-when-compile
10946 (format "\\`%s[ \t]+" org-comment-string))))
10947 (goto-char (point-min))
10948 (catch :found
10949 (while (re-search-forward title-re nil t)
10950 (when (equal words
10951 (split-string
10952 (replace-regexp-in-string
10953 cookie-re ""
10954 (replace-regexp-in-string
10955 comment-re "" (org-get-heading t t t)))))
10956 (throw :found t)))
10957 nil)))
10958 (beginning-of-line)
10959 (setq type 'dedicated))
10960 ;; Offer to create non-existent headline depending on
10961 ;; `org-link-search-must-match-exact-headline'.
10962 ((and (derived-mode-p 'org-mode)
10963 (not org-link-search-inhibit-query)
10964 (eq org-link-search-must-match-exact-headline 'query-to-create)
10965 (yes-or-no-p "No match - create this as a new heading? "))
10966 (goto-char (point-max))
10967 (unless (bolp) (newline))
10968 (org-insert-heading nil t t)
10969 (insert s "\n")
10970 (beginning-of-line 0))
10971 ;; Only headlines are looked after. No need to process
10972 ;; further: throw an error.
10973 ((and (derived-mode-p 'org-mode)
10974 (or starred org-link-search-must-match-exact-headline))
10975 (goto-char origin)
10976 (error "No match for fuzzy expression: %s" normalized))
10977 ;; Regular text search.
10978 ((catch :fuzzy-match
10979 (goto-char (point-min))
10980 (while (re-search-forward s-multi-re nil t)
10981 ;; Skip match if it contains AVOID-POS or it is included in
10982 ;; a link with a description but outside the description.
10983 (unless (or (and avoid-pos
10984 (<= (match-beginning 0) avoid-pos)
10985 (> (match-end 0) avoid-pos))
10986 (and (save-match-data
10987 (org-in-regexp org-bracket-link-regexp))
10988 (match-beginning 3)
10989 (or (> (match-beginning 3) (point))
10990 (<= (match-end 3) (point)))
10991 (org-element-lineage
10992 (save-match-data (org-element-context))
10993 '(link) t)))
10994 (goto-char (match-beginning 0))
10995 (setq type 'fuzzy)
10996 (throw :fuzzy-match t)))
10997 nil))
10998 ;; All failed. Throw an error.
10999 (t (goto-char origin)
11000 (error "No match for fuzzy expression: %s" normalized)))
11001 ;; Disclose surroundings of match, if appropriate.
11002 (when (and (derived-mode-p 'org-mode) (not stealth))
11003 (org-show-context 'link-search))
11004 type))
11006 (defun org-get-buffer-for-internal-link (buffer)
11007 "Return a buffer to be used for displaying the link target of internal links."
11008 (cond
11009 ((not org-display-internal-link-with-indirect-buffer)
11010 buffer)
11011 ((string-suffix-p "(Clone)" (buffer-name buffer))
11012 (message "Buffer is already a clone, not making another one")
11013 ;; we also do not modify visibility in this case
11014 buffer)
11015 (t ; make a new indirect buffer for displaying the link
11016 (let* ((bn (buffer-name buffer))
11017 (ibn (concat bn "(Clone)"))
11018 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11019 (with-current-buffer ib (org-overview))
11020 ib))))
11022 (defun org-do-occur (regexp &optional cleanup)
11023 "Call the Emacs command `occur'.
11024 If CLEANUP is non-nil, remove the printout of the regular expression
11025 in the *Occur* buffer. This is useful if the regex is long and not useful
11026 to read."
11027 (occur regexp)
11028 (when cleanup
11029 (let ((cwin (selected-window)) win beg end)
11030 (when (setq win (get-buffer-window "*Occur*"))
11031 (select-window win))
11032 (goto-char (point-min))
11033 (when (re-search-forward "match[a-z]+" nil t)
11034 (setq beg (match-end 0))
11035 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11036 (setq end (1- (match-beginning 0)))))
11037 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11038 (goto-char (point-min))
11039 (select-window cwin))))
11041 ;;; The mark ring for links jumps
11043 (defvar org-mark-ring nil
11044 "Mark ring for positions before jumps in Org mode.")
11045 (defvar org-mark-ring-last-goto nil
11046 "Last position in the mark ring used to go back.")
11047 ;; Fill and close the ring
11048 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11049 (dotimes (_ org-mark-ring-length)
11050 (push (make-marker) org-mark-ring))
11051 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11052 org-mark-ring)
11054 (defun org-mark-ring-push (&optional pos buffer)
11055 "Put the current position or POS into the mark ring and rotate it."
11056 (interactive)
11057 (setq pos (or pos (point)))
11058 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11059 (move-marker (car org-mark-ring)
11060 (or pos (point))
11061 (or buffer (current-buffer)))
11062 (message "%s"
11063 (substitute-command-keys
11064 "Position saved to mark ring, go back with \
11065 `\\[org-mark-ring-goto]'.")))
11067 (defun org-mark-ring-goto (&optional n)
11068 "Jump to the previous position in the mark ring.
11069 With prefix arg N, jump back that many stored positions. When
11070 called several times in succession, walk through the entire ring.
11071 Org mode commands jumping to a different position in the current file,
11072 or to another Org file, automatically push the old position onto the ring."
11073 (interactive "p")
11074 (let (p m)
11075 (if (eq last-command this-command)
11076 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11077 (setq p org-mark-ring))
11078 (setq org-mark-ring-last-goto p)
11079 (setq m (car p))
11080 (pop-to-buffer-same-window (marker-buffer m))
11081 (goto-char m)
11082 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11084 (defun org-add-angle-brackets (s)
11085 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11086 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11089 ;;; Following specific links
11091 (defvar org-agenda-buffer-tmp-name)
11092 (defvar org-agenda-start-on-weekday)
11093 (defun org-follow-timestamp-link ()
11094 "Open an agenda view for the time-stamp date/range at point."
11095 (cond
11096 ((org-at-date-range-p t)
11097 (let ((org-agenda-start-on-weekday)
11098 (t1 (match-string 1))
11099 (t2 (match-string 2)) tt1 tt2)
11100 (setq tt1 (time-to-days (org-time-string-to-time t1))
11101 tt2 (time-to-days (org-time-string-to-time t2)))
11102 (let ((org-agenda-buffer-tmp-name
11103 (format "*Org Agenda(a:%s)"
11104 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11105 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11106 ((org-at-timestamp-p 'lax)
11107 (let ((org-agenda-buffer-tmp-name
11108 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11109 (org-agenda-list nil (time-to-days (org-time-string-to-time
11110 (substring (match-string 1) 0 10)))
11111 1)))
11112 (t (error "This should not happen"))))
11115 ;;; Following file links
11116 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11117 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11118 (declare-function mailcap-mime-info
11119 "mailcap" (string &optional request no-decode))
11120 (defvar org-wait nil)
11121 (defun org-open-file (path &optional in-emacs line search)
11122 "Open the file at PATH.
11123 First, this expands any special file name abbreviations. Then the
11124 configuration variable `org-file-apps' is checked if it contains an
11125 entry for this file type, and if yes, the corresponding command is launched.
11127 If no application is found, Emacs simply visits the file.
11129 With optional prefix argument IN-EMACS, Emacs will visit the file.
11130 With a double \\[universal-argument] \\[universal-argument] \
11131 prefix arg, Org tries to avoid opening in Emacs
11132 and to use an external application to visit the file.
11134 Optional LINE specifies a line to go to, optional SEARCH a string
11135 to search for. If LINE or SEARCH is given, the file will be
11136 opened in Emacs, unless an entry from org-file-apps that makes
11137 use of groups in a regexp matches.
11139 If you want to change the way frames are used when following a
11140 link, please customize `org-link-frame-setup'.
11142 If the file does not exist, an error is thrown."
11143 (let* ((file (if (equal path "")
11144 buffer-file-name
11145 (substitute-in-file-name (expand-file-name path))))
11146 (file-apps (append org-file-apps (org-default-apps)))
11147 (apps (cl-remove-if
11148 'org-file-apps-entry-match-against-dlink-p file-apps))
11149 (apps-dlink (cl-remove-if-not
11150 'org-file-apps-entry-match-against-dlink-p file-apps))
11151 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11152 (dirp (unless remp (file-directory-p file)))
11153 (file (if (and dirp org-open-directory-means-index-dot-org)
11154 (concat (file-name-as-directory file) "index.org")
11155 file))
11156 (a-m-a-p (assq 'auto-mode apps))
11157 (dfile (downcase file))
11158 ;; Reconstruct the original link from the PATH, LINE and
11159 ;; SEARCH args.
11160 (link (cond (line (concat file "::" (number-to-string line)))
11161 (search (concat file "::" search))
11162 (t file)))
11163 (dlink (downcase link))
11164 (ext
11165 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11166 (match-string 1 dfile)))
11167 (save-position-maybe
11168 (let ((old-buffer (current-buffer))
11169 (old-pos (point))
11170 (old-mode major-mode))
11171 (lambda ()
11172 (and (derived-mode-p 'org-mode)
11173 (eq old-mode 'org-mode)
11174 (or (not (eq old-buffer (current-buffer)))
11175 (not (eq old-pos (point))))
11176 (org-mark-ring-push old-pos old-buffer)))))
11177 cmd link-match-data)
11178 (cond
11179 ((member in-emacs '((16) system))
11180 (setq cmd (cdr (assq 'system apps))))
11181 (in-emacs (setq cmd 'emacs))
11183 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11184 (and dirp (cdr (assq 'directory apps)))
11185 ;; First, try matching against apps-dlink if we
11186 ;; get a match here, store the match data for
11187 ;; later.
11188 (let ((match (assoc-default dlink apps-dlink
11189 'string-match)))
11190 (if match
11191 (progn (setq link-match-data (match-data))
11192 match)
11193 (progn (setq in-emacs (or in-emacs line search))
11194 nil))) ; if we have no match in apps-dlink,
11195 ; always open the file in emacs if line or search
11196 ; is given (for backwards compatibility)
11197 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11198 'string-match)
11199 (cdr (assoc ext apps))
11200 (cdr (assq t apps))))))
11201 (when (eq cmd 'system)
11202 (setq cmd (cdr (assq 'system apps))))
11203 (when (eq cmd 'default)
11204 (setq cmd (cdr (assoc t apps))))
11205 (when (eq cmd 'mailcap)
11206 (require 'mailcap)
11207 (mailcap-parse-mailcaps)
11208 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11209 (command (mailcap-mime-info mime-type)))
11210 (if (stringp command)
11211 (setq cmd command)
11212 (setq cmd 'emacs))))
11213 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11214 (not (file-exists-p file))
11215 (not org-open-non-existing-files))
11216 (user-error "No such file: %s" file))
11217 (cond
11218 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11219 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11220 (while (string-match "['\"]%s['\"]" cmd)
11221 (setq cmd (replace-match "%s" t t cmd)))
11222 (setq cmd (replace-regexp-in-string
11223 "%s"
11224 (shell-quote-argument (convert-standard-filename file))
11226 nil t))
11228 ;; Replace "%1", "%2" etc. in command with group matches from regex
11229 (save-match-data
11230 (let ((match-index 1)
11231 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11232 (set-match-data link-match-data)
11233 (while (<= match-index number-of-groups)
11234 (let ((regex (concat "%" (number-to-string match-index)))
11235 (replace-with (match-string match-index dlink)))
11236 (while (string-match regex cmd)
11237 (setq cmd (replace-match replace-with t t cmd))))
11238 (setq match-index (+ match-index 1)))))
11240 (save-window-excursion
11241 (message "Running %s...done" cmd)
11242 (start-process-shell-command cmd nil cmd)
11243 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11244 ((or (stringp cmd)
11245 (eq cmd 'emacs))
11246 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11247 (widen)
11248 (cond (line (org-goto-line line)
11249 (when (derived-mode-p 'org-mode) (org-reveal)))
11250 (search (condition-case err
11251 (org-link-search search)
11252 ;; Save position before error-ing out so user
11253 ;; can easily move back to the original buffer.
11254 (error (funcall save-position-maybe)
11255 (error (nth 1 err)))))))
11256 ((functionp cmd)
11257 (save-match-data
11258 (set-match-data link-match-data)
11259 (condition-case nil
11260 (funcall cmd file link)
11261 ;; FIXME: Remove this check when most default installations
11262 ;; of Emacs have at least Org 9.0.
11263 ((debug wrong-number-of-arguments wrong-type-argument
11264 invalid-function)
11265 (user-error "Please see Org News for version 9.0 about \
11266 `org-file-apps'--Lisp error: %S" cmd)))))
11267 ((consp cmd)
11268 ;; FIXME: Remove this check when most default installations of
11269 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11270 ;; fall back to `org-link-frame-setup' for an old usage of
11271 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11272 (user-error "Please see Org News for version 9.0 about \
11273 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11274 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11275 (funcall save-position-maybe)))
11277 (defun org-file-apps-entry-match-against-dlink-p (entry)
11278 "This function returns non-nil if `entry' uses a regular
11279 expression which should be matched against the whole link by
11280 org-open-file.
11282 It assumes that is the case when the entry uses a regular
11283 expression which has at least one grouping construct and the
11284 action is either a lisp form or a command string containing
11285 `%1', i.e. using at least one subexpression match as a
11286 parameter."
11287 (let ((selector (car entry))
11288 (action (cdr entry)))
11289 (if (stringp selector)
11290 (and (> (regexp-opt-depth selector) 0)
11291 (or (and (stringp action)
11292 (string-match "%[0-9]" action))
11293 (consp action)))
11294 nil)))
11296 (defun org-default-apps ()
11297 "Return the default applications for this operating system."
11298 (cond
11299 ((eq system-type 'darwin)
11300 org-file-apps-defaults-macosx)
11301 ((eq system-type 'windows-nt)
11302 org-file-apps-defaults-windowsnt)
11303 (t org-file-apps-defaults-gnu)))
11305 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11306 "Convert extensions to regular expressions in the cars of LIST.
11307 Also, weed out any non-string entries, because the return value is used
11308 only for regexp matching.
11309 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11310 point to the symbol `emacs', indicating that the file should
11311 be opened in Emacs."
11312 (append
11313 (delq nil
11314 (mapcar (lambda (x)
11315 (unless (not (stringp (car x)))
11316 (if (string-match "\\W" (car x))
11318 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11319 list))
11320 (when add-auto-mode
11321 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11323 (defvar ange-ftp-name-format)
11324 (defun org-file-remote-p (file)
11325 "Test whether FILE specifies a location on a remote system.
11326 Return non-nil if the location is indeed remote.
11328 For example, the filename \"/user@host:/foo\" specifies a location
11329 on the system \"/user@host:\"."
11330 (cond ((fboundp 'file-remote-p)
11331 (file-remote-p file))
11332 ((fboundp 'tramp-handle-file-remote-p)
11333 (tramp-handle-file-remote-p file))
11334 ((and (boundp 'ange-ftp-name-format)
11335 (string-match (car ange-ftp-name-format) file))
11336 t)))
11339 ;;;; Refiling
11341 (defun org-get-org-file ()
11342 "Read a filename, with default directory `org-directory'."
11343 (let ((default (or org-default-notes-file remember-data-file)))
11344 (read-file-name (format "File name [%s]: " default)
11345 (file-name-as-directory org-directory)
11346 default)))
11348 (defun org-notes-order-reversed-p ()
11349 "Check if the current file should receive notes in reversed order."
11350 (cond
11351 ((not org-reverse-note-order) nil)
11352 ((eq t org-reverse-note-order) t)
11353 ((not (listp org-reverse-note-order)) nil)
11354 (t (catch 'exit
11355 (dolist (entry org-reverse-note-order)
11356 (when (string-match (car entry) buffer-file-name)
11357 (throw 'exit (cdr entry))))))))
11359 (defvar org-refile-target-table nil
11360 "The list of refile targets, created by `org-refile'.")
11362 (defvar org-agenda-new-buffers nil
11363 "Buffers created to visit agenda files.")
11365 (defvar org-refile-cache nil
11366 "Cache for refile targets.")
11368 (defvar org-refile-markers nil
11369 "All the markers used for caching refile locations.")
11371 (defun org-refile-marker (pos)
11372 "Get a new refile marker, but only if caching is in use."
11373 (if (not org-refile-use-cache)
11375 (let ((m (make-marker)))
11376 (move-marker m pos)
11377 (push m org-refile-markers)
11378 m)))
11380 (defun org-refile-cache-clear ()
11381 "Clear the refile cache and disable all the markers."
11382 (dolist (m org-refile-markers) (move-marker m nil))
11383 (setq org-refile-markers nil)
11384 (setq org-refile-cache nil)
11385 (message "Refile cache has been cleared"))
11387 (defun org-refile-cache-check-set (set)
11388 "Check if all the markers in the cache still have live buffers."
11389 (let (marker)
11390 (catch 'exit
11391 (while (and set (setq marker (nth 3 (pop set))))
11392 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11393 (when (and marker (null (marker-buffer marker)))
11394 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11395 (sit-for 3)
11396 (throw 'exit nil)))
11397 t)))
11399 (defun org-refile-cache-put (set &rest identifiers)
11400 "Push the refile targets SET into the cache, under IDENTIFIERS."
11401 (let* ((key (sha1 (prin1-to-string identifiers)))
11402 (entry (assoc key org-refile-cache)))
11403 (if entry
11404 (setcdr entry set)
11405 (push (cons key set) org-refile-cache))))
11407 (defun org-refile-cache-get (&rest identifiers)
11408 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11409 (cond
11410 ((not org-refile-cache) nil)
11411 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11413 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11414 org-refile-cache))))
11415 (and set (org-refile-cache-check-set set) set)))))
11417 (defvar org-outline-path-cache nil
11418 "Alist between buffer positions and outline paths.
11419 It value is an alist (POSITION . PATH) where POSITION is the
11420 buffer position at the beginning of an entry and PATH is a list
11421 of strings describing the outline path for that entry, in reverse
11422 order.")
11424 (defun org-refile-get-targets (&optional default-buffer)
11425 "Produce a table with refile targets."
11426 (let ((case-fold-search nil)
11427 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11428 (entries (or org-refile-targets '((nil . (:level . 1)))))
11429 targets tgs files desc descre)
11430 (message "Getting targets...")
11431 (with-current-buffer (or default-buffer (current-buffer))
11432 (dolist (entry entries)
11433 (setq files (car entry) desc (cdr entry))
11434 (cond
11435 ((null files) (setq files (list (current-buffer))))
11436 ((eq files 'org-agenda-files)
11437 (setq files (org-agenda-files 'unrestricted)))
11438 ((and (symbolp files) (fboundp files))
11439 (setq files (funcall files)))
11440 ((and (symbolp files) (boundp files))
11441 (setq files (symbol-value files))))
11442 (when (stringp files) (setq files (list files)))
11443 (cond
11444 ((eq (car desc) :tag)
11445 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11446 ((eq (car desc) :todo)
11447 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11448 ((eq (car desc) :regexp)
11449 (setq descre (cdr desc)))
11450 ((eq (car desc) :level)
11451 (setq descre (concat "^\\*\\{" (number-to-string
11452 (if org-odd-levels-only
11453 (1- (* 2 (cdr desc)))
11454 (cdr desc)))
11455 "\\}[ \t]")))
11456 ((eq (car desc) :maxlevel)
11457 (setq descre (concat "^\\*\\{1," (number-to-string
11458 (if org-odd-levels-only
11459 (1- (* 2 (cdr desc)))
11460 (cdr desc)))
11461 "\\}[ \t]")))
11462 (t (error "Bad refiling target description %s" desc)))
11463 (dolist (f files)
11464 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11466 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11467 (progn
11468 (when (bufferp f)
11469 (setq f (buffer-file-name (buffer-base-buffer f))))
11470 (setq f (and f (expand-file-name f)))
11471 (when (eq org-refile-use-outline-path 'file)
11472 (push (list (file-name-nondirectory f) f nil nil) tgs))
11473 (when (eq org-refile-use-outline-path 'buffer-name)
11474 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11475 (when (eq org-refile-use-outline-path 'full-file-path)
11476 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11477 (org-with-wide-buffer
11478 (goto-char (point-min))
11479 (setq org-outline-path-cache nil)
11480 (while (re-search-forward descre nil t)
11481 (beginning-of-line)
11482 (let ((case-fold-search nil))
11483 (looking-at org-complex-heading-regexp))
11484 (let ((begin (point))
11485 (heading (match-string-no-properties 4)))
11486 (unless (or (and
11487 org-refile-target-verify-function
11488 (not
11489 (funcall org-refile-target-verify-function)))
11490 (not heading))
11491 (let ((re (format org-complex-heading-regexp-format
11492 (regexp-quote heading)))
11493 (target
11494 (if (not org-refile-use-outline-path) heading
11495 (mapconcat
11496 #'identity
11497 (append
11498 (pcase org-refile-use-outline-path
11499 (`file (list (file-name-nondirectory
11500 (buffer-file-name
11501 (buffer-base-buffer)))))
11502 (`full-file-path
11503 (list (buffer-file-name
11504 (buffer-base-buffer))))
11505 (`buffer-name
11506 (list (buffer-name
11507 (buffer-base-buffer))))
11508 (_ nil))
11509 (mapcar (lambda (s) (replace-regexp-in-string
11510 "/" "\\/" s nil t))
11511 (org-get-outline-path t t)))
11512 "/"))))
11513 (push (list target f re (org-refile-marker (point)))
11514 tgs)))
11515 (when (= (point) begin)
11516 ;; Verification function has not moved point.
11517 (end-of-line)))))))
11518 (when org-refile-use-cache
11519 (org-refile-cache-put tgs (buffer-file-name) descre))
11520 (setq targets (append tgs targets))))))
11521 (message "Getting targets...done")
11522 (delete-dups (nreverse targets))))
11524 (defun org--get-outline-path-1 (&optional use-cache)
11525 "Return outline path to current headline.
11527 Outline path is a list of strings, in reverse order. When
11528 optional argument USE-CACHE is non-nil, make use of a cache. See
11529 `org-get-outline-path' for details.
11531 Assume buffer is widened and point is on a headline."
11532 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11533 (let ((p (point))
11534 (heading (let ((case-fold-search nil))
11535 (looking-at org-complex-heading-regexp)
11536 (if (not (match-end 4)) ""
11537 ;; Remove statistics cookies.
11538 (org-trim
11539 (org-link-display-format
11540 (replace-regexp-in-string
11541 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11542 (match-string-no-properties 4))))))))
11543 (if (org-up-heading-safe)
11544 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11545 (when use-cache
11546 (push (cons p path) org-outline-path-cache))
11547 path)
11548 ;; This is a new root node. Since we assume we are moving
11549 ;; forward, we can drop previous cache so as to limit number
11550 ;; of associations there.
11551 (let ((path (list heading)))
11552 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11553 path)))))
11555 (defun org-get-outline-path (&optional with-self use-cache)
11556 "Return the outline path to the current entry.
11558 An outline path is a list of ancestors for current headline, as
11559 a list of strings. Statistics cookies are removed and links are
11560 replaced with their description, if any, or their path otherwise.
11562 When optional argument WITH-SELF is non-nil, the path also
11563 includes the current headline.
11565 When optional argument USE-CACHE is non-nil, cache outline paths
11566 between calls to this function so as to avoid backtracking. This
11567 argument is useful when planning to find more than one outline
11568 path in the same document. In that case, there are two
11569 conditions to satisfy:
11570 - `org-outline-path-cache' is set to nil before starting the
11571 process;
11572 - outline paths are computed by increasing buffer positions."
11573 (org-with-wide-buffer
11574 (and (or (and with-self (org-back-to-heading t))
11575 (org-up-heading-safe))
11576 (reverse (org--get-outline-path-1 use-cache)))))
11578 (defun org-format-outline-path (path &optional width prefix separator)
11579 "Format the outline path PATH for display.
11580 WIDTH is the maximum number of characters that is available.
11581 PREFIX is a prefix to be included in the returned string,
11582 such as the file name.
11583 SEPARATOR is inserted between the different parts of the path,
11584 the default is \"/\"."
11585 (setq width (or width 79))
11586 (setq path (delq nil path))
11587 (unless (> width 0)
11588 (user-error "Argument `width' must be positive"))
11589 (setq separator (or separator "/"))
11590 (let* ((org-odd-levels-only nil)
11591 (fpath (concat
11592 prefix (and prefix path separator)
11593 (mapconcat
11594 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11595 (cl-loop for head in path
11596 for n from 0
11597 collect (org-add-props
11598 head nil 'face
11599 (nth (% n org-n-level-faces) org-level-faces)))
11600 separator))))
11601 (when (> (length fpath) width)
11602 (if (< width 7)
11603 ;; It's unlikely that `width' will be this small, but don't
11604 ;; waste characters by adding ".." if it is.
11605 (setq fpath (substring fpath 0 width))
11606 (setf (substring fpath (- width 2)) "..")))
11607 fpath))
11609 (defun org-display-outline-path (&optional file current separator just-return-string)
11610 "Display the current outline path in the echo area.
11612 If FILE is non-nil, prepend the output with the file name.
11613 If CURRENT is non-nil, append the current heading to the output.
11614 SEPARATOR is passed through to `org-format-outline-path'. It separates
11615 the different parts of the path and defaults to \"/\".
11616 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11617 (interactive "P")
11618 (let* (case-fold-search
11619 (bfn (buffer-file-name (buffer-base-buffer)))
11620 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11621 res)
11622 (when current (setq path (append path
11623 (save-excursion
11624 (org-back-to-heading t)
11625 (when (looking-at org-complex-heading-regexp)
11626 (list (match-string 4)))))))
11627 (setq res
11628 (org-format-outline-path
11629 path
11630 (1- (frame-width))
11631 (and file bfn (concat (file-name-nondirectory bfn) separator))
11632 separator))
11633 (if just-return-string
11634 (org-no-properties res)
11635 (org-unlogged-message "%s" res))))
11637 (defvar org-refile-history nil
11638 "History for refiling operations.")
11640 (defvar org-after-refile-insert-hook nil
11641 "Hook run after `org-refile' has inserted its stuff at the new location.
11642 Note that this is still *before* the stuff will be removed from
11643 the *old* location.")
11645 (defvar org-capture-last-stored-marker)
11646 (defvar org-refile-keep nil
11647 "Non-nil means `org-refile' will copy instead of refile.")
11649 (defun org-copy ()
11650 "Like `org-refile', but copy."
11651 (interactive)
11652 (let ((org-refile-keep t))
11653 (funcall 'org-refile nil nil nil "Copy")))
11655 (defun org-refile (&optional arg default-buffer rfloc msg)
11656 "Move the entry or entries at point to another heading.
11658 The list of target headings is compiled using the information in
11659 `org-refile-targets', which see.
11661 At the target location, the entry is filed as a subitem of the
11662 target heading. Depending on `org-reverse-note-order', the new
11663 subitem will either be the first or the last subitem.
11665 If there is an active region, all entries in that region will be
11666 refiled. However, the region must fulfill the requirement that
11667 the first heading sets the top-level of the moved text.
11669 With a `\\[universal-argument]' ARG, the command will only visit the target \
11670 location
11671 and not actually move anything.
11673 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11674 location where the last
11675 refiling operation has put the subtree.
11677 With a numeric prefix argument of `2', refile to the running clock.
11679 With a numeric prefix argument of `3', emulate `org-refile-keep'
11680 being set to t and copy to the target location, don't move it.
11681 Beware that keeping refiled entries may result in duplicated ID
11682 properties.
11684 RFLOC can be a refile location obtained in a different way.
11686 MSG is a string to replace \"Refile\" in the default prompt with
11687 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11689 See also `org-refile-use-outline-path'.
11691 If you are using target caching (see `org-refile-use-cache'), you
11692 have to clear the target cache in order to find new targets.
11693 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11694 prefix argument (`C-u C-u C-u C-c C-w')."
11695 (interactive "P")
11696 (if (member arg '(0 (64)))
11697 (org-refile-cache-clear)
11698 (let* ((actionmsg (cond (msg msg)
11699 ((equal arg 3) "Refile (and keep)")
11700 (t "Refile")))
11701 (regionp (org-region-active-p))
11702 (region-start (and regionp (region-beginning)))
11703 (region-end (and regionp (region-end)))
11704 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11705 pos it nbuf file level reversed)
11706 (setq last-command nil)
11707 (when regionp
11708 (goto-char region-start)
11709 (or (bolp) (goto-char (point-at-bol)))
11710 (setq region-start (point))
11711 (unless (or (org-kill-is-subtree-p
11712 (buffer-substring region-start region-end))
11713 (prog1 org-refile-active-region-within-subtree
11714 (let ((s (point-at-eol)))
11715 (org-toggle-heading)
11716 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11717 (user-error "The region is not a (sequence of) subtree(s)")))
11718 (if (equal arg '(16))
11719 (org-refile-goto-last-stored)
11720 (when (or
11721 (and (equal arg 2)
11722 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11723 (prog1
11724 (setq it (list (or org-clock-heading "running clock")
11725 (buffer-file-name
11726 (marker-buffer org-clock-hd-marker))
11728 (marker-position org-clock-hd-marker)))
11729 (setq arg nil)))
11730 (setq it
11731 (or rfloc
11732 (let (heading-text)
11733 (save-excursion
11734 (unless (and arg (listp arg))
11735 (org-back-to-heading t)
11736 (setq heading-text
11737 (replace-regexp-in-string
11738 org-bracket-link-regexp
11739 "\\3"
11740 (or (nth 4 (org-heading-components))
11741 ""))))
11742 (org-refile-get-location
11743 (cond ((and arg (listp arg)) "Goto")
11744 (regionp (concat actionmsg " region to"))
11745 (t (concat actionmsg " subtree \""
11746 heading-text "\" to")))
11747 default-buffer
11748 (and (not (equal '(4) arg))
11749 org-refile-allow-creating-parent-nodes)))))))
11750 (setq file (nth 1 it)
11751 pos (nth 3 it))
11752 (when (and (not arg)
11754 (equal (buffer-file-name) file)
11755 (if regionp
11756 (and (>= pos region-start)
11757 (<= pos region-end))
11758 (and (>= pos (point))
11759 (< pos (save-excursion
11760 (org-end-of-subtree t t))))))
11761 (error "Cannot refile to position inside the tree or region"))
11762 (setq nbuf (or (find-buffer-visiting file)
11763 (find-file-noselect file)))
11764 (if (and arg (not (equal arg 3)))
11765 (progn
11766 (pop-to-buffer-same-window nbuf)
11767 (goto-char (cond (pos)
11768 ((org-notes-order-reversed-p) (point-min))
11769 (t (point-max))))
11770 (org-show-context 'org-goto))
11771 (if regionp
11772 (progn
11773 (org-kill-new (buffer-substring region-start region-end))
11774 (org-save-markers-in-region region-start region-end))
11775 (org-copy-subtree 1 nil t))
11776 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11777 (find-file-noselect file)))
11778 (setq reversed (org-notes-order-reversed-p))
11779 (org-with-wide-buffer
11780 (if pos
11781 (progn
11782 (goto-char pos)
11783 (setq level (org-get-valid-level (funcall outline-level) 1))
11784 (goto-char
11785 (if reversed
11786 (or (outline-next-heading) (point-max))
11787 (or (save-excursion (org-get-next-sibling))
11788 (org-end-of-subtree t t)
11789 (point-max)))))
11790 (setq level 1)
11791 (if (not reversed)
11792 (goto-char (point-max))
11793 (goto-char (point-min))
11794 (or (outline-next-heading) (goto-char (point-max)))))
11795 (unless (bolp) (newline))
11796 (org-paste-subtree level nil nil t)
11797 (when org-log-refile
11798 (org-add-log-setup 'refile nil nil org-log-refile)
11799 (unless (eq org-log-refile 'note)
11800 (save-excursion (org-add-log-note))))
11801 (and org-auto-align-tags
11802 (let ((org-loop-over-headlines-in-active-region nil))
11803 (org-set-tags nil t)))
11804 (let ((bookmark-name (plist-get org-bookmark-names-plist
11805 :last-refile)))
11806 (when bookmark-name
11807 (with-demoted-errors
11808 (bookmark-set bookmark-name))))
11809 ;; If we are refiling for capture, make sure that the
11810 ;; last-capture pointers point here
11811 (when (bound-and-true-p org-capture-is-refiling)
11812 (let ((bookmark-name (plist-get org-bookmark-names-plist
11813 :last-capture-marker)))
11814 (when bookmark-name
11815 (with-demoted-errors
11816 (bookmark-set bookmark-name))))
11817 (move-marker org-capture-last-stored-marker (point)))
11818 (when (fboundp 'deactivate-mark) (deactivate-mark))
11819 (run-hooks 'org-after-refile-insert-hook)))
11820 (unless org-refile-keep
11821 (if regionp
11822 (delete-region (point) (+ (point) (- region-end region-start)))
11823 (delete-region
11824 (and (org-back-to-heading t) (point))
11825 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11826 (when (featurep 'org-inlinetask)
11827 (org-inlinetask-remove-END-maybe))
11828 (setq org-markers-to-move nil)
11829 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11831 (defun org-refile-goto-last-stored ()
11832 "Go to the location where the last refile was stored."
11833 (interactive)
11834 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11835 (message "This is the location of the last refile"))
11837 (defun org-refile--get-location (refloc tbl)
11838 "When user refile to REFLOC, find the associated target in TBL.
11839 Also check `org-refile-target-table'."
11840 (car (delq
11842 (mapcar
11843 (lambda (r) (or (assoc r tbl)
11844 (assoc r org-refile-target-table)))
11845 (list (replace-regexp-in-string "/$" "" refloc)
11846 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11848 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11849 "Prompt the user for a refile location, using PROMPT.
11850 PROMPT should not be suffixed with a colon and a space, because
11851 this function appends the default value from
11852 `org-refile-history' automatically, if that is not empty."
11853 (let ((org-refile-targets org-refile-targets)
11854 (org-refile-use-outline-path org-refile-use-outline-path))
11855 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11856 (unless org-refile-target-table
11857 (user-error "No refile targets"))
11858 (let* ((cbuf (current-buffer))
11859 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11860 (cfunc (if (and org-refile-use-outline-path
11861 org-outline-path-complete-in-steps)
11862 #'org-olpath-completing-read
11863 #'completing-read))
11864 (extra (if org-refile-use-outline-path "/" ""))
11865 (cbnex (concat (buffer-name) extra))
11866 (filename (and cfn (expand-file-name cfn)))
11867 (tbl (mapcar
11868 (lambda (x)
11869 (if (and (not (member org-refile-use-outline-path
11870 '(file full-file-path)))
11871 (not (equal filename (nth 1 x))))
11872 (cons (concat (car x) extra " ("
11873 (file-name-nondirectory (nth 1 x)) ")")
11874 (cdr x))
11875 (cons (concat (car x) extra) (cdr x))))
11876 org-refile-target-table))
11877 (completion-ignore-case t)
11878 cdef
11879 (prompt (concat prompt
11880 (or (and (car org-refile-history)
11881 (concat " (default " (car org-refile-history) ")"))
11882 (and (assoc cbnex tbl) (setq cdef cbnex)
11883 (concat " (default " cbnex ")"))) ": "))
11884 pa answ parent-target child parent old-hist)
11885 (setq old-hist org-refile-history)
11886 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11887 nil 'org-refile-history (or cdef (car org-refile-history))))
11888 (if (setq pa (org-refile--get-location answ tbl))
11889 (progn
11890 (org-refile-check-position pa)
11891 (when (or (not org-refile-history)
11892 (not (eq old-hist org-refile-history))
11893 (not (equal (car pa) (car org-refile-history))))
11894 (setq org-refile-history
11895 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11896 org-refile-history
11897 (cdr org-refile-history))))
11898 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11899 (pop org-refile-history)))
11901 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11902 (progn
11903 (setq parent (match-string 1 answ)
11904 child (match-string 2 answ))
11905 (setq parent-target (org-refile--get-location parent tbl))
11906 (when (and parent-target
11907 (or (eq new-nodes t)
11908 (and (eq new-nodes 'confirm)
11909 (y-or-n-p (format "Create new node \"%s\"? "
11910 child)))))
11911 (org-refile-new-child parent-target child)))
11912 (user-error "Invalid target location")))))
11914 (declare-function org-string-nw-p "org-macs" (s))
11915 (defun org-refile-check-position (refile-pointer)
11916 "Check if the refile pointer matches the headline to which it points."
11917 (let* ((file (nth 1 refile-pointer))
11918 (re (nth 2 refile-pointer))
11919 (pos (nth 3 refile-pointer))
11920 buffer)
11921 (if (and (not (markerp pos)) (not file))
11922 (user-error "Please indicate a target file in the refile path")
11923 (when (org-string-nw-p re)
11924 (setq buffer (if (markerp pos)
11925 (marker-buffer pos)
11926 (or (find-buffer-visiting file)
11927 (find-file-noselect file))))
11928 (with-current-buffer buffer
11929 (org-with-wide-buffer
11930 (goto-char pos)
11931 (beginning-of-line 1)
11932 (unless (looking-at-p re)
11933 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11935 (defun org-refile-new-child (parent-target child)
11936 "Use refile target PARENT-TARGET to add new CHILD below it."
11937 (unless parent-target
11938 (error "Cannot find parent for new node"))
11939 (let ((file (nth 1 parent-target))
11940 (pos (nth 3 parent-target))
11941 level)
11942 (with-current-buffer (or (find-buffer-visiting file)
11943 (find-file-noselect file))
11944 (org-with-wide-buffer
11945 (if pos
11946 (goto-char pos)
11947 (goto-char (point-max))
11948 (unless (bolp) (newline)))
11949 (when (looking-at org-outline-regexp)
11950 (setq level (funcall outline-level))
11951 (org-end-of-subtree t t))
11952 (org-back-over-empty-lines)
11953 (insert "\n" (make-string
11954 (if pos (org-get-valid-level level 1) 1) ?*)
11955 " " child "\n")
11956 (beginning-of-line 0)
11957 (list (concat (car parent-target) "/" child) file "" (point))))))
11959 (defun org-olpath-completing-read (prompt collection &rest args)
11960 "Read an outline path like a file name."
11961 (let ((thetable collection))
11962 (apply #'completing-read
11963 prompt
11964 (lambda (string predicate &optional flag)
11965 (cond
11966 ((eq flag nil) (try-completion string thetable))
11967 ((eq flag t)
11968 (let ((l (length string)))
11969 (mapcar (lambda (x)
11970 (let ((r (substring x l))
11971 (f (if (string-match " ([^)]*)$" x)
11972 (match-string 0 x)
11973 "")))
11974 (if (string-match "/" r)
11975 (concat string (substring r 0 (match-end 0)) f)
11976 x)))
11977 (all-completions string thetable predicate))))
11978 ;; Exact match?
11979 ((eq flag 'lambda) (assoc string thetable))))
11980 args)))
11982 ;;;; Dynamic blocks
11984 (defun org-find-dblock (name)
11985 "Find the first dynamic block with name NAME in the buffer.
11986 If not found, stay at current position and return nil."
11987 (let ((case-fold-search t) pos)
11988 (save-excursion
11989 (goto-char (point-min))
11990 (setq pos (and (re-search-forward
11991 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11992 (match-beginning 0))))
11993 (when pos (goto-char pos))
11994 pos))
11996 (defun org-create-dblock (plist)
11997 "Create a dynamic block section, with parameters taken from PLIST.
11998 PLIST must contain a :name entry which is used as the name of the block."
11999 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12000 (end-of-line 1)
12001 (newline))
12002 (let ((col (current-column))
12003 (name (plist-get plist :name)))
12004 (insert "#+BEGIN: " name)
12005 (while plist
12006 (if (eq (car plist) :name)
12007 (setq plist (cddr plist))
12008 (insert " " (prin1-to-string (pop plist)))))
12009 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12010 (beginning-of-line -2)))
12012 (defun org-prepare-dblock ()
12013 "Prepare dynamic block for refresh.
12014 This empties the block, puts the cursor at the insert position and returns
12015 the property list including an extra property :name with the block name."
12016 (unless (looking-at org-dblock-start-re)
12017 (user-error "Not at a dynamic block"))
12018 (let* ((begdel (1+ (match-end 0)))
12019 (name (org-no-properties (match-string 1)))
12020 (params (append (list :name name)
12021 (read (concat "(" (match-string 3) ")")))))
12022 (save-excursion
12023 (beginning-of-line 1)
12024 (skip-chars-forward " \t")
12025 (setq params (plist-put params :indentation-column (current-column))))
12026 (unless (re-search-forward org-dblock-end-re nil t)
12027 (error "Dynamic block not terminated"))
12028 (setq params
12029 (append params
12030 (list :content (buffer-substring
12031 begdel (match-beginning 0)))))
12032 (delete-region begdel (match-beginning 0))
12033 (goto-char begdel)
12034 (open-line 1)
12035 params))
12037 (defun org-map-dblocks (&optional command)
12038 "Apply COMMAND to all dynamic blocks in the current buffer.
12039 If COMMAND is not given, use `org-update-dblock'."
12040 (let ((cmd (or command 'org-update-dblock)))
12041 (save-excursion
12042 (goto-char (point-min))
12043 (while (re-search-forward org-dblock-start-re nil t)
12044 (goto-char (match-beginning 0))
12045 (save-excursion
12046 (condition-case nil
12047 (funcall cmd)
12048 (error (message "Error during update of dynamic block"))))
12049 (unless (re-search-forward org-dblock-end-re nil t)
12050 (error "Dynamic block not terminated"))))))
12052 (defun org-dblock-update (&optional arg)
12053 "User command for updating dynamic blocks.
12054 Update the dynamic block at point. With prefix ARG, update all dynamic
12055 blocks in the buffer."
12056 (interactive "P")
12057 (if arg
12058 (org-update-all-dblocks)
12059 (or (looking-at org-dblock-start-re)
12060 (org-beginning-of-dblock))
12061 (org-update-dblock)))
12063 (defun org-update-dblock ()
12064 "Update the dynamic block at point.
12065 This means to empty the block, parse for parameters and then call
12066 the correct writing function."
12067 (interactive)
12068 (save-excursion
12069 (let* ((win (selected-window))
12070 (pos (point))
12071 (line (org-current-line))
12072 (params (org-prepare-dblock))
12073 (name (plist-get params :name))
12074 (indent (plist-get params :indentation-column))
12075 (cmd (intern (concat "org-dblock-write:" name))))
12076 (message "Updating dynamic block `%s' at line %d..." name line)
12077 (funcall cmd params)
12078 (message "Updating dynamic block `%s' at line %d...done" name line)
12079 (goto-char pos)
12080 (when (and indent (> indent 0))
12081 (setq indent (make-string indent ?\ ))
12082 (save-excursion
12083 (select-window win)
12084 (org-beginning-of-dblock)
12085 (forward-line 1)
12086 (while (not (looking-at org-dblock-end-re))
12087 (insert indent)
12088 (beginning-of-line 2))
12089 (when (looking-at org-dblock-end-re)
12090 (and (looking-at "[ \t]+")
12091 (replace-match ""))
12092 (insert indent)))))))
12094 (defun org-beginning-of-dblock ()
12095 "Find the beginning of the dynamic block at point.
12096 Error if there is no such block at point."
12097 (let ((pos (point))
12098 beg)
12099 (end-of-line 1)
12100 (if (and (re-search-backward org-dblock-start-re nil t)
12101 (setq beg (match-beginning 0))
12102 (re-search-forward org-dblock-end-re nil t)
12103 (> (match-end 0) pos))
12104 (goto-char beg)
12105 (goto-char pos)
12106 (error "Not in a dynamic block"))))
12108 (defun org-update-all-dblocks ()
12109 "Update all dynamic blocks in the buffer.
12110 This function can be used in a hook."
12111 (interactive)
12112 (when (derived-mode-p 'org-mode)
12113 (org-map-dblocks 'org-update-dblock)))
12116 ;;;; Completion
12118 (declare-function org-export-backend-options "ox" (cl-x) t)
12119 (defun org-get-export-keywords ()
12120 "Return a list of all currently understood export keywords.
12121 Export keywords include options, block names, attributes and
12122 keywords relative to each registered export back-end."
12123 (let (keywords)
12124 (dolist (backend
12125 (bound-and-true-p org-export-registered-backends)
12126 (delq nil keywords))
12127 ;; Back-end name (for keywords, like #+LATEX:)
12128 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12129 (dolist (option-entry (org-export-backend-options backend))
12130 ;; Back-end options.
12131 (push (nth 1 option-entry) keywords)))))
12133 (defconst org-options-keywords
12134 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12135 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12136 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12137 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12138 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12140 (defcustom org-structure-template-alist
12141 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12142 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12143 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12144 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12145 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12146 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12147 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12148 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12149 ("L" "#+LaTeX: ")
12150 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12151 ("H" "#+HTML: ")
12152 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12153 ("A" "#+ASCII: ")
12154 ("i" "#+INDEX: ?")
12155 ("I" "#+INCLUDE: %file ?"))
12156 "Structure completion elements.
12157 This is a list of abbreviation keys and values. The value gets inserted
12158 if you type `<' followed by the key and then press the completion key,
12159 usually `TAB'. %file will be replaced by a file name after prompting
12160 for the file using completion. The cursor will be placed at the position
12161 of the `?' in the template.
12162 There are two templates for each key, the first uses the original Org syntax,
12163 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12164 the default when the /org-mtags.el/ module has been loaded. See also the
12165 variable `org-mtags-prefer-muse-templates'."
12166 :group 'org-completion
12167 :type '(repeat
12168 (list
12169 (string :tag "Key")
12170 (string :tag "Template")))
12171 :version "26.1"
12172 :package-version '(Org . "8.3"))
12174 (defun org-try-structure-completion ()
12175 "Try to complete a structure template before point.
12176 This looks for strings like \"<e\" on an otherwise empty line and
12177 expands them."
12178 (let ((l (buffer-substring (point-at-bol) (point)))
12180 (when (and (looking-at "[ \t]*$")
12181 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12182 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12183 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12184 (match-beginning 1)) a)
12185 t)))
12187 (defun org-complete-expand-structure-template (start cell)
12188 "Expand a structure template."
12189 (let ((rpl (nth 1 cell))
12190 (ind ""))
12191 (delete-region start (point))
12192 (when (string-match "\\`[ \t]*#\\+" rpl)
12193 (cond
12194 ((bolp))
12195 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12196 (setq ind (buffer-substring (point-at-bol) (point))))
12197 (t (newline))))
12198 (setq start (point))
12199 (when (string-match "%file" rpl)
12200 (setq rpl (replace-match
12201 (concat
12202 "\""
12203 (save-match-data
12204 (abbreviate-file-name (read-file-name "Include file: ")))
12205 "\"")
12206 t t rpl)))
12207 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12208 (concat "\n" ind)))
12209 (insert rpl)
12210 (when (re-search-backward "\\?" start t) (delete-char 1))))
12212 ;;;; TODO, DEADLINE, Comments
12214 (defun org-toggle-comment ()
12215 "Change the COMMENT state of an entry."
12216 (interactive)
12217 (save-excursion
12218 (org-back-to-heading)
12219 (let ((case-fold-search nil))
12220 (looking-at org-complex-heading-regexp))
12221 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12222 (skip-chars-forward " \t")
12223 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12224 (if (org-in-commented-heading-p t)
12225 (delete-region (point)
12226 (progn (search-forward " " (line-end-position) 'move)
12227 (skip-chars-forward " \t")
12228 (point)))
12229 (insert org-comment-string)
12230 (unless (eolp) (insert " ")))))
12232 (defvar org-last-todo-state-is-todo nil
12233 "This is non-nil when the last TODO state change led to a TODO state.
12234 If the last change removed the TODO tag or switched to DONE, then
12235 this is nil.")
12237 (defvar org-setting-tags nil) ; dynamically skipped
12239 (defvar org-todo-setup-filter-hook nil
12240 "Hook for functions that pre-filter todo specs.
12241 Each function takes a todo spec and returns either nil or the spec
12242 transformed into canonical form." )
12244 (defvar org-todo-get-default-hook nil
12245 "Hook for functions that get a default item for todo.
12246 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12247 nil or a string to be used for the todo mark." )
12249 (defvar org-agenda-headline-snapshot-before-repeat)
12251 (defun org-current-effective-time ()
12252 "Return current time adjusted for `org-extend-today-until' variable."
12253 (let* ((ct (org-current-time))
12254 (dct (decode-time ct))
12255 (ct1
12256 (cond
12257 (org-use-last-clock-out-time-as-effective-time
12258 (or (org-clock-get-last-clock-out-time) ct))
12259 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12260 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12261 (t ct))))
12262 ct1))
12264 (defun org-todo-yesterday (&optional arg)
12265 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12266 (interactive "P")
12267 (if (eq major-mode 'org-agenda-mode)
12268 (apply 'org-agenda-todo-yesterday arg)
12269 (let* ((org-use-effective-time t)
12270 (hour (nth 2 (decode-time (org-current-time))))
12271 (org-extend-today-until (1+ hour)))
12272 (org-todo arg))))
12274 (defvar org-block-entry-blocking ""
12275 "First entry preventing the TODO state change.")
12277 (defun org-cancel-repeater ()
12278 "Cancel a repeater by setting its numeric value to zero."
12279 (interactive)
12280 (save-excursion
12281 (org-back-to-heading t)
12282 (let ((bound1 (point))
12283 (bound0 (save-excursion (outline-next-heading) (point))))
12284 (when (and (re-search-forward
12285 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12286 org-deadline-time-regexp "\\)\\|\\("
12287 org-ts-regexp "\\)")
12288 bound0 t)
12289 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12290 bound1 t))
12291 (replace-match "0" t nil nil 1)))))
12293 (defvar org-state)
12294 (defvar org-blocked-by-checkboxes)
12295 (defun org-todo (&optional arg)
12296 "Change the TODO state of an item.
12298 The state of an item is given by a keyword at the start of the heading,
12299 like
12300 *** TODO Write paper
12301 *** DONE Call mom
12303 The different keywords are specified in the variable `org-todo-keywords'.
12304 By default the available states are \"TODO\" and \"DONE\". So, for this
12305 example: when the item starts with TODO, it is changed to DONE.
12306 When it starts with DONE, the DONE is removed. And when neither TODO nor
12307 DONE are present, add TODO at the beginning of the heading.
12309 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12310 state.
12311 With numeric prefix ARG, switch to that state.
12312 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12313 next set of TODO \
12314 keywords (nextset).
12315 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12316 prefix, circumvent any state blocking.
12317 With a numeric prefix arg of 0, inhibit note taking for the change.
12318 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12320 When called through ELisp, arg is also interpreted in the following way:
12321 `none' -> empty state
12322 \"\" -> switch to empty state
12323 `done' -> switch to DONE
12324 `nextset' -> switch to the next set of keywords
12325 `previousset' -> switch to the previous set of keywords
12326 \"WAITING\" -> switch to the specified keyword, but only if it
12327 really is a member of `org-todo-keywords'."
12328 (interactive "P")
12329 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12330 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12331 'region-start-level 'region))
12332 org-loop-over-headlines-in-active-region)
12333 (org-map-entries
12334 `(org-todo ,arg)
12335 org-loop-over-headlines-in-active-region
12336 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12337 (when (equal arg '(16)) (setq arg 'nextset))
12338 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12339 (let ((org-blocker-hook org-blocker-hook)
12340 commentp
12341 case-fold-search)
12342 (when (equal arg '(64))
12343 (setq arg nil org-blocker-hook nil))
12344 (when (and org-blocker-hook
12345 (or org-inhibit-blocking
12346 (org-entry-get nil "NOBLOCKING")))
12347 (setq org-blocker-hook nil))
12348 (save-excursion
12349 (catch 'exit
12350 (org-back-to-heading t)
12351 (when (org-in-commented-heading-p t)
12352 (org-toggle-comment)
12353 (setq commentp t))
12354 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12355 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12356 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12357 (let* ((match-data (match-data))
12358 (startpos (point-at-bol))
12359 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12360 (org-log-done org-log-done)
12361 (org-log-repeat org-log-repeat)
12362 (org-todo-log-states org-todo-log-states)
12363 (org-inhibit-logging
12364 (if (equal arg 0)
12365 (progn (setq arg nil) 'note) org-inhibit-logging))
12366 (this (match-string 1))
12367 (hl-pos (match-beginning 0))
12368 (head (org-get-todo-sequence-head this))
12369 (ass (assoc head org-todo-kwd-alist))
12370 (interpret (nth 1 ass))
12371 (done-word (nth 3 ass))
12372 (final-done-word (nth 4 ass))
12373 (org-last-state (or this ""))
12374 (completion-ignore-case t)
12375 (member (member this org-todo-keywords-1))
12376 (tail (cdr member))
12377 (org-state (cond
12378 ((and org-todo-key-trigger
12379 (or (and (equal arg '(4))
12380 (eq org-use-fast-todo-selection 'prefix))
12381 (and (not arg) org-use-fast-todo-selection
12382 (not (eq org-use-fast-todo-selection
12383 'prefix)))))
12384 ;; Use fast selection.
12385 (org-fast-todo-selection))
12386 ((and (equal arg '(4))
12387 (or (not org-use-fast-todo-selection)
12388 (not org-todo-key-trigger)))
12389 ;; Read a state with completion.
12390 (completing-read
12391 "State: " (mapcar #'list org-todo-keywords-1)
12392 nil t))
12393 ((eq arg 'right)
12394 (if this
12395 (if tail (car tail) nil)
12396 (car org-todo-keywords-1)))
12397 ((eq arg 'left)
12398 (unless (equal member org-todo-keywords-1)
12399 (if this
12400 (nth (- (length org-todo-keywords-1)
12401 (length tail) 2)
12402 org-todo-keywords-1)
12403 (org-last org-todo-keywords-1))))
12404 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12405 (setq arg nil))) ;hack to fall back to cycling
12406 (arg
12407 ;; User or caller requests a specific state.
12408 (cond
12409 ((equal arg "") nil)
12410 ((eq arg 'none) nil)
12411 ((eq arg 'done) (or done-word (car org-done-keywords)))
12412 ((eq arg 'nextset)
12413 (or (car (cdr (member head org-todo-heads)))
12414 (car org-todo-heads)))
12415 ((eq arg 'previousset)
12416 (let ((org-todo-heads (reverse org-todo-heads)))
12417 (or (car (cdr (member head org-todo-heads)))
12418 (car org-todo-heads))))
12419 ((car (member arg org-todo-keywords-1)))
12420 ((stringp arg)
12421 (user-error "State `%s' not valid in this file" arg))
12422 ((nth (1- (prefix-numeric-value arg))
12423 org-todo-keywords-1))))
12424 ((null member) (or head (car org-todo-keywords-1)))
12425 ((equal this final-done-word) nil) ;-> make empty
12426 ((null tail) nil) ;-> first entry
12427 ((memq interpret '(type priority))
12428 (if (eq this-command last-command)
12429 (car tail)
12430 (if (> (length tail) 0)
12431 (or done-word (car org-done-keywords))
12432 nil)))
12434 (car tail))))
12435 (org-state (or
12436 (run-hook-with-args-until-success
12437 'org-todo-get-default-hook org-state org-last-state)
12438 org-state))
12439 (next (if org-state (concat " " org-state " ") " "))
12440 (change-plist (list :type 'todo-state-change :from this :to org-state
12441 :position startpos))
12442 dolog now-done-p)
12443 (when org-blocker-hook
12444 (let (org-blocked-by-checkboxes block-reason)
12445 (setq org-last-todo-state-is-todo
12446 (not (member this org-done-keywords)))
12447 (unless (save-excursion
12448 (save-match-data
12449 (org-with-wide-buffer
12450 (run-hook-with-args-until-failure
12451 'org-blocker-hook change-plist))))
12452 (setq block-reason (if org-blocked-by-checkboxes
12453 "contained checkboxes"
12454 (format "\"%s\"" org-block-entry-blocking)))
12455 (if (called-interactively-p 'interactive)
12456 (user-error "TODO state change from %s to %s blocked (by %s)"
12457 this org-state block-reason)
12458 ;; Fail silently.
12459 (message "TODO state change from %s to %s blocked (by %s)"
12460 this org-state block-reason)
12461 (throw 'exit nil)))))
12462 (store-match-data match-data)
12463 (replace-match next t t)
12464 (cond ((equal this org-state)
12465 (message "TODO state was already %s" (org-trim next)))
12466 ((not (pos-visible-in-window-p hl-pos))
12467 (message "TODO state changed to %s" (org-trim next))))
12468 (unless head
12469 (setq head (org-get-todo-sequence-head org-state)
12470 ass (assoc head org-todo-kwd-alist)
12471 interpret (nth 1 ass)
12472 done-word (nth 3 ass)
12473 final-done-word (nth 4 ass)))
12474 (when (memq arg '(nextset previousset))
12475 (message "Keyword-Set %d/%d: %s"
12476 (- (length org-todo-sets) -1
12477 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12478 (length org-todo-sets)
12479 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12480 (setq org-last-todo-state-is-todo
12481 (not (member org-state org-done-keywords)))
12482 (setq now-done-p (and (member org-state org-done-keywords)
12483 (not (member this org-done-keywords))))
12484 (and logging (org-local-logging logging))
12485 (when (and (or org-todo-log-states org-log-done)
12486 (not (eq org-inhibit-logging t))
12487 (not (memq arg '(nextset previousset))))
12488 ;; We need to look at recording a time and note.
12489 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12490 (nth 2 (assoc this org-todo-log-states))))
12491 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12492 (setq dolog 'time))
12493 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12494 (and org-state
12495 (member org-state org-not-done-keywords)
12496 (not (member this org-not-done-keywords))))
12497 ;; This is now a todo state and was not one before
12498 ;; If there was a CLOSED time stamp, get rid of it.
12499 (org-add-planning-info nil nil 'closed))
12500 (when (and now-done-p org-log-done)
12501 ;; It is now done, and it was not done before.
12502 (org-add-planning-info 'closed (org-current-effective-time))
12503 (when (and (not dolog) (eq 'note org-log-done))
12504 (org-add-log-setup 'done org-state this 'note)))
12505 (when (and org-state dolog)
12506 ;; This is a non-nil state, and we need to log it.
12507 (org-add-log-setup 'state org-state this dolog)))
12508 ;; Fixup tag positioning.
12509 (org-todo-trigger-tag-changes org-state)
12510 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12511 (when org-provide-todo-statistics
12512 (org-update-parent-todo-statistics))
12513 (run-hooks 'org-after-todo-state-change-hook)
12514 (when (and arg (not (member org-state org-done-keywords)))
12515 (setq head (org-get-todo-sequence-head org-state)))
12516 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12517 ;; Do we need to trigger a repeat?
12518 (when now-done-p
12519 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12520 ;; This is for the agenda, take a snapshot of the headline.
12521 (save-match-data
12522 (setq org-agenda-headline-snapshot-before-repeat
12523 (org-get-heading))))
12524 (org-auto-repeat-maybe org-state))
12525 ;; Fixup cursor location if close to the keyword.
12526 (when (and (outline-on-heading-p)
12527 (not (bolp))
12528 (save-excursion (beginning-of-line 1)
12529 (looking-at org-todo-line-regexp))
12530 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12531 (goto-char (or (match-end 2) (match-end 1)))
12532 (and (looking-at " ") (just-one-space)))
12533 (when org-trigger-hook
12534 (save-excursion
12535 (run-hook-with-args 'org-trigger-hook change-plist)))
12536 (when commentp (org-toggle-comment))))))))
12538 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12539 "Block turning an entry into a TODO, using the hierarchy.
12540 This checks whether the current task should be blocked from state
12541 changes. Such blocking occurs when:
12543 1. The task has children which are not all in a completed state.
12545 2. A task has a parent with the property :ORDERED:, and there
12546 are siblings prior to the current task with incomplete
12547 status.
12549 3. The parent of the task is blocked because it has siblings that should
12550 be done first, or is child of a block grandparent TODO entry."
12552 (if (not org-enforce-todo-dependencies)
12553 t ; if locally turned off don't block
12554 (catch 'dont-block
12555 ;; If this is not a todo state change, or if this entry is already DONE,
12556 ;; do not block
12557 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12558 (member (plist-get change-plist :from)
12559 (cons 'done org-done-keywords))
12560 (member (plist-get change-plist :to)
12561 (cons 'todo org-not-done-keywords))
12562 (not (plist-get change-plist :to)))
12563 (throw 'dont-block t))
12564 ;; If this task has children, and any are undone, it's blocked
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (let ((this-level (funcall outline-level)))
12568 (outline-next-heading)
12569 (let ((child-level (funcall outline-level)))
12570 (while (and (not (eobp))
12571 (> child-level this-level))
12572 ;; this todo has children, check whether they are all
12573 ;; completed
12574 (when (and (not (org-entry-is-done-p))
12575 (org-entry-is-todo-p))
12576 (setq org-block-entry-blocking (org-get-heading))
12577 (throw 'dont-block nil))
12578 (outline-next-heading)
12579 (setq child-level (funcall outline-level))))))
12580 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12581 ;; any previous siblings are undone, it's blocked
12582 (save-excursion
12583 (org-back-to-heading t)
12584 (let* ((pos (point))
12585 (parent-pos (and (org-up-heading-safe) (point)))
12586 (case-fold-search nil))
12587 (unless parent-pos (throw 'dont-block t)) ; no parent
12588 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12589 (forward-line 1)
12590 (re-search-forward org-not-done-heading-regexp pos t))
12591 (setq org-block-entry-blocking (match-string 0))
12592 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12593 ;; Search further up the hierarchy, to see if an ancestor is blocked
12594 (while t
12595 (goto-char parent-pos)
12596 (unless (looking-at org-not-done-heading-regexp)
12597 (throw 'dont-block t)) ; do not block, parent is not a TODO
12598 (setq pos (point))
12599 (setq parent-pos (and (org-up-heading-safe) (point)))
12600 (unless parent-pos (throw 'dont-block t)) ; no parent
12601 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12602 (forward-line 1)
12603 (re-search-forward org-not-done-heading-regexp pos t)
12604 (setq org-block-entry-blocking (org-get-heading)))
12605 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12607 (defcustom org-track-ordered-property-with-tag nil
12608 "Should the ORDERED property also be shown as a tag?
12609 The ORDERED property decides if an entry should require subtasks to be
12610 completed in sequence. Since a property is not very visible, setting
12611 this option means that toggling the ORDERED property with the command
12612 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12613 not relevant for the behavior, but it makes things more visible.
12615 Note that toggling the tag with tags commands will not change the property
12616 and therefore not influence behavior!
12618 This can be t, meaning the tag ORDERED should be used, It can also be a
12619 string to select a different tag for this task."
12620 :group 'org-todo
12621 :type '(choice
12622 (const :tag "No tracking" nil)
12623 (const :tag "Track with ORDERED tag" t)
12624 (string :tag "Use other tag")))
12626 (defun org-toggle-ordered-property ()
12627 "Toggle the ORDERED property of the current entry.
12628 For better visibility, you can track the value of this property with a tag.
12629 See variable `org-track-ordered-property-with-tag'."
12630 (interactive)
12631 (let* ((t1 org-track-ordered-property-with-tag)
12632 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12633 (save-excursion
12634 (org-back-to-heading)
12635 (if (org-entry-get nil "ORDERED")
12636 (progn
12637 (org-delete-property "ORDERED")
12638 (and tag (org-toggle-tag tag 'off))
12639 (message "Subtasks can be completed in arbitrary order"))
12640 (org-entry-put nil "ORDERED" "t")
12641 (and tag (org-toggle-tag tag 'on))
12642 (message "Subtasks must be completed in sequence")))))
12644 (defun org-block-todo-from-checkboxes (change-plist)
12645 "Block turning an entry into a TODO, using checkboxes.
12646 This checks whether the current task should be blocked from state
12647 changes because there are unchecked boxes in this entry."
12648 (if (not org-enforce-todo-checkbox-dependencies)
12649 t ; if locally turned off don't block
12650 (catch 'dont-block
12651 ;; If this is not a todo state change, or if this entry is already DONE,
12652 ;; do not block
12653 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12654 (member (plist-get change-plist :from)
12655 (cons 'done org-done-keywords))
12656 (member (plist-get change-plist :to)
12657 (cons 'todo org-not-done-keywords))
12658 (not (plist-get change-plist :to)))
12659 (throw 'dont-block t))
12660 ;; If this task has checkboxes that are not checked, it's blocked
12661 (save-excursion
12662 (org-back-to-heading t)
12663 (let ((beg (point)) end)
12664 (outline-next-heading)
12665 (setq end (point))
12666 (goto-char beg)
12667 (when (org-list-search-forward
12668 (concat (org-item-beginning-re)
12669 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12670 "\\[[- ]\\]")
12671 end t)
12672 (when (boundp 'org-blocked-by-checkboxes)
12673 (setq org-blocked-by-checkboxes t))
12674 (throw 'dont-block nil))))
12675 t))) ; do not block
12677 (defun org-entry-blocked-p ()
12678 "Non-nil if entry at point is blocked."
12679 (and (not (org-entry-get nil "NOBLOCKING"))
12680 (member (org-entry-get nil "TODO") org-not-done-keywords)
12681 (not (run-hook-with-args-until-failure
12682 'org-blocker-hook
12683 (list :type 'todo-state-change
12684 :position (point)
12685 :from 'todo
12686 :to 'done)))))
12688 (defun org-update-statistics-cookies (all)
12689 "Update the statistics cookie, either from TODO or from checkboxes.
12690 This should be called with the cursor in a line with a statistics
12691 cookie. When called with a \\[universal-argument] prefix, update
12692 all statistics cookies in the buffer."
12693 (interactive "P")
12694 (if all
12695 (progn
12696 (org-update-checkbox-count 'all)
12697 (org-map-entries 'org-update-parent-todo-statistics))
12698 (if (not (org-at-heading-p))
12699 (org-update-checkbox-count)
12700 (let ((pos (point-marker))
12701 end l1 l2)
12702 (ignore-errors (org-back-to-heading t))
12703 (if (not (org-at-heading-p))
12704 (org-update-checkbox-count)
12705 (setq l1 (org-outline-level))
12706 (setq end (save-excursion
12707 (outline-next-heading)
12708 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12709 (point)))
12710 (if (and (save-excursion
12711 (re-search-forward
12712 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12713 (not (save-excursion (re-search-forward
12714 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12715 (org-update-checkbox-count)
12716 (if (and l2 (> l2 l1))
12717 (progn
12718 (goto-char end)
12719 (org-update-parent-todo-statistics))
12720 (goto-char pos)
12721 (beginning-of-line 1)
12722 (while (re-search-forward
12723 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12724 (point-at-eol) t)
12725 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12726 (goto-char pos)
12727 (move-marker pos nil)))))
12729 (defvar org-entry-property-inherited-from) ;; defined below
12730 (defun org-update-parent-todo-statistics ()
12731 "Update any statistics cookie in the parent of the current headline.
12732 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12733 the entire subtree and this will travel up the hierarchy and update
12734 statistics everywhere."
12735 (let* ((prop (save-excursion (org-up-heading-safe)
12736 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12737 (recursive (or (not org-hierarchical-todo-statistics)
12738 (and prop (string-match "\\<recursive\\>" prop))))
12739 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12741 (first t)
12742 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12743 level ltoggle l1 new ndel
12744 (cnt-all 0) (cnt-done 0) is-percent kwd
12745 checkbox-beg cookie-present)
12746 (catch 'exit
12747 (save-excursion
12748 (beginning-of-line 1)
12749 (setq ltoggle (funcall outline-level))
12750 ;; Three situations are to consider:
12752 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12753 ;; to the top-level ancestor on the headline;
12755 ;; 2. If parent has "recursive" property, repeat up to the
12756 ;; headline setting that property, taking inheritance into
12757 ;; account;
12759 ;; 3. Else, move up to direct parent and proceed only once.
12760 (while (and (setq level (org-up-heading-safe))
12761 (or recursive first)
12762 (>= (point) lim))
12763 (setq first nil cookie-present nil)
12764 (unless (and level
12765 (not (string-match
12766 "\\<checkbox\\>"
12767 (downcase (or (org-entry-get nil "COOKIE_DATA")
12768 "")))))
12769 (throw 'exit nil))
12770 (while (re-search-forward box-re (point-at-eol) t)
12771 (setq cnt-all 0 cnt-done 0 cookie-present t)
12772 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12773 (save-match-data
12774 (unless (outline-next-heading) (throw 'exit nil))
12775 (while (and (looking-at org-complex-heading-regexp)
12776 (> (setq l1 (length (match-string 1))) level))
12777 (setq kwd (and (or recursive (= l1 ltoggle))
12778 (match-string 2)))
12779 (if (or (eq org-provide-todo-statistics 'all-headlines)
12780 (and (eq org-provide-todo-statistics t)
12781 (or (member kwd org-done-keywords)))
12782 (and (listp org-provide-todo-statistics)
12783 (stringp (car org-provide-todo-statistics))
12784 (or (member kwd org-provide-todo-statistics)
12785 (member kwd org-done-keywords)))
12786 (and (listp org-provide-todo-statistics)
12787 (listp (car org-provide-todo-statistics))
12788 (or (member kwd (car org-provide-todo-statistics))
12789 (and (member kwd org-done-keywords)
12790 (member kwd (cadr org-provide-todo-statistics))))))
12791 (setq cnt-all (1+ cnt-all))
12792 (and (eq org-provide-todo-statistics t)
12794 (setq cnt-all (1+ cnt-all))))
12795 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12796 (member kwd org-done-keywords))
12797 (and (listp org-provide-todo-statistics)
12798 (listp (car org-provide-todo-statistics))
12799 (member kwd org-done-keywords)
12800 (member kwd (cadr org-provide-todo-statistics)))
12801 (and (listp org-provide-todo-statistics)
12802 (stringp (car org-provide-todo-statistics))
12803 (member kwd org-done-keywords)))
12804 (setq cnt-done (1+ cnt-done)))
12805 (outline-next-heading)))
12806 (setq new
12807 (if is-percent
12808 (format "[%d%%]" (floor (* 100.0 cnt-done)
12809 (max 1 cnt-all)))
12810 (format "[%d/%d]" cnt-done cnt-all))
12811 ndel (- (match-end 0) checkbox-beg))
12812 (goto-char checkbox-beg)
12813 (insert new)
12814 (delete-region (point) (+ (point) ndel))
12815 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12816 (when cookie-present
12817 (run-hook-with-args 'org-after-todo-statistics-hook
12818 cnt-done (- cnt-all cnt-done))))))
12819 (run-hooks 'org-todo-statistics-hook)))
12821 (defvar org-after-todo-statistics-hook nil
12822 "Hook that is called after a TODO statistics cookie has been updated.
12823 Each function is called with two arguments: the number of not-done entries
12824 and the number of done entries.
12826 For example, the following function, when added to this hook, will switch
12827 an entry to DONE when all children are done, and back to TODO when new
12828 entries are set to a TODO status. Note that this hook is only called
12829 when there is a statistics cookie in the headline!
12831 (defun org-summary-todo (n-done n-not-done)
12832 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12833 (let (org-log-done org-log-states) ; turn off logging
12834 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12837 (defvar org-todo-statistics-hook nil
12838 "Hook that is run whenever Org thinks TODO statistics should be updated.
12839 This hook runs even if there is no statistics cookie present, in which case
12840 `org-after-todo-statistics-hook' would not run.")
12842 (defun org-todo-trigger-tag-changes (state)
12843 "Apply the changes defined in `org-todo-state-tags-triggers'."
12844 (let ((l org-todo-state-tags-triggers)
12845 changes)
12846 (when (or (not state) (equal state ""))
12847 (setq changes (append changes (cdr (assoc "" l)))))
12848 (when (and (stringp state) (> (length state) 0))
12849 (setq changes (append changes (cdr (assoc state l)))))
12850 (when (member state org-not-done-keywords)
12851 (setq changes (append changes (cdr (assq 'todo l)))))
12852 (when (member state org-done-keywords)
12853 (setq changes (append changes (cdr (assq 'done l)))))
12854 (dolist (c changes)
12855 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12857 (defun org-local-logging (value)
12858 "Get logging settings from a property VALUE."
12859 ;; Directly set the variables, they are already local.
12860 (setq org-log-done nil
12861 org-log-repeat nil
12862 org-todo-log-states nil)
12863 (dolist (w (org-split-string value))
12864 (let (a)
12865 (cond
12866 ((setq a (assoc w org-startup-options))
12867 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12868 (set (nth 1 a) (nth 2 a))))
12869 ((setq a (org-extract-log-state-settings w))
12870 (and (member (car a) org-todo-keywords-1)
12871 (push a org-todo-log-states)))))))
12873 (defun org-get-todo-sequence-head (kwd)
12874 "Return the head of the TODO sequence to which KWD belongs.
12875 If KWD is not set, check if there is a text property remembering the
12876 right sequence."
12877 (let (p)
12878 (cond
12879 ((not kwd)
12880 (or (get-text-property (point-at-bol) 'org-todo-head)
12881 (progn
12882 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12883 nil (point-at-eol)))
12884 (get-text-property p 'org-todo-head))))
12885 ((not (member kwd org-todo-keywords-1))
12886 (car org-todo-keywords-1))
12887 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12889 (defun org-fast-todo-selection ()
12890 "Fast TODO keyword selection with single keys.
12891 Returns the new TODO keyword, or nil if no state change should occur."
12892 (let* ((fulltable org-todo-key-alist)
12893 (done-keywords org-done-keywords) ;; needed for the faces.
12894 (maxlen (apply 'max (mapcar
12895 (lambda (x)
12896 (if (stringp (car x)) (string-width (car x)) 0))
12897 fulltable)))
12898 (expert nil)
12899 (fwidth (+ maxlen 3 1 3))
12900 (ncol (/ (- (window-width) 4) fwidth))
12901 tg cnt e c tbl
12902 groups ingroup)
12903 (save-excursion
12904 (save-window-excursion
12905 (if expert
12906 (set-buffer (get-buffer-create " *Org todo*"))
12907 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12908 (erase-buffer)
12909 (setq-local org-done-keywords done-keywords)
12910 (setq tbl fulltable cnt 0)
12911 (while (setq e (pop tbl))
12912 (cond
12913 ((equal e '(:startgroup))
12914 (push '() groups) (setq ingroup t)
12915 (unless (= cnt 0)
12916 (setq cnt 0)
12917 (insert "\n"))
12918 (insert "{ "))
12919 ((equal e '(:endgroup))
12920 (setq ingroup nil cnt 0)
12921 (insert "}\n"))
12922 ((equal e '(:newline))
12923 (unless (= cnt 0)
12924 (setq cnt 0)
12925 (insert "\n")
12926 (setq e (car tbl))
12927 (while (equal (car tbl) '(:newline))
12928 (insert "\n")
12929 (setq tbl (cdr tbl)))))
12931 (setq tg (car e) c (cdr e))
12932 (when ingroup (push tg (car groups)))
12933 (setq tg (org-add-props tg nil 'face
12934 (org-get-todo-face tg)))
12935 (when (and (= cnt 0) (not ingroup)) (insert " "))
12936 (insert "[" c "] " tg (make-string
12937 (- fwidth 4 (length tg)) ?\ ))
12938 (when (= (setq cnt (1+ cnt)) ncol)
12939 (insert "\n")
12940 (when ingroup (insert " "))
12941 (setq cnt 0)))))
12942 (insert "\n")
12943 (goto-char (point-min))
12944 (unless expert (org-fit-window-to-buffer))
12945 (message "[a-z..]:Set [SPC]:clear")
12946 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12947 (cond
12948 ((or (= c ?\C-g)
12949 (and (= c ?q) (not (rassoc c fulltable))))
12950 (setq quit-flag t))
12951 ((= c ?\ ) nil)
12952 ((setq e (rassoc c fulltable) tg (car e))
12954 (t (setq quit-flag t)))))))
12956 (defun org-entry-is-todo-p ()
12957 (member (org-get-todo-state) org-not-done-keywords))
12959 (defun org-entry-is-done-p ()
12960 (member (org-get-todo-state) org-done-keywords))
12962 (defun org-get-todo-state ()
12963 "Return the TODO keyword of the current subtree."
12964 (save-excursion
12965 (org-back-to-heading t)
12966 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12967 (match-end 2)
12968 (match-string 2))))
12970 (defun org-at-date-range-p (&optional inactive-ok)
12971 "Non-nil if point is inside a date range.
12973 When optional argument INACTIVE-OK is non-nil, also consider
12974 inactive time ranges.
12976 When this function returns a non-nil value, match data is set
12977 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12978 on INACTIVE-OK."
12979 (interactive)
12980 (save-excursion
12981 (catch 'exit
12982 (let ((pos (point)))
12983 (skip-chars-backward "^[<\r\n")
12984 (skip-chars-backward "<[")
12985 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12986 (>= (match-end 0) pos)
12987 (throw 'exit t))
12988 (skip-chars-backward "^<[\r\n")
12989 (skip-chars-backward "<[")
12990 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12991 (>= (match-end 0) pos)
12992 (throw 'exit t)))
12993 nil)))
12995 (defun org-get-repeat (&optional timestamp)
12996 "Check if there is a time-stamp with repeater in this entry.
12998 Return the repeater, as a string, or nil. Also return nil when
12999 this function is called before first heading.
13001 When optional argument TIMESTAMP is a string, extract the
13002 repeater from there instead."
13003 (save-match-data
13004 (cond (timestamp
13005 (and (string-match org-repeat-re timestamp)
13006 (match-string-no-properties 1 timestamp)))
13007 ((org-before-first-heading-p) nil)
13009 (save-excursion
13010 (org-back-to-heading t)
13011 (let ((end (org-entry-end-position)))
13012 (catch :repeat
13013 (while (re-search-forward org-repeat-re end t)
13014 (when (save-match-data (org-at-timestamp-p 'agenda))
13015 (throw :repeat (match-string-no-properties 1)))))))))))
13017 (defvar org-last-changed-timestamp)
13018 (defvar org-last-inserted-timestamp)
13019 (defvar org-log-post-message)
13020 (defvar org-log-note-purpose)
13021 (defvar org-log-note-how nil)
13022 (defvar org-log-note-extra)
13023 (defun org-auto-repeat-maybe (done-word)
13024 "Check if the current headline contains a repeated time-stamp.
13026 If yes, set TODO state back to what it was and change the base date
13027 of repeating deadline/scheduled time stamps to new date.
13029 This function is run automatically after each state change to a DONE state."
13030 (let* ((repeat (org-get-repeat))
13031 (aa (assoc org-last-state org-todo-kwd-alist))
13032 (interpret (nth 1 aa))
13033 (head (nth 2 aa))
13034 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13035 (msg "Entry repeats: ")
13036 (org-log-done nil)
13037 (org-todo-log-states nil)
13038 (end (copy-marker (org-entry-end-position))))
13039 (unwind-protect
13040 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13041 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13042 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13043 org-todo-repeat-to-state)))
13044 (org-todo (cond
13045 ((and to-state (member to-state org-todo-keywords-1))
13046 to-state)
13047 ((eq interpret 'type) org-last-state)
13048 (head)
13049 (t 'none))))
13050 (org-back-to-heading t)
13051 (org-add-planning-info nil nil 'closed)
13052 ;; When `org-log-repeat' is non-nil or entry contains
13053 ;; a clock, set LAST_REPEAT property.
13054 (when (or org-log-repeat
13055 (catch :clock
13056 (while (re-search-forward org-clock-line-re end t)
13057 (when (org-at-clock-log-p) (throw :clock t)))))
13058 (org-entry-put nil "LAST_REPEAT" (format-time-string
13059 (org-time-stamp-format t t)
13060 (current-time))))
13061 (when org-log-repeat
13062 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13063 (memq 'org-add-log-note post-command-hook))
13064 ;; We are already setup for some record.
13065 (when (eq org-log-repeat 'note)
13066 ;; Make sure we take a note, not only a time stamp.
13067 (setq org-log-note-how 'note))
13068 ;; Set up for taking a record.
13069 (org-add-log-setup 'state
13070 (or done-word (car org-done-keywords))
13071 org-last-state
13072 org-log-repeat)))
13073 (let ((planning-re (regexp-opt
13074 (list org-scheduled-string org-deadline-string))))
13075 (while (re-search-forward org-ts-regexp end t)
13076 (let* ((ts (match-string 0))
13077 (planning? (org-at-planning-p))
13078 (type (if (not planning?) "Plain:"
13079 (save-excursion
13080 (re-search-backward
13081 planning-re (line-beginning-position) t)
13082 (match-string 0)))))
13083 (cond
13084 ;; Ignore fake time-stamps (e.g., within comments).
13085 ((not (org-at-timestamp-p 'agenda)))
13086 ;; Time-stamps without a repeater are usually
13087 ;; skipped. However, a SCHEDULED time-stamp without
13088 ;; one is removed, as they are no longer relevant.
13089 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13090 ts))
13091 (when (equal type org-scheduled-string)
13092 (org-remove-timestamp-with-keyword type)))
13094 (let ((n (string-to-number (match-string 2 ts)))
13095 (what (match-string 3 ts)))
13096 (when (equal what "w") (setq n (* n 7) what "d"))
13097 (when (and (equal what "h")
13098 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13099 ts)))
13100 (user-error
13101 "Cannot repeat in Repeat in %d hour(s) because no hour \
13102 has been set"
13104 ;; Preparation, see if we need to modify the start
13105 ;; date for the change.
13106 (when (match-end 1)
13107 (let ((time (save-match-data
13108 (org-time-string-to-time ts))))
13109 (cond
13110 ((equal (match-string 1 ts) ".")
13111 ;; Shift starting date to today
13112 (org-timestamp-change
13113 (- (org-today) (time-to-days time))
13114 'day))
13115 ((equal (match-string 1 ts) "+")
13116 (let ((nshiftmax 10)
13117 (nshift 0))
13118 (while (or (= nshift 0)
13119 (not (time-less-p (current-time) time)))
13120 (when (= (cl-incf nshift) nshiftmax)
13121 (or (y-or-n-p
13122 (format "%d repeater intervals were not \
13123 enough to shift date past today. Continue? "
13124 nshift))
13125 (user-error "Abort")))
13126 (org-timestamp-change n (cdr (assoc what whata)))
13127 (org-in-regexp org-ts-regexp3)
13128 (setq ts (match-string 1))
13129 (setq time
13130 (save-match-data
13131 (org-time-string-to-time ts)))))
13132 (org-timestamp-change (- n) (cdr (assoc what whata)))
13133 ;; Rematch, so that we have everything in place
13134 ;; for the real shift.
13135 (org-in-regexp org-ts-regexp3)
13136 (setq ts (match-string 1))
13137 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13138 ts)))))
13139 (save-excursion
13140 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13141 (setq msg
13142 (concat
13143 msg type " " org-last-changed-timestamp " "))))))))
13144 (setq org-log-post-message msg)
13145 (message "%s" msg))
13146 (set-marker end nil))))
13148 (defun org-show-todo-tree (arg)
13149 "Make a compact tree which shows all headlines marked with TODO.
13150 The tree will show the lines where the regexp matches, and all higher
13151 headlines above the match.
13152 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13153 With a numeric prefix N, construct a sparse tree for the Nth element
13154 of `org-todo-keywords-1'."
13155 (interactive "P")
13156 (let ((case-fold-search nil)
13157 (kwd-re
13158 (cond ((null arg) org-not-done-regexp)
13159 ((equal arg '(4))
13160 (let ((kwd
13161 (completing-read "Keyword (or KWD1|KWD2|...): "
13162 (mapcar #'list org-todo-keywords-1))))
13163 (concat "\\("
13164 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13165 "\\)\\>")))
13166 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13167 (regexp-quote (nth (1- (prefix-numeric-value arg))
13168 org-todo-keywords-1)))
13169 (t (user-error "Invalid prefix argument: %s" arg)))))
13170 (message "%d TODO entries found"
13171 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13173 (defun org--deadline-or-schedule (arg type time)
13174 "Insert DEADLINE or SCHEDULE information in current entry.
13175 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13176 `org-schedule' for information about ARG and TIME arguments."
13177 (let* ((deadline? (eq type 'deadline))
13178 (keyword (if deadline? org-deadline-string org-scheduled-string))
13179 (log (if deadline? org-log-redeadline org-log-reschedule))
13180 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13181 (old-date-time (and old-date (org-time-string-to-time old-date)))
13182 ;; Save repeater cookie from either TIME or current scheduled
13183 ;; time stamp. We are going to insert it back at the end of
13184 ;; the process.
13185 (repeater (or (and (org-string-nw-p time)
13186 ;; We use `org-repeat-re' because we need
13187 ;; to tell the difference between a real
13188 ;; repeater and a time delta, e.g. "+2d".
13189 (string-match org-repeat-re time)
13190 (match-string 1 time))
13191 (and (org-string-nw-p old-date)
13192 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13193 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13194 old-date)
13195 (match-string 1 old-date)))))
13196 (pcase arg
13197 (`(4)
13198 (when (and old-date log)
13199 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13200 nil old-date log))
13201 (org-remove-timestamp-with-keyword keyword)
13202 (message (if deadline? "Item no longer has a deadline."
13203 "Item is no longer scheduled.")))
13204 (`(16)
13205 (save-excursion
13206 (org-back-to-heading t)
13207 (let ((regexp (if deadline? org-deadline-time-regexp
13208 org-scheduled-time-regexp)))
13209 (if (not (re-search-forward regexp (line-end-position 2) t))
13210 (user-error (if deadline? "No deadline information to update"
13211 "No scheduled information to update"))
13212 (let* ((rpl0 (match-string 1))
13213 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13214 (msg (if deadline? "Warn starting from" "Delay until")))
13215 (replace-match
13216 (concat keyword
13217 " <" rpl
13218 (format " -%dd"
13219 (abs (- (time-to-days
13220 (save-match-data
13221 (org-read-date
13222 nil t nil msg old-date-time)))
13223 (time-to-days old-date-time))))
13224 ">") t t))))))
13226 (org-add-planning-info type time 'closed)
13227 (when (and old-date
13229 (not (equal old-date org-last-inserted-timestamp)))
13230 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13231 org-last-inserted-timestamp
13232 old-date
13233 log))
13234 (when repeater
13235 (save-excursion
13236 (org-back-to-heading t)
13237 (when (re-search-forward
13238 (concat keyword " " org-last-inserted-timestamp)
13239 (line-end-position 2)
13241 (goto-char (1- (match-end 0)))
13242 (insert " " repeater)
13243 (setq org-last-inserted-timestamp
13244 (concat (substring org-last-inserted-timestamp 0 -1)
13245 " " repeater
13246 (substring org-last-inserted-timestamp -1))))))
13247 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13248 org-last-inserted-timestamp)))))
13250 (defun org-deadline (arg &optional time)
13251 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13252 With one universal prefix argument, remove any deadline from the item.
13253 With two universal prefix arguments, prompt for a warning delay.
13254 With argument TIME, set the deadline at the corresponding date. TIME
13255 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13256 (interactive "P")
13257 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13258 (org-map-entries
13259 (lambda () (org--deadline-or-schedule arg 'deadline time))
13261 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13262 'region-start-level
13263 'region)
13264 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13265 (org--deadline-or-schedule arg 'deadline time)))
13267 (defun org-schedule (arg &optional time)
13268 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13269 With one universal prefix argument, remove any scheduling date from the item.
13270 With two universal prefix arguments, prompt for a delay cookie.
13271 With argument TIME, scheduled at the corresponding date. TIME can
13272 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13273 (interactive "P")
13274 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13275 (org-map-entries
13276 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13278 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13279 'region-start-level
13280 'region)
13281 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13282 (org--deadline-or-schedule arg 'scheduled time)))
13284 (defun org-get-scheduled-time (pom &optional inherit)
13285 "Get the scheduled time as a time tuple, of a format suitable
13286 for calling org-schedule with, or if there is no scheduling,
13287 returns nil."
13288 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13289 (when time
13290 (apply 'encode-time (org-parse-time-string time)))))
13292 (defun org-get-deadline-time (pom &optional inherit)
13293 "Get the deadline as a time tuple, of a format suitable for
13294 calling org-deadline with, or if there is no scheduling, returns
13295 nil."
13296 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13297 (when time
13298 (apply 'encode-time (org-parse-time-string time)))))
13300 (defun org-remove-timestamp-with-keyword (keyword)
13301 "Remove all time stamps with KEYWORD in the current entry."
13302 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13303 beg)
13304 (save-excursion
13305 (org-back-to-heading t)
13306 (setq beg (point))
13307 (outline-next-heading)
13308 (while (re-search-backward re beg t)
13309 (replace-match "")
13310 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13311 (equal (char-before) ?\ ))
13312 (backward-delete-char 1)
13313 (when (string-match "^[ \t]*$" (buffer-substring
13314 (point-at-bol) (point-at-eol)))
13315 (delete-region (point-at-bol)
13316 (min (point-max) (1+ (point-at-eol))))))))))
13318 (defvar org-time-was-given) ; dynamically scoped parameter
13319 (defvar org-end-time-was-given) ; dynamically scoped parameter
13321 (defun org-at-planning-p ()
13322 "Non-nil when point is on a planning info line."
13323 ;; This is as accurate and faster than `org-element-at-point' since
13324 ;; planning info location is fixed in the section.
13325 (org-with-wide-buffer
13326 (beginning-of-line)
13327 (and (looking-at-p org-planning-line-re)
13328 (eq (point)
13329 (ignore-errors
13330 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13331 (org-back-to-heading t)
13332 (org-with-limited-levels (org-back-to-heading t)))
13333 (line-beginning-position 2))))))
13335 (defun org-add-planning-info (what &optional time &rest remove)
13336 "Insert new timestamp with keyword in the planning line.
13337 WHAT indicates what kind of time stamp to add. It is a symbol
13338 among `closed', `deadline', `scheduled' and nil. TIME indicates
13339 the time to use. If none is given, the user is prompted for
13340 a date. REMOVE indicates what kind of entries to remove. An old
13341 WHAT entry will also be removed."
13342 (let (org-time-was-given org-end-time-was-given default-time default-input)
13343 (catch 'exit
13344 (when (and (memq what '(scheduled deadline))
13345 (or (not time)
13346 (and (stringp time)
13347 (string-match "^[-+]+[0-9]" time))))
13348 ;; Try to get a default date/time from existing timestamp
13349 (save-excursion
13350 (org-back-to-heading t)
13351 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13352 (when (re-search-forward (if (eq what 'scheduled)
13353 org-scheduled-time-regexp
13354 org-deadline-time-regexp)
13355 end t)
13356 (setq ts (match-string 1)
13357 default-time (apply 'encode-time (org-parse-time-string ts))
13358 default-input (and ts (org-get-compact-tod ts)))))))
13359 (when what
13360 (setq time
13361 (if (stringp time)
13362 ;; This is a string (relative or absolute), set
13363 ;; proper date.
13364 (apply #'encode-time
13365 (org-read-date-analyze
13366 time default-time (decode-time default-time)))
13367 ;; If necessary, get the time from the user
13368 (or time (org-read-date nil 'to-time nil nil
13369 default-time default-input)))))
13371 (org-with-wide-buffer
13372 (org-back-to-heading t)
13373 (forward-line)
13374 (unless (bolp) (insert "\n"))
13375 (cond ((looking-at-p org-planning-line-re)
13376 ;; Move to current indentation.
13377 (skip-chars-forward " \t")
13378 ;; Check if we have to remove something.
13379 (dolist (type (if what (cons what remove) remove))
13380 (save-excursion
13381 (when (re-search-forward
13382 (cl-case type
13383 (closed org-closed-time-regexp)
13384 (deadline org-deadline-time-regexp)
13385 (scheduled org-scheduled-time-regexp)
13386 (otherwise
13387 (error "Invalid planning type: %s" type)))
13388 (line-end-position) t)
13389 ;; Delete until next keyword or end of line.
13390 (delete-region
13391 (match-beginning 0)
13392 (if (re-search-forward org-keyword-time-not-clock-regexp
13393 (line-end-position)
13395 (match-beginning 0)
13396 (line-end-position))))))
13397 ;; If there is nothing more to add and no more keyword
13398 ;; is left, remove the line completely.
13399 (if (and (looking-at-p "[ \t]*$") (not what))
13400 (delete-region (line-beginning-position)
13401 (line-beginning-position 2))
13402 ;; If we removed last keyword, do not leave trailing
13403 ;; white space at the end of line.
13404 (let ((p (point)))
13405 (save-excursion
13406 (end-of-line)
13407 (unless (= (skip-chars-backward " \t" p) 0)
13408 (delete-region (point) (line-end-position)))))))
13409 ((not what) (throw 'exit nil)) ; Nothing to do.
13410 (t (insert-before-markers "\n")
13411 (backward-char 1)
13412 (when org-adapt-indentation
13413 (indent-to-column (1+ (org-outline-level))))))
13414 (when what
13415 ;; Insert planning keyword.
13416 (insert (cl-case what
13417 (closed org-closed-string)
13418 (deadline org-deadline-string)
13419 (scheduled org-scheduled-string)
13420 (otherwise (error "Invalid planning type: %s" what)))
13421 " ")
13422 ;; Insert associated timestamp.
13423 (let ((ts (org-insert-time-stamp
13424 time
13425 (or org-time-was-given
13426 (and (eq what 'closed) org-log-done-with-time))
13427 (eq what 'closed)
13428 nil nil (list org-end-time-was-given))))
13429 (unless (eolp) (insert " "))
13430 ts))))))
13432 (defvar org-log-note-marker (make-marker)
13433 "Marker pointing at the entry where the note is to be inserted.")
13434 (defvar org-log-note-purpose nil)
13435 (defvar org-log-note-state nil)
13436 (defvar org-log-note-previous-state nil)
13437 (defvar org-log-note-extra nil)
13438 (defvar org-log-note-window-configuration nil)
13439 (defvar org-log-note-return-to (make-marker))
13440 (defvar org-log-note-effective-time nil
13441 "Remembered current time so that dynamically scoped
13442 `org-extend-today-until' affects timestamps in state change log")
13444 (defvar org-log-post-message nil
13445 "Message to be displayed after a log note has been stored.
13446 The auto-repeater uses this.")
13448 (defun org-add-note ()
13449 "Add a note to the current entry.
13450 This is done in the same way as adding a state change note."
13451 (interactive)
13452 (org-add-log-setup 'note))
13454 (defun org-log-beginning (&optional create)
13455 "Return expected start of log notes in current entry.
13456 When optional argument CREATE is non-nil, the function creates
13457 a drawer to store notes, if necessary. Returned position ignores
13458 narrowing."
13459 (org-with-wide-buffer
13460 (let ((drawer (org-log-into-drawer)))
13461 (cond
13462 (drawer
13463 (org-end-of-meta-data)
13464 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13465 (end (if (org-at-heading-p) (point)
13466 (save-excursion (outline-next-heading) (point))))
13467 (case-fold-search t))
13468 (catch 'exit
13469 ;; Try to find existing drawer.
13470 (while (re-search-forward regexp end t)
13471 (let ((element (org-element-at-point)))
13472 (when (eq (org-element-type element) 'drawer)
13473 (let ((cend (org-element-property :contents-end element)))
13474 (when (and (not org-log-states-order-reversed) cend)
13475 (goto-char cend)))
13476 (throw 'exit nil))))
13477 ;; No drawer found. Create one, if permitted.
13478 (when create
13479 (unless (bolp) (insert "\n"))
13480 (let ((beg (point)))
13481 (insert ":" drawer ":\n:END:\n")
13482 (org-indent-region beg (point)))
13483 (end-of-line -1)))))
13485 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13486 (skip-chars-forward " \t\n")
13487 (beginning-of-line)
13488 (unless org-log-states-order-reversed
13489 (org-skip-over-state-notes)
13490 (skip-chars-backward " \t\n")
13491 (forward-line)))))
13492 (if (bolp) (point) (line-beginning-position 2))))
13494 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13495 "Set up the post command hook to take a note.
13496 If this is about to TODO state change, the new state is expected in STATE.
13497 HOW is an indicator what kind of note should be created.
13498 EXTRA is additional text that will be inserted into the notes buffer."
13499 (move-marker org-log-note-marker (point))
13500 (setq org-log-note-purpose purpose
13501 org-log-note-state state
13502 org-log-note-previous-state prev-state
13503 org-log-note-how how
13504 org-log-note-extra extra
13505 org-log-note-effective-time (org-current-effective-time))
13506 (add-hook 'post-command-hook 'org-add-log-note 'append))
13508 (defun org-skip-over-state-notes ()
13509 "Skip past the list of State notes in an entry."
13510 (when (ignore-errors (goto-char (org-in-item-p)))
13511 (let* ((struct (org-list-struct))
13512 (prevs (org-list-prevs-alist struct))
13513 (regexp
13514 (concat "[ \t]*- +"
13515 (replace-regexp-in-string
13516 " +" " +"
13517 (org-replace-escapes
13518 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13519 `(("%d" . ,org-ts-regexp-inactive)
13520 ("%D" . ,org-ts-regexp)
13521 ("%s" . "\"\\S-+\"")
13522 ("%S" . "\"\\S-+\"")
13523 ("%t" . ,org-ts-regexp-inactive)
13524 ("%T" . ,org-ts-regexp)
13525 ("%u" . ".*?")
13526 ("%U" . ".*?")))))))
13527 (while (looking-at-p regexp)
13528 (goto-char (or (org-list-get-next-item (point) struct prevs)
13529 (org-list-get-item-end (point) struct)))))))
13531 (defun org-add-log-note (&optional _purpose)
13532 "Pop up a window for taking a note, and add this note later."
13533 (remove-hook 'post-command-hook 'org-add-log-note)
13534 (setq org-log-note-window-configuration (current-window-configuration))
13535 (delete-other-windows)
13536 (move-marker org-log-note-return-to (point))
13537 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13538 (goto-char org-log-note-marker)
13539 (org-switch-to-buffer-other-window "*Org Note*")
13540 (erase-buffer)
13541 (if (memq org-log-note-how '(time state))
13542 (org-store-log-note)
13543 (let ((org-inhibit-startup t)) (org-mode))
13544 (insert (format "# Insert note for %s.
13545 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13546 (cond
13547 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13548 ((eq org-log-note-purpose 'done) "closed todo item")
13549 ((eq org-log-note-purpose 'state)
13550 (format "state change from \"%s\" to \"%s\""
13551 (or org-log-note-previous-state "")
13552 (or org-log-note-state "")))
13553 ((eq org-log-note-purpose 'reschedule)
13554 "rescheduling")
13555 ((eq org-log-note-purpose 'delschedule)
13556 "no longer scheduled")
13557 ((eq org-log-note-purpose 'redeadline)
13558 "changing deadline")
13559 ((eq org-log-note-purpose 'deldeadline)
13560 "removing deadline")
13561 ((eq org-log-note-purpose 'refile)
13562 "refiling")
13563 ((eq org-log-note-purpose 'note)
13564 "this entry")
13565 (t (error "This should not happen")))))
13566 (when org-log-note-extra (insert org-log-note-extra))
13567 (setq-local org-finish-function 'org-store-log-note)
13568 (run-hooks 'org-log-buffer-setup-hook)))
13570 (defvar org-note-abort nil) ; dynamically scoped
13571 (defun org-store-log-note ()
13572 "Finish taking a log note, and insert it to where it belongs."
13573 (let ((txt (prog1 (buffer-string)
13574 (kill-buffer)))
13575 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13576 lines)
13577 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13578 (setq txt (replace-match "" t t txt)))
13579 (when (string-match "\\s-+\\'" txt)
13580 (setq txt (replace-match "" t t txt)))
13581 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13582 (when (org-string-nw-p note)
13583 (setq note
13584 (org-replace-escapes
13585 note
13586 (list (cons "%u" (user-login-name))
13587 (cons "%U" user-full-name)
13588 (cons "%t" (format-time-string
13589 (org-time-stamp-format 'long 'inactive)
13590 org-log-note-effective-time))
13591 (cons "%T" (format-time-string
13592 (org-time-stamp-format 'long nil)
13593 org-log-note-effective-time))
13594 (cons "%d" (format-time-string
13595 (org-time-stamp-format nil 'inactive)
13596 org-log-note-effective-time))
13597 (cons "%D" (format-time-string
13598 (org-time-stamp-format nil nil)
13599 org-log-note-effective-time))
13600 (cons "%s" (cond
13601 ((not org-log-note-state) "")
13602 ((string-match-p org-ts-regexp
13603 org-log-note-state)
13604 (format "\"[%s]\""
13605 (substring org-log-note-state 1 -1)))
13606 (t (format "\"%s\"" org-log-note-state))))
13607 (cons "%S"
13608 (cond
13609 ((not org-log-note-previous-state) "")
13610 ((string-match-p org-ts-regexp
13611 org-log-note-previous-state)
13612 (format "\"[%s]\""
13613 (substring
13614 org-log-note-previous-state 1 -1)))
13615 (t (format "\"%s\""
13616 org-log-note-previous-state)))))))
13617 (when lines (setq note (concat note " \\\\")))
13618 (push note lines))
13619 (when (and lines (not org-note-abort))
13620 (with-current-buffer (marker-buffer org-log-note-marker)
13621 (org-with-wide-buffer
13622 ;; Find location for the new note.
13623 (goto-char org-log-note-marker)
13624 (set-marker org-log-note-marker nil)
13625 ;; Note associated to a clock is to be located right after
13626 ;; the clock. Do not move point.
13627 (unless (eq org-log-note-purpose 'clock-out)
13628 (goto-char (org-log-beginning t)))
13629 ;; Make sure point is at the beginning of an empty line.
13630 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13631 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13632 ;; In an existing list, add a new item at the top level.
13633 ;; Otherwise, indent line like a regular one.
13634 (let ((itemp (org-in-item-p)))
13635 (if itemp
13636 (indent-line-to
13637 (let ((struct (save-excursion
13638 (goto-char itemp) (org-list-struct))))
13639 (org-list-get-ind (org-list-get-top-point struct) struct)))
13640 (org-indent-line)))
13641 (insert (org-list-bullet-string "-") (pop lines))
13642 (let ((ind (org-list-item-body-column (line-beginning-position))))
13643 (dolist (line lines)
13644 (insert "\n")
13645 (indent-line-to ind)
13646 (insert line)))
13647 (message "Note stored")
13648 (org-back-to-heading t)
13649 (org-cycle-hide-drawers 'children))
13650 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13651 ;; from within `org-add-log-note' because `buffer-undo-list'
13652 ;; is then modified outside of `org-with-remote-undo'.
13653 (when (eq this-command 'org-agenda-todo)
13654 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13655 ;; Don't add undo information when called from `org-agenda-todo'.
13656 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13657 (set-window-configuration org-log-note-window-configuration)
13658 (with-current-buffer (marker-buffer org-log-note-return-to)
13659 (goto-char org-log-note-return-to))
13660 (move-marker org-log-note-return-to nil)
13661 (when org-log-post-message (message "%s" org-log-post-message))))
13663 (defun org-remove-empty-drawer-at (pos)
13664 "Remove an empty drawer at position POS.
13665 POS may also be a marker."
13666 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13667 (org-with-wide-buffer
13668 (goto-char pos)
13669 (let ((drawer (org-element-at-point)))
13670 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13671 (not (org-element-property :contents-begin drawer)))
13672 (delete-region (org-element-property :begin drawer)
13673 (progn (goto-char (org-element-property :end drawer))
13674 (skip-chars-backward " \r\t\n")
13675 (forward-line)
13676 (point))))))))
13678 (defvar org-ts-type nil)
13679 (defun org-sparse-tree (&optional arg type)
13680 "Create a sparse tree, prompt for the details.
13681 This command can create sparse trees. You first need to select the type
13682 of match used to create the tree:
13684 t Show all TODO entries.
13685 T Show entries with a specific TODO keyword.
13686 m Show entries selected by a tags/property match.
13687 p Enter a property name and its value (both with completion on existing
13688 names/values) and show entries with that property.
13689 r Show entries matching a regular expression (`/' can be used as well).
13690 b Show deadlines and scheduled items before a date.
13691 a Show deadlines and scheduled items after a date.
13692 d Show deadlines due within `org-deadline-warning-days'.
13693 D Show deadlines and scheduled items between a date range."
13694 (interactive "P")
13695 (setq type (or type org-sparse-tree-default-date-type))
13696 (setq org-ts-type type)
13697 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13698 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13699 \[c]ycle through date types: %s"
13700 (cl-case type
13701 (all "all timestamps")
13702 (scheduled "only scheduled")
13703 (deadline "only deadline")
13704 (active "only active timestamps")
13705 (inactive "only inactive timestamps")
13706 (closed "with a closed time-stamp")
13707 (otherwise "scheduled/deadline")))
13708 (let ((answer (read-char-exclusive)))
13709 (cl-case answer
13711 (org-sparse-tree
13713 (cadr
13714 (memq type '(nil all scheduled deadline active inactive closed)))))
13715 (?d (call-interactively 'org-check-deadlines))
13716 (?b (call-interactively 'org-check-before-date))
13717 (?a (call-interactively 'org-check-after-date))
13718 (?D (call-interactively 'org-check-dates-range))
13719 (?t (call-interactively 'org-show-todo-tree))
13720 (?T (org-show-todo-tree '(4)))
13721 (?m (call-interactively 'org-match-sparse-tree))
13722 ((?p ?P)
13723 (let* ((kwd (completing-read
13724 "Property: " (mapcar #'list (org-buffer-property-keys))))
13725 (value (completing-read
13726 "Value: " (mapcar #'list (org-property-values kwd)))))
13727 (unless (string-match "\\`{.*}\\'" value)
13728 (setq value (concat "\"" value "\"")))
13729 (org-match-sparse-tree arg (concat kwd "=" value))))
13730 ((?r ?R ?/) (call-interactively 'org-occur))
13731 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13733 (defvar-local org-occur-highlights nil
13734 "List of overlays used for occur matches.")
13735 (defvar-local org-occur-parameters nil
13736 "Parameters of the active org-occur calls.
13737 This is a list, each call to org-occur pushes as cons cell,
13738 containing the regular expression and the callback, onto the list.
13739 The list can contain several entries if `org-occur' has been called
13740 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13741 will only contain one set of parameters. When the highlights are
13742 removed (for example with `C-c C-c', or with the next edit (depending
13743 on `org-remove-highlights-with-change'), this variable is emptied
13744 as well.")
13746 (defun org-occur (regexp &optional keep-previous callback)
13747 "Make a compact tree which shows all matches of REGEXP.
13749 The tree will show the lines where the regexp matches, and any other context
13750 defined in `org-show-context-detail', which see.
13752 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13753 done by a previous call to `org-occur' will be kept, to allow stacking of
13754 calls to this command.
13756 Optional argument CALLBACK can be a function of no argument. In this case,
13757 it is called with point at the end of the match, match data being set
13758 accordingly. Current match is shown only if the return value is non-nil.
13759 The function must neither move point nor alter narrowing."
13760 (interactive "sRegexp: \nP")
13761 (when (equal regexp "")
13762 (user-error "Regexp cannot be empty"))
13763 (unless keep-previous
13764 (org-remove-occur-highlights nil nil t))
13765 (push (cons regexp callback) org-occur-parameters)
13766 (let ((cnt 0))
13767 (save-excursion
13768 (goto-char (point-min))
13769 (when (or (not keep-previous) ; do not want to keep
13770 (not org-occur-highlights)) ; no previous matches
13771 ;; hide everything
13772 (org-overview))
13773 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13774 (isearch-no-upper-case-p regexp t)
13775 org-occur-case-fold-search)))
13776 (while (re-search-forward regexp nil t)
13777 (when (or (not callback)
13778 (save-match-data (funcall callback)))
13779 (setq cnt (1+ cnt))
13780 (when org-highlight-sparse-tree-matches
13781 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13782 (org-show-context 'occur-tree)))))
13783 (when org-remove-highlights-with-change
13784 (add-hook 'before-change-functions 'org-remove-occur-highlights
13785 nil 'local))
13786 (unless org-sparse-tree-open-archived-trees
13787 (org-hide-archived-subtrees (point-min) (point-max)))
13788 (run-hooks 'org-occur-hook)
13789 (when (called-interactively-p 'interactive)
13790 (message "%d match(es) for regexp %s" cnt regexp))
13791 cnt))
13793 (defun org-occur-next-match (&optional n _reset)
13794 "Function for `next-error-function' to find sparse tree matches.
13795 N is the number of matches to move, when negative move backwards.
13796 This function always goes back to the starting point when no
13797 match is found."
13798 (let* ((limit (if (< n 0) (point-min) (point-max)))
13799 (search-func (if (< n 0)
13800 'previous-single-char-property-change
13801 'next-single-char-property-change))
13802 (n (abs n))
13803 (pos (point))
13805 (catch 'exit
13806 (while (setq p1 (funcall search-func (point) 'org-type))
13807 (when (equal p1 limit)
13808 (goto-char pos)
13809 (user-error "No more matches"))
13810 (when (equal (get-char-property p1 'org-type) 'org-occur)
13811 (setq n (1- n))
13812 (when (= n 0)
13813 (goto-char p1)
13814 (throw 'exit (point))))
13815 (goto-char p1))
13816 (goto-char p1)
13817 (user-error "No more matches"))))
13819 (defun org-show-context (&optional key)
13820 "Make sure point and context are visible.
13821 Optional argument KEY, when non-nil, is a symbol. See
13822 `org-show-context-detail' for allowed values and how much is to
13823 be shown."
13824 (org-show-set-visibility
13825 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13826 ((cdr (assq key org-show-context-detail)))
13827 (t (cdr (assq 'default org-show-context-detail))))))
13829 (defun org-show-set-visibility (detail)
13830 "Set visibility around point according to DETAIL.
13831 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13832 `tree', `canonical' or t. See `org-show-context-detail' for more
13833 information."
13834 ;; Show current heading and possibly its entry, following headline
13835 ;; or all children.
13836 (if (and (org-at-heading-p) (not (eq detail 'local)))
13837 (org-flag-heading nil)
13838 (org-show-entry)
13839 ;; If point is hidden within a drawer or a block, make sure to
13840 ;; expose it.
13841 (dolist (o (overlays-at (point)))
13842 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13843 (delete-overlay o)))
13844 (unless (org-before-first-heading-p)
13845 (org-with-limited-levels
13846 (cl-case detail
13847 ((tree canonical t) (org-show-children))
13848 ((nil minimal ancestors))
13849 (t (save-excursion
13850 (outline-next-heading)
13851 (org-flag-heading nil)))))))
13852 ;; Show all siblings.
13853 (when (eq detail 'lineage) (org-show-siblings))
13854 ;; Show ancestors, possibly with their children.
13855 (when (memq detail '(ancestors lineage tree canonical t))
13856 (save-excursion
13857 (while (org-up-heading-safe)
13858 (org-flag-heading nil)
13859 (when (memq detail '(canonical t)) (org-show-entry))
13860 (when (memq detail '(tree canonical t)) (org-show-children))))))
13862 (defvar org-reveal-start-hook nil
13863 "Hook run before revealing a location.")
13865 (defun org-reveal (&optional siblings)
13866 "Show current entry, hierarchy above it, and the following headline.
13868 This can be used to show a consistent set of context around
13869 locations exposed with `org-show-context'.
13871 With optional argument SIBLINGS, on each level of the hierarchy all
13872 siblings are shown. This repairs the tree structure to what it would
13873 look like when opened with hierarchical calls to `org-cycle'.
13875 With a \\[universal-argument] \\[universal-argument] prefix, \
13876 go to the parent and show the entire tree."
13877 (interactive "P")
13878 (run-hooks 'org-reveal-start-hook)
13879 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13880 ((equal siblings '(16))
13881 (save-excursion
13882 (when (org-up-heading-safe)
13883 (org-show-subtree)
13884 (run-hook-with-args 'org-cycle-hook 'subtree))))
13885 (t (org-show-set-visibility 'lineage))))
13887 (defun org-highlight-new-match (beg end)
13888 "Highlight from BEG to END and mark the highlight is an occur headline."
13889 (let ((ov (make-overlay beg end)))
13890 (overlay-put ov 'face 'secondary-selection)
13891 (overlay-put ov 'org-type 'org-occur)
13892 (push ov org-occur-highlights)))
13894 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13895 "Remove the occur highlights from the buffer.
13896 BEG and END are ignored. If NOREMOVE is nil, remove this function
13897 from the `before-change-functions' in the current buffer."
13898 (interactive)
13899 (unless org-inhibit-highlight-removal
13900 (mapc #'delete-overlay org-occur-highlights)
13901 (setq org-occur-highlights nil)
13902 (setq org-occur-parameters nil)
13903 (unless noremove
13904 (remove-hook 'before-change-functions
13905 'org-remove-occur-highlights 'local))))
13907 ;;;; Priorities
13909 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13910 "Regular expression matching the priority indicator.")
13912 (defvar org-remove-priority-next-time nil)
13914 (defun org-priority-up ()
13915 "Increase the priority of the current item."
13916 (interactive)
13917 (org-priority 'up))
13919 (defun org-priority-down ()
13920 "Decrease the priority of the current item."
13921 (interactive)
13922 (org-priority 'down))
13924 (defun org-priority (&optional action _show)
13925 "Change the priority of an item.
13926 ACTION can be `set', `up', `down', or a character."
13927 (interactive "P")
13928 (if (equal action '(4))
13929 (org-show-priority)
13930 (unless org-enable-priority-commands
13931 (user-error "Priority commands are disabled"))
13932 (setq action (or action 'set))
13933 (let (current new news have remove)
13934 (save-excursion
13935 (org-back-to-heading t)
13936 (when (looking-at org-priority-regexp)
13937 (setq current (string-to-char (match-string 2))
13938 have t))
13939 (cond
13940 ((eq action 'remove)
13941 (setq remove t new ?\ ))
13942 ((or (eq action 'set)
13943 (integerp action))
13944 (if (not (eq action 'set))
13945 (setq new action)
13946 (message "Priority %c-%c, SPC to remove: "
13947 org-highest-priority org-lowest-priority)
13948 (save-match-data
13949 (setq new (read-char-exclusive))))
13950 (when (and (= (upcase org-highest-priority) org-highest-priority)
13951 (= (upcase org-lowest-priority) org-lowest-priority))
13952 (setq new (upcase new)))
13953 (cond ((equal new ?\ ) (setq remove t))
13954 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13955 (user-error "Priority must be between `%c' and `%c'"
13956 org-highest-priority org-lowest-priority))))
13957 ((eq action 'up)
13958 (setq new (if have
13959 (1- current) ; normal cycling
13960 ;; last priority was empty
13961 (if (eq last-command this-command)
13962 org-lowest-priority ; wrap around empty to lowest
13963 ;; default
13964 (if org-priority-start-cycle-with-default
13965 org-default-priority
13966 (1- org-default-priority))))))
13967 ((eq action 'down)
13968 (setq new (if have
13969 (1+ current) ; normal cycling
13970 ;; last priority was empty
13971 (if (eq last-command this-command)
13972 org-highest-priority ; wrap around empty to highest
13973 ;; default
13974 (if org-priority-start-cycle-with-default
13975 org-default-priority
13976 (1+ org-default-priority))))))
13977 (t (user-error "Invalid action")))
13978 (when (or (< (upcase new) org-highest-priority)
13979 (> (upcase new) org-lowest-priority))
13980 (if (and (memq action '(up down))
13981 (not have) (not (eq last-command this-command)))
13982 ;; `new' is from default priority
13983 (error
13984 "The default can not be set, see `org-default-priority' why")
13985 ;; normal cycling: `new' is beyond highest/lowest priority
13986 ;; and is wrapped around to the empty priority
13987 (setq remove t)))
13988 (setq news (format "%c" new))
13989 (if have
13990 (if remove
13991 (replace-match "" t t nil 1)
13992 (replace-match news t t nil 2))
13993 (if remove
13994 (user-error "No priority cookie found in line")
13995 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13996 (if (match-end 2)
13997 (progn
13998 (goto-char (match-end 2))
13999 (insert " [#" news "]"))
14000 (goto-char (match-beginning 3))
14001 (insert "[#" news "] "))))
14002 (org-set-tags nil 'align))
14003 (if remove
14004 (message "Priority removed")
14005 (message "Priority of current item set to %s" news)))))
14007 (defun org-show-priority ()
14008 "Show the priority of the current item.
14009 This priority is composed of the main priority given with the [#A] cookies,
14010 and by additional input from the age of a schedules or deadline entry."
14011 (interactive)
14012 (let ((pri (if (eq major-mode 'org-agenda-mode)
14013 (org-get-at-bol 'priority)
14014 (save-excursion
14015 (save-match-data
14016 (beginning-of-line)
14017 (and (looking-at org-heading-regexp)
14018 (org-get-priority (match-string 0))))))))
14019 (message "Priority is %d" (if pri pri -1000))))
14021 (defun org-get-priority (s)
14022 "Find priority cookie and return priority."
14023 (save-match-data
14024 (if (functionp org-get-priority-function)
14025 (funcall org-get-priority-function)
14026 (if (not (string-match org-priority-regexp s))
14027 (* 1000 (- org-lowest-priority org-default-priority))
14028 (* 1000 (- org-lowest-priority
14029 (string-to-char (match-string 2 s))))))))
14031 ;;;; Tags
14033 (defvar org-agenda-archives-mode)
14034 (defvar org-map-continue-from nil
14035 "Position from where mapping should continue.
14036 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14038 (defvar org-scanner-tags nil
14039 "The current tag list while the tags scanner is running.")
14041 (defvar org-trust-scanner-tags nil
14042 "Should `org-get-tags-at' use the tags for the scanner.
14043 This is for internal dynamical scoping only.
14044 When this is non-nil, the function `org-get-tags-at' will return the value
14045 of `org-scanner-tags' instead of building the list by itself. This
14046 can lead to large speed-ups when the tags scanner is used in a file with
14047 many entries, and when the list of tags is retrieved, for example to
14048 obtain a list of properties. Building the tags list for each entry in such
14049 a file becomes an N^2 operation - but with this variable set, it scales
14050 as N.")
14052 (defvar org--matcher-tags-todo-only nil)
14054 (defun org-scan-tags (action matcher todo-only &optional start-level)
14055 "Scan headline tags with inheritance and produce output ACTION.
14057 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14058 or `agenda' to produce an entry list for an agenda view. It can also be
14059 a Lisp form or a function that should be called at each matched headline, in
14060 this case the return value is a list of all return values from these calls.
14062 MATCHER is a function accepting three arguments, returning
14063 a non-nil value whenever a given set of tags qualifies a headline
14064 for inclusion. See `org-make-tags-matcher' for more information.
14065 As a special case, it can also be set to t (respectively nil) in
14066 order to match all (respectively none) headline.
14068 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14069 included in the output.
14071 START-LEVEL can be a string with asterisks, reducing the scope to
14072 headlines matching this string."
14073 (require 'org-agenda)
14074 (let* ((re (concat "^"
14075 (if start-level
14076 ;; Get the correct level to match
14077 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14078 org-outline-regexp)
14079 " *\\(\\<\\("
14080 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14081 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14082 (props (list 'face 'default
14083 'done-face 'org-agenda-done
14084 'undone-face 'default
14085 'mouse-face 'highlight
14086 'org-not-done-regexp org-not-done-regexp
14087 'org-todo-regexp org-todo-regexp
14088 'org-complex-heading-regexp org-complex-heading-regexp
14089 'help-echo
14090 (format "mouse-2 or RET jump to org file %s"
14091 (abbreviate-file-name
14092 (or (buffer-file-name (buffer-base-buffer))
14093 (buffer-name (buffer-base-buffer)))))))
14094 (org-map-continue-from nil)
14095 lspos tags tags-list
14096 (tags-alist (list (cons 0 org-file-tags)))
14097 (llast 0) rtn rtn1 level category i txt
14098 todo marker entry priority
14099 ts-date ts-date-type ts-date-pair)
14100 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14101 (setq action (list 'lambda nil action)))
14102 (save-excursion
14103 (goto-char (point-min))
14104 (when (eq action 'sparse-tree)
14105 (org-overview)
14106 (org-remove-occur-highlights))
14107 (while (let (case-fold-search)
14108 (re-search-forward re nil t))
14109 (setq org-map-continue-from nil)
14110 (catch :skip
14111 (setq todo
14112 ;; TODO: is the 1-2 difference a bug?
14113 (when (match-end 1) (match-string-no-properties 2))
14114 tags (when (match-end 4) (match-string-no-properties 4)))
14115 (goto-char (setq lspos (match-beginning 0)))
14116 (setq level (org-reduced-level (org-outline-level))
14117 category (org-get-category))
14118 (when (eq action 'agenda)
14119 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14120 ts-date (car ts-date-pair)
14121 ts-date-type (cdr ts-date-pair)))
14122 (setq i llast llast level)
14123 ;; remove tag lists from same and sublevels
14124 (while (>= i level)
14125 (when (setq entry (assoc i tags-alist))
14126 (setq tags-alist (delete entry tags-alist)))
14127 (setq i (1- i)))
14128 ;; add the next tags
14129 (when tags
14130 (setq tags (org-split-string tags ":")
14131 tags-alist
14132 (cons (cons level tags) tags-alist)))
14133 ;; compile tags for current headline
14134 (setq tags-list
14135 (if org-use-tag-inheritance
14136 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14137 tags)
14138 org-scanner-tags tags-list)
14139 (when org-use-tag-inheritance
14140 (setcdr (car tags-alist)
14141 (mapcar (lambda (x)
14142 (setq x (copy-sequence x))
14143 (org-add-prop-inherited x))
14144 (cdar tags-alist))))
14145 (when (and tags org-use-tag-inheritance
14146 (or (not (eq t org-use-tag-inheritance))
14147 org-tags-exclude-from-inheritance))
14148 ;; Selective inheritance, remove uninherited ones.
14149 (setcdr (car tags-alist)
14150 (org-remove-uninherited-tags (cdar tags-alist))))
14151 (when (and
14153 ;; eval matcher only when the todo condition is OK
14154 (and (or (not todo-only) (member todo org-todo-keywords-1))
14155 (if (functionp matcher)
14156 (let ((case-fold-search t) (org-trust-scanner-tags t))
14157 (funcall matcher todo tags-list level))
14158 matcher))
14160 ;; Call the skipper, but return t if it does not
14161 ;; skip, so that the `and' form continues evaluating.
14162 (progn
14163 (unless (eq action 'sparse-tree) (org-agenda-skip))
14166 ;; Check if timestamps are deselecting this entry
14167 (or (not todo-only)
14168 (and (member todo org-todo-keywords-1)
14169 (or (not org-agenda-tags-todo-honor-ignore-options)
14170 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14172 ;; select this headline
14173 (cond
14174 ((eq action 'sparse-tree)
14175 (and org-highlight-sparse-tree-matches
14176 (org-get-heading) (match-end 0)
14177 (org-highlight-new-match
14178 (match-beginning 1) (match-end 1)))
14179 (org-show-context 'tags-tree))
14180 ((eq action 'agenda)
14181 (setq txt (org-agenda-format-item
14183 (concat
14184 (if (eq org-tags-match-list-sublevels 'indented)
14185 (make-string (1- level) ?.) "")
14186 (org-get-heading))
14187 (make-string level ?\s)
14188 category
14189 tags-list)
14190 priority (org-get-priority txt))
14191 (goto-char lspos)
14192 (setq marker (org-agenda-new-marker))
14193 (org-add-props txt props
14194 'org-marker marker 'org-hd-marker marker 'org-category category
14195 'todo-state todo
14196 'ts-date ts-date
14197 'priority priority
14198 'type (concat "tagsmatch" ts-date-type))
14199 (push txt rtn))
14200 ((functionp action)
14201 (setq org-map-continue-from nil)
14202 (save-excursion
14203 (setq rtn1 (funcall action))
14204 (push rtn1 rtn)))
14205 (t (user-error "Invalid action")))
14207 ;; if we are to skip sublevels, jump to end of subtree
14208 (unless org-tags-match-list-sublevels
14209 (org-end-of-subtree t)
14210 (backward-char 1))))
14211 ;; Get the correct position from where to continue
14212 (if org-map-continue-from
14213 (goto-char org-map-continue-from)
14214 (and (= (point) lspos) (end-of-line 1)))))
14215 (when (and (eq action 'sparse-tree)
14216 (not org-sparse-tree-open-archived-trees))
14217 (org-hide-archived-subtrees (point-min) (point-max)))
14218 (nreverse rtn)))
14220 (defun org-remove-uninherited-tags (tags)
14221 "Remove all tags that are not inherited from the list TAGS."
14222 (cond
14223 ((eq org-use-tag-inheritance t)
14224 (if org-tags-exclude-from-inheritance
14225 (org-delete-all org-tags-exclude-from-inheritance tags)
14226 tags))
14227 ((not org-use-tag-inheritance) nil)
14228 ((stringp org-use-tag-inheritance)
14229 (delq nil (mapcar
14230 (lambda (x)
14231 (if (and (string-match org-use-tag-inheritance x)
14232 (not (member x org-tags-exclude-from-inheritance)))
14233 x nil))
14234 tags)))
14235 ((listp org-use-tag-inheritance)
14236 (delq nil (mapcar
14237 (lambda (x)
14238 (if (member x org-use-tag-inheritance) x nil))
14239 tags)))))
14241 (defun org-match-sparse-tree (&optional todo-only match)
14242 "Create a sparse tree according to tags string MATCH.
14244 MATCH is a string with match syntax. It can contain a selection
14245 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14246 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14247 those. See the manual for details.
14249 If optional argument TODO-ONLY is non-nil, only select lines that
14250 are also TODO tasks."
14251 (interactive "P")
14252 (org-agenda-prepare-buffers (list (current-buffer)))
14253 (let ((org--matcher-tags-todo-only todo-only))
14254 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14255 org--matcher-tags-todo-only)))
14257 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14259 (defvar org-cached-props nil)
14260 (defun org-cached-entry-get (pom property)
14261 (if (or (eq t org-use-property-inheritance)
14262 (and (stringp org-use-property-inheritance)
14263 (let ((case-fold-search t))
14264 (string-match-p org-use-property-inheritance property)))
14265 (and (listp org-use-property-inheritance)
14266 (member-ignore-case property org-use-property-inheritance)))
14267 ;; Caching is not possible, check it directly.
14268 (org-entry-get pom property 'inherit)
14269 ;; Get all properties, so we can do complicated checks easily.
14270 (cdr (assoc-string property
14271 (or org-cached-props
14272 (setq org-cached-props (org-entry-properties pom)))
14273 t))))
14275 (defun org-global-tags-completion-table (&optional files)
14276 "Return the list of all tags in all agenda buffer/files.
14277 Optional FILES argument is a list of files which can be used
14278 instead of the agenda files."
14279 (save-excursion
14280 (org-uniquify
14281 (delq nil
14282 (apply #'append
14283 (mapcar
14284 (lambda (file)
14285 (set-buffer (find-file-noselect file))
14286 (mapcar (lambda (x)
14287 (and (stringp (car-safe x))
14288 (list (car-safe x))))
14289 (or org-current-tag-alist (org-get-buffer-tags))))
14290 (if (car-safe files) files
14291 (org-agenda-files))))))))
14293 (defun org-make-tags-matcher (match)
14294 "Create the TAGS/TODO matcher form for the selection string MATCH.
14296 Returns a cons of the selection string MATCH and a function
14297 implementing the matcher.
14299 The matcher is to be called at an Org entry, with point on the
14300 headline, and returns non-nil if the entry matches the selection
14301 string MATCH. It must be called with three arguments: the TODO
14302 keyword at the entry (or nil if none), the list of all tags at
14303 the entry including inherited ones and the reduced level of the
14304 headline. Additionally, the category of the entry, if any, must
14305 be specified as the text property `org-category' on the headline.
14307 This function sets the variable `org--matcher-tags-todo-only' to
14308 a non-nil value if the matcher restricts matching to TODO
14309 entries, otherwise it is not touched.
14311 See also `org-scan-tags'."
14312 (unless match
14313 ;; Get a new match request, with completion against the global
14314 ;; tags table and the local tags in current buffer.
14315 (let ((org-last-tags-completion-table
14316 (org-uniquify
14317 (delq nil (append (org-get-buffer-tags)
14318 (org-global-tags-completion-table))))))
14319 (setq match
14320 (completing-read
14321 "Match: "
14322 'org-tags-completion-function nil nil nil 'org-tags-history))))
14324 (let ((match0 match)
14325 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14326 (start 0)
14327 tagsmatch todomatch tagsmatcher todomatcher)
14329 ;; Expand group tags.
14330 (setq match (org-tags-expand match))
14332 ;; Check if there is a TODO part of this match, which would be the
14333 ;; part after a "/". To make sure that this slash is not part of
14334 ;; a property value to be matched against, we also check that
14335 ;; there is no / after that slash. First, find the last slash.
14336 (let ((s 0))
14337 (while (string-match "/+" match s)
14338 (setq start (match-beginning 0))
14339 (setq s (match-end 0))))
14340 (if (and (string-match "/+" match start)
14341 (not (string-match-p "\"" match start)))
14342 ;; Match contains also a TODO-matching request.
14343 (progn
14344 (setq tagsmatch (substring match 0 (match-beginning 0)))
14345 (setq todomatch (substring match (match-end 0)))
14346 (when (string-prefix-p "!" todomatch)
14347 (setq org--matcher-tags-todo-only t)
14348 (setq todomatch (substring todomatch 1)))
14349 (when (string-match "\\`\\s-*\\'" todomatch)
14350 (setq todomatch nil)))
14351 ;; Only matching tags.
14352 (setq tagsmatch match)
14353 (setq todomatch nil))
14355 ;; Make the tags matcher.
14356 (when (org-string-nw-p tagsmatch)
14357 (let ((orlist nil)
14358 (orterms (org-split-string tagsmatch "|"))
14359 term)
14360 (while (setq term (pop orterms))
14361 (while (and (equal (substring term -1) "\\") orterms)
14362 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14363 (while (string-match re term)
14364 (let* ((rest (substring term (match-end 0)))
14365 (minus (and (match-end 1)
14366 (equal (match-string 1 term) "-")))
14367 (tag (save-match-data
14368 (replace-regexp-in-string
14369 "\\\\-" "-" (match-string 2 term))))
14370 (regexp (eq (string-to-char tag) ?{))
14371 (levelp (match-end 4))
14372 (propp (match-end 5))
14374 (cond
14375 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14376 (levelp
14377 `(,(org-op-to-function (match-string 3 term))
14378 level
14379 ,(string-to-number (match-string 4 term))))
14380 (propp
14381 (let* ((gv (pcase (upcase (match-string 5 term))
14382 ("CATEGORY"
14383 '(get-text-property (point) 'org-category))
14384 ("TODO" 'todo)
14385 (p `(org-cached-entry-get nil ,p))))
14386 (pv (match-string 7 term))
14387 (regexp (eq (string-to-char pv) ?{))
14388 (strp (eq (string-to-char pv) ?\"))
14389 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14390 (po (org-op-to-function (match-string 6 term)
14391 (if timep 'time strp))))
14392 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14393 (when timep (setq pv (org-matcher-time pv)))
14394 (cond ((and regexp (eq po 'org<>))
14395 `(not (string-match ,pv (or ,gv ""))))
14396 (regexp `(string-match ,pv (or ,gv "")))
14397 (strp `(,po (or ,gv "") ,pv))
14399 `(,po
14400 (string-to-number (or ,gv ""))
14401 ,(string-to-number pv))))))
14402 (t `(member ,tag tags-list)))))
14403 (push (if minus `(not ,mm) mm) tagsmatcher)
14404 (setq term rest)))
14405 (push `(and ,@tagsmatcher) orlist)
14406 (setq tagsmatcher nil))
14407 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14409 ;; Make the TODO matcher.
14410 (when (org-string-nw-p todomatch)
14411 (let ((orlist nil))
14412 (dolist (term (org-split-string todomatch "|"))
14413 (while (string-match re term)
14414 (let* ((minus (and (match-end 1)
14415 (equal (match-string 1 term) "-")))
14416 (kwd (match-string 2 term))
14417 (regexp (eq (string-to-char kwd) ?{))
14418 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14419 `(equal todo ,kwd))))
14420 (push (if minus `(not ,mm) mm) todomatcher))
14421 (setq term (substring term (match-end 0))))
14422 (push (if (> (length todomatcher) 1)
14423 (cons 'and todomatcher)
14424 (car todomatcher))
14425 orlist)
14426 (setq todomatcher nil))
14427 (setq todomatcher (cons 'or orlist))))
14429 ;; Return the string and function of the matcher. If no
14430 ;; tags-specific or todo-specific matcher exists, match
14431 ;; everything.
14432 (let ((matcher (if (and tagsmatcher todomatcher)
14433 `(and ,tagsmatcher ,todomatcher)
14434 (or tagsmatcher todomatcher t))))
14435 (when org--matcher-tags-todo-only
14436 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14437 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14439 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14440 "Expand group tags in MATCH.
14442 This replaces every group tag in MATCH with a regexp tag search.
14443 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14444 will be replaced like this:
14446 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14447 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14448 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14450 Replacing by a regexp preserves the structure of the match.
14451 E.g., this expansion
14453 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14455 will match anything tagged with \"Lab\" and \"Home\", or tagged
14456 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14458 A group tag in MATCH can contain regular expressions of its own.
14459 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14460 will be replaced like this:
14462 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14464 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14465 assumed to be a single group tag, and the function will return
14466 the list of tags in this group.
14468 When DOWNCASE is non-nil, expand downcased TAGS."
14469 (if org-group-tags
14470 (let* ((case-fold-search t)
14471 (stable org-mode-syntax-table)
14472 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14473 (taggroups (if downcased
14474 (mapcar (lambda (tg) (mapcar #'downcase tg))
14475 taggroups)
14476 taggroups))
14477 (taggroups-keys (mapcar #'car taggroups))
14478 (return-match (if downcased (downcase match) match))
14479 (count 0)
14480 (work-already-expanded tags-already-expanded)
14481 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14482 ;; @ and _ are allowed as word-components in tags.
14483 (modify-syntax-entry ?@ "w" stable)
14484 (modify-syntax-entry ?_ "w" stable)
14485 ;; Temporarily replace regexp-expressions in the match-expression.
14486 (while (string-match "{.+?}" return-match)
14487 (cl-incf count)
14488 (push (match-string 0 return-match) regexps-in-match)
14489 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14490 (while (and taggroups-keys
14491 (with-syntax-table stable
14492 (string-match
14493 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14494 (regexp-opt taggroups-keys) "\\>\\)")
14495 return-match)))
14496 (let* ((dir (match-string 1 return-match))
14497 (tag (match-string 2 return-match))
14498 (tag (if downcased (downcase tag) tag)))
14499 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14500 (member tag work-already-expanded))
14501 (setq tags-in-group (assoc tag taggroups))
14502 (push tag work-already-expanded)
14503 ;; Recursively expand each tag in the group, if the tag hasn't
14504 ;; already been expanded. Restore the match-data after all recursive calls.
14505 (save-match-data
14506 (let (tags-expanded)
14507 (dolist (x (cdr tags-in-group))
14508 (if (and (member x taggroups-keys)
14509 (not (member x work-already-expanded)))
14510 (setq tags-expanded
14511 (delete-dups
14512 (append
14513 (org-tags-expand x t downcased
14514 work-already-expanded)
14515 tags-expanded)))
14516 (setq tags-expanded
14517 (append (list x) tags-expanded)))
14518 (setq work-already-expanded
14519 (delete-dups
14520 (append tags-expanded
14521 work-already-expanded))))
14522 (setq tags-in-group
14523 (delete-dups (cons (car tags-in-group)
14524 tags-expanded)))))
14525 ;; Filter tag-regexps from tags.
14526 (setq regexp-in-group-escaped
14527 (delq nil (mapcar (lambda (x)
14528 (if (stringp x)
14529 (and (equal "{" (substring x 0 1))
14530 (equal "}" (substring x -1))
14533 tags-in-group))
14534 regexp-in-group
14535 (mapcar (lambda (x)
14536 (substring x 1 -1))
14537 regexp-in-group-escaped)
14538 tags-in-group
14539 (delq nil (mapcar (lambda (x)
14540 (if (stringp x)
14541 (and (not (equal "{" (substring x 0 1)))
14542 (not (equal "}" (substring x -1)))
14545 tags-in-group)))
14546 ;; If single-as-list, do no more in the while-loop.
14547 (if (not single-as-list)
14548 (progn
14549 (when regexp-in-group
14550 (setq regexp-in-group
14551 (concat "\\|"
14552 (mapconcat 'identity regexp-in-group
14553 "\\|"))))
14554 (setq tags-in-group
14555 (concat dir
14556 "{\\<"
14557 (regexp-opt tags-in-group)
14558 "\\>"
14559 regexp-in-group
14560 "}"))
14561 (when (stringp tags-in-group)
14562 (org-add-props tags-in-group '(grouptag t)))
14563 (setq return-match
14564 (replace-match tags-in-group t t return-match)))
14565 (setq tags-in-group
14566 (append regexp-in-group-escaped tags-in-group))))
14567 (setq taggroups-keys (delete tag taggroups-keys))))
14568 ;; Add the regular expressions back into the match-expression again.
14569 (while regexps-in-match
14570 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14571 (pop regexps-in-match)
14572 return-match t t))
14573 (cl-decf count))
14574 (if single-as-list
14575 (if tags-in-group tags-in-group (list return-match))
14576 return-match))
14577 (if single-as-list
14578 (list (if downcased (downcase match) match))
14579 match)))
14581 (defun org-op-to-function (op &optional stringp)
14582 "Turn an operator into the appropriate function."
14583 (setq op
14584 (cond
14585 ((equal op "<" ) '(< string< org-time<))
14586 ((equal op ">" ) '(> org-string> org-time>))
14587 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14588 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14589 ((member op '("=" "==")) '(= string= org-time=))
14590 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14591 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14593 (defun org<> (a b) (not (= a b)))
14594 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14595 (defun org-string>= (a b) (not (string< a b)))
14596 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14597 (defun org-string<> (a b) (not (string= 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) (< a b)))
14600 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14601 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14602 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14603 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14604 (defun org-2ft (s)
14605 "Convert S to a floating point time.
14606 If S is already a number, just return it. If it is a string, parse
14607 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14608 (cond
14609 ((numberp s) s)
14610 ((stringp s)
14611 (condition-case nil
14612 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14613 (error 0.)))
14614 (t 0.)))
14616 (defun org-time-today ()
14617 "Time in seconds today at 0:00.
14618 Returns the float number of seconds since the beginning of the
14619 epoch to the beginning of today (00:00)."
14620 (float-time (apply 'encode-time
14621 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14623 (defun org-matcher-time (s)
14624 "Interpret a time comparison value."
14625 (save-match-data
14626 (cond
14627 ((string= s "<now>") (float-time))
14628 ((string= s "<today>") (org-time-today))
14629 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14630 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14631 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14632 (+ (org-time-today)
14633 (* (string-to-number (match-string 1 s))
14634 (cdr (assoc (match-string 2 s)
14635 '(("d" . 86400.0) ("w" . 604800.0)
14636 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14637 (t (org-2ft s)))))
14639 (defun org-match-any-p (re list)
14640 "Does re match any element of list?"
14641 (setq list (mapcar (lambda (x) (string-match re x)) list))
14642 (delq nil list))
14644 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14645 (defvar org-tags-overlay (make-overlay 1 1))
14646 (delete-overlay org-tags-overlay)
14648 (defun org-get-local-tags-at (&optional pos)
14649 "Get a list of tags defined in the current headline."
14650 (org-get-tags-at pos 'local))
14652 (defun org-get-local-tags ()
14653 "Get a list of tags defined in the current headline."
14654 (org-get-tags-at nil 'local))
14656 (defun org-get-tags-at (&optional pos local)
14657 "Get a list of all headline tags applicable at POS.
14658 POS defaults to point. If tags are inherited, the list contains
14659 the targets in the same sequence as the headlines appear, i.e.
14660 the tags of the current headline come last.
14661 When LOCAL is non-nil, only return tags from the current headline,
14662 ignore inherited ones."
14663 (interactive)
14664 (if (and org-trust-scanner-tags
14665 (or (not pos) (equal pos (point)))
14666 (not local))
14667 org-scanner-tags
14668 (let (tags ltags lastpos parent)
14669 (save-excursion
14670 (save-restriction
14671 (widen)
14672 (goto-char (or pos (point)))
14673 (save-match-data
14674 (catch 'done
14675 (condition-case nil
14676 (progn
14677 (org-back-to-heading t)
14678 (while (not (equal lastpos (point)))
14679 (setq lastpos (point))
14680 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14681 (setq ltags (org-split-string
14682 (match-string-no-properties 1) ":"))
14683 (when parent
14684 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14685 (setq tags (append
14686 (if parent
14687 (org-remove-uninherited-tags ltags)
14688 ltags)
14689 tags)))
14690 (or org-use-tag-inheritance (throw 'done t))
14691 (when local (throw 'done t))
14692 (or (org-up-heading-safe) (error nil))
14693 (setq parent t)))
14694 (error nil)))))
14695 (if local
14696 tags
14697 (reverse (delete-dups
14698 (reverse (append
14699 (org-remove-uninherited-tags
14700 org-file-tags)
14701 tags)))))))))
14703 (defun org-add-prop-inherited (s)
14704 (add-text-properties 0 (length s) '(inherited t) s)
14707 (defun org-toggle-tag (tag &optional onoff)
14708 "Toggle the tag TAG for the current line.
14709 If ONOFF is `on' or `off', don't toggle but set to this state."
14710 (save-excursion
14711 (org-back-to-heading t)
14712 (let ((current
14713 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14714 (line-end-position) t)
14715 (let ((tags (match-string 1)))
14716 ;; Clear current tags.
14717 (replace-match "")
14718 ;; Reverse the tags list so any new tag is appended to
14719 ;; the current list of tags.
14720 (nreverse (org-split-string tags ":")))))
14721 res)
14722 (pcase onoff
14723 (`off (setq current (delete tag current)))
14724 ((or `on (guard (not (member tag current))))
14725 (setq res t)
14726 (cl-pushnew tag current :test #'equal))
14727 (_ (setq current (delete tag current))))
14728 (end-of-line)
14729 (if current
14730 (progn
14731 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14732 (org-set-tags nil t))
14733 (delete-horizontal-space))
14734 (run-hooks 'org-after-tags-change-hook)
14735 res)))
14737 (defun org--align-tags-here (to-col)
14738 "Align tags on the current headline to TO-COL.
14739 Assume point is on a headline."
14740 (let ((pos (point)))
14741 (beginning-of-line)
14742 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14743 (>= pos (match-beginning 2)))
14744 ;; No tags or point within tags: do not align.
14745 (goto-char pos)
14746 (goto-char (match-beginning 1))
14747 (let ((shift (max (- (if (>= to-col 0) to-col
14748 (- (abs to-col) (string-width (match-string 2))))
14749 (current-column))
14750 1)))
14751 (replace-match (make-string shift ?\s) nil nil nil 1)
14752 ;; Preserve initial position, if possible. In any case, stop
14753 ;; before tags.
14754 (when (< pos (point)) (goto-char pos))))))
14756 (defun org-set-tags-command (&optional arg just-align)
14757 "Call the set-tags command for the current entry."
14758 (interactive "P")
14759 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14760 (org-set-tags arg just-align)
14761 (save-excursion
14762 (unless (and (org-region-active-p)
14763 org-loop-over-headlines-in-active-region)
14764 (org-back-to-heading t))
14765 (org-set-tags arg just-align))))
14767 (defun org-set-tags-to (data)
14768 "Set the tags of the current entry to DATA, replacing the current tags.
14769 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14770 If DATA is nil or the empty string, any tags will be removed."
14771 (interactive "sTags: ")
14772 (setq data
14773 (cond
14774 ((eq data nil) "")
14775 ((equal data "") "")
14776 ((stringp data)
14777 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14778 ":"))
14779 ((listp data)
14780 (concat ":" (mapconcat 'identity data ":") ":"))))
14781 (when data
14782 (save-excursion
14783 (org-back-to-heading t)
14784 (when (let ((case-fold-search nil))
14785 (looking-at org-complex-heading-regexp))
14786 (if (match-end 5)
14787 (progn
14788 (goto-char (match-beginning 5))
14789 (insert data)
14790 (delete-region (point) (point-at-eol))
14791 (org-set-tags nil 'align))
14792 (goto-char (point-at-eol))
14793 (insert " " data)
14794 (org-set-tags nil 'align)))
14795 (beginning-of-line 1)
14796 (when (looking-at ".*?\\([ \t]+\\)$")
14797 (delete-region (match-beginning 1) (match-end 1))))))
14799 (defun org-align-all-tags ()
14800 "Align the tags in all headings."
14801 (interactive)
14802 (save-excursion
14803 (or (ignore-errors (org-back-to-heading t))
14804 (outline-next-heading))
14805 (if (org-at-heading-p)
14806 (org-set-tags t)
14807 (message "No headings"))))
14809 (defvar org-indent-indentation-per-level)
14810 (defun org-set-tags (&optional arg just-align)
14811 "Set the tags for the current headline.
14812 With prefix ARG, realign all tags in headings in the current buffer.
14813 When JUST-ALIGN is non-nil, only align tags."
14814 (interactive "P")
14815 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14816 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14817 'region-start-level
14818 'region))
14819 org-loop-over-headlines-in-active-region)
14820 (org-map-entries
14821 ;; We don't use ARG and JUST-ALIGN here because these args
14822 ;; are not useful when looping over headlines.
14823 #'org-set-tags
14824 org-loop-over-headlines-in-active-region
14826 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14827 (let ((org-setting-tags t))
14828 (if arg
14829 (save-excursion
14830 (goto-char (point-min))
14831 (while (re-search-forward org-outline-regexp-bol nil t)
14832 (org-set-tags nil t)
14833 (end-of-line))
14834 (message "All tags realigned to column %d" org-tags-column))
14835 (let* ((current (org-get-tags-string))
14836 (tags
14837 (if just-align current
14838 ;; Get a new set of tags from the user.
14839 (save-excursion
14840 (let* ((seen)
14841 (table
14842 (setq
14843 org-last-tags-completion-table
14844 ;; Uniquify tags in alists, yet preserve
14845 ;; structure (i.e., keywords).
14846 (delq nil
14847 (mapcar
14848 (lambda (pair)
14849 (let ((head (car pair)))
14850 (cond ((symbolp head) pair)
14851 ((member head seen) nil)
14852 (t (push head seen)
14853 pair))))
14854 (append
14855 (or org-current-tag-alist
14856 (org-get-buffer-tags))
14857 (and
14858 org-complete-tags-always-offer-all-agenda-tags
14859 (org-global-tags-completion-table
14860 (org-agenda-files))))))))
14861 (current-tags (org-split-string current ":"))
14862 (inherited-tags
14863 (nreverse (nthcdr (length current-tags)
14864 (nreverse (org-get-tags-at))))))
14865 (replace-regexp-in-string
14866 "\\([-+&]+\\|,\\)"
14868 (if (or (eq t org-use-fast-tag-selection)
14869 (and org-use-fast-tag-selection
14870 (delq nil (mapcar #'cdr table))))
14871 (org-fast-tag-selection
14872 current-tags inherited-tags table
14873 (and org-fast-tag-selection-include-todo
14874 org-todo-key-alist))
14875 (let ((org-add-colon-after-tag-completion
14876 (< 1 (length table))))
14877 (org-trim
14878 (completing-read
14879 "Tags: "
14880 #'org-tags-completion-function
14881 nil nil current 'org-tags-history))))))))))
14883 (when org-tags-sort-function
14884 (setq tags
14885 (mapconcat
14886 #'identity
14887 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14888 org-tags-sort-function)
14889 ":")))
14891 (if (or (string= ":" tags)
14892 (string= "::" tags))
14893 (setq tags ""))
14894 (if (not (org-string-nw-p tags)) (setq tags "")
14895 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14896 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14898 ;; Insert new tags at the correct column.
14899 (unless (equal current tags)
14900 (save-excursion
14901 (beginning-of-line)
14902 (let ((case-fold-search nil))
14903 (looking-at org-complex-heading-regexp))
14904 ;; Remove current tags, if any.
14905 (when (match-end 5) (replace-match "" nil nil nil 5))
14906 ;; Insert new tags, if any. Otherwise, remove trailing
14907 ;; white spaces.
14908 (end-of-line)
14909 (if (not (equal tags ""))
14910 ;; When text is being inserted on an invisible
14911 ;; region boundary, it can be inadvertently sucked
14912 ;; into invisibility.
14913 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14914 (skip-chars-backward " \t")
14915 (delete-region (point) (line-end-position)))))
14916 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14917 ;; is on.
14918 (unless (equal tags "")
14919 (let* ((level (save-excursion
14920 (beginning-of-line)
14921 (skip-chars-forward "\\*")))
14922 (offset (if (bound-and-true-p org-indent-mode)
14923 (* (1- org-indent-indentation-per-level)
14924 (1- level))
14926 (tags-column
14927 (+ org-tags-column
14928 (if (> org-tags-column 0) (- offset) offset))))
14929 (org--align-tags-here tags-column))))
14930 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14932 (defun org-change-tag-in-region (beg end tag off)
14933 "Add or remove TAG for each entry in the region.
14934 This works in the agenda, and also in an Org buffer."
14935 (interactive
14936 (list (region-beginning) (region-end)
14937 (let ((org-last-tags-completion-table
14938 (if (derived-mode-p 'org-mode)
14939 (org-uniquify
14940 (delq nil (append (org-get-buffer-tags)
14941 (org-global-tags-completion-table))))
14942 (org-global-tags-completion-table))))
14943 (completing-read
14944 "Tag: " 'org-tags-completion-function nil nil nil
14945 'org-tags-history))
14946 (progn
14947 (message "[s]et or [r]emove? ")
14948 (equal (read-char-exclusive) ?r))))
14949 (when (fboundp 'deactivate-mark) (deactivate-mark))
14950 (let ((agendap (equal major-mode 'org-agenda-mode))
14951 l1 l2 m buf pos newhead (cnt 0))
14952 (goto-char end)
14953 (setq l2 (1- (org-current-line)))
14954 (goto-char beg)
14955 (setq l1 (org-current-line))
14956 (cl-loop for l from l1 to l2 do
14957 (org-goto-line l)
14958 (setq m (get-text-property (point) 'org-hd-marker))
14959 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14960 (and agendap m))
14961 (setq buf (if agendap (marker-buffer m) (current-buffer))
14962 pos (if agendap m (point)))
14963 (with-current-buffer buf
14964 (save-excursion
14965 (save-restriction
14966 (goto-char pos)
14967 (setq cnt (1+ cnt))
14968 (org-toggle-tag tag (if off 'off 'on))
14969 (setq newhead (org-get-heading)))))
14970 (and agendap (org-agenda-change-all-lines newhead m))))
14971 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14973 (defun org-tags-completion-function (string _predicate &optional flag)
14974 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14975 (confirm (lambda (x) (stringp (car x)))))
14976 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14977 (setq s1 (match-string 1 string)
14978 s2 (match-string 2 string))
14979 (setq s1 "" s2 string))
14980 (cond
14981 ((eq flag nil)
14982 ;; try completion
14983 (setq rtn (try-completion s2 ctable confirm))
14984 (when (stringp rtn)
14985 (setq rtn
14986 (concat s1 s2 (substring rtn (length s2))
14987 (if (and org-add-colon-after-tag-completion
14988 (assoc rtn ctable))
14989 ":" ""))))
14990 rtn)
14991 ((eq flag t)
14992 ;; all-completions
14993 (all-completions s2 ctable confirm))
14994 ((eq flag 'lambda)
14995 ;; exact match?
14996 (assoc s2 ctable)))))
14998 (defun org-fast-tag-insert (kwd tags face &optional end)
14999 "Insert KDW, and the TAGS, the latter with face FACE.
15000 Also insert END."
15001 (insert (format "%-12s" (concat kwd ":"))
15002 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15003 (or end "")))
15005 (defun org-fast-tag-show-exit (flag)
15006 (save-excursion
15007 (org-goto-line 3)
15008 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15009 (replace-match ""))
15010 (when flag
15011 (end-of-line 1)
15012 (org-move-to-column (- (window-width) 19) t)
15013 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15015 (defun org-set-current-tags-overlay (current prefix)
15016 "Add an overlay to CURRENT tag with PREFIX."
15017 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15018 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15019 (org-overlay-display org-tags-overlay (concat prefix s))))
15021 (defvar org-last-tag-selection-key nil)
15022 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15023 "Fast tag selection with single keys.
15024 CURRENT is the current list of tags in the headline, INHERITED is the
15025 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15026 possibly with grouping information. TODO-TABLE is a similar table with
15027 TODO keywords, should these have keys assigned to them.
15028 If the keys are nil, a-z are automatically assigned.
15029 Returns the new tags string, or nil to not change the current settings."
15030 (let* ((fulltable (append table todo-table))
15031 (maxlen (apply 'max (mapcar
15032 (lambda (x)
15033 (if (stringp (car x)) (string-width (car x)) 0))
15034 fulltable)))
15035 (buf (current-buffer))
15036 (expert (eq org-fast-tag-selection-single-key 'expert))
15037 (buffer-tags nil)
15038 (fwidth (+ maxlen 3 1 3))
15039 (ncol (/ (- (window-width) 4) fwidth))
15040 (i-face 'org-done)
15041 (c-face 'org-todo)
15042 tg cnt e c char c1 c2 ntable tbl rtn
15043 ov-start ov-end ov-prefix
15044 (exit-after-next org-fast-tag-selection-single-key)
15045 (done-keywords org-done-keywords)
15046 groups ingroup intaggroup)
15047 (save-excursion
15048 (beginning-of-line 1)
15049 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15050 (setq ov-start (match-beginning 1)
15051 ov-end (match-end 1)
15052 ov-prefix "")
15053 (setq ov-start (1- (point-at-eol))
15054 ov-end (1+ ov-start))
15055 (skip-chars-forward "^\n\r")
15056 (setq ov-prefix
15057 (concat
15058 (buffer-substring (1- (point)) (point))
15059 (if (> (current-column) org-tags-column)
15061 (make-string (- org-tags-column (current-column)) ?\ ))))))
15062 (move-overlay org-tags-overlay ov-start ov-end)
15063 (save-window-excursion
15064 (if expert
15065 (set-buffer (get-buffer-create " *Org tags*"))
15066 (delete-other-windows)
15067 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15068 (org-switch-to-buffer-other-window " *Org tags*"))
15069 (erase-buffer)
15070 (setq-local org-done-keywords done-keywords)
15071 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15072 (org-fast-tag-insert "Current" current c-face "\n\n")
15073 (org-fast-tag-show-exit exit-after-next)
15074 (org-set-current-tags-overlay current ov-prefix)
15075 (setq tbl fulltable char ?a cnt 0)
15076 (while (setq e (pop tbl))
15077 (cond
15078 ((eq (car e) :startgroup)
15079 (push '() groups) (setq ingroup t)
15080 (unless (zerop cnt)
15081 (setq cnt 0)
15082 (insert "\n"))
15083 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15084 ((eq (car e) :endgroup)
15085 (setq ingroup nil cnt 0)
15086 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15087 ((eq (car e) :startgrouptag)
15088 (setq intaggroup t)
15089 (unless (zerop cnt)
15090 (setq cnt 0)
15091 (insert "\n"))
15092 (insert "[ "))
15093 ((eq (car e) :endgrouptag)
15094 (setq intaggroup nil cnt 0)
15095 (insert "]\n"))
15096 ((equal e '(:newline))
15097 (unless (zerop cnt)
15098 (setq cnt 0)
15099 (insert "\n")
15100 (setq e (car tbl))
15101 (while (equal (car tbl) '(:newline))
15102 (insert "\n")
15103 (setq tbl (cdr tbl)))))
15104 ((equal e '(:grouptags)) (insert " : "))
15106 (setq tg (copy-sequence (car e)) c2 nil)
15107 (if (cdr e)
15108 (setq c (cdr e))
15109 ;; automatically assign a character.
15110 (setq c1 (string-to-char
15111 (downcase (substring
15112 tg (if (= (string-to-char tg) ?@) 1 0)))))
15113 (if (or (rassoc c1 ntable) (rassoc c1 table))
15114 (while (or (rassoc char ntable) (rassoc char table))
15115 (setq char (1+ char)))
15116 (setq c2 c1))
15117 (setq c (or c2 char)))
15118 (when ingroup (push tg (car groups)))
15119 (setq tg (org-add-props tg nil 'face
15120 (cond
15121 ((not (assoc tg table))
15122 (org-get-todo-face tg))
15123 ((member tg current) c-face)
15124 ((member tg inherited) i-face))))
15125 (when (equal (caar tbl) :grouptags)
15126 (org-add-props tg nil 'face 'org-tag-group))
15127 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15128 (insert "[" c "] " tg (make-string
15129 (- fwidth 4 (length tg)) ?\ ))
15130 (push (cons tg c) ntable)
15131 (when (= (cl-incf cnt) ncol)
15132 (insert "\n")
15133 (when (or ingroup intaggroup) (insert " "))
15134 (setq cnt 0)))))
15135 (setq ntable (nreverse ntable))
15136 (insert "\n")
15137 (goto-char (point-min))
15138 (unless expert (org-fit-window-to-buffer))
15139 (setq rtn
15140 (catch 'exit
15141 (while t
15142 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15143 (if (not groups) "no " "")
15144 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15145 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15146 (setq org-last-tag-selection-key c)
15147 (cond
15148 ((= c ?\r) (throw 'exit t))
15149 ((= c ?!)
15150 (setq groups (not groups))
15151 (goto-char (point-min))
15152 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15153 ((= c ?\C-c)
15154 (if (not expert)
15155 (org-fast-tag-show-exit
15156 (setq exit-after-next (not exit-after-next)))
15157 (setq expert nil)
15158 (delete-other-windows)
15159 (set-window-buffer (split-window-vertically) " *Org tags*")
15160 (org-switch-to-buffer-other-window " *Org tags*")
15161 (org-fit-window-to-buffer)))
15162 ((or (= c ?\C-g)
15163 (and (= c ?q) (not (rassoc c ntable))))
15164 (delete-overlay org-tags-overlay)
15165 (setq quit-flag t))
15166 ((= c ?\ )
15167 (setq current nil)
15168 (when exit-after-next (setq exit-after-next 'now)))
15169 ((= c ?\t)
15170 (condition-case nil
15171 (setq tg (completing-read
15172 "Tag: "
15173 (or buffer-tags
15174 (with-current-buffer buf
15175 (setq buffer-tags
15176 (org-get-buffer-tags))))))
15177 (quit (setq tg "")))
15178 (when (string-match "\\S-" tg)
15179 (cl-pushnew (list tg) buffer-tags :test #'equal)
15180 (if (member tg current)
15181 (setq current (delete tg current))
15182 (push tg current)))
15183 (when exit-after-next (setq exit-after-next 'now)))
15184 ((setq e (rassoc c todo-table) tg (car e))
15185 (with-current-buffer buf
15186 (save-excursion (org-todo tg)))
15187 (when exit-after-next (setq exit-after-next 'now)))
15188 ((setq e (rassoc c ntable) tg (car e))
15189 (if (member tg current)
15190 (setq current (delete tg current))
15191 (cl-loop for g in groups do
15192 (when (member tg g)
15193 (dolist (x g) (setq current (delete x current)))))
15194 (push tg current))
15195 (when exit-after-next (setq exit-after-next 'now))))
15197 ;; Create a sorted list
15198 (setq current
15199 (sort current
15200 (lambda (a b)
15201 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15202 (when (eq exit-after-next 'now) (throw 'exit t))
15203 (goto-char (point-min))
15204 (beginning-of-line 2)
15205 (delete-region (point) (point-at-eol))
15206 (org-fast-tag-insert "Current" current c-face)
15207 (org-set-current-tags-overlay current ov-prefix)
15208 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15209 (setq tg (match-string 1))
15210 (add-text-properties
15211 (match-beginning 1) (match-end 1)
15212 (list 'face
15213 (cond
15214 ((member tg current) c-face)
15215 ((member tg inherited) i-face)
15216 (t (get-text-property (match-beginning 1) 'face))))))
15217 (goto-char (point-min)))))
15218 (delete-overlay org-tags-overlay)
15219 (if rtn
15220 (mapconcat 'identity current ":")
15221 nil))))
15223 (defun org-get-tags-string ()
15224 "Get the TAGS string in the current headline."
15225 (unless (org-at-heading-p t)
15226 (user-error "Not on a heading"))
15227 (save-excursion
15228 (beginning-of-line 1)
15229 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15230 (match-string-no-properties 1)
15231 "")))
15233 (defun org-get-tags ()
15234 "Get the list of tags specified in the current headline."
15235 (org-split-string (org-get-tags-string) ":"))
15237 (defun org-get-buffer-tags ()
15238 "Get a table of all tags used in the buffer, for completion."
15239 (org-with-wide-buffer
15240 (goto-char (point-min))
15241 (let ((tag-re (concat org-outline-regexp-bol
15242 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15243 tags)
15244 (while (re-search-forward tag-re nil t)
15245 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15246 (push tag tags)))
15247 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15249 ;;;; The mapping API
15251 (defvar org-agenda-skip-comment-trees)
15252 (defvar org-agenda-skip-function)
15253 (defun org-map-entries (func &optional match scope &rest skip)
15254 "Call FUNC at each headline selected by MATCH in SCOPE.
15256 FUNC is a function or a lisp form. The function will be called without
15257 arguments, with the cursor positioned at the beginning of the headline.
15258 The return values of all calls to the function will be collected and
15259 returned as a list.
15261 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15262 does not need to preserve point. After evaluation, the cursor will be
15263 moved to the end of the line (presumably of the headline of the
15264 processed entry) and search continues from there. Under some
15265 circumstances, this may not produce the wanted results. For example,
15266 if you have removed (e.g. archived) the current (sub)tree it could
15267 mean that the next entry will be skipped entirely. In such cases, you
15268 can specify the position from where search should continue by making
15269 FUNC set the variable `org-map-continue-from' to the desired buffer
15270 position.
15272 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15273 Only headlines that are matched by this query will be considered during
15274 the iteration. When MATCH is nil or t, all headlines will be
15275 visited by the iteration.
15277 SCOPE determines the scope of this command. It can be any of:
15279 nil The current buffer, respecting the restriction if any
15280 tree The subtree started with the entry at point
15281 region The entries within the active region, if any
15282 region-start-level
15283 The entries within the active region, but only those at
15284 the same level than the first one.
15285 file The current buffer, without restriction
15286 file-with-archives
15287 The current buffer, and any archives associated with it
15288 agenda All agenda files
15289 agenda-with-archives
15290 All agenda files with any archive files associated with them
15291 \(file1 file2 ...)
15292 If this is a list, all files in the list will be scanned
15294 The remaining args are treated as settings for the skipping facilities of
15295 the scanner. The following items can be given here:
15297 archive skip trees with the archive tag
15298 comment skip trees with the COMMENT keyword
15299 function or Emacs Lisp form:
15300 will be used as value for `org-agenda-skip-function', so
15301 whenever the function returns a position, FUNC will not be
15302 called for that entry and search will continue from the
15303 position returned
15305 If your function needs to retrieve the tags including inherited tags
15306 at the *current* entry, you can use the value of the variable
15307 `org-scanner-tags' which will be much faster than getting the value
15308 with `org-get-tags-at'. If your function gets properties with
15309 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15310 to t around the call to `org-entry-properties' to get the same speedup.
15311 Note that if your function moves around to retrieve tags and properties at
15312 a *different* entry, you cannot use these techniques."
15313 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15314 (not (org-region-active-p)))
15315 (let* ((org-agenda-archives-mode nil) ; just to make sure
15316 (org-agenda-skip-archived-trees (memq 'archive skip))
15317 (org-agenda-skip-comment-trees (memq 'comment skip))
15318 (org-agenda-skip-function
15319 (car (org-delete-all '(comment archive) skip)))
15320 (org-tags-match-list-sublevels t)
15321 (start-level (eq scope 'region-start-level))
15322 matcher res
15323 org-todo-keywords-for-agenda
15324 org-done-keywords-for-agenda
15325 org-todo-keyword-alist-for-agenda
15326 org-tag-alist-for-agenda
15327 org--matcher-tags-todo-only)
15329 (cond
15330 ((eq match t) (setq matcher t))
15331 ((eq match nil) (setq matcher t))
15332 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15334 (save-excursion
15335 (save-restriction
15336 (cond ((eq scope 'tree)
15337 (org-back-to-heading t)
15338 (org-narrow-to-subtree)
15339 (setq scope nil))
15340 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15341 (org-region-active-p))
15342 ;; If needed, set start-level to a string like "2"
15343 (when start-level
15344 (save-excursion
15345 (goto-char (region-beginning))
15346 (unless (org-at-heading-p) (outline-next-heading))
15347 (setq start-level (org-current-level))))
15348 (narrow-to-region (region-beginning)
15349 (save-excursion
15350 (goto-char (region-end))
15351 (unless (and (bolp) (org-at-heading-p))
15352 (outline-next-heading))
15353 (point)))
15354 (setq scope nil)))
15356 (if (not scope)
15357 (progn
15358 (org-agenda-prepare-buffers
15359 (and buffer-file-name (list buffer-file-name)))
15360 (setq res
15361 (org-scan-tags
15362 func matcher org--matcher-tags-todo-only start-level)))
15363 ;; Get the right scope
15364 (cond
15365 ((and scope (listp scope) (symbolp (car scope)))
15366 (setq scope (eval scope)))
15367 ((eq scope 'agenda)
15368 (setq scope (org-agenda-files t)))
15369 ((eq scope 'agenda-with-archives)
15370 (setq scope (org-agenda-files t))
15371 (setq scope (org-add-archive-files scope)))
15372 ((eq scope 'file)
15373 (setq scope (and buffer-file-name (list buffer-file-name))))
15374 ((eq scope 'file-with-archives)
15375 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15376 (org-agenda-prepare-buffers scope)
15377 (dolist (file scope)
15378 (with-current-buffer (org-find-base-buffer-visiting file)
15379 (org-with-wide-buffer
15380 (goto-char (point-min))
15381 (setq res
15382 (append
15384 (org-scan-tags
15385 func matcher org--matcher-tags-todo-only)))))))))
15386 res)))
15388 ;;; Properties API
15390 (defconst org-special-properties
15391 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15392 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15393 "The special properties valid in Org mode.
15394 These are properties that are not defined in the property drawer,
15395 but in some other way.")
15397 (defconst org-default-properties
15398 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15399 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15400 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15401 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15402 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15403 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15404 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15405 "Some properties that are used by Org mode for various purposes.
15406 Being in this list makes sure that they are offered for completion.")
15408 (defun org--valid-property-p (property)
15409 "Non nil when string PROPERTY is a valid property name."
15410 (not
15411 (or (equal property "")
15412 (string-match-p "\\s-" property))))
15414 (defun org--update-property-plist (key val props)
15415 "Associate KEY to VAL in alist PROPS.
15416 Modifications are made by side-effect. Return new alist."
15417 (let* ((appending (string= (substring key -1) "+"))
15418 (key (if appending (substring key 0 -1) key))
15419 (old (assoc-string key props t)))
15420 (if (not old) (cons (cons key val) props)
15421 (setcdr old (if appending (concat (cdr old) " " val) val))
15422 props)))
15424 (defun org-get-property-block (&optional beg force)
15425 "Return the (beg . end) range of the body of the property drawer.
15426 BEG is the beginning of the current subtree, or of the part
15427 before the first headline. If it is not given, it will be found.
15428 If the drawer does not exist, create it if FORCE is non-nil, or
15429 return nil."
15430 (org-with-wide-buffer
15431 (when beg (goto-char beg))
15432 (unless (org-before-first-heading-p)
15433 (let ((beg (cond (beg)
15434 ((or (not (featurep 'org-inlinetask))
15435 (org-inlinetask-in-task-p))
15436 (org-back-to-heading t))
15437 (t (org-with-limited-levels (org-back-to-heading t))))))
15438 (forward-line)
15439 (when (looking-at-p org-planning-line-re) (forward-line))
15440 (cond ((looking-at org-property-drawer-re)
15441 (forward-line)
15442 (cons (point) (progn (goto-char (match-end 0))
15443 (line-beginning-position))))
15444 (force
15445 (goto-char beg)
15446 (org-insert-property-drawer)
15447 (let ((pos (save-excursion (search-forward ":END:")
15448 (line-beginning-position))))
15449 (cons pos pos))))))))
15451 (defun org-at-property-p ()
15452 "Non-nil when point is inside a property drawer.
15453 See `org-property-re' for match data, if applicable."
15454 (save-excursion
15455 (beginning-of-line)
15456 (and (looking-at org-property-re)
15457 (let ((property-drawer (save-match-data (org-get-property-block))))
15458 (and property-drawer
15459 (>= (point) (car property-drawer))
15460 (< (point) (cdr property-drawer)))))))
15462 (defun org-property-action ()
15463 "Do an action on properties."
15464 (interactive)
15465 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15466 (let ((c (read-char-exclusive)))
15467 (cl-case c
15468 (?s (call-interactively #'org-set-property))
15469 (?d (call-interactively #'org-delete-property))
15470 (?D (call-interactively #'org-delete-property-globally))
15471 (?c (call-interactively #'org-compute-property-at-point))
15472 (otherwise (user-error "No such property action %c" c)))))
15474 (defun org-inc-effort ()
15475 "Increment the value of the effort property in the current entry."
15476 (interactive)
15477 (org-set-effort nil t))
15479 (defvar org-clock-effort) ; Defined in org-clock.el.
15480 (defvar org-clock-current-task) ; Defined in org-clock.el.
15481 (defun org-set-effort (&optional value increment)
15482 "Set the effort property of the current entry.
15483 With numerical prefix arg, use the nth allowed value, 0 stands for the
15484 10th allowed value.
15486 When INCREMENT is non-nil, set the property to the next allowed value."
15487 (interactive "P")
15488 (when (equal value 0) (setq value 10))
15489 (let* ((completion-ignore-case t)
15490 (prop org-effort-property)
15491 (cur (org-entry-get nil prop))
15492 (allowed (org-property-get-allowed-values nil prop 'table))
15493 (existing (mapcar 'list (org-property-values prop)))
15494 (heading (nth 4 (org-heading-components)))
15496 (val (cond
15497 ((stringp value) value)
15498 ((and allowed (integerp value))
15499 (or (car (nth (1- value) allowed))
15500 (car (org-last allowed))))
15501 ((and allowed increment)
15502 (or (cl-caadr (member (list cur) allowed))
15503 (user-error "Allowed effort values are not set")))
15504 (allowed
15505 (message "Select 1-9,0, [RET%s]: %s"
15506 (if cur (concat "=" cur) "")
15507 (mapconcat 'car allowed " "))
15508 (setq rpl (read-char-exclusive))
15509 (if (equal rpl ?\r)
15511 (setq rpl (- rpl ?0))
15512 (when (equal rpl 0) (setq rpl 10))
15513 (if (and (> rpl 0) (<= rpl (length allowed)))
15514 (car (nth (1- rpl) allowed))
15515 (org-completing-read "Effort: " allowed nil))))
15517 (org-completing-read
15518 (concat "Effort" (and cur (string-match "\\S-" cur)
15519 (concat " [" cur "]"))
15520 ": ")
15521 existing nil nil "" nil cur)))))
15522 (unless (equal (org-entry-get nil prop) val)
15523 (org-entry-put nil prop val))
15524 (org-refresh-property
15525 '((effort . identity)
15526 (effort-minutes . org-duration-to-minutes))
15527 val)
15528 (when (equal heading (bound-and-true-p org-clock-current-task))
15529 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15530 (org-clock-update-mode-line))
15531 (message "%s is now %s" prop val)))
15533 (defun org-entry-properties (&optional pom which)
15534 "Get all properties of the current entry.
15536 When POM is a buffer position, get all properties from the entry
15537 there instead.
15539 This includes the TODO keyword, the tags, time strings for
15540 deadline, scheduled, and clocking, and any additional properties
15541 defined in the entry.
15543 If WHICH is nil or `all', get all properties. If WHICH is
15544 `special' or `standard', only get that subclass. If WHICH is
15545 a string, only get that property.
15547 Return value is an alist. Keys are properties, as upcased
15548 strings."
15549 (org-with-point-at pom
15550 (when (and (derived-mode-p 'org-mode)
15551 (ignore-errors (org-back-to-heading t)))
15552 (catch 'exit
15553 (let* ((beg (point))
15554 (specific (and (stringp which) (upcase which)))
15555 (which (cond ((not specific) which)
15556 ((member specific org-special-properties) 'special)
15557 (t 'standard)))
15558 props)
15559 ;; Get the special properties, like TODO and TAGS.
15560 (when (memq which '(nil all special))
15561 (when (or (not specific) (string= specific "CLOCKSUM"))
15562 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15563 (when clocksum
15564 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15565 props)))
15566 (when specific (throw 'exit props)))
15567 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15568 (let ((clocksumt (get-text-property (point)
15569 :org-clock-minutes-today)))
15570 (when clocksumt
15571 (push (cons "CLOCKSUM_T"
15572 (org-duration-from-minutes clocksumt))
15573 props)))
15574 (when specific (throw 'exit props)))
15575 (when (or (not specific) (string= specific "ITEM"))
15576 (let ((case-fold-search nil))
15577 (when (looking-at org-complex-heading-regexp)
15578 (push (cons "ITEM"
15579 (let ((title (match-string-no-properties 4)))
15580 (if (org-string-nw-p title)
15581 (org-remove-tabs title)
15582 "")))
15583 props)))
15584 (when specific (throw 'exit props)))
15585 (when (or (not specific) (string= specific "TODO"))
15586 (let ((case-fold-search nil))
15587 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15588 (push (cons "TODO" (match-string-no-properties 2)) props)))
15589 (when specific (throw 'exit props)))
15590 (when (or (not specific) (string= specific "PRIORITY"))
15591 (push (cons "PRIORITY"
15592 (if (looking-at org-priority-regexp)
15593 (match-string-no-properties 2)
15594 (char-to-string org-default-priority)))
15595 props)
15596 (when specific (throw 'exit props)))
15597 (when (or (not specific) (string= specific "FILE"))
15598 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15599 props)
15600 (when specific (throw 'exit props)))
15601 (when (or (not specific) (string= specific "TAGS"))
15602 (let ((value (org-string-nw-p (org-get-tags-string))))
15603 (when value (push (cons "TAGS" value) props)))
15604 (when specific (throw 'exit props)))
15605 (when (or (not specific) (string= specific "ALLTAGS"))
15606 (let ((value (org-get-tags-at)))
15607 (when value
15608 (push (cons "ALLTAGS"
15609 (format ":%s:" (mapconcat #'identity value ":")))
15610 props)))
15611 (when specific (throw 'exit props)))
15612 (when (or (not specific) (string= specific "BLOCKED"))
15613 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15614 (when specific (throw 'exit props)))
15615 (when (or (not specific)
15616 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15617 (forward-line)
15618 (when (looking-at-p org-planning-line-re)
15619 (end-of-line)
15620 (let ((bol (line-beginning-position))
15621 ;; Backward compatibility: time keywords used to
15622 ;; be configurable (before 8.3). Make sure we
15623 ;; get the correct keyword.
15624 (key-assoc `(("CLOSED" . ,org-closed-string)
15625 ("DEADLINE" . ,org-deadline-string)
15626 ("SCHEDULED" . ,org-scheduled-string))))
15627 (dolist (pair (if specific (list (assoc specific key-assoc))
15628 key-assoc))
15629 (save-excursion
15630 (when (search-backward (cdr pair) bol t)
15631 (goto-char (match-end 0))
15632 (skip-chars-forward " \t")
15633 (and (looking-at org-ts-regexp-both)
15634 (push (cons (car pair)
15635 (match-string-no-properties 0))
15636 props)))))))
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific)
15639 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15640 (let ((find-ts
15641 (lambda (end ts)
15642 ;; Fix next time-stamp before END. TS is the
15643 ;; list of time-stamps found so far.
15644 (let ((ts ts)
15645 (regexp (cond
15646 ((string= specific "TIMESTAMP")
15647 org-ts-regexp)
15648 ((string= specific "TIMESTAMP_IA")
15649 org-ts-regexp-inactive)
15650 ((assoc "TIMESTAMP_IA" ts)
15651 org-ts-regexp)
15652 ((assoc "TIMESTAMP" ts)
15653 org-ts-regexp-inactive)
15654 (t org-ts-regexp-both))))
15655 (catch 'next
15656 (while (re-search-forward regexp end t)
15657 (backward-char)
15658 (let ((object (org-element-context)))
15659 ;; Accept to match timestamps in node
15660 ;; properties, too.
15661 (when (memq (org-element-type object)
15662 '(node-property timestamp))
15663 (let ((type
15664 (org-element-property :type object)))
15665 (cond
15666 ((and (memq type '(active active-range))
15667 (not (equal specific "TIMESTAMP_IA")))
15668 (unless (assoc "TIMESTAMP" ts)
15669 (push (cons "TIMESTAMP"
15670 (org-element-property
15671 :raw-value object))
15673 (when specific (throw 'exit ts))))
15674 ((and (memq type '(inactive inactive-range))
15675 (not (string= specific "TIMESTAMP")))
15676 (unless (assoc "TIMESTAMP_IA" ts)
15677 (push (cons "TIMESTAMP_IA"
15678 (org-element-property
15679 :raw-value object))
15681 (when specific (throw 'exit ts))))))
15682 ;; Both timestamp types are found,
15683 ;; move to next part.
15684 (when (= (length ts) 2) (throw 'next ts)))))
15685 ts)))))
15686 (goto-char beg)
15687 ;; First look for timestamps within headline.
15688 (let ((ts (funcall find-ts (line-end-position) nil)))
15689 (if (= (length ts) 2) (setq props (nconc ts props))
15690 ;; Then find timestamps in the section, skipping
15691 ;; planning line.
15692 (let ((end (save-excursion (outline-next-heading))))
15693 (forward-line)
15694 (when (looking-at-p org-planning-line-re) (forward-line))
15695 (setq props (nconc (funcall find-ts end ts) props))))))))
15696 ;; Get the standard properties, like :PROP:.
15697 (when (memq which '(nil all standard))
15698 ;; If we are looking after a specific property, delegate
15699 ;; to `org-entry-get', which is faster. However, make an
15700 ;; exception for "CATEGORY", since it can be also set
15701 ;; through keywords (i.e. #+CATEGORY).
15702 (if (and specific (not (equal specific "CATEGORY")))
15703 (let ((value (org-entry-get beg specific nil t)))
15704 (throw 'exit (and value (list (cons specific value)))))
15705 (let ((range (org-get-property-block beg)))
15706 (when range
15707 (let ((end (cdr range)) seen-base)
15708 (goto-char (car range))
15709 ;; Unlike to `org--update-property-plist', we
15710 ;; handle the case where base values is found
15711 ;; after its extension. We also forbid standard
15712 ;; properties to be named as special properties.
15713 (while (re-search-forward org-property-re end t)
15714 (let* ((key (upcase (match-string-no-properties 2)))
15715 (extendp (string-match-p "\\+\\'" key))
15716 (key-base (if extendp (substring key 0 -1) key))
15717 (value (match-string-no-properties 3)))
15718 (cond
15719 ((member-ignore-case key-base org-special-properties))
15720 (extendp
15721 (setq props
15722 (org--update-property-plist key value props)))
15723 ((member key seen-base))
15724 (t (push key seen-base)
15725 (let ((p (assoc-string key props t)))
15726 (if p (setcdr p (concat value " " (cdr p)))
15727 (push (cons key value) props))))))))))))
15728 (unless (assoc "CATEGORY" props)
15729 (push (cons "CATEGORY" (org-get-category beg)) props)
15730 (when (string= specific "CATEGORY") (throw 'exit props)))
15731 ;; Return value.
15732 props)))))
15734 (defun org--property-local-values (property literal-nil)
15735 "Return value for PROPERTY in current entry.
15736 Value is a list whose car is the base value for PROPERTY and cdr
15737 a list of accumulated values. Return nil if neither is found in
15738 the entry. Also return nil when PROPERTY is set to \"nil\",
15739 unless LITERAL-NIL is non-nil."
15740 (let ((range (org-get-property-block)))
15741 (when range
15742 (goto-char (car range))
15743 (let* ((case-fold-search t)
15744 (end (cdr range))
15745 (value
15746 ;; Base value.
15747 (save-excursion
15748 (let ((v (and (re-search-forward
15749 (org-re-property property nil t) end t)
15750 (match-string-no-properties 3))))
15751 (list (if literal-nil v (org-not-nil v)))))))
15752 ;; Find additional values.
15753 (let* ((property+ (org-re-property (concat property "+") nil t)))
15754 (while (re-search-forward property+ end t)
15755 (push (match-string-no-properties 3) value)))
15756 ;; Return final values.
15757 (and (not (equal value '(nil))) (nreverse value))))))
15759 (defun org--property-global-value (property literal-nil)
15760 "Return value for PROPERTY in current buffer.
15761 Return value is a string. Return nil if property is not set
15762 globally. Also return nil when PROPERTY is set to \"nil\",
15763 unless LITERAL-NIL is non-nil."
15764 (let ((global
15765 (cdr (or (assoc-string property org-file-properties t)
15766 (assoc-string property org-global-properties t)
15767 (assoc-string property org-global-properties-fixed t)))))
15768 (if literal-nil global (org-not-nil global))))
15770 (defun org-entry-get (pom property &optional inherit literal-nil)
15771 "Get value of PROPERTY for entry or content at point-or-marker POM.
15773 If INHERIT is non-nil and the entry does not have the property,
15774 then also check higher levels of the hierarchy. If INHERIT is
15775 the symbol `selective', use inheritance only if the setting in
15776 `org-use-property-inheritance' selects PROPERTY for inheritance.
15778 If the property is present but empty, the return value is the
15779 empty string. If the property is not present at all, nil is
15780 returned. In any other case, return the value as a string.
15781 Search is case-insensitive.
15783 If LITERAL-NIL is set, return the string value \"nil\" as
15784 a string, do not interpret it as the list atom nil. This is used
15785 for inheritance when a \"nil\" value can supersede a non-nil
15786 value higher up the hierarchy."
15787 (org-with-point-at pom
15788 (cond
15789 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15790 ;; We need a special property. Use `org-entry-properties' to
15791 ;; retrieve it, but specify the wanted property.
15792 (cdr (assoc-string property (org-entry-properties nil property))))
15793 ((and inherit
15794 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15795 (org-entry-get-with-inheritance property literal-nil))
15797 (let* ((local (org--property-local-values property literal-nil))
15798 (value (and local (mapconcat #'identity (delq nil local) " "))))
15799 (if literal-nil value (org-not-nil value)))))))
15801 (defun org-property-or-variable-value (var &optional inherit)
15802 "Check if there is a property fixing the value of VAR.
15803 If yes, return this value. If not, return the current value of the variable."
15804 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15805 (if (and prop (stringp prop) (string-match "\\S-" prop))
15806 (read prop)
15807 (symbol-value var))))
15809 (defun org-entry-delete (pom property)
15810 "Delete PROPERTY from entry at point-or-marker POM.
15811 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15812 non-nil when a property was removed."
15813 (org-with-point-at pom
15814 (pcase (org-get-property-block)
15815 (`(,begin . ,origin)
15816 (let* ((end (copy-marker origin))
15817 (re (org-re-property
15818 (concat (regexp-quote property) "\\+?") t t)))
15819 (goto-char begin)
15820 (while (re-search-forward re end t)
15821 (delete-region (match-beginning 0) (line-beginning-position 2)))
15822 ;; If drawer is empty, remove it altogether.
15823 (when (= begin end)
15824 (delete-region (line-beginning-position 0)
15825 (line-beginning-position 2)))
15826 ;; Return non-nil if some property was removed.
15827 (prog1 (/= end origin) (set-marker end nil))))
15828 (_ nil))))
15830 ;; Multi-values properties are properties that contain multiple values
15831 ;; These values are assumed to be single words, separated by whitespace.
15832 (defun org-entry-add-to-multivalued-property (pom property value)
15833 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15834 (let* ((old (org-entry-get pom property))
15835 (values (and old (org-split-string old "[ \t]"))))
15836 (setq value (org-entry-protect-space value))
15837 (unless (member value values)
15838 (setq values (append values (list value)))
15839 (org-entry-put pom property
15840 (mapconcat 'identity values " ")))))
15842 (defun org-entry-remove-from-multivalued-property (pom property value)
15843 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15844 (let* ((old (org-entry-get pom property))
15845 (values (and old (org-split-string old "[ \t]"))))
15846 (setq value (org-entry-protect-space value))
15847 (when (member value values)
15848 (setq values (delete value values))
15849 (org-entry-put pom property
15850 (mapconcat 'identity values " ")))))
15852 (defun org-entry-member-in-multivalued-property (pom property value)
15853 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15854 (let* ((old (org-entry-get pom property))
15855 (values (and old (org-split-string old "[ \t]"))))
15856 (setq value (org-entry-protect-space value))
15857 (member value values)))
15859 (defun org-entry-get-multivalued-property (pom property)
15860 "Return a list of values in a multivalued property."
15861 (let* ((value (org-entry-get pom property))
15862 (values (and value (org-split-string value "[ \t]"))))
15863 (mapcar 'org-entry-restore-space values)))
15865 (defun org-entry-put-multivalued-property (pom property &rest values)
15866 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15867 VALUES should be a list of strings. Spaces will be protected."
15868 (org-entry-put pom property
15869 (mapconcat 'org-entry-protect-space values " "))
15870 (let* ((value (org-entry-get pom property))
15871 (values (and value (org-split-string value "[ \t]"))))
15872 (mapcar 'org-entry-restore-space values)))
15874 (defun org-entry-protect-space (s)
15875 "Protect spaces and newline in string S."
15876 (while (string-match " " s)
15877 (setq s (replace-match "%20" t t s)))
15878 (while (string-match "\n" s)
15879 (setq s (replace-match "%0A" t t s)))
15882 (defun org-entry-restore-space (s)
15883 "Restore spaces and newline in string S."
15884 (while (string-match "%20" s)
15885 (setq s (replace-match " " t t s)))
15886 (while (string-match "%0A" s)
15887 (setq s (replace-match "\n" t t s)))
15890 (defvar org-entry-property-inherited-from (make-marker)
15891 "Marker pointing to the entry from where a property was inherited.
15892 Each call to `org-entry-get-with-inheritance' will set this marker to the
15893 location of the entry where the inheritance search matched. If there was
15894 no match, the marker will point nowhere.
15895 Note that also `org-entry-get' calls this function, if the INHERIT flag
15896 is set.")
15898 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15899 "Get PROPERTY of entry or content at point, search higher levels if needed.
15900 The search will stop at the first ancestor which has the property defined.
15901 If the value found is \"nil\", return nil to show that the property
15902 should be considered as undefined (this is the meaning of nil here).
15903 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15904 (move-marker org-entry-property-inherited-from nil)
15905 (org-with-wide-buffer
15906 (let (value)
15907 (catch 'exit
15908 (while t
15909 (let ((v (org--property-local-values property literal-nil)))
15910 (when v
15911 (setq value
15912 (concat (mapconcat #'identity (delq nil v) " ")
15913 (and value " ")
15914 value)))
15915 (cond
15916 ((car v)
15917 (org-back-to-heading t)
15918 (move-marker org-entry-property-inherited-from (point))
15919 (throw 'exit nil))
15920 ((org-up-heading-safe))
15922 (let ((global (org--property-global-value property literal-nil)))
15923 (cond ((not global))
15924 (value (setq value (concat global " " value)))
15925 (t (setq value global))))
15926 (throw 'exit nil))))))
15927 (if literal-nil value (org-not-nil value)))))
15929 (defvar org-property-changed-functions nil
15930 "Hook called when the value of a property has changed.
15931 Each hook function should accept two arguments, the name of the property
15932 and the new value.")
15934 (defun org-entry-put (pom property value)
15935 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15937 If the value is nil, it is converted to the empty string. If it
15938 is not a string, an error is raised. Also raise an error on
15939 invalid property names.
15941 PROPERTY can be any regular property (see
15942 `org-special-properties'). It can also be \"TODO\",
15943 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15945 For the last two properties, VALUE may have any of the special
15946 values \"earlier\" and \"later\". The function then increases or
15947 decreases scheduled or deadline date by one day."
15948 (cond ((null value) (setq value ""))
15949 ((not (stringp value)) (error "Properties values should be strings"))
15950 ((not (org--valid-property-p property))
15951 (user-error "Invalid property name: \"%s\"" property)))
15952 (org-with-point-at pom
15953 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15954 (org-back-to-heading t)
15955 (org-with-limited-levels (org-back-to-heading t)))
15956 (let ((beg (point)))
15957 (cond
15958 ((equal property "TODO")
15959 (cond ((not (org-string-nw-p value)) (setq value 'none))
15960 ((not (member value org-todo-keywords-1))
15961 (user-error "\"%s\" is not a valid TODO state" value)))
15962 (org-todo value)
15963 (org-set-tags nil 'align))
15964 ((equal property "PRIORITY")
15965 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15966 (org-set-tags nil 'align))
15967 ((equal property "SCHEDULED")
15968 (forward-line)
15969 (if (and (looking-at-p org-planning-line-re)
15970 (re-search-forward
15971 org-scheduled-time-regexp (line-end-position) t))
15972 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15973 ((string= value "later") (org-timestamp-change 1 'day))
15974 ((string= value "") (org-schedule '(4)))
15975 (t (org-schedule nil value)))
15976 (if (member value '("earlier" "later" ""))
15977 (call-interactively #'org-schedule)
15978 (org-schedule nil value))))
15979 ((equal property "DEADLINE")
15980 (forward-line)
15981 (if (and (looking-at-p org-planning-line-re)
15982 (re-search-forward
15983 org-deadline-time-regexp (line-end-position) t))
15984 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15985 ((string= value "later") (org-timestamp-change 1 'day))
15986 ((string= value "") (org-deadline '(4)))
15987 (t (org-deadline nil value)))
15988 (if (member value '("earlier" "later" ""))
15989 (call-interactively #'org-deadline)
15990 (org-deadline nil value))))
15991 ((member property org-special-properties)
15992 (error "The %s property cannot be set with `org-entry-put'" property))
15994 (let* ((range (org-get-property-block beg 'force))
15995 (end (cdr range))
15996 (case-fold-search t))
15997 (goto-char (car range))
15998 (if (re-search-forward (org-re-property property nil t) end t)
15999 (progn (delete-region (match-beginning 0) (match-end 0))
16000 (goto-char (match-beginning 0)))
16001 (goto-char end)
16002 (insert "\n")
16003 (backward-char))
16004 (insert ":" property ":")
16005 (when value (insert " " value))
16006 (org-indent-line)))))
16007 (run-hook-with-args 'org-property-changed-functions property value)))
16009 (defun org-buffer-property-keys
16010 (&optional specials defaults columns ignore-malformed)
16011 "Get all property keys in the current buffer.
16013 When SPECIALS is non-nil, also list the special properties that
16014 reflect things like tags and TODO state.
16016 When DEFAULTS is non-nil, also include properties that has
16017 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16018 DESCRIPTION, LOCATION, and LOGGING and others.
16020 When COLUMNS in non-nil, also include property names given in
16021 COLUMN formats in the current buffer.
16023 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16024 automatically performed, such drawers will be silently ignored."
16025 (let ((case-fold-search t)
16026 (props (append
16027 (and specials org-special-properties)
16028 (and defaults (cons org-effort-property org-default-properties))
16029 nil)))
16030 (org-with-wide-buffer
16031 (goto-char (point-min))
16032 (while (re-search-forward org-property-start-re nil t)
16033 (let ((range (org-get-property-block)))
16034 (catch 'skip
16035 (unless range
16036 (when (and (not ignore-malformed)
16037 (not (org-before-first-heading-p))
16038 (y-or-n-p (format "Malformed drawer at %d, repair?"
16039 (line-beginning-position))))
16040 (org-get-property-block nil t))
16041 (throw 'skip nil))
16042 (goto-char (car range))
16043 (let ((begin (car range))
16044 (end (cdr range)))
16045 ;; Make sure that found property block is not located
16046 ;; before current point, as it would generate an infloop.
16047 ;; It can happen, for example, in the following
16048 ;; situation:
16050 ;; * Headline
16051 ;; :PROPERTIES:
16052 ;; ...
16053 ;; :END:
16054 ;; *************** Inlinetask
16055 ;; #+BEGIN_EXAMPLE
16056 ;; :PROPERTIES:
16057 ;; #+END_EXAMPLE
16059 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16060 (while (< (point) end)
16061 (let ((p (progn (looking-at org-property-re)
16062 (match-string-no-properties 2))))
16063 ;; Only add true property name, not extension symbol.
16064 (push (if (not (string-match-p "\\+\\'" p)) p
16065 (substring p 0 -1))
16066 props))
16067 (forward-line))))
16068 (outline-next-heading)))
16069 (when columns
16070 (goto-char (point-min))
16071 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16072 (let ((element (org-element-at-point)))
16073 (when (memq (org-element-type element) '(keyword node-property))
16074 (let ((value (org-element-property :value element))
16075 (start 0))
16076 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16077 (setq start (match-end 0))
16078 (let ((p (match-string-no-properties 1 value)))
16079 (unless (member-ignore-case p org-special-properties)
16080 (push p props))))))))))
16081 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16083 (defun org-property-values (key)
16084 "List all non-nil values of property KEY in current buffer."
16085 (org-with-wide-buffer
16086 (goto-char (point-min))
16087 (let ((case-fold-search t)
16088 (re (org-re-property key))
16089 values)
16090 (while (re-search-forward re nil t)
16091 (push (org-entry-get (point) key) values))
16092 (delete-dups values))))
16094 (defun org-insert-property-drawer ()
16095 "Insert a property drawer into the current entry."
16096 (org-with-wide-buffer
16097 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16098 (org-back-to-heading t)
16099 (org-with-limited-levels (org-back-to-heading t)))
16100 (forward-line)
16101 (when (looking-at-p org-planning-line-re) (forward-line))
16102 (unless (looking-at-p org-property-drawer-re)
16103 ;; Make sure we start editing a line from current entry, not from
16104 ;; next one. It prevents extending text properties or overlays
16105 ;; belonging to the latter.
16106 (when (bolp) (backward-char))
16107 (let ((begin (1+ (point)))
16108 (inhibit-read-only t))
16109 (insert "\n:PROPERTIES:\n:END:")
16110 (when (eobp) (insert "\n"))
16111 (org-indent-region begin (point))))))
16113 (defun org-insert-drawer (&optional arg drawer)
16114 "Insert a drawer at point.
16116 When optional argument ARG is non-nil, insert a property drawer.
16118 Optional argument DRAWER, when non-nil, is a string representing
16119 drawer's name. Otherwise, the user is prompted for a name.
16121 If a region is active, insert the drawer around that region
16122 instead.
16124 Point is left between drawer's boundaries."
16125 (interactive "P")
16126 (let* ((drawer (if arg "PROPERTIES"
16127 (or drawer (read-from-minibuffer "Drawer: ")))))
16128 (cond
16129 ;; With C-u, fall back on `org-insert-property-drawer'
16130 (arg (org-insert-property-drawer))
16131 ;; Check validity of suggested drawer's name.
16132 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16133 (user-error "Invalid drawer name"))
16134 ;; With an active region, insert a drawer at point.
16135 ((not (org-region-active-p))
16136 (progn
16137 (unless (bolp) (insert "\n"))
16138 (insert (format ":%s:\n\n:END:\n" drawer))
16139 (forward-line -2)))
16140 ;; Otherwise, insert the drawer at point
16142 (let ((rbeg (region-beginning))
16143 (rend (copy-marker (region-end))))
16144 (unwind-protect
16145 (progn
16146 (goto-char rbeg)
16147 (beginning-of-line)
16148 (when (save-excursion
16149 (re-search-forward org-outline-regexp-bol rend t))
16150 (user-error "Drawers cannot contain headlines"))
16151 ;; Position point at the beginning of the first
16152 ;; non-blank line in region. Insert drawer's opening
16153 ;; there, then indent it.
16154 (org-skip-whitespace)
16155 (beginning-of-line)
16156 (insert ":" drawer ":\n")
16157 (forward-line -1)
16158 (indent-for-tab-command)
16159 ;; Move point to the beginning of the first blank line
16160 ;; after the last non-blank line in region. Insert
16161 ;; drawer's closing, then indent it.
16162 (goto-char rend)
16163 (skip-chars-backward " \r\t\n")
16164 (insert "\n:END:")
16165 (deactivate-mark t)
16166 (indent-for-tab-command)
16167 (unless (eolp) (insert "\n")))
16168 ;; Clear marker, whatever the outcome of insertion is.
16169 (set-marker rend nil)))))))
16171 (defvar org-property-set-functions-alist nil
16172 "Property set function alist.
16173 Each entry should have the following format:
16175 (PROPERTY . READ-FUNCTION)
16177 The read function will be called with the same argument as
16178 `org-completing-read'.")
16180 (defun org-set-property-function (property)
16181 "Get the function that should be used to set PROPERTY.
16182 This is computed according to `org-property-set-functions-alist'."
16183 (or (cdr (assoc property org-property-set-functions-alist))
16184 'org-completing-read))
16186 (defun org-read-property-value (property)
16187 "Read PROPERTY value from user."
16188 (let* ((completion-ignore-case t)
16189 (allowed (org-property-get-allowed-values nil property 'table))
16190 (cur (org-entry-get nil property))
16191 (prompt (concat property " value"
16192 (if (and cur (string-match "\\S-" cur))
16193 (concat " [" cur "]") "") ": "))
16194 (set-function (org-set-property-function property))
16195 (val (if allowed
16196 (funcall set-function prompt allowed nil
16197 (not (get-text-property 0 'org-unrestricted
16198 (caar allowed))))
16199 (funcall set-function prompt
16200 (mapcar 'list (org-property-values property))
16201 nil nil "" nil cur))))
16202 (org-trim val)))
16204 (defvar org-last-set-property nil)
16205 (defvar org-last-set-property-value nil)
16206 (defun org-read-property-name ()
16207 "Read a property name."
16208 (let ((completion-ignore-case t)
16209 (default-prop (or (and (org-at-property-p)
16210 (match-string-no-properties 2))
16211 org-last-set-property)))
16212 (org-completing-read
16213 (concat "Property"
16214 (if default-prop (concat " [" default-prop "]") "")
16215 ": ")
16216 (mapcar #'list (org-buffer-property-keys nil t t))
16217 nil nil nil nil default-prop)))
16219 (defun org-set-property-and-value (use-last)
16220 "Allow to set [PROPERTY]: [value] direction from prompt.
16221 When use-default, don't even ask, just use the last
16222 \"[PROPERTY]: [value]\" string from the history."
16223 (interactive "P")
16224 (let* ((completion-ignore-case t)
16225 (pv (or (and use-last org-last-set-property-value)
16226 (org-completing-read
16227 "Enter a \"[Property]: [value]\" pair: "
16228 nil nil nil nil nil
16229 org-last-set-property-value)))
16230 prop val)
16231 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16232 (setq prop (match-string 1 pv)
16233 val (match-string 2 pv))
16234 (org-set-property prop val))))
16236 (defun org-set-property (property value)
16237 "In the current entry, set PROPERTY to VALUE.
16239 When called interactively, this will prompt for a property name, offering
16240 completion on existing and default properties. And then it will prompt
16241 for a value, offering completion either on allowed values (via an inherited
16242 xxx_ALL property) or on existing values in other instances of this property
16243 in the current file.
16245 Throw an error when trying to set a property with an invalid name."
16246 (interactive (list nil nil))
16247 (let ((property (or property (org-read-property-name))))
16248 ;; `org-entry-put' also makes the following check, but this one
16249 ;; avoids polluting `org-last-set-property' and
16250 ;; `org-last-set-property-value' needlessly.
16251 (unless (org--valid-property-p property)
16252 (user-error "Invalid property name: \"%s\"" property))
16253 (let ((value (or value (org-read-property-value property)))
16254 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16255 (setq org-last-set-property property)
16256 (setq org-last-set-property-value (concat property ": " value))
16257 ;; Possibly postprocess the inserted value:
16258 (when fn (setq value (funcall fn value)))
16259 (unless (equal (org-entry-get nil property) value)
16260 (org-entry-put nil property value)))))
16262 (defun org-find-property (property &optional value)
16263 "Find first entry in buffer that sets PROPERTY.
16265 When optional argument VALUE is non-nil, only consider an entry
16266 if it contains PROPERTY set to this value. If PROPERTY should be
16267 explicitly set to nil, use string \"nil\" for VALUE.
16269 Return position where the entry begins, or nil if there is no
16270 such entry. If narrowing is in effect, only search the visible
16271 part of the buffer."
16272 (save-excursion
16273 (goto-char (point-min))
16274 (let ((case-fold-search t)
16275 (re (org-re-property property nil (not value) value)))
16276 (catch 'exit
16277 (while (re-search-forward re nil t)
16278 (when (if value (org-at-property-p)
16279 (org-entry-get (point) property nil t))
16280 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16282 (defun org-delete-property (property)
16283 "In the current entry, delete PROPERTY."
16284 (interactive
16285 (let* ((completion-ignore-case t)
16286 (cat (org-entry-get (point) "CATEGORY"))
16287 (props0 (org-entry-properties nil 'standard))
16288 (props (if cat props0
16289 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16290 (prop (if (< 1 (length props))
16291 (completing-read "Property: " props nil t)
16292 (caar props))))
16293 (list prop)))
16294 (if (not property)
16295 (message "No property to delete in this entry")
16296 (org-entry-delete nil property)
16297 (message "Property \"%s\" deleted" property)))
16299 (defun org-delete-property-globally (property)
16300 "Remove PROPERTY globally, from all entries.
16301 This function ignores narrowing, if any."
16302 (interactive
16303 (let* ((completion-ignore-case t)
16304 (prop (completing-read
16305 "Globally remove property: "
16306 (mapcar #'list (org-buffer-property-keys)))))
16307 (list prop)))
16308 (org-with-wide-buffer
16309 (goto-char (point-min))
16310 (let ((count 0)
16311 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16312 (while (re-search-forward re nil t)
16313 (when (org-entry-delete (point) property) (cl-incf count)))
16314 (message "Property \"%s\" removed from %d entries" property count))))
16316 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16318 (defun org-compute-property-at-point ()
16319 "Compute the property at point.
16320 This looks for an enclosing column format, extracts the operator and
16321 then applies it to the property in the column format's scope."
16322 (interactive)
16323 (unless (org-at-property-p)
16324 (user-error "Not at a property"))
16325 (let ((prop (match-string-no-properties 2)))
16326 (org-columns-get-format-and-top-level)
16327 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16328 (user-error "No operator defined for property %s" prop))
16329 (org-columns-compute prop)))
16331 (defvar org-property-allowed-value-functions nil
16332 "Hook for functions supplying allowed values for a specific property.
16333 The functions must take a single argument, the name of the property, and
16334 return a flat list of allowed values. If \":ETC\" is one of
16335 the values, this means that these values are intended as defaults for
16336 completion, but that other values should be allowed too.
16337 The functions must return nil if they are not responsible for this
16338 property.")
16340 (defun org-property-get-allowed-values (pom property &optional table)
16341 "Get allowed values for the property PROPERTY.
16342 When TABLE is non-nil, return an alist that can directly be used for
16343 completion."
16344 (let (vals)
16345 (cond
16346 ((equal property "TODO")
16347 (setq vals (org-with-point-at pom
16348 (append org-todo-keywords-1 '("")))))
16349 ((equal property "PRIORITY")
16350 (let ((n org-lowest-priority))
16351 (while (>= n org-highest-priority)
16352 (push (char-to-string n) vals)
16353 (setq n (1- n)))))
16354 ((equal property "CATEGORY"))
16355 ((member property org-special-properties))
16356 ((setq vals (run-hook-with-args-until-success
16357 'org-property-allowed-value-functions property)))
16359 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16360 (when (and vals (string-match "\\S-" vals))
16361 (setq vals (car (read-from-string (concat "(" vals ")"))))
16362 (setq vals (mapcar (lambda (x)
16363 (cond ((stringp x) x)
16364 ((numberp x) (number-to-string x))
16365 ((symbolp x) (symbol-name x))
16366 (t "???")))
16367 vals)))))
16368 (when (member ":ETC" vals)
16369 (setq vals (remove ":ETC" vals))
16370 (org-add-props (car vals) '(org-unrestricted t)))
16371 (if table (mapcar 'list vals) vals)))
16373 (defun org-property-previous-allowed-value (&optional _previous)
16374 "Switch to the next allowed value for this property."
16375 (interactive)
16376 (org-property-next-allowed-value t))
16378 (defun org-property-next-allowed-value (&optional previous)
16379 "Switch to the next allowed value for this property."
16380 (interactive)
16381 (unless (org-at-property-p)
16382 (user-error "Not at a property"))
16383 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16384 (key (match-string 2))
16385 (value (match-string 3))
16386 (allowed (or (org-property-get-allowed-values (point) key)
16387 (and (member value '("[ ]" "[-]" "[X]"))
16388 '("[ ]" "[X]"))))
16389 (heading (save-match-data (nth 4 (org-heading-components))))
16390 nval)
16391 (unless allowed
16392 (user-error "Allowed values for this property have not been defined"))
16393 (when previous (setq allowed (reverse allowed)))
16394 (when (member value allowed)
16395 (setq nval (car (cdr (member value allowed)))))
16396 (setq nval (or nval (car allowed)))
16397 (when (equal nval value)
16398 (user-error "Only one allowed value for this property"))
16399 (org-at-property-p)
16400 (replace-match (concat " :" key ": " nval) t t)
16401 (org-indent-line)
16402 (beginning-of-line 1)
16403 (skip-chars-forward " \t")
16404 (when (equal prop org-effort-property)
16405 (org-refresh-property
16406 '((effort . identity)
16407 (effort-minutes . org-duration-to-minutes))
16408 nval)
16409 (when (string= org-clock-current-task heading)
16410 (setq org-clock-effort nval)
16411 (org-clock-update-mode-line)))
16412 (run-hook-with-args 'org-property-changed-functions key nval)))
16414 (defun org-find-olp (path &optional this-buffer)
16415 "Return a marker pointing to the entry at outline path OLP.
16416 If anything goes wrong, throw an error.
16417 You can wrap this call to catch the error like this:
16419 (condition-case msg
16420 (org-mobile-locate-entry (match-string 4))
16421 (error (nth 1 msg)))
16423 The return value will then be either a string with the error message,
16424 or a marker if everything is OK.
16426 If THIS-BUFFER is set, the outline path does not contain a file,
16427 only headings."
16428 (let* ((file (if this-buffer buffer-file-name (pop path)))
16429 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16430 (level 1)
16431 (lmin 1)
16432 (lmax 1)
16433 end found flevel)
16434 (unless buffer (error "File not found :%s" file))
16435 (with-current-buffer buffer
16436 (unless (derived-mode-p 'org-mode)
16437 (error "Buffer %s needs to be in Org mode" buffer))
16438 (org-with-wide-buffer
16439 (goto-char (point-min))
16440 (dolist (heading path)
16441 (let ((re (format org-complex-heading-regexp-format
16442 (regexp-quote heading)))
16443 (cnt 0))
16444 (while (re-search-forward re end t)
16445 (setq level (- (match-end 1) (match-beginning 1)))
16446 (when (and (>= level lmin) (<= level lmax))
16447 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16448 (when (= cnt 0)
16449 (error "Heading not found on level %d: %s" lmax heading))
16450 (when (> cnt 1)
16451 (error "Heading not unique on level %d: %s" lmax heading))
16452 (goto-char found)
16453 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16454 (setq end (save-excursion (org-end-of-subtree t t)))))
16455 (when (org-at-heading-p)
16456 (point-marker))))))
16458 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16459 "Find node HEADING in BUFFER.
16460 Return a marker to the heading if it was found, or nil if not.
16461 If POS-ONLY is set, return just the position instead of a marker.
16463 The heading text must match exact, but it may have a TODO keyword,
16464 a priority cookie and tags in the standard locations."
16465 (with-current-buffer (or buffer (current-buffer))
16466 (org-with-wide-buffer
16467 (goto-char (point-min))
16468 (let (case-fold-search)
16469 (when (re-search-forward
16470 (format org-complex-heading-regexp-format
16471 (regexp-quote heading)) nil t)
16472 (if pos-only
16473 (match-beginning 0)
16474 (move-marker (make-marker) (match-beginning 0))))))))
16476 (defun org-find-exact-heading-in-directory (heading &optional dir)
16477 "Find Org node headline HEADING in all .org files in directory DIR.
16478 When the target headline is found, return a marker to this location."
16479 (let ((files (directory-files (or dir default-directory)
16480 t "\\`[^.#].*\\.org\\'"))
16481 visiting m buffer)
16482 (catch 'found
16483 (dolist (file files)
16484 (message "trying %s" file)
16485 (setq visiting (org-find-base-buffer-visiting file))
16486 (setq buffer (or visiting (find-file-noselect file)))
16487 (setq m (org-find-exact-headline-in-buffer
16488 heading buffer))
16489 (when (and (not m) (not visiting)) (kill-buffer buffer))
16490 (and m (throw 'found m))))))
16492 (defun org-find-entry-with-id (ident)
16493 "Locate the entry that contains the ID property with exact value IDENT.
16494 IDENT can be a string, a symbol or a number, this function will search for
16495 the string representation of it.
16496 Return the position where this entry starts, or nil if there is no such entry."
16497 (interactive "sID: ")
16498 (let ((id (cond
16499 ((stringp ident) ident)
16500 ((symbolp ident) (symbol-name ident))
16501 ((numberp ident) (number-to-string ident))
16502 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16503 (org-with-wide-buffer (org-find-property "ID" id))))
16505 ;;;; Timestamps
16507 (defvar org-last-changed-timestamp nil)
16508 (defvar org-last-inserted-timestamp nil
16509 "The last time stamp inserted with `org-insert-time-stamp'.")
16511 (defun org-time-stamp (arg &optional inactive)
16512 "Prompt for a date/time and insert a time stamp.
16514 If the user specifies a time like HH:MM or if this command is
16515 called with at least one prefix argument, the time stamp contains
16516 the date and the time. Otherwise, only the date is included.
16518 All parts of a date not specified by the user are filled in from
16519 the timestamp at point, if any, or the current date/time
16520 otherwise.
16522 If there is already a timestamp at the cursor, it is replaced.
16524 With two universal prefix arguments, insert an active timestamp
16525 with the current time without prompting the user.
16527 When called from lisp, the timestamp is inactive if INACTIVE is
16528 non-nil."
16529 (interactive "P")
16530 (let* ((ts (cond
16531 ((org-at-date-range-p t)
16532 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16533 ((org-at-timestamp-p 'lax) (match-string 0))))
16534 ;; Default time is either the timestamp at point or today.
16535 ;; When entering a range, only the range start is considered.
16536 (default-time (if (not ts) (current-time)
16537 (apply #'encode-time (org-parse-time-string ts))))
16538 (default-input (and ts (org-get-compact-tod ts)))
16539 (repeater (and ts
16540 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16541 (match-string 0 ts)))
16542 org-time-was-given
16543 org-end-time-was-given
16544 (time
16545 (and (if (equal arg '(16)) (current-time)
16546 ;; Preserve `this-command' and `last-command'.
16547 (let ((this-command this-command)
16548 (last-command last-command))
16549 (org-read-date
16550 arg 'totime nil nil default-time default-input
16551 inactive))))))
16552 (cond
16553 ((and ts
16554 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16555 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16556 (insert "--")
16557 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16559 ;; Make sure we're on a timestamp. When in the middle of a date
16560 ;; range, move arbitrarily to range end.
16561 (unless (org-at-timestamp-p 'lax)
16562 (skip-chars-forward "-")
16563 (org-at-timestamp-p 'lax))
16564 (replace-match "")
16565 (setq org-last-changed-timestamp
16566 (org-insert-time-stamp
16567 time (or org-time-was-given arg)
16568 inactive nil nil (list org-end-time-was-given)))
16569 (when repeater
16570 (backward-char)
16571 (insert " " repeater)
16572 (setq org-last-changed-timestamp
16573 (concat (substring org-last-inserted-timestamp 0 -1)
16574 " " repeater ">")))
16575 (message "Timestamp updated"))
16576 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16577 (t (org-insert-time-stamp
16578 time (or org-time-was-given arg) inactive nil nil
16579 (list org-end-time-was-given))))))
16581 ;; FIXME: can we use this for something else, like computing time differences?
16582 (defun org-get-compact-tod (s)
16583 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16584 (let* ((t1 (match-string 1 s))
16585 (h1 (string-to-number (match-string 2 s)))
16586 (m1 (string-to-number (match-string 3 s)))
16587 (t2 (and (match-end 4) (match-string 5 s)))
16588 (h2 (and t2 (string-to-number (match-string 6 s))))
16589 (m2 (and t2 (string-to-number (match-string 7 s))))
16590 dh dm)
16591 (if (not t2)
16593 (setq dh (- h2 h1) dm (- m2 m1))
16594 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16595 (concat t1 "+" (number-to-string dh)
16596 (and (/= 0 dm) (format ":%02d" dm)))))))
16598 (defun org-time-stamp-inactive (&optional arg)
16599 "Insert an inactive time stamp.
16600 An inactive time stamp is enclosed in square brackets instead of angle
16601 brackets. It is inactive in the sense that it does not trigger agenda entries,
16602 does not link to the calendar and cannot be changed with the S-cursor keys.
16603 So these are more for recording a certain time/date."
16604 (interactive "P")
16605 (org-time-stamp arg 'inactive))
16607 (defvar org-date-ovl (make-overlay 1 1))
16608 (overlay-put org-date-ovl 'face 'org-date-selected)
16609 (delete-overlay org-date-ovl)
16611 (defvar org-ans1) ; dynamically scoped parameter
16612 (defvar org-ans2) ; dynamically scoped parameter
16614 (defvar org-plain-time-of-day-regexp) ; defined below
16616 (defvar org-overriding-default-time nil) ; dynamically scoped
16617 (defvar org-read-date-overlay nil)
16618 (defvar org-dcst nil) ; dynamically scoped
16619 (defvar org-read-date-history nil)
16620 (defvar org-read-date-final-answer nil)
16621 (defvar org-read-date-analyze-futurep nil)
16622 (defvar org-read-date-analyze-forced-year nil)
16623 (defvar org-read-date-inactive)
16625 (defvar org-read-date-minibuffer-local-map
16626 (let* ((map (make-sparse-keymap)))
16627 (set-keymap-parent map minibuffer-local-map)
16628 (org-defkey map (kbd ".")
16629 (lambda () (interactive)
16630 ;; Are we at the beginning of the prompt?
16631 (if (looking-back "^[^:]+: "
16632 (let ((inhibit-field-text-motion t))
16633 (line-beginning-position)))
16634 (org-eval-in-calendar '(calendar-goto-today))
16635 (insert "."))))
16636 (org-defkey map (kbd "C-.")
16637 (lambda () (interactive)
16638 (org-eval-in-calendar '(calendar-goto-today))))
16639 (org-defkey map [(meta shift left)]
16640 (lambda () (interactive)
16641 (org-eval-in-calendar '(calendar-backward-month 1))))
16642 (org-defkey map [(meta shift right)]
16643 (lambda () (interactive)
16644 (org-eval-in-calendar '(calendar-forward-month 1))))
16645 (org-defkey map [(meta shift up)]
16646 (lambda () (interactive)
16647 (org-eval-in-calendar '(calendar-backward-year 1))))
16648 (org-defkey map [(meta shift down)]
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-forward-year 1))))
16651 (org-defkey map [?\e (shift left)]
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-backward-month 1))))
16654 (org-defkey map [?\e (shift right)]
16655 (lambda () (interactive)
16656 (org-eval-in-calendar '(calendar-forward-month 1))))
16657 (org-defkey map [?\e (shift up)]
16658 (lambda () (interactive)
16659 (org-eval-in-calendar '(calendar-backward-year 1))))
16660 (org-defkey map [?\e (shift down)]
16661 (lambda () (interactive)
16662 (org-eval-in-calendar '(calendar-forward-year 1))))
16663 (org-defkey map [(shift up)]
16664 (lambda () (interactive)
16665 (org-eval-in-calendar '(calendar-backward-week 1))))
16666 (org-defkey map [(shift down)]
16667 (lambda () (interactive)
16668 (org-eval-in-calendar '(calendar-forward-week 1))))
16669 (org-defkey map [(shift left)]
16670 (lambda () (interactive)
16671 (org-eval-in-calendar '(calendar-backward-day 1))))
16672 (org-defkey map [(shift right)]
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-forward-day 1))))
16675 (org-defkey map "!"
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(diary-view-entries))
16678 (message "")))
16679 (org-defkey map ">"
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(calendar-scroll-left 1))))
16682 (org-defkey map "<"
16683 (lambda () (interactive)
16684 (org-eval-in-calendar '(calendar-scroll-right 1))))
16685 (org-defkey map "\C-v"
16686 (lambda () (interactive)
16687 (org-eval-in-calendar
16688 '(calendar-scroll-left-three-months 1))))
16689 (org-defkey map "\M-v"
16690 (lambda () (interactive)
16691 (org-eval-in-calendar
16692 '(calendar-scroll-right-three-months 1))))
16693 map)
16694 "Keymap for minibuffer commands when using `org-read-date'.")
16696 (defvar org-def)
16697 (defvar org-defdecode)
16698 (defvar org-with-time)
16700 (defvar calendar-setup) ; Dynamically scoped.
16701 (defun org-read-date (&optional with-time to-time from-string prompt
16702 default-time default-input inactive)
16703 "Read a date, possibly a time, and make things smooth for the user.
16704 The prompt will suggest to enter an ISO date, but you can also enter anything
16705 which will at least partially be understood by `parse-time-string'.
16706 Unrecognized parts of the date will default to the current day, month, year,
16707 hour and minute. If this command is called to replace a timestamp at point,
16708 or to enter the second timestamp of a range, the default time is taken
16709 from the existing stamp. Furthermore, the command prefers the future,
16710 so if you are giving a date where the year is not given, and the day-month
16711 combination is already past in the current year, it will assume you
16712 mean next year. For details, see the manual. A few examples:
16714 3-2-5 --> 2003-02-05
16715 feb 15 --> currentyear-02-15
16716 2/15 --> currentyear-02-15
16717 sep 12 9 --> 2009-09-12
16718 12:45 --> today 12:45
16719 22 sept 0:34 --> currentyear-09-22 0:34
16720 12 --> currentyear-currentmonth-12
16721 Fri --> nearest Friday after today
16722 -Tue --> last Tuesday
16723 etc.
16725 Furthermore you can specify a relative date by giving, as the *first* thing
16726 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16727 change in days weeks, months, years.
16728 With a single plus or minus, the date is relative to today. With a double
16729 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16730 +4d --> four days from today
16731 +4 --> same as above
16732 +2w --> two weeks from today
16733 ++5 --> five days from default date
16735 The function understands only English month and weekday abbreviations.
16737 While prompting, a calendar is popped up - you can also select the
16738 date with the mouse (button 1). The calendar shows a period of three
16739 months. To scroll it to other months, use the keys `>' and `<'.
16740 If you don't like the calendar, turn it off with
16741 (setq org-read-date-popup-calendar nil)
16743 With optional argument TO-TIME, the date will immediately be converted
16744 to an internal time.
16745 With an optional argument WITH-TIME, the prompt will suggest to
16746 also insert a time. Note that when WITH-TIME is not set, you can
16747 still enter a time, and this function will inform the calling routine
16748 about this change. The calling routine may then choose to change the
16749 format used to insert the time stamp into the buffer to include the time.
16750 With optional argument FROM-STRING, read from this string instead from
16751 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16752 the time/date that is used for everything that is not specified by the
16753 user."
16754 (require 'parse-time)
16755 (let* ((org-with-time with-time)
16756 (org-time-stamp-rounding-minutes
16757 (if (equal org-with-time '(16))
16758 '(0 0)
16759 org-time-stamp-rounding-minutes))
16760 (org-dcst org-display-custom-times)
16761 (ct (org-current-time))
16762 (org-def (or org-overriding-default-time default-time ct))
16763 (org-defdecode (decode-time org-def))
16764 (cur-frame (selected-frame))
16765 (mouse-autoselect-window nil) ; Don't let the mouse jump
16766 (calendar-setup
16767 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16768 (calendar-move-hook nil)
16769 (calendar-view-diary-initially-flag nil)
16770 (calendar-view-holidays-initially-flag nil)
16771 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16772 ;; Rationalize `org-def' and `org-defdecode', if required.
16773 (when (< (nth 2 org-defdecode) org-extend-today-until)
16774 (setf (nth 2 org-defdecode) -1)
16775 (setf (nth 1 org-defdecode) 59)
16776 (setq org-def (apply #'encode-time org-defdecode))
16777 (setq org-defdecode (decode-time org-def)))
16778 (let* ((timestr (format-time-string
16779 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16780 org-def))
16781 (prompt (concat (if prompt (concat prompt " ") "")
16782 (format "Date+time [%s]: " timestr))))
16783 (cond
16784 (from-string (setq ans from-string))
16785 (org-read-date-popup-calendar
16786 (save-excursion
16787 (save-window-excursion
16788 (calendar)
16789 (when (eq calendar-setup 'calendar-only)
16790 (setq cal-frame
16791 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16792 (select-frame cal-frame))
16793 (org-eval-in-calendar '(setq cursor-type nil) t)
16794 (unwind-protect
16795 (progn
16796 (calendar-forward-day (- (time-to-days org-def)
16797 (calendar-absolute-from-gregorian
16798 (calendar-current-date))))
16799 (org-eval-in-calendar nil t)
16800 (let* ((old-map (current-local-map))
16801 (map (copy-keymap calendar-mode-map))
16802 (minibuffer-local-map
16803 (copy-keymap org-read-date-minibuffer-local-map)))
16804 (org-defkey map (kbd "RET") 'org-calendar-select)
16805 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16806 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16807 (unwind-protect
16808 (progn
16809 (use-local-map map)
16810 (setq org-read-date-inactive inactive)
16811 (add-hook 'post-command-hook 'org-read-date-display)
16812 (setq org-ans0
16813 (read-string prompt
16814 default-input
16815 'org-read-date-history
16816 nil))
16817 ;; org-ans0: from prompt
16818 ;; org-ans1: from mouse click
16819 ;; org-ans2: from calendar motion
16820 (setq ans
16821 (concat org-ans0 " " (or org-ans1 org-ans2))))
16822 (remove-hook 'post-command-hook 'org-read-date-display)
16823 (use-local-map old-map)
16824 (when org-read-date-overlay
16825 (delete-overlay org-read-date-overlay)
16826 (setq org-read-date-overlay nil)))))
16827 (bury-buffer "*Calendar*")
16828 (when cal-frame
16829 (delete-frame cal-frame)
16830 (select-frame-set-input-focus cur-frame))))))
16832 (t ; Naked prompt only
16833 (unwind-protect
16834 (setq ans (read-string prompt default-input
16835 'org-read-date-history timestr))
16836 (when org-read-date-overlay
16837 (delete-overlay org-read-date-overlay)
16838 (setq org-read-date-overlay nil))))))
16840 (setq final (org-read-date-analyze ans org-def org-defdecode))
16842 (when org-read-date-analyze-forced-year
16843 (message "Year was forced into %s"
16844 (if org-read-date-force-compatible-dates
16845 "compatible range (1970-2037)"
16846 "range representable on this machine"))
16847 (ding))
16849 ;; One round trip to get rid of 34th of August and stuff like that....
16850 (setq final (decode-time (apply 'encode-time final)))
16852 (setq org-read-date-final-answer ans)
16854 (if to-time
16855 (apply 'encode-time final)
16856 (if (and (boundp 'org-time-was-given) org-time-was-given)
16857 (format "%04d-%02d-%02d %02d:%02d"
16858 (nth 5 final) (nth 4 final) (nth 3 final)
16859 (nth 2 final) (nth 1 final))
16860 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16862 (defun org-read-date-display ()
16863 "Display the current date prompt interpretation in the minibuffer."
16864 (when org-read-date-display-live
16865 (when org-read-date-overlay
16866 (delete-overlay org-read-date-overlay))
16867 (when (minibufferp (current-buffer))
16868 (save-excursion
16869 (end-of-line 1)
16870 (while (not (equal (buffer-substring
16871 (max (point-min) (- (point) 4)) (point))
16872 " "))
16873 (insert " ")))
16874 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16875 " " (or org-ans1 org-ans2)))
16876 (org-end-time-was-given nil)
16877 (f (org-read-date-analyze ans org-def org-defdecode))
16878 (fmts (if org-dcst
16879 org-time-stamp-custom-formats
16880 org-time-stamp-formats))
16881 (fmt (if (or org-with-time
16882 (and (boundp 'org-time-was-given) org-time-was-given))
16883 (cdr fmts)
16884 (car fmts)))
16885 (txt (format-time-string fmt (apply 'encode-time f)))
16886 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16887 (txt (concat "=> " txt)))
16888 (when (and org-end-time-was-given
16889 (string-match org-plain-time-of-day-regexp txt))
16890 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16891 org-end-time-was-given
16892 (substring txt (match-end 0)))))
16893 (when org-read-date-analyze-futurep
16894 (setq txt (concat txt " (=>F)")))
16895 (setq org-read-date-overlay
16896 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16897 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16899 (defun org-read-date-analyze (ans def defdecode)
16900 "Analyze the combined answer of the date prompt."
16901 ;; FIXME: cleanup and comment
16902 ;; Pass `current-time' result to `decode-time' (instead of calling
16903 ;; without arguments) so that only `current-time' has to be
16904 ;; overridden in tests.
16905 (let ((org-def def)
16906 (org-defdecode defdecode)
16907 (nowdecode (decode-time (current-time)))
16908 delta deltan deltaw deltadef year month day
16909 hour minute second wday pm h2 m2 tl wday1
16910 iso-year iso-weekday iso-week iso-date futurep kill-year)
16911 (setq org-read-date-analyze-futurep nil
16912 org-read-date-analyze-forced-year nil)
16913 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16914 (setq ans "+0"))
16916 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16917 (setq ans (replace-match "" t t ans)
16918 deltan (car delta)
16919 deltaw (nth 1 delta)
16920 deltadef (nth 2 delta)))
16922 ;; Check if there is an iso week date in there. If yes, store the
16923 ;; info and postpone interpreting it until the rest of the parsing
16924 ;; is done.
16925 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16926 (setq iso-year (when (match-end 1)
16927 (org-small-year-to-year
16928 (string-to-number (match-string 1 ans))))
16929 iso-weekday (when (match-end 3)
16930 (string-to-number (match-string 3 ans)))
16931 iso-week (string-to-number (match-string 2 ans)))
16932 (setq ans (replace-match "" t t ans)))
16934 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16935 (when (string-match
16936 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16937 (setq year (if (match-end 2)
16938 (string-to-number (match-string 2 ans))
16939 (progn (setq kill-year t)
16940 (string-to-number (format-time-string "%Y"))))
16941 month (string-to-number (match-string 3 ans))
16942 day (string-to-number (match-string 4 ans)))
16943 (setq year (org-small-year-to-year year))
16944 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16945 t nil ans)))
16947 ;; Help matching dotted european dates
16948 (when (string-match
16949 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16950 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16951 (setq kill-year t)
16952 (string-to-number (format-time-string "%Y")))
16953 day (string-to-number (match-string 1 ans))
16954 month (string-to-number (match-string 2 ans))
16955 ans (replace-match (format "%04d-%02d-%02d" year month day)
16956 t nil ans)))
16958 ;; Help matching american dates, like 5/30 or 5/30/7
16959 (when (string-match
16960 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16961 (setq year (if (match-end 4)
16962 (string-to-number (match-string 4 ans))
16963 (progn (setq kill-year t)
16964 (string-to-number (format-time-string "%Y"))))
16965 month (string-to-number (match-string 1 ans))
16966 day (string-to-number (match-string 2 ans)))
16967 (setq year (org-small-year-to-year year))
16968 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16969 t nil ans)))
16970 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16971 ;; If there is a time with am/pm, and *no* time without it, we convert
16972 ;; so that matching will be successful.
16973 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16974 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16975 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16976 (setq hour (string-to-number (match-string 1 ans))
16977 minute (if (match-end 3)
16978 (string-to-number (match-string 3 ans))
16980 pm (equal ?p
16981 (string-to-char (downcase (match-string 4 ans)))))
16982 (if (and (= hour 12) (not pm))
16983 (setq hour 0)
16984 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16985 (setq ans (replace-match (format "%02d:%02d" hour minute)
16986 t t ans))))
16988 ;; Check if a time range is given as a duration
16989 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16990 (setq hour (string-to-number (match-string 1 ans))
16991 h2 (+ hour (string-to-number (match-string 3 ans)))
16992 minute (string-to-number (match-string 2 ans))
16993 m2 (+ minute (if (match-end 5) (string-to-number
16994 (match-string 5 ans))0)))
16995 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16996 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16997 t t ans)))
16999 ;; Check if there is a time range
17000 (when (boundp 'org-end-time-was-given)
17001 (setq org-time-was-given nil)
17002 (when (and (string-match org-plain-time-of-day-regexp ans)
17003 (match-end 8))
17004 (setq org-end-time-was-given (match-string 8 ans))
17005 (setq ans (concat (substring ans 0 (match-beginning 7))
17006 (substring ans (match-end 7))))))
17008 (setq tl (parse-time-string ans)
17009 day (or (nth 3 tl) (nth 3 org-defdecode))
17010 month
17011 (cond ((nth 4 tl))
17012 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17013 ;; Day was specified. Make sure DAY+MONTH
17014 ;; combination happens in the future.
17015 ((nth 3 tl)
17016 (setq futurep t)
17017 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17018 (nth 4 nowdecode)))
17019 (t (nth 4 org-defdecode)))
17020 year
17021 (cond ((and (not kill-year) (nth 5 tl)))
17022 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17023 ;; Month was guessed in the future and is at least
17024 ;; equal to NOWDECODE's. Fix year accordingly.
17025 (futurep
17026 (if (or (> month (nth 4 nowdecode))
17027 (>= day (nth 3 nowdecode)))
17028 (nth 5 nowdecode)
17029 (1+ (nth 5 nowdecode))))
17030 ;; Month was specified. Make sure MONTH+YEAR
17031 ;; combination happens in the future.
17032 ((nth 4 tl)
17033 (setq futurep t)
17034 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17035 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17036 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17037 (t (nth 5 nowdecode))))
17038 (t (nth 5 org-defdecode)))
17039 hour (or (nth 2 tl) (nth 2 org-defdecode))
17040 minute (or (nth 1 tl) (nth 1 org-defdecode))
17041 second (or (nth 0 tl) 0)
17042 wday (nth 6 tl))
17044 (when (and (eq org-read-date-prefer-future 'time)
17045 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17046 (equal day (nth 3 nowdecode))
17047 (equal month (nth 4 nowdecode))
17048 (equal year (nth 5 nowdecode))
17049 (nth 2 tl)
17050 (or (< (nth 2 tl) (nth 2 nowdecode))
17051 (and (= (nth 2 tl) (nth 2 nowdecode))
17052 (nth 1 tl)
17053 (< (nth 1 tl) (nth 1 nowdecode)))))
17054 (setq day (1+ day)
17055 futurep t))
17057 ;; Special date definitions below
17058 (cond
17059 (iso-week
17060 ;; There was an iso week
17061 (require 'cal-iso)
17062 (setq futurep nil)
17063 (setq year (or iso-year year)
17064 day (or iso-weekday wday 1)
17065 wday nil ; to make sure that the trigger below does not match
17066 iso-date (calendar-gregorian-from-absolute
17067 (calendar-iso-to-absolute
17068 (list iso-week day year))))
17069 ; FIXME: Should we also push ISO weeks into the future?
17070 ; (when (and org-read-date-prefer-future
17071 ; (not iso-year)
17072 ; (< (calendar-absolute-from-gregorian iso-date)
17073 ; (time-to-days (current-time))))
17074 ; (setq year (1+ year)
17075 ; iso-date (calendar-gregorian-from-absolute
17076 ; (calendar-iso-to-absolute
17077 ; (list iso-week day year)))))
17078 (setq month (car iso-date)
17079 year (nth 2 iso-date)
17080 day (nth 1 iso-date)))
17081 (deltan
17082 (setq futurep nil)
17083 (unless deltadef
17084 ;; Pass `current-time' result to `decode-time' (instead of
17085 ;; calling without arguments) so that only `current-time' has
17086 ;; to be overridden in tests.
17087 (let ((now (decode-time (current-time))))
17088 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17089 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17090 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17091 ((equal deltaw "m") (setq month (+ month deltan)))
17092 ((equal deltaw "y") (setq year (+ year deltan)))))
17093 ((and wday (not (nth 3 tl)))
17094 ;; Weekday was given, but no day, so pick that day in the week
17095 ;; on or after the derived date.
17096 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17097 (unless (equal wday wday1)
17098 (setq day (+ day (% (- wday wday1 -7) 7))))))
17099 (when (and (boundp 'org-time-was-given)
17100 (nth 2 tl))
17101 (setq org-time-was-given t))
17102 (when (< year 100) (setq year (+ 2000 year)))
17103 ;; Check of the date is representable
17104 (if org-read-date-force-compatible-dates
17105 (progn
17106 (when (< year 1970)
17107 (setq year 1970 org-read-date-analyze-forced-year t))
17108 (when (> year 2037)
17109 (setq year 2037 org-read-date-analyze-forced-year t)))
17110 (condition-case nil
17111 (ignore (encode-time second minute hour day month year))
17112 (error
17113 (setq year (nth 5 org-defdecode))
17114 (setq org-read-date-analyze-forced-year t))))
17115 (setq org-read-date-analyze-futurep futurep)
17116 (list second minute hour day month year)))
17118 (defvar parse-time-weekdays)
17119 (defun org-read-date-get-relative (s today default)
17120 "Check string S for special relative date string.
17121 TODAY and DEFAULT are internal times, for today and for a default.
17122 Return shift list (N what def-flag)
17123 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17124 N is the number of WHATs to shift.
17125 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17126 the DEFAULT date rather than TODAY."
17127 (require 'parse-time)
17128 (when (and
17129 (string-match
17130 (concat
17131 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17132 "\\([0-9]+\\)?"
17133 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17134 "\\([ \t]\\|$\\)") s)
17135 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17136 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17137 (string-to-char (substring (match-string 1 s) -1))
17138 ?+))
17139 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17140 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17141 (what (if (match-end 3) (match-string 3 s) "d"))
17142 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17143 (date (if rel default today))
17144 (wday (nth 6 (decode-time date)))
17145 delta)
17146 (if wday1
17147 (progn
17148 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17149 (when (= delta 0) (setq delta 7))
17150 (when (= dir ?-)
17151 (setq delta (- delta 7))
17152 (when (= delta 0) (setq delta -7)))
17153 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17154 (list delta "d" rel))
17155 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17157 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17158 "Turn a user-specified date into the internal representation.
17159 The internal representation needed by the calendar is (month day year).
17160 This is a wrapper to handle the brain-dead convention in calendar that
17161 user function argument order change dependent on argument order."
17162 (pcase calendar-date-style
17163 (`american (list arg1 arg2 arg3))
17164 (`european (list arg2 arg1 arg3))
17165 (`iso (list arg2 arg3 arg1))))
17167 (defun org-eval-in-calendar (form &optional keepdate)
17168 "Eval FORM in the calendar window and return to current window.
17169 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17170 (let ((sf (selected-frame))
17171 (sw (selected-window)))
17172 (select-window (get-buffer-window "*Calendar*" t))
17173 (eval form)
17174 (when (and (not keepdate) (calendar-cursor-to-date))
17175 (let* ((date (calendar-cursor-to-date))
17176 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17177 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17178 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17179 (select-window sw)
17180 (select-frame-set-input-focus sf)))
17182 (defun org-calendar-select ()
17183 "Return to `org-read-date' with the date currently selected.
17184 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17185 (interactive)
17186 (when (calendar-cursor-to-date)
17187 (let* ((date (calendar-cursor-to-date))
17188 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17189 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17190 (when (active-minibuffer-window) (exit-minibuffer))))
17192 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17193 "Insert a date stamp for the date given by the internal TIME.
17194 See `format-time-string' for the format of TIME.
17195 WITH-HM means use the stamp format that includes the time of the day.
17196 INACTIVE means use square brackets instead of angular ones, so that the
17197 stamp will not contribute to the agenda.
17198 PRE and POST are optional strings to be inserted before and after the
17199 stamp.
17200 The command returns the inserted time stamp."
17201 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17202 stamp)
17203 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17204 (insert-before-markers (or pre ""))
17205 (when (listp extra)
17206 (setq extra (car extra))
17207 (if (and (stringp extra)
17208 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17209 (setq extra (format "-%02d:%02d"
17210 (string-to-number (match-string 1 extra))
17211 (string-to-number (match-string 2 extra))))
17212 (setq extra nil)))
17213 (when extra
17214 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17215 (insert-before-markers (setq stamp (format-time-string fmt time)))
17216 (insert-before-markers (or post ""))
17217 (setq org-last-inserted-timestamp stamp)))
17219 (defun org-toggle-time-stamp-overlays ()
17220 "Toggle the use of custom time stamp formats."
17221 (interactive)
17222 (setq org-display-custom-times (not org-display-custom-times))
17223 (unless org-display-custom-times
17224 (let ((p (point-min)) (bmp (buffer-modified-p)))
17225 (while (setq p (next-single-property-change p 'display))
17226 (when (and (get-text-property p 'display)
17227 (eq (get-text-property p 'face) 'org-date))
17228 (remove-text-properties
17229 p (setq p (next-single-property-change p 'display))
17230 '(display t))))
17231 (set-buffer-modified-p bmp)))
17232 (org-restart-font-lock)
17233 (setq org-table-may-need-update t)
17234 (if org-display-custom-times
17235 (message "Time stamps are overlaid with custom format")
17236 (message "Time stamp overlays removed")))
17238 (defun org-display-custom-time (beg end)
17239 "Overlay modified time stamp format over timestamp between BEG and END."
17240 (let* ((ts (buffer-substring beg end))
17241 t1 with-hm tf time str (off 0))
17242 (save-match-data
17243 (setq t1 (org-parse-time-string ts t))
17244 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17245 (setq off (- (match-end 0) (match-beginning 0)))))
17246 (setq end (- end off))
17247 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17248 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17249 time (org-fix-decoded-time t1)
17250 str (org-add-props
17251 (format-time-string
17252 (substring tf 1 -1) (apply 'encode-time time))
17253 nil 'mouse-face 'highlight))
17254 (put-text-property beg end 'display str)))
17256 (defun org-fix-decoded-time (time)
17257 "Set 0 instead of nil for the first 6 elements of time.
17258 Don't touch the rest."
17259 (let ((n 0))
17260 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17262 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17263 "Difference between TIMESTAMP-STRING and now in days.
17264 If SECONDS is non-nil, return the difference in seconds."
17265 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17266 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17267 (funcall fdiff (current-time)))))
17269 (defun org-deadline-close-p (timestamp-string &optional ndays)
17270 "Is the time in TIMESTAMP-STRING close to the current date?"
17271 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17272 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17273 (not (org-entry-is-done-p))))
17275 (defun org-get-wdays (ts &optional delay zero-delay)
17276 "Get the deadline lead time appropriate for timestring TS.
17277 When DELAY is non-nil, get the delay time for scheduled items
17278 instead of the deadline lead time. When ZERO-DELAY is non-nil
17279 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17280 don't try to find the delay cookie in the scheduled timestamp."
17281 (let ((tv (if delay org-scheduled-delay-days
17282 org-deadline-warning-days)))
17283 (cond
17284 ((or (and delay (< tv 0))
17285 (and delay zero-delay (<= tv 0))
17286 (and (not delay) (<= tv 0)))
17287 ;; Enforce this value no matter what
17288 (- tv))
17289 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17290 ;; lead time is specified.
17291 (floor (* (string-to-number (match-string 1 ts))
17292 (cdr (assoc (match-string 2 ts)
17293 '(("d" . 1) ("w" . 7)
17294 ("m" . 30.4) ("y" . 365.25)
17295 ("h" . 0.041667)))))))
17296 ;; go for the default.
17297 (t tv))))
17299 (defun org-calendar-select-mouse (ev)
17300 "Return to `org-read-date' with the date currently selected.
17301 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17302 (interactive "e")
17303 (mouse-set-point ev)
17304 (when (calendar-cursor-to-date)
17305 (let* ((date (calendar-cursor-to-date))
17306 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17307 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17308 (when (active-minibuffer-window) (exit-minibuffer))))
17310 (defun org-check-deadlines (ndays)
17311 "Check if there are any deadlines due or past due.
17312 A deadline is considered due if it happens within `org-deadline-warning-days'
17313 days from today's date. If the deadline appears in an entry marked DONE,
17314 it is not shown. A numeric prefix argument NDAYS can be used to test that
17315 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17316 are shown."
17317 (interactive "P")
17318 (let* ((org-warn-days
17319 (cond
17320 ((equal ndays '(4)) 100000)
17321 (ndays (prefix-numeric-value ndays))
17322 (t (abs org-deadline-warning-days))))
17323 (case-fold-search nil)
17324 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17325 (callback
17326 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17327 (message "%d deadlines past-due or due within %d days"
17328 (org-occur regexp nil callback)
17329 org-warn-days)))
17331 (defsubst org-re-timestamp (type)
17332 "Return a regexp for timestamp TYPE.
17333 Allowed values for TYPE are:
17335 all: all timestamps
17336 active: only active timestamps (<...>)
17337 inactive: only inactive timestamps ([...])
17338 scheduled: only scheduled timestamps
17339 deadline: only deadline timestamps
17340 closed: only closed time-stamps
17342 When TYPE is nil, fall back on returning a regexp that matches
17343 both scheduled and deadline timestamps."
17344 (cl-case type
17345 (all org-ts-regexp-both)
17346 (active org-ts-regexp)
17347 (inactive org-ts-regexp-inactive)
17348 (scheduled org-scheduled-time-regexp)
17349 (deadline org-deadline-time-regexp)
17350 (closed org-closed-time-regexp)
17351 (otherwise
17352 (concat "\\<"
17353 (regexp-opt (list org-deadline-string org-scheduled-string))
17354 " *<\\([^>]+\\)>"))))
17356 (defun org-check-before-date (d)
17357 "Check if there are deadlines or scheduled entries before date D."
17358 (interactive (list (org-read-date)))
17359 (let* ((case-fold-search nil)
17360 (regexp (org-re-timestamp org-ts-type))
17361 (ts-type org-ts-type)
17362 (callback
17363 (lambda ()
17364 (let ((match (match-string 1)))
17365 (and (if (memq ts-type '(active inactive all))
17366 (eq (org-element-type (save-excursion
17367 (backward-char)
17368 (org-element-context)))
17369 'timestamp)
17370 (org-at-planning-p))
17371 (time-less-p
17372 (org-time-string-to-time match t)
17373 (org-time-string-to-time d t)))))))
17374 (message "%d entries before %s"
17375 (org-occur regexp nil callback)
17376 d)))
17378 (defun org-check-after-date (d)
17379 "Check if there are deadlines or scheduled entries after date D."
17380 (interactive (list (org-read-date)))
17381 (let* ((case-fold-search nil)
17382 (regexp (org-re-timestamp org-ts-type))
17383 (ts-type org-ts-type)
17384 (callback
17385 (lambda ()
17386 (let ((match (match-string 1)))
17387 (and (if (memq ts-type '(active inactive all))
17388 (eq (org-element-type (save-excursion
17389 (backward-char)
17390 (org-element-context)))
17391 'timestamp)
17392 (org-at-planning-p))
17393 (not (time-less-p
17394 (org-time-string-to-time match t)
17395 (org-time-string-to-time d t))))))))
17396 (message "%d entries after %s"
17397 (org-occur regexp nil callback)
17398 d)))
17400 (defun org-check-dates-range (start-date end-date)
17401 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17402 (interactive (list (org-read-date nil nil nil "Range starts")
17403 (org-read-date nil nil nil "Range end")))
17404 (let ((case-fold-search nil)
17405 (regexp (org-re-timestamp org-ts-type))
17406 (callback
17407 (let ((type org-ts-type))
17408 (lambda ()
17409 (let ((match (match-string 1)))
17410 (and
17411 (if (memq type '(active inactive all))
17412 (eq (org-element-type (save-excursion
17413 (backward-char)
17414 (org-element-context)))
17415 'timestamp)
17416 (org-at-planning-p))
17417 (not (time-less-p
17418 (org-time-string-to-time match t)
17419 (org-time-string-to-time start-date t)))
17420 (time-less-p
17421 (org-time-string-to-time match t)
17422 (org-time-string-to-time end-date t))))))))
17423 (message "%d entries between %s and %s"
17424 (org-occur regexp nil callback) start-date end-date)))
17426 (defun org-evaluate-time-range (&optional to-buffer)
17427 "Evaluate a time range by computing the difference between start and end.
17428 Normally the result is just printed in the echo area, but with prefix arg
17429 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17430 If the time range is actually in a table, the result is inserted into the
17431 next column.
17432 For time difference computation, a year is assumed to be exactly 365
17433 days in order to avoid rounding problems."
17434 (interactive "P")
17436 (org-clock-update-time-maybe)
17437 (save-excursion
17438 (unless (org-at-date-range-p t)
17439 (goto-char (point-at-bol))
17440 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17441 (unless (org-at-date-range-p t)
17442 (user-error "Not at a time-stamp range, and none found in current line")))
17443 (let* ((ts1 (match-string 1))
17444 (ts2 (match-string 2))
17445 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17446 (match-end (match-end 0))
17447 (time1 (org-time-string-to-time ts1))
17448 (time2 (org-time-string-to-time ts2))
17449 (t1 (float-time time1))
17450 (t2 (float-time time2))
17451 (diff (abs (- t2 t1)))
17452 (negative (< (- t2 t1) 0))
17453 ;; (ys (floor (* 365 24 60 60)))
17454 (ds (* 24 60 60))
17455 (hs (* 60 60))
17456 (fy "%dy %dd %02d:%02d")
17457 (fy1 "%dy %dd")
17458 (fd "%dd %02d:%02d")
17459 (fd1 "%dd")
17460 (fh "%02d:%02d")
17461 y d h m align)
17462 (if havetime
17463 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17465 d (floor (/ diff ds)) diff (mod diff ds)
17466 h (floor (/ diff hs)) diff (mod diff hs)
17467 m (floor (/ diff 60)))
17468 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17470 d (floor (+ (/ diff ds) 0.5))
17471 h 0 m 0))
17472 (if (not to-buffer)
17473 (message "%s" (org-make-tdiff-string y d h m))
17474 (if (org-at-table-p)
17475 (progn
17476 (goto-char match-end)
17477 (setq align t)
17478 (and (looking-at " *|") (goto-char (match-end 0))))
17479 (goto-char match-end))
17480 (when (looking-at
17481 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17482 (replace-match ""))
17483 (when negative (insert " -"))
17484 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17485 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17486 (insert " " (format fh h m))))
17487 (when align (org-table-align))
17488 (message "Time difference inserted")))))
17490 (defun org-make-tdiff-string (y d h m)
17491 (let ((fmt "")
17492 (l nil))
17493 (when (> y 0)
17494 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17495 (push y l))
17496 (when (> d 0)
17497 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17498 (push d l))
17499 (when (> h 0)
17500 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17501 (push h l))
17502 (when (> m 0)
17503 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17504 (push m l))
17505 (apply 'format fmt (nreverse l))))
17507 (defun org-time-string-to-time (s &optional zone)
17508 "Convert timestamp string S into internal time.
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 (apply #'encode-time (org-parse-time-string s nil zone)))
17514 (defun org-time-string-to-seconds (s &optional zone)
17515 "Convert a timestamp string S into a number of seconds.
17516 The optional ZONE is omitted or nil for Emacs local time, t for
17517 Universal Time, ‘wall’ for system wall clock time, or a string as
17518 in the TZ environment variable."
17519 (float-time (org-time-string-to-time s zone)))
17521 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17523 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17524 "Convert time stamp S to an absolute day number.
17526 If DAYNR in non-nil, and there is a specifier for a cyclic time
17527 stamp, get the closest date to DAYNR. If PREFER is
17528 `past' (respectively `future') return a date past (respectively
17529 after) or equal to DAYNR.
17531 POS is the location of time stamp S, as a buffer position in
17532 BUFFER.
17534 Diary sexp timestamps are matched against DAYNR, when non-nil.
17535 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17536 signaled."
17537 (cond
17538 ((string-match "\\`%%\\((.*)\\)" s)
17539 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17540 ;; only able to match individual dates. If it fails, raise an
17541 ;; error.
17542 (if (and daynr
17543 (org-diary-sexp-entry
17544 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17545 daynr
17546 (signal 'org-diary-sexp-no-match (list s))))
17547 (daynr (org-closest-date s daynr prefer))
17548 (t (time-to-days
17549 (condition-case errdata
17550 (apply #'encode-time (org-parse-time-string s))
17551 (error (error "Bad timestamp `%s'%s\nError was: %s"
17553 (if (not (and buffer pos)) ""
17554 (format-message " at %d in buffer `%s'" pos buffer))
17555 (cdr errdata))))))))
17557 (defun org-days-to-iso-week (days)
17558 "Return the iso week number."
17559 (require 'cal-iso)
17560 (car (calendar-iso-from-absolute days)))
17562 (defun org-small-year-to-year (year)
17563 "Convert 2-digit years into 4-digit years.
17564 YEAR is expanded into one of the 30 next years, if possible, or
17565 into a past one. Any year larger than 99 is returned unchanged."
17566 (if (>= year 100) year
17567 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17568 (century (/ current 100))
17569 (offset (- year (% current 100))))
17570 (cond ((> offset 30) (+ (* (1- century) 100) year))
17571 ((> offset -70) (+ (* century 100) year))
17572 (t (+ (* (1+ century) 100) year))))))
17574 (defun org-time-from-absolute (d)
17575 "Return the time corresponding to date D.
17576 D may be an absolute day number, or a calendar-type list (month day year)."
17577 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17578 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17580 (defvar org-agenda-current-date)
17581 (defun org-calendar-holiday ()
17582 "List of holidays, for Diary display in Org mode."
17583 (require 'holidays)
17584 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17585 (and hl (mapconcat #'identity hl "; "))))
17587 (defun org-diary-sexp-entry (sexp entry d)
17588 "Process a SEXP diary ENTRY for date D."
17589 (require 'diary-lib)
17590 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17591 ;; dynamically.
17592 (let* ((sexp `(let ((entry ,entry)
17593 (date ',d))
17594 ,(car (read-from-string sexp))))
17595 (result (if calendar-debug-sexp (eval sexp)
17596 (condition-case nil
17597 (eval sexp)
17598 (error
17599 (beep)
17600 (message "Bad sexp at line %d in %s: %s"
17601 (org-current-line)
17602 (buffer-file-name) sexp)
17603 (sleep-for 2))))))
17604 (cond ((stringp result) (split-string result "; "))
17605 ((and (consp result)
17606 (not (consp (cdr result)))
17607 (stringp (cdr result))) (cdr result))
17608 ((and (consp result)
17609 (stringp (car result))) result)
17610 (result entry))))
17612 (defun org-diary-to-ical-string (frombuf)
17613 "Get iCalendar entries from diary entries in buffer FROMBUF.
17614 This uses the icalendar.el library."
17615 (let* ((tmpdir temporary-file-directory)
17616 (tmpfile (make-temp-name
17617 (expand-file-name "orgics" tmpdir)))
17618 buf rtn b e)
17619 (with-current-buffer frombuf
17620 (icalendar-export-region (point-min) (point-max) tmpfile)
17621 (setq buf (find-buffer-visiting tmpfile))
17622 (set-buffer buf)
17623 (goto-char (point-min))
17624 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17625 (setq b (match-beginning 0)))
17626 (goto-char (point-max))
17627 (when (re-search-backward "^END:VEVENT" nil t)
17628 (setq e (match-end 0)))
17629 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17630 (kill-buffer buf)
17631 (delete-file tmpfile)
17632 rtn))
17634 (defun org-closest-date (start current prefer)
17635 "Return closest date to CURRENT starting from START.
17637 CURRENT and START are both time stamps.
17639 When PREFER is `past', return a date that is either CURRENT or
17640 past. When PREFER is `future', return a date that is either
17641 CURRENT or future.
17643 Only time stamps with a repeater are modified. Any other time
17644 stamp stay unchanged. In any case, return value is an absolute
17645 day number."
17646 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17647 ;; No repeater. Do not shift time stamp.
17648 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17649 (let ((value (string-to-number (match-string 1 start)))
17650 (type (match-string 2 start)))
17651 (if (= 0 value)
17652 ;; Repeater with a 0-value is considered as void.
17653 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17654 (let* ((base (org-date-to-gregorian start))
17655 (target (org-date-to-gregorian current))
17656 (sday (calendar-absolute-from-gregorian base))
17657 (cday (calendar-absolute-from-gregorian target))
17658 n1 n2)
17659 ;; If START is already past CURRENT, just return START.
17660 (if (<= cday sday) sday
17661 ;; Compute closest date before (N1) and closest date past
17662 ;; (N2) CURRENT.
17663 (pcase type
17664 ("h"
17665 (let ((missing-hours
17666 (mod (+ (- (* 24 (- cday sday))
17667 (nth 2 (org-parse-time-string start)))
17668 org-extend-today-until)
17669 value)))
17670 (setf n1 (if (= missing-hours 0) cday
17671 (- cday (1+ (/ missing-hours 24)))))
17672 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17673 ((or "d" "w")
17674 (let ((value (if (equal type "w") (* 7 value) value)))
17675 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17676 (setf n2 (+ n1 value))))
17677 ("m"
17678 (let* ((add-months
17679 (lambda (d n)
17680 ;; Add N months to gregorian date D, i.e.,
17681 ;; a list (MONTH DAY YEAR). Return a valid
17682 ;; gregorian date.
17683 (let ((m (+ (nth 0 d) n)))
17684 (list (mod m 12)
17685 (nth 1 d)
17686 (+ (/ m 12) (nth 2 d))))))
17687 (months ; Complete months to TARGET.
17688 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17689 (- (nth 0 target) (nth 0 base))
17690 ;; If START's day is greater than
17691 ;; TARGET's, remove incomplete month.
17692 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17693 value)
17694 value))
17695 (before (funcall add-months base months)))
17696 (setf n1 (calendar-absolute-from-gregorian before))
17697 (setf n2
17698 (calendar-absolute-from-gregorian
17699 (funcall add-months before value)))))
17701 (let* ((d (nth 1 base))
17702 (m (nth 0 base))
17703 (y (nth 2 base))
17704 (years ; Complete years to TARGET.
17705 (* (/ (- (nth 2 target)
17707 ;; If START's month and day are
17708 ;; greater than TARGET's, remove
17709 ;; incomplete year.
17710 (if (or (> (nth 0 target) m)
17711 (and (= (nth 0 target) m)
17712 (> (nth 1 target) d)))
17715 value)
17716 value))
17717 (before (list m d (+ y years))))
17718 (setf n1 (calendar-absolute-from-gregorian before))
17719 (setf n2 (calendar-absolute-from-gregorian
17720 (list m d (+ (nth 2 before) value)))))))
17721 ;; Handle PREFER parameter, if any.
17722 (cond
17723 ((eq prefer 'past) (if (= cday n2) n2 n1))
17724 ((eq prefer 'future) (if (= cday n1) n1 n2))
17725 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17727 (defun org-date-to-gregorian (d)
17728 "Turn any specification of date D into a Gregorian date for the calendar."
17729 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17730 ((and (listp d) (= (length d) 3)) d)
17731 ((stringp d)
17732 (let ((d (org-parse-time-string d)))
17733 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17734 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17736 (defun org-parse-time-string (s &optional nodefault zone)
17737 "Parse the standard Org time string.
17739 This should be a lot faster than the normal `parse-time-string'.
17741 If time is not given, defaults to 0:00. However, with optional
17742 NODEFAULT, hour and minute fields will be nil if not given.
17744 The optional ZONE is omitted or nil for Emacs local time, t for
17745 Universal Time, ‘wall’ for system wall clock time, or a string as
17746 in the TZ environment variable."
17747 (cond ((string-match org-ts-regexp0 s)
17748 (list 0
17749 (when (or (match-beginning 8) (not nodefault))
17750 (string-to-number (or (match-string 8 s) "0")))
17751 (when (or (match-beginning 7) (not nodefault))
17752 (string-to-number (or (match-string 7 s) "0")))
17753 (string-to-number (match-string 4 s))
17754 (string-to-number (match-string 3 s))
17755 (string-to-number (match-string 2 s))
17756 nil nil zone))
17757 ((string-match "^<[^>]+>$" s)
17758 ;; FIXME: `decode-time' needs to be called with ZONE as its
17759 ;; second argument. However, this requires at least Emacs
17760 ;; 25.1. We can do it when we switch to this version as our
17761 ;; minimal requirement.
17762 (decode-time (seconds-to-time (org-matcher-time s))))
17763 (t (error "Not a standard Org time string: %s" s))))
17765 (defun org-timestamp-up (&optional arg)
17766 "Increase the date item at the cursor by one.
17767 If the cursor is on the year, change the year. If it is on the month,
17768 the day or the time, change that.
17769 With prefix ARG, change by that many units."
17770 (interactive "p")
17771 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17773 (defun org-timestamp-down (&optional arg)
17774 "Decrease the date item at the cursor by one.
17775 If the cursor is on the year, change the year. If it is on the month,
17776 the day or the time, change that.
17777 With prefix ARG, change by that many units."
17778 (interactive "p")
17779 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17781 (defun org-timestamp-up-day (&optional arg)
17782 "Increase the date in the time stamp by one day.
17783 With prefix ARG, change that many days."
17784 (interactive "p")
17785 (if (and (not (org-at-timestamp-p 'lax))
17786 (org-at-heading-p))
17787 (org-todo 'up)
17788 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17790 (defun org-timestamp-down-day (&optional arg)
17791 "Decrease the date in the time stamp by one day.
17792 With prefix ARG, change that many days."
17793 (interactive "p")
17794 (if (and (not (org-at-timestamp-p 'lax))
17795 (org-at-heading-p))
17796 (org-todo 'down)
17797 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17799 (defun org-at-timestamp-p (&optional extended)
17800 "Non-nil if point is inside a timestamp.
17802 By default, the function only consider syntactically valid active
17803 timestamps. However, the caller may have a broader definition
17804 for timestamps. As a consequence, optional argument EXTENDED can
17805 be set to the following values
17807 `inactive'
17809 Include also syntactically valid inactive timestamps.
17811 `agenda'
17813 Include timestamps allowed in Agenda, i.e., those in
17814 properties drawers, planning lines and clock lines.
17816 `lax'
17818 Ignore context. The function matches any part of the
17819 document looking like a timestamp. This includes comments,
17820 example blocks...
17822 For backward-compatibility with Org 9.0, every other non-nil
17823 value is equivalent to `inactive'.
17825 When at a timestamp, return the position of the point as a symbol
17826 among `bracket', `after', `year', `month', `hour', `minute',
17827 `day' or a number of character from the last know part of the
17828 time stamp.
17830 When matching, the match groups are the following:
17831 group 1: year
17832 group 2: month
17833 group 3: day number
17834 group 4: day name
17835 group 5: hours, if any
17836 group 6: minutes, if any"
17837 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17838 (pos (point))
17839 (match?
17840 (let ((boundaries (org-in-regexp regexp)))
17841 (save-match-data
17842 (cond ((null boundaries) nil)
17843 ((eq extended 'lax) t)
17845 (or (and (eq extended 'agenda)
17846 (or (org-at-planning-p)
17847 (org-at-property-p)
17848 (and (bound-and-true-p
17849 org-agenda-include-inactive-timestamps)
17850 (org-at-clock-log-p))))
17851 (eq 'timestamp
17852 (save-excursion
17853 (when (= pos (cdr boundaries)) (forward-char -1))
17854 (org-element-type (org-element-context)))))))))))
17855 (cond
17856 ((not match?) nil)
17857 ((= pos (match-beginning 0)) 'bracket)
17858 ;; Distinguish location right before the closing bracket from
17859 ;; right after it.
17860 ((= pos (1- (match-end 0))) 'bracket)
17861 ((= pos (match-end 0)) 'after)
17862 ((org-pos-in-match-range pos 2) 'year)
17863 ((org-pos-in-match-range pos 3) 'month)
17864 ((org-pos-in-match-range pos 7) 'hour)
17865 ((org-pos-in-match-range pos 8) 'minute)
17866 ((or (org-pos-in-match-range pos 4)
17867 (org-pos-in-match-range pos 5)) 'day)
17868 ((and (> pos (or (match-end 8) (match-end 5)))
17869 (< pos (match-end 0)))
17870 (- pos (or (match-end 8) (match-end 5))))
17871 (t 'day))))
17873 (defun org-toggle-timestamp-type ()
17874 "Toggle the type (<active> or [inactive]) of a time stamp."
17875 (interactive)
17876 (when (org-at-timestamp-p 'lax)
17877 (let ((beg (match-beginning 0)) (end (match-end 0))
17878 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17879 (save-excursion
17880 (goto-char beg)
17881 (while (re-search-forward "[][<>]" end t)
17882 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17883 t t)))
17884 (message "Timestamp is now %sactive"
17885 (if (equal (char-after beg) ?<) "" "in")))))
17887 (defun org-at-clock-log-p ()
17888 "Non-nil if point is on a clock log line."
17889 (and (org-match-line org-clock-line-re)
17890 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17892 (defvar org-clock-history) ; defined in org-clock.el
17893 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17894 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17895 "Change the date in the time stamp at point.
17896 The date will be changed by N times WHAT. WHAT can be `day', `month',
17897 `year', `minute', `second'. If WHAT is not given, the cursor position
17898 in the timestamp determines what will be changed.
17899 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17900 (let ((origin (point))
17901 (timestamp? (org-at-timestamp-p 'lax))
17902 origin-cat
17903 with-hm inactive
17904 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17905 extra rem
17906 ts time time0 fixnext clrgx)
17907 (unless timestamp? (user-error "Not at a timestamp"))
17908 (if (and (not what) (eq timestamp? 'bracket))
17909 (org-toggle-timestamp-type)
17910 ;; Point isn't on brackets. Remember the part of the time-stamp
17911 ;; the point was in. Indeed, size of time-stamps may change,
17912 ;; but point must be kept in the same category nonetheless.
17913 (setq origin-cat timestamp?)
17914 (when (and (not what) (not (eq timestamp? 'day))
17915 org-display-custom-times
17916 (get-text-property (point) 'display)
17917 (not (get-text-property (1- (point)) 'display)))
17918 (setq timestamp? 'day))
17919 (setq timestamp? (or what timestamp?)
17920 inactive (= (char-after (match-beginning 0)) ?\[)
17921 ts (match-string 0))
17922 (replace-match "")
17923 (when (string-match
17924 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17926 (setq extra (match-string 1 ts))
17927 (when suppress-tmp-delay
17928 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17929 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17930 (setq with-hm t))
17931 (setq time0 (org-parse-time-string ts))
17932 (when (and updown
17933 (eq timestamp? 'minute)
17934 (not current-prefix-arg))
17935 ;; This looks like s-up and s-down. Change by one rounding step.
17936 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17937 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17938 (setcar (cdr time0) (+ (nth 1 time0)
17939 (if (> n 0) (- rem) (- dm rem))))))
17940 (setq time
17941 (apply #'encode-time
17942 (or (car time0) 0)
17943 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17944 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17945 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17946 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17947 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17948 (nthcdr 6 time0)))
17949 (when (and (memq timestamp? '(hour minute))
17950 extra
17951 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17952 (setq extra (org-modify-ts-extra
17953 extra
17954 (if (eq timestamp? 'hour) 2 5)
17955 n dm)))
17956 (when (integerp timestamp?)
17957 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17958 (when (eq what 'calendar)
17959 (let ((cal-date (org-get-date-from-calendar)))
17960 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17961 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17962 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17963 (setcar time0 (or (car time0) 0))
17964 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17965 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17966 (setq time (apply 'encode-time time0))))
17967 ;; Insert the new time-stamp, and ensure point stays in the same
17968 ;; category as before (i.e. not after the last position in that
17969 ;; category).
17970 (let ((pos (point)))
17971 ;; Stay before inserted string. `save-excursion' is of no use.
17972 (setq org-last-changed-timestamp
17973 (org-insert-time-stamp time with-hm inactive nil nil extra))
17974 (goto-char pos))
17975 (save-match-data
17976 (looking-at org-ts-regexp3)
17977 (goto-char
17978 (pcase origin-cat
17979 ;; `day' category ends before `hour' if any, or at the end
17980 ;; of the day name.
17981 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17982 (`hour (min (match-end 7) origin))
17983 (`minute (min (1- (match-end 8)) origin))
17984 ((pred integerp) (min (1- (match-end 0)) origin))
17985 ;; Point was right after the time-stamp. However, the
17986 ;; time-stamp length might have changed, so refer to
17987 ;; (match-end 0) instead.
17988 (`after (match-end 0))
17989 ;; `year' and `month' have both fixed size: point couldn't
17990 ;; have moved into another part.
17991 (_ origin))))
17992 ;; Update clock if on a CLOCK line.
17993 (org-clock-update-time-maybe)
17994 ;; Maybe adjust the closest clock in `org-clock-history'
17995 (when org-clock-adjust-closest
17996 (if (not (and (org-at-clock-log-p)
17997 (< 1 (length (delq nil (mapcar 'marker-position
17998 org-clock-history))))))
17999 (message "No clock to adjust")
18000 (cond ((save-excursion ; fix previous clock?
18001 (re-search-backward org-ts-regexp0 nil t)
18002 (looking-back (concat org-clock-string " \\[")
18003 (line-beginning-position)))
18004 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18005 ((save-excursion ; fix next clock?
18006 (re-search-backward org-ts-regexp0 nil t)
18007 (looking-at (concat org-ts-regexp0 "\\] =>")))
18008 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18009 (save-window-excursion
18010 ;; Find closest clock to point, adjust the previous/next one in history
18011 (let* ((p (save-excursion (org-back-to-heading t)))
18012 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18013 (clfixnth
18014 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18015 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18016 (if (not clfixpos)
18017 (message "No clock to adjust")
18018 (save-excursion
18019 (org-goto-marker-or-bmk clfixpos)
18020 (org-show-subtree)
18021 (when (re-search-forward clrgx nil t)
18022 (goto-char (match-beginning 1))
18023 (let (org-clock-adjust-closest)
18024 (org-timestamp-change n timestamp? updown))
18025 (message "Clock adjusted in %s for heading: %s"
18026 (file-name-nondirectory (buffer-file-name))
18027 (org-get-heading t t)))))))))
18028 ;; Try to recenter the calendar window, if any.
18029 (when (and org-calendar-follow-timestamp-change
18030 (get-buffer-window "*Calendar*" t)
18031 (memq timestamp? '(day month year)))
18032 (org-recenter-calendar (time-to-days time))))))
18034 (defun org-modify-ts-extra (s pos n dm)
18035 "Change the different parts of the lead-time and repeat fields in timestamp."
18036 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18037 ng h m new rem)
18038 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18039 (cond
18040 ((or (org-pos-in-match-range pos 2)
18041 (org-pos-in-match-range pos 3))
18042 (setq m (string-to-number (match-string 3 s))
18043 h (string-to-number (match-string 2 s)))
18044 (if (org-pos-in-match-range pos 2)
18045 (setq h (+ h n))
18046 (setq n (* dm (with-no-warnings (signum n))))
18047 (unless (= 0 (setq rem (% m dm)))
18048 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18049 (setq m (+ m n)))
18050 (when (< m 0) (setq m (+ m 60) h (1- h)))
18051 (when (> m 59) (setq m (- m 60) h (1+ h)))
18052 (setq h (mod h 24))
18053 (setq ng 1 new (format "-%02d:%02d" h m)))
18054 ((org-pos-in-match-range pos 6)
18055 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18056 ((org-pos-in-match-range pos 5)
18057 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18059 ((org-pos-in-match-range pos 9)
18060 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18061 ((org-pos-in-match-range pos 8)
18062 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18064 (when ng
18065 (setq s (concat
18066 (substring s 0 (match-beginning ng))
18068 (substring s (match-end ng))))))
18071 (defun org-recenter-calendar (d)
18072 "If the calendar is visible, recenter it to date D."
18073 (let ((cwin (get-buffer-window "*Calendar*" t)))
18074 (when cwin
18075 (let ((calendar-move-hook nil))
18076 (with-selected-window cwin
18077 (calendar-goto-date
18078 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18080 (defun org-goto-calendar (&optional arg)
18081 "Go to the Emacs calendar at the current date.
18082 If there is a time stamp in the current line, go to that date.
18083 A prefix ARG can be used to force the current date."
18084 (interactive "P")
18085 (let ((calendar-move-hook nil)
18086 (calendar-view-holidays-initially-flag nil)
18087 (calendar-view-diary-initially-flag nil)
18088 diff)
18089 (when (or (org-at-timestamp-p 'lax)
18090 (org-match-line (concat ".*" org-ts-regexp)))
18091 (let ((d1 (time-to-days (current-time)))
18092 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18093 (setq diff (- d2 d1))))
18094 (calendar)
18095 (calendar-goto-today)
18096 (when (and diff (not arg)) (calendar-forward-day diff))))
18098 (defun org-get-date-from-calendar ()
18099 "Return a list (month day year) of date at point in calendar."
18100 (with-current-buffer "*Calendar*"
18101 (save-match-data
18102 (calendar-cursor-to-date))))
18104 (defun org-date-from-calendar ()
18105 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18106 If there is already a time stamp at the cursor position, update it."
18107 (interactive)
18108 (if (org-at-timestamp-p 'lax)
18109 (org-timestamp-change 0 'calendar)
18110 (let ((cal-date (org-get-date-from-calendar)))
18111 (org-insert-time-stamp
18112 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18114 (defcustom org-effort-durations
18115 `(("min" . 1)
18116 ("h" . 60)
18117 ("d" . ,(* 60 8))
18118 ("w" . ,(* 60 8 5))
18119 ("m" . ,(* 60 8 5 4))
18120 ("y" . ,(* 60 8 5 40)))
18121 "Conversion factor to minutes for an effort modifier.
18123 Each entry has the form (MODIFIER . MINUTES).
18125 In an effort string, a number followed by MODIFIER is multiplied
18126 by the specified number of MINUTES to obtain an effort in
18127 minutes.
18129 For example, if the value of this variable is ((\"hours\" . 60)), then an
18130 effort string \"2hours\" is equivalent to 120 minutes."
18131 :group 'org-agenda
18132 :version "26.1"
18133 :package-version '(Org . "8.3")
18134 :type '(alist :key-type (string :tag "Modifier")
18135 :value-type (number :tag "Minutes")))
18137 (defcustom org-image-actual-width t
18138 "Should we use the actual width of images when inlining them?
18140 When set to t, always use the image width.
18142 When set to a number, use imagemagick (when available) to set
18143 the image's width to this value.
18145 When set to a number in a list, try to get the width from any
18146 #+ATTR.* keyword if it matches a width specification like
18148 #+ATTR_HTML: :width 300px
18150 and fall back on that number if none is found.
18152 When set to nil, try to get the width from an #+ATTR.* keyword
18153 and fall back on the original width if none is found.
18155 This requires Emacs >= 24.1, build with imagemagick support."
18156 :group 'org-appearance
18157 :version "24.4"
18158 :package-version '(Org . "8.0")
18159 :type '(choice
18160 (const :tag "Use the image width" t)
18161 (integer :tag "Use a number of pixels")
18162 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18163 (const :tag "Use #+ATTR* or don't resize" nil)))
18165 (defcustom org-agenda-inhibit-startup nil
18166 "Inhibit startup when preparing agenda buffers.
18167 When this variable is t, the initialization of the Org agenda
18168 buffers is inhibited: e.g. the visibility state is not set, the
18169 tables are not re-aligned, etc."
18170 :type 'boolean
18171 :version "24.3"
18172 :group 'org-agenda)
18174 (defcustom org-agenda-ignore-properties nil
18175 "Avoid updating text properties when building the agenda.
18176 Properties are used to prepare buffers for effort estimates,
18177 appointments, statistics and subtree-local categories.
18178 If you don't use these in the agenda, you can add them to this
18179 list and agenda building will be a bit faster.
18180 The value is a list, with zero or more of the symbols `effort', `appt',
18181 `stats' or `category'."
18182 :type '(set :greedy t
18183 (const effort)
18184 (const appt)
18185 (const stats)
18186 (const category))
18187 :version "26.1"
18188 :package-version '(Org . "8.3")
18189 :group 'org-agenda)
18191 ;;;; Files
18193 (defun org-save-all-org-buffers ()
18194 "Save all Org buffers without user confirmation."
18195 (interactive)
18196 (message "Saving all Org buffers...")
18197 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18198 (when (featurep 'org-id) (org-id-locations-save))
18199 (message "Saving all Org buffers... done"))
18201 (defun org-revert-all-org-buffers ()
18202 "Revert all Org buffers.
18203 Prompt for confirmation when there are unsaved changes.
18204 Be sure you know what you are doing before letting this function
18205 overwrite your changes.
18207 This function is useful in a setup where one tracks org files
18208 with a version control system, to revert on one machine after pulling
18209 changes from another. I believe the procedure must be like this:
18211 1. M-x org-save-all-org-buffers
18212 2. Pull changes from the other machine, resolve conflicts
18213 3. M-x org-revert-all-org-buffers"
18214 (interactive)
18215 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18216 (user-error "Abort"))
18217 (save-excursion
18218 (save-window-excursion
18219 (dolist (b (buffer-list))
18220 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18221 (with-current-buffer b buffer-file-name))
18222 (pop-to-buffer-same-window b)
18223 (revert-buffer t 'no-confirm)))
18224 (when (and (featurep 'org-id) org-id-track-globally)
18225 (org-id-locations-load)))))
18227 ;;;; Agenda files
18229 ;;;###autoload
18230 (defun org-switchb (&optional arg)
18231 "Switch between Org buffers.
18233 With `\\[universal-argument]' prefix, restrict available buffers to files.
18235 With `\\[universal-argument] \\[universal-argument]' \
18236 prefix, restrict available buffers to agenda files."
18237 (interactive "P")
18238 (let ((blist (org-buffer-list
18239 (cond ((equal arg '(4)) 'files)
18240 ((equal arg '(16)) 'agenda)))))
18241 (pop-to-buffer-same-window
18242 (completing-read "Org buffer: "
18243 (mapcar #'list (mapcar #'buffer-name blist))
18244 nil t))))
18246 (defun org-buffer-list (&optional predicate exclude-tmp)
18247 "Return a list of Org buffers.
18248 PREDICATE can be `export', `files' or `agenda'.
18250 export restrict the list to Export buffers.
18251 files restrict the list to buffers visiting Org files.
18252 agenda restrict the list to buffers visiting agenda files.
18254 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18255 (let* ((bfn nil)
18256 (agenda-files (and (eq predicate 'agenda)
18257 (mapcar 'file-truename (org-agenda-files t))))
18258 (filter
18259 (cond
18260 ((eq predicate 'files)
18261 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18262 ((eq predicate 'export)
18263 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18264 ((eq predicate 'agenda)
18265 (lambda (b)
18266 (with-current-buffer b
18267 (and (derived-mode-p 'org-mode)
18268 (setq bfn (buffer-file-name b))
18269 (member (file-truename bfn) agenda-files)))))
18270 (t (lambda (b) (with-current-buffer b
18271 (or (derived-mode-p 'org-mode)
18272 (string-match "\\*Org .*Export"
18273 (buffer-name b)))))))))
18274 (delq nil
18275 (mapcar
18276 (lambda(b)
18277 (if (and (funcall filter b)
18278 (or (not exclude-tmp)
18279 (not (string-match "tmp" (buffer-name b)))))
18281 nil))
18282 (buffer-list)))))
18284 (defun org-agenda-files (&optional unrestricted archives)
18285 "Get the list of agenda files.
18286 Optional UNRESTRICTED means return the full list even if a restriction
18287 is currently in place.
18288 When ARCHIVES is t, include all archive files that are really being
18289 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18290 `org-agenda-archives-mode' is t."
18291 (let ((files
18292 (cond
18293 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18294 ((stringp org-agenda-files) (org-read-agenda-file-list))
18295 ((listp org-agenda-files) org-agenda-files)
18296 (t (error "Invalid value of `org-agenda-files'")))))
18297 (setq files (apply 'append
18298 (mapcar (lambda (f)
18299 (if (file-directory-p f)
18300 (directory-files
18301 f t org-agenda-file-regexp)
18302 (list f)))
18303 files)))
18304 (when org-agenda-skip-unavailable-files
18305 (setq files (delq nil
18306 (mapcar (function
18307 (lambda (file)
18308 (and (file-readable-p file) file)))
18309 files))))
18310 (when (or (eq archives t)
18311 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18312 (setq files (org-add-archive-files files)))
18313 files))
18315 (defun org-agenda-file-p (&optional file)
18316 "Return non-nil, if FILE is an agenda file.
18317 If FILE is omitted, use the file associated with the current
18318 buffer."
18319 (let ((fname (or file (buffer-file-name))))
18320 (and fname
18321 (member (file-truename fname)
18322 (mapcar #'file-truename (org-agenda-files t))))))
18324 (defun org-edit-agenda-file-list ()
18325 "Edit the list of agenda files.
18326 Depending on setup, this either uses customize to edit the variable
18327 `org-agenda-files', or it visits the file that is holding the list. In the
18328 latter case, the buffer is set up in a way that saving it automatically kills
18329 the buffer and restores the previous window configuration."
18330 (interactive)
18331 (if (stringp org-agenda-files)
18332 (let ((cw (current-window-configuration)))
18333 (find-file org-agenda-files)
18334 (setq-local org-window-configuration cw)
18335 (add-hook 'after-save-hook
18336 (lambda ()
18337 (set-window-configuration
18338 (prog1 org-window-configuration
18339 (kill-buffer (current-buffer))))
18340 (org-install-agenda-files-menu)
18341 (message "New agenda file list installed"))
18342 nil 'local)
18343 (message "%s" (substitute-command-keys
18344 "Edit list and finish with \\[save-buffer]")))
18345 (customize-variable 'org-agenda-files)))
18347 (defun org-store-new-agenda-file-list (list)
18348 "Set new value for the agenda file list and save it correctly."
18349 (if (stringp org-agenda-files)
18350 (let ((fe (org-read-agenda-file-list t)) b u)
18351 (while (setq b (find-buffer-visiting org-agenda-files))
18352 (kill-buffer b))
18353 (with-temp-file org-agenda-files
18354 (insert
18355 (mapconcat
18356 (lambda (f) ;; Keep un-expanded entries.
18357 (if (setq u (assoc f fe))
18358 (cdr u)
18360 list "\n")
18361 "\n")))
18362 (let ((org-mode-hook nil) (org-inhibit-startup t)
18363 (org-insert-mode-line-in-empty-file nil))
18364 (setq org-agenda-files list)
18365 (customize-save-variable 'org-agenda-files org-agenda-files))))
18367 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18368 "Read the list of agenda files from a file.
18369 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18370 filenames, used by `org-store-new-agenda-file-list' to write back
18371 un-expanded file names."
18372 (when (file-directory-p org-agenda-files)
18373 (error "`org-agenda-files' cannot be a single directory"))
18374 (when (stringp org-agenda-files)
18375 (with-temp-buffer
18376 (insert-file-contents org-agenda-files)
18377 (mapcar
18378 (lambda (f)
18379 (let ((e (expand-file-name (substitute-in-file-name f)
18380 org-directory)))
18381 (if pair-with-expansion
18382 (cons e f)
18383 e)))
18384 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18386 ;;;###autoload
18387 (defun org-cycle-agenda-files ()
18388 "Cycle through the files in `org-agenda-files'.
18389 If the current buffer visits an agenda file, find the next one in the list.
18390 If the current buffer does not, find the first agenda file."
18391 (interactive)
18392 (let* ((fs (or (org-agenda-files t)
18393 (user-error "No agenda files")))
18394 (files (copy-sequence fs))
18395 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18396 file)
18397 (when tcf
18398 (while (and (setq file (pop files))
18399 (not (equal (file-truename file) tcf)))))
18400 (find-file (car (or files fs)))
18401 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18403 (defun org-agenda-file-to-front (&optional to-end)
18404 "Move/add the current file to the top of the agenda file list.
18405 If the file is not present in the list, it is added to the front. If it is
18406 present, it is moved there. With optional argument TO-END, add/move to the
18407 end of the list."
18408 (interactive "P")
18409 (let ((org-agenda-skip-unavailable-files nil)
18410 (file-alist (mapcar (lambda (x)
18411 (cons (file-truename x) x))
18412 (org-agenda-files t)))
18413 (ctf (file-truename
18414 (or buffer-file-name
18415 (user-error "Please save the current buffer to a file"))))
18416 x had)
18417 (setq x (assoc ctf file-alist) had x)
18419 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18420 (if to-end
18421 (setq file-alist (append (delq x file-alist) (list x)))
18422 (setq file-alist (cons x (delq x file-alist))))
18423 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18424 (org-install-agenda-files-menu)
18425 (message "File %s to %s of agenda file list"
18426 (if had "moved" "added") (if to-end "end" "front"))))
18428 (defun org-remove-file (&optional file)
18429 "Remove current file from the list of files in variable `org-agenda-files'.
18430 These are the files which are being checked for agenda entries.
18431 Optional argument FILE means use this file instead of the current."
18432 (interactive)
18433 (let* ((org-agenda-skip-unavailable-files nil)
18434 (file (or file buffer-file-name
18435 (user-error "Current buffer does not visit a file")))
18436 (true-file (file-truename file))
18437 (afile (abbreviate-file-name file))
18438 (files (delq nil (mapcar
18439 (lambda (x)
18440 (unless (equal true-file
18441 (file-truename x))
18443 (org-agenda-files t)))))
18444 (if (not (= (length files) (length (org-agenda-files t))))
18445 (progn
18446 (org-store-new-agenda-file-list files)
18447 (org-install-agenda-files-menu)
18448 (message "Removed from Org Agenda list: %s" afile))
18449 (message "File was not in list: %s (not removed)" afile))))
18451 (defun org-file-menu-entry (file)
18452 (vector file (list 'find-file file) t))
18454 (defun org-check-agenda-file (file)
18455 "Make sure FILE exists. If not, ask user what to do."
18456 (unless (file-exists-p file)
18457 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18458 (abbreviate-file-name file))
18459 (let ((r (downcase (read-char-exclusive))))
18460 (cond
18461 ((equal r ?r)
18462 (org-remove-file file)
18463 (throw 'nextfile t))
18464 (t (user-error "Abort"))))))
18466 (defun org-get-agenda-file-buffer (file)
18467 "Get an agenda buffer visiting FILE.
18468 If the buffer needs to be created, add it to the list of buffers
18469 which might be released later."
18470 (let ((buf (org-find-base-buffer-visiting file)))
18471 (if buf
18472 buf ; just return it
18473 ;; Make a new buffer and remember it
18474 (setq buf (find-file-noselect file))
18475 (when buf (push buf org-agenda-new-buffers))
18476 buf)))
18478 (defun org-release-buffers (blist)
18479 "Release all buffers in list, asking the user for confirmation when needed.
18480 When a buffer is unmodified, it is just killed. When modified, it is saved
18481 \(if the user agrees) and then killed."
18482 (let (file)
18483 (dolist (buf blist)
18484 (setq file (buffer-file-name buf))
18485 (when (and (buffer-modified-p buf)
18486 file
18487 (y-or-n-p (format "Save file %s? " file)))
18488 (with-current-buffer buf (save-buffer)))
18489 (kill-buffer buf))))
18491 (defun org-agenda-prepare-buffers (files)
18492 "Create buffers for all agenda files, protect archived trees and comments."
18493 (interactive)
18494 (let ((pa '(:org-archived t))
18495 (pc '(:org-comment t))
18496 (pall '(:org-archived t :org-comment t))
18497 (inhibit-read-only t)
18498 (org-inhibit-startup org-agenda-inhibit-startup)
18499 (rea (concat ":" org-archive-tag ":"))
18500 re pos)
18501 (setq org-tag-alist-for-agenda nil
18502 org-tag-groups-alist-for-agenda nil)
18503 (save-excursion
18504 (save-restriction
18505 (dolist (file files)
18506 (catch 'nextfile
18507 (if (bufferp file)
18508 (set-buffer file)
18509 (org-check-agenda-file file)
18510 (set-buffer (org-get-agenda-file-buffer file)))
18511 (widen)
18512 (org-set-regexps-and-options 'tags-only)
18513 (setq pos (point))
18514 (or (memq 'category org-agenda-ignore-properties)
18515 (org-refresh-category-properties))
18516 (or (memq 'stats org-agenda-ignore-properties)
18517 (org-refresh-stats-properties))
18518 (or (memq 'effort org-agenda-ignore-properties)
18519 (org-refresh-effort-properties))
18520 (or (memq 'appt org-agenda-ignore-properties)
18521 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18522 (setq org-todo-keywords-for-agenda
18523 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18524 (setq org-done-keywords-for-agenda
18525 (append org-done-keywords-for-agenda org-done-keywords))
18526 (setq org-todo-keyword-alist-for-agenda
18527 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18528 (setq org-tag-alist-for-agenda
18529 (org-uniquify
18530 (append org-tag-alist-for-agenda
18531 org-current-tag-alist)))
18532 ;; Merge current file's tag groups into global
18533 ;; `org-tag-groups-alist-for-agenda'.
18534 (when org-group-tags
18535 (dolist (alist org-tag-groups-alist)
18536 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18537 (if old
18538 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18539 (push alist org-tag-groups-alist-for-agenda)))))
18540 (org-with-silent-modifications
18541 (save-excursion
18542 (remove-text-properties (point-min) (point-max) pall)
18543 (when org-agenda-skip-archived-trees
18544 (goto-char (point-min))
18545 (while (re-search-forward rea nil t)
18546 (when (org-at-heading-p t)
18547 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18548 (goto-char (point-min))
18549 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18550 (while (re-search-forward re nil t)
18551 (when (save-match-data (org-in-commented-heading-p t))
18552 (add-text-properties
18553 (match-beginning 0) (org-end-of-subtree t) pc)))))
18554 (goto-char pos)))))
18555 (setq org-todo-keywords-for-agenda
18556 (org-uniquify org-todo-keywords-for-agenda))
18557 (setq org-todo-keyword-alist-for-agenda
18558 (org-uniquify org-todo-keyword-alist-for-agenda))))
18561 ;;;; CDLaTeX minor mode
18563 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18564 "Keymap for the minor `org-cdlatex-mode'.")
18566 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18567 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18568 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18569 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18570 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18572 (defvar org-cdlatex-texmathp-advice-is-done nil
18573 "Flag remembering if we have applied the advice to texmathp already.")
18575 (define-minor-mode org-cdlatex-mode
18576 "Toggle the minor `org-cdlatex-mode'.
18577 This mode supports entering LaTeX environment and math in LaTeX fragments
18578 in Org mode.
18579 \\{org-cdlatex-mode-map}"
18580 nil " OCDL" nil
18581 (when org-cdlatex-mode
18582 (require 'cdlatex)
18583 (run-hooks 'cdlatex-mode-hook)
18584 (cdlatex-compute-tables))
18585 (unless org-cdlatex-texmathp-advice-is-done
18586 (setq org-cdlatex-texmathp-advice-is-done t)
18587 (defadvice texmathp (around org-math-always-on activate)
18588 "Always return t in Org buffers.
18589 This is because we want to insert math symbols without dollars even outside
18590 the LaTeX math segments. If Org mode thinks that point is actually inside
18591 an embedded LaTeX fragment, let `texmathp' do its job.
18592 `\\[org-cdlatex-mode-map]'"
18593 (interactive)
18594 (let (p)
18595 (cond
18596 ((not (derived-mode-p 'org-mode)) ad-do-it)
18597 ((eq this-command 'cdlatex-math-symbol)
18598 (setq ad-return-value t
18599 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18601 (let ((p (org-inside-LaTeX-fragment-p)))
18602 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18603 (setq ad-return-value t
18604 texmathp-why '("Org mode embedded math" . 0))
18605 (when p ad-do-it)))))))))
18607 (defun turn-on-org-cdlatex ()
18608 "Unconditionally turn on `org-cdlatex-mode'."
18609 (org-cdlatex-mode 1))
18611 (defun org-try-cdlatex-tab ()
18612 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18613 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18614 - inside a LaTeX fragment, or
18615 - after the first word in a line, where an abbreviation expansion could
18616 insert a LaTeX environment."
18617 (when org-cdlatex-mode
18618 (cond
18619 ;; Before any word on the line: No expansion possible.
18620 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18621 ;; Just after first word on the line: Expand it. Make sure it
18622 ;; cannot happen on headlines, though.
18623 ((save-excursion
18624 (skip-chars-backward "a-zA-Z0-9*")
18625 (skip-chars-backward " \t")
18626 (and (bolp) (not (org-at-heading-p))))
18627 (cdlatex-tab) t)
18628 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18630 (defun org-cdlatex-underscore-caret (&optional _arg)
18631 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18632 Revert to the normal definition outside of these fragments."
18633 (interactive "P")
18634 (if (org-inside-LaTeX-fragment-p)
18635 (call-interactively 'cdlatex-sub-superscript)
18636 (let (org-cdlatex-mode)
18637 (call-interactively (key-binding (vector last-input-event))))))
18639 (defun org-cdlatex-math-modify (&optional _arg)
18640 "Execute `cdlatex-math-modify' in LaTeX fragments.
18641 Revert to the normal definition outside of these fragments."
18642 (interactive "P")
18643 (if (org-inside-LaTeX-fragment-p)
18644 (call-interactively 'cdlatex-math-modify)
18645 (let (org-cdlatex-mode)
18646 (call-interactively (key-binding (vector last-input-event))))))
18648 (defun org-cdlatex-environment-indent (&optional environment item)
18649 "Execute `cdlatex-environment' and indent the inserted environment.
18651 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18653 The inserted environment is indented to current indentation
18654 unless point is at the beginning of the line, in which the
18655 environment remains unintended."
18656 (interactive)
18657 ;; cdlatex-environment always return nil. Therefore, capture output
18658 ;; first and determine if an environment was selected.
18659 (let* ((beg (point-marker))
18660 (end (copy-marker (point) t))
18661 (inserted (progn
18662 (ignore-errors (cdlatex-environment environment item))
18663 (< beg end)))
18664 ;; Figure out how many lines to move forward after the
18665 ;; environment has been inserted.
18666 (lines (when inserted
18667 (save-excursion
18668 (- (cl-loop while (< beg (point))
18669 with x = 0
18670 do (forward-line -1)
18671 (cl-incf x)
18672 finally return x)
18673 (if (progn (goto-char beg)
18674 (and (progn (skip-chars-forward " \t") (eolp))
18675 (progn (skip-chars-backward " \t") (bolp))))
18676 1 0)))))
18677 (env (org-trim (delete-and-extract-region beg end))))
18678 (when inserted
18679 ;; Get indentation of next line unless at column 0.
18680 (let ((ind (if (bolp) 0
18681 (save-excursion
18682 (org-return-indent)
18683 (prog1 (org-get-indentation)
18684 (when (progn (skip-chars-forward " \t") (eolp))
18685 (delete-region beg (point)))))))
18686 (bol (progn (skip-chars-backward " \t") (bolp))))
18687 ;; Insert a newline before environment unless at column zero
18688 ;; to "escape" the current line. Insert a newline if
18689 ;; something is one the same line as \end{ENVIRONMENT}.
18690 (insert
18691 (concat (unless bol "\n") env
18692 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18693 (unless (zerop ind)
18694 (save-excursion
18695 (goto-char beg)
18696 (while (< (point) end)
18697 (unless (eolp) (indent-line-to ind))
18698 (forward-line))))
18699 (goto-char beg)
18700 (forward-line lines)
18701 (indent-line-to ind)))
18702 (set-marker beg nil)
18703 (set-marker end nil)))
18706 ;;;; LaTeX fragments
18708 (defun org-inside-LaTeX-fragment-p ()
18709 "Test if point is inside a LaTeX fragment.
18710 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18711 sequence appearing also before point.
18712 Even though the matchers for math are configurable, this function assumes
18713 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18714 delimiters are skipped when they have been removed by customization.
18715 The return value is nil, or a cons cell with the delimiter and the
18716 position of this delimiter.
18718 This function does a reasonably good job, but can locally be fooled by
18719 for example currency specifications. For example it will assume being in
18720 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18721 fragments that are properly closed, but during editing, we have to live
18722 with the uncertainty caused by missing closing delimiters. This function
18723 looks only before point, not after."
18724 (catch 'exit
18725 (let ((pos (point))
18726 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18727 (lim (save-excursion (org-backward-paragraph) (point)))
18728 dd-on str (start 0) m re)
18729 (goto-char pos)
18730 (when dodollar
18731 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18732 re (nth 1 (assoc "$" org-latex-regexps)))
18733 (while (string-match re str start)
18734 (cond
18735 ((= (match-end 0) (length str))
18736 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18737 ((= (match-end 0) (- (length str) 5))
18738 (throw 'exit nil))
18739 (t (setq start (match-end 0))))))
18740 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18741 (goto-char pos)
18742 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18743 (and (match-beginning 2) (throw 'exit nil))
18744 ;; count $$
18745 (while (re-search-backward "\\$\\$" lim t)
18746 (setq dd-on (not dd-on)))
18747 (goto-char pos)
18748 (when dd-on (cons "$$" m))))))
18750 (defun org-inside-latex-macro-p ()
18751 "Is point inside a LaTeX macro or its arguments?"
18752 (save-match-data
18753 (org-in-regexp
18754 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18756 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18757 "Build an overlay between BEG and END using IMAGE file.
18758 Argument IMAGETYPE is the extension of the displayed image,
18759 as a string. It defaults to \"png\"."
18760 (let ((ov (make-overlay beg end))
18761 (imagetype (or (intern imagetype) 'png)))
18762 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18763 (overlay-put ov 'evaporate t)
18764 (overlay-put ov
18765 'modification-hooks
18766 (list (lambda (o _flag _beg _end &optional _l)
18767 (delete-overlay o))))
18768 (overlay-put ov
18769 'display
18770 (list 'image :type imagetype :file image :ascent 'center))))
18772 (defun org--list-latex-overlays (&optional beg end)
18773 "List all Org LaTeX overlays in current buffer.
18774 Limit to overlays between BEG and END when those are provided."
18775 (cl-remove-if-not
18776 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18777 (overlays-in (or beg (point-min)) (or end (point-max)))))
18779 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18780 "Remove all overlays with LaTeX fragment images in current buffer.
18781 When optional arguments BEG and END are non-nil, remove all
18782 overlays between them instead. Return a non-nil value when some
18783 overlays were removed, nil otherwise."
18784 (let ((overlays (org--list-latex-overlays beg end)))
18785 (mapc #'delete-overlay overlays)
18786 overlays))
18788 (defun org-toggle-latex-fragment (&optional arg)
18789 "Preview the LaTeX fragment at point, or all locally or globally.
18791 If the cursor is on a LaTeX fragment, create the image and overlay
18792 it over the source code, if there is none. Remove it otherwise.
18793 If there is no fragment at point, display all fragments in the
18794 current section.
18796 With prefix ARG, preview or clear image for all fragments in the
18797 current subtree or in the whole buffer when used before the first
18798 headline. With a prefix ARG `\\[universal-argument] \
18799 \\[universal-argument]' preview or clear images
18800 for all fragments in the buffer."
18801 (interactive "P")
18802 (when (display-graphic-p)
18803 (catch 'exit
18804 (save-excursion
18805 (let (beg end msg)
18806 (cond
18807 ((or (equal arg '(16))
18808 (and (equal arg '(4))
18809 (org-with-limited-levels (org-before-first-heading-p))))
18810 (if (org-remove-latex-fragment-image-overlays)
18811 (progn (message "LaTeX fragments images removed from buffer")
18812 (throw 'exit nil))
18813 (setq msg "Creating images for buffer...")))
18814 ((equal arg '(4))
18815 (org-with-limited-levels (org-back-to-heading t))
18816 (setq beg (point))
18817 (setq end (progn (org-end-of-subtree t) (point)))
18818 (if (org-remove-latex-fragment-image-overlays beg end)
18819 (progn
18820 (message "LaTeX fragment images removed from subtree")
18821 (throw 'exit nil))
18822 (setq msg "Creating images for subtree...")))
18823 ((let ((datum (org-element-context)))
18824 (when (memq (org-element-type datum)
18825 '(latex-environment latex-fragment))
18826 (setq beg (org-element-property :begin datum))
18827 (setq end (org-element-property :end datum))
18828 (if (org-remove-latex-fragment-image-overlays beg end)
18829 (progn (message "LaTeX fragment image removed")
18830 (throw 'exit nil))
18831 (setq msg "Creating image...")))))
18833 (org-with-limited-levels
18834 (setq beg (if (org-at-heading-p) (line-beginning-position)
18835 (outline-previous-heading)
18836 (point)))
18837 (setq end (progn (outline-next-heading) (point)))
18838 (if (org-remove-latex-fragment-image-overlays beg end)
18839 (progn
18840 (message "LaTeX fragment images removed from section")
18841 (throw 'exit nil))
18842 (setq msg "Creating images for section...")))))
18843 (let ((file (buffer-file-name (buffer-base-buffer))))
18844 (org-format-latex
18845 (concat org-preview-latex-image-directory "org-ltximg")
18846 beg end
18847 ;; Emacs cannot overlay images from remote hosts. Create
18848 ;; it in `temporary-file-directory' instead.
18849 (if (or (not file) (file-remote-p file))
18850 temporary-file-directory
18851 default-directory)
18852 'overlays msg 'forbuffer org-preview-latex-default-process))
18853 (message (concat msg "done")))))))
18855 (defun org-format-latex
18856 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18857 "Replace LaTeX fragments with links to an image.
18859 The function takes care of creating the replacement image.
18861 Only consider fragments between BEG and END when those are
18862 provided.
18864 When optional argument OVERLAYS is non-nil, display the image on
18865 top of the fragment instead of replacing it.
18867 PROCESSING-TYPE is the conversion method to use, as a symbol.
18869 Some of the options can be changed using the variable
18870 `org-format-latex-options', which see."
18871 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18872 (unless (eq processing-type 'verbatim)
18873 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18874 (cnt 0)
18875 checkdir-flag)
18876 (goto-char (or beg (point-min)))
18877 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18878 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18879 (overlay-recenter (or end (point-max))))
18880 (while (re-search-forward math-regexp end t)
18881 (unless (and overlays
18882 (eq (get-char-property (point) 'org-overlay-type)
18883 'org-latex-overlay))
18884 (let* ((context (org-element-context))
18885 (type (org-element-type context)))
18886 (when (memq type '(latex-environment latex-fragment))
18887 (let ((block-type (eq type 'latex-environment))
18888 (value (org-element-property :value context))
18889 (beg (org-element-property :begin context))
18890 (end (save-excursion
18891 (goto-char (org-element-property :end context))
18892 (skip-chars-backward " \r\t\n")
18893 (point))))
18894 (cond
18895 ((eq processing-type 'mathjax)
18896 ;; Prepare for MathJax processing.
18897 (if (not (string-match "\\`\\$\\$?" value))
18898 (goto-char end)
18899 (delete-region beg end)
18900 (if (string= (match-string 0 value) "$$")
18901 (insert "\\[" (substring value 2 -2) "\\]")
18902 (insert "\\(" (substring value 1 -1) "\\)"))))
18903 ((assq processing-type org-preview-latex-process-alist)
18904 ;; Process to an image.
18905 (cl-incf cnt)
18906 (goto-char beg)
18907 (let* ((processing-info
18908 (cdr (assq processing-type org-preview-latex-process-alist)))
18909 (face (face-at-point))
18910 ;; Get the colors from the face at point.
18912 (let ((color (plist-get org-format-latex-options
18913 :foreground)))
18914 (if (and forbuffer (eq color 'auto))
18915 (face-attribute face :foreground nil 'default)
18916 color)))
18918 (let ((color (plist-get org-format-latex-options
18919 :background)))
18920 (if (and forbuffer (eq color 'auto))
18921 (face-attribute face :background nil 'default)
18922 color)))
18923 (hash (sha1 (prin1-to-string
18924 (list org-format-latex-header
18925 org-latex-default-packages-alist
18926 org-latex-packages-alist
18927 org-format-latex-options
18928 forbuffer value fg bg))))
18929 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18930 (absprefix (expand-file-name prefix dir))
18931 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18932 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18933 (sep (and block-type "\n\n"))
18934 (link (concat sep "[[file:" linkfile "]]" sep))
18935 (options
18936 (org-combine-plists
18937 org-format-latex-options
18938 `(:foreground ,fg :background ,bg))))
18939 (when msg (message msg cnt))
18940 (unless checkdir-flag ; Ensure the directory exists.
18941 (setq checkdir-flag t)
18942 (let ((todir (file-name-directory absprefix)))
18943 (unless (file-directory-p todir)
18944 (make-directory todir t))))
18945 (unless (file-exists-p movefile)
18946 (org-create-formula-image
18947 value movefile options forbuffer processing-type))
18948 (if overlays
18949 (progn
18950 (dolist (o (overlays-in beg end))
18951 (when (eq (overlay-get o 'org-overlay-type)
18952 'org-latex-overlay)
18953 (delete-overlay o)))
18954 (org--format-latex-make-overlay beg end movefile imagetype)
18955 (goto-char end))
18956 (delete-region beg end)
18957 (insert
18958 (org-add-props link
18959 (list 'org-latex-src
18960 (replace-regexp-in-string "\"" "" value)
18961 'org-latex-src-embed-type
18962 (if block-type 'paragraph 'character)))))))
18963 ((eq processing-type 'mathml)
18964 ;; Process to MathML.
18965 (unless (org-format-latex-mathml-available-p)
18966 (user-error "LaTeX to MathML converter not configured"))
18967 (cl-incf cnt)
18968 (when msg (message msg cnt))
18969 (goto-char beg)
18970 (delete-region beg end)
18971 (insert (org-format-latex-as-mathml
18972 value block-type prefix dir)))
18974 (error "Unknown conversion process %s for LaTeX fragments"
18975 processing-type)))))))))))
18977 (defun org-create-math-formula (latex-frag &optional mathml-file)
18978 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18979 Use `org-latex-to-mathml-convert-command'. If the conversion is
18980 sucessful, return the portion between \"<math...> </math>\"
18981 elements otherwise return nil. When MATHML-FILE is specified,
18982 write the results in to that file. When invoked as an
18983 interactive command, prompt for LATEX-FRAG, with initial value
18984 set to the current active region and echo the results for user
18985 inspection."
18986 (interactive (list (let ((frag (when (org-region-active-p)
18987 (buffer-substring-no-properties
18988 (region-beginning) (region-end)))))
18989 (read-string "LaTeX Fragment: " frag nil frag))))
18990 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18991 (let* ((tmp-in-file
18992 (let ((file (file-relative-name
18993 (make-temp-name (expand-file-name "ltxmathml-in")))))
18994 (write-region latex-frag nil file)
18995 file))
18996 (tmp-out-file (file-relative-name
18997 (make-temp-name (expand-file-name "ltxmathml-out"))))
18998 (cmd (format-spec
18999 org-latex-to-mathml-convert-command
19000 `((?j . ,(and org-latex-to-mathml-jar-file
19001 (shell-quote-argument
19002 (expand-file-name
19003 org-latex-to-mathml-jar-file))))
19004 (?I . ,(shell-quote-argument tmp-in-file))
19005 (?i . ,latex-frag)
19006 (?o . ,(shell-quote-argument tmp-out-file)))))
19007 mathml shell-command-output)
19008 (when (called-interactively-p 'any)
19009 (unless (org-format-latex-mathml-available-p)
19010 (user-error "LaTeX to MathML converter not configured")))
19011 (message "Running %s" cmd)
19012 (setq shell-command-output (shell-command-to-string cmd))
19013 (setq mathml
19014 (when (file-readable-p tmp-out-file)
19015 (with-current-buffer (find-file-noselect tmp-out-file t)
19016 (goto-char (point-min))
19017 (when (re-search-forward
19018 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19019 (regexp-quote
19020 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19021 nil t)
19022 (prog1 (match-string 0) (kill-buffer))))))
19023 (cond
19024 (mathml
19025 (setq mathml
19026 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19027 (when mathml-file
19028 (write-region mathml nil mathml-file))
19029 (when (called-interactively-p 'any)
19030 (message mathml)))
19031 ((message "LaTeX to MathML conversion failed")
19032 (message shell-command-output)))
19033 (delete-file tmp-in-file)
19034 (when (file-exists-p tmp-out-file)
19035 (delete-file tmp-out-file))
19036 mathml))
19038 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19039 prefix &optional dir)
19040 "Use `org-create-math-formula' but check local cache first."
19041 (let* ((absprefix (expand-file-name prefix dir))
19042 (print-length nil) (print-level nil)
19043 (formula-id (concat
19044 "formula-"
19045 (sha1
19046 (prin1-to-string
19047 (list latex-frag
19048 org-latex-to-mathml-convert-command)))))
19049 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19050 (formula-cache-dir (file-name-directory formula-cache)))
19052 (unless (file-directory-p formula-cache-dir)
19053 (make-directory formula-cache-dir t))
19055 (unless (file-exists-p formula-cache)
19056 (org-create-math-formula latex-frag formula-cache))
19058 (if (file-exists-p formula-cache)
19059 ;; Successful conversion. Return the link to MathML file.
19060 (org-add-props
19061 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19062 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19063 'org-latex-src-embed-type (if latex-frag-type
19064 'paragraph 'character)))
19065 ;; Failed conversion. Return the LaTeX fragment verbatim
19066 latex-frag)))
19068 (defun org--get-display-dpi ()
19069 "Get the DPI of the display.
19070 The function assumes that the display has the same pixel width in
19071 the horizontal and vertical directions."
19072 (if (display-graphic-p)
19073 (round (/ (display-pixel-height)
19074 (/ (display-mm-height) 25.4)))
19075 (error "Attempt to calculate the dpi of a non-graphic display")))
19077 (defun org-create-formula-image
19078 (string tofile options buffer &optional processing-type)
19079 "Create an image from LaTeX source using external processes.
19081 The LaTeX STRING is saved to a temporary LaTeX file, then
19082 converted to an image file by process PROCESSING-TYPE defined in
19083 `org-preview-latex-process-alist'. A nil value defaults to
19084 `org-preview-latex-default-process'.
19086 The generated image file is eventually moved to TOFILE.
19088 The OPTIONS argument controls the size, foreground color and
19089 background color of the generated image.
19091 When BUFFER non-nil, this function is used for LaTeX previewing.
19092 Otherwise, it is used to deal with LaTeX snippets showed in
19093 a HTML file."
19094 (let* ((processing-type (or processing-type
19095 org-preview-latex-default-process))
19096 (processing-info
19097 (cdr (assq processing-type org-preview-latex-process-alist)))
19098 (programs (plist-get processing-info :programs))
19099 (error-message (or (plist-get processing-info :message) ""))
19100 (use-xcolor (plist-get processing-info :use-xcolor))
19101 (image-input-type (plist-get processing-info :image-input-type))
19102 (image-output-type (plist-get processing-info :image-output-type))
19103 (post-clean (or (plist-get processing-info :post-clean)
19104 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19105 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19106 (latex-header
19107 (or (plist-get processing-info :latex-header)
19108 (org-latex-make-preamble
19109 (org-export-get-environment (org-export-get-backend 'latex))
19110 org-format-latex-header
19111 'snippet)))
19112 (latex-compiler (plist-get processing-info :latex-compiler))
19113 (image-converter (plist-get processing-info :image-converter))
19114 (tmpdir temporary-file-directory)
19115 (texfilebase (make-temp-name
19116 (expand-file-name "orgtex" tmpdir)))
19117 (texfile (concat texfilebase ".tex"))
19118 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19119 '(1.0 . 1.0)))
19120 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19121 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19122 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19123 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19124 "Black"))
19125 (bg (or (plist-get options (if buffer :background :html-background))
19126 "Transparent"))
19127 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19128 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19129 (dolist (program programs)
19130 (org-check-external-command program error-message))
19131 (if use-xcolor
19132 (progn (if (eq fg 'default)
19133 (setq fg (org-latex-color :foreground))
19134 (setq fg (org-latex-color-format fg)))
19135 (if (eq bg 'default)
19136 (setq bg (org-latex-color :background))
19137 (setq bg (org-latex-color-format
19138 (if (string= bg "Transparent") "white" bg))))
19139 (with-temp-file texfile
19140 (insert latex-header)
19141 (insert "\n\\begin{document}\n"
19142 "\\definecolor{fg}{rgb}{" fg "}\n"
19143 "\\definecolor{bg}{rgb}{" bg "}\n"
19144 "\n\\pagecolor{bg}\n"
19145 "\n{\\color{fg}\n"
19146 string
19147 "\n}\n"
19148 "\n\\end{document}\n")))
19149 (if (eq fg 'default)
19150 (setq fg (org-dvipng-color :foreground))
19151 (unless (string= fg "Transparent")
19152 (setq fg (org-dvipng-color-format fg))))
19153 (if (eq bg 'default)
19154 (setq bg (org-dvipng-color :background))
19155 (unless (string= bg "Transparent")
19156 (setq bg (org-dvipng-color-format bg))))
19157 (with-temp-file texfile
19158 (insert latex-header)
19159 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19161 (let* ((err-msg (format "Please adjust `%s' part of \
19162 `org-preview-latex-process-alist'."
19163 processing-type))
19164 (image-input-file
19165 (org-compile-file
19166 texfile latex-compiler image-input-type err-msg log-buf))
19167 (image-output-file
19168 (org-compile-file
19169 image-input-file image-converter image-output-type err-msg log-buf
19170 `((?F . ,(shell-quote-argument fg))
19171 (?B . ,(shell-quote-argument bg))
19172 (?D . ,(shell-quote-argument (format "%s" dpi)))
19173 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19174 (copy-file image-output-file tofile 'replace)
19175 (dolist (e post-clean)
19176 (when (file-exists-p (concat texfilebase e))
19177 (delete-file (concat texfilebase e))))
19178 image-output-file)))
19180 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19181 "Fill a LaTeX header template TPL.
19182 In the template, the following place holders will be recognized:
19184 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19185 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19186 [PACKAGES] \\usepackage statements for PKG
19187 [NO-PACKAGES] do not include PKG
19188 [EXTRA] the string EXTRA
19189 [NO-EXTRA] do not include EXTRA
19191 For backward compatibility, if both the positive and the negative place
19192 holder is missing, the positive one (without the \"NO-\") will be
19193 assumed to be present at the end of the template.
19194 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19195 EXTRA is a string.
19196 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19197 (let (rpl (end ""))
19198 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19199 (setq rpl (if (or (match-end 1) (not def-pkg))
19200 "" (org-latex-packages-to-string def-pkg snippets-p t))
19201 tpl (replace-match rpl t t tpl))
19202 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19204 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19205 (setq rpl (if (or (match-end 1) (not pkg))
19206 "" (org-latex-packages-to-string pkg snippets-p t))
19207 tpl (replace-match rpl t t tpl))
19208 (when pkg (setq end
19209 (concat end "\n"
19210 (org-latex-packages-to-string pkg snippets-p)))))
19212 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19213 (setq rpl (if (or (match-end 1) (not extra))
19214 "" (concat extra "\n"))
19215 tpl (replace-match rpl t t tpl))
19216 (when (and extra (string-match "\\S-" extra))
19217 (setq end (concat end "\n" extra))))
19219 (if (string-match "\\S-" end)
19220 (concat tpl "\n" end)
19221 tpl)))
19223 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19224 "Turn an alist of packages into a string with the \\usepackage macros."
19225 (setq pkg (mapconcat (lambda(p)
19226 (cond
19227 ((stringp p) p)
19228 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19229 (format "%% Package %s omitted" (cadr p)))
19230 ((equal "" (car p))
19231 (format "\\usepackage{%s}" (cadr p)))
19233 (format "\\usepackage[%s]{%s}"
19234 (car p) (cadr p)))))
19236 "\n"))
19237 (if newline (concat pkg "\n") pkg))
19239 (defun org-dvipng-color (attr)
19240 "Return a RGB color specification for dvipng."
19241 (org-dvipng-color-format (face-attribute 'default attr nil)))
19243 (defun org-dvipng-color-format (color-name)
19244 "Convert COLOR-NAME to a RGB color value for dvipng."
19245 (apply #'format "rgb %s %s %s"
19246 (mapcar 'org-normalize-color
19247 (color-values color-name))))
19249 (defun org-latex-color (attr)
19250 "Return a RGB color for the LaTeX color package."
19251 (org-latex-color-format (face-attribute 'default attr nil)))
19253 (defun org-latex-color-format (color-name)
19254 "Convert COLOR-NAME to a RGB color value."
19255 (apply #'format "%s,%s,%s"
19256 (mapcar 'org-normalize-color
19257 (color-values color-name))))
19259 (defun org-normalize-color (value)
19260 "Return string to be used as color value for an RGB component."
19261 (format "%g" (/ value 65535.0)))
19265 ;; Image display
19267 (defvar-local org-inline-image-overlays nil)
19269 (defun org-toggle-inline-images (&optional include-linked)
19270 "Toggle the display of inline images.
19271 INCLUDE-LINKED is passed to `org-display-inline-images'."
19272 (interactive "P")
19273 (if org-inline-image-overlays
19274 (progn
19275 (org-remove-inline-images)
19276 (when (called-interactively-p 'interactive)
19277 (message "Inline image display turned off")))
19278 (org-display-inline-images include-linked)
19279 (when (called-interactively-p 'interactive)
19280 (message (if org-inline-image-overlays
19281 (format "%d images displayed inline"
19282 (length org-inline-image-overlays))
19283 "No images to display inline")))))
19285 (defun org-redisplay-inline-images ()
19286 "Refresh the display of inline images."
19287 (interactive)
19288 (if (not org-inline-image-overlays)
19289 (org-toggle-inline-images)
19290 (org-toggle-inline-images)
19291 (org-toggle-inline-images)))
19293 (defun org-display-inline-images (&optional include-linked refresh beg end)
19294 "Display inline images.
19296 An inline image is a link which follows either of these
19297 conventions:
19299 1. Its path is a file with an extension matching return value
19300 from `image-file-name-regexp' and it has no contents.
19302 2. Its description consists in a single link of the previous
19303 type.
19305 When optional argument INCLUDE-LINKED is non-nil, also links with
19306 a text description part will be inlined. This can be nice for
19307 a quick look at those images, but it does not reflect what
19308 exported files will look like.
19310 When optional argument REFRESH is non-nil, refresh existing
19311 images between BEG and END. This will create new image displays
19312 only if necessary. BEG and END default to the buffer
19313 boundaries."
19314 (interactive "P")
19315 (when (display-graphic-p)
19316 (unless refresh
19317 (org-remove-inline-images)
19318 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19319 (org-with-wide-buffer
19320 (goto-char (or beg (point-min)))
19321 (let* ((case-fold-search t)
19322 (file-extension-re (image-file-name-regexp))
19323 (link-abbrevs (mapcar #'car
19324 (append org-link-abbrev-alist-local
19325 org-link-abbrev-alist)))
19326 ;; Check absolute, relative file names and explicit
19327 ;; "file:" links. Also check link abbreviations since
19328 ;; some might expand to "file" links.
19329 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19330 (and link-abbrevs
19331 (format "\\|\\(?:%s:\\)"
19332 (regexp-opt link-abbrevs))))))
19333 (while (re-search-forward file-types-re end t)
19334 (let ((link (save-match-data (org-element-context))))
19335 ;; Check if we're at an inline image, i.e., an image file
19336 ;; link without a description (unless INCLUDE-LINKED is
19337 ;; non-nil).
19338 (when (and (equal "file" (org-element-property :type link))
19339 (or include-linked
19340 (null (org-element-contents link)))
19341 (string-match-p file-extension-re
19342 (org-element-property :path link)))
19343 (let ((file (expand-file-name
19344 (org-link-unescape
19345 (org-element-property :path link)))))
19346 (when (file-exists-p file)
19347 (let ((width
19348 ;; Apply `org-image-actual-width' specifications.
19349 (cond
19350 ((not (image-type-available-p 'imagemagick)) nil)
19351 ((eq org-image-actual-width t) nil)
19352 ((listp org-image-actual-width)
19354 ;; First try to find a width among
19355 ;; attributes associated to the paragraph
19356 ;; containing link.
19357 (let ((paragraph
19358 (let ((e link))
19359 (while (and (setq e (org-element-property
19360 :parent e))
19361 (not (eq (org-element-type e)
19362 'paragraph))))
19363 e)))
19364 (when paragraph
19365 (save-excursion
19366 (goto-char (org-element-property :begin paragraph))
19367 (when
19368 (re-search-forward
19369 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19370 (org-element-property
19371 :post-affiliated paragraph)
19373 (string-to-number (match-string 1))))))
19374 ;; Otherwise, fall-back to provided number.
19375 (car org-image-actual-width)))
19376 ((numberp org-image-actual-width)
19377 org-image-actual-width)))
19378 (old (get-char-property-and-overlay
19379 (org-element-property :begin link)
19380 'org-image-overlay)))
19381 (if (and (car-safe old) refresh)
19382 (image-refresh (overlay-get (cdr old) 'display))
19383 (let ((image (create-image file
19384 (and width 'imagemagick)
19386 :width width)))
19387 (when image
19388 (let ((ov (make-overlay
19389 (org-element-property :begin link)
19390 (progn
19391 (goto-char
19392 (org-element-property :end link))
19393 (skip-chars-backward " \t")
19394 (point)))))
19395 (overlay-put ov 'display image)
19396 (overlay-put ov 'face 'default)
19397 (overlay-put ov 'org-image-overlay t)
19398 (overlay-put
19399 ov 'modification-hooks
19400 (list 'org-display-inline-remove-overlay))
19401 (push ov org-inline-image-overlays)))))))))))))))
19403 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19404 "Remove inline-display overlay if a corresponding region is modified."
19405 (let ((inhibit-modification-hooks t))
19406 (when (and ov after)
19407 (delete ov org-inline-image-overlays)
19408 (delete-overlay ov))))
19410 (defun org-remove-inline-images ()
19411 "Remove inline display of images."
19412 (interactive)
19413 (mapc #'delete-overlay org-inline-image-overlays)
19414 (setq org-inline-image-overlays nil))
19416 ;;;; Key bindings
19418 (defun org-remap (map &rest commands)
19419 "In MAP, remap the functions given in COMMANDS.
19420 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19421 (let (new old)
19422 (while commands
19423 (setq old (pop commands) new (pop commands))
19424 (org-defkey map (vector 'remap old) new))))
19426 ;; Outline functions from `outline-mode-prefix-map'
19427 ;; that can be remapped in Org:
19428 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19429 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19430 (define-key org-mode-map [remap outline-forward-same-level]
19431 'org-forward-heading-same-level)
19432 (define-key org-mode-map [remap outline-backward-same-level]
19433 'org-backward-heading-same-level)
19434 (define-key org-mode-map [remap outline-show-branches]
19435 'org-kill-note-or-show-branches)
19436 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19437 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19438 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19439 (define-key org-mode-map [remap outline-next-visible-heading]
19440 'org-next-visible-heading)
19441 (define-key org-mode-map [remap outline-previous-visible-heading]
19442 'org-previous-visible-heading)
19443 (define-key org-mode-map [remap show-children] 'org-show-children)
19445 ;; Outline functions from `outline-mode-prefix-map' that can not
19446 ;; be remapped in Org:
19448 ;; - the column "key binding" shows whether the Outline function is still
19449 ;; available in Org mode on the same key that it has been bound to in
19450 ;; Outline mode:
19451 ;; - "overridden": key used for a different functionality in Org mode
19452 ;; - else: key still bound to the same Outline function in Org mode
19454 ;; | Outline function | key binding | Org replacement |
19455 ;; |------------------------------------+-------------+--------------------------|
19456 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19457 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19458 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19459 ;; | `show-entry' | overridden | no replacement |
19460 ;; | `show-branches' | `C-c C-k' | still same function |
19461 ;; | `show-subtree' | overridden | visibility cycling |
19462 ;; | `show-all' | overridden | no replacement |
19463 ;; | `hide-subtree' | overridden | visibility cycling |
19464 ;; | `hide-body' | overridden | no replacement |
19465 ;; | `hide-entry' | overridden | visibility cycling |
19466 ;; | `hide-leaves' | overridden | no replacement |
19467 ;; | `hide-sublevels' | overridden | no replacement |
19468 ;; | `hide-other' | overridden | no replacement |
19470 ;; Make `C-c C-x' a prefix key
19471 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19473 ;; TAB key with modifiers
19474 (org-defkey org-mode-map "\C-i" 'org-cycle)
19475 (org-defkey org-mode-map [(tab)] 'org-cycle)
19476 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19477 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19479 ;; The following line is necessary under Suse GNU/Linux
19480 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19481 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19482 (define-key org-mode-map [backtab] 'org-shifttab)
19484 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19485 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19486 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19488 ;; Cursor keys with modifiers
19489 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19490 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19491 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19492 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19494 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19495 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19496 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19497 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19498 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19499 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19501 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19502 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19503 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19504 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19506 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19507 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19508 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19509 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19511 ;; Babel keys
19512 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19513 (dolist (pair org-babel-key-bindings)
19514 (define-key org-babel-map (car pair) (cdr pair)))
19516 ;;; Extra keys for tty access.
19517 ;; We only set them when really needed because otherwise the
19518 ;; menus don't show the simple keys
19520 (when (or org-use-extra-keys (not window-system))
19521 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19522 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19523 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19524 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19525 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19526 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19527 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19528 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19529 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19530 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19531 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19532 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19533 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19534 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19535 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19536 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19537 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19538 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19539 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19540 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19541 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19542 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19543 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19544 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19545 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19546 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19547 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19548 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19550 ;; All the other keys
19551 (org-remap org-mode-map
19552 'self-insert-command 'org-self-insert-command
19553 'delete-char 'org-delete-char
19554 'delete-backward-char 'org-delete-backward-char)
19555 (org-defkey org-mode-map "|" 'org-force-self-insert)
19557 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19558 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19559 (if (boundp 'narrow-map)
19560 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19561 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19562 (if (boundp 'narrow-map)
19563 (org-defkey narrow-map "b" 'org-narrow-to-block)
19564 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19565 (if (boundp 'narrow-map)
19566 (org-defkey narrow-map "e" 'org-narrow-to-element)
19567 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19568 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19569 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19570 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19571 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19572 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19573 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19574 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19575 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19576 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19577 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19578 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19579 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19580 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19581 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19582 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19583 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19584 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19585 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19586 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19587 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19588 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19589 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19590 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19591 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19592 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19593 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19594 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19595 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19596 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19597 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19598 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19599 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19600 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19601 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19602 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19603 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19604 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19605 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19606 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19607 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19608 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19609 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19610 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19611 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19612 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19613 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19614 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19615 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19616 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19617 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19618 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19619 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19620 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19621 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19622 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19623 (org-defkey org-mode-map "\C-c^" 'org-sort)
19624 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19625 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19626 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19627 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19628 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19629 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19630 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19631 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19632 (org-defkey org-mode-map "\C-m" 'org-return)
19633 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19634 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19635 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19636 (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
19637 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19638 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19639 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19640 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19641 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19642 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19643 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19644 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19645 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19646 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19647 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19648 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19649 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19650 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19651 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19652 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19653 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19654 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19655 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19656 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19657 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19658 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19660 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19661 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19662 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19664 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19665 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19666 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19667 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19668 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19669 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19670 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19671 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19672 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19673 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19674 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19675 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19676 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19677 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19678 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19679 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19680 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19681 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19682 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19683 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19684 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19685 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19687 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19688 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19689 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19690 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19691 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19693 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19695 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19697 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19698 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19700 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19703 (defconst org-speed-commands-default
19705 ("Outline Navigation")
19706 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19707 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19708 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19709 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19710 ("F" . org-next-block)
19711 ("B" . org-previous-block)
19712 ("u" . (org-speed-move-safe 'outline-up-heading))
19713 ("j" . org-goto)
19714 ("g" . (org-refile t))
19715 ("Outline Visibility")
19716 ("c" . org-cycle)
19717 ("C" . org-shifttab)
19718 (" " . org-display-outline-path)
19719 ("s" . org-narrow-to-subtree)
19720 ("=" . org-columns)
19721 ("Outline Structure Editing")
19722 ("U" . org-metaup)
19723 ("D" . org-metadown)
19724 ("r" . org-metaright)
19725 ("l" . org-metaleft)
19726 ("R" . org-shiftmetaright)
19727 ("L" . org-shiftmetaleft)
19728 ("i" . (progn (forward-char 1) (call-interactively
19729 'org-insert-heading-respect-content)))
19730 ("^" . org-sort)
19731 ("w" . org-refile)
19732 ("a" . org-archive-subtree-default-with-confirmation)
19733 ("@" . org-mark-subtree)
19734 ("#" . org-toggle-comment)
19735 ("Clock Commands")
19736 ("I" . org-clock-in)
19737 ("O" . org-clock-out)
19738 ("Meta Data Editing")
19739 ("t" . org-todo)
19740 ("," . (org-priority))
19741 ("0" . (org-priority ?\ ))
19742 ("1" . (org-priority ?A))
19743 ("2" . (org-priority ?B))
19744 ("3" . (org-priority ?C))
19745 (":" . org-set-tags-command)
19746 ("e" . org-set-effort)
19747 ("E" . org-inc-effort)
19748 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19749 (org-entry-put (point) "APPT_WARNTIME" m)))
19750 ("Agenda Views etc")
19751 ("v" . org-agenda)
19752 ("/" . org-sparse-tree)
19753 ("Misc")
19754 ("o" . org-open-at-point)
19755 ("?" . org-speed-command-help)
19756 ("<" . (org-agenda-set-restriction-lock 'subtree))
19757 (">" . (org-agenda-remove-restriction-lock))
19759 "The default speed commands.")
19761 (defun org-print-speed-command (e)
19762 (if (> (length (car e)) 1)
19763 (progn
19764 (princ "\n")
19765 (princ (car e))
19766 (princ "\n")
19767 (princ (make-string (length (car e)) ?-))
19768 (princ "\n"))
19769 (princ (car e))
19770 (princ " ")
19771 (if (symbolp (cdr e))
19772 (princ (symbol-name (cdr e)))
19773 (prin1 (cdr e)))
19774 (princ "\n")))
19776 (defun org-speed-command-help ()
19777 "Show the available speed commands."
19778 (interactive)
19779 (if (not org-use-speed-commands)
19780 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19781 (with-output-to-temp-buffer "*Help*"
19782 (princ "User-defined Speed commands\n===========================\n")
19783 (mapc #'org-print-speed-command org-speed-commands-user)
19784 (princ "\n")
19785 (princ "Built-in Speed commands\n=======================\n")
19786 (mapc #'org-print-speed-command org-speed-commands-default))
19787 (with-current-buffer "*Help*"
19788 (setq truncate-lines t))))
19790 (defun org-speed-move-safe (cmd)
19791 "Execute CMD, but make sure that the cursor always ends up in a headline.
19792 If not, return to the original position and throw an error."
19793 (interactive)
19794 (let ((pos (point)))
19795 (call-interactively cmd)
19796 (unless (and (bolp) (org-at-heading-p))
19797 (goto-char pos)
19798 (error "Boundary reached while executing %s" cmd))))
19800 (defvar org-self-insert-command-undo-counter 0)
19802 (defvar org-table-auto-blank-field) ; defined in org-table.el
19803 (defvar org-speed-command nil)
19805 (defun org-speed-command-activate (keys)
19806 "Hook for activating single-letter speed commands.
19807 `org-speed-commands-default' specifies a minimal command set.
19808 Use `org-speed-commands-user' for further customization."
19809 (when (or (and (bolp) (looking-at org-outline-regexp))
19810 (and (functionp org-use-speed-commands)
19811 (funcall org-use-speed-commands)))
19812 (cdr (assoc keys (append org-speed-commands-user
19813 org-speed-commands-default)))))
19815 (defun org-babel-speed-command-activate (keys)
19816 "Hook for activating single-letter code block commands."
19817 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19818 (cdr (assoc keys org-babel-key-bindings))))
19820 (defcustom org-speed-command-hook
19821 '(org-speed-command-activate org-babel-speed-command-activate)
19822 "Hook for activating speed commands at strategic locations.
19823 Hook functions are called in sequence until a valid handler is
19824 found.
19826 Each hook takes a single argument, a user-pressed command key
19827 which is also a `self-insert-command' from the global map.
19829 Within the hook, examine the cursor position and the command key
19830 and return nil or a valid handler as appropriate. Handler could
19831 be one of an interactive command, a function, or a form.
19833 Set `org-use-speed-commands' to non-nil value to enable this
19834 hook. The default setting is `org-speed-command-activate'."
19835 :group 'org-structure
19836 :version "24.1"
19837 :type 'hook)
19839 (defun org-self-insert-command (N)
19840 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19841 If the cursor is in a table looking at whitespace, the whitespace is
19842 overwritten, and the table is not marked as requiring realignment."
19843 (interactive "p")
19844 (org-check-before-invisible-edit 'insert)
19845 (cond
19846 ((and org-use-speed-commands
19847 (let ((kv (this-command-keys-vector)))
19848 (setq org-speed-command
19849 (run-hook-with-args-until-success
19850 'org-speed-command-hook
19851 (make-string 1 (aref kv (1- (length kv))))))))
19852 (cond
19853 ((commandp org-speed-command)
19854 (setq this-command org-speed-command)
19855 (call-interactively org-speed-command))
19856 ((functionp org-speed-command)
19857 (funcall org-speed-command))
19858 ((and org-speed-command (listp org-speed-command))
19859 (eval org-speed-command))
19860 (t (let (org-use-speed-commands)
19861 (call-interactively 'org-self-insert-command)))))
19862 ((and
19863 (org-at-table-p)
19864 (eq N 1)
19865 (not (org-region-active-p))
19866 (progn
19867 ;; Check if we blank the field, and if that triggers align.
19868 (and (featurep 'org-table) org-table-auto-blank-field
19869 (memq last-command
19870 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19871 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19872 ;; Got extra space, this field does not determine
19873 ;; column width.
19874 (let (org-table-may-need-update) (org-table-blank-field))
19875 ;; No extra space, this field may determine column
19876 ;; width.
19877 (org-table-blank-field)))
19879 (looking-at "[^|\n]* \\( \\)|"))
19880 ;; There is room for insertion without re-aligning the table.
19881 (delete-region (match-beginning 1) (match-end 1))
19882 (self-insert-command N))
19884 (setq org-table-may-need-update t)
19885 (self-insert-command N)
19886 (org-fix-tags-on-the-fly)
19887 (when org-self-insert-cluster-for-undo
19888 (if (not (eq last-command 'org-self-insert-command))
19889 (setq org-self-insert-command-undo-counter 1)
19890 (if (>= org-self-insert-command-undo-counter 20)
19891 (setq org-self-insert-command-undo-counter 1)
19892 (and (> org-self-insert-command-undo-counter 0)
19893 buffer-undo-list (listp buffer-undo-list)
19894 (not (cadr buffer-undo-list)) ; remove nil entry
19895 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19896 (setq org-self-insert-command-undo-counter
19897 (1+ org-self-insert-command-undo-counter))))))))
19899 (defun org-check-before-invisible-edit (kind)
19900 "Check is editing if kind KIND would be dangerous with invisible text around.
19901 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19902 ;; First, try to get out of here as quickly as possible, to reduce overhead
19903 (when (and org-catch-invisible-edits
19904 (or (not (boundp 'visible-mode)) (not visible-mode))
19905 (or (get-char-property (point) 'invisible)
19906 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19907 ;; OK, we need to take a closer look. Do not consider
19908 ;; invisibility obtained through text properties (e.g., link
19909 ;; fontification), as it cannot be toggled.
19910 (let* ((invisible-at-point
19911 (pcase (get-char-property-and-overlay (point) 'invisible)
19912 (`(,_ . ,(and (pred overlayp) o)) o)))
19913 ;; Assume that point cannot land in the middle of an
19914 ;; overlay, or between two overlays.
19915 (invisible-before-point
19916 (and (not invisible-at-point)
19917 (not (bobp))
19918 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19919 (`(,_ . ,(and (pred overlayp) o)) o))))
19920 (border-and-ok-direction
19922 ;; Check if we are acting predictably before invisible
19923 ;; text.
19924 (and invisible-at-point
19925 (memq kind '(insert delete-backward)))
19926 ;; Check if we are acting predictably after invisible text
19927 ;; This works not well, and I have turned it off. It seems
19928 ;; better to always show and stop after invisible text.
19929 ;; (and (not invisible-at-point) invisible-before-point
19930 ;; (memq kind '(insert delete)))
19932 (when (or invisible-at-point invisible-before-point)
19933 (when (eq org-catch-invisible-edits 'error)
19934 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19935 (if (and org-custom-properties-overlays
19936 (y-or-n-p "Display invisible properties in this buffer? "))
19937 (org-toggle-custom-properties-visibility)
19938 ;; Make the area visible
19939 (save-excursion
19940 (when invisible-before-point
19941 (goto-char
19942 (previous-single-char-property-change (point) 'invisible)))
19943 ;; Remove whatever overlay is currently making yet-to-be
19944 ;; edited text invisible. Also remove nested invisibility
19945 ;; related overlays.
19946 (delete-overlay (or invisible-at-point invisible-before-point))
19947 (let ((origin (if invisible-at-point (point) (1- (point)))))
19948 (while (pcase (get-char-property-and-overlay origin 'invisible)
19949 (`(,_ . ,(and (pred overlayp) o))
19950 (delete-overlay o)
19951 t)))))
19952 (cond
19953 ((eq org-catch-invisible-edits 'show)
19954 ;; That's it, we do the edit after showing
19955 (message
19956 "Unfolding invisible region around point before editing")
19957 (sit-for 1))
19958 ((and (eq org-catch-invisible-edits 'smart)
19959 border-and-ok-direction)
19960 (message "Unfolding invisible region around point before editing"))
19962 ;; Don't do the edit, make the user repeat it in full visibility
19963 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19965 (defun org-fix-tags-on-the-fly ()
19966 "Align tags in headline at point.
19967 Unlike to `org-set-tags', it ignores region and sorting."
19968 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19969 (org-at-heading-p))
19970 (let ((org-ignore-region t)
19971 (org-tags-sort-function nil))
19972 (org-set-tags nil t))))
19974 (defun org-delete-backward-char (N)
19975 "Like `delete-backward-char', insert whitespace at field end in tables.
19976 When deleting backwards, in tables this function will insert whitespace in
19977 front of the next \"|\" separator, to keep the table aligned. The table will
19978 still be marked for re-alignment if the field did fill the entire column,
19979 because, in this case the deletion might narrow the column."
19980 (interactive "p")
19981 (save-match-data
19982 (org-check-before-invisible-edit 'delete-backward)
19983 (if (and (org-at-table-p)
19984 (eq N 1)
19985 (not (org-region-active-p))
19986 (string-match "|" (buffer-substring (point-at-bol) (point)))
19987 (looking-at ".*?|"))
19988 (let ((pos (point))
19989 (noalign (looking-at "[^|\n\r]* |"))
19990 (c org-table-may-need-update))
19991 (backward-delete-char N)
19992 (unless overwrite-mode
19993 (skip-chars-forward "^|")
19994 (insert " ")
19995 (goto-char (1- pos)))
19996 ;; noalign: if there were two spaces at the end, this field
19997 ;; does not determine the width of the column.
19998 (when noalign (setq org-table-may-need-update c)))
19999 (backward-delete-char N)
20000 (org-fix-tags-on-the-fly))))
20002 (defun org-delete-char (N)
20003 "Like `delete-char', but insert whitespace at field end in tables.
20004 When deleting characters, in tables this function will insert whitespace in
20005 front of the next \"|\" separator, to keep the table aligned. The table will
20006 still be marked for re-alignment if the field did fill the entire column,
20007 because, in this case the deletion might narrow the column."
20008 (interactive "p")
20009 (save-match-data
20010 (org-check-before-invisible-edit 'delete)
20011 (if (and (org-at-table-p)
20012 (not (bolp))
20013 (not (= (char-after) ?|))
20014 (eq N 1))
20015 (if (looking-at ".*?|")
20016 (let ((pos (point))
20017 (noalign (looking-at "[^|\n\r]* |"))
20018 (c org-table-may-need-update))
20019 (replace-match
20020 (concat (substring (match-string 0) 1 -1) " |") nil t)
20021 (goto-char pos)
20022 ;; noalign: if there were two spaces at the end, this field
20023 ;; does not determine the width of the column.
20024 (when noalign (setq org-table-may-need-update c)))
20025 (delete-char N))
20026 (delete-char N)
20027 (org-fix-tags-on-the-fly))))
20029 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20030 (put 'org-self-insert-command 'delete-selection
20031 (lambda ()
20032 (not (run-hook-with-args-until-success
20033 'self-insert-uses-region-functions))))
20034 (put 'orgtbl-self-insert-command 'delete-selection
20035 (lambda ()
20036 (not (run-hook-with-args-until-success
20037 'self-insert-uses-region-functions))))
20038 (put 'org-delete-char 'delete-selection 'supersede)
20039 (put 'org-delete-backward-char 'delete-selection 'supersede)
20040 (put 'org-yank 'delete-selection 'yank)
20042 ;; Make `flyspell-mode' delay after some commands
20043 (put 'org-self-insert-command 'flyspell-delayed t)
20044 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20045 (put 'org-delete-char 'flyspell-delayed t)
20046 (put 'org-delete-backward-char 'flyspell-delayed t)
20048 ;; Make pabbrev-mode expand after Org mode commands
20049 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20050 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20052 (defun org-transpose-words ()
20053 "Transpose words for Org.
20054 This uses the `org-mode-transpose-word-syntax-table' syntax
20055 table, which interprets characters in `org-emphasis-alist' as
20056 word constituents."
20057 (interactive)
20058 (with-syntax-table org-mode-transpose-word-syntax-table
20059 (call-interactively 'transpose-words)))
20060 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20062 (defvar org-ctrl-c-ctrl-c-hook nil
20063 "Hook for functions attaching themselves to `C-c C-c'.
20065 This can be used to add additional functionality to the C-c C-c
20066 key which executes context-dependent commands. This hook is run
20067 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20068 run after the last test.
20070 Each function will be called with no arguments. The function
20071 must check if the context is appropriate for it to act. If yes,
20072 it should do its thing and then return a non-nil value. If the
20073 context is wrong, just do nothing and return nil.")
20075 (defvar org-ctrl-c-ctrl-c-final-hook nil
20076 "Hook for functions attaching themselves to `C-c C-c'.
20078 This can be used to add additional functionality to the C-c C-c
20079 key which executes context-dependent commands. This hook is run
20080 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20081 before the first test.
20083 Each function will be called with no arguments. The function
20084 must check if the context is appropriate for it to act. If yes,
20085 it should do its thing and then return a non-nil value. If the
20086 context is wrong, just do nothing and return nil.")
20088 (defvar org-tab-first-hook nil
20089 "Hook for functions to attach themselves to TAB.
20090 See `org-ctrl-c-ctrl-c-hook' for more information.
20091 This hook runs as the first action when TAB is pressed, even before
20092 `org-cycle' messes around with the `outline-regexp' to cater for
20093 inline tasks and plain list item folding.
20094 If any function in this hook returns t, any other actions that
20095 would have been caused by TAB (such as table field motion or visibility
20096 cycling) will not occur.")
20098 (defvar org-tab-after-check-for-table-hook nil
20099 "Hook for functions to attach themselves to TAB.
20100 See `org-ctrl-c-ctrl-c-hook' for more information.
20101 This hook runs after it has been established that the cursor is not in a
20102 table, but before checking if the cursor is in a headline or if global cycling
20103 should be done.
20104 If any function in this hook returns t, not other actions like visibility
20105 cycling will be done.")
20107 (defvar org-tab-after-check-for-cycling-hook nil
20108 "Hook for functions to attach themselves to TAB.
20109 See `org-ctrl-c-ctrl-c-hook' for more information.
20110 This hook runs after it has been established that not table field motion and
20111 not visibility should be done because of current context. This is probably
20112 the place where a package like yasnippets can hook in.")
20114 (defvar org-tab-before-tab-emulation-hook nil
20115 "Hook for functions to attach themselves to TAB.
20116 See `org-ctrl-c-ctrl-c-hook' for more information.
20117 This hook runs after every other options for TAB have been exhausted, but
20118 before indentation and \t insertion takes place.")
20120 (defvar org-metaleft-hook nil
20121 "Hook for functions attaching themselves to `M-left'.
20122 See `org-ctrl-c-ctrl-c-hook' for more information.")
20123 (defvar org-metaright-hook nil
20124 "Hook for functions attaching themselves to `M-right'.
20125 See `org-ctrl-c-ctrl-c-hook' for more information.")
20126 (defvar org-metaup-hook nil
20127 "Hook for functions attaching themselves to `M-up'.
20128 See `org-ctrl-c-ctrl-c-hook' for more information.")
20129 (defvar org-metadown-hook nil
20130 "Hook for functions attaching themselves to `M-down'.
20131 See `org-ctrl-c-ctrl-c-hook' for more information.")
20132 (defvar org-shiftmetaleft-hook nil
20133 "Hook for functions attaching themselves to `M-S-left'.
20134 See `org-ctrl-c-ctrl-c-hook' for more information.")
20135 (defvar org-shiftmetaright-hook nil
20136 "Hook for functions attaching themselves to `M-S-right'.
20137 See `org-ctrl-c-ctrl-c-hook' for more information.")
20138 (defvar org-shiftmetaup-hook nil
20139 "Hook for functions attaching themselves to `M-S-up'.
20140 See `org-ctrl-c-ctrl-c-hook' for more information.")
20141 (defvar org-shiftmetadown-hook nil
20142 "Hook for functions attaching themselves to `M-S-down'.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-metareturn-hook nil
20145 "Hook for functions attaching themselves to `M-RET'.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.")
20147 (defvar org-shiftup-hook nil
20148 "Hook for functions attaching themselves to `S-up'.
20149 See `org-ctrl-c-ctrl-c-hook' for more information.")
20150 (defvar org-shiftup-final-hook nil
20151 "Hook for functions attaching themselves to `S-up'.
20152 This one runs after all other options except shift-select have been excluded.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-shiftdown-hook nil
20155 "Hook for functions attaching themselves to `S-down'.
20156 See `org-ctrl-c-ctrl-c-hook' for more information.")
20157 (defvar org-shiftdown-final-hook nil
20158 "Hook for functions attaching themselves to `S-down'.
20159 This one runs after all other options except shift-select have been excluded.
20160 See `org-ctrl-c-ctrl-c-hook' for more information.")
20161 (defvar org-shiftleft-hook nil
20162 "Hook for functions attaching themselves to `S-left'.
20163 See `org-ctrl-c-ctrl-c-hook' for more information.")
20164 (defvar org-shiftleft-final-hook nil
20165 "Hook for functions attaching themselves to `S-left'.
20166 This one runs after all other options except shift-select have been excluded.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defvar org-shiftright-hook nil
20169 "Hook for functions attaching themselves to `S-right'.
20170 See `org-ctrl-c-ctrl-c-hook' for more information.")
20171 (defvar org-shiftright-final-hook nil
20172 "Hook for functions attaching themselves to `S-right'.
20173 This one runs after all other options except shift-select have been excluded.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20176 (defun org-modifier-cursor-error ()
20177 "Throw an error, a modified cursor command was applied in wrong context."
20178 (user-error "This command is active in special context like tables, headlines or items"))
20180 (defun org-shiftselect-error ()
20181 "Throw an error because Shift-Cursor command was applied in wrong context."
20182 (if (and (boundp 'shift-select-mode) shift-select-mode)
20183 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20184 (user-error "This command works only in special context like headlines or timestamps")))
20186 (defun org-call-for-shift-select (cmd)
20187 (let ((this-command-keys-shift-translated t))
20188 (call-interactively cmd)))
20190 (defun org-shifttab (&optional arg)
20191 "Global visibility cycling or move to previous table field.
20192 Call `org-table-previous-field' within a table.
20193 When ARG is nil, cycle globally through visibility states.
20194 When ARG is a numeric prefix, show contents of this level."
20195 (interactive "P")
20196 (cond
20197 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20198 ((integerp arg)
20199 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20200 (message "Content view to level: %d" arg)
20201 (org-content (prefix-numeric-value arg2))
20202 (org-cycle-show-empty-lines t)
20203 (setq org-cycle-global-status 'overview)))
20204 (t (call-interactively 'org-global-cycle))))
20206 (defun org-shiftmetaleft ()
20207 "Promote subtree or delete table column.
20208 Calls `org-promote-subtree', `org-outdent-item-tree', or
20209 `org-table-delete-column', depending on context. See the
20210 individual commands for more information."
20211 (interactive)
20212 (cond
20213 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20214 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20215 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20216 ((if (not (org-region-active-p)) (org-at-item-p)
20217 (save-excursion (goto-char (region-beginning))
20218 (org-at-item-p)))
20219 (call-interactively 'org-outdent-item-tree))
20220 (t (org-modifier-cursor-error))))
20222 (defun org-shiftmetaright ()
20223 "Demote subtree or insert table column.
20224 Calls `org-demote-subtree', `org-indent-item-tree', or
20225 `org-table-insert-column', depending on context. See the
20226 individual commands for more information."
20227 (interactive)
20228 (cond
20229 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20230 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20231 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20232 ((if (not (org-region-active-p)) (org-at-item-p)
20233 (save-excursion (goto-char (region-beginning))
20234 (org-at-item-p)))
20235 (call-interactively 'org-indent-item-tree))
20236 (t (org-modifier-cursor-error))))
20238 (defun org-shiftmetaup (&optional _arg)
20239 "Drag the line at point up.
20240 In a table, kill the current row.
20241 On a clock timestamp, update the value of the timestamp like `S-<up>'
20242 but also adjust the previous clocked item in the clock history.
20243 Everywhere else, drag the line at point up."
20244 (interactive "P")
20245 (cond
20246 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20247 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20248 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20249 (call-interactively 'org-timestamp-up)))
20250 (t (call-interactively 'org-drag-line-backward))))
20252 (defun org-shiftmetadown (&optional _arg)
20253 "Drag the line at point down.
20254 In a table, insert an empty row at the current line.
20255 On a clock timestamp, update the value of the timestamp like `S-<down>'
20256 but also adjust the previous clocked item in the clock history.
20257 Everywhere else, drag the line at point down."
20258 (interactive "P")
20259 (cond
20260 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20261 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20262 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20263 (call-interactively 'org-timestamp-down)))
20264 (t (call-interactively 'org-drag-line-forward))))
20266 (defsubst org-hidden-tree-error ()
20267 (user-error
20268 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20270 (defun org-metaleft (&optional _arg)
20271 "Promote heading, list item at point or move table column left.
20273 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20274 depending on context. With no specific context, calls the Emacs
20275 default `backward-word'. See the individual commands for more
20276 information.
20278 This function runs the hook `org-metaleft-hook' as a first step,
20279 and returns at first non-nil value."
20280 (interactive "P")
20281 (cond
20282 ((run-hook-with-args-until-success 'org-metaleft-hook))
20283 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20284 ((org-with-limited-levels
20285 (or (org-at-heading-p)
20286 (and (org-region-active-p)
20287 (save-excursion
20288 (goto-char (region-beginning))
20289 (org-at-heading-p)))))
20290 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20291 (call-interactively 'org-do-promote))
20292 ;; At an inline task.
20293 ((org-at-heading-p)
20294 (call-interactively 'org-inlinetask-promote))
20295 ((or (org-at-item-p)
20296 (and (org-region-active-p)
20297 (save-excursion
20298 (goto-char (region-beginning))
20299 (org-at-item-p))))
20300 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20301 (call-interactively 'org-outdent-item))
20302 (t (call-interactively 'backward-word))))
20304 (defun org-metaright (&optional _arg)
20305 "Demote heading, list item at point or move table column right.
20307 In front of a drawer or a block keyword, indent it correctly.
20309 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20310 `org-indent-drawer' or `org-indent-block' depending on context.
20311 With no specific context, calls the Emacs default `forward-word'.
20312 See the individual commands for more information.
20314 This function runs the hook `org-metaright-hook' as a first step,
20315 and returns at first non-nil value."
20316 (interactive "P")
20317 (cond
20318 ((run-hook-with-args-until-success 'org-metaright-hook))
20319 ((org-at-table-p) (call-interactively 'org-table-move-column))
20320 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20321 ((org-at-block-p) (call-interactively 'org-indent-block))
20322 ((org-with-limited-levels
20323 (or (org-at-heading-p)
20324 (and (org-region-active-p)
20325 (save-excursion
20326 (goto-char (region-beginning))
20327 (org-at-heading-p)))))
20328 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20329 (call-interactively 'org-do-demote))
20330 ;; At an inline task.
20331 ((org-at-heading-p)
20332 (call-interactively 'org-inlinetask-demote))
20333 ((or (org-at-item-p)
20334 (and (org-region-active-p)
20335 (save-excursion
20336 (goto-char (region-beginning))
20337 (org-at-item-p))))
20338 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20339 (call-interactively 'org-indent-item))
20340 (t (call-interactively 'forward-word))))
20342 (defun org-check-for-hidden (what)
20343 "Check if there are hidden headlines/items in the current visual line.
20344 WHAT can be either `headlines' or `items'. If the current line is
20345 an outline or item heading and it has a folded subtree below it,
20346 this function returns t, nil otherwise."
20347 (let ((re (cond
20348 ((eq what 'headlines) org-outline-regexp-bol)
20349 ((eq what 'items) (org-item-beginning-re))
20350 (t (error "This should not happen"))))
20351 beg end)
20352 (save-excursion
20353 (catch 'exit
20354 (unless (org-region-active-p)
20355 (setq beg (point-at-bol))
20356 (beginning-of-line 2)
20357 (while (and (not (eobp)) ;; this is like `next-line'
20358 (get-char-property (1- (point)) 'invisible))
20359 (beginning-of-line 2))
20360 (setq end (point))
20361 (goto-char beg)
20362 (goto-char (point-at-eol))
20363 (setq end (max end (point)))
20364 (while (re-search-forward re end t)
20365 (when (get-char-property (match-beginning 0) 'invisible)
20366 (throw 'exit t))))
20367 nil))))
20369 (defun org-metaup (&optional _arg)
20370 "Move subtree up or move table row up.
20371 Calls `org-move-subtree-up' or `org-table-move-row' or
20372 `org-move-item-up', depending on context. See the individual commands
20373 for more information."
20374 (interactive "P")
20375 (cond
20376 ((run-hook-with-args-until-success 'org-metaup-hook))
20377 ((org-region-active-p)
20378 (let* ((a (min (region-beginning) (region-end)))
20379 (b (1- (max (region-beginning) (region-end))))
20380 (c (save-excursion (goto-char a)
20381 (move-beginning-of-line 0)))
20382 (d (save-excursion (goto-char a)
20383 (move-end-of-line 0) (point))))
20384 (transpose-regions a b c d)
20385 (goto-char c)))
20386 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20387 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20388 ((org-at-item-p) (call-interactively 'org-move-item-up))
20389 (t (org-drag-element-backward))))
20391 (defun org-metadown (&optional _arg)
20392 "Move subtree down or move table row down.
20393 Calls `org-move-subtree-down' or `org-table-move-row' or
20394 `org-move-item-down', depending on context. See the individual
20395 commands for more information."
20396 (interactive "P")
20397 (cond
20398 ((run-hook-with-args-until-success 'org-metadown-hook))
20399 ((org-region-active-p)
20400 (let* ((a (min (region-beginning) (region-end)))
20401 (b (max (region-beginning) (region-end)))
20402 (c (save-excursion (goto-char b)
20403 (move-beginning-of-line 1)))
20404 (d (save-excursion (goto-char b)
20405 (move-end-of-line 1) (1+ (point)))))
20406 (transpose-regions a b c d)
20407 (goto-char d)))
20408 ((org-at-table-p) (call-interactively 'org-table-move-row))
20409 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20410 ((org-at-item-p) (call-interactively 'org-move-item-down))
20411 (t (org-drag-element-forward))))
20413 (defun org-shiftup (&optional arg)
20414 "Increase item in timestamp or increase priority of current headline.
20415 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20416 depending on context. See the individual commands for more information."
20417 (interactive "P")
20418 (cond
20419 ((run-hook-with-args-until-success 'org-shiftup-hook))
20420 ((and org-support-shift-select (org-region-active-p))
20421 (org-call-for-shift-select 'previous-line))
20422 ((org-at-timestamp-p 'lax)
20423 (call-interactively (if org-edit-timestamp-down-means-later
20424 'org-timestamp-down 'org-timestamp-up)))
20425 ((and (not (eq org-support-shift-select 'always))
20426 org-enable-priority-commands
20427 (org-at-heading-p))
20428 (call-interactively 'org-priority-up))
20429 ((and (not org-support-shift-select) (org-at-item-p))
20430 (call-interactively 'org-previous-item))
20431 ((org-clocktable-try-shift 'up arg))
20432 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20433 (org-support-shift-select
20434 (org-call-for-shift-select 'previous-line))
20435 (t (org-shiftselect-error))))
20437 (defun org-shiftdown (&optional arg)
20438 "Decrease item in timestamp or decrease priority of current headline.
20439 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20440 depending on context. See the individual commands for more information."
20441 (interactive "P")
20442 (cond
20443 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20444 ((and org-support-shift-select (org-region-active-p))
20445 (org-call-for-shift-select 'next-line))
20446 ((org-at-timestamp-p 'lax)
20447 (call-interactively (if org-edit-timestamp-down-means-later
20448 'org-timestamp-up 'org-timestamp-down)))
20449 ((and (not (eq org-support-shift-select 'always))
20450 org-enable-priority-commands
20451 (org-at-heading-p))
20452 (call-interactively 'org-priority-down))
20453 ((and (not org-support-shift-select) (org-at-item-p))
20454 (call-interactively 'org-next-item))
20455 ((org-clocktable-try-shift 'down arg))
20456 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20457 (org-support-shift-select
20458 (org-call-for-shift-select 'next-line))
20459 (t (org-shiftselect-error))))
20461 (defun org-shiftright (&optional arg)
20462 "Cycle the thing at point or in the current line, depending on context.
20463 Depending on context, this does one of the following:
20465 - switch a timestamp at point one day into the future
20466 - on a headline, switch to the next TODO keyword.
20467 - on an item, switch entire list to the next bullet type
20468 - on a property line, switch to the next allowed value
20469 - on a clocktable definition line, move time block into the future"
20470 (interactive "P")
20471 (cond
20472 ((run-hook-with-args-until-success 'org-shiftright-hook))
20473 ((and org-support-shift-select (org-region-active-p))
20474 (org-call-for-shift-select 'forward-char))
20475 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20476 ((and (not (eq org-support-shift-select 'always))
20477 (org-at-heading-p))
20478 (let ((org-inhibit-logging
20479 (not org-treat-S-cursor-todo-selection-as-state-change))
20480 (org-inhibit-blocking
20481 (not org-treat-S-cursor-todo-selection-as-state-change)))
20482 (org-call-with-arg 'org-todo 'right)))
20483 ((or (and org-support-shift-select
20484 (not (eq org-support-shift-select 'always))
20485 (org-at-item-bullet-p))
20486 (and (not org-support-shift-select) (org-at-item-p)))
20487 (org-call-with-arg 'org-cycle-list-bullet nil))
20488 ((and (not (eq org-support-shift-select 'always))
20489 (org-at-property-p))
20490 (call-interactively 'org-property-next-allowed-value))
20491 ((org-clocktable-try-shift 'right arg))
20492 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20493 (org-support-shift-select
20494 (org-call-for-shift-select 'forward-char))
20495 (t (org-shiftselect-error))))
20497 (defun org-shiftleft (&optional arg)
20498 "Cycle the thing at point or in the current line, depending on context.
20499 Depending on context, this does one of the following:
20501 - switch a timestamp at point one day into the past
20502 - on a headline, switch to the previous TODO keyword.
20503 - on an item, switch entire list to the previous bullet type
20504 - on a property line, switch to the previous allowed value
20505 - on a clocktable definition line, move time block into the past"
20506 (interactive "P")
20507 (cond
20508 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20509 ((and org-support-shift-select (org-region-active-p))
20510 (org-call-for-shift-select 'backward-char))
20511 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20512 ((and (not (eq org-support-shift-select 'always))
20513 (org-at-heading-p))
20514 (let ((org-inhibit-logging
20515 (not org-treat-S-cursor-todo-selection-as-state-change))
20516 (org-inhibit-blocking
20517 (not org-treat-S-cursor-todo-selection-as-state-change)))
20518 (org-call-with-arg 'org-todo 'left)))
20519 ((or (and org-support-shift-select
20520 (not (eq org-support-shift-select 'always))
20521 (org-at-item-bullet-p))
20522 (and (not org-support-shift-select) (org-at-item-p)))
20523 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20524 ((and (not (eq org-support-shift-select 'always))
20525 (org-at-property-p))
20526 (call-interactively 'org-property-previous-allowed-value))
20527 ((org-clocktable-try-shift 'left arg))
20528 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20529 (org-support-shift-select
20530 (org-call-for-shift-select 'backward-char))
20531 (t (org-shiftselect-error))))
20533 (defun org-shiftcontrolright ()
20534 "Switch to next TODO set."
20535 (interactive)
20536 (cond
20537 ((and org-support-shift-select (org-region-active-p))
20538 (org-call-for-shift-select 'forward-word))
20539 ((and (not (eq org-support-shift-select 'always))
20540 (org-at-heading-p))
20541 (org-call-with-arg 'org-todo 'nextset))
20542 (org-support-shift-select
20543 (org-call-for-shift-select 'forward-word))
20544 (t (org-shiftselect-error))))
20546 (defun org-shiftcontrolleft ()
20547 "Switch to previous TODO set."
20548 (interactive)
20549 (cond
20550 ((and org-support-shift-select (org-region-active-p))
20551 (org-call-for-shift-select 'backward-word))
20552 ((and (not (eq org-support-shift-select 'always))
20553 (org-at-heading-p))
20554 (org-call-with-arg 'org-todo 'previousset))
20555 (org-support-shift-select
20556 (org-call-for-shift-select 'backward-word))
20557 (t (org-shiftselect-error))))
20559 (defun org-shiftcontrolup (&optional n)
20560 "Change timestamps synchronously up in CLOCK log lines.
20561 Optional argument N tells to change by that many units."
20562 (interactive "P")
20563 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20564 (let (org-support-shift-select)
20565 (org-clock-timestamps-up n))
20566 (user-error "Not at a clock log")))
20568 (defun org-shiftcontroldown (&optional n)
20569 "Change timestamps synchronously down in CLOCK log lines.
20570 Optional argument N tells to change by that many units."
20571 (interactive "P")
20572 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20573 (let (org-support-shift-select)
20574 (org-clock-timestamps-down n))
20575 (user-error "Not at a clock log")))
20577 (defun org-increase-number-at-point (&optional inc)
20578 "Increment the number at point.
20579 With an optional prefix numeric argument INC, increment using
20580 this numeric value."
20581 (interactive "p")
20582 (if (not (number-at-point))
20583 (user-error "Not on a number")
20584 (unless inc (setq inc 1))
20585 (let ((pos (point))
20586 (beg (skip-chars-backward "-+^/*0-9eE."))
20587 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20588 (setq nap (buffer-substring-no-properties
20589 (+ pos beg) (+ pos beg end)))
20590 (delete-region (+ pos beg) (+ pos beg end))
20591 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20592 (when (org-at-table-p)
20593 (org-table-align)
20594 (org-table-end-of-field 1))))
20596 (defun org-decrease-number-at-point (&optional inc)
20597 "Decrement the number at point.
20598 With an optional prefix numeric argument INC, decrement using
20599 this numeric value."
20600 (interactive "p")
20601 (org-increase-number-at-point (- (or inc 1))))
20603 (defun org-ctrl-c-ret ()
20604 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20605 (interactive)
20606 (cond
20607 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20608 (t (call-interactively 'org-insert-heading))))
20610 (defun org-find-visible ()
20611 (let ((s (point)))
20612 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20613 (get-char-property s 'invisible)))
20615 (defun org-find-invisible ()
20616 (let ((s (point)))
20617 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20618 (not (get-char-property s 'invisible))))
20621 (defun org-copy-visible (beg end)
20622 "Copy the visible parts of the region."
20623 (interactive "r")
20624 (let ((result ""))
20625 (while (/= beg end)
20626 (when (get-char-property beg 'invisible)
20627 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20628 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20629 (setq result (concat result (buffer-substring beg next)))
20630 (setq beg next)))
20631 (kill-new result)))
20633 (defun org-copy-special ()
20634 "Copy region in table or copy current subtree.
20635 Calls `org-table-copy-region' or `org-copy-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-copy-region #'org-copy-subtree)))
20641 (defun org-cut-special ()
20642 "Cut region in table or cut current subtree.
20643 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20644 context. See the individual commands for more information."
20645 (interactive)
20646 (call-interactively
20647 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20649 (defun org-paste-special (arg)
20650 "Paste rectangular region into table, or past subtree relative to level.
20651 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20652 See the individual commands for more information."
20653 (interactive "P")
20654 (if (org-at-table-p)
20655 (org-table-paste-rectangle)
20656 (org-paste-subtree arg)))
20658 (defun org-edit-special (&optional arg)
20659 "Call a special editor for the element at point.
20660 When at a table, call the formula editor with `org-table-edit-formulas'.
20661 When in a source code block, call `org-edit-src-code'.
20662 When in a fixed-width region, call `org-edit-fixed-width-region'.
20663 When in an export block, call `org-edit-export-block'.
20664 When in a LaTeX environment, call `org-edit-latex-environment'.
20665 When at an #+INCLUDE keyword, visit the included file.
20666 When at a footnote reference, call `org-edit-footnote-reference'
20667 On a link, call `ffap' to visit the link at point.
20668 Otherwise, return a user error."
20669 (interactive "P")
20670 (let ((element (org-element-at-point)))
20671 (barf-if-buffer-read-only)
20672 (pcase (org-element-type element)
20673 (`src-block
20674 (if (not arg) (org-edit-src-code)
20675 (let* ((info (org-babel-get-src-block-info))
20676 (lang (nth 0 info))
20677 (params (nth 2 info))
20678 (session (cdr (assq :session params))))
20679 (if (not session) (org-edit-src-code)
20680 ;; At a src-block with a session and function called with
20681 ;; an ARG: switch to the buffer related to the inferior
20682 ;; process.
20683 (switch-to-buffer
20684 (funcall (intern (concat "org-babel-prep-session:" lang))
20685 session params))))))
20686 (`keyword
20687 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20688 (org-open-link-from-string
20689 (format "[[%s]]"
20690 (expand-file-name
20691 (let ((value (org-element-property :value element)))
20692 (cond ((org-file-url-p value)
20693 (user-error "The file is specified as a URL, cannot be edited"))
20694 ((not (org-string-nw-p value))
20695 (user-error "No file to edit"))
20696 ((string-match "\\`\"\\(.*?\\)\"" value)
20697 (match-string 1 value))
20698 ((string-match "\\`[^ \t\"]\\S-*" value)
20699 (match-string 0 value))
20700 (t (user-error "No valid file specified")))))))
20701 (user-error "No special environment to edit here")))
20702 (`table
20703 (if (eq (org-element-property :type element) 'table.el)
20704 (org-edit-table.el)
20705 (call-interactively 'org-table-edit-formulas)))
20706 ;; Only Org tables contain `table-row' type elements.
20707 (`table-row (call-interactively 'org-table-edit-formulas))
20708 (`example-block (org-edit-src-code))
20709 (`export-block (org-edit-export-block))
20710 (`fixed-width (org-edit-fixed-width-region))
20711 (`latex-environment (org-edit-latex-environment))
20713 ;; No notable element at point. Though, we may be at a link or
20714 ;; a footnote reference, which are objects. Thus, scan deeper.
20715 (let ((context (org-element-context element)))
20716 (pcase (org-element-type context)
20717 (`footnote-reference (org-edit-footnote-reference))
20718 (`inline-src-block (org-edit-inline-src-code))
20719 (`link (call-interactively #'ffap))
20720 (_ (user-error "No special environment to edit here"))))))))
20722 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20723 (defun org-ctrl-c-ctrl-c (&optional arg)
20724 "Set tags in headline, or update according to changed information at point.
20726 This command does many different things, depending on context:
20728 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20729 this is what we do.
20731 - If the cursor is on a statistics cookie, update it.
20733 - If the cursor is in a headline, prompt for tags and insert them
20734 into the current line, aligned to `org-tags-column'. When called
20735 with prefix arg, realign all tags in the current buffer.
20737 - If the cursor is in one of the special #+KEYWORD lines, this
20738 triggers scanning the buffer for these lines and updating the
20739 information.
20741 - If the cursor is inside a table, realign the table. This command
20742 works even if the automatic table editor has been turned off.
20744 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20745 the entire table.
20747 - If the cursor is at a footnote reference or definition, jump to
20748 the corresponding definition or references, respectively.
20750 - If the cursor is a the beginning of a dynamic block, update it.
20752 - If the current buffer is a capture buffer, close note and file it.
20754 - If the cursor is on a <<<target>>>, update radio targets and
20755 corresponding links in this buffer.
20757 - If the cursor is on a numbered item in a plain list, renumber the
20758 ordered list.
20760 - If the cursor is on a checkbox, toggle it.
20762 - If the cursor is on a code block, evaluate it. The variable
20763 `org-confirm-babel-evaluate' can be used to control prompting
20764 before code block evaluation, by default every code block
20765 evaluation requires confirmation. Code block evaluation can be
20766 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20767 (interactive "P")
20768 (cond
20769 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20770 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20771 (org-remove-occur-highlights)
20772 (message "Temporary highlights/overlays removed from current buffer"))
20773 ((and (local-variable-p 'org-finish-function)
20774 (fboundp org-finish-function))
20775 (funcall org-finish-function))
20776 ((org-babel-hash-at-point))
20777 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20779 (let* ((context
20780 (org-element-lineage
20781 (org-element-context)
20782 ;; Limit to supported contexts.
20783 '(babel-call clock dynamic-block footnote-definition
20784 footnote-reference inline-babel-call inline-src-block
20785 inlinetask item keyword node-property paragraph
20786 plain-list property-drawer radio-target src-block
20787 statistics-cookie table table-cell table-row
20788 timestamp)
20790 (type (org-element-type context)))
20791 ;; For convenience: at the first line of a paragraph on the same
20792 ;; line as an item, apply function on that item instead.
20793 (when (eq type 'paragraph)
20794 (let ((parent (org-element-property :parent context)))
20795 (when (and (eq (org-element-type parent) 'item)
20796 (= (line-beginning-position)
20797 (org-element-property :begin parent)))
20798 (setq context parent)
20799 (setq type 'item))))
20800 ;; Act according to type of element or object at point.
20802 ;; Do nothing on a blank line, except if it is contained in
20803 ;; a src block. Hence, we first check if point is in such
20804 ;; a block and then if it is at a blank line.
20805 (pcase type
20806 ((or `inline-src-block `src-block)
20807 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20808 (org-babel-eval-wipe-error-buffer)
20809 (org-babel-execute-src-block
20810 current-prefix-arg (org-babel-get-src-block-info nil context))))
20811 ((guard (org-match-line "[ \t]*$"))
20812 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20813 (user-error
20814 (substitute-command-keys
20815 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20816 ((or `babel-call `inline-babel-call)
20817 (let ((info (org-babel-lob-get-info context)))
20818 (when info (org-babel-execute-src-block nil info))))
20819 (`clock (org-clock-update-time-maybe))
20820 (`dynamic-block
20821 (save-excursion
20822 (goto-char (org-element-property :post-affiliated context))
20823 (org-update-dblock)))
20824 (`footnote-definition
20825 (goto-char (org-element-property :post-affiliated context))
20826 (call-interactively 'org-footnote-action))
20827 (`footnote-reference (call-interactively #'org-footnote-action))
20828 ((or `headline `inlinetask)
20829 (save-excursion (goto-char (org-element-property :begin context))
20830 (call-interactively #'org-set-tags)))
20831 (`item
20832 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20833 ;; unconditionally, whereas `C-u' will toggle its presence.
20834 ;; Without a universal argument, if the item has a checkbox,
20835 ;; toggle it. Otherwise repair the list.
20836 (let* ((box (org-element-property :checkbox context))
20837 (struct (org-element-property :structure context))
20838 (old-struct (copy-tree struct))
20839 (parents (org-list-parents-alist struct))
20840 (prevs (org-list-prevs-alist struct))
20841 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20842 (org-list-set-checkbox
20843 (org-element-property :begin context) struct
20844 (cond ((equal arg '(16)) "[-]")
20845 ((and (not box) (equal arg '(4))) "[ ]")
20846 ((or (not box) (equal arg '(4))) nil)
20847 ((eq box 'on) "[ ]")
20848 (t "[X]")))
20849 ;; Mimic `org-list-write-struct' but with grabbing a return
20850 ;; value from `org-list-struct-fix-box'.
20851 (org-list-struct-fix-ind struct parents 2)
20852 (org-list-struct-fix-item-end struct)
20853 (org-list-struct-fix-bul struct prevs)
20854 (org-list-struct-fix-ind struct parents)
20855 (let ((block-item
20856 (org-list-struct-fix-box struct parents prevs orderedp)))
20857 (if (and box (equal struct old-struct))
20858 (if (equal arg '(16))
20859 (message "Checkboxes already reset")
20860 (user-error "Cannot toggle this checkbox: %s"
20861 (if (eq box 'on)
20862 "all subitems checked"
20863 "unchecked subitems")))
20864 (org-list-struct-apply-struct struct old-struct)
20865 (org-update-checkbox-count-maybe))
20866 (when block-item
20867 (message "Checkboxes were removed due to empty box at line %d"
20868 (org-current-line block-item))))))
20869 (`keyword
20870 (let ((org-inhibit-startup-visibility-stuff t)
20871 (org-startup-align-all-tables nil))
20872 (when (boundp 'org-table-coordinate-overlays)
20873 (mapc #'delete-overlay org-table-coordinate-overlays)
20874 (setq org-table-coordinate-overlays nil))
20875 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20876 (message "Local setup has been refreshed"))
20877 (`plain-list
20878 ;; At a plain list, with a double C-u argument, set
20879 ;; checkboxes of each item to "[-]", whereas a single one
20880 ;; will toggle their presence according to the state of the
20881 ;; first item in the list. Without an argument, repair the
20882 ;; list.
20883 (let* ((begin (org-element-property :contents-begin context))
20884 (beginm (move-marker (make-marker) begin))
20885 (struct (org-element-property :structure context))
20886 (old-struct (copy-tree struct))
20887 (first-box (save-excursion
20888 (goto-char begin)
20889 (looking-at org-list-full-item-re)
20890 (match-string-no-properties 3)))
20891 (new-box (cond ((equal arg '(16)) "[-]")
20892 ((equal arg '(4)) (unless first-box "[ ]"))
20893 ((equal first-box "[X]") "[ ]")
20894 (t "[X]"))))
20895 (cond
20896 (arg
20897 (dolist (pos
20898 (org-list-get-all-items
20899 begin struct (org-list-prevs-alist struct)))
20900 (org-list-set-checkbox pos struct new-box)))
20901 ((and first-box (eq (point) begin))
20902 ;; For convenience, when point is at bol on the first
20903 ;; item of the list and no argument is provided, simply
20904 ;; toggle checkbox of that item, if any.
20905 (org-list-set-checkbox begin struct new-box)))
20906 (org-list-write-struct
20907 struct (org-list-parents-alist struct) old-struct)
20908 (org-update-checkbox-count-maybe)
20909 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20910 ((or `property-drawer `node-property)
20911 (call-interactively #'org-property-action))
20912 (`radio-target
20913 (call-interactively #'org-update-radio-target-regexp))
20914 (`statistics-cookie
20915 (call-interactively #'org-update-statistics-cookies))
20916 ((or `table `table-cell `table-row)
20917 ;; At a table, recalculate every field and align it. Also
20918 ;; send the table if necessary. If the table has
20919 ;; a `table.el' type, just give up. At a table row or cell,
20920 ;; maybe recalculate line but always align table.
20921 (if (eq (org-element-property :type context) 'table.el)
20922 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20923 Use `\\[org-edit-special]' to edit table.el tables"))
20924 (if (or (eq type 'table)
20925 ;; Check if point is at a TBLFM line.
20926 (and (eq type 'table-row)
20927 (= (point) (org-element-property :end context))))
20928 (save-excursion
20929 (if (org-at-TBLFM-p)
20930 (progn (require 'org-table)
20931 (org-table-calc-current-TBLFM))
20932 (goto-char (org-element-property :contents-begin context))
20933 (org-call-with-arg 'org-table-recalculate (or arg t))
20934 (orgtbl-send-table 'maybe)))
20935 (org-table-maybe-eval-formula)
20936 (cond (arg (call-interactively #'org-table-recalculate))
20937 ((org-table-maybe-recalculate-line))
20938 (t (org-table-align))))))
20939 (`timestamp (org-timestamp-change 0 'day))
20940 ((and `nil (guard (org-at-heading-p)))
20941 ;; When point is on an unsupported object type, we can miss
20942 ;; the fact that it also is at a heading. Handle it here.
20943 (call-interactively #'org-set-tags))
20944 ((guard
20945 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20947 (user-error
20948 (substitute-command-keys
20949 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20951 (defun org-mode-restart ()
20952 (interactive)
20953 (let ((indent-status (bound-and-true-p org-indent-mode)))
20954 (funcall major-mode)
20955 (hack-local-variables)
20956 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20957 (org-indent-mode -1))
20958 (org-reset-file-cache))
20959 (message "%s restarted" major-mode))
20961 (defun org-kill-note-or-show-branches ()
20962 "Abort storing current note, or call `outline-show-branches'."
20963 (interactive)
20964 (if (not org-finish-function)
20965 (progn
20966 (outline-hide-subtree)
20967 (call-interactively 'outline-show-branches))
20968 (let ((org-note-abort t))
20969 (funcall org-finish-function))))
20971 (defun org-delete-indentation (&optional arg)
20972 "Join current line to previous and fix whitespace at join.
20974 If previous line is a headline add to headline title. Otherwise
20975 the function calls `delete-indentation'.
20977 With a non-nil optional argument, join it to the following one."
20978 (interactive "*P")
20979 (if (save-excursion
20980 (beginning-of-line (if arg 1 0))
20981 (let ((case-fold-search nil))
20982 (looking-at org-complex-heading-regexp)))
20983 ;; At headline.
20984 (let ((tags-column (when (match-beginning 5)
20985 (save-excursion (goto-char (match-beginning 5))
20986 (current-column))))
20987 (string (concat " " (progn (when arg (forward-line 1))
20988 (org-trim (delete-and-extract-region
20989 (line-beginning-position)
20990 (line-end-position)))))))
20991 (unless (bobp) (delete-region (point) (1- (point))))
20992 (goto-char (or (match-end 4)
20993 (match-beginning 5)
20994 (match-end 0)))
20995 (skip-chars-backward " \t")
20996 (save-excursion (insert string))
20997 ;; Adjust alignment of tags.
20998 (cond
20999 ((not tags-column)) ;no tags
21000 (org-auto-align-tags (org-set-tags nil t))
21001 (t (org--align-tags-here tags-column)))) ;preserve tags column
21002 (delete-indentation arg)))
21004 (defun org-open-line (n)
21005 "Insert a new row in tables, call `open-line' elsewhere.
21006 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21007 As a special case, when a document starts with a table, allow to
21008 call `open-line' on the very first character."
21009 (interactive "*p")
21010 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21011 (org-table-insert-row)
21012 (open-line n)))
21014 (defun org-return (&optional indent)
21015 "Goto next table row or insert a newline.
21017 Calls `org-table-next-row' or `newline', depending on context.
21019 When optional INDENT argument is non-nil, call
21020 `newline-and-indent' instead of `newline'.
21022 When `org-return-follows-link' is non-nil and point is on
21023 a timestamp or a link, call `org-open-at-point'. However, it
21024 will not happen if point is in a table or on a \"dead\"
21025 object (e.g., within a comment). In these case, you need to use
21026 `org-open-at-point' directly."
21027 (interactive)
21028 (let ((context (if org-return-follows-link (org-element-context)
21029 (org-element-at-point))))
21030 (cond
21031 ;; In a table, call `org-table-next-row'.
21032 ((or (and (eq (org-element-type context) 'table)
21033 (>= (point) (org-element-property :contents-begin context))
21034 (< (point) (org-element-property :contents-end context)))
21035 (org-element-lineage context '(table-row table-cell) t))
21036 (org-table-justify-field-maybe)
21037 (call-interactively #'org-table-next-row))
21038 ;; On a link or a timestamp, call `org-open-at-point' if
21039 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21040 ;; locations, e.g., in a comment, as `org-open-at-point'.
21041 ((and org-return-follows-link
21042 (or (org-in-regexp org-ts-regexp-both nil t)
21043 (org-in-regexp org-tsr-regexp-both nil t)
21044 (org-in-regexp org-any-link-re nil t)))
21045 (call-interactively #'org-open-at-point))
21046 ;; Insert newline in heading, but preserve tags.
21047 ((and (not (bolp))
21048 (save-excursion (beginning-of-line)
21049 (let ((case-fold-search nil))
21050 (looking-at org-complex-heading-regexp))))
21051 ;; At headline. Split line. However, if point is on keyword,
21052 ;; priority cookie or tags, do not break any of them: add
21053 ;; a newline after the headline instead.
21054 (let ((tags-column (and (match-beginning 5)
21055 (save-excursion (goto-char (match-beginning 5))
21056 (current-column))))
21057 (string
21058 (when (and (match-end 4) (org-point-in-group (point) 4))
21059 (delete-and-extract-region (point) (match-end 4)))))
21060 ;; Adjust tag alignment.
21061 (cond
21062 ((not (and tags-column string)))
21063 (org-auto-align-tags (org-set-tags nil t))
21064 (t (org--align-tags-here tags-column))) ;preserve tags column
21065 (end-of-line)
21066 (org-show-entry)
21067 (if indent (newline-and-indent) (newline))
21068 (when string (save-excursion (insert (org-trim string))))))
21069 ;; In a list, make sure indenting keeps trailing text within.
21070 ((and indent
21071 (not (eolp))
21072 (org-element-lineage context '(item)))
21073 (let ((trailing-data
21074 (delete-and-extract-region (point) (line-end-position))))
21075 (newline-and-indent)
21076 (save-excursion (insert trailing-data))))
21077 (t (if indent (newline-and-indent) (newline))))))
21079 (defun org-return-indent ()
21080 "Goto next table row or insert a newline and indent.
21081 Calls `org-table-next-row' or `newline-and-indent', depending on
21082 context. See the individual commands for more information."
21083 (interactive)
21084 (org-return t))
21086 (defun org-ctrl-c-star ()
21087 "Compute table, or change heading status of lines.
21088 Calls `org-table-recalculate' or `org-toggle-heading',
21089 depending on context."
21090 (interactive)
21091 (cond
21092 ((org-at-table-p)
21093 (call-interactively 'org-table-recalculate))
21095 ;; Convert all lines in region to list items
21096 (call-interactively 'org-toggle-heading))))
21098 (defun org-ctrl-c-minus ()
21099 "Insert separator line in table or modify bullet status of line.
21100 Also turns a plain line or a region of lines into list items.
21101 Calls `org-table-insert-hline', `org-toggle-item', or
21102 `org-cycle-list-bullet', depending on context."
21103 (interactive)
21104 (cond
21105 ((org-at-table-p)
21106 (call-interactively 'org-table-insert-hline))
21107 ((org-region-active-p)
21108 (call-interactively 'org-toggle-item))
21109 ((org-in-item-p)
21110 (call-interactively 'org-cycle-list-bullet))
21112 (call-interactively 'org-toggle-item))))
21114 (defun org-toggle-heading (&optional nstars)
21115 "Convert headings to normal text, or items or text to headings.
21116 If there is no active region, only convert the current line.
21118 With a `\\[universal-argument]' prefix, convert the whole list at
21119 point into heading.
21121 In a region:
21123 - If the first non blank line is a headline, remove the stars
21124 from all headlines in the region.
21126 - If it is a normal line, turn each and every normal line (i.e.,
21127 not an heading or an item) in the region into headings. If you
21128 want to convert only the first line of this region, use one
21129 universal prefix argument.
21131 - If it is a plain list item, turn all plain list items into headings.
21133 When converting a line into a heading, the number of stars is chosen
21134 such that the lines become children of the current entry. However,
21135 when a numeric prefix argument is given, its value determines the
21136 number of stars to add."
21137 (interactive "P")
21138 (let ((skip-blanks
21139 (function
21140 ;; Return beginning of first non-blank line, starting from
21141 ;; line at POS.
21142 (lambda (pos)
21143 (save-excursion
21144 (goto-char pos)
21145 (while (org-at-comment-p) (forward-line))
21146 (skip-chars-forward " \r\t\n")
21147 (point-at-bol)))))
21148 beg end toggled)
21149 ;; Determine boundaries of changes. If a universal prefix has
21150 ;; been given, put the list in a region. If region ends at a bol,
21151 ;; do not consider the last line to be in the region.
21153 (when (and current-prefix-arg (org-at-item-p))
21154 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21155 (org-mark-element))
21157 (if (org-region-active-p)
21158 (setq beg (funcall skip-blanks (region-beginning))
21159 end (copy-marker (save-excursion
21160 (goto-char (region-end))
21161 (if (bolp) (point) (point-at-eol)))))
21162 (setq beg (funcall skip-blanks (point-at-bol))
21163 end (copy-marker (point-at-eol))))
21164 ;; Ensure inline tasks don't count as headings.
21165 (org-with-limited-levels
21166 (save-excursion
21167 (goto-char beg)
21168 (cond
21169 ;; Case 1. Started at an heading: de-star headings.
21170 ((org-at-heading-p)
21171 (while (< (point) end)
21172 (when (org-at-heading-p t)
21173 (looking-at org-outline-regexp) (replace-match "")
21174 (setq toggled t))
21175 (forward-line)))
21176 ;; Case 2. Started at an item: change items into headlines.
21177 ;; One star will be added by `org-list-to-subtree'.
21178 ((org-at-item-p)
21179 (while (< (point) end)
21180 (when (org-at-item-p)
21181 ;; Pay attention to cases when region ends before list.
21182 (let* ((struct (org-list-struct))
21183 (list-end
21184 (min (org-list-get-bottom-point struct) (1+ end))))
21185 (save-restriction
21186 (narrow-to-region (point) list-end)
21187 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21188 (setq toggled t))
21189 (forward-line)))
21190 ;; Case 3. Started at normal text: make every line an heading,
21191 ;; skipping headlines and items.
21192 (t (let* ((stars
21193 (make-string
21194 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21195 (add-stars
21196 (cond (nstars "") ; stars from prefix only
21197 ((equal stars "") "*") ; before first heading
21198 (org-odd-levels-only "**") ; inside heading, odd
21199 (t "*"))) ; inside heading, oddeven
21200 (rpl (concat stars add-stars " "))
21201 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21202 (while (< (point) (if (equal nstars '(4)) lend end))
21203 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21204 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21205 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21206 (forward-line)))))))
21207 (unless toggled (message "Cannot toggle heading from here"))))
21209 (defun org-meta-return (&optional arg)
21210 "Insert a new heading or wrap a region in a table.
21211 Calls `org-insert-heading', `org-insert-item' or
21212 `org-table-wrap-region', depending on context. When called with
21213 an argument, unconditionally call `org-insert-heading'."
21214 (interactive "P")
21215 (org-check-before-invisible-edit 'insert)
21216 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21217 (call-interactively (cond (arg #'org-insert-heading)
21218 ((org-at-table-p) #'org-table-wrap-region)
21219 ((org-in-item-p) #'org-insert-item)
21220 (t #'org-insert-heading)))))
21222 ;;; Menu entries
21224 (defsubst org-in-subtree-not-table-p ()
21225 "Are we in a subtree and not in a table?"
21226 (and (not (org-before-first-heading-p))
21227 (not (org-at-table-p))))
21229 ;; Define the Org mode menus
21230 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21231 '("Tbl"
21232 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21233 ["Next Field" org-cycle (org-at-table-p)]
21234 ["Previous Field" org-shifttab (org-at-table-p)]
21235 ["Next Row" org-return (org-at-table-p)]
21236 "--"
21237 ["Blank Field" org-table-blank-field (org-at-table-p)]
21238 ["Edit Field" org-table-edit-field (org-at-table-p)]
21239 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21240 "--"
21241 ("Column"
21242 ["Move Column Left" org-metaleft (org-at-table-p)]
21243 ["Move Column Right" org-metaright (org-at-table-p)]
21244 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21245 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21246 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21247 ("Row"
21248 ["Move Row Up" org-metaup (org-at-table-p)]
21249 ["Move Row Down" org-metadown (org-at-table-p)]
21250 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21251 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21252 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21253 "--"
21254 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21255 ("Rectangle"
21256 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21257 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21258 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21259 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21260 "--"
21261 ("Calculate"
21262 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21263 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21264 ["Edit Formulas" org-edit-special (org-at-table-p)]
21265 "--"
21266 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21267 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21268 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21269 "--"
21270 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21271 "--"
21272 ["Sum Column/Rectangle" org-table-sum
21273 (or (org-at-table-p) (org-region-active-p))]
21274 ["Which Column?" org-table-current-column (org-at-table-p)])
21275 ["Debug Formulas"
21276 org-table-toggle-formula-debugger
21277 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21278 ["Show Col/Row Numbers"
21279 org-table-toggle-coordinate-overlays
21280 :style toggle
21281 :selected (bound-and-true-p org-table-overlay-coordinates)]
21282 "--"
21283 ["Create" org-table-create (not (org-at-table-p))]
21284 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21285 ["Import from File" org-table-import (not (org-at-table-p))]
21286 ["Export to File" org-table-export (org-at-table-p)]
21287 "--"
21288 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21289 "--"
21290 ("Plot"
21291 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21292 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21294 (easy-menu-define org-org-menu org-mode-map "Org menu"
21295 '("Org"
21296 ("Show/Hide"
21297 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21298 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21299 ["Sparse Tree..." org-sparse-tree t]
21300 ["Reveal Context" org-reveal t]
21301 ["Show All" outline-show-all t]
21302 "--"
21303 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21304 "--"
21305 ["New Heading" org-insert-heading t]
21306 ("Navigate Headings"
21307 ["Up" outline-up-heading t]
21308 ["Next" outline-next-visible-heading t]
21309 ["Previous" outline-previous-visible-heading t]
21310 ["Next Same Level" outline-forward-same-level t]
21311 ["Previous Same Level" outline-backward-same-level t]
21312 "--"
21313 ["Jump" org-goto t])
21314 ("Edit Structure"
21315 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21316 "--"
21317 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21318 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21319 "--"
21320 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21321 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21322 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21323 "--"
21324 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21325 "--"
21326 ["Copy visible text" org-copy-visible t]
21327 "--"
21328 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21329 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21330 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21331 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21332 "--"
21333 ["Sort Region/Children" org-sort t]
21334 "--"
21335 ["Convert to odd levels" org-convert-to-odd-levels t]
21336 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21337 ("Editing"
21338 ["Emphasis..." org-emphasize t]
21339 ["Edit Source Example" org-edit-special t]
21340 "--"
21341 ["Footnote new/jump" org-footnote-action t]
21342 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21343 ("Archive"
21344 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21345 "--"
21346 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21347 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21348 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21350 "--"
21351 ("Hyperlinks"
21352 ["Store Link (Global)" org-store-link t]
21353 ["Find existing link to here" org-occur-link-in-agenda-files t]
21354 ["Insert Link" org-insert-link t]
21355 ["Follow Link" org-open-at-point t]
21356 "--"
21357 ["Next link" org-next-link t]
21358 ["Previous link" org-previous-link t]
21359 "--"
21360 ["Descriptive Links"
21361 org-toggle-link-display
21362 :style radio
21363 :selected org-descriptive-links
21365 ["Literal Links"
21366 org-toggle-link-display
21367 :style radio
21368 :selected (not org-descriptive-links)])
21369 "--"
21370 ("TODO Lists"
21371 ["TODO/DONE/-" org-todo t]
21372 ("Select keyword"
21373 ["Next keyword" org-shiftright (org-at-heading-p)]
21374 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21375 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21376 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21377 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21378 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21379 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21380 "--"
21381 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21382 :selected org-enforce-todo-dependencies :style toggle :active t]
21383 "Settings for tree at point"
21384 ["Do Children sequentially" org-toggle-ordered-property :style radio
21385 :selected (org-entry-get nil "ORDERED")
21386 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21387 ["Do Children parallel" org-toggle-ordered-property :style radio
21388 :selected (not (org-entry-get nil "ORDERED"))
21389 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21390 "--"
21391 ["Set Priority" org-priority t]
21392 ["Priority Up" org-shiftup t]
21393 ["Priority Down" org-shiftdown t]
21394 "--"
21395 ["Get news from all feeds" org-feed-update-all t]
21396 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21397 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21398 ("TAGS and Properties"
21399 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21400 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21401 "--"
21402 ["Set property" org-set-property (not (org-before-first-heading-p))]
21403 ["Column view of properties" org-columns t]
21404 ["Insert Column View DBlock" org-columns-insert-dblock t])
21405 ("Dates and Scheduling"
21406 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21407 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21408 ("Change Date"
21409 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21410 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21411 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21412 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21413 ["Compute Time Range" org-evaluate-time-range t]
21414 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21415 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21416 "--"
21417 ["Custom time format" org-toggle-time-stamp-overlays
21418 :style radio :selected org-display-custom-times]
21419 "--"
21420 ["Goto Calendar" org-goto-calendar t]
21421 ["Date from Calendar" org-date-from-calendar t]
21422 "--"
21423 ["Start/Restart Timer" org-timer-start t]
21424 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21425 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21426 ["Insert Timer String" org-timer t]
21427 ["Insert Timer Item" org-timer-item t])
21428 ("Logging work"
21429 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21430 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21431 ["Clock out" org-clock-out t]
21432 ["Clock cancel" org-clock-cancel t]
21433 "--"
21434 ["Mark as default task" org-clock-mark-default-task t]
21435 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21436 ["Goto running clock" org-clock-goto t]
21437 "--"
21438 ["Display times" org-clock-display t]
21439 ["Create clock table" org-clock-report t]
21440 "--"
21441 ["Record DONE time"
21442 (progn (setq org-log-done (not org-log-done))
21443 (message "Switching to %s will %s record a timestamp"
21444 (car org-done-keywords)
21445 (if org-log-done "automatically" "not")))
21446 :style toggle :selected org-log-done])
21447 "--"
21448 ["Agenda Command..." org-agenda t]
21449 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21450 ("File List for Agenda")
21451 ("Special views current file"
21452 ["TODO Tree" org-show-todo-tree t]
21453 ["Check Deadlines" org-check-deadlines t]
21454 ["Tags/Property tree" org-match-sparse-tree t])
21455 "--"
21456 ["Export/Publish..." org-export-dispatch t]
21457 ("LaTeX"
21458 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21459 :selected org-cdlatex-mode]
21460 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21461 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21462 ["Modify math symbol" org-cdlatex-math-modify
21463 (org-inside-LaTeX-fragment-p)]
21464 ["Insert citation" org-reftex-citation t])
21465 "--"
21466 ("MobileOrg"
21467 ["Push Files and Views" org-mobile-push t]
21468 ["Get Captured and Flagged" org-mobile-pull t]
21469 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21470 "--"
21471 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21472 "--"
21473 ("Documentation"
21474 ["Show Version" org-version t]
21475 ["Info Documentation" org-info t])
21476 ("Customize"
21477 ["Browse Org Group" org-customize t]
21478 "--"
21479 ["Expand This Menu" org-create-customize-menu
21480 (fboundp 'customize-menu-create)])
21481 ["Send bug report" org-submit-bug-report t]
21482 "--"
21483 ("Refresh/Reload"
21484 ["Refresh setup current buffer" org-mode-restart t]
21485 ["Reload Org (after update)" org-reload t]
21486 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21489 (defun org-info (&optional node)
21490 "Read documentation for Org in the info system.
21491 With optional NODE, go directly to that node."
21492 (interactive)
21493 (info (format "(org)%s" (or node ""))))
21495 ;;;###autoload
21496 (defun org-submit-bug-report ()
21497 "Submit a bug report on Org via mail.
21499 Don't hesitate to report any problems or inaccurate documentation.
21501 If you don't have setup sending mail from (X)Emacs, please copy the
21502 output buffer into your mail program, as it gives us important
21503 information about your Org version and configuration."
21504 (interactive)
21505 (require 'reporter)
21506 (defvar reporter-prompt-for-summary-p)
21507 (org-load-modules-maybe)
21508 (org-require-autoloaded-modules)
21509 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21510 (reporter-submit-bug-report
21511 "emacs-orgmode@gnu.org"
21512 (org-version nil 'full)
21513 (let (list)
21514 (save-window-excursion
21515 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21516 (delete-other-windows)
21517 (erase-buffer)
21518 (insert "You are about to submit a bug report to the Org mailing list.
21520 We would like to add your full Org and Outline configuration to the
21521 bug report. This greatly simplifies the work of the maintainer and
21522 other experts on the mailing list.
21524 HOWEVER, some variables you have customized may contain private
21525 information. The names of customers, colleagues, or friends, might
21526 appear in the form of file names, tags, todo states, or search strings.
21527 If you answer yes to the prompt, you might want to check and remove
21528 such private information before sending the email.")
21529 (add-text-properties (point-min) (point-max) '(face org-warning))
21530 (when (yes-or-no-p "Include your Org configuration ")
21531 (mapatoms
21532 (lambda (v)
21533 (and (boundp v)
21534 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21535 (or (and (symbol-value v)
21536 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21537 (and
21538 (get v 'custom-type) (get v 'standard-value)
21539 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21540 (push v list)))))
21541 (kill-buffer (get-buffer "*Warn about privacy*"))
21542 list))
21543 nil nil
21544 "Remember to cover the basics, that is, what you expected to happen and
21545 what in fact did happen. You don't know how to make a good report? See
21547 http://orgmode.org/manual/Feedback.html#Feedback
21549 Your bug report will be posted to the Org mailing list.
21550 ------------------------------------------------------------------------")
21551 (save-excursion
21552 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21553 (replace-match "\\1Bug: \\3 [\\2]")))))
21556 (defun org-install-agenda-files-menu ()
21557 (let ((bl (buffer-list)))
21558 (save-excursion
21559 (while bl
21560 (set-buffer (pop bl))
21561 (when (derived-mode-p 'org-mode) (setq bl nil)))
21562 (when (derived-mode-p 'org-mode)
21563 (easy-menu-change
21564 '("Org") "File List for Agenda"
21565 (append
21566 (list
21567 ["Edit File List" (org-edit-agenda-file-list) t]
21568 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21569 ["Remove Current File from List" org-remove-file t]
21570 ["Cycle through agenda files" org-cycle-agenda-files t]
21571 ["Occur in all agenda files" org-occur-in-agenda-files t]
21572 "--")
21573 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21575 ;;;; Documentation
21577 (defun org-require-autoloaded-modules ()
21578 (interactive)
21579 (mapc #'require
21580 '(org-agenda org-archive org-attach org-clock org-colview org-id
21581 org-table org-timer)))
21583 ;;;###autoload
21584 (defun org-reload (&optional uncompiled)
21585 "Reload all org lisp files.
21586 With prefix arg UNCOMPILED, load the uncompiled versions."
21587 (interactive "P")
21588 (require 'loadhist)
21589 (let* ((org-dir (org-find-library-dir "org"))
21590 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21591 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21592 (remove-re (format "\\`%s\\'"
21593 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21594 (feats (delete-dups
21595 (mapcar 'file-name-sans-extension
21596 (mapcar 'file-name-nondirectory
21597 (delq nil
21598 (mapcar 'feature-file
21599 features))))))
21600 (lfeat (append
21601 (sort
21602 (setq feats
21603 (delq nil (mapcar
21604 (lambda (f)
21605 (if (and (string-match feature-re f)
21606 (not (string-match remove-re f)))
21607 f nil))
21608 feats)))
21609 'string-lessp)
21610 (list "org-version" "org")))
21611 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21612 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21613 load-uncore load-misses)
21614 (setq load-misses
21615 (delq 't
21616 (mapcar (lambda (f)
21617 (or (org-load-noerror-mustsuffix (concat org-dir f))
21618 (and (string= org-dir contrib-dir)
21619 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21620 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21621 (add-to-list 'load-uncore f 'append)
21624 lfeat)))
21625 (when load-uncore
21626 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21627 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21628 (if load-misses
21629 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21630 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21631 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21633 ;;;###autoload
21634 (defun org-customize ()
21635 "Call the customize function with org as argument."
21636 (interactive)
21637 (org-load-modules-maybe)
21638 (org-require-autoloaded-modules)
21639 (customize-browse 'org))
21641 (defun org-create-customize-menu ()
21642 "Create a full customization menu for Org mode, insert it into the menu."
21643 (interactive)
21644 (org-load-modules-maybe)
21645 (org-require-autoloaded-modules)
21646 (if (fboundp 'customize-menu-create)
21647 (progn
21648 (easy-menu-change
21649 '("Org") "Customize"
21650 `(["Browse Org group" org-customize t]
21651 "--"
21652 ,(customize-menu-create 'org)
21653 ["Set" Custom-set t]
21654 ["Save" Custom-save t]
21655 ["Reset to Current" Custom-reset-current t]
21656 ["Reset to Saved" Custom-reset-saved t]
21657 ["Reset to Standard Settings" Custom-reset-standard t]))
21658 (message "\"Org\"-menu now contains full customization menu"))
21659 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21661 ;;;; Miscellaneous stuff
21663 ;;; Generally useful functions
21665 (defun org-get-at-eol (property n)
21666 "Get text property PROPERTY at the end of line less N characters."
21667 (get-text-property (- (point-at-eol) n) property))
21669 (defun org-find-text-property-in-string (prop s)
21670 "Return the first non-nil value of property PROP in string S."
21671 (or (get-text-property 0 prop s)
21672 (get-text-property (or (next-single-property-change 0 prop s) 0)
21673 prop s)))
21675 (defun org-display-warning (message)
21676 "Display the given MESSAGE as a warning."
21677 (display-warning 'org message :warning))
21679 (defun org-eval (form)
21680 "Eval FORM and return result."
21681 (condition-case error
21682 (eval form)
21683 (error (format "%%![Error: %s]" error))))
21685 (defun org-in-clocktable-p ()
21686 "Check if the cursor is in a clocktable."
21687 (let ((pos (point)) start)
21688 (save-excursion
21689 (end-of-line 1)
21690 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21691 (setq start (match-beginning 0))
21692 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21693 (>= (match-end 0) pos)
21694 start))))
21696 (defun org-in-verbatim-emphasis ()
21697 (save-match-data
21698 (and (org-in-regexp org-verbatim-re 2)
21699 (>= (point) (match-beginning 3))
21700 (<= (point) (match-end 4)))))
21702 (defun org-overlay-display (ovl text &optional face evap)
21703 "Make overlay OVL display TEXT with face FACE."
21704 (overlay-put ovl 'display text)
21705 (if face (overlay-put ovl 'face face))
21706 (if evap (overlay-put ovl 'evaporate t)))
21708 (defun org-overlay-before-string (ovl text &optional face evap)
21709 "Make overlay OVL display TEXT with face FACE."
21710 (if face (org-add-props text nil 'face face))
21711 (overlay-put ovl 'before-string text)
21712 (if evap (overlay-put ovl 'evaporate t)))
21714 (defun org-find-overlays (prop &optional pos delete)
21715 "Find all overlays specifying PROP at POS or point.
21716 If DELETE is non-nil, delete all those overlays."
21717 (let (found)
21718 (dolist (ov (overlays-at (or pos (point))) found)
21719 (cond ((not (overlay-get ov prop)))
21720 (delete (delete-overlay ov))
21721 (t (push ov found))))))
21723 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21724 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21725 (if (and marker (marker-buffer marker)
21726 (buffer-live-p (marker-buffer marker)))
21727 (progn
21728 (pop-to-buffer-same-window (marker-buffer marker))
21729 (when (or (> marker (point-max)) (< marker (point-min)))
21730 (widen))
21731 (goto-char marker)
21732 (org-show-context 'org-goto))
21733 (if bookmark
21734 (bookmark-jump bookmark)
21735 (error "Cannot find location"))))
21737 (defun org-quote-csv-field (s)
21738 "Quote field for inclusion in CSV material."
21739 (if (string-match "[\",]" s)
21740 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21743 (defun org-force-self-insert (N)
21744 "Needed to enforce self-insert under remapping."
21745 (interactive "p")
21746 (self-insert-command N))
21748 (defun org-shorten-string (s maxlength)
21749 "Shorten string S so that it is no longer than MAXLENGTH characters.
21750 If the string is shorter or has length MAXLENGTH, just return the
21751 original string. If it is longer, the functions finds a space in the
21752 string, breaks this string off at that locations and adds three dots
21753 as ellipsis. Including the ellipsis, the string will not be longer
21754 than MAXLENGTH. If finding a good breaking point in the string does
21755 not work, the string is just chopped off in the middle of a word
21756 if necessary."
21757 (if (<= (length s) maxlength)
21759 (let* ((n (max (- maxlength 4) 1))
21760 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21761 (if (string-match re s)
21762 (concat (match-string 1 s) "...")
21763 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21765 (defun org-get-indentation (&optional line)
21766 "Get the indentation of the current line, interpreting tabs.
21767 When LINE is given, assume it represents a line and compute its indentation."
21768 (if line
21769 (when (string-match "^ *" (org-remove-tabs line))
21770 (match-end 0))
21771 (save-excursion
21772 (beginning-of-line 1)
21773 (skip-chars-forward " \t")
21774 (current-column))))
21776 (defun org-get-string-indentation (s)
21777 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21778 (let ((n -1) (i 0) (w tab-width) c)
21779 (catch 'exit
21780 (while (< (setq n (1+ n)) (length s))
21781 (setq c (aref s n))
21782 (cond ((= c ?\ ) (setq i (1+ i)))
21783 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21784 (t (throw 'exit t)))))
21787 (defun org-remove-tabs (s &optional width)
21788 "Replace tabulators in S with spaces.
21789 Assumes that s is a single line, starting in column 0."
21790 (setq width (or width tab-width))
21791 (while (string-match "\t" s)
21792 (setq s (replace-match
21793 (make-string
21794 (- (* width (/ (+ (match-beginning 0) width) width))
21795 (match-beginning 0)) ?\ )
21796 t t s)))
21799 (defun org-fix-indentation (line ind)
21800 "Fix indentation in LINE.
21801 IND is a cons cell with target and minimum indentation.
21802 If the current indentation in LINE is smaller than the minimum,
21803 leave it alone. If it is larger than ind, set it to the target."
21804 (let* ((l (org-remove-tabs line))
21805 (i (org-get-indentation l))
21806 (i1 (car ind)) (i2 (cdr ind)))
21807 (when (>= i i2) (setq l (substring line i2)))
21808 (if (> i1 0)
21809 (concat (make-string i1 ?\ ) l)
21810 l)))
21812 (defun org-remove-indentation (code &optional n)
21813 "Remove maximum common indentation in string CODE and return it.
21814 N may optionally be the number of columns to remove. Return CODE
21815 as-is if removal failed."
21816 (with-temp-buffer
21817 (insert code)
21818 (if (org-do-remove-indentation n) (buffer-string) code)))
21820 (defun org-do-remove-indentation (&optional n)
21821 "Remove the maximum common indentation from the buffer.
21822 When optional argument N is a positive integer, remove exactly
21823 that much characters from indentation, if possible. Return nil
21824 if it fails."
21825 (catch :exit
21826 (goto-char (point-min))
21827 ;; Find maximum common indentation, if not specified.
21828 (let ((n (or n
21829 (let ((min-ind (point-max)))
21830 (save-excursion
21831 (while (re-search-forward "^[ \t]*\\S-" nil t)
21832 (let ((ind (1- (current-column))))
21833 (if (zerop ind) (throw :exit nil)
21834 (setq min-ind (min min-ind ind))))))
21835 min-ind))))
21836 (if (zerop n) (throw :exit nil)
21837 ;; Remove exactly N indentation, but give up if not possible.
21838 (while (not (eobp))
21839 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21840 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21841 ((< ind n) (throw :exit nil))
21842 (t (indent-line-to (- ind n))))
21843 (forward-line)))
21844 ;; Signal success.
21845 t))))
21847 (defun org-fill-template (template alist)
21848 "Find each %key of ALIST in TEMPLATE and replace it."
21849 (let ((case-fold-search nil))
21850 (dolist (entry (sort (copy-sequence alist)
21851 (lambda (a b) (< (length (car a)) (length (car b))))))
21852 (setq template
21853 (replace-regexp-in-string
21854 (concat "%" (regexp-quote (car entry)))
21855 (or (cdr entry) "") template t t)))
21856 template))
21858 (defun org-base-buffer (buffer)
21859 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21860 (if (not buffer)
21861 buffer
21862 (or (buffer-base-buffer buffer)
21863 buffer)))
21865 (defun org-wrap (string &optional width lines)
21866 "Wrap string to either a number of lines, or a width in characters.
21867 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21868 that costs. If there is a word longer than WIDTH, the text is actually
21869 wrapped to the length of that word.
21870 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21871 many lines, whatever width that takes.
21872 The return value is a list of lines, without newlines at the end."
21873 (let* ((words (org-split-string string "[ \t\n]+"))
21874 (maxword (apply 'max (mapcar 'org-string-width words)))
21875 w ll)
21876 (cond (width
21877 (org-do-wrap words (max maxword width)))
21878 (lines
21879 (setq w maxword)
21880 (setq ll (org-do-wrap words maxword))
21881 (if (<= (length ll) lines)
21883 (setq ll words)
21884 (while (> (length ll) lines)
21885 (setq w (1+ w))
21886 (setq ll (org-do-wrap words w)))
21887 ll))
21888 (t (error "Cannot wrap this")))))
21890 (defun org-do-wrap (words width)
21891 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21892 (let (lines line)
21893 (while words
21894 (setq line (pop words))
21895 (while (and words (< (+ (length line) (length (car words))) width))
21896 (setq line (concat line " " (pop words))))
21897 (setq lines (push line lines)))
21898 (nreverse lines)))
21900 (defun org-quote-vert (s)
21901 "Replace \"|\" with \"\\vert\"."
21902 (while (string-match "|" s)
21903 (setq s (replace-match "\\vert" t t s)))
21906 (defun org-uuidgen-p (s)
21907 "Is S an ID created by UUIDGEN?"
21908 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21910 (defun org-in-src-block-p (&optional inside)
21911 "Whether point is in a code source block.
21912 When INSIDE is non-nil, don't consider we are within a src block
21913 when point is at #+BEGIN_SRC or #+END_SRC."
21914 (let ((case-fold-search t))
21915 (or (and (eq (get-char-property (point) 'src-block) t))
21916 (and (not inside)
21917 (save-match-data
21918 (save-excursion
21919 (beginning-of-line)
21920 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21922 (defun org-context ()
21923 "Return a list of contexts of the current cursor position.
21924 If several contexts apply, all are returned.
21925 Each context entry is a list with a symbol naming the context, and
21926 two positions indicating start and end of the context. Possible
21927 contexts are:
21929 :headline anywhere in a headline
21930 :headline-stars on the leading stars in a headline
21931 :todo-keyword on a TODO keyword (including DONE) in a headline
21932 :tags on the TAGS in a headline
21933 :priority on the priority cookie in a headline
21934 :item on the first line of a plain list item
21935 :item-bullet on the bullet/number of a plain list item
21936 :checkbox on the checkbox in a plain list item
21937 :table in an Org table
21938 :table-special on a special filed in a table
21939 :table-table in a table.el table
21940 :clocktable in a clocktable
21941 :src-block in a source block
21942 :link on a hyperlink
21943 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21944 :target on a <<target>>
21945 :radio-target on a <<<radio-target>>>
21946 :latex-fragment on a LaTeX fragment
21947 :latex-preview on a LaTeX fragment with overlaid preview image
21949 This function expects the position to be visible because it uses font-lock
21950 faces as a help to recognize the following contexts: :table-special, :link,
21951 and :keyword."
21952 (let* ((f (get-text-property (point) 'face))
21953 (faces (if (listp f) f (list f)))
21954 (case-fold-search t)
21955 (p (point)) clist o)
21956 ;; First the large context
21957 (cond
21958 ((org-at-heading-p t)
21959 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21960 (when (progn
21961 (beginning-of-line 1)
21962 (looking-at org-todo-line-tags-regexp))
21963 (push (org-point-in-group p 1 :headline-stars) clist)
21964 (push (org-point-in-group p 2 :todo-keyword) clist)
21965 (push (org-point-in-group p 4 :tags) clist))
21966 (goto-char p)
21967 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21968 (when (looking-at "\\[#[A-Z0-9]\\]")
21969 (push (org-point-in-group p 0 :priority) clist)))
21971 ((org-at-item-p)
21972 (push (org-point-in-group p 2 :item-bullet) clist)
21973 (push (list :item (point-at-bol)
21974 (save-excursion (org-end-of-item) (point)))
21975 clist)
21976 (and (org-at-item-checkbox-p)
21977 (push (org-point-in-group p 0 :checkbox) clist)))
21979 ((org-at-table-p)
21980 (push (list :table (org-table-begin) (org-table-end)) clist)
21981 (when (memq 'org-formula faces)
21982 (push (list :table-special
21983 (previous-single-property-change p 'face)
21984 (next-single-property-change p 'face)) clist)))
21985 ((org-at-table-p 'any)
21986 (push (list :table-table) clist)))
21987 (goto-char p)
21989 (let ((case-fold-search t))
21990 ;; New the "medium" contexts: clocktables, source blocks
21991 (cond ((org-in-clocktable-p)
21992 (push (list :clocktable
21993 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21994 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21995 (match-beginning 1))
21996 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21997 (match-end 0))) clist))
21998 ((org-in-src-block-p)
21999 (push (list :src-block
22000 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22001 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22002 (match-beginning 1))
22003 (and (search-forward "#+END_SRC" nil t)
22004 (match-beginning 0))) clist))))
22005 (goto-char p)
22007 ;; Now the small context
22008 (cond
22009 ((org-at-timestamp-p)
22010 (push (org-point-in-group p 0 :timestamp) clist))
22011 ((memq 'org-link faces)
22012 (push (list :link
22013 (previous-single-property-change p 'face)
22014 (next-single-property-change p 'face)) clist))
22015 ((memq 'org-special-keyword faces)
22016 (push (list :keyword
22017 (previous-single-property-change p 'face)
22018 (next-single-property-change p 'face)) clist))
22019 ((org-at-target-p)
22020 (push (org-point-in-group p 0 :target) clist)
22021 (goto-char (1- (match-beginning 0)))
22022 (when (looking-at org-radio-target-regexp)
22023 (push (org-point-in-group p 0 :radio-target) clist))
22024 (goto-char p))
22025 ((setq o (cl-some
22026 (lambda (o)
22027 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22029 (overlays-at (point))))
22030 (push (list :latex-fragment
22031 (overlay-start o) (overlay-end o)) clist)
22032 (push (list :latex-preview
22033 (overlay-start o) (overlay-end o)) clist))
22034 ((org-inside-LaTeX-fragment-p)
22035 ;; FIXME: positions wrong.
22036 (push (list :latex-fragment (point) (point)) clist)))
22038 (setq clist (nreverse (delq nil clist)))
22039 clist))
22041 (defun org-in-regexp (regexp &optional nlines visually)
22042 "Check if point is inside a match of REGEXP.
22044 Normally only the current line is checked, but you can include
22045 NLINES extra lines around point into the search. If VISUALLY is
22046 set, require that the cursor is not after the match but really
22047 on, so that the block visually is on the match.
22049 Return nil or a cons cell (BEG . END) where BEG and END are,
22050 respectively, the positions at the beginning and the end of the
22051 match."
22052 (catch :exit
22053 (let ((pos (point))
22054 (eol (line-end-position (if nlines (1+ nlines) 1))))
22055 (save-excursion
22056 (beginning-of-line (- 1 (or nlines 0)))
22057 (while (and (re-search-forward regexp eol t)
22058 (<= (match-beginning 0) pos))
22059 (let ((end (match-end 0)))
22060 (when (or (> end pos) (and (= end pos) (not visually)))
22061 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22063 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22064 "Non-nil when point is between matches of START-RE and END-RE.
22066 Also return a non-nil value when point is on one of the matches.
22068 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22069 buffer positions. Default values are the positions of headlines
22070 surrounding the point.
22072 The functions returns a cons cell whose car (resp. cdr) is the
22073 position before START-RE (resp. after END-RE)."
22074 (save-match-data
22075 (let ((pos (point))
22076 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22077 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22078 beg end)
22079 (save-excursion
22080 ;; Point is on a block when on START-RE or if START-RE can be
22081 ;; found before it...
22082 (and (or (org-in-regexp start-re)
22083 (re-search-backward start-re limit-up t))
22084 (setq beg (match-beginning 0))
22085 ;; ... and END-RE after it...
22086 (goto-char (match-end 0))
22087 (re-search-forward end-re limit-down t)
22088 (> (setq end (match-end 0)) pos)
22089 ;; ... without another START-RE in-between.
22090 (goto-char (match-beginning 0))
22091 (not (re-search-backward start-re (1+ beg) t))
22092 ;; Return value.
22093 (cons beg end))))))
22095 (defun org-in-block-p (names)
22096 "Non-nil when point belongs to a block whose name belongs to NAMES.
22098 NAMES is a list of strings containing names of blocks.
22100 Return first block name matched, or nil. Beware that in case of
22101 nested blocks, the returned name may not belong to the closest
22102 block from point."
22103 (save-match-data
22104 (catch 'exit
22105 (let ((case-fold-search t)
22106 (lim-up (save-excursion (outline-previous-heading)))
22107 (lim-down (save-excursion (outline-next-heading))))
22108 (dolist (name names)
22109 (let ((n (regexp-quote name)))
22110 (when (org-between-regexps-p
22111 (concat "^[ \t]*#\\+begin_" n)
22112 (concat "^[ \t]*#\\+end_" n)
22113 lim-up lim-down)
22114 (throw 'exit n)))))
22115 nil)))
22117 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22118 "Call `multi-occur' with buffers for all agenda files."
22119 (interactive "sOrg-files matching: ")
22120 (let* ((files (org-agenda-files))
22121 (tnames (mapcar #'file-truename files))
22122 (extra org-agenda-text-search-extra-files))
22123 (when (eq (car extra) 'agenda-archives)
22124 (setq extra (cdr extra))
22125 (setq files (org-add-archive-files files)))
22126 (dolist (f extra)
22127 (unless (member (file-truename f) tnames)
22128 (unless (member f files) (setq files (append files (list f))))
22129 (setq tnames (append tnames (list (file-truename f))))))
22130 (multi-occur
22131 (mapcar (lambda (x)
22132 (with-current-buffer
22133 ;; FIXME: Why not just (find-file-noselect x)?
22134 ;; Is it to avoid the "revert buffer" prompt?
22135 (or (get-file-buffer x) (find-file-noselect x))
22136 (widen)
22137 (current-buffer)))
22138 files)
22139 regexp)))
22141 (add-hook 'occur-mode-find-occurrence-hook
22142 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22144 (defun org-occur-link-in-agenda-files ()
22145 "Create a link and search for it in the agendas.
22146 The link is not stored in `org-stored-links', it is just created
22147 for the search purpose."
22148 (interactive)
22149 (let ((link (condition-case nil
22150 (org-store-link nil)
22151 (error "Unable to create a link to here"))))
22152 (org-occur-in-agenda-files (regexp-quote link))))
22154 (defun org-reverse-string (string)
22155 "Return the reverse of STRING."
22156 (apply 'string (reverse (string-to-list string))))
22158 ;; defsubst org-uniquify must be defined before first use
22160 (defun org-uniquify-alist (alist)
22161 "Merge elements of ALIST with the same key.
22163 For example, in this alist:
22165 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22166 => \\='((a 1 3) (b 2))
22168 merge (a 1) and (a 3) into (a 1 3).
22170 The function returns the new ALIST."
22171 (let (rtn)
22172 (dolist (e alist rtn)
22173 (let (n)
22174 (if (not (assoc (car e) rtn))
22175 (push e rtn)
22176 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22177 (setq rtn (assq-delete-all (car e) rtn))
22178 (push n rtn))))))
22180 (defun org-delete-all (elts list)
22181 "Remove all elements in ELTS from LIST.
22182 Comparison is done with `equal'. It is a destructive operation
22183 that may remove elements by altering the list structure."
22184 (while elts
22185 (setq list (delete (pop elts) list)))
22186 list)
22188 (defun org-back-over-empty-lines ()
22189 "Move backwards over whitespace, to the beginning of the first empty line.
22190 Returns the number of empty lines passed."
22191 (let ((pos (point)))
22192 (if (cdr (assq 'heading org-blank-before-new-entry))
22193 (skip-chars-backward " \t\n\r")
22194 (unless (eobp)
22195 (forward-line -1)))
22196 (beginning-of-line 2)
22197 (goto-char (min (point) pos))
22198 (count-lines (point) pos)))
22200 (defun org-skip-whitespace ()
22201 (skip-chars-forward " \t\n\r"))
22203 (defun org-point-in-group (point group &optional context)
22204 "Check if POINT is in match-group GROUP.
22205 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22206 match. If the match group does not exist or point is not inside it,
22207 return nil."
22208 (and (match-beginning group)
22209 (>= point (match-beginning group))
22210 (<= point (match-end group))
22211 (if context
22212 (list context (match-beginning group) (match-end group))
22213 t)))
22215 (defun org-switch-to-buffer-other-window (&rest args)
22216 "Switch to buffer in a second window on the current frame.
22217 In particular, do not allow pop-up frames.
22218 Returns the newly created buffer."
22219 (org-no-popups
22220 (apply 'switch-to-buffer-other-window args)))
22222 (defun org-combine-plists (&rest plists)
22223 "Create a single property list from all plists in PLISTS.
22224 The process starts by copying the first list, and then setting properties
22225 from the other lists. Settings in the last list are the most significant
22226 ones and overrule settings in the other lists."
22227 (let ((rtn (copy-sequence (pop plists)))
22228 p v ls)
22229 (while plists
22230 (setq ls (pop plists))
22231 (while ls
22232 (setq p (pop ls) v (pop ls))
22233 (setq rtn (plist-put rtn p v))))
22234 rtn))
22236 (defun org-replace-escapes (string table)
22237 "Replace %-escapes in STRING with values in TABLE.
22238 TABLE is an association list with keys like \"%a\" and string values.
22239 The sequences in STRING may contain normal field width and padding information,
22240 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22241 so values can contain further %-escapes if they are define later in TABLE."
22242 (let ((tbl (copy-alist table))
22243 (case-fold-search nil)
22244 (pchg 0)
22245 re rpl)
22246 (dolist (e tbl)
22247 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22248 (when (and (cdr e) (string-match re (cdr e)))
22249 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22250 (safe "SREF"))
22251 (add-text-properties 0 3 (list 'sref sref) safe)
22252 (setcdr e (replace-match safe t t (cdr e)))))
22253 (while (string-match re string)
22254 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22255 (cdr e)))
22256 (setq string (replace-match rpl t t string))))
22257 (while (setq pchg (next-property-change pchg string))
22258 (let ((sref (get-text-property pchg 'sref string)))
22259 (when (and sref (string-match "SREF" string pchg))
22260 (setq string (replace-match sref t t string)))))
22261 string))
22263 (defun org-find-base-buffer-visiting (file)
22264 "Like `find-buffer-visiting' but always return the base buffer and
22265 not an indirect buffer."
22266 (let ((buf (or (get-file-buffer file)
22267 (find-buffer-visiting file))))
22268 (if buf
22269 (or (buffer-base-buffer buf) buf)
22270 nil)))
22272 ;;; TODO: Only called once, from ox-odt which should probably use
22273 ;;; org-export-inline-image-p or something.
22274 (defun org-file-image-p (file)
22275 "Return non-nil if FILE is an image."
22276 (save-match-data
22277 (string-match (image-file-name-regexp) file)))
22279 (defun org-get-cursor-date (&optional with-time)
22280 "Return the date at cursor in as a time.
22281 This works in the calendar and in the agenda, anywhere else it just
22282 returns the current time.
22283 If WITH-TIME is non-nil, returns the time of the event at point (in
22284 the agenda) or the current time of the day."
22285 (let (date day defd tp hod mod)
22286 (when with-time
22287 (setq tp (get-text-property (point) 'time))
22288 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22289 (setq hod (string-to-number (match-string 1 tp))
22290 mod (string-to-number (match-string 2 tp))))
22291 (or tp (let ((now (decode-time)))
22292 (setq hod (nth 2 now)
22293 mod (nth 1 now)))))
22294 (cond
22295 ((eq major-mode 'calendar-mode)
22296 (setq date (calendar-cursor-to-date)
22297 defd (encode-time 0 (or mod 0) (or hod 0)
22298 (nth 1 date) (nth 0 date) (nth 2 date))))
22299 ((eq major-mode 'org-agenda-mode)
22300 (setq day (get-text-property (point) 'day))
22301 (when day
22302 (setq date (calendar-gregorian-from-absolute day)
22303 defd (encode-time 0 (or mod 0) (or hod 0)
22304 (nth 1 date) (nth 0 date) (nth 2 date))))))
22305 (or defd (current-time))))
22307 (defun org-mark-subtree (&optional up)
22308 "Mark the current subtree.
22309 This puts point at the start of the current subtree, and mark at
22310 the end. If a numeric prefix UP is given, move up into the
22311 hierarchy of headlines by UP levels before marking the subtree."
22312 (interactive "P")
22313 (org-with-limited-levels
22314 (cond ((org-at-heading-p) (beginning-of-line))
22315 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22316 (t (outline-previous-visible-heading 1))))
22317 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22318 (if (called-interactively-p 'any)
22319 (call-interactively 'org-mark-element)
22320 (org-mark-element)))
22322 (defun org-file-newer-than-p (file time)
22323 "Non-nil if FILE is newer than TIME.
22324 FILE is a filename, as a string, TIME is a list of integers, as
22325 returned by, e.g., `current-time'."
22326 (and (file-exists-p file)
22327 ;; Only compare times up to whole seconds as some file-systems
22328 ;; (e.g. HFS+) do not retain any finer granularity. As
22329 ;; a consequence, make sure we return non-nil when the two
22330 ;; times are equal.
22331 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22332 (cl-subseq time 0 2)))))
22334 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22335 "Compile a SOURCE file using PROCESS.
22337 PROCESS is either a function or a list of shell commands, as
22338 strings. EXT is a file extension, without the leading dot, as
22339 a string. It is used to check if the process actually succeeded.
22341 PROCESS must create a file with the same base name and directory
22342 as SOURCE, but ending with EXT. The function then returns its
22343 filename. Otherwise, it raises an error. The error message can
22344 then be refined by providing string ERR-MSG, which is appended to
22345 the standard message.
22347 If PROCESS is a function, it is called with a single argument:
22348 the SOURCE file.
22350 If it is a list of commands, each of them is called using
22351 `shell-command'. By default, in each command, %b, %f, %F, %o and
22352 %O are replaced with, respectively, SOURCE base name, name, full
22353 name, directory and absolute output file name. It is possible,
22354 however, to use more place-holders by specifying them in optional
22355 argument SPEC, as an alist following the pattern
22357 (CHARACTER . REPLACEMENT-STRING).
22359 When PROCESS is a list of commands, optional argument LOG-BUF can
22360 be set to a buffer or a buffer name. `shell-command' then uses
22361 it for output."
22362 (let* ((base-name (file-name-base source))
22363 (full-name (file-truename source))
22364 (out-dir (or (file-name-directory source) "./"))
22365 (output (expand-file-name (concat base-name "." ext) out-dir))
22366 (time (current-time))
22367 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22368 (save-window-excursion
22369 (pcase process
22370 ((pred functionp) (funcall process (shell-quote-argument source)))
22371 ((pred consp)
22372 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22373 (spec (append spec
22374 `((?b . ,(shell-quote-argument base-name))
22375 (?f . ,(shell-quote-argument source))
22376 (?F . ,(shell-quote-argument full-name))
22377 (?o . ,(shell-quote-argument out-dir))
22378 (?O . ,(shell-quote-argument output))))))
22379 (dolist (command process)
22380 (shell-command (format-spec command spec) log-buf))
22381 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22382 (_ (error "No valid command to process %S%s" source err-msg))))
22383 ;; Check for process failure. Output file is expected to be
22384 ;; located in the same directory as SOURCE.
22385 (unless (org-file-newer-than-p output time)
22386 (error (format "File %S wasn't produced%s" output err-msg)))
22387 output))
22389 ;;; Indentation
22391 (defvar org-element-greater-elements)
22392 (defun org--get-expected-indentation (element contentsp)
22393 "Expected indentation column for current line, according to ELEMENT.
22394 ELEMENT is an element containing point. CONTENTSP is non-nil
22395 when indentation is to be computed according to contents of
22396 ELEMENT."
22397 (let ((type (org-element-type element))
22398 (start (org-element-property :begin element))
22399 (post-affiliated (org-element-property :post-affiliated element)))
22400 (org-with-wide-buffer
22401 (cond
22402 (contentsp
22403 (cl-case type
22404 ((diary-sexp footnote-definition) 0)
22405 ((headline inlinetask nil)
22406 (if (not org-adapt-indentation) 0
22407 (let ((level (org-current-level)))
22408 (if level (1+ level) 0))))
22409 ((item plain-list) (org-list-item-body-column post-affiliated))
22411 (goto-char start)
22412 (org-get-indentation))))
22413 ((memq type '(headline inlinetask nil))
22414 (if (org-match-line "[ \t]*$")
22415 (org--get-expected-indentation element t)
22417 ((memq type '(diary-sexp footnote-definition)) 0)
22418 ;; First paragraph of a footnote definition or an item.
22419 ;; Indent like parent.
22420 ((< (line-beginning-position) start)
22421 (org--get-expected-indentation
22422 (org-element-property :parent element) t))
22423 ;; At first line: indent according to previous sibling, if any,
22424 ;; ignoring footnote definitions and inline tasks, or parent's
22425 ;; contents.
22426 ((= (line-beginning-position) start)
22427 (catch 'exit
22428 (while t
22429 (if (= (point-min) start) (throw 'exit 0)
22430 (goto-char (1- start))
22431 (let* ((previous (org-element-at-point))
22432 (parent previous))
22433 (while (and parent (<= (org-element-property :end parent) start))
22434 (setq previous parent
22435 parent (org-element-property :parent parent)))
22436 (cond
22437 ((not previous) (throw 'exit 0))
22438 ((> (org-element-property :end previous) start)
22439 (throw 'exit (org--get-expected-indentation previous t)))
22440 ((memq (org-element-type previous)
22441 '(footnote-definition inlinetask))
22442 (setq start (org-element-property :begin previous)))
22443 (t (goto-char (org-element-property :begin previous))
22444 (throw 'exit
22445 (if (bolp) (org-get-indentation)
22446 ;; At first paragraph in an item or
22447 ;; a footnote definition.
22448 (org--get-expected-indentation
22449 (org-element-property :parent previous) t))))))))))
22450 ;; Otherwise, move to the first non-blank line above.
22452 (beginning-of-line)
22453 (let ((pos (point)))
22454 (skip-chars-backward " \r\t\n")
22455 (cond
22456 ;; Two blank lines end a footnote definition or a plain
22457 ;; list. When we indent an empty line after them, the
22458 ;; containing list or footnote definition is over, so it
22459 ;; qualifies as a previous sibling. Therefore, we indent
22460 ;; like its first line.
22461 ((and (memq type '(footnote-definition plain-list))
22462 (> (count-lines (point) pos) 2))
22463 (goto-char start)
22464 (org-get-indentation))
22465 ;; Line above is the first one of a paragraph at the
22466 ;; beginning of an item or a footnote definition. Indent
22467 ;; like parent.
22468 ((< (line-beginning-position) start)
22469 (org--get-expected-indentation
22470 (org-element-property :parent element) t))
22471 ;; Line above is the beginning of an element, i.e., point
22472 ;; was originally on the blank lines between element's start
22473 ;; and contents.
22474 ((= (line-beginning-position) post-affiliated)
22475 (org--get-expected-indentation element t))
22476 ;; POS is after contents in a greater element. Indent like
22477 ;; the beginning of the element.
22478 ((and (memq type org-element-greater-elements)
22479 (let ((cend (org-element-property :contents-end element)))
22480 (and cend (<= cend pos))))
22481 ;; As a special case, if point is at the end of a footnote
22482 ;; definition or an item, indent like the very last element
22483 ;; within. If that last element is an item, indent like
22484 ;; its contents.
22485 (if (memq type '(footnote-definition item plain-list))
22486 (let ((last (org-element-at-point)))
22487 (goto-char pos)
22488 (org--get-expected-indentation
22489 last (eq (org-element-type last) 'item)))
22490 (goto-char start)
22491 (org-get-indentation)))
22492 ;; In any other case, indent like the current line.
22493 (t (org-get-indentation)))))))))
22495 (defun org--align-node-property ()
22496 "Align node property at point.
22497 Alignment is done according to `org-property-format', which see."
22498 (when (save-excursion
22499 (beginning-of-line)
22500 (looking-at org-property-re))
22501 (replace-match
22502 (concat (match-string 4)
22503 (org-trim
22504 (format org-property-format (match-string 1) (match-string 3))))
22505 t t)))
22507 (defun org-indent-line ()
22508 "Indent line depending on context.
22510 Indentation is done according to the following rules:
22512 - Footnote definitions, diary sexps, headlines and inline tasks
22513 have to start at column 0.
22515 - On the very first line of an element, consider, in order, the
22516 next rules until one matches:
22518 1. If there's a sibling element before, ignoring footnote
22519 definitions and inline tasks, indent like its first line.
22521 2. If element has a parent, indent like its contents. More
22522 precisely, if parent is an item, indent after the
22523 description part, if any, or the bullet (see
22524 `org-list-description-max-indent'). Else, indent like
22525 parent's first line.
22527 3. Otherwise, indent relatively to current level, if
22528 `org-adapt-indentation' is non-nil, or to left margin.
22530 - On a blank line at the end of an element, indent according to
22531 the type of the element. More precisely
22533 1. If element is a plain list, an item, or a footnote
22534 definition, indent like the very last element within.
22536 2. If element is a paragraph, indent like its last non blank
22537 line.
22539 3. Otherwise, indent like its very first line.
22541 - In the code part of a source block, use language major mode
22542 to indent current line if `org-src-tab-acts-natively' is
22543 non-nil. If it is nil, do nothing.
22545 - Otherwise, indent like the first non-blank line above.
22547 The function doesn't indent an item as it could break the whole
22548 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22549 `\\[org-shiftmetaright]'.
22551 Also align node properties according to `org-property-format'."
22552 (interactive)
22553 (cond
22554 (orgstruct-is-++
22555 (let ((indent-line-function
22556 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22557 (indent-according-to-mode)))
22558 ((org-at-heading-p) 'noindent)
22560 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22561 (type (org-element-type element)))
22562 (cond ((and (memq type '(plain-list item))
22563 (= (line-beginning-position)
22564 (org-element-property :post-affiliated element)))
22565 'noindent)
22566 ((and (eq type 'latex-environment)
22567 (>= (point) (org-element-property :post-affiliated element))
22568 (< (point) (org-with-wide-buffer
22569 (goto-char (org-element-property :end element))
22570 (skip-chars-backward " \r\t\n")
22571 (line-beginning-position 2))))
22572 'noindent)
22573 ((and (eq type 'src-block)
22574 org-src-tab-acts-natively
22575 (> (line-beginning-position)
22576 (org-element-property :post-affiliated element))
22577 (< (line-beginning-position)
22578 (org-with-wide-buffer
22579 (goto-char (org-element-property :end element))
22580 (skip-chars-backward " \r\t\n")
22581 (line-beginning-position))))
22582 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22584 (let ((column (org--get-expected-indentation element nil)))
22585 ;; Preserve current column.
22586 (if (<= (current-column) (current-indentation))
22587 (indent-line-to column)
22588 (save-excursion (indent-line-to column))))
22589 ;; Align node property. Also preserve current column.
22590 (when (eq type 'node-property)
22591 (let ((column (current-column)))
22592 (org--align-node-property)
22593 (org-move-to-column column)))))))))
22595 (defun org-indent-region (start end)
22596 "Indent each non-blank line in the region.
22597 Called from a program, START and END specify the region to
22598 indent. The function will not indent contents of example blocks,
22599 verse blocks and export blocks as leading white spaces are
22600 assumed to be significant there."
22601 (interactive "r")
22602 (save-excursion
22603 (goto-char start)
22604 (skip-chars-forward " \r\t\n")
22605 (unless (eobp) (beginning-of-line))
22606 (let ((indent-to
22607 (lambda (ind pos)
22608 ;; Set IND as indentation for all lines between point and
22609 ;; POS. Blank lines are ignored. Leave point after POS
22610 ;; once done.
22611 (let ((limit (copy-marker pos)))
22612 (while (< (point) limit)
22613 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22614 (forward-line))
22615 (set-marker limit nil))))
22616 (end (copy-marker end)))
22617 (while (< (point) end)
22618 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22619 (let* ((element (org-element-at-point))
22620 (type (org-element-type element))
22621 (element-end (copy-marker (org-element-property :end element)))
22622 (ind (org--get-expected-indentation element nil)))
22623 (cond
22624 ;; Element indented as a single block. Example blocks
22625 ;; preserving indentation are a special case since the
22626 ;; "contents" must not be indented whereas the block
22627 ;; boundaries can.
22628 ((or (memq type '(export-block latex-environment))
22629 (and (eq type 'example-block)
22630 (not
22631 (or org-src-preserve-indentation
22632 (org-element-property :preserve-indent element)))))
22633 (let ((offset (- ind (org-get-indentation))))
22634 (unless (zerop offset)
22635 (indent-rigidly (org-element-property :begin element)
22636 (org-element-property :end element)
22637 offset)))
22638 (goto-char element-end))
22639 ;; Elements indented line wise. Be sure to exclude
22640 ;; example blocks (preserving indentation) and source
22641 ;; blocks from this category as they are treated
22642 ;; specially later.
22643 ((or (memq type '(paragraph table table-row))
22644 (not (or (org-element-property :contents-begin element)
22645 (memq type '(example-block src-block)))))
22646 (when (eq type 'node-property)
22647 (org--align-node-property)
22648 (beginning-of-line))
22649 (funcall indent-to ind (min element-end end)))
22650 ;; Elements consisting of three parts: before the
22651 ;; contents, the contents, and after the contents. The
22652 ;; contents are treated specially, according to the
22653 ;; element type, or not indented at all. Other parts are
22654 ;; indented as a single block.
22656 (let* ((post (copy-marker
22657 (org-element-property :post-affiliated element)))
22658 (cbeg
22659 (copy-marker
22660 (cond
22661 ((not (org-element-property :contents-begin element))
22662 ;; Fake contents for source blocks.
22663 (org-with-wide-buffer
22664 (goto-char post)
22665 (line-beginning-position 2)))
22666 ((memq type '(footnote-definition item plain-list))
22667 ;; Contents in these elements could start on
22668 ;; the same line as the beginning of the
22669 ;; element. Make sure we start indenting
22670 ;; from the second line.
22671 (org-with-wide-buffer
22672 (goto-char post)
22673 (end-of-line)
22674 (skip-chars-forward " \r\t\n")
22675 (if (eobp) (point) (line-beginning-position))))
22676 (t (org-element-property :contents-begin element)))))
22677 (cend (copy-marker
22678 (or (org-element-property :contents-end element)
22679 ;; Fake contents for source blocks.
22680 (org-with-wide-buffer
22681 (goto-char element-end)
22682 (skip-chars-backward " \r\t\n")
22683 (line-beginning-position)))
22684 t)))
22685 ;; Do not change items indentation individually as it
22686 ;; might break the list as a whole. On the other
22687 ;; hand, when at a plain list, indent it as a whole.
22688 (cond ((eq type 'plain-list)
22689 (let ((offset (- ind (org-get-indentation))))
22690 (unless (zerop offset)
22691 (indent-rigidly (org-element-property :begin element)
22692 (org-element-property :end element)
22693 offset))
22694 (goto-char cbeg)))
22695 ((eq type 'item) (goto-char cbeg))
22696 (t (funcall indent-to ind (min cbeg end))))
22697 (when (< (point) end)
22698 (cl-case type
22699 ((example-block verse-block))
22700 (src-block
22701 ;; In a source block, indent source code
22702 ;; according to language major mode, but only if
22703 ;; `org-src-tab-acts-natively' is non-nil.
22704 (when (and (< (point) end) org-src-tab-acts-natively)
22705 (ignore-errors
22706 (org-babel-do-in-edit-buffer
22707 (indent-region (point-min) (point-max))))))
22708 (t (org-indent-region (point) (min cend end))))
22709 (goto-char (min cend end))
22710 (when (< (point) end)
22711 (funcall indent-to ind (min element-end end))))
22712 (set-marker post nil)
22713 (set-marker cbeg nil)
22714 (set-marker cend nil))))
22715 (set-marker element-end nil))))
22716 (set-marker end nil))))
22718 (defun org-indent-drawer ()
22719 "Indent the drawer at point."
22720 (interactive)
22721 (unless (save-excursion
22722 (beginning-of-line)
22723 (looking-at-p org-drawer-regexp))
22724 (user-error "Not at a drawer"))
22725 (let ((element (org-element-at-point)))
22726 (unless (memq (org-element-type element) '(drawer property-drawer))
22727 (user-error "Not at a drawer"))
22728 (org-with-wide-buffer
22729 (org-indent-region (org-element-property :begin element)
22730 (org-element-property :end element))))
22731 (message "Drawer at point indented"))
22733 (defun org-indent-block ()
22734 "Indent the block at point."
22735 (interactive)
22736 (unless (save-excursion
22737 (beginning-of-line)
22738 (let ((case-fold-search t))
22739 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22740 (user-error "Not at a block"))
22741 (let ((element (org-element-at-point)))
22742 (unless (memq (org-element-type element)
22743 '(comment-block center-block dynamic-block example-block
22744 export-block quote-block special-block
22745 src-block verse-block))
22746 (user-error "Not at a block"))
22747 (org-with-wide-buffer
22748 (org-indent-region (org-element-property :begin element)
22749 (org-element-property :end element))))
22750 (message "Block at point indented"))
22753 ;;; Filling
22755 ;; We use our own fill-paragraph and auto-fill functions.
22757 ;; `org-fill-paragraph' relies on adaptive filling and context
22758 ;; checking. Appropriate `fill-prefix' is computed with
22759 ;; `org-adaptive-fill-function'.
22761 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22762 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22763 ;; `org-adaptive-fill-function' value. Internally,
22764 ;; `org-comment-line-break-function' breaks the line.
22766 ;; `org-setup-filling' installs filling and auto-filling related
22767 ;; variables during `org-mode' initialization.
22769 (defvar org-element-paragraph-separate) ; org-element.el
22770 (defun org-setup-filling ()
22771 (require 'org-element)
22772 ;; Prevent auto-fill from inserting unwanted new items.
22773 (when (boundp 'fill-nobreak-predicate)
22774 (setq-local
22775 fill-nobreak-predicate
22776 (org-uniquify
22777 (append fill-nobreak-predicate
22778 '(org-fill-line-break-nobreak-p
22779 org-fill-n-macro-as-item-nobreak-p
22780 org-fill-paragraph-with-timestamp-nobreak-p)))))
22781 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22782 (setq-local paragraph-start paragraph-ending)
22783 (setq-local paragraph-separate paragraph-ending))
22784 (setq-local fill-paragraph-function 'org-fill-paragraph)
22785 (setq-local auto-fill-inhibit-regexp nil)
22786 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22787 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22788 (setq-local comment-line-break-function 'org-comment-line-break-function))
22790 (defun org-fill-line-break-nobreak-p ()
22791 "Non-nil when a new line at point would create an Org line break."
22792 (save-excursion
22793 (skip-chars-backward "[ \t]")
22794 (skip-chars-backward "\\\\")
22795 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22797 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22798 "Non-nil when a new line at point would split a timestamp."
22799 (and (org-at-timestamp-p 'lax)
22800 (not (looking-at org-ts-regexp-both))))
22802 (defun org-fill-n-macro-as-item-nobreak-p ()
22803 "Non-nil when a new line at point would create a new list."
22804 ;; During export, a "n" macro followed by a dot or a closing
22805 ;; parenthesis can end up being parsed as a new list item.
22806 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22808 (declare-function message-in-body-p "message" ())
22809 (defvar orgtbl-line-start-regexp) ; From org-table.el
22810 (defun org-adaptive-fill-function ()
22811 "Compute a fill prefix for the current line.
22812 Return fill prefix, as a string, or nil if current line isn't
22813 meant to be filled. For convenience, if `adaptive-fill-regexp'
22814 matches in paragraphs or comments, use it."
22815 (catch 'exit
22816 (when (derived-mode-p 'message-mode)
22817 (save-excursion
22818 (beginning-of-line)
22819 (cond ((not (message-in-body-p)) (throw 'exit nil))
22820 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22821 ((looking-at message-cite-prefix-regexp)
22822 (throw 'exit (match-string-no-properties 0)))
22823 ((looking-at org-outline-regexp)
22824 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22825 (org-with-wide-buffer
22826 (unless (org-at-heading-p)
22827 (let* ((p (line-beginning-position))
22828 (element (save-excursion
22829 (beginning-of-line)
22830 (org-element-at-point)))
22831 (type (org-element-type element))
22832 (post-affiliated (org-element-property :post-affiliated element)))
22833 (unless (< p post-affiliated)
22834 (cl-case type
22835 (comment
22836 (save-excursion
22837 (beginning-of-line)
22838 (looking-at "[ \t]*")
22839 (concat (match-string 0) "# ")))
22840 (footnote-definition "")
22841 ((item plain-list)
22842 (make-string (org-list-item-body-column post-affiliated) ?\s))
22843 (paragraph
22844 ;; Fill prefix is usually the same as the current line,
22845 ;; unless the paragraph is at the beginning of an item.
22846 (let ((parent (org-element-property :parent element)))
22847 (save-excursion
22848 (beginning-of-line)
22849 (cond ((eq (org-element-type parent) 'item)
22850 (make-string (org-list-item-body-column
22851 (org-element-property :begin parent))
22852 ?\s))
22853 ((and adaptive-fill-regexp
22854 ;; Locally disable
22855 ;; `adaptive-fill-function' to let
22856 ;; `fill-context-prefix' handle
22857 ;; `adaptive-fill-regexp' variable.
22858 (let (adaptive-fill-function)
22859 (fill-context-prefix
22860 post-affiliated
22861 (org-element-property :end element)))))
22862 ((looking-at "[ \t]+") (match-string 0))
22863 (t "")))))
22864 (comment-block
22865 ;; Only fill contents if P is within block boundaries.
22866 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22867 (forward-line)
22868 (point)))
22869 (cend (save-excursion
22870 (goto-char (org-element-property :end element))
22871 (skip-chars-backward " \r\t\n")
22872 (line-beginning-position))))
22873 (when (and (>= p cbeg) (< p cend))
22874 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22875 (match-string 0)
22876 "")))))))))))
22878 (declare-function message-goto-body "message" ())
22879 (defvar message-cite-prefix-regexp) ; From message.el
22881 (defun org-fill-element (&optional justify)
22882 "Fill element at point, when applicable.
22884 This function only applies to comment blocks, comments, example
22885 blocks and paragraphs. Also, as a special case, re-align table
22886 when point is at one.
22888 If JUSTIFY is non-nil (interactively, with prefix argument),
22889 justify as well. If `sentence-end-double-space' is non-nil, then
22890 period followed by one space does not end a sentence, so don't
22891 break a line there. The variable `fill-column' controls the
22892 width for filling.
22894 For convenience, when point is at a plain list, an item or
22895 a footnote definition, try to fill the first paragraph within."
22896 (with-syntax-table org-mode-transpose-word-syntax-table
22897 ;; Move to end of line in order to get the first paragraph within
22898 ;; a plain list or a footnote definition.
22899 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22900 ;; First check if point is in a blank line at the beginning of
22901 ;; the buffer. In that case, ignore filling.
22902 (cl-case (org-element-type element)
22903 ;; Use major mode filling function is src blocks.
22904 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22905 ;; Align Org tables, leave table.el tables as-is.
22906 (table-row (org-table-align) t)
22907 (table
22908 (when (eq (org-element-property :type element) 'org)
22909 (save-excursion
22910 (goto-char (org-element-property :post-affiliated element))
22911 (org-table-align)))
22913 (paragraph
22914 ;; Paragraphs may contain `line-break' type objects.
22915 (let ((beg (max (point-min)
22916 (org-element-property :contents-begin element)))
22917 (end (min (point-max)
22918 (org-element-property :contents-end element))))
22919 ;; Do nothing if point is at an affiliated keyword.
22920 (if (< (line-end-position) beg) t
22921 (when (derived-mode-p 'message-mode)
22922 ;; In `message-mode', do not fill following citation
22923 ;; in current paragraph nor text before message body.
22924 (let ((body-start (save-excursion (message-goto-body))))
22925 (when body-start (setq beg (max body-start beg))))
22926 (when (save-excursion
22927 (re-search-forward
22928 (concat "^" message-cite-prefix-regexp) end t))
22929 (setq end (match-beginning 0))))
22930 ;; Fill paragraph, taking line breaks into account.
22931 (save-excursion
22932 (goto-char beg)
22933 (let ((cuts (list beg)))
22934 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22935 (when (eq 'line-break
22936 (org-element-type
22937 (save-excursion (backward-char)
22938 (org-element-context))))
22939 (push (point) cuts)))
22940 (dolist (c (delq end cuts))
22941 (fill-region-as-paragraph c end justify)
22942 (setq end c))))
22943 t)))
22944 ;; Contents of `comment-block' type elements should be
22945 ;; filled as plain text, but only if point is within block
22946 ;; markers.
22947 (comment-block
22948 (let* ((case-fold-search t)
22949 (beg (save-excursion
22950 (goto-char (org-element-property :begin element))
22951 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22952 (forward-line)
22953 (point)))
22954 (end (save-excursion
22955 (goto-char (org-element-property :end element))
22956 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22957 (line-beginning-position))))
22958 (if (or (< (point) beg) (> (point) end)) t
22959 (fill-region-as-paragraph
22960 (save-excursion (end-of-line)
22961 (re-search-backward "^[ \t]*$" beg 'move)
22962 (line-beginning-position))
22963 (save-excursion (beginning-of-line)
22964 (re-search-forward "^[ \t]*$" end 'move)
22965 (line-beginning-position))
22966 justify))))
22967 ;; Fill comments.
22968 (comment
22969 (let ((begin (org-element-property :post-affiliated element))
22970 (end (org-element-property :end element)))
22971 (when (and (>= (point) begin) (<= (point) end))
22972 (let ((begin (save-excursion
22973 (end-of-line)
22974 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22975 (progn (forward-line) (point))
22976 begin)))
22977 (end (save-excursion
22978 (end-of-line)
22979 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22980 (1- (line-beginning-position))
22981 (skip-chars-backward " \r\t\n")
22982 (line-end-position)))))
22983 ;; Do not fill comments when at a blank line.
22984 (when (> end begin)
22985 (let ((fill-prefix
22986 (save-excursion
22987 (beginning-of-line)
22988 (looking-at "[ \t]*#")
22989 (let ((comment-prefix (match-string 0)))
22990 (goto-char (match-end 0))
22991 (if (looking-at adaptive-fill-regexp)
22992 (concat comment-prefix (match-string 0))
22993 (concat comment-prefix " "))))))
22994 (save-excursion
22995 (fill-region-as-paragraph begin end justify))))))
22997 ;; Ignore every other element.
22998 (otherwise t)))))
23000 (defun org-fill-paragraph (&optional justify region)
23001 "Fill element at point, when applicable.
23003 This function only applies to comment blocks, comments, example
23004 blocks and paragraphs. Also, as a special case, re-align table
23005 when point is at one.
23007 For convenience, when point is at a plain list, an item or
23008 a footnote definition, try to fill the first paragraph within.
23010 If JUSTIFY is non-nil (interactively, with prefix argument),
23011 justify as well. If `sentence-end-double-space' is non-nil, then
23012 period followed by one space does not end a sentence, so don't
23013 break a line there. The variable `fill-column' controls the
23014 width for filling.
23016 The REGION argument is non-nil if called interactively; in that
23017 case, if Transient Mark mode is enabled and the mark is active,
23018 fill each of the elements in the active region, instead of just
23019 filling the current element."
23020 (interactive (progn
23021 (barf-if-buffer-read-only)
23022 (list (if current-prefix-arg 'full) t)))
23023 (cond
23024 ((and (derived-mode-p 'message-mode)
23025 (or (not (message-in-body-p))
23026 (save-excursion (move-beginning-of-line 1)
23027 (looking-at message-cite-prefix-regexp))))
23028 ;; First ensure filling is correct in message-mode.
23029 (let ((fill-paragraph-function
23030 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23031 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23032 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23033 (paragraph-separate
23034 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23035 (fill-paragraph nil)))
23036 ((and region transient-mark-mode mark-active
23037 (not (eq (region-beginning) (region-end))))
23038 (let ((origin (point-marker))
23039 (start (region-beginning)))
23040 (unwind-protect
23041 (progn
23042 (goto-char (region-end))
23043 (while (> (point) start)
23044 (org-backward-paragraph)
23045 (org-fill-element justify)))
23046 (goto-char origin)
23047 (set-marker origin nil))))
23048 (t (org-fill-element justify))))
23049 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23051 (defun org-auto-fill-function ()
23052 "Auto-fill function."
23053 ;; Check if auto-filling is meaningful.
23054 (let ((fc (current-fill-column)))
23055 (when (and fc (> (current-column) fc))
23056 (let* ((fill-prefix (org-adaptive-fill-function))
23057 ;; Enforce empty fill prefix, if required. Otherwise, it
23058 ;; will be computed again.
23059 (adaptive-fill-mode (not (equal fill-prefix ""))))
23060 (when fill-prefix (do-auto-fill))))))
23062 (defun org-comment-line-break-function (&optional soft)
23063 "Break line at point and indent, continuing comment if within one.
23064 The inserted newline is marked hard if variable
23065 `use-hard-newlines' is true, unless optional argument SOFT is
23066 non-nil."
23067 (if soft (insert-and-inherit ?\n) (newline 1))
23068 (save-excursion (forward-char -1) (delete-horizontal-space))
23069 (delete-horizontal-space)
23070 (indent-to-left-margin)
23071 (insert-before-markers-and-inherit fill-prefix))
23074 ;;; Fixed Width Areas
23076 (defun org-toggle-fixed-width ()
23077 "Toggle fixed-width markup.
23079 Add or remove fixed-width markup on current line, whenever it
23080 makes sense. Return an error otherwise.
23082 If a region is active and if it contains only fixed-width areas
23083 or blank lines, remove all fixed-width markup in it. If the
23084 region contains anything else, convert all non-fixed-width lines
23085 to fixed-width ones.
23087 Blank lines at the end of the region are ignored unless the
23088 region only contains such lines."
23089 (interactive)
23090 (if (not (org-region-active-p))
23091 ;; No region:
23093 ;; Remove fixed width marker only in a fixed-with element.
23095 ;; Add fixed width maker in paragraphs, in blank lines after
23096 ;; elements or at the beginning of a headline or an inlinetask,
23097 ;; and before any one-line elements (e.g., a clock).
23098 (progn
23099 (beginning-of-line)
23100 (let* ((element (org-element-at-point))
23101 (type (org-element-type element)))
23102 (cond
23103 ((and (eq type 'fixed-width)
23104 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23105 (replace-match
23106 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23107 ((and (memq type '(babel-call clock comment diary-sexp headline
23108 horizontal-rule keyword paragraph
23109 planning))
23110 (<= (org-element-property :post-affiliated element) (point)))
23111 (skip-chars-forward " \t")
23112 (insert ": "))
23113 ((and (looking-at-p "[ \t]*$")
23114 (or (eq type 'inlinetask)
23115 (save-excursion
23116 (skip-chars-forward " \r\t\n")
23117 (<= (org-element-property :end element) (point)))))
23118 (delete-region (point) (line-end-position))
23119 (org-indent-line)
23120 (insert ": "))
23121 (t (user-error "Cannot insert a fixed-width line here")))))
23122 ;; Region active.
23123 (let* ((begin (save-excursion
23124 (goto-char (region-beginning))
23125 (line-beginning-position)))
23126 (end (copy-marker
23127 (save-excursion
23128 (goto-char (region-end))
23129 (unless (eolp) (beginning-of-line))
23130 (if (save-excursion (re-search-backward "\\S-" begin t))
23131 (progn (skip-chars-backward " \r\t\n") (point))
23132 (point)))))
23133 (all-fixed-width-p
23134 (catch 'not-all-p
23135 (save-excursion
23136 (goto-char begin)
23137 (skip-chars-forward " \r\t\n")
23138 (when (eobp) (throw 'not-all-p nil))
23139 (while (< (point) end)
23140 (let ((element (org-element-at-point)))
23141 (if (eq (org-element-type element) 'fixed-width)
23142 (goto-char (org-element-property :end element))
23143 (throw 'not-all-p nil))))
23144 t))))
23145 (if all-fixed-width-p
23146 (save-excursion
23147 (goto-char begin)
23148 (while (< (point) end)
23149 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23150 (replace-match
23151 "" nil nil nil
23152 (if (= (line-end-position) (match-end 0)) 0 1)))
23153 (forward-line)))
23154 (let ((min-ind (point-max)))
23155 ;; Find minimum indentation across all lines.
23156 (save-excursion
23157 (goto-char begin)
23158 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23159 (setq min-ind 0)
23160 (catch 'zerop
23161 (while (< (point) end)
23162 (unless (looking-at-p "[ \t]*$")
23163 (let ((ind (org-get-indentation)))
23164 (setq min-ind (min min-ind ind))
23165 (when (zerop ind) (throw 'zerop t))))
23166 (forward-line)))))
23167 ;; Loop over all lines and add fixed-width markup everywhere
23168 ;; but in fixed-width lines.
23169 (save-excursion
23170 (goto-char begin)
23171 (while (< (point) end)
23172 (cond
23173 ((org-at-heading-p)
23174 (insert ": ")
23175 (forward-line)
23176 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23177 (insert ":")
23178 (forward-line)))
23179 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23180 (let* ((element (org-element-at-point))
23181 (element-end (org-element-property :end element)))
23182 (if (eq (org-element-type element) 'fixed-width)
23183 (progn (goto-char element-end)
23184 (skip-chars-backward " \r\t\n")
23185 (forward-line))
23186 (let ((limit (min end element-end)))
23187 (while (< (point) limit)
23188 (org-move-to-column min-ind t)
23189 (insert ": ")
23190 (forward-line))))))
23192 (org-move-to-column min-ind t)
23193 (insert ": ")
23194 (forward-line)))))))
23195 (set-marker end nil))))
23198 ;;; Comments
23200 ;; Org comments syntax is quite complex. It requires the entire line
23201 ;; to be just a comment. Also, even with the right syntax at the
23202 ;; beginning of line, some elements (e.g., verse-block or
23203 ;; example-block) don't accept comments. Usual Emacs comment commands
23204 ;; cannot cope with those requirements. Therefore, Org replaces them.
23206 ;; Org still relies on `comment-dwim', but cannot trust
23207 ;; `comment-only-p'. So, `comment-region-function' and
23208 ;; `uncomment-region-function' both point
23209 ;; to`org-comment-or-uncomment-region'. Eventually,
23210 ;; `org-insert-comment' takes care of insertion of comments at the
23211 ;; beginning of line.
23213 ;; `org-setup-comments-handling' install comments related variables
23214 ;; during `org-mode' initialization.
23216 (defun org-setup-comments-handling ()
23217 (interactive)
23218 (setq-local comment-use-syntax nil)
23219 (setq-local comment-start "# ")
23220 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23221 (setq-local comment-insert-comment-function 'org-insert-comment)
23222 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23223 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23225 (defun org-insert-comment ()
23226 "Insert an empty comment above current line.
23227 If the line is empty, insert comment at its beginning. When
23228 point is within a source block, comment according to the related
23229 major mode."
23230 (if (let ((element (org-element-at-point)))
23231 (and (eq (org-element-type element) 'src-block)
23232 (< (save-excursion
23233 (goto-char (org-element-property :post-affiliated element))
23234 (line-end-position))
23235 (point))
23236 (> (save-excursion
23237 (goto-char (org-element-property :end element))
23238 (skip-chars-backward " \r\t\n")
23239 (line-beginning-position))
23240 (point))))
23241 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23242 (beginning-of-line)
23243 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23244 (open-line 1))
23245 (org-indent-line)
23246 (insert "# ")))
23248 (defvar comment-empty-lines) ; From newcomment.el.
23249 (defun org-comment-or-uncomment-region (beg end &rest _)
23250 "Comment or uncomment each non-blank line in the region.
23251 Uncomment each non-blank line between BEG and END if it only
23252 contains commented lines. Otherwise, comment them. If region is
23253 strictly within a source block, use appropriate comment syntax."
23254 (if (let ((element (org-element-at-point)))
23255 (and (eq (org-element-type element) 'src-block)
23256 (< (save-excursion
23257 (goto-char (org-element-property :post-affiliated element))
23258 (line-end-position))
23259 beg)
23260 (>= (save-excursion
23261 (goto-char (org-element-property :end element))
23262 (skip-chars-backward " \r\t\n")
23263 (line-beginning-position))
23264 end)))
23265 ;; Translate region boundaries for the Org buffer to the source
23266 ;; buffer.
23267 (let ((offset (- end beg)))
23268 (save-excursion
23269 (goto-char beg)
23270 (org-babel-do-in-edit-buffer
23271 (comment-or-uncomment-region (point) (+ offset (point))))))
23272 (save-restriction
23273 ;; Restrict region
23274 (narrow-to-region (save-excursion (goto-char beg)
23275 (skip-chars-forward " \r\t\n" end)
23276 (line-beginning-position))
23277 (save-excursion (goto-char end)
23278 (skip-chars-backward " \r\t\n" beg)
23279 (line-end-position)))
23280 (let ((uncommentp
23281 ;; UNCOMMENTP is non-nil when every non blank line between
23282 ;; BEG and END is a comment.
23283 (save-excursion
23284 (goto-char (point-min))
23285 (while (and (not (eobp))
23286 (let ((element (org-element-at-point)))
23287 (and (eq (org-element-type element) 'comment)
23288 (goto-char (min (point-max)
23289 (org-element-property
23290 :end element)))))))
23291 (eobp))))
23292 (if uncommentp
23293 ;; Only blank lines and comments in region: uncomment it.
23294 (save-excursion
23295 (goto-char (point-min))
23296 (while (not (eobp))
23297 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23298 (replace-match "" nil nil nil 1))
23299 (forward-line)))
23300 ;; Comment each line in region.
23301 (let ((min-indent (point-max)))
23302 ;; First find the minimum indentation across all lines.
23303 (save-excursion
23304 (goto-char (point-min))
23305 (while (and (not (eobp)) (not (zerop min-indent)))
23306 (unless (looking-at "[ \t]*$")
23307 (setq min-indent (min min-indent (current-indentation))))
23308 (forward-line)))
23309 ;; Then loop over all lines.
23310 (save-excursion
23311 (goto-char (point-min))
23312 (while (not (eobp))
23313 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23314 ;; Don't get fooled by invisible text (e.g. link path)
23315 ;; when moving to column MIN-INDENT.
23316 (let ((buffer-invisibility-spec nil))
23317 (org-move-to-column min-indent t))
23318 (insert comment-start))
23319 (forward-line)))))))))
23321 (defun org-comment-dwim (_arg)
23322 "Call `comment-dwim' within a source edit buffer if needed."
23323 (interactive "*P")
23324 (if (org-in-src-block-p)
23325 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23326 (call-interactively 'comment-dwim)))
23329 ;;; Timestamps API
23331 ;; This section contains tools to operate on timestamp objects, as
23332 ;; returned by, e.g. `org-element-context'.
23334 (defun org-timestamp--to-internal-time (timestamp &optional end)
23335 "Encode TIMESTAMP object into Emacs internal time.
23336 Use end of date range or time range when END is non-nil."
23337 (apply #'encode-time
23338 (cons 0
23339 (mapcar
23340 (lambda (prop) (or (org-element-property prop timestamp) 0))
23341 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23342 '(:minute-start :hour-start :day-start :month-start
23343 :year-start))))))
23345 (defun org-timestamp-has-time-p (timestamp)
23346 "Non-nil when TIMESTAMP has a time specified."
23347 (org-element-property :hour-start timestamp))
23349 (defun org-timestamp-format (timestamp format &optional end utc)
23350 "Format a TIMESTAMP object into a string.
23352 FORMAT is a format specifier to be passed to
23353 `format-time-string'.
23355 When optional argument END is non-nil, use end of date-range or
23356 time-range, if possible.
23358 When optional argument UTC is non-nil, time will be expressed as
23359 Universal Time."
23360 (format-time-string
23361 format (org-timestamp--to-internal-time timestamp end)
23362 (and utc t)))
23364 (defun org-timestamp-split-range (timestamp &optional end)
23365 "Extract a TIMESTAMP object from a date or time range.
23367 END, when non-nil, means extract the end of the range.
23368 Otherwise, extract its start.
23370 Return a new timestamp object."
23371 (let ((type (org-element-property :type timestamp)))
23372 (if (memq type '(active inactive diary)) timestamp
23373 (let ((split-ts (org-element-copy timestamp)))
23374 ;; Set new type.
23375 (org-element-put-property
23376 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23377 ;; Copy start properties over end properties if END is
23378 ;; non-nil. Otherwise, copy end properties over `start' ones.
23379 (let ((p-alist '((:minute-start . :minute-end)
23380 (:hour-start . :hour-end)
23381 (:day-start . :day-end)
23382 (:month-start . :month-end)
23383 (:year-start . :year-end))))
23384 (dolist (p-cell p-alist)
23385 (org-element-put-property
23386 split-ts
23387 (funcall (if end #'car #'cdr) p-cell)
23388 (org-element-property
23389 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23390 ;; Eventually refresh `:raw-value'.
23391 (org-element-put-property split-ts :raw-value nil)
23392 (org-element-put-property
23393 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23395 (defun org-timestamp-translate (timestamp &optional boundary)
23396 "Translate TIMESTAMP object to custom format.
23398 Format string is defined in `org-time-stamp-custom-formats',
23399 which see.
23401 When optional argument BOUNDARY is non-nil, it is either the
23402 symbol `start' or `end'. In this case, only translate the
23403 starting or ending part of TIMESTAMP if it is a date or time
23404 range. Otherwise, translate both parts.
23406 Return timestamp as-is if `org-display-custom-times' is nil or if
23407 it has a `diary' type."
23408 (let ((type (org-element-property :type timestamp)))
23409 (if (or (not org-display-custom-times) (eq type 'diary))
23410 (org-element-interpret-data timestamp)
23411 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23412 org-time-stamp-custom-formats)))
23413 (if (and (not boundary) (memq type '(active-range inactive-range)))
23414 (concat (org-timestamp-format timestamp fmt)
23415 "--"
23416 (org-timestamp-format timestamp fmt t))
23417 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23421 ;;; Other stuff.
23423 (defvar reftex-docstruct-symbol)
23424 (defvar org--rds)
23426 (defun org-reftex-citation ()
23427 "Use reftex-citation to insert a citation into the buffer.
23428 This looks for a line like
23430 #+BIBLIOGRAPHY: foo plain option:-d
23432 and derives from it that foo.bib is the bibliography file relevant
23433 for this document. It then installs the necessary environment for RefTeX
23434 to work in this buffer and calls `reftex-citation' to insert a citation
23435 into the buffer.
23437 Export of such citations to both LaTeX and HTML is handled by the contributed
23438 package ox-bibtex by Taru Karttunen."
23439 (interactive)
23440 (let ((reftex-docstruct-symbol 'org--rds)
23441 org--rds bib)
23442 (org-with-wide-buffer
23443 (let ((case-fold-search t)
23444 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23445 (if (not (save-excursion
23446 (or (re-search-forward re nil t)
23447 (re-search-backward re nil t))))
23448 (user-error "No bibliography defined in file")
23449 (setq bib (concat (match-string 1) ".bib")
23450 org--rds (list (list 'bib bib))))))
23451 (call-interactively 'reftex-citation)))
23453 ;;;; Functions extending outline functionality
23455 (defun org-beginning-of-line (&optional n)
23456 "Go to the beginning of the current visible line.
23458 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23459 tags on the first attempt, and only move to after the tags when
23460 the cursor is already beyond the end of the headline.
23462 With argument N not nil or 1, move forward N - 1 lines first."
23463 (interactive "^p")
23464 (let ((origin (point))
23465 (special (pcase org-special-ctrl-a/e
23466 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23467 deactivate-mark)
23468 ;; First move to a visible line.
23469 (if (bound-and-true-p visual-line-mode)
23470 (beginning-of-visual-line n)
23471 (move-beginning-of-line n)
23472 ;; `move-beginning-of-line' may leave point after invisible
23473 ;; characters if line starts with such of these (e.g., with
23474 ;; a link at column 0). Really move to the beginning of the
23475 ;; current visible line.
23476 (beginning-of-line))
23477 (cond
23478 ;; No special behavior. Point is already at the beginning of
23479 ;; a line, logical or visual.
23480 ((not special))
23481 ;; `beginning-of-visual-line' left point before logical beginning
23482 ;; of line: point is at the beginning of a visual line. Bail
23483 ;; out.
23484 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23485 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23486 ;; At a headline, special position is before the title, but
23487 ;; after any TODO keyword or priority cookie.
23488 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23489 (line-end-position)))
23490 (bol (point)))
23491 (if (eq special 'reversed)
23492 (when (and (= origin bol) (eq last-command this-command))
23493 (goto-char refpos))
23494 (when (or (> origin refpos) (= origin bol))
23495 (goto-char refpos)))))
23496 ((and (looking-at org-list-full-item-re)
23497 (memq (org-element-type (save-match-data (org-element-at-point)))
23498 '(item plain-list)))
23499 ;; Set special position at first white space character after
23500 ;; bullet, and check-box, if any.
23501 (let ((after-bullet
23502 (let ((box (match-end 3)))
23503 (cond ((not box) (match-end 1))
23504 ((eq (char-after box) ?\s) (1+ box))
23505 (t box)))))
23506 (if (eq special 'reversed)
23507 (when (and (= (point) origin) (eq last-command this-command))
23508 (goto-char after-bullet))
23509 (when (or (> origin after-bullet) (= (point) origin))
23510 (goto-char after-bullet)))))
23511 ;; No special context. Point is already at beginning of line.
23512 (t nil))))
23514 (defun org-end-of-line (&optional n)
23515 "Go to the end of the line, but before ellipsis, if any.
23517 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23518 tags on the first attempt, and only move to after the tags when
23519 the cursor is already beyond the end of the headline.
23521 With argument N not nil or 1, move forward N - 1 lines first."
23522 (interactive "^p")
23523 (let ((origin (point))
23524 (special (pcase org-special-ctrl-a/e
23525 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23526 deactivate-mark)
23527 ;; First move to a visible line.
23528 (if (bound-and-true-p visual-line-mode)
23529 (beginning-of-visual-line n)
23530 (move-beginning-of-line n))
23531 (cond
23532 ;; At a headline, with tags.
23533 ((and special
23534 (save-excursion
23535 (beginning-of-line)
23536 (let ((case-fold-search nil))
23537 (looking-at org-complex-heading-regexp)))
23538 (match-end 5))
23539 (let ((tags (save-excursion
23540 (goto-char (match-beginning 5))
23541 (skip-chars-backward " \t")
23542 (point)))
23543 (visual-end (and (bound-and-true-p visual-line-mode)
23544 (save-excursion
23545 (end-of-visual-line)
23546 (point)))))
23547 ;; If `end-of-visual-line' brings us before end of line or
23548 ;; even tags, i.e., the headline spans over multiple visual
23549 ;; lines, move there.
23550 (cond ((and visual-end
23551 (< visual-end tags)
23552 (<= origin visual-end))
23553 (goto-char visual-end))
23554 ((eq special 'reversed)
23555 (if (and (= origin (line-end-position))
23556 (eq this-command last-command))
23557 (goto-char tags)
23558 (end-of-line)))
23560 (if (or (< origin tags) (= origin (line-end-position)))
23561 (goto-char tags)
23562 (end-of-line))))))
23563 ((bound-and-true-p visual-line-mode)
23564 (let ((bol (line-beginning-position)))
23565 (end-of-visual-line)
23566 ;; If `end-of-visual-line' gets us past the ellipsis at the
23567 ;; end of a line, backtrack and use `end-of-line' instead.
23568 (when (/= bol (line-beginning-position))
23569 (goto-char bol)
23570 (end-of-line))))
23571 (t (end-of-line)))))
23573 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23574 (define-key org-mode-map "\C-e" 'org-end-of-line)
23576 (defun org-backward-sentence (&optional _arg)
23577 "Go to beginning of sentence, or beginning of table field.
23578 This will call `backward-sentence' or `org-table-beginning-of-field',
23579 depending on context."
23580 (interactive)
23581 (let* ((element (org-element-at-point))
23582 (contents-begin (org-element-property :contents-begin element))
23583 (table (org-element-lineage element '(table) t)))
23584 (if (and table
23585 (> (point) contents-begin)
23586 (<= (point) (org-element-property :contents-end table)))
23587 (call-interactively #'org-table-beginning-of-field)
23588 (save-restriction
23589 (when (and contents-begin
23590 (< (point-min) contents-begin)
23591 (> (point) contents-begin))
23592 (narrow-to-region contents-begin
23593 (org-element-property :contents-end element)))
23594 (call-interactively #'backward-sentence)))))
23596 (defun org-forward-sentence (&optional _arg)
23597 "Go to end of sentence, or end of table field.
23598 This will call `forward-sentence' or `org-table-end-of-field',
23599 depending on context."
23600 (interactive)
23601 (let* ((element (org-element-at-point))
23602 (contents-end (org-element-property :contents-end element))
23603 (table (org-element-lineage element '(table) t)))
23604 (if (and table
23605 (>= (point) (org-element-property :contents-begin table))
23606 (< (point) contents-end))
23607 (call-interactively #'org-table-end-of-field)
23608 (save-restriction
23609 (when (and contents-end
23610 (> (point-max) contents-end)
23611 ;; Skip blank lines between elements.
23612 (< (org-element-property :end element)
23613 (save-excursion (goto-char contents-end)
23614 (skip-chars-forward " \r\t\n"))))
23615 (narrow-to-region (org-element-property :contents-begin element)
23616 contents-end))
23617 (call-interactively #'forward-sentence)))))
23619 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23620 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23622 (defun org-kill-line (&optional _arg)
23623 "Kill line, to tags or end of line."
23624 (interactive)
23625 (cond
23626 ((or (not org-special-ctrl-k)
23627 (bolp)
23628 (not (org-at-heading-p)))
23629 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23630 org-ctrl-k-protect-subtree
23631 (or (eq org-ctrl-k-protect-subtree 'error)
23632 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23633 (user-error "C-k aborted as it would kill a hidden subtree"))
23634 (call-interactively
23635 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23636 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23637 (kill-region (point) (match-beginning 1))
23638 (org-set-tags nil t))
23639 (t (kill-region (point) (point-at-eol)))))
23641 (define-key org-mode-map "\C-k" 'org-kill-line)
23643 (defun org-yank (&optional arg)
23644 "Yank. If the kill is a subtree, treat it specially.
23645 This command will look at the current kill and check if is a single
23646 subtree, or a series of subtrees[1]. If it passes the test, and if the
23647 cursor is at the beginning of a line or after the stars of a currently
23648 empty headline, then the yank is handled specially. How exactly depends
23649 on the value of the following variables.
23651 `org-yank-folded-subtrees'
23652 By default, this variable is non-nil, which results in
23653 subtree(s) being folded after insertion, except if doing so
23654 would swallow text after the yanked text.
23656 `org-yank-adjusted-subtrees'
23657 When non-nil (the default value is nil), the subtree will be
23658 promoted or demoted in order to fit into the local outline tree
23659 structure, which means that the level will be adjusted so that it
23660 becomes the smaller one of the two *visible* surrounding headings.
23662 Any prefix to this command will cause `yank' to be called directly with
23663 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23664 will just
23665 plainly yank the text as it is.
23667 \[1] The test checks if the first non-white line is a heading
23668 and if there are no other headings with fewer stars."
23669 (interactive "P")
23670 (org-yank-generic 'yank arg))
23672 (defun org-yank-generic (command arg)
23673 "Perform some yank-like command.
23675 This function implements the behavior described in the `org-yank'
23676 documentation. However, it has been generalized to work for any
23677 interactive command with similar behavior."
23679 ;; pretend to be command COMMAND
23680 (setq this-command command)
23682 (if arg
23683 (call-interactively command)
23685 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23686 (and (org-kill-is-subtree-p)
23687 (or (bolp)
23688 (and (looking-at "[ \t]*$")
23689 (string-match
23690 "\\`\\*+\\'"
23691 (buffer-substring (point-at-bol) (point)))))))
23692 swallowp)
23693 (cond
23694 ((and subtreep org-yank-folded-subtrees)
23695 (let ((beg (point))
23696 end)
23697 (if (and subtreep org-yank-adjusted-subtrees)
23698 (org-paste-subtree nil nil 'for-yank)
23699 (call-interactively command))
23701 (setq end (point))
23702 (goto-char beg)
23703 (when (and (bolp) subtreep
23704 (not (setq swallowp
23705 (org-yank-folding-would-swallow-text beg end))))
23706 (org-with-limited-levels
23707 (or (looking-at org-outline-regexp)
23708 (re-search-forward org-outline-regexp-bol end t))
23709 (while (and (< (point) end) (looking-at org-outline-regexp))
23710 (outline-hide-subtree)
23711 (org-cycle-show-empty-lines 'folded)
23712 (condition-case nil
23713 (outline-forward-same-level 1)
23714 (error (goto-char end))))))
23715 (when swallowp
23716 (message
23717 "Inserted text not folded because that would swallow text"))
23719 (goto-char end)
23720 (skip-chars-forward " \t\n\r")
23721 (beginning-of-line 1)
23722 (push-mark beg 'nomsg)))
23723 ((and subtreep org-yank-adjusted-subtrees)
23724 (let ((beg (point-at-bol)))
23725 (org-paste-subtree nil nil 'for-yank)
23726 (push-mark beg 'nomsg)))
23728 (call-interactively command))))))
23730 (defun org-yank-folding-would-swallow-text (beg end)
23731 "Would hide-subtree at BEG swallow any text after END?"
23732 (let (level)
23733 (org-with-limited-levels
23734 (save-excursion
23735 (goto-char beg)
23736 (when (or (looking-at org-outline-regexp)
23737 (re-search-forward org-outline-regexp-bol end t))
23738 (setq level (org-outline-level)))
23739 (goto-char end)
23740 (skip-chars-forward " \t\r\n\v\f")
23741 (not (or (eobp)
23742 (and (bolp) (looking-at-p org-outline-regexp)
23743 (<= (org-outline-level) level))))))))
23745 (define-key org-mode-map "\C-y" 'org-yank)
23747 (defun org-truely-invisible-p ()
23748 "Check if point is at a character currently not visible.
23749 This version does not only check the character property, but also
23750 `visible-mode'."
23751 (unless (bound-and-true-p visible-mode)
23752 (org-invisible-p)))
23754 (defun org-invisible-p2 ()
23755 "Check if point is at a character currently not visible.
23757 If the point is at EOL (and not at the beginning of a buffer too),
23758 move it back by one char before doing this check."
23759 (save-excursion
23760 (when (and (eolp) (not (bobp)))
23761 (backward-char 1))
23762 (org-invisible-p)))
23764 (defun org-back-to-heading (&optional invisible-ok)
23765 "Call `outline-back-to-heading', but provide a better error message."
23766 (condition-case nil
23767 (outline-back-to-heading invisible-ok)
23768 (error (error "Before first headline at position %d in buffer %s"
23769 (point) (current-buffer)))))
23771 (defun org-before-first-heading-p ()
23772 "Before first heading?"
23773 (save-excursion
23774 (end-of-line)
23775 (null (re-search-backward org-outline-regexp-bol nil t))))
23777 (defun org-at-heading-p (&optional ignored)
23778 (outline-on-heading-p t))
23780 (defun org-in-commented-heading-p (&optional no-inheritance)
23781 "Non-nil if point is under a commented heading.
23782 This function also checks ancestors of the current headline,
23783 unless optional argument NO-INHERITANCE is non-nil."
23784 (cond
23785 ((org-before-first-heading-p) nil)
23786 ((let ((headline (nth 4 (org-heading-components))))
23787 (and headline
23788 (let ((case-fold-search nil))
23789 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23790 headline)))))
23791 (no-inheritance nil)
23793 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23795 (defun org-at-comment-p nil
23796 "Is cursor in a commented line?"
23797 (save-excursion
23798 (save-match-data
23799 (beginning-of-line)
23800 (looking-at "^[ \t]*# "))))
23802 (defun org-at-drawer-p nil
23803 "Is cursor at a drawer keyword?"
23804 (save-excursion
23805 (move-beginning-of-line 1)
23806 (looking-at org-drawer-regexp)))
23808 (defun org-at-block-p nil
23809 "Is cursor at a block keyword?"
23810 (save-excursion
23811 (move-beginning-of-line 1)
23812 (looking-at org-block-regexp)))
23814 (defun org-point-at-end-of-empty-headline ()
23815 "If point is at the end of an empty headline, return t, else nil.
23816 If the heading only contains a TODO keyword, it is still still considered
23817 empty."
23818 (let ((case-fold-search nil))
23819 (and (looking-at "[ \t]*$")
23820 org-todo-line-regexp
23821 (save-excursion
23822 (beginning-of-line)
23823 (looking-at org-todo-line-regexp)
23824 (string= (match-string 3) "")))))
23826 (defun org-at-heading-or-item-p ()
23827 (or (org-at-heading-p) (org-at-item-p)))
23829 (defun org-at-target-p ()
23830 (or (org-in-regexp org-radio-target-regexp)
23831 (org-in-regexp org-target-regexp)))
23832 ;; Compatibility alias with Org versions < 7.8.03
23833 (defalias 'org-on-target-p 'org-at-target-p)
23835 (defun org-up-heading-all (arg)
23836 "Move to the heading line of which the present line is a subheading.
23837 This function considers both visible and invisible heading lines.
23838 With argument, move up ARG levels."
23839 (outline-up-heading arg t))
23841 (defun org-up-heading-safe ()
23842 "Move to the heading line of which the present line is a subheading.
23843 This version will not throw an error. It will return the level of the
23844 headline found, or nil if no higher level is found.
23846 Also, this function will be a lot faster than `outline-up-heading',
23847 because it relies on stars being the outline starters. This can really
23848 make a significant difference in outlines with very many siblings."
23849 (when (ignore-errors (org-back-to-heading t))
23850 (let ((level-up (1- (funcall outline-level))))
23851 (and (> level-up 0)
23852 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23853 (funcall outline-level)))))
23855 (defun org-first-sibling-p ()
23856 "Is this heading the first child of its parents?"
23857 (interactive)
23858 (let ((re org-outline-regexp-bol)
23859 level l)
23860 (unless (org-at-heading-p t)
23861 (user-error "Not at a heading"))
23862 (setq level (funcall outline-level))
23863 (save-excursion
23864 (if (not (re-search-backward re nil t))
23866 (setq l (funcall outline-level))
23867 (< l level)))))
23869 (defun org-goto-sibling (&optional previous)
23870 "Goto the next sibling, even if it is invisible.
23871 When PREVIOUS is set, go to the previous sibling instead. Returns t
23872 when a sibling was found. When none is found, return nil and don't
23873 move point."
23874 (let ((fun (if previous 're-search-backward 're-search-forward))
23875 (pos (point))
23876 (re org-outline-regexp-bol)
23877 level l)
23878 (when (ignore-errors (org-back-to-heading t))
23879 (setq level (funcall outline-level))
23880 (catch 'exit
23881 (or previous (forward-char 1))
23882 (while (funcall fun re nil t)
23883 (setq l (funcall outline-level))
23884 (when (< l level) (goto-char pos) (throw 'exit nil))
23885 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23886 (goto-char pos)
23887 nil))))
23889 (defun org-show-siblings ()
23890 "Show all siblings of the current headline."
23891 (save-excursion
23892 (while (org-goto-sibling) (org-flag-heading nil)))
23893 (save-excursion
23894 (while (org-goto-sibling 'previous)
23895 (org-flag-heading nil))))
23897 (defun org-goto-first-child ()
23898 "Goto the first child, even if it is invisible.
23899 Return t when a child was found. Otherwise don't move point and
23900 return nil."
23901 (let (level (pos (point)) (re org-outline-regexp-bol))
23902 (when (ignore-errors (org-back-to-heading t))
23903 (setq level (outline-level))
23904 (forward-char 1)
23905 (if (and (re-search-forward re nil t) (> (outline-level) level))
23906 (progn (goto-char (match-beginning 0)) t)
23907 (goto-char pos) nil))))
23909 (defun org-show-hidden-entry ()
23910 "Show an entry where even the heading is hidden."
23911 (save-excursion
23912 (org-show-entry)))
23914 (defun org-flag-heading (flag &optional entry)
23915 "Flag the current heading. FLAG non-nil means make invisible.
23916 When ENTRY is non-nil, show the entire entry."
23917 (save-excursion
23918 (org-back-to-heading t)
23919 ;; Check if we should show the entire entry
23920 (if entry
23921 (progn
23922 (org-show-entry)
23923 (save-excursion
23924 (and (outline-next-heading)
23925 (org-flag-heading nil))))
23926 (outline-flag-region (max (point-min) (1- (point)))
23927 (save-excursion (outline-end-of-heading) (point))
23928 flag))))
23930 (defun org-get-next-sibling ()
23931 "Move to next heading of the same level, and return point.
23932 If there is no such heading, return nil.
23933 This is like outline-next-sibling, but invisible headings are ok."
23934 (let ((level (funcall outline-level)))
23935 (outline-next-heading)
23936 (while (and (not (eobp)) (> (funcall outline-level) level))
23937 (outline-next-heading))
23938 (unless (or (eobp) (< (funcall outline-level) level))
23939 (point))))
23941 (defun org-get-last-sibling ()
23942 "Move to previous heading of the same level, and return point.
23943 If there is no such heading, return nil."
23944 (let ((opoint (point))
23945 (level (funcall outline-level)))
23946 (outline-previous-heading)
23947 (when (and (/= (point) opoint) (outline-on-heading-p t))
23948 (while (and (> (funcall outline-level) level)
23949 (not (bobp)))
23950 (outline-previous-heading))
23951 (unless (< (funcall outline-level) level)
23952 (point)))))
23954 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23955 "Goto to the end of a subtree."
23956 ;; This contains an exact copy of the original function, but it uses
23957 ;; `org-back-to-heading', to make it work also in invisible
23958 ;; trees. And is uses an invisible-ok argument.
23959 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23960 ;; Furthermore, when used inside Org, finding the end of a large subtree
23961 ;; with many children and grandchildren etc, this can be much faster
23962 ;; than the outline version.
23963 (org-back-to-heading invisible-ok)
23964 (let ((first t)
23965 (level (funcall outline-level)))
23966 (if (and (derived-mode-p 'org-mode) (< level 1000))
23967 ;; A true heading (not a plain list item), in Org
23968 ;; This means we can easily find the end by looking
23969 ;; only for the right number of stars. Using a regexp to do
23970 ;; this is so much faster than using a Lisp loop.
23971 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23972 (forward-char 1)
23973 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23974 ;; something else, do it the slow way
23975 (while (and (not (eobp))
23976 (or first (> (funcall outline-level) level)))
23977 (setq first nil)
23978 (outline-next-heading)))
23979 (unless to-heading
23980 (when (memq (preceding-char) '(?\n ?\^M))
23981 ;; Go to end of line before heading
23982 (forward-char -1)
23983 (when (memq (preceding-char) '(?\n ?\^M))
23984 ;; leave blank line before heading
23985 (forward-char -1)))))
23986 (point))
23988 (defun org-end-of-meta-data (&optional full)
23989 "Skip planning line and properties drawer in current entry.
23990 When optional argument FULL is non-nil, also skip empty lines,
23991 clocking lines and regular drawers at the beginning of the
23992 entry."
23993 (org-back-to-heading t)
23994 (forward-line)
23995 (when (looking-at-p org-planning-line-re) (forward-line))
23996 (when (looking-at org-property-drawer-re)
23997 (goto-char (match-end 0))
23998 (forward-line))
23999 (when (and full (not (org-at-heading-p)))
24000 (catch 'exit
24001 (let ((end (save-excursion (outline-next-heading) (point)))
24002 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24003 (while (not (eobp))
24004 (cond ((looking-at-p org-drawer-regexp)
24005 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24006 (forward-line)
24007 (throw 'exit t)))
24008 ((looking-at-p re) (forward-line))
24009 (t (throw 'exit t))))))))
24011 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24012 "Move forward to the ARG'th subheading at same level as this one.
24013 Stop at the first and last subheadings of a superior heading.
24014 Normally this only looks at visible headings, but when INVISIBLE-OK is
24015 non-nil it will also look at invisible ones."
24016 (interactive "p")
24017 (let ((backward? (and arg (< arg 0))))
24018 (if (org-before-first-heading-p)
24019 (if backward? (goto-char (point-min)) (outline-next-heading))
24020 (org-back-to-heading invisible-ok)
24021 (unless backward? (end-of-line)) ;do not match current headline
24022 (let ((level (- (match-end 0) (match-beginning 0) 1))
24023 (f (if backward? #'re-search-backward #'re-search-forward))
24024 (count (if arg (abs arg) 1))
24025 (result (point)))
24026 (while (and (> count 0)
24027 (funcall f org-outline-regexp-bol nil 'move))
24028 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24029 (cond ((< l level) (setq count 0))
24030 ((and (= l level)
24031 (or invisible-ok
24032 (not (org-invisible-p
24033 (line-beginning-position)))))
24034 (cl-decf count)
24035 (when (= l level) (setq result (point)))))))
24036 (goto-char result))
24037 (beginning-of-line))))
24039 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24040 "Move backward to the ARG'th subheading at same level as this one.
24041 Stop at the first and last subheadings of a superior heading."
24042 (interactive "p")
24043 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24045 (defun org-next-visible-heading (arg)
24046 "Move to the next visible heading.
24048 This function wraps `outline-next-visible-heading' with
24049 `org-with-limited-levels' in order to skip over inline tasks and
24050 respect customization of `org-odd-levels-only'."
24051 (interactive "p")
24052 (org-with-limited-levels
24053 (outline-next-visible-heading arg)))
24055 (defun org-previous-visible-heading (arg)
24056 "Move to the previous visible heading.
24058 This function wraps `outline-previous-visible-heading' with
24059 `org-with-limited-levels' in order to skip over inline tasks and
24060 respect customization of `org-odd-levels-only'."
24061 (interactive "p")
24062 (org-with-limited-levels
24063 (outline-previous-visible-heading arg)))
24065 (defun org-next-block (arg &optional backward block-regexp)
24066 "Jump to the next block.
24068 With a prefix argument ARG, jump forward ARG many blocks.
24070 When BACKWARD is non-nil, jump to the previous block.
24072 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24073 Match data is set according to this regexp when the function
24074 returns.
24076 Return point at beginning of the opening line of found block.
24077 Throw an error if no block is found."
24078 (interactive "p")
24079 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24080 (case-fold-search t)
24081 (search-fn (if backward #'re-search-backward #'re-search-forward))
24082 (count (or arg 1))
24083 (origin (point))
24084 last-element)
24085 (if backward (beginning-of-line) (end-of-line))
24086 (while (and (> count 0) (funcall search-fn re nil t))
24087 (let ((element (save-excursion
24088 (goto-char (match-beginning 0))
24089 (save-match-data (org-element-at-point)))))
24090 (when (and (memq (org-element-type element)
24091 '(center-block comment-block dynamic-block
24092 example-block export-block quote-block
24093 special-block src-block verse-block))
24094 (<= (match-beginning 0)
24095 (org-element-property :post-affiliated element)))
24096 (setq last-element element)
24097 (cl-decf count))))
24098 (if (= count 0)
24099 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24100 (save-match-data (org-show-context)))
24101 (goto-char origin)
24102 (user-error "No %s code blocks" (if backward "previous" "further")))))
24104 (defun org-previous-block (arg &optional block-regexp)
24105 "Jump to the previous block.
24106 With a prefix argument ARG, jump backward ARG many source blocks.
24107 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24108 (interactive "p")
24109 (org-next-block arg t block-regexp))
24111 (defun org-forward-paragraph ()
24112 "Move forward to beginning of next paragraph or equivalent.
24114 The function moves point to the beginning of the next visible
24115 structural element, which can be a paragraph, a table, a list
24116 item, etc. It also provides some special moves for convenience:
24118 - On an affiliated keyword, jump to the beginning of the
24119 relative element.
24120 - On an item or a footnote definition, move to the second
24121 element inside, if any.
24122 - On a table or a property drawer, jump after it.
24123 - On a verse or source block, stop after blank lines."
24124 (interactive)
24125 (unless (eobp)
24126 (let* ((deactivate-mark nil)
24127 (element (org-element-at-point))
24128 (type (org-element-type element))
24129 (post-affiliated (org-element-property :post-affiliated element))
24130 (contents-begin (org-element-property :contents-begin element))
24131 (contents-end (org-element-property :contents-end element))
24132 (end (let ((end (org-element-property :end element)) (parent element))
24133 (while (and (setq parent (org-element-property :parent parent))
24134 (= (org-element-property :contents-end parent) end))
24135 (setq end (org-element-property :end parent)))
24136 end)))
24137 (cond ((not element)
24138 (skip-chars-forward " \r\t\n")
24139 (or (eobp) (beginning-of-line)))
24140 ;; On affiliated keywords, move to element's beginning.
24141 ((< (point) post-affiliated)
24142 (goto-char post-affiliated))
24143 ;; At a table row, move to the end of the table. Similarly,
24144 ;; at a node property, move to the end of the property
24145 ;; drawer.
24146 ((memq type '(node-property table-row))
24147 (goto-char (org-element-property
24148 :end (org-element-property :parent element))))
24149 ((memq type '(property-drawer table)) (goto-char end))
24150 ;; Consider blank lines as separators in verse and source
24151 ;; blocks to ease editing.
24152 ((memq type '(src-block verse-block))
24153 (when (eq type 'src-block)
24154 (setq contents-end
24155 (save-excursion (goto-char end)
24156 (skip-chars-backward " \r\t\n")
24157 (line-beginning-position))))
24158 (beginning-of-line)
24159 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24160 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24161 (goto-char end)
24162 (skip-chars-forward " \r\t\n")
24163 (if (= (point) contents-end) (goto-char end)
24164 (beginning-of-line))))
24165 ;; With no contents, just skip element.
24166 ((not contents-begin) (goto-char end))
24167 ;; If contents are invisible, skip the element altogether.
24168 ((org-invisible-p (line-end-position))
24169 (cl-case type
24170 (headline
24171 (org-with-limited-levels (outline-next-visible-heading 1)))
24172 ;; At a plain list, make sure we move to the next item
24173 ;; instead of skipping the whole list.
24174 (plain-list (forward-char)
24175 (org-forward-paragraph))
24176 (otherwise (goto-char end))))
24177 ((>= (point) contents-end) (goto-char end))
24178 ((>= (point) contents-begin)
24179 ;; This can only happen on paragraphs and plain lists.
24180 (cl-case type
24181 (paragraph (goto-char end))
24182 ;; At a plain list, try to move to second element in
24183 ;; first item, if possible.
24184 (plain-list (end-of-line)
24185 (org-forward-paragraph))))
24186 ;; When contents start on the middle of a line (e.g. in
24187 ;; items and footnote definitions), try to reach first
24188 ;; element starting after current line.
24189 ((> (line-end-position) contents-begin)
24190 (end-of-line)
24191 (org-forward-paragraph))
24192 (t (goto-char contents-begin))))))
24194 (defun org-backward-paragraph ()
24195 "Move backward to start of previous paragraph or equivalent.
24197 The function moves point to the beginning of the current
24198 structural element, which can be a paragraph, a table, a list
24199 item, etc., or to the beginning of the previous visible one if
24200 point is already there. It also provides some special moves for
24201 convenience:
24203 - On an affiliated keyword, jump to the first one.
24204 - On a table or a property drawer, move to its beginning.
24205 - On a verse or source block, stop before blank lines."
24206 (interactive)
24207 (unless (bobp)
24208 (let* ((deactivate-mark nil)
24209 (element (org-element-at-point))
24210 (type (org-element-type element))
24211 (contents-begin (org-element-property :contents-begin element))
24212 (contents-end (org-element-property :contents-end element))
24213 (post-affiliated (org-element-property :post-affiliated element))
24214 (begin (org-element-property :begin element)))
24215 (cond
24216 ((not element) (goto-char (point-min)))
24217 ((= (point) begin)
24218 (backward-char)
24219 (org-backward-paragraph))
24220 ((<= (point) post-affiliated) (goto-char begin))
24221 ((memq type '(node-property table-row))
24222 (goto-char (org-element-property
24223 :post-affiliated (org-element-property :parent element))))
24224 ((memq type '(property-drawer table)) (goto-char begin))
24225 ((memq type '(src-block verse-block))
24226 (when (eq type 'src-block)
24227 (setq contents-begin
24228 (save-excursion (goto-char begin) (forward-line) (point))))
24229 (if (= (point) contents-begin) (goto-char post-affiliated)
24230 ;; Inside a verse block, see blank lines as paragraph
24231 ;; separators.
24232 (let ((origin (point)))
24233 (skip-chars-backward " \r\t\n" contents-begin)
24234 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24235 (skip-chars-forward " \r\t\n" origin)
24236 (if (= (point) origin) (goto-char contents-begin)
24237 (beginning-of-line))))))
24238 ((not contents-begin) (goto-char (or post-affiliated begin)))
24239 ((eq type 'paragraph)
24240 (goto-char contents-begin)
24241 ;; When at first paragraph in an item or a footnote definition,
24242 ;; move directly to beginning of line.
24243 (let ((parent-contents
24244 (org-element-property
24245 :contents-begin (org-element-property :parent element))))
24246 (when (and parent-contents (= parent-contents contents-begin))
24247 (beginning-of-line))))
24248 ;; At the end of a greater element, move to the beginning of the
24249 ;; last element within.
24250 ((>= (point) contents-end)
24251 (goto-char (1- contents-end))
24252 (org-backward-paragraph))
24253 (t (goto-char (or post-affiliated begin))))
24254 ;; Ensure we never leave point invisible.
24255 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24257 (defun org-forward-element ()
24258 "Move forward by one element.
24259 Move to the next element at the same level, when possible."
24260 (interactive)
24261 (cond ((eobp) (user-error "Cannot move further down"))
24262 ((org-with-limited-levels (org-at-heading-p))
24263 (let ((origin (point)))
24264 (goto-char (org-end-of-subtree nil t))
24265 (unless (org-with-limited-levels (org-at-heading-p))
24266 (goto-char origin)
24267 (user-error "Cannot move further down"))))
24269 (let* ((elem (org-element-at-point))
24270 (end (org-element-property :end elem))
24271 (parent (org-element-property :parent elem)))
24272 (cond ((and parent (= (org-element-property :contents-end parent) end))
24273 (goto-char (org-element-property :end parent)))
24274 ((integer-or-marker-p end) (goto-char end))
24275 (t (message "No element at point")))))))
24277 (defun org-backward-element ()
24278 "Move backward by one element.
24279 Move to the previous element at the same level, when possible."
24280 (interactive)
24281 (cond ((bobp) (user-error "Cannot move further up"))
24282 ((org-with-limited-levels (org-at-heading-p))
24283 ;; At a headline, move to the previous one, if any, or stay
24284 ;; here.
24285 (let ((origin (point)))
24286 (org-with-limited-levels (org-backward-heading-same-level 1))
24287 ;; When current headline has no sibling above, move to its
24288 ;; parent.
24289 (when (= (point) origin)
24290 (or (org-with-limited-levels (org-up-heading-safe))
24291 (progn (goto-char origin)
24292 (user-error "Cannot move further up"))))))
24294 (let* ((elem (org-element-at-point))
24295 (beg (org-element-property :begin elem)))
24296 (cond
24297 ;; Move to beginning of current element if point isn't
24298 ;; there already.
24299 ((null beg) (message "No element at point"))
24300 ((/= (point) beg) (goto-char beg))
24301 (t (goto-char beg)
24302 (skip-chars-backward " \r\t\n")
24303 (unless (bobp)
24304 (let ((prev (org-element-at-point)))
24305 (goto-char (org-element-property :begin prev))
24306 (while (and (setq prev (org-element-property :parent prev))
24307 (<= (org-element-property :end prev) beg))
24308 (goto-char (org-element-property :begin prev)))))))))))
24310 (defun org-up-element ()
24311 "Move to upper element."
24312 (interactive)
24313 (if (org-with-limited-levels (org-at-heading-p))
24314 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24315 (let* ((elem (org-element-at-point))
24316 (parent (org-element-property :parent elem)))
24317 (if parent (goto-char (org-element-property :begin parent))
24318 (if (org-with-limited-levels (org-before-first-heading-p))
24319 (user-error "No surrounding element")
24320 (org-with-limited-levels (org-back-to-heading)))))))
24322 (defun org-down-element ()
24323 "Move to inner element."
24324 (interactive)
24325 (let ((element (org-element-at-point)))
24326 (cond
24327 ((memq (org-element-type element) '(plain-list table))
24328 (goto-char (org-element-property :contents-begin element))
24329 (forward-char))
24330 ((memq (org-element-type element) org-element-greater-elements)
24331 ;; If contents are hidden, first disclose them.
24332 (when (org-invisible-p (line-end-position)) (org-cycle))
24333 (goto-char (or (org-element-property :contents-begin element)
24334 (user-error "No content for this element"))))
24335 (t (user-error "No inner element")))))
24337 (defun org-drag-element-backward ()
24338 "Move backward element at point."
24339 (interactive)
24340 (let ((elem (or (org-element-at-point)
24341 (user-error "No element at point"))))
24342 (if (eq (org-element-type elem) 'headline)
24343 ;; Preserve point when moving a whole tree, even if point was
24344 ;; on blank lines below the headline.
24345 (let ((offset (skip-chars-backward " \t\n")))
24346 (unwind-protect (org-move-subtree-up)
24347 (forward-char (- offset))))
24348 (let ((prev-elem
24349 (save-excursion
24350 (goto-char (org-element-property :begin elem))
24351 (skip-chars-backward " \r\t\n")
24352 (unless (bobp)
24353 (let* ((beg (org-element-property :begin elem))
24354 (prev (org-element-at-point))
24355 (up prev))
24356 (while (and (setq up (org-element-property :parent up))
24357 (<= (org-element-property :end up) beg))
24358 (setq prev up))
24359 prev)))))
24360 ;; Error out if no previous element or previous element is
24361 ;; a parent of the current one.
24362 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24363 (user-error "Cannot drag element backward")
24364 (let ((pos (point)))
24365 (org-element-swap-A-B prev-elem elem)
24366 (goto-char (+ (org-element-property :begin prev-elem)
24367 (- pos (org-element-property :begin elem))))))))))
24369 (defun org-drag-element-forward ()
24370 "Move forward element at point."
24371 (interactive)
24372 (let* ((pos (point))
24373 (elem (or (org-element-at-point)
24374 (user-error "No element at point"))))
24375 (when (= (point-max) (org-element-property :end elem))
24376 (user-error "Cannot drag element forward"))
24377 (goto-char (org-element-property :end elem))
24378 (let ((next-elem (org-element-at-point)))
24379 (when (or (org-element-nested-p elem next-elem)
24380 (and (eq (org-element-type next-elem) 'headline)
24381 (not (eq (org-element-type elem) 'headline))))
24382 (goto-char pos)
24383 (user-error "Cannot drag element forward"))
24384 ;; Compute new position of point: it's shifted by NEXT-ELEM
24385 ;; body's length (without final blanks) and by the length of
24386 ;; blanks between ELEM and NEXT-ELEM.
24387 (let ((size-next (- (save-excursion
24388 (goto-char (org-element-property :end next-elem))
24389 (skip-chars-backward " \r\t\n")
24390 (forward-line)
24391 ;; Small correction if buffer doesn't end
24392 ;; with a newline character.
24393 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24394 (org-element-property :begin next-elem)))
24395 (size-blank (- (org-element-property :end elem)
24396 (save-excursion
24397 (goto-char (org-element-property :end elem))
24398 (skip-chars-backward " \r\t\n")
24399 (forward-line)
24400 (point)))))
24401 (org-element-swap-A-B elem next-elem)
24402 (goto-char (+ pos size-next size-blank))))))
24404 (defun org-drag-line-forward (arg)
24405 "Drag the line at point ARG lines forward."
24406 (interactive "p")
24407 (dotimes (_ (abs arg))
24408 (let ((c (current-column)))
24409 (if (< 0 arg)
24410 (progn
24411 (beginning-of-line 2)
24412 (transpose-lines 1)
24413 (beginning-of-line 0))
24414 (transpose-lines 1)
24415 (beginning-of-line -1))
24416 (org-move-to-column c))))
24418 (defun org-drag-line-backward (arg)
24419 "Drag the line at point ARG lines backward."
24420 (interactive "p")
24421 (org-drag-line-forward (- arg)))
24423 (defun org-mark-element ()
24424 "Put point at beginning of this element, mark at end.
24426 Interactively, if this command is repeated or (in Transient Mark
24427 mode) if the mark is active, it marks the next element after the
24428 ones already marked."
24429 (interactive)
24430 (let (deactivate-mark)
24431 (if (and (called-interactively-p 'any)
24432 (or (and (eq last-command this-command) (mark t))
24433 (and transient-mark-mode mark-active)))
24434 (set-mark
24435 (save-excursion
24436 (goto-char (mark))
24437 (goto-char (org-element-property :end (org-element-at-point)))))
24438 (let ((element (org-element-at-point)))
24439 (end-of-line)
24440 (push-mark (org-element-property :end element) t t)
24441 (goto-char (org-element-property :begin element))))))
24443 (defun org-narrow-to-element ()
24444 "Narrow buffer to current element."
24445 (interactive)
24446 (let ((elem (org-element-at-point)))
24447 (cond
24448 ((eq (car elem) 'headline)
24449 (narrow-to-region
24450 (org-element-property :begin elem)
24451 (org-element-property :end elem)))
24452 ((memq (car elem) org-element-greater-elements)
24453 (narrow-to-region
24454 (org-element-property :contents-begin elem)
24455 (org-element-property :contents-end elem)))
24457 (narrow-to-region
24458 (org-element-property :begin elem)
24459 (org-element-property :end elem))))))
24461 (defun org-transpose-element ()
24462 "Transpose current and previous elements, keeping blank lines between.
24463 Point is moved after both elements."
24464 (interactive)
24465 (org-skip-whitespace)
24466 (let ((end (org-element-property :end (org-element-at-point))))
24467 (org-drag-element-backward)
24468 (goto-char end)))
24470 (defun org-unindent-buffer ()
24471 "Un-indent the visible part of the buffer.
24472 Relative indentation (between items, inside blocks, etc.) isn't
24473 modified."
24474 (interactive)
24475 (unless (eq major-mode 'org-mode)
24476 (user-error "Cannot un-indent a buffer not in Org mode"))
24477 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24478 (unindent-tree
24479 (lambda (contents)
24480 (dolist (element (reverse contents))
24481 (if (memq (org-element-type element) '(headline section))
24482 (funcall unindent-tree (org-element-contents element))
24483 (save-excursion
24484 (save-restriction
24485 (narrow-to-region
24486 (org-element-property :begin element)
24487 (org-element-property :end element))
24488 (org-do-remove-indentation))))))))
24489 (funcall unindent-tree (org-element-contents parse-tree))))
24491 (defun org-show-children (&optional level)
24492 "Show all direct subheadings of this heading.
24493 Prefix arg LEVEL is how many levels below the current level
24494 should be shown. Default is enough to cause the following
24495 heading to appear."
24496 (interactive "p")
24497 ;; If `orgstruct-mode' is active, use the slower version.
24498 (if orgstruct-mode (call-interactively #'outline-show-children)
24499 (save-excursion
24500 (org-back-to-heading t)
24501 (let* ((current-level (funcall outline-level))
24502 (max-level (org-get-valid-level
24503 current-level
24504 (if level (prefix-numeric-value level) 1)))
24505 (end (save-excursion (org-end-of-subtree t t)))
24506 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24507 (past-first-child nil)
24508 ;; Make sure to skip inlinetasks.
24509 (re (format regexp-fmt
24510 current-level
24511 (cond
24512 ((not (featurep 'org-inlinetask)) "")
24513 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24515 (t (1- org-inlinetask-min-level))))))
24516 ;; Display parent heading.
24517 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24518 (forward-line)
24519 ;; Display children. First child may be deeper than expected
24520 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24521 ;; MAX-LEVEL accordingly.
24522 (while (re-search-forward re end t)
24523 (unless past-first-child
24524 (setq re (format regexp-fmt
24525 current-level
24526 (max (funcall outline-level) max-level)))
24527 (setq past-first-child t))
24528 (outline-flag-region
24529 (line-end-position 0) (line-end-position) nil))))))
24531 (defun org-show-subtree ()
24532 "Show everything after this heading at deeper levels."
24533 (interactive)
24534 (outline-flag-region
24535 (point)
24536 (save-excursion
24537 (org-end-of-subtree t t))
24538 nil))
24540 (defun org-show-entry ()
24541 "Show the body directly following this heading.
24542 Show the heading too, if it is currently invisible."
24543 (interactive)
24544 (save-excursion
24545 (ignore-errors
24546 (org-back-to-heading t)
24547 (outline-flag-region
24548 (max (point-min) (1- (point)))
24549 (save-excursion
24550 (if (re-search-forward
24551 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24552 (match-beginning 1)
24553 (point-max)))
24554 nil)
24555 (org-cycle-hide-drawers 'children))))
24557 (defun org-make-options-regexp (kwds &optional extra)
24558 "Make a regular expression for keyword lines.
24559 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24560 when non-nil, is a regexp matching keywords names."
24561 (concat "^[ \t]*#\\+\\("
24562 (regexp-opt kwds)
24563 (and extra (concat (and kwds "\\|") extra))
24564 "\\):[ \t]*\\(.*\\)"))
24566 ;;;; Integration with and fixes for other packages
24568 ;;; Imenu support
24570 (defvar-local org-imenu-markers nil
24571 "All markers currently used by Imenu.")
24573 (defun org-imenu-new-marker (&optional pos)
24574 "Return a new marker for use by Imenu, and remember the marker."
24575 (let ((m (make-marker)))
24576 (move-marker m (or pos (point)))
24577 (push m org-imenu-markers)
24580 (defun org-imenu-get-tree ()
24581 "Produce the index for Imenu."
24582 (dolist (x org-imenu-markers) (move-marker x nil))
24583 (setq org-imenu-markers nil)
24584 (let* ((case-fold-search nil)
24585 (n org-imenu-depth)
24586 (re (concat "^" (org-get-limited-outline-regexp)))
24587 (subs (make-vector (1+ n) nil))
24588 (last-level 0)
24589 m level head0 head)
24590 (org-with-wide-buffer
24591 (goto-char (point-max))
24592 (while (re-search-backward re nil t)
24593 (setq level (org-reduced-level (funcall outline-level)))
24594 (when (and (<= level n)
24595 (looking-at org-complex-heading-regexp)
24596 (setq head0 (match-string-no-properties 4)))
24597 (setq head (org-link-display-format head0)
24598 m (org-imenu-new-marker))
24599 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24600 (if (>= level last-level)
24601 (push (cons head m) (aref subs level))
24602 (push (cons head (aref subs (1+ level))) (aref subs level))
24603 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24604 (setq last-level level))))
24605 (aref subs 1)))
24607 (eval-after-load "imenu"
24608 '(progn
24609 (add-hook 'imenu-after-jump-hook
24610 (lambda ()
24611 (when (derived-mode-p 'org-mode)
24612 (org-show-context 'org-goto))))))
24614 (defun org-link-display-format (s)
24615 "Replace links in string S with their description.
24616 If there is no description, use the link target."
24617 (save-match-data
24618 (replace-regexp-in-string
24619 org-bracket-link-analytic-regexp
24620 (lambda (m)
24621 (if (match-end 5) (match-string 5 m)
24622 (concat (match-string 1 m) (match-string 3 m))))
24623 s nil t)))
24625 (defun org-toggle-link-display ()
24626 "Toggle the literal or descriptive display of links."
24627 (interactive)
24628 (if org-descriptive-links
24629 (progn (org-remove-from-invisibility-spec '(org-link))
24630 (org-restart-font-lock)
24631 (setq org-descriptive-links nil))
24632 (progn (add-to-invisibility-spec '(org-link))
24633 (org-restart-font-lock)
24634 (setq org-descriptive-links t))))
24636 ;; Speedbar support
24638 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24639 "Overlay marking the agenda restriction line in speedbar.")
24640 (overlay-put org-speedbar-restriction-lock-overlay
24641 'face 'org-agenda-restriction-lock)
24642 (overlay-put org-speedbar-restriction-lock-overlay
24643 'help-echo "Agendas are currently limited to this item.")
24644 (delete-overlay org-speedbar-restriction-lock-overlay)
24646 (defun org-speedbar-set-agenda-restriction ()
24647 "Restrict future agenda commands to the location at point in speedbar.
24648 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24649 (interactive)
24650 (require 'org-agenda)
24651 (let (p m tp np dir txt)
24652 (cond
24653 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24654 'org-imenu t))
24655 (setq m (get-text-property p 'org-imenu-marker))
24656 (with-current-buffer (marker-buffer m)
24657 (goto-char m)
24658 (org-agenda-set-restriction-lock 'subtree)))
24659 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24660 'speedbar-function 'speedbar-find-file))
24661 (setq tp (previous-single-property-change
24662 (1+ p) 'speedbar-function)
24663 np (next-single-property-change
24664 tp 'speedbar-function)
24665 dir (speedbar-line-directory)
24666 txt (buffer-substring-no-properties (or tp (point-min))
24667 (or np (point-max))))
24668 (with-current-buffer (find-file-noselect
24669 (let ((default-directory dir))
24670 (expand-file-name txt)))
24671 (unless (derived-mode-p 'org-mode)
24672 (user-error "Cannot restrict to non-Org mode file"))
24673 (org-agenda-set-restriction-lock 'file)))
24674 (t (user-error "Don't know how to restrict Org mode agenda")))
24675 (move-overlay org-speedbar-restriction-lock-overlay
24676 (point-at-bol) (point-at-eol))
24677 (setq current-prefix-arg nil)
24678 (org-agenda-maybe-redo)))
24680 (defvar speedbar-file-key-map)
24681 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24682 (eval-after-load "speedbar"
24683 '(progn
24684 (speedbar-add-supported-extension ".org")
24685 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24686 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24687 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24688 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24689 (add-hook 'speedbar-visiting-tag-hook
24690 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24692 ;;; Fixes and Hacks for problems with other packages
24694 (defun org--flyspell-object-check-p (element)
24695 "Non-nil when Flyspell can check object at point.
24696 ELEMENT is the element at point."
24697 (let ((object (save-excursion
24698 (when (looking-at-p "\\>") (backward-char))
24699 (org-element-context element))))
24700 (cl-case (org-element-type object)
24701 ;; Prevent checks in links due to keybinding conflict with
24702 ;; Flyspell.
24703 ((code entity export-snippet inline-babel-call
24704 inline-src-block line-break latex-fragment link macro
24705 statistics-cookie target timestamp verbatim)
24706 nil)
24707 (footnote-reference
24708 ;; Only in inline footnotes, within the definition.
24709 (and (eq (org-element-property :type object) 'inline)
24710 (< (save-excursion
24711 (goto-char (org-element-property :begin object))
24712 (search-forward ":" nil t 2))
24713 (point))))
24714 (otherwise t))))
24716 (defun org-mode-flyspell-verify ()
24717 "Function used for `flyspell-generic-check-word-predicate'."
24718 (if (org-at-heading-p)
24719 ;; At a headline or an inlinetask, check title only. This is
24720 ;; faster than relying on `org-element-at-point'.
24721 (and (save-excursion (beginning-of-line)
24722 (and (let ((case-fold-search t))
24723 (not (looking-at-p "\\*+ END[ \t]*$")))
24724 (let ((case-fold-search nil))
24725 (looking-at org-complex-heading-regexp))))
24726 (match-beginning 4)
24727 (>= (point) (match-beginning 4))
24728 (or (not (match-beginning 5))
24729 (< (point) (match-beginning 5))))
24730 (let* ((element (org-element-at-point))
24731 (post-affiliated (org-element-property :post-affiliated element)))
24732 (cond
24733 ;; Ignore checks in all affiliated keywords but captions.
24734 ((< (point) post-affiliated)
24735 (and (save-excursion
24736 (beginning-of-line)
24737 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24738 (> (point) (match-end 0))
24739 (org--flyspell-object-check-p element)))
24740 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24741 ((let ((log (org-log-into-drawer)))
24742 (and log
24743 (let ((drawer (org-element-lineage element '(drawer))))
24744 (and drawer
24745 (eq (compare-strings
24746 log nil nil
24747 (org-element-property :drawer-name drawer) nil nil t)
24748 t)))))
24749 nil)
24751 (cl-case (org-element-type element)
24752 ((comment quote-section) t)
24753 (comment-block
24754 ;; Allow checks between block markers, not on them.
24755 (and (> (line-beginning-position) post-affiliated)
24756 (save-excursion
24757 (end-of-line)
24758 (skip-chars-forward " \r\t\n")
24759 (< (point) (org-element-property :end element)))))
24760 ;; Arbitrary list of keywords where checks are meaningful.
24761 ;; Make sure point is on the value part of the element.
24762 (keyword
24763 (and (member (org-element-property :key element)
24764 '("DESCRIPTION" "TITLE"))
24765 (save-excursion
24766 (search-backward ":" (line-beginning-position) t))))
24767 ;; Check is globally allowed in paragraphs verse blocks and
24768 ;; table rows (after affiliated keywords) but some objects
24769 ;; must not be affected.
24770 ((paragraph table-row verse-block)
24771 (let ((cbeg (org-element-property :contents-begin element))
24772 (cend (org-element-property :contents-end element)))
24773 (and cbeg (>= (point) cbeg) (< (point) cend)
24774 (org--flyspell-object-check-p element))))))))))
24775 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24777 (defun org-remove-flyspell-overlays-in (beg end)
24778 "Remove flyspell overlays in region."
24779 (and (bound-and-true-p flyspell-mode)
24780 (fboundp 'flyspell-delete-region-overlays)
24781 (flyspell-delete-region-overlays beg end)))
24783 (defvar flyspell-delayed-commands)
24784 (eval-after-load "flyspell"
24785 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24787 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24788 (eval-after-load "bookmark"
24789 '(if (boundp 'bookmark-after-jump-hook)
24790 ;; We can use the hook
24791 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24792 ;; Hook not available, use advice
24793 (defadvice bookmark-jump (after org-make-visible activate)
24794 "Make the position visible."
24795 (org-bookmark-jump-unhide))))
24797 ;; Make sure saveplace shows the location if it was hidden
24798 (eval-after-load "saveplace"
24799 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24800 "Make the position visible."
24801 (org-bookmark-jump-unhide)))
24803 ;; Make sure ecb shows the location if it was hidden
24804 (eval-after-load "ecb"
24805 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24806 "Make hierarchy visible when jumping into location from ECB tree buffer."
24807 (when (derived-mode-p 'org-mode)
24808 (org-show-context))))
24810 (defun org-bookmark-jump-unhide ()
24811 "Unhide the current position, to show the bookmark location."
24812 (and (derived-mode-p 'org-mode)
24813 (or (org-invisible-p)
24814 (save-excursion (goto-char (max (point-min) (1- (point))))
24815 (org-invisible-p)))
24816 (org-show-context 'bookmark-jump)))
24818 (defun org-mark-jump-unhide ()
24819 "Make the point visible with `org-show-context' after jumping to the mark."
24820 (when (and (derived-mode-p 'org-mode)
24821 (org-invisible-p))
24822 (org-show-context 'mark-goto)))
24824 (eval-after-load "simple"
24825 '(defadvice pop-to-mark-command (after org-make-visible activate)
24826 "Make the point visible with `org-show-context'."
24827 (org-mark-jump-unhide)))
24829 (eval-after-load "simple"
24830 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24831 "Make the point visible with `org-show-context'."
24832 (org-mark-jump-unhide)))
24834 (eval-after-load "simple"
24835 '(defadvice pop-global-mark (after org-make-visible activate)
24836 "Make the point visible with `org-show-context'."
24837 (org-mark-jump-unhide)))
24839 ;; Make session.el ignore our circular variable
24840 (defvar session-globals-exclude)
24841 (eval-after-load "session"
24842 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24844 ;;;; Finish up
24846 (provide 'org)
24848 (run-hooks 'org-load-hook)
24850 ;;; org.el ends here