Fix spurious colons next to TODO keywords
[org-mode/org-tableheadings.git] / lisp / org.el
blob9da1da26be9a8211993b0ee5252fdae110a5d129
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function
133 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
134 (declare-function org-element-at-point "org-element" ())
135 (declare-function org-element-cache-refresh "org-element" (pos))
136 (declare-function org-element-cache-reset "org-element" (&optional all))
137 (declare-function org-element-contents "org-element" (element))
138 (declare-function org-element-context "org-element" (&optional element))
139 (declare-function org-element-copy "org-element" (datum))
140 (declare-function org-element-interpret-data "org-element" (data))
141 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
142 (declare-function org-element-link-parser "org-element" ())
143 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
144 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-put-property "org-element" (element property value))
147 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
148 (declare-function org-element-type "org-element" (element))
149 (declare-function org-element-update-syntax "org-element" ())
150 (declare-function org-id-find-id-file "org-id" (id))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
153 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
154 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
155 (declare-function org-plot/gnuplot "org-plot" (&optional params))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-beginning-of-field "org-table" (&optional n))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
161 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
162 (declare-function org-table-cut-region "org-table" (beg end))
163 (declare-function org-table-edit-field "org-table" (arg))
164 (declare-function org-table-end "org-table" (&optional table-type))
165 (declare-function org-table-end-of-field "org-table" (&optional n))
166 (declare-function org-table-insert-row "org-table" (&optional arg))
167 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
168 (declare-function org-table-maybe-eval-formula "org-table" ())
169 (declare-function org-table-maybe-recalculate-line "org-table" ())
170 (declare-function org-table-next-row "org-table" ())
171 (declare-function org-table-paste-rectangle "org-table" ())
172 (declare-function org-table-recalculate "org-table" (&optional all noalign))
173 (declare-function
174 org-table-sort-lines "org-table"
175 (&optional with-case sorting-type getkey-func compare-func interactive?))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp) ;Silence byte-compiler
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s &optional keep-lead)
195 "Remove whitespace at the beginning and the end of string S.
196 When optional argument KEEP-LEAD is non-nil, removing blank lines
197 at the beginning of the string does not affect leading indentation."
198 (replace-regexp-in-string
199 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
200 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
202 ;; load languages based on value of `org-babel-load-languages'
203 (defvar org-babel-load-languages)
205 ;;;###autoload
206 (defun org-babel-do-load-languages (sym value)
207 "Load the languages defined in `org-babel-load-languages'."
208 (set-default sym value)
209 (dolist (pair org-babel-load-languages)
210 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
211 (if active
212 (require (intern (concat "ob-" lang)))
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the Org file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 ;; Tangle-file traversal returns reversed list of tangled files
238 ;; and we want to evaluate the first target.
239 (setq exported-file
240 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "hledger" hledger)
280 (const :tag "IO" io)
281 (const :tag "J" J)
282 (const :tag "Java" java)
283 (const :tag "Javascript" js)
284 (const :tag "LaTeX" latex)
285 (const :tag "Ledger" ledger)
286 (const :tag "Lilypond" lilypond)
287 (const :tag "Lisp" lisp)
288 (const :tag "Makefile" makefile)
289 (const :tag "Maxima" maxima)
290 (const :tag "Matlab" matlab)
291 (const :tag "Mscgen" mscgen)
292 (const :tag "Ocaml" ocaml)
293 (const :tag "Octave" octave)
294 (const :tag "Org" org)
295 (const :tag "Perl" perl)
296 (const :tag "Pico Lisp" picolisp)
297 (const :tag "PlantUML" plantuml)
298 (const :tag "Python" python)
299 (const :tag "Ruby" ruby)
300 (const :tag "Sass" sass)
301 (const :tag "Scala" scala)
302 (const :tag "Scheme" scheme)
303 (const :tag "Screen" screen)
304 (const :tag "Shell Script" shell)
305 (const :tag "Shen" shen)
306 (const :tag "Sql" sql)
307 (const :tag "Sqlite" sqlite)
308 (const :tag "Stan" stan)
309 (const :tag "ebnf2ps" ebnf2ps))
310 :value-type (boolean :tag "Activate" :value t)))
312 ;;;; Customization variables
313 (defcustom org-clone-delete-id nil
314 "Remove ID property of clones of a subtree.
315 When non-nil, clones of a subtree don't inherit the ID property.
316 Otherwise they inherit the ID property with a new unique
317 identifier."
318 :type 'boolean
319 :version "24.1"
320 :group 'org-id)
322 ;;; Version
323 (org-check-version)
325 ;;;###autoload
326 (defun org-version (&optional here full message)
327 "Show the Org version.
328 Interactively, or when MESSAGE is non-nil, show it in echo area.
329 With prefix argument, or when HERE is non-nil, insert it at point.
330 In non-interactive uses, a reduced version string is output unless
331 FULL is given."
332 (interactive (list current-prefix-arg t (not current-prefix-arg)))
333 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
334 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
335 (load-suffixes (list ".el"))
336 (org-install-dir
337 (ignore-errors (org-find-library-dir "org-loaddefs"))))
338 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
339 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
340 (let* ((load-suffixes save-load-suffixes)
341 (release (org-release))
342 (git-version (org-git-version))
343 (version (format "Org mode version %s (%s @ %s)"
344 release
345 git-version
346 (if org-install-dir
347 (if (string= org-dir org-install-dir)
348 org-install-dir
349 (concat "mixed installation! "
350 org-install-dir
351 " and "
352 org-dir))
353 "org-loaddefs.el can not be found!")))
354 (version1 (if full version release)))
355 (when here (insert version1))
356 (when message (message "%s" version1))
357 version1)))
359 (defconst org-version (org-version))
362 ;;; Syntax Constants
364 ;;;; Block
366 (defconst org-block-regexp
367 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
368 "Regular expression for hiding blocks.")
370 (defconst org-dblock-start-re
371 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
372 "Matches the start line of a dynamic block, with parameters.")
374 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
375 "Matches the end of a dynamic block.")
377 ;;;; Clock and Planning
379 (defconst org-clock-string "CLOCK:"
380 "String used as prefix for timestamps clocking work hours on an item.")
382 (defvar org-closed-string "CLOSED:"
383 "String used as the prefix for timestamps logging closing a TODO entry.")
385 (defvar org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 \\<org-mode-map>
388 A deadline is this string, followed by a time stamp. It must be
389 a word, terminated by a colon. You can insert a schedule keyword
390 and a timestamp with `\\[org-deadline]'.")
392 (defvar org-scheduled-string "SCHEDULED:"
393 "String to mark scheduled TODO entries.
394 \\<org-mode-map>
395 A schedule is this string, followed by a time stamp. It must be
396 a word, terminated by a colon. You can insert a schedule keyword
397 and a timestamp with `\\[org-schedule]'.")
399 (defconst org-ds-keyword-length
400 (+ 2
401 (apply #'max
402 (mapcar #'length
403 (list org-deadline-string org-scheduled-string
404 org-clock-string org-closed-string))))
405 "Maximum length of the DEADLINE and SCHEDULED keywords.")
407 (defconst org-planning-line-re
408 (concat "^[ \t]*"
409 (regexp-opt
410 (list org-closed-string org-deadline-string org-scheduled-string)
412 "Matches a line with planning info.
413 Matched keyword is in group 1.")
415 (defconst org-clock-line-re
416 (concat "^[ \t]*" org-clock-string)
417 "Matches a line with clock info.")
419 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
420 "Matches the DEADLINE keyword.")
422 (defconst org-deadline-time-regexp
423 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
424 "Matches the DEADLINE keyword together with a time stamp.")
426 (defconst org-deadline-time-hour-regexp
427 (concat "\\<" org-deadline-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
431 (defconst org-deadline-line-regexp
432 (concat "\\<\\(" org-deadline-string "\\).*")
433 "Matches the DEADLINE keyword and the rest of the line.")
435 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
436 "Matches the SCHEDULED keyword.")
438 (defconst org-scheduled-time-regexp
439 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
440 "Matches the SCHEDULED keyword together with a time stamp.")
442 (defconst org-scheduled-time-hour-regexp
443 (concat "\\<" org-scheduled-string
444 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
445 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
447 (defconst org-closed-time-regexp
448 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
449 "Matches the CLOSED keyword together with a time stamp.")
451 (defconst org-keyword-time-regexp
452 (concat "\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 4 keywords, together with the time stamp.")
460 (defconst org-keyword-time-not-clock-regexp
461 (concat
462 "\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string) t)
465 " *[[<]\\([^]>]+\\)[]>]")
466 "Matches any of the 3 keywords, together with the time stamp.")
468 (defconst org-maybe-keyword-time-regexp
469 (concat "\\(\\<"
470 (regexp-opt
471 (list org-scheduled-string org-deadline-string org-closed-string
472 org-clock-string)
474 "\\)?"
475 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
476 "\\|"
477 "<%%([^\r\n>]*>\\)")
478 "Matches a timestamp, possibly preceded by a keyword.")
480 (defconst org-all-time-keywords
481 (mapcar (lambda (w) (substring w 0 -1))
482 (list org-scheduled-string org-deadline-string
483 org-clock-string org-closed-string))
484 "List of time keywords.")
486 ;;;; Drawer
488 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
489 "Matches first or last line of a hidden block.
490 Group 1 contains drawer's name or \"END\".")
492 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
493 "Regular expression matching the first line of a property drawer.")
495 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
496 "Regular expression matching the last line of a property drawer.")
498 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
499 "Regular expression matching the first line of a clock drawer.")
501 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
502 "Regular expression matching the last line of a clock drawer.")
504 (defconst org-property-drawer-re
505 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
506 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
507 "[ \t]*:END:[ \t]*$")
508 "Matches an entire property drawer.")
510 (defconst org-clock-drawer-re
511 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
512 org-clock-drawer-end-re "\\)\n?")
513 "Matches an entire clock drawer.")
515 ;;;; Headline
517 (defconst org-heading-keyword-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline with some keyword.
520 This regexp will match the headline of any node which has the
521 exact keyword that is put into the format. The keyword isn't in
522 any group by default, but the stars and the body are.")
524 (defconst org-heading-keyword-maybe-regexp-format
525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
526 "Printf format for a regexp matching a headline, possibly with some keyword.
527 This regexp can match any headline with the specified keyword, or
528 without a keyword. The keyword isn't in any group by default,
529 but the stars and the body are.")
531 (defconst org-archive-tag "ARCHIVE"
532 "The tag that marks a subtree as archived.
533 An archived subtree does not open during visibility cycling, and does
534 not contribute to the agenda listings.")
536 (eval-and-compile
537 (defconst org-comment-string "COMMENT"
538 "Entries starting with this keyword will never be exported.
539 \\<org-mode-map>
540 An entry can be toggled between COMMENT and normal with
541 `\\[org-toggle-comment]'."))
544 ;;;; LaTeX Environments and Fragments
546 (defconst org-latex-regexps
547 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
548 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
549 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
550 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
551 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
552 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
553 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
554 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
555 "Regular expressions for matching embedded LaTeX.")
557 ;;;; Node Property
559 (defconst org-effort-property "Effort"
560 "The property that is being used to keep track of effort estimates.
561 Effort estimates given in this property need to have the format H:MM.")
563 ;;;; Table
565 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
566 "Detect an org-type or table-type table.")
568 (defconst org-table-line-regexp "^[ \t]*|"
569 "Detect an org-type table line.")
571 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
572 "Detect an org-type table line.")
574 (defconst org-table-hline-regexp "^[ \t]*|-"
575 "Detect an org-type table hline.")
577 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
578 "Detect a table-type table hline.")
580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
581 "Detect the first line outside a table when searching from within it.
582 This works for both table types.")
584 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
585 "Detect a #+TBLFM line.")
587 ;;;; Timestamp
589 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
590 "Regular expression for fast time stamp matching.")
592 (defconst org-ts-regexp-inactive
593 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
594 "Regular expression for fast inactive time stamp matching.")
596 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
597 "Regular expression for fast time stamp matching.")
599 (defconst org-ts-regexp0
600 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
601 "Regular expression matching time strings for analysis.
602 This one does not require the space after the date, so it can be used
603 on a string that terminates immediately after the date.")
605 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
606 "Regular expression matching time strings for analysis.")
608 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
609 "Regular expression matching time stamps, with groups.")
611 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
612 "Regular expression matching time stamps (also [..]), with groups.")
614 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
615 "Regular expression matching a time stamp range.")
617 (defconst org-tr-regexp-both
618 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
622 org-ts-regexp "\\)?")
623 "Regular expression matching a time stamp or time stamp range.")
625 (defconst org-tsr-regexp-both
626 (concat org-ts-regexp-both "\\(--?-?"
627 org-ts-regexp-both "\\)?")
628 "Regular expression matching a time stamp or time stamp range.
629 The time stamps may be either active or inactive.")
631 (defconst org-repeat-re
632 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
633 "Regular expression for specifying repeated events.
634 After a match, group 1 contains the repeat expression.")
636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
637 "Formats for `format-time-string' which are used for time stamps.")
640 ;;; The custom variables
642 (defgroup org nil
643 "Outline-based notes management and organizer."
644 :tag "Org"
645 :group 'outlines
646 :group 'calendar)
648 (defcustom org-mode-hook nil
649 "Mode hook for Org mode, run after the mode was turned on."
650 :group 'org
651 :type 'hook)
653 (defcustom org-load-hook nil
654 "Hook that is run after org.el has been loaded."
655 :group 'org
656 :type 'hook)
658 (defcustom org-log-buffer-setup-hook nil
659 "Hook that is run after an Org log buffer is created."
660 :group 'org
661 :version "24.1"
662 :type 'hook)
664 (defvar org-modules) ; defined below
665 (defvar org-modules-loaded nil
666 "Have the modules been loaded already?")
668 (defun org-load-modules-maybe (&optional force)
669 "Load all extensions listed in `org-modules'."
670 (when (or force (not org-modules-loaded))
671 (dolist (ext org-modules)
672 (condition-case nil (require ext)
673 (error (message "Problems while trying to load feature `%s'" ext))))
674 (setq org-modules-loaded t)))
676 (defun org-set-modules (var value)
677 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
678 (set var value)
679 (when (featurep 'org)
680 (org-load-modules-maybe 'force)
681 (org-element-cache-reset 'all)))
683 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
684 "Modules that should always be loaded together with org.el.
686 If a description starts with <C>, the file is not part of Emacs
687 and loading it will require that you have downloaded and properly
688 installed the Org mode distribution.
690 You can also use this system to load external packages (i.e. neither Org
691 core modules, nor modules from the CONTRIB directory). Just add symbols
692 to the end of the list. If the package is called org-xyz.el, then you need
693 to add the symbol `xyz', and the package must have a call to:
695 (provide \\='org-xyz)
697 For export specific modules, see also `org-export-backends'."
698 :group 'org
699 :set 'org-set-modules
700 :version "24.4"
701 :package-version '(Org . "8.0")
702 :type
703 '(set :greedy t
704 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
705 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
706 (const :tag " crypt: Encryption of subtrees" org-crypt)
707 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
708 (const :tag " docview: Links to doc-view buffers" org-docview)
709 (const :tag " eww: Store link to url of eww" org-eww)
710 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
711 (const :tag " habit: Track your consistency with habits" org-habit)
712 (const :tag " id: Global IDs for identifying entries" org-id)
713 (const :tag " info: Links to Info nodes" org-info)
714 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
715 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
716 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
717 (const :tag " mouse: Additional mouse support" org-mouse)
718 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
719 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
720 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
722 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
723 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
724 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
725 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
726 (const :tag "C collector: Collect properties into tables" org-collector)
727 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
728 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
729 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
730 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
731 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
732 (const :tag "C eval: Include command output as text" org-eval)
733 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
734 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
735 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
736 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
737 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
738 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
739 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
740 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
741 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
742 (const :tag "C man: Support for links to manpages in Org mode" org-man)
743 (const :tag "C mew: Links to Mew folders/messages" org-mew)
744 (const :tag "C mtags: Support for muse-like tags" org-mtags)
745 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
746 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
747 (const :tag "C registry: A registry for Org links" org-registry)
748 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
749 (const :tag "C secretary: Team management with org-mode" org-secretary)
750 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
751 (const :tag "C toc: Table of contents for Org buffer" org-toc)
752 (const :tag "C track: Keep up with Org mode development" org-track)
753 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
754 (const :tag "C vm: Links to VM folders/messages" org-vm)
755 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
756 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
757 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
759 (defvar org-export-registered-backends) ; From ox.el.
760 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
761 (declare-function org-export-backend-name "ox" (backend) t)
762 (defcustom org-export-backends '(ascii html icalendar latex odt)
763 "List of export back-ends that should be always available.
765 If a description starts with <C>, the file is not part of Emacs
766 and loading it will require that you have downloaded and properly
767 installed the Org mode distribution.
769 Unlike to `org-modules', libraries in this list will not be
770 loaded along with Org, but only once the export framework is
771 needed.
773 This variable needs to be set before org.el is loaded. If you
774 need to make a change while Emacs is running, use the customize
775 interface or run the following code, where VAL stands for the new
776 value of the variable, after updating it:
778 (progn
779 (setq org-export-registered-backends
780 (cl-remove-if-not
781 (lambda (backend)
782 (let ((name (org-export-backend-name backend)))
783 (or (memq name val)
784 (catch \\='parentp
785 (dolist (b val)
786 (and (org-export-derived-backend-p b name)
787 (throw \\='parentp t)))))))
788 org-export-registered-backends))
789 (let ((new-list (mapcar #\\='org-export-backend-name
790 org-export-registered-backends)))
791 (dolist (backend val)
792 (cond
793 ((not (load (format \"ox-%s\" backend) t t))
794 (message \"Problems while trying to load export back-end \\=`%s\\='\"
795 backend))
796 ((not (memq backend new-list)) (push backend new-list))))
797 (set-default \\='org-export-backends new-list)))
799 Adding a back-end to this list will also pull the back-end it
800 depends on, if any."
801 :group 'org
802 :group 'org-export
803 :version "26.1"
804 :package-version '(Org . "9.0")
805 :initialize 'custom-initialize-set
806 :set (lambda (var val)
807 (if (not (featurep 'ox)) (set-default var val)
808 ;; Any back-end not required anymore (not present in VAL and not
809 ;; a parent of any back-end in the new value) is removed from the
810 ;; list of registered back-ends.
811 (setq org-export-registered-backends
812 (cl-remove-if-not
813 (lambda (backend)
814 (let ((name (org-export-backend-name backend)))
815 (or (memq name val)
816 (catch 'parentp
817 (dolist (b val)
818 (and (org-export-derived-backend-p b name)
819 (throw 'parentp t)))))))
820 org-export-registered-backends))
821 ;; Now build NEW-LIST of both new back-ends and required
822 ;; parents.
823 (let ((new-list (mapcar #'org-export-backend-name
824 org-export-registered-backends)))
825 (dolist (backend val)
826 (cond
827 ((not (load (format "ox-%s" backend) t t))
828 (message "Problems while trying to load export back-end `%s'"
829 backend))
830 ((not (memq backend new-list)) (push backend new-list))))
831 ;; Set VAR to that list with fixed dependencies.
832 (set-default var new-list))))
833 :type '(set :greedy t
834 (const :tag " ascii Export buffer to ASCII format" ascii)
835 (const :tag " beamer Export buffer to Beamer presentation" beamer)
836 (const :tag " html Export buffer to HTML format" html)
837 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
838 (const :tag " latex Export buffer to LaTeX format" latex)
839 (const :tag " man Export buffer to MAN format" man)
840 (const :tag " md Export buffer to Markdown format" md)
841 (const :tag " odt Export buffer to ODT format" odt)
842 (const :tag " org Export buffer to Org format" org)
843 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
844 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
845 (const :tag "C deck Export buffer to deck.js presentations" deck)
846 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
847 (const :tag "C groff Export buffer to Groff format" groff)
848 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
849 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
850 (const :tag "C s5 Export buffer to s5 presentations" s5)
851 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
853 (eval-after-load 'ox
854 '(dolist (backend org-export-backends)
855 (condition-case nil (require (intern (format "ox-%s" backend)))
856 (error (message "Problems while trying to load export back-end `%s'"
857 backend)))))
859 (defcustom org-support-shift-select nil
860 "Non-nil means make shift-cursor commands select text when possible.
861 \\<org-mode-map>\
863 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
864 start selecting a region, or enlarge regions started in this way.
865 In Org mode, in special contexts, these same keys are used for
866 other purposes, important enough to compete with shift selection.
867 Org tries to balance these needs by supporting `shift-select-mode'
868 outside these special contexts, under control of this variable.
870 The default of this variable is nil, to avoid confusing behavior. Shifted
871 cursor keys will then execute Org commands in the following contexts:
872 - on a headline, changing TODO state (left/right) and priority (up/down)
873 - on a time stamp, changing the time
874 - in a plain list item, changing the bullet type
875 - in a property definition line, switching between allowed values
876 - in the BEGIN line of a clock table (changing the time block).
877 Outside these contexts, the commands will throw an error.
879 When this variable is t and the cursor is not in a special
880 context, Org mode will support shift-selection for making and
881 enlarging regions. To make this more effective, the bullet
882 cycling will no longer happen anywhere in an item line, but only
883 if the cursor is exactly on the bullet.
885 If you set this variable to the symbol `always', then the keys
886 will not be special in headlines, property lines, and item lines,
887 to make shift selection work there as well. If this is what you
888 want, you can use the following alternative commands:
889 `\\[org-todo]' and `\\[org-priority]' \
890 to change TODO state and priority,
891 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
892 can be used to switch TODO sets,
893 `\\[org-ctrl-c-minus]' to cycle item bullet types,
894 and properties can be edited by hand or in column view.
896 However, when the cursor is on a timestamp, shift-cursor commands
897 will still edit the time stamp - this is just too good to give up."
898 :group 'org
899 :type '(choice
900 (const :tag "Never" nil)
901 (const :tag "When outside special context" t)
902 (const :tag "Everywhere except timestamps" always)))
904 (defcustom org-loop-over-headlines-in-active-region nil
905 "Shall some commands act upon headlines in the active region?
907 When set to t, some commands will be performed in all headlines
908 within the active region.
910 When set to `start-level', some commands will be performed in all
911 headlines within the active region, provided that these headlines
912 are of the same level than the first one.
914 When set to a string, those commands will be performed on the
915 matching headlines within the active region. Such string must be
916 a tags/property/todo match as it is used in the agenda tags view.
918 The list of commands is: `org-schedule', `org-deadline',
919 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
920 `org-archive-to-archive-sibling'. The archiving commands skip
921 already archived entries."
922 :type '(choice (const :tag "Don't loop" nil)
923 (const :tag "All headlines in active region" t)
924 (const :tag "In active region, headlines at the same level than the first one" start-level)
925 (string :tag "Tags/Property/Todo matcher"))
926 :version "24.1"
927 :group 'org-todo
928 :group 'org-archive)
930 (defgroup org-startup nil
931 "Options concerning startup of Org mode."
932 :tag "Org Startup"
933 :group 'org)
935 (defcustom org-startup-folded t
936 "Non-nil means entering Org mode will switch to OVERVIEW.
938 This can also be configured on a per-file basis by adding one of
939 the following lines anywhere in the buffer:
941 #+STARTUP: fold (or `overview', this is equivalent)
942 #+STARTUP: nofold (or `showall', this is equivalent)
943 #+STARTUP: content
944 #+STARTUP: showeverything
946 Set `org-agenda-inhibit-startup' to a non-nil value if you want
947 to ignore this option when Org opens agenda files for the first
948 time."
949 :group 'org-startup
950 :type '(choice
951 (const :tag "nofold: show all" nil)
952 (const :tag "fold: overview" t)
953 (const :tag "content: all headlines" content)
954 (const :tag "show everything, even drawers" showeverything)))
956 (defcustom org-startup-truncated t
957 "Non-nil means entering Org mode will set `truncate-lines'.
958 This is useful since some lines containing links can be very long and
959 uninteresting. Also tables look terrible when wrapped.
961 The variable `org-startup-truncated' allows to configure
962 truncation for Org mode different to the other modes that use the
963 variable `truncate-lines' and as a shortcut instead of putting
964 the variable `truncate-lines' into the `org-mode-hook'. If one
965 wants to configure truncation for Org mode not statically but
966 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
967 the variable `truncate-lines' has to be used because in such a
968 case it is too late to set the variable `org-startup-truncated'."
969 :group 'org-startup
970 :type 'boolean)
972 (defcustom org-startup-indented nil
973 "Non-nil means turn on `org-indent-mode' on startup.
974 This can also be configured on a per-file basis by adding one of
975 the following lines anywhere in the buffer:
977 #+STARTUP: indent
978 #+STARTUP: noindent"
979 :group 'org-structure
980 :type '(choice
981 (const :tag "Not" nil)
982 (const :tag "Globally (slow on startup in large files)" t)))
984 (defcustom org-use-sub-superscripts t
985 "Non-nil means interpret \"_\" and \"^\" for display.
987 If you want to control how Org exports those characters, see
988 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
989 used to be an alias for `org-export-with-sub-superscripts' in
990 Org <8.0, it is not anymore.
992 When this option is turned on, you can use TeX-like syntax for
993 sub- and superscripts within the buffer. Several characters after
994 \"_\" or \"^\" will be considered as a single item - so grouping
995 with {} is normally not needed. For example, the following things
996 will be parsed as single sub- or superscripts:
998 10^24 or 10^tau several digits will be considered 1 item.
999 10^-12 or 10^-tau a leading sign with digits or a word
1000 x^2-y^3 will be read as x^2 - y^3, because items are
1001 terminated by almost any nonword/nondigit char.
1002 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1004 Still, ambiguity is possible. So when in doubt, use {} to enclose
1005 the sub/superscript. If you set this variable to the symbol `{}',
1006 the braces are *required* in order to trigger interpretations as
1007 sub/superscript. This can be helpful in documents that need \"_\"
1008 frequently in plain text."
1009 :group 'org-startup
1010 :version "24.4"
1011 :package-version '(Org . "8.0")
1012 :type '(choice
1013 (const :tag "Always interpret" t)
1014 (const :tag "Only with braces" {})
1015 (const :tag "Never interpret" nil)))
1017 (defcustom org-startup-with-beamer-mode nil
1018 "Non-nil means turn on `org-beamer-mode' on startup.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1022 #+STARTUP: beamer"
1023 :group 'org-startup
1024 :version "24.1"
1025 :type 'boolean)
1027 (defcustom org-startup-align-all-tables nil
1028 "Non-nil means align all tables when visiting a file.
1029 This is useful when the column width in tables is forced with <N> cookies
1030 in table fields. Such tables will look correct only after the first re-align.
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-with-inline-images nil
1039 "Non-nil means show inline images when loading a new Org file.
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: inlineimages
1043 #+STARTUP: noinlineimages"
1044 :group 'org-startup
1045 :version "24.1"
1046 :type 'boolean)
1048 (defcustom org-startup-with-latex-preview nil
1049 "Non-nil means preview LaTeX fragments 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: latexpreview
1054 #+STARTUP: nolatexpreview"
1055 :group 'org-startup
1056 :version "24.4"
1057 :package-version '(Org . "8.0")
1058 :type 'boolean)
1060 (defcustom org-insert-mode-line-in-empty-file nil
1061 "Non-nil means insert the first line setting Org mode in empty files.
1062 When the function `org-mode' is called interactively in an empty file, this
1063 normally means that the file name does not automatically trigger Org mode.
1064 To ensure that the file will always be in Org mode in the future, a
1065 line enforcing Org mode will be inserted into the buffer, if this option
1066 has been set."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-replace-disputed-keys nil
1071 "Non-nil means use alternative key bindings for some keys.
1072 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1073 These keys are also used by other packages like shift-selection-mode'
1074 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1075 If you want to use Org mode together with one of these other modes,
1076 or more generally if you would like to move some Org mode commands to
1077 other keys, set this variable and configure the keys with the variable
1078 `org-disputed-keys'.
1080 This option is only relevant at load-time of Org mode, and must be set
1081 *before* org.el is loaded. Changing it requires a restart of Emacs to
1082 become effective."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defcustom org-use-extra-keys nil
1087 "Non-nil means use extra key sequence definitions for certain commands.
1088 This happens automatically if `window-system' is nil. This
1089 variable lets you do the same manually. You must set it before
1090 loading Org."
1091 :group 'org-startup
1092 :type 'boolean)
1094 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1096 (defcustom org-disputed-keys
1097 '(([(shift up)] . [(meta p)])
1098 ([(shift down)] . [(meta n)])
1099 ([(shift left)] . [(meta -)])
1100 ([(shift right)] . [(meta +)])
1101 ([(control shift right)] . [(meta shift +)])
1102 ([(control shift left)] . [(meta shift -)]))
1103 "Keys for which Org mode and other modes compete.
1104 This is an alist, cars are the default keys, second element specifies
1105 the alternative to use when `org-replace-disputed-keys' is t.
1107 Keys can be specified in any syntax supported by `define-key'.
1108 The value of this option takes effect only at Org mode startup,
1109 therefore you'll have to restart Emacs to apply it after changing."
1110 :group 'org-startup
1111 :type 'alist)
1113 (defun org-key (key)
1114 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1115 Or return the original if not disputed."
1116 (when org-replace-disputed-keys
1117 (let* ((nkey (key-description key))
1118 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1119 org-disputed-keys)))
1120 (setq key (if x (cdr x) key))))
1121 key)
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org mode outline.
1130 When nil, just use the standard three dots. When a non-empty string,
1131 use that string instead.
1133 The change affects only Org mode (which will then use its own display table).
1134 Changing this requires executing `\\[org-mode]' in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (string :tag "String" :value "...#"))
1139 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1141 (defvar org-display-table nil
1142 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defcustom org-show-context-detail '((agenda . local)
1168 (bookmark-jump . lineage)
1169 (isearch . lineage)
1170 (default . ancestors))
1171 "Alist between context and visibility span when revealing a location.
1173 \\<org-mode-map>Some actions may move point into invisible
1174 locations. As a consequence, Org always expose a neighborhood
1175 around point. How much is shown depends on the initial action,
1176 or context. Valid contexts are
1178 agenda when exposing an entry from the agenda
1179 org-goto when using the command `org-goto' (`\\[org-goto]')
1180 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1181 tags-tree when constructing a sparse tree based on tags matches
1182 link-search when exposing search matches associated with a link
1183 mark-goto when exposing the jump goal of a mark
1184 bookmark-jump when exposing a bookmark location
1185 isearch when exiting from an incremental search
1186 default default for all contexts not set explicitly
1188 Allowed visibility spans are
1190 minimal show current headline; if point is not on headline,
1191 also show entry
1193 local show current headline, entry and next headline
1195 ancestors show current headline and its direct ancestors; if
1196 point is not on headline, also show entry
1198 lineage show current headline, its direct ancestors and all
1199 their children; if point is not on headline, also show
1200 entry and first child
1202 tree show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and all children
1206 canonical show current headline, its direct ancestors along with
1207 their entries and children; if point is not located on
1208 the headline, also show current entry and all children
1210 As special cases, a nil or t value means show all contexts in
1211 `minimal' or `canonical' view, respectively.
1213 Some views can make displayed information very compact, but also
1214 make it harder to edit the location of the match. In such
1215 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1216 more context."
1217 :group 'org-reveal-location
1218 :version "26.1"
1219 :package-version '(Org . "9.0")
1220 :type '(choice
1221 (const :tag "Canonical" t)
1222 (const :tag "Minimal" nil)
1223 (repeat :greedy t :tag "Individual contexts"
1224 (cons
1225 (choice :tag "Context"
1226 (const agenda)
1227 (const org-goto)
1228 (const occur-tree)
1229 (const tags-tree)
1230 (const link-search)
1231 (const mark-goto)
1232 (const bookmark-jump)
1233 (const isearch)
1234 (const default))
1235 (choice :tag "Detail level"
1236 (const minimal)
1237 (const local)
1238 (const ancestors)
1239 (const lineage)
1240 (const tree)
1241 (const canonical))))))
1243 (defcustom org-indirect-buffer-display 'other-window
1244 "How should indirect tree buffers be displayed?
1246 This applies to indirect buffers created with the commands
1247 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1249 Valid values are:
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group 'org-structure
1257 :group 'org-agenda-windows
1258 :type '(choice
1259 (const :tag "In current window" current-window)
1260 (const :tag "In current frame, other window" other-window)
1261 (const :tag "Each time a new frame" new-frame)
1262 (const :tag "One dedicated frame" dedicated-frame)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group 'org-structure
1275 :type '(choice
1276 (const :tag "Never" nil)
1277 (const :tag "At beginning of headline stars" t)
1278 (function)))
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group 'org-structure
1293 :type '(repeat :value ("k" . ignore)
1294 (choice :value ("k" . ignore)
1295 (list :tag "Descriptive Headline" (string :tag "Headline"))
1296 (cons :tag "Letter and Command"
1297 (string :tag "Command letter")
1298 (choice
1299 (function)
1300 (sexp))))))
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture "org-capture-last-stored"
1304 :last-refile "org-refile-last-stored"
1305 :last-capture-marker "org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1309 :last-capture
1310 :last-capture-marker
1311 :last-refile
1312 When a key does not show up in the property list, the corresponding bookmark
1313 is not set."
1314 :group 'org-structure
1315 :type 'plist)
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org mode."
1319 :tag "Org Cycle"
1320 :group 'org-structure)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1324 :group 'org-cycle
1325 :type 'boolean)
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1336 than its value."
1337 :group 'org-cycle
1338 :type '(choice
1339 (const :tag "No limit" nil)
1340 (integer :tag "Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1348 :group 'org-startup
1349 :group 'org-cycle
1350 :type 'boolean)
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1355 This makes it possible to do global cycling without having to use `S-TAB'
1356 or `\\[universal-argument] TAB'. For this special case to work, the first \
1357 line of the buffer
1358 must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer.
1363 When this option is nil, don't do anything special at the beginning of
1364 the buffer."
1365 :group 'org-cycle
1366 :type 'boolean)
1368 (defcustom org-cycle-level-after-item/entry-creation t
1369 "Non-nil means cycle entry level or item indentation in new empty entries.
1371 When the cursor is at the end of an empty headline, i.e., with only stars
1372 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1373 and then all possible ancestor states, before returning to the original state.
1374 This makes data entry extremely fast: M-RET to create a new headline,
1375 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1377 When the cursor is at the end of an empty plain list item, one TAB will
1378 make it a subitem, two or more tabs will back up to make this an item
1379 higher up in the item hierarchy."
1380 :group 'org-cycle
1381 :type 'boolean)
1383 (defcustom org-cycle-emulate-tab t
1384 "Where should `org-cycle' emulate TAB.
1385 nil Never
1386 white Only in completely white lines
1387 whitestart Only at the beginning of lines, before the first non-white char
1388 t Everywhere except in headlines
1389 exc-hl-bol Everywhere except at the start of a headline
1390 If TAB is used in a place where it does not emulate TAB, the current subtree
1391 visibility is cycled."
1392 :group 'org-cycle
1393 :type '(choice (const :tag "Never" nil)
1394 (const :tag "Only in completely white lines" white)
1395 (const :tag "Before first char in a line" whitestart)
1396 (const :tag "Everywhere except in headlines" t)
1397 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1399 (defcustom org-cycle-separator-lines 2
1400 "Number of empty lines needed to keep an empty line between collapsed trees.
1401 If you leave an empty line between the end of a subtree and the following
1402 headline, this empty line is hidden when the subtree is folded.
1403 Org mode will leave (exactly) one empty line visible if the number of
1404 empty lines is equal or larger to the number given in this variable.
1405 So the default 2 means at least 2 empty lines after the end of a subtree
1406 are needed to produce free space between a collapsed subtree and the
1407 following headline.
1409 If the number is negative, and the number of empty lines is at least -N,
1410 all empty lines are shown.
1412 Special case: when 0, never leave empty lines in collapsed view."
1413 :group 'org-cycle
1414 :type 'integer)
1415 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1417 (defcustom org-pre-cycle-hook nil
1418 "Hook that is run before visibility cycling is happening.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that will be set right after running this hook. The
1421 argument is a symbol. Before a global state change, it can have the values
1422 `overview', `content', or `all'. Before a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook)
1427 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1428 org-cycle-hide-drawers
1429 org-cycle-show-empty-lines
1430 org-optimize-window-after-visibility-change)
1431 "Hook that is run after `org-cycle' has changed the buffer visibility.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that was set by the most recent `org-cycle' command. The
1434 argument is a symbol. After a global state change, it can have the values
1435 `overview', `contents', or `all'. After a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook
1439 :version "26.1"
1440 :package-version '(Org . "8.3"))
1442 (defgroup org-edit-structure nil
1443 "Options concerning structure editing in Org mode."
1444 :tag "Org Edit Structure"
1445 :group 'org-structure)
1447 (defcustom org-odd-levels-only nil
1448 "Non-nil means skip even levels and only use odd levels for the outline.
1449 This has the effect that two stars are being added/taken away in
1450 promotion/demotion commands. It also influences how levels are
1451 handled by the exporters.
1452 Changing it requires restart of `font-lock-mode' to become effective
1453 for fontification also in regions already fontified.
1454 You may also set this on a per-file basis by adding one of the following
1455 lines to the buffer:
1457 #+STARTUP: odd
1458 #+STARTUP: oddeven"
1459 :group 'org-edit-structure
1460 :group 'org-appearance
1461 :type 'boolean)
1463 (defcustom org-adapt-indentation t
1464 "Non-nil means adapt indentation to outline node level.
1466 When this variable is set, Org assumes that you write outlines by
1467 indenting text in each node to align with the headline (after the
1468 stars). The following issues are influenced by this variable:
1470 - The indentation is increased by one space in a demotion
1471 command, and decreased by one in a promotion command. However,
1472 in the latter case, if shifting some line in the entry body
1473 would alter document structure (e.g., insert a new headline),
1474 indentation is not changed at all.
1476 - Property drawers and planning information is inserted indented
1477 when this variable is set. When nil, they will not be indented.
1479 - TAB indents a line relative to current level. The lines below
1480 a headline will be indented when this variable is set.
1482 Note that this is all about true indentation, by adding and
1483 removing space characters. See also `org-indent.el' which does
1484 level-dependent indentation in a virtual way, i.e. at display
1485 time in Emacs."
1486 :group 'org-edit-structure
1487 :type 'boolean)
1489 (defcustom org-special-ctrl-a/e nil
1490 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1492 When t, `C-a' will bring back the cursor to the beginning of the
1493 headline text, i.e. after the stars and after a possible TODO
1494 keyword. In an item, this will be the position after bullet and
1495 check-box, if any. When the cursor is already at that position,
1496 another `C-a' will bring it to the beginning of the line.
1498 `C-e' will jump to the end of the headline, ignoring the presence
1499 of tags in the headline. A second `C-e' will then jump to the
1500 true end of the line, after any tags. This also means that, when
1501 this variable is non-nil, `C-e' also will never jump beyond the
1502 end of the heading of a folded section, i.e. not after the
1503 ellipses.
1505 When set to the symbol `reversed', the first `C-a' or `C-e' works
1506 normally, going to the true line boundary first. Only a directly
1507 following, identical keypress will bring the cursor to the
1508 special positions.
1510 This may also be a cons cell where the behavior for `C-a' and
1511 `C-e' is set separately."
1512 :group 'org-edit-structure
1513 :type '(choice
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet and before tags first" t)
1516 (const :tag "reversed: true line boundary first" reversed)
1517 (cons :tag "Set C-a and C-e separately"
1518 (choice :tag "Special C-a"
1519 (const :tag "off" nil)
1520 (const :tag "on: after stars/bullet first" t)
1521 (const :tag "reversed: before stars/bullet first" reversed))
1522 (choice :tag "Special C-e"
1523 (const :tag "off" nil)
1524 (const :tag "on: before tags first" t)
1525 (const :tag "reversed: after tags first" reversed)))))
1526 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1528 (defcustom org-special-ctrl-k nil
1529 "Non-nil means `C-k' will behave specially in headlines.
1530 When nil, `C-k' will call the default `kill-line' command.
1531 When t, the following will happen while the cursor is in the headline:
1533 - When the cursor is at the beginning of a headline, kill the entire
1534 line and possible the folded subtree below the line.
1535 - When in the middle of the headline text, kill the headline up to the tags.
1536 - When after the headline text, kill the tags."
1537 :group 'org-edit-structure
1538 :type 'boolean)
1540 (defcustom org-ctrl-k-protect-subtree nil
1541 "Non-nil means, do not delete a hidden subtree with C-k.
1542 When set to the symbol `error', simply throw an error when C-k is
1543 used to kill (part-of) a headline that has hidden text behind it.
1544 Any other non-nil value will result in a query to the user, if it is
1545 OK to kill that hidden subtree. When nil, kill without remorse."
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not protect hidden subtrees" nil)
1550 (const :tag "Protect hidden subtrees with a security query" t)
1551 (const :tag "Never kill a hidden subtree with C-k" error)))
1553 (defcustom org-special-ctrl-o t
1554 "Non-nil means, make `C-o' insert a row in tables."
1555 :group 'org-edit-structure
1556 :type 'boolean)
1558 (defcustom org-catch-invisible-edits nil
1559 "Check if in invisible region before inserting or deleting a character.
1560 Valid values are:
1562 nil Do not check, so just do invisible edits.
1563 error Throw an error and do nothing.
1564 show Make point visible, and do the requested edit.
1565 show-and-error Make point visible, then throw an error and abort the edit.
1566 smart Make point visible, and do insertion/deletion if it is
1567 adjacent to visible text and the change feels predictable.
1568 Never delete a previously invisible character or add in the
1569 middle or right after an invisible region. Basically, this
1570 allows insertion and backward-delete right before ellipses.
1571 FIXME: maybe in this case we should not even show?"
1572 :group 'org-edit-structure
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Do not check" nil)
1576 (const :tag "Throw error when trying to edit" error)
1577 (const :tag "Unhide, but do not do the edit" show-and-error)
1578 (const :tag "Show invisible part and do the edit" show)
1579 (const :tag "Be smart and do the right thing" smart)))
1581 (defcustom org-yank-folded-subtrees t
1582 "Non-nil means when yanking subtrees, fold them.
1583 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1584 it starts with a heading and all other headings in it are either children
1585 or siblings, then fold all the subtrees. However, do this only if no
1586 text after the yank would be swallowed into a folded tree by this action."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-yank-adjusted-subtrees nil
1591 "Non-nil means when yanking subtrees, adjust the level.
1592 With this setting, `org-paste-subtree' is used to insert the subtree, see
1593 this function for details."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-M-RET-may-split-line '((default . t))
1598 "Non-nil means M-RET will split the line at the cursor position.
1599 When nil, it will go to the end of the line before making a
1600 new line.
1601 You may also set this option in a different way for different
1602 contexts. Valid contexts are:
1604 headline when creating a new headline
1605 item when creating a new item
1606 table in a table field
1607 default the value to be used for all contexts not explicitly
1608 customized"
1609 :group 'org-structure
1610 :group 'org-table
1611 :type '(choice
1612 (const :tag "Always" t)
1613 (const :tag "Never" nil)
1614 (repeat :greedy t :tag "Individual contexts"
1615 (cons
1616 (choice :tag "Context"
1617 (const headline)
1618 (const item)
1619 (const table)
1620 (const default))
1621 (boolean)))))
1624 (defcustom org-insert-heading-respect-content nil
1625 "Non-nil means insert new headings after the current subtree.
1626 \\<org-mode-map>
1627 When nil, the new heading is created directly after the current line.
1628 The commands `\\[org-insert-heading-respect-content]' and \
1629 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1630 for the duration of the command."
1631 :group 'org-structure
1632 :type 'boolean)
1634 (defcustom org-blank-before-new-entry '((heading . auto)
1635 (plain-list-item . auto))
1636 "Should `org-insert-heading' leave a blank line before new heading/item?
1637 The value is an alist, with `heading' and `plain-list-item' as CAR,
1638 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1639 which case Org will look at the surrounding headings/items and try to
1640 make an intelligent decision whether to insert a blank line or not."
1641 :group 'org-edit-structure
1642 :type '(list
1643 (cons (const heading)
1644 (choice (const :tag "Never" nil)
1645 (const :tag "Always" t)
1646 (const :tag "Auto" auto)))
1647 (cons (const plain-list-item)
1648 (choice (const :tag "Never" nil)
1649 (const :tag "Always" t)
1650 (const :tag "Auto" auto)))))
1652 (defcustom org-insert-heading-hook nil
1653 "Hook being run after inserting a new heading."
1654 :group 'org-edit-structure
1655 :type 'hook)
1657 (defcustom org-enable-fixed-width-editor t
1658 "Non-nil means lines starting with \":\" are treated as fixed-width.
1659 This currently only means they are never auto-wrapped.
1660 When nil, such lines will be treated like ordinary lines."
1661 :group 'org-edit-structure
1662 :type 'boolean)
1664 (defcustom org-goto-auto-isearch t
1665 "Non-nil means typing characters in `org-goto' starts incremental search.
1666 When nil, you can use these keybindings to navigate the buffer:
1668 q Quit the org-goto interface
1669 n Go to the next visible heading
1670 p Go to the previous visible heading
1671 f Go one heading forward on same level
1672 b Go one heading backward on same level
1673 u Go one heading up"
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defgroup org-sparse-trees nil
1678 "Options concerning sparse trees in Org mode."
1679 :tag "Org Sparse Trees"
1680 :group 'org-structure)
1682 (defcustom org-highlight-sparse-tree-matches t
1683 "Non-nil means highlight all matches that define a sparse tree.
1684 The highlights will automatically disappear the next time the buffer is
1685 changed by an edit command."
1686 :group 'org-sparse-trees
1687 :type 'boolean)
1689 (defcustom org-remove-highlights-with-change t
1690 "Non-nil means any change to the buffer will remove temporary highlights.
1691 \\<org-mode-map>\
1692 Such highlights are created by `org-occur' and `org-clock-display'.
1693 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1694 to get rid of the highlights.
1695 The highlights created by `org-toggle-latex-fragment' always need
1696 `\\[org-toggle-latex-fragment]' to be removed."
1697 :group 'org-sparse-trees
1698 :group 'org-time
1699 :type 'boolean)
1701 (defcustom org-occur-case-fold-search t
1702 "Non-nil means `org-occur' should be case-insensitive.
1703 If set to `smart' the search will be case-insensitive only if it
1704 doesn't specify any upper case character."
1705 :group 'org-sparse-trees
1706 :version "26.1"
1707 :type '(choice
1708 (const :tag "Case-sensitive" nil)
1709 (const :tag "Case-insensitive" t)
1710 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1712 (defcustom org-occur-hook '(org-first-headline-recenter)
1713 "Hook that is run after `org-occur' has constructed a sparse tree.
1714 This can be used to recenter the window to show as much of the structure
1715 as possible."
1716 :group 'org-sparse-trees
1717 :type 'hook)
1719 (defgroup org-imenu-and-speedbar nil
1720 "Options concerning imenu and speedbar in Org mode."
1721 :tag "Org Imenu and Speedbar"
1722 :group 'org-structure)
1724 (defcustom org-imenu-depth 2
1725 "The maximum level for Imenu access to Org headlines.
1726 This also applied for speedbar access."
1727 :group 'org-imenu-and-speedbar
1728 :type 'integer)
1730 (defgroup org-table nil
1731 "Options concerning tables in Org mode."
1732 :tag "Org Table"
1733 :group 'org)
1735 (defcustom org-enable-table-editor 'optimized
1736 "Non-nil means lines starting with \"|\" are handled by the table editor.
1737 When nil, such lines will be treated like ordinary lines.
1739 When equal to the symbol `optimized', the table editor will be optimized to
1740 do the following:
1741 - Automatic overwrite mode in front of whitespace in table fields.
1742 This makes the structure of the table stay in tact as long as the edited
1743 field does not exceed the column width.
1744 - Minimize the number of realigns. Normally, the table is aligned each time
1745 TAB or RET are pressed to move to another field. With optimization this
1746 happens only if changes to a field might have changed the column width.
1747 Optimization requires replacing the functions `self-insert-command',
1748 `delete-char', and `backward-delete-char' in Org buffers, with a
1749 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1750 good at guessing when a re-align will be necessary, but you can always
1751 force one with `\\[org-ctrl-c-ctrl-c]'.
1753 If you would like to use the optimized version in Org mode, but the
1754 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1756 This variable can be used to turn on and off the table editor during a session,
1757 but in order to toggle optimization, a restart is required.
1759 See also the variable `org-table-auto-blank-field'."
1760 :group 'org-table
1761 :type '(choice
1762 (const :tag "off" nil)
1763 (const :tag "on" t)
1764 (const :tag "on, optimized" optimized)))
1766 (defcustom org-self-insert-cluster-for-undo nil
1767 "Non-nil means cluster self-insert commands for undo when possible.
1768 If this is set, then, like in the Emacs command loop, 20 consecutive
1769 characters will be undone together.
1770 This is configurable, because there is some impact on typing performance."
1771 :group 'org-table
1772 :type 'boolean)
1774 (defcustom org-table-tab-recognizes-table.el t
1775 "Non-nil means TAB will automatically notice a table.el table.
1776 When it sees such a table, it moves point into it and - if necessary -
1777 calls `table-recognize-table'."
1778 :group 'org-table-editing
1779 :type 'boolean)
1781 (defgroup org-link nil
1782 "Options concerning links in Org mode."
1783 :tag "Org Link"
1784 :group 'org)
1786 (defvar-local org-link-abbrev-alist-local nil
1787 "Buffer-local version of `org-link-abbrev-alist', which see.
1788 The value of this is taken from the #+LINK lines.")
1790 (defcustom org-link-parameters
1791 '(("doi" :follow org--open-doi-link)
1792 ("elisp" :follow org--open-elisp-link)
1793 ("file" :complete org-file-complete-link)
1794 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1795 ("help" :follow org--open-help-link)
1796 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1797 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1798 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1799 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1800 ("shell" :follow org--open-shell-link))
1801 "An alist of properties that defines all the links in Org mode.
1802 The key in each association is a string of the link type.
1803 Subsequent optional elements make up a p-list of link properties.
1805 :follow - A function that takes the link path as an argument.
1807 :export - A function that takes the link path, description and
1808 export-backend as arguments.
1810 :store - A function responsible for storing the link. See the
1811 function `org-store-link-functions'.
1813 :complete - A function that inserts a link with completion. The
1814 function takes one optional prefix arg.
1816 :face - A face for the link, or a function that returns a face.
1817 The function takes one argument which is the link path. The
1818 default face is `org-link'.
1820 :mouse-face - The mouse-face. The default is `highlight'.
1822 :display - `full' will not fold the link in descriptive
1823 display. Default is `org-link'.
1825 :help-echo - A string or function that takes (window object position)
1826 as arguments and returns a string.
1828 :keymap - A keymap that is active on the link. The default is
1829 `org-mouse-map'.
1831 :htmlize-link - A function for the htmlize-link. Defaults
1832 to (list :uri \"type:path\")
1834 :activate-func - A function to run at the end of font-lock
1835 activation. The function must accept (link-start link-end path bracketp)
1836 as arguments."
1837 :group 'org-link
1838 :type '(alist :tag "Link display parameters"
1839 :value-type plist)
1840 :version "26.1"
1841 :package-version '(Org . "9.1"))
1843 (defun org-link-get-parameter (type key)
1844 "Get TYPE link property for KEY.
1845 TYPE is a string and KEY is a plist keyword."
1846 (plist-get
1847 (cdr (assoc type org-link-parameters))
1848 key))
1850 (defun org-link-set-parameters (type &rest parameters)
1851 "Set link TYPE properties to PARAMETERS.
1852 PARAMETERS should be :key val pairs."
1853 (let ((data (assoc type org-link-parameters)))
1854 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1855 (push (cons type parameters) org-link-parameters)
1856 (org-make-link-regexps)
1857 (org-element-update-syntax))))
1859 (defun org-link-types ()
1860 "Return a list of known link types."
1861 (mapcar #'car org-link-parameters))
1863 (defcustom org-link-abbrev-alist nil
1864 "Alist of link abbreviations.
1865 The car of each element is a string, to be replaced at the start of a link.
1866 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1867 links in Org buffers can have an optional tag after a double colon, e.g.,
1869 [[linkkey:tag][description]]
1871 The `linkkey' must be a single word, starting with a letter, followed
1872 by letters, numbers, `-' or `_'.
1874 If REPLACE is a string, the tag will simply be appended to create the link.
1875 If the string contains \"%s\", the tag will be inserted there. If the string
1876 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1877 at that point (see the function `url-hexify-string'). If the string contains
1878 the specifier \"%(my-function)\", then the custom function `my-function' will
1879 be invoked: this function takes the tag as its only argument and must return
1880 a string.
1882 REPLACE may also be a function that will be called with the tag as the
1883 only argument to create the link, which should be returned as a string.
1885 See the manual for examples."
1886 :group 'org-link
1887 :type '(repeat
1888 (cons
1889 (string :tag "Protocol")
1890 (choice
1891 (string :tag "Format")
1892 (function)))))
1894 (defcustom org-descriptive-links t
1895 "Non-nil means Org will display descriptive links.
1896 E.g. [[http://orgmode.org][Org website]] will be displayed as
1897 \"Org Website\", hiding the link itself and just displaying its
1898 description. When set to nil, Org will display the full links
1899 literally.
1901 You can interactively set the value of this variable by calling
1902 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1903 :group 'org-link
1904 :type 'boolean)
1906 (defcustom org-link-file-path-type 'adaptive
1907 "How the path name in file links should be stored.
1908 Valid values are:
1910 relative Relative to the current directory, i.e. the directory of the file
1911 into which the link is being inserted.
1912 absolute Absolute path, if possible with ~ for home directory.
1913 noabbrev Absolute path, no abbreviation of home directory.
1914 adaptive Use relative path for files in the current directory and sub-
1915 directories of it. For other files, use an absolute path."
1916 :group 'org-link
1917 :type '(choice
1918 (const relative)
1919 (const absolute)
1920 (const noabbrev)
1921 (const adaptive)))
1923 (defvaralias 'org-activate-links 'org-highlight-links)
1924 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1925 "Types of links that should be highlighted in Org files.
1927 This is a list of symbols, each one of them leading to the
1928 highlighting of a certain link type.
1930 You can still open links that are not highlighted.
1932 In principle, it does not hurt to turn on highlighting for all
1933 link types. There may be a small gain when turning off unused
1934 link types. The types are:
1936 bracket The recommended [[link][description]] or [[link]] links with hiding.
1937 angle Links in angular brackets that may contain whitespace like
1938 <bbdb:Carsten Dominik>.
1939 plain Plain links in normal text, no whitespace, like http://google.com.
1940 radio Text that is matched by a radio target, see manual for details.
1941 tag Tag settings in a headline (link to tag search).
1942 date Time stamps (link to calendar).
1943 footnote Footnote labels.
1945 If you set this variable during an Emacs session, use `org-mode-restart'
1946 in the Org buffer so that the change takes effect."
1947 :group 'org-link
1948 :group 'org-appearance
1949 :type '(set :greedy t
1950 (const :tag "Double bracket links" bracket)
1951 (const :tag "Angular bracket links" angle)
1952 (const :tag "Plain text links" plain)
1953 (const :tag "Radio target matches" radio)
1954 (const :tag "Tags" tag)
1955 (const :tag "Timestamps" date)
1956 (const :tag "Footnotes" footnote)))
1958 (defcustom org-make-link-description-function nil
1959 "Function to use for generating link descriptions from links.
1960 When nil, the link location will be used. This function must take
1961 two parameters: the first one is the link, the second one is the
1962 description generated by `org-insert-link'. The function should
1963 return the description to use."
1964 :group 'org-link
1965 :type '(choice (const nil) (function)))
1967 (defgroup org-link-store nil
1968 "Options concerning storing links in Org mode."
1969 :tag "Org Store Link"
1970 :group 'org-link)
1972 (defcustom org-url-hexify-p t
1973 "When non-nil, hexify URL when creating a link."
1974 :type 'boolean
1975 :version "24.3"
1976 :group 'org-link-store)
1978 (defcustom org-email-link-description-format "Email %c: %.30s"
1979 "Format of the description part of a link to an email or usenet message.
1980 The following %-escapes will be replaced by corresponding information:
1982 %F full \"From\" field
1983 %f name, taken from \"From\" field, address if no name
1984 %T full \"To\" field
1985 %t first name in \"To\" field, address if no name
1986 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1987 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1988 %s subject
1989 %d date
1990 %m message-id.
1992 You may use normal field width specification between the % and the letter.
1993 This is for example useful to limit the length of the subject.
1995 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1996 :group 'org-link-store
1997 :type 'string)
1999 (defcustom org-from-is-user-regexp
2000 (let (r1 r2)
2001 (when (and user-mail-address (not (string= user-mail-address "")))
2002 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
2003 (when (and user-full-name (not (string= user-full-name "")))
2004 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2005 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2006 "Regexp matched against the \"From:\" header of an email or usenet message.
2007 It should match if the message is from the user him/herself."
2008 :group 'org-link-store
2009 :type 'regexp)
2011 (defcustom org-context-in-file-links t
2012 "Non-nil means file links from `org-store-link' contain context.
2013 \\<org-mode-map>
2014 A search string will be added to the file name with :: as separator
2015 and used to find the context when the link is activated by the command
2016 `org-open-at-point'. When this option is t, the entire active region
2017 will be placed in the search string of the file link. If set to a
2018 positive integer, only the first n lines of context will be stored.
2020 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2021 \\[org-store-link]')
2022 negates this setting for the duration of the command."
2023 :group 'org-link-store
2024 :type '(choice boolean integer))
2026 (defcustom org-keep-stored-link-after-insertion nil
2027 "Non-nil means keep link in list for entire session.
2028 \\<org-mode-map>
2029 The command `org-store-link' adds a link pointing to the current
2030 location to an internal list. These links accumulate during a session.
2031 The command `org-insert-link' can be used to insert links into any
2032 Org file (offering completion for all stored links).
2034 When this option is nil, every link which has been inserted once using
2035 `\\[org-insert-link]' will be removed from the list, to make completing the \
2036 unused
2037 links more efficient."
2038 :group 'org-link-store
2039 :type 'boolean)
2041 (defgroup org-link-follow nil
2042 "Options concerning following links in Org mode."
2043 :tag "Org Follow Link"
2044 :group 'org-link)
2046 (defcustom org-link-translation-function nil
2047 "Function to translate links with different syntax to Org syntax.
2048 This can be used to translate links created for example by the Planner
2049 or emacs-wiki packages to Org syntax.
2050 The function must accept two parameters, a TYPE containing the link
2051 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2052 which is everything after the link protocol. It should return a cons
2053 with possibly modified values of type and path.
2054 Org contains a function for this, so if you set this variable to
2055 `org-translate-link-from-planner', you should be able follow many
2056 links created by planner."
2057 :group 'org-link-follow
2058 :type '(choice (const nil) (function)))
2060 (defcustom org-follow-link-hook nil
2061 "Hook that is run after a link has been followed."
2062 :group 'org-link-follow
2063 :type 'hook)
2065 (defcustom org-tab-follows-link nil
2066 "Non-nil means on links TAB will follow the link.
2067 Needs to be set before org.el is loaded.
2068 This really should not be used, it does not make sense, and the
2069 implementation is bad."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-return-follows-link nil
2074 "Non-nil means on links RET will follow the link.
2075 In tables, the special behavior of RET has precedence."
2076 :group 'org-link-follow
2077 :type 'boolean)
2079 (defcustom org-mouse-1-follows-link
2080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2081 "Non-nil means mouse-1 on a link will follow the link.
2082 A longer mouse click will still set point. Needs to be set
2083 before org.el is loaded."
2084 :group 'org-link-follow
2085 :version "24.4"
2086 :package-version '(Org . "8.3")
2087 :type '(choice
2088 (const :tag "A double click follows the link" double)
2089 (const :tag "Unconditionally follow the link with mouse-1" t)
2090 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2092 (defcustom org-mark-ring-length 4
2093 "Number of different positions to be recorded in the ring.
2094 Changing this requires a restart of Emacs to work correctly."
2095 :group 'org-link-follow
2096 :type 'integer)
2098 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2099 "Non-nil means internal fuzzy links can only match headlines.
2101 When nil, the a fuzzy link may point to a target or a named
2102 construct in the document. When set to the special value
2103 `query-to-create', offer to create a new headline when none
2104 matched.
2106 Spaces and statistics cookies are ignored during heading searches."
2107 :group 'org-link-follow
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "Use fuzzy text search" nil)
2111 (const :tag "Match only exact headline" t)
2112 (const :tag "Match exact headline or query to create it"
2113 query-to-create))
2114 :safe #'symbolp)
2116 (defcustom org-link-frame-setup
2117 '((vm . vm-visit-folder-other-frame)
2118 (vm-imap . vm-visit-imap-folder-other-frame)
2119 (gnus . org-gnus-no-new-news)
2120 (file . find-file-other-window)
2121 (wl . wl-other-frame))
2122 "Setup the frame configuration for following links.
2123 When following a link with Emacs, it may often be useful to display
2124 this link in another window or frame. This variable can be used to
2125 set this up for the different types of links.
2126 For VM, use any of
2127 `vm-visit-folder'
2128 `vm-visit-folder-other-window'
2129 `vm-visit-folder-other-frame'
2130 For Gnus, use any of
2131 `gnus'
2132 `gnus-other-frame'
2133 `org-gnus-no-new-news'
2134 For FILE, use any of
2135 `find-file'
2136 `find-file-other-window'
2137 `find-file-other-frame'
2138 For Wanderlust use any of
2139 `wl'
2140 `wl-other-frame'
2141 For the calendar, use the variable `calendar-setup'.
2142 For BBDB, it is currently only possible to display the matches in
2143 another window."
2144 :group 'org-link-follow
2145 :type '(list
2146 (cons (const vm)
2147 (choice
2148 (const vm-visit-folder)
2149 (const vm-visit-folder-other-window)
2150 (const vm-visit-folder-other-frame)))
2151 (cons (const vm-imap)
2152 (choice
2153 (const vm-visit-imap-folder)
2154 (const vm-visit-imap-folder-other-window)
2155 (const vm-visit-imap-folder-other-frame)))
2156 (cons (const gnus)
2157 (choice
2158 (const gnus)
2159 (const gnus-other-frame)
2160 (const org-gnus-no-new-news)))
2161 (cons (const file)
2162 (choice
2163 (const find-file)
2164 (const find-file-other-window)
2165 (const find-file-other-frame)))
2166 (cons (const wl)
2167 (choice
2168 (const wl)
2169 (const wl-other-frame)))))
2171 (defcustom org-display-internal-link-with-indirect-buffer nil
2172 "Non-nil means use indirect buffer to display infile links.
2173 Activating internal links (from one location in a file to another location
2174 in the same file) normally just jumps to the location. When the link is
2175 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2176 is displayed in
2177 another window. When this option is set, the other window actually displays
2178 an indirect buffer clone of the current buffer, to avoid any visibility
2179 changes to the current buffer."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-non-existing-files nil
2184 "Non-nil means `org-open-file' will open non-existing files.
2185 When nil, an error will be generated.
2186 This variable applies only to external applications because they
2187 might choke on non-existing files. If the link is to a file that
2188 will be opened in Emacs, the variable is ignored."
2189 :group 'org-link-follow
2190 :type 'boolean)
2192 (defcustom org-open-directory-means-index-dot-org nil
2193 "Non-nil means a link to a directory really means to index.org.
2194 When nil, following a directory link will run dired or open a finder/explorer
2195 window on that directory."
2196 :group 'org-link-follow
2197 :type 'boolean)
2199 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2200 "Non-nil means ask for confirmation before executing shell links.
2201 Shell links can be dangerous: just think about a link
2203 [[shell:rm -rf ~/*][Google Search]]
2205 This link would show up in your Org document as \"Google Search\",
2206 but really it would remove your entire home directory.
2207 Therefore we advise against setting this variable to nil.
2208 Just change it to `y-or-n-p' if you want to confirm with a
2209 single keystroke rather than having to type \"yes\"."
2210 :group 'org-link-follow
2211 :type '(choice
2212 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2213 (const :tag "with y-or-n (faster)" y-or-n-p)
2214 (const :tag "no confirmation (dangerous)" nil)))
2215 (put 'org-confirm-shell-link-function
2216 'safe-local-variable
2217 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2219 (defcustom org-confirm-shell-link-not-regexp ""
2220 "A regexp to skip confirmation for shell links."
2221 :group 'org-link-follow
2222 :version "24.1"
2223 :type 'regexp)
2225 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2226 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2227 Elisp links can be dangerous: just think about a link
2229 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2231 This link would show up in your Org document as \"Google Search\",
2232 but really it would remove your entire home directory.
2233 Therefore we advise against setting this variable to nil.
2234 Just change it to `y-or-n-p' if you want to confirm with a
2235 single keystroke rather than having to type \"yes\"."
2236 :group 'org-link-follow
2237 :type '(choice
2238 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2239 (const :tag "with y-or-n (faster)" y-or-n-p)
2240 (const :tag "no confirmation (dangerous)" nil)))
2241 (put 'org-confirm-shell-link-function
2242 'safe-local-variable
2243 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2245 (defcustom org-confirm-elisp-link-not-regexp ""
2246 "A regexp to skip confirmation for Elisp links."
2247 :group 'org-link-follow
2248 :version "24.1"
2249 :type 'regexp)
2251 (defconst org-file-apps-defaults-gnu
2252 '((remote . emacs)
2253 (system . mailcap)
2254 (t . mailcap))
2255 "Default file applications on a UNIX or GNU/Linux system.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-macosx
2259 '((remote . emacs)
2260 (system . "open %s")
2261 ("ps.gz" . "gv %s")
2262 ("eps.gz" . "gv %s")
2263 ("dvi" . "xdvi %s")
2264 ("fig" . "xfig %s")
2265 (t . "open %s"))
2266 "Default file applications on a macOS system.
2267 The system \"open\" is known as a default, but we use X11 applications
2268 for some files for which the OS does not have a good default.
2269 See `org-file-apps'.")
2271 (defconst org-file-apps-defaults-windowsnt
2272 (list '(remote . emacs)
2273 (cons 'system (lambda (file _path)
2274 (with-no-warnings (w32-shell-execute "open" file))))
2275 (cons t (lambda (file _path)
2276 (with-no-warnings (w32-shell-execute "open" file)))))
2277 "Default file applications on a Windows NT system.
2278 The system \"open\" is used for most files.
2279 See `org-file-apps'.")
2281 (defcustom org-file-apps
2282 '((auto-mode . emacs)
2283 ("\\.mm\\'" . default)
2284 ("\\.x?html?\\'" . default)
2285 ("\\.pdf\\'" . default))
2286 "External applications for opening `file:path' items in a document.
2287 \\<org-mode-map>\
2289 Org mode uses system defaults for different file types, but
2290 you can use this variable to set the application for a given file
2291 extension. The entries in this list are cons cells where the car identifies
2292 files and the cdr the corresponding command.
2294 Possible values for the file identifier are:
2296 \"string\" A string as a file identifier can be interpreted in different
2297 ways, depending on its contents:
2299 - Alphanumeric characters only:
2300 Match links with this file extension.
2301 Example: (\"pdf\" . \"evince %s\")
2302 to open PDFs with evince.
2304 - Regular expression: Match links where the
2305 filename matches the regexp. If you want to
2306 use groups here, use shy groups.
2308 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2309 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2310 to open *.html and *.xhtml with firefox.
2312 - Regular expression which contains (non-shy) groups:
2313 Match links where the whole link, including \"::\", and
2314 anything after that, matches the regexp.
2315 In a custom command string, %1, %2, etc. are replaced with
2316 the parts of the link that were matched by the groups.
2317 For backwards compatibility, if a command string is given
2318 that does not use any of the group matches, this case is
2319 handled identically to the second one (i.e. match against
2320 file name only).
2321 In a custom function, you can access the group matches with
2322 (match-string n link).
2324 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2325 \"evince -p %1 %s\")
2326 to open [[file:document.pdf::5]] with evince at page 5.
2328 `directory' Matches a directory
2329 `remote' Matches a remote file, accessible through tramp or efs.
2330 Remote files most likely should be visited through Emacs
2331 because external applications cannot handle such paths.
2332 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2333 so all files Emacs knows how to handle. Using this with
2334 command `emacs' will open most files in Emacs. Beware that this
2335 will also open html files inside Emacs, unless you add
2336 (\"html\" . default) to the list as well.
2337 `system' The system command to open files, like `open' on Windows
2338 and macOS, and mailcap under GNU/Linux. This is the command
2339 that will be selected if you call `org-open-at-point' with a
2340 double prefix argument (`\\[universal-argument] \
2341 \\[universal-argument] \\[org-open-at-point]').
2342 t Default for files not matched by any of the other options.
2344 Possible values for the command are:
2346 `emacs' The file will be visited by the current Emacs process.
2347 `default' Use the default application for this file type, which is the
2348 association for t in the list, most likely in the system-specific
2349 part. This can be used to overrule an unwanted setting in the
2350 system-specific variable.
2351 `system' Use the system command for opening files, like \"open\".
2352 This command is specified by the entry whose car is `system'.
2353 Most likely, the system-specific version of this variable
2354 does define this command, but you can overrule/replace it
2355 here.
2356 `mailcap' Use command specified in the mailcaps.
2357 string A command to be executed by a shell; %s will be replaced
2358 by the path to the file.
2359 function A Lisp function, which will be called with two arguments:
2360 the file path and the original link string, without the
2361 \"file:\" prefix.
2363 For more examples, see the system specific constants
2364 `org-file-apps-defaults-macosx'
2365 `org-file-apps-defaults-windowsnt'
2366 `org-file-apps-defaults-gnu'."
2367 :group 'org-link-follow
2368 :type '(repeat
2369 (cons (choice :value ""
2370 (string :tag "Extension")
2371 (const :tag "System command to open files" system)
2372 (const :tag "Default for unrecognized files" t)
2373 (const :tag "Remote file" remote)
2374 (const :tag "Links to a directory" directory)
2375 (const :tag "Any files that have Emacs modes"
2376 auto-mode))
2377 (choice :value ""
2378 (const :tag "Visit with Emacs" emacs)
2379 (const :tag "Use default" default)
2380 (const :tag "Use the system command" system)
2381 (string :tag "Command")
2382 (function :tag "Function")))))
2384 (defcustom org-doi-server-url "http://dx.doi.org/"
2385 "The URL of the DOI server."
2386 :type 'string
2387 :version "24.3"
2388 :group 'org-link-follow)
2390 (defgroup org-refile nil
2391 "Options concerning refiling entries in Org mode."
2392 :tag "Org Refile"
2393 :group 'org)
2395 (defcustom org-directory "~/org"
2396 "Directory with Org files.
2397 This is just a default location to look for Org files. There is no need
2398 at all to put your files into this directory. It is used in the
2399 following situations:
2401 1. When a capture template specifies a target file that is not an
2402 absolute path. The path will then be interpreted relative to
2403 `org-directory'
2404 2. When the value of variable `org-agenda-files' is a single file, any
2405 relative paths in this file will be taken as relative to
2406 `org-directory'."
2407 :group 'org-refile
2408 :group 'org-capture
2409 :type 'directory)
2411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2412 "Default target for storing notes.
2413 Used as a fall back file for org-capture.el, for templates that
2414 do not specify a target file."
2415 :group 'org-refile
2416 :group 'org-capture
2417 :type 'file)
2419 (defcustom org-goto-interface 'outline
2420 "The default interface to be used for `org-goto'.
2421 Allowed values are:
2422 outline The interface shows an outline of the relevant file
2423 and the correct heading is found by moving through
2424 the outline or by searching with incremental search.
2425 outline-path-completion Headlines in the current buffer are offered via
2426 completion. This is the interface also used by
2427 the refile command."
2428 :group 'org-refile
2429 :type '(choice
2430 (const :tag "Outline" outline)
2431 (const :tag "Outline-path-completion" outline-path-completion)))
2433 (defcustom org-goto-max-level 5
2434 "Maximum target level when running `org-goto' with refile interface."
2435 :group 'org-refile
2436 :type 'integer)
2438 (defcustom org-reverse-note-order nil
2439 "Non-nil means store new notes at the beginning of a file or entry.
2440 When nil, new notes will be filed to the end of a file or entry.
2441 This can also be a list with cons cells of regular expressions that
2442 are matched against file names, and values."
2443 :group 'org-capture
2444 :group 'org-refile
2445 :type '(choice
2446 (const :tag "Reverse always" t)
2447 (const :tag "Reverse never" nil)
2448 (repeat :tag "By file name regexp"
2449 (cons regexp boolean))))
2451 (defcustom org-log-refile nil
2452 "Information to record when a task is refiled.
2454 Possible values are:
2456 nil Don't add anything
2457 time Add a time stamp to the task
2458 note Prompt for a note and add it with template `org-log-note-headings'
2460 This option can also be set with on a per-file-basis with
2462 #+STARTUP: nologrefile
2463 #+STARTUP: logrefile
2464 #+STARTUP: lognoterefile
2466 You can have local logging settings for a subtree by setting the LOGGING
2467 property to one or more of these keywords.
2469 When bulk-refiling from the agenda, the value `note' is forbidden and
2470 will temporarily be changed to `time'."
2471 :group 'org-refile
2472 :group 'org-progress
2473 :version "24.1"
2474 :type '(choice
2475 (const :tag "No logging" nil)
2476 (const :tag "Record timestamp" time)
2477 (const :tag "Record timestamp with note." note)))
2479 (defcustom org-refile-targets nil
2480 "Targets for refiling entries with `\\[org-refile]'.
2481 This is a list of cons cells. Each cell contains:
2482 - a specification of the files to be considered, either a list of files,
2483 or a symbol whose function or variable value will be used to retrieve
2484 a file name or a list of file names. If you use `org-agenda-files' for
2485 that, all agenda files will be scanned for targets. Nil means consider
2486 headings in the current buffer.
2487 - A specification of how to find candidate refile targets. This may be
2488 any of:
2489 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2490 This tag has to be present in all target headlines, inheritance will
2491 not be considered.
2492 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2493 todo keyword.
2494 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2495 headlines that are refiling targets.
2496 - a cons cell (:level . N). Any headline of level N is considered a target.
2497 Note that, when `org-odd-levels-only' is set, level corresponds to
2498 order in hierarchy, not to the number of stars.
2499 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2500 Note that, when `org-odd-levels-only' is set, level corresponds to
2501 order in hierarchy, not to the number of stars.
2503 Each element of this list generates a set of possible targets.
2504 The union of these sets is presented (with completion) to
2505 the user by `org-refile'.
2507 You can set the variable `org-refile-target-verify-function' to a function
2508 to verify each headline found by the simple criteria above.
2510 When this variable is nil, all top-level headlines in the current buffer
2511 are used, equivalent to the value `((nil . (:level . 1))'."
2512 :group 'org-refile
2513 :type '(repeat
2514 (cons
2515 (choice :value org-agenda-files
2516 (const :tag "All agenda files" org-agenda-files)
2517 (const :tag "Current buffer" nil)
2518 (function) (variable) (file))
2519 (choice :tag "Identify target headline by"
2520 (cons :tag "Specific tag" (const :value :tag) (string))
2521 (cons :tag "TODO keyword" (const :value :todo) (string))
2522 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2523 (cons :tag "Level number" (const :value :level) (integer))
2524 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2526 (defcustom org-refile-target-verify-function nil
2527 "Function to verify if the headline at point should be a refile target.
2528 The function will be called without arguments, with point at the
2529 beginning of the headline. It should return t and leave point
2530 where it is if the headline is a valid target for refiling.
2532 If the target should not be selected, the function must return nil.
2533 In addition to this, it may move point to a place from where the search
2534 should be continued. For example, the function may decide that the entire
2535 subtree of the current entry should be excluded and move point to the end
2536 of the subtree."
2537 :group 'org-refile
2538 :type '(choice
2539 (const nil)
2540 (function)))
2542 (defcustom org-refile-use-cache nil
2543 "Non-nil means cache refile targets to speed up the process.
2544 \\<org-mode-map>\
2545 The cache for a particular file will be updated automatically when
2546 the buffer has been killed, or when any of the marker used for flagging
2547 refile targets no longer points at a live buffer.
2548 If you have added new entries to a buffer that might themselves be targets,
2549 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2550 if you find that easier, \
2551 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2552 \\[org-refile]'."
2553 :group 'org-refile
2554 :version "24.1"
2555 :type 'boolean)
2557 (defcustom org-refile-use-outline-path nil
2558 "Non-nil means provide refile targets as paths.
2559 So a level 3 headline will be available as level1/level2/level3.
2561 When the value is `file', also include the file name (without directory)
2562 into the path. In this case, you can also stop the completion after
2563 the file name, to get entries inserted as top level in the file.
2565 When `full-file-path', include the full file path.
2567 When `buffer-name', use the buffer name."
2568 :group 'org-refile
2569 :type '(choice
2570 (const :tag "Not" nil)
2571 (const :tag "Yes" t)
2572 (const :tag "Start with file name" file)
2573 (const :tag "Start with full file path" full-file-path)
2574 (const :tag "Start with buffer name" buffer-name)))
2576 (defcustom org-outline-path-complete-in-steps t
2577 "Non-nil means complete the outline path in hierarchical steps.
2578 When Org uses the refile interface to select an outline path (see
2579 `org-refile-use-outline-path'), the completion of the path can be
2580 done in a single go, or it can be done in steps down the headline
2581 hierarchy. Going in steps is probably the best if you do not use
2582 a special completion package like `ido' or `icicles'. However,
2583 when using these packages, going in one step can be very fast,
2584 while still showing the whole path to the entry."
2585 :group 'org-refile
2586 :type 'boolean)
2588 (defcustom org-refile-allow-creating-parent-nodes nil
2589 "Non-nil means allow the creation of new nodes as refile targets.
2590 New nodes are then created by adding \"/new node name\" to the completion
2591 of an existing node. When the value of this variable is `confirm',
2592 new node creation must be confirmed by the user (recommended).
2593 When nil, the completion must match an existing entry.
2595 Note that, if the new heading is not seen by the criteria
2596 listed in `org-refile-targets', multiple instances of the same
2597 heading would be created by trying again to file under the new
2598 heading."
2599 :group 'org-refile
2600 :type '(choice
2601 (const :tag "Never" nil)
2602 (const :tag "Always" t)
2603 (const :tag "Prompt for confirmation" confirm)))
2605 (defcustom org-refile-active-region-within-subtree nil
2606 "Non-nil means also refile active region within a subtree.
2608 By default `org-refile' doesn't allow refiling regions if they
2609 don't contain a set of subtrees, but it might be convenient to
2610 do so sometimes: in that case, the first line of the region is
2611 converted to a headline before refiling."
2612 :group 'org-refile
2613 :version "24.1"
2614 :type 'boolean)
2616 (defgroup org-todo nil
2617 "Options concerning TODO items in Org mode."
2618 :tag "Org TODO"
2619 :group 'org)
2621 (defgroup org-progress nil
2622 "Options concerning Progress logging in Org mode."
2623 :tag "Org Progress"
2624 :group 'org-time)
2626 (defvar org-todo-interpretation-widgets
2627 '((:tag "Sequence (cycling hits every state)" sequence)
2628 (:tag "Type (cycling directly to DONE)" type))
2629 "The available interpretation symbols for customizing `org-todo-keywords'.
2630 Interested libraries should add to this list.")
2632 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2633 "List of TODO entry keyword sequences and their interpretation.
2634 \\<org-mode-map>This is a list of sequences.
2636 Each sequence starts with a symbol, either `sequence' or `type',
2637 indicating if the keywords should be interpreted as a sequence of
2638 action steps, or as different types of TODO items. The first
2639 keywords are states requiring action - these states will select a headline
2640 for inclusion into the global TODO list Org produces. If one of the
2641 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2642 signify that no further action is necessary. If \"|\" is not found,
2643 the last keyword is treated as the only DONE state of the sequence.
2645 The command `\\[org-todo]' cycles an entry through these states, and one
2646 additional state where no keyword is present. For details about this
2647 cycling, see the manual.
2649 TODO keywords and interpretation can also be set on a per-file basis with
2650 the special #+SEQ_TODO and #+TYP_TODO lines.
2652 Each keyword can optionally specify a character for fast state selection
2653 \(in combination with the variable `org-use-fast-todo-selection')
2654 and specifiers for state change logging, using the same syntax that
2655 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2656 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2657 indicates to record a time stamp each time this state is selected.
2659 Each keyword may also specify if a timestamp or a note should be
2660 recorded when entering or leaving the state, by adding additional
2661 characters in the parenthesis after the keyword. This looks like this:
2662 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2663 record only the time of the state change. With X and Y being either
2664 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2665 Y when leaving the state if and only if the *target* state does not
2666 define X. You may omit any of the fast-selection key or X or /Y,
2667 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2669 For backward compatibility, this variable may also be just a list
2670 of keywords. In this case the interpretation (sequence or type) will be
2671 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2672 :group 'org-todo
2673 :group 'org-keywords
2674 :type '(choice
2675 (repeat :tag "Old syntax, just keywords"
2676 (string :tag "Keyword"))
2677 (repeat :tag "New syntax"
2678 (cons
2679 (choice
2680 :tag "Interpretation"
2681 ;;Quick and dirty way to see
2682 ;;`org-todo-interpretations'. This takes the
2683 ;;place of item arguments
2684 :convert-widget
2685 (lambda (widget)
2686 (widget-put widget
2687 :args (mapcar
2688 (lambda (x)
2689 (widget-convert
2690 (cons 'const x)))
2691 org-todo-interpretation-widgets))
2692 widget))
2693 (repeat
2694 (string :tag "Keyword"))))))
2696 (defvar-local org-todo-keywords-1 nil
2697 "All TODO and DONE keywords active in a buffer.")
2698 (defvar org-todo-keywords-for-agenda nil)
2699 (defvar org-done-keywords-for-agenda nil)
2700 (defvar org-todo-keyword-alist-for-agenda nil)
2701 (defvar org-tag-alist-for-agenda nil
2702 "Alist of all tags from all agenda files.")
2703 (defvar org-tag-groups-alist-for-agenda nil
2704 "Alist of all groups tags from all current agenda files.")
2705 (defvar-local org-tag-groups-alist nil)
2706 (defvar org-agenda-contributing-files nil)
2707 (defvar-local org-current-tag-alist nil
2708 "Alist of all tag groups in current buffer.
2709 This variable takes into consideration `org-tag-alist',
2710 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2711 (defvar-local org-not-done-keywords nil)
2712 (defvar-local org-done-keywords nil)
2713 (defvar-local org-todo-heads nil)
2714 (defvar-local org-todo-sets nil)
2715 (defvar-local org-todo-log-states nil)
2716 (defvar-local org-todo-kwd-alist nil)
2717 (defvar-local org-todo-key-alist nil)
2718 (defvar-local org-todo-key-trigger nil)
2720 (defcustom org-todo-interpretation 'sequence
2721 "Controls how TODO keywords are interpreted.
2722 This variable is in principle obsolete and is only used for
2723 backward compatibility, if the interpretation of todo keywords is
2724 not given already in `org-todo-keywords'. See that variable for
2725 more information."
2726 :group 'org-todo
2727 :group 'org-keywords
2728 :type '(choice (const sequence)
2729 (const type)))
2731 (defcustom org-use-fast-todo-selection t
2732 "\\<org-mode-map>\
2733 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2734 This variable describes if and under what circumstances the cycling
2735 mechanism for TODO keywords will be replaced by a single-key, direct
2736 selection scheme.
2738 When nil, fast selection is never used.
2740 When the symbol `prefix', it will be used when `org-todo' is called
2741 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2742 in an Org buffer, and
2743 `\\[universal-argument] t' in an agenda buffer.
2745 When t, fast selection is used by default. In this case, the prefix
2746 argument forces cycling instead.
2748 In all cases, the special interface is only used if access keys have
2749 actually been assigned by the user, i.e. if keywords in the configuration
2750 are followed by a letter in parenthesis, like TODO(t)."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Never" nil)
2754 (const :tag "By default" t)
2755 (const :tag "Only with C-u C-c C-t" prefix)))
2757 (defcustom org-provide-todo-statistics t
2758 "Non-nil means update todo statistics after insert and toggle.
2759 ALL-HEADLINES means update todo statistics by including headlines
2760 with no TODO keyword as well, counting them as not done.
2761 A list of TODO keywords means the same, but skip keywords that are
2762 not in this list.
2763 When set to a list of two lists, the first list contains keywords
2764 to consider as TODO keywords, the second list contains keywords
2765 to consider as DONE keywords.
2767 When this is set, todo statistics is updated in the parent of the
2768 current entry each time a todo state is changed."
2769 :group 'org-todo
2770 :type '(choice
2771 (const :tag "Yes, only for TODO entries" t)
2772 (const :tag "Yes, including all entries" all-headlines)
2773 (repeat :tag "Yes, for TODOs in this list"
2774 (string :tag "TODO keyword"))
2775 (list :tag "Yes, for TODOs and DONEs in these lists"
2776 (repeat (string :tag "TODO keyword"))
2777 (repeat (string :tag "DONE keyword")))
2778 (other :tag "No TODO statistics" nil)))
2780 (defcustom org-hierarchical-todo-statistics t
2781 "Non-nil means TODO statistics covers just direct children.
2782 When nil, all entries in the subtree are considered.
2783 This has only an effect if `org-provide-todo-statistics' is set.
2784 To set this to nil for only a single subtree, use a COOKIE_DATA
2785 property and include the word \"recursive\" into the value."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-after-todo-state-change-hook nil
2790 "Hook which is run after the state of a TODO item was changed.
2791 The new state (a string with a TODO keyword, or nil) is available in the
2792 Lisp variable `org-state'."
2793 :group 'org-todo
2794 :type 'hook)
2796 (defvar org-blocker-hook nil
2797 "Hook for functions that are allowed to block a state change.
2799 Functions in this hook should not modify the buffer.
2800 Each function gets as its single argument a property list,
2801 see `org-trigger-hook' for more information about this list.
2803 If any of the functions in this hook returns nil, the state change
2804 is blocked.")
2806 (defvar org-trigger-hook nil
2807 "Hook for functions that are triggered by a state change.
2809 Each function gets as its single argument a property list with at
2810 least the following elements:
2812 (:type type-of-change :position pos-at-entry-start
2813 :from old-state :to new-state)
2815 Depending on the type, more properties may be present.
2817 This mechanism is currently implemented for:
2819 TODO state changes
2820 ------------------
2821 :type todo-state-change
2822 :from previous state (keyword as a string), or nil, or a symbol
2823 `todo' or `done', to indicate the general type of state.
2824 :to new state, like in :from")
2826 (defcustom org-enforce-todo-dependencies nil
2827 "Non-nil means undone TODO entries will block switching the parent to DONE.
2828 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2829 be blocked if any prior sibling is not yet done.
2830 Finally, if the parent is blocked because of ordered siblings of its own,
2831 the child will also be blocked."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-children-or-siblings-or-parent)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-children-or-siblings-or-parent)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-enforce-todo-checkbox-dependencies nil
2843 "Non-nil means unchecked boxes will block switching the parent to DONE.
2844 When this is nil, checkboxes have no influence on switching TODO states.
2845 When non-nil, you first need to check off all check boxes before the TODO
2846 entry can be switched to DONE.
2847 This variable needs to be set before org.el is loaded, and you need to
2848 restart Emacs after a change to make the change effective. The only way
2849 to change is while Emacs is running is through the customize interface."
2850 :set (lambda (var val)
2851 (set var val)
2852 (if val
2853 (add-hook 'org-blocker-hook
2854 'org-block-todo-from-checkboxes)
2855 (remove-hook 'org-blocker-hook
2856 'org-block-todo-from-checkboxes)))
2857 :group 'org-todo
2858 :type 'boolean)
2860 (defcustom org-treat-insert-todo-heading-as-state-change nil
2861 "Non-nil means inserting a TODO heading is treated as state change.
2862 So when the command `\\[org-insert-todo-heading]' is used, state change
2863 logging will apply if appropriate. When nil, the new TODO item will
2864 be inserted directly, and no logging will take place."
2865 :group 'org-todo
2866 :type 'boolean)
2868 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2869 "Non-nil means switching TODO states with S-cursor counts as state change.
2870 This is the default behavior. However, setting this to nil allows a
2871 convenient way to select a TODO state and bypass any logging associated
2872 with that."
2873 :group 'org-todo
2874 :type 'boolean)
2876 (defcustom org-todo-state-tags-triggers nil
2877 "Tag changes that should be triggered by TODO state changes.
2878 This is a list. Each entry is
2880 (state-change (tag . flag) .......)
2882 State-change can be a string with a state, and empty string to indicate the
2883 state that has no TODO keyword, or it can be one of the symbols `todo'
2884 or `done', meaning any not-done or done state, respectively."
2885 :group 'org-todo
2886 :group 'org-tags
2887 :type '(repeat
2888 (cons (choice :tag "When changing to"
2889 (const :tag "Not-done state" todo)
2890 (const :tag "Done state" done)
2891 (string :tag "State"))
2892 (repeat
2893 (cons :tag "Tag action"
2894 (string :tag "Tag")
2895 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2897 (defcustom org-log-done nil
2898 "Information to record when a task moves to the DONE state.
2900 Possible values are:
2902 nil Don't add anything, just change the keyword
2903 time Add a time stamp to the task
2904 note Prompt for a note and add it with template `org-log-note-headings'
2906 This option can also be set with on a per-file-basis with
2908 #+STARTUP: nologdone
2909 #+STARTUP: logdone
2910 #+STARTUP: lognotedone
2912 You can have local logging settings for a subtree by setting the LOGGING
2913 property to one or more of these keywords."
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type '(choice
2917 (const :tag "No logging" nil)
2918 (const :tag "Record CLOSED timestamp" time)
2919 (const :tag "Record CLOSED timestamp with note." note)))
2921 ;; Normalize old uses of org-log-done.
2922 (cond
2923 ((eq org-log-done t) (setq org-log-done 'time))
2924 ((and (listp org-log-done) (memq 'done org-log-done))
2925 (setq org-log-done 'note)))
2927 (defcustom org-log-reschedule nil
2928 "Information to record when the scheduling date of a tasks is modified.
2930 Possible values are:
2932 nil Don't add anything, just change the date
2933 time Add a time stamp to the task
2934 note Prompt for a note and add it with template `org-log-note-headings'
2936 This option can also be set with on a per-file-basis with
2938 #+STARTUP: nologreschedule
2939 #+STARTUP: logreschedule
2940 #+STARTUP: lognotereschedule"
2941 :group 'org-todo
2942 :group 'org-progress
2943 :type '(choice
2944 (const :tag "No logging" nil)
2945 (const :tag "Record timestamp" time)
2946 (const :tag "Record timestamp with note." note)))
2948 (defcustom org-log-redeadline nil
2949 "Information to record when the deadline date of a tasks is modified.
2951 Possible values are:
2953 nil Don't add anything, just change the date
2954 time Add a time stamp to the task
2955 note Prompt for a note and add it with template `org-log-note-headings'
2957 This option can also be set with on a per-file-basis with
2959 #+STARTUP: nologredeadline
2960 #+STARTUP: logredeadline
2961 #+STARTUP: lognoteredeadline
2963 You can have local logging settings for a subtree by setting the LOGGING
2964 property to one or more of these keywords."
2965 :group 'org-todo
2966 :group 'org-progress
2967 :type '(choice
2968 (const :tag "No logging" nil)
2969 (const :tag "Record timestamp" time)
2970 (const :tag "Record timestamp with note." note)))
2972 (defcustom org-log-note-clock-out nil
2973 "Non-nil means record a note when clocking out of an item.
2974 This can also be configured on a per-file basis by adding one of
2975 the following lines anywhere in the buffer:
2977 #+STARTUP: lognoteclock-out
2978 #+STARTUP: nolognoteclock-out"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-log-done-with-time t
2984 "Non-nil means the CLOSED time stamp will contain date and time.
2985 When nil, only the date will be recorded."
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-log-note-headings
2990 '((done . "CLOSING NOTE %t")
2991 (state . "State %-12s from %-12S %t")
2992 (note . "Note taken on %t")
2993 (reschedule . "Rescheduled from %S on %t")
2994 (delschedule . "Not scheduled, was %S on %t")
2995 (redeadline . "New deadline from %S on %t")
2996 (deldeadline . "Removed deadline, was %S on %t")
2997 (refile . "Refiled on %t")
2998 (clock-out . ""))
2999 "Headings for notes added to entries.
3001 The value is an alist, with the car being a symbol indicating the
3002 note context, and the cdr is the heading to be used. The heading
3003 may also be the empty string. The following placeholders can be
3004 used:
3006 %t a time stamp.
3007 %T an active time stamp instead the default inactive one
3008 %d a short-format time stamp.
3009 %D an active short-format time stamp.
3010 %s the new TODO state or time stamp (inactive), in double quotes.
3011 %S the old TODO state or time stamp (inactive), in double quotes.
3012 %u the user name.
3013 %U full user name.
3015 In fact, it is not a good idea to change the `state' entry,
3016 because Agenda Log mode depends on the format of these entries."
3017 :group 'org-todo
3018 :group 'org-progress
3019 :type '(list :greedy t
3020 (cons (const :tag "Heading when closing an item" done) string)
3021 (cons (const :tag
3022 "Heading when changing todo state (todo sequence only)"
3023 state) string)
3024 (cons (const :tag "Heading when just taking a note" note) string)
3025 (cons (const :tag "Heading when rescheduling" reschedule) string)
3026 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3027 (cons (const :tag "Heading when changing deadline" redeadline) string)
3028 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3029 (cons (const :tag "Heading when refiling" refile) string)
3030 (cons (const :tag "Heading when clocking out" clock-out) string)))
3032 (unless (assq 'note org-log-note-headings)
3033 (push '(note . "%t") org-log-note-headings))
3035 (defcustom org-log-into-drawer nil
3036 "Non-nil means insert state change notes and time stamps into a drawer.
3037 When nil, state changes notes will be inserted after the headline and
3038 any scheduling and clock lines, but not inside a drawer.
3040 The value of this variable should be the name of the drawer to use.
3041 LOGBOOK is proposed as the default drawer for this purpose, you can
3042 also set this to a string to define the drawer of your choice.
3044 A value of t is also allowed, representing \"LOGBOOK\".
3046 A value of t or nil can also be set with on a per-file-basis with
3048 #+STARTUP: logdrawer
3049 #+STARTUP: nologdrawer
3051 If this variable is set, `org-log-state-notes-insert-after-drawers'
3052 will be ignored.
3054 You can set the property LOG_INTO_DRAWER to overrule this setting for
3055 a subtree.
3057 Do not check directly this variable in a Lisp program. Call
3058 function `org-log-into-drawer' instead."
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type '(choice
3062 (const :tag "Not into a drawer" nil)
3063 (const :tag "LOGBOOK" t)
3064 (string :tag "Other")))
3066 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3068 (defun org-log-into-drawer ()
3069 "Name of the log drawer, as a string, or nil.
3070 This is the value of `org-log-into-drawer'. However, if the
3071 current entry has or inherits a LOG_INTO_DRAWER property, it will
3072 be used instead of the default value."
3073 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3074 (cond ((equal p "nil") nil)
3075 ((equal p "t") "LOGBOOK")
3076 ((stringp p) p)
3077 (p "LOGBOOK")
3078 ((stringp org-log-into-drawer) org-log-into-drawer)
3079 (org-log-into-drawer "LOGBOOK"))))
3081 (defcustom org-log-state-notes-insert-after-drawers nil
3082 "Non-nil means insert state change notes after any drawers in entry.
3083 Only the drawers that *immediately* follow the headline and the
3084 deadline/scheduled line are skipped.
3085 When nil, insert notes right after the heading and perhaps the line
3086 with deadline/scheduling if present.
3088 This variable will have no effect if `org-log-into-drawer' is
3089 set."
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-log-states-order-reversed t
3095 "Non-nil means the latest state note will be directly after heading.
3096 When nil, the state change notes will be ordered according to time.
3098 This option can also be set with on a per-file-basis with
3100 #+STARTUP: logstatesreversed
3101 #+STARTUP: nologstatesreversed"
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type 'boolean)
3106 (defcustom org-todo-repeat-to-state nil
3107 "The TODO state to which a repeater should return the repeating task.
3108 By default this is the first task in a TODO sequence, or the previous state
3109 in a TODO_TYP set. But you can specify another task here.
3110 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3111 :group 'org-todo
3112 :version "24.1"
3113 :type '(choice (const :tag "Head of sequence" nil)
3114 (string :tag "Specific state")))
3116 (defcustom org-log-repeat 'time
3117 "Non-nil means record moving through the DONE state when triggering repeat.
3118 An auto-repeating task is immediately switched back to TODO when
3119 marked DONE. If you are not logging state changes (by adding \"@\"
3120 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3121 record a closing note, there will be no record of the task moving
3122 through DONE. This variable forces taking a note anyway.
3124 nil Don't force a record
3125 time Record a time stamp
3126 note Prompt for a note and add it with template `org-log-note-headings'
3128 This option can also be set with on a per-file-basis with
3130 #+STARTUP: nologrepeat
3131 #+STARTUP: logrepeat
3132 #+STARTUP: lognoterepeat
3134 You can have local logging settings for a subtree by setting the LOGGING
3135 property to one or more of these keywords."
3136 :group 'org-todo
3137 :group 'org-progress
3138 :type '(choice
3139 (const :tag "Don't force a record" nil)
3140 (const :tag "Force recording the DONE state" time)
3141 (const :tag "Force recording a note with the DONE state" note)))
3144 (defgroup org-priorities nil
3145 "Priorities in Org mode."
3146 :tag "Org Priorities"
3147 :group 'org-todo)
3149 (defcustom org-enable-priority-commands t
3150 "Non-nil means priority commands are active.
3151 When nil, these commands will be disabled, so that you never accidentally
3152 set a priority."
3153 :group 'org-priorities
3154 :type 'boolean)
3156 (defcustom org-highest-priority ?A
3157 "The highest priority of TODO items. A character like ?A, ?B etc.
3158 Must have a smaller ASCII number than `org-lowest-priority'."
3159 :group 'org-priorities
3160 :type 'character)
3162 (defcustom org-lowest-priority ?C
3163 "The lowest priority of TODO items. A character like ?A, ?B etc.
3164 Must have a larger ASCII number than `org-highest-priority'."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-default-priority ?B
3169 "The default priority of TODO items.
3170 This is the priority an item gets if no explicit priority is given.
3171 When starting to cycle on an empty priority the first step in the cycle
3172 depends on `org-priority-start-cycle-with-default'. The resulting first
3173 step priority must not exceed the range from `org-highest-priority' to
3174 `org-lowest-priority' which means that `org-default-priority' has to be
3175 in this range exclusive or inclusive the range boundaries. Else the
3176 first step refuses to set the default and the second will fall back
3177 to (depending on the command used) the highest or lowest priority."
3178 :group 'org-priorities
3179 :type 'character)
3181 (defcustom org-priority-start-cycle-with-default t
3182 "Non-nil means start with default priority when starting to cycle.
3183 When this is nil, the first step in the cycle will be (depending on the
3184 command used) one higher or lower than the default priority.
3185 See also `org-default-priority'."
3186 :group 'org-priorities
3187 :type 'boolean)
3189 (defcustom org-get-priority-function nil
3190 "Function to extract the priority from a string.
3191 The string is normally the headline. If this is nil Org computes the
3192 priority from the priority cookie like [#A] in the headline. It returns
3193 an integer, increasing by 1000 for each priority level.
3194 The user can set a different function here, which should take a string
3195 as an argument and return the numeric priority."
3196 :group 'org-priorities
3197 :version "24.1"
3198 :type '(choice
3199 (const nil)
3200 (function)))
3202 (defgroup org-time nil
3203 "Options concerning time stamps and deadlines in Org mode."
3204 :tag "Org Time"
3205 :group 'org)
3207 (defcustom org-time-stamp-rounding-minutes '(0 5)
3208 "Number of minutes to round time stamps to.
3209 \\<org-mode-map>\
3210 These are two values, the first applies when first creating a time stamp.
3211 The second applies when changing it with the commands `S-up' and `S-down'.
3212 When changing the time stamp, this means that it will change in steps
3213 of N minutes, as given by the second value.
3215 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3216 numbers should be factors of 60, so for example 5, 10, 15.
3218 When this is larger than 1, you can still force an exact time stamp by using
3219 a double prefix argument to a time stamp command like \
3220 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3221 and by using a prefix arg to `S-up/down' to specify the exact number
3222 of minutes to shift."
3223 :group 'org-time
3224 :get (lambda (var) ; Make sure both elements are there
3225 (if (integerp (default-value var))
3226 (list (default-value var) 5)
3227 (default-value var)))
3228 :type '(list
3229 (integer :tag "when inserting times")
3230 (integer :tag "when modifying times")))
3232 ;; Normalize old customizations of this variable.
3233 (when (integerp org-time-stamp-rounding-minutes)
3234 (setq org-time-stamp-rounding-minutes
3235 (list org-time-stamp-rounding-minutes
3236 org-time-stamp-rounding-minutes)))
3238 (defcustom org-display-custom-times nil
3239 "Non-nil means overlay custom formats over all time stamps.
3240 The formats are defined through the variable `org-time-stamp-custom-formats'.
3241 To turn this on on a per-file basis, insert anywhere in the file:
3242 #+STARTUP: customtime"
3243 :group 'org-time
3244 :set 'set-default
3245 :type 'sexp)
3246 (make-variable-buffer-local 'org-display-custom-times)
3248 (defcustom org-time-stamp-custom-formats
3249 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3250 "Custom formats for time stamps. See `format-time-string' for the syntax.
3251 These are overlaid over the default ISO format if the variable
3252 `org-display-custom-times' is set. Time like %H:%M should be at the
3253 end of the second format. The custom formats are also honored by export
3254 commands, if custom time display is turned on at the time of export."
3255 :group 'org-time
3256 :type 'sexp)
3258 (defun org-time-stamp-format (&optional long inactive)
3259 "Get the right format for a time string."
3260 (let ((f (if long (cdr org-time-stamp-formats)
3261 (car org-time-stamp-formats))))
3262 (if inactive
3263 (concat "[" (substring f 1 -1) "]")
3264 f)))
3266 (defcustom org-deadline-warning-days 14
3267 "Number of days before expiration during which a deadline becomes active.
3268 This variable governs the display in sparse trees and in the agenda.
3269 When 0 or negative, it means use this number (the absolute value of it)
3270 even if a deadline has a different individual lead time specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :type 'integer)
3277 (defcustom org-scheduled-delay-days 0
3278 "Number of days before a scheduled item becomes active.
3279 This variable governs the display in sparse trees and in the agenda.
3280 The default value (i.e. 0) means: don't delay scheduled item.
3281 When negative, it means use this number (the absolute value of it)
3282 even if a scheduled item has a different individual delay time
3283 specified.
3285 Custom commands can set this variable in the options section."
3286 :group 'org-time
3287 :group 'org-agenda-daily/weekly
3288 :version "24.4"
3289 :package-version '(Org . "8.0")
3290 :type 'integer)
3292 (defcustom org-read-date-prefer-future t
3293 "Non-nil means assume future for incomplete date input from user.
3294 This affects the following situations:
3295 1. The user gives a month but not a year.
3296 For example, if it is April and you enter \"feb 2\", this will be read
3297 as Feb 2, *next* year. \"May 5\", however, will be this year.
3298 2. The user gives a day, but no month.
3299 For example, if today is the 15th, and you enter \"3\", Org will read
3300 this as the third of *next* month. However, if you enter \"17\",
3301 it will be considered as *this* month.
3303 If you set this variable to the symbol `time', then also the following
3304 will work:
3306 3. If the user gives a time.
3307 If the time is before now, it will be interpreted as tomorrow.
3309 Currently none of this works for ISO week specifications.
3311 When this option is nil, the current day, month and year will always be
3312 used as defaults.
3314 See also `org-agenda-jump-prefer-future'."
3315 :group 'org-time
3316 :type '(choice
3317 (const :tag "Never" nil)
3318 (const :tag "Check month and day" t)
3319 (const :tag "Check month, day, and time" time)))
3321 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3322 "Should the agenda jump command prefer the future for incomplete dates?
3323 The default is to do the same as configured in `org-read-date-prefer-future'.
3324 But you can also set a deviating value here.
3325 This may t or nil, or the symbol `org-read-date-prefer-future'."
3326 :group 'org-agenda
3327 :group 'org-time
3328 :version "24.1"
3329 :type '(choice
3330 (const :tag "Use org-read-date-prefer-future"
3331 org-read-date-prefer-future)
3332 (const :tag "Never" nil)
3333 (const :tag "Always" t)))
3335 (defcustom org-read-date-force-compatible-dates t
3336 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3338 Depending on the system Emacs is running on, certain dates cannot
3339 be represented with the type used internally to represent time.
3340 Dates between 1970-1-1 and 2038-1-1 can always be represented
3341 correctly. Some systems allow for earlier dates, some for later,
3342 some for both. One way to find out it to insert any date into an
3343 Org buffer, putting the cursor on the year and hitting S-up and
3344 S-down to test the range.
3346 When this variable is set to t, the date/time prompt will not let
3347 you specify dates outside the 1970-2037 range, so it is certain that
3348 these dates will work in whatever version of Emacs you are
3349 running, and also that you can move a file from one Emacs implementation
3350 to another. WHenever Org is forcing the year for you, it will display
3351 a message and beep.
3353 When this variable is nil, Org will check if the date is
3354 representable in the specific Emacs implementation you are using.
3355 If not, it will force a year, usually the current year, and beep
3356 to remind you. Currently this setting is not recommended because
3357 the likelihood that you will open your Org files in an Emacs that
3358 has limited date range is not negligible.
3360 A workaround for this problem is to use diary sexp dates for time
3361 stamps outside of this range."
3362 :group 'org-time
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-read-date-display-live t
3367 "Non-nil means display current interpretation of date prompt live.
3368 This display will be in an overlay, in the minibuffer."
3369 :group 'org-time
3370 :type 'boolean)
3372 (defcustom org-read-date-popup-calendar t
3373 "Non-nil means pop up a calendar when prompting for a date.
3374 In the calendar, the date can be selected with mouse-1. However, the
3375 minibuffer will also be active, and you can simply enter the date as well.
3376 When nil, only the minibuffer will be available."
3377 :group 'org-time
3378 :type 'boolean)
3379 (defvaralias 'org-popup-calendar-for-date-prompt
3380 'org-read-date-popup-calendar)
3382 (defcustom org-extend-today-until 0
3383 "The hour when your day really ends. Must be an integer.
3384 This has influence for the following applications:
3385 - When switching the agenda to \"today\". It it is still earlier than
3386 the time given here, the day recognized as TODAY is actually yesterday.
3387 - When a date is read from the user and it is still before the time given
3388 here, the current date and time will be assumed to be yesterday, 23:59.
3389 Also, timestamps inserted in capture templates follow this rule.
3391 IMPORTANT: This is a feature whose implementation is and likely will
3392 remain incomplete. Really, it is only here because past midnight seems to
3393 be the favorite working time of John Wiegley :-)"
3394 :group 'org-time
3395 :type 'integer)
3397 (defcustom org-use-effective-time nil
3398 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3399 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3400 \"effective time\" of any timestamps between midnight and 8am will be
3401 23:59 of the previous day."
3402 :group 'org-time
3403 :version "24.1"
3404 :type 'boolean)
3406 (defcustom org-use-last-clock-out-time-as-effective-time nil
3407 "When non-nil, use the last clock out time for `org-todo'.
3408 Note that this option has precedence over the combined use of
3409 `org-use-effective-time' and `org-extend-today-until'."
3410 :group 'org-time
3411 :version "24.4"
3412 :package-version '(Org . "8.0")
3413 :type 'boolean)
3415 (defcustom org-edit-timestamp-down-means-later nil
3416 "Non-nil means S-down will increase the time in a time stamp.
3417 When nil, S-up will increase."
3418 :group 'org-time
3419 :type 'boolean)
3421 (defcustom org-calendar-follow-timestamp-change t
3422 "Non-nil means make the calendar window follow timestamp changes.
3423 When a timestamp is modified and the calendar window is visible, it will be
3424 moved to the new date."
3425 :group 'org-time
3426 :type 'boolean)
3428 (defgroup org-tags nil
3429 "Options concerning tags in Org mode."
3430 :tag "Org Tags"
3431 :group 'org)
3433 (defcustom org-tag-alist nil
3434 "Default tags available in Org files.
3436 The value of this variable is an alist. Associations either:
3438 (TAG)
3439 (TAG . SELECT)
3440 (SPECIAL)
3442 where TAG is a tag as a string, SELECT is character, used to
3443 select that tag through the fast tag selection interface, and
3444 SPECIAL is one of the following keywords: `:startgroup',
3445 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3446 `:newline'. These keywords are used to define a hierarchy of
3447 tags. See manual for details.
3449 When this variable is nil, Org mode bases tag input on what is
3450 already in the buffer. The value can be overridden locally by
3451 using a TAGS keyword, e.g.,
3453 #+TAGS: tag1 tag2
3455 See also `org-tag-persistent-alist' to sidestep this behavior."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (const :tag "Start radio group" (:startgroup))
3462 (const :tag "Start tag group, non distinct" (:startgrouptag))
3463 (const :tag "Group tags delimiter" (:grouptags))
3464 (const :tag "End radio group" (:endgroup))
3465 (const :tag "End tag group, non distinct" (:endgrouptag))
3466 (const :tag "New line" (:newline)))))
3468 (defcustom org-tag-persistent-alist nil
3469 "Tags always available in Org files.
3471 The value of this variable is an alist. Associations either:
3473 (TAG)
3474 (TAG . SELECT)
3475 (SPECIAL)
3477 where TAG is a tag as a string, SELECT is a character, used to
3478 select that tag through the fast tag selection interface, and
3479 SPECIAL is one of the following keywords: `:startgroup',
3480 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3481 `:newline'. These keywords are used to define a hierarchy of
3482 tags. See manual for details.
3484 Unlike to `org-tag-alist', tags defined in this variable do not
3485 depend on a local TAGS keyword. Instead, to disable these tags
3486 on a per-file basis, insert anywhere in the file:
3488 #+STARTUP: noptag"
3489 :group 'org-tags
3490 :type '(repeat
3491 (choice
3492 (cons (string :tag "Tag name")
3493 (character :tag "Access char"))
3494 (const :tag "Start radio group" (:startgroup))
3495 (const :tag "Start tag group, non distinct" (:startgrouptag))
3496 (const :tag "Group tags delimiter" (:grouptags))
3497 (const :tag "End radio group" (:endgroup))
3498 (const :tag "End tag group, non distinct" (:endgrouptag))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column -77
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Return a non-nil value if PROPERTY should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member-ignore-case property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defconst org-global-properties-fixed
3744 '(("VISIBILITY_ALL" . "folded children content all")
3745 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3746 "List of property/value pairs that can be inherited by any entry.
3748 These are fixed values, for the preset properties. The user variable
3749 that can be used to add to this list is `org-global-properties'.
3751 The entries in this list are cons cells where the car is a property
3752 name and cdr is a string with the value. If the value represents
3753 multiple items like an \"_ALL\" property, separate the items by
3754 spaces.")
3756 (defcustom org-global-properties nil
3757 "List of property/value pairs that can be inherited by any entry.
3759 This list will be combined with the constant `org-global-properties-fixed'.
3761 The entries in this list are cons cells where the car is a property
3762 name and cdr is a string with the value.
3764 You can set buffer-local values for the same purpose in the variable
3765 `org-file-properties' this by adding lines like
3767 #+PROPERTY: NAME VALUE"
3768 :group 'org-properties
3769 :type '(repeat
3770 (cons (string :tag "Property")
3771 (string :tag "Value"))))
3773 (defvar-local org-file-properties nil
3774 "List of property/value pairs that can be inherited by any entry.
3775 Valid for the current buffer.
3776 This variable is populated from #+PROPERTY lines.")
3778 (defgroup org-agenda nil
3779 "Options concerning agenda views in Org mode."
3780 :tag "Org Agenda"
3781 :group 'org)
3783 (defvar-local org-category nil
3784 "Variable used by org files to set a category for agenda display.
3785 Such files should use a file variable to set it, for example
3787 # -*- mode: org; org-category: \"ELisp\"
3789 or contain a special line
3791 #+CATEGORY: ELisp
3793 If the file does not specify a category, then file's base name
3794 is used instead.")
3795 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3797 (defcustom org-agenda-files nil
3798 "The files to be used for agenda display.
3800 If an entry is a directory, all files in that directory that are matched
3801 by `org-agenda-file-regexp' will be part of the file list.
3803 If the value of the variable is not a list but a single file name, then
3804 the list of agenda files is actually stored and maintained in that file,
3805 one agenda file per line. In this file paths can be given relative to
3806 `org-directory'. Tilde expansion and environment variable substitution
3807 are also made.
3809 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3810 and removed with `\\[org-remove-file]'."
3811 :group 'org-agenda
3812 :type '(choice
3813 (repeat :tag "List of files and directories" file)
3814 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3816 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3817 "Regular expression to match files for `org-agenda-files'.
3818 If any element in the list in that variable contains a directory instead
3819 of a normal file, all files in that directory that are matched by this
3820 regular expression will be included."
3821 :group 'org-agenda
3822 :type 'regexp)
3824 (defcustom org-agenda-text-search-extra-files nil
3825 "List of extra files to be searched by text search commands.
3826 These files will be searched in addition to the agenda files by the
3827 commands `org-search-view' (`\\[org-agenda] s') \
3828 and `org-occur-in-agenda-files'.
3829 Note that these files will only be searched for text search commands,
3830 not for the other agenda views like todo lists, tag searches or the weekly
3831 agenda. This variable is intended to list notes and possibly archive files
3832 that should also be searched by these two commands.
3833 In fact, if the first element in the list is the symbol `agenda-archives',
3834 then all archive files of all agenda files will be added to the search
3835 scope."
3836 :group 'org-agenda
3837 :type '(set :greedy t
3838 (const :tag "Agenda Archives" agenda-archives)
3839 (repeat :inline t (file))))
3841 (defvaralias 'org-agenda-multi-occur-extra-files
3842 'org-agenda-text-search-extra-files)
3844 (defcustom org-agenda-skip-unavailable-files nil
3845 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3846 A nil value means to remove them, after a query, from the list."
3847 :group 'org-agenda
3848 :type 'boolean)
3850 (defcustom org-calendar-to-agenda-key [?c]
3851 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3852 The command `org-calendar-goto-agenda' will be bound to this key. The
3853 default is the character `c' because then `c' can be used to switch back and
3854 forth between agenda and calendar."
3855 :group 'org-agenda
3856 :type 'sexp)
3858 (defcustom org-calendar-insert-diary-entry-key [?i]
3859 "The key to be installed in `calendar-mode-map' for adding diary entries.
3860 This option is irrelevant until `org-agenda-diary-file' has been configured
3861 to point to an Org file. When that is the case, the command
3862 `org-agenda-diary-entry' will be bound to the key given here, by default
3863 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3864 if you want to continue doing this, you need to change this to a different
3865 key."
3866 :group 'org-agenda
3867 :type 'sexp)
3869 (defcustom org-agenda-diary-file 'diary-file
3870 "File to which to add new entries with the `i' key in agenda and calendar.
3871 When this is the symbol `diary-file', the functionality in the Emacs
3872 calendar will be used to add entries to the `diary-file'. But when this
3873 points to a file, `org-agenda-diary-entry' will be used instead."
3874 :group 'org-agenda
3875 :type '(choice
3876 (const :tag "The standard Emacs diary file" diary-file)
3877 (file :tag "Special Org file diary entries")))
3879 (eval-after-load "calendar"
3880 '(progn
3881 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3882 'org-calendar-goto-agenda)
3883 (add-hook 'calendar-mode-hook
3884 (lambda ()
3885 (unless (eq org-agenda-diary-file 'diary-file)
3886 (define-key calendar-mode-map
3887 org-calendar-insert-diary-entry-key
3888 'org-agenda-diary-entry))))))
3890 (defgroup org-latex nil
3891 "Options for embedding LaTeX code into Org mode."
3892 :tag "Org LaTeX"
3893 :group 'org)
3895 (defcustom org-format-latex-options
3896 '(:foreground default :background default :scale 1.0
3897 :html-foreground "Black" :html-background "Transparent"
3898 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3899 "Options for creating images from LaTeX fragments.
3900 This is a property list with the following properties:
3901 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3902 `default' means use the foreground of the default face.
3903 `auto' means use the foreground from the text face.
3904 :background the background color, or \"Transparent\".
3905 `default' means use the background of the default face.
3906 `auto' means use the background from the text face.
3907 :scale a scaling factor for the size of the images, to get more pixels
3908 :html-foreground, :html-background, :html-scale
3909 the same numbers for HTML export.
3910 :matchers a list indicating which matchers should be used to
3911 find LaTeX fragments. Valid members of this list are:
3912 \"begin\" find environments
3913 \"$1\" find single characters surrounded by $.$
3914 \"$\" find math expressions surrounded by $...$
3915 \"$$\" find math expressions surrounded by $$....$$
3916 \"\\(\" find math expressions surrounded by \\(...\\)
3917 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3918 :group 'org-latex
3919 :type 'plist)
3921 (defcustom org-format-latex-signal-error t
3922 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3923 When nil, just push out a message."
3924 :group 'org-latex
3925 :version "24.1"
3926 :type 'boolean)
3928 (defcustom org-latex-to-mathml-jar-file nil
3929 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3930 Use this to specify additional executable file say a jar file.
3932 When using MathToWeb as the converter, specify the full-path to
3933 your mathtoweb.jar file."
3934 :group 'org-latex
3935 :version "24.1"
3936 :type '(choice
3937 (const :tag "None" nil)
3938 (file :tag "JAR file" :must-match t)))
3940 (defcustom org-latex-to-mathml-convert-command nil
3941 "Command to convert LaTeX fragments to MathML.
3942 Replace format-specifiers in the command as noted below and use
3943 `shell-command' to convert LaTeX to MathML.
3944 %j: Executable file in fully expanded form as specified by
3945 `org-latex-to-mathml-jar-file'.
3946 %I: Input LaTeX file in fully expanded form.
3947 %i: The latex fragment to be converted.
3948 %o: Output MathML file.
3950 This command is used by `org-create-math-formula'.
3952 When using MathToWeb as the converter, set this option to
3953 \"java -jar %j -unicode -force -df %o %I\".
3955 When using LaTeXML set this option to
3956 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3957 :group 'org-latex
3958 :version "24.1"
3959 :type '(choice
3960 (const :tag "None" nil)
3961 (string :tag "\nShell command")))
3963 (defcustom org-preview-latex-default-process 'dvipng
3964 "The default process to convert LaTeX fragments to image files.
3965 All available processes and theirs documents can be found in
3966 `org-preview-latex-process-alist', which see."
3967 :group 'org-latex
3968 :version "26.1"
3969 :package-version '(Org . "9.0")
3970 :type 'symbol)
3972 (defcustom org-preview-latex-process-alist
3973 '((dvipng
3974 :programs ("latex" "dvipng")
3975 :description "dvi > png"
3976 :message "you need to install the programs: latex and dvipng."
3977 :image-input-type "dvi"
3978 :image-output-type "png"
3979 :image-size-adjust (1.0 . 1.0)
3980 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3981 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3982 (dvisvgm
3983 :programs ("latex" "dvisvgm")
3984 :description "dvi > svg"
3985 :message "you need to install the programs: latex and dvisvgm."
3986 :use-xcolor t
3987 :image-input-type "dvi"
3988 :image-output-type "svg"
3989 :image-size-adjust (1.7 . 1.5)
3990 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3991 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3992 (imagemagick
3993 :programs ("latex" "convert")
3994 :description "pdf > png"
3995 :message "you need to install the programs: latex and imagemagick."
3996 :use-xcolor t
3997 :image-input-type "pdf"
3998 :image-output-type "png"
3999 :image-size-adjust (1.0 . 1.0)
4000 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4001 :image-converter
4002 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4003 "Definitions of external processes for LaTeX previewing.
4004 Org mode can use some external commands to generate TeX snippet's images for
4005 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4006 `org-create-formula-image' how to call them.
4008 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4009 PROPERTIES accepts the following attributes:
4011 :programs list of strings, required programs.
4012 :description string, describe the process.
4013 :message string, message it when required programs cannot be found.
4014 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4015 :image-output-type string, output file type of image converter (e.g., \"png\").
4016 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4017 deal with background and foreground color of image.
4018 Otherwise, dvipng style background and foreground color
4019 format are generated. You may then refer to them in
4020 command options with \"%F\" and \"%B\".
4021 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4022 image size showed in buffer and the cdr element is for
4023 HTML file. This option is only useful for process
4024 developers, users should use variable
4025 `org-format-latex-options' instead.
4026 :post-clean list of strings, files matched are to be cleaned up once
4027 the image is generated. When nil, the files with \".dvi\",
4028 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4029 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4030 be cleaned up.
4031 :latex-header list of strings, the LaTeX header of the snippet file.
4032 When nil, the fallback value is used instead, which is
4033 controlled by `org-format-latex-header',
4034 `org-latex-default-packages-alist' and
4035 `org-latex-packages-alist', which see.
4036 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4037 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4038 replaced with values defined below.
4039 :image-converter list of image converter commands strings. Each of them is
4040 given to the shell and supports any of the following
4041 place-holders defined below.
4043 Place-holders used by `:image-converter' and `:latex-compiler':
4045 %f input file name
4046 %b base name of input file
4047 %o base directory of input file
4048 %O absolute output file name
4050 Place-holders only used by `:image-converter':
4052 %F foreground of image
4053 %B background of image
4054 %D dpi, which is used to adjust image size by some processing commands.
4055 %S the image size scale ratio, which is used to adjust image size by some
4056 processing commands."
4057 :group 'org-latex
4058 :version "26.1"
4059 :package-version '(Org . "9.0")
4060 :type '(alist :tag "LaTeX to image backends"
4061 :value-type (plist)))
4063 (defcustom org-preview-latex-image-directory "ltximg/"
4064 "Path to store latex preview images.
4065 A relative path here creates many directories relative to the
4066 processed org files paths. An absolute path puts all preview
4067 images at the same place."
4068 :group 'org-latex
4069 :version "26.1"
4070 :package-version '(Org . "9.0")
4071 :type 'string)
4073 (defun org-format-latex-mathml-available-p ()
4074 "Return t if `org-latex-to-mathml-convert-command' is usable."
4075 (save-match-data
4076 (when (and (boundp 'org-latex-to-mathml-convert-command)
4077 org-latex-to-mathml-convert-command)
4078 (let ((executable (car (split-string
4079 org-latex-to-mathml-convert-command))))
4080 (when (executable-find executable)
4081 (if (string-match
4082 "%j" org-latex-to-mathml-convert-command)
4083 (file-readable-p org-latex-to-mathml-jar-file)
4084 t))))))
4086 (defcustom org-format-latex-header "\\documentclass{article}
4087 \\usepackage[usenames]{color}
4088 \[PACKAGES]
4089 \[DEFAULT-PACKAGES]
4090 \\pagestyle{empty} % do not remove
4091 % The settings below are copied from fullpage.sty
4092 \\setlength{\\textwidth}{\\paperwidth}
4093 \\addtolength{\\textwidth}{-3cm}
4094 \\setlength{\\oddsidemargin}{1.5cm}
4095 \\addtolength{\\oddsidemargin}{-2.54cm}
4096 \\setlength{\\evensidemargin}{\\oddsidemargin}
4097 \\setlength{\\textheight}{\\paperheight}
4098 \\addtolength{\\textheight}{-\\headheight}
4099 \\addtolength{\\textheight}{-\\headsep}
4100 \\addtolength{\\textheight}{-\\footskip}
4101 \\addtolength{\\textheight}{-3cm}
4102 \\setlength{\\topmargin}{1.5cm}
4103 \\addtolength{\\topmargin}{-2.54cm}"
4104 "The document header used for processing LaTeX fragments.
4105 It is imperative that this header make sure that no page number
4106 appears on the page. The package defined in the variables
4107 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4108 will either replace the placeholder \"[PACKAGES]\" in this
4109 header, or they will be appended."
4110 :group 'org-latex
4111 :type 'string)
4113 (defun org-set-packages-alist (var val)
4114 "Set the packages alist and make sure it has 3 elements per entry."
4115 (set var (mapcar (lambda (x)
4116 (if (and (consp x) (= (length x) 2))
4117 (list (car x) (nth 1 x) t)
4119 val)))
4121 (defun org-get-packages-alist (var)
4122 "Get the packages alist and make sure it has 3 elements per entry."
4123 (mapcar (lambda (x)
4124 (if (and (consp x) (= (length x) 2))
4125 (list (car x) (nth 1 x) t)
4127 (default-value var)))
4129 (defcustom org-latex-default-packages-alist
4130 '(("AUTO" "inputenc" t ("pdflatex"))
4131 ("T1" "fontenc" t ("pdflatex"))
4132 ("" "graphicx" t)
4133 ("" "grffile" t)
4134 ("" "longtable" nil)
4135 ("" "wrapfig" nil)
4136 ("" "rotating" nil)
4137 ("normalem" "ulem" t)
4138 ("" "amsmath" t)
4139 ("" "textcomp" t)
4140 ("" "amssymb" t)
4141 ("" "capt-of" nil)
4142 ("" "hyperref" nil))
4143 "Alist of default packages to be inserted in the header.
4145 Change this only if one of the packages here causes an
4146 incompatibility with another package you are using.
4148 The packages in this list are needed by one part or another of
4149 Org mode to function properly:
4151 - inputenc, fontenc: for basic font and character selection
4152 - graphicx: for including images
4153 - grffile: allow periods and spaces in graphics file names
4154 - longtable: For multipage tables
4155 - wrapfig: for figure placement
4156 - rotating: for sideways figures and tables
4157 - ulem: for underline and strike-through
4158 - amsmath: for subscript and superscript and math environments
4159 - textcomp, amssymb: for various symbols used
4160 for interpreting the entities in `org-entities'. You can skip
4161 some of these packages if you don't use any of their symbols.
4162 - capt-of: for captions outside of floats
4163 - hyperref: for cross references
4165 Therefore you should not modify this variable unless you know
4166 what you are doing. The one reason to change it anyway is that
4167 you might be loading some other package that conflicts with one
4168 of the default packages. Each element is either a cell or
4169 a string.
4171 A cell is of the format
4173 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4175 If SNIPPET-FLAG is non-nil, the package also needs to be included
4176 when compiling LaTeX snippets into images for inclusion into
4177 non-LaTeX output. COMPILERS is a list of compilers that should
4178 include the package, see `org-latex-compiler'. If the document
4179 compiler is not in the list, and the list is non-nil, the package
4180 will not be inserted in the final document.
4182 A string will be inserted as-is in the header of the document."
4183 :group 'org-latex
4184 :group 'org-export-latex
4185 :set 'org-set-packages-alist
4186 :get 'org-get-packages-alist
4187 :version "26.1"
4188 :package-version '(Org . "8.3")
4189 :type '(repeat
4190 (choice
4191 (list :tag "options/package pair"
4192 (string :tag "options")
4193 (string :tag "package")
4194 (boolean :tag "Snippet"))
4195 (string :tag "A line of LaTeX"))))
4197 (defcustom org-latex-packages-alist nil
4198 "Alist of packages to be inserted in every LaTeX header.
4200 These will be inserted after `org-latex-default-packages-alist'.
4201 Each element is either a cell or a string.
4203 A cell is of the format:
4205 (\"options\" \"package\" SNIPPET-FLAG)
4207 SNIPPET-FLAG, when non-nil, indicates that this package is also
4208 needed when turning LaTeX snippets into images for inclusion into
4209 non-LaTeX output.
4211 A string will be inserted as-is in the header of the document.
4213 Make sure that you only list packages here which:
4215 - you want in every file;
4216 - do not conflict with the setup in `org-format-latex-header';
4217 - do not conflict with the default packages in
4218 `org-latex-default-packages-alist'."
4219 :group 'org-latex
4220 :group 'org-export-latex
4221 :set 'org-set-packages-alist
4222 :get 'org-get-packages-alist
4223 :type '(repeat
4224 (choice
4225 (list :tag "options/package pair"
4226 (string :tag "options")
4227 (string :tag "package")
4228 (boolean :tag "Snippet"))
4229 (string :tag "A line of LaTeX"))))
4231 (defgroup org-appearance nil
4232 "Settings for Org mode appearance."
4233 :tag "Org Appearance"
4234 :group 'org)
4236 (defcustom org-level-color-stars-only nil
4237 "Non-nil means fontify only the stars in each headline.
4238 When nil, the entire headline is fontified.
4239 Changing it requires restart of `font-lock-mode' to become effective
4240 also in regions already fontified."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hide-leading-stars nil
4245 "Non-nil means hide the first N-1 stars in a headline.
4246 This works by using the face `org-hide' for these stars. This
4247 face is white for a light background, and black for a dark
4248 background. You may have to customize the face `org-hide' to
4249 make this work.
4250 Changing it requires restart of `font-lock-mode' to become effective
4251 also in regions already fontified.
4252 You may also set this on a per-file basis by adding one of the following
4253 lines to the buffer:
4255 #+STARTUP: hidestars
4256 #+STARTUP: showstars"
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-hidden-keywords nil
4261 "List of symbols corresponding to keywords to be hidden the org buffer.
4262 For example, a value \\='(title) for this list will make the document's title
4263 appear in the buffer without the initial #+TITLE: keyword."
4264 :group 'org-appearance
4265 :version "24.1"
4266 :type '(set (const :tag "#+AUTHOR" author)
4267 (const :tag "#+DATE" date)
4268 (const :tag "#+EMAIL" email)
4269 (const :tag "#+TITLE" title)))
4271 (defcustom org-custom-properties nil
4272 "List of properties (as strings) with a special meaning.
4273 The default use of these custom properties is to let the user
4274 hide them with `org-toggle-custom-properties-visibility'."
4275 :group 'org-properties
4276 :group 'org-appearance
4277 :version "24.3"
4278 :type '(repeat (string :tag "Property Name")))
4280 (defcustom org-fontify-done-headline nil
4281 "Non-nil means change the face of a headline if it is marked DONE.
4282 Normally, only the TODO/DONE keyword indicates the state of a headline.
4283 When this is non-nil, the headline after the keyword is set to the
4284 `org-headline-done' as an additional indication."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-fontify-emphasized-text t
4289 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4290 Changing this variable requires a restart of Emacs to take effect."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-fontify-whole-heading-line nil
4295 "Non-nil means fontify the whole line for headings.
4296 This is useful when setting a background color for the
4297 org-level-* faces."
4298 :group 'org-appearance
4299 :type 'boolean)
4301 (defcustom org-highlight-latex-and-related nil
4302 "Non-nil means highlight LaTeX related syntax in the buffer.
4303 When non nil, the value should be a list containing any of the
4304 following symbols:
4305 `latex' Highlight LaTeX snippets and environments.
4306 `script' Highlight subscript and superscript.
4307 `entities' Highlight entities."
4308 :group 'org-appearance
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(choice
4312 (const :tag "No highlighting" nil)
4313 (set :greedy t :tag "Highlight"
4314 (const :tag "LaTeX snippets and environments" latex)
4315 (const :tag "Subscript and superscript" script)
4316 (const :tag "Entities" entities))))
4318 (defcustom org-hide-emphasis-markers nil
4319 "Non-nil mean font-lock should hide the emphasis marker characters."
4320 :group 'org-appearance
4321 :type 'boolean)
4323 (defcustom org-hide-macro-markers nil
4324 "Non-nil mean font-lock should hide the brackets marking macro calls."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-pretty-entities nil
4329 "Non-nil means show entities as UTF8 characters.
4330 When nil, the \\name form remains in the buffer."
4331 :group 'org-appearance
4332 :version "24.1"
4333 :type 'boolean)
4335 (defcustom org-pretty-entities-include-sub-superscripts t
4336 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4337 :group 'org-appearance
4338 :version "24.1"
4339 :type 'boolean)
4341 (defvar org-emph-re nil
4342 "Regular expression for matching emphasis.
4343 After a match, the match groups contain these elements:
4344 0 The match of the full regular expression, including the characters
4345 before and after the proper match
4346 1 The character before the proper match, or empty at beginning of line
4347 2 The proper match, including the leading and trailing markers
4348 3 The leading marker like * or /, indicating the type of highlighting
4349 4 The text between the emphasis markers, not including the markers
4350 5 The character after the match, empty at the end of a line")
4352 (defvar org-verbatim-re nil
4353 "Regular expression for matching verbatim text.")
4355 (defvar org-emphasis-regexp-components) ; defined just below
4356 (defvar org-emphasis-alist) ; defined just below
4357 (defun org-set-emph-re (var val)
4358 "Set variable and compute the emphasis regular expression."
4359 (set var val)
4360 (when (and (boundp 'org-emphasis-alist)
4361 (boundp 'org-emphasis-regexp-components)
4362 org-emphasis-alist org-emphasis-regexp-components)
4363 (pcase-let*
4364 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4365 (body (if (<= nl 0) body
4366 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4367 (template
4368 (format (concat "\\([%s]\\|^\\)" ;before markers
4369 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4370 "\\([%s]\\|$\\)") ;after markers
4371 pre border border body border post)))
4372 (setq org-emph-re (format template "*/_+"))
4373 (setq org-verbatim-re (format template "=~")))))
4375 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4376 ;; set this option proved cumbersome. See this message/thread:
4377 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4378 (defvar org-emphasis-regexp-components
4379 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4380 "Components used to build the regular expression for emphasis.
4381 This is a list with five entries. Terminology: In an emphasis string
4382 like \" *strong word* \", we call the initial space PREMATCH, the final
4383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4384 and \"trong wor\" is the body. The different components in this variable
4385 specify what is allowed/forbidden in each part:
4387 pre Chars allowed as prematch. Beginning of line will be allowed too.
4388 post Chars allowed as postmatch. End of line will be allowed too.
4389 border The chars *forbidden* as border characters.
4390 body-regexp A regexp like \".\" to match a body character. Don't use
4391 non-shy groups here, and don't allow newline here.
4392 newline The maximum number of newlines allowed in an emphasis exp.
4394 You need to reload Org or to restart Emacs after customizing this.")
4396 (defcustom org-emphasis-alist
4397 '(("*" bold)
4398 ("/" italic)
4399 ("_" underline)
4400 ("=" org-verbatim verbatim)
4401 ("~" org-code verbatim)
4402 ("+" (:strike-through t)))
4403 "Alist of characters and faces to emphasize text.
4404 Text starting and ending with a special character will be emphasized,
4405 for example *bold*, _underlined_ and /italic/. This variable sets the
4406 marker characters and the face to be used by font-lock for highlighting
4407 in Org buffers.
4409 You need to reload Org or to restart Emacs after customizing this."
4410 :group 'org-appearance
4411 :set 'org-set-emph-re
4412 :version "24.4"
4413 :package-version '(Org . "8.0")
4414 :type '(repeat
4415 (list
4416 (string :tag "Marker character")
4417 (choice
4418 (face :tag "Font-lock-face")
4419 (plist :tag "Face property list"))
4420 (option (const verbatim)))))
4422 (defvar org-protecting-blocks '("src" "example" "export")
4423 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4424 This is needed for font-lock setup.")
4426 ;;; Functions and variables from their packages
4427 ;; Declared here to avoid compiler warnings
4428 (defvar mark-active)
4430 ;; Various packages
4431 (declare-function calc-eval "calc" (str &optional separator &rest args))
4432 (declare-function calendar-forward-day "cal-move" (arg))
4433 (declare-function calendar-goto-date "cal-move" (date))
4434 (declare-function calendar-goto-today "cal-move" ())
4435 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4436 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4437 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4438 (declare-function cdlatex-tab "ext:cdlatex" ())
4439 (declare-function dired-get-filename
4440 "dired"
4441 (&optional localp no-error-if-not-filep))
4442 (declare-function iswitchb-read-buffer
4443 "iswitchb"
4444 (prompt &optional
4445 default require-match _predicate start matches-set))
4446 (declare-function org-agenda-change-all-lines
4447 "org-agenda"
4448 (newhead hdmarker &optional fixface just-this))
4449 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4450 "org-agenda"
4451 (&optional end))
4452 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4453 (declare-function org-agenda-format-item
4454 "org-agenda"
4455 (extra txt &optional level category tags dotime
4456 remove-re habitp))
4457 (declare-function org-agenda-maybe-redo "org-agenda" ())
4458 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4459 (declare-function org-agenda-save-markers-for-cut-and-paste
4460 "org-agenda"
4461 (beg end))
4462 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4463 (declare-function org-agenda-skip "org-agenda" ())
4464 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4465 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4466 (declare-function org-indent-mode "org-indent" (&optional arg))
4467 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4468 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4469 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4470 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4471 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4472 (declare-function parse-time-string "parse-time" (string))
4473 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4475 (defvar align-mode-rules-list)
4476 (defvar calc-embedded-close-formula)
4477 (defvar calc-embedded-open-formula)
4478 (defvar calc-embedded-open-mode)
4479 (defvar font-lock-unfontify-region-function)
4480 (defvar iswitchb-temp-buflist)
4481 (defvar org-agenda-tags-todo-honor-ignore-options)
4482 (defvar remember-data-file)
4483 (defvar texmathp-why)
4485 ;;;###autoload
4486 (defun turn-on-orgtbl ()
4487 "Unconditionally turn on `orgtbl-mode'."
4488 (require 'org-table)
4489 (orgtbl-mode 1))
4491 (defun org-at-table-p (&optional table-type)
4492 "Non-nil if the cursor is inside an Org table.
4493 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4494 If `org-enable-table-editor' is nil, return nil unconditionally."
4495 (and
4496 org-enable-table-editor
4497 (save-excursion
4498 (beginning-of-line)
4499 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4500 (or (not (derived-mode-p 'org-mode))
4501 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4502 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (defun org-at-table.el-p ()
4505 "Non-nil when point is at a table.el table."
4506 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4507 (let ((element (org-element-at-point)))
4508 (and (eq (org-element-type element) 'table)
4509 (eq (org-element-property :type element) 'table.el)))))
4511 (defun org-at-table-hline-p ()
4512 "Non-nil when point is inside a hline in a table.
4513 Assume point is already in a table. If `org-enable-table-editor'
4514 is nil, return nil unconditionally."
4515 (and org-enable-table-editor
4516 (save-excursion
4517 (beginning-of-line)
4518 (looking-at org-table-hline-regexp))))
4520 (defun org-table-map-tables (function &optional quietly)
4521 "Apply FUNCTION to the start of all tables in the buffer."
4522 (org-with-wide-buffer
4523 (goto-char (point-min))
4524 (while (re-search-forward org-table-any-line-regexp nil t)
4525 (unless quietly
4526 (message "Mapping tables: %d%%"
4527 (floor (* 100.0 (point)) (buffer-size))))
4528 (beginning-of-line 1)
4529 (when (and (looking-at org-table-line-regexp)
4530 ;; Exclude tables in src/example/verbatim/clocktable blocks
4531 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4532 (save-excursion (funcall function))
4533 (or (looking-at org-table-line-regexp)
4534 (forward-char 1)))
4535 (re-search-forward org-table-any-border-regexp nil 1)))
4536 (unless quietly (message "Mapping tables: done")))
4538 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4539 (declare-function org-clock-update-mode-line "org-clock" ())
4540 (declare-function org-resolve-clocks "org-clock"
4541 (&optional also-non-dangling-p prompt last-valid))
4543 (defun org-at-TBLFM-p (&optional pos)
4544 "Non-nil when point (or POS) is in #+TBLFM line."
4545 (save-excursion
4546 (goto-char (or pos (point)))
4547 (beginning-of-line)
4548 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4549 (eq (org-element-type (org-element-at-point)) 'table))))
4551 (defvar org-clock-start-time)
4552 (defvar org-clock-marker (make-marker)
4553 "Marker recording the last clock-in.")
4554 (defvar org-clock-hd-marker (make-marker)
4555 "Marker recording the last clock-in, but the headline position.")
4556 (defvar org-clock-heading ""
4557 "The heading of the current clock entry.")
4558 (defun org-clock-is-active ()
4559 "Return the buffer where the clock is currently running.
4560 Return nil if no clock is running."
4561 (marker-buffer org-clock-marker))
4563 (defun org-check-running-clock ()
4564 "Check if the current buffer contains the running clock.
4565 If yes, offer to stop it and to save the buffer with the changes."
4566 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4567 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4568 (buffer-name))))
4569 (org-clock-out)
4570 (when (y-or-n-p "Save changed buffer?")
4571 (save-buffer))))
4573 (defun org-clocktable-try-shift (dir n)
4574 "Check if this line starts a clock table, if yes, shift the time block."
4575 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4576 (org-clocktable-shift dir n)))
4578 ;;;###autoload
4579 (defun org-clock-persistence-insinuate ()
4580 "Set up hooks for clock persistence."
4581 (require 'org-clock)
4582 (add-hook 'org-mode-hook 'org-clock-load)
4583 (add-hook 'kill-emacs-hook 'org-clock-save))
4585 (defgroup org-archive nil
4586 "Options concerning archiving in Org mode."
4587 :tag "Org Archive"
4588 :group 'org-structure)
4590 (defcustom org-archive-location "%s_archive::"
4591 "The location where subtrees should be archived.
4593 The value of this variable is a string, consisting of two parts,
4594 separated by a double-colon. The first part is a filename and
4595 the second part is a headline.
4597 When the filename is omitted, archiving happens in the same file.
4598 %s in the filename will be replaced by the current file
4599 name (without the directory part). Archiving to a different file
4600 is useful to keep archived entries from contributing to the
4601 Org Agenda.
4603 The archived entries will be filed as subtrees of the specified
4604 headline. When the headline is omitted, the subtrees are simply
4605 filed away at the end of the file, as top-level entries. Also in
4606 the heading you can use %s to represent the file name, this can be
4607 useful when using the same archive for a number of different files.
4609 Here are a few examples:
4610 \"%s_archive::\"
4611 If the current file is Projects.org, archive in file
4612 Projects.org_archive, as top-level trees. This is the default.
4614 \"::* Archived Tasks\"
4615 Archive in the current file, under the top-level headline
4616 \"* Archived Tasks\".
4618 \"~/org/archive.org::\"
4619 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4621 \"~/org/archive.org::* From %s\"
4622 Archive in file ~/org/archive.org (absolute path), under headlines
4623 \"From FILENAME\" where file name is the current file name.
4625 \"~/org/datetree.org::datetree/* Finished Tasks\"
4626 The \"datetree/\" string is special, signifying to archive
4627 items to the datetree. Items are placed in either the CLOSED
4628 date of the item, or the current date if there is no CLOSED date.
4629 The heading will be a subentry to the current date. There doesn't
4630 need to be a heading, but there always needs to be a slash after
4631 datetree. For example, to store archived items directly in the
4632 datetree, use \"~/org/datetree.org::datetree/\".
4634 \"basement::** Finished Tasks\"
4635 Archive in file ./basement (relative path), as level 3 trees
4636 below the level 2 heading \"** Finished Tasks\".
4638 You may set this option on a per-file basis by adding to the buffer a
4639 line like
4641 #+ARCHIVE: basement::** Finished Tasks
4643 You may also define it locally for a subtree by setting an ARCHIVE property
4644 in the entry. If such a property is found in an entry, or anywhere up
4645 the hierarchy, it will be used."
4646 :group 'org-archive
4647 :type 'string)
4649 (defcustom org-agenda-skip-archived-trees t
4650 "Non-nil means the agenda will skip any items located in archived trees.
4651 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4652 variable is no longer recommended, you should leave it at the value t.
4653 Instead, use the key `v' to cycle the archives-mode in the agenda."
4654 :group 'org-archive
4655 :group 'org-agenda-skip
4656 :type 'boolean)
4658 (defcustom org-columns-skip-archived-trees t
4659 "Non-nil means ignore archived trees when creating column view."
4660 :group 'org-archive
4661 :group 'org-properties
4662 :type 'boolean)
4664 (defcustom org-cycle-open-archived-trees nil
4665 "Non-nil means `org-cycle' will open archived trees.
4666 An archived tree is a tree marked with the tag ARCHIVE.
4667 When nil, archived trees will stay folded. You can still open them with
4668 normal outline commands like `show-all', but not with the cycling commands."
4669 :group 'org-archive
4670 :group 'org-cycle
4671 :type 'boolean)
4673 (defcustom org-sparse-tree-open-archived-trees nil
4674 "Non-nil means sparse tree construction shows matches in archived trees.
4675 When nil, matches in these trees are highlighted, but the trees are kept in
4676 collapsed state."
4677 :group 'org-archive
4678 :group 'org-sparse-trees
4679 :type 'boolean)
4681 (defcustom org-sparse-tree-default-date-type nil
4682 "The default date type when building a sparse tree.
4683 When this is nil, a date is a scheduled or a deadline timestamp.
4684 Otherwise, these types are allowed:
4686 all: all timestamps
4687 active: only active timestamps (<...>)
4688 inactive: only inactive timestamps ([...])
4689 scheduled: only scheduled timestamps
4690 deadline: only deadline timestamps"
4691 :type '(choice (const :tag "Scheduled or deadline" nil)
4692 (const :tag "All timestamps" all)
4693 (const :tag "Only active timestamps" active)
4694 (const :tag "Only inactive timestamps" inactive)
4695 (const :tag "Only scheduled timestamps" scheduled)
4696 (const :tag "Only deadline timestamps" deadline)
4697 (const :tag "Only closed timestamps" closed))
4698 :version "26.1"
4699 :package-version '(Org . "8.3")
4700 :group 'org-sparse-trees)
4702 (defun org-cycle-hide-archived-subtrees (state)
4703 "Re-hide all archived subtrees after a visibility state change.
4704 STATE should be one of the symbols listed in the docstring of
4705 `org-cycle-hook'."
4706 (when (and (not org-cycle-open-archived-trees)
4707 (not (memq state '(overview folded))))
4708 (save-excursion
4709 (let* ((globalp (memq state '(contents all)))
4710 (beg (if globalp (point-min) (point)))
4711 (end (if globalp (point-max) (org-end-of-subtree t))))
4712 (org-hide-archived-subtrees beg end)
4713 (goto-char beg)
4714 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4715 (message "%s" (substitute-command-keys
4716 "Subtree is archived and stays closed. Use \
4717 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4719 (defun org-force-cycle-archived ()
4720 "Cycle subtree even if it is archived."
4721 (interactive)
4722 (setq this-command 'org-cycle)
4723 (let ((org-cycle-open-archived-trees t))
4724 (call-interactively 'org-cycle)))
4726 (defun org-hide-archived-subtrees (beg end)
4727 "Re-hide all archived subtrees after a visibility state change."
4728 (org-with-wide-buffer
4729 (let ((case-fold-search nil)
4730 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4731 (goto-char beg)
4732 ;; Include headline point is currently on.
4733 (beginning-of-line)
4734 (while (and (< (point) end) (re-search-forward re end t))
4735 (when (member org-archive-tag (org-get-tags))
4736 (org-flag-subtree t)
4737 (org-end-of-subtree t))))))
4739 (declare-function outline-end-of-heading "outline" ())
4740 (declare-function outline-flag-region "outline" (from to flag))
4741 (defun org-flag-subtree (flag)
4742 (save-excursion
4743 (org-back-to-heading t)
4744 (outline-end-of-heading)
4745 (outline-flag-region (point)
4746 (progn (org-end-of-subtree t) (point))
4747 flag)))
4749 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4751 ;; Declare Column View Code
4753 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4754 (declare-function org-columns-compute "org-colview" (property))
4756 ;; Declare ID code
4758 (declare-function org-id-store-link "org-id")
4759 (declare-function org-id-locations-load "org-id")
4760 (declare-function org-id-locations-save "org-id")
4761 (defvar org-id-track-globally)
4763 ;;; Variables for pre-computed regular expressions, all buffer local
4765 (defvar-local org-todo-regexp nil
4766 "Matches any of the TODO state keywords.
4767 Since TODO keywords are case-sensitive, `case-fold-search' is
4768 expected to be bound to nil when matching against this regexp.")
4770 (defvar-local org-not-done-regexp nil
4771 "Matches any of the TODO state keywords except the last one.
4772 Since TODO keywords are case-sensitive, `case-fold-search' is
4773 expected to be bound to nil when matching against this regexp.")
4775 (defvar-local org-not-done-heading-regexp nil
4776 "Matches a TODO headline that is not done.
4777 Since TODO keywords are case-sensitive, `case-fold-search' is
4778 expected to be bound to nil when matching against this regexp.")
4780 (defvar-local org-todo-line-regexp nil
4781 "Matches a headline and puts TODO state into group 2 if present.
4782 Since TODO keywords are case-sensitive, `case-fold-search' is
4783 expected to be bound to nil when matching against this regexp.")
4785 (defvar-local org-complex-heading-regexp nil
4786 "Matches a headline and puts everything into groups:
4788 group 1: Stars
4789 group 2: The TODO keyword, maybe
4790 group 3: Priority cookie
4791 group 4: True headline
4792 group 5: Tags
4794 Since TODO keywords are case-sensitive, `case-fold-search' is
4795 expected to be bound to nil when matching against this regexp.")
4797 (defvar-local org-complex-heading-regexp-format nil
4798 "Printf format to make regexp to match an exact headline.
4799 This regexp will match the headline of any node which has the
4800 exact headline text that is put into the format, but may have any
4801 TODO state, priority and tags.")
4803 (defvar-local org-todo-line-tags-regexp nil
4804 "Matches a headline and puts TODO state into group 2 if present.
4805 Also put tags into group 4 if tags are present.")
4807 (defconst org-plain-time-of-day-regexp
4808 (concat
4809 "\\(\\<[012]?[0-9]"
4810 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4811 "\\(--?"
4812 "\\(\\<[012]?[0-9]"
4813 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4814 "\\)?")
4815 "Regular expression to match a plain time or time range.
4816 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4817 groups carry important information:
4818 0 the full match
4819 1 the first time, range or not
4820 8 the second time, if it is a range.")
4822 (defconst org-plain-time-extension-regexp
4823 (concat
4824 "\\(\\<[012]?[0-9]"
4825 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4826 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4827 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4828 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4829 groups carry important information:
4830 0 the full match
4831 7 hours of duration
4832 9 minutes of duration")
4834 (defconst org-stamp-time-of-day-regexp
4835 (concat
4836 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4837 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4838 "\\(--?"
4839 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4840 "Regular expression to match a timestamp time or time range.
4841 After a match, the following groups carry important information:
4842 0 the full match
4843 1 date plus weekday, for back referencing to make sure both times are on the same day
4844 2 the first time, range or not
4845 4 the second time, if it is a range.")
4847 (defconst org-startup-options
4848 '(("fold" org-startup-folded t)
4849 ("overview" org-startup-folded t)
4850 ("nofold" org-startup-folded nil)
4851 ("showall" org-startup-folded nil)
4852 ("showeverything" org-startup-folded showeverything)
4853 ("content" org-startup-folded content)
4854 ("indent" org-startup-indented t)
4855 ("noindent" org-startup-indented nil)
4856 ("hidestars" org-hide-leading-stars t)
4857 ("showstars" org-hide-leading-stars nil)
4858 ("odd" org-odd-levels-only t)
4859 ("oddeven" org-odd-levels-only nil)
4860 ("align" org-startup-align-all-tables t)
4861 ("noalign" org-startup-align-all-tables nil)
4862 ("inlineimages" org-startup-with-inline-images t)
4863 ("noinlineimages" org-startup-with-inline-images nil)
4864 ("latexpreview" org-startup-with-latex-preview t)
4865 ("nolatexpreview" org-startup-with-latex-preview nil)
4866 ("customtime" org-display-custom-times t)
4867 ("logdone" org-log-done time)
4868 ("lognotedone" org-log-done note)
4869 ("nologdone" org-log-done nil)
4870 ("lognoteclock-out" org-log-note-clock-out t)
4871 ("nolognoteclock-out" org-log-note-clock-out nil)
4872 ("logrepeat" org-log-repeat state)
4873 ("lognoterepeat" org-log-repeat note)
4874 ("logdrawer" org-log-into-drawer t)
4875 ("nologdrawer" org-log-into-drawer nil)
4876 ("logstatesreversed" org-log-states-order-reversed t)
4877 ("nologstatesreversed" org-log-states-order-reversed nil)
4878 ("nologrepeat" org-log-repeat nil)
4879 ("logreschedule" org-log-reschedule time)
4880 ("lognotereschedule" org-log-reschedule note)
4881 ("nologreschedule" org-log-reschedule nil)
4882 ("logredeadline" org-log-redeadline time)
4883 ("lognoteredeadline" org-log-redeadline note)
4884 ("nologredeadline" org-log-redeadline nil)
4885 ("logrefile" org-log-refile time)
4886 ("lognoterefile" org-log-refile note)
4887 ("nologrefile" org-log-refile nil)
4888 ("fninline" org-footnote-define-inline t)
4889 ("nofninline" org-footnote-define-inline nil)
4890 ("fnlocal" org-footnote-section nil)
4891 ("fnauto" org-footnote-auto-label t)
4892 ("fnprompt" org-footnote-auto-label nil)
4893 ("fnconfirm" org-footnote-auto-label confirm)
4894 ("fnplain" org-footnote-auto-label plain)
4895 ("fnadjust" org-footnote-auto-adjust t)
4896 ("nofnadjust" org-footnote-auto-adjust nil)
4897 ("constcgs" constants-unit-system cgs)
4898 ("constSI" constants-unit-system SI)
4899 ("noptag" org-tag-persistent-alist nil)
4900 ("hideblocks" org-hide-block-startup t)
4901 ("nohideblocks" org-hide-block-startup nil)
4902 ("beamer" org-startup-with-beamer-mode t)
4903 ("entitiespretty" org-pretty-entities t)
4904 ("entitiesplain" org-pretty-entities nil))
4905 "Variable associated with STARTUP options for org-mode.
4906 Each element is a list of three items: the startup options (as written
4907 in the #+STARTUP line), the corresponding variable, and the value to set
4908 this variable to if the option is found. An optional forth element PUSH
4909 means to push this value onto the list in the variable.")
4911 (defcustom org-group-tags t
4912 "When non-nil (the default), use group tags.
4913 This can be turned on/off through `org-toggle-tags-groups'."
4914 :group 'org-tags
4915 :group 'org-startup
4916 :type 'boolean)
4918 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4920 (defun org-toggle-tags-groups ()
4921 "Toggle support for group tags.
4922 Support for group tags is controlled by the option
4923 `org-group-tags', which is non-nil by default."
4924 (interactive)
4925 (setq org-group-tags (not org-group-tags))
4926 (cond ((and (derived-mode-p 'org-agenda-mode)
4927 org-group-tags)
4928 (org-agenda-redo))
4929 ((derived-mode-p 'org-mode)
4930 (let ((org-inhibit-startup t)) (org-mode))))
4931 (message "Groups tags support has been turned %s"
4932 (if org-group-tags "on" "off")))
4934 (defun org-set-regexps-and-options (&optional tags-only)
4935 "Precompute regular expressions used in the current buffer.
4936 When optional argument TAGS-ONLY is non-nil, only compute tags
4937 related expressions."
4938 (when (derived-mode-p 'org-mode)
4939 (let ((alist (org--setup-collect-keywords
4940 (org-make-options-regexp
4941 (append '("FILETAGS" "TAGS" "SETUPFILE")
4942 (and (not tags-only)
4943 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4944 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4945 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4946 ;; Startup options. Get this early since it does change
4947 ;; behavior for other options (e.g., tags).
4948 (let ((startup (cdr (assq 'startup alist))))
4949 (dolist (option startup)
4950 (let ((entry (assoc-string option org-startup-options t)))
4951 (when entry
4952 (let ((var (nth 1 entry))
4953 (val (nth 2 entry)))
4954 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4955 (unless (listp (symbol-value var))
4956 (set (make-local-variable var) nil))
4957 (add-to-list var val)))))))
4958 (setq-local org-file-tags
4959 (mapcar #'org-add-prop-inherited
4960 (cdr (assq 'filetags alist))))
4961 (setq org-current-tag-alist
4962 (append org-tag-persistent-alist
4963 (let ((tags (cdr (assq 'tags alist))))
4964 (if tags (org-tag-string-to-alist tags)
4965 org-tag-alist))))
4966 (setq org-tag-groups-alist
4967 (org-tag-alist-to-groups org-current-tag-alist))
4968 (unless tags-only
4969 ;; File properties.
4970 (setq-local org-file-properties (cdr (assq 'property alist)))
4971 ;; Archive location.
4972 (let ((archive (cdr (assq 'archive alist))))
4973 (when archive (setq-local org-archive-location archive)))
4974 ;; Category.
4975 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4976 (when cat
4977 (setq-local org-category (intern cat))
4978 (setq-local org-file-properties
4979 (org--update-property-plist
4980 "CATEGORY" cat org-file-properties))))
4981 ;; Columns.
4982 (let ((column (cdr (assq 'columns alist))))
4983 (when column (setq-local org-columns-default-format column)))
4984 ;; Constants.
4985 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4986 ;; Link abbreviations.
4987 (let ((links (cdr (assq 'link alist))))
4988 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4989 ;; Priorities.
4990 (let ((priorities (cdr (assq 'priorities alist))))
4991 (when priorities
4992 (setq-local org-highest-priority (nth 0 priorities))
4993 (setq-local org-lowest-priority (nth 1 priorities))
4994 (setq-local org-default-priority (nth 2 priorities))))
4995 ;; Scripts.
4996 (let ((scripts (assq 'scripts alist)))
4997 (when scripts
4998 (setq-local org-use-sub-superscripts (cdr scripts))))
4999 ;; TODO keywords.
5000 (setq-local org-todo-kwd-alist nil)
5001 (setq-local org-todo-key-alist nil)
5002 (setq-local org-todo-key-trigger nil)
5003 (setq-local org-todo-keywords-1 nil)
5004 (setq-local org-done-keywords nil)
5005 (setq-local org-todo-heads nil)
5006 (setq-local org-todo-sets nil)
5007 (setq-local org-todo-log-states nil)
5008 (let ((todo-sequences
5009 (or (nreverse (cdr (assq 'todo alist)))
5010 (let ((d (default-value 'org-todo-keywords)))
5011 (if (not (stringp (car d))) d
5012 ;; XXX: Backward compatibility code.
5013 (list (cons org-todo-interpretation d)))))))
5014 (dolist (sequence todo-sequences)
5015 (let* ((sequence (or (run-hook-with-args-until-success
5016 'org-todo-setup-filter-hook sequence)
5017 sequence))
5018 (sequence-type (car sequence))
5019 (keywords (cdr sequence))
5020 (sep (member "|" keywords))
5021 names alist)
5022 (dolist (k (remove "|" keywords))
5023 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5025 (error "Invalid TODO keyword %s" k))
5026 (let ((name (match-string 1 k))
5027 (key (match-string 2 k))
5028 (log (org-extract-log-state-settings k)))
5029 (push name names)
5030 (push (cons name (and key (string-to-char key))) alist)
5031 (when log (push log org-todo-log-states))))
5032 (let* ((names (nreverse names))
5033 (done (if sep (org-remove-keyword-keys (cdr sep))
5034 (last names)))
5035 (head (car names))
5036 (tail (list sequence-type head (car done) (org-last done))))
5037 (add-to-list 'org-todo-heads head 'append)
5038 (push names org-todo-sets)
5039 (setq org-done-keywords (append org-done-keywords done nil))
5040 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5041 (setq org-todo-key-alist
5042 (append org-todo-key-alist
5043 (and alist
5044 (append '((:startgroup))
5045 (nreverse alist)
5046 '((:endgroup))))))
5047 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5048 (setq org-todo-sets (nreverse org-todo-sets)
5049 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5050 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5051 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5052 ;; Compute the regular expressions and other local variables.
5053 ;; Using `org-outline-regexp-bol' would complicate them much,
5054 ;; because of the fixed white space at the end of that string.
5055 (unless org-done-keywords
5056 (setq org-done-keywords
5057 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5058 (setq org-not-done-keywords
5059 (org-delete-all org-done-keywords
5060 (copy-sequence org-todo-keywords-1))
5061 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5062 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5063 org-not-done-heading-regexp
5064 (format org-heading-keyword-regexp-format org-not-done-regexp)
5065 org-todo-line-regexp
5066 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5067 org-complex-heading-regexp
5068 (concat "^\\(\\*+\\)"
5069 "\\(?: +" org-todo-regexp "\\)?"
5070 "\\(?: +\\(\\[#.\\]\\)\\)?"
5071 "\\(?: +\\(.*?\\)\\)??"
5072 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5073 "[ \t]*$")
5074 org-complex-heading-regexp-format
5075 (concat "^\\(\\*+\\)"
5076 "\\(?: +" org-todo-regexp "\\)?"
5077 "\\(?: +\\(\\[#.\\]\\)\\)?"
5078 "\\(?: +"
5079 ;; Stats cookies can be stuck to body.
5080 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5081 "\\(%s\\)"
5082 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5083 "\\)"
5084 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5085 "[ \t]*$")
5086 org-todo-line-tags-regexp
5087 (concat "^\\(\\*+\\)"
5088 "\\(?: +" org-todo-regexp "\\)?"
5089 "\\(?: +\\(.*?\\)\\)??"
5090 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5091 "[ \t]*$"))
5092 (org-compute-latex-and-related-regexp)))))
5094 (defun org--setup-collect-keywords (regexp &optional files alist)
5095 "Return setup keywords values as an alist.
5097 REGEXP matches a subset of setup keywords. FILES is a list of
5098 file names already visited. It is used to avoid circular setup
5099 files. ALIST, when non-nil, is the alist computed so far.
5101 Return value contains the following keys: `archive', `category',
5102 `columns', `constants', `filetags', `link', `priorities',
5103 `property', `scripts', `startup', `tags' and `todo'."
5104 (org-with-wide-buffer
5105 (goto-char (point-min))
5106 (let ((case-fold-search t))
5107 (while (re-search-forward regexp nil t)
5108 (let ((element (org-element-at-point)))
5109 (when (eq (org-element-type element) 'keyword)
5110 (let ((key (org-element-property :key element))
5111 (value (org-element-property :value element)))
5112 (cond
5113 ((equal key "ARCHIVE")
5114 (when (org-string-nw-p value)
5115 (push (cons 'archive value) alist)))
5116 ((equal key "CATEGORY") (push (cons 'category value) alist))
5117 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5118 ((equal key "CONSTANTS")
5119 (let* ((constants (assq 'constants alist))
5120 (store (cdr constants)))
5121 (dolist (pair (org-split-string value))
5122 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5123 pair)
5124 (let* ((name (match-string 1 pair))
5125 (value (match-string 2 pair))
5126 (old (assoc name store)))
5127 (if old (setcdr old value)
5128 (push (cons name value) store)))))
5129 (if constants (setcdr constants store)
5130 (push (cons 'constants store) alist))))
5131 ((equal key "FILETAGS")
5132 (when (org-string-nw-p value)
5133 (let ((old (assq 'filetags alist))
5134 (new (apply #'nconc
5135 (mapcar (lambda (x) (org-split-string x ":"))
5136 (org-split-string value)))))
5137 (if old (setcdr old (append new (cdr old)))
5138 (push (cons 'filetags new) alist)))))
5139 ((equal key "LINK")
5140 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5141 (let ((links (assq 'link alist))
5142 (pair (cons (match-string-no-properties 1 value)
5143 (match-string-no-properties 2 value))))
5144 (if links (push pair (cdr links))
5145 (push (list 'link pair) alist)))))
5146 ((equal key "OPTIONS")
5147 (when (and (org-string-nw-p value)
5148 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5149 (push (cons 'scripts (read (match-string 1 value))) alist)))
5150 ((equal key "PRIORITIES")
5151 (push (cons 'priorities
5152 (let ((prio (org-split-string value)))
5153 (if (< (length prio) 3) '(?A ?C ?B)
5154 (mapcar #'string-to-char prio))))
5155 alist))
5156 ((equal key "PROPERTY")
5157 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5158 (let* ((property (assq 'property alist))
5159 (value (org--update-property-plist
5160 (match-string-no-properties 1 value)
5161 (match-string-no-properties 2 value)
5162 (cdr property))))
5163 (if property (setcdr property value)
5164 (push (cons 'property value) alist)))))
5165 ((equal key "STARTUP")
5166 (let ((startup (assq 'startup alist)))
5167 (if startup
5168 (setcdr startup
5169 (append (cdr startup) (org-split-string value)))
5170 (push (cons 'startup (org-split-string value)) alist))))
5171 ((equal key "TAGS")
5172 (let ((tag-cell (assq 'tags alist)))
5173 (if tag-cell
5174 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5175 (push (cons 'tags value) alist))))
5176 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5177 (let ((todo (assq 'todo alist))
5178 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5179 (org-split-string value))))
5180 (if todo (push value (cdr todo))
5181 (push (list 'todo value) alist))))
5182 ((equal key "SETUPFILE")
5183 (unless buffer-read-only ; Do not check in Gnus messages.
5184 (let ((f (and (org-string-nw-p value)
5185 (expand-file-name
5186 (org-unbracket-string "\"" "\"" value)))))
5187 (when (and f (file-readable-p f) (not (member f files)))
5188 (with-temp-buffer
5189 (setq default-directory (file-name-directory f))
5190 (insert-file-contents f)
5191 (setq alist
5192 ;; Fake Org mode to benefit from cache
5193 ;; without recurring needlessly.
5194 (let ((major-mode 'org-mode))
5195 (org--setup-collect-keywords
5196 regexp (cons f files) alist)))))))))))))))
5197 alist)
5199 (defun org-tag-string-to-alist (s)
5200 "Return tag alist associated to string S.
5201 S is a value for TAGS keyword or produced with
5202 `org-tag-alist-to-string'. Return value is an alist suitable for
5203 `org-tag-alist' or `org-tag-persistent-alist'."
5204 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5205 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5206 "\\|{.+?}\\)" ; regular expression
5207 "\\(?:(\\(.\\))\\)?\\'"))
5208 alist group-flag)
5209 (dolist (tokens lines (cdr (nreverse alist)))
5210 (push '(:newline) alist)
5211 (while tokens
5212 (let ((token (pop tokens)))
5213 (pcase token
5214 ("{"
5215 (push '(:startgroup) alist)
5216 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5217 ("}"
5218 (push '(:endgroup) alist)
5219 (setq group-flag nil))
5220 ("["
5221 (push '(:startgrouptag) alist)
5222 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5223 ("]"
5224 (push '(:endgrouptag) alist)
5225 (setq group-flag nil))
5226 (":"
5227 (push '(:grouptags) alist))
5228 ((guard (string-match tag-re token))
5229 (let ((tag (match-string 1 token))
5230 (key (and (match-beginning 2)
5231 (string-to-char (match-string 2 token)))))
5232 ;; Push all tags in groups, no matter if they already
5233 ;; appear somewhere else in the list.
5234 (when (or group-flag (not (assoc tag alist)))
5235 (push (cons tag key) alist))))))))))
5237 (defun org-tag-alist-to-string (alist &optional skip-key)
5238 "Return tag string associated to ALIST.
5240 ALIST is an alist, as defined in `org-tag-alist' or
5241 `org-tag-persistent-alist', or produced with
5242 `org-tag-string-to-alist'.
5244 Return value is a string suitable as a value for \"TAGS\"
5245 keyword.
5247 When optional argument SKIP-KEY is non-nil, skip selection keys
5248 next to tags."
5249 (mapconcat (lambda (token)
5250 (pcase token
5251 (`(:startgroup) "{")
5252 (`(:endgroup) "}")
5253 (`(:startgrouptag) "[")
5254 (`(:endgrouptag) "]")
5255 (`(:grouptags) ":")
5256 (`(:newline) "\\n")
5257 ((and
5258 (guard (not skip-key))
5259 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5260 (format "%s(%c)" tag key))
5261 (`(,(and tag (pred stringp)) . ,_) tag)
5262 (_ (user-error "Invalid tag token: %S" token))))
5263 alist
5264 " "))
5266 (defun org-tag-alist-to-groups (alist)
5267 "Return group alist from tag ALIST.
5268 ALIST is an alist, as defined in `org-tag-alist' or
5269 `org-tag-persistent-alist', or produced with
5270 `org-tag-string-to-alist'. Return value is an alist following
5271 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5272 a string, summarizing TAGS, as a list of strings."
5273 (let (groups group-status current-group)
5274 (dolist (token alist (nreverse groups))
5275 (pcase token
5276 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5277 (`(,(or :endgroup :endgrouptag))
5278 (when (eq group-status 'append)
5279 (push (nreverse current-group) groups))
5280 (setq group-status nil))
5281 (`(:grouptags) (setq group-status 'append))
5282 ((and `(,tag . ,_) (guard group-status))
5283 (if (eq group-status 'append) (push tag current-group)
5284 (setq current-group (list tag))))
5285 (_ nil)))))
5287 (defvar org--file-cache (make-hash-table :test #'equal)
5288 "Hash table to store contents of files referenced via a URL.
5289 This is the cache of file URLs read using `org-file-contents'.")
5291 (defun org-reset-file-cache ()
5292 "Reset the cache of files downloaded by `org-file-contents'."
5293 (clrhash org--file-cache))
5295 (defun org-file-url-p (file)
5296 "Non-nil if FILE is a URL."
5297 (require 'ffap)
5298 (string-match-p ffap-url-regexp file))
5300 (defun org-file-contents (file &optional noerror nocache)
5301 "Return the contents of FILE, as a string.
5303 FILE can be a file name or URL.
5305 If FILE is a URL, download the contents. If the URL contents are
5306 already cached in the `org--file-cache' hash table, the download step
5307 is skipped.
5309 If NOERROR is non-nil, ignore the error when unable to read the FILE
5310 from file or URL.
5312 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5313 is available. This option applies only if FILE is a URL."
5314 (let* ((is-url (org-file-url-p file))
5315 (cache (and is-url
5316 (not nocache)
5317 (gethash file org--file-cache))))
5318 (cond
5319 (cache)
5320 (is-url
5321 (with-current-buffer (url-retrieve-synchronously file)
5322 (goto-char (point-min))
5323 ;; Move point to after the url-retrieve header.
5324 (search-forward "\n\n" nil :move)
5325 ;; Search for the success code only in the url-retrieve header.
5326 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5327 ;; Update the cache `org--file-cache' and return contents.
5328 (puthash file
5329 (buffer-substring-no-properties (point) (point-max))
5330 org--file-cache)
5331 (funcall (if noerror #'message #'user-error)
5332 "Unable to fetch file from %S"
5333 file))))
5335 (with-temp-buffer
5336 (condition-case err
5337 (progn
5338 (insert-file-contents file)
5339 (buffer-string))
5340 (file-error
5341 (funcall (if noerror #'message #'user-error)
5342 (error-message-string err)))))))))
5344 (defun org-extract-log-state-settings (x)
5345 "Extract the log state setting from a TODO keyword string.
5346 This will extract info from a string like \"WAIT(w@/!)\"."
5347 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5348 (let ((kw (match-string 1 x))
5349 (log1 (and (match-end 3) (match-string 3 x)))
5350 (log2 (and (match-end 4) (match-string 4 x))))
5351 (and (or log1 log2)
5352 (list kw
5353 (and log1 (if (equal log1 "!") 'time 'note))
5354 (and log2 (if (equal log2 "!") 'time 'note)))))))
5356 (defun org-remove-keyword-keys (list)
5357 "Remove a pair of parenthesis at the end of each string in LIST."
5358 (mapcar (lambda (x)
5359 (if (string-match "(.*)$" x)
5360 (substring x 0 (match-beginning 0))
5362 list))
5364 (defun org-assign-fast-keys (alist)
5365 "Assign fast keys to a keyword-key alist.
5366 Respect keys that are already there."
5367 (let (new e (alt ?0))
5368 (while (setq e (pop alist))
5369 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5370 (cdr e)) ;; Key already assigned.
5371 (push e new)
5372 (let ((clist (string-to-list (downcase (car e))))
5373 (used (append new alist)))
5374 (when (= (car clist) ?@)
5375 (pop clist))
5376 (while (and clist (rassoc (car clist) used))
5377 (pop clist))
5378 (unless clist
5379 (while (rassoc alt used)
5380 (cl-incf alt)))
5381 (push (cons (car e) (or (car clist) alt)) new))))
5382 (nreverse new)))
5384 ;;; Some variables used in various places
5386 (defvar org-window-configuration nil
5387 "Used in various places to store a window configuration.")
5388 (defvar org-selected-window nil
5389 "Used in various places to store a window configuration.")
5390 (defvar org-finish-function nil
5391 "Function to be called when `C-c C-c' is used.
5392 This is for getting out of special buffers like capture.")
5393 (defvar org-last-state)
5395 ;; Defined somewhere in this file, but used before definition.
5396 (defvar org-entities) ;; defined in org-entities.el
5397 (defvar org-struct-menu)
5398 (defvar org-org-menu)
5399 (defvar org-tbl-menu)
5401 ;;;; Define the Org mode
5403 ;; We use a before-change function to check if a table might need
5404 ;; an update.
5405 (defvar org-table-may-need-update t
5406 "Indicates that a table might need an update.
5407 This variable is set by `org-before-change-function'.
5408 `org-table-align' sets it back to nil.")
5409 (defun org-before-change-function (_beg _end)
5410 "Every change indicates that a table might need an update."
5411 (setq org-table-may-need-update t))
5412 (defvar org-mode-map)
5413 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5414 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5415 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5416 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5417 (defvar org-table-buffer-is-an nil)
5419 (defvar bidi-paragraph-direction)
5420 (defvar buffer-face-mode-face)
5422 (require 'outline)
5424 ;; Other stuff we need.
5425 (require 'time-date)
5426 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5427 (require 'easymenu)
5428 (autoload 'easy-menu-add "easymenu")
5429 (require 'overlay)
5431 ;; (require 'org-macs) moved higher up in the file before it is first used
5432 (require 'org-entities)
5433 ;; (require 'org-compat) moved higher up in the file before it is first used
5434 (require 'org-faces)
5435 (require 'org-list)
5436 (require 'org-pcomplete)
5437 (require 'org-src)
5438 (require 'org-footnote)
5439 (require 'org-macro)
5441 ;; babel
5442 (require 'ob)
5444 ;;;###autoload
5445 (define-derived-mode org-mode outline-mode "Org"
5446 "Outline-based notes management and organizer, alias
5447 \"Carsten's outline-mode for keeping track of everything.\"
5449 Org mode develops organizational tasks around a NOTES file which
5450 contains information about projects as plain text. Org mode is
5451 implemented on top of Outline mode, which is ideal to keep the content
5452 of large files well structured. It supports ToDo items, deadlines and
5453 time stamps, which magically appear in the diary listing of the Emacs
5454 calendar. Tables are easily created with a built-in table editor.
5455 Plain text URL-like links connect to websites, emails (VM), Usenet
5456 messages (Gnus), BBDB entries, and any files related to the project.
5457 For printing and sharing of notes, an Org file (or a part of it)
5458 can be exported as a structured ASCII or HTML file.
5460 The following commands are available:
5462 \\{org-mode-map}"
5464 ;; Get rid of Outline menus, they are not needed
5465 ;; Need to do this here because define-derived-mode sets up
5466 ;; the keymap so late. Still, it is a waste to call this each time
5467 ;; we switch another buffer into Org mode.
5468 (define-key org-mode-map [menu-bar headings] 'undefined)
5469 (define-key org-mode-map [menu-bar hide] 'undefined)
5470 (define-key org-mode-map [menu-bar show] 'undefined)
5472 (org-load-modules-maybe)
5473 (org-install-agenda-files-menu)
5474 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5475 (add-to-invisibility-spec '(org-cwidth))
5476 (add-to-invisibility-spec '(org-hide-block . t))
5477 (setq-local outline-regexp org-outline-regexp)
5478 (setq-local outline-level 'org-outline-level)
5479 (setq bidi-paragraph-direction 'left-to-right)
5480 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5481 (unless org-display-table
5482 (setq org-display-table (make-display-table)))
5483 (set-display-table-slot
5484 org-display-table 4
5485 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5486 org-ellipsis)))
5487 (setq buffer-display-table org-display-table))
5488 (org-set-regexps-and-options)
5489 (org-set-font-lock-defaults)
5490 (when (and org-tag-faces (not org-tags-special-faces-re))
5491 ;; tag faces set outside customize.... force initialization.
5492 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5493 ;; Calc embedded
5494 (setq-local calc-embedded-open-mode "# ")
5495 ;; Modify a few syntax entries
5496 (modify-syntax-entry ?@ "w")
5497 (modify-syntax-entry ?\" "\"")
5498 (modify-syntax-entry ?\\ "_")
5499 (modify-syntax-entry ?~ "_")
5500 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5501 ;; Activate before-change-function
5502 (setq-local org-table-may-need-update t)
5503 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5504 ;; Check for running clock before killing a buffer
5505 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5506 ;; Initialize macros templates.
5507 (org-macro-initialize-templates)
5508 ;; Initialize radio targets.
5509 (org-update-radio-target-regexp)
5510 ;; Indentation.
5511 (setq-local indent-line-function 'org-indent-line)
5512 (setq-local indent-region-function 'org-indent-region)
5513 ;; Filling and auto-filling.
5514 (org-setup-filling)
5515 ;; Comments.
5516 (org-setup-comments-handling)
5517 ;; Initialize cache.
5518 (org-element-cache-reset)
5519 ;; Beginning/end of defun
5520 (setq-local beginning-of-defun-function 'org-backward-element)
5521 (setq-local end-of-defun-function
5522 (lambda ()
5523 (if (not (org-at-heading-p))
5524 (org-forward-element)
5525 (org-forward-element)
5526 (forward-char -1))))
5527 ;; Next error for sparse trees
5528 (setq-local next-error-function 'org-occur-next-match)
5529 ;; Make sure dependence stuff works reliably, even for users who set it
5530 ;; too late :-(
5531 (if org-enforce-todo-dependencies
5532 (add-hook 'org-blocker-hook
5533 'org-block-todo-from-children-or-siblings-or-parent)
5534 (remove-hook 'org-blocker-hook
5535 'org-block-todo-from-children-or-siblings-or-parent))
5536 (if org-enforce-todo-checkbox-dependencies
5537 (add-hook 'org-blocker-hook
5538 'org-block-todo-from-checkboxes)
5539 (remove-hook 'org-blocker-hook
5540 'org-block-todo-from-checkboxes))
5542 ;; Align options lines
5543 (setq-local
5544 align-mode-rules-list
5545 '((org-in-buffer-settings
5546 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5547 (modes . '(org-mode)))))
5549 ;; Imenu
5550 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5552 ;; Make isearch reveal context
5553 (setq-local outline-isearch-open-invisible-function
5554 (lambda (&rest _) (org-show-context 'isearch)))
5556 ;; Setup the pcomplete hooks
5557 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5558 (setq-local pcomplete-command-name-function 'org-command-at-point)
5559 (setq-local pcomplete-default-completion-function 'ignore)
5560 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5561 (setq-local pcomplete-termination-string "")
5562 (setq-local buffer-face-mode-face 'org-default)
5564 ;; If empty file that did not turn on Org mode automatically, make
5565 ;; it to.
5566 (when (and org-insert-mode-line-in-empty-file
5567 (called-interactively-p 'any)
5568 (= (point-min) (point-max)))
5569 (insert "# -*- mode: org -*-\n\n"))
5570 (unless org-inhibit-startup
5571 (org-unmodified
5572 (when org-startup-with-beamer-mode (org-beamer-mode))
5573 (when org-startup-align-all-tables
5574 (org-table-map-tables #'org-table-align t))
5575 (when org-startup-with-inline-images (org-display-inline-images))
5576 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5577 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5578 (when org-startup-truncated (setq truncate-lines t))
5579 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5580 (org-refresh-effort-properties)))
5581 ;; Try to set `org-hide' face correctly.
5582 (let ((foreground (org-find-invisible-foreground)))
5583 (when foreground
5584 (set-face-foreground 'org-hide foreground))))
5586 ;; Update `customize-package-emacs-version-alist'
5587 (add-to-list 'customize-package-emacs-version-alist
5588 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5589 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5590 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5591 ("9.0" . "26.1")))
5593 (defvar org-mode-transpose-word-syntax-table
5594 (let ((st (make-syntax-table text-mode-syntax-table)))
5595 (dolist (c org-emphasis-alist st)
5596 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5598 (when (fboundp 'abbrev-table-put)
5599 (abbrev-table-put org-mode-abbrev-table
5600 :parents (list text-mode-abbrev-table)))
5602 (defun org-find-invisible-foreground ()
5603 (let ((candidates (remove
5604 "unspecified-bg"
5605 (nconc
5606 (list (face-background 'default)
5607 (face-background 'org-default))
5608 (mapcar
5609 (lambda (alist)
5610 (when (boundp alist)
5611 (cdr (assq 'background-color (symbol-value alist)))))
5612 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5613 (list (face-foreground 'org-hide))))))
5614 (car (remove nil candidates))))
5616 (defun org-current-time (&optional rounding-minutes past)
5617 "Current time, possibly rounded to ROUNDING-MINUTES.
5618 When ROUNDING-MINUTES is not an integer, fall back on the car of
5619 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5620 the rounding returns a past time."
5621 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5622 (car org-time-stamp-rounding-minutes)))
5623 (time (decode-time)) res)
5624 (if (< r 1)
5625 (current-time)
5626 (setq res
5627 (apply 'encode-time
5628 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5629 (nthcdr 2 time))))
5630 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5631 (seconds-to-time (- (float-time res) (* r 60)))
5632 res))))
5634 (defun org-today ()
5635 "Return today date, considering `org-extend-today-until'."
5636 (time-to-days
5637 (time-subtract (current-time)
5638 (list 0 (* 3600 org-extend-today-until) 0))))
5640 ;;;; Font-Lock stuff, including the activators
5642 (defvar org-mouse-map (make-sparse-keymap))
5643 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5644 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5645 (when org-mouse-1-follows-link
5646 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5647 (when org-tab-follows-link
5648 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5649 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5651 (require 'font-lock)
5653 (defconst org-non-link-chars "]\t\n\r<>")
5654 (defvar org-link-types-re nil
5655 "Matches a link that has a url-like prefix like \"http:\"")
5656 (defvar org-link-re-with-space nil
5657 "Matches a link with spaces, optional angular brackets around it.")
5658 (defvar org-link-re-with-space2 nil
5659 "Matches a link with spaces, optional angular brackets around it.")
5660 (defvar org-link-re-with-space3 nil
5661 "Matches a link with spaces, only for internal part in bracket links.")
5662 (defvar org-angle-link-re nil
5663 "Matches link with angular brackets, spaces are allowed.")
5664 (defvar org-plain-link-re nil
5665 "Matches plain link, without spaces.")
5666 (defvar org-bracket-link-regexp nil
5667 "Matches a link in double brackets.")
5668 (defvar org-bracket-link-analytic-regexp nil
5669 "Regular expression used to analyze links.
5670 Here is what the match groups contain after a match:
5671 1: http:
5672 2: http
5673 3: path
5674 4: [desc]
5675 5: desc")
5676 (defvar org-bracket-link-analytic-regexp++ nil
5677 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5678 (defvar org-any-link-re nil
5679 "Regular expression matching any link.")
5681 (defconst org-match-sexp-depth 3
5682 "Number of stacked braces for sub/superscript matching.")
5684 (defun org-create-multibrace-regexp (left right n)
5685 "Create a regular expression which will match a balanced sexp.
5686 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5687 as single character strings.
5688 The regexp returned will match the entire expression including the
5689 delimiters. It will also define a single group which contains the
5690 match except for the outermost delimiters. The maximum depth of
5691 stacked delimiters is N. Escaping delimiters is not possible."
5692 (let* ((nothing (concat "[^" left right "]*?"))
5693 (or "\\|")
5694 (re nothing)
5695 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5696 (while (> n 1)
5697 (setq n (1- n)
5698 re (concat re or next)
5699 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5700 (concat left "\\(" re "\\)" right)))
5702 (defconst org-match-substring-regexp
5703 (concat
5704 "\\(\\S-\\)\\([_^]\\)\\("
5705 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5706 "\\|"
5707 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5708 "\\|"
5709 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5710 "The regular expression matching a sub- or superscript.")
5712 (defconst org-match-substring-with-braces-regexp
5713 (concat
5714 "\\(\\S-\\)\\([_^]\\)"
5715 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5716 "The regular expression matching a sub- or superscript, forcing braces.")
5718 (defun org-make-link-regexps ()
5719 "Update the link regular expressions.
5720 This should be called after the variable `org-link-parameters' has changed."
5721 (let ((types-re (regexp-opt (org-link-types) t)))
5722 (setq org-link-types-re
5723 (concat "\\`" types-re ":")
5724 org-link-re-with-space
5725 (concat "<?" types-re ":"
5726 "\\([^" org-non-link-chars " ]"
5727 "[^" org-non-link-chars "]*"
5728 "[^" org-non-link-chars " ]\\)>?")
5729 org-link-re-with-space2
5730 (concat "<?" types-re ":"
5731 "\\([^" org-non-link-chars " ]"
5732 "[^\t\n\r]*"
5733 "[^" org-non-link-chars " ]\\)>?")
5734 org-link-re-with-space3
5735 (concat "<?" types-re ":"
5736 "\\([^" org-non-link-chars " ]"
5737 "[^\t\n\r]*\\)")
5738 org-angle-link-re
5739 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5740 types-re)
5741 org-plain-link-re
5742 (concat
5743 "\\<" types-re ":"
5744 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5745 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5746 org-bracket-link-regexp
5747 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5748 org-bracket-link-analytic-regexp
5749 (concat
5750 "\\[\\["
5751 "\\(" types-re ":\\)?"
5752 "\\([^]]+\\)"
5753 "\\]"
5754 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5755 "\\]")
5756 org-bracket-link-analytic-regexp++
5757 (concat
5758 "\\[\\["
5759 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5760 "\\([^]]+\\)"
5761 "\\]"
5762 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5763 "\\]")
5764 org-any-link-re
5765 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5766 org-angle-link-re "\\)\\|\\("
5767 org-plain-link-re "\\)"))))
5769 (org-make-link-regexps)
5771 (defvar org-emph-face nil)
5773 (defun org-do-emphasis-faces (limit)
5774 "Run through the buffer and emphasize strings."
5775 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5776 (car org-emphasis-regexp-components))))
5777 (catch :exit
5778 (while (re-search-forward quick-re limit t)
5779 (let* ((marker (match-string 2))
5780 (verbatim? (member marker '("~" "="))))
5781 (when (save-excursion
5782 (goto-char (match-beginning 0))
5783 ;; Do not match headline stars. Do not consider
5784 ;; stars of a headline as closing marker for bold
5785 ;; markup either. Do not match table hlines.
5786 (and
5787 (not (looking-at-p org-outline-regexp-bol))
5788 (not (and (equal marker "+")
5789 (org-match-line
5790 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5791 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5792 (not (string-match-p
5793 (concat org-outline-regexp-bol "\\'")
5794 (match-string 0)))))
5795 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5796 (font-lock-prepend-text-property
5797 (match-beginning 2) (match-end 2) 'face face)
5798 (when verbatim?
5799 (org-remove-flyspell-overlays-in
5800 (match-beginning 0) (match-end 0)))
5801 (add-text-properties (match-beginning 2) (match-end 2)
5802 '(font-lock-multiline t org-emphasis t))
5803 (when org-hide-emphasis-markers
5804 (add-text-properties (match-end 4) (match-beginning 5)
5805 '(invisible org-link))
5806 (add-text-properties (match-beginning 3) (match-end 3)
5807 '(invisible org-link)))
5808 (throw :exit t))))))))
5810 (defun org-emphasize (&optional char)
5811 "Insert or change an emphasis, i.e. a font like bold or italic.
5812 If there is an active region, change that region to a new emphasis.
5813 If there is no region, just insert the marker characters and position
5814 the cursor between them.
5815 CHAR should be the marker character. If it is a space, it means to
5816 remove the emphasis of the selected region.
5817 If CHAR is not given (for example in an interactive call) it will be
5818 prompted for."
5819 (interactive)
5820 (let ((erc org-emphasis-regexp-components)
5821 (string "") beg end move s)
5822 (if (org-region-active-p)
5823 (setq beg (region-beginning)
5824 end (region-end)
5825 string (buffer-substring beg end))
5826 (setq move t))
5828 (unless char
5829 (message "Emphasis marker or tag: [%s]"
5830 (mapconcat #'car org-emphasis-alist ""))
5831 (setq char (read-char-exclusive)))
5832 (if (equal char ?\s)
5833 (setq s ""
5834 move nil)
5835 (unless (assoc (char-to-string char) org-emphasis-alist)
5836 (user-error "No such emphasis marker: \"%c\"" char))
5837 (setq s (char-to-string char)))
5838 (while (and (> (length string) 1)
5839 (equal (substring string 0 1) (substring string -1))
5840 (assoc (substring string 0 1) org-emphasis-alist))
5841 (setq string (substring string 1 -1)))
5842 (setq string (concat s string s))
5843 (when beg (delete-region beg end))
5844 (unless (or (bolp)
5845 (string-match (concat "[" (nth 0 erc) "\n]")
5846 (char-to-string (char-before (point)))))
5847 (insert " "))
5848 (unless (or (eobp)
5849 (string-match (concat "[" (nth 1 erc) "\n]")
5850 (char-to-string (char-after (point)))))
5851 (insert " ") (backward-char 1))
5852 (insert string)
5853 (and move (backward-char 1))))
5855 (defconst org-nonsticky-props
5856 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5858 (defsubst org-rear-nonsticky-at (pos)
5859 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5861 (defun org-activate-links (limit)
5862 "Add link properties to links.
5863 This includes angle, plain, and bracket links."
5864 (catch :exit
5865 (while (re-search-forward org-any-link-re limit t)
5866 (let* ((start (match-beginning 0))
5867 (end (match-end 0))
5868 (style (cond ((eq ?< (char-after start)) 'angle)
5869 ((eq ?\[ (char-after (1+ start))) 'bracket)
5870 (t 'plain))))
5871 (when (and (memq style org-highlight-links)
5872 ;; Do not confuse plain links with tags.
5873 (not (and (eq style 'plain)
5874 (let ((face (get-text-property
5875 (max (1- start) (point-min)) 'face)))
5876 (if (consp face) (memq 'org-tag face)
5877 (eq 'org-tag face))))))
5878 (let* ((link-object (save-excursion
5879 (goto-char start)
5880 (save-match-data (org-element-link-parser))))
5881 (link (org-element-property :raw-link link-object))
5882 (type (org-element-property :type link-object))
5883 (path (org-element-property :path link-object))
5884 (properties ;for link's visible part
5885 (list
5886 'face (pcase (org-link-get-parameter type :face)
5887 ((and (pred functionp) face) (funcall face path))
5888 ((and (pred facep) face) face)
5889 ((and (pred consp) face) face) ;anonymous
5890 (_ 'org-link))
5891 'mouse-face (or (org-link-get-parameter type :mouse-face)
5892 'highlight)
5893 'keymap (or (org-link-get-parameter type :keymap)
5894 org-mouse-map)
5895 'help-echo (pcase (org-link-get-parameter type :help-echo)
5896 ((and (pred stringp) echo) echo)
5897 ((and (pred functionp) echo) echo)
5898 (_ (concat "LINK: " link)))
5899 'htmlize-link (pcase (org-link-get-parameter type
5900 :htmlize-link)
5901 ((and (pred functionp) f) (funcall f))
5902 (_ `(:uri ,link)))
5903 'font-lock-multiline t)))
5904 (org-remove-flyspell-overlays-in start end)
5905 (org-rear-nonsticky-at end)
5906 (if (not (eq 'bracket style))
5907 (add-text-properties start end properties)
5908 ;; Handle invisible parts in bracket links.
5909 (remove-text-properties start end '(invisible nil))
5910 (let ((hidden
5911 (append `(invisible
5912 ,(or (org-link-get-parameter type :display)
5913 'org-link))
5914 properties))
5915 (visible-start (or (match-beginning 4) (match-beginning 2)))
5916 (visible-end (or (match-end 4) (match-end 2))))
5917 (add-text-properties start visible-start hidden)
5918 (add-text-properties visible-start visible-end properties)
5919 (add-text-properties visible-end end hidden)
5920 (org-rear-nonsticky-at visible-start)
5921 (org-rear-nonsticky-at visible-end)))
5922 (let ((f (org-link-get-parameter type :activate-func)))
5923 (when (functionp f)
5924 (funcall f start end path (eq style 'bracket))))
5925 (throw :exit t))))) ;signal success
5926 nil))
5928 (defun org-activate-code (limit)
5929 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5930 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5931 (remove-text-properties (match-beginning 0) (match-end 0)
5932 '(display t invisible t intangible t))
5935 (defcustom org-src-fontify-natively t
5936 "When non-nil, fontify code in code blocks.
5937 See also the `org-block' face."
5938 :type 'boolean
5939 :version "24.4"
5940 :package-version '(Org . "8.3")
5941 :group 'org-appearance
5942 :group 'org-babel)
5944 (defcustom org-allow-promoting-top-level-subtree nil
5945 "When non-nil, allow promoting a top level subtree.
5946 The leading star of the top level headline will be replaced
5947 by a #."
5948 :type 'boolean
5949 :version "24.1"
5950 :group 'org-appearance)
5952 (defun org-fontify-meta-lines-and-blocks (limit)
5953 (condition-case nil
5954 (org-fontify-meta-lines-and-blocks-1 limit)
5955 (error (message "org-mode fontification error in %S at %d"
5956 (current-buffer)
5957 (line-number-at-pos)))))
5959 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5960 "Fontify #+ lines and blocks."
5961 (let ((case-fold-search t))
5962 (when (re-search-forward
5963 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5964 limit t)
5965 (let ((beg (match-beginning 0))
5966 (block-start (match-end 0))
5967 (block-end nil)
5968 (lang (match-string 7))
5969 (beg1 (line-beginning-position 2))
5970 (dc1 (downcase (match-string 2)))
5971 (dc3 (downcase (match-string 3)))
5972 end end1 quoting block-type)
5973 (cond
5974 ((and (match-end 4) (equal dc3 "+begin"))
5975 ;; Truly a block
5976 (setq block-type (downcase (match-string 5))
5977 quoting (member block-type org-protecting-blocks))
5978 (when (re-search-forward
5979 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5980 nil t) ;; on purpose, we look further than LIMIT
5981 (setq end (min (point-max) (match-end 0))
5982 end1 (min (point-max) (1- (match-beginning 0))))
5983 (setq block-end (match-beginning 0))
5984 (when quoting
5985 (org-remove-flyspell-overlays-in beg1 end1)
5986 (remove-text-properties beg end
5987 '(display t invisible t intangible t)))
5988 (add-text-properties
5989 beg end '(font-lock-fontified t font-lock-multiline t))
5990 (add-text-properties beg beg1 '(face org-meta-line))
5991 (org-remove-flyspell-overlays-in beg beg1)
5992 (add-text-properties ; For end_src
5993 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5994 (org-remove-flyspell-overlays-in end1 end)
5995 (cond
5996 ((and lang (not (string= lang "")) org-src-fontify-natively)
5997 (org-src-font-lock-fontify-block lang block-start block-end)
5998 (add-text-properties beg1 block-end '(src-block t)))
5999 (quoting
6000 (add-text-properties beg1 (min (point-max) (1+ end1))
6001 (list 'face
6002 (list :inherit
6003 (let ((face-name
6004 (intern (format "org-block-%s" lang))))
6005 (append (and (facep face-name) (list face-name))
6006 '(org-block))))))) ; end of source block
6007 ((not org-fontify-quote-and-verse-blocks))
6008 ((string= block-type "quote")
6009 (add-face-text-property
6010 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6011 ((string= block-type "verse")
6012 (add-face-text-property
6013 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6014 (add-text-properties beg beg1 '(face org-block-begin-line))
6015 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6016 '(face org-block-end-line))
6018 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6019 (org-remove-flyspell-overlays-in
6020 (match-beginning 0)
6021 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6022 (add-text-properties
6023 beg (match-end 3)
6024 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6025 '(font-lock-fontified t invisible t)
6026 '(font-lock-fontified t face org-document-info-keyword)))
6027 (add-text-properties
6028 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6029 (if (string-equal dc1 "+title:")
6030 '(font-lock-fontified t face org-document-title)
6031 '(font-lock-fontified t face org-document-info))))
6032 ((string-prefix-p "+caption" dc1)
6033 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6034 (remove-text-properties (match-beginning 0) (match-end 0)
6035 '(display t invisible t intangible t))
6036 ;; Handle short captions.
6037 (save-excursion
6038 (beginning-of-line)
6039 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6040 (add-text-properties (line-beginning-position) (match-end 1)
6041 '(font-lock-fontified t face org-meta-line))
6042 (add-text-properties (match-end 0) (line-end-position)
6043 '(font-lock-fontified t face org-block))
6045 ((member dc3 '(" " ""))
6046 (org-remove-flyspell-overlays-in beg (match-end 0))
6047 (add-text-properties
6048 beg (match-end 0)
6049 '(font-lock-fontified t face font-lock-comment-face)))
6050 (t ;; just any other in-buffer setting, but not indented
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (remove-text-properties (match-beginning 0) (match-end 0)
6053 '(display t invisible t intangible t))
6054 (add-text-properties beg (match-end 0)
6055 '(font-lock-fontified t face org-meta-line))
6056 t))))))
6058 (defun org-fontify-drawers (limit)
6059 "Fontify drawers."
6060 (when (re-search-forward org-drawer-regexp limit t)
6061 (add-text-properties
6062 (match-beginning 0) (match-end 0)
6063 '(font-lock-fontified t face org-special-keyword))
6064 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6067 (defun org-fontify-macros (limit)
6068 "Fontify macros."
6069 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6070 (add-text-properties
6071 (match-beginning 0) (match-end 0)
6072 '(font-lock-fontified t face org-macro))
6073 (when org-hide-macro-markers
6074 (add-text-properties (match-end 2) (match-beginning 2)
6075 '(invisible t))
6076 (add-text-properties (match-beginning 1) (match-end 1)
6077 '(invisible t)))
6078 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6081 (defun org-activate-footnote-links (limit)
6082 "Add text properties for footnotes."
6083 (let ((fn (org-footnote-next-reference-or-definition limit)))
6084 (when fn
6085 (let* ((beg (nth 1 fn))
6086 (end (nth 2 fn))
6087 (label (car fn))
6088 (referencep (/= (line-beginning-position) beg)))
6089 (when (and referencep (nth 3 fn))
6090 (save-excursion
6091 (goto-char beg)
6092 (search-forward (or label "fn:"))
6093 (org-remove-flyspell-overlays-in beg (match-end 0))))
6094 (add-text-properties beg end
6095 (list 'mouse-face 'highlight
6096 'keymap org-mouse-map
6097 'help-echo
6098 (if referencep "Footnote reference"
6099 "Footnote definition")
6100 'font-lock-fontified t
6101 'font-lock-multiline t
6102 'face 'org-footnote))))))
6104 (defun org-activate-dates (limit)
6105 "Add text properties for dates."
6106 (when (and (re-search-forward org-tsr-regexp-both limit t)
6107 (not (equal (char-before (match-beginning 0)) 91)))
6108 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6109 (add-text-properties (match-beginning 0) (match-end 0)
6110 (list 'mouse-face 'highlight
6111 'keymap org-mouse-map))
6112 (org-rear-nonsticky-at (match-end 0))
6113 (when org-display-custom-times
6114 ;; If it's a date range, activate custom time for second date.
6115 (when (match-end 3)
6116 (org-display-custom-time (match-beginning 3) (match-end 3)))
6117 (org-display-custom-time (match-beginning 1) (match-end 1)))
6120 (defvar-local org-target-link-regexp nil
6121 "Regular expression matching radio targets in plain text.")
6123 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6124 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6125 border border border))
6126 "Regular expression matching a link target.")
6128 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6129 "Regular expression matching a radio target.")
6131 (defconst org-any-target-regexp
6132 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6133 "Regular expression matching any target.")
6135 (defun org-activate-target-links (limit)
6136 "Add text properties for target matches."
6137 (when org-target-link-regexp
6138 (let ((case-fold-search t))
6139 (when (re-search-forward org-target-link-regexp limit t)
6140 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6141 (add-text-properties (match-beginning 1) (match-end 1)
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map
6144 'help-echo "Radio target link"
6145 'org-linked-text t))
6146 (org-rear-nonsticky-at (match-end 1))
6147 t))))
6149 (defun org-update-radio-target-regexp ()
6150 "Find all radio targets in this file and update the regular expression.
6151 Also refresh fontification if needed."
6152 (interactive)
6153 (let ((old-regexp org-target-link-regexp)
6154 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6155 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6156 (targets
6157 (org-with-wide-buffer
6158 (goto-char (point-min))
6159 (let (rtn)
6160 (while (re-search-forward org-radio-target-regexp nil t)
6161 ;; Make sure point is really within the object.
6162 (backward-char)
6163 (let ((obj (org-element-context)))
6164 (when (eq (org-element-type obj) 'radio-target)
6165 (cl-pushnew (org-element-property :value obj) rtn
6166 :test #'equal))))
6167 rtn))))
6168 (setq org-target-link-regexp
6169 (and targets
6170 (concat before-re
6171 (mapconcat
6172 (lambda (x)
6173 (replace-regexp-in-string
6174 " +" "\\s-+" (regexp-quote x) t t))
6175 targets
6176 "\\|")
6177 after-re)))
6178 (unless (equal old-regexp org-target-link-regexp)
6179 ;; Clean-up cache.
6180 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6181 ((not org-target-link-regexp) old-regexp)
6183 (concat before-re
6184 (mapconcat
6185 (lambda (re)
6186 (substring re (length before-re)
6187 (- (length after-re))))
6188 (list old-regexp org-target-link-regexp)
6189 "\\|")
6190 after-re)))))
6191 (org-with-wide-buffer
6192 (goto-char (point-min))
6193 (while (re-search-forward regexp nil t)
6194 (org-element-cache-refresh (match-beginning 1)))))
6195 ;; Re fontify buffer.
6196 (when (memq 'radio org-highlight-links)
6197 (org-restart-font-lock)))))
6199 (defun org-hide-wide-columns (limit)
6200 (let (s e)
6201 (setq s (text-property-any (point) (or limit (point-max))
6202 'org-cwidth t))
6203 (when s
6204 (setq e (next-single-property-change s 'org-cwidth))
6205 (add-text-properties s e '(invisible org-cwidth))
6206 (goto-char e)
6207 t)))
6209 (defvar org-latex-and-related-regexp nil
6210 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6212 (defun org-compute-latex-and-related-regexp ()
6213 "Compute regular expression for LaTeX, entities and sub/superscript.
6214 Result depends on variable `org-highlight-latex-and-related'."
6215 (setq-local
6216 org-latex-and-related-regexp
6217 (let* ((re-sub
6218 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6219 ((eq org-use-sub-superscripts '{})
6220 (list org-match-substring-with-braces-regexp))
6221 (org-use-sub-superscripts (list org-match-substring-regexp))))
6222 (re-latex
6223 (when (memq 'latex org-highlight-latex-and-related)
6224 (let ((matchers (plist-get org-format-latex-options :matchers)))
6225 (delq nil
6226 (mapcar (lambda (x)
6227 (and (member (car x) matchers) (nth 1 x)))
6228 org-latex-regexps)))))
6229 (re-entities
6230 (when (memq 'entities org-highlight-latex-and-related)
6231 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6232 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6234 (defun org-do-latex-and-related (limit)
6235 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6236 LIMIT bounds the search for syntax to highlight. Stop at first
6237 highlighted object, if any. Return t if some highlighting was
6238 done, nil otherwise."
6239 (when (org-string-nw-p org-latex-and-related-regexp)
6240 (catch 'found
6241 (while (re-search-forward org-latex-and-related-regexp limit t)
6242 (unless
6243 (cl-some
6244 (lambda (f)
6245 (memq f '(org-code org-verbatim underline org-special-keyword)))
6246 (save-excursion
6247 (goto-char (1+ (match-beginning 0)))
6248 (face-at-point nil t)))
6249 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6250 '(?_ ?^))
6252 0)))
6253 (font-lock-prepend-text-property
6254 (+ offset (match-beginning 0)) (match-end 0)
6255 'face 'org-latex-and-related)
6256 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6257 '(font-lock-multiline t)))
6258 (throw 'found t)))
6259 nil)))
6261 (defun org-restart-font-lock ()
6262 "Restart `font-lock-mode', to force refontification."
6263 (when (and (boundp 'font-lock-mode) font-lock-mode)
6264 (font-lock-mode -1)
6265 (font-lock-mode 1)))
6267 (defun org-activate-tags (limit)
6268 (when (re-search-forward
6269 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6270 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6271 (add-text-properties (match-beginning 1) (match-end 1)
6272 (list 'mouse-face 'highlight
6273 'keymap org-mouse-map))
6274 (org-rear-nonsticky-at (match-end 1))
6277 (defun org-outline-level ()
6278 "Compute the outline level of the heading at point.
6280 If this is called at a normal headline, the level is the number
6281 of stars. Use `org-reduced-level' to remove the effect of
6282 `org-odd-levels'. Unlike to `org-current-level', this function
6283 takes into consideration inlinetasks."
6284 (org-with-wide-buffer
6285 (end-of-line)
6286 (if (re-search-backward org-outline-regexp-bol nil t)
6287 (1- (- (match-end 0) (match-beginning 0)))
6288 0)))
6290 (defvar org-font-lock-keywords nil)
6292 (defsubst org-re-property (property &optional literal allow-null value)
6293 "Return a regexp matching a PROPERTY line.
6295 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6296 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6297 non-nil, match properties even without a value.
6299 Match group 3 is set to the value when it exists. If there is no
6300 value and ALLOW-NULL is non-nil, it is set to the empty string.
6302 With optional argument VALUE, match only property lines with
6303 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6304 unless LITERAL is non-nil."
6305 (concat
6306 "^\\(?4:[ \t]*\\)"
6307 (format "\\(?1::\\(?2:%s\\):\\)"
6308 (if literal property (regexp-quote property)))
6309 (cond (value
6310 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6311 (if literal value (regexp-quote value))))
6312 (allow-null
6313 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6315 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6317 (defconst org-property-re
6318 (org-re-property "\\S-+" 'literal t)
6319 "Regular expression matching a property line.
6320 There are four matching groups:
6321 1: :PROPKEY: including the leading and trailing colon,
6322 2: PROPKEY without the leading and trailing colon,
6323 3: PROPVAL without leading or trailing spaces,
6324 4: the indentation of the current line,
6325 5: trailing whitespace.")
6327 (defvar org-font-lock-hook nil
6328 "Functions to be called for special font lock stuff.")
6330 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6332 (defvar org-font-lock-set-keywords-hook nil
6333 "Functions that can manipulate `org-font-lock-extra-keywords'.
6334 This is called after `org-font-lock-extra-keywords' is defined, but before
6335 it is installed to be used by font lock. This can be useful if something
6336 needs to be inserted at a specific position in the font-lock sequence.")
6338 (defun org-font-lock-hook (limit)
6339 "Run `org-font-lock-hook' within LIMIT."
6340 (run-hook-with-args 'org-font-lock-hook limit))
6342 (defun org-set-font-lock-defaults ()
6343 "Set font lock defaults for the current buffer."
6344 (let* ((em org-fontify-emphasized-text)
6345 (lk org-highlight-links)
6346 (org-font-lock-extra-keywords
6347 (list
6348 ;; Call the hook
6349 '(org-font-lock-hook)
6350 ;; Headlines
6351 `(,(if org-fontify-whole-heading-line
6352 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6353 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6354 (1 (org-get-level-face 1))
6355 (2 (org-get-level-face 2))
6356 (3 (org-get-level-face 3)))
6357 ;; Table lines
6358 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6359 (1 'org-table t))
6360 ;; Table internals
6361 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6362 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6363 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6364 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6365 ;; Drawers
6366 '(org-fontify-drawers)
6367 ;; Properties
6368 (list org-property-re
6369 '(1 'org-special-keyword t)
6370 '(3 'org-property-value t))
6371 ;; Link related fontification.
6372 '(org-activate-links)
6373 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6374 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6375 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6376 (when (memq 'footnote lk) '(org-activate-footnote-links))
6377 ;; Targets.
6378 (list org-any-target-regexp '(0 'org-target t))
6379 ;; Diary sexps.
6380 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6381 ;; Macro
6382 '(org-fontify-macros)
6383 '(org-hide-wide-columns (0 nil append))
6384 ;; TODO keyword
6385 (list (format org-heading-keyword-regexp-format
6386 org-todo-regexp)
6387 '(2 (org-get-todo-face 2) t))
6388 ;; DONE
6389 (if org-fontify-done-headline
6390 (list (format org-heading-keyword-regexp-format
6391 (concat
6392 "\\(?:"
6393 (mapconcat 'regexp-quote org-done-keywords "\\|")
6394 "\\)"))
6395 '(2 'org-headline-done t))
6396 nil)
6397 ;; Priorities
6398 '(org-font-lock-add-priority-faces)
6399 ;; Tags
6400 '(org-font-lock-add-tag-faces)
6401 ;; Tags groups
6402 (when (and org-group-tags org-tag-groups-alist)
6403 (list (concat org-outline-regexp-bol ".+\\(:"
6404 (regexp-opt (mapcar 'car org-tag-groups-alist))
6405 ":\\).*$")
6406 '(1 'org-tag-group prepend)))
6407 ;; Special keywords
6408 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6409 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6410 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6411 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6412 ;; Emphasis
6413 (when em '(org-do-emphasis-faces))
6414 ;; Checkboxes
6415 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6416 1 'org-checkbox prepend)
6417 (when (cdr (assq 'checkbox org-list-automatic-rules))
6418 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6419 (0 (org-get-checkbox-statistics-face) t)))
6420 ;; Description list items
6421 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6422 1 'org-list-dt prepend)
6423 ;; ARCHIVEd headings
6424 (list (concat
6425 org-outline-regexp-bol
6426 "\\(.*:" org-archive-tag ":.*\\)")
6427 '(1 'org-archived prepend))
6428 ;; Specials
6429 '(org-do-latex-and-related)
6430 '(org-fontify-entities)
6431 '(org-raise-scripts)
6432 ;; Code
6433 '(org-activate-code (1 'org-code t))
6434 ;; COMMENT
6435 (list (format
6436 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6437 org-todo-regexp
6438 org-comment-string)
6439 '(9 'org-special-keyword t))
6440 ;; Blocks and meta lines
6441 '(org-fontify-meta-lines-and-blocks))))
6442 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6443 (run-hooks 'org-font-lock-set-keywords-hook)
6444 ;; Now set the full font-lock-keywords
6445 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6446 (setq-local font-lock-defaults
6447 '(org-font-lock-keywords t nil nil backward-paragraph))
6448 (kill-local-variable 'font-lock-keywords)
6449 nil))
6451 (defun org-toggle-pretty-entities ()
6452 "Toggle the composition display of entities as UTF8 characters."
6453 (interactive)
6454 (setq-local org-pretty-entities (not org-pretty-entities))
6455 (org-restart-font-lock)
6456 (if org-pretty-entities
6457 (message "Entities are now displayed as UTF8 characters")
6458 (save-restriction
6459 (widen)
6460 (decompose-region (point-min) (point-max))
6461 (message "Entities are now displayed as plain text"))))
6463 (defvar-local org-custom-properties-overlays nil
6464 "List of overlays used for custom properties.")
6466 (defun org-toggle-custom-properties-visibility ()
6467 "Display or hide properties in `org-custom-properties'."
6468 (interactive)
6469 (if org-custom-properties-overlays
6470 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6471 (setq org-custom-properties-overlays nil))
6472 (when org-custom-properties
6473 (org-with-wide-buffer
6474 (goto-char (point-min))
6475 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6476 (while (re-search-forward regexp nil t)
6477 (let ((end (cdr (save-match-data (org-get-property-block)))))
6478 (when (and end (< (point) end))
6479 ;; Hide first custom property in current drawer.
6480 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6481 (overlay-put o 'invisible t)
6482 (overlay-put o 'org-custom-property t)
6483 (push o org-custom-properties-overlays))
6484 ;; Hide additional custom properties in the same drawer.
6485 (while (re-search-forward regexp end t)
6486 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6487 (overlay-put o 'invisible t)
6488 (overlay-put o 'org-custom-property t)
6489 (push o org-custom-properties-overlays)))))
6490 ;; Each entry is limited to a single property drawer.
6491 (outline-next-heading)))))))
6493 (defun org-fontify-entities (limit)
6494 "Find an entity to fontify."
6495 (let (ee)
6496 (when org-pretty-entities
6497 (catch 'match
6498 ;; "\_ "-family is left out on purpose. Only the first one,
6499 ;; i.e., "\_ ", could be fontified anyway, and it would be
6500 ;; confusing when adding a second white space character.
6501 (while (re-search-forward
6502 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6503 limit t)
6504 (when (and (not (org-at-comment-p))
6505 (setq ee (org-entity-get (match-string 1)))
6506 (= (length (nth 6 ee)) 1))
6507 (let* ((end (if (equal (match-string 2) "{}")
6508 (match-end 2)
6509 (match-end 1))))
6510 (add-text-properties
6511 (match-beginning 0) end
6512 (list 'font-lock-fontified t))
6513 (compose-region (match-beginning 0) end
6514 (nth 6 ee) nil)
6515 (backward-char 1)
6516 (throw 'match t))))
6517 nil))))
6519 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6520 "Fontify string S like in Org mode."
6521 (with-temp-buffer
6522 (insert s)
6523 (let ((org-odd-levels-only odd-levels))
6524 (org-mode)
6525 (org-font-lock-ensure)
6526 (buffer-string))))
6528 (defvar org-m nil)
6529 (defvar org-l nil)
6530 (defvar org-f nil)
6531 (defun org-get-level-face (n)
6532 "Get the right face for match N in font-lock matching of headlines."
6533 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6534 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6535 (if org-cycle-level-faces
6536 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6537 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6538 (cond
6539 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6540 ((eq n 2) org-f)
6541 (t (unless org-level-color-stars-only org-f))))
6543 (defun org-face-from-face-or-color (context inherit face-or-color)
6544 "Create a face list that inherits INHERIT, but sets the foreground color.
6545 When FACE-OR-COLOR is not a string, just return it."
6546 (if (stringp face-or-color)
6547 (list :inherit inherit
6548 (cdr (assoc context org-faces-easy-properties))
6549 face-or-color)
6550 face-or-color))
6552 (defun org-get-todo-face (kwd)
6553 "Get the right face for a TODO keyword KWD.
6554 If KWD is a number, get the corresponding match group."
6555 (when (numberp kwd) (setq kwd (match-string kwd)))
6556 (or (org-face-from-face-or-color
6557 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6558 (and (member kwd org-done-keywords) 'org-done)
6559 'org-todo))
6561 (defun org-get-priority-face (priority)
6562 "Get the right face for PRIORITY.
6563 PRIORITY is a character."
6564 (or (org-face-from-face-or-color
6565 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6566 'org-priority))
6568 (defun org-get-tag-face (tag)
6569 "Get the right face for TAG.
6570 If TAG is a number, get the corresponding match group."
6571 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6572 (or (org-face-from-face-or-color
6573 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6574 'org-tag)))
6576 (defun org-font-lock-add-priority-faces (limit)
6577 "Add the special priority faces."
6578 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6579 (add-text-properties
6580 (match-beginning 1) (match-end 1)
6581 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6582 'font-lock-fontified t))))
6584 (defun org-font-lock-add-tag-faces (limit)
6585 "Add the special tag faces."
6586 (when (and org-tag-faces org-tags-special-faces-re)
6587 (while (re-search-forward org-tags-special-faces-re limit t)
6588 (add-text-properties (match-beginning 1) (match-end 1)
6589 (list 'face (org-get-tag-face 1)
6590 'font-lock-fontified t))
6591 (backward-char 1))))
6593 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6594 "Remove fontification and activation overlays from links."
6595 (font-lock-default-unfontify-region beg end)
6596 (let* ((buffer-undo-list t)
6597 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6598 (inhibit-modification-hooks t)
6599 deactivate-mark buffer-file-name buffer-file-truename)
6600 (decompose-region beg end)
6601 (remove-text-properties beg end
6602 '(mouse-face t keymap t org-linked-text t
6603 invisible t intangible t
6604 org-emphasis t))
6605 (org-remove-font-lock-display-properties beg end)))
6607 (defconst org-script-display '(((raise -0.3) (height 0.7))
6608 ((raise 0.3) (height 0.7))
6609 ((raise -0.5))
6610 ((raise 0.5)))
6611 "Display properties for showing superscripts and subscripts.")
6613 (defun org-remove-font-lock-display-properties (beg end)
6614 "Remove specific display properties that have been added by font lock.
6615 The will remove the raise properties that are used to show superscripts
6616 and subscripts."
6617 (let (next prop)
6618 (while (< beg end)
6619 (setq next (next-single-property-change beg 'display nil end)
6620 prop (get-text-property beg 'display))
6621 (when (member prop org-script-display)
6622 (put-text-property beg next 'display nil))
6623 (setq beg next))))
6625 (defun org-raise-scripts (limit)
6626 "Add raise properties to sub/superscripts."
6627 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6628 (re-search-forward
6629 (if (eq org-use-sub-superscripts t)
6630 org-match-substring-regexp
6631 org-match-substring-with-braces-regexp)
6632 limit t))
6633 (let* ((pos (point)) table-p comment-p
6634 (mpos (match-beginning 3))
6635 (emph-p (get-text-property mpos 'org-emphasis))
6636 (link-p (get-text-property mpos 'mouse-face))
6637 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6638 (goto-char (point-at-bol))
6639 (setq table-p (looking-at-p org-table-dataline-regexp)
6640 comment-p (looking-at-p "^[ \t]*#[ +]"))
6641 (goto-char pos)
6642 ;; Handle a_b^c
6643 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6644 (unless (or comment-p emph-p link-p keyw-p)
6645 (put-text-property (match-beginning 3) (match-end 0)
6646 'display
6647 (if (equal (char-after (match-beginning 2)) ?^)
6648 (nth (if table-p 3 1) org-script-display)
6649 (nth (if table-p 2 0) org-script-display)))
6650 (add-text-properties (match-beginning 2) (match-end 2)
6651 (list 'invisible t))
6652 (when (and (eq (char-after (match-beginning 3)) ?{)
6653 (eq (char-before (match-end 3)) ?}))
6654 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6655 (list 'invisible t))
6656 (add-text-properties (1- (match-end 3)) (match-end 3)
6657 (list 'invisible t))))
6658 t)))
6660 ;;;; Visibility cycling, including org-goto and indirect buffer
6662 ;;; Cycling
6664 (defvar-local org-cycle-global-status nil)
6665 (put 'org-cycle-global-status 'org-state t)
6666 (defvar-local org-cycle-subtree-status nil)
6667 (put 'org-cycle-subtree-status 'org-state t)
6669 (defvar org-inlinetask-min-level)
6671 (defun org-unlogged-message (&rest args)
6672 "Display a message, but avoid logging it in the *Messages* buffer."
6673 (let ((message-log-max nil))
6674 (apply 'message args)))
6676 ;;;###autoload
6677 (defun org-cycle (&optional arg)
6678 "TAB-action and visibility cycling for Org mode.
6680 This is the command invoked in Org mode by the `TAB' key. Its main
6681 purpose is outline visibility cycling, but it also invokes other actions
6682 in special contexts.
6684 When this function is called with a `\\[universal-argument]' prefix, rotate \
6685 the entire
6686 buffer through 3 states (global cycling)
6687 1. OVERVIEW: Show only top-level headlines.
6688 2. CONTENTS: Show all headlines of all levels, but no body text.
6689 3. SHOW ALL: Show everything.
6691 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6692 switch to the startup visibility,
6693 determined by the variable `org-startup-folded', and by any VISIBILITY
6694 properties in the buffer.
6696 With a `\\[universal-argument] \\[universal-argument] \
6697 \\[universal-argument]' prefix argument, show the entire buffer, including
6698 any drawers.
6700 When inside a table, re-align the table and move to the next field.
6702 When point is at the beginning of a headline, rotate the subtree started
6703 by this line through 3 different states (local cycling)
6704 1. FOLDED: Only the main headline is shown.
6705 2. CHILDREN: The main headline and the direct children are shown.
6706 From this state, you can move to one of the children
6707 and zoom in further.
6708 3. SUBTREE: Show the entire subtree, including body text.
6709 If there is no subtree, switch directly from CHILDREN to FOLDED.
6711 When point is at the beginning of an empty headline and the variable
6712 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6713 of the headline by demoting and promoting it to likely levels. This
6714 speeds up creation document structure by pressing `TAB' once or several
6715 times right after creating a new headline.
6717 When there is a numeric prefix, go up to a heading with level ARG, do
6718 a `show-subtree' and return to the previous cursor position. If ARG
6719 is negative, go up that many levels.
6721 When point is not at the beginning of a headline, execute the global
6722 binding for `TAB', which is re-indenting the line. See the option
6723 `org-cycle-emulate-tab' for details.
6725 As a special case, if point is at the beginning of the buffer and there is
6726 no headline in line 1, this function will act as if called with prefix arg
6727 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6728 prefix arg, but only
6729 if the variable `org-cycle-global-at-bob' is t."
6730 (interactive "P")
6731 (org-load-modules-maybe)
6732 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6733 (and org-cycle-level-after-item/entry-creation
6734 (or (org-cycle-level)
6735 (org-cycle-item-indentation))))
6736 (let* ((limit-level
6737 (or org-cycle-max-level
6738 (and (boundp 'org-inlinetask-min-level)
6739 org-inlinetask-min-level
6740 (1- org-inlinetask-min-level))))
6741 (nstars (and limit-level
6742 (if org-odd-levels-only
6743 (and limit-level (1- (* limit-level 2)))
6744 limit-level)))
6745 (org-outline-regexp
6746 (if (not (derived-mode-p 'org-mode))
6747 outline-regexp
6748 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6749 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6750 (not (looking-at org-outline-regexp))))
6751 (org-cycle-hook
6752 (if bob-special
6753 (delq 'org-optimize-window-after-visibility-change
6754 (copy-sequence org-cycle-hook))
6755 org-cycle-hook))
6756 (pos (point)))
6758 (cond
6760 ((equal arg '(16))
6761 (setq last-command 'dummy)
6762 (org-set-startup-visibility)
6763 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6765 ((equal arg '(64))
6766 (outline-show-all)
6767 (org-unlogged-message "Entire buffer visible, including drawers"))
6769 ((equal arg '(4)) (org-cycle-internal-global))
6771 ;; Try hiding block at point.
6772 ((org-hide-block-toggle-maybe))
6774 ;; Try cdlatex TAB completion
6775 ((org-try-cdlatex-tab))
6777 ;; Table: enter it or move to the next field.
6778 ((org-at-table-p 'any)
6779 (if (org-at-table.el-p)
6780 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6781 Use `\\[org-edit-special]' to edit table.el tables"))
6782 (if arg (org-table-edit-field t)
6783 (org-table-justify-field-maybe)
6784 (call-interactively 'org-table-next-field))))
6786 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6788 ;; Global cycling: delegate to `org-cycle-internal-global'.
6789 (bob-special (org-cycle-internal-global))
6791 ;; Drawers: delegate to `org-flag-drawer'.
6792 ((save-excursion
6793 (beginning-of-line 1)
6794 (looking-at org-drawer-regexp))
6795 (org-flag-drawer ; toggle block visibility
6796 (not (get-char-property (match-end 0) 'invisible))))
6798 ;; Show-subtree, ARG levels up from here.
6799 ((integerp arg)
6800 (save-excursion
6801 (org-back-to-heading)
6802 (outline-up-heading (if (< arg 0) (- arg)
6803 (- (funcall outline-level) arg)))
6804 (org-show-subtree)))
6806 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6807 ((and (featurep 'org-inlinetask)
6808 (org-inlinetask-at-task-p)
6809 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6810 (org-inlinetask-toggle-visibility))
6812 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6813 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6814 (save-excursion (move-beginning-of-line 1)
6815 (looking-at org-outline-regexp)))
6816 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6817 (org-cycle-internal-local))
6819 ;; From there: TAB emulation and template completion.
6820 (buffer-read-only (org-back-to-heading))
6822 ((run-hook-with-args-until-success
6823 'org-tab-after-check-for-cycling-hook))
6825 ((org-try-structure-completion))
6827 ((run-hook-with-args-until-success
6828 'org-tab-before-tab-emulation-hook))
6830 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6831 (or (not (bolp))
6832 (not (looking-at org-outline-regexp))))
6833 (call-interactively (global-key-binding "\t")))
6835 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6836 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6837 (or (and (eq org-cycle-emulate-tab 'white)
6838 (= (match-end 0) (point-at-eol)))
6839 (and (eq org-cycle-emulate-tab 'whitestart)
6840 (>= (match-end 0) pos))))
6842 (eq org-cycle-emulate-tab t))
6843 (call-interactively (global-key-binding "\t")))
6845 (t (save-excursion
6846 (org-back-to-heading)
6847 (org-cycle)))))))
6849 (defun org-cycle-internal-global ()
6850 "Do the global cycling action."
6851 ;; Hack to avoid display of messages for .org attachments in Gnus
6852 (let ((ga (string-match "\\*fontification" (buffer-name))))
6853 (cond
6854 ((and (eq last-command this-command)
6855 (eq org-cycle-global-status 'overview))
6856 ;; We just created the overview - now do table of contents
6857 ;; This can be slow in very large buffers, so indicate action
6858 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6859 (unless ga (org-unlogged-message "CONTENTS..."))
6860 (org-content)
6861 (unless ga (org-unlogged-message "CONTENTS...done"))
6862 (setq org-cycle-global-status 'contents)
6863 (run-hook-with-args 'org-cycle-hook 'contents))
6865 ((and (eq last-command this-command)
6866 (eq org-cycle-global-status 'contents))
6867 ;; We just showed the table of contents - now show everything
6868 (run-hook-with-args 'org-pre-cycle-hook 'all)
6869 (outline-show-all)
6870 (unless ga (org-unlogged-message "SHOW ALL"))
6871 (setq org-cycle-global-status 'all)
6872 (run-hook-with-args 'org-cycle-hook 'all))
6875 ;; Default action: go to overview
6876 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6877 (org-overview)
6878 (unless ga (org-unlogged-message "OVERVIEW"))
6879 (setq org-cycle-global-status 'overview)
6880 (run-hook-with-args 'org-cycle-hook 'overview)))))
6882 (defvar org-called-with-limited-levels nil
6883 "Non-nil when `org-with-limited-levels' is currently active.")
6885 (defun org-invisible-p (&optional pos)
6886 "Non-nil if the character after POS is invisible.
6887 If POS is nil, use `point' instead."
6888 (get-char-property (or pos (point)) 'invisible))
6890 (defun org-cycle-internal-local ()
6891 "Do the local cycling action."
6892 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6893 ;; First, determine end of headline (EOH), end of subtree or item
6894 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6895 (save-excursion
6896 (if (org-at-item-p)
6897 (progn
6898 (beginning-of-line)
6899 (setq struct (org-list-struct))
6900 (setq eoh (point-at-eol))
6901 (setq eos (org-list-get-item-end-before-blank (point) struct))
6902 (setq has-children (org-list-has-child-p (point) struct)))
6903 (org-back-to-heading)
6904 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6905 (setq eos (save-excursion (org-end-of-subtree t t)
6906 (when (bolp) (backward-char)) (point)))
6907 (setq has-children
6908 (or (save-excursion
6909 (let ((level (funcall outline-level)))
6910 (outline-next-heading)
6911 (and (org-at-heading-p t)
6912 (> (funcall outline-level) level))))
6913 (save-excursion
6914 (org-list-search-forward (org-item-beginning-re) eos t)))))
6915 ;; Determine end invisible part of buffer (EOL)
6916 (beginning-of-line 2)
6917 (while (and (not (eobp)) ;This is like `next-line'.
6918 (get-char-property (1- (point)) 'invisible))
6919 (goto-char (next-single-char-property-change (point) 'invisible))
6920 (and (eolp) (beginning-of-line 2)))
6921 (setq eol (point)))
6922 ;; Find out what to do next and set `this-command'
6923 (cond
6924 ((= eos eoh)
6925 ;; Nothing is hidden behind this heading
6926 (unless (org-before-first-heading-p)
6927 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6928 (org-unlogged-message "EMPTY ENTRY")
6929 (setq org-cycle-subtree-status nil)
6930 (save-excursion
6931 (goto-char eos)
6932 (outline-next-heading)
6933 (when (org-invisible-p) (org-flag-heading nil))))
6934 ((and (or (>= eol eos)
6935 (not (string-match "\\S-" (buffer-substring eol eos))))
6936 (or has-children
6937 (not (setq children-skipped
6938 org-cycle-skip-children-state-if-no-children))))
6939 ;; Entire subtree is hidden in one line: children view
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-pre-cycle-hook 'children))
6942 (if (org-at-item-p)
6943 (org-list-set-item-visibility (point-at-bol) struct 'children)
6944 (org-show-entry)
6945 (org-with-limited-levels (org-show-children))
6946 ;; FIXME: This slows down the func way too much.
6947 ;; How keep drawers hidden in subtree anyway?
6948 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6949 ;; (org-cycle-hide-drawers 'subtree))
6951 ;; Fold every list in subtree to top-level items.
6952 (when (eq org-cycle-include-plain-lists 'integrate)
6953 (save-excursion
6954 (org-back-to-heading)
6955 (while (org-list-search-forward (org-item-beginning-re) eos t)
6956 (beginning-of-line 1)
6957 (let* ((struct (org-list-struct))
6958 (prevs (org-list-prevs-alist struct))
6959 (end (org-list-get-bottom-point struct)))
6960 (dolist (e (org-list-get-all-items (point) struct prevs))
6961 (org-list-set-item-visibility e struct 'folded))
6962 (goto-char (if (< end eos) end eos)))))))
6963 (org-unlogged-message "CHILDREN")
6964 (save-excursion
6965 (goto-char eos)
6966 (outline-next-heading)
6967 (when (org-invisible-p) (org-flag-heading nil)))
6968 (setq org-cycle-subtree-status 'children)
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-cycle-hook 'children)))
6971 ((or children-skipped
6972 (and (eq last-command this-command)
6973 (eq org-cycle-subtree-status 'children)))
6974 ;; We just showed the children, or no children are there,
6975 ;; now show everything.
6976 (unless (org-before-first-heading-p)
6977 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6978 (outline-flag-region eoh eos nil)
6979 (org-unlogged-message
6980 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6981 (setq org-cycle-subtree-status 'subtree)
6982 (unless (org-before-first-heading-p)
6983 (run-hook-with-args 'org-cycle-hook 'subtree)))
6985 ;; Default action: hide the subtree.
6986 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6987 (outline-flag-region eoh eos t)
6988 (org-unlogged-message "FOLDED")
6989 (setq org-cycle-subtree-status 'folded)
6990 (unless (org-before-first-heading-p)
6991 (run-hook-with-args 'org-cycle-hook 'folded))))))
6993 ;;;###autoload
6994 (defun org-global-cycle (&optional arg)
6995 "Cycle the global visibility. For details see `org-cycle'.
6996 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6997 With a numeric prefix, show all headlines up to that level."
6998 (interactive "P")
6999 (let ((org-cycle-include-plain-lists
7000 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7001 (cond
7002 ((integerp arg)
7003 (outline-show-all)
7004 (outline-hide-sublevels arg)
7005 (setq org-cycle-global-status 'contents))
7006 ((equal arg '(4))
7007 (org-set-startup-visibility)
7008 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7010 (org-cycle '(4))))))
7012 (defun org-set-startup-visibility ()
7013 "Set the visibility required by startup options and properties."
7014 (cond
7015 ((eq org-startup-folded t)
7016 (org-overview))
7017 ((eq org-startup-folded 'content)
7018 (org-content))
7019 ((or (eq org-startup-folded 'showeverything)
7020 (eq org-startup-folded nil))
7021 (outline-show-all)))
7022 (unless (eq org-startup-folded 'showeverything)
7023 (when org-hide-block-startup (org-hide-block-all))
7024 (org-set-visibility-according-to-property 'no-cleanup)
7025 (org-cycle-hide-archived-subtrees 'all)
7026 (org-cycle-hide-drawers 'all)
7027 (org-cycle-show-empty-lines t)))
7029 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7030 "Switch subtree visibilities according to :VISIBILITY: property."
7031 (interactive)
7032 (org-with-wide-buffer
7033 (goto-char (point-min))
7034 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7035 (if (not (org-at-property-p)) (outline-next-heading)
7036 (let ((state (match-string 3)))
7037 (save-excursion
7038 (org-back-to-heading t)
7039 (outline-hide-subtree)
7040 (org-reveal)
7041 (cond
7042 ((equal state "folded")
7043 (outline-hide-subtree))
7044 ((equal state "children")
7045 (org-show-hidden-entry)
7046 (org-show-children))
7047 ((equal state "content")
7048 (save-excursion
7049 (save-restriction
7050 (org-narrow-to-subtree)
7051 (org-content))))
7052 ((member state '("all" "showall"))
7053 (outline-show-subtree)))))))
7054 (unless no-cleanup
7055 (org-cycle-hide-archived-subtrees 'all)
7056 (org-cycle-hide-drawers 'all)
7057 (org-cycle-show-empty-lines 'all))))
7059 ;; This function uses outline-regexp instead of the more fundamental
7060 ;; org-outline-regexp so that org-cycle-global works outside of Org
7061 ;; buffers, where outline-regexp is needed.
7062 (defun org-overview ()
7063 "Switch to overview mode, showing only top-level headlines.
7064 This shows all headlines with a level equal or greater than the level
7065 of the first headline in the buffer. This is important, because if the
7066 first headline is not level one, then (hide-sublevels 1) gives confusing
7067 results."
7068 (interactive)
7069 (save-excursion
7070 (let ((level
7071 (save-excursion
7072 (goto-char (point-min))
7073 (when (re-search-forward (concat "^" outline-regexp) nil t)
7074 (goto-char (match-beginning 0))
7075 (funcall outline-level)))))
7076 (and level (outline-hide-sublevels level)))))
7078 (defun org-content (&optional arg)
7079 "Show all headlines in the buffer, like a table of contents.
7080 With numerical argument N, show content up to level N."
7081 (interactive "P")
7082 (org-overview)
7083 (save-excursion
7084 ;; Visit all headings and show their offspring
7085 (and (integerp arg) (org-overview))
7086 (goto-char (point-max))
7087 (catch 'exit
7088 (while (and (progn (condition-case nil
7089 (outline-previous-visible-heading 1)
7090 (error (goto-char (point-min))))
7092 (looking-at org-outline-regexp))
7093 (if (integerp arg)
7094 (org-show-children (1- arg))
7095 (outline-show-branches))
7096 (when (bobp) (throw 'exit nil))))))
7098 (defun org-optimize-window-after-visibility-change (state)
7099 "Adjust the window after a change in outline visibility.
7100 This function is the default value of the hook `org-cycle-hook'."
7101 (when (get-buffer-window (current-buffer))
7102 (cond
7103 ((eq state 'content) nil)
7104 ((eq state 'all) nil)
7105 ((eq state 'folded) nil)
7106 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7107 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7109 (defun org-remove-empty-overlays-at (pos)
7110 "Remove outline overlays that do not contain non-white stuff."
7111 (dolist (o (overlays-at pos))
7112 (and (eq 'outline (overlay-get o 'invisible))
7113 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7114 (overlay-end o))))
7115 (delete-overlay o))))
7117 (defun org-clean-visibility-after-subtree-move ()
7118 "Fix visibility issues after moving a subtree."
7119 ;; First, find a reasonable region to look at:
7120 ;; Start two siblings above, end three below
7121 (let* ((beg (save-excursion
7122 (and (org-get-last-sibling)
7123 (org-get-last-sibling))
7124 (point)))
7125 (end (save-excursion
7126 (and (org-get-next-sibling)
7127 (org-get-next-sibling)
7128 (org-get-next-sibling))
7129 (if (org-at-heading-p)
7130 (point-at-eol)
7131 (point))))
7132 (level (looking-at "\\*+"))
7133 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7134 (save-excursion
7135 (save-restriction
7136 (narrow-to-region beg end)
7137 (when re
7138 ;; Properly fold already folded siblings
7139 (goto-char (point-min))
7140 (while (re-search-forward re nil t)
7141 (when (and (not (org-invisible-p))
7142 (save-excursion
7143 (goto-char (point-at-eol)) (org-invisible-p)))
7144 (outline-hide-entry))))
7145 (org-cycle-show-empty-lines 'overview)
7146 (org-cycle-hide-drawers 'overview)))))
7148 (defun org-cycle-show-empty-lines (state)
7149 "Show empty lines above all visible headlines.
7150 The region to be covered depends on STATE when called through
7151 `org-cycle-hook'. Lisp program can use t for STATE to get the
7152 entire buffer covered. Note that an empty line is only shown if there
7153 are at least `org-cycle-separator-lines' empty lines before the headline."
7154 (when (/= org-cycle-separator-lines 0)
7155 (save-excursion
7156 (let* ((n (abs org-cycle-separator-lines))
7157 (re (cond
7158 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7159 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7160 (t (let ((ns (number-to-string (- n 2))))
7161 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7162 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7163 beg end)
7164 (cond
7165 ((memq state '(overview contents t))
7166 (setq beg (point-min) end (point-max)))
7167 ((memq state '(children folded))
7168 (setq beg (point)
7169 end (progn (org-end-of-subtree t t)
7170 (line-beginning-position 2)))))
7171 (when beg
7172 (goto-char beg)
7173 (while (re-search-forward re end t)
7174 (unless (get-char-property (match-end 1) 'invisible)
7175 (let ((e (match-end 1))
7176 (b (if (>= org-cycle-separator-lines 0)
7177 (match-beginning 1)
7178 (save-excursion
7179 (goto-char (match-beginning 0))
7180 (skip-chars-backward " \t\n")
7181 (line-end-position)))))
7182 (outline-flag-region b e nil))))))))
7183 ;; Never hide empty lines at the end of the file.
7184 (save-excursion
7185 (goto-char (point-max))
7186 (outline-previous-heading)
7187 (outline-end-of-heading)
7188 (when (and (looking-at "[ \t\n]+")
7189 (= (match-end 0) (point-max)))
7190 (outline-flag-region (point) (match-end 0) nil))))
7192 (defun org-show-empty-lines-in-parent ()
7193 "Move to the parent and re-show empty lines before visible headlines."
7194 (save-excursion
7195 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7196 (org-cycle-show-empty-lines context))))
7198 (defun org-files-list ()
7199 "Return `org-agenda-files' list, plus all open Org files.
7200 This is useful for operations that need to scan all of a user's
7201 open and agenda-wise Org files."
7202 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7203 (dolist (buf (buffer-list))
7204 (with-current-buffer buf
7205 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7206 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7207 files))
7209 (defsubst org-entry-beginning-position ()
7210 "Return the beginning position of the current entry."
7211 (save-excursion (org-back-to-heading t) (point)))
7213 (defsubst org-entry-end-position ()
7214 "Return the end position of the current entry."
7215 (save-excursion (outline-next-heading) (point)))
7217 (defun org-cycle-hide-drawers (state &optional exceptions)
7218 "Re-hide all drawers after a visibility state change.
7219 STATE should be one of the symbols listed in the docstring of
7220 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7221 a list of strings specifying which drawers should not be hidden."
7222 (when (and (derived-mode-p 'org-mode)
7223 (not (memq state '(overview folded contents))))
7224 (save-excursion
7225 (let* ((globalp (eq state 'all))
7226 (beg (if globalp (point-min) (point)))
7227 (end (if globalp (point-max)
7228 (if (eq state 'children)
7229 (save-excursion (outline-next-heading) (point))
7230 (org-end-of-subtree t)))))
7231 (goto-char beg)
7232 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7233 (unless (member-ignore-case (match-string 1) exceptions)
7234 (let ((drawer (org-element-at-point)))
7235 (when (memq (org-element-type drawer) '(drawer property-drawer))
7236 (org-flag-drawer t drawer)
7237 ;; Make sure to skip drawer entirely or we might flag
7238 ;; it another time when matching its ending line with
7239 ;; `org-drawer-regexp'.
7240 (goto-char (org-element-property :end drawer))))))))))
7242 (defun org-flag-drawer (flag &optional element)
7243 "When FLAG is non-nil, hide the drawer we are at.
7244 Otherwise make it visible. When optional argument ELEMENT is
7245 a parsed drawer, as returned by `org-element-at-point', hide or
7246 show that drawer instead."
7247 (let ((drawer (or element
7248 (and (save-excursion
7249 (beginning-of-line)
7250 (looking-at-p org-drawer-regexp))
7251 (org-element-at-point)))))
7252 (when (memq (org-element-type drawer) '(drawer property-drawer))
7253 (let ((post (org-element-property :post-affiliated drawer)))
7254 (save-excursion
7255 (outline-flag-region
7256 (progn (goto-char post) (line-end-position))
7257 (progn (goto-char (org-element-property :end drawer))
7258 (skip-chars-backward " \r\t\n")
7259 (line-end-position))
7260 flag))
7261 ;; When the drawer is hidden away, make sure point lies in
7262 ;; a visible part of the buffer.
7263 (when (and flag (> (line-beginning-position) post))
7264 (goto-char post))))))
7266 (defun org-subtree-end-visible-p ()
7267 "Is the end of the current subtree visible?"
7268 (pos-visible-in-window-p
7269 (save-excursion (org-end-of-subtree t) (point))))
7271 (defun org-first-headline-recenter ()
7272 "Move cursor to the first headline and recenter the headline."
7273 (let ((window (get-buffer-window)))
7274 (when window
7275 (goto-char (point-min))
7276 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7277 (set-window-start window (line-beginning-position))))))
7279 ;;; Saving and restoring visibility
7281 (defun org-outline-overlay-data (&optional use-markers)
7282 "Return a list of the locations of all outline overlays.
7283 These are overlays with the `invisible' property value `outline'.
7284 The return value is a list of cons cells, with start and stop
7285 positions for each overlay.
7286 If USE-MARKERS is set, return the positions as markers."
7287 (let (beg end)
7288 (org-with-wide-buffer
7289 (delq nil
7290 (mapcar (lambda (o)
7291 (when (eq (overlay-get o 'invisible) 'outline)
7292 (setq beg (overlay-start o)
7293 end (overlay-end o))
7294 (and beg end (> end beg)
7295 (if use-markers
7296 (cons (copy-marker beg)
7297 (copy-marker end t))
7298 (cons beg end)))))
7299 (overlays-in (point-min) (point-max)))))))
7301 (defun org-set-outline-overlay-data (data)
7302 "Create visibility overlays for all positions in DATA.
7303 DATA should have been made by `org-outline-overlay-data'."
7304 (org-with-wide-buffer
7305 (outline-show-all)
7306 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7308 ;;; Folding of blocks
7310 (defvar-local org-hide-block-overlays nil
7311 "Overlays hiding blocks.")
7313 (defun org-block-map (function &optional start end)
7314 "Call FUNCTION at the head of all source blocks in the current buffer.
7315 Optional arguments START and END can be used to limit the range."
7316 (let ((start (or start (point-min)))
7317 (end (or end (point-max))))
7318 (save-excursion
7319 (goto-char start)
7320 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7321 (save-excursion
7322 (save-match-data
7323 (goto-char (match-beginning 0))
7324 (funcall function)))))))
7326 (defun org-hide-block-toggle-all ()
7327 "Toggle the visibility of all blocks in the current buffer."
7328 (org-block-map 'org-hide-block-toggle))
7330 (defun org-hide-block-all ()
7331 "Fold all blocks in the current buffer."
7332 (interactive)
7333 (org-show-block-all)
7334 (org-block-map 'org-hide-block-toggle-maybe))
7336 (defun org-show-block-all ()
7337 "Unfold all blocks in the current buffer."
7338 (interactive)
7339 (mapc #'delete-overlay org-hide-block-overlays)
7340 (setq org-hide-block-overlays nil))
7342 (defun org-hide-block-toggle-maybe ()
7343 "Toggle visibility of block at point.
7344 Unlike to `org-hide-block-toggle', this function does not throw
7345 an error. Return a non-nil value when toggling is successful."
7346 (interactive)
7347 (ignore-errors (org-hide-block-toggle)))
7349 (defun org-hide-block-toggle (&optional force)
7350 "Toggle the visibility of the current block.
7351 When optional argument FORCE is `off', make block visible. If it
7352 is non-nil, hide it unconditionally. Throw an error when not at
7353 a block. Return a non-nil value when toggling is successful."
7354 (interactive)
7355 (let ((element (org-element-at-point)))
7356 (unless (memq (org-element-type element)
7357 '(center-block comment-block dynamic-block example-block
7358 export-block quote-block special-block
7359 src-block verse-block))
7360 (user-error "Not at a block"))
7361 (let* ((start (save-excursion
7362 (goto-char (org-element-property :post-affiliated element))
7363 (line-end-position)))
7364 (end (save-excursion
7365 (goto-char (org-element-property :end element))
7366 (skip-chars-backward " \r\t\n")
7367 (line-end-position)))
7368 (overlays (overlays-at start)))
7369 (cond
7370 ;; Do nothing when not before or at the block opening line or
7371 ;; at the block closing line.
7372 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7373 ((and (not (eq force 'off))
7374 (not (memq t (mapcar
7375 (lambda (o)
7376 (eq (overlay-get o 'invisible) 'org-hide-block))
7377 overlays))))
7378 (let ((ov (make-overlay start end)))
7379 (overlay-put ov 'invisible 'org-hide-block)
7380 ;; Make the block accessible to `isearch'.
7381 (overlay-put
7382 ov 'isearch-open-invisible
7383 (lambda (ov)
7384 (when (memq ov org-hide-block-overlays)
7385 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7386 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7387 (delete-overlay ov))))
7388 (push ov org-hide-block-overlays)
7389 ;; When the block is hidden away, make sure point is left in
7390 ;; a visible part of the buffer.
7391 (when (> (line-beginning-position) start)
7392 (goto-char start)
7393 (beginning-of-line))
7394 ;; Signal successful toggling.
7396 ((or (not force) (eq force 'off))
7397 (dolist (ov overlays t)
7398 (when (memq ov org-hide-block-overlays)
7399 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7400 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7401 (delete-overlay ov))))))))
7403 ;; Remove overlays when changing major mode
7404 (add-hook 'org-mode-hook
7405 (lambda () (add-hook 'change-major-mode-hook
7406 'org-show-block-all 'append 'local)))
7408 ;;; Org-goto
7410 (defvar org-goto-window-configuration nil)
7411 (defvar org-goto-marker nil)
7412 (defvar org-goto-map)
7413 (defun org-goto-map ()
7414 "Set the keymap `org-goto'."
7415 (setq org-goto-map
7416 (let ((map (make-sparse-keymap)))
7417 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7418 mouse-drag-region universal-argument org-occur)))
7419 (dolist (cmd cmds)
7420 (substitute-key-definition cmd cmd map global-map)))
7421 (suppress-keymap map)
7422 (org-defkey map "\C-m" 'org-goto-ret)
7423 (org-defkey map [(return)] 'org-goto-ret)
7424 (org-defkey map [(left)] 'org-goto-left)
7425 (org-defkey map [(right)] 'org-goto-right)
7426 (org-defkey map [(control ?g)] 'org-goto-quit)
7427 (org-defkey map "\C-i" 'org-cycle)
7428 (org-defkey map [(tab)] 'org-cycle)
7429 (org-defkey map [(down)] 'outline-next-visible-heading)
7430 (org-defkey map [(up)] 'outline-previous-visible-heading)
7431 (if org-goto-auto-isearch
7432 (if (fboundp 'define-key-after)
7433 (define-key-after map [t] 'org-goto-local-auto-isearch)
7434 nil)
7435 (org-defkey map "q" 'org-goto-quit)
7436 (org-defkey map "n" 'outline-next-visible-heading)
7437 (org-defkey map "p" 'outline-previous-visible-heading)
7438 (org-defkey map "f" 'outline-forward-same-level)
7439 (org-defkey map "b" 'outline-backward-same-level)
7440 (org-defkey map "u" 'outline-up-heading))
7441 (org-defkey map "/" 'org-occur)
7442 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7443 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7444 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7445 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7446 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7447 map)))
7449 (defconst org-goto-help
7450 "Browse buffer copy, to find location or copy text.%s
7451 RET=jump to location C-g=quit and return to previous location
7452 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7454 (defvar org-goto-start-pos) ; dynamically scoped parameter
7456 (defun org-goto (&optional alternative-interface)
7457 "Look up a different location in the current file, keeping current visibility.
7459 When you want look-up or go to a different location in a
7460 document, the fastest way is often to fold the entire buffer and
7461 then dive into the tree. This method has the disadvantage, that
7462 the previous location will be folded, which may not be what you
7463 want.
7465 This command works around this by showing a copy of the current
7466 buffer in an indirect buffer, in overview mode. You can dive
7467 into the tree in that copy, use org-occur and incremental search
7468 to find a location. When pressing RET or `Q', the command
7469 returns to the original buffer in which the visibility is still
7470 unchanged. After RET it will also jump to the location selected
7471 in the indirect buffer and expose the headline hierarchy above.
7473 With a prefix argument, use the alternative interface: e.g., if
7474 `org-goto-interface' is `outline' use `outline-path-completion'."
7475 (interactive "P")
7476 (org-goto-map)
7477 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7478 (org-refile-use-outline-path t)
7479 (org-refile-target-verify-function nil)
7480 (interface
7481 (if (not alternative-interface)
7482 org-goto-interface
7483 (if (eq org-goto-interface 'outline)
7484 'outline-path-completion
7485 'outline)))
7486 (org-goto-start-pos (point))
7487 (selected-point
7488 (if (eq interface 'outline)
7489 (car (org-get-location (current-buffer) org-goto-help))
7490 (let ((pa (org-refile-get-location "Goto")))
7491 (org-refile-check-position pa)
7492 (nth 3 pa)))))
7493 (if selected-point
7494 (progn
7495 (org-mark-ring-push org-goto-start-pos)
7496 (goto-char selected-point)
7497 (when (or (org-invisible-p) (org-invisible-p2))
7498 (org-show-context 'org-goto)))
7499 (message "Quit"))))
7501 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7502 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7503 (defvar org-goto-local-auto-isearch-map) ; defined below
7505 (defun org-get-location (_buf help)
7506 "Let the user select a location in current buffer.
7507 This function uses a recursive edit. It returns the selected position
7508 or nil."
7509 (org-no-popups
7510 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7511 (isearch-hide-immediately nil)
7512 (isearch-search-fun-function
7513 (lambda () 'org-goto-local-search-headings))
7514 (org-goto-selected-point org-goto-exit-command))
7515 (save-excursion
7516 (save-window-excursion
7517 (delete-other-windows)
7518 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7519 (pop-to-buffer-same-window
7520 (condition-case nil
7521 (make-indirect-buffer (current-buffer) "*org-goto*")
7522 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7523 (with-output-to-temp-buffer "*Org Help*"
7524 (princ (format help (if org-goto-auto-isearch
7525 " Just type for auto-isearch."
7526 " n/p/f/b/u to navigate, q to quit."))))
7527 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7528 (setq buffer-read-only nil)
7529 (let ((org-startup-truncated t)
7530 (org-startup-folded nil)
7531 (org-startup-align-all-tables nil))
7532 (org-mode)
7533 (org-overview))
7534 (setq buffer-read-only t)
7535 (if (and (boundp 'org-goto-start-pos)
7536 (integer-or-marker-p org-goto-start-pos))
7537 (progn (goto-char org-goto-start-pos)
7538 (when (org-invisible-p)
7539 (org-show-set-visibility 'lineage)))
7540 (goto-char (point-min)))
7541 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7542 (message "Select location and press RET")
7543 (use-local-map org-goto-map)
7544 (recursive-edit)))
7545 (kill-buffer "*org-goto*")
7546 (cons org-goto-selected-point org-goto-exit-command))))
7548 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7549 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7550 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7551 (if (fboundp 'isearch-other-control-char)
7552 (progn
7553 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7554 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7555 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7556 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7557 (define-key org-goto-local-auto-isearch-map [return] nil))
7559 (defun org-goto-local-search-headings (string bound noerror)
7560 "Search and make sure that any matches are in headlines."
7561 (catch 'return
7562 (while (if isearch-forward
7563 (search-forward string bound noerror)
7564 (search-backward string bound noerror))
7565 (when (save-match-data
7566 (and (save-excursion
7567 (beginning-of-line)
7568 (looking-at org-complex-heading-regexp))
7569 (or (not (match-beginning 5))
7570 (< (point) (match-beginning 5)))))
7571 (throw 'return (point))))))
7573 (defun org-goto-local-auto-isearch ()
7574 "Start isearch."
7575 (interactive)
7576 (goto-char (point-min))
7577 (let ((keys (this-command-keys)))
7578 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7579 (isearch-mode t)
7580 (isearch-process-search-char (string-to-char keys)))))
7582 (defun org-goto-ret (&optional _arg)
7583 "Finish `org-goto' by going to the new location."
7584 (interactive "P")
7585 (setq org-goto-selected-point (point))
7586 (setq org-goto-exit-command 'return)
7587 (throw 'exit nil))
7589 (defun org-goto-left ()
7590 "Finish `org-goto' by going to the new location."
7591 (interactive)
7592 (if (org-at-heading-p)
7593 (progn
7594 (beginning-of-line 1)
7595 (setq org-goto-selected-point (point)
7596 org-goto-exit-command 'left)
7597 (throw 'exit nil))
7598 (user-error "Not on a heading")))
7600 (defun org-goto-right ()
7601 "Finish `org-goto' by going to the new location."
7602 (interactive)
7603 (if (org-at-heading-p)
7604 (progn
7605 (setq org-goto-selected-point (point)
7606 org-goto-exit-command 'right)
7607 (throw 'exit nil))
7608 (user-error "Not on a heading")))
7610 (defun org-goto-quit ()
7611 "Finish `org-goto' without cursor motion."
7612 (interactive)
7613 (setq org-goto-selected-point nil)
7614 (setq org-goto-exit-command 'quit)
7615 (throw 'exit nil))
7617 ;;; Indirect buffer display of subtrees
7619 (defvar org-indirect-dedicated-frame nil
7620 "This is the frame being used for indirect tree display.")
7621 (defvar org-last-indirect-buffer nil)
7623 (defun org-tree-to-indirect-buffer (&optional arg)
7624 "Create indirect buffer and narrow it to current subtree.
7626 With a numerical prefix ARG, go up to this level and then take that tree.
7627 If ARG is negative, go up that many levels.
7629 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7630 indirect buffer previously made with this command, to avoid proliferation of
7631 indirect buffers. However, when you call the command with a \
7632 `\\[universal-argument]' prefix, or
7633 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7634 so that you can work with several indirect buffers at the same time. If
7635 `org-indirect-buffer-display' is `dedicated-frame', the \
7636 `\\[universal-argument]' prefix also
7637 requests that a new frame be made for the new buffer, so that the dedicated
7638 frame is not changed."
7639 (interactive "P")
7640 (let ((cbuf (current-buffer))
7641 (cwin (selected-window))
7642 (pos (point))
7643 beg end level heading ibuf)
7644 (save-excursion
7645 (org-back-to-heading t)
7646 (when (numberp arg)
7647 (setq level (org-outline-level))
7648 (when (< arg 0) (setq arg (+ level arg)))
7649 (while (> (setq level (org-outline-level)) arg)
7650 (org-up-heading-safe)))
7651 (setq beg (point)
7652 heading (org-get-heading 'no-tags))
7653 (org-end-of-subtree t t)
7654 (when (org-at-heading-p) (backward-char 1))
7655 (setq end (point)))
7656 (when (and (buffer-live-p org-last-indirect-buffer)
7657 (not (eq org-indirect-buffer-display 'new-frame))
7658 (not arg))
7659 (kill-buffer org-last-indirect-buffer))
7660 (setq ibuf (org-get-indirect-buffer cbuf heading)
7661 org-last-indirect-buffer ibuf)
7662 (cond
7663 ((or (eq org-indirect-buffer-display 'new-frame)
7664 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7665 (select-frame (make-frame))
7666 (delete-other-windows)
7667 (pop-to-buffer-same-window ibuf)
7668 (org-set-frame-title heading))
7669 ((eq org-indirect-buffer-display 'dedicated-frame)
7670 (raise-frame
7671 (select-frame (or (and org-indirect-dedicated-frame
7672 (frame-live-p org-indirect-dedicated-frame)
7673 org-indirect-dedicated-frame)
7674 (setq org-indirect-dedicated-frame (make-frame)))))
7675 (delete-other-windows)
7676 (pop-to-buffer-same-window ibuf)
7677 (org-set-frame-title (concat "Indirect: " heading)))
7678 ((eq org-indirect-buffer-display 'current-window)
7679 (pop-to-buffer-same-window ibuf))
7680 ((eq org-indirect-buffer-display 'other-window)
7681 (pop-to-buffer ibuf))
7682 (t (error "Invalid value")))
7683 (narrow-to-region beg end)
7684 (outline-show-all)
7685 (goto-char pos)
7686 (run-hook-with-args 'org-cycle-hook 'all)
7687 (and (window-live-p cwin) (select-window cwin))))
7689 (defun org-get-indirect-buffer (&optional buffer heading)
7690 (setq buffer (or buffer (current-buffer)))
7691 (let ((n 1) (base (buffer-name buffer)) bname)
7692 (while (buffer-live-p
7693 (get-buffer
7694 (setq bname
7695 (concat base "-"
7696 (if heading (concat heading "-" (number-to-string n))
7697 (number-to-string n))))))
7698 (setq n (1+ n)))
7699 (condition-case nil
7700 (make-indirect-buffer buffer bname 'clone)
7701 (error (make-indirect-buffer buffer bname)))))
7703 (defun org-set-frame-title (title)
7704 "Set the title of the current frame to the string TITLE."
7705 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7707 ;;;; Structure editing
7709 ;;; Inserting headlines
7711 (defun org--line-empty-p (n)
7712 "Is the Nth next line empty?
7714 Counts the current line as N = 1 and the previous line as N = 0;
7715 see `beginning-of-line'."
7716 (save-excursion
7717 (and (not (bobp))
7718 (or (beginning-of-line n) t)
7719 (save-match-data
7720 (looking-at "[ \t]*$")))))
7722 (defun org-previous-line-empty-p ()
7723 "Is the previous line a blank line?
7724 When NEXT is non-nil, check the next line instead."
7725 (org--line-empty-p 0))
7727 (defun org-next-line-empty-p ()
7728 "Is the previous line a blank line?
7729 When NEXT is non-nil, check the next line instead."
7730 (org--line-empty-p 2))
7732 (defun org--blank-before-heading-p (&optional parent)
7733 "Non-nil when an empty line should precede a new heading here.
7734 When optional argument PARENT is non-nil, consider parent
7735 headline instead of current one."
7736 (pcase (assq 'heading org-blank-before-new-entry)
7737 (`(heading . auto)
7738 (save-excursion
7739 (org-with-limited-levels
7740 (unless (and (org-before-first-heading-p)
7741 (not (outline-next-heading)))
7742 (org-back-to-heading t)
7743 (when parent (org-up-heading-safe))
7744 (cond ((not (bobp))
7745 (org-previous-line-empty-p))
7746 ((outline-next-heading)
7747 (org-previous-line-empty-p))
7748 ;; Ignore trailing spaces on last buffer line.
7749 ((progn (skip-chars-backward " \t") (bolp))
7750 (org-previous-line-empty-p))
7751 (t nil))))))
7752 (`(heading . ,value) value)
7753 (_ nil)))
7755 (defun org-insert-heading (&optional arg invisible-ok top)
7756 "Insert a new heading or an item with the same depth at point.
7758 If point is at the beginning of a heading, insert a new heading
7759 or a new headline above the current one. When at the beginning
7760 of a regular line of text, turn it into a heading.
7762 If point is in the middle of a line, split it and create a new
7763 headline with the text in the current line after point (see
7764 `org-M-RET-may-split-line' on how to modify this behavior). As
7765 a special case, on a headline, splitting can only happen on the
7766 title itself. E.g., this excludes breaking stars or tags.
7768 With a `\\[universal-argument]' prefix, set \
7769 `org-insert-heading-respect-content' to
7770 a non-nil value for the duration of the command. This forces the
7771 insertion of a heading after the current subtree, independently
7772 on the location of point.
7774 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7775 insert the heading at the end of the tree
7776 above the current heading. For example, if point is within a
7777 2nd-level heading, then it will insert a 2nd-level heading at
7778 the end of the 1st-level parent subtree.
7780 When INVISIBLE-OK is set, stop at invisible headlines when going
7781 back. This is important for non-interactive uses of the
7782 command.
7784 When optional argument TOP is non-nil, insert a level 1 heading,
7785 unconditionally."
7786 (interactive "P")
7787 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7788 (level (org-current-level))
7789 (stars (make-string (if (and level (not top)) level 1) ?*)))
7790 (cond
7791 ((or org-insert-heading-respect-content
7792 (member arg '((4) (16)))
7793 (and (not invisible-ok)
7794 (invisible-p (max (1- (point)) (point-min)))))
7795 ;; Position point at the location of insertion.
7796 (if (not level) ;before first headline
7797 (org-with-limited-levels (outline-next-heading))
7798 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7799 ;; is nil.
7800 (org-with-limited-levels (org-back-to-heading invisible-ok))
7801 (cond ((equal arg '(16))
7802 (org-up-heading-safe)
7803 (org-end-of-subtree t t))
7805 (org-end-of-subtree t t))))
7806 (unless (bolp) (insert "\n")) ;ensure final newline
7807 (unless (and blank? (org-previous-line-empty-p))
7808 (org-N-empty-lines-before-current (if blank? 1 0)))
7809 (insert stars " \n")
7810 (forward-char -1))
7811 ;; At a headline...
7812 ((org-at-heading-p)
7813 (cond ((bolp)
7814 (when blank? (save-excursion (insert "\n")))
7815 (save-excursion (insert stars " \n"))
7816 (unless (and blank? (org-previous-line-empty-p))
7817 (org-N-empty-lines-before-current (if blank? 1 0)))
7818 (end-of-line))
7819 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7820 (org-match-line org-complex-heading-regexp)
7821 (org-pos-in-match-range (point) 4))
7822 ;; Grab the text that should moved to the new headline.
7823 ;; Preserve tags.
7824 (let ((split (delete-and-extract-region (point) (match-end 4))))
7825 (if (looking-at "[ \t]*$") (replace-match "")
7826 (org-set-tags nil t))
7827 (end-of-line)
7828 (when blank? (insert "\n"))
7829 (insert "\n" stars " ")
7830 (when (org-string-nw-p split) (insert split))
7831 (when (eobp) (save-excursion (insert "\n")))))
7833 (end-of-line)
7834 (when blank? (insert "\n"))
7835 (insert "\n" stars " ")
7836 (when (eobp) (save-excursion (insert "\n"))))))
7837 ;; On regular text, turn line into a headline or split, if
7838 ;; appropriate.
7839 ((bolp)
7840 (insert stars " ")
7841 (unless (and blank? (org-previous-line-empty-p))
7842 (org-N-empty-lines-before-current (if blank? 1 0))))
7844 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7845 (end-of-line))
7846 (insert "\n" stars " ")
7847 (unless (and blank? (org-previous-line-empty-p))
7848 (org-N-empty-lines-before-current (if blank? 1 0))))))
7849 (run-hooks 'org-insert-heading-hook))
7851 (defun org-N-empty-lines-before-current (n)
7852 "Make the number of empty lines before current exactly N.
7853 So this will delete or add empty lines."
7854 (let ((column (current-column)))
7855 (beginning-of-line)
7856 (unless (bobp)
7857 (let ((start (save-excursion
7858 (skip-chars-backward " \r\t\n")
7859 (line-end-position))))
7860 (delete-region start (line-end-position 0))))
7861 (insert (make-string n ?\n))
7862 (move-to-column column)))
7864 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7865 "Return the heading of the current entry, without the stars.
7866 When NO-TAGS is non-nil, don't include tags.
7867 When NO-TODO is non-nil, don't include TODO keywords.
7868 When NO-PRIORITY is non-nil, don't include priority cookie.
7869 When NO-COMMENT is non-nil, don't include COMMENT string."
7870 (save-excursion
7871 (org-back-to-heading t)
7872 (let ((case-fold-search nil))
7873 (looking-at org-complex-heading-regexp)
7874 (let ((todo (and (not no-todo) (match-string 2)))
7875 (priority (and (not no-priority) (match-string 3)))
7876 (headline (pcase (match-string 4)
7877 (`nil "")
7878 ((and (guard no-comment) h)
7879 (replace-regexp-in-string
7880 (eval-when-compile
7881 (format "\\`%s[ \t]+" org-comment-string))
7882 "" h))
7883 (h h)))
7884 (tags (and (not no-tags) (match-string 5))))
7885 (mapconcat #'identity
7886 (delq nil (list todo priority headline tags))
7887 " ")))))
7889 (defvar orgstruct-mode) ; defined below
7891 (defun org-heading-components ()
7892 "Return the components of the current heading.
7893 This is a list with the following elements:
7894 - the level as an integer
7895 - the reduced level, different if `org-odd-levels-only' is set.
7896 - the TODO keyword, or nil
7897 - the priority character, like ?A, or nil if no priority is given
7898 - the headline text itself, or the tags string if no headline text
7899 - the tags string, or nil."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (when (let (case-fold-search)
7903 (looking-at
7904 (if orgstruct-mode
7905 org-heading-regexp
7906 org-complex-heading-regexp)))
7907 (if orgstruct-mode
7908 (list (length (match-string 1))
7909 (org-reduced-level (length (match-string 1)))
7912 (match-string 2)
7913 nil)
7914 (list (length (match-string 1))
7915 (org-reduced-level (length (match-string 1)))
7916 (match-string-no-properties 2)
7917 (and (match-end 3) (aref (match-string 3) 2))
7918 (match-string-no-properties 4)
7919 (match-string-no-properties 5))))))
7921 (defun org-get-entry ()
7922 "Get the entry text, after heading, entire subtree."
7923 (save-excursion
7924 (org-back-to-heading t)
7925 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7927 (defun org-edit-headline (&optional heading)
7928 "Edit the current headline.
7929 Set it to HEADING when provided."
7930 (interactive)
7931 (org-with-wide-buffer
7932 (org-back-to-heading t)
7933 (let ((case-fold-search nil))
7934 (when (looking-at org-complex-heading-regexp)
7935 (let* ((old (match-string-no-properties 4))
7936 (new (save-match-data
7937 (org-trim (or heading (read-string "Edit: " old))))))
7938 (unless (equal old new)
7939 (if old (replace-match new t t nil 4)
7940 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7941 (insert " " new))
7942 (org-set-tags nil t)
7943 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7945 (defun org-insert-heading-after-current ()
7946 "Insert a new heading with same level as current, after current subtree."
7947 (interactive)
7948 (org-back-to-heading)
7949 (org-insert-heading)
7950 (org-move-subtree-down)
7951 (end-of-line 1))
7953 (defun org-insert-heading-respect-content (&optional invisible-ok)
7954 "Insert heading with `org-insert-heading-respect-content' set to t."
7955 (interactive)
7956 (org-insert-heading '(4) invisible-ok))
7958 (defun org-insert-todo-heading-respect-content (&optional force-state)
7959 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7960 (interactive)
7961 (org-insert-todo-heading force-state '(4)))
7963 (defun org-insert-todo-heading (arg &optional force-heading)
7964 "Insert a new heading with the same level and TODO state as current heading.
7966 If the heading has no TODO state, or if the state is DONE, use
7967 the first state (TODO by default). Also with one prefix arg,
7968 force first state. With two prefix args, force inserting at the
7969 end of the parent subtree.
7971 When called at a plain list item, insert a new item with an
7972 unchecked check box."
7973 (interactive "P")
7974 (when (or force-heading (not (org-insert-item 'checkbox)))
7975 (org-insert-heading (or (and (equal arg '(16)) '(16))
7976 force-heading))
7977 (save-excursion
7978 (org-back-to-heading)
7979 (outline-previous-heading)
7980 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7981 (let* ((new-mark-x
7982 (if (or (equal arg '(4))
7983 (not (match-beginning 2))
7984 (member (match-string 2) org-done-keywords))
7985 (car org-todo-keywords-1)
7986 (match-string 2)))
7987 (new-mark
7989 (run-hook-with-args-until-success
7990 'org-todo-get-default-hook new-mark-x nil)
7991 new-mark-x)))
7992 (beginning-of-line 1)
7993 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7994 (if org-treat-insert-todo-heading-as-state-change
7995 (org-todo new-mark)
7996 (insert new-mark " "))))
7997 (when org-provide-todo-statistics
7998 (org-update-parent-todo-statistics))))
8000 (defun org-insert-subheading (arg)
8001 "Insert a new subheading and demote it.
8002 Works for outline headings and for plain lists alike."
8003 (interactive "P")
8004 (org-insert-heading arg)
8005 (cond
8006 ((org-at-heading-p) (org-do-demote))
8007 ((org-at-item-p) (org-indent-item))))
8009 (defun org-insert-todo-subheading (arg)
8010 "Insert a new subheading with TODO keyword or checkbox and demote it.
8011 Works for outline headings and for plain lists alike."
8012 (interactive "P")
8013 (org-insert-todo-heading arg)
8014 (cond
8015 ((org-at-heading-p) (org-do-demote))
8016 ((org-at-item-p) (org-indent-item))))
8018 ;;; Promotion and Demotion
8020 (defvar org-after-demote-entry-hook nil
8021 "Hook run after an entry has been demoted.
8022 The cursor will be at the beginning of the entry.
8023 When a subtree is being demoted, the hook will be called for each node.")
8025 (defvar org-after-promote-entry-hook nil
8026 "Hook run after an entry has been promoted.
8027 The cursor will be at the beginning of the entry.
8028 When a subtree is being promoted, the hook will be called for each node.")
8030 (defun org-promote-subtree ()
8031 "Promote the entire subtree.
8032 See also `org-promote'."
8033 (interactive)
8034 (save-excursion
8035 (org-with-limited-levels (org-map-tree 'org-promote)))
8036 (org-fix-position-after-promote))
8038 (defun org-demote-subtree ()
8039 "Demote the entire subtree.
8040 See `org-demote' and `org-promote'."
8041 (interactive)
8042 (save-excursion
8043 (org-with-limited-levels (org-map-tree 'org-demote)))
8044 (org-fix-position-after-promote))
8046 (defun org-do-promote ()
8047 "Promote the current heading higher up the tree.
8048 If the region is active in `transient-mark-mode', promote all
8049 headings in the region."
8050 (interactive)
8051 (save-excursion
8052 (if (org-region-active-p)
8053 (org-map-region 'org-promote (region-beginning) (region-end))
8054 (org-promote)))
8055 (org-fix-position-after-promote))
8057 (defun org-do-demote ()
8058 "Demote the current heading lower down the tree.
8059 If the region is active in `transient-mark-mode', demote all
8060 headings in the region."
8061 (interactive)
8062 (save-excursion
8063 (if (org-region-active-p)
8064 (org-map-region 'org-demote (region-beginning) (region-end))
8065 (org-demote)))
8066 (org-fix-position-after-promote))
8068 (defun org-fix-position-after-promote ()
8069 "Fix cursor position and indentation after demoting/promoting."
8070 (let ((pos (point)))
8071 (when (save-excursion
8072 (beginning-of-line)
8073 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8074 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8075 (cond ((eobp) (insert " "))
8076 ((eolp) (insert " "))
8077 ((equal (char-after) ?\s) (forward-char 1))))))
8079 (defun org-current-level ()
8080 "Return the level of the current entry, or nil if before the first headline.
8081 The level is the number of stars at the beginning of the
8082 headline. Use `org-reduced-level' to remove the effect of
8083 `org-odd-levels'. Unlike to `org-outline-level', this function
8084 ignores inlinetasks."
8085 (let ((level (org-with-limited-levels (org-outline-level))))
8086 (and (> level 0) level)))
8088 (defun org-get-previous-line-level ()
8089 "Return the outline depth of the last headline before the current line.
8090 Returns 0 for the first headline in the buffer, and nil if before the
8091 first headline."
8092 (and (org-current-level)
8093 (or (and (/= (line-beginning-position) (point-min))
8094 (save-excursion (beginning-of-line 0) (org-current-level)))
8095 0)))
8097 (defun org-reduced-level (l)
8098 "Compute the effective level of a heading.
8099 This takes into account the setting of `org-odd-levels-only'."
8100 (cond
8101 ((zerop l) 0)
8102 (org-odd-levels-only (1+ (floor (/ l 2))))
8103 (t l)))
8105 (defun org-level-increment ()
8106 "Return the number of stars that will be added or removed at a
8107 time to headlines when structure editing, based on the value of
8108 `org-odd-levels-only'."
8109 (if org-odd-levels-only 2 1))
8111 (defun org-get-valid-level (level &optional change)
8112 "Rectify a level change under the influence of `org-odd-levels-only'.
8113 LEVEL is a current level, CHANGE is by how much the level should
8114 be modified. Even if CHANGE is nil, LEVEL may be returned
8115 modified because even level numbers will become the next higher
8116 odd number. Returns values greater than 0."
8117 (if org-odd-levels-only
8118 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8119 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8120 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8121 (max 1 (+ level (or change 0)))))
8123 (defun org-promote ()
8124 "Promote the current heading higher up the tree."
8125 (org-with-wide-buffer
8126 (org-back-to-heading t)
8127 (let* ((after-change-functions (remq 'flyspell-after-change-function
8128 after-change-functions))
8129 (level (save-match-data (funcall outline-level)))
8130 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8131 (diff (abs (- level (length up-head) -1))))
8132 (cond
8133 ((and (= level 1) org-allow-promoting-top-level-subtree)
8134 (replace-match "# " nil t))
8135 ((= level 1)
8136 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8137 (t (replace-match up-head nil t)))
8138 (unless (= level 1)
8139 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8140 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8141 (run-hooks 'org-after-promote-entry-hook))))
8143 (defun org-demote ()
8144 "Demote the current heading lower down the tree."
8145 (org-with-wide-buffer
8146 (org-back-to-heading t)
8147 (let* ((after-change-functions (remq 'flyspell-after-change-function
8148 after-change-functions))
8149 (level (save-match-data (funcall outline-level)))
8150 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8151 (diff (abs (- level (length down-head) -1))))
8152 (replace-match down-head nil t)
8153 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8154 (when org-adapt-indentation (org-fixup-indentation diff))
8155 (run-hooks 'org-after-demote-entry-hook))))
8157 (defun org-cycle-level ()
8158 "Cycle the level of an empty headline through possible states.
8159 This goes first to child, then to parent, level, then up the hierarchy.
8160 After top level, it switches back to sibling level."
8161 (interactive)
8162 (let ((org-adapt-indentation nil))
8163 (when (org-point-at-end-of-empty-headline)
8164 (setq this-command 'org-cycle-level) ; Only needed for caching
8165 (let ((cur-level (org-current-level))
8166 (prev-level (org-get-previous-line-level)))
8167 (cond
8168 ;; If first headline in file, promote to top-level.
8169 ((= prev-level 0)
8170 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8171 do (org-do-promote)))
8172 ;; If same level as prev, demote one.
8173 ((= prev-level cur-level)
8174 (org-do-demote))
8175 ;; If parent is top-level, promote to top level if not already.
8176 ((= prev-level 1)
8177 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8178 do (org-do-promote)))
8179 ;; If top-level, return to prev-level.
8180 ((= cur-level 1)
8181 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8182 do (org-do-demote)))
8183 ;; If less than prev-level, promote one.
8184 ((< cur-level prev-level)
8185 (org-do-promote))
8186 ;; If deeper than prev-level, promote until higher than
8187 ;; prev-level.
8188 ((> cur-level prev-level)
8189 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8190 do (org-do-promote))))
8191 t))))
8193 (defun org-map-tree (fun)
8194 "Call FUN for every heading underneath the current one."
8195 (org-back-to-heading t)
8196 (let ((level (funcall outline-level)))
8197 (save-excursion
8198 (funcall fun)
8199 (while (and (progn
8200 (outline-next-heading)
8201 (> (funcall outline-level) level))
8202 (not (eobp)))
8203 (funcall fun)))))
8205 (defun org-map-region (fun beg end)
8206 "Call FUN for every heading between BEG and END."
8207 (let ((org-ignore-region t))
8208 (save-excursion
8209 (setq end (copy-marker end))
8210 (goto-char beg)
8211 (when (and (re-search-forward org-outline-regexp-bol nil t)
8212 (< (point) end))
8213 (funcall fun))
8214 (while (and (progn
8215 (outline-next-heading)
8216 (< (point) end))
8217 (not (eobp)))
8218 (funcall fun)))))
8220 (defun org-fixup-indentation (diff)
8221 "Change the indentation in the current entry by DIFF.
8223 DIFF is an integer. Indentation is done according to the
8224 following rules:
8226 - Planning information and property drawers are always indented
8227 according to the new level of the headline;
8229 - Footnote definitions and their contents are ignored;
8231 - Inlinetasks' boundaries are not shifted;
8233 - Empty lines are ignored;
8235 - Other lines' indentation are shifted by DIFF columns, unless
8236 it would introduce a structural change in the document, in
8237 which case no shifting is done at all.
8239 Assume point is at a heading or an inlinetask beginning."
8240 (org-with-wide-buffer
8241 (narrow-to-region (line-beginning-position)
8242 (save-excursion
8243 (if (org-with-limited-levels (org-at-heading-p))
8244 (org-with-limited-levels (outline-next-heading))
8245 (org-inlinetask-goto-end))
8246 (point)))
8247 (forward-line)
8248 ;; Indent properly planning info and property drawer.
8249 (when (looking-at-p org-planning-line-re)
8250 (org-indent-line)
8251 (forward-line))
8252 (when (looking-at org-property-drawer-re)
8253 (goto-char (match-end 0))
8254 (forward-line)
8255 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8256 (catch 'no-shift
8257 (when (zerop diff) (throw 'no-shift nil))
8258 ;; If DIFF is negative, first check if a shift is possible at all
8259 ;; (e.g., it doesn't break structure). This can only happen if
8260 ;; some contents are not properly indented.
8261 (let ((case-fold-search t))
8262 (when (< diff 0)
8263 (let ((diff (- diff))
8264 (forbidden-re (concat org-outline-regexp
8265 "\\|"
8266 (substring org-footnote-definition-re 1))))
8267 (save-excursion
8268 (while (not (eobp))
8269 (cond
8270 ((looking-at-p "[ \t]*$") (forward-line))
8271 ((and (looking-at-p org-footnote-definition-re)
8272 (let ((e (org-element-at-point)))
8273 (and (eq (org-element-type e) 'footnote-definition)
8274 (goto-char (org-element-property :end e))))))
8275 ((looking-at-p org-outline-regexp) (forward-line))
8276 ;; Give up if shifting would move before column 0 or
8277 ;; if it would introduce a headline or a footnote
8278 ;; definition.
8280 (skip-chars-forward " \t")
8281 (let ((ind (current-column)))
8282 (when (or (< ind diff)
8283 (and (= ind diff) (looking-at-p forbidden-re)))
8284 (throw 'no-shift nil)))
8285 ;; Ignore contents of example blocks and source
8286 ;; blocks if their indentation is meant to be
8287 ;; preserved. Jump to block's closing line.
8288 (beginning-of-line)
8289 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8290 (let ((e (org-element-at-point)))
8291 (and (memq (org-element-type e)
8292 '(example-block src-block))
8293 (or org-src-preserve-indentation
8294 (org-element-property :preserve-indent e))
8295 (goto-char (org-element-property :end e))
8296 (progn (skip-chars-backward " \r\t\n")
8297 (beginning-of-line)
8298 t))))
8299 (forward-line))))))))
8300 ;; Shift lines but footnote definitions, inlinetasks boundaries
8301 ;; by DIFF. Also skip contents of source or example blocks
8302 ;; when indentation is meant to be preserved.
8303 (while (not (eobp))
8304 (cond
8305 ((and (looking-at-p org-footnote-definition-re)
8306 (let ((e (org-element-at-point)))
8307 (and (eq (org-element-type e) 'footnote-definition)
8308 (goto-char (org-element-property :end e))))))
8309 ((looking-at-p org-outline-regexp) (forward-line))
8310 ((looking-at-p "[ \t]*$") (forward-line))
8312 (indent-line-to (+ (org-get-indentation) diff))
8313 (beginning-of-line)
8314 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8315 (let ((e (org-element-at-point)))
8316 (and (memq (org-element-type e)
8317 '(example-block src-block))
8318 (or org-src-preserve-indentation
8319 (org-element-property :preserve-indent e))
8320 (goto-char (org-element-property :end e))
8321 (progn (skip-chars-backward " \r\t\n")
8322 (beginning-of-line)
8323 t))))
8324 (forward-line)))))))))
8326 (defun org-convert-to-odd-levels ()
8327 "Convert an Org file with all levels allowed to one with odd levels.
8328 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8329 level 5 etc."
8330 (interactive)
8331 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8332 (let ((outline-level 'org-outline-level)
8333 (org-odd-levels-only nil) n)
8334 (save-excursion
8335 (goto-char (point-min))
8336 (while (re-search-forward "^\\*\\*+ " nil t)
8337 (setq n (- (length (match-string 0)) 2))
8338 (while (>= (setq n (1- n)) 0)
8339 (org-demote))
8340 (end-of-line 1))))))
8342 (defun org-convert-to-oddeven-levels ()
8343 "Convert an Org file with only odd levels to one with odd/even levels.
8344 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8345 file contains a section with an even level, conversion would
8346 destroy the structure of the file. An error is signaled in this
8347 case."
8348 (interactive)
8349 (goto-char (point-min))
8350 ;; First check if there are no even levels
8351 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8352 (org-show-set-visibility 'canonical)
8353 (error "Not all levels are odd in this file. Conversion not possible"))
8354 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8355 (let ((outline-regexp org-outline-regexp)
8356 (outline-level 'org-outline-level)
8357 (org-odd-levels-only nil) n)
8358 (save-excursion
8359 (goto-char (point-min))
8360 (while (re-search-forward "^\\*\\*+ " nil t)
8361 (setq n (/ (1- (length (match-string 0))) 2))
8362 (while (>= (setq n (1- n)) 0)
8363 (org-promote))
8364 (end-of-line 1))))))
8366 (defun org-tr-level (n)
8367 "Make N odd if required."
8368 (if org-odd-levels-only (1+ (/ n 2)) n))
8370 ;;; Vertical tree motion, cutting and pasting of subtrees
8372 (defun org-move-subtree-up (&optional arg)
8373 "Move the current subtree up past ARG headlines of the same level."
8374 (interactive "p")
8375 (org-move-subtree-down (- (prefix-numeric-value arg))))
8377 (defun org-move-subtree-down (&optional arg)
8378 "Move the current subtree down past ARG headlines of the same level."
8379 (interactive "p")
8380 (setq arg (prefix-numeric-value arg))
8381 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8382 'org-get-last-sibling))
8383 (ins-point (make-marker))
8384 (cnt (abs arg))
8385 (col (current-column))
8386 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8387 ;; Select the tree
8388 (org-back-to-heading)
8389 (setq beg0 (point))
8390 (save-excursion
8391 (setq ne-beg (org-back-over-empty-lines))
8392 (setq beg (point)))
8393 (save-match-data
8394 (save-excursion (outline-end-of-heading)
8395 (setq folded (org-invisible-p)))
8396 (progn (org-end-of-subtree nil t)
8397 (unless (eobp) (backward-char))))
8398 (outline-next-heading)
8399 (setq ne-end (org-back-over-empty-lines))
8400 (setq end (point))
8401 (goto-char beg0)
8402 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8403 ;; include less whitespace
8404 (save-excursion
8405 (goto-char beg)
8406 (forward-line (- ne-beg ne-end))
8407 (setq beg (point))))
8408 ;; Find insertion point, with error handling
8409 (while (> cnt 0)
8410 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8411 (progn (goto-char beg0)
8412 (user-error "Cannot move past superior level or buffer limit")))
8413 (setq cnt (1- cnt)))
8414 (when (> arg 0)
8415 ;; Moving forward - still need to move over subtree
8416 (org-end-of-subtree t t)
8417 (save-excursion
8418 (org-back-over-empty-lines)
8419 (or (bolp) (newline))))
8420 (setq ne-ins (org-back-over-empty-lines))
8421 (move-marker ins-point (point))
8422 (setq txt (buffer-substring beg end))
8423 (org-save-markers-in-region beg end)
8424 (delete-region beg end)
8425 (org-remove-empty-overlays-at beg)
8426 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8427 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8428 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8429 (let ((bbb (point)))
8430 (insert-before-markers txt)
8431 (org-reinstall-markers-in-region bbb)
8432 (move-marker ins-point bbb))
8433 (or (bolp) (insert "\n"))
8434 (setq ins-end (point))
8435 (goto-char ins-point)
8436 (org-skip-whitespace)
8437 (when (and (< arg 0)
8438 (org-first-sibling-p)
8439 (> ne-ins ne-beg))
8440 ;; Move whitespace back to beginning
8441 (save-excursion
8442 (goto-char ins-end)
8443 (let ((kill-whole-line t))
8444 (kill-line (- ne-ins ne-beg)) (point)))
8445 (insert (make-string (- ne-ins ne-beg) ?\n)))
8446 (move-marker ins-point nil)
8447 (if folded
8448 (outline-hide-subtree)
8449 (org-show-entry)
8450 (org-show-children)
8451 (org-cycle-hide-drawers 'children))
8452 (org-clean-visibility-after-subtree-move)
8453 ;; move back to the initial column we were at
8454 (move-to-column col)))
8456 (defvar org-subtree-clip ""
8457 "Clipboard for cut and paste of subtrees.
8458 This is actually only a copy of the kill, because we use the normal kill
8459 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8461 (defvar org-subtree-clip-folded nil
8462 "Was the last copied subtree folded?
8463 This is used to fold the tree back after pasting.")
8465 (defun org-cut-subtree (&optional n)
8466 "Cut the current subtree into the clipboard.
8467 With prefix arg N, cut this many sequential subtrees.
8468 This is a short-hand for marking the subtree and then cutting it."
8469 (interactive "p")
8470 (org-copy-subtree n 'cut))
8472 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8473 "Copy the current subtree it in the clipboard.
8474 With prefix arg N, copy this many sequential subtrees.
8475 This is a short-hand for marking the subtree and then copying it.
8476 If CUT is non-nil, actually cut the subtree.
8477 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8478 of some markers in the region, even if CUT is non-nil. This is
8479 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8480 (interactive "p")
8481 (let (beg end folded (beg0 (point)))
8482 (if (called-interactively-p 'any)
8483 (org-back-to-heading nil) ; take what looks like a subtree
8484 (org-back-to-heading t)) ; take what is really there
8485 (setq beg (point))
8486 (skip-chars-forward " \t\r\n")
8487 (save-match-data
8488 (if nosubtrees
8489 (outline-next-heading)
8490 (save-excursion (outline-end-of-heading)
8491 (setq folded (org-invisible-p)))
8492 (ignore-errors (org-forward-heading-same-level (1- n) t))
8493 (org-end-of-subtree t t)))
8494 ;; Include the end of an inlinetask
8495 (when (and (featurep 'org-inlinetask)
8496 (looking-at-p (concat (org-inlinetask-outline-regexp)
8497 "END[ \t]*$")))
8498 (end-of-line))
8499 (setq end (point))
8500 (goto-char beg0)
8501 (when (> end beg)
8502 (setq org-subtree-clip-folded folded)
8503 (when (or cut force-store-markers)
8504 (org-save-markers-in-region beg end))
8505 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8506 (setq org-subtree-clip (current-kill 0))
8507 (message "%s: Subtree(s) with %d characters"
8508 (if cut "Cut" "Copied")
8509 (length org-subtree-clip)))))
8511 (defun org-paste-subtree (&optional level tree for-yank remove)
8512 "Paste the clipboard as a subtree, with modification of headline level.
8513 The entire subtree is promoted or demoted in order to match a new headline
8514 level.
8516 If the cursor is at the beginning of a headline, the same level as
8517 that headline is used to paste the tree.
8519 If not, the new level is derived from the *visible* headings
8520 before and after the insertion point, and taken to be the inferior headline
8521 level of the two. So if the previous visible heading is level 3 and the
8522 next is level 4 (or vice versa), level 4 will be used for insertion.
8523 This makes sure that the subtree remains an independent subtree and does
8524 not swallow low level entries.
8526 You can also force a different level, either by using a numeric prefix
8527 argument, or by inserting the heading marker by hand. For example, if the
8528 cursor is after \"*****\", then the tree will be shifted to level 5.
8530 If optional TREE is given, use this text instead of the kill ring.
8532 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8533 move back over whitespace before inserting, and move point to the end of
8534 the inserted text when done.
8536 When REMOVE is non-nil, remove the subtree from the clipboard."
8537 (interactive "P")
8538 (setq tree (or tree (and kill-ring (current-kill 0))))
8539 (unless (org-kill-is-subtree-p tree)
8540 (user-error "%s"
8541 (substitute-command-keys
8542 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8543 (org-with-limited-levels
8544 (let* ((visp (not (org-invisible-p)))
8545 (txt tree)
8546 (^re_ "\\(\\*+\\)[ \t]*")
8547 (old-level (if (string-match org-outline-regexp-bol txt)
8548 (- (match-end 0) (match-beginning 0) 1)
8549 -1))
8550 (force-level (cond (level (prefix-numeric-value level))
8551 ((and (looking-at "[ \t]*$")
8552 (string-match
8553 "^\\*+$" (buffer-substring
8554 (point-at-bol) (point))))
8555 (- (match-end 0) (match-beginning 0)))
8556 ((and (bolp)
8557 (looking-at org-outline-regexp))
8558 (- (match-end 0) (point) 1))))
8559 (previous-level (save-excursion
8560 (condition-case nil
8561 (progn
8562 (outline-previous-visible-heading 1)
8563 (if (looking-at ^re_)
8564 (- (match-end 0) (match-beginning 0) 1)
8566 (error 1))))
8567 (next-level (save-excursion
8568 (condition-case nil
8569 (progn
8570 (or (looking-at org-outline-regexp)
8571 (outline-next-visible-heading 1))
8572 (if (looking-at ^re_)
8573 (- (match-end 0) (match-beginning 0) 1)
8575 (error 1))))
8576 (new-level (or force-level (max previous-level next-level)))
8577 (shift (if (or (= old-level -1)
8578 (= new-level -1)
8579 (= old-level new-level))
8581 (- new-level old-level)))
8582 (delta (if (> shift 0) -1 1))
8583 (func (if (> shift 0) 'org-demote 'org-promote))
8584 (org-odd-levels-only nil)
8585 beg end newend)
8586 ;; Remove the forced level indicator
8587 (when force-level
8588 (delete-region (point-at-bol) (point)))
8589 ;; Paste
8590 (beginning-of-line (if (bolp) 1 2))
8591 (setq beg (point))
8592 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8593 (insert-before-markers txt)
8594 (unless (string-suffix-p "\n" txt) (insert "\n"))
8595 (setq newend (point))
8596 (org-reinstall-markers-in-region beg)
8597 (setq end (point))
8598 (goto-char beg)
8599 (skip-chars-forward " \t\n\r")
8600 (setq beg (point))
8601 (when (and (org-invisible-p) visp)
8602 (save-excursion (outline-show-heading)))
8603 ;; Shift if necessary
8604 (unless (= shift 0)
8605 (save-restriction
8606 (narrow-to-region beg end)
8607 (while (not (= shift 0))
8608 (org-map-region func (point-min) (point-max))
8609 (setq shift (+ delta shift)))
8610 (goto-char (point-min))
8611 (setq newend (point-max))))
8612 (when (or (called-interactively-p 'interactive) for-yank)
8613 (message "Clipboard pasted as level %d subtree" new-level))
8614 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8615 kill-ring
8616 (eq org-subtree-clip (current-kill 0))
8617 org-subtree-clip-folded)
8618 ;; The tree was folded before it was killed/copied
8619 (outline-hide-subtree))
8620 (and for-yank (goto-char newend))
8621 (and remove (setq kill-ring (cdr kill-ring))))))
8623 (defun org-kill-is-subtree-p (&optional txt)
8624 "Check if the current kill is an outline subtree, or a set of trees.
8625 Returns nil if kill does not start with a headline, or if the first
8626 headline level is not the largest headline level in the tree.
8627 So this will actually accept several entries of equal levels as well,
8628 which is OK for `org-paste-subtree'.
8629 If optional TXT is given, check this string instead of the current kill."
8630 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8631 (re (org-get-limited-outline-regexp))
8632 (^re (concat "^" re))
8633 (start-level (and kill
8634 (string-match
8635 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8636 kill)
8637 (- (match-end 2) (match-beginning 2) 1)))
8638 (start (1+ (or (match-beginning 2) -1))))
8639 (if (not start-level)
8640 (progn
8641 nil) ;; does not even start with a heading
8642 (catch 'exit
8643 (while (setq start (string-match ^re kill (1+ start)))
8644 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8645 (throw 'exit nil)))
8646 t))))
8648 (defvar org-markers-to-move nil
8649 "Markers that should be moved with a cut-and-paste operation.
8650 Those markers are stored together with their positions relative to
8651 the start of the region.")
8653 (defun org-save-markers-in-region (beg end)
8654 "Check markers in region.
8655 If these markers are between BEG and END, record their position relative
8656 to BEG, so that after moving the block of text, we can put the markers back
8657 into place.
8658 This function gets called just before an entry or tree gets cut from the
8659 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8660 called immediately, to move the markers with the entries."
8661 (setq org-markers-to-move nil)
8662 (when (featurep 'org-clock)
8663 (org-clock-save-markers-for-cut-and-paste beg end))
8664 (when (featurep 'org-agenda)
8665 (org-agenda-save-markers-for-cut-and-paste beg end)))
8667 (defun org-check-and-save-marker (marker beg end)
8668 "Check if MARKER is between BEG and END.
8669 If yes, remember the marker and the distance to BEG."
8670 (when (and (marker-buffer marker)
8671 (equal (marker-buffer marker) (current-buffer))
8672 (>= marker beg) (< marker end))
8673 (push (cons marker (- marker beg)) org-markers-to-move)))
8675 (defun org-reinstall-markers-in-region (beg)
8676 "Move all remembered markers to their position relative to BEG."
8677 (dolist (x org-markers-to-move)
8678 (move-marker (car x) (+ beg (cdr x))))
8679 (setq org-markers-to-move nil))
8681 (defun org-narrow-to-subtree ()
8682 "Narrow buffer to the current subtree."
8683 (interactive)
8684 (save-excursion
8685 (save-match-data
8686 (org-with-limited-levels
8687 (narrow-to-region
8688 (progn (org-back-to-heading t) (point))
8689 (progn (org-end-of-subtree t t)
8690 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8691 (point)))))))
8693 (defun org-narrow-to-block ()
8694 "Narrow buffer to the current block."
8695 (interactive)
8696 (let* ((case-fold-search t)
8697 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8698 "^[ \t]*#\\+end_.*")))
8699 (if blockp
8700 (narrow-to-region (car blockp) (cdr blockp))
8701 (user-error "Not in a block"))))
8703 (defun org-clone-subtree-with-time-shift (n &optional shift)
8704 "Clone the task (subtree) at point N times.
8705 The clones will be inserted as siblings.
8707 In interactive use, the user will be prompted for the number of
8708 clones to be produced. If the entry has a timestamp, the user
8709 will also be prompted for a time shift, which may be a repeater
8710 as used in time stamps, for example `+3d'. To disable this,
8711 you can call the function with a universal prefix argument.
8713 When a valid repeater is given and the entry contains any time
8714 stamps, the clones will become a sequence in time, with time
8715 stamps in the subtree shifted for each clone produced. If SHIFT
8716 is nil or the empty string, time stamps will be left alone. The
8717 ID property of the original subtree is removed.
8719 In each clone, all the CLOCK entries will be removed. This
8720 prevents Org from considering that the clocked times overlap.
8722 If the original subtree did contain time stamps with a repeater,
8723 the following will happen:
8724 - the repeater will be removed in each clone
8725 - an additional clone will be produced, with the current, unshifted
8726 date(s) in the entry.
8727 - the original entry will be placed *after* all the clones, with
8728 repeater intact.
8729 - the start days in the repeater in the original entry will be shifted
8730 to past the last clone.
8731 In this way you can spell out a number of instances of a repeating task,
8732 and still retain the repeater to cover future instances of the task.
8734 As described above, N+1 clones are produced when the original
8735 subtree has a repeater. Setting N to 0, then, can be used to
8736 remove the repeater from a subtree and create a shifted clone
8737 with the original repeater."
8738 (interactive "nNumber of clones to produce: ")
8739 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8740 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8741 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8742 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8743 (shift
8744 (or shift
8745 (if (and (not (equal current-prefix-arg '(4)))
8746 (save-excursion
8747 (goto-char beg)
8748 (re-search-forward org-ts-regexp-both end-of-tree t)))
8749 (read-from-minibuffer
8750 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8751 ""))) ;No time shift
8752 (doshift
8753 (and (org-string-nw-p shift)
8754 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8755 shift)
8756 (user-error "Invalid shift specification %s" shift)))))
8757 (goto-char end-of-tree)
8758 (unless (bolp) (insert "\n"))
8759 (let* ((end (point))
8760 (template (buffer-substring beg end))
8761 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8762 (shift-what (pcase (and doshift (match-string 2 shift))
8763 (`nil nil)
8764 ("d" 'day)
8765 ("w" (setq shift-n (* 7 shift-n)) 'day)
8766 ("m" 'month)
8767 ("y" 'year)
8768 (_ (error "Unsupported time unit"))))
8769 (nmin 1)
8770 (nmax n)
8771 (n-no-remove -1)
8772 (idprop (org-entry-get nil "ID")))
8773 (when (and doshift
8774 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8775 template))
8776 (delete-region beg end)
8777 (setq end beg)
8778 (setq nmin 0)
8779 (setq nmax (1+ nmax))
8780 (setq n-no-remove nmax))
8781 (goto-char end)
8782 (cl-loop for n from nmin to nmax do
8783 (insert
8784 ;; Prepare clone.
8785 (with-temp-buffer
8786 (insert template)
8787 (org-mode)
8788 (goto-char (point-min))
8789 (org-show-subtree)
8790 (and idprop (if org-clone-delete-id
8791 (org-entry-delete nil "ID")
8792 (org-id-get-create t)))
8793 (unless (= n 0)
8794 (while (re-search-forward org-clock-line-re nil t)
8795 (delete-region (line-beginning-position)
8796 (line-beginning-position 2)))
8797 (goto-char (point-min))
8798 (while (re-search-forward org-drawer-regexp nil t)
8799 (org-remove-empty-drawer-at (point))))
8800 (goto-char (point-min))
8801 (when doshift
8802 (while (re-search-forward org-ts-regexp-both nil t)
8803 (org-timestamp-change (* n shift-n) shift-what))
8804 (unless (= n n-no-remove)
8805 (goto-char (point-min))
8806 (while (re-search-forward org-ts-regexp nil t)
8807 (save-excursion
8808 (goto-char (match-beginning 0))
8809 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8810 (delete-region (match-beginning 1) (match-end 1)))))))
8811 (buffer-string)))))
8812 (goto-char beg)))
8814 ;;; Outline Sorting
8816 (defun org-sort (&optional with-case)
8817 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8818 Optional argument WITH-CASE means sort case-sensitively."
8819 (interactive "P")
8820 (org-call-with-arg
8821 (cond ((org-at-table-p) #'org-table-sort-lines)
8822 ((org-at-item-p) #'org-sort-list)
8823 (t #'org-sort-entries))
8824 with-case))
8826 (defun org-sort-remove-invisible (s)
8827 "Remove invisible part of links and emphasis markers from string S."
8828 (remove-text-properties 0 (length s) org-rm-props s)
8829 (replace-regexp-in-string
8830 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8831 (replace-regexp-in-string
8832 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8833 (org-link-display-format s)
8834 t t) t t))
8836 (defvar org-priority-regexp) ; defined later in the file
8838 (defvar org-after-sorting-entries-or-items-hook nil
8839 "Hook that is run after a bunch of entries or items have been sorted.
8840 When children are sorted, the cursor is in the parent line when this
8841 hook gets called. When a region or a plain list is sorted, the cursor
8842 will be in the first entry of the sorted region/list.")
8844 (defun org-sort-entries
8845 (&optional with-case sorting-type getkey-func compare-func property
8846 interactive?)
8847 "Sort entries on a certain level of an outline tree.
8848 If there is an active region, the entries in the region are sorted.
8849 Else, if the cursor is before the first entry, sort the top-level items.
8850 Else, the children of the entry at point are sorted.
8852 Sorting can be alphabetically, numerically, by date/time as given by
8853 a time stamp, by a property, by priority order, or by a custom function.
8855 The command prompts for the sorting type unless it has been given to the
8856 function through the SORTING-TYPE argument, which needs to be a character,
8857 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8858 the precise meaning of each character:
8860 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8861 c By creation time, which is assumed to be the first inactive time stamp
8862 at the beginning of a line.
8863 d By deadline date/time.
8864 k By clocking time.
8865 n Numerically, by converting the beginning of the entry/item to a number.
8866 o By order of TODO keywords.
8867 p By priority according to the cookie.
8868 r By the value of a property.
8869 s By scheduled date/time.
8870 t By date/time, either the first active time stamp in the entry, or, if
8871 none exist, by the first inactive one.
8873 Capital letters will reverse the sort order.
8875 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8876 called with point at the beginning of the record. It must return a
8877 value that is compatible with COMPARE-FUNC, the function used to
8878 compare entries.
8880 Comparing entries ignores case by default. However, with an optional argument
8881 WITH-CASE, the sorting considers case as well.
8883 Sorting is done against the visible part of the headlines, it ignores hidden
8884 links.
8886 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8888 A non-nil value for INTERACTIVE? is used to signal that this
8889 function is being called interactively."
8890 (interactive (list current-prefix-arg nil nil nil nil t))
8891 (let ((case-func (if with-case 'identity 'downcase))
8892 (cmstr
8893 ;; The clock marker is lost when using `sort-subr', let's
8894 ;; store the clocking string.
8895 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8896 (save-excursion
8897 (goto-char org-clock-marker)
8898 (buffer-substring-no-properties (line-beginning-position)
8899 (point)))))
8900 start beg end stars re re2
8901 txt what tmp)
8902 ;; Find beginning and end of region to sort
8903 (cond
8904 ((org-region-active-p)
8905 ;; we will sort the region
8906 (setq end (region-end)
8907 what "region")
8908 (goto-char (region-beginning))
8909 (unless (org-at-heading-p) (outline-next-heading))
8910 (setq start (point)))
8911 ((or (org-at-heading-p)
8912 (ignore-errors (progn (org-back-to-heading) t)))
8913 ;; we will sort the children of the current headline
8914 (org-back-to-heading)
8915 (setq start (point)
8916 end (progn (org-end-of-subtree t t)
8917 (or (bolp) (insert "\n"))
8918 (when (>= (org-back-over-empty-lines) 1)
8919 (forward-line 1))
8920 (point))
8921 what "children")
8922 (goto-char start)
8923 (outline-show-subtree)
8924 (outline-next-heading))
8926 ;; we will sort the top-level entries in this file
8927 (goto-char (point-min))
8928 (or (org-at-heading-p) (outline-next-heading))
8929 (setq start (point))
8930 (goto-char (point-max))
8931 (beginning-of-line 1)
8932 (when (looking-at ".*?\\S-")
8933 ;; File ends in a non-white line
8934 (end-of-line 1)
8935 (insert "\n"))
8936 (setq end (point-max))
8937 (setq what "top-level")
8938 (goto-char start)
8939 (outline-show-all)))
8941 (setq beg (point))
8942 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8944 (looking-at "\\(\\*+\\)")
8945 (setq stars (match-string 1)
8946 re (concat "^" (regexp-quote stars) " +")
8947 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8948 txt (buffer-substring beg end))
8949 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8950 (when (and (not (equal stars "*")) (string-match re2 txt))
8951 (user-error "Region to sort contains a level above the first entry"))
8953 (unless sorting-type
8954 (message
8955 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8956 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8957 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8958 what)
8959 (setq sorting-type (read-char-exclusive)))
8961 (unless getkey-func
8962 (and (= (downcase sorting-type) ?f)
8963 (setq getkey-func
8964 (or (and interactive?
8965 (org-read-function
8966 "Function for extracting keys: "))
8967 (error "Missing key extractor")))))
8969 (and (= (downcase sorting-type) ?r)
8970 (not property)
8971 (setq property
8972 (completing-read "Property: "
8973 (mapcar #'list (org-buffer-property-keys t))
8974 nil t)))
8976 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8977 (message "Sorting entries...")
8979 (save-restriction
8980 (narrow-to-region start end)
8981 (let ((dcst (downcase sorting-type))
8982 (case-fold-search nil)
8983 (now (current-time)))
8984 (sort-subr
8985 (/= dcst sorting-type)
8986 ;; This function moves to the beginning character of the "record" to
8987 ;; be sorted.
8988 (lambda nil
8989 (if (re-search-forward re nil t)
8990 (goto-char (match-beginning 0))
8991 (goto-char (point-max))))
8992 ;; This function moves to the last character of the "record" being
8993 ;; sorted.
8994 (lambda nil
8995 (save-match-data
8996 (condition-case nil
8997 (outline-forward-same-level 1)
8998 (error
8999 (goto-char (point-max))))))
9000 ;; This function returns the value that gets sorted against.
9001 (lambda nil
9002 (cond
9003 ((= dcst ?n)
9004 (if (looking-at org-complex-heading-regexp)
9005 (string-to-number (org-sort-remove-invisible (match-string 4)))
9006 nil))
9007 ((= dcst ?a)
9008 (if (looking-at org-complex-heading-regexp)
9009 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9010 nil))
9011 ((= dcst ?k)
9012 (or (get-text-property (point) :org-clock-minutes) 0))
9013 ((= dcst ?t)
9014 (let ((end (save-excursion (outline-next-heading) (point))))
9015 (if (or (re-search-forward org-ts-regexp end t)
9016 (re-search-forward org-ts-regexp-both end t))
9017 (org-time-string-to-seconds (match-string 0))
9018 (float-time now))))
9019 ((= dcst ?c)
9020 (let ((end (save-excursion (outline-next-heading) (point))))
9021 (if (re-search-forward
9022 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9023 end t)
9024 (org-time-string-to-seconds (match-string 0))
9025 (float-time now))))
9026 ((= dcst ?s)
9027 (let ((end (save-excursion (outline-next-heading) (point))))
9028 (if (re-search-forward org-scheduled-time-regexp end t)
9029 (org-time-string-to-seconds (match-string 1))
9030 (float-time now))))
9031 ((= dcst ?d)
9032 (let ((end (save-excursion (outline-next-heading) (point))))
9033 (if (re-search-forward org-deadline-time-regexp end t)
9034 (org-time-string-to-seconds (match-string 1))
9035 (float-time now))))
9036 ((= dcst ?p)
9037 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9038 (string-to-char (match-string 2))
9039 org-default-priority))
9040 ((= dcst ?r)
9041 (or (org-entry-get nil property) ""))
9042 ((= dcst ?o)
9043 (when (looking-at org-complex-heading-regexp)
9044 (let* ((m (match-string 2))
9045 (s (if (member m org-done-keywords) '- '+)))
9046 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9047 ((= dcst ?f)
9048 (if getkey-func
9049 (progn
9050 (setq tmp (funcall getkey-func))
9051 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9052 tmp)
9053 (error "Invalid key function `%s'" getkey-func)))
9054 (t (error "Invalid sorting type `%c'" sorting-type))))
9056 (cond
9057 ((= dcst ?a) 'string<)
9058 ((= dcst ?f)
9059 (or compare-func
9060 (and interactive?
9061 (org-read-function
9062 (concat "Function for comparing keys "
9063 "(empty for default `sort-subr' predicate): ")
9064 'allow-empty))))
9065 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9066 (run-hooks 'org-after-sorting-entries-or-items-hook)
9067 ;; Reset the clock marker if needed
9068 (when cmstr
9069 (save-excursion
9070 (goto-char start)
9071 (search-forward cmstr nil t)
9072 (move-marker org-clock-marker (point))))
9073 (message "Sorting entries...done")))
9075 ;;; The orgstruct minor mode
9077 ;; Define a minor mode which can be used in other modes in order to
9078 ;; integrate the Org mode structure editing commands.
9080 ;; This is really a hack, because the Org mode structure commands use
9081 ;; keys which normally belong to the major mode. Here is how it
9082 ;; works: The minor mode defines all the keys necessary to operate the
9083 ;; structure commands, but wraps the commands into a function which
9084 ;; tests if the cursor is currently at a headline or a plain list
9085 ;; item. If that is the case, the structure command is used,
9086 ;; temporarily setting many Org mode variables like regular
9087 ;; expressions for filling etc. However, when any of those keys is
9088 ;; used at a different location, function uses `key-binding' to look
9089 ;; up if the key has an associated command in another currently active
9090 ;; keymap (minor modes, major mode, global), and executes that
9091 ;; command. There might be problems if any of the keys is otherwise
9092 ;; used as a prefix key.
9094 (defcustom orgstruct-heading-prefix-regexp ""
9095 "Regexp that matches the custom prefix of Org headlines in
9096 orgstruct(++)-mode."
9097 :group 'org
9098 :version "24.4"
9099 :package-version '(Org . "8.3")
9100 :type 'regexp)
9101 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9103 (defcustom orgstruct-setup-hook nil
9104 "Hook run after orgstruct-mode-map is filled."
9105 :group 'org
9106 :version "24.4"
9107 :package-version '(Org . "8.0")
9108 :type 'hook)
9110 (defvar orgstruct-initialized nil)
9112 (defvar org-local-vars nil
9113 "List of local variables, for use by `orgstruct-mode'.")
9115 ;;;###autoload
9116 (define-minor-mode orgstruct-mode
9117 "Toggle the minor mode `orgstruct-mode'.
9118 This mode is for using Org mode structure commands in other
9119 modes. The following keys behave as if Org mode were active, if
9120 the cursor is on a headline, or on a plain list item (both as
9121 defined by Org mode)."
9122 nil " OrgStruct" (make-sparse-keymap)
9123 (funcall (if orgstruct-mode
9124 'add-to-invisibility-spec
9125 'remove-from-invisibility-spec)
9126 '(outline . t))
9127 (when orgstruct-mode
9128 (org-load-modules-maybe)
9129 (unless orgstruct-initialized
9130 (orgstruct-setup)
9131 (setq orgstruct-initialized t))))
9133 ;;;###autoload
9134 (defun turn-on-orgstruct ()
9135 "Unconditionally turn on `orgstruct-mode'."
9136 (orgstruct-mode 1))
9138 (defvar-local orgstruct-is-++ nil
9139 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9140 (defvar-local org-fb-vars nil)
9141 (defun orgstruct++-mode (&optional arg)
9142 "Toggle `orgstruct-mode', the enhanced version of it.
9143 In addition to setting orgstruct-mode, this also exports all
9144 indentation and autofilling variables from Org mode into the
9145 buffer. It will also recognize item context in multiline items."
9146 (interactive "P")
9147 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9148 (if (< arg 1)
9149 (progn (orgstruct-mode -1)
9150 (dolist (v org-fb-vars)
9151 (set (make-local-variable (car v))
9152 (if (eq (car-safe (cadr v)) 'quote)
9153 (cl-cadadr v)
9154 (nth 1 v)))))
9155 (orgstruct-mode 1)
9156 (setq org-fb-vars nil)
9157 (unless org-local-vars
9158 (setq org-local-vars (org-get-local-variables)))
9159 (let (var val)
9160 (dolist (x org-local-vars)
9161 (when (string-match
9162 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9163 \\|fill-prefix\\|indent-\\)"
9164 (symbol-name (car x)))
9165 (setq var (car x) val (nth 1 x))
9166 (push (list var `(quote ,(eval var))) org-fb-vars)
9167 (set (make-local-variable var)
9168 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9169 (setq-local orgstruct-is-++ t))))
9171 ;;;###autoload
9172 (defun turn-on-orgstruct++ ()
9173 "Unconditionally turn on `orgstruct++-mode'."
9174 (orgstruct++-mode 1))
9176 (defun orgstruct-error ()
9177 "Error when there is no default binding for a structure key."
9178 (interactive)
9179 (funcall (if (fboundp 'user-error)
9180 'user-error
9181 'error)
9182 "This key has no function outside structure elements"))
9184 (defun orgstruct-setup ()
9185 "Setup orgstruct keymap."
9186 (dolist (cell '((org-demote . t)
9187 (org-metaleft . t)
9188 (org-metaright . t)
9189 (org-promote . t)
9190 (org-shiftmetaleft . t)
9191 (org-shiftmetaright . t)
9192 org-backward-element
9193 org-backward-heading-same-level
9194 org-ctrl-c-ret
9195 org-ctrl-c-minus
9196 org-ctrl-c-star
9197 org-cycle
9198 org-force-cycle-archived
9199 org-forward-heading-same-level
9200 org-insert-heading
9201 org-insert-heading-respect-content
9202 org-kill-note-or-show-branches
9203 org-mark-subtree
9204 org-meta-return
9205 org-metadown
9206 org-metaup
9207 org-narrow-to-subtree
9208 org-promote-subtree
9209 org-reveal
9210 org-shiftdown
9211 org-shiftleft
9212 org-shiftmetadown
9213 org-shiftmetaup
9214 org-shiftright
9215 org-shifttab
9216 org-shifttab
9217 org-shiftup
9218 org-show-children
9219 org-show-subtree
9220 org-sort
9221 org-up-element
9222 outline-demote
9223 outline-next-visible-heading
9224 outline-previous-visible-heading
9225 outline-promote
9226 outline-up-heading))
9227 (let ((f (or (car-safe cell) cell))
9228 (disable-when-heading-prefix (cdr-safe cell)))
9229 (when (fboundp f)
9230 (let ((new-bindings))
9231 (dolist (binding (nconc (where-is-internal f org-mode-map)
9232 (where-is-internal f outline-mode-map)))
9233 (push binding new-bindings)
9234 ;; TODO use local-function-key-map
9235 (dolist (rep '(("<tab>" . "TAB")
9236 ("<return>" . "RET")
9237 ("<escape>" . "ESC")
9238 ("<delete>" . "DEL")))
9239 (setq binding (read-kbd-macro
9240 (let ((case-fold-search))
9241 (replace-regexp-in-string
9242 (regexp-quote (cdr rep))
9243 (car rep)
9244 (key-description binding)))))
9245 (cl-pushnew binding new-bindings :test 'equal)))
9246 (dolist (binding new-bindings)
9247 (let ((key (lookup-key orgstruct-mode-map binding)))
9248 (when (or (not key) (numberp key))
9249 (ignore-errors
9250 (org-defkey orgstruct-mode-map
9251 binding
9252 (orgstruct-make-binding
9253 f binding disable-when-heading-prefix))))))))))
9254 (run-hooks 'orgstruct-setup-hook))
9256 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9257 "Create a function for binding in the structure minor mode.
9258 FUN is the command to call inside a table. KEY is the key that
9259 should be checked in for a command to execute outside of tables.
9260 Non-nil `disable-when-heading-prefix' means to disable the command
9261 if `orgstruct-heading-prefix-regexp' is not empty."
9262 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9263 (let ((nname name)
9264 (i 0))
9265 (while (fboundp (intern nname))
9266 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9267 (setq name (intern nname)))
9268 (eval
9269 (let ((bindings '((org-heading-regexp
9270 (concat "^"
9271 orgstruct-heading-prefix-regexp
9272 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9273 (org-outline-regexp
9274 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9275 (org-outline-regexp-bol
9276 (concat "^" org-outline-regexp))
9277 (outline-regexp org-outline-regexp)
9278 (outline-heading-end-regexp "\n")
9279 (outline-level 'org-outline-level)
9280 (outline-heading-alist))))
9281 `(defun ,name (arg)
9282 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9283 "Outside of structure, run the binding of `"
9284 (key-description key) "'."
9285 (when disable-when-heading-prefix
9286 (concat
9287 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9288 "back to the default binding due to limitations of Org's implementation of\n"
9289 "`" (symbol-name fun) "'.")))
9290 (interactive "p")
9291 (let* ((disable
9292 ,(and disable-when-heading-prefix
9293 '(not (string= orgstruct-heading-prefix-regexp ""))))
9294 (fallback
9295 (or disable
9296 (not
9297 (let* ,bindings
9298 (org-context-p 'headline 'item
9299 ,(when (memq fun
9300 '(org-insert-heading
9301 org-insert-heading-respect-content
9302 org-meta-return))
9303 '(when orgstruct-is-++
9304 'item-body))))))))
9305 (if fallback
9306 (let* ((orgstruct-mode)
9307 (binding
9308 (let ((key ,key))
9309 (catch 'exit
9310 (dolist
9311 (rep
9312 '(nil
9313 ("<\\([^>]*\\)tab>" . "\\1TAB")
9314 ("<\\([^>]*\\)return>" . "\\1RET")
9315 ("<\\([^>]*\\)escape>" . "\\1ESC")
9316 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9317 nil)
9318 (when rep
9319 (setq key (read-kbd-macro
9320 (let ((case-fold-search))
9321 (replace-regexp-in-string
9322 (car rep)
9323 (cdr rep)
9324 (key-description key))))))
9325 (when (key-binding key)
9326 (throw 'exit (key-binding key))))))))
9327 (if (keymapp binding)
9328 (org-set-transient-map binding)
9329 (let ((func (or binding
9330 (unless disable
9331 'orgstruct-error))))
9332 (when func
9333 (call-interactively func)))))
9334 (org-run-like-in-org-mode
9335 (lambda ()
9336 (interactive)
9337 (let* ,bindings
9338 (call-interactively ',fun)))))))))
9339 name))
9341 (defun org-contextualize-keys (alist contexts)
9342 "Return valid elements in ALIST depending on CONTEXTS.
9344 `org-agenda-custom-commands' or `org-capture-templates' are the
9345 values used for ALIST, and `org-agenda-custom-commands-contexts'
9346 or `org-capture-templates-contexts' are the associated contexts
9347 definitions."
9348 (let ((contexts
9349 ;; normalize contexts
9350 (mapcar
9351 (lambda(c) (cond ((listp (cadr c))
9352 (list (car c) (car c) (nth 1 c)))
9353 ((string= "" (cadr c))
9354 (list (car c) (car c) (nth 2 c)))
9355 (t c)))
9356 contexts))
9357 (a alist) r s)
9358 ;; loop over all commands or templates
9359 (dolist (c a)
9360 (let (vrules repl)
9361 (cond
9362 ((not (assoc (car c) contexts))
9363 (push c r))
9364 ((and (assoc (car c) contexts)
9365 (setq vrules (org-contextualize-validate-key
9366 (car c) contexts)))
9367 (mapc (lambda (vr)
9368 (unless (equal (car vr) (cadr vr))
9369 (setq repl vr)))
9370 vrules)
9371 (if (not repl) (push c r)
9372 (push (cadr repl) s)
9373 (push
9374 (cons (car c)
9375 (cdr (or (assoc (cadr repl) alist)
9376 (error "Undefined key `%s' as contextual replacement for `%s'"
9377 (cadr repl) (car c)))))
9378 r))))))
9379 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9380 (delq
9382 (delete-dups
9383 (mapcar (lambda (x)
9384 (let ((tpl (car x)))
9385 (unless (delq
9387 (mapcar (lambda (y)
9388 (equal y tpl))
9390 x)))
9391 (reverse r))))))
9393 (defun org-contextualize-validate-key (key contexts)
9394 "Check CONTEXTS for agenda or capture KEY."
9395 (let (res)
9396 (dolist (r contexts)
9397 (dolist (rr (car (last r)))
9398 (when
9399 (and (equal key (car r))
9400 (if (functionp rr) (funcall rr)
9401 (or (and (eq (car rr) 'in-file)
9402 (buffer-file-name)
9403 (string-match (cdr rr) (buffer-file-name)))
9404 (and (eq (car rr) 'in-mode)
9405 (string-match (cdr rr) (symbol-name major-mode)))
9406 (and (eq (car rr) 'in-buffer)
9407 (string-match (cdr rr) (buffer-name)))
9408 (when (and (eq (car rr) 'not-in-file)
9409 (buffer-file-name))
9410 (not (string-match (cdr rr) (buffer-file-name))))
9411 (when (eq (car rr) 'not-in-mode)
9412 (not (string-match (cdr rr) (symbol-name major-mode))))
9413 (when (eq (car rr) 'not-in-buffer)
9414 (not (string-match (cdr rr) (buffer-name)))))))
9415 (push r res))))
9416 (delete-dups (delq nil res))))
9418 (defun org-context-p (&rest contexts)
9419 "Check if local context is any of CONTEXTS.
9420 Possible values in the list of contexts are `table', `headline', and `item'."
9421 (let ((pos (point)))
9422 (goto-char (point-at-bol))
9423 (prog1 (or (and (memq 'table contexts)
9424 (looking-at "[ \t]*|"))
9425 (and (memq 'headline contexts)
9426 (looking-at org-outline-regexp))
9427 (and (memq 'item contexts)
9428 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9429 (and (memq 'item-body contexts)
9430 (org-in-item-p)))
9431 (goto-char pos))))
9433 ;;;###autoload
9434 (defun org-run-like-in-org-mode (cmd)
9435 "Run a command, pretending that the current buffer is in Org mode.
9436 This will temporarily bind local variables that are typically bound in
9437 Org mode to the values they have in Org mode, and then interactively
9438 call CMD."
9439 (org-load-modules-maybe)
9440 (unless org-local-vars
9441 (setq org-local-vars (org-get-local-variables)))
9442 (let (binds)
9443 (dolist (var org-local-vars)
9444 (when (or (not (boundp (car var)))
9445 (eq (symbol-value (car var))
9446 (default-value (car var))))
9447 (push (list (car var) `(quote ,(cadr var))) binds)))
9448 (eval `(let ,binds
9449 (call-interactively (quote ,cmd))))))
9451 (defun org-get-category (&optional pos force-refresh)
9452 "Get the category applying to position POS."
9453 (save-match-data
9454 (when force-refresh (org-refresh-category-properties))
9455 (let ((pos (or pos (point))))
9456 (or (get-text-property pos 'org-category)
9457 (progn (org-refresh-category-properties)
9458 (get-text-property pos 'org-category))))))
9460 ;;; Refresh properties
9462 (defun org-refresh-properties (dprop tprop)
9463 "Refresh buffer text properties.
9464 DPROP is the drawer property and TPROP is either the
9465 corresponding text property to set, or an alist with each element
9466 being a text property (as a symbol) and a function to apply to
9467 the value of the drawer property."
9468 (let* ((case-fold-search t)
9469 (inhibit-read-only t)
9470 (inherit? (org-property-inherit-p dprop))
9471 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9472 (global (and inherit? (org--property-global-value dprop nil))))
9473 (org-with-silent-modifications
9474 (org-with-point-at 1
9475 ;; Set global values (e.g., values defined through
9476 ;; "#+PROPERTY:" keywords) to the whole buffer.
9477 (when global (put-text-property (point-min) (point-max) tprop global))
9478 ;; Set local values.
9479 (while (re-search-forward property-re nil t)
9480 (when (org-at-property-p)
9481 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9482 (outline-next-heading))))))
9484 (defun org-refresh-property (tprop p &optional inherit)
9485 "Refresh the buffer text property TPROP from the drawer property P.
9486 The refresh happens only for the current headline, or the whole
9487 sub-tree if optional argument INHERIT is non-nil."
9488 (unless (org-before-first-heading-p)
9489 (save-excursion
9490 (org-back-to-heading t)
9491 (let ((start (point))
9492 (end (save-excursion
9493 (if inherit (org-end-of-subtree t t)
9494 (or (outline-next-heading) (point-max))))))
9495 (if (symbolp tprop)
9496 ;; TPROP is a text property symbol.
9497 (put-text-property start end tprop p)
9498 ;; TPROP is an alist with (property . function) elements.
9499 (pcase-dolist (`(,prop . ,f) tprop)
9500 (put-text-property start end prop (funcall f p))))))))
9502 (defun org-refresh-category-properties ()
9503 "Refresh category text properties in the buffer."
9504 (let ((case-fold-search t)
9505 (inhibit-read-only t)
9506 (default-category
9507 (cond ((null org-category)
9508 (if buffer-file-name
9509 (file-name-sans-extension
9510 (file-name-nondirectory buffer-file-name))
9511 "???"))
9512 ((symbolp org-category) (symbol-name org-category))
9513 (t org-category))))
9514 (org-with-silent-modifications
9515 (org-with-wide-buffer
9516 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9517 ;; This is the default category for the buffer. If none is
9518 ;; found, fall-back to `org-category' or buffer file name.
9519 (put-text-property
9520 (point-min) (point-max)
9521 'org-category
9522 (catch 'buffer-category
9523 (goto-char (point-max))
9524 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9525 (let ((element (org-element-at-point)))
9526 (when (eq (org-element-type element) 'keyword)
9527 (throw 'buffer-category
9528 (org-element-property :value element)))))
9529 default-category))
9530 ;; Set sub-tree specific categories.
9531 (goto-char (point-min))
9532 (let ((regexp (org-re-property "CATEGORY")))
9533 (while (re-search-forward regexp nil t)
9534 (let ((value (match-string-no-properties 3)))
9535 (when (org-at-property-p)
9536 (put-text-property
9537 (save-excursion (org-back-to-heading t) (point))
9538 (save-excursion (org-end-of-subtree t t) (point))
9539 'org-category
9540 value)))))))))
9542 (defun org-refresh-stats-properties ()
9543 "Refresh stats text properties in the buffer."
9544 (org-with-silent-modifications
9545 (org-with-point-at 1
9546 (let ((regexp (concat org-outline-regexp-bol
9547 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9548 (while (re-search-forward regexp nil t)
9549 (let* ((numerator (string-to-number (match-string 1)))
9550 (denominator (and (match-end 2)
9551 (string-to-number (match-string 2))))
9552 (stats (cond ((not denominator) numerator) ;percent
9553 ((= denominator 0) 0)
9554 (t (/ (* numerator 100) denominator)))))
9555 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9556 'org-stats stats)))))))
9558 (defun org-refresh-effort-properties ()
9559 "Refresh effort properties"
9560 (org-refresh-properties
9561 org-effort-property
9562 '((effort . identity)
9563 (effort-minutes . org-duration-to-minutes))))
9565 ;;;; Link Stuff
9567 ;;; Link abbreviations
9569 (defun org-link-expand-abbrev (link)
9570 "Apply replacements as defined in `org-link-abbrev-alist'."
9571 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9572 (let* ((key (match-string 1 link))
9573 (as (or (assoc key org-link-abbrev-alist-local)
9574 (assoc key org-link-abbrev-alist)))
9575 (tag (and (match-end 2) (match-string 3 link)))
9576 rpl)
9577 (if (not as)
9578 link
9579 (setq rpl (cdr as))
9580 (cond
9581 ((symbolp rpl) (funcall rpl tag))
9582 ((string-match "%(\\([^)]+\\))" rpl)
9583 (replace-match
9584 (save-match-data
9585 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9586 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9587 ((string-match "%h" rpl)
9588 (replace-match (url-hexify-string (or tag "")) t t rpl))
9589 (t (concat rpl tag)))))
9590 link))
9592 ;;; Storing and inserting links
9594 (defvar org-insert-link-history nil
9595 "Minibuffer history for links inserted with `org-insert-link'.")
9597 (defvar org-stored-links nil
9598 "Contains the links stored with `org-store-link'.")
9600 (defvar org-store-link-plist nil
9601 "Plist with info about the most recently link created with `org-store-link'.")
9603 (defun org-store-link-functions ()
9604 "Return a list of functions that are called to create and store a link.
9605 The functions defined in the :store property of
9606 `org-link-parameters'.
9608 Each function will be called in turn until one returns a non-nil
9609 value. Each function should check if it is responsible for
9610 creating this link (for example by looking at the major mode).
9611 If not, it must exit and return nil. If yes, it should return
9612 a non-nil value after calling `org-store-link-props' with a list
9613 of properties and values. Special properties are:
9615 :type The link prefix, like \"http\". This must be given.
9616 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9617 This is obligatory as well.
9618 :description Optional default description for the second pair
9619 of brackets in an Org mode link. The user can still change
9620 this when inserting this link into an Org mode buffer.
9622 In addition to these, any additional properties can be specified
9623 and then used in capture templates."
9624 (cl-loop for link in org-link-parameters
9625 with store-func
9626 do (setq store-func (org-link-get-parameter (car link) :store))
9627 if store-func
9628 collect store-func))
9630 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9631 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9633 ;;;###autoload
9634 (defun org-store-link (arg)
9635 "Store an org-link to the current location.
9636 \\<org-mode-map>
9637 This link is added to `org-stored-links' and can later be inserted
9638 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9640 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9641 A single
9642 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9643 `org-gnus-prefer-web-links' for links to Usenet articles.
9645 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9646 skipping storing functions that are not
9647 part of Org core.
9649 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9650 prefix ARG forces storing a link for each line in the
9651 active region."
9652 (interactive "P")
9653 (org-load-modules-maybe)
9654 (if (and (equal arg '(64)) (org-region-active-p))
9655 (save-excursion
9656 (let ((end (region-end)))
9657 (goto-char (region-beginning))
9658 (set-mark (point))
9659 (while (< (point-at-eol) end)
9660 (move-end-of-line 1) (activate-mark)
9661 (let (current-prefix-arg)
9662 (call-interactively 'org-store-link))
9663 (move-beginning-of-line 2)
9664 (set-mark (point)))))
9665 (setq org-store-link-plist nil)
9666 (let (link cpltxt desc description search
9667 txt custom-id agenda-link sfuns sfunsn)
9668 (cond
9670 ;; Store a link using an external link type
9671 ((and (not (equal arg '(16)))
9672 (setq sfuns
9673 (delq
9674 nil (mapcar (lambda (f)
9675 (let (fs) (if (funcall f) (push f fs))))
9676 (org-store-link-functions)))
9677 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9678 (or (and (cdr sfuns)
9679 (funcall (intern
9680 (completing-read
9681 "Which function for creating the link? "
9682 sfunsn nil t (car sfunsn)))))
9683 (funcall (caar sfuns)))
9684 (setq link (plist-get org-store-link-plist :link)
9685 desc (or (plist-get org-store-link-plist
9686 :description)
9687 link))))
9689 ;; Store a link from a source code buffer.
9690 ((org-src-edit-buffer-p)
9691 (let ((coderef-format (org-src-coderef-format)))
9692 (cond ((save-excursion
9693 (beginning-of-line)
9694 (looking-at (org-src-coderef-regexp coderef-format)))
9695 (setq link (format "(%s)" (match-string-no-properties 3))))
9696 ((called-interactively-p 'any)
9697 (let ((label (read-string "Code line label: ")))
9698 (end-of-line)
9699 (setq link (format coderef-format label))
9700 (let ((gc (- 79 (length link))))
9701 (if (< (current-column) gc)
9702 (org-move-to-column gc t)
9703 (insert " ")))
9704 (insert link)
9705 (setq link (concat "(" label ")"))
9706 (setq desc nil)))
9707 (t (setq link nil)))))
9709 ;; We are in the agenda, link to referenced location
9710 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9711 (let ((m (or (get-text-property (point) 'org-hd-marker)
9712 (get-text-property (point) 'org-marker))))
9713 (when m
9714 (org-with-point-at m
9715 (setq agenda-link
9716 (if (called-interactively-p 'any)
9717 (call-interactively 'org-store-link)
9718 (org-store-link nil)))))))
9720 ((eq major-mode 'calendar-mode)
9721 (let ((cd (calendar-cursor-to-date)))
9722 (setq link
9723 (format-time-string
9724 (car org-time-stamp-formats)
9725 (apply 'encode-time
9726 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9727 nil nil nil))))
9728 (org-store-link-props :type "calendar" :date cd)))
9730 ((eq major-mode 'help-mode)
9731 (setq link (concat "help:" (save-excursion
9732 (goto-char (point-min))
9733 (looking-at "^[^ ]+")
9734 (match-string 0))))
9735 (org-store-link-props :type "help"))
9737 ((eq major-mode 'w3-mode)
9738 (setq cpltxt (if (and (buffer-name)
9739 (not (string-match "Untitled" (buffer-name))))
9740 (buffer-name)
9741 (url-view-url t))
9742 link (url-view-url t))
9743 (org-store-link-props :type "w3" :url (url-view-url t)))
9745 ((eq major-mode 'image-mode)
9746 (setq cpltxt (concat "file:"
9747 (abbreviate-file-name buffer-file-name))
9748 link cpltxt)
9749 (org-store-link-props :type "image" :file buffer-file-name))
9751 ;; In dired, store a link to the file of the current line
9752 ((derived-mode-p 'dired-mode)
9753 (let ((file (dired-get-filename nil t)))
9754 (setq file (if file
9755 (abbreviate-file-name
9756 (expand-file-name (dired-get-filename nil t)))
9757 ;; otherwise, no file so use current directory.
9758 default-directory))
9759 (setq cpltxt (concat "file:" file)
9760 link cpltxt)))
9762 ((setq search (run-hook-with-args-until-success
9763 'org-create-file-search-functions))
9764 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9765 "::" search))
9766 (setq cpltxt (or description link)))
9768 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9769 (org-with-limited-levels
9770 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9771 (cond
9772 ;; Store a link using the target at point
9773 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9774 (setq cpltxt
9775 (concat "file:"
9776 (abbreviate-file-name
9777 (buffer-file-name (buffer-base-buffer)))
9778 "::" (match-string 1))
9779 link cpltxt))
9780 ((and (featurep 'org-id)
9781 (or (eq org-id-link-to-org-use-id t)
9782 (and (called-interactively-p 'any)
9783 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9784 (and (eq org-id-link-to-org-use-id
9785 'create-if-interactive-and-no-custom-id)
9786 (not custom-id))))
9787 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9788 ;; Store a link using the ID at point
9789 (setq link (condition-case nil
9790 (prog1 (org-id-store-link)
9791 (setq desc (or (plist-get org-store-link-plist
9792 :description)
9793 "")))
9794 (error
9795 ;; Probably before first headline, link only to file
9796 (concat "file:"
9797 (abbreviate-file-name
9798 (buffer-file-name (buffer-base-buffer))))))))
9800 ;; Just link to current headline
9801 (setq cpltxt (concat "file:"
9802 (abbreviate-file-name
9803 (buffer-file-name (buffer-base-buffer)))))
9804 ;; Add a context search string
9805 (when (org-xor org-context-in-file-links
9806 (equal arg '(4)))
9807 (let* ((element (org-element-at-point))
9808 (name (org-element-property :name element)))
9809 (setq txt (cond
9810 ((org-at-heading-p) nil)
9811 (name)
9812 ((org-region-active-p)
9813 (buffer-substring (region-beginning) (region-end)))))
9814 (when (or (null txt) (string-match "\\S-" txt))
9815 (setq cpltxt
9816 (concat cpltxt "::"
9817 (condition-case nil
9818 (org-make-org-heading-search-string txt)
9819 (error "")))
9820 desc (or name
9821 (nth 4 (ignore-errors (org-heading-components)))
9822 "NONE")))))
9823 (when (string-match "::\\'" cpltxt)
9824 (setq cpltxt (substring cpltxt 0 -2)))
9825 (setq link cpltxt)))))
9827 ((buffer-file-name (buffer-base-buffer))
9828 ;; Just link to this file here.
9829 (setq cpltxt (concat "file:"
9830 (abbreviate-file-name
9831 (buffer-file-name (buffer-base-buffer)))))
9832 ;; Add a context string.
9833 (when (org-xor org-context-in-file-links
9834 (equal arg '(4)))
9835 (setq txt (if (org-region-active-p)
9836 (buffer-substring (region-beginning) (region-end))
9837 (buffer-substring (point-at-bol) (point-at-eol))))
9838 ;; Only use search option if there is some text.
9839 (when (string-match "\\S-" txt)
9840 (setq cpltxt
9841 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9842 desc "NONE")))
9843 (setq link cpltxt))
9845 ((called-interactively-p 'interactive)
9846 (user-error "No method for storing a link from this buffer"))
9848 (t (setq link nil)))
9850 ;; We're done setting link and desc, clean up
9851 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9852 (setq link (or link cpltxt)
9853 desc (or desc cpltxt))
9854 (cond ((not desc))
9855 ((equal desc "NONE") (setq desc nil))
9856 (t (setq desc
9857 (replace-regexp-in-string
9858 org-bracket-link-analytic-regexp
9859 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9860 desc))))
9861 ;; Return the link
9862 (if (not (and (or (called-interactively-p 'any)
9863 executing-kbd-macro)
9864 link))
9865 (or agenda-link (and link (org-make-link-string link desc)))
9866 (push (list link desc) org-stored-links)
9867 (message "Stored: %s" (or desc link))
9868 (when custom-id
9869 (setq link (concat "file:" (abbreviate-file-name
9870 (buffer-file-name)) "::#" custom-id))
9871 (push (list link desc) org-stored-links))
9872 (car org-stored-links)))))
9874 (defun org-store-link-props (&rest plist)
9875 "Store link properties, extract names, addresses and dates."
9876 (let ((x (plist-get plist :from)))
9877 (when x
9878 (let ((adr (mail-extract-address-components x)))
9879 (setq plist (plist-put plist :fromname (car adr)))
9880 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9881 (let ((x (plist-get plist :to)))
9882 (when x
9883 (let ((adr (mail-extract-address-components x)))
9884 (setq plist (plist-put plist :toname (car adr)))
9885 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9886 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9887 (when x
9888 (setq plist (plist-put plist :date-timestamp
9889 (format-time-string
9890 (org-time-stamp-format t) x)))
9891 (setq plist (plist-put plist :date-timestamp-inactive
9892 (format-time-string
9893 (org-time-stamp-format t t) x)))))
9894 (let ((from (plist-get plist :from))
9895 (to (plist-get plist :to)))
9896 (when (and from to org-from-is-user-regexp)
9897 (setq plist
9898 (plist-put plist :fromto
9899 (if (string-match org-from-is-user-regexp from)
9900 (concat "to %t")
9901 (concat "from %f"))))))
9902 (setq org-store-link-plist plist))
9904 (defun org-add-link-props (&rest plist)
9905 "Add these properties to the link property list."
9906 (let (key value)
9907 (while plist
9908 (setq key (pop plist) value (pop plist))
9909 (setq org-store-link-plist
9910 (plist-put org-store-link-plist key value)))))
9912 (defun org-email-link-description (&optional fmt)
9913 "Return the description part of an email link.
9914 This takes information from `org-store-link-plist' and formats it
9915 according to FMT (default from `org-email-link-description-format')."
9916 (setq fmt (or fmt org-email-link-description-format))
9917 (let* ((p org-store-link-plist)
9918 (to (plist-get p :toaddress))
9919 (from (plist-get p :fromaddress))
9920 (table
9921 (list
9922 (cons "%c" (plist-get p :fromto))
9923 (cons "%F" (plist-get p :from))
9924 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9925 (cons "%T" (plist-get p :to))
9926 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9927 (cons "%s" (plist-get p :subject))
9928 (cons "%d" (plist-get p :date))
9929 (cons "%m" (plist-get p :message-id)))))
9930 (when (string-match "%c" fmt)
9931 ;; Check if the user wrote this message
9932 (if (and org-from-is-user-regexp from to
9933 (save-match-data (string-match org-from-is-user-regexp from)))
9934 (setq fmt (replace-match "to %t" t t fmt))
9935 (setq fmt (replace-match "from %f" t t fmt))))
9936 (org-replace-escapes fmt table)))
9938 (defun org-make-org-heading-search-string (&optional string)
9939 "Make search string for the current headline or STRING."
9940 (let ((s (or string
9941 (and (derived-mode-p 'org-mode)
9942 (save-excursion
9943 (org-back-to-heading t)
9944 (org-element-property :raw-value (org-element-at-point))))))
9945 (lines org-context-in-file-links))
9946 (or string (setq s (concat "*" s))) ; Add * for headlines
9947 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9948 (when (and string (integerp lines) (> lines 0))
9949 (let ((slines (org-split-string s "\n")))
9950 (when (< lines (length slines))
9951 (setq s (mapconcat
9952 'identity
9953 (reverse (nthcdr (- (length slines) lines)
9954 (reverse slines))) "\n")))))
9955 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9957 (defun org-make-link-string (link &optional description)
9958 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9959 (unless (org-string-nw-p link) (error "Empty link"))
9960 (let ((uri (cond ((string-match org-link-types-re link)
9961 (concat (match-string 1 link)
9962 (org-link-escape (substring link (match-end 1)))))
9963 ;; For readability, url-encode internal links only
9964 ;; when absolutely needed (i.e, when they contain
9965 ;; square brackets). File links however, are
9966 ;; encoded since, e.g., spaces are significant.
9967 ((or (file-name-absolute-p link)
9968 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9969 (org-link-escape link))
9970 (t link)))
9971 (description
9972 (and (org-string-nw-p description)
9973 ;; Remove brackets from description, as they are fatal.
9974 (replace-regexp-in-string
9975 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9976 (org-trim description)))))
9977 (format "[[%s]%s]"
9979 (if description (format "[%s]" description) ""))))
9981 (defconst org-link-escape-chars
9982 ;;%20 %5B %5D %25
9983 '(?\s ?\[ ?\] ?%)
9984 "List of characters that should be escaped in a link when stored to Org.
9985 This is the list that is used for internal purposes.")
9987 (defun org-link-escape (text &optional table merge)
9988 "Return percent escaped representation of TEXT.
9989 TEXT is a string with the text to escape.
9990 Optional argument TABLE is a list with characters that should be
9991 escaped. When nil, `org-link-escape-chars' is used.
9992 If optional argument MERGE is set, merge TABLE into
9993 `org-link-escape-chars'."
9994 (let ((characters-to-encode
9995 (cond ((null table) org-link-escape-chars)
9996 (merge (append org-link-escape-chars table))
9997 (t table))))
9998 (mapconcat
9999 (lambda (c)
10000 (if (or (memq c characters-to-encode)
10001 (and org-url-hexify-p (or (< c 32) (> c 126))))
10002 (mapconcat (lambda (e) (format "%%%.2X" e))
10003 (or (encode-coding-char c 'utf-8)
10004 (error "Unable to percent escape character: %c" c))
10006 (char-to-string c)))
10007 text "")))
10009 (defun org-link-unescape (str)
10010 "Unhex hexified Unicode parts in string STR.
10011 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10012 reciprocal of `org-link-escape', which see."
10013 (if (org-string-nw-p str)
10014 (replace-regexp-in-string
10015 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10016 str))
10018 (defun org-link-unescape-compound (hex)
10019 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10020 Note: this function also decodes single byte encodings like
10021 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10022 (save-match-data
10023 (let* ((bytes (cdr (split-string hex "%")))
10024 (ret "")
10025 (eat 0)
10026 (sum 0))
10027 (while bytes
10028 (let* ((val (string-to-number (pop bytes) 16))
10029 (shift-xor
10030 (if (= 0 eat)
10031 (cond
10032 ((>= val 252) (cons 6 252))
10033 ((>= val 248) (cons 5 248))
10034 ((>= val 240) (cons 4 240))
10035 ((>= val 224) (cons 3 224))
10036 ((>= val 192) (cons 2 192))
10037 (t (cons 0 0)))
10038 (cons 6 128))))
10039 (when (>= val 192) (setq eat (car shift-xor)))
10040 (setq val (logxor val (cdr shift-xor)))
10041 (setq sum (+ (lsh sum (car shift-xor)) val))
10042 (when (> eat 0) (setq eat (- eat 1)))
10043 (cond
10044 ((= 0 eat) ;multi byte
10045 (setq ret (concat ret (char-to-string sum)))
10046 (setq sum 0))
10047 ((not bytes) ; single byte(s)
10048 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10049 ret)))
10051 (defun org-link-unescape-single-byte-sequence (hex)
10052 "Unhexify hex-encoded single byte character sequences."
10053 (mapconcat (lambda (byte)
10054 (char-to-string (string-to-number byte 16)))
10055 (cdr (split-string hex "%")) ""))
10057 (defun org-xor (a b)
10058 "Exclusive or."
10059 (if a (not b) b))
10061 (defun org-fixup-message-id-for-http (s)
10062 "Replace special characters in a message id, so it can be used in an http query."
10063 (when (string-match "%" s)
10064 (setq s (mapconcat (lambda (c)
10065 (if (eq c ?%)
10066 "%25"
10067 (char-to-string c)))
10068 s "")))
10069 (while (string-match "<" s)
10070 (setq s (replace-match "%3C" t t s)))
10071 (while (string-match ">" s)
10072 (setq s (replace-match "%3E" t t s)))
10073 (while (string-match "@" s)
10074 (setq s (replace-match "%40" t t s)))
10077 (defun org-link-prettify (link)
10078 "Return a human-readable representation of LINK.
10079 The car of LINK must be a raw link.
10080 The cdr of LINK must be either a link description or nil."
10081 (let ((desc (or (cadr link) "<no description>")))
10082 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10083 "<" (car link) ">")))
10085 ;;;###autoload
10086 (defun org-insert-link-global ()
10087 "Insert a link like Org mode does.
10088 This command can be called in any mode to insert a link in Org syntax."
10089 (interactive)
10090 (org-load-modules-maybe)
10091 (org-run-like-in-org-mode 'org-insert-link))
10093 (defun org-insert-all-links (arg &optional pre post)
10094 "Insert all links in `org-stored-links'.
10095 When a universal prefix, do not delete the links from `org-stored-links'.
10096 When `ARG' is a number, insert the last N link(s).
10097 `PRE' and `POST' are optional arguments to define a string to
10098 prepend or to append."
10099 (interactive "P")
10100 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10101 (links (copy-sequence org-stored-links))
10102 (pr (or pre "- "))
10103 (po (or post "\n"))
10104 (cnt 1) l)
10105 (if (null org-stored-links)
10106 (message "No link to insert")
10107 (while (and (or (listp arg) (>= arg cnt))
10108 (setq l (if (listp arg)
10109 (pop links)
10110 (pop org-stored-links))))
10111 (setq cnt (1+ cnt))
10112 (insert pr)
10113 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10114 (insert po)))))
10116 (defun org-insert-last-stored-link (arg)
10117 "Insert the last link stored in `org-stored-links'."
10118 (interactive "p")
10119 (org-insert-all-links arg "" "\n"))
10121 (defun org-link-fontify-links-to-this-file ()
10122 "Fontify links to the current file in `org-stored-links'."
10123 (let ((f (buffer-file-name)) a b)
10124 (setq a (mapcar (lambda(l)
10125 (let ((ll (car l)))
10126 (when (and (string-match "^file:\\(.+\\)::" ll)
10127 (equal f (expand-file-name (match-string 1 ll))))
10128 ll)))
10129 org-stored-links))
10130 (when (featurep 'org-id)
10131 (setq b (mapcar (lambda(l)
10132 (let ((ll (car l)))
10133 (when (and (string-match "^id:\\(.+\\)$" ll)
10134 (equal f (expand-file-name
10135 (or (org-id-find-id-file
10136 (match-string 1 ll)) ""))))
10137 ll)))
10138 org-stored-links)))
10139 (mapcar (lambda(l)
10140 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10141 (delq nil (append a b)))))
10143 (defvar org--links-history nil)
10144 (defun org-insert-link (&optional complete-file link-location default-description)
10145 "Insert a link. At the prompt, enter the link.
10147 Completion can be used to insert any of the link protocol prefixes in use.
10149 The history can be used to select a link previously stored with
10150 `org-store-link'. When the empty string is entered (i.e. if you just
10151 press `RET' at the prompt), the link defaults to the most recently
10152 stored link. As `SPC' triggers completion in the minibuffer, you need to
10153 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10155 You will also be prompted for a description, and if one is given, it will
10156 be displayed in the buffer instead of the link.
10158 If there is already a link at point, this command will allow you to edit
10159 link and description parts.
10161 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10162 file name can be
10163 selected using completion. The path to the file will be relative to the
10164 current directory if the file is in the current directory or a subdirectory.
10165 Otherwise, the link will be the absolute path as completed in the minibuffer
10166 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10167 option `org-link-file-path-type'.
10169 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10170 absolute path even if the file is in
10171 the current directory or below.
10173 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10174 prefix negates `org-keep-stored-link-after-insertion'.
10176 If `org-make-link-description-function' is non-nil, this function will be
10177 called with the link target, and the result will be the default
10178 link description.
10180 If the LINK-LOCATION parameter is non-nil, this value will be used as
10181 the link location instead of reading one interactively.
10183 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10184 as the default description."
10185 (interactive "P")
10186 (let* ((wcf (current-window-configuration))
10187 (origbuf (current-buffer))
10188 (region (when (org-region-active-p)
10189 (buffer-substring (region-beginning) (region-end))))
10190 (remove (and region (list (region-beginning) (region-end))))
10191 (desc region)
10192 (link link-location)
10193 (abbrevs org-link-abbrev-alist-local)
10194 entry all-prefixes auto-desc)
10195 (cond
10196 (link-location) ; specified by arg, just use it.
10197 ((org-in-regexp org-bracket-link-regexp 1)
10198 ;; We do have a link at point, and we are going to edit it.
10199 (setq remove (list (match-beginning 0) (match-end 0)))
10200 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10201 (setq link (read-string "Link: "
10202 (org-link-unescape
10203 (match-string-no-properties 1)))))
10204 ((or (org-in-regexp org-angle-link-re)
10205 (org-in-regexp org-plain-link-re))
10206 ;; Convert to bracket link
10207 (setq remove (list (match-beginning 0) (match-end 0))
10208 link (read-string "Link: "
10209 (org-unbracket-string "<" ">" (match-string 0)))))
10210 ((member complete-file '((4) (16)))
10211 ;; Completing read for file names.
10212 (setq link (org-file-complete-link complete-file)))
10214 ;; Read link, with completion for stored links.
10215 (org-link-fontify-links-to-this-file)
10216 (org-switch-to-buffer-other-window "*Org Links*")
10217 (with-current-buffer "*Org Links*"
10218 (erase-buffer)
10219 (insert "Insert a link.
10220 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10221 (when org-stored-links
10222 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10223 (insert (mapconcat 'org-link-prettify
10224 (reverse org-stored-links) "\n")))
10225 (goto-char (point-min)))
10226 (let ((cw (selected-window)))
10227 (select-window (get-buffer-window "*Org Links*" 'visible))
10228 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10229 (unless (pos-visible-in-window-p (point-max))
10230 (org-fit-window-to-buffer))
10231 (and (window-live-p cw) (select-window cw)))
10232 (setq all-prefixes (append (mapcar 'car abbrevs)
10233 (mapcar 'car org-link-abbrev-alist)
10234 (org-link-types)))
10235 (unwind-protect
10236 ;; Fake a link history, containing the stored links.
10237 (let ((org--links-history
10238 (append (mapcar #'car org-stored-links)
10239 org-insert-link-history)))
10240 (setq link
10241 (org-completing-read
10242 "Link: "
10243 (append
10244 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10245 (mapcar #'car org-stored-links))
10246 nil nil nil
10247 'org--links-history
10248 (caar org-stored-links)))
10249 (unless (org-string-nw-p link) (user-error "No link selected"))
10250 (dolist (l org-stored-links)
10251 (when (equal link (cadr l))
10252 (setq link (car l))
10253 (setq auto-desc t)))
10254 (when (or (member link all-prefixes)
10255 (and (equal ":" (substring link -1))
10256 (member (substring link 0 -1) all-prefixes)
10257 (setq link (substring link 0 -1))))
10258 (setq link (with-current-buffer origbuf
10259 (org-link-try-special-completion link)))))
10260 (set-window-configuration wcf)
10261 (kill-buffer "*Org Links*"))
10262 (setq entry (assoc link org-stored-links))
10263 (or entry (push link org-insert-link-history))
10264 (setq desc (or desc (nth 1 entry)))))
10266 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10267 (not org-keep-stored-link-after-insertion))
10268 (setq org-stored-links (delq (assoc link org-stored-links)
10269 org-stored-links)))
10271 (when (and (string-match org-plain-link-re link)
10272 (not (string-match org-ts-regexp link)))
10273 ;; URL-like link, normalize the use of angular brackets.
10274 (setq link (org-unbracket-string "<" ">" link)))
10276 ;; Check if we are linking to the current file with a search
10277 ;; option If yes, simplify the link by using only the search
10278 ;; option.
10279 (when (and buffer-file-name
10280 (let ((case-fold-search nil))
10281 (string-match "\\`file:\\(.+?\\)::" link)))
10282 (let ((path (match-string-no-properties 1 link))
10283 (search (substring-no-properties link (match-end 0))))
10284 (save-match-data
10285 (when (equal (file-truename buffer-file-name) (file-truename path))
10286 ;; We are linking to this same file, with a search option
10287 (setq link search)))))
10289 ;; Check if we can/should use a relative path. If yes, simplify the link
10290 (let ((case-fold-search nil))
10291 (when (string-match "\\`\\(file\\|docview\\):" link)
10292 (let* ((type (match-string-no-properties 0 link))
10293 (path (substring-no-properties link (match-end 0)))
10294 (origpath path))
10295 (cond
10296 ((or (eq org-link-file-path-type 'absolute)
10297 (equal complete-file '(16)))
10298 (setq path (abbreviate-file-name (expand-file-name path))))
10299 ((eq org-link-file-path-type 'noabbrev)
10300 (setq path (expand-file-name path)))
10301 ((eq org-link-file-path-type 'relative)
10302 (setq path (file-relative-name path)))
10304 (save-match-data
10305 (if (string-match (concat "^" (regexp-quote
10306 (expand-file-name
10307 (file-name-as-directory
10308 default-directory))))
10309 (expand-file-name path))
10310 ;; We are linking a file with relative path name.
10311 (setq path (substring (expand-file-name path)
10312 (match-end 0)))
10313 (setq path (abbreviate-file-name (expand-file-name path)))))))
10314 (setq link (concat type path))
10315 (when (equal desc origpath)
10316 (setq desc path)))))
10318 (if org-make-link-description-function
10319 (setq desc
10320 (or (condition-case nil
10321 (funcall org-make-link-description-function link desc)
10322 (error (progn (message "Can't get link description from `%s'"
10323 (symbol-name org-make-link-description-function))
10324 (sit-for 2) nil)))
10325 (read-string "Description: " default-description)))
10326 (if default-description (setq desc default-description)
10327 (setq desc (or (and auto-desc desc)
10328 (read-string "Description: " desc)))))
10330 (unless (string-match "\\S-" desc) (setq desc nil))
10331 (when remove (apply 'delete-region remove))
10332 (insert (org-make-link-string link desc))
10333 ;; Redisplay so as the new link has proper invisible characters.
10334 (sit-for 0)))
10336 (defun org-link-try-special-completion (type)
10337 "If there is completion support for link type TYPE, offer it."
10338 (let ((fun (org-link-get-parameter type :complete)))
10339 (if (functionp fun)
10340 (funcall fun)
10341 (read-string "Link (no completion support): " (concat type ":")))))
10343 (defun org-file-complete-link (&optional arg)
10344 "Create a file link using completion."
10345 (let ((file (read-file-name "File: "))
10346 (pwd (file-name-as-directory (expand-file-name ".")))
10347 (pwd1 (file-name-as-directory (abbreviate-file-name
10348 (expand-file-name ".")))))
10349 (cond ((equal arg '(16))
10350 (concat "file:"
10351 (abbreviate-file-name (expand-file-name file))))
10352 ((string-match
10353 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10354 (concat "file:" (match-string 1 file)))
10355 ((string-match
10356 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10357 (expand-file-name file))
10358 (concat "file:"
10359 (match-string 1 (expand-file-name file))))
10360 (t (concat "file:" file)))))
10362 (defun org-completing-read (&rest args)
10363 "Completing-read with SPACE being a normal character."
10364 (let ((enable-recursive-minibuffers t)
10365 (minibuffer-local-completion-map
10366 (copy-keymap minibuffer-local-completion-map)))
10367 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10368 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10369 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10370 'org-time-stamp-inactive)
10371 (apply #'completing-read args)))
10373 ;;; Opening/following a link
10375 (defvar org-link-search-failed nil)
10377 (defvar org-open-link-functions nil
10378 "Hook for functions finding a plain text link.
10379 These functions must take a single argument, the link content.
10380 They will be called for links that look like [[link text][description]]
10381 when LINK TEXT does not have a protocol like \"http:\" and does not look
10382 like a filename (e.g. \"./blue.png\").
10384 These functions will be called *before* Org attempts to resolve the
10385 link by doing text searches in the current buffer - so if you want a
10386 link \"[[target]]\" to still find \"<<target>>\", your function should
10387 handle this as a special case.
10389 When the function does handle the link, it must return a non-nil value.
10390 If it decides that it is not responsible for this link, it must return
10391 nil to indicate that that Org can continue with other options like
10392 exact and fuzzy text search.")
10394 (defun org-next-link (&optional search-backward)
10395 "Move forward to the next link.
10396 If the link is in hidden text, expose it."
10397 (interactive "P")
10398 (when (and org-link-search-failed (eq this-command last-command))
10399 (goto-char (point-min))
10400 (message "Link search wrapped back to beginning of buffer"))
10401 (setq org-link-search-failed nil)
10402 (let* ((pos (point))
10403 (ct (org-context))
10404 (a (assq :link ct))
10405 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10406 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10407 ((looking-at org-any-link-re)
10408 ;; Don't stay stuck at link without an org-link face
10409 (forward-char (if search-backward -1 1))))
10410 (if (funcall srch-fun org-any-link-re nil t)
10411 (progn
10412 (goto-char (match-beginning 0))
10413 (when (org-invisible-p) (org-show-context)))
10414 (goto-char pos)
10415 (setq org-link-search-failed t)
10416 (message "No further link found"))))
10418 (defun org-previous-link ()
10419 "Move backward to the previous link.
10420 If the link is in hidden text, expose it."
10421 (interactive)
10422 (funcall 'org-next-link t))
10424 (defun org-translate-link (s)
10425 "Translate a link string if a translation function has been defined."
10426 (with-temp-buffer
10427 (insert (org-trim s))
10428 (org-trim (org-element-interpret-data (org-element-context)))))
10430 (defun org-translate-link-from-planner (type path)
10431 "Translate a link from Emacs Planner syntax so that Org can follow it.
10432 This is still an experimental function, your mileage may vary."
10433 (cond
10434 ((member type '("http" "https" "news" "ftp"))
10435 ;; standard Internet links are the same.
10436 nil)
10437 ((and (equal type "irc") (string-match "^//" path))
10438 ;; Planner has two / at the beginning of an irc link, we have 1.
10439 ;; We should have zero, actually....
10440 (setq path (substring path 1)))
10441 ((and (equal type "lisp") (string-match "^/" path))
10442 ;; Planner has a slash, we do not.
10443 (setq type "elisp" path (substring path 1)))
10444 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10445 ;; A typical message link. Planner has the id after the final slash,
10446 ;; we separate it with a hash mark
10447 (setq path (concat (match-string 1 path) "#"
10448 (org-unbracket-string "<" ">" (match-string 2 path))))))
10449 (cons type path))
10451 (defun org-find-file-at-mouse (ev)
10452 "Open file link or URL at mouse."
10453 (interactive "e")
10454 (mouse-set-point ev)
10455 (org-open-at-point 'in-emacs))
10457 (defun org-open-at-mouse (ev)
10458 "Open file link or URL at mouse.
10459 See the docstring of `org-open-file' for details."
10460 (interactive "e")
10461 (mouse-set-point ev)
10462 (when (eq major-mode 'org-agenda-mode)
10463 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10464 (org-open-at-point))
10466 (defvar org-window-config-before-follow-link nil
10467 "The window configuration before following a link.
10468 This is saved in case the need arises to restore it.")
10470 ;;;###autoload
10471 (defun org-open-at-point-global ()
10472 "Follow a link or time-stamp like Org mode does.
10473 This command can be called in any mode to follow an external link
10474 or a time-stamp that has Org mode syntax. Its behavior is
10475 undefined when called on internal links (e.g., fuzzy links).
10476 Raise an error when there is nothing to follow. "
10477 (interactive)
10478 (cond ((org-in-regexp org-any-link-re)
10479 (org-open-link-from-string (match-string-no-properties 0)))
10480 ((or (org-in-regexp org-ts-regexp-both nil t)
10481 (org-in-regexp org-tsr-regexp-both nil t))
10482 (org-follow-timestamp-link))
10483 (t (user-error "No link found"))))
10485 ;;;###autoload
10486 (defun org-open-link-from-string (s &optional arg reference-buffer)
10487 "Open a link in the string S, as if it was in Org mode."
10488 (interactive "sLink: \nP")
10489 (let ((reference-buffer (or reference-buffer (current-buffer))))
10490 (with-temp-buffer
10491 (let ((org-inhibit-startup (not reference-buffer)))
10492 (org-mode)
10493 (insert s)
10494 (goto-char (point-min))
10495 (when reference-buffer
10496 (setq org-link-abbrev-alist-local
10497 (with-current-buffer reference-buffer
10498 org-link-abbrev-alist-local)))
10499 (org-open-at-point arg reference-buffer)))))
10501 (defvar org-open-at-point-functions nil
10502 "Hook that is run when following a link at point.
10504 Functions in this hook must return t if they identify and follow
10505 a link at point. If they don't find anything interesting at point,
10506 they must return nil.")
10508 (defvar org-link-search-inhibit-query nil)
10509 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10510 (defun org--open-doi-link (path)
10511 "Open a \"doi\" type link.
10512 PATH is a the path to search for, as a string."
10513 (browse-url (url-encode-url (concat org-doi-server-url path))))
10515 (defun org--open-elisp-link (path)
10516 "Open a \"elisp\" type link.
10517 PATH is the sexp to evaluate, as a string."
10518 (let ((cmd path))
10519 (if (or (and (org-string-nw-p
10520 org-confirm-elisp-link-not-regexp)
10521 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10522 (not org-confirm-elisp-link-function)
10523 (funcall org-confirm-elisp-link-function
10524 (format "Execute \"%s\" as elisp? "
10525 (org-add-props cmd nil 'face 'org-warning))))
10526 (message "%s => %s" cmd
10527 (if (eq (string-to-char cmd) ?\()
10528 (eval (read cmd))
10529 (call-interactively (read cmd))))
10530 (user-error "Abort"))))
10532 (defun org--open-help-link (path)
10533 "Open a \"help\" type link.
10534 PATH is a symbol name, as a string."
10535 (pcase (intern path)
10536 ((and (pred fboundp) variable) (describe-function variable))
10537 ((and (pred boundp) function) (describe-variable function))
10538 (name (user-error "Unknown function or variable: %s" name))))
10540 (defun org--open-shell-link (path)
10541 "Open a \"shell\" type link.
10542 PATH is the command to execute, as a string."
10543 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10544 (cmd path))
10545 (if (or (and (org-string-nw-p
10546 org-confirm-shell-link-not-regexp)
10547 (string-match
10548 org-confirm-shell-link-not-regexp cmd))
10549 (not org-confirm-shell-link-function)
10550 (funcall org-confirm-shell-link-function
10551 (format "Execute \"%s\" in shell? "
10552 (org-add-props cmd nil
10553 'face 'org-warning))))
10554 (progn
10555 (message "Executing %s" cmd)
10556 (shell-command cmd buf)
10557 (when (featurep 'midnight)
10558 (setq clean-buffer-list-kill-buffer-names
10559 (cons (buffer-name buf)
10560 clean-buffer-list-kill-buffer-names))))
10561 (user-error "Abort"))))
10563 (defun org-open-at-point (&optional arg reference-buffer)
10564 "Open link, timestamp, footnote or tags at point.
10566 When point is on a link, follow it. Normally, files will be
10567 opened by an appropriate application. If the optional prefix
10568 argument ARG is non-nil, Emacs will visit the file. With
10569 a double prefix argument, try to open outside of Emacs, in the
10570 application the system uses for this file type.
10572 When point is on a timestamp, open the agenda at the day
10573 specified.
10575 When point is a footnote definition, move to the first reference
10576 found. If it is on a reference, move to the associated
10577 definition.
10579 When point is on a headline, display a list of every link in the
10580 entry, so it is possible to pick one, or all, of them. If point
10581 is on a tag, call `org-tags-view' instead.
10583 When optional argument REFERENCE-BUFFER is non-nil, it should
10584 specify a buffer from where the link search should happen. This
10585 is used internally by `org-open-link-from-string'.
10587 On top of syntactically correct links, this function will also
10588 try to open links and time-stamps in comments, example
10589 blocks... i.e., whenever point is on something looking like
10590 a timestamp or a link."
10591 (interactive "P")
10592 ;; On a code block, open block's results.
10593 (unless (call-interactively 'org-babel-open-src-block-result)
10594 (org-load-modules-maybe)
10595 (setq org-window-config-before-follow-link (current-window-configuration))
10596 (org-remove-occur-highlights nil nil t)
10597 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10598 (let* ((context
10599 ;; Only consider supported types, even if they are not
10600 ;; the closest one.
10601 (org-element-lineage
10602 (org-element-context)
10603 '(clock footnote-definition footnote-reference headline
10604 inlinetask link timestamp)
10606 (type (org-element-type context))
10607 (value (org-element-property :value context)))
10608 (cond
10609 ;; On a headline or an inlinetask, but not on a timestamp,
10610 ;; a link, a footnote reference or on tags.
10611 ((and (memq type '(headline inlinetask))
10612 ;; Not on tags.
10613 (let ((case-fold-search nil))
10614 (and (org-match-line org-complex-heading-regexp)
10615 (or (not (match-beginning 5))
10616 (< (point) (match-beginning 5))))))
10617 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10618 (links (car data))
10619 (links-end (cdr data)))
10620 (if links
10621 (dolist (link (if (stringp links) (list links) links))
10622 (search-forward link nil links-end)
10623 (goto-char (match-beginning 0))
10624 (org-open-at-point))
10625 (require 'org-attach)
10626 (org-attach-reveal 'if-exists))))
10627 ;; On a footnote reference or at definition's label.
10628 ((or (eq type 'footnote-reference)
10629 (and (eq type 'footnote-definition)
10630 (save-excursion
10631 ;; Do not validate action when point is on the
10632 ;; spaces right after the footnote label, in
10633 ;; order to be on par with behaviour on links.
10634 (skip-chars-forward " \t")
10635 (let ((begin
10636 (org-element-property :contents-begin context)))
10637 (if begin (< (point) begin)
10638 (= (org-element-property :post-affiliated context)
10639 (line-beginning-position)))))))
10640 (org-footnote-action))
10641 ;; No valid context. Ignore catch-all types like `headline'.
10642 ;; If point is on something looking like a link or
10643 ;; a time-stamp, try opening it. It may be useful in
10644 ;; comments, example blocks...
10645 ((memq type '(footnote-definition headline inlinetask nil))
10646 (call-interactively #'org-open-at-point-global))
10647 ;; On a clock line, make sure point is on the timestamp
10648 ;; before opening it.
10649 ((and (eq type 'clock)
10650 value
10651 (>= (point) (org-element-property :begin value))
10652 (<= (point) (org-element-property :end value)))
10653 (org-follow-timestamp-link))
10654 ;; Do nothing on white spaces after an object.
10655 ((>= (point)
10656 (save-excursion
10657 (goto-char (org-element-property :end context))
10658 (skip-chars-backward " \t")
10659 (point)))
10660 (user-error "No link found"))
10661 ((eq type 'timestamp) (org-follow-timestamp-link))
10662 ;; On tags within a headline or an inlinetask.
10663 ((and (memq type '(headline inlinetask))
10664 (let ((case-fold-search nil))
10665 (save-excursion (beginning-of-line)
10666 (looking-at org-complex-heading-regexp))
10667 (and (match-beginning 5)
10668 (>= (point) (match-beginning 5)))))
10669 (org-tags-view arg (substring (match-string 5) 0 -1)))
10670 ((eq type 'link)
10671 (let ((type (org-element-property :type context))
10672 (path (org-link-unescape (org-element-property :path context))))
10673 ;; Switch back to REFERENCE-BUFFER needed when called in
10674 ;; a temporary buffer through `org-open-link-from-string'.
10675 (with-current-buffer (or reference-buffer (current-buffer))
10676 (cond
10677 ((equal type "file")
10678 (if (string-match "[*?{]" (file-name-nondirectory path))
10679 (dired path)
10680 ;; Look into `org-link-parameters' in order to find
10681 ;; a DEDICATED-FUNCTION to open file. The function
10682 ;; will be applied on raw link instead of parsed
10683 ;; link due to the limitation in `org-add-link-type'
10684 ;; ("open" function called with a single argument).
10685 ;; If no such function is found, fallback to
10686 ;; `org-open-file'.
10687 (let* ((option (org-element-property :search-option context))
10688 (app (org-element-property :application context))
10689 (dedicated-function
10690 (org-link-get-parameter
10691 (if app (concat type "+" app) type)
10692 :follow)))
10693 (if dedicated-function
10694 (funcall dedicated-function
10695 (concat path
10696 (and option (concat "::" option))))
10697 (apply #'org-open-file
10698 path
10699 (cond (arg)
10700 ((equal app "emacs") 'emacs)
10701 ((equal app "sys") 'system))
10702 (cond ((not option) nil)
10703 ((string-match-p "\\`[0-9]+\\'" option)
10704 (list (string-to-number option)))
10705 (t (list nil
10706 (org-link-unescape option)))))))))
10707 ((functionp (org-link-get-parameter type :follow))
10708 (funcall (org-link-get-parameter type :follow) path))
10709 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10710 (unless (run-hook-with-args-until-success
10711 'org-open-link-functions path)
10712 (if (not arg) (org-mark-ring-push)
10713 (switch-to-buffer-other-window
10714 (org-get-buffer-for-internal-link (current-buffer))))
10715 (let ((destination
10716 (org-with-wide-buffer
10717 (if (equal type "radio")
10718 (org-search-radio-target
10719 (org-element-property :path context))
10720 (org-link-search
10721 (if (member type '("custom-id" "coderef"))
10722 (org-element-property :raw-link context)
10723 path)
10724 ;; Prevent fuzzy links from matching
10725 ;; themselves.
10726 (and (equal type "fuzzy")
10727 (+ 2 (org-element-property :begin context)))))
10728 (point))))
10729 (unless (and (<= (point-min) destination)
10730 (>= (point-max) destination))
10731 (widen))
10732 (goto-char destination))))
10733 (t (browse-url-at-point))))))
10734 (t (user-error "No link found")))))
10735 (run-hook-with-args 'org-follow-link-hook)))
10737 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10738 "Offer links in the current entry and return the selected link.
10739 If there is only one link, return it.
10740 If NTH is an integer, return the NTH link found.
10741 If ZERO is a string, check also this string for a link, and if
10742 there is one, return it."
10743 (with-current-buffer buffer
10744 (org-with-wide-buffer
10745 (goto-char marker)
10746 (let ((cnt ?0)
10747 have-zero end links link c)
10748 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10749 (push (match-string 0 zero) links)
10750 (setq cnt (1- cnt) have-zero t))
10751 (save-excursion
10752 (org-back-to-heading t)
10753 (setq end (save-excursion (outline-next-heading) (point)))
10754 (while (re-search-forward org-any-link-re end t)
10755 (push (match-string 0) links))
10756 (setq links (org-uniquify (reverse links))))
10757 (cond
10758 ((null links)
10759 (message "No links"))
10760 ((equal (length links) 1)
10761 (setq link (car links)))
10762 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10763 (setq link (nth (if have-zero nth (1- nth)) links)))
10764 (t ; we have to select a link
10765 (save-excursion
10766 (save-window-excursion
10767 (delete-other-windows)
10768 (with-output-to-temp-buffer "*Select Link*"
10769 (dolist (l links)
10770 (cond
10771 ((not (string-match org-bracket-link-regexp l))
10772 (princ (format "[%c] %s\n" (cl-incf cnt)
10773 (org-unbracket-string "<" ">" l))))
10774 ((match-end 3)
10775 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10776 (match-string 3 l) (match-string 1 l))))
10777 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10778 (match-string 1 l)))))))
10779 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10780 (message "Select link to open, RET to open all:")
10781 (setq c (read-char-exclusive))
10782 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10783 (when (equal c ?q) (user-error "Abort"))
10784 (if (equal c ?\C-m)
10785 (setq link links)
10786 (setq nth (- c ?0))
10787 (when have-zero (setq nth (1+ nth)))
10788 (unless (and (integerp nth) (>= (length links) nth))
10789 (user-error "Invalid link selection"))
10790 (setq link (nth (1- nth) links)))))
10791 (cons link end)))))
10793 ;; TODO: These functions are deprecated since `org-open-at-point'
10794 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10795 (defun org-open-file-with-system (path)
10796 "Open file at PATH using the system way of opening it."
10797 (org-open-file path 'system))
10798 (defun org-open-file-with-emacs (path)
10799 "Open file at PATH in Emacs."
10800 (org-open-file path 'emacs))
10803 ;;; File search
10805 (defvar org-create-file-search-functions nil
10806 "List of functions to construct the right search string for a file link.
10807 These functions are called in turn with point at the location to
10808 which the link should point.
10810 A function in the hook should first test if it would like to
10811 handle this file type, for example by checking the `major-mode'
10812 or the file extension. If it decides not to handle this file, it
10813 should just return nil to give other functions a chance. If it
10814 does handle the file, it must return the search string to be used
10815 when following the link. The search string will be part of the
10816 file link, given after a double colon, and `org-open-at-point'
10817 will automatically search for it. If special measures must be
10818 taken to make the search successful, another function should be
10819 added to the companion hook `org-execute-file-search-functions',
10820 which see.
10822 A function in this hook may also use `setq' to set the variable
10823 `description' to provide a suggestion for the descriptive text to
10824 be used for this link when it gets inserted into an Org buffer
10825 with \\[org-insert-link].")
10827 (defvar org-execute-file-search-functions nil
10828 "List of functions to execute a file search triggered by a link.
10830 Functions added to this hook must accept a single argument, the
10831 search string that was part of the file link, the part after the
10832 double colon. The function must first check if it would like to
10833 handle this search, for example by checking the `major-mode' or
10834 the file extension. If it decides not to handle this search, it
10835 should just return nil to give other functions a chance. If it
10836 does handle the search, it must return a non-nil value to keep
10837 other functions from trying.
10839 Each function can access the current prefix argument through the
10840 variable `current-prefix-arg'. Note that a single prefix is used
10841 to force opening a link in Emacs, so it may be good to only use a
10842 numeric or double prefix to guide the search function.
10844 In case this is needed, a function in this hook can also restore
10845 the window configuration before `org-open-at-point' was called using:
10847 (set-window-configuration org-window-config-before-follow-link)")
10849 (defun org-search-radio-target (target)
10850 "Search a radio target matching TARGET in current buffer.
10851 White spaces are not significant."
10852 (let ((re (format "<<<%s>>>"
10853 (mapconcat #'regexp-quote
10854 (org-split-string target "[ \t\n]+")
10855 "[ \t]+\\(?:\n[ \t]*\\)?")))
10856 (origin (point)))
10857 (goto-char (point-min))
10858 (catch :radio-match
10859 (while (re-search-forward re nil t)
10860 (backward-char)
10861 (let ((object (org-element-context)))
10862 (when (eq (org-element-type object) 'radio-target)
10863 (goto-char (org-element-property :begin object))
10864 (org-show-context 'link-search)
10865 (throw :radio-match nil))))
10866 (goto-char origin)
10867 (user-error "No match for radio target: %s" target))))
10869 (defun org-link-search (s &optional avoid-pos stealth)
10870 "Search for a search string S.
10872 If S starts with \"#\", it triggers a custom ID search.
10874 If S is enclosed within parenthesis, it initiates a coderef
10875 search.
10877 If S is surrounded by forward slashes, it is interpreted as
10878 a regular expression. In Org mode files, this will create an
10879 `org-occur' sparse tree. In ordinary files, `occur' will be used
10880 to list matches. If the current buffer is in `dired-mode', grep
10881 will be used to search in all files.
10883 When AVOID-POS is given, ignore matches near that position.
10885 When optional argument STEALTH is non-nil, do not modify
10886 visibility around point, thus ignoring `org-show-context-detail'
10887 variable.
10889 Search is case-insensitive and ignores white spaces. Return type
10890 of matched result, which is either `dedicated' or `fuzzy'."
10891 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10892 (let* ((case-fold-search t)
10893 (origin (point))
10894 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10895 (starred (eq (string-to-char normalized) ?*))
10896 (words (split-string (if starred (substring s 1) s)))
10897 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10898 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10899 type)
10900 (cond
10901 ;; Check if there are any special search functions.
10902 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10903 ((eq (string-to-char s) ?#)
10904 ;; Look for a custom ID S if S starts with "#".
10905 (let* ((id (substring normalized 1))
10906 (match (org-find-property "CUSTOM_ID" id)))
10907 (if match (progn (goto-char match) (setf type 'dedicated))
10908 (error "No match for custom ID: %s" id))))
10909 ((string-match "\\`(\\(.*\\))\\'" normalized)
10910 ;; Look for coderef targets if S is enclosed within parenthesis.
10911 (let ((coderef (match-string-no-properties 1 normalized))
10912 (re (substring s-single-re 1 -1)))
10913 (goto-char (point-min))
10914 (catch :coderef-match
10915 (while (re-search-forward re nil t)
10916 (let ((element (org-element-at-point)))
10917 (when (and (memq (org-element-type element)
10918 '(example-block src-block))
10919 ;; Build proper regexp according to current
10920 ;; block's label format.
10921 (let ((label-fmt
10922 (regexp-quote
10923 (or (org-element-property :label-fmt element)
10924 org-coderef-label-format))))
10925 (save-excursion
10926 (beginning-of-line)
10927 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10928 (format label-fmt coderef))))))
10929 (setq type 'dedicated)
10930 (goto-char (match-beginning 1))
10931 (throw :coderef-match nil))))
10932 (goto-char origin)
10933 (error "No match for coderef: %s" coderef))))
10934 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10935 ;; Look for a regular expression.
10936 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10937 (match-string 1 s)))
10938 ;; From here, we handle fuzzy links.
10940 ;; Look for targets, only if not in a headline search.
10941 ((and (not starred)
10942 (let ((target (format "<<%s>>" s-multi-re)))
10943 (catch :target-match
10944 (goto-char (point-min))
10945 (while (re-search-forward target nil t)
10946 (backward-char)
10947 (let ((context (org-element-context)))
10948 (when (eq (org-element-type context) 'target)
10949 (setq type 'dedicated)
10950 (goto-char (org-element-property :begin context))
10951 (throw :target-match t))))
10952 nil))))
10953 ;; Look for elements named after S, only if not in a headline
10954 ;; search.
10955 ((and (not starred)
10956 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10957 (catch :name-match
10958 (goto-char (point-min))
10959 (while (re-search-forward name nil t)
10960 (let ((element (org-element-at-point)))
10961 (when (equal words
10962 (split-string
10963 (org-element-property :name element)))
10964 (setq type 'dedicated)
10965 (beginning-of-line)
10966 (throw :name-match t))))
10967 nil))))
10968 ;; Regular text search. Prefer headlines in Org mode buffers.
10969 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10970 ;; statistics cookies and tags.
10971 ((and (derived-mode-p 'org-mode)
10972 (let ((title-re
10973 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10974 org-outline-regexp-bol
10975 org-comment-string
10976 (mapconcat #'regexp-quote words ".+")))
10977 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10978 (comment-re (eval-when-compile
10979 (format "\\`%s[ \t]+" org-comment-string))))
10980 (goto-char (point-min))
10981 (catch :found
10982 (while (re-search-forward title-re nil t)
10983 (when (equal words
10984 (split-string
10985 (replace-regexp-in-string
10986 cookie-re ""
10987 (replace-regexp-in-string
10988 comment-re "" (org-get-heading t t t)))))
10989 (throw :found t)))
10990 nil)))
10991 (beginning-of-line)
10992 (setq type 'dedicated))
10993 ;; Offer to create non-existent headline depending on
10994 ;; `org-link-search-must-match-exact-headline'.
10995 ((and (derived-mode-p 'org-mode)
10996 (not org-link-search-inhibit-query)
10997 (eq org-link-search-must-match-exact-headline 'query-to-create)
10998 (yes-or-no-p "No match - create this as a new heading? "))
10999 (goto-char (point-max))
11000 (unless (bolp) (newline))
11001 (org-insert-heading nil t t)
11002 (insert s "\n")
11003 (beginning-of-line 0))
11004 ;; Only headlines are looked after. No need to process
11005 ;; further: throw an error.
11006 ((and (derived-mode-p 'org-mode)
11007 (or starred org-link-search-must-match-exact-headline))
11008 (goto-char origin)
11009 (error "No match for fuzzy expression: %s" normalized))
11010 ;; Regular text search.
11011 ((catch :fuzzy-match
11012 (goto-char (point-min))
11013 (while (re-search-forward s-multi-re nil t)
11014 ;; Skip match if it contains AVOID-POS or it is included in
11015 ;; a link with a description but outside the description.
11016 (unless (or (and avoid-pos
11017 (<= (match-beginning 0) avoid-pos)
11018 (> (match-end 0) avoid-pos))
11019 (and (save-match-data
11020 (org-in-regexp org-bracket-link-regexp))
11021 (match-beginning 3)
11022 (or (> (match-beginning 3) (point))
11023 (<= (match-end 3) (point)))
11024 (org-element-lineage
11025 (save-match-data (org-element-context))
11026 '(link) t)))
11027 (goto-char (match-beginning 0))
11028 (setq type 'fuzzy)
11029 (throw :fuzzy-match t)))
11030 nil))
11031 ;; All failed. Throw an error.
11032 (t (goto-char origin)
11033 (error "No match for fuzzy expression: %s" normalized)))
11034 ;; Disclose surroundings of match, if appropriate.
11035 (when (and (derived-mode-p 'org-mode) (not stealth))
11036 (org-show-context 'link-search))
11037 type))
11039 (defun org-get-buffer-for-internal-link (buffer)
11040 "Return a buffer to be used for displaying the link target of internal links."
11041 (cond
11042 ((not org-display-internal-link-with-indirect-buffer)
11043 buffer)
11044 ((string-suffix-p "(Clone)" (buffer-name buffer))
11045 (message "Buffer is already a clone, not making another one")
11046 ;; we also do not modify visibility in this case
11047 buffer)
11048 (t ; make a new indirect buffer for displaying the link
11049 (let* ((bn (buffer-name buffer))
11050 (ibn (concat bn "(Clone)"))
11051 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11052 (with-current-buffer ib (org-overview))
11053 ib))))
11055 (defun org-do-occur (regexp &optional cleanup)
11056 "Call the Emacs command `occur'.
11057 If CLEANUP is non-nil, remove the printout of the regular expression
11058 in the *Occur* buffer. This is useful if the regex is long and not useful
11059 to read."
11060 (occur regexp)
11061 (when cleanup
11062 (let ((cwin (selected-window)) win beg end)
11063 (when (setq win (get-buffer-window "*Occur*"))
11064 (select-window win))
11065 (goto-char (point-min))
11066 (when (re-search-forward "match[a-z]+" nil t)
11067 (setq beg (match-end 0))
11068 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11069 (setq end (1- (match-beginning 0)))))
11070 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11071 (goto-char (point-min))
11072 (select-window cwin))))
11074 ;;; The mark ring for links jumps
11076 (defvar org-mark-ring nil
11077 "Mark ring for positions before jumps in Org mode.")
11078 (defvar org-mark-ring-last-goto nil
11079 "Last position in the mark ring used to go back.")
11080 ;; Fill and close the ring
11081 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11082 (dotimes (_ org-mark-ring-length)
11083 (push (make-marker) org-mark-ring))
11084 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11085 org-mark-ring)
11087 (defun org-mark-ring-push (&optional pos buffer)
11088 "Put the current position or POS into the mark ring and rotate it."
11089 (interactive)
11090 (setq pos (or pos (point)))
11091 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11092 (move-marker (car org-mark-ring)
11093 (or pos (point))
11094 (or buffer (current-buffer)))
11095 (message "%s"
11096 (substitute-command-keys
11097 "Position saved to mark ring, go back with \
11098 `\\[org-mark-ring-goto]'.")))
11100 (defun org-mark-ring-goto (&optional n)
11101 "Jump to the previous position in the mark ring.
11102 With prefix arg N, jump back that many stored positions. When
11103 called several times in succession, walk through the entire ring.
11104 Org mode commands jumping to a different position in the current file,
11105 or to another Org file, automatically push the old position onto the ring."
11106 (interactive "p")
11107 (let (p m)
11108 (if (eq last-command this-command)
11109 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11110 (setq p org-mark-ring))
11111 (setq org-mark-ring-last-goto p)
11112 (setq m (car p))
11113 (pop-to-buffer-same-window (marker-buffer m))
11114 (goto-char m)
11115 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11117 (defun org-add-angle-brackets (s)
11118 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11119 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11122 ;;; Following specific links
11124 (defvar org-agenda-buffer-tmp-name)
11125 (defvar org-agenda-start-on-weekday)
11126 (defun org-follow-timestamp-link ()
11127 "Open an agenda view for the time-stamp date/range at point."
11128 (cond
11129 ((org-at-date-range-p t)
11130 (let ((org-agenda-start-on-weekday)
11131 (t1 (match-string 1))
11132 (t2 (match-string 2)) tt1 tt2)
11133 (setq tt1 (time-to-days (org-time-string-to-time t1))
11134 tt2 (time-to-days (org-time-string-to-time t2)))
11135 (let ((org-agenda-buffer-tmp-name
11136 (format "*Org Agenda(a:%s)"
11137 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11138 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11139 ((org-at-timestamp-p 'lax)
11140 (let ((org-agenda-buffer-tmp-name
11141 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11142 (org-agenda-list nil (time-to-days (org-time-string-to-time
11143 (substring (match-string 1) 0 10)))
11144 1)))
11145 (t (error "This should not happen"))))
11148 ;;; Following file links
11149 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11150 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11151 (declare-function mailcap-mime-info
11152 "mailcap" (string &optional request no-decode))
11153 (defvar org-wait nil)
11154 (defun org-open-file (path &optional in-emacs line search)
11155 "Open the file at PATH.
11156 First, this expands any special file name abbreviations. Then the
11157 configuration variable `org-file-apps' is checked if it contains an
11158 entry for this file type, and if yes, the corresponding command is launched.
11160 If no application is found, Emacs simply visits the file.
11162 With optional prefix argument IN-EMACS, Emacs will visit the file.
11163 With a double \\[universal-argument] \\[universal-argument] \
11164 prefix arg, Org tries to avoid opening in Emacs
11165 and to use an external application to visit the file.
11167 Optional LINE specifies a line to go to, optional SEARCH a string
11168 to search for. If LINE or SEARCH is given, the file will be
11169 opened in Emacs, unless an entry from org-file-apps that makes
11170 use of groups in a regexp matches.
11172 If you want to change the way frames are used when following a
11173 link, please customize `org-link-frame-setup'.
11175 If the file does not exist, an error is thrown."
11176 (let* ((file (if (equal path "")
11177 buffer-file-name
11178 (substitute-in-file-name (expand-file-name path))))
11179 (file-apps (append org-file-apps (org-default-apps)))
11180 (apps (cl-remove-if
11181 'org-file-apps-entry-match-against-dlink-p file-apps))
11182 (apps-dlink (cl-remove-if-not
11183 'org-file-apps-entry-match-against-dlink-p file-apps))
11184 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11185 (dirp (unless remp (file-directory-p file)))
11186 (file (if (and dirp org-open-directory-means-index-dot-org)
11187 (concat (file-name-as-directory file) "index.org")
11188 file))
11189 (a-m-a-p (assq 'auto-mode apps))
11190 (dfile (downcase file))
11191 ;; Reconstruct the original link from the PATH, LINE and
11192 ;; SEARCH args.
11193 (link (cond (line (concat file "::" (number-to-string line)))
11194 (search (concat file "::" search))
11195 (t file)))
11196 (dlink (downcase link))
11197 (ext
11198 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11199 (match-string 1 dfile)))
11200 (save-position-maybe
11201 (let ((old-buffer (current-buffer))
11202 (old-pos (point))
11203 (old-mode major-mode))
11204 (lambda ()
11205 (and (derived-mode-p 'org-mode)
11206 (eq old-mode 'org-mode)
11207 (or (not (eq old-buffer (current-buffer)))
11208 (not (eq old-pos (point))))
11209 (org-mark-ring-push old-pos old-buffer)))))
11210 cmd link-match-data)
11211 (cond
11212 ((member in-emacs '((16) system))
11213 (setq cmd (cdr (assq 'system apps))))
11214 (in-emacs (setq cmd 'emacs))
11216 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11217 (and dirp (cdr (assq 'directory apps)))
11218 ;; First, try matching against apps-dlink if we
11219 ;; get a match here, store the match data for
11220 ;; later.
11221 (let ((match (assoc-default dlink apps-dlink
11222 'string-match)))
11223 (if match
11224 (progn (setq link-match-data (match-data))
11225 match)
11226 (progn (setq in-emacs (or in-emacs line search))
11227 nil))) ; if we have no match in apps-dlink,
11228 ; always open the file in emacs if line or search
11229 ; is given (for backwards compatibility)
11230 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11231 'string-match)
11232 (cdr (assoc ext apps))
11233 (cdr (assq t apps))))))
11234 (when (eq cmd 'system)
11235 (setq cmd (cdr (assq 'system apps))))
11236 (when (eq cmd 'default)
11237 (setq cmd (cdr (assoc t apps))))
11238 (when (eq cmd 'mailcap)
11239 (require 'mailcap)
11240 (mailcap-parse-mailcaps)
11241 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11242 (command (mailcap-mime-info mime-type)))
11243 (if (stringp command)
11244 (setq cmd command)
11245 (setq cmd 'emacs))))
11246 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11247 (not (file-exists-p file))
11248 (not org-open-non-existing-files))
11249 (user-error "No such file: %s" file))
11250 (cond
11251 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11252 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11253 (while (string-match "['\"]%s['\"]" cmd)
11254 (setq cmd (replace-match "%s" t t cmd)))
11255 (setq cmd (replace-regexp-in-string
11256 "%s"
11257 (shell-quote-argument (convert-standard-filename file))
11259 nil t))
11261 ;; Replace "%1", "%2" etc. in command with group matches from regex
11262 (save-match-data
11263 (let ((match-index 1)
11264 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11265 (set-match-data link-match-data)
11266 (while (<= match-index number-of-groups)
11267 (let ((regex (concat "%" (number-to-string match-index)))
11268 (replace-with (match-string match-index dlink)))
11269 (while (string-match regex cmd)
11270 (setq cmd (replace-match replace-with t t cmd))))
11271 (setq match-index (+ match-index 1)))))
11273 (save-window-excursion
11274 (message "Running %s...done" cmd)
11275 (start-process-shell-command cmd nil cmd)
11276 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11277 ((or (stringp cmd)
11278 (eq cmd 'emacs))
11279 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11280 (widen)
11281 (cond (line (org-goto-line line)
11282 (when (derived-mode-p 'org-mode) (org-reveal)))
11283 (search (condition-case err
11284 (org-link-search search)
11285 ;; Save position before error-ing out so user
11286 ;; can easily move back to the original buffer.
11287 (error (funcall save-position-maybe)
11288 (error (nth 1 err)))))))
11289 ((functionp cmd)
11290 (save-match-data
11291 (set-match-data link-match-data)
11292 (condition-case nil
11293 (funcall cmd file link)
11294 ;; FIXME: Remove this check when most default installations
11295 ;; of Emacs have at least Org 9.0.
11296 ((debug wrong-number-of-arguments wrong-type-argument
11297 invalid-function)
11298 (user-error "Please see Org News for version 9.0 about \
11299 `org-file-apps'--Lisp error: %S" cmd)))))
11300 ((consp cmd)
11301 ;; FIXME: Remove this check when most default installations of
11302 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11303 ;; fall back to `org-link-frame-setup' for an old usage of
11304 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11305 (user-error "Please see Org News for version 9.0 about \
11306 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11307 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11308 (funcall save-position-maybe)))
11310 (defun org-file-apps-entry-match-against-dlink-p (entry)
11311 "This function returns non-nil if `entry' uses a regular
11312 expression which should be matched against the whole link by
11313 org-open-file.
11315 It assumes that is the case when the entry uses a regular
11316 expression which has at least one grouping construct and the
11317 action is either a lisp form or a command string containing
11318 `%1', i.e. using at least one subexpression match as a
11319 parameter."
11320 (let ((selector (car entry))
11321 (action (cdr entry)))
11322 (if (stringp selector)
11323 (and (> (regexp-opt-depth selector) 0)
11324 (or (and (stringp action)
11325 (string-match "%[0-9]" action))
11326 (consp action)))
11327 nil)))
11329 (defun org-default-apps ()
11330 "Return the default applications for this operating system."
11331 (cond
11332 ((eq system-type 'darwin)
11333 org-file-apps-defaults-macosx)
11334 ((eq system-type 'windows-nt)
11335 org-file-apps-defaults-windowsnt)
11336 (t org-file-apps-defaults-gnu)))
11338 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11339 "Convert extensions to regular expressions in the cars of LIST.
11340 Also, weed out any non-string entries, because the return value is used
11341 only for regexp matching.
11342 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11343 point to the symbol `emacs', indicating that the file should
11344 be opened in Emacs."
11345 (append
11346 (delq nil
11347 (mapcar (lambda (x)
11348 (unless (not (stringp (car x)))
11349 (if (string-match "\\W" (car x))
11351 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11352 list))
11353 (when add-auto-mode
11354 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11356 (defvar ange-ftp-name-format)
11357 (defun org-file-remote-p (file)
11358 "Test whether FILE specifies a location on a remote system.
11359 Return non-nil if the location is indeed remote.
11361 For example, the filename \"/user@host:/foo\" specifies a location
11362 on the system \"/user@host:\"."
11363 (cond ((fboundp 'file-remote-p)
11364 (file-remote-p file))
11365 ((fboundp 'tramp-handle-file-remote-p)
11366 (tramp-handle-file-remote-p file))
11367 ((and (boundp 'ange-ftp-name-format)
11368 (string-match (car ange-ftp-name-format) file))
11369 t)))
11372 ;;;; Refiling
11374 (defun org-get-org-file ()
11375 "Read a filename, with default directory `org-directory'."
11376 (let ((default (or org-default-notes-file remember-data-file)))
11377 (read-file-name (format "File name [%s]: " default)
11378 (file-name-as-directory org-directory)
11379 default)))
11381 (defun org-notes-order-reversed-p ()
11382 "Check if the current file should receive notes in reversed order."
11383 (cond
11384 ((not org-reverse-note-order) nil)
11385 ((eq t org-reverse-note-order) t)
11386 ((not (listp org-reverse-note-order)) nil)
11387 (t (catch 'exit
11388 (dolist (entry org-reverse-note-order)
11389 (when (string-match (car entry) buffer-file-name)
11390 (throw 'exit (cdr entry))))))))
11392 (defvar org-refile-target-table nil
11393 "The list of refile targets, created by `org-refile'.")
11395 (defvar org-agenda-new-buffers nil
11396 "Buffers created to visit agenda files.")
11398 (defvar org-refile-cache nil
11399 "Cache for refile targets.")
11401 (defvar org-refile-markers nil
11402 "All the markers used for caching refile locations.")
11404 (defun org-refile-marker (pos)
11405 "Get a new refile marker, but only if caching is in use."
11406 (if (not org-refile-use-cache)
11408 (let ((m (make-marker)))
11409 (move-marker m pos)
11410 (push m org-refile-markers)
11411 m)))
11413 (defun org-refile-cache-clear ()
11414 "Clear the refile cache and disable all the markers."
11415 (dolist (m org-refile-markers) (move-marker m nil))
11416 (setq org-refile-markers nil)
11417 (setq org-refile-cache nil)
11418 (message "Refile cache has been cleared"))
11420 (defun org-refile-cache-check-set (set)
11421 "Check if all the markers in the cache still have live buffers."
11422 (let (marker)
11423 (catch 'exit
11424 (while (and set (setq marker (nth 3 (pop set))))
11425 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11426 (when (and marker (null (marker-buffer marker)))
11427 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11428 (sit-for 3)
11429 (throw 'exit nil)))
11430 t)))
11432 (defun org-refile-cache-put (set &rest identifiers)
11433 "Push the refile targets SET into the cache, under IDENTIFIERS."
11434 (let* ((key (sha1 (prin1-to-string identifiers)))
11435 (entry (assoc key org-refile-cache)))
11436 (if entry
11437 (setcdr entry set)
11438 (push (cons key set) org-refile-cache))))
11440 (defun org-refile-cache-get (&rest identifiers)
11441 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11442 (cond
11443 ((not org-refile-cache) nil)
11444 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11446 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11447 org-refile-cache))))
11448 (and set (org-refile-cache-check-set set) set)))))
11450 (defvar org-outline-path-cache nil
11451 "Alist between buffer positions and outline paths.
11452 It value is an alist (POSITION . PATH) where POSITION is the
11453 buffer position at the beginning of an entry and PATH is a list
11454 of strings describing the outline path for that entry, in reverse
11455 order.")
11457 (defun org-refile-get-targets (&optional default-buffer)
11458 "Produce a table with refile targets."
11459 (let ((case-fold-search nil)
11460 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11461 (entries (or org-refile-targets '((nil . (:level . 1)))))
11462 targets tgs files desc descre)
11463 (message "Getting targets...")
11464 (with-current-buffer (or default-buffer (current-buffer))
11465 (dolist (entry entries)
11466 (setq files (car entry) desc (cdr entry))
11467 (cond
11468 ((null files) (setq files (list (current-buffer))))
11469 ((eq files 'org-agenda-files)
11470 (setq files (org-agenda-files 'unrestricted)))
11471 ((and (symbolp files) (fboundp files))
11472 (setq files (funcall files)))
11473 ((and (symbolp files) (boundp files))
11474 (setq files (symbol-value files))))
11475 (when (stringp files) (setq files (list files)))
11476 (cond
11477 ((eq (car desc) :tag)
11478 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11479 ((eq (car desc) :todo)
11480 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11481 ((eq (car desc) :regexp)
11482 (setq descre (cdr desc)))
11483 ((eq (car desc) :level)
11484 (setq descre (concat "^\\*\\{" (number-to-string
11485 (if org-odd-levels-only
11486 (1- (* 2 (cdr desc)))
11487 (cdr desc)))
11488 "\\}[ \t]")))
11489 ((eq (car desc) :maxlevel)
11490 (setq descre (concat "^\\*\\{1," (number-to-string
11491 (if org-odd-levels-only
11492 (1- (* 2 (cdr desc)))
11493 (cdr desc)))
11494 "\\}[ \t]")))
11495 (t (error "Bad refiling target description %s" desc)))
11496 (dolist (f files)
11497 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11499 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11500 (progn
11501 (when (bufferp f)
11502 (setq f (buffer-file-name (buffer-base-buffer f))))
11503 (setq f (and f (expand-file-name f)))
11504 (when (eq org-refile-use-outline-path 'file)
11505 (push (list (file-name-nondirectory f) f nil nil) tgs))
11506 (when (eq org-refile-use-outline-path 'buffer-name)
11507 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11508 (when (eq org-refile-use-outline-path 'full-file-path)
11509 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11510 (org-with-wide-buffer
11511 (goto-char (point-min))
11512 (setq org-outline-path-cache nil)
11513 (while (re-search-forward descre nil t)
11514 (beginning-of-line)
11515 (let ((case-fold-search nil))
11516 (looking-at org-complex-heading-regexp))
11517 (let ((begin (point))
11518 (heading (match-string-no-properties 4)))
11519 (unless (or (and
11520 org-refile-target-verify-function
11521 (not
11522 (funcall org-refile-target-verify-function)))
11523 (not heading))
11524 (let ((re (format org-complex-heading-regexp-format
11525 (regexp-quote heading)))
11526 (target
11527 (if (not org-refile-use-outline-path) heading
11528 (mapconcat
11529 #'identity
11530 (append
11531 (pcase org-refile-use-outline-path
11532 (`file (list (file-name-nondirectory
11533 (buffer-file-name
11534 (buffer-base-buffer)))))
11535 (`full-file-path
11536 (list (buffer-file-name
11537 (buffer-base-buffer))))
11538 (`buffer-name
11539 (list (buffer-name
11540 (buffer-base-buffer))))
11541 (_ nil))
11542 (mapcar (lambda (s) (replace-regexp-in-string
11543 "/" "\\/" s nil t))
11544 (org-get-outline-path t t)))
11545 "/"))))
11546 (push (list target f re (org-refile-marker (point)))
11547 tgs)))
11548 (when (= (point) begin)
11549 ;; Verification function has not moved point.
11550 (end-of-line)))))))
11551 (when org-refile-use-cache
11552 (org-refile-cache-put tgs (buffer-file-name) descre))
11553 (setq targets (append tgs targets))))))
11554 (message "Getting targets...done")
11555 (delete-dups (nreverse targets))))
11557 (defun org--get-outline-path-1 (&optional use-cache)
11558 "Return outline path to current headline.
11560 Outline path is a list of strings, in reverse order. When
11561 optional argument USE-CACHE is non-nil, make use of a cache. See
11562 `org-get-outline-path' for details.
11564 Assume buffer is widened and point is on a headline."
11565 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11566 (let ((p (point))
11567 (heading (let ((case-fold-search nil))
11568 (looking-at org-complex-heading-regexp)
11569 (if (not (match-end 4)) ""
11570 ;; Remove statistics cookies.
11571 (org-trim
11572 (org-link-display-format
11573 (replace-regexp-in-string
11574 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11575 (match-string-no-properties 4))))))))
11576 (if (org-up-heading-safe)
11577 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11578 (when use-cache
11579 (push (cons p path) org-outline-path-cache))
11580 path)
11581 ;; This is a new root node. Since we assume we are moving
11582 ;; forward, we can drop previous cache so as to limit number
11583 ;; of associations there.
11584 (let ((path (list heading)))
11585 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11586 path)))))
11588 (defun org-get-outline-path (&optional with-self use-cache)
11589 "Return the outline path to the current entry.
11591 An outline path is a list of ancestors for current headline, as
11592 a list of strings. Statistics cookies are removed and links are
11593 replaced with their description, if any, or their path otherwise.
11595 When optional argument WITH-SELF is non-nil, the path also
11596 includes the current headline.
11598 When optional argument USE-CACHE is non-nil, cache outline paths
11599 between calls to this function so as to avoid backtracking. This
11600 argument is useful when planning to find more than one outline
11601 path in the same document. In that case, there are two
11602 conditions to satisfy:
11603 - `org-outline-path-cache' is set to nil before starting the
11604 process;
11605 - outline paths are computed by increasing buffer positions."
11606 (org-with-wide-buffer
11607 (and (or (and with-self (org-back-to-heading t))
11608 (org-up-heading-safe))
11609 (reverse (org--get-outline-path-1 use-cache)))))
11611 (defun org-format-outline-path (path &optional width prefix separator)
11612 "Format the outline path PATH for display.
11613 WIDTH is the maximum number of characters that is available.
11614 PREFIX is a prefix to be included in the returned string,
11615 such as the file name.
11616 SEPARATOR is inserted between the different parts of the path,
11617 the default is \"/\"."
11618 (setq width (or width 79))
11619 (setq path (delq nil path))
11620 (unless (> width 0)
11621 (user-error "Argument `width' must be positive"))
11622 (setq separator (or separator "/"))
11623 (let* ((org-odd-levels-only nil)
11624 (fpath (concat
11625 prefix (and prefix path separator)
11626 (mapconcat
11627 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11628 (cl-loop for head in path
11629 for n from 0
11630 collect (org-add-props
11631 head nil 'face
11632 (nth (% n org-n-level-faces) org-level-faces)))
11633 separator))))
11634 (when (> (length fpath) width)
11635 (if (< width 7)
11636 ;; It's unlikely that `width' will be this small, but don't
11637 ;; waste characters by adding ".." if it is.
11638 (setq fpath (substring fpath 0 width))
11639 (setf (substring fpath (- width 2)) "..")))
11640 fpath))
11642 (defun org-display-outline-path (&optional file current separator just-return-string)
11643 "Display the current outline path in the echo area.
11645 If FILE is non-nil, prepend the output with the file name.
11646 If CURRENT is non-nil, append the current heading to the output.
11647 SEPARATOR is passed through to `org-format-outline-path'. It separates
11648 the different parts of the path and defaults to \"/\".
11649 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11650 (interactive "P")
11651 (let* (case-fold-search
11652 (bfn (buffer-file-name (buffer-base-buffer)))
11653 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11654 res)
11655 (when current (setq path (append path
11656 (save-excursion
11657 (org-back-to-heading t)
11658 (when (looking-at org-complex-heading-regexp)
11659 (list (match-string 4)))))))
11660 (setq res
11661 (org-format-outline-path
11662 path
11663 (1- (frame-width))
11664 (and file bfn (concat (file-name-nondirectory bfn) separator))
11665 separator))
11666 (if just-return-string
11667 (org-no-properties res)
11668 (org-unlogged-message "%s" res))))
11670 (defvar org-refile-history nil
11671 "History for refiling operations.")
11673 (defvar org-after-refile-insert-hook nil
11674 "Hook run after `org-refile' has inserted its stuff at the new location.
11675 Note that this is still *before* the stuff will be removed from
11676 the *old* location.")
11678 (defvar org-capture-last-stored-marker)
11679 (defvar org-refile-keep nil
11680 "Non-nil means `org-refile' will copy instead of refile.")
11682 (defun org-copy ()
11683 "Like `org-refile', but copy."
11684 (interactive)
11685 (let ((org-refile-keep t))
11686 (funcall 'org-refile nil nil nil "Copy")))
11688 (defun org-refile (&optional arg default-buffer rfloc msg)
11689 "Move the entry or entries at point to another heading.
11691 The list of target headings is compiled using the information in
11692 `org-refile-targets', which see.
11694 At the target location, the entry is filed as a subitem of the
11695 target heading. Depending on `org-reverse-note-order', the new
11696 subitem will either be the first or the last subitem.
11698 If there is an active region, all entries in that region will be
11699 refiled. However, the region must fulfill the requirement that
11700 the first heading sets the top-level of the moved text.
11702 With a `\\[universal-argument]' ARG, the command will only visit the target \
11703 location
11704 and not actually move anything.
11706 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11707 location where the last
11708 refiling operation has put the subtree.
11710 With a numeric prefix argument of `2', refile to the running clock.
11712 With a numeric prefix argument of `3', emulate `org-refile-keep'
11713 being set to t and copy to the target location, don't move it.
11714 Beware that keeping refiled entries may result in duplicated ID
11715 properties.
11717 RFLOC can be a refile location obtained in a different way.
11719 MSG is a string to replace \"Refile\" in the default prompt with
11720 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11722 See also `org-refile-use-outline-path'.
11724 If you are using target caching (see `org-refile-use-cache'), you
11725 have to clear the target cache in order to find new targets.
11726 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11727 prefix argument (`C-u C-u C-u C-c C-w')."
11728 (interactive "P")
11729 (if (member arg '(0 (64)))
11730 (org-refile-cache-clear)
11731 (let* ((actionmsg (cond (msg msg)
11732 ((equal arg 3) "Refile (and keep)")
11733 (t "Refile")))
11734 (regionp (org-region-active-p))
11735 (region-start (and regionp (region-beginning)))
11736 (region-end (and regionp (region-end)))
11737 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11738 pos it nbuf file level reversed)
11739 (setq last-command nil)
11740 (when regionp
11741 (goto-char region-start)
11742 (or (bolp) (goto-char (point-at-bol)))
11743 (setq region-start (point))
11744 (unless (or (org-kill-is-subtree-p
11745 (buffer-substring region-start region-end))
11746 (prog1 org-refile-active-region-within-subtree
11747 (let ((s (point-at-eol)))
11748 (org-toggle-heading)
11749 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11750 (user-error "The region is not a (sequence of) subtree(s)")))
11751 (if (equal arg '(16))
11752 (org-refile-goto-last-stored)
11753 (when (or
11754 (and (equal arg 2)
11755 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11756 (prog1
11757 (setq it (list (or org-clock-heading "running clock")
11758 (buffer-file-name
11759 (marker-buffer org-clock-hd-marker))
11761 (marker-position org-clock-hd-marker)))
11762 (setq arg nil)))
11763 (setq it
11764 (or rfloc
11765 (let (heading-text)
11766 (save-excursion
11767 (unless (and arg (listp arg))
11768 (org-back-to-heading t)
11769 (setq heading-text
11770 (replace-regexp-in-string
11771 org-bracket-link-regexp
11772 "\\3"
11773 (or (nth 4 (org-heading-components))
11774 ""))))
11775 (org-refile-get-location
11776 (cond ((and arg (listp arg)) "Goto")
11777 (regionp (concat actionmsg " region to"))
11778 (t (concat actionmsg " subtree \""
11779 heading-text "\" to")))
11780 default-buffer
11781 (and (not (equal '(4) arg))
11782 org-refile-allow-creating-parent-nodes)))))))
11783 (setq file (nth 1 it)
11784 pos (nth 3 it))
11785 (when (and (not arg)
11787 (equal (buffer-file-name) file)
11788 (if regionp
11789 (and (>= pos region-start)
11790 (<= pos region-end))
11791 (and (>= pos (point))
11792 (< pos (save-excursion
11793 (org-end-of-subtree t t))))))
11794 (error "Cannot refile to position inside the tree or region"))
11795 (setq nbuf (or (find-buffer-visiting file)
11796 (find-file-noselect file)))
11797 (if (and arg (not (equal arg 3)))
11798 (progn
11799 (pop-to-buffer-same-window nbuf)
11800 (goto-char (cond (pos)
11801 ((org-notes-order-reversed-p) (point-min))
11802 (t (point-max))))
11803 (org-show-context 'org-goto))
11804 (if regionp
11805 (progn
11806 (org-kill-new (buffer-substring region-start region-end))
11807 (org-save-markers-in-region region-start region-end))
11808 (org-copy-subtree 1 nil t))
11809 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11810 (find-file-noselect file)))
11811 (setq reversed (org-notes-order-reversed-p))
11812 (org-with-wide-buffer
11813 (if pos
11814 (progn
11815 (goto-char pos)
11816 (setq level (org-get-valid-level (funcall outline-level) 1))
11817 (goto-char
11818 (if reversed
11819 (or (outline-next-heading) (point-max))
11820 (or (save-excursion (org-get-next-sibling))
11821 (org-end-of-subtree t t)
11822 (point-max)))))
11823 (setq level 1)
11824 (if (not reversed)
11825 (goto-char (point-max))
11826 (goto-char (point-min))
11827 (or (outline-next-heading) (goto-char (point-max)))))
11828 (unless (bolp) (newline))
11829 (org-paste-subtree level nil nil t)
11830 (when org-log-refile
11831 (org-add-log-setup 'refile nil nil org-log-refile)
11832 (unless (eq org-log-refile 'note)
11833 (save-excursion (org-add-log-note))))
11834 (and org-auto-align-tags
11835 (let ((org-loop-over-headlines-in-active-region nil))
11836 (org-set-tags nil t)))
11837 (let ((bookmark-name (plist-get org-bookmark-names-plist
11838 :last-refile)))
11839 (when bookmark-name
11840 (with-demoted-errors
11841 (bookmark-set bookmark-name))))
11842 ;; If we are refiling for capture, make sure that the
11843 ;; last-capture pointers point here
11844 (when (bound-and-true-p org-capture-is-refiling)
11845 (let ((bookmark-name (plist-get org-bookmark-names-plist
11846 :last-capture-marker)))
11847 (when bookmark-name
11848 (with-demoted-errors
11849 (bookmark-set bookmark-name))))
11850 (move-marker org-capture-last-stored-marker (point)))
11851 (when (fboundp 'deactivate-mark) (deactivate-mark))
11852 (run-hooks 'org-after-refile-insert-hook)))
11853 (unless org-refile-keep
11854 (if regionp
11855 (delete-region (point) (+ (point) (- region-end region-start)))
11856 (delete-region
11857 (and (org-back-to-heading t) (point))
11858 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11859 (when (featurep 'org-inlinetask)
11860 (org-inlinetask-remove-END-maybe))
11861 (setq org-markers-to-move nil)
11862 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11864 (defun org-refile-goto-last-stored ()
11865 "Go to the location where the last refile was stored."
11866 (interactive)
11867 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11868 (message "This is the location of the last refile"))
11870 (defun org-refile--get-location (refloc tbl)
11871 "When user refile to REFLOC, find the associated target in TBL.
11872 Also check `org-refile-target-table'."
11873 (car (delq
11875 (mapcar
11876 (lambda (r) (or (assoc r tbl)
11877 (assoc r org-refile-target-table)))
11878 (list (replace-regexp-in-string "/$" "" refloc)
11879 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11881 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11882 "Prompt the user for a refile location, using PROMPT.
11883 PROMPT should not be suffixed with a colon and a space, because
11884 this function appends the default value from
11885 `org-refile-history' automatically, if that is not empty."
11886 (let ((org-refile-targets org-refile-targets)
11887 (org-refile-use-outline-path org-refile-use-outline-path))
11888 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11889 (unless org-refile-target-table
11890 (user-error "No refile targets"))
11891 (let* ((cbuf (current-buffer))
11892 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11893 (cfunc (if (and org-refile-use-outline-path
11894 org-outline-path-complete-in-steps)
11895 #'org-olpath-completing-read
11896 #'completing-read))
11897 (extra (if org-refile-use-outline-path "/" ""))
11898 (cbnex (concat (buffer-name) extra))
11899 (filename (and cfn (expand-file-name cfn)))
11900 (tbl (mapcar
11901 (lambda (x)
11902 (if (and (not (member org-refile-use-outline-path
11903 '(file full-file-path)))
11904 (not (equal filename (nth 1 x))))
11905 (cons (concat (car x) extra " ("
11906 (file-name-nondirectory (nth 1 x)) ")")
11907 (cdr x))
11908 (cons (concat (car x) extra) (cdr x))))
11909 org-refile-target-table))
11910 (completion-ignore-case t)
11911 cdef
11912 (prompt (concat prompt
11913 (or (and (car org-refile-history)
11914 (concat " (default " (car org-refile-history) ")"))
11915 (and (assoc cbnex tbl) (setq cdef cbnex)
11916 (concat " (default " cbnex ")"))) ": "))
11917 pa answ parent-target child parent old-hist)
11918 (setq old-hist org-refile-history)
11919 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11920 nil 'org-refile-history (or cdef (car org-refile-history))))
11921 (if (setq pa (org-refile--get-location answ tbl))
11922 (progn
11923 (org-refile-check-position pa)
11924 (when (or (not org-refile-history)
11925 (not (eq old-hist org-refile-history))
11926 (not (equal (car pa) (car org-refile-history))))
11927 (setq org-refile-history
11928 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11929 org-refile-history
11930 (cdr org-refile-history))))
11931 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11932 (pop org-refile-history)))
11934 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11935 (progn
11936 (setq parent (match-string 1 answ)
11937 child (match-string 2 answ))
11938 (setq parent-target (org-refile--get-location parent tbl))
11939 (when (and parent-target
11940 (or (eq new-nodes t)
11941 (and (eq new-nodes 'confirm)
11942 (y-or-n-p (format "Create new node \"%s\"? "
11943 child)))))
11944 (org-refile-new-child parent-target child)))
11945 (user-error "Invalid target location")))))
11947 (declare-function org-string-nw-p "org-macs" (s))
11948 (defun org-refile-check-position (refile-pointer)
11949 "Check if the refile pointer matches the headline to which it points."
11950 (let* ((file (nth 1 refile-pointer))
11951 (re (nth 2 refile-pointer))
11952 (pos (nth 3 refile-pointer))
11953 buffer)
11954 (if (and (not (markerp pos)) (not file))
11955 (user-error "Please indicate a target file in the refile path")
11956 (when (org-string-nw-p re)
11957 (setq buffer (if (markerp pos)
11958 (marker-buffer pos)
11959 (or (find-buffer-visiting file)
11960 (find-file-noselect file))))
11961 (with-current-buffer buffer
11962 (org-with-wide-buffer
11963 (goto-char pos)
11964 (beginning-of-line 1)
11965 (unless (looking-at-p re)
11966 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11968 (defun org-refile-new-child (parent-target child)
11969 "Use refile target PARENT-TARGET to add new CHILD below it."
11970 (unless parent-target
11971 (error "Cannot find parent for new node"))
11972 (let ((file (nth 1 parent-target))
11973 (pos (nth 3 parent-target))
11974 level)
11975 (with-current-buffer (or (find-buffer-visiting file)
11976 (find-file-noselect file))
11977 (org-with-wide-buffer
11978 (if pos
11979 (goto-char pos)
11980 (goto-char (point-max))
11981 (unless (bolp) (newline)))
11982 (when (looking-at org-outline-regexp)
11983 (setq level (funcall outline-level))
11984 (org-end-of-subtree t t))
11985 (org-back-over-empty-lines)
11986 (insert "\n" (make-string
11987 (if pos (org-get-valid-level level 1) 1) ?*)
11988 " " child "\n")
11989 (beginning-of-line 0)
11990 (list (concat (car parent-target) "/" child) file "" (point))))))
11992 (defun org-olpath-completing-read (prompt collection &rest args)
11993 "Read an outline path like a file name."
11994 (let ((thetable collection))
11995 (apply #'completing-read
11996 prompt
11997 (lambda (string predicate &optional flag)
11998 (cond
11999 ((eq flag nil) (try-completion string thetable))
12000 ((eq flag t)
12001 (let ((l (length string)))
12002 (mapcar (lambda (x)
12003 (let ((r (substring x l))
12004 (f (if (string-match " ([^)]*)$" x)
12005 (match-string 0 x)
12006 "")))
12007 (if (string-match "/" r)
12008 (concat string (substring r 0 (match-end 0)) f)
12009 x)))
12010 (all-completions string thetable predicate))))
12011 ;; Exact match?
12012 ((eq flag 'lambda) (assoc string thetable))))
12013 args)))
12015 ;;;; Dynamic blocks
12017 (defun org-find-dblock (name)
12018 "Find the first dynamic block with name NAME in the buffer.
12019 If not found, stay at current position and return nil."
12020 (let ((case-fold-search t) pos)
12021 (save-excursion
12022 (goto-char (point-min))
12023 (setq pos (and (re-search-forward
12024 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12025 (match-beginning 0))))
12026 (when pos (goto-char pos))
12027 pos))
12029 (defun org-create-dblock (plist)
12030 "Create a dynamic block section, with parameters taken from PLIST.
12031 PLIST must contain a :name entry which is used as the name of the block."
12032 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12033 (end-of-line 1)
12034 (newline))
12035 (let ((col (current-column))
12036 (name (plist-get plist :name)))
12037 (insert "#+BEGIN: " name)
12038 (while plist
12039 (if (eq (car plist) :name)
12040 (setq plist (cddr plist))
12041 (insert " " (prin1-to-string (pop plist)))))
12042 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12043 (beginning-of-line -2)))
12045 (defun org-prepare-dblock ()
12046 "Prepare dynamic block for refresh.
12047 This empties the block, puts the cursor at the insert position and returns
12048 the property list including an extra property :name with the block name."
12049 (unless (looking-at org-dblock-start-re)
12050 (user-error "Not at a dynamic block"))
12051 (let* ((begdel (1+ (match-end 0)))
12052 (name (org-no-properties (match-string 1)))
12053 (params (append (list :name name)
12054 (read (concat "(" (match-string 3) ")")))))
12055 (save-excursion
12056 (beginning-of-line 1)
12057 (skip-chars-forward " \t")
12058 (setq params (plist-put params :indentation-column (current-column))))
12059 (unless (re-search-forward org-dblock-end-re nil t)
12060 (error "Dynamic block not terminated"))
12061 (setq params
12062 (append params
12063 (list :content (buffer-substring
12064 begdel (match-beginning 0)))))
12065 (delete-region begdel (match-beginning 0))
12066 (goto-char begdel)
12067 (open-line 1)
12068 params))
12070 (defun org-map-dblocks (&optional command)
12071 "Apply COMMAND to all dynamic blocks in the current buffer.
12072 If COMMAND is not given, use `org-update-dblock'."
12073 (let ((cmd (or command 'org-update-dblock)))
12074 (save-excursion
12075 (goto-char (point-min))
12076 (while (re-search-forward org-dblock-start-re nil t)
12077 (goto-char (match-beginning 0))
12078 (save-excursion
12079 (condition-case nil
12080 (funcall cmd)
12081 (error (message "Error during update of dynamic block"))))
12082 (unless (re-search-forward org-dblock-end-re nil t)
12083 (error "Dynamic block not terminated"))))))
12085 (defun org-dblock-update (&optional arg)
12086 "User command for updating dynamic blocks.
12087 Update the dynamic block at point. With prefix ARG, update all dynamic
12088 blocks in the buffer."
12089 (interactive "P")
12090 (if arg
12091 (org-update-all-dblocks)
12092 (or (looking-at org-dblock-start-re)
12093 (org-beginning-of-dblock))
12094 (org-update-dblock)))
12096 (defun org-update-dblock ()
12097 "Update the dynamic block at point.
12098 This means to empty the block, parse for parameters and then call
12099 the correct writing function."
12100 (interactive)
12101 (save-excursion
12102 (let* ((win (selected-window))
12103 (pos (point))
12104 (line (org-current-line))
12105 (params (org-prepare-dblock))
12106 (name (plist-get params :name))
12107 (indent (plist-get params :indentation-column))
12108 (cmd (intern (concat "org-dblock-write:" name))))
12109 (message "Updating dynamic block `%s' at line %d..." name line)
12110 (funcall cmd params)
12111 (message "Updating dynamic block `%s' at line %d...done" name line)
12112 (goto-char pos)
12113 (when (and indent (> indent 0))
12114 (setq indent (make-string indent ?\ ))
12115 (save-excursion
12116 (select-window win)
12117 (org-beginning-of-dblock)
12118 (forward-line 1)
12119 (while (not (looking-at org-dblock-end-re))
12120 (insert indent)
12121 (beginning-of-line 2))
12122 (when (looking-at org-dblock-end-re)
12123 (and (looking-at "[ \t]+")
12124 (replace-match ""))
12125 (insert indent)))))))
12127 (defun org-beginning-of-dblock ()
12128 "Find the beginning of the dynamic block at point.
12129 Error if there is no such block at point."
12130 (let ((pos (point))
12131 beg)
12132 (end-of-line 1)
12133 (if (and (re-search-backward org-dblock-start-re nil t)
12134 (setq beg (match-beginning 0))
12135 (re-search-forward org-dblock-end-re nil t)
12136 (> (match-end 0) pos))
12137 (goto-char beg)
12138 (goto-char pos)
12139 (error "Not in a dynamic block"))))
12141 (defun org-update-all-dblocks ()
12142 "Update all dynamic blocks in the buffer.
12143 This function can be used in a hook."
12144 (interactive)
12145 (when (derived-mode-p 'org-mode)
12146 (org-map-dblocks 'org-update-dblock)))
12149 ;;;; Completion
12151 (declare-function org-export-backend-options "ox" (cl-x) t)
12152 (defun org-get-export-keywords ()
12153 "Return a list of all currently understood export keywords.
12154 Export keywords include options, block names, attributes and
12155 keywords relative to each registered export back-end."
12156 (let (keywords)
12157 (dolist (backend
12158 (bound-and-true-p org-export-registered-backends)
12159 (delq nil keywords))
12160 ;; Back-end name (for keywords, like #+LATEX:)
12161 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12162 (dolist (option-entry (org-export-backend-options backend))
12163 ;; Back-end options.
12164 (push (nth 1 option-entry) keywords)))))
12166 (defconst org-options-keywords
12167 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12168 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12169 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12170 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12171 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12173 (defcustom org-structure-template-alist
12174 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12175 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12176 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12177 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12178 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12179 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12180 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12181 ("L" "#+LaTeX: ")
12182 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12183 ("H" "#+HTML: ")
12184 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12185 ("A" "#+ASCII: ")
12186 ("i" "#+INDEX: ?")
12187 ("I" "#+INCLUDE: %file ?"))
12188 "Structure completion elements.
12189 This is a list of abbreviation keys and values. The value gets inserted
12190 if you type `<' followed by the key and then press the completion key,
12191 usually `TAB'. %file will be replaced by a file name after prompting
12192 for the file using completion. The cursor will be placed at the position
12193 of the `?' in the template.
12194 There are two templates for each key, the first uses the original Org syntax,
12195 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12196 the default when the /org-mtags.el/ module has been loaded. See also the
12197 variable `org-mtags-prefer-muse-templates'."
12198 :group 'org-completion
12199 :type '(repeat
12200 (list
12201 (string :tag "Key")
12202 (string :tag "Template")))
12203 :version "26.1"
12204 :package-version '(Org . "8.3"))
12206 (defun org-try-structure-completion ()
12207 "Try to complete a structure template before point.
12208 This looks for strings like \"<e\" on an otherwise empty line and
12209 expands them."
12210 (let ((l (buffer-substring (point-at-bol) (point)))
12212 (when (and (looking-at "[ \t]*$")
12213 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12214 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12215 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12216 (match-beginning 1)) a)
12217 t)))
12219 (defun org-complete-expand-structure-template (start cell)
12220 "Expand a structure template."
12221 (let ((rpl (nth 1 cell))
12222 (ind ""))
12223 (delete-region start (point))
12224 (when (string-match "\\`[ \t]*#\\+" rpl)
12225 (cond
12226 ((bolp))
12227 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12228 (setq ind (buffer-substring (point-at-bol) (point))))
12229 (t (newline))))
12230 (setq start (point))
12231 (when (string-match "%file" rpl)
12232 (setq rpl (replace-match
12233 (concat
12234 "\""
12235 (save-match-data
12236 (abbreviate-file-name (read-file-name "Include file: ")))
12237 "\"")
12238 t t rpl)))
12239 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12240 (concat "\n" ind)))
12241 (insert rpl)
12242 (when (re-search-backward "\\?" start t) (delete-char 1))))
12244 ;;;; TODO, DEADLINE, Comments
12246 (defun org-toggle-comment ()
12247 "Change the COMMENT state of an entry."
12248 (interactive)
12249 (save-excursion
12250 (org-back-to-heading)
12251 (let ((case-fold-search nil))
12252 (looking-at org-complex-heading-regexp))
12253 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12254 (skip-chars-forward " \t")
12255 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12256 (if (org-in-commented-heading-p t)
12257 (delete-region (point)
12258 (progn (search-forward " " (line-end-position) 'move)
12259 (skip-chars-forward " \t")
12260 (point)))
12261 (insert org-comment-string)
12262 (unless (eolp) (insert " ")))))
12264 (defvar org-last-todo-state-is-todo nil
12265 "This is non-nil when the last TODO state change led to a TODO state.
12266 If the last change removed the TODO tag or switched to DONE, then
12267 this is nil.")
12269 (defvar org-setting-tags nil) ; dynamically skipped
12271 (defvar org-todo-setup-filter-hook nil
12272 "Hook for functions that pre-filter todo specs.
12273 Each function takes a todo spec and returns either nil or the spec
12274 transformed into canonical form." )
12276 (defvar org-todo-get-default-hook nil
12277 "Hook for functions that get a default item for todo.
12278 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12279 nil or a string to be used for the todo mark." )
12281 (defvar org-agenda-headline-snapshot-before-repeat)
12283 (defun org-current-effective-time ()
12284 "Return current time adjusted for `org-extend-today-until' variable."
12285 (let* ((ct (org-current-time))
12286 (dct (decode-time ct))
12287 (ct1
12288 (cond
12289 (org-use-last-clock-out-time-as-effective-time
12290 (or (org-clock-get-last-clock-out-time) ct))
12291 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12292 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12293 (t ct))))
12294 ct1))
12296 (defun org-todo-yesterday (&optional arg)
12297 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12298 (interactive "P")
12299 (if (eq major-mode 'org-agenda-mode)
12300 (apply 'org-agenda-todo-yesterday arg)
12301 (let* ((org-use-effective-time t)
12302 (hour (nth 2 (decode-time (org-current-time))))
12303 (org-extend-today-until (1+ hour)))
12304 (org-todo arg))))
12306 (defvar org-block-entry-blocking ""
12307 "First entry preventing the TODO state change.")
12309 (defun org-cancel-repeater ()
12310 "Cancel a repeater by setting its numeric value to zero."
12311 (interactive)
12312 (save-excursion
12313 (org-back-to-heading t)
12314 (let ((bound1 (point))
12315 (bound0 (save-excursion (outline-next-heading) (point))))
12316 (when (and (re-search-forward
12317 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12318 org-deadline-time-regexp "\\)\\|\\("
12319 org-ts-regexp "\\)")
12320 bound0 t)
12321 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12322 bound1 t))
12323 (replace-match "0" t nil nil 1)))))
12325 (defvar org-state)
12326 (defvar org-blocked-by-checkboxes)
12327 (defun org-todo (&optional arg)
12328 "Change the TODO state of an item.
12330 The state of an item is given by a keyword at the start of the heading,
12331 like
12332 *** TODO Write paper
12333 *** DONE Call mom
12335 The different keywords are specified in the variable `org-todo-keywords'.
12336 By default the available states are \"TODO\" and \"DONE\". So, for this
12337 example: when the item starts with TODO, it is changed to DONE.
12338 When it starts with DONE, the DONE is removed. And when neither TODO nor
12339 DONE are present, add TODO at the beginning of the heading.
12341 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12342 state.
12343 With numeric prefix ARG, switch to that state.
12344 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12345 next set of TODO \
12346 keywords (nextset).
12347 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12348 prefix, circumvent any state blocking.
12349 With a numeric prefix arg of 0, inhibit note taking for the change.
12350 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12352 When called through ELisp, arg is also interpreted in the following way:
12353 `none' -> empty state
12354 \"\" -> switch to empty state
12355 `done' -> switch to DONE
12356 `nextset' -> switch to the next set of keywords
12357 `previousset' -> switch to the previous set of keywords
12358 \"WAITING\" -> switch to the specified keyword, but only if it
12359 really is a member of `org-todo-keywords'."
12360 (interactive "P")
12361 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12362 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12363 'region-start-level 'region))
12364 org-loop-over-headlines-in-active-region)
12365 (org-map-entries
12366 `(org-todo ,arg)
12367 org-loop-over-headlines-in-active-region
12368 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12369 (when (equal arg '(16)) (setq arg 'nextset))
12370 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12371 (let ((org-blocker-hook org-blocker-hook)
12372 commentp
12373 case-fold-search)
12374 (when (equal arg '(64))
12375 (setq arg nil org-blocker-hook nil))
12376 (when (and org-blocker-hook
12377 (or org-inhibit-blocking
12378 (org-entry-get nil "NOBLOCKING")))
12379 (setq org-blocker-hook nil))
12380 (save-excursion
12381 (catch 'exit
12382 (org-back-to-heading t)
12383 (when (org-in-commented-heading-p t)
12384 (org-toggle-comment)
12385 (setq commentp t))
12386 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12387 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12388 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12389 (let* ((match-data (match-data))
12390 (startpos (point-at-bol))
12391 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12392 (org-log-done org-log-done)
12393 (org-log-repeat org-log-repeat)
12394 (org-todo-log-states org-todo-log-states)
12395 (org-inhibit-logging
12396 (if (equal arg 0)
12397 (progn (setq arg nil) 'note) org-inhibit-logging))
12398 (this (match-string 1))
12399 (hl-pos (match-beginning 0))
12400 (head (org-get-todo-sequence-head this))
12401 (ass (assoc head org-todo-kwd-alist))
12402 (interpret (nth 1 ass))
12403 (done-word (nth 3 ass))
12404 (final-done-word (nth 4 ass))
12405 (org-last-state (or this ""))
12406 (completion-ignore-case t)
12407 (member (member this org-todo-keywords-1))
12408 (tail (cdr member))
12409 (org-state (cond
12410 ((and org-todo-key-trigger
12411 (or (and (equal arg '(4))
12412 (eq org-use-fast-todo-selection 'prefix))
12413 (and (not arg) org-use-fast-todo-selection
12414 (not (eq org-use-fast-todo-selection
12415 'prefix)))))
12416 ;; Use fast selection.
12417 (org-fast-todo-selection))
12418 ((and (equal arg '(4))
12419 (or (not org-use-fast-todo-selection)
12420 (not org-todo-key-trigger)))
12421 ;; Read a state with completion.
12422 (completing-read
12423 "State: " (mapcar #'list org-todo-keywords-1)
12424 nil t))
12425 ((eq arg 'right)
12426 (if this
12427 (if tail (car tail) nil)
12428 (car org-todo-keywords-1)))
12429 ((eq arg 'left)
12430 (unless (equal member org-todo-keywords-1)
12431 (if this
12432 (nth (- (length org-todo-keywords-1)
12433 (length tail) 2)
12434 org-todo-keywords-1)
12435 (org-last org-todo-keywords-1))))
12436 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12437 (setq arg nil))) ;hack to fall back to cycling
12438 (arg
12439 ;; User or caller requests a specific state.
12440 (cond
12441 ((equal arg "") nil)
12442 ((eq arg 'none) nil)
12443 ((eq arg 'done) (or done-word (car org-done-keywords)))
12444 ((eq arg 'nextset)
12445 (or (car (cdr (member head org-todo-heads)))
12446 (car org-todo-heads)))
12447 ((eq arg 'previousset)
12448 (let ((org-todo-heads (reverse org-todo-heads)))
12449 (or (car (cdr (member head org-todo-heads)))
12450 (car org-todo-heads))))
12451 ((car (member arg org-todo-keywords-1)))
12452 ((stringp arg)
12453 (user-error "State `%s' not valid in this file" arg))
12454 ((nth (1- (prefix-numeric-value arg))
12455 org-todo-keywords-1))))
12456 ((null member) (or head (car org-todo-keywords-1)))
12457 ((equal this final-done-word) nil) ;-> make empty
12458 ((null tail) nil) ;-> first entry
12459 ((memq interpret '(type priority))
12460 (if (eq this-command last-command)
12461 (car tail)
12462 (if (> (length tail) 0)
12463 (or done-word (car org-done-keywords))
12464 nil)))
12466 (car tail))))
12467 (org-state (or
12468 (run-hook-with-args-until-success
12469 'org-todo-get-default-hook org-state org-last-state)
12470 org-state))
12471 (next (if org-state (concat " " org-state " ") " "))
12472 (change-plist (list :type 'todo-state-change :from this :to org-state
12473 :position startpos))
12474 dolog now-done-p)
12475 (when org-blocker-hook
12476 (let (org-blocked-by-checkboxes block-reason)
12477 (setq org-last-todo-state-is-todo
12478 (not (member this org-done-keywords)))
12479 (unless (save-excursion
12480 (save-match-data
12481 (org-with-wide-buffer
12482 (run-hook-with-args-until-failure
12483 'org-blocker-hook change-plist))))
12484 (setq block-reason (if org-blocked-by-checkboxes
12485 "contained checkboxes"
12486 (format "\"%s\"" org-block-entry-blocking)))
12487 (if (called-interactively-p 'interactive)
12488 (user-error "TODO state change from %s to %s blocked (by %s)"
12489 this org-state block-reason)
12490 ;; Fail silently.
12491 (message "TODO state change from %s to %s blocked (by %s)"
12492 this org-state block-reason)
12493 (throw 'exit nil)))))
12494 (store-match-data match-data)
12495 (replace-match next t t)
12496 (cond ((equal this org-state)
12497 (message "TODO state was already %s" (org-trim next)))
12498 ((not (pos-visible-in-window-p hl-pos))
12499 (message "TODO state changed to %s" (org-trim next))))
12500 (unless head
12501 (setq head (org-get-todo-sequence-head org-state)
12502 ass (assoc head org-todo-kwd-alist)
12503 interpret (nth 1 ass)
12504 done-word (nth 3 ass)
12505 final-done-word (nth 4 ass)))
12506 (when (memq arg '(nextset previousset))
12507 (message "Keyword-Set %d/%d: %s"
12508 (- (length org-todo-sets) -1
12509 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12510 (length org-todo-sets)
12511 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12512 (setq org-last-todo-state-is-todo
12513 (not (member org-state org-done-keywords)))
12514 (setq now-done-p (and (member org-state org-done-keywords)
12515 (not (member this org-done-keywords))))
12516 (and logging (org-local-logging logging))
12517 (when (and (or org-todo-log-states org-log-done)
12518 (not (eq org-inhibit-logging t))
12519 (not (memq arg '(nextset previousset))))
12520 ;; We need to look at recording a time and note.
12521 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12522 (nth 2 (assoc this org-todo-log-states))))
12523 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12524 (setq dolog 'time))
12525 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12526 (and org-state
12527 (member org-state org-not-done-keywords)
12528 (not (member this org-not-done-keywords))))
12529 ;; This is now a todo state and was not one before
12530 ;; If there was a CLOSED time stamp, get rid of it.
12531 (org-add-planning-info nil nil 'closed))
12532 (when (and now-done-p org-log-done)
12533 ;; It is now done, and it was not done before.
12534 (org-add-planning-info 'closed (org-current-effective-time))
12535 (when (and (not dolog) (eq 'note org-log-done))
12536 (org-add-log-setup 'done org-state this 'note)))
12537 (when (and org-state dolog)
12538 ;; This is a non-nil state, and we need to log it.
12539 (org-add-log-setup 'state org-state this dolog)))
12540 ;; Fixup tag positioning.
12541 (org-todo-trigger-tag-changes org-state)
12542 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12543 (when org-provide-todo-statistics
12544 (org-update-parent-todo-statistics))
12545 (run-hooks 'org-after-todo-state-change-hook)
12546 (when (and arg (not (member org-state org-done-keywords)))
12547 (setq head (org-get-todo-sequence-head org-state)))
12548 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12549 ;; Do we need to trigger a repeat?
12550 (when now-done-p
12551 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12552 ;; This is for the agenda, take a snapshot of the headline.
12553 (save-match-data
12554 (setq org-agenda-headline-snapshot-before-repeat
12555 (org-get-heading))))
12556 (org-auto-repeat-maybe org-state))
12557 ;; Fixup cursor location if close to the keyword.
12558 (when (and (outline-on-heading-p)
12559 (not (bolp))
12560 (save-excursion (beginning-of-line 1)
12561 (looking-at org-todo-line-regexp))
12562 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12563 (goto-char (or (match-end 2) (match-end 1)))
12564 (and (looking-at " ") (just-one-space)))
12565 (when org-trigger-hook
12566 (save-excursion
12567 (run-hook-with-args 'org-trigger-hook change-plist)))
12568 (when commentp (org-toggle-comment))))))))
12570 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12571 "Block turning an entry into a TODO, using the hierarchy.
12572 This checks whether the current task should be blocked from state
12573 changes. Such blocking occurs when:
12575 1. The task has children which are not all in a completed state.
12577 2. A task has a parent with the property :ORDERED:, and there
12578 are siblings prior to the current task with incomplete
12579 status.
12581 3. The parent of the task is blocked because it has siblings that should
12582 be done first, or is child of a block grandparent TODO entry."
12584 (if (not org-enforce-todo-dependencies)
12585 t ; if locally turned off don't block
12586 (catch 'dont-block
12587 ;; If this is not a todo state change, or if this entry is already DONE,
12588 ;; do not block
12589 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12590 (member (plist-get change-plist :from)
12591 (cons 'done org-done-keywords))
12592 (member (plist-get change-plist :to)
12593 (cons 'todo org-not-done-keywords))
12594 (not (plist-get change-plist :to)))
12595 (throw 'dont-block t))
12596 ;; If this task has children, and any are undone, it's blocked
12597 (save-excursion
12598 (org-back-to-heading t)
12599 (let ((this-level (funcall outline-level)))
12600 (outline-next-heading)
12601 (let ((child-level (funcall outline-level)))
12602 (while (and (not (eobp))
12603 (> child-level this-level))
12604 ;; this todo has children, check whether they are all
12605 ;; completed
12606 (when (and (not (org-entry-is-done-p))
12607 (org-entry-is-todo-p))
12608 (setq org-block-entry-blocking (org-get-heading))
12609 (throw 'dont-block nil))
12610 (outline-next-heading)
12611 (setq child-level (funcall outline-level))))))
12612 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12613 ;; any previous siblings are undone, it's blocked
12614 (save-excursion
12615 (org-back-to-heading t)
12616 (let* ((pos (point))
12617 (parent-pos (and (org-up-heading-safe) (point)))
12618 (case-fold-search nil))
12619 (unless parent-pos (throw 'dont-block t)) ; no parent
12620 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12621 (forward-line 1)
12622 (re-search-forward org-not-done-heading-regexp pos t))
12623 (setq org-block-entry-blocking (match-string 0))
12624 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12625 ;; Search further up the hierarchy, to see if an ancestor is blocked
12626 (while t
12627 (goto-char parent-pos)
12628 (unless (looking-at org-not-done-heading-regexp)
12629 (throw 'dont-block t)) ; do not block, parent is not a TODO
12630 (setq pos (point))
12631 (setq parent-pos (and (org-up-heading-safe) (point)))
12632 (unless parent-pos (throw 'dont-block t)) ; no parent
12633 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12634 (forward-line 1)
12635 (re-search-forward org-not-done-heading-regexp pos t)
12636 (setq org-block-entry-blocking (org-get-heading)))
12637 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12639 (defcustom org-track-ordered-property-with-tag nil
12640 "Should the ORDERED property also be shown as a tag?
12641 The ORDERED property decides if an entry should require subtasks to be
12642 completed in sequence. Since a property is not very visible, setting
12643 this option means that toggling the ORDERED property with the command
12644 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12645 not relevant for the behavior, but it makes things more visible.
12647 Note that toggling the tag with tags commands will not change the property
12648 and therefore not influence behavior!
12650 This can be t, meaning the tag ORDERED should be used, It can also be a
12651 string to select a different tag for this task."
12652 :group 'org-todo
12653 :type '(choice
12654 (const :tag "No tracking" nil)
12655 (const :tag "Track with ORDERED tag" t)
12656 (string :tag "Use other tag")))
12658 (defun org-toggle-ordered-property ()
12659 "Toggle the ORDERED property of the current entry.
12660 For better visibility, you can track the value of this property with a tag.
12661 See variable `org-track-ordered-property-with-tag'."
12662 (interactive)
12663 (let* ((t1 org-track-ordered-property-with-tag)
12664 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12665 (save-excursion
12666 (org-back-to-heading)
12667 (if (org-entry-get nil "ORDERED")
12668 (progn
12669 (org-delete-property "ORDERED")
12670 (and tag (org-toggle-tag tag 'off))
12671 (message "Subtasks can be completed in arbitrary order"))
12672 (org-entry-put nil "ORDERED" "t")
12673 (and tag (org-toggle-tag tag 'on))
12674 (message "Subtasks must be completed in sequence")))))
12676 (defun org-block-todo-from-checkboxes (change-plist)
12677 "Block turning an entry into a TODO, using checkboxes.
12678 This checks whether the current task should be blocked from state
12679 changes because there are unchecked boxes in this entry."
12680 (if (not org-enforce-todo-checkbox-dependencies)
12681 t ; if locally turned off don't block
12682 (catch 'dont-block
12683 ;; If this is not a todo state change, or if this entry is already DONE,
12684 ;; do not block
12685 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12686 (member (plist-get change-plist :from)
12687 (cons 'done org-done-keywords))
12688 (member (plist-get change-plist :to)
12689 (cons 'todo org-not-done-keywords))
12690 (not (plist-get change-plist :to)))
12691 (throw 'dont-block t))
12692 ;; If this task has checkboxes that are not checked, it's blocked
12693 (save-excursion
12694 (org-back-to-heading t)
12695 (let ((beg (point)) end)
12696 (outline-next-heading)
12697 (setq end (point))
12698 (goto-char beg)
12699 (when (org-list-search-forward
12700 (concat (org-item-beginning-re)
12701 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12702 "\\[[- ]\\]")
12703 end t)
12704 (when (boundp 'org-blocked-by-checkboxes)
12705 (setq org-blocked-by-checkboxes t))
12706 (throw 'dont-block nil))))
12707 t))) ; do not block
12709 (defun org-entry-blocked-p ()
12710 "Non-nil if entry at point is blocked."
12711 (and (not (org-entry-get nil "NOBLOCKING"))
12712 (member (org-entry-get nil "TODO") org-not-done-keywords)
12713 (not (run-hook-with-args-until-failure
12714 'org-blocker-hook
12715 (list :type 'todo-state-change
12716 :position (point)
12717 :from 'todo
12718 :to 'done)))))
12720 (defun org-update-statistics-cookies (all)
12721 "Update the statistics cookie, either from TODO or from checkboxes.
12722 This should be called with the cursor in a line with a statistics
12723 cookie. When called with a \\[universal-argument] prefix, update
12724 all statistics cookies in the buffer."
12725 (interactive "P")
12726 (if all
12727 (progn
12728 (org-update-checkbox-count 'all)
12729 (org-map-entries 'org-update-parent-todo-statistics))
12730 (if (not (org-at-heading-p))
12731 (org-update-checkbox-count)
12732 (let ((pos (point-marker))
12733 end l1 l2)
12734 (ignore-errors (org-back-to-heading t))
12735 (if (not (org-at-heading-p))
12736 (org-update-checkbox-count)
12737 (setq l1 (org-outline-level))
12738 (setq end (save-excursion
12739 (outline-next-heading)
12740 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12741 (point)))
12742 (if (and (save-excursion
12743 (re-search-forward
12744 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12745 (not (save-excursion (re-search-forward
12746 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12747 (org-update-checkbox-count)
12748 (if (and l2 (> l2 l1))
12749 (progn
12750 (goto-char end)
12751 (org-update-parent-todo-statistics))
12752 (goto-char pos)
12753 (beginning-of-line 1)
12754 (while (re-search-forward
12755 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12756 (point-at-eol) t)
12757 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12758 (goto-char pos)
12759 (move-marker pos nil)))))
12761 (defvar org-entry-property-inherited-from) ;; defined below
12762 (defun org-update-parent-todo-statistics ()
12763 "Update any statistics cookie in the parent of the current headline.
12764 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12765 the entire subtree and this will travel up the hierarchy and update
12766 statistics everywhere."
12767 (let* ((prop (save-excursion (org-up-heading-safe)
12768 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12769 (recursive (or (not org-hierarchical-todo-statistics)
12770 (and prop (string-match "\\<recursive\\>" prop))))
12771 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12773 (first t)
12774 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12775 level ltoggle l1 new ndel
12776 (cnt-all 0) (cnt-done 0) is-percent kwd
12777 checkbox-beg cookie-present)
12778 (catch 'exit
12779 (save-excursion
12780 (beginning-of-line 1)
12781 (setq ltoggle (funcall outline-level))
12782 ;; Three situations are to consider:
12784 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12785 ;; to the top-level ancestor on the headline;
12787 ;; 2. If parent has "recursive" property, repeat up to the
12788 ;; headline setting that property, taking inheritance into
12789 ;; account;
12791 ;; 3. Else, move up to direct parent and proceed only once.
12792 (while (and (setq level (org-up-heading-safe))
12793 (or recursive first)
12794 (>= (point) lim))
12795 (setq first nil cookie-present nil)
12796 (unless (and level
12797 (not (string-match
12798 "\\<checkbox\\>"
12799 (downcase (or (org-entry-get nil "COOKIE_DATA")
12800 "")))))
12801 (throw 'exit nil))
12802 (while (re-search-forward box-re (point-at-eol) t)
12803 (setq cnt-all 0 cnt-done 0 cookie-present t)
12804 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12805 (save-match-data
12806 (unless (outline-next-heading) (throw 'exit nil))
12807 (while (and (looking-at org-complex-heading-regexp)
12808 (> (setq l1 (length (match-string 1))) level))
12809 (setq kwd (and (or recursive (= l1 ltoggle))
12810 (match-string 2)))
12811 (if (or (eq org-provide-todo-statistics 'all-headlines)
12812 (and (eq org-provide-todo-statistics t)
12813 (or (member kwd org-done-keywords)))
12814 (and (listp org-provide-todo-statistics)
12815 (stringp (car org-provide-todo-statistics))
12816 (or (member kwd org-provide-todo-statistics)
12817 (member kwd org-done-keywords)))
12818 (and (listp org-provide-todo-statistics)
12819 (listp (car org-provide-todo-statistics))
12820 (or (member kwd (car org-provide-todo-statistics))
12821 (and (member kwd org-done-keywords)
12822 (member kwd (cadr org-provide-todo-statistics))))))
12823 (setq cnt-all (1+ cnt-all))
12824 (and (eq org-provide-todo-statistics t)
12826 (setq cnt-all (1+ cnt-all))))
12827 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12828 (member kwd org-done-keywords))
12829 (and (listp org-provide-todo-statistics)
12830 (listp (car org-provide-todo-statistics))
12831 (member kwd org-done-keywords)
12832 (member kwd (cadr org-provide-todo-statistics)))
12833 (and (listp org-provide-todo-statistics)
12834 (stringp (car org-provide-todo-statistics))
12835 (member kwd org-done-keywords)))
12836 (setq cnt-done (1+ cnt-done)))
12837 (outline-next-heading)))
12838 (setq new
12839 (if is-percent
12840 (format "[%d%%]" (floor (* 100.0 cnt-done)
12841 (max 1 cnt-all)))
12842 (format "[%d/%d]" cnt-done cnt-all))
12843 ndel (- (match-end 0) checkbox-beg))
12844 (goto-char checkbox-beg)
12845 (insert new)
12846 (delete-region (point) (+ (point) ndel))
12847 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12848 (when cookie-present
12849 (run-hook-with-args 'org-after-todo-statistics-hook
12850 cnt-done (- cnt-all cnt-done))))))
12851 (run-hooks 'org-todo-statistics-hook)))
12853 (defvar org-after-todo-statistics-hook nil
12854 "Hook that is called after a TODO statistics cookie has been updated.
12855 Each function is called with two arguments: the number of not-done entries
12856 and the number of done entries.
12858 For example, the following function, when added to this hook, will switch
12859 an entry to DONE when all children are done, and back to TODO when new
12860 entries are set to a TODO status. Note that this hook is only called
12861 when there is a statistics cookie in the headline!
12863 (defun org-summary-todo (n-done n-not-done)
12864 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12865 (let (org-log-done org-log-states) ; turn off logging
12866 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12869 (defvar org-todo-statistics-hook nil
12870 "Hook that is run whenever Org thinks TODO statistics should be updated.
12871 This hook runs even if there is no statistics cookie present, in which case
12872 `org-after-todo-statistics-hook' would not run.")
12874 (defun org-todo-trigger-tag-changes (state)
12875 "Apply the changes defined in `org-todo-state-tags-triggers'."
12876 (let ((l org-todo-state-tags-triggers)
12877 changes)
12878 (when (or (not state) (equal state ""))
12879 (setq changes (append changes (cdr (assoc "" l)))))
12880 (when (and (stringp state) (> (length state) 0))
12881 (setq changes (append changes (cdr (assoc state l)))))
12882 (when (member state org-not-done-keywords)
12883 (setq changes (append changes (cdr (assq 'todo l)))))
12884 (when (member state org-done-keywords)
12885 (setq changes (append changes (cdr (assq 'done l)))))
12886 (dolist (c changes)
12887 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12889 (defun org-local-logging (value)
12890 "Get logging settings from a property VALUE."
12891 ;; Directly set the variables, they are already local.
12892 (setq org-log-done nil
12893 org-log-repeat nil
12894 org-todo-log-states nil)
12895 (dolist (w (org-split-string value))
12896 (let (a)
12897 (cond
12898 ((setq a (assoc w org-startup-options))
12899 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12900 (set (nth 1 a) (nth 2 a))))
12901 ((setq a (org-extract-log-state-settings w))
12902 (and (member (car a) org-todo-keywords-1)
12903 (push a org-todo-log-states)))))))
12905 (defun org-get-todo-sequence-head (kwd)
12906 "Return the head of the TODO sequence to which KWD belongs.
12907 If KWD is not set, check if there is a text property remembering the
12908 right sequence."
12909 (let (p)
12910 (cond
12911 ((not kwd)
12912 (or (get-text-property (point-at-bol) 'org-todo-head)
12913 (progn
12914 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12915 nil (point-at-eol)))
12916 (get-text-property p 'org-todo-head))))
12917 ((not (member kwd org-todo-keywords-1))
12918 (car org-todo-keywords-1))
12919 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12921 (defun org-fast-todo-selection ()
12922 "Fast TODO keyword selection with single keys.
12923 Returns the new TODO keyword, or nil if no state change should occur."
12924 (let* ((fulltable org-todo-key-alist)
12925 (done-keywords org-done-keywords) ;; needed for the faces.
12926 (maxlen (apply 'max (mapcar
12927 (lambda (x)
12928 (if (stringp (car x)) (string-width (car x)) 0))
12929 fulltable)))
12930 (expert nil)
12931 (fwidth (+ maxlen 3 1 3))
12932 (ncol (/ (- (window-width) 4) fwidth))
12933 tg cnt e c tbl
12934 groups ingroup)
12935 (save-excursion
12936 (save-window-excursion
12937 (if expert
12938 (set-buffer (get-buffer-create " *Org todo*"))
12939 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12940 (erase-buffer)
12941 (setq-local org-done-keywords done-keywords)
12942 (setq tbl fulltable cnt 0)
12943 (while (setq e (pop tbl))
12944 (cond
12945 ((equal e '(:startgroup))
12946 (push '() groups) (setq ingroup t)
12947 (unless (= cnt 0)
12948 (setq cnt 0)
12949 (insert "\n"))
12950 (insert "{ "))
12951 ((equal e '(:endgroup))
12952 (setq ingroup nil cnt 0)
12953 (insert "}\n"))
12954 ((equal e '(:newline))
12955 (unless (= cnt 0)
12956 (setq cnt 0)
12957 (insert "\n")
12958 (setq e (car tbl))
12959 (while (equal (car tbl) '(:newline))
12960 (insert "\n")
12961 (setq tbl (cdr tbl)))))
12963 (setq tg (car e) c (cdr e))
12964 (when ingroup (push tg (car groups)))
12965 (setq tg (org-add-props tg nil 'face
12966 (org-get-todo-face tg)))
12967 (when (and (= cnt 0) (not ingroup)) (insert " "))
12968 (insert "[" c "] " tg (make-string
12969 (- fwidth 4 (length tg)) ?\ ))
12970 (when (= (setq cnt (1+ cnt)) ncol)
12971 (insert "\n")
12972 (when ingroup (insert " "))
12973 (setq cnt 0)))))
12974 (insert "\n")
12975 (goto-char (point-min))
12976 (unless expert (org-fit-window-to-buffer))
12977 (message "[a-z..]:Set [SPC]:clear")
12978 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12979 (cond
12980 ((or (= c ?\C-g)
12981 (and (= c ?q) (not (rassoc c fulltable))))
12982 (setq quit-flag t))
12983 ((= c ?\ ) nil)
12984 ((setq e (rassoc c fulltable) tg (car e))
12986 (t (setq quit-flag t)))))))
12988 (defun org-entry-is-todo-p ()
12989 (member (org-get-todo-state) org-not-done-keywords))
12991 (defun org-entry-is-done-p ()
12992 (member (org-get-todo-state) org-done-keywords))
12994 (defun org-get-todo-state ()
12995 "Return the TODO keyword of the current subtree."
12996 (save-excursion
12997 (org-back-to-heading t)
12998 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12999 (match-end 2)
13000 (match-string 2))))
13002 (defun org-at-date-range-p (&optional inactive-ok)
13003 "Non-nil if point is inside a date range.
13005 When optional argument INACTIVE-OK is non-nil, also consider
13006 inactive time ranges.
13008 When this function returns a non-nil value, match data is set
13009 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13010 on INACTIVE-OK."
13011 (interactive)
13012 (save-excursion
13013 (catch 'exit
13014 (let ((pos (point)))
13015 (skip-chars-backward "^[<\r\n")
13016 (skip-chars-backward "<[")
13017 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13018 (>= (match-end 0) pos)
13019 (throw 'exit t))
13020 (skip-chars-backward "^<[\r\n")
13021 (skip-chars-backward "<[")
13022 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13023 (>= (match-end 0) pos)
13024 (throw 'exit t)))
13025 nil)))
13027 (defun org-get-repeat (&optional timestamp)
13028 "Check if there is a time-stamp with repeater in this entry.
13030 Return the repeater, as a string, or nil. Also return nil when
13031 this function is called before first heading.
13033 When optional argument TIMESTAMP is a string, extract the
13034 repeater from there instead."
13035 (save-match-data
13036 (cond (timestamp
13037 (and (string-match org-repeat-re timestamp)
13038 (match-string-no-properties 1 timestamp)))
13039 ((org-before-first-heading-p) nil)
13041 (save-excursion
13042 (org-back-to-heading t)
13043 (let ((end (org-entry-end-position)))
13044 (catch :repeat
13045 (while (re-search-forward org-repeat-re end t)
13046 (when (save-match-data (org-at-timestamp-p 'agenda))
13047 (throw :repeat (match-string-no-properties 1)))))))))))
13049 (defvar org-last-changed-timestamp)
13050 (defvar org-last-inserted-timestamp)
13051 (defvar org-log-post-message)
13052 (defvar org-log-note-purpose)
13053 (defvar org-log-note-how nil)
13054 (defvar org-log-note-extra)
13055 (defun org-auto-repeat-maybe (done-word)
13056 "Check if the current headline contains a repeated time-stamp.
13058 If yes, set TODO state back to what it was and change the base date
13059 of repeating deadline/scheduled time stamps to new date.
13061 This function is run automatically after each state change to a DONE state."
13062 (let* ((repeat (org-get-repeat))
13063 (aa (assoc org-last-state org-todo-kwd-alist))
13064 (interpret (nth 1 aa))
13065 (head (nth 2 aa))
13066 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13067 (msg "Entry repeats: ")
13068 (org-log-done nil)
13069 (org-todo-log-states nil)
13070 (end (copy-marker (org-entry-end-position))))
13071 (unwind-protect
13072 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13073 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13074 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13075 org-todo-repeat-to-state)))
13076 (org-todo (cond
13077 ((and to-state (member to-state org-todo-keywords-1))
13078 to-state)
13079 ((eq interpret 'type) org-last-state)
13080 (head)
13081 (t 'none))))
13082 (org-back-to-heading t)
13083 (org-add-planning-info nil nil 'closed)
13084 ;; When `org-log-repeat' is non-nil or entry contains
13085 ;; a clock, set LAST_REPEAT property.
13086 (when (or org-log-repeat
13087 (catch :clock
13088 (while (re-search-forward org-clock-line-re end t)
13089 (when (org-at-clock-log-p) (throw :clock t)))))
13090 (org-entry-put nil "LAST_REPEAT" (format-time-string
13091 (org-time-stamp-format t t)
13092 (current-time))))
13093 (when org-log-repeat
13094 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13095 (memq 'org-add-log-note post-command-hook))
13096 ;; We are already setup for some record.
13097 (when (eq org-log-repeat 'note)
13098 ;; Make sure we take a note, not only a time stamp.
13099 (setq org-log-note-how 'note))
13100 ;; Set up for taking a record.
13101 (org-add-log-setup 'state
13102 (or done-word (car org-done-keywords))
13103 org-last-state
13104 org-log-repeat)))
13105 (let ((planning-re (regexp-opt
13106 (list org-scheduled-string org-deadline-string))))
13107 (while (re-search-forward org-ts-regexp end t)
13108 (let* ((ts (match-string 0))
13109 (planning? (org-at-planning-p))
13110 (type (if (not planning?) "Plain:"
13111 (save-excursion
13112 (re-search-backward
13113 planning-re (line-beginning-position) t)
13114 (match-string 0)))))
13115 (cond
13116 ;; Ignore fake time-stamps (e.g., within comments).
13117 ((not (org-at-timestamp-p 'agenda)))
13118 ;; Time-stamps without a repeater are usually
13119 ;; skipped. However, a SCHEDULED time-stamp without
13120 ;; one is removed, as they are no longer relevant.
13121 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13122 ts))
13123 (when (equal type org-scheduled-string)
13124 (org-remove-timestamp-with-keyword type)))
13126 (let ((n (string-to-number (match-string 2 ts)))
13127 (what (match-string 3 ts)))
13128 (when (equal what "w") (setq n (* n 7) what "d"))
13129 (when (and (equal what "h")
13130 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13131 ts)))
13132 (user-error
13133 "Cannot repeat in Repeat in %d hour(s) because no hour \
13134 has been set"
13136 ;; Preparation, see if we need to modify the start
13137 ;; date for the change.
13138 (when (match-end 1)
13139 (let ((time (save-match-data
13140 (org-time-string-to-time ts))))
13141 (cond
13142 ((equal (match-string 1 ts) ".")
13143 ;; Shift starting date to today
13144 (org-timestamp-change
13145 (- (org-today) (time-to-days time))
13146 'day))
13147 ((equal (match-string 1 ts) "+")
13148 (let ((nshiftmax 10)
13149 (nshift 0))
13150 (while (or (= nshift 0)
13151 (not (time-less-p (current-time) time)))
13152 (when (= (cl-incf nshift) nshiftmax)
13153 (or (y-or-n-p
13154 (format "%d repeater intervals were not \
13155 enough to shift date past today. Continue? "
13156 nshift))
13157 (user-error "Abort")))
13158 (org-timestamp-change n (cdr (assoc what whata)))
13159 (org-in-regexp org-ts-regexp3)
13160 (setq ts (match-string 1))
13161 (setq time
13162 (save-match-data
13163 (org-time-string-to-time ts)))))
13164 (org-timestamp-change (- n) (cdr (assoc what whata)))
13165 ;; Rematch, so that we have everything in place
13166 ;; for the real shift.
13167 (org-in-regexp org-ts-regexp3)
13168 (setq ts (match-string 1))
13169 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13170 ts)))))
13171 (save-excursion
13172 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13173 (setq msg
13174 (concat
13175 msg type " " org-last-changed-timestamp " "))))))))
13176 (setq org-log-post-message msg)
13177 (message "%s" msg))
13178 (set-marker end nil))))
13180 (defun org-show-todo-tree (arg)
13181 "Make a compact tree which shows all headlines marked with TODO.
13182 The tree will show the lines where the regexp matches, and all higher
13183 headlines above the match.
13184 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13185 With a numeric prefix N, construct a sparse tree for the Nth element
13186 of `org-todo-keywords-1'."
13187 (interactive "P")
13188 (let ((case-fold-search nil)
13189 (kwd-re
13190 (cond ((null arg) org-not-done-regexp)
13191 ((equal arg '(4))
13192 (let ((kwd
13193 (completing-read "Keyword (or KWD1|KWD2|...): "
13194 (mapcar #'list org-todo-keywords-1))))
13195 (concat "\\("
13196 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13197 "\\)\\>")))
13198 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13199 (regexp-quote (nth (1- (prefix-numeric-value arg))
13200 org-todo-keywords-1)))
13201 (t (user-error "Invalid prefix argument: %s" arg)))))
13202 (message "%d TODO entries found"
13203 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13205 (defun org--deadline-or-schedule (arg type time)
13206 "Insert DEADLINE or SCHEDULE information in current entry.
13207 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13208 `org-schedule' for information about ARG and TIME arguments."
13209 (let* ((deadline? (eq type 'deadline))
13210 (keyword (if deadline? org-deadline-string org-scheduled-string))
13211 (log (if deadline? org-log-redeadline org-log-reschedule))
13212 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13213 (old-date-time (and old-date (org-time-string-to-time old-date)))
13214 ;; Save repeater cookie from either TIME or current scheduled
13215 ;; time stamp. We are going to insert it back at the end of
13216 ;; the process.
13217 (repeater (or (and (org-string-nw-p time)
13218 ;; We use `org-repeat-re' because we need
13219 ;; to tell the difference between a real
13220 ;; repeater and a time delta, e.g. "+2d".
13221 (string-match org-repeat-re time)
13222 (match-string 1 time))
13223 (and (org-string-nw-p old-date)
13224 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13225 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13226 old-date)
13227 (match-string 1 old-date)))))
13228 (pcase arg
13229 (`(4)
13230 (when (and old-date log)
13231 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13232 nil old-date log))
13233 (org-remove-timestamp-with-keyword keyword)
13234 (message (if deadline? "Item no longer has a deadline."
13235 "Item is no longer scheduled.")))
13236 (`(16)
13237 (save-excursion
13238 (org-back-to-heading t)
13239 (let ((regexp (if deadline? org-deadline-time-regexp
13240 org-scheduled-time-regexp)))
13241 (if (not (re-search-forward regexp (line-end-position 2) t))
13242 (user-error (if deadline? "No deadline information to update"
13243 "No scheduled information to update"))
13244 (let* ((rpl0 (match-string 1))
13245 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13246 (msg (if deadline? "Warn starting from" "Delay until")))
13247 (replace-match
13248 (concat keyword
13249 " <" rpl
13250 (format " -%dd"
13251 (abs (- (time-to-days
13252 (save-match-data
13253 (org-read-date
13254 nil t nil msg old-date-time)))
13255 (time-to-days old-date-time))))
13256 ">") t t))))))
13258 (org-add-planning-info type time 'closed)
13259 (when (and old-date
13261 (not (equal old-date org-last-inserted-timestamp)))
13262 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13263 org-last-inserted-timestamp
13264 old-date
13265 log))
13266 (when repeater
13267 (save-excursion
13268 (org-back-to-heading t)
13269 (when (re-search-forward
13270 (concat keyword " " org-last-inserted-timestamp)
13271 (line-end-position 2)
13273 (goto-char (1- (match-end 0)))
13274 (insert " " repeater)
13275 (setq org-last-inserted-timestamp
13276 (concat (substring org-last-inserted-timestamp 0 -1)
13277 " " repeater
13278 (substring org-last-inserted-timestamp -1))))))
13279 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13280 org-last-inserted-timestamp)))))
13282 (defun org-deadline (arg &optional time)
13283 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13284 With one universal prefix argument, remove any deadline from the item.
13285 With two universal prefix arguments, prompt for a warning delay.
13286 With argument TIME, set the deadline at the corresponding date. TIME
13287 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13288 (interactive "P")
13289 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13290 (org-map-entries
13291 (lambda () (org--deadline-or-schedule arg 'deadline time))
13293 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13294 'region-start-level
13295 'region)
13296 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13297 (org--deadline-or-schedule arg 'deadline time)))
13299 (defun org-schedule (arg &optional time)
13300 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13301 With one universal prefix argument, remove any scheduling date from the item.
13302 With two universal prefix arguments, prompt for a delay cookie.
13303 With argument TIME, scheduled at the corresponding date. TIME can
13304 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13305 (interactive "P")
13306 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13307 (org-map-entries
13308 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13310 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13311 'region-start-level
13312 'region)
13313 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13314 (org--deadline-or-schedule arg 'scheduled time)))
13316 (defun org-get-scheduled-time (pom &optional inherit)
13317 "Get the scheduled time as a time tuple, of a format suitable
13318 for calling org-schedule with, or if there is no scheduling,
13319 returns nil."
13320 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13321 (when time
13322 (apply 'encode-time (org-parse-time-string time)))))
13324 (defun org-get-deadline-time (pom &optional inherit)
13325 "Get the deadline as a time tuple, of a format suitable for
13326 calling org-deadline with, or if there is no scheduling, returns
13327 nil."
13328 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13329 (when time
13330 (apply 'encode-time (org-parse-time-string time)))))
13332 (defun org-remove-timestamp-with-keyword (keyword)
13333 "Remove all time stamps with KEYWORD in the current entry."
13334 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13335 beg)
13336 (save-excursion
13337 (org-back-to-heading t)
13338 (setq beg (point))
13339 (outline-next-heading)
13340 (while (re-search-backward re beg t)
13341 (replace-match "")
13342 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13343 (equal (char-before) ?\ ))
13344 (backward-delete-char 1)
13345 (when (string-match "^[ \t]*$" (buffer-substring
13346 (point-at-bol) (point-at-eol)))
13347 (delete-region (point-at-bol)
13348 (min (point-max) (1+ (point-at-eol))))))))))
13350 (defvar org-time-was-given) ; dynamically scoped parameter
13351 (defvar org-end-time-was-given) ; dynamically scoped parameter
13353 (defun org-at-planning-p ()
13354 "Non-nil when point is on a planning info line."
13355 ;; This is as accurate and faster than `org-element-at-point' since
13356 ;; planning info location is fixed in the section.
13357 (org-with-wide-buffer
13358 (beginning-of-line)
13359 (and (looking-at-p org-planning-line-re)
13360 (eq (point)
13361 (ignore-errors
13362 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13363 (org-back-to-heading t)
13364 (org-with-limited-levels (org-back-to-heading t)))
13365 (line-beginning-position 2))))))
13367 (defun org-add-planning-info (what &optional time &rest remove)
13368 "Insert new timestamp with keyword in the planning line.
13369 WHAT indicates what kind of time stamp to add. It is a symbol
13370 among `closed', `deadline', `scheduled' and nil. TIME indicates
13371 the time to use. If none is given, the user is prompted for
13372 a date. REMOVE indicates what kind of entries to remove. An old
13373 WHAT entry will also be removed."
13374 (let (org-time-was-given org-end-time-was-given default-time default-input)
13375 (catch 'exit
13376 (when (and (memq what '(scheduled deadline))
13377 (or (not time)
13378 (and (stringp time)
13379 (string-match "^[-+]+[0-9]" time))))
13380 ;; Try to get a default date/time from existing timestamp
13381 (save-excursion
13382 (org-back-to-heading t)
13383 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13384 (when (re-search-forward (if (eq what 'scheduled)
13385 org-scheduled-time-regexp
13386 org-deadline-time-regexp)
13387 end t)
13388 (setq ts (match-string 1)
13389 default-time (apply 'encode-time (org-parse-time-string ts))
13390 default-input (and ts (org-get-compact-tod ts)))))))
13391 (when what
13392 (setq time
13393 (if (stringp time)
13394 ;; This is a string (relative or absolute), set
13395 ;; proper date.
13396 (apply #'encode-time
13397 (org-read-date-analyze
13398 time default-time (decode-time default-time)))
13399 ;; If necessary, get the time from the user
13400 (or time (org-read-date nil 'to-time nil nil
13401 default-time default-input)))))
13403 (org-with-wide-buffer
13404 (org-back-to-heading t)
13405 (forward-line)
13406 (unless (bolp) (insert "\n"))
13407 (cond ((looking-at-p org-planning-line-re)
13408 ;; Move to current indentation.
13409 (skip-chars-forward " \t")
13410 ;; Check if we have to remove something.
13411 (dolist (type (if what (cons what remove) remove))
13412 (save-excursion
13413 (when (re-search-forward
13414 (cl-case type
13415 (closed org-closed-time-regexp)
13416 (deadline org-deadline-time-regexp)
13417 (scheduled org-scheduled-time-regexp)
13418 (otherwise
13419 (error "Invalid planning type: %s" type)))
13420 (line-end-position) t)
13421 ;; Delete until next keyword or end of line.
13422 (delete-region
13423 (match-beginning 0)
13424 (if (re-search-forward org-keyword-time-not-clock-regexp
13425 (line-end-position)
13427 (match-beginning 0)
13428 (line-end-position))))))
13429 ;; If there is nothing more to add and no more keyword
13430 ;; is left, remove the line completely.
13431 (if (and (looking-at-p "[ \t]*$") (not what))
13432 (delete-region (line-beginning-position)
13433 (line-beginning-position 2))
13434 ;; If we removed last keyword, do not leave trailing
13435 ;; white space at the end of line.
13436 (let ((p (point)))
13437 (save-excursion
13438 (end-of-line)
13439 (unless (= (skip-chars-backward " \t" p) 0)
13440 (delete-region (point) (line-end-position)))))))
13441 ((not what) (throw 'exit nil)) ; Nothing to do.
13442 (t (insert-before-markers "\n")
13443 (backward-char 1)
13444 (when org-adapt-indentation
13445 (indent-to-column (1+ (org-outline-level))))))
13446 (when what
13447 ;; Insert planning keyword.
13448 (insert (cl-case what
13449 (closed org-closed-string)
13450 (deadline org-deadline-string)
13451 (scheduled org-scheduled-string)
13452 (otherwise (error "Invalid planning type: %s" what)))
13453 " ")
13454 ;; Insert associated timestamp.
13455 (let ((ts (org-insert-time-stamp
13456 time
13457 (or org-time-was-given
13458 (and (eq what 'closed) org-log-done-with-time))
13459 (eq what 'closed)
13460 nil nil (list org-end-time-was-given))))
13461 (unless (eolp) (insert " "))
13462 ts))))))
13464 (defvar org-log-note-marker (make-marker)
13465 "Marker pointing at the entry where the note is to be inserted.")
13466 (defvar org-log-note-purpose nil)
13467 (defvar org-log-note-state nil)
13468 (defvar org-log-note-previous-state nil)
13469 (defvar org-log-note-extra nil)
13470 (defvar org-log-note-window-configuration nil)
13471 (defvar org-log-note-return-to (make-marker))
13472 (defvar org-log-note-effective-time nil
13473 "Remembered current time so that dynamically scoped
13474 `org-extend-today-until' affects timestamps in state change log")
13476 (defvar org-log-post-message nil
13477 "Message to be displayed after a log note has been stored.
13478 The auto-repeater uses this.")
13480 (defun org-add-note ()
13481 "Add a note to the current entry.
13482 This is done in the same way as adding a state change note."
13483 (interactive)
13484 (org-add-log-setup 'note))
13486 (defun org-log-beginning (&optional create)
13487 "Return expected start of log notes in current entry.
13488 When optional argument CREATE is non-nil, the function creates
13489 a drawer to store notes, if necessary. Returned position ignores
13490 narrowing."
13491 (org-with-wide-buffer
13492 (let ((drawer (org-log-into-drawer)))
13493 (cond
13494 (drawer
13495 (org-end-of-meta-data)
13496 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13497 (end (if (org-at-heading-p) (point)
13498 (save-excursion (outline-next-heading) (point))))
13499 (case-fold-search t))
13500 (catch 'exit
13501 ;; Try to find existing drawer.
13502 (while (re-search-forward regexp end t)
13503 (let ((element (org-element-at-point)))
13504 (when (eq (org-element-type element) 'drawer)
13505 (let ((cend (org-element-property :contents-end element)))
13506 (when (and (not org-log-states-order-reversed) cend)
13507 (goto-char cend)))
13508 (throw 'exit nil))))
13509 ;; No drawer found. Create one, if permitted.
13510 (when create
13511 (unless (bolp) (insert "\n"))
13512 (let ((beg (point)))
13513 (insert ":" drawer ":\n:END:\n")
13514 (org-indent-region beg (point)))
13515 (end-of-line -1)))))
13517 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13518 (skip-chars-forward " \t\n")
13519 (beginning-of-line)
13520 (unless org-log-states-order-reversed
13521 (org-skip-over-state-notes)
13522 (skip-chars-backward " \t\n")
13523 (forward-line)))))
13524 (if (bolp) (point) (line-beginning-position 2))))
13526 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13527 "Set up the post command hook to take a note.
13528 If this is about to TODO state change, the new state is expected in STATE.
13529 HOW is an indicator what kind of note should be created.
13530 EXTRA is additional text that will be inserted into the notes buffer."
13531 (move-marker org-log-note-marker (point))
13532 (setq org-log-note-purpose purpose
13533 org-log-note-state state
13534 org-log-note-previous-state prev-state
13535 org-log-note-how how
13536 org-log-note-extra extra
13537 org-log-note-effective-time (org-current-effective-time))
13538 (add-hook 'post-command-hook 'org-add-log-note 'append))
13540 (defun org-skip-over-state-notes ()
13541 "Skip past the list of State notes in an entry."
13542 (when (ignore-errors (goto-char (org-in-item-p)))
13543 (let* ((struct (org-list-struct))
13544 (prevs (org-list-prevs-alist struct))
13545 (regexp
13546 (concat "[ \t]*- +"
13547 (replace-regexp-in-string
13548 " +" " +"
13549 (org-replace-escapes
13550 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13551 `(("%d" . ,org-ts-regexp-inactive)
13552 ("%D" . ,org-ts-regexp)
13553 ("%s" . "\"\\S-+\"")
13554 ("%S" . "\"\\S-+\"")
13555 ("%t" . ,org-ts-regexp-inactive)
13556 ("%T" . ,org-ts-regexp)
13557 ("%u" . ".*?")
13558 ("%U" . ".*?")))))))
13559 (while (looking-at-p regexp)
13560 (goto-char (or (org-list-get-next-item (point) struct prevs)
13561 (org-list-get-item-end (point) struct)))))))
13563 (defun org-add-log-note (&optional _purpose)
13564 "Pop up a window for taking a note, and add this note later."
13565 (remove-hook 'post-command-hook 'org-add-log-note)
13566 (setq org-log-note-window-configuration (current-window-configuration))
13567 (delete-other-windows)
13568 (move-marker org-log-note-return-to (point))
13569 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13570 (goto-char org-log-note-marker)
13571 (org-switch-to-buffer-other-window "*Org Note*")
13572 (erase-buffer)
13573 (if (memq org-log-note-how '(time state))
13574 (org-store-log-note)
13575 (let ((org-inhibit-startup t)) (org-mode))
13576 (insert (format "# Insert note for %s.
13577 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13578 (cond
13579 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13580 ((eq org-log-note-purpose 'done) "closed todo item")
13581 ((eq org-log-note-purpose 'state)
13582 (format "state change from \"%s\" to \"%s\""
13583 (or org-log-note-previous-state "")
13584 (or org-log-note-state "")))
13585 ((eq org-log-note-purpose 'reschedule)
13586 "rescheduling")
13587 ((eq org-log-note-purpose 'delschedule)
13588 "no longer scheduled")
13589 ((eq org-log-note-purpose 'redeadline)
13590 "changing deadline")
13591 ((eq org-log-note-purpose 'deldeadline)
13592 "removing deadline")
13593 ((eq org-log-note-purpose 'refile)
13594 "refiling")
13595 ((eq org-log-note-purpose 'note)
13596 "this entry")
13597 (t (error "This should not happen")))))
13598 (when org-log-note-extra (insert org-log-note-extra))
13599 (setq-local org-finish-function 'org-store-log-note)
13600 (run-hooks 'org-log-buffer-setup-hook)))
13602 (defvar org-note-abort nil) ; dynamically scoped
13603 (defun org-store-log-note ()
13604 "Finish taking a log note, and insert it to where it belongs."
13605 (let ((txt (prog1 (buffer-string)
13606 (kill-buffer)))
13607 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13608 lines)
13609 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13610 (setq txt (replace-match "" t t txt)))
13611 (when (string-match "\\s-+\\'" txt)
13612 (setq txt (replace-match "" t t txt)))
13613 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13614 (when (org-string-nw-p note)
13615 (setq note
13616 (org-replace-escapes
13617 note
13618 (list (cons "%u" (user-login-name))
13619 (cons "%U" user-full-name)
13620 (cons "%t" (format-time-string
13621 (org-time-stamp-format 'long 'inactive)
13622 org-log-note-effective-time))
13623 (cons "%T" (format-time-string
13624 (org-time-stamp-format 'long nil)
13625 org-log-note-effective-time))
13626 (cons "%d" (format-time-string
13627 (org-time-stamp-format nil 'inactive)
13628 org-log-note-effective-time))
13629 (cons "%D" (format-time-string
13630 (org-time-stamp-format nil nil)
13631 org-log-note-effective-time))
13632 (cons "%s" (cond
13633 ((not org-log-note-state) "")
13634 ((string-match-p org-ts-regexp
13635 org-log-note-state)
13636 (format "\"[%s]\""
13637 (substring org-log-note-state 1 -1)))
13638 (t (format "\"%s\"" org-log-note-state))))
13639 (cons "%S"
13640 (cond
13641 ((not org-log-note-previous-state) "")
13642 ((string-match-p org-ts-regexp
13643 org-log-note-previous-state)
13644 (format "\"[%s]\""
13645 (substring
13646 org-log-note-previous-state 1 -1)))
13647 (t (format "\"%s\""
13648 org-log-note-previous-state)))))))
13649 (when lines (setq note (concat note " \\\\")))
13650 (push note lines))
13651 (when (and lines (not org-note-abort))
13652 (with-current-buffer (marker-buffer org-log-note-marker)
13653 (org-with-wide-buffer
13654 ;; Find location for the new note.
13655 (goto-char org-log-note-marker)
13656 (set-marker org-log-note-marker nil)
13657 ;; Note associated to a clock is to be located right after
13658 ;; the clock. Do not move point.
13659 (unless (eq org-log-note-purpose 'clock-out)
13660 (goto-char (org-log-beginning t)))
13661 ;; Make sure point is at the beginning of an empty line.
13662 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13663 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13664 ;; In an existing list, add a new item at the top level.
13665 ;; Otherwise, indent line like a regular one.
13666 (let ((itemp (org-in-item-p)))
13667 (if itemp
13668 (indent-line-to
13669 (let ((struct (save-excursion
13670 (goto-char itemp) (org-list-struct))))
13671 (org-list-get-ind (org-list-get-top-point struct) struct)))
13672 (org-indent-line)))
13673 (insert (org-list-bullet-string "-") (pop lines))
13674 (let ((ind (org-list-item-body-column (line-beginning-position))))
13675 (dolist (line lines)
13676 (insert "\n")
13677 (indent-line-to ind)
13678 (insert line)))
13679 (message "Note stored")
13680 (org-back-to-heading t)
13681 (org-cycle-hide-drawers 'children))
13682 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13683 ;; from within `org-add-log-note' because `buffer-undo-list'
13684 ;; is then modified outside of `org-with-remote-undo'.
13685 (when (eq this-command 'org-agenda-todo)
13686 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13687 ;; Don't add undo information when called from `org-agenda-todo'.
13688 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13689 (set-window-configuration org-log-note-window-configuration)
13690 (with-current-buffer (marker-buffer org-log-note-return-to)
13691 (goto-char org-log-note-return-to))
13692 (move-marker org-log-note-return-to nil)
13693 (when org-log-post-message (message "%s" org-log-post-message))))
13695 (defun org-remove-empty-drawer-at (pos)
13696 "Remove an empty drawer at position POS.
13697 POS may also be a marker."
13698 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13699 (org-with-wide-buffer
13700 (goto-char pos)
13701 (let ((drawer (org-element-at-point)))
13702 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13703 (not (org-element-property :contents-begin drawer)))
13704 (delete-region (org-element-property :begin drawer)
13705 (progn (goto-char (org-element-property :end drawer))
13706 (skip-chars-backward " \r\t\n")
13707 (forward-line)
13708 (point))))))))
13710 (defvar org-ts-type nil)
13711 (defun org-sparse-tree (&optional arg type)
13712 "Create a sparse tree, prompt for the details.
13713 This command can create sparse trees. You first need to select the type
13714 of match used to create the tree:
13716 t Show all TODO entries.
13717 T Show entries with a specific TODO keyword.
13718 m Show entries selected by a tags/property match.
13719 p Enter a property name and its value (both with completion on existing
13720 names/values) and show entries with that property.
13721 r Show entries matching a regular expression (`/' can be used as well).
13722 b Show deadlines and scheduled items before a date.
13723 a Show deadlines and scheduled items after a date.
13724 d Show deadlines due within `org-deadline-warning-days'.
13725 D Show deadlines and scheduled items between a date range."
13726 (interactive "P")
13727 (setq type (or type org-sparse-tree-default-date-type))
13728 (setq org-ts-type type)
13729 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13730 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13731 \[c]ycle through date types: %s"
13732 (cl-case type
13733 (all "all timestamps")
13734 (scheduled "only scheduled")
13735 (deadline "only deadline")
13736 (active "only active timestamps")
13737 (inactive "only inactive timestamps")
13738 (closed "with a closed time-stamp")
13739 (otherwise "scheduled/deadline")))
13740 (let ((answer (read-char-exclusive)))
13741 (cl-case answer
13743 (org-sparse-tree
13745 (cadr
13746 (memq type '(nil all scheduled deadline active inactive closed)))))
13747 (?d (call-interactively 'org-check-deadlines))
13748 (?b (call-interactively 'org-check-before-date))
13749 (?a (call-interactively 'org-check-after-date))
13750 (?D (call-interactively 'org-check-dates-range))
13751 (?t (call-interactively 'org-show-todo-tree))
13752 (?T (org-show-todo-tree '(4)))
13753 (?m (call-interactively 'org-match-sparse-tree))
13754 ((?p ?P)
13755 (let* ((kwd (completing-read
13756 "Property: " (mapcar #'list (org-buffer-property-keys))))
13757 (value (completing-read
13758 "Value: " (mapcar #'list (org-property-values kwd)))))
13759 (unless (string-match "\\`{.*}\\'" value)
13760 (setq value (concat "\"" value "\"")))
13761 (org-match-sparse-tree arg (concat kwd "=" value))))
13762 ((?r ?R ?/) (call-interactively 'org-occur))
13763 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13765 (defvar-local org-occur-highlights nil
13766 "List of overlays used for occur matches.")
13767 (defvar-local org-occur-parameters nil
13768 "Parameters of the active org-occur calls.
13769 This is a list, each call to org-occur pushes as cons cell,
13770 containing the regular expression and the callback, onto the list.
13771 The list can contain several entries if `org-occur' has been called
13772 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13773 will only contain one set of parameters. When the highlights are
13774 removed (for example with `C-c C-c', or with the next edit (depending
13775 on `org-remove-highlights-with-change'), this variable is emptied
13776 as well.")
13778 (defun org-occur (regexp &optional keep-previous callback)
13779 "Make a compact tree which shows all matches of REGEXP.
13781 The tree will show the lines where the regexp matches, and any other context
13782 defined in `org-show-context-detail', which see.
13784 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13785 done by a previous call to `org-occur' will be kept, to allow stacking of
13786 calls to this command.
13788 Optional argument CALLBACK can be a function of no argument. In this case,
13789 it is called with point at the end of the match, match data being set
13790 accordingly. Current match is shown only if the return value is non-nil.
13791 The function must neither move point nor alter narrowing."
13792 (interactive "sRegexp: \nP")
13793 (when (equal regexp "")
13794 (user-error "Regexp cannot be empty"))
13795 (unless keep-previous
13796 (org-remove-occur-highlights nil nil t))
13797 (push (cons regexp callback) org-occur-parameters)
13798 (let ((cnt 0))
13799 (save-excursion
13800 (goto-char (point-min))
13801 (when (or (not keep-previous) ; do not want to keep
13802 (not org-occur-highlights)) ; no previous matches
13803 ;; hide everything
13804 (org-overview))
13805 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13806 (isearch-no-upper-case-p regexp t)
13807 org-occur-case-fold-search)))
13808 (while (re-search-forward regexp nil t)
13809 (when (or (not callback)
13810 (save-match-data (funcall callback)))
13811 (setq cnt (1+ cnt))
13812 (when org-highlight-sparse-tree-matches
13813 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13814 (org-show-context 'occur-tree)))))
13815 (when org-remove-highlights-with-change
13816 (add-hook 'before-change-functions 'org-remove-occur-highlights
13817 nil 'local))
13818 (unless org-sparse-tree-open-archived-trees
13819 (org-hide-archived-subtrees (point-min) (point-max)))
13820 (run-hooks 'org-occur-hook)
13821 (when (called-interactively-p 'interactive)
13822 (message "%d match(es) for regexp %s" cnt regexp))
13823 cnt))
13825 (defun org-occur-next-match (&optional n _reset)
13826 "Function for `next-error-function' to find sparse tree matches.
13827 N is the number of matches to move, when negative move backwards.
13828 This function always goes back to the starting point when no
13829 match is found."
13830 (let* ((limit (if (< n 0) (point-min) (point-max)))
13831 (search-func (if (< n 0)
13832 'previous-single-char-property-change
13833 'next-single-char-property-change))
13834 (n (abs n))
13835 (pos (point))
13837 (catch 'exit
13838 (while (setq p1 (funcall search-func (point) 'org-type))
13839 (when (equal p1 limit)
13840 (goto-char pos)
13841 (user-error "No more matches"))
13842 (when (equal (get-char-property p1 'org-type) 'org-occur)
13843 (setq n (1- n))
13844 (when (= n 0)
13845 (goto-char p1)
13846 (throw 'exit (point))))
13847 (goto-char p1))
13848 (goto-char p1)
13849 (user-error "No more matches"))))
13851 (defun org-show-context (&optional key)
13852 "Make sure point and context are visible.
13853 Optional argument KEY, when non-nil, is a symbol. See
13854 `org-show-context-detail' for allowed values and how much is to
13855 be shown."
13856 (org-show-set-visibility
13857 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13858 ((cdr (assq key org-show-context-detail)))
13859 (t (cdr (assq 'default org-show-context-detail))))))
13861 (defun org-show-set-visibility (detail)
13862 "Set visibility around point according to DETAIL.
13863 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13864 `tree', `canonical' or t. See `org-show-context-detail' for more
13865 information."
13866 ;; Show current heading and possibly its entry, following headline
13867 ;; or all children.
13868 (if (and (org-at-heading-p) (not (eq detail 'local)))
13869 (org-flag-heading nil)
13870 (org-show-entry)
13871 ;; If point is hidden within a drawer or a block, make sure to
13872 ;; expose it.
13873 (dolist (o (overlays-at (point)))
13874 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13875 (delete-overlay o)))
13876 (unless (org-before-first-heading-p)
13877 (org-with-limited-levels
13878 (cl-case detail
13879 ((tree canonical t) (org-show-children))
13880 ((nil minimal ancestors))
13881 (t (save-excursion
13882 (outline-next-heading)
13883 (org-flag-heading nil)))))))
13884 ;; Show all siblings.
13885 (when (eq detail 'lineage) (org-show-siblings))
13886 ;; Show ancestors, possibly with their children.
13887 (when (memq detail '(ancestors lineage tree canonical t))
13888 (save-excursion
13889 (while (org-up-heading-safe)
13890 (org-flag-heading nil)
13891 (when (memq detail '(canonical t)) (org-show-entry))
13892 (when (memq detail '(tree canonical t)) (org-show-children))))))
13894 (defvar org-reveal-start-hook nil
13895 "Hook run before revealing a location.")
13897 (defun org-reveal (&optional siblings)
13898 "Show current entry, hierarchy above it, and the following headline.
13900 This can be used to show a consistent set of context around
13901 locations exposed with `org-show-context'.
13903 With optional argument SIBLINGS, on each level of the hierarchy all
13904 siblings are shown. This repairs the tree structure to what it would
13905 look like when opened with hierarchical calls to `org-cycle'.
13907 With a \\[universal-argument] \\[universal-argument] prefix, \
13908 go to the parent and show the entire tree."
13909 (interactive "P")
13910 (run-hooks 'org-reveal-start-hook)
13911 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13912 ((equal siblings '(16))
13913 (save-excursion
13914 (when (org-up-heading-safe)
13915 (org-show-subtree)
13916 (run-hook-with-args 'org-cycle-hook 'subtree))))
13917 (t (org-show-set-visibility 'lineage))))
13919 (defun org-highlight-new-match (beg end)
13920 "Highlight from BEG to END and mark the highlight is an occur headline."
13921 (let ((ov (make-overlay beg end)))
13922 (overlay-put ov 'face 'secondary-selection)
13923 (overlay-put ov 'org-type 'org-occur)
13924 (push ov org-occur-highlights)))
13926 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13927 "Remove the occur highlights from the buffer.
13928 BEG and END are ignored. If NOREMOVE is nil, remove this function
13929 from the `before-change-functions' in the current buffer."
13930 (interactive)
13931 (unless org-inhibit-highlight-removal
13932 (mapc #'delete-overlay org-occur-highlights)
13933 (setq org-occur-highlights nil)
13934 (setq org-occur-parameters nil)
13935 (unless noremove
13936 (remove-hook 'before-change-functions
13937 'org-remove-occur-highlights 'local))))
13939 ;;;; Priorities
13941 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13942 "Regular expression matching the priority indicator.")
13944 (defvar org-remove-priority-next-time nil)
13946 (defun org-priority-up ()
13947 "Increase the priority of the current item."
13948 (interactive)
13949 (org-priority 'up))
13951 (defun org-priority-down ()
13952 "Decrease the priority of the current item."
13953 (interactive)
13954 (org-priority 'down))
13956 (defun org-priority (&optional action _show)
13957 "Change the priority of an item.
13958 ACTION can be `set', `up', `down', or a character."
13959 (interactive "P")
13960 (if (equal action '(4))
13961 (org-show-priority)
13962 (unless org-enable-priority-commands
13963 (user-error "Priority commands are disabled"))
13964 (setq action (or action 'set))
13965 (let (current new news have remove)
13966 (save-excursion
13967 (org-back-to-heading t)
13968 (when (looking-at org-priority-regexp)
13969 (setq current (string-to-char (match-string 2))
13970 have t))
13971 (cond
13972 ((eq action 'remove)
13973 (setq remove t new ?\ ))
13974 ((or (eq action 'set)
13975 (integerp action))
13976 (if (not (eq action 'set))
13977 (setq new action)
13978 (message "Priority %c-%c, SPC to remove: "
13979 org-highest-priority org-lowest-priority)
13980 (save-match-data
13981 (setq new (read-char-exclusive))))
13982 (when (and (= (upcase org-highest-priority) org-highest-priority)
13983 (= (upcase org-lowest-priority) org-lowest-priority))
13984 (setq new (upcase new)))
13985 (cond ((equal new ?\ ) (setq remove t))
13986 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13987 (user-error "Priority must be between `%c' and `%c'"
13988 org-highest-priority org-lowest-priority))))
13989 ((eq action 'up)
13990 (setq new (if have
13991 (1- current) ; normal cycling
13992 ;; last priority was empty
13993 (if (eq last-command this-command)
13994 org-lowest-priority ; wrap around empty to lowest
13995 ;; default
13996 (if org-priority-start-cycle-with-default
13997 org-default-priority
13998 (1- org-default-priority))))))
13999 ((eq action 'down)
14000 (setq new (if have
14001 (1+ current) ; normal cycling
14002 ;; last priority was empty
14003 (if (eq last-command this-command)
14004 org-highest-priority ; wrap around empty to highest
14005 ;; default
14006 (if org-priority-start-cycle-with-default
14007 org-default-priority
14008 (1+ org-default-priority))))))
14009 (t (user-error "Invalid action")))
14010 (when (or (< (upcase new) org-highest-priority)
14011 (> (upcase new) org-lowest-priority))
14012 (if (and (memq action '(up down))
14013 (not have) (not (eq last-command this-command)))
14014 ;; `new' is from default priority
14015 (error
14016 "The default can not be set, see `org-default-priority' why")
14017 ;; normal cycling: `new' is beyond highest/lowest priority
14018 ;; and is wrapped around to the empty priority
14019 (setq remove t)))
14020 (setq news (format "%c" new))
14021 (if have
14022 (if remove
14023 (replace-match "" t t nil 1)
14024 (replace-match news t t nil 2))
14025 (if remove
14026 (user-error "No priority cookie found in line")
14027 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14028 (if (match-end 2)
14029 (progn
14030 (goto-char (match-end 2))
14031 (insert " [#" news "]"))
14032 (goto-char (match-beginning 3))
14033 (insert "[#" news "] "))))
14034 (org-set-tags nil 'align))
14035 (if remove
14036 (message "Priority removed")
14037 (message "Priority of current item set to %s" news)))))
14039 (defun org-show-priority ()
14040 "Show the priority of the current item.
14041 This priority is composed of the main priority given with the [#A] cookies,
14042 and by additional input from the age of a schedules or deadline entry."
14043 (interactive)
14044 (let ((pri (if (eq major-mode 'org-agenda-mode)
14045 (org-get-at-bol 'priority)
14046 (save-excursion
14047 (save-match-data
14048 (beginning-of-line)
14049 (and (looking-at org-heading-regexp)
14050 (org-get-priority (match-string 0))))))))
14051 (message "Priority is %d" (if pri pri -1000))))
14053 (defun org-get-priority (s)
14054 "Find priority cookie and return priority."
14055 (save-match-data
14056 (if (functionp org-get-priority-function)
14057 (funcall org-get-priority-function)
14058 (if (not (string-match org-priority-regexp s))
14059 (* 1000 (- org-lowest-priority org-default-priority))
14060 (* 1000 (- org-lowest-priority
14061 (string-to-char (match-string 2 s))))))))
14063 ;;;; Tags
14065 (defvar org-agenda-archives-mode)
14066 (defvar org-map-continue-from nil
14067 "Position from where mapping should continue.
14068 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14070 (defvar org-scanner-tags nil
14071 "The current tag list while the tags scanner is running.")
14073 (defvar org-trust-scanner-tags nil
14074 "Should `org-get-tags-at' use the tags for the scanner.
14075 This is for internal dynamical scoping only.
14076 When this is non-nil, the function `org-get-tags-at' will return the value
14077 of `org-scanner-tags' instead of building the list by itself. This
14078 can lead to large speed-ups when the tags scanner is used in a file with
14079 many entries, and when the list of tags is retrieved, for example to
14080 obtain a list of properties. Building the tags list for each entry in such
14081 a file becomes an N^2 operation - but with this variable set, it scales
14082 as N.")
14084 (defvar org--matcher-tags-todo-only nil)
14086 (defun org-scan-tags (action matcher todo-only &optional start-level)
14087 "Scan headline tags with inheritance and produce output ACTION.
14089 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14090 or `agenda' to produce an entry list for an agenda view. It can also be
14091 a Lisp form or a function that should be called at each matched headline, in
14092 this case the return value is a list of all return values from these calls.
14094 MATCHER is a function accepting three arguments, returning
14095 a non-nil value whenever a given set of tags qualifies a headline
14096 for inclusion. See `org-make-tags-matcher' for more information.
14097 As a special case, it can also be set to t (respectively nil) in
14098 order to match all (respectively none) headline.
14100 When TODO-ONLY is non-nil, only lines with a not-done TODO
14101 keyword are included in the output.
14103 START-LEVEL can be a string with asterisks, reducing the scope to
14104 headlines matching this string."
14105 (require 'org-agenda)
14106 (let* ((re (concat "^"
14107 (if start-level
14108 ;; Get the correct level to match
14109 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14110 org-outline-regexp)
14111 " *\\(\\<\\("
14112 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14113 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14114 (props (list 'face 'default
14115 'done-face 'org-agenda-done
14116 'undone-face 'default
14117 'mouse-face 'highlight
14118 'org-not-done-regexp org-not-done-regexp
14119 'org-todo-regexp org-todo-regexp
14120 'org-complex-heading-regexp org-complex-heading-regexp
14121 'help-echo
14122 (format "mouse-2 or RET jump to org file %s"
14123 (abbreviate-file-name
14124 (or (buffer-file-name (buffer-base-buffer))
14125 (buffer-name (buffer-base-buffer)))))))
14126 (org-map-continue-from nil)
14127 lspos tags tags-list
14128 (tags-alist (list (cons 0 org-file-tags)))
14129 (llast 0) rtn rtn1 level category i txt
14130 todo marker entry priority
14131 ts-date ts-date-type ts-date-pair)
14132 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14133 (setq action (list 'lambda nil action)))
14134 (save-excursion
14135 (goto-char (point-min))
14136 (when (eq action 'sparse-tree)
14137 (org-overview)
14138 (org-remove-occur-highlights))
14139 (while (let (case-fold-search)
14140 (re-search-forward re nil t))
14141 (setq org-map-continue-from nil)
14142 (catch :skip
14143 (setq todo
14144 ;; TODO: is the 1-2 difference a bug?
14145 (when (match-end 1) (match-string-no-properties 2))
14146 tags (when (match-end 4) (match-string-no-properties 4)))
14147 (goto-char (setq lspos (match-beginning 0)))
14148 (setq level (org-reduced-level (org-outline-level))
14149 category (org-get-category))
14150 (when (eq action 'agenda)
14151 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14152 ts-date (car ts-date-pair)
14153 ts-date-type (cdr ts-date-pair)))
14154 (setq i llast llast level)
14155 ;; remove tag lists from same and sublevels
14156 (while (>= i level)
14157 (when (setq entry (assoc i tags-alist))
14158 (setq tags-alist (delete entry tags-alist)))
14159 (setq i (1- i)))
14160 ;; add the next tags
14161 (when tags
14162 (setq tags (org-split-string tags ":")
14163 tags-alist
14164 (cons (cons level tags) tags-alist)))
14165 ;; compile tags for current headline
14166 (setq tags-list
14167 (if org-use-tag-inheritance
14168 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14169 tags)
14170 org-scanner-tags tags-list)
14171 (when org-use-tag-inheritance
14172 (setcdr (car tags-alist)
14173 (mapcar (lambda (x)
14174 (setq x (copy-sequence x))
14175 (org-add-prop-inherited x))
14176 (cdar tags-alist))))
14177 (when (and tags org-use-tag-inheritance
14178 (or (not (eq t org-use-tag-inheritance))
14179 org-tags-exclude-from-inheritance))
14180 ;; Selective inheritance, remove uninherited ones.
14181 (setcdr (car tags-alist)
14182 (org-remove-uninherited-tags (cdar tags-alist))))
14183 (when (and
14185 ;; eval matcher only when the todo condition is OK
14186 (and (or (not todo-only) (member todo org-not-done-keywords))
14187 (if (functionp matcher)
14188 (let ((case-fold-search t) (org-trust-scanner-tags t))
14189 (funcall matcher todo tags-list level))
14190 matcher))
14192 ;; Call the skipper, but return t if it does not
14193 ;; skip, so that the `and' form continues evaluating.
14194 (progn
14195 (unless (eq action 'sparse-tree) (org-agenda-skip))
14198 ;; Check if timestamps are deselecting this entry
14199 (or (not todo-only)
14200 (and (member todo org-not-done-keywords)
14201 (or (not org-agenda-tags-todo-honor-ignore-options)
14202 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14204 ;; select this headline
14205 (cond
14206 ((eq action 'sparse-tree)
14207 (and org-highlight-sparse-tree-matches
14208 (org-get-heading) (match-end 0)
14209 (org-highlight-new-match
14210 (match-beginning 1) (match-end 1)))
14211 (org-show-context 'tags-tree))
14212 ((eq action 'agenda)
14213 (setq txt (org-agenda-format-item
14215 (concat
14216 (if (eq org-tags-match-list-sublevels 'indented)
14217 (make-string (1- level) ?.) "")
14218 (org-get-heading))
14219 (make-string level ?\s)
14220 category
14221 tags-list)
14222 priority (org-get-priority txt))
14223 (goto-char lspos)
14224 (setq marker (org-agenda-new-marker))
14225 (org-add-props txt props
14226 'org-marker marker 'org-hd-marker marker 'org-category category
14227 'todo-state todo
14228 'ts-date ts-date
14229 'priority priority
14230 'type (concat "tagsmatch" ts-date-type))
14231 (push txt rtn))
14232 ((functionp action)
14233 (setq org-map-continue-from nil)
14234 (save-excursion
14235 (setq rtn1 (funcall action))
14236 (push rtn1 rtn)))
14237 (t (user-error "Invalid action")))
14239 ;; if we are to skip sublevels, jump to end of subtree
14240 (unless org-tags-match-list-sublevels
14241 (org-end-of-subtree t)
14242 (backward-char 1))))
14243 ;; Get the correct position from where to continue
14244 (if org-map-continue-from
14245 (goto-char org-map-continue-from)
14246 (and (= (point) lspos) (end-of-line 1)))))
14247 (when (and (eq action 'sparse-tree)
14248 (not org-sparse-tree-open-archived-trees))
14249 (org-hide-archived-subtrees (point-min) (point-max)))
14250 (nreverse rtn)))
14252 (defun org-remove-uninherited-tags (tags)
14253 "Remove all tags that are not inherited from the list TAGS."
14254 (cond
14255 ((eq org-use-tag-inheritance t)
14256 (if org-tags-exclude-from-inheritance
14257 (org-delete-all org-tags-exclude-from-inheritance tags)
14258 tags))
14259 ((not org-use-tag-inheritance) nil)
14260 ((stringp org-use-tag-inheritance)
14261 (delq nil (mapcar
14262 (lambda (x)
14263 (if (and (string-match org-use-tag-inheritance x)
14264 (not (member x org-tags-exclude-from-inheritance)))
14265 x nil))
14266 tags)))
14267 ((listp org-use-tag-inheritance)
14268 (delq nil (mapcar
14269 (lambda (x)
14270 (if (member x org-use-tag-inheritance) x nil))
14271 tags)))))
14273 (defun org-match-sparse-tree (&optional todo-only match)
14274 "Create a sparse tree according to tags string MATCH.
14276 MATCH is a string with match syntax. It can contain a selection
14277 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14278 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14279 those. See the manual for details.
14281 If optional argument TODO-ONLY is non-nil, only select lines that
14282 are also TODO tasks."
14283 (interactive "P")
14284 (org-agenda-prepare-buffers (list (current-buffer)))
14285 (let ((org--matcher-tags-todo-only todo-only))
14286 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14287 org--matcher-tags-todo-only)))
14289 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14291 (defvar org-cached-props nil)
14292 (defun org-cached-entry-get (pom property)
14293 (if (or (eq t org-use-property-inheritance)
14294 (and (stringp org-use-property-inheritance)
14295 (let ((case-fold-search t))
14296 (string-match-p org-use-property-inheritance property)))
14297 (and (listp org-use-property-inheritance)
14298 (member-ignore-case property org-use-property-inheritance)))
14299 ;; Caching is not possible, check it directly.
14300 (org-entry-get pom property 'inherit)
14301 ;; Get all properties, so we can do complicated checks easily.
14302 (cdr (assoc-string property
14303 (or org-cached-props
14304 (setq org-cached-props (org-entry-properties pom)))
14305 t))))
14307 (defun org-global-tags-completion-table (&optional files)
14308 "Return the list of all tags in all agenda buffer/files.
14309 Optional FILES argument is a list of files which can be used
14310 instead of the agenda files."
14311 (save-excursion
14312 (org-uniquify
14313 (delq nil
14314 (apply #'append
14315 (mapcar
14316 (lambda (file)
14317 (set-buffer (find-file-noselect file))
14318 (mapcar (lambda (x)
14319 (and (stringp (car-safe x))
14320 (list (car-safe x))))
14321 (or org-current-tag-alist (org-get-buffer-tags))))
14322 (if (car-safe files) files
14323 (org-agenda-files))))))))
14325 (defun org-make-tags-matcher (match)
14326 "Create the TAGS/TODO matcher form for the selection string MATCH.
14328 Returns a cons of the selection string MATCH and a function
14329 implementing the matcher.
14331 The matcher is to be called at an Org entry, with point on the
14332 headline, and returns non-nil if the entry matches the selection
14333 string MATCH. It must be called with three arguments: the TODO
14334 keyword at the entry (or nil if none), the list of all tags at
14335 the entry including inherited ones and the reduced level of the
14336 headline. Additionally, the category of the entry, if any, must
14337 be specified as the text property `org-category' on the headline.
14339 This function sets the variable `org--matcher-tags-todo-only' to
14340 a non-nil value if the matcher restricts matching to TODO
14341 entries, otherwise it is not touched.
14343 See also `org-scan-tags'."
14344 (unless match
14345 ;; Get a new match request, with completion against the global
14346 ;; tags table and the local tags in current buffer.
14347 (let ((org-last-tags-completion-table
14348 (org-uniquify
14349 (delq nil (append (org-get-buffer-tags)
14350 (org-global-tags-completion-table))))))
14351 (setq match
14352 (completing-read
14353 "Match: "
14354 'org-tags-completion-function nil nil nil 'org-tags-history))))
14356 (let ((match0 match)
14357 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14358 (start 0)
14359 tagsmatch todomatch tagsmatcher todomatcher)
14361 ;; Expand group tags.
14362 (setq match (org-tags-expand match))
14364 ;; Check if there is a TODO part of this match, which would be the
14365 ;; part after a "/". To make sure that this slash is not part of
14366 ;; a property value to be matched against, we also check that
14367 ;; there is no / after that slash. First, find the last slash.
14368 (let ((s 0))
14369 (while (string-match "/+" match s)
14370 (setq start (match-beginning 0))
14371 (setq s (match-end 0))))
14372 (if (and (string-match "/+" match start)
14373 (not (string-match-p "\"" match start)))
14374 ;; Match contains also a TODO-matching request.
14375 (progn
14376 (setq tagsmatch (substring match 0 (match-beginning 0)))
14377 (setq todomatch (substring match (match-end 0)))
14378 (when (string-prefix-p "!" todomatch)
14379 (setq org--matcher-tags-todo-only t)
14380 (setq todomatch (substring todomatch 1)))
14381 (when (string-match "\\`\\s-*\\'" todomatch)
14382 (setq todomatch nil)))
14383 ;; Only matching tags.
14384 (setq tagsmatch match)
14385 (setq todomatch nil))
14387 ;; Make the tags matcher.
14388 (when (org-string-nw-p tagsmatch)
14389 (let ((orlist nil)
14390 (orterms (org-split-string tagsmatch "|"))
14391 term)
14392 (while (setq term (pop orterms))
14393 (while (and (equal (substring term -1) "\\") orterms)
14394 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14395 (while (string-match re term)
14396 (let* ((rest (substring term (match-end 0)))
14397 (minus (and (match-end 1)
14398 (equal (match-string 1 term) "-")))
14399 (tag (save-match-data
14400 (replace-regexp-in-string
14401 "\\\\-" "-" (match-string 2 term))))
14402 (regexp (eq (string-to-char tag) ?{))
14403 (levelp (match-end 4))
14404 (propp (match-end 5))
14406 (cond
14407 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14408 (levelp
14409 `(,(org-op-to-function (match-string 3 term))
14410 level
14411 ,(string-to-number (match-string 4 term))))
14412 (propp
14413 (let* ((gv (pcase (upcase (match-string 5 term))
14414 ("CATEGORY"
14415 '(get-text-property (point) 'org-category))
14416 ("TODO" 'todo)
14417 (p `(org-cached-entry-get nil ,p))))
14418 (pv (match-string 7 term))
14419 (regexp (eq (string-to-char pv) ?{))
14420 (strp (eq (string-to-char pv) ?\"))
14421 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14422 (po (org-op-to-function (match-string 6 term)
14423 (if timep 'time strp))))
14424 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14425 (when timep (setq pv (org-matcher-time pv)))
14426 (cond ((and regexp (eq po 'org<>))
14427 `(not (string-match ,pv (or ,gv ""))))
14428 (regexp `(string-match ,pv (or ,gv "")))
14429 (strp `(,po (or ,gv "") ,pv))
14431 `(,po
14432 (string-to-number (or ,gv ""))
14433 ,(string-to-number pv))))))
14434 (t `(member ,tag tags-list)))))
14435 (push (if minus `(not ,mm) mm) tagsmatcher)
14436 (setq term rest)))
14437 (push `(and ,@tagsmatcher) orlist)
14438 (setq tagsmatcher nil))
14439 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14441 ;; Make the TODO matcher.
14442 (when (org-string-nw-p todomatch)
14443 (let ((orlist nil))
14444 (dolist (term (org-split-string todomatch "|"))
14445 (while (string-match re term)
14446 (let* ((minus (and (match-end 1)
14447 (equal (match-string 1 term) "-")))
14448 (kwd (match-string 2 term))
14449 (regexp (eq (string-to-char kwd) ?{))
14450 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14451 `(equal todo ,kwd))))
14452 (push (if minus `(not ,mm) mm) todomatcher))
14453 (setq term (substring term (match-end 0))))
14454 (push (if (> (length todomatcher) 1)
14455 (cons 'and todomatcher)
14456 (car todomatcher))
14457 orlist)
14458 (setq todomatcher nil))
14459 (setq todomatcher (cons 'or orlist))))
14461 ;; Return the string and function of the matcher. If no
14462 ;; tags-specific or todo-specific matcher exists, match
14463 ;; everything.
14464 (let ((matcher (if (and tagsmatcher todomatcher)
14465 `(and ,tagsmatcher ,todomatcher)
14466 (or tagsmatcher todomatcher t))))
14467 (when org--matcher-tags-todo-only
14468 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14469 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14471 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14472 "Expand group tags in MATCH.
14474 This replaces every group tag in MATCH with a regexp tag search.
14475 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14476 will be replaced like this:
14478 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14479 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14480 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14482 Replacing by a regexp preserves the structure of the match.
14483 E.g., this expansion
14485 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14487 will match anything tagged with \"Lab\" and \"Home\", or tagged
14488 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14490 A group tag in MATCH can contain regular expressions of its own.
14491 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14492 will be replaced like this:
14494 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14496 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14497 assumed to be a single group tag, and the function will return
14498 the list of tags in this group.
14500 When DOWNCASE is non-nil, expand downcased TAGS."
14501 (if org-group-tags
14502 (let* ((case-fold-search t)
14503 (stable org-mode-syntax-table)
14504 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14505 (taggroups (if downcased
14506 (mapcar (lambda (tg) (mapcar #'downcase tg))
14507 taggroups)
14508 taggroups))
14509 (taggroups-keys (mapcar #'car taggroups))
14510 (return-match (if downcased (downcase match) match))
14511 (count 0)
14512 (work-already-expanded tags-already-expanded)
14513 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14514 ;; @ and _ are allowed as word-components in tags.
14515 (modify-syntax-entry ?@ "w" stable)
14516 (modify-syntax-entry ?_ "w" stable)
14517 ;; Temporarily replace regexp-expressions in the match-expression.
14518 (while (string-match "{.+?}" return-match)
14519 (cl-incf count)
14520 (push (match-string 0 return-match) regexps-in-match)
14521 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14522 (while (and taggroups-keys
14523 (with-syntax-table stable
14524 (string-match
14525 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14526 (regexp-opt taggroups-keys) "\\>\\)")
14527 return-match)))
14528 (let* ((dir (match-string 1 return-match))
14529 (tag (match-string 2 return-match))
14530 (tag (if downcased (downcase tag) tag)))
14531 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14532 (member tag work-already-expanded))
14533 (setq tags-in-group (assoc tag taggroups))
14534 (push tag work-already-expanded)
14535 ;; Recursively expand each tag in the group, if the tag hasn't
14536 ;; already been expanded. Restore the match-data after all recursive calls.
14537 (save-match-data
14538 (let (tags-expanded)
14539 (dolist (x (cdr tags-in-group))
14540 (if (and (member x taggroups-keys)
14541 (not (member x work-already-expanded)))
14542 (setq tags-expanded
14543 (delete-dups
14544 (append
14545 (org-tags-expand x t downcased
14546 work-already-expanded)
14547 tags-expanded)))
14548 (setq tags-expanded
14549 (append (list x) tags-expanded)))
14550 (setq work-already-expanded
14551 (delete-dups
14552 (append tags-expanded
14553 work-already-expanded))))
14554 (setq tags-in-group
14555 (delete-dups (cons (car tags-in-group)
14556 tags-expanded)))))
14557 ;; Filter tag-regexps from tags.
14558 (setq regexp-in-group-escaped
14559 (delq nil (mapcar (lambda (x)
14560 (if (stringp x)
14561 (and (equal "{" (substring x 0 1))
14562 (equal "}" (substring x -1))
14565 tags-in-group))
14566 regexp-in-group
14567 (mapcar (lambda (x)
14568 (substring x 1 -1))
14569 regexp-in-group-escaped)
14570 tags-in-group
14571 (delq nil (mapcar (lambda (x)
14572 (if (stringp x)
14573 (and (not (equal "{" (substring x 0 1)))
14574 (not (equal "}" (substring x -1)))
14577 tags-in-group)))
14578 ;; If single-as-list, do no more in the while-loop.
14579 (if (not single-as-list)
14580 (progn
14581 (when regexp-in-group
14582 (setq regexp-in-group
14583 (concat "\\|"
14584 (mapconcat 'identity regexp-in-group
14585 "\\|"))))
14586 (setq tags-in-group
14587 (concat dir
14588 "{\\<"
14589 (regexp-opt tags-in-group)
14590 "\\>"
14591 regexp-in-group
14592 "}"))
14593 (when (stringp tags-in-group)
14594 (org-add-props tags-in-group '(grouptag t)))
14595 (setq return-match
14596 (replace-match tags-in-group t t return-match)))
14597 (setq tags-in-group
14598 (append regexp-in-group-escaped tags-in-group))))
14599 (setq taggroups-keys (delete tag taggroups-keys))))
14600 ;; Add the regular expressions back into the match-expression again.
14601 (while regexps-in-match
14602 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14603 (pop regexps-in-match)
14604 return-match t t))
14605 (cl-decf count))
14606 (if single-as-list
14607 (if tags-in-group tags-in-group (list return-match))
14608 return-match))
14609 (if single-as-list
14610 (list (if downcased (downcase match) match))
14611 match)))
14613 (defun org-op-to-function (op &optional stringp)
14614 "Turn an operator into the appropriate function."
14615 (setq op
14616 (cond
14617 ((equal op "<" ) '(< string< org-time<))
14618 ((equal op ">" ) '(> org-string> org-time>))
14619 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14620 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14621 ((member op '("=" "==")) '(= string= org-time=))
14622 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14623 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14625 (defun org<> (a b) (not (= a b)))
14626 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14627 (defun org-string>= (a b) (not (string< a b)))
14628 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14629 (defun org-string<> (a b) (not (string= a b)))
14630 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14631 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14632 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14633 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14634 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14635 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14636 (defun org-2ft (s)
14637 "Convert S to a floating point time.
14638 If S is already a number, just return it. If it is a string, parse
14639 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14640 (cond
14641 ((numberp s) s)
14642 ((stringp s)
14643 (condition-case nil
14644 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14645 (error 0.)))
14646 (t 0.)))
14648 (defun org-time-today ()
14649 "Time in seconds today at 0:00.
14650 Returns the float number of seconds since the beginning of the
14651 epoch to the beginning of today (00:00)."
14652 (float-time (apply 'encode-time
14653 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14655 (defun org-matcher-time (s)
14656 "Interpret a time comparison value."
14657 (save-match-data
14658 (cond
14659 ((string= s "<now>") (float-time))
14660 ((string= s "<today>") (org-time-today))
14661 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14662 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14663 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14664 (+ (org-time-today)
14665 (* (string-to-number (match-string 1 s))
14666 (cdr (assoc (match-string 2 s)
14667 '(("d" . 86400.0) ("w" . 604800.0)
14668 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14669 (t (org-2ft s)))))
14671 (defun org-match-any-p (re list)
14672 "Does re match any element of list?"
14673 (setq list (mapcar (lambda (x) (string-match re x)) list))
14674 (delq nil list))
14676 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14677 (defvar org-tags-overlay (make-overlay 1 1))
14678 (delete-overlay org-tags-overlay)
14680 (defun org-get-local-tags-at (&optional pos)
14681 "Get a list of tags defined in the current headline."
14682 (org-get-tags-at pos 'local))
14684 (defun org-get-local-tags ()
14685 "Get a list of tags defined in the current headline."
14686 (org-get-tags-at nil 'local))
14688 (defun org-get-tags-at (&optional pos local)
14689 "Get a list of all headline tags applicable at POS.
14690 POS defaults to point. If tags are inherited, the list contains
14691 the targets in the same sequence as the headlines appear, i.e.
14692 the tags of the current headline come last.
14693 When LOCAL is non-nil, only return tags from the current headline,
14694 ignore inherited ones."
14695 (interactive)
14696 (if (and org-trust-scanner-tags
14697 (or (not pos) (equal pos (point)))
14698 (not local))
14699 org-scanner-tags
14700 (let (tags ltags lastpos parent)
14701 (save-excursion
14702 (save-restriction
14703 (widen)
14704 (goto-char (or pos (point)))
14705 (save-match-data
14706 (catch 'done
14707 (condition-case nil
14708 (progn
14709 (org-back-to-heading t)
14710 (while (not (equal lastpos (point)))
14711 (setq lastpos (point))
14712 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14713 (setq ltags (org-split-string
14714 (match-string-no-properties 1) ":"))
14715 (when parent
14716 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14717 (setq tags (append
14718 (if parent
14719 (org-remove-uninherited-tags ltags)
14720 ltags)
14721 tags)))
14722 (or org-use-tag-inheritance (throw 'done t))
14723 (when local (throw 'done t))
14724 (or (org-up-heading-safe) (error nil))
14725 (setq parent t)))
14726 (error nil)))))
14727 (if local
14728 tags
14729 (reverse (delete-dups
14730 (reverse (append
14731 (org-remove-uninherited-tags
14732 org-file-tags)
14733 tags)))))))))
14735 (defun org-add-prop-inherited (s)
14736 (add-text-properties 0 (length s) '(inherited t) s)
14739 (defun org-toggle-tag (tag &optional onoff)
14740 "Toggle the tag TAG for the current line.
14741 If ONOFF is `on' or `off', don't toggle but set to this state."
14742 (save-excursion
14743 (org-back-to-heading t)
14744 (let ((current
14745 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14746 (point-at-eol) t)
14747 (replace-match "")
14748 (nreverse (org-split-string (match-string 1) ":"))))
14749 res)
14750 (pcase onoff
14751 (`off (setq current (delete tag current)))
14752 ((or `on (guard (not (member tag current))))
14753 (setq res t)
14754 (cl-pushnew tag current :test #'equal))
14755 (_ (setq current (delete tag current))))
14756 (end-of-line)
14757 (if current
14758 (progn
14759 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14760 (org-set-tags nil t))
14761 (delete-horizontal-space))
14762 (run-hooks 'org-after-tags-change-hook))
14763 res))
14765 (defun org--align-tags-here (to-col)
14766 "Align tags on the current headline to TO-COL.
14767 Assume point is on a headline."
14768 (let ((pos (point)))
14769 (beginning-of-line)
14770 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14771 (>= pos (match-beginning 2)))
14772 ;; No tags or point within tags: do not align.
14773 (goto-char pos)
14774 (goto-char (match-beginning 1))
14775 (let ((shift (max (- (if (>= to-col 0) to-col
14776 (- (abs to-col) (string-width (match-string 2))))
14777 (current-column))
14778 1)))
14779 (replace-match (make-string shift ?\s) nil nil nil 1)
14780 ;; Preserve initial position, if possible. In any case, stop
14781 ;; before tags.
14782 (when (< pos (point)) (goto-char pos))))))
14784 (defun org-set-tags-command (&optional arg just-align)
14785 "Call the set-tags command for the current entry."
14786 (interactive "P")
14787 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14788 (org-set-tags arg just-align)
14789 (save-excursion
14790 (unless (and (org-region-active-p)
14791 org-loop-over-headlines-in-active-region)
14792 (org-back-to-heading t))
14793 (org-set-tags arg just-align))))
14795 (defun org-set-tags-to (data)
14796 "Set the tags of the current entry to DATA, replacing the current tags.
14797 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14798 If DATA is nil or the empty string, any tags will be removed."
14799 (interactive "sTags: ")
14800 (setq data
14801 (cond
14802 ((eq data nil) "")
14803 ((equal data "") "")
14804 ((stringp data)
14805 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14806 ":"))
14807 ((listp data)
14808 (concat ":" (mapconcat 'identity data ":") ":"))))
14809 (when data
14810 (save-excursion
14811 (org-back-to-heading t)
14812 (when (let ((case-fold-search nil))
14813 (looking-at org-complex-heading-regexp))
14814 (if (match-end 5)
14815 (progn
14816 (goto-char (match-beginning 5))
14817 (insert data)
14818 (delete-region (point) (point-at-eol))
14819 (org-set-tags nil 'align))
14820 (goto-char (point-at-eol))
14821 (insert " " data)
14822 (org-set-tags nil 'align)))
14823 (beginning-of-line 1)
14824 (when (looking-at ".*?\\([ \t]+\\)$")
14825 (delete-region (match-beginning 1) (match-end 1))))))
14827 (defun org-align-all-tags ()
14828 "Align the tags in all headings."
14829 (interactive)
14830 (save-excursion
14831 (or (ignore-errors (org-back-to-heading t))
14832 (outline-next-heading))
14833 (if (org-at-heading-p)
14834 (org-set-tags t)
14835 (message "No headings"))))
14837 (defvar org-indent-indentation-per-level)
14838 (defun org-set-tags (&optional arg just-align)
14839 "Set the tags for the current headline.
14840 With prefix ARG, realign all tags in headings in the current buffer.
14841 When JUST-ALIGN is non-nil, only align tags."
14842 (interactive "P")
14843 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14844 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14845 'region-start-level
14846 'region))
14847 org-loop-over-headlines-in-active-region)
14848 (org-map-entries
14849 ;; We don't use ARG and JUST-ALIGN here because these args
14850 ;; are not useful when looping over headlines.
14851 #'org-set-tags
14852 org-loop-over-headlines-in-active-region
14854 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14855 (let ((org-setting-tags t))
14856 (if arg
14857 (save-excursion
14858 (goto-char (point-min))
14859 (while (re-search-forward org-outline-regexp-bol nil t)
14860 (org-set-tags nil t)
14861 (end-of-line))
14862 (message "All tags realigned to column %d" org-tags-column))
14863 (let* ((current (org-get-tags-string))
14864 (tags
14865 (if just-align current
14866 ;; Get a new set of tags from the user.
14867 (save-excursion
14868 (let* ((seen)
14869 (table
14870 (setq
14871 org-last-tags-completion-table
14872 ;; Uniquify tags in alists, yet preserve
14873 ;; structure (i.e., keywords).
14874 (delq nil
14875 (mapcar
14876 (lambda (pair)
14877 (let ((head (car pair)))
14878 (cond ((symbolp head) pair)
14879 ((member head seen) nil)
14880 (t (push head seen)
14881 pair))))
14882 (append
14883 (or org-current-tag-alist
14884 (org-get-buffer-tags))
14885 (and
14886 org-complete-tags-always-offer-all-agenda-tags
14887 (org-global-tags-completion-table
14888 (org-agenda-files))))))))
14889 (current-tags (org-split-string current ":"))
14890 (inherited-tags
14891 (nreverse (nthcdr (length current-tags)
14892 (nreverse (org-get-tags-at))))))
14893 (replace-regexp-in-string
14894 "\\([-+&]+\\|,\\)"
14896 (if (or (eq t org-use-fast-tag-selection)
14897 (and org-use-fast-tag-selection
14898 (delq nil (mapcar #'cdr table))))
14899 (org-fast-tag-selection
14900 current-tags inherited-tags table
14901 (and org-fast-tag-selection-include-todo
14902 org-todo-key-alist))
14903 (let ((org-add-colon-after-tag-completion
14904 (< 1 (length table))))
14905 (org-trim
14906 (completing-read
14907 "Tags: "
14908 #'org-tags-completion-function
14909 nil nil current 'org-tags-history))))))))))
14911 (when org-tags-sort-function
14912 (setq tags
14913 (mapconcat
14914 #'identity
14915 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14916 org-tags-sort-function)
14917 ":")))
14919 (if (or (string= ":" tags)
14920 (string= "::" tags))
14921 (setq tags ""))
14922 (if (not (org-string-nw-p tags)) (setq tags "")
14923 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14924 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14926 ;; Insert new tags at the correct column.
14927 (unless (equal current tags)
14928 (save-excursion
14929 (beginning-of-line)
14930 (let ((case-fold-search nil))
14931 (looking-at org-complex-heading-regexp))
14932 ;; Remove current tags, if any.
14933 (when (match-end 5) (replace-match "" nil nil nil 5))
14934 ;; Insert new tags, if any. Otherwise, remove trailing
14935 ;; white spaces.
14936 (end-of-line)
14937 (if (not (equal tags ""))
14938 ;; When text is being inserted on an invisible
14939 ;; region boundary, it can be inadvertently sucked
14940 ;; into invisibility.
14941 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14942 (skip-chars-backward " \t")
14943 (delete-region (point) (line-end-position)))))
14944 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14945 ;; is on.
14946 (unless (equal tags "")
14947 (let* ((level (save-excursion
14948 (beginning-of-line)
14949 (skip-chars-forward "\\*")))
14950 (offset (if (bound-and-true-p org-indent-mode)
14951 (* (1- org-indent-indentation-per-level)
14952 (1- level))
14954 (tags-column
14955 (+ org-tags-column
14956 (if (> org-tags-column 0) (- offset) offset))))
14957 (org--align-tags-here tags-column))))
14958 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14960 (defun org-change-tag-in-region (beg end tag off)
14961 "Add or remove TAG for each entry in the region.
14962 This works in the agenda, and also in an Org buffer."
14963 (interactive
14964 (list (region-beginning) (region-end)
14965 (let ((org-last-tags-completion-table
14966 (if (derived-mode-p 'org-mode)
14967 (org-uniquify
14968 (delq nil (append (org-get-buffer-tags)
14969 (org-global-tags-completion-table))))
14970 (org-global-tags-completion-table))))
14971 (completing-read
14972 "Tag: " 'org-tags-completion-function nil nil nil
14973 'org-tags-history))
14974 (progn
14975 (message "[s]et or [r]emove? ")
14976 (equal (read-char-exclusive) ?r))))
14977 (when (fboundp 'deactivate-mark) (deactivate-mark))
14978 (let ((agendap (equal major-mode 'org-agenda-mode))
14979 l1 l2 m buf pos newhead (cnt 0))
14980 (goto-char end)
14981 (setq l2 (1- (org-current-line)))
14982 (goto-char beg)
14983 (setq l1 (org-current-line))
14984 (cl-loop for l from l1 to l2 do
14985 (org-goto-line l)
14986 (setq m (get-text-property (point) 'org-hd-marker))
14987 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14988 (and agendap m))
14989 (setq buf (if agendap (marker-buffer m) (current-buffer))
14990 pos (if agendap m (point)))
14991 (with-current-buffer buf
14992 (save-excursion
14993 (save-restriction
14994 (goto-char pos)
14995 (setq cnt (1+ cnt))
14996 (org-toggle-tag tag (if off 'off 'on))
14997 (setq newhead (org-get-heading)))))
14998 (and agendap (org-agenda-change-all-lines newhead m))))
14999 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15001 (defun org-tags-completion-function (string _predicate &optional flag)
15002 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15003 (confirm (lambda (x) (stringp (car x)))))
15004 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15005 (setq s1 (match-string 1 string)
15006 s2 (match-string 2 string))
15007 (setq s1 "" s2 string))
15008 (cond
15009 ((eq flag nil)
15010 ;; try completion
15011 (setq rtn (try-completion s2 ctable confirm))
15012 (when (stringp rtn)
15013 (setq rtn
15014 (concat s1 s2 (substring rtn (length s2))
15015 (if (and org-add-colon-after-tag-completion
15016 (assoc rtn ctable))
15017 ":" ""))))
15018 rtn)
15019 ((eq flag t)
15020 ;; all-completions
15021 (all-completions s2 ctable confirm))
15022 ((eq flag 'lambda)
15023 ;; exact match?
15024 (assoc s2 ctable)))))
15026 (defun org-fast-tag-insert (kwd tags face &optional end)
15027 "Insert KDW, and the TAGS, the latter with face FACE.
15028 Also insert END."
15029 (insert (format "%-12s" (concat kwd ":"))
15030 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15031 (or end "")))
15033 (defun org-fast-tag-show-exit (flag)
15034 (save-excursion
15035 (org-goto-line 3)
15036 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15037 (replace-match ""))
15038 (when flag
15039 (end-of-line 1)
15040 (org-move-to-column (- (window-width) 19) t)
15041 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15043 (defun org-set-current-tags-overlay (current prefix)
15044 "Add an overlay to CURRENT tag with PREFIX."
15045 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15046 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15047 (org-overlay-display org-tags-overlay (concat prefix s))))
15049 (defvar org-last-tag-selection-key nil)
15050 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15051 "Fast tag selection with single keys.
15052 CURRENT is the current list of tags in the headline, INHERITED is the
15053 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15054 possibly with grouping information. TODO-TABLE is a similar table with
15055 TODO keywords, should these have keys assigned to them.
15056 If the keys are nil, a-z are automatically assigned.
15057 Returns the new tags string, or nil to not change the current settings."
15058 (let* ((fulltable (append table todo-table))
15059 (maxlen (apply 'max (mapcar
15060 (lambda (x)
15061 (if (stringp (car x)) (string-width (car x)) 0))
15062 fulltable)))
15063 (buf (current-buffer))
15064 (expert (eq org-fast-tag-selection-single-key 'expert))
15065 (buffer-tags nil)
15066 (fwidth (+ maxlen 3 1 3))
15067 (ncol (/ (- (window-width) 4) fwidth))
15068 (i-face 'org-done)
15069 (c-face 'org-todo)
15070 tg cnt e c char c1 c2 ntable tbl rtn
15071 ov-start ov-end ov-prefix
15072 (exit-after-next org-fast-tag-selection-single-key)
15073 (done-keywords org-done-keywords)
15074 groups ingroup intaggroup)
15075 (save-excursion
15076 (beginning-of-line 1)
15077 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15078 (setq ov-start (match-beginning 1)
15079 ov-end (match-end 1)
15080 ov-prefix "")
15081 (setq ov-start (1- (point-at-eol))
15082 ov-end (1+ ov-start))
15083 (skip-chars-forward "^\n\r")
15084 (setq ov-prefix
15085 (concat
15086 (buffer-substring (1- (point)) (point))
15087 (if (> (current-column) org-tags-column)
15089 (make-string (- org-tags-column (current-column)) ?\ ))))))
15090 (move-overlay org-tags-overlay ov-start ov-end)
15091 (save-window-excursion
15092 (if expert
15093 (set-buffer (get-buffer-create " *Org tags*"))
15094 (delete-other-windows)
15095 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15096 (org-switch-to-buffer-other-window " *Org tags*"))
15097 (erase-buffer)
15098 (setq-local org-done-keywords done-keywords)
15099 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15100 (org-fast-tag-insert "Current" current c-face "\n\n")
15101 (org-fast-tag-show-exit exit-after-next)
15102 (org-set-current-tags-overlay current ov-prefix)
15103 (setq tbl fulltable char ?a cnt 0)
15104 (while (setq e (pop tbl))
15105 (cond
15106 ((eq (car e) :startgroup)
15107 (push '() groups) (setq ingroup t)
15108 (unless (zerop cnt)
15109 (setq cnt 0)
15110 (insert "\n"))
15111 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15112 ((eq (car e) :endgroup)
15113 (setq ingroup nil cnt 0)
15114 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15115 ((eq (car e) :startgrouptag)
15116 (setq intaggroup t)
15117 (unless (zerop cnt)
15118 (setq cnt 0)
15119 (insert "\n"))
15120 (insert "[ "))
15121 ((eq (car e) :endgrouptag)
15122 (setq intaggroup nil cnt 0)
15123 (insert "]\n"))
15124 ((equal e '(:newline))
15125 (unless (zerop cnt)
15126 (setq cnt 0)
15127 (insert "\n")
15128 (setq e (car tbl))
15129 (while (equal (car tbl) '(:newline))
15130 (insert "\n")
15131 (setq tbl (cdr tbl)))))
15132 ((equal e '(:grouptags)) (insert " : "))
15134 (setq tg (copy-sequence (car e)) c2 nil)
15135 (if (cdr e)
15136 (setq c (cdr e))
15137 ;; automatically assign a character.
15138 (setq c1 (string-to-char
15139 (downcase (substring
15140 tg (if (= (string-to-char tg) ?@) 1 0)))))
15141 (if (or (rassoc c1 ntable) (rassoc c1 table))
15142 (while (or (rassoc char ntable) (rassoc char table))
15143 (setq char (1+ char)))
15144 (setq c2 c1))
15145 (setq c (or c2 char)))
15146 (when ingroup (push tg (car groups)))
15147 (setq tg (org-add-props tg nil 'face
15148 (cond
15149 ((not (assoc tg table))
15150 (org-get-todo-face tg))
15151 ((member tg current) c-face)
15152 ((member tg inherited) i-face))))
15153 (when (equal (caar tbl) :grouptags)
15154 (org-add-props tg nil 'face 'org-tag-group))
15155 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15156 (insert "[" c "] " tg (make-string
15157 (- fwidth 4 (length tg)) ?\ ))
15158 (push (cons tg c) ntable)
15159 (when (= (cl-incf cnt) ncol)
15160 (insert "\n")
15161 (when (or ingroup intaggroup) (insert " "))
15162 (setq cnt 0)))))
15163 (setq ntable (nreverse ntable))
15164 (insert "\n")
15165 (goto-char (point-min))
15166 (unless expert (org-fit-window-to-buffer))
15167 (setq rtn
15168 (catch 'exit
15169 (while t
15170 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15171 (if (not groups) "no " "")
15172 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15173 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15174 (setq org-last-tag-selection-key c)
15175 (cond
15176 ((= c ?\r) (throw 'exit t))
15177 ((= c ?!)
15178 (setq groups (not groups))
15179 (goto-char (point-min))
15180 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15181 ((= c ?\C-c)
15182 (if (not expert)
15183 (org-fast-tag-show-exit
15184 (setq exit-after-next (not exit-after-next)))
15185 (setq expert nil)
15186 (delete-other-windows)
15187 (set-window-buffer (split-window-vertically) " *Org tags*")
15188 (org-switch-to-buffer-other-window " *Org tags*")
15189 (org-fit-window-to-buffer)))
15190 ((or (= c ?\C-g)
15191 (and (= c ?q) (not (rassoc c ntable))))
15192 (delete-overlay org-tags-overlay)
15193 (setq quit-flag t))
15194 ((= c ?\ )
15195 (setq current nil)
15196 (when exit-after-next (setq exit-after-next 'now)))
15197 ((= c ?\t)
15198 (condition-case nil
15199 (setq tg (completing-read
15200 "Tag: "
15201 (or buffer-tags
15202 (with-current-buffer buf
15203 (setq buffer-tags
15204 (org-get-buffer-tags))))))
15205 (quit (setq tg "")))
15206 (when (string-match "\\S-" tg)
15207 (cl-pushnew (list tg) buffer-tags :test #'equal)
15208 (if (member tg current)
15209 (setq current (delete tg current))
15210 (push tg current)))
15211 (when exit-after-next (setq exit-after-next 'now)))
15212 ((setq e (rassoc c todo-table) tg (car e))
15213 (with-current-buffer buf
15214 (save-excursion (org-todo tg)))
15215 (when exit-after-next (setq exit-after-next 'now)))
15216 ((setq e (rassoc c ntable) tg (car e))
15217 (if (member tg current)
15218 (setq current (delete tg current))
15219 (cl-loop for g in groups do
15220 (when (member tg g)
15221 (dolist (x g) (setq current (delete x current)))))
15222 (push tg current))
15223 (when exit-after-next (setq exit-after-next 'now))))
15225 ;; Create a sorted list
15226 (setq current
15227 (sort current
15228 (lambda (a b)
15229 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15230 (when (eq exit-after-next 'now) (throw 'exit t))
15231 (goto-char (point-min))
15232 (beginning-of-line 2)
15233 (delete-region (point) (point-at-eol))
15234 (org-fast-tag-insert "Current" current c-face)
15235 (org-set-current-tags-overlay current ov-prefix)
15236 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15237 (setq tg (match-string 1))
15238 (add-text-properties
15239 (match-beginning 1) (match-end 1)
15240 (list 'face
15241 (cond
15242 ((member tg current) c-face)
15243 ((member tg inherited) i-face)
15244 (t (get-text-property (match-beginning 1) 'face))))))
15245 (goto-char (point-min)))))
15246 (delete-overlay org-tags-overlay)
15247 (if rtn
15248 (mapconcat 'identity current ":")
15249 nil))))
15251 (defun org-get-tags-string ()
15252 "Get the TAGS string in the current headline."
15253 (unless (org-at-heading-p t)
15254 (user-error "Not on a heading"))
15255 (save-excursion
15256 (beginning-of-line 1)
15257 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15258 (match-string-no-properties 1)
15259 "")))
15261 (defun org-get-tags ()
15262 "Get the list of tags specified in the current headline."
15263 (org-split-string (org-get-tags-string) ":"))
15265 (defun org-get-buffer-tags ()
15266 "Get a table of all tags used in the buffer, for completion."
15267 (org-with-wide-buffer
15268 (goto-char (point-min))
15269 (let ((tag-re (concat org-outline-regexp-bol
15270 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15271 tags)
15272 (while (re-search-forward tag-re nil t)
15273 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15274 (push tag tags)))
15275 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15277 ;;;; The mapping API
15279 (defvar org-agenda-skip-comment-trees)
15280 (defvar org-agenda-skip-function)
15281 (defun org-map-entries (func &optional match scope &rest skip)
15282 "Call FUNC at each headline selected by MATCH in SCOPE.
15284 FUNC is a function or a lisp form. The function will be called without
15285 arguments, with the cursor positioned at the beginning of the headline.
15286 The return values of all calls to the function will be collected and
15287 returned as a list.
15289 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15290 does not need to preserve point. After evaluation, the cursor will be
15291 moved to the end of the line (presumably of the headline of the
15292 processed entry) and search continues from there. Under some
15293 circumstances, this may not produce the wanted results. For example,
15294 if you have removed (e.g. archived) the current (sub)tree it could
15295 mean that the next entry will be skipped entirely. In such cases, you
15296 can specify the position from where search should continue by making
15297 FUNC set the variable `org-map-continue-from' to the desired buffer
15298 position.
15300 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15301 Only headlines that are matched by this query will be considered during
15302 the iteration. When MATCH is nil or t, all headlines will be
15303 visited by the iteration.
15305 SCOPE determines the scope of this command. It can be any of:
15307 nil The current buffer, respecting the restriction if any
15308 tree The subtree started with the entry at point
15309 region The entries within the active region, if any
15310 region-start-level
15311 The entries within the active region, but only those at
15312 the same level than the first one.
15313 file The current buffer, without restriction
15314 file-with-archives
15315 The current buffer, and any archives associated with it
15316 agenda All agenda files
15317 agenda-with-archives
15318 All agenda files with any archive files associated with them
15319 \(file1 file2 ...)
15320 If this is a list, all files in the list will be scanned
15322 The remaining args are treated as settings for the skipping facilities of
15323 the scanner. The following items can be given here:
15325 archive skip trees with the archive tag
15326 comment skip trees with the COMMENT keyword
15327 function or Emacs Lisp form:
15328 will be used as value for `org-agenda-skip-function', so
15329 whenever the function returns a position, FUNC will not be
15330 called for that entry and search will continue from the
15331 position returned
15333 If your function needs to retrieve the tags including inherited tags
15334 at the *current* entry, you can use the value of the variable
15335 `org-scanner-tags' which will be much faster than getting the value
15336 with `org-get-tags-at'. If your function gets properties with
15337 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15338 to t around the call to `org-entry-properties' to get the same speedup.
15339 Note that if your function moves around to retrieve tags and properties at
15340 a *different* entry, you cannot use these techniques."
15341 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15342 (not (org-region-active-p)))
15343 (let* ((org-agenda-archives-mode nil) ; just to make sure
15344 (org-agenda-skip-archived-trees (memq 'archive skip))
15345 (org-agenda-skip-comment-trees (memq 'comment skip))
15346 (org-agenda-skip-function
15347 (car (org-delete-all '(comment archive) skip)))
15348 (org-tags-match-list-sublevels t)
15349 (start-level (eq scope 'region-start-level))
15350 matcher res
15351 org-todo-keywords-for-agenda
15352 org-done-keywords-for-agenda
15353 org-todo-keyword-alist-for-agenda
15354 org-tag-alist-for-agenda
15355 org--matcher-tags-todo-only)
15357 (cond
15358 ((eq match t) (setq matcher t))
15359 ((eq match nil) (setq matcher t))
15360 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15362 (save-excursion
15363 (save-restriction
15364 (cond ((eq scope 'tree)
15365 (org-back-to-heading t)
15366 (org-narrow-to-subtree)
15367 (setq scope nil))
15368 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15369 (org-region-active-p))
15370 ;; If needed, set start-level to a string like "2"
15371 (when start-level
15372 (save-excursion
15373 (goto-char (region-beginning))
15374 (unless (org-at-heading-p) (outline-next-heading))
15375 (setq start-level (org-current-level))))
15376 (narrow-to-region (region-beginning)
15377 (save-excursion
15378 (goto-char (region-end))
15379 (unless (and (bolp) (org-at-heading-p))
15380 (outline-next-heading))
15381 (point)))
15382 (setq scope nil)))
15384 (if (not scope)
15385 (progn
15386 (org-agenda-prepare-buffers
15387 (and buffer-file-name (list buffer-file-name)))
15388 (setq res
15389 (org-scan-tags
15390 func matcher org--matcher-tags-todo-only start-level)))
15391 ;; Get the right scope
15392 (cond
15393 ((and scope (listp scope) (symbolp (car scope)))
15394 (setq scope (eval scope)))
15395 ((eq scope 'agenda)
15396 (setq scope (org-agenda-files t)))
15397 ((eq scope 'agenda-with-archives)
15398 (setq scope (org-agenda-files t))
15399 (setq scope (org-add-archive-files scope)))
15400 ((eq scope 'file)
15401 (setq scope (and buffer-file-name (list buffer-file-name))))
15402 ((eq scope 'file-with-archives)
15403 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15404 (org-agenda-prepare-buffers scope)
15405 (dolist (file scope)
15406 (with-current-buffer (org-find-base-buffer-visiting file)
15407 (org-with-wide-buffer
15408 (goto-char (point-min))
15409 (setq res
15410 (append
15412 (org-scan-tags
15413 func matcher org--matcher-tags-todo-only)))))))))
15414 res)))
15416 ;;; Properties API
15418 (defconst org-special-properties
15419 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15420 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15421 "The special properties valid in Org mode.
15422 These are properties that are not defined in the property drawer,
15423 but in some other way.")
15425 (defconst org-default-properties
15426 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15427 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15428 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15429 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15430 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15431 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15432 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15433 "Some properties that are used by Org mode for various purposes.
15434 Being in this list makes sure that they are offered for completion.")
15436 (defun org--valid-property-p (property)
15437 "Non nil when string PROPERTY is a valid property name."
15438 (not
15439 (or (equal property "")
15440 (string-match-p "\\s-" property))))
15442 (defun org--update-property-plist (key val props)
15443 "Associate KEY to VAL in alist PROPS.
15444 Modifications are made by side-effect. Return new alist."
15445 (let* ((appending (string= (substring key -1) "+"))
15446 (key (if appending (substring key 0 -1) key))
15447 (old (assoc-string key props t)))
15448 (if (not old) (cons (cons key val) props)
15449 (setcdr old (if appending (concat (cdr old) " " val) val))
15450 props)))
15452 (defun org-get-property-block (&optional beg force)
15453 "Return the (beg . end) range of the body of the property drawer.
15454 BEG is the beginning of the current subtree, or of the part
15455 before the first headline. If it is not given, it will be found.
15456 If the drawer does not exist, create it if FORCE is non-nil, or
15457 return nil."
15458 (org-with-wide-buffer
15459 (when beg (goto-char beg))
15460 (unless (org-before-first-heading-p)
15461 (let ((beg (cond (beg)
15462 ((or (not (featurep 'org-inlinetask))
15463 (org-inlinetask-in-task-p))
15464 (org-back-to-heading t))
15465 (t (org-with-limited-levels (org-back-to-heading t))))))
15466 (forward-line)
15467 (when (looking-at-p org-planning-line-re) (forward-line))
15468 (cond ((looking-at org-property-drawer-re)
15469 (forward-line)
15470 (cons (point) (progn (goto-char (match-end 0))
15471 (line-beginning-position))))
15472 (force
15473 (goto-char beg)
15474 (org-insert-property-drawer)
15475 (let ((pos (save-excursion (search-forward ":END:")
15476 (line-beginning-position))))
15477 (cons pos pos))))))))
15479 (defun org-at-property-p ()
15480 "Non-nil when point is inside a property drawer.
15481 See `org-property-re' for match data, if applicable."
15482 (save-excursion
15483 (beginning-of-line)
15484 (and (looking-at org-property-re)
15485 (let ((property-drawer (save-match-data (org-get-property-block))))
15486 (and property-drawer
15487 (>= (point) (car property-drawer))
15488 (< (point) (cdr property-drawer)))))))
15490 (defun org-property-action ()
15491 "Do an action on properties."
15492 (interactive)
15493 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15494 (let ((c (read-char-exclusive)))
15495 (cl-case c
15496 (?s (call-interactively #'org-set-property))
15497 (?d (call-interactively #'org-delete-property))
15498 (?D (call-interactively #'org-delete-property-globally))
15499 (?c (call-interactively #'org-compute-property-at-point))
15500 (otherwise (user-error "No such property action %c" c)))))
15502 (defun org-inc-effort ()
15503 "Increment the value of the effort property in the current entry."
15504 (interactive)
15505 (org-set-effort nil t))
15507 (defvar org-clock-effort) ; Defined in org-clock.el.
15508 (defvar org-clock-current-task) ; Defined in org-clock.el.
15509 (defun org-set-effort (&optional value increment)
15510 "Set the effort property of the current entry.
15511 With numerical prefix arg, use the nth allowed value, 0 stands for the
15512 10th allowed value.
15514 When INCREMENT is non-nil, set the property to the next allowed value."
15515 (interactive "P")
15516 (when (equal value 0) (setq value 10))
15517 (let* ((completion-ignore-case t)
15518 (prop org-effort-property)
15519 (cur (org-entry-get nil prop))
15520 (allowed (org-property-get-allowed-values nil prop 'table))
15521 (existing (mapcar 'list (org-property-values prop)))
15522 (heading (nth 4 (org-heading-components)))
15524 (val (cond
15525 ((stringp value) value)
15526 ((and allowed (integerp value))
15527 (or (car (nth (1- value) allowed))
15528 (car (org-last allowed))))
15529 ((and allowed increment)
15530 (or (cl-caadr (member (list cur) allowed))
15531 (user-error "Allowed effort values are not set")))
15532 (allowed
15533 (message "Select 1-9,0, [RET%s]: %s"
15534 (if cur (concat "=" cur) "")
15535 (mapconcat 'car allowed " "))
15536 (setq rpl (read-char-exclusive))
15537 (if (equal rpl ?\r)
15539 (setq rpl (- rpl ?0))
15540 (when (equal rpl 0) (setq rpl 10))
15541 (if (and (> rpl 0) (<= rpl (length allowed)))
15542 (car (nth (1- rpl) allowed))
15543 (org-completing-read "Effort: " allowed nil))))
15545 (org-completing-read
15546 (concat "Effort" (and cur (string-match "\\S-" cur)
15547 (concat " [" cur "]"))
15548 ": ")
15549 existing nil nil "" nil cur)))))
15550 (unless (equal (org-entry-get nil prop) val)
15551 (org-entry-put nil prop val))
15552 (org-refresh-property
15553 '((effort . identity)
15554 (effort-minutes . org-duration-to-minutes))
15555 val)
15556 (when (equal heading (bound-and-true-p org-clock-current-task))
15557 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15558 (org-clock-update-mode-line))
15559 (message "%s is now %s" prop val)))
15561 (defun org-entry-properties (&optional pom which)
15562 "Get all properties of the current entry.
15564 When POM is a buffer position, get all properties from the entry
15565 there instead.
15567 This includes the TODO keyword, the tags, time strings for
15568 deadline, scheduled, and clocking, and any additional properties
15569 defined in the entry.
15571 If WHICH is nil or `all', get all properties. If WHICH is
15572 `special' or `standard', only get that subclass. If WHICH is
15573 a string, only get that property.
15575 Return value is an alist. Keys are properties, as upcased
15576 strings."
15577 (org-with-point-at pom
15578 (when (and (derived-mode-p 'org-mode)
15579 (ignore-errors (org-back-to-heading t)))
15580 (catch 'exit
15581 (let* ((beg (point))
15582 (specific (and (stringp which) (upcase which)))
15583 (which (cond ((not specific) which)
15584 ((member specific org-special-properties) 'special)
15585 (t 'standard)))
15586 props)
15587 ;; Get the special properties, like TODO and TAGS.
15588 (when (memq which '(nil all special))
15589 (when (or (not specific) (string= specific "CLOCKSUM"))
15590 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15591 (when clocksum
15592 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15593 props)))
15594 (when specific (throw 'exit props)))
15595 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15596 (let ((clocksumt (get-text-property (point)
15597 :org-clock-minutes-today)))
15598 (when clocksumt
15599 (push (cons "CLOCKSUM_T"
15600 (org-duration-from-minutes clocksumt))
15601 props)))
15602 (when specific (throw 'exit props)))
15603 (when (or (not specific) (string= specific "ITEM"))
15604 (let ((case-fold-search nil))
15605 (when (looking-at org-complex-heading-regexp)
15606 (push (cons "ITEM"
15607 (let ((title (match-string-no-properties 4)))
15608 (if (org-string-nw-p title)
15609 (org-remove-tabs title)
15610 "")))
15611 props)))
15612 (when specific (throw 'exit props)))
15613 (when (or (not specific) (string= specific "TODO"))
15614 (let ((case-fold-search nil))
15615 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15616 (push (cons "TODO" (match-string-no-properties 2)) props)))
15617 (when specific (throw 'exit props)))
15618 (when (or (not specific) (string= specific "PRIORITY"))
15619 (push (cons "PRIORITY"
15620 (if (looking-at org-priority-regexp)
15621 (match-string-no-properties 2)
15622 (char-to-string org-default-priority)))
15623 props)
15624 (when specific (throw 'exit props)))
15625 (when (or (not specific) (string= specific "FILE"))
15626 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15627 props)
15628 (when specific (throw 'exit props)))
15629 (when (or (not specific) (string= specific "TAGS"))
15630 (let ((value (org-string-nw-p (org-get-tags-string))))
15631 (when value (push (cons "TAGS" value) props)))
15632 (when specific (throw 'exit props)))
15633 (when (or (not specific) (string= specific "ALLTAGS"))
15634 (let ((value (org-get-tags-at)))
15635 (when value
15636 (push (cons "ALLTAGS"
15637 (format ":%s:" (mapconcat #'identity value ":")))
15638 props)))
15639 (when specific (throw 'exit props)))
15640 (when (or (not specific) (string= specific "BLOCKED"))
15641 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific)
15644 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15645 (forward-line)
15646 (when (looking-at-p org-planning-line-re)
15647 (end-of-line)
15648 (let ((bol (line-beginning-position))
15649 ;; Backward compatibility: time keywords used to
15650 ;; be configurable (before 8.3). Make sure we
15651 ;; get the correct keyword.
15652 (key-assoc `(("CLOSED" . ,org-closed-string)
15653 ("DEADLINE" . ,org-deadline-string)
15654 ("SCHEDULED" . ,org-scheduled-string))))
15655 (dolist (pair (if specific (list (assoc specific key-assoc))
15656 key-assoc))
15657 (save-excursion
15658 (when (search-backward (cdr pair) bol t)
15659 (goto-char (match-end 0))
15660 (skip-chars-forward " \t")
15661 (and (looking-at org-ts-regexp-both)
15662 (push (cons (car pair)
15663 (match-string-no-properties 0))
15664 props)))))))
15665 (when specific (throw 'exit props)))
15666 (when (or (not specific)
15667 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15668 (let ((find-ts
15669 (lambda (end ts)
15670 ;; Fix next time-stamp before END. TS is the
15671 ;; list of time-stamps found so far.
15672 (let ((ts ts)
15673 (regexp (cond
15674 ((string= specific "TIMESTAMP")
15675 org-ts-regexp)
15676 ((string= specific "TIMESTAMP_IA")
15677 org-ts-regexp-inactive)
15678 ((assoc "TIMESTAMP_IA" ts)
15679 org-ts-regexp)
15680 ((assoc "TIMESTAMP" ts)
15681 org-ts-regexp-inactive)
15682 (t org-ts-regexp-both))))
15683 (catch 'next
15684 (while (re-search-forward regexp end t)
15685 (backward-char)
15686 (let ((object (org-element-context)))
15687 ;; Accept to match timestamps in node
15688 ;; properties, too.
15689 (when (memq (org-element-type object)
15690 '(node-property timestamp))
15691 (let ((type
15692 (org-element-property :type object)))
15693 (cond
15694 ((and (memq type '(active active-range))
15695 (not (equal specific "TIMESTAMP_IA")))
15696 (unless (assoc "TIMESTAMP" ts)
15697 (push (cons "TIMESTAMP"
15698 (org-element-property
15699 :raw-value object))
15701 (when specific (throw 'exit ts))))
15702 ((and (memq type '(inactive inactive-range))
15703 (not (string= specific "TIMESTAMP")))
15704 (unless (assoc "TIMESTAMP_IA" ts)
15705 (push (cons "TIMESTAMP_IA"
15706 (org-element-property
15707 :raw-value object))
15709 (when specific (throw 'exit ts))))))
15710 ;; Both timestamp types are found,
15711 ;; move to next part.
15712 (when (= (length ts) 2) (throw 'next ts)))))
15713 ts)))))
15714 (goto-char beg)
15715 ;; First look for timestamps within headline.
15716 (let ((ts (funcall find-ts (line-end-position) nil)))
15717 (if (= (length ts) 2) (setq props (nconc ts props))
15718 ;; Then find timestamps in the section, skipping
15719 ;; planning line.
15720 (let ((end (save-excursion (outline-next-heading))))
15721 (forward-line)
15722 (when (looking-at-p org-planning-line-re) (forward-line))
15723 (setq props (nconc (funcall find-ts end ts) props))))))))
15724 ;; Get the standard properties, like :PROP:.
15725 (when (memq which '(nil all standard))
15726 ;; If we are looking after a specific property, delegate
15727 ;; to `org-entry-get', which is faster. However, make an
15728 ;; exception for "CATEGORY", since it can be also set
15729 ;; through keywords (i.e. #+CATEGORY).
15730 (if (and specific (not (equal specific "CATEGORY")))
15731 (let ((value (org-entry-get beg specific nil t)))
15732 (throw 'exit (and value (list (cons specific value)))))
15733 (let ((range (org-get-property-block beg)))
15734 (when range
15735 (let ((end (cdr range)) seen-base)
15736 (goto-char (car range))
15737 ;; Unlike to `org--update-property-plist', we
15738 ;; handle the case where base values is found
15739 ;; after its extension. We also forbid standard
15740 ;; properties to be named as special properties.
15741 (while (re-search-forward org-property-re end t)
15742 (let* ((key (upcase (match-string-no-properties 2)))
15743 (extendp (string-match-p "\\+\\'" key))
15744 (key-base (if extendp (substring key 0 -1) key))
15745 (value (match-string-no-properties 3)))
15746 (cond
15747 ((member-ignore-case key-base org-special-properties))
15748 (extendp
15749 (setq props
15750 (org--update-property-plist key value props)))
15751 ((member key seen-base))
15752 (t (push key seen-base)
15753 (let ((p (assoc-string key props t)))
15754 (if p (setcdr p (concat value " " (cdr p)))
15755 (push (cons key value) props))))))))))))
15756 (unless (assoc "CATEGORY" props)
15757 (push (cons "CATEGORY" (org-get-category beg)) props)
15758 (when (string= specific "CATEGORY") (throw 'exit props)))
15759 ;; Return value.
15760 props)))))
15762 (defun org--property-local-values (property literal-nil)
15763 "Return value for PROPERTY in current entry.
15764 Value is a list whose car is the base value for PROPERTY and cdr
15765 a list of accumulated values. Return nil if neither is found in
15766 the entry. Also return nil when PROPERTY is set to \"nil\",
15767 unless LITERAL-NIL is non-nil."
15768 (let ((range (org-get-property-block)))
15769 (when range
15770 (goto-char (car range))
15771 (let* ((case-fold-search t)
15772 (end (cdr range))
15773 (value
15774 ;; Base value.
15775 (save-excursion
15776 (let ((v (and (re-search-forward
15777 (org-re-property property nil t) end t)
15778 (match-string-no-properties 3))))
15779 (list (if literal-nil v (org-not-nil v)))))))
15780 ;; Find additional values.
15781 (let* ((property+ (org-re-property (concat property "+") nil t)))
15782 (while (re-search-forward property+ end t)
15783 (push (match-string-no-properties 3) value)))
15784 ;; Return final values.
15785 (and (not (equal value '(nil))) (nreverse value))))))
15787 (defun org--property-global-value (property literal-nil)
15788 "Return value for PROPERTY in current buffer.
15789 Return value is a string. Return nil if property is not set
15790 globally. Also return nil when PROPERTY is set to \"nil\",
15791 unless LITERAL-NIL is non-nil."
15792 (let ((global
15793 (cdr (or (assoc-string property org-file-properties t)
15794 (assoc-string property org-global-properties t)
15795 (assoc-string property org-global-properties-fixed t)))))
15796 (if literal-nil global (org-not-nil global))))
15798 (defun org-entry-get (pom property &optional inherit literal-nil)
15799 "Get value of PROPERTY for entry or content at point-or-marker POM.
15801 If INHERIT is non-nil and the entry does not have the property,
15802 then also check higher levels of the hierarchy. If INHERIT is
15803 the symbol `selective', use inheritance only if the setting in
15804 `org-use-property-inheritance' selects PROPERTY for inheritance.
15806 If the property is present but empty, the return value is the
15807 empty string. If the property is not present at all, nil is
15808 returned. In any other case, return the value as a string.
15809 Search is case-insensitive.
15811 If LITERAL-NIL is set, return the string value \"nil\" as
15812 a string, do not interpret it as the list atom nil. This is used
15813 for inheritance when a \"nil\" value can supersede a non-nil
15814 value higher up the hierarchy."
15815 (org-with-point-at pom
15816 (cond
15817 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15818 ;; We need a special property. Use `org-entry-properties' to
15819 ;; retrieve it, but specify the wanted property.
15820 (cdr (assoc-string property (org-entry-properties nil property))))
15821 ((and inherit
15822 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15823 (org-entry-get-with-inheritance property literal-nil))
15825 (let* ((local (org--property-local-values property literal-nil))
15826 (value (and local (mapconcat #'identity (delq nil local) " "))))
15827 (if literal-nil value (org-not-nil value)))))))
15829 (defun org-property-or-variable-value (var &optional inherit)
15830 "Check if there is a property fixing the value of VAR.
15831 If yes, return this value. If not, return the current value of the variable."
15832 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15833 (if (and prop (stringp prop) (string-match "\\S-" prop))
15834 (read prop)
15835 (symbol-value var))))
15837 (defun org-entry-delete (pom property)
15838 "Delete PROPERTY from entry at point-or-marker POM.
15839 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15840 non-nil when a property was removed."
15841 (org-with-point-at pom
15842 (pcase (org-get-property-block)
15843 (`(,begin . ,origin)
15844 (let* ((end (copy-marker origin))
15845 (re (org-re-property
15846 (concat (regexp-quote property) "\\+?") t t)))
15847 (goto-char begin)
15848 (while (re-search-forward re end t)
15849 (delete-region (match-beginning 0) (line-beginning-position 2)))
15850 ;; If drawer is empty, remove it altogether.
15851 (when (= begin end)
15852 (delete-region (line-beginning-position 0)
15853 (line-beginning-position 2)))
15854 ;; Return non-nil if some property was removed.
15855 (prog1 (/= end origin) (set-marker end nil))))
15856 (_ nil))))
15858 ;; Multi-values properties are properties that contain multiple values
15859 ;; These values are assumed to be single words, separated by whitespace.
15860 (defun org-entry-add-to-multivalued-property (pom property value)
15861 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15862 (let* ((old (org-entry-get pom property))
15863 (values (and old (org-split-string old "[ \t]"))))
15864 (setq value (org-entry-protect-space value))
15865 (unless (member value values)
15866 (setq values (append values (list value)))
15867 (org-entry-put pom property
15868 (mapconcat 'identity values " ")))))
15870 (defun org-entry-remove-from-multivalued-property (pom property value)
15871 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15872 (let* ((old (org-entry-get pom property))
15873 (values (and old (org-split-string old "[ \t]"))))
15874 (setq value (org-entry-protect-space value))
15875 (when (member value values)
15876 (setq values (delete value values))
15877 (org-entry-put pom property
15878 (mapconcat 'identity values " ")))))
15880 (defun org-entry-member-in-multivalued-property (pom property value)
15881 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15882 (let* ((old (org-entry-get pom property))
15883 (values (and old (org-split-string old "[ \t]"))))
15884 (setq value (org-entry-protect-space value))
15885 (member value values)))
15887 (defun org-entry-get-multivalued-property (pom property)
15888 "Return a list of values in a multivalued property."
15889 (let* ((value (org-entry-get pom property))
15890 (values (and value (org-split-string value "[ \t]"))))
15891 (mapcar 'org-entry-restore-space values)))
15893 (defun org-entry-put-multivalued-property (pom property &rest values)
15894 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15895 VALUES should be a list of strings. Spaces will be protected."
15896 (org-entry-put pom property
15897 (mapconcat 'org-entry-protect-space values " "))
15898 (let* ((value (org-entry-get pom property))
15899 (values (and value (org-split-string value "[ \t]"))))
15900 (mapcar 'org-entry-restore-space values)))
15902 (defun org-entry-protect-space (s)
15903 "Protect spaces and newline in string S."
15904 (while (string-match " " s)
15905 (setq s (replace-match "%20" t t s)))
15906 (while (string-match "\n" s)
15907 (setq s (replace-match "%0A" t t s)))
15910 (defun org-entry-restore-space (s)
15911 "Restore spaces and newline in string S."
15912 (while (string-match "%20" s)
15913 (setq s (replace-match " " t t s)))
15914 (while (string-match "%0A" s)
15915 (setq s (replace-match "\n" t t s)))
15918 (defvar org-entry-property-inherited-from (make-marker)
15919 "Marker pointing to the entry from where a property was inherited.
15920 Each call to `org-entry-get-with-inheritance' will set this marker to the
15921 location of the entry where the inheritance search matched. If there was
15922 no match, the marker will point nowhere.
15923 Note that also `org-entry-get' calls this function, if the INHERIT flag
15924 is set.")
15926 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15927 "Get PROPERTY of entry or content at point, search higher levels if needed.
15928 The search will stop at the first ancestor which has the property defined.
15929 If the value found is \"nil\", return nil to show that the property
15930 should be considered as undefined (this is the meaning of nil here).
15931 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15932 (move-marker org-entry-property-inherited-from nil)
15933 (org-with-wide-buffer
15934 (let (value)
15935 (catch 'exit
15936 (while t
15937 (let ((v (org--property-local-values property literal-nil)))
15938 (when v
15939 (setq value
15940 (concat (mapconcat #'identity (delq nil v) " ")
15941 (and value " ")
15942 value)))
15943 (cond
15944 ((car v)
15945 (org-back-to-heading t)
15946 (move-marker org-entry-property-inherited-from (point))
15947 (throw 'exit nil))
15948 ((org-up-heading-safe))
15950 (let ((global (org--property-global-value property literal-nil)))
15951 (cond ((not global))
15952 (value (setq value (concat global " " value)))
15953 (t (setq value global))))
15954 (throw 'exit nil))))))
15955 (if literal-nil value (org-not-nil value)))))
15957 (defvar org-property-changed-functions nil
15958 "Hook called when the value of a property has changed.
15959 Each hook function should accept two arguments, the name of the property
15960 and the new value.")
15962 (defun org-entry-put (pom property value)
15963 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15965 If the value is nil, it is converted to the empty string. If it
15966 is not a string, an error is raised. Also raise an error on
15967 invalid property names.
15969 PROPERTY can be any regular property (see
15970 `org-special-properties'). It can also be \"TODO\",
15971 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15973 For the last two properties, VALUE may have any of the special
15974 values \"earlier\" and \"later\". The function then increases or
15975 decreases scheduled or deadline date by one day."
15976 (cond ((null value) (setq value ""))
15977 ((not (stringp value)) (error "Properties values should be strings"))
15978 ((not (org--valid-property-p property))
15979 (user-error "Invalid property name: \"%s\"" property)))
15980 (org-with-point-at pom
15981 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15982 (org-back-to-heading t)
15983 (org-with-limited-levels (org-back-to-heading t)))
15984 (let ((beg (point)))
15985 (cond
15986 ((equal property "TODO")
15987 (cond ((not (org-string-nw-p value)) (setq value 'none))
15988 ((not (member value org-todo-keywords-1))
15989 (user-error "\"%s\" is not a valid TODO state" value)))
15990 (org-todo value)
15991 (org-set-tags nil 'align))
15992 ((equal property "PRIORITY")
15993 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15994 (org-set-tags nil 'align))
15995 ((equal property "SCHEDULED")
15996 (forward-line)
15997 (if (and (looking-at-p org-planning-line-re)
15998 (re-search-forward
15999 org-scheduled-time-regexp (line-end-position) t))
16000 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16001 ((string= value "later") (org-timestamp-change 1 'day))
16002 ((string= value "") (org-schedule '(4)))
16003 (t (org-schedule nil value)))
16004 (if (member value '("earlier" "later" ""))
16005 (call-interactively #'org-schedule)
16006 (org-schedule nil value))))
16007 ((equal property "DEADLINE")
16008 (forward-line)
16009 (if (and (looking-at-p org-planning-line-re)
16010 (re-search-forward
16011 org-deadline-time-regexp (line-end-position) t))
16012 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16013 ((string= value "later") (org-timestamp-change 1 'day))
16014 ((string= value "") (org-deadline '(4)))
16015 (t (org-deadline nil value)))
16016 (if (member value '("earlier" "later" ""))
16017 (call-interactively #'org-deadline)
16018 (org-deadline nil value))))
16019 ((member property org-special-properties)
16020 (error "The %s property cannot be set with `org-entry-put'" property))
16022 (let* ((range (org-get-property-block beg 'force))
16023 (end (cdr range))
16024 (case-fold-search t))
16025 (goto-char (car range))
16026 (if (re-search-forward (org-re-property property nil t) end t)
16027 (progn (delete-region (match-beginning 0) (match-end 0))
16028 (goto-char (match-beginning 0)))
16029 (goto-char end)
16030 (insert "\n")
16031 (backward-char))
16032 (insert ":" property ":")
16033 (when value (insert " " value))
16034 (org-indent-line)))))
16035 (run-hook-with-args 'org-property-changed-functions property value)))
16037 (defun org-buffer-property-keys
16038 (&optional specials defaults columns ignore-malformed)
16039 "Get all property keys in the current buffer.
16041 When SPECIALS is non-nil, also list the special properties that
16042 reflect things like tags and TODO state.
16044 When DEFAULTS is non-nil, also include properties that has
16045 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16046 DESCRIPTION, LOCATION, and LOGGING and others.
16048 When COLUMNS in non-nil, also include property names given in
16049 COLUMN formats in the current buffer.
16051 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16052 automatically performed, such drawers will be silently ignored."
16053 (let ((case-fold-search t)
16054 (props (append
16055 (and specials org-special-properties)
16056 (and defaults (cons org-effort-property org-default-properties))
16057 nil)))
16058 (org-with-wide-buffer
16059 (goto-char (point-min))
16060 (while (re-search-forward org-property-start-re nil t)
16061 (let ((range (org-get-property-block)))
16062 (catch 'skip
16063 (unless range
16064 (when (and (not ignore-malformed)
16065 (not (org-before-first-heading-p))
16066 (y-or-n-p (format "Malformed drawer at %d, repair?"
16067 (line-beginning-position))))
16068 (org-get-property-block nil t))
16069 (throw 'skip nil))
16070 (goto-char (car range))
16071 (let ((begin (car range))
16072 (end (cdr range)))
16073 ;; Make sure that found property block is not located
16074 ;; before current point, as it would generate an infloop.
16075 ;; It can happen, for example, in the following
16076 ;; situation:
16078 ;; * Headline
16079 ;; :PROPERTIES:
16080 ;; ...
16081 ;; :END:
16082 ;; *************** Inlinetask
16083 ;; #+BEGIN_EXAMPLE
16084 ;; :PROPERTIES:
16085 ;; #+END_EXAMPLE
16087 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16088 (while (< (point) end)
16089 (let ((p (progn (looking-at org-property-re)
16090 (match-string-no-properties 2))))
16091 ;; Only add true property name, not extension symbol.
16092 (push (if (not (string-match-p "\\+\\'" p)) p
16093 (substring p 0 -1))
16094 props))
16095 (forward-line))))
16096 (outline-next-heading)))
16097 (when columns
16098 (goto-char (point-min))
16099 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16100 (let ((element (org-element-at-point)))
16101 (when (memq (org-element-type element) '(keyword node-property))
16102 (let ((value (org-element-property :value element))
16103 (start 0))
16104 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16105 (setq start (match-end 0))
16106 (let ((p (match-string-no-properties 1 value)))
16107 (unless (member-ignore-case p org-special-properties)
16108 (push p props))))))))))
16109 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16111 (defun org-property-values (key)
16112 "List all non-nil values of property KEY in current buffer."
16113 (org-with-wide-buffer
16114 (goto-char (point-min))
16115 (let ((case-fold-search t)
16116 (re (org-re-property key))
16117 values)
16118 (while (re-search-forward re nil t)
16119 (push (org-entry-get (point) key) values))
16120 (delete-dups values))))
16122 (defun org-insert-property-drawer ()
16123 "Insert a property drawer into the current entry."
16124 (org-with-wide-buffer
16125 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16126 (org-back-to-heading t)
16127 (org-with-limited-levels (org-back-to-heading t)))
16128 (forward-line)
16129 (when (looking-at-p org-planning-line-re) (forward-line))
16130 (unless (looking-at-p org-property-drawer-re)
16131 ;; Make sure we start editing a line from current entry, not from
16132 ;; next one. It prevents extending text properties or overlays
16133 ;; belonging to the latter.
16134 (when (bolp) (backward-char))
16135 (let ((begin (1+ (point)))
16136 (inhibit-read-only t))
16137 (insert "\n:PROPERTIES:\n:END:")
16138 (when (eobp) (insert "\n"))
16139 (org-indent-region begin (point))))))
16141 (defun org-insert-drawer (&optional arg drawer)
16142 "Insert a drawer at point.
16144 When optional argument ARG is non-nil, insert a property drawer.
16146 Optional argument DRAWER, when non-nil, is a string representing
16147 drawer's name. Otherwise, the user is prompted for a name.
16149 If a region is active, insert the drawer around that region
16150 instead.
16152 Point is left between drawer's boundaries."
16153 (interactive "P")
16154 (let* ((drawer (if arg "PROPERTIES"
16155 (or drawer (read-from-minibuffer "Drawer: ")))))
16156 (cond
16157 ;; With C-u, fall back on `org-insert-property-drawer'
16158 (arg (org-insert-property-drawer))
16159 ;; Check validity of suggested drawer's name.
16160 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16161 (user-error "Invalid drawer name"))
16162 ;; With an active region, insert a drawer at point.
16163 ((not (org-region-active-p))
16164 (progn
16165 (unless (bolp) (insert "\n"))
16166 (insert (format ":%s:\n\n:END:\n" drawer))
16167 (forward-line -2)))
16168 ;; Otherwise, insert the drawer at point
16170 (let ((rbeg (region-beginning))
16171 (rend (copy-marker (region-end))))
16172 (unwind-protect
16173 (progn
16174 (goto-char rbeg)
16175 (beginning-of-line)
16176 (when (save-excursion
16177 (re-search-forward org-outline-regexp-bol rend t))
16178 (user-error "Drawers cannot contain headlines"))
16179 ;; Position point at the beginning of the first
16180 ;; non-blank line in region. Insert drawer's opening
16181 ;; there, then indent it.
16182 (org-skip-whitespace)
16183 (beginning-of-line)
16184 (insert ":" drawer ":\n")
16185 (forward-line -1)
16186 (indent-for-tab-command)
16187 ;; Move point to the beginning of the first blank line
16188 ;; after the last non-blank line in region. Insert
16189 ;; drawer's closing, then indent it.
16190 (goto-char rend)
16191 (skip-chars-backward " \r\t\n")
16192 (insert "\n:END:")
16193 (deactivate-mark t)
16194 (indent-for-tab-command)
16195 (unless (eolp) (insert "\n")))
16196 ;; Clear marker, whatever the outcome of insertion is.
16197 (set-marker rend nil)))))))
16199 (defvar org-property-set-functions-alist nil
16200 "Property set function alist.
16201 Each entry should have the following format:
16203 (PROPERTY . READ-FUNCTION)
16205 The read function will be called with the same argument as
16206 `org-completing-read'.")
16208 (defun org-set-property-function (property)
16209 "Get the function that should be used to set PROPERTY.
16210 This is computed according to `org-property-set-functions-alist'."
16211 (or (cdr (assoc property org-property-set-functions-alist))
16212 'org-completing-read))
16214 (defun org-read-property-value (property)
16215 "Read PROPERTY value from user."
16216 (let* ((completion-ignore-case t)
16217 (allowed (org-property-get-allowed-values nil property 'table))
16218 (cur (org-entry-get nil property))
16219 (prompt (concat property " value"
16220 (if (and cur (string-match "\\S-" cur))
16221 (concat " [" cur "]") "") ": "))
16222 (set-function (org-set-property-function property))
16223 (val (if allowed
16224 (funcall set-function prompt allowed nil
16225 (not (get-text-property 0 'org-unrestricted
16226 (caar allowed))))
16227 (funcall set-function prompt
16228 (mapcar 'list (org-property-values property))
16229 nil nil "" nil cur))))
16230 (org-trim val)))
16232 (defvar org-last-set-property nil)
16233 (defvar org-last-set-property-value nil)
16234 (defun org-read-property-name ()
16235 "Read a property name."
16236 (let ((completion-ignore-case t)
16237 (default-prop (or (and (org-at-property-p)
16238 (match-string-no-properties 2))
16239 org-last-set-property)))
16240 (org-completing-read
16241 (concat "Property"
16242 (if default-prop (concat " [" default-prop "]") "")
16243 ": ")
16244 (mapcar #'list (org-buffer-property-keys nil t t))
16245 nil nil nil nil default-prop)))
16247 (defun org-set-property-and-value (use-last)
16248 "Allow to set [PROPERTY]: [value] direction from prompt.
16249 When use-default, don't even ask, just use the last
16250 \"[PROPERTY]: [value]\" string from the history."
16251 (interactive "P")
16252 (let* ((completion-ignore-case t)
16253 (pv (or (and use-last org-last-set-property-value)
16254 (org-completing-read
16255 "Enter a \"[Property]: [value]\" pair: "
16256 nil nil nil nil nil
16257 org-last-set-property-value)))
16258 prop val)
16259 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16260 (setq prop (match-string 1 pv)
16261 val (match-string 2 pv))
16262 (org-set-property prop val))))
16264 (defun org-set-property (property value)
16265 "In the current entry, set PROPERTY to VALUE.
16267 When called interactively, this will prompt for a property name, offering
16268 completion on existing and default properties. And then it will prompt
16269 for a value, offering completion either on allowed values (via an inherited
16270 xxx_ALL property) or on existing values in other instances of this property
16271 in the current file.
16273 Throw an error when trying to set a property with an invalid name."
16274 (interactive (list nil nil))
16275 (let ((property (or property (org-read-property-name))))
16276 ;; `org-entry-put' also makes the following check, but this one
16277 ;; avoids polluting `org-last-set-property' and
16278 ;; `org-last-set-property-value' needlessly.
16279 (unless (org--valid-property-p property)
16280 (user-error "Invalid property name: \"%s\"" property))
16281 (let ((value (or value (org-read-property-value property)))
16282 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16283 (setq org-last-set-property property)
16284 (setq org-last-set-property-value (concat property ": " value))
16285 ;; Possibly postprocess the inserted value:
16286 (when fn (setq value (funcall fn value)))
16287 (unless (equal (org-entry-get nil property) value)
16288 (org-entry-put nil property value)))))
16290 (defun org-find-property (property &optional value)
16291 "Find first entry in buffer that sets PROPERTY.
16293 When optional argument VALUE is non-nil, only consider an entry
16294 if it contains PROPERTY set to this value. If PROPERTY should be
16295 explicitly set to nil, use string \"nil\" for VALUE.
16297 Return position where the entry begins, or nil if there is no
16298 such entry. If narrowing is in effect, only search the visible
16299 part of the buffer."
16300 (save-excursion
16301 (goto-char (point-min))
16302 (let ((case-fold-search t)
16303 (re (org-re-property property nil (not value) value)))
16304 (catch 'exit
16305 (while (re-search-forward re nil t)
16306 (when (if value (org-at-property-p)
16307 (org-entry-get (point) property nil t))
16308 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16310 (defun org-delete-property (property)
16311 "In the current entry, delete PROPERTY."
16312 (interactive
16313 (let* ((completion-ignore-case t)
16314 (cat (org-entry-get (point) "CATEGORY"))
16315 (props0 (org-entry-properties nil 'standard))
16316 (props (if cat props0
16317 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16318 (prop (if (< 1 (length props))
16319 (completing-read "Property: " props nil t)
16320 (caar props))))
16321 (list prop)))
16322 (if (not property)
16323 (message "No property to delete in this entry")
16324 (org-entry-delete nil property)
16325 (message "Property \"%s\" deleted" property)))
16327 (defun org-delete-property-globally (property)
16328 "Remove PROPERTY globally, from all entries.
16329 This function ignores narrowing, if any."
16330 (interactive
16331 (let* ((completion-ignore-case t)
16332 (prop (completing-read
16333 "Globally remove property: "
16334 (mapcar #'list (org-buffer-property-keys)))))
16335 (list prop)))
16336 (org-with-wide-buffer
16337 (goto-char (point-min))
16338 (let ((count 0)
16339 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16340 (while (re-search-forward re nil t)
16341 (when (org-entry-delete (point) property) (cl-incf count)))
16342 (message "Property \"%s\" removed from %d entries" property count))))
16344 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16346 (defun org-compute-property-at-point ()
16347 "Compute the property at point.
16348 This looks for an enclosing column format, extracts the operator and
16349 then applies it to the property in the column format's scope."
16350 (interactive)
16351 (unless (org-at-property-p)
16352 (user-error "Not at a property"))
16353 (let ((prop (match-string-no-properties 2)))
16354 (org-columns-get-format-and-top-level)
16355 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16356 (user-error "No operator defined for property %s" prop))
16357 (org-columns-compute prop)))
16359 (defvar org-property-allowed-value-functions nil
16360 "Hook for functions supplying allowed values for a specific property.
16361 The functions must take a single argument, the name of the property, and
16362 return a flat list of allowed values. If \":ETC\" is one of
16363 the values, this means that these values are intended as defaults for
16364 completion, but that other values should be allowed too.
16365 The functions must return nil if they are not responsible for this
16366 property.")
16368 (defun org-property-get-allowed-values (pom property &optional table)
16369 "Get allowed values for the property PROPERTY.
16370 When TABLE is non-nil, return an alist that can directly be used for
16371 completion."
16372 (let (vals)
16373 (cond
16374 ((equal property "TODO")
16375 (setq vals (org-with-point-at pom
16376 (append org-todo-keywords-1 '("")))))
16377 ((equal property "PRIORITY")
16378 (let ((n org-lowest-priority))
16379 (while (>= n org-highest-priority)
16380 (push (char-to-string n) vals)
16381 (setq n (1- n)))))
16382 ((equal property "CATEGORY"))
16383 ((member property org-special-properties))
16384 ((setq vals (run-hook-with-args-until-success
16385 'org-property-allowed-value-functions property)))
16387 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16388 (when (and vals (string-match "\\S-" vals))
16389 (setq vals (car (read-from-string (concat "(" vals ")"))))
16390 (setq vals (mapcar (lambda (x)
16391 (cond ((stringp x) x)
16392 ((numberp x) (number-to-string x))
16393 ((symbolp x) (symbol-name x))
16394 (t "???")))
16395 vals)))))
16396 (when (member ":ETC" vals)
16397 (setq vals (remove ":ETC" vals))
16398 (org-add-props (car vals) '(org-unrestricted t)))
16399 (if table (mapcar 'list vals) vals)))
16401 (defun org-property-previous-allowed-value (&optional _previous)
16402 "Switch to the next allowed value for this property."
16403 (interactive)
16404 (org-property-next-allowed-value t))
16406 (defun org-property-next-allowed-value (&optional previous)
16407 "Switch to the next allowed value for this property."
16408 (interactive)
16409 (unless (org-at-property-p)
16410 (user-error "Not at a property"))
16411 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16412 (key (match-string 2))
16413 (value (match-string 3))
16414 (allowed (or (org-property-get-allowed-values (point) key)
16415 (and (member value '("[ ]" "[-]" "[X]"))
16416 '("[ ]" "[X]"))))
16417 (heading (save-match-data (nth 4 (org-heading-components))))
16418 nval)
16419 (unless allowed
16420 (user-error "Allowed values for this property have not been defined"))
16421 (when previous (setq allowed (reverse allowed)))
16422 (when (member value allowed)
16423 (setq nval (car (cdr (member value allowed)))))
16424 (setq nval (or nval (car allowed)))
16425 (when (equal nval value)
16426 (user-error "Only one allowed value for this property"))
16427 (org-at-property-p)
16428 (replace-match (concat " :" key ": " nval) t t)
16429 (org-indent-line)
16430 (beginning-of-line 1)
16431 (skip-chars-forward " \t")
16432 (when (equal prop org-effort-property)
16433 (org-refresh-property
16434 '((effort . identity)
16435 (effort-minutes . org-duration-to-minutes))
16436 nval)
16437 (when (string= org-clock-current-task heading)
16438 (setq org-clock-effort nval)
16439 (org-clock-update-mode-line)))
16440 (run-hook-with-args 'org-property-changed-functions key nval)))
16442 (defun org-find-olp (path &optional this-buffer)
16443 "Return a marker pointing to the entry at outline path OLP.
16444 If anything goes wrong, throw an error.
16445 You can wrap this call to catch the error like this:
16447 (condition-case msg
16448 (org-mobile-locate-entry (match-string 4))
16449 (error (nth 1 msg)))
16451 The return value will then be either a string with the error message,
16452 or a marker if everything is OK.
16454 If THIS-BUFFER is set, the outline path does not contain a file,
16455 only headings."
16456 (let* ((file (if this-buffer buffer-file-name (pop path)))
16457 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16458 (level 1)
16459 (lmin 1)
16460 (lmax 1)
16461 end found flevel)
16462 (unless buffer (error "File not found :%s" file))
16463 (with-current-buffer buffer
16464 (unless (derived-mode-p 'org-mode)
16465 (error "Buffer %s needs to be in Org mode" buffer))
16466 (org-with-wide-buffer
16467 (goto-char (point-min))
16468 (dolist (heading path)
16469 (let ((re (format org-complex-heading-regexp-format
16470 (regexp-quote heading)))
16471 (cnt 0))
16472 (while (re-search-forward re end t)
16473 (setq level (- (match-end 1) (match-beginning 1)))
16474 (when (and (>= level lmin) (<= level lmax))
16475 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16476 (when (= cnt 0)
16477 (error "Heading not found on level %d: %s" lmax heading))
16478 (when (> cnt 1)
16479 (error "Heading not unique on level %d: %s" lmax heading))
16480 (goto-char found)
16481 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16482 (setq end (save-excursion (org-end-of-subtree t t)))))
16483 (when (org-at-heading-p)
16484 (point-marker))))))
16486 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16487 "Find node HEADING in BUFFER.
16488 Return a marker to the heading if it was found, or nil if not.
16489 If POS-ONLY is set, return just the position instead of a marker.
16491 The heading text must match exact, but it may have a TODO keyword,
16492 a priority cookie and tags in the standard locations."
16493 (with-current-buffer (or buffer (current-buffer))
16494 (org-with-wide-buffer
16495 (goto-char (point-min))
16496 (let (case-fold-search)
16497 (when (re-search-forward
16498 (format org-complex-heading-regexp-format
16499 (regexp-quote heading)) nil t)
16500 (if pos-only
16501 (match-beginning 0)
16502 (move-marker (make-marker) (match-beginning 0))))))))
16504 (defun org-find-exact-heading-in-directory (heading &optional dir)
16505 "Find Org node headline HEADING in all .org files in directory DIR.
16506 When the target headline is found, return a marker to this location."
16507 (let ((files (directory-files (or dir default-directory)
16508 t "\\`[^.#].*\\.org\\'"))
16509 visiting m buffer)
16510 (catch 'found
16511 (dolist (file files)
16512 (message "trying %s" file)
16513 (setq visiting (org-find-base-buffer-visiting file))
16514 (setq buffer (or visiting (find-file-noselect file)))
16515 (setq m (org-find-exact-headline-in-buffer
16516 heading buffer))
16517 (when (and (not m) (not visiting)) (kill-buffer buffer))
16518 (and m (throw 'found m))))))
16520 (defun org-find-entry-with-id (ident)
16521 "Locate the entry that contains the ID property with exact value IDENT.
16522 IDENT can be a string, a symbol or a number, this function will search for
16523 the string representation of it.
16524 Return the position where this entry starts, or nil if there is no such entry."
16525 (interactive "sID: ")
16526 (let ((id (cond
16527 ((stringp ident) ident)
16528 ((symbolp ident) (symbol-name ident))
16529 ((numberp ident) (number-to-string ident))
16530 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16531 (org-with-wide-buffer (org-find-property "ID" id))))
16533 ;;;; Timestamps
16535 (defvar org-last-changed-timestamp nil)
16536 (defvar org-last-inserted-timestamp nil
16537 "The last time stamp inserted with `org-insert-time-stamp'.")
16539 (defun org-time-stamp (arg &optional inactive)
16540 "Prompt for a date/time and insert a time stamp.
16542 If the user specifies a time like HH:MM or if this command is
16543 called with at least one prefix argument, the time stamp contains
16544 the date and the time. Otherwise, only the date is included.
16546 All parts of a date not specified by the user are filled in from
16547 the timestamp at point, if any, or the current date/time
16548 otherwise.
16550 If there is already a timestamp at the cursor, it is replaced.
16552 With two universal prefix arguments, insert an active timestamp
16553 with the current time without prompting the user.
16555 When called from lisp, the timestamp is inactive if INACTIVE is
16556 non-nil."
16557 (interactive "P")
16558 (let* ((ts (cond
16559 ((org-at-date-range-p t)
16560 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16561 ((org-at-timestamp-p 'lax) (match-string 0))))
16562 ;; Default time is either the timestamp at point or today.
16563 ;; When entering a range, only the range start is considered.
16564 (default-time (if (not ts) (current-time)
16565 (apply #'encode-time (org-parse-time-string ts))))
16566 (default-input (and ts (org-get-compact-tod ts)))
16567 (repeater (and ts
16568 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16569 (match-string 0 ts)))
16570 org-time-was-given
16571 org-end-time-was-given
16572 (time
16573 (and (if (equal arg '(16)) (current-time)
16574 ;; Preserve `this-command' and `last-command'.
16575 (let ((this-command this-command)
16576 (last-command last-command))
16577 (org-read-date
16578 arg 'totime nil nil default-time default-input
16579 inactive))))))
16580 (cond
16581 ((and ts
16582 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16583 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16584 (insert "--")
16585 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16587 ;; Make sure we're on a timestamp. When in the middle of a date
16588 ;; range, move arbitrarily to range end.
16589 (unless (org-at-timestamp-p 'lax)
16590 (skip-chars-forward "-")
16591 (org-at-timestamp-p 'lax))
16592 (replace-match "")
16593 (setq org-last-changed-timestamp
16594 (org-insert-time-stamp
16595 time (or org-time-was-given arg)
16596 inactive nil nil (list org-end-time-was-given)))
16597 (when repeater
16598 (backward-char)
16599 (insert " " repeater)
16600 (setq org-last-changed-timestamp
16601 (concat (substring org-last-inserted-timestamp 0 -1)
16602 " " repeater ">")))
16603 (message "Timestamp updated"))
16604 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16605 (t (org-insert-time-stamp
16606 time (or org-time-was-given arg) inactive nil nil
16607 (list org-end-time-was-given))))))
16609 ;; FIXME: can we use this for something else, like computing time differences?
16610 (defun org-get-compact-tod (s)
16611 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16612 (let* ((t1 (match-string 1 s))
16613 (h1 (string-to-number (match-string 2 s)))
16614 (m1 (string-to-number (match-string 3 s)))
16615 (t2 (and (match-end 4) (match-string 5 s)))
16616 (h2 (and t2 (string-to-number (match-string 6 s))))
16617 (m2 (and t2 (string-to-number (match-string 7 s))))
16618 dh dm)
16619 (if (not t2)
16621 (setq dh (- h2 h1) dm (- m2 m1))
16622 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16623 (concat t1 "+" (number-to-string dh)
16624 (and (/= 0 dm) (format ":%02d" dm)))))))
16626 (defun org-time-stamp-inactive (&optional arg)
16627 "Insert an inactive time stamp.
16628 An inactive time stamp is enclosed in square brackets instead of angle
16629 brackets. It is inactive in the sense that it does not trigger agenda entries,
16630 does not link to the calendar and cannot be changed with the S-cursor keys.
16631 So these are more for recording a certain time/date."
16632 (interactive "P")
16633 (org-time-stamp arg 'inactive))
16635 (defvar org-date-ovl (make-overlay 1 1))
16636 (overlay-put org-date-ovl 'face 'org-date-selected)
16637 (delete-overlay org-date-ovl)
16639 (defvar org-ans1) ; dynamically scoped parameter
16640 (defvar org-ans2) ; dynamically scoped parameter
16642 (defvar org-plain-time-of-day-regexp) ; defined below
16644 (defvar org-overriding-default-time nil) ; dynamically scoped
16645 (defvar org-read-date-overlay nil)
16646 (defvar org-dcst nil) ; dynamically scoped
16647 (defvar org-read-date-history nil)
16648 (defvar org-read-date-final-answer nil)
16649 (defvar org-read-date-analyze-futurep nil)
16650 (defvar org-read-date-analyze-forced-year nil)
16651 (defvar org-read-date-inactive)
16653 (defvar org-read-date-minibuffer-local-map
16654 (let* ((map (make-sparse-keymap)))
16655 (set-keymap-parent map minibuffer-local-map)
16656 (org-defkey map (kbd ".")
16657 (lambda () (interactive)
16658 ;; Are we at the beginning of the prompt?
16659 (if (looking-back "^[^:]+: "
16660 (let ((inhibit-field-text-motion t))
16661 (line-beginning-position)))
16662 (org-eval-in-calendar '(calendar-goto-today))
16663 (insert "."))))
16664 (org-defkey map (kbd "C-.")
16665 (lambda () (interactive)
16666 (org-eval-in-calendar '(calendar-goto-today))))
16667 (org-defkey map [(meta shift left)]
16668 (lambda () (interactive)
16669 (org-eval-in-calendar '(calendar-backward-month 1))))
16670 (org-defkey map [(meta shift right)]
16671 (lambda () (interactive)
16672 (org-eval-in-calendar '(calendar-forward-month 1))))
16673 (org-defkey map [(meta shift up)]
16674 (lambda () (interactive)
16675 (org-eval-in-calendar '(calendar-backward-year 1))))
16676 (org-defkey map [(meta shift down)]
16677 (lambda () (interactive)
16678 (org-eval-in-calendar '(calendar-forward-year 1))))
16679 (org-defkey map [?\e (shift left)]
16680 (lambda () (interactive)
16681 (org-eval-in-calendar '(calendar-backward-month 1))))
16682 (org-defkey map [?\e (shift right)]
16683 (lambda () (interactive)
16684 (org-eval-in-calendar '(calendar-forward-month 1))))
16685 (org-defkey map [?\e (shift up)]
16686 (lambda () (interactive)
16687 (org-eval-in-calendar '(calendar-backward-year 1))))
16688 (org-defkey map [?\e (shift down)]
16689 (lambda () (interactive)
16690 (org-eval-in-calendar '(calendar-forward-year 1))))
16691 (org-defkey map [(shift up)]
16692 (lambda () (interactive)
16693 (org-eval-in-calendar '(calendar-backward-week 1))))
16694 (org-defkey map [(shift down)]
16695 (lambda () (interactive)
16696 (org-eval-in-calendar '(calendar-forward-week 1))))
16697 (org-defkey map [(shift left)]
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(calendar-backward-day 1))))
16700 (org-defkey map [(shift right)]
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-forward-day 1))))
16703 (org-defkey map "!"
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(diary-view-entries))
16706 (message "")))
16707 (org-defkey map ">"
16708 (lambda () (interactive)
16709 (org-eval-in-calendar '(calendar-scroll-left 1))))
16710 (org-defkey map "<"
16711 (lambda () (interactive)
16712 (org-eval-in-calendar '(calendar-scroll-right 1))))
16713 (org-defkey map "\C-v"
16714 (lambda () (interactive)
16715 (org-eval-in-calendar
16716 '(calendar-scroll-left-three-months 1))))
16717 (org-defkey map "\M-v"
16718 (lambda () (interactive)
16719 (org-eval-in-calendar
16720 '(calendar-scroll-right-three-months 1))))
16721 map)
16722 "Keymap for minibuffer commands when using `org-read-date'.")
16724 (defvar org-def)
16725 (defvar org-defdecode)
16726 (defvar org-with-time)
16728 (defvar calendar-setup) ; Dynamically scoped.
16729 (defun org-read-date (&optional with-time to-time from-string prompt
16730 default-time default-input inactive)
16731 "Read a date, possibly a time, and make things smooth for the user.
16732 The prompt will suggest to enter an ISO date, but you can also enter anything
16733 which will at least partially be understood by `parse-time-string'.
16734 Unrecognized parts of the date will default to the current day, month, year,
16735 hour and minute. If this command is called to replace a timestamp at point,
16736 or to enter the second timestamp of a range, the default time is taken
16737 from the existing stamp. Furthermore, the command prefers the future,
16738 so if you are giving a date where the year is not given, and the day-month
16739 combination is already past in the current year, it will assume you
16740 mean next year. For details, see the manual. A few examples:
16742 3-2-5 --> 2003-02-05
16743 feb 15 --> currentyear-02-15
16744 2/15 --> currentyear-02-15
16745 sep 12 9 --> 2009-09-12
16746 12:45 --> today 12:45
16747 22 sept 0:34 --> currentyear-09-22 0:34
16748 12 --> currentyear-currentmonth-12
16749 Fri --> nearest Friday after today
16750 -Tue --> last Tuesday
16751 etc.
16753 Furthermore you can specify a relative date by giving, as the *first* thing
16754 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16755 change in days weeks, months, years.
16756 With a single plus or minus, the date is relative to today. With a double
16757 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16758 +4d --> four days from today
16759 +4 --> same as above
16760 +2w --> two weeks from today
16761 ++5 --> five days from default date
16763 The function understands only English month and weekday abbreviations.
16765 While prompting, a calendar is popped up - you can also select the
16766 date with the mouse (button 1). The calendar shows a period of three
16767 months. To scroll it to other months, use the keys `>' and `<'.
16768 If you don't like the calendar, turn it off with
16769 (setq org-read-date-popup-calendar nil)
16771 With optional argument TO-TIME, the date will immediately be converted
16772 to an internal time.
16773 With an optional argument WITH-TIME, the prompt will suggest to
16774 also insert a time. Note that when WITH-TIME is not set, you can
16775 still enter a time, and this function will inform the calling routine
16776 about this change. The calling routine may then choose to change the
16777 format used to insert the time stamp into the buffer to include the time.
16778 With optional argument FROM-STRING, read from this string instead from
16779 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16780 the time/date that is used for everything that is not specified by the
16781 user."
16782 (require 'parse-time)
16783 (let* ((org-with-time with-time)
16784 (org-time-stamp-rounding-minutes
16785 (if (equal org-with-time '(16))
16786 '(0 0)
16787 org-time-stamp-rounding-minutes))
16788 (org-dcst org-display-custom-times)
16789 (ct (org-current-time))
16790 (org-def (or org-overriding-default-time default-time ct))
16791 (org-defdecode (decode-time org-def))
16792 (cur-frame (selected-frame))
16793 (mouse-autoselect-window nil) ; Don't let the mouse jump
16794 (calendar-setup
16795 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16796 (calendar-move-hook nil)
16797 (calendar-view-diary-initially-flag nil)
16798 (calendar-view-holidays-initially-flag nil)
16799 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16800 ;; Rationalize `org-def' and `org-defdecode', if required.
16801 (when (< (nth 2 org-defdecode) org-extend-today-until)
16802 (setf (nth 2 org-defdecode) -1)
16803 (setf (nth 1 org-defdecode) 59)
16804 (setq org-def (apply #'encode-time org-defdecode))
16805 (setq org-defdecode (decode-time org-def)))
16806 (let* ((timestr (format-time-string
16807 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16808 org-def))
16809 (prompt (concat (if prompt (concat prompt " ") "")
16810 (format "Date+time [%s]: " timestr))))
16811 (cond
16812 (from-string (setq ans from-string))
16813 (org-read-date-popup-calendar
16814 (save-excursion
16815 (save-window-excursion
16816 (calendar)
16817 (when (eq calendar-setup 'calendar-only)
16818 (setq cal-frame
16819 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16820 (select-frame cal-frame))
16821 (org-eval-in-calendar '(setq cursor-type nil) t)
16822 (unwind-protect
16823 (progn
16824 (calendar-forward-day (- (time-to-days org-def)
16825 (calendar-absolute-from-gregorian
16826 (calendar-current-date))))
16827 (org-eval-in-calendar nil t)
16828 (let* ((old-map (current-local-map))
16829 (map (copy-keymap calendar-mode-map))
16830 (minibuffer-local-map
16831 (copy-keymap org-read-date-minibuffer-local-map)))
16832 (org-defkey map (kbd "RET") 'org-calendar-select)
16833 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16834 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16835 (unwind-protect
16836 (progn
16837 (use-local-map map)
16838 (setq org-read-date-inactive inactive)
16839 (add-hook 'post-command-hook 'org-read-date-display)
16840 (setq org-ans0
16841 (read-string prompt
16842 default-input
16843 'org-read-date-history
16844 nil))
16845 ;; org-ans0: from prompt
16846 ;; org-ans1: from mouse click
16847 ;; org-ans2: from calendar motion
16848 (setq ans
16849 (concat org-ans0 " " (or org-ans1 org-ans2))))
16850 (remove-hook 'post-command-hook 'org-read-date-display)
16851 (use-local-map old-map)
16852 (when org-read-date-overlay
16853 (delete-overlay org-read-date-overlay)
16854 (setq org-read-date-overlay nil)))))
16855 (bury-buffer "*Calendar*")
16856 (when cal-frame
16857 (delete-frame cal-frame)
16858 (select-frame-set-input-focus cur-frame))))))
16860 (t ; Naked prompt only
16861 (unwind-protect
16862 (setq ans (read-string prompt default-input
16863 'org-read-date-history timestr))
16864 (when org-read-date-overlay
16865 (delete-overlay org-read-date-overlay)
16866 (setq org-read-date-overlay nil))))))
16868 (setq final (org-read-date-analyze ans org-def org-defdecode))
16870 (when org-read-date-analyze-forced-year
16871 (message "Year was forced into %s"
16872 (if org-read-date-force-compatible-dates
16873 "compatible range (1970-2037)"
16874 "range representable on this machine"))
16875 (ding))
16877 ;; One round trip to get rid of 34th of August and stuff like that....
16878 (setq final (decode-time (apply 'encode-time final)))
16880 (setq org-read-date-final-answer ans)
16882 (if to-time
16883 (apply 'encode-time final)
16884 (if (and (boundp 'org-time-was-given) org-time-was-given)
16885 (format "%04d-%02d-%02d %02d:%02d"
16886 (nth 5 final) (nth 4 final) (nth 3 final)
16887 (nth 2 final) (nth 1 final))
16888 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16890 (defun org-read-date-display ()
16891 "Display the current date prompt interpretation in the minibuffer."
16892 (when org-read-date-display-live
16893 (when org-read-date-overlay
16894 (delete-overlay org-read-date-overlay))
16895 (when (minibufferp (current-buffer))
16896 (save-excursion
16897 (end-of-line 1)
16898 (while (not (equal (buffer-substring
16899 (max (point-min) (- (point) 4)) (point))
16900 " "))
16901 (insert " ")))
16902 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16903 " " (or org-ans1 org-ans2)))
16904 (org-end-time-was-given nil)
16905 (f (org-read-date-analyze ans org-def org-defdecode))
16906 (fmts (if org-dcst
16907 org-time-stamp-custom-formats
16908 org-time-stamp-formats))
16909 (fmt (if (or org-with-time
16910 (and (boundp 'org-time-was-given) org-time-was-given))
16911 (cdr fmts)
16912 (car fmts)))
16913 (txt (format-time-string fmt (apply 'encode-time f)))
16914 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16915 (txt (concat "=> " txt)))
16916 (when (and org-end-time-was-given
16917 (string-match org-plain-time-of-day-regexp txt))
16918 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16919 org-end-time-was-given
16920 (substring txt (match-end 0)))))
16921 (when org-read-date-analyze-futurep
16922 (setq txt (concat txt " (=>F)")))
16923 (setq org-read-date-overlay
16924 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16925 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16927 (defun org-read-date-analyze (ans def defdecode)
16928 "Analyze the combined answer of the date prompt."
16929 ;; FIXME: cleanup and comment
16930 ;; Pass `current-time' result to `decode-time' (instead of calling
16931 ;; without arguments) so that only `current-time' has to be
16932 ;; overridden in tests.
16933 (let ((org-def def)
16934 (org-defdecode defdecode)
16935 (nowdecode (decode-time (current-time)))
16936 delta deltan deltaw deltadef year month day
16937 hour minute second wday pm h2 m2 tl wday1
16938 iso-year iso-weekday iso-week iso-date futurep kill-year)
16939 (setq org-read-date-analyze-futurep nil
16940 org-read-date-analyze-forced-year nil)
16941 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16942 (setq ans "+0"))
16944 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16945 (setq ans (replace-match "" t t ans)
16946 deltan (car delta)
16947 deltaw (nth 1 delta)
16948 deltadef (nth 2 delta)))
16950 ;; Check if there is an iso week date in there. If yes, store the
16951 ;; info and postpone interpreting it until the rest of the parsing
16952 ;; is done.
16953 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16954 (setq iso-year (when (match-end 1)
16955 (org-small-year-to-year
16956 (string-to-number (match-string 1 ans))))
16957 iso-weekday (when (match-end 3)
16958 (string-to-number (match-string 3 ans)))
16959 iso-week (string-to-number (match-string 2 ans)))
16960 (setq ans (replace-match "" t t ans)))
16962 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16963 (when (string-match
16964 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16965 (setq year (if (match-end 2)
16966 (string-to-number (match-string 2 ans))
16967 (progn (setq kill-year t)
16968 (string-to-number (format-time-string "%Y"))))
16969 month (string-to-number (match-string 3 ans))
16970 day (string-to-number (match-string 4 ans)))
16971 (setq year (org-small-year-to-year year))
16972 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16973 t nil ans)))
16975 ;; Help matching dotted european dates
16976 (when (string-match
16977 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16978 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16979 (setq kill-year t)
16980 (string-to-number (format-time-string "%Y")))
16981 day (string-to-number (match-string 1 ans))
16982 month (string-to-number (match-string 2 ans))
16983 ans (replace-match (format "%04d-%02d-%02d" year month day)
16984 t nil ans)))
16986 ;; Help matching american dates, like 5/30 or 5/30/7
16987 (when (string-match
16988 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16989 (setq year (if (match-end 4)
16990 (string-to-number (match-string 4 ans))
16991 (progn (setq kill-year t)
16992 (string-to-number (format-time-string "%Y"))))
16993 month (string-to-number (match-string 1 ans))
16994 day (string-to-number (match-string 2 ans)))
16995 (setq year (org-small-year-to-year year))
16996 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16997 t nil ans)))
16998 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16999 ;; If there is a time with am/pm, and *no* time without it, we convert
17000 ;; so that matching will be successful.
17001 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17002 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17003 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17004 (setq hour (string-to-number (match-string 1 ans))
17005 minute (if (match-end 3)
17006 (string-to-number (match-string 3 ans))
17008 pm (equal ?p
17009 (string-to-char (downcase (match-string 4 ans)))))
17010 (if (and (= hour 12) (not pm))
17011 (setq hour 0)
17012 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17013 (setq ans (replace-match (format "%02d:%02d" hour minute)
17014 t t ans))))
17016 ;; Check if a time range is given as a duration
17017 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17018 (setq hour (string-to-number (match-string 1 ans))
17019 h2 (+ hour (string-to-number (match-string 3 ans)))
17020 minute (string-to-number (match-string 2 ans))
17021 m2 (+ minute (if (match-end 5) (string-to-number
17022 (match-string 5 ans))0)))
17023 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17024 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17025 t t ans)))
17027 ;; Check if there is a time range
17028 (when (boundp 'org-end-time-was-given)
17029 (setq org-time-was-given nil)
17030 (when (and (string-match org-plain-time-of-day-regexp ans)
17031 (match-end 8))
17032 (setq org-end-time-was-given (match-string 8 ans))
17033 (setq ans (concat (substring ans 0 (match-beginning 7))
17034 (substring ans (match-end 7))))))
17036 (setq tl (parse-time-string ans)
17037 day (or (nth 3 tl) (nth 3 org-defdecode))
17038 month
17039 (cond ((nth 4 tl))
17040 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17041 ;; Day was specified. Make sure DAY+MONTH
17042 ;; combination happens in the future.
17043 ((nth 3 tl)
17044 (setq futurep t)
17045 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17046 (nth 4 nowdecode)))
17047 (t (nth 4 org-defdecode)))
17048 year
17049 (cond ((and (not kill-year) (nth 5 tl)))
17050 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17051 ;; Month was guessed in the future and is at least
17052 ;; equal to NOWDECODE's. Fix year accordingly.
17053 (futurep
17054 (if (or (> month (nth 4 nowdecode))
17055 (>= day (nth 3 nowdecode)))
17056 (nth 5 nowdecode)
17057 (1+ (nth 5 nowdecode))))
17058 ;; Month was specified. Make sure MONTH+YEAR
17059 ;; combination happens in the future.
17060 ((nth 4 tl)
17061 (setq futurep t)
17062 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17063 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17064 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17065 (t (nth 5 nowdecode))))
17066 (t (nth 5 org-defdecode)))
17067 hour (or (nth 2 tl) (nth 2 org-defdecode))
17068 minute (or (nth 1 tl) (nth 1 org-defdecode))
17069 second (or (nth 0 tl) 0)
17070 wday (nth 6 tl))
17072 (when (and (eq org-read-date-prefer-future 'time)
17073 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17074 (equal day (nth 3 nowdecode))
17075 (equal month (nth 4 nowdecode))
17076 (equal year (nth 5 nowdecode))
17077 (nth 2 tl)
17078 (or (< (nth 2 tl) (nth 2 nowdecode))
17079 (and (= (nth 2 tl) (nth 2 nowdecode))
17080 (nth 1 tl)
17081 (< (nth 1 tl) (nth 1 nowdecode)))))
17082 (setq day (1+ day)
17083 futurep t))
17085 ;; Special date definitions below
17086 (cond
17087 (iso-week
17088 ;; There was an iso week
17089 (require 'cal-iso)
17090 (setq futurep nil)
17091 (setq year (or iso-year year)
17092 day (or iso-weekday wday 1)
17093 wday nil ; to make sure that the trigger below does not match
17094 iso-date (calendar-gregorian-from-absolute
17095 (calendar-iso-to-absolute
17096 (list iso-week day year))))
17097 ; FIXME: Should we also push ISO weeks into the future?
17098 ; (when (and org-read-date-prefer-future
17099 ; (not iso-year)
17100 ; (< (calendar-absolute-from-gregorian iso-date)
17101 ; (time-to-days (current-time))))
17102 ; (setq year (1+ year)
17103 ; iso-date (calendar-gregorian-from-absolute
17104 ; (calendar-iso-to-absolute
17105 ; (list iso-week day year)))))
17106 (setq month (car iso-date)
17107 year (nth 2 iso-date)
17108 day (nth 1 iso-date)))
17109 (deltan
17110 (setq futurep nil)
17111 (unless deltadef
17112 ;; Pass `current-time' result to `decode-time' (instead of
17113 ;; calling without arguments) so that only `current-time' has
17114 ;; to be overridden in tests.
17115 (let ((now (decode-time (current-time))))
17116 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17117 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17118 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17119 ((equal deltaw "m") (setq month (+ month deltan)))
17120 ((equal deltaw "y") (setq year (+ year deltan)))))
17121 ((and wday (not (nth 3 tl)))
17122 ;; Weekday was given, but no day, so pick that day in the week
17123 ;; on or after the derived date.
17124 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17125 (unless (equal wday wday1)
17126 (setq day (+ day (% (- wday wday1 -7) 7))))))
17127 (when (and (boundp 'org-time-was-given)
17128 (nth 2 tl))
17129 (setq org-time-was-given t))
17130 (when (< year 100) (setq year (+ 2000 year)))
17131 ;; Check of the date is representable
17132 (if org-read-date-force-compatible-dates
17133 (progn
17134 (when (< year 1970)
17135 (setq year 1970 org-read-date-analyze-forced-year t))
17136 (when (> year 2037)
17137 (setq year 2037 org-read-date-analyze-forced-year t)))
17138 (condition-case nil
17139 (ignore (encode-time second minute hour day month year))
17140 (error
17141 (setq year (nth 5 org-defdecode))
17142 (setq org-read-date-analyze-forced-year t))))
17143 (setq org-read-date-analyze-futurep futurep)
17144 (list second minute hour day month year)))
17146 (defvar parse-time-weekdays)
17147 (defun org-read-date-get-relative (s today default)
17148 "Check string S for special relative date string.
17149 TODAY and DEFAULT are internal times, for today and for a default.
17150 Return shift list (N what def-flag)
17151 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17152 N is the number of WHATs to shift.
17153 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17154 the DEFAULT date rather than TODAY."
17155 (require 'parse-time)
17156 (when (and
17157 (string-match
17158 (concat
17159 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17160 "\\([0-9]+\\)?"
17161 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17162 "\\([ \t]\\|$\\)") s)
17163 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17164 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17165 (string-to-char (substring (match-string 1 s) -1))
17166 ?+))
17167 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17168 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17169 (what (if (match-end 3) (match-string 3 s) "d"))
17170 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17171 (date (if rel default today))
17172 (wday (nth 6 (decode-time date)))
17173 delta)
17174 (if wday1
17175 (progn
17176 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17177 (when (= delta 0) (setq delta 7))
17178 (when (= dir ?-)
17179 (setq delta (- delta 7))
17180 (when (= delta 0) (setq delta -7)))
17181 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17182 (list delta "d" rel))
17183 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17185 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17186 "Turn a user-specified date into the internal representation.
17187 The internal representation needed by the calendar is (month day year).
17188 This is a wrapper to handle the brain-dead convention in calendar that
17189 user function argument order change dependent on argument order."
17190 (pcase calendar-date-style
17191 (`american (list arg1 arg2 arg3))
17192 (`european (list arg2 arg1 arg3))
17193 (`iso (list arg2 arg3 arg1))))
17195 (defun org-eval-in-calendar (form &optional keepdate)
17196 "Eval FORM in the calendar window and return to current window.
17197 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17198 (let ((sf (selected-frame))
17199 (sw (selected-window)))
17200 (select-window (get-buffer-window "*Calendar*" t))
17201 (eval form)
17202 (when (and (not keepdate) (calendar-cursor-to-date))
17203 (let* ((date (calendar-cursor-to-date))
17204 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17205 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17206 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17207 (select-window sw)
17208 (select-frame-set-input-focus sf)))
17210 (defun org-calendar-select ()
17211 "Return to `org-read-date' with the date currently selected.
17212 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17213 (interactive)
17214 (when (calendar-cursor-to-date)
17215 (let* ((date (calendar-cursor-to-date))
17216 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17217 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17218 (when (active-minibuffer-window) (exit-minibuffer))))
17220 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17221 "Insert a date stamp for the date given by the internal TIME.
17222 See `format-time-string' for the format of TIME.
17223 WITH-HM means use the stamp format that includes the time of the day.
17224 INACTIVE means use square brackets instead of angular ones, so that the
17225 stamp will not contribute to the agenda.
17226 PRE and POST are optional strings to be inserted before and after the
17227 stamp.
17228 The command returns the inserted time stamp."
17229 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17230 stamp)
17231 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17232 (insert-before-markers (or pre ""))
17233 (when (listp extra)
17234 (setq extra (car extra))
17235 (if (and (stringp extra)
17236 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17237 (setq extra (format "-%02d:%02d"
17238 (string-to-number (match-string 1 extra))
17239 (string-to-number (match-string 2 extra))))
17240 (setq extra nil)))
17241 (when extra
17242 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17243 (insert-before-markers (setq stamp (format-time-string fmt time)))
17244 (insert-before-markers (or post ""))
17245 (setq org-last-inserted-timestamp stamp)))
17247 (defun org-toggle-time-stamp-overlays ()
17248 "Toggle the use of custom time stamp formats."
17249 (interactive)
17250 (setq org-display-custom-times (not org-display-custom-times))
17251 (unless org-display-custom-times
17252 (let ((p (point-min)) (bmp (buffer-modified-p)))
17253 (while (setq p (next-single-property-change p 'display))
17254 (when (and (get-text-property p 'display)
17255 (eq (get-text-property p 'face) 'org-date))
17256 (remove-text-properties
17257 p (setq p (next-single-property-change p 'display))
17258 '(display t))))
17259 (set-buffer-modified-p bmp)))
17260 (org-restart-font-lock)
17261 (setq org-table-may-need-update t)
17262 (if org-display-custom-times
17263 (message "Time stamps are overlaid with custom format")
17264 (message "Time stamp overlays removed")))
17266 (defun org-display-custom-time (beg end)
17267 "Overlay modified time stamp format over timestamp between BEG and END."
17268 (let* ((ts (buffer-substring beg end))
17269 t1 with-hm tf time str (off 0))
17270 (save-match-data
17271 (setq t1 (org-parse-time-string ts t))
17272 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17273 (setq off (- (match-end 0) (match-beginning 0)))))
17274 (setq end (- end off))
17275 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17276 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17277 time (org-fix-decoded-time t1)
17278 str (org-add-props
17279 (format-time-string
17280 (substring tf 1 -1) (apply 'encode-time time))
17281 nil 'mouse-face 'highlight))
17282 (put-text-property beg end 'display str)))
17284 (defun org-fix-decoded-time (time)
17285 "Set 0 instead of nil for the first 6 elements of time.
17286 Don't touch the rest."
17287 (let ((n 0))
17288 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17290 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17291 "Difference between TIMESTAMP-STRING and now in days.
17292 If SECONDS is non-nil, return the difference in seconds."
17293 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17294 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17295 (funcall fdiff (current-time)))))
17297 (defun org-deadline-close-p (timestamp-string &optional ndays)
17298 "Is the time in TIMESTAMP-STRING close to the current date?"
17299 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17300 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17301 (not (org-entry-is-done-p))))
17303 (defun org-get-wdays (ts &optional delay zero-delay)
17304 "Get the deadline lead time appropriate for timestring TS.
17305 When DELAY is non-nil, get the delay time for scheduled items
17306 instead of the deadline lead time. When ZERO-DELAY is non-nil
17307 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17308 don't try to find the delay cookie in the scheduled timestamp."
17309 (let ((tv (if delay org-scheduled-delay-days
17310 org-deadline-warning-days)))
17311 (cond
17312 ((or (and delay (< tv 0))
17313 (and delay zero-delay (<= tv 0))
17314 (and (not delay) (<= tv 0)))
17315 ;; Enforce this value no matter what
17316 (- tv))
17317 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17318 ;; lead time is specified.
17319 (floor (* (string-to-number (match-string 1 ts))
17320 (cdr (assoc (match-string 2 ts)
17321 '(("d" . 1) ("w" . 7)
17322 ("m" . 30.4) ("y" . 365.25)
17323 ("h" . 0.041667)))))))
17324 ;; go for the default.
17325 (t tv))))
17327 (defun org-calendar-select-mouse (ev)
17328 "Return to `org-read-date' with the date currently selected.
17329 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17330 (interactive "e")
17331 (mouse-set-point ev)
17332 (when (calendar-cursor-to-date)
17333 (let* ((date (calendar-cursor-to-date))
17334 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17335 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17336 (when (active-minibuffer-window) (exit-minibuffer))))
17338 (defun org-check-deadlines (ndays)
17339 "Check if there are any deadlines due or past due.
17340 A deadline is considered due if it happens within `org-deadline-warning-days'
17341 days from today's date. If the deadline appears in an entry marked DONE,
17342 it is not shown. A numeric prefix argument NDAYS can be used to test that
17343 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17344 are shown."
17345 (interactive "P")
17346 (let* ((org-warn-days
17347 (cond
17348 ((equal ndays '(4)) 100000)
17349 (ndays (prefix-numeric-value ndays))
17350 (t (abs org-deadline-warning-days))))
17351 (case-fold-search nil)
17352 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17353 (callback
17354 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17355 (message "%d deadlines past-due or due within %d days"
17356 (org-occur regexp nil callback)
17357 org-warn-days)))
17359 (defsubst org-re-timestamp (type)
17360 "Return a regexp for timestamp TYPE.
17361 Allowed values for TYPE are:
17363 all: all timestamps
17364 active: only active timestamps (<...>)
17365 inactive: only inactive timestamps ([...])
17366 scheduled: only scheduled timestamps
17367 deadline: only deadline timestamps
17368 closed: only closed time-stamps
17370 When TYPE is nil, fall back on returning a regexp that matches
17371 both scheduled and deadline timestamps."
17372 (cl-case type
17373 (all org-ts-regexp-both)
17374 (active org-ts-regexp)
17375 (inactive org-ts-regexp-inactive)
17376 (scheduled org-scheduled-time-regexp)
17377 (deadline org-deadline-time-regexp)
17378 (closed org-closed-time-regexp)
17379 (otherwise
17380 (concat "\\<"
17381 (regexp-opt (list org-deadline-string org-scheduled-string))
17382 " *<\\([^>]+\\)>"))))
17384 (defun org-check-before-date (d)
17385 "Check if there are deadlines or scheduled entries before date D."
17386 (interactive (list (org-read-date)))
17387 (let* ((case-fold-search nil)
17388 (regexp (org-re-timestamp org-ts-type))
17389 (ts-type org-ts-type)
17390 (callback
17391 (lambda ()
17392 (let ((match (match-string 1)))
17393 (and (if (memq ts-type '(active inactive all))
17394 (eq (org-element-type (save-excursion
17395 (backward-char)
17396 (org-element-context)))
17397 'timestamp)
17398 (org-at-planning-p))
17399 (time-less-p
17400 (org-time-string-to-time match t)
17401 (org-time-string-to-time d t)))))))
17402 (message "%d entries before %s"
17403 (org-occur regexp nil callback)
17404 d)))
17406 (defun org-check-after-date (d)
17407 "Check if there are deadlines or scheduled entries after date D."
17408 (interactive (list (org-read-date)))
17409 (let* ((case-fold-search nil)
17410 (regexp (org-re-timestamp org-ts-type))
17411 (ts-type org-ts-type)
17412 (callback
17413 (lambda ()
17414 (let ((match (match-string 1)))
17415 (and (if (memq ts-type '(active inactive all))
17416 (eq (org-element-type (save-excursion
17417 (backward-char)
17418 (org-element-context)))
17419 'timestamp)
17420 (org-at-planning-p))
17421 (not (time-less-p
17422 (org-time-string-to-time match t)
17423 (org-time-string-to-time d t))))))))
17424 (message "%d entries after %s"
17425 (org-occur regexp nil callback)
17426 d)))
17428 (defun org-check-dates-range (start-date end-date)
17429 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17430 (interactive (list (org-read-date nil nil nil "Range starts")
17431 (org-read-date nil nil nil "Range end")))
17432 (let ((case-fold-search nil)
17433 (regexp (org-re-timestamp org-ts-type))
17434 (callback
17435 (let ((type org-ts-type))
17436 (lambda ()
17437 (let ((match (match-string 1)))
17438 (and
17439 (if (memq type '(active inactive all))
17440 (eq (org-element-type (save-excursion
17441 (backward-char)
17442 (org-element-context)))
17443 'timestamp)
17444 (org-at-planning-p))
17445 (not (time-less-p
17446 (org-time-string-to-time match t)
17447 (org-time-string-to-time start-date t)))
17448 (time-less-p
17449 (org-time-string-to-time match t)
17450 (org-time-string-to-time end-date t))))))))
17451 (message "%d entries between %s and %s"
17452 (org-occur regexp nil callback) start-date end-date)))
17454 (defun org-evaluate-time-range (&optional to-buffer)
17455 "Evaluate a time range by computing the difference between start and end.
17456 Normally the result is just printed in the echo area, but with prefix arg
17457 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17458 If the time range is actually in a table, the result is inserted into the
17459 next column.
17460 For time difference computation, a year is assumed to be exactly 365
17461 days in order to avoid rounding problems."
17462 (interactive "P")
17464 (org-clock-update-time-maybe)
17465 (save-excursion
17466 (unless (org-at-date-range-p t)
17467 (goto-char (point-at-bol))
17468 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17469 (unless (org-at-date-range-p t)
17470 (user-error "Not at a time-stamp range, and none found in current line")))
17471 (let* ((ts1 (match-string 1))
17472 (ts2 (match-string 2))
17473 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17474 (match-end (match-end 0))
17475 (time1 (org-time-string-to-time ts1))
17476 (time2 (org-time-string-to-time ts2))
17477 (t1 (float-time time1))
17478 (t2 (float-time time2))
17479 (diff (abs (- t2 t1)))
17480 (negative (< (- t2 t1) 0))
17481 ;; (ys (floor (* 365 24 60 60)))
17482 (ds (* 24 60 60))
17483 (hs (* 60 60))
17484 (fy "%dy %dd %02d:%02d")
17485 (fy1 "%dy %dd")
17486 (fd "%dd %02d:%02d")
17487 (fd1 "%dd")
17488 (fh "%02d:%02d")
17489 y d h m align)
17490 (if havetime
17491 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17493 d (floor (/ diff ds)) diff (mod diff ds)
17494 h (floor (/ diff hs)) diff (mod diff hs)
17495 m (floor (/ diff 60)))
17496 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17498 d (floor (+ (/ diff ds) 0.5))
17499 h 0 m 0))
17500 (if (not to-buffer)
17501 (message "%s" (org-make-tdiff-string y d h m))
17502 (if (org-at-table-p)
17503 (progn
17504 (goto-char match-end)
17505 (setq align t)
17506 (and (looking-at " *|") (goto-char (match-end 0))))
17507 (goto-char match-end))
17508 (when (looking-at
17509 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17510 (replace-match ""))
17511 (when negative (insert " -"))
17512 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17513 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17514 (insert " " (format fh h m))))
17515 (when align (org-table-align))
17516 (message "Time difference inserted")))))
17518 (defun org-make-tdiff-string (y d h m)
17519 (let ((fmt "")
17520 (l nil))
17521 (when (> y 0)
17522 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17523 (push y l))
17524 (when (> d 0)
17525 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17526 (push d l))
17527 (when (> h 0)
17528 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17529 (push h l))
17530 (when (> m 0)
17531 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17532 (push m l))
17533 (apply 'format fmt (nreverse l))))
17535 (defun org-time-string-to-time (s &optional zone)
17536 "Convert timestamp string S into internal time.
17537 The optional ZONE is omitted or nil for Emacs local time, t for
17538 Universal Time, ‘wall’ for system wall clock time, or a string as
17539 in the TZ environment variable."
17540 (apply #'encode-time (org-parse-time-string s nil zone)))
17542 (defun org-time-string-to-seconds (s &optional zone)
17543 "Convert a timestamp string S into a number of seconds.
17544 The optional ZONE is omitted or nil for Emacs local time, t for
17545 Universal Time, ‘wall’ for system wall clock time, or a string as
17546 in the TZ environment variable."
17547 (float-time (org-time-string-to-time s zone)))
17549 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17551 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17552 "Convert time stamp S to an absolute day number.
17554 If DAYNR in non-nil, and there is a specifier for a cyclic time
17555 stamp, get the closest date to DAYNR. If PREFER is
17556 `past' (respectively `future') return a date past (respectively
17557 after) or equal to DAYNR.
17559 POS is the location of time stamp S, as a buffer position in
17560 BUFFER.
17562 Diary sexp timestamps are matched against DAYNR, when non-nil.
17563 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17564 signaled."
17565 (cond
17566 ((string-match "\\`%%\\((.*)\\)" s)
17567 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17568 ;; only able to match individual dates. If it fails, raise an
17569 ;; error.
17570 (if (and daynr
17571 (org-diary-sexp-entry
17572 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17573 daynr
17574 (signal 'org-diary-sexp-no-match (list s))))
17575 (daynr (org-closest-date s daynr prefer))
17576 (t (time-to-days
17577 (condition-case errdata
17578 (apply #'encode-time (org-parse-time-string s))
17579 (error (error "Bad timestamp `%s'%s\nError was: %s"
17581 (if (not (and buffer pos)) ""
17582 (format-message " at %d in buffer `%s'" pos buffer))
17583 (cdr errdata))))))))
17585 (defun org-days-to-iso-week (days)
17586 "Return the iso week number."
17587 (require 'cal-iso)
17588 (car (calendar-iso-from-absolute days)))
17590 (defun org-small-year-to-year (year)
17591 "Convert 2-digit years into 4-digit years.
17592 YEAR is expanded into one of the 30 next years, if possible, or
17593 into a past one. Any year larger than 99 is returned unchanged."
17594 (if (>= year 100) year
17595 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17596 (century (/ current 100))
17597 (offset (- year (% current 100))))
17598 (cond ((> offset 30) (+ (* (1- century) 100) year))
17599 ((> offset -70) (+ (* century 100) year))
17600 (t (+ (* (1+ century) 100) year))))))
17602 (defun org-time-from-absolute (d)
17603 "Return the time corresponding to date D.
17604 D may be an absolute day number, or a calendar-type list (month day year)."
17605 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17606 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17608 (defvar org-agenda-current-date)
17609 (defun org-calendar-holiday ()
17610 "List of holidays, for Diary display in Org mode."
17611 (require 'holidays)
17612 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17613 (and hl (mapconcat #'identity hl "; "))))
17615 (defun org-diary-sexp-entry (sexp entry d)
17616 "Process a SEXP diary ENTRY for date D."
17617 (require 'diary-lib)
17618 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17619 ;; dynamically.
17620 (let* ((sexp `(let ((entry ,entry)
17621 (date ',d))
17622 ,(car (read-from-string sexp))))
17623 (result (if calendar-debug-sexp (eval sexp)
17624 (condition-case nil
17625 (eval sexp)
17626 (error
17627 (beep)
17628 (message "Bad sexp at line %d in %s: %s"
17629 (org-current-line)
17630 (buffer-file-name) sexp)
17631 (sleep-for 2))))))
17632 (cond ((stringp result) (split-string result "; "))
17633 ((and (consp result)
17634 (not (consp (cdr result)))
17635 (stringp (cdr result))) (cdr result))
17636 ((and (consp result)
17637 (stringp (car result))) result)
17638 (result entry))))
17640 (defun org-diary-to-ical-string (frombuf)
17641 "Get iCalendar entries from diary entries in buffer FROMBUF.
17642 This uses the icalendar.el library."
17643 (let* ((tmpdir temporary-file-directory)
17644 (tmpfile (make-temp-name
17645 (expand-file-name "orgics" tmpdir)))
17646 buf rtn b e)
17647 (with-current-buffer frombuf
17648 (icalendar-export-region (point-min) (point-max) tmpfile)
17649 (setq buf (find-buffer-visiting tmpfile))
17650 (set-buffer buf)
17651 (goto-char (point-min))
17652 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17653 (setq b (match-beginning 0)))
17654 (goto-char (point-max))
17655 (when (re-search-backward "^END:VEVENT" nil t)
17656 (setq e (match-end 0)))
17657 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17658 (kill-buffer buf)
17659 (delete-file tmpfile)
17660 rtn))
17662 (defun org-closest-date (start current prefer)
17663 "Return closest date to CURRENT starting from START.
17665 CURRENT and START are both time stamps.
17667 When PREFER is `past', return a date that is either CURRENT or
17668 past. When PREFER is `future', return a date that is either
17669 CURRENT or future.
17671 Only time stamps with a repeater are modified. Any other time
17672 stamp stay unchanged. In any case, return value is an absolute
17673 day number."
17674 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17675 ;; No repeater. Do not shift time stamp.
17676 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17677 (let ((value (string-to-number (match-string 1 start)))
17678 (type (match-string 2 start)))
17679 (if (= 0 value)
17680 ;; Repeater with a 0-value is considered as void.
17681 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17682 (let* ((base (org-date-to-gregorian start))
17683 (target (org-date-to-gregorian current))
17684 (sday (calendar-absolute-from-gregorian base))
17685 (cday (calendar-absolute-from-gregorian target))
17686 n1 n2)
17687 ;; If START is already past CURRENT, just return START.
17688 (if (<= cday sday) sday
17689 ;; Compute closest date before (N1) and closest date past
17690 ;; (N2) CURRENT.
17691 (pcase type
17692 ("h"
17693 (let ((missing-hours
17694 (mod (+ (- (* 24 (- cday sday))
17695 (nth 2 (org-parse-time-string start)))
17696 org-extend-today-until)
17697 value)))
17698 (setf n1 (if (= missing-hours 0) cday
17699 (- cday (1+ (/ missing-hours 24)))))
17700 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17701 ((or "d" "w")
17702 (let ((value (if (equal type "w") (* 7 value) value)))
17703 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17704 (setf n2 (+ n1 value))))
17705 ("m"
17706 (let* ((add-months
17707 (lambda (d n)
17708 ;; Add N months to gregorian date D, i.e.,
17709 ;; a list (MONTH DAY YEAR). Return a valid
17710 ;; gregorian date.
17711 (let ((m (+ (nth 0 d) n)))
17712 (list (mod m 12)
17713 (nth 1 d)
17714 (+ (/ m 12) (nth 2 d))))))
17715 (months ; Complete months to TARGET.
17716 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17717 (- (nth 0 target) (nth 0 base))
17718 ;; If START's day is greater than
17719 ;; TARGET's, remove incomplete month.
17720 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17721 value)
17722 value))
17723 (before (funcall add-months base months)))
17724 (setf n1 (calendar-absolute-from-gregorian before))
17725 (setf n2
17726 (calendar-absolute-from-gregorian
17727 (funcall add-months before value)))))
17729 (let* ((d (nth 1 base))
17730 (m (nth 0 base))
17731 (y (nth 2 base))
17732 (years ; Complete years to TARGET.
17733 (* (/ (- (nth 2 target)
17735 ;; If START's month and day are
17736 ;; greater than TARGET's, remove
17737 ;; incomplete year.
17738 (if (or (> (nth 0 target) m)
17739 (and (= (nth 0 target) m)
17740 (> (nth 1 target) d)))
17743 value)
17744 value))
17745 (before (list m d (+ y years))))
17746 (setf n1 (calendar-absolute-from-gregorian before))
17747 (setf n2 (calendar-absolute-from-gregorian
17748 (list m d (+ (nth 2 before) value)))))))
17749 ;; Handle PREFER parameter, if any.
17750 (cond
17751 ((eq prefer 'past) (if (= cday n2) n2 n1))
17752 ((eq prefer 'future) (if (= cday n1) n1 n2))
17753 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17755 (defun org-date-to-gregorian (d)
17756 "Turn any specification of date D into a Gregorian date for the calendar."
17757 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17758 ((and (listp d) (= (length d) 3)) d)
17759 ((stringp d)
17760 (let ((d (org-parse-time-string d)))
17761 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17762 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17764 (defun org-parse-time-string (s &optional nodefault zone)
17765 "Parse the standard Org time string.
17767 This should be a lot faster than the normal `parse-time-string'.
17769 If time is not given, defaults to 0:00. However, with optional
17770 NODEFAULT, hour and minute fields will be nil if not given.
17772 The optional ZONE is omitted or nil for Emacs local time, t for
17773 Universal Time, ‘wall’ for system wall clock time, or a string as
17774 in the TZ environment variable."
17775 (cond ((string-match org-ts-regexp0 s)
17776 (list 0
17777 (when (or (match-beginning 8) (not nodefault))
17778 (string-to-number (or (match-string 8 s) "0")))
17779 (when (or (match-beginning 7) (not nodefault))
17780 (string-to-number (or (match-string 7 s) "0")))
17781 (string-to-number (match-string 4 s))
17782 (string-to-number (match-string 3 s))
17783 (string-to-number (match-string 2 s))
17784 nil nil zone))
17785 ((string-match "^<[^>]+>$" s)
17786 ;; FIXME: `decode-time' needs to be called with ZONE as its
17787 ;; second argument. However, this requires at least Emacs
17788 ;; 25.1. We can do it when we switch to this version as our
17789 ;; minimal requirement.
17790 (decode-time (seconds-to-time (org-matcher-time s))))
17791 (t (error "Not a standard Org time string: %s" s))))
17793 (defun org-timestamp-up (&optional arg)
17794 "Increase the date item at the cursor by one.
17795 If the cursor is on the year, change the year. If it is on the month,
17796 the day or the time, change that.
17797 With prefix ARG, change by that many units."
17798 (interactive "p")
17799 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17801 (defun org-timestamp-down (&optional arg)
17802 "Decrease the date item at the cursor by one.
17803 If the cursor is on the year, change the year. If it is on the month,
17804 the day or the time, change that.
17805 With prefix ARG, change by that many units."
17806 (interactive "p")
17807 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17809 (defun org-timestamp-up-day (&optional arg)
17810 "Increase the date in the time stamp by one day.
17811 With prefix ARG, change that many days."
17812 (interactive "p")
17813 (if (and (not (org-at-timestamp-p 'lax))
17814 (org-at-heading-p))
17815 (org-todo 'up)
17816 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17818 (defun org-timestamp-down-day (&optional arg)
17819 "Decrease the date in the time stamp by one day.
17820 With prefix ARG, change that many days."
17821 (interactive "p")
17822 (if (and (not (org-at-timestamp-p 'lax))
17823 (org-at-heading-p))
17824 (org-todo 'down)
17825 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17827 (defun org-at-timestamp-p (&optional extended)
17828 "Non-nil if point is inside a timestamp.
17830 By default, the function only consider syntactically valid active
17831 timestamps. However, the caller may have a broader definition
17832 for timestamps. As a consequence, optional argument EXTENDED can
17833 be set to the following values
17835 `inactive'
17837 Include also syntactically valid inactive timestamps.
17839 `agenda'
17841 Include timestamps allowed in Agenda, i.e., those in
17842 properties drawers, planning lines and clock lines.
17844 `lax'
17846 Ignore context. The function matches any part of the
17847 document looking like a timestamp. This includes comments,
17848 example blocks...
17850 For backward-compatibility with Org 9.0, every other non-nil
17851 value is equivalent to `inactive'.
17853 When at a timestamp, return the position of the point as a symbol
17854 among `bracket', `after', `year', `month', `hour', `minute',
17855 `day' or a number of character from the last know part of the
17856 time stamp.
17858 When matching, the match groups are the following:
17859 group 1: year
17860 group 2: month
17861 group 3: day number
17862 group 4: day name
17863 group 5: hours, if any
17864 group 6: minutes, if any"
17865 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17866 (pos (point))
17867 (match?
17868 (let ((boundaries (org-in-regexp regexp)))
17869 (save-match-data
17870 (cond ((null boundaries) nil)
17871 ((eq extended 'lax) t)
17873 (or (and (eq extended 'agenda)
17874 (or (org-at-planning-p)
17875 (org-at-property-p)
17876 (and (bound-and-true-p
17877 org-agenda-include-inactive-timestamps)
17878 (org-at-clock-log-p))))
17879 (eq 'timestamp
17880 (save-excursion
17881 (when (= pos (cdr boundaries)) (forward-char -1))
17882 (org-element-type (org-element-context)))))))))))
17883 (cond
17884 ((not match?) nil)
17885 ((= pos (match-beginning 0)) 'bracket)
17886 ;; Distinguish location right before the closing bracket from
17887 ;; right after it.
17888 ((= pos (1- (match-end 0))) 'bracket)
17889 ((= pos (match-end 0)) 'after)
17890 ((org-pos-in-match-range pos 2) 'year)
17891 ((org-pos-in-match-range pos 3) 'month)
17892 ((org-pos-in-match-range pos 7) 'hour)
17893 ((org-pos-in-match-range pos 8) 'minute)
17894 ((or (org-pos-in-match-range pos 4)
17895 (org-pos-in-match-range pos 5)) 'day)
17896 ((and (> pos (or (match-end 8) (match-end 5)))
17897 (< pos (match-end 0)))
17898 (- pos (or (match-end 8) (match-end 5))))
17899 (t 'day))))
17901 (defun org-toggle-timestamp-type ()
17902 "Toggle the type (<active> or [inactive]) of a time stamp."
17903 (interactive)
17904 (when (org-at-timestamp-p 'lax)
17905 (let ((beg (match-beginning 0)) (end (match-end 0))
17906 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17907 (save-excursion
17908 (goto-char beg)
17909 (while (re-search-forward "[][<>]" end t)
17910 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17911 t t)))
17912 (message "Timestamp is now %sactive"
17913 (if (equal (char-after beg) ?<) "" "in")))))
17915 (defun org-at-clock-log-p ()
17916 "Non-nil if point is on a clock log line."
17917 (and (org-match-line org-clock-line-re)
17918 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17920 (defvar org-clock-history) ; defined in org-clock.el
17921 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17922 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17923 "Change the date in the time stamp at point.
17924 The date will be changed by N times WHAT. WHAT can be `day', `month',
17925 `year', `minute', `second'. If WHAT is not given, the cursor position
17926 in the timestamp determines what will be changed.
17927 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17928 (let ((origin (point))
17929 (timestamp? (org-at-timestamp-p 'lax))
17930 origin-cat
17931 with-hm inactive
17932 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17933 extra rem
17934 ts time time0 fixnext clrgx)
17935 (unless timestamp? (user-error "Not at a timestamp"))
17936 (if (and (not what) (eq timestamp? 'bracket))
17937 (org-toggle-timestamp-type)
17938 ;; Point isn't on brackets. Remember the part of the time-stamp
17939 ;; the point was in. Indeed, size of time-stamps may change,
17940 ;; but point must be kept in the same category nonetheless.
17941 (setq origin-cat timestamp?)
17942 (when (and (not what) (not (eq timestamp? 'day))
17943 org-display-custom-times
17944 (get-text-property (point) 'display)
17945 (not (get-text-property (1- (point)) 'display)))
17946 (setq timestamp? 'day))
17947 (setq timestamp? (or what timestamp?)
17948 inactive (= (char-after (match-beginning 0)) ?\[)
17949 ts (match-string 0))
17950 (replace-match "")
17951 (when (string-match
17952 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17954 (setq extra (match-string 1 ts))
17955 (when suppress-tmp-delay
17956 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17957 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17958 (setq with-hm t))
17959 (setq time0 (org-parse-time-string ts))
17960 (when (and updown
17961 (eq timestamp? 'minute)
17962 (not current-prefix-arg))
17963 ;; This looks like s-up and s-down. Change by one rounding step.
17964 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17965 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17966 (setcar (cdr time0) (+ (nth 1 time0)
17967 (if (> n 0) (- rem) (- dm rem))))))
17968 (setq time
17969 (apply #'encode-time
17970 (or (car time0) 0)
17971 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17972 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17973 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17974 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17975 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17976 (nthcdr 6 time0)))
17977 (when (and (memq timestamp? '(hour minute))
17978 extra
17979 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17980 (setq extra (org-modify-ts-extra
17981 extra
17982 (if (eq timestamp? 'hour) 2 5)
17983 n dm)))
17984 (when (integerp timestamp?)
17985 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17986 (when (eq what 'calendar)
17987 (let ((cal-date (org-get-date-from-calendar)))
17988 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17989 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17990 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17991 (setcar time0 (or (car time0) 0))
17992 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17993 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17994 (setq time (apply 'encode-time time0))))
17995 ;; Insert the new time-stamp, and ensure point stays in the same
17996 ;; category as before (i.e. not after the last position in that
17997 ;; category).
17998 (let ((pos (point)))
17999 ;; Stay before inserted string. `save-excursion' is of no use.
18000 (setq org-last-changed-timestamp
18001 (org-insert-time-stamp time with-hm inactive nil nil extra))
18002 (goto-char pos))
18003 (save-match-data
18004 (looking-at org-ts-regexp3)
18005 (goto-char
18006 (pcase origin-cat
18007 ;; `day' category ends before `hour' if any, or at the end
18008 ;; of the day name.
18009 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18010 (`hour (min (match-end 7) origin))
18011 (`minute (min (1- (match-end 8)) origin))
18012 ((pred integerp) (min (1- (match-end 0)) origin))
18013 ;; Point was right after the time-stamp. However, the
18014 ;; time-stamp length might have changed, so refer to
18015 ;; (match-end 0) instead.
18016 (`after (match-end 0))
18017 ;; `year' and `month' have both fixed size: point couldn't
18018 ;; have moved into another part.
18019 (_ origin))))
18020 ;; Update clock if on a CLOCK line.
18021 (org-clock-update-time-maybe)
18022 ;; Maybe adjust the closest clock in `org-clock-history'
18023 (when org-clock-adjust-closest
18024 (if (not (and (org-at-clock-log-p)
18025 (< 1 (length (delq nil (mapcar 'marker-position
18026 org-clock-history))))))
18027 (message "No clock to adjust")
18028 (cond ((save-excursion ; fix previous clock?
18029 (re-search-backward org-ts-regexp0 nil t)
18030 (looking-back (concat org-clock-string " \\[")
18031 (line-beginning-position)))
18032 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18033 ((save-excursion ; fix next clock?
18034 (re-search-backward org-ts-regexp0 nil t)
18035 (looking-at (concat org-ts-regexp0 "\\] =>")))
18036 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18037 (save-window-excursion
18038 ;; Find closest clock to point, adjust the previous/next one in history
18039 (let* ((p (save-excursion (org-back-to-heading t)))
18040 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18041 (clfixnth
18042 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18043 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18044 (if (not clfixpos)
18045 (message "No clock to adjust")
18046 (save-excursion
18047 (org-goto-marker-or-bmk clfixpos)
18048 (org-show-subtree)
18049 (when (re-search-forward clrgx nil t)
18050 (goto-char (match-beginning 1))
18051 (let (org-clock-adjust-closest)
18052 (org-timestamp-change n timestamp? updown))
18053 (message "Clock adjusted in %s for heading: %s"
18054 (file-name-nondirectory (buffer-file-name))
18055 (org-get-heading t t)))))))))
18056 ;; Try to recenter the calendar window, if any.
18057 (when (and org-calendar-follow-timestamp-change
18058 (get-buffer-window "*Calendar*" t)
18059 (memq timestamp? '(day month year)))
18060 (org-recenter-calendar (time-to-days time))))))
18062 (defun org-modify-ts-extra (s pos n dm)
18063 "Change the different parts of the lead-time and repeat fields in timestamp."
18064 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18065 ng h m new rem)
18066 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18067 (cond
18068 ((or (org-pos-in-match-range pos 2)
18069 (org-pos-in-match-range pos 3))
18070 (setq m (string-to-number (match-string 3 s))
18071 h (string-to-number (match-string 2 s)))
18072 (if (org-pos-in-match-range pos 2)
18073 (setq h (+ h n))
18074 (setq n (* dm (with-no-warnings (signum n))))
18075 (unless (= 0 (setq rem (% m dm)))
18076 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18077 (setq m (+ m n)))
18078 (when (< m 0) (setq m (+ m 60) h (1- h)))
18079 (when (> m 59) (setq m (- m 60) h (1+ h)))
18080 (setq h (mod h 24))
18081 (setq ng 1 new (format "-%02d:%02d" h m)))
18082 ((org-pos-in-match-range pos 6)
18083 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18084 ((org-pos-in-match-range pos 5)
18085 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18087 ((org-pos-in-match-range pos 9)
18088 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18089 ((org-pos-in-match-range pos 8)
18090 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18092 (when ng
18093 (setq s (concat
18094 (substring s 0 (match-beginning ng))
18096 (substring s (match-end ng))))))
18099 (defun org-recenter-calendar (d)
18100 "If the calendar is visible, recenter it to date D."
18101 (let ((cwin (get-buffer-window "*Calendar*" t)))
18102 (when cwin
18103 (let ((calendar-move-hook nil))
18104 (with-selected-window cwin
18105 (calendar-goto-date
18106 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18108 (defun org-goto-calendar (&optional arg)
18109 "Go to the Emacs calendar at the current date.
18110 If there is a time stamp in the current line, go to that date.
18111 A prefix ARG can be used to force the current date."
18112 (interactive "P")
18113 (let ((calendar-move-hook nil)
18114 (calendar-view-holidays-initially-flag nil)
18115 (calendar-view-diary-initially-flag nil)
18116 diff)
18117 (when (or (org-at-timestamp-p 'lax)
18118 (org-match-line (concat ".*" org-ts-regexp)))
18119 (let ((d1 (time-to-days (current-time)))
18120 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18121 (setq diff (- d2 d1))))
18122 (calendar)
18123 (calendar-goto-today)
18124 (when (and diff (not arg)) (calendar-forward-day diff))))
18126 (defun org-get-date-from-calendar ()
18127 "Return a list (month day year) of date at point in calendar."
18128 (with-current-buffer "*Calendar*"
18129 (save-match-data
18130 (calendar-cursor-to-date))))
18132 (defun org-date-from-calendar ()
18133 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18134 If there is already a time stamp at the cursor position, update it."
18135 (interactive)
18136 (if (org-at-timestamp-p 'lax)
18137 (org-timestamp-change 0 'calendar)
18138 (let ((cal-date (org-get-date-from-calendar)))
18139 (org-insert-time-stamp
18140 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18142 (defcustom org-effort-durations
18143 `(("min" . 1)
18144 ("h" . 60)
18145 ("d" . ,(* 60 8))
18146 ("w" . ,(* 60 8 5))
18147 ("m" . ,(* 60 8 5 4))
18148 ("y" . ,(* 60 8 5 40)))
18149 "Conversion factor to minutes for an effort modifier.
18151 Each entry has the form (MODIFIER . MINUTES).
18153 In an effort string, a number followed by MODIFIER is multiplied
18154 by the specified number of MINUTES to obtain an effort in
18155 minutes.
18157 For example, if the value of this variable is ((\"hours\" . 60)), then an
18158 effort string \"2hours\" is equivalent to 120 minutes."
18159 :group 'org-agenda
18160 :version "26.1"
18161 :package-version '(Org . "8.3")
18162 :type '(alist :key-type (string :tag "Modifier")
18163 :value-type (number :tag "Minutes")))
18165 (defcustom org-image-actual-width t
18166 "Should we use the actual width of images when inlining them?
18168 When set to t, always use the image width.
18170 When set to a number, use imagemagick (when available) to set
18171 the image's width to this value.
18173 When set to a number in a list, try to get the width from any
18174 #+ATTR.* keyword if it matches a width specification like
18176 #+ATTR_HTML: :width 300px
18178 and fall back on that number if none is found.
18180 When set to nil, try to get the width from an #+ATTR.* keyword
18181 and fall back on the original width if none is found.
18183 This requires Emacs >= 24.1, build with imagemagick support."
18184 :group 'org-appearance
18185 :version "24.4"
18186 :package-version '(Org . "8.0")
18187 :type '(choice
18188 (const :tag "Use the image width" t)
18189 (integer :tag "Use a number of pixels")
18190 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18191 (const :tag "Use #+ATTR* or don't resize" nil)))
18193 (defcustom org-agenda-inhibit-startup nil
18194 "Inhibit startup when preparing agenda buffers.
18195 When this variable is t, the initialization of the Org agenda
18196 buffers is inhibited: e.g. the visibility state is not set, the
18197 tables are not re-aligned, etc."
18198 :type 'boolean
18199 :version "24.3"
18200 :group 'org-agenda)
18202 (defcustom org-agenda-ignore-properties nil
18203 "Avoid updating text properties when building the agenda.
18204 Properties are used to prepare buffers for effort estimates,
18205 appointments, statistics and subtree-local categories.
18206 If you don't use these in the agenda, you can add them to this
18207 list and agenda building will be a bit faster.
18208 The value is a list, with zero or more of the symbols `effort', `appt',
18209 `stats' or `category'."
18210 :type '(set :greedy t
18211 (const effort)
18212 (const appt)
18213 (const stats)
18214 (const category))
18215 :version "26.1"
18216 :package-version '(Org . "8.3")
18217 :group 'org-agenda)
18219 ;;;; Files
18221 (defun org-save-all-org-buffers ()
18222 "Save all Org buffers without user confirmation."
18223 (interactive)
18224 (message "Saving all Org buffers...")
18225 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18226 (when (featurep 'org-id) (org-id-locations-save))
18227 (message "Saving all Org buffers... done"))
18229 (defun org-revert-all-org-buffers ()
18230 "Revert all Org buffers.
18231 Prompt for confirmation when there are unsaved changes.
18232 Be sure you know what you are doing before letting this function
18233 overwrite your changes.
18235 This function is useful in a setup where one tracks org files
18236 with a version control system, to revert on one machine after pulling
18237 changes from another. I believe the procedure must be like this:
18239 1. M-x org-save-all-org-buffers
18240 2. Pull changes from the other machine, resolve conflicts
18241 3. M-x org-revert-all-org-buffers"
18242 (interactive)
18243 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18244 (user-error "Abort"))
18245 (save-excursion
18246 (save-window-excursion
18247 (dolist (b (buffer-list))
18248 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18249 (with-current-buffer b buffer-file-name))
18250 (pop-to-buffer-same-window b)
18251 (revert-buffer t 'no-confirm)))
18252 (when (and (featurep 'org-id) org-id-track-globally)
18253 (org-id-locations-load)))))
18255 ;;;; Agenda files
18257 ;;;###autoload
18258 (defun org-switchb (&optional arg)
18259 "Switch between Org buffers.
18261 With `\\[universal-argument]' prefix, restrict available buffers to files.
18263 With `\\[universal-argument] \\[universal-argument]' \
18264 prefix, restrict available buffers to agenda files."
18265 (interactive "P")
18266 (let ((blist (org-buffer-list
18267 (cond ((equal arg '(4)) 'files)
18268 ((equal arg '(16)) 'agenda)))))
18269 (pop-to-buffer-same-window
18270 (completing-read "Org buffer: "
18271 (mapcar #'list (mapcar #'buffer-name blist))
18272 nil t))))
18274 (defun org-buffer-list (&optional predicate exclude-tmp)
18275 "Return a list of Org buffers.
18276 PREDICATE can be `export', `files' or `agenda'.
18278 export restrict the list to Export buffers.
18279 files restrict the list to buffers visiting Org files.
18280 agenda restrict the list to buffers visiting agenda files.
18282 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18283 (let* ((bfn nil)
18284 (agenda-files (and (eq predicate 'agenda)
18285 (mapcar 'file-truename (org-agenda-files t))))
18286 (filter
18287 (cond
18288 ((eq predicate 'files)
18289 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18290 ((eq predicate 'export)
18291 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18292 ((eq predicate 'agenda)
18293 (lambda (b)
18294 (with-current-buffer b
18295 (and (derived-mode-p 'org-mode)
18296 (setq bfn (buffer-file-name b))
18297 (member (file-truename bfn) agenda-files)))))
18298 (t (lambda (b) (with-current-buffer b
18299 (or (derived-mode-p 'org-mode)
18300 (string-match "\\*Org .*Export"
18301 (buffer-name b)))))))))
18302 (delq nil
18303 (mapcar
18304 (lambda(b)
18305 (if (and (funcall filter b)
18306 (or (not exclude-tmp)
18307 (not (string-match "tmp" (buffer-name b)))))
18309 nil))
18310 (buffer-list)))))
18312 (defun org-agenda-files (&optional unrestricted archives)
18313 "Get the list of agenda files.
18314 Optional UNRESTRICTED means return the full list even if a restriction
18315 is currently in place.
18316 When ARCHIVES is t, include all archive files that are really being
18317 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18318 `org-agenda-archives-mode' is t."
18319 (let ((files
18320 (cond
18321 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18322 ((stringp org-agenda-files) (org-read-agenda-file-list))
18323 ((listp org-agenda-files) org-agenda-files)
18324 (t (error "Invalid value of `org-agenda-files'")))))
18325 (setq files (apply 'append
18326 (mapcar (lambda (f)
18327 (if (file-directory-p f)
18328 (directory-files
18329 f t org-agenda-file-regexp)
18330 (list f)))
18331 files)))
18332 (when org-agenda-skip-unavailable-files
18333 (setq files (delq nil
18334 (mapcar (function
18335 (lambda (file)
18336 (and (file-readable-p file) file)))
18337 files))))
18338 (when (or (eq archives t)
18339 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18340 (setq files (org-add-archive-files files)))
18341 files))
18343 (defun org-agenda-file-p (&optional file)
18344 "Return non-nil, if FILE is an agenda file.
18345 If FILE is omitted, use the file associated with the current
18346 buffer."
18347 (let ((fname (or file (buffer-file-name))))
18348 (and fname
18349 (member (file-truename fname)
18350 (mapcar #'file-truename (org-agenda-files t))))))
18352 (defun org-edit-agenda-file-list ()
18353 "Edit the list of agenda files.
18354 Depending on setup, this either uses customize to edit the variable
18355 `org-agenda-files', or it visits the file that is holding the list. In the
18356 latter case, the buffer is set up in a way that saving it automatically kills
18357 the buffer and restores the previous window configuration."
18358 (interactive)
18359 (if (stringp org-agenda-files)
18360 (let ((cw (current-window-configuration)))
18361 (find-file org-agenda-files)
18362 (setq-local org-window-configuration cw)
18363 (add-hook 'after-save-hook
18364 (lambda ()
18365 (set-window-configuration
18366 (prog1 org-window-configuration
18367 (kill-buffer (current-buffer))))
18368 (org-install-agenda-files-menu)
18369 (message "New agenda file list installed"))
18370 nil 'local)
18371 (message "%s" (substitute-command-keys
18372 "Edit list and finish with \\[save-buffer]")))
18373 (customize-variable 'org-agenda-files)))
18375 (defun org-store-new-agenda-file-list (list)
18376 "Set new value for the agenda file list and save it correctly."
18377 (if (stringp org-agenda-files)
18378 (let ((fe (org-read-agenda-file-list t)) b u)
18379 (while (setq b (find-buffer-visiting org-agenda-files))
18380 (kill-buffer b))
18381 (with-temp-file org-agenda-files
18382 (insert
18383 (mapconcat
18384 (lambda (f) ;; Keep un-expanded entries.
18385 (if (setq u (assoc f fe))
18386 (cdr u)
18388 list "\n")
18389 "\n")))
18390 (let ((org-mode-hook nil) (org-inhibit-startup t)
18391 (org-insert-mode-line-in-empty-file nil))
18392 (setq org-agenda-files list)
18393 (customize-save-variable 'org-agenda-files org-agenda-files))))
18395 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18396 "Read the list of agenda files from a file.
18397 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18398 filenames, used by `org-store-new-agenda-file-list' to write back
18399 un-expanded file names."
18400 (when (file-directory-p org-agenda-files)
18401 (error "`org-agenda-files' cannot be a single directory"))
18402 (when (stringp org-agenda-files)
18403 (with-temp-buffer
18404 (insert-file-contents org-agenda-files)
18405 (mapcar
18406 (lambda (f)
18407 (let ((e (expand-file-name (substitute-in-file-name f)
18408 org-directory)))
18409 (if pair-with-expansion
18410 (cons e f)
18411 e)))
18412 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18414 ;;;###autoload
18415 (defun org-cycle-agenda-files ()
18416 "Cycle through the files in `org-agenda-files'.
18417 If the current buffer visits an agenda file, find the next one in the list.
18418 If the current buffer does not, find the first agenda file."
18419 (interactive)
18420 (let* ((fs (or (org-agenda-files t)
18421 (user-error "No agenda files")))
18422 (files (copy-sequence fs))
18423 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18424 file)
18425 (when tcf
18426 (while (and (setq file (pop files))
18427 (not (equal (file-truename file) tcf)))))
18428 (find-file (car (or files fs)))
18429 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18431 (defun org-agenda-file-to-front (&optional to-end)
18432 "Move/add the current file to the top of the agenda file list.
18433 If the file is not present in the list, it is added to the front. If it is
18434 present, it is moved there. With optional argument TO-END, add/move to the
18435 end of the list."
18436 (interactive "P")
18437 (let ((org-agenda-skip-unavailable-files nil)
18438 (file-alist (mapcar (lambda (x)
18439 (cons (file-truename x) x))
18440 (org-agenda-files t)))
18441 (ctf (file-truename
18442 (or buffer-file-name
18443 (user-error "Please save the current buffer to a file"))))
18444 x had)
18445 (setq x (assoc ctf file-alist) had x)
18447 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18448 (if to-end
18449 (setq file-alist (append (delq x file-alist) (list x)))
18450 (setq file-alist (cons x (delq x file-alist))))
18451 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18452 (org-install-agenda-files-menu)
18453 (message "File %s to %s of agenda file list"
18454 (if had "moved" "added") (if to-end "end" "front"))))
18456 (defun org-remove-file (&optional file)
18457 "Remove current file from the list of files in variable `org-agenda-files'.
18458 These are the files which are being checked for agenda entries.
18459 Optional argument FILE means use this file instead of the current."
18460 (interactive)
18461 (let* ((org-agenda-skip-unavailable-files nil)
18462 (file (or file buffer-file-name
18463 (user-error "Current buffer does not visit a file")))
18464 (true-file (file-truename file))
18465 (afile (abbreviate-file-name file))
18466 (files (delq nil (mapcar
18467 (lambda (x)
18468 (unless (equal true-file
18469 (file-truename x))
18471 (org-agenda-files t)))))
18472 (if (not (= (length files) (length (org-agenda-files t))))
18473 (progn
18474 (org-store-new-agenda-file-list files)
18475 (org-install-agenda-files-menu)
18476 (message "Removed from Org Agenda list: %s" afile))
18477 (message "File was not in list: %s (not removed)" afile))))
18479 (defun org-file-menu-entry (file)
18480 (vector file (list 'find-file file) t))
18482 (defun org-check-agenda-file (file)
18483 "Make sure FILE exists. If not, ask user what to do."
18484 (unless (file-exists-p file)
18485 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18486 (abbreviate-file-name file))
18487 (let ((r (downcase (read-char-exclusive))))
18488 (cond
18489 ((equal r ?r)
18490 (org-remove-file file)
18491 (throw 'nextfile t))
18492 (t (user-error "Abort"))))))
18494 (defun org-get-agenda-file-buffer (file)
18495 "Get an agenda buffer visiting FILE.
18496 If the buffer needs to be created, add it to the list of buffers
18497 which might be released later."
18498 (let ((buf (org-find-base-buffer-visiting file)))
18499 (if buf
18500 buf ; just return it
18501 ;; Make a new buffer and remember it
18502 (setq buf (find-file-noselect file))
18503 (when buf (push buf org-agenda-new-buffers))
18504 buf)))
18506 (defun org-release-buffers (blist)
18507 "Release all buffers in list, asking the user for confirmation when needed.
18508 When a buffer is unmodified, it is just killed. When modified, it is saved
18509 \(if the user agrees) and then killed."
18510 (let (file)
18511 (dolist (buf blist)
18512 (setq file (buffer-file-name buf))
18513 (when (and (buffer-modified-p buf)
18514 file
18515 (y-or-n-p (format "Save file %s? " file)))
18516 (with-current-buffer buf (save-buffer)))
18517 (kill-buffer buf))))
18519 (defun org-agenda-prepare-buffers (files)
18520 "Create buffers for all agenda files, protect archived trees and comments."
18521 (interactive)
18522 (let ((pa '(:org-archived t))
18523 (pc '(:org-comment t))
18524 (pall '(:org-archived t :org-comment t))
18525 (inhibit-read-only t)
18526 (org-inhibit-startup org-agenda-inhibit-startup)
18527 (rea (concat ":" org-archive-tag ":"))
18528 re pos)
18529 (setq org-tag-alist-for-agenda nil
18530 org-tag-groups-alist-for-agenda nil)
18531 (save-excursion
18532 (save-restriction
18533 (dolist (file files)
18534 (catch 'nextfile
18535 (if (bufferp file)
18536 (set-buffer file)
18537 (org-check-agenda-file file)
18538 (set-buffer (org-get-agenda-file-buffer file)))
18539 (widen)
18540 (org-set-regexps-and-options 'tags-only)
18541 (setq pos (point))
18542 (or (memq 'category org-agenda-ignore-properties)
18543 (org-refresh-category-properties))
18544 (or (memq 'stats org-agenda-ignore-properties)
18545 (org-refresh-stats-properties))
18546 (or (memq 'effort org-agenda-ignore-properties)
18547 (org-refresh-effort-properties))
18548 (or (memq 'appt org-agenda-ignore-properties)
18549 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18550 (setq org-todo-keywords-for-agenda
18551 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18552 (setq org-done-keywords-for-agenda
18553 (append org-done-keywords-for-agenda org-done-keywords))
18554 (setq org-todo-keyword-alist-for-agenda
18555 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18556 (setq org-tag-alist-for-agenda
18557 (org-uniquify
18558 (append org-tag-alist-for-agenda
18559 org-current-tag-alist)))
18560 ;; Merge current file's tag groups into global
18561 ;; `org-tag-groups-alist-for-agenda'.
18562 (when org-group-tags
18563 (dolist (alist org-tag-groups-alist)
18564 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18565 (if old
18566 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18567 (push alist org-tag-groups-alist-for-agenda)))))
18568 (org-with-silent-modifications
18569 (save-excursion
18570 (remove-text-properties (point-min) (point-max) pall)
18571 (when org-agenda-skip-archived-trees
18572 (goto-char (point-min))
18573 (while (re-search-forward rea nil t)
18574 (when (org-at-heading-p t)
18575 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18576 (goto-char (point-min))
18577 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18578 (while (re-search-forward re nil t)
18579 (when (save-match-data (org-in-commented-heading-p t))
18580 (add-text-properties
18581 (match-beginning 0) (org-end-of-subtree t) pc)))))
18582 (goto-char pos)))))
18583 (setq org-todo-keywords-for-agenda
18584 (org-uniquify org-todo-keywords-for-agenda))
18585 (setq org-todo-keyword-alist-for-agenda
18586 (org-uniquify org-todo-keyword-alist-for-agenda))))
18589 ;;;; CDLaTeX minor mode
18591 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18592 "Keymap for the minor `org-cdlatex-mode'.")
18594 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18595 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18596 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18597 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18598 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18600 (defvar org-cdlatex-texmathp-advice-is-done nil
18601 "Flag remembering if we have applied the advice to texmathp already.")
18603 (define-minor-mode org-cdlatex-mode
18604 "Toggle the minor `org-cdlatex-mode'.
18605 This mode supports entering LaTeX environment and math in LaTeX fragments
18606 in Org mode.
18607 \\{org-cdlatex-mode-map}"
18608 nil " OCDL" nil
18609 (when org-cdlatex-mode
18610 (require 'cdlatex)
18611 (run-hooks 'cdlatex-mode-hook)
18612 (cdlatex-compute-tables))
18613 (unless org-cdlatex-texmathp-advice-is-done
18614 (setq org-cdlatex-texmathp-advice-is-done t)
18615 (defadvice texmathp (around org-math-always-on activate)
18616 "Always return t in Org buffers.
18617 This is because we want to insert math symbols without dollars even outside
18618 the LaTeX math segments. If Org mode thinks that point is actually inside
18619 an embedded LaTeX fragment, let `texmathp' do its job.
18620 `\\[org-cdlatex-mode-map]'"
18621 (interactive)
18622 (let (p)
18623 (cond
18624 ((not (derived-mode-p 'org-mode)) ad-do-it)
18625 ((eq this-command 'cdlatex-math-symbol)
18626 (setq ad-return-value t
18627 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18629 (let ((p (org-inside-LaTeX-fragment-p)))
18630 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18631 (setq ad-return-value t
18632 texmathp-why '("Org mode embedded math" . 0))
18633 (when p ad-do-it)))))))))
18635 (defun turn-on-org-cdlatex ()
18636 "Unconditionally turn on `org-cdlatex-mode'."
18637 (org-cdlatex-mode 1))
18639 (defun org-try-cdlatex-tab ()
18640 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18641 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18642 - inside a LaTeX fragment, or
18643 - after the first word in a line, where an abbreviation expansion could
18644 insert a LaTeX environment."
18645 (when org-cdlatex-mode
18646 (cond
18647 ;; Before any word on the line: No expansion possible.
18648 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18649 ;; Just after first word on the line: Expand it. Make sure it
18650 ;; cannot happen on headlines, though.
18651 ((save-excursion
18652 (skip-chars-backward "a-zA-Z0-9*")
18653 (skip-chars-backward " \t")
18654 (and (bolp) (not (org-at-heading-p))))
18655 (cdlatex-tab) t)
18656 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18658 (defun org-cdlatex-underscore-caret (&optional _arg)
18659 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18660 Revert to the normal definition outside of these fragments."
18661 (interactive "P")
18662 (if (org-inside-LaTeX-fragment-p)
18663 (call-interactively 'cdlatex-sub-superscript)
18664 (let (org-cdlatex-mode)
18665 (call-interactively (key-binding (vector last-input-event))))))
18667 (defun org-cdlatex-math-modify (&optional _arg)
18668 "Execute `cdlatex-math-modify' in LaTeX fragments.
18669 Revert to the normal definition outside of these fragments."
18670 (interactive "P")
18671 (if (org-inside-LaTeX-fragment-p)
18672 (call-interactively 'cdlatex-math-modify)
18673 (let (org-cdlatex-mode)
18674 (call-interactively (key-binding (vector last-input-event))))))
18676 (defun org-cdlatex-environment-indent (&optional environment item)
18677 "Execute `cdlatex-environment' and indent the inserted environment.
18679 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18681 The inserted environment is indented to current indentation
18682 unless point is at the beginning of the line, in which the
18683 environment remains unintended."
18684 (interactive)
18685 ;; cdlatex-environment always return nil. Therefore, capture output
18686 ;; first and determine if an environment was selected.
18687 (let* ((beg (point-marker))
18688 (end (copy-marker (point) t))
18689 (inserted (progn
18690 (ignore-errors (cdlatex-environment environment item))
18691 (< beg end)))
18692 ;; Figure out how many lines to move forward after the
18693 ;; environment has been inserted.
18694 (lines (when inserted
18695 (save-excursion
18696 (- (cl-loop while (< beg (point))
18697 with x = 0
18698 do (forward-line -1)
18699 (cl-incf x)
18700 finally return x)
18701 (if (progn (goto-char beg)
18702 (and (progn (skip-chars-forward " \t") (eolp))
18703 (progn (skip-chars-backward " \t") (bolp))))
18704 1 0)))))
18705 (env (org-trim (delete-and-extract-region beg end))))
18706 (when inserted
18707 ;; Get indentation of next line unless at column 0.
18708 (let ((ind (if (bolp) 0
18709 (save-excursion
18710 (org-return-indent)
18711 (prog1 (org-get-indentation)
18712 (when (progn (skip-chars-forward " \t") (eolp))
18713 (delete-region beg (point)))))))
18714 (bol (progn (skip-chars-backward " \t") (bolp))))
18715 ;; Insert a newline before environment unless at column zero
18716 ;; to "escape" the current line. Insert a newline if
18717 ;; something is one the same line as \end{ENVIRONMENT}.
18718 (insert
18719 (concat (unless bol "\n") env
18720 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18721 (unless (zerop ind)
18722 (save-excursion
18723 (goto-char beg)
18724 (while (< (point) end)
18725 (unless (eolp) (indent-line-to ind))
18726 (forward-line))))
18727 (goto-char beg)
18728 (forward-line lines)
18729 (indent-line-to ind)))
18730 (set-marker beg nil)
18731 (set-marker end nil)))
18734 ;;;; LaTeX fragments
18736 (defun org-inside-LaTeX-fragment-p ()
18737 "Test if point is inside a LaTeX fragment.
18738 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18739 sequence appearing also before point.
18740 Even though the matchers for math are configurable, this function assumes
18741 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18742 delimiters are skipped when they have been removed by customization.
18743 The return value is nil, or a cons cell with the delimiter and the
18744 position of this delimiter.
18746 This function does a reasonably good job, but can locally be fooled by
18747 for example currency specifications. For example it will assume being in
18748 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18749 fragments that are properly closed, but during editing, we have to live
18750 with the uncertainty caused by missing closing delimiters. This function
18751 looks only before point, not after."
18752 (catch 'exit
18753 (let ((pos (point))
18754 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18755 (lim (save-excursion (org-backward-paragraph) (point)))
18756 dd-on str (start 0) m re)
18757 (goto-char pos)
18758 (when dodollar
18759 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18760 re (nth 1 (assoc "$" org-latex-regexps)))
18761 (while (string-match re str start)
18762 (cond
18763 ((= (match-end 0) (length str))
18764 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18765 ((= (match-end 0) (- (length str) 5))
18766 (throw 'exit nil))
18767 (t (setq start (match-end 0))))))
18768 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18769 (goto-char pos)
18770 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18771 (and (match-beginning 2) (throw 'exit nil))
18772 ;; count $$
18773 (while (re-search-backward "\\$\\$" lim t)
18774 (setq dd-on (not dd-on)))
18775 (goto-char pos)
18776 (when dd-on (cons "$$" m))))))
18778 (defun org-inside-latex-macro-p ()
18779 "Is point inside a LaTeX macro or its arguments?"
18780 (save-match-data
18781 (org-in-regexp
18782 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18784 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18785 "Build an overlay between BEG and END using IMAGE file.
18786 Argument IMAGETYPE is the extension of the displayed image,
18787 as a string. It defaults to \"png\"."
18788 (let ((ov (make-overlay beg end))
18789 (imagetype (or (intern imagetype) 'png)))
18790 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18791 (overlay-put ov 'evaporate t)
18792 (overlay-put ov
18793 'modification-hooks
18794 (list (lambda (o _flag _beg _end &optional _l)
18795 (delete-overlay o))))
18796 (overlay-put ov
18797 'display
18798 (list 'image :type imagetype :file image :ascent 'center))))
18800 (defun org--list-latex-overlays (&optional beg end)
18801 "List all Org LaTeX overlays in current buffer.
18802 Limit to overlays between BEG and END when those are provided."
18803 (cl-remove-if-not
18804 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18805 (overlays-in (or beg (point-min)) (or end (point-max)))))
18807 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18808 "Remove all overlays with LaTeX fragment images in current buffer.
18809 When optional arguments BEG and END are non-nil, remove all
18810 overlays between them instead. Return a non-nil value when some
18811 overlays were removed, nil otherwise."
18812 (let ((overlays (org--list-latex-overlays beg end)))
18813 (mapc #'delete-overlay overlays)
18814 overlays))
18816 (defun org-toggle-latex-fragment (&optional arg)
18817 "Preview the LaTeX fragment at point, or all locally or globally.
18819 If the cursor is on a LaTeX fragment, create the image and overlay
18820 it over the source code, if there is none. Remove it otherwise.
18821 If there is no fragment at point, display all fragments in the
18822 current section.
18824 With prefix ARG, preview or clear image for all fragments in the
18825 current subtree or in the whole buffer when used before the first
18826 headline. With a prefix ARG `\\[universal-argument] \
18827 \\[universal-argument]' preview or clear images
18828 for all fragments in the buffer."
18829 (interactive "P")
18830 (when (display-graphic-p)
18831 (catch 'exit
18832 (save-excursion
18833 (let (beg end msg)
18834 (cond
18835 ((or (equal arg '(16))
18836 (and (equal arg '(4))
18837 (org-with-limited-levels (org-before-first-heading-p))))
18838 (if (org-remove-latex-fragment-image-overlays)
18839 (progn (message "LaTeX fragments images removed from buffer")
18840 (throw 'exit nil))
18841 (setq msg "Creating images for buffer...")))
18842 ((equal arg '(4))
18843 (org-with-limited-levels (org-back-to-heading t))
18844 (setq beg (point))
18845 (setq end (progn (org-end-of-subtree t) (point)))
18846 (if (org-remove-latex-fragment-image-overlays beg end)
18847 (progn
18848 (message "LaTeX fragment images removed from subtree")
18849 (throw 'exit nil))
18850 (setq msg "Creating images for subtree...")))
18851 ((let ((datum (org-element-context)))
18852 (when (memq (org-element-type datum)
18853 '(latex-environment latex-fragment))
18854 (setq beg (org-element-property :begin datum))
18855 (setq end (org-element-property :end datum))
18856 (if (org-remove-latex-fragment-image-overlays beg end)
18857 (progn (message "LaTeX fragment image removed")
18858 (throw 'exit nil))
18859 (setq msg "Creating image...")))))
18861 (org-with-limited-levels
18862 (setq beg (if (org-at-heading-p) (line-beginning-position)
18863 (outline-previous-heading)
18864 (point)))
18865 (setq end (progn (outline-next-heading) (point)))
18866 (if (org-remove-latex-fragment-image-overlays beg end)
18867 (progn
18868 (message "LaTeX fragment images removed from section")
18869 (throw 'exit nil))
18870 (setq msg "Creating images for section...")))))
18871 (let ((file (buffer-file-name (buffer-base-buffer))))
18872 (org-format-latex
18873 (concat org-preview-latex-image-directory "org-ltximg")
18874 beg end
18875 ;; Emacs cannot overlay images from remote hosts. Create
18876 ;; it in `temporary-file-directory' instead.
18877 (if (or (not file) (file-remote-p file))
18878 temporary-file-directory
18879 default-directory)
18880 'overlays msg 'forbuffer org-preview-latex-default-process))
18881 (message (concat msg "done")))))))
18883 (defun org-format-latex
18884 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18885 "Replace LaTeX fragments with links to an image.
18887 The function takes care of creating the replacement image.
18889 Only consider fragments between BEG and END when those are
18890 provided.
18892 When optional argument OVERLAYS is non-nil, display the image on
18893 top of the fragment instead of replacing it.
18895 PROCESSING-TYPE is the conversion method to use, as a symbol.
18897 Some of the options can be changed using the variable
18898 `org-format-latex-options', which see."
18899 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18900 (unless (eq processing-type 'verbatim)
18901 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18902 (cnt 0)
18903 checkdir-flag)
18904 (goto-char (or beg (point-min)))
18905 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18906 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18907 (overlay-recenter (or end (point-max))))
18908 (while (re-search-forward math-regexp end t)
18909 (unless (and overlays
18910 (eq (get-char-property (point) 'org-overlay-type)
18911 'org-latex-overlay))
18912 (let* ((context (org-element-context))
18913 (type (org-element-type context)))
18914 (when (memq type '(latex-environment latex-fragment))
18915 (let ((block-type (eq type 'latex-environment))
18916 (value (org-element-property :value context))
18917 (beg (org-element-property :begin context))
18918 (end (save-excursion
18919 (goto-char (org-element-property :end context))
18920 (skip-chars-backward " \r\t\n")
18921 (point))))
18922 (cond
18923 ((eq processing-type 'mathjax)
18924 ;; Prepare for MathJax processing.
18925 (if (not (string-match "\\`\\$\\$?" value))
18926 (goto-char end)
18927 (delete-region beg end)
18928 (if (string= (match-string 0 value) "$$")
18929 (insert "\\[" (substring value 2 -2) "\\]")
18930 (insert "\\(" (substring value 1 -1) "\\)"))))
18931 ((assq processing-type org-preview-latex-process-alist)
18932 ;; Process to an image.
18933 (cl-incf cnt)
18934 (goto-char beg)
18935 (let* ((processing-info
18936 (cdr (assq processing-type org-preview-latex-process-alist)))
18937 (face (face-at-point))
18938 ;; Get the colors from the face at point.
18940 (let ((color (plist-get org-format-latex-options
18941 :foreground)))
18942 (if (and forbuffer (eq color 'auto))
18943 (face-attribute face :foreground nil 'default)
18944 color)))
18946 (let ((color (plist-get org-format-latex-options
18947 :background)))
18948 (if (and forbuffer (eq color 'auto))
18949 (face-attribute face :background nil 'default)
18950 color)))
18951 (hash (sha1 (prin1-to-string
18952 (list org-format-latex-header
18953 org-latex-default-packages-alist
18954 org-latex-packages-alist
18955 org-format-latex-options
18956 forbuffer value fg bg))))
18957 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18958 (absprefix (expand-file-name prefix dir))
18959 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18960 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18961 (sep (and block-type "\n\n"))
18962 (link (concat sep "[[file:" linkfile "]]" sep))
18963 (options
18964 (org-combine-plists
18965 org-format-latex-options
18966 `(:foreground ,fg :background ,bg))))
18967 (when msg (message msg cnt))
18968 (unless checkdir-flag ; Ensure the directory exists.
18969 (setq checkdir-flag t)
18970 (let ((todir (file-name-directory absprefix)))
18971 (unless (file-directory-p todir)
18972 (make-directory todir t))))
18973 (unless (file-exists-p movefile)
18974 (org-create-formula-image
18975 value movefile options forbuffer processing-type))
18976 (if overlays
18977 (progn
18978 (dolist (o (overlays-in beg end))
18979 (when (eq (overlay-get o 'org-overlay-type)
18980 'org-latex-overlay)
18981 (delete-overlay o)))
18982 (org--format-latex-make-overlay beg end movefile imagetype)
18983 (goto-char end))
18984 (delete-region beg end)
18985 (insert
18986 (org-add-props link
18987 (list 'org-latex-src
18988 (replace-regexp-in-string "\"" "" value)
18989 'org-latex-src-embed-type
18990 (if block-type 'paragraph 'character)))))))
18991 ((eq processing-type 'mathml)
18992 ;; Process to MathML.
18993 (unless (org-format-latex-mathml-available-p)
18994 (user-error "LaTeX to MathML converter not configured"))
18995 (cl-incf cnt)
18996 (when msg (message msg cnt))
18997 (goto-char beg)
18998 (delete-region beg end)
18999 (insert (org-format-latex-as-mathml
19000 value block-type prefix dir)))
19002 (error "Unknown conversion process %s for LaTeX fragments"
19003 processing-type)))))))))))
19005 (defun org-create-math-formula (latex-frag &optional mathml-file)
19006 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19007 Use `org-latex-to-mathml-convert-command'. If the conversion is
19008 sucessful, return the portion between \"<math...> </math>\"
19009 elements otherwise return nil. When MATHML-FILE is specified,
19010 write the results in to that file. When invoked as an
19011 interactive command, prompt for LATEX-FRAG, with initial value
19012 set to the current active region and echo the results for user
19013 inspection."
19014 (interactive (list (let ((frag (when (org-region-active-p)
19015 (buffer-substring-no-properties
19016 (region-beginning) (region-end)))))
19017 (read-string "LaTeX Fragment: " frag nil frag))))
19018 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19019 (let* ((tmp-in-file
19020 (let ((file (file-relative-name
19021 (make-temp-name (expand-file-name "ltxmathml-in")))))
19022 (write-region latex-frag nil file)
19023 file))
19024 (tmp-out-file (file-relative-name
19025 (make-temp-name (expand-file-name "ltxmathml-out"))))
19026 (cmd (format-spec
19027 org-latex-to-mathml-convert-command
19028 `((?j . ,(and org-latex-to-mathml-jar-file
19029 (shell-quote-argument
19030 (expand-file-name
19031 org-latex-to-mathml-jar-file))))
19032 (?I . ,(shell-quote-argument tmp-in-file))
19033 (?i . ,latex-frag)
19034 (?o . ,(shell-quote-argument tmp-out-file)))))
19035 mathml shell-command-output)
19036 (when (called-interactively-p 'any)
19037 (unless (org-format-latex-mathml-available-p)
19038 (user-error "LaTeX to MathML converter not configured")))
19039 (message "Running %s" cmd)
19040 (setq shell-command-output (shell-command-to-string cmd))
19041 (setq mathml
19042 (when (file-readable-p tmp-out-file)
19043 (with-current-buffer (find-file-noselect tmp-out-file t)
19044 (goto-char (point-min))
19045 (when (re-search-forward
19046 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19047 (regexp-quote
19048 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19049 nil t)
19050 (prog1 (match-string 0) (kill-buffer))))))
19051 (cond
19052 (mathml
19053 (setq mathml
19054 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19055 (when mathml-file
19056 (write-region mathml nil mathml-file))
19057 (when (called-interactively-p 'any)
19058 (message mathml)))
19059 ((message "LaTeX to MathML conversion failed")
19060 (message shell-command-output)))
19061 (delete-file tmp-in-file)
19062 (when (file-exists-p tmp-out-file)
19063 (delete-file tmp-out-file))
19064 mathml))
19066 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19067 prefix &optional dir)
19068 "Use `org-create-math-formula' but check local cache first."
19069 (let* ((absprefix (expand-file-name prefix dir))
19070 (print-length nil) (print-level nil)
19071 (formula-id (concat
19072 "formula-"
19073 (sha1
19074 (prin1-to-string
19075 (list latex-frag
19076 org-latex-to-mathml-convert-command)))))
19077 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19078 (formula-cache-dir (file-name-directory formula-cache)))
19080 (unless (file-directory-p formula-cache-dir)
19081 (make-directory formula-cache-dir t))
19083 (unless (file-exists-p formula-cache)
19084 (org-create-math-formula latex-frag formula-cache))
19086 (if (file-exists-p formula-cache)
19087 ;; Successful conversion. Return the link to MathML file.
19088 (org-add-props
19089 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19090 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19091 'org-latex-src-embed-type (if latex-frag-type
19092 'paragraph 'character)))
19093 ;; Failed conversion. Return the LaTeX fragment verbatim
19094 latex-frag)))
19096 (defun org--get-display-dpi ()
19097 "Get the DPI of the display.
19098 The function assumes that the display has the same pixel width in
19099 the horizontal and vertical directions."
19100 (if (display-graphic-p)
19101 (round (/ (display-pixel-height)
19102 (/ (display-mm-height) 25.4)))
19103 (error "Attempt to calculate the dpi of a non-graphic display")))
19105 (defun org-create-formula-image
19106 (string tofile options buffer &optional processing-type)
19107 "Create an image from LaTeX source using external processes.
19109 The LaTeX STRING is saved to a temporary LaTeX file, then
19110 converted to an image file by process PROCESSING-TYPE defined in
19111 `org-preview-latex-process-alist'. A nil value defaults to
19112 `org-preview-latex-default-process'.
19114 The generated image file is eventually moved to TOFILE.
19116 The OPTIONS argument controls the size, foreground color and
19117 background color of the generated image.
19119 When BUFFER non-nil, this function is used for LaTeX previewing.
19120 Otherwise, it is used to deal with LaTeX snippets showed in
19121 a HTML file."
19122 (let* ((processing-type (or processing-type
19123 org-preview-latex-default-process))
19124 (processing-info
19125 (cdr (assq processing-type org-preview-latex-process-alist)))
19126 (programs (plist-get processing-info :programs))
19127 (error-message (or (plist-get processing-info :message) ""))
19128 (use-xcolor (plist-get processing-info :use-xcolor))
19129 (image-input-type (plist-get processing-info :image-input-type))
19130 (image-output-type (plist-get processing-info :image-output-type))
19131 (post-clean (or (plist-get processing-info :post-clean)
19132 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19133 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19134 (latex-header
19135 (or (plist-get processing-info :latex-header)
19136 (org-latex-make-preamble
19137 (org-export-get-environment (org-export-get-backend 'latex))
19138 org-format-latex-header
19139 'snippet)))
19140 (latex-compiler (plist-get processing-info :latex-compiler))
19141 (image-converter (plist-get processing-info :image-converter))
19142 (tmpdir temporary-file-directory)
19143 (texfilebase (make-temp-name
19144 (expand-file-name "orgtex" tmpdir)))
19145 (texfile (concat texfilebase ".tex"))
19146 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19147 '(1.0 . 1.0)))
19148 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19149 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19150 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19151 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19152 "Black"))
19153 (bg (or (plist-get options (if buffer :background :html-background))
19154 "Transparent"))
19155 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19156 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19157 (dolist (program programs)
19158 (org-check-external-command program error-message))
19159 (if use-xcolor
19160 (progn (if (eq fg 'default)
19161 (setq fg (org-latex-color :foreground))
19162 (setq fg (org-latex-color-format fg)))
19163 (if (eq bg 'default)
19164 (setq bg (org-latex-color :background))
19165 (setq bg (org-latex-color-format
19166 (if (string= bg "Transparent") "white" bg))))
19167 (with-temp-file texfile
19168 (insert latex-header)
19169 (insert "\n\\begin{document}\n"
19170 "\\definecolor{fg}{rgb}{" fg "}\n"
19171 "\\definecolor{bg}{rgb}{" bg "}\n"
19172 "\n\\pagecolor{bg}\n"
19173 "\n{\\color{fg}\n"
19174 string
19175 "\n}\n"
19176 "\n\\end{document}\n")))
19177 (if (eq fg 'default)
19178 (setq fg (org-dvipng-color :foreground))
19179 (unless (string= fg "Transparent")
19180 (setq fg (org-dvipng-color-format fg))))
19181 (if (eq bg 'default)
19182 (setq bg (org-dvipng-color :background))
19183 (unless (string= bg "Transparent")
19184 (setq bg (org-dvipng-color-format bg))))
19185 (with-temp-file texfile
19186 (insert latex-header)
19187 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19189 (let* ((err-msg (format "Please adjust `%s' part of \
19190 `org-preview-latex-process-alist'."
19191 processing-type))
19192 (image-input-file
19193 (org-compile-file
19194 texfile latex-compiler image-input-type err-msg log-buf))
19195 (image-output-file
19196 (org-compile-file
19197 image-input-file image-converter image-output-type err-msg log-buf
19198 `((?F . ,(shell-quote-argument fg))
19199 (?B . ,(shell-quote-argument bg))
19200 (?D . ,(shell-quote-argument (format "%s" dpi)))
19201 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19202 (copy-file image-output-file tofile 'replace)
19203 (dolist (e post-clean)
19204 (when (file-exists-p (concat texfilebase e))
19205 (delete-file (concat texfilebase e))))
19206 image-output-file)))
19208 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19209 "Fill a LaTeX header template TPL.
19210 In the template, the following place holders will be recognized:
19212 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19213 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19214 [PACKAGES] \\usepackage statements for PKG
19215 [NO-PACKAGES] do not include PKG
19216 [EXTRA] the string EXTRA
19217 [NO-EXTRA] do not include EXTRA
19219 For backward compatibility, if both the positive and the negative place
19220 holder is missing, the positive one (without the \"NO-\") will be
19221 assumed to be present at the end of the template.
19222 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19223 EXTRA is a string.
19224 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19225 (let (rpl (end ""))
19226 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19227 (setq rpl (if (or (match-end 1) (not def-pkg))
19228 "" (org-latex-packages-to-string def-pkg snippets-p t))
19229 tpl (replace-match rpl t t tpl))
19230 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19232 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19233 (setq rpl (if (or (match-end 1) (not pkg))
19234 "" (org-latex-packages-to-string pkg snippets-p t))
19235 tpl (replace-match rpl t t tpl))
19236 (when pkg (setq end
19237 (concat end "\n"
19238 (org-latex-packages-to-string pkg snippets-p)))))
19240 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19241 (setq rpl (if (or (match-end 1) (not extra))
19242 "" (concat extra "\n"))
19243 tpl (replace-match rpl t t tpl))
19244 (when (and extra (string-match "\\S-" extra))
19245 (setq end (concat end "\n" extra))))
19247 (if (string-match "\\S-" end)
19248 (concat tpl "\n" end)
19249 tpl)))
19251 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19252 "Turn an alist of packages into a string with the \\usepackage macros."
19253 (setq pkg (mapconcat (lambda(p)
19254 (cond
19255 ((stringp p) p)
19256 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19257 (format "%% Package %s omitted" (cadr p)))
19258 ((equal "" (car p))
19259 (format "\\usepackage{%s}" (cadr p)))
19261 (format "\\usepackage[%s]{%s}"
19262 (car p) (cadr p)))))
19264 "\n"))
19265 (if newline (concat pkg "\n") pkg))
19267 (defun org-dvipng-color (attr)
19268 "Return a RGB color specification for dvipng."
19269 (org-dvipng-color-format (face-attribute 'default attr nil)))
19271 (defun org-dvipng-color-format (color-name)
19272 "Convert COLOR-NAME to a RGB color value for dvipng."
19273 (apply #'format "rgb %s %s %s"
19274 (mapcar 'org-normalize-color
19275 (color-values color-name))))
19277 (defun org-latex-color (attr)
19278 "Return a RGB color for the LaTeX color package."
19279 (org-latex-color-format (face-attribute 'default attr nil)))
19281 (defun org-latex-color-format (color-name)
19282 "Convert COLOR-NAME to a RGB color value."
19283 (apply #'format "%s,%s,%s"
19284 (mapcar 'org-normalize-color
19285 (color-values color-name))))
19287 (defun org-normalize-color (value)
19288 "Return string to be used as color value for an RGB component."
19289 (format "%g" (/ value 65535.0)))
19293 ;; Image display
19295 (defvar-local org-inline-image-overlays nil)
19297 (defun org-toggle-inline-images (&optional include-linked)
19298 "Toggle the display of inline images.
19299 INCLUDE-LINKED is passed to `org-display-inline-images'."
19300 (interactive "P")
19301 (if org-inline-image-overlays
19302 (progn
19303 (org-remove-inline-images)
19304 (when (called-interactively-p 'interactive)
19305 (message "Inline image display turned off")))
19306 (org-display-inline-images include-linked)
19307 (when (called-interactively-p 'interactive)
19308 (message (if org-inline-image-overlays
19309 (format "%d images displayed inline"
19310 (length org-inline-image-overlays))
19311 "No images to display inline")))))
19313 (defun org-redisplay-inline-images ()
19314 "Refresh the display of inline images."
19315 (interactive)
19316 (if (not org-inline-image-overlays)
19317 (org-toggle-inline-images)
19318 (org-toggle-inline-images)
19319 (org-toggle-inline-images)))
19321 (defun org-display-inline-images (&optional include-linked refresh beg end)
19322 "Display inline images.
19324 An inline image is a link which follows either of these
19325 conventions:
19327 1. Its path is a file with an extension matching return value
19328 from `image-file-name-regexp' and it has no contents.
19330 2. Its description consists in a single link of the previous
19331 type.
19333 When optional argument INCLUDE-LINKED is non-nil, also links with
19334 a text description part will be inlined. This can be nice for
19335 a quick look at those images, but it does not reflect what
19336 exported files will look like.
19338 When optional argument REFRESH is non-nil, refresh existing
19339 images between BEG and END. This will create new image displays
19340 only if necessary. BEG and END default to the buffer
19341 boundaries."
19342 (interactive "P")
19343 (when (display-graphic-p)
19344 (unless refresh
19345 (org-remove-inline-images)
19346 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19347 (org-with-wide-buffer
19348 (goto-char (or beg (point-min)))
19349 (let ((case-fold-search t)
19350 (file-extension-re (image-file-name-regexp)))
19351 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19352 (let ((link (save-match-data (org-element-context))))
19353 ;; Check if we're at an inline image.
19354 (when (and (equal (org-element-property :type link) "file")
19355 (or include-linked
19356 (not (org-element-property :contents-begin link)))
19357 (let ((parent (org-element-property :parent link)))
19358 (or (not (eq (org-element-type parent) 'link))
19359 (not (cdr (org-element-contents parent)))))
19360 (string-match-p file-extension-re
19361 (org-element-property :path link)))
19362 (let ((file (expand-file-name
19363 (org-link-unescape
19364 (org-element-property :path link)))))
19365 (when (file-exists-p file)
19366 (let ((width
19367 ;; Apply `org-image-actual-width' specifications.
19368 (cond
19369 ((not (image-type-available-p 'imagemagick)) nil)
19370 ((eq org-image-actual-width t) nil)
19371 ((listp org-image-actual-width)
19373 ;; First try to find a width among
19374 ;; attributes associated to the paragraph
19375 ;; containing link.
19376 (let ((paragraph
19377 (let ((e link))
19378 (while (and (setq e (org-element-property
19379 :parent e))
19380 (not (eq (org-element-type e)
19381 'paragraph))))
19382 e)))
19383 (when paragraph
19384 (save-excursion
19385 (goto-char (org-element-property :begin paragraph))
19386 (when
19387 (re-search-forward
19388 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19389 (org-element-property
19390 :post-affiliated paragraph)
19392 (string-to-number (match-string 1))))))
19393 ;; Otherwise, fall-back to provided number.
19394 (car org-image-actual-width)))
19395 ((numberp org-image-actual-width)
19396 org-image-actual-width)))
19397 (old (get-char-property-and-overlay
19398 (org-element-property :begin link)
19399 'org-image-overlay)))
19400 (if (and (car-safe old) refresh)
19401 (image-refresh (overlay-get (cdr old) 'display))
19402 (let ((image (create-image file
19403 (and width 'imagemagick)
19405 :width width)))
19406 (when image
19407 (let* ((link
19408 ;; If inline image is the description
19409 ;; of another link, be sure to
19410 ;; consider the latter as the one to
19411 ;; apply the overlay on.
19412 (let ((parent
19413 (org-element-property :parent link)))
19414 (if (eq (org-element-type parent) 'link)
19415 parent
19416 link)))
19417 (ov (make-overlay
19418 (org-element-property :begin link)
19419 (progn
19420 (goto-char
19421 (org-element-property :end link))
19422 (skip-chars-backward " \t")
19423 (point)))))
19424 (overlay-put ov 'display image)
19425 (overlay-put ov 'face 'default)
19426 (overlay-put ov 'org-image-overlay t)
19427 (overlay-put
19428 ov 'modification-hooks
19429 (list 'org-display-inline-remove-overlay))
19430 (push ov org-inline-image-overlays)))))))))))))))
19432 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19433 "Remove inline-display overlay if a corresponding region is modified."
19434 (let ((inhibit-modification-hooks t))
19435 (when (and ov after)
19436 (delete ov org-inline-image-overlays)
19437 (delete-overlay ov))))
19439 (defun org-remove-inline-images ()
19440 "Remove inline display of images."
19441 (interactive)
19442 (mapc #'delete-overlay org-inline-image-overlays)
19443 (setq org-inline-image-overlays nil))
19445 ;;;; Key bindings
19447 ;; Outline functions from `outline-mode-prefix-map'
19448 ;; that can be remapped in Org:
19449 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19450 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19451 (define-key org-mode-map [remap outline-forward-same-level]
19452 'org-forward-heading-same-level)
19453 (define-key org-mode-map [remap outline-backward-same-level]
19454 'org-backward-heading-same-level)
19455 (define-key org-mode-map [remap outline-show-branches]
19456 'org-kill-note-or-show-branches)
19457 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19458 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19459 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19460 (define-key org-mode-map [remap outline-next-visible-heading]
19461 'org-next-visible-heading)
19462 (define-key org-mode-map [remap outline-previous-visible-heading]
19463 'org-previous-visible-heading)
19464 (define-key org-mode-map [remap show-children] 'org-show-children)
19466 ;; Outline functions from `outline-mode-prefix-map' that can not
19467 ;; be remapped in Org:
19469 ;; - the column "key binding" shows whether the Outline function is still
19470 ;; available in Org mode on the same key that it has been bound to in
19471 ;; Outline mode:
19472 ;; - "overridden": key used for a different functionality in Org mode
19473 ;; - else: key still bound to the same Outline function in Org mode
19475 ;; | Outline function | key binding | Org replacement |
19476 ;; |------------------------------------+-------------+--------------------------|
19477 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19478 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19479 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19480 ;; | `show-entry' | overridden | no replacement |
19481 ;; | `show-branches' | `C-c C-k' | still same function |
19482 ;; | `show-subtree' | overridden | visibility cycling |
19483 ;; | `show-all' | overridden | no replacement |
19484 ;; | `hide-subtree' | overridden | visibility cycling |
19485 ;; | `hide-body' | overridden | no replacement |
19486 ;; | `hide-entry' | overridden | visibility cycling |
19487 ;; | `hide-leaves' | overridden | no replacement |
19488 ;; | `hide-sublevels' | overridden | no replacement |
19489 ;; | `hide-other' | overridden | no replacement |
19491 ;; Make `C-c C-x' a prefix key
19492 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19494 ;; TAB key with modifiers
19495 (org-defkey org-mode-map "\C-i" 'org-cycle)
19496 (org-defkey org-mode-map [(tab)] 'org-cycle)
19497 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19498 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19499 ;; The following line is necessary under Suse GNU/Linux
19500 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19501 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19502 (define-key org-mode-map [backtab] 'org-shifttab)
19504 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19505 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19506 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19508 ;; Cursor keys with modifiers
19509 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19510 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19511 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19512 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19514 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19515 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19516 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19517 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19518 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19519 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19521 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19522 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19523 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19524 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19526 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19527 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19528 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19529 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19531 ;; Babel keys
19532 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19533 (dolist (pair org-babel-key-bindings)
19534 (define-key org-babel-map (car pair) (cdr pair)))
19536 ;;; Extra keys for tty access.
19537 ;; We only set them when really needed because otherwise the
19538 ;; menus don't show the simple keys
19540 (when (or org-use-extra-keys (not window-system))
19541 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19542 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19543 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19544 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19545 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19546 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19547 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19548 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19549 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19550 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19551 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19552 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19553 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19554 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19555 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19556 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19557 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19558 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19559 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19560 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19561 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19562 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19563 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19564 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19565 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19566 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19567 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19568 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19570 ;; All the other keys
19572 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19573 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19574 (if (boundp 'narrow-map)
19575 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19576 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19577 (if (boundp 'narrow-map)
19578 (org-defkey narrow-map "b" 'org-narrow-to-block)
19579 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19580 (if (boundp 'narrow-map)
19581 (org-defkey narrow-map "e" 'org-narrow-to-element)
19582 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19583 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19584 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19585 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19586 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19587 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19588 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19589 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19590 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19591 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19592 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19593 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19594 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19595 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19596 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19597 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19598 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19599 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19600 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19601 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19602 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19603 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19604 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19605 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19606 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19607 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19608 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19609 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19610 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19611 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19612 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19613 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19614 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19615 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19616 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19617 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19618 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19619 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19620 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19621 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19622 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19623 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19624 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19625 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19626 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19627 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19628 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19629 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19630 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19631 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19632 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19633 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19634 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19635 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19636 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19637 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19638 (org-defkey org-mode-map "\C-c^" 'org-sort)
19639 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19640 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19641 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19642 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19643 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19644 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19645 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19646 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19647 (org-defkey org-mode-map "\C-m" 'org-return)
19648 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19649 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19650 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19651 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19652 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19653 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19654 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19655 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19656 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19657 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19658 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19659 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19660 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19661 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19662 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19663 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19664 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19665 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19666 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19667 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19668 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19669 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19670 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19671 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19672 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19674 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19675 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19676 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19678 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19679 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19680 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19681 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19682 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19683 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19684 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19685 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19686 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19687 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19688 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19689 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19690 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19691 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19692 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19693 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19694 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19695 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19696 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19697 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19698 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19699 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19701 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19702 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19703 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19704 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19705 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19707 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19709 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19711 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19712 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19714 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19717 (defconst org-speed-commands-default
19719 ("Outline Navigation")
19720 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19721 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19722 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19723 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19724 ("F" . org-next-block)
19725 ("B" . org-previous-block)
19726 ("u" . (org-speed-move-safe 'outline-up-heading))
19727 ("j" . org-goto)
19728 ("g" . (org-refile t))
19729 ("Outline Visibility")
19730 ("c" . org-cycle)
19731 ("C" . org-shifttab)
19732 (" " . org-display-outline-path)
19733 ("s" . org-narrow-to-subtree)
19734 ("=" . org-columns)
19735 ("Outline Structure Editing")
19736 ("U" . org-metaup)
19737 ("D" . org-metadown)
19738 ("r" . org-metaright)
19739 ("l" . org-metaleft)
19740 ("R" . org-shiftmetaright)
19741 ("L" . org-shiftmetaleft)
19742 ("i" . (progn (forward-char 1) (call-interactively
19743 'org-insert-heading-respect-content)))
19744 ("^" . org-sort)
19745 ("w" . org-refile)
19746 ("a" . org-archive-subtree-default-with-confirmation)
19747 ("@" . org-mark-subtree)
19748 ("#" . org-toggle-comment)
19749 ("Clock Commands")
19750 ("I" . org-clock-in)
19751 ("O" . org-clock-out)
19752 ("Meta Data Editing")
19753 ("t" . org-todo)
19754 ("," . (org-priority))
19755 ("0" . (org-priority ?\ ))
19756 ("1" . (org-priority ?A))
19757 ("2" . (org-priority ?B))
19758 ("3" . (org-priority ?C))
19759 (":" . org-set-tags-command)
19760 ("e" . org-set-effort)
19761 ("E" . org-inc-effort)
19762 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19763 (org-entry-put (point) "APPT_WARNTIME" m)))
19764 ("Agenda Views etc")
19765 ("v" . org-agenda)
19766 ("/" . org-sparse-tree)
19767 ("Misc")
19768 ("o" . org-open-at-point)
19769 ("?" . org-speed-command-help)
19770 ("<" . (org-agenda-set-restriction-lock 'subtree))
19771 (">" . (org-agenda-remove-restriction-lock))
19773 "The default speed commands.")
19775 (defun org-print-speed-command (e)
19776 (if (> (length (car e)) 1)
19777 (progn
19778 (princ "\n")
19779 (princ (car e))
19780 (princ "\n")
19781 (princ (make-string (length (car e)) ?-))
19782 (princ "\n"))
19783 (princ (car e))
19784 (princ " ")
19785 (if (symbolp (cdr e))
19786 (princ (symbol-name (cdr e)))
19787 (prin1 (cdr e)))
19788 (princ "\n")))
19790 (defun org-speed-command-help ()
19791 "Show the available speed commands."
19792 (interactive)
19793 (if (not org-use-speed-commands)
19794 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19795 (with-output-to-temp-buffer "*Help*"
19796 (princ "User-defined Speed commands\n===========================\n")
19797 (mapc #'org-print-speed-command org-speed-commands-user)
19798 (princ "\n")
19799 (princ "Built-in Speed commands\n=======================\n")
19800 (mapc #'org-print-speed-command org-speed-commands-default))
19801 (with-current-buffer "*Help*"
19802 (setq truncate-lines t))))
19804 (defun org-speed-move-safe (cmd)
19805 "Execute CMD, but make sure that the cursor always ends up in a headline.
19806 If not, return to the original position and throw an error."
19807 (interactive)
19808 (let ((pos (point)))
19809 (call-interactively cmd)
19810 (unless (and (bolp) (org-at-heading-p))
19811 (goto-char pos)
19812 (error "Boundary reached while executing %s" cmd))))
19814 (defvar org-self-insert-command-undo-counter 0)
19816 (defvar org-table-auto-blank-field) ; defined in org-table.el
19817 (defvar org-speed-command nil)
19819 (defun org-speed-command-activate (keys)
19820 "Hook for activating single-letter speed commands.
19821 `org-speed-commands-default' specifies a minimal command set.
19822 Use `org-speed-commands-user' for further customization."
19823 (when (or (and (bolp) (looking-at org-outline-regexp))
19824 (and (functionp org-use-speed-commands)
19825 (funcall org-use-speed-commands)))
19826 (cdr (assoc keys (append org-speed-commands-user
19827 org-speed-commands-default)))))
19829 (defun org-babel-speed-command-activate (keys)
19830 "Hook for activating single-letter code block commands."
19831 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19832 (cdr (assoc keys org-babel-key-bindings))))
19834 (defcustom org-speed-command-hook
19835 '(org-speed-command-activate org-babel-speed-command-activate)
19836 "Hook for activating speed commands at strategic locations.
19837 Hook functions are called in sequence until a valid handler is
19838 found.
19840 Each hook takes a single argument, a user-pressed command key
19841 which is also a `self-insert-command' from the global map.
19843 Within the hook, examine the cursor position and the command key
19844 and return nil or a valid handler as appropriate. Handler could
19845 be one of an interactive command, a function, or a form.
19847 Set `org-use-speed-commands' to non-nil value to enable this
19848 hook. The default setting is `org-speed-command-activate'."
19849 :group 'org-structure
19850 :version "24.1"
19851 :type 'hook)
19853 (defun org-self-insert-command (N)
19854 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19855 If the cursor is in a table looking at whitespace, the whitespace is
19856 overwritten, and the table is not marked as requiring realignment."
19857 (interactive "p")
19858 (org-check-before-invisible-edit 'insert)
19859 (cond
19860 ((and org-use-speed-commands
19861 (let ((kv (this-command-keys-vector)))
19862 (setq org-speed-command
19863 (run-hook-with-args-until-success
19864 'org-speed-command-hook
19865 (make-string 1 (aref kv (1- (length kv))))))))
19866 (cond
19867 ((commandp org-speed-command)
19868 (setq this-command org-speed-command)
19869 (call-interactively org-speed-command))
19870 ((functionp org-speed-command)
19871 (funcall org-speed-command))
19872 ((and org-speed-command (listp org-speed-command))
19873 (eval org-speed-command))
19874 (t (let (org-use-speed-commands)
19875 (call-interactively 'org-self-insert-command)))))
19876 ((and
19877 (org-at-table-p)
19878 (progn
19879 ;; Check if we blank the field, and if that triggers align.
19880 (and (featurep 'org-table) org-table-auto-blank-field
19881 (memq last-command
19882 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19883 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19884 ;; Got extra space, this field does not determine
19885 ;; column width.
19886 (let (org-table-may-need-update) (org-table-blank-field))
19887 ;; No extra space, this field may determine column
19888 ;; width.
19889 (org-table-blank-field)))
19891 (eq N 1)
19892 (looking-at "[^|\n]* \\( \\)|"))
19893 ;; There is room for insertion without re-aligning the table.
19894 (delete-region (match-beginning 1) (match-end 1))
19895 (self-insert-command N))
19897 (setq org-table-may-need-update t)
19898 (self-insert-command N)
19899 (org-fix-tags-on-the-fly)
19900 (when org-self-insert-cluster-for-undo
19901 (if (not (eq last-command 'org-self-insert-command))
19902 (setq org-self-insert-command-undo-counter 1)
19903 (if (>= org-self-insert-command-undo-counter 20)
19904 (setq org-self-insert-command-undo-counter 1)
19905 (and (> org-self-insert-command-undo-counter 0)
19906 buffer-undo-list (listp buffer-undo-list)
19907 (not (cadr buffer-undo-list)) ; remove nil entry
19908 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19909 (setq org-self-insert-command-undo-counter
19910 (1+ org-self-insert-command-undo-counter))))))))
19912 (defun org-check-before-invisible-edit (kind)
19913 "Check is editing if kind KIND would be dangerous with invisible text around.
19914 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19915 ;; First, try to get out of here as quickly as possible, to reduce overhead
19916 (when (and org-catch-invisible-edits
19917 (or (not (boundp 'visible-mode)) (not visible-mode))
19918 (or (get-char-property (point) 'invisible)
19919 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19920 ;; OK, we need to take a closer look. Do not consider
19921 ;; invisibility obtained through text properties (e.g., link
19922 ;; fontification), as it cannot be toggled.
19923 (let* ((invisible-at-point
19924 (pcase (get-char-property-and-overlay (point) 'invisible)
19925 (`(,_ . ,(and (pred overlayp) o)) o)))
19926 ;; Assume that point cannot land in the middle of an
19927 ;; overlay, or between two overlays.
19928 (invisible-before-point
19929 (and (not invisible-at-point)
19930 (not (bobp))
19931 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19932 (`(,_ . ,(and (pred overlayp) o)) o))))
19933 (border-and-ok-direction
19935 ;; Check if we are acting predictably before invisible
19936 ;; text.
19937 (and invisible-at-point
19938 (memq kind '(insert delete-backward)))
19939 ;; Check if we are acting predictably after invisible text
19940 ;; This works not well, and I have turned it off. It seems
19941 ;; better to always show and stop after invisible text.
19942 ;; (and (not invisible-at-point) invisible-before-point
19943 ;; (memq kind '(insert delete)))
19945 (when (or invisible-at-point invisible-before-point)
19946 (when (eq org-catch-invisible-edits 'error)
19947 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19948 (if (and org-custom-properties-overlays
19949 (y-or-n-p "Display invisible properties in this buffer? "))
19950 (org-toggle-custom-properties-visibility)
19951 ;; Make the area visible
19952 (save-excursion
19953 (when invisible-before-point
19954 (goto-char
19955 (previous-single-char-property-change (point) 'invisible)))
19956 ;; Remove whatever overlay is currently making yet-to-be
19957 ;; edited text invisible. Also remove nested invisibility
19958 ;; related overlays.
19959 (delete-overlay (or invisible-at-point invisible-before-point))
19960 (let ((origin (if invisible-at-point (point) (1- (point)))))
19961 (while (pcase (get-char-property-and-overlay origin 'invisible)
19962 (`(,_ . ,(and (pred overlayp) o))
19963 (delete-overlay o)
19964 t)))))
19965 (cond
19966 ((eq org-catch-invisible-edits 'show)
19967 ;; That's it, we do the edit after showing
19968 (message
19969 "Unfolding invisible region around point before editing")
19970 (sit-for 1))
19971 ((and (eq org-catch-invisible-edits 'smart)
19972 border-and-ok-direction)
19973 (message "Unfolding invisible region around point before editing"))
19975 ;; Don't do the edit, make the user repeat it in full visibility
19976 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19978 (defun org-fix-tags-on-the-fly ()
19979 "Align tags in headline at point.
19980 Unlike to `org-set-tags', it ignores region and sorting."
19981 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19982 (org-at-heading-p))
19983 (let ((org-ignore-region t)
19984 (org-tags-sort-function nil))
19985 (org-set-tags nil t))))
19987 (defun org-delete-backward-char (N)
19988 "Like `delete-backward-char', insert whitespace at field end in tables.
19989 When deleting backwards, in tables this function will insert whitespace in
19990 front of the next \"|\" separator, to keep the table aligned. The table will
19991 still be marked for re-alignment if the field did fill the entire column,
19992 because, in this case the deletion might narrow the column."
19993 (interactive "p")
19994 (save-match-data
19995 (org-check-before-invisible-edit 'delete-backward)
19996 (if (and (org-at-table-p)
19997 (eq N 1)
19998 (string-match "|" (buffer-substring (point-at-bol) (point)))
19999 (looking-at ".*?|"))
20000 (let ((pos (point))
20001 (noalign (looking-at "[^|\n\r]* |"))
20002 (c org-table-may-need-update))
20003 (backward-delete-char N)
20004 (unless overwrite-mode
20005 (skip-chars-forward "^|")
20006 (insert " ")
20007 (goto-char (1- pos)))
20008 ;; noalign: if there were two spaces at the end, this field
20009 ;; does not determine the width of the column.
20010 (when noalign (setq org-table-may-need-update c)))
20011 (backward-delete-char N)
20012 (org-fix-tags-on-the-fly))))
20014 (defun org-delete-char (N)
20015 "Like `delete-char', but insert whitespace at field end in tables.
20016 When deleting characters, in tables this function will insert whitespace in
20017 front of the next \"|\" separator, to keep the table aligned. The table will
20018 still be marked for re-alignment if the field did fill the entire column,
20019 because, in this case the deletion might narrow the column."
20020 (interactive "p")
20021 (save-match-data
20022 (org-check-before-invisible-edit 'delete)
20023 (if (and (org-at-table-p)
20024 (not (bolp))
20025 (not (= (char-after) ?|))
20026 (eq N 1))
20027 (if (looking-at ".*?|")
20028 (let ((pos (point))
20029 (noalign (looking-at "[^|\n\r]* |"))
20030 (c org-table-may-need-update))
20031 (replace-match
20032 (concat (substring (match-string 0) 1 -1) " |") nil t)
20033 (goto-char pos)
20034 ;; noalign: if there were two spaces at the end, this field
20035 ;; does not determine the width of the column.
20036 (when noalign (setq org-table-may-need-update c)))
20037 (delete-char N))
20038 (delete-char N)
20039 (org-fix-tags-on-the-fly))))
20041 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20042 (put 'org-self-insert-command 'delete-selection
20043 (lambda ()
20044 (not (run-hook-with-args-until-success
20045 'self-insert-uses-region-functions))))
20046 (put 'orgtbl-self-insert-command 'delete-selection
20047 (lambda ()
20048 (not (run-hook-with-args-until-success
20049 'self-insert-uses-region-functions))))
20050 (put 'org-delete-char 'delete-selection 'supersede)
20051 (put 'org-delete-backward-char 'delete-selection 'supersede)
20052 (put 'org-yank 'delete-selection 'yank)
20054 ;; Make `flyspell-mode' delay after some commands
20055 (put 'org-self-insert-command 'flyspell-delayed t)
20056 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20057 (put 'org-delete-char 'flyspell-delayed t)
20058 (put 'org-delete-backward-char 'flyspell-delayed t)
20060 ;; Make pabbrev-mode expand after Org mode commands
20061 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20062 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20064 (defun org-remap (map &rest commands)
20065 "In MAP, remap the functions given in COMMANDS.
20066 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20067 (let (new old)
20068 (while commands
20069 (setq old (pop commands) new (pop commands))
20070 (org-defkey map (vector 'remap old) new))))
20072 (defun org-transpose-words ()
20073 "Transpose words for Org.
20074 This uses the `org-mode-transpose-word-syntax-table' syntax
20075 table, which interprets characters in `org-emphasis-alist' as
20076 word constituents."
20077 (interactive)
20078 (with-syntax-table org-mode-transpose-word-syntax-table
20079 (call-interactively 'transpose-words)))
20080 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20082 (when (eq org-enable-table-editor 'optimized)
20083 ;; If the user wants maximum table support, we need to hijack
20084 ;; some standard editing functions
20085 (org-remap org-mode-map
20086 'self-insert-command 'org-self-insert-command
20087 'delete-char 'org-delete-char
20088 'delete-backward-char 'org-delete-backward-char)
20089 (org-defkey org-mode-map "|" 'org-force-self-insert))
20091 (defvar org-ctrl-c-ctrl-c-hook nil
20092 "Hook for functions attaching themselves to `C-c C-c'.
20094 This can be used to add additional functionality to the C-c C-c
20095 key which executes context-dependent commands. This hook is run
20096 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20097 run after the last test.
20099 Each function will be called with no arguments. The function
20100 must check if the context is appropriate for it to act. If yes,
20101 it should do its thing and then return a non-nil value. If the
20102 context is wrong, just do nothing and return nil.")
20104 (defvar org-ctrl-c-ctrl-c-final-hook nil
20105 "Hook for functions attaching themselves to `C-c C-c'.
20107 This can be used to add additional functionality to the C-c C-c
20108 key which executes context-dependent commands. This hook is run
20109 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20110 before the first test.
20112 Each function will be called with no arguments. The function
20113 must check if the context is appropriate for it to act. If yes,
20114 it should do its thing and then return a non-nil value. If the
20115 context is wrong, just do nothing and return nil.")
20117 (defvar org-tab-first-hook nil
20118 "Hook for functions to attach themselves to TAB.
20119 See `org-ctrl-c-ctrl-c-hook' for more information.
20120 This hook runs as the first action when TAB is pressed, even before
20121 `org-cycle' messes around with the `outline-regexp' to cater for
20122 inline tasks and plain list item folding.
20123 If any function in this hook returns t, any other actions that
20124 would have been caused by TAB (such as table field motion or visibility
20125 cycling) will not occur.")
20127 (defvar org-tab-after-check-for-table-hook nil
20128 "Hook for functions to attach themselves to TAB.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.
20130 This hook runs after it has been established that the cursor is not in a
20131 table, but before checking if the cursor is in a headline or if global cycling
20132 should be done.
20133 If any function in this hook returns t, not other actions like visibility
20134 cycling will be done.")
20136 (defvar org-tab-after-check-for-cycling-hook nil
20137 "Hook for functions to attach themselves to TAB.
20138 See `org-ctrl-c-ctrl-c-hook' for more information.
20139 This hook runs after it has been established that not table field motion and
20140 not visibility should be done because of current context. This is probably
20141 the place where a package like yasnippets can hook in.")
20143 (defvar org-tab-before-tab-emulation-hook nil
20144 "Hook for functions to attach themselves to TAB.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.
20146 This hook runs after every other options for TAB have been exhausted, but
20147 before indentation and \t insertion takes place.")
20149 (defvar org-metaleft-hook nil
20150 "Hook for functions attaching themselves to `M-left'.
20151 See `org-ctrl-c-ctrl-c-hook' for more information.")
20152 (defvar org-metaright-hook nil
20153 "Hook for functions attaching themselves to `M-right'.
20154 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defvar org-metaup-hook nil
20156 "Hook for functions attaching themselves to `M-up'.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-metadown-hook nil
20159 "Hook for functions attaching themselves to `M-down'.
20160 See `org-ctrl-c-ctrl-c-hook' for more information.")
20161 (defvar org-shiftmetaleft-hook nil
20162 "Hook for functions attaching themselves to `M-S-left'.
20163 See `org-ctrl-c-ctrl-c-hook' for more information.")
20164 (defvar org-shiftmetaright-hook nil
20165 "Hook for functions attaching themselves to `M-S-right'.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.")
20167 (defvar org-shiftmetaup-hook nil
20168 "Hook for functions attaching themselves to `M-S-up'.
20169 See `org-ctrl-c-ctrl-c-hook' for more information.")
20170 (defvar org-shiftmetadown-hook nil
20171 "Hook for functions attaching themselves to `M-S-down'.
20172 See `org-ctrl-c-ctrl-c-hook' for more information.")
20173 (defvar org-metareturn-hook nil
20174 "Hook for functions attaching themselves to `M-RET'.
20175 See `org-ctrl-c-ctrl-c-hook' for more information.")
20176 (defvar org-shiftup-hook nil
20177 "Hook for functions attaching themselves to `S-up'.
20178 See `org-ctrl-c-ctrl-c-hook' for more information.")
20179 (defvar org-shiftup-final-hook nil
20180 "Hook for functions attaching themselves to `S-up'.
20181 This one runs after all other options except shift-select have been excluded.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-shiftdown-hook nil
20184 "Hook for functions attaching themselves to `S-down'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftdown-final-hook nil
20187 "Hook for functions attaching themselves to `S-down'.
20188 This one runs after all other options except shift-select have been excluded.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftleft-hook nil
20191 "Hook for functions attaching themselves to `S-left'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftleft-final-hook nil
20194 "Hook for functions attaching themselves to `S-left'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-shiftright-hook nil
20198 "Hook for functions attaching themselves to `S-right'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftright-final-hook nil
20201 "Hook for functions attaching themselves to `S-right'.
20202 This one runs after all other options except shift-select have been excluded.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20205 (defun org-modifier-cursor-error ()
20206 "Throw an error, a modified cursor command was applied in wrong context."
20207 (user-error "This command is active in special context like tables, headlines or items"))
20209 (defun org-shiftselect-error ()
20210 "Throw an error because Shift-Cursor command was applied in wrong context."
20211 (if (and (boundp 'shift-select-mode) shift-select-mode)
20212 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20213 (user-error "This command works only in special context like headlines or timestamps")))
20215 (defun org-call-for-shift-select (cmd)
20216 (let ((this-command-keys-shift-translated t))
20217 (call-interactively cmd)))
20219 (defun org-shifttab (&optional arg)
20220 "Global visibility cycling or move to previous table field.
20221 Call `org-table-previous-field' within a table.
20222 When ARG is nil, cycle globally through visibility states.
20223 When ARG is a numeric prefix, show contents of this level."
20224 (interactive "P")
20225 (cond
20226 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20227 ((integerp arg)
20228 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20229 (message "Content view to level: %d" arg)
20230 (org-content (prefix-numeric-value arg2))
20231 (org-cycle-show-empty-lines t)
20232 (setq org-cycle-global-status 'overview)))
20233 (t (call-interactively 'org-global-cycle))))
20235 (defun org-shiftmetaleft ()
20236 "Promote subtree or delete table column.
20237 Calls `org-promote-subtree', `org-outdent-item-tree', or
20238 `org-table-delete-column', depending on context. See the
20239 individual commands for more information."
20240 (interactive)
20241 (cond
20242 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20243 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20244 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20245 ((if (not (org-region-active-p)) (org-at-item-p)
20246 (save-excursion (goto-char (region-beginning))
20247 (org-at-item-p)))
20248 (call-interactively 'org-outdent-item-tree))
20249 (t (org-modifier-cursor-error))))
20251 (defun org-shiftmetaright ()
20252 "Demote subtree or insert table column.
20253 Calls `org-demote-subtree', `org-indent-item-tree', or
20254 `org-table-insert-column', depending on context. See the
20255 individual commands for more information."
20256 (interactive)
20257 (cond
20258 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20259 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20260 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20261 ((if (not (org-region-active-p)) (org-at-item-p)
20262 (save-excursion (goto-char (region-beginning))
20263 (org-at-item-p)))
20264 (call-interactively 'org-indent-item-tree))
20265 (t (org-modifier-cursor-error))))
20267 (defun org-shiftmetaup (&optional _arg)
20268 "Drag the line at point up.
20269 In a table, kill the current row.
20270 On a clock timestamp, update the value of the timestamp like `S-<up>'
20271 but also adjust the previous clocked item in the clock history.
20272 Everywhere else, drag the line at point up."
20273 (interactive "P")
20274 (cond
20275 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20276 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20277 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20278 (call-interactively 'org-timestamp-up)))
20279 (t (call-interactively 'org-drag-line-backward))))
20281 (defun org-shiftmetadown (&optional _arg)
20282 "Drag the line at point down.
20283 In a table, insert an empty row at the current line.
20284 On a clock timestamp, update the value of the timestamp like `S-<down>'
20285 but also adjust the previous clocked item in the clock history.
20286 Everywhere else, drag the line at point down."
20287 (interactive "P")
20288 (cond
20289 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20290 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20291 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20292 (call-interactively 'org-timestamp-down)))
20293 (t (call-interactively 'org-drag-line-forward))))
20295 (defsubst org-hidden-tree-error ()
20296 (user-error
20297 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20299 (defun org-metaleft (&optional _arg)
20300 "Promote heading, list item at point or move table column left.
20302 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20303 depending on context. With no specific context, calls the Emacs
20304 default `backward-word'. See the individual commands for more
20305 information.
20307 This function runs the hook `org-metaleft-hook' as a first step,
20308 and returns at first non-nil value."
20309 (interactive "P")
20310 (cond
20311 ((run-hook-with-args-until-success 'org-metaleft-hook))
20312 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20313 ((org-with-limited-levels
20314 (or (org-at-heading-p)
20315 (and (org-region-active-p)
20316 (save-excursion
20317 (goto-char (region-beginning))
20318 (org-at-heading-p)))))
20319 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20320 (call-interactively 'org-do-promote))
20321 ;; At an inline task.
20322 ((org-at-heading-p)
20323 (call-interactively 'org-inlinetask-promote))
20324 ((or (org-at-item-p)
20325 (and (org-region-active-p)
20326 (save-excursion
20327 (goto-char (region-beginning))
20328 (org-at-item-p))))
20329 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20330 (call-interactively 'org-outdent-item))
20331 (t (call-interactively 'backward-word))))
20333 (defun org-metaright (&optional _arg)
20334 "Demote heading, list item at point or move table column right.
20336 In front of a drawer or a block keyword, indent it correctly.
20338 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20339 `org-indent-drawer' or `org-indent-block' depending on context.
20340 With no specific context, calls the Emacs default `forward-word'.
20341 See the individual commands for more information.
20343 This function runs the hook `org-metaright-hook' as a first step,
20344 and returns at first non-nil value."
20345 (interactive "P")
20346 (cond
20347 ((run-hook-with-args-until-success 'org-metaright-hook))
20348 ((org-at-table-p) (call-interactively 'org-table-move-column))
20349 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20350 ((org-at-block-p) (call-interactively 'org-indent-block))
20351 ((org-with-limited-levels
20352 (or (org-at-heading-p)
20353 (and (org-region-active-p)
20354 (save-excursion
20355 (goto-char (region-beginning))
20356 (org-at-heading-p)))))
20357 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20358 (call-interactively 'org-do-demote))
20359 ;; At an inline task.
20360 ((org-at-heading-p)
20361 (call-interactively 'org-inlinetask-demote))
20362 ((or (org-at-item-p)
20363 (and (org-region-active-p)
20364 (save-excursion
20365 (goto-char (region-beginning))
20366 (org-at-item-p))))
20367 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20368 (call-interactively 'org-indent-item))
20369 (t (call-interactively 'forward-word))))
20371 (defun org-check-for-hidden (what)
20372 "Check if there are hidden headlines/items in the current visual line.
20373 WHAT can be either `headlines' or `items'. If the current line is
20374 an outline or item heading and it has a folded subtree below it,
20375 this function returns t, nil otherwise."
20376 (let ((re (cond
20377 ((eq what 'headlines) org-outline-regexp-bol)
20378 ((eq what 'items) (org-item-beginning-re))
20379 (t (error "This should not happen"))))
20380 beg end)
20381 (save-excursion
20382 (catch 'exit
20383 (unless (org-region-active-p)
20384 (setq beg (point-at-bol))
20385 (beginning-of-line 2)
20386 (while (and (not (eobp)) ;; this is like `next-line'
20387 (get-char-property (1- (point)) 'invisible))
20388 (beginning-of-line 2))
20389 (setq end (point))
20390 (goto-char beg)
20391 (goto-char (point-at-eol))
20392 (setq end (max end (point)))
20393 (while (re-search-forward re end t)
20394 (when (get-char-property (match-beginning 0) 'invisible)
20395 (throw 'exit t))))
20396 nil))))
20398 (defun org-metaup (&optional _arg)
20399 "Move subtree up or move table row up.
20400 Calls `org-move-subtree-up' or `org-table-move-row' or
20401 `org-move-item-up', depending on context. See the individual commands
20402 for more information."
20403 (interactive "P")
20404 (cond
20405 ((run-hook-with-args-until-success 'org-metaup-hook))
20406 ((org-region-active-p)
20407 (let* ((a (min (region-beginning) (region-end)))
20408 (b (1- (max (region-beginning) (region-end))))
20409 (c (save-excursion (goto-char a)
20410 (move-beginning-of-line 0)))
20411 (d (save-excursion (goto-char a)
20412 (move-end-of-line 0) (point))))
20413 (transpose-regions a b c d)
20414 (goto-char c)))
20415 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20416 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20417 ((org-at-item-p) (call-interactively 'org-move-item-up))
20418 (t (org-drag-element-backward))))
20420 (defun org-metadown (&optional _arg)
20421 "Move subtree down or move table row down.
20422 Calls `org-move-subtree-down' or `org-table-move-row' or
20423 `org-move-item-down', depending on context. See the individual
20424 commands for more information."
20425 (interactive "P")
20426 (cond
20427 ((run-hook-with-args-until-success 'org-metadown-hook))
20428 ((org-region-active-p)
20429 (let* ((a (min (region-beginning) (region-end)))
20430 (b (max (region-beginning) (region-end)))
20431 (c (save-excursion (goto-char b)
20432 (move-beginning-of-line 1)))
20433 (d (save-excursion (goto-char b)
20434 (move-end-of-line 1) (1+ (point)))))
20435 (transpose-regions a b c d)
20436 (goto-char d)))
20437 ((org-at-table-p) (call-interactively 'org-table-move-row))
20438 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20439 ((org-at-item-p) (call-interactively 'org-move-item-down))
20440 (t (org-drag-element-forward))))
20442 (defun org-shiftup (&optional arg)
20443 "Increase item in timestamp or increase priority of current headline.
20444 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20445 depending on context. See the individual commands for more information."
20446 (interactive "P")
20447 (cond
20448 ((run-hook-with-args-until-success 'org-shiftup-hook))
20449 ((and org-support-shift-select (org-region-active-p))
20450 (org-call-for-shift-select 'previous-line))
20451 ((org-at-timestamp-p 'lax)
20452 (call-interactively (if org-edit-timestamp-down-means-later
20453 'org-timestamp-down 'org-timestamp-up)))
20454 ((and (not (eq org-support-shift-select 'always))
20455 org-enable-priority-commands
20456 (org-at-heading-p))
20457 (call-interactively 'org-priority-up))
20458 ((and (not org-support-shift-select) (org-at-item-p))
20459 (call-interactively 'org-previous-item))
20460 ((org-clocktable-try-shift 'up arg))
20461 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20462 (org-support-shift-select
20463 (org-call-for-shift-select 'previous-line))
20464 (t (org-shiftselect-error))))
20466 (defun org-shiftdown (&optional arg)
20467 "Decrease item in timestamp or decrease priority of current headline.
20468 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20469 depending on context. See the individual commands for more information."
20470 (interactive "P")
20471 (cond
20472 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20473 ((and org-support-shift-select (org-region-active-p))
20474 (org-call-for-shift-select 'next-line))
20475 ((org-at-timestamp-p 'lax)
20476 (call-interactively (if org-edit-timestamp-down-means-later
20477 'org-timestamp-up 'org-timestamp-down)))
20478 ((and (not (eq org-support-shift-select 'always))
20479 org-enable-priority-commands
20480 (org-at-heading-p))
20481 (call-interactively 'org-priority-down))
20482 ((and (not org-support-shift-select) (org-at-item-p))
20483 (call-interactively 'org-next-item))
20484 ((org-clocktable-try-shift 'down arg))
20485 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20486 (org-support-shift-select
20487 (org-call-for-shift-select 'next-line))
20488 (t (org-shiftselect-error))))
20490 (defun org-shiftright (&optional arg)
20491 "Cycle the thing at point or in the current line, depending on context.
20492 Depending on context, this does one of the following:
20494 - switch a timestamp at point one day into the future
20495 - on a headline, switch to the next TODO keyword.
20496 - on an item, switch entire list to the next bullet type
20497 - on a property line, switch to the next allowed value
20498 - on a clocktable definition line, move time block into the future"
20499 (interactive "P")
20500 (cond
20501 ((run-hook-with-args-until-success 'org-shiftright-hook))
20502 ((and org-support-shift-select (org-region-active-p))
20503 (org-call-for-shift-select 'forward-char))
20504 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20505 ((and (not (eq org-support-shift-select 'always))
20506 (org-at-heading-p))
20507 (let ((org-inhibit-logging
20508 (not org-treat-S-cursor-todo-selection-as-state-change))
20509 (org-inhibit-blocking
20510 (not org-treat-S-cursor-todo-selection-as-state-change)))
20511 (org-call-with-arg 'org-todo 'right)))
20512 ((or (and org-support-shift-select
20513 (not (eq org-support-shift-select 'always))
20514 (org-at-item-bullet-p))
20515 (and (not org-support-shift-select) (org-at-item-p)))
20516 (org-call-with-arg 'org-cycle-list-bullet nil))
20517 ((and (not (eq org-support-shift-select 'always))
20518 (org-at-property-p))
20519 (call-interactively 'org-property-next-allowed-value))
20520 ((org-clocktable-try-shift 'right arg))
20521 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20522 (org-support-shift-select
20523 (org-call-for-shift-select 'forward-char))
20524 (t (org-shiftselect-error))))
20526 (defun org-shiftleft (&optional arg)
20527 "Cycle the thing at point or in the current line, depending on context.
20528 Depending on context, this does one of the following:
20530 - switch a timestamp at point one day into the past
20531 - on a headline, switch to the previous TODO keyword.
20532 - on an item, switch entire list to the previous bullet type
20533 - on a property line, switch to the previous allowed value
20534 - on a clocktable definition line, move time block into the past"
20535 (interactive "P")
20536 (cond
20537 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20538 ((and org-support-shift-select (org-region-active-p))
20539 (org-call-for-shift-select 'backward-char))
20540 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20541 ((and (not (eq org-support-shift-select 'always))
20542 (org-at-heading-p))
20543 (let ((org-inhibit-logging
20544 (not org-treat-S-cursor-todo-selection-as-state-change))
20545 (org-inhibit-blocking
20546 (not org-treat-S-cursor-todo-selection-as-state-change)))
20547 (org-call-with-arg 'org-todo 'left)))
20548 ((or (and org-support-shift-select
20549 (not (eq org-support-shift-select 'always))
20550 (org-at-item-bullet-p))
20551 (and (not org-support-shift-select) (org-at-item-p)))
20552 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20553 ((and (not (eq org-support-shift-select 'always))
20554 (org-at-property-p))
20555 (call-interactively 'org-property-previous-allowed-value))
20556 ((org-clocktable-try-shift 'left arg))
20557 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20558 (org-support-shift-select
20559 (org-call-for-shift-select 'backward-char))
20560 (t (org-shiftselect-error))))
20562 (defun org-shiftcontrolright ()
20563 "Switch to next TODO set."
20564 (interactive)
20565 (cond
20566 ((and org-support-shift-select (org-region-active-p))
20567 (org-call-for-shift-select 'forward-word))
20568 ((and (not (eq org-support-shift-select 'always))
20569 (org-at-heading-p))
20570 (org-call-with-arg 'org-todo 'nextset))
20571 (org-support-shift-select
20572 (org-call-for-shift-select 'forward-word))
20573 (t (org-shiftselect-error))))
20575 (defun org-shiftcontrolleft ()
20576 "Switch to previous TODO set."
20577 (interactive)
20578 (cond
20579 ((and org-support-shift-select (org-region-active-p))
20580 (org-call-for-shift-select 'backward-word))
20581 ((and (not (eq org-support-shift-select 'always))
20582 (org-at-heading-p))
20583 (org-call-with-arg 'org-todo 'previousset))
20584 (org-support-shift-select
20585 (org-call-for-shift-select 'backward-word))
20586 (t (org-shiftselect-error))))
20588 (defun org-shiftcontrolup (&optional n)
20589 "Change timestamps synchronously up in CLOCK log lines.
20590 Optional argument N tells to change by that many units."
20591 (interactive "P")
20592 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20593 (let (org-support-shift-select)
20594 (org-clock-timestamps-up n))
20595 (user-error "Not at a clock log")))
20597 (defun org-shiftcontroldown (&optional n)
20598 "Change timestamps synchronously down in CLOCK log lines.
20599 Optional argument N tells to change by that many units."
20600 (interactive "P")
20601 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20602 (let (org-support-shift-select)
20603 (org-clock-timestamps-down n))
20604 (user-error "Not at a clock log")))
20606 (defun org-increase-number-at-point (&optional inc)
20607 "Increment the number at point.
20608 With an optional prefix numeric argument INC, increment using
20609 this numeric value."
20610 (interactive "p")
20611 (if (not (number-at-point))
20612 (user-error "Not on a number")
20613 (unless inc (setq inc 1))
20614 (let ((pos (point))
20615 (beg (skip-chars-backward "-+^/*0-9eE."))
20616 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20617 (setq nap (buffer-substring-no-properties
20618 (+ pos beg) (+ pos beg end)))
20619 (delete-region (+ pos beg) (+ pos beg end))
20620 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20621 (when (org-at-table-p)
20622 (org-table-align)
20623 (org-table-end-of-field 1))))
20625 (defun org-decrease-number-at-point (&optional inc)
20626 "Decrement the number at point.
20627 With an optional prefix numeric argument INC, decrement using
20628 this numeric value."
20629 (interactive "p")
20630 (org-increase-number-at-point (- (or inc 1))))
20632 (defun org-ctrl-c-ret ()
20633 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20634 (interactive)
20635 (cond
20636 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20637 (t (call-interactively 'org-insert-heading))))
20639 (defun org-find-visible ()
20640 (let ((s (point)))
20641 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20642 (get-char-property s 'invisible)))
20644 (defun org-find-invisible ()
20645 (let ((s (point)))
20646 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20647 (not (get-char-property s 'invisible))))
20650 (defun org-copy-visible (beg end)
20651 "Copy the visible parts of the region."
20652 (interactive "r")
20653 (let (snippets s)
20654 (save-excursion
20655 (save-restriction
20656 (narrow-to-region beg end)
20657 (setq s (goto-char (point-min)))
20658 (while (not (= (point) (point-max)))
20659 (goto-char (org-find-invisible))
20660 (push (buffer-substring s (point)) snippets)
20661 (setq s (goto-char (org-find-visible))))))
20662 (kill-new (apply 'concat (nreverse snippets)))))
20664 (defun org-copy-special ()
20665 "Copy region in table or copy current subtree.
20666 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20667 context. See the individual commands for more information."
20668 (interactive)
20669 (call-interactively
20670 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20672 (defun org-cut-special ()
20673 "Cut region in table or cut current subtree.
20674 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20675 context. See the individual commands for more information."
20676 (interactive)
20677 (call-interactively
20678 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20680 (defun org-paste-special (arg)
20681 "Paste rectangular region into table, or past subtree relative to level.
20682 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20683 See the individual commands for more information."
20684 (interactive "P")
20685 (if (org-at-table-p)
20686 (org-table-paste-rectangle)
20687 (org-paste-subtree arg)))
20689 (defun org-edit-special (&optional arg)
20690 "Call a special editor for the element at point.
20691 When at a table, call the formula editor with `org-table-edit-formulas'.
20692 When in a source code block, call `org-edit-src-code'.
20693 When in a fixed-width region, call `org-edit-fixed-width-region'.
20694 When in an export block, call `org-edit-export-block'.
20695 When in a LaTeX environment, call `org-edit-latex-environment'.
20696 When at an #+INCLUDE keyword, visit the included file.
20697 When at a footnote reference, call `org-edit-footnote-reference'
20698 On a link, call `ffap' to visit the link at point.
20699 Otherwise, return a user error."
20700 (interactive "P")
20701 (let ((element (org-element-at-point)))
20702 (barf-if-buffer-read-only)
20703 (pcase (org-element-type element)
20704 (`src-block
20705 (if (not arg) (org-edit-src-code)
20706 (let* ((info (org-babel-get-src-block-info))
20707 (lang (nth 0 info))
20708 (params (nth 2 info))
20709 (session (cdr (assq :session params))))
20710 (if (not session) (org-edit-src-code)
20711 ;; At a src-block with a session and function called with
20712 ;; an ARG: switch to the buffer related to the inferior
20713 ;; process.
20714 (switch-to-buffer
20715 (funcall (intern (concat "org-babel-prep-session:" lang))
20716 session params))))))
20717 (`keyword
20718 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20719 (org-open-link-from-string
20720 (format "[[%s]]"
20721 (expand-file-name
20722 (let ((value (org-element-property :value element)))
20723 (cond ((org-file-url-p value)
20724 (user-error "The file is specified as a URL, cannot be edited"))
20725 ((not (org-string-nw-p value))
20726 (user-error "No file to edit"))
20727 ((string-match "\\`\"\\(.*?\\)\"" value)
20728 (match-string 1 value))
20729 ((string-match "\\`[^ \t\"]\\S-*" value)
20730 (match-string 0 value))
20731 (t (user-error "No valid file specified")))))))
20732 (user-error "No special environment to edit here")))
20733 (`table
20734 (if (eq (org-element-property :type element) 'table.el)
20735 (org-edit-table.el)
20736 (call-interactively 'org-table-edit-formulas)))
20737 ;; Only Org tables contain `table-row' type elements.
20738 (`table-row (call-interactively 'org-table-edit-formulas))
20739 (`example-block (org-edit-src-code))
20740 (`export-block (org-edit-export-block))
20741 (`fixed-width (org-edit-fixed-width-region))
20742 (`latex-environment (org-edit-latex-environment))
20744 ;; No notable element at point. Though, we may be at a link or
20745 ;; a footnote reference, which are objects. Thus, scan deeper.
20746 (let ((context (org-element-context element)))
20747 (pcase (org-element-type context)
20748 (`footnote-reference (org-edit-footnote-reference))
20749 (`inline-src-block (org-edit-inline-src-code))
20750 (`link (call-interactively #'ffap))
20751 (_ (user-error "No special environment to edit here"))))))))
20753 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20754 (defun org-ctrl-c-ctrl-c (&optional arg)
20755 "Set tags in headline, or update according to changed information at point.
20757 This command does many different things, depending on context:
20759 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20760 this is what we do.
20762 - If the cursor is on a statistics cookie, update it.
20764 - If the cursor is in a headline, prompt for tags and insert them
20765 into the current line, aligned to `org-tags-column'. When called
20766 with prefix arg, realign all tags in the current buffer.
20768 - If the cursor is in one of the special #+KEYWORD lines, this
20769 triggers scanning the buffer for these lines and updating the
20770 information.
20772 - If the cursor is inside a table, realign the table. This command
20773 works even if the automatic table editor has been turned off.
20775 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20776 the entire table.
20778 - If the cursor is at a footnote reference or definition, jump to
20779 the corresponding definition or references, respectively.
20781 - If the cursor is a the beginning of a dynamic block, update it.
20783 - If the current buffer is a capture buffer, close note and file it.
20785 - If the cursor is on a <<<target>>>, update radio targets and
20786 corresponding links in this buffer.
20788 - If the cursor is on a numbered item in a plain list, renumber the
20789 ordered list.
20791 - If the cursor is on a checkbox, toggle it.
20793 - If the cursor is on a code block, evaluate it. The variable
20794 `org-confirm-babel-evaluate' can be used to control prompting
20795 before code block evaluation, by default every code block
20796 evaluation requires confirmation. Code block evaluation can be
20797 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20798 (interactive "P")
20799 (cond
20800 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20801 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20802 (org-remove-occur-highlights)
20803 (message "Temporary highlights/overlays removed from current buffer"))
20804 ((and (local-variable-p 'org-finish-function)
20805 (fboundp org-finish-function))
20806 (funcall org-finish-function))
20807 ((org-babel-hash-at-point))
20808 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20810 (let* ((context
20811 (org-element-lineage
20812 (org-element-context)
20813 ;; Limit to supported contexts.
20814 '(babel-call clock dynamic-block footnote-definition
20815 footnote-reference inline-babel-call inline-src-block
20816 inlinetask item keyword node-property paragraph
20817 plain-list property-drawer radio-target src-block
20818 statistics-cookie table table-cell table-row
20819 timestamp)
20821 (type (org-element-type context)))
20822 ;; For convenience: at the first line of a paragraph on the same
20823 ;; line as an item, apply function on that item instead.
20824 (when (eq type 'paragraph)
20825 (let ((parent (org-element-property :parent context)))
20826 (when (and (eq (org-element-type parent) 'item)
20827 (= (line-beginning-position)
20828 (org-element-property :begin parent)))
20829 (setq context parent)
20830 (setq type 'item))))
20831 ;; Act according to type of element or object at point.
20833 ;; Do nothing on a blank line, except if it is contained in
20834 ;; a src block. Hence, we first check if point is in such
20835 ;; a block and then if it is at a blank line.
20836 (pcase type
20837 ((or `inline-src-block `src-block)
20838 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20839 (org-babel-eval-wipe-error-buffer)
20840 (org-babel-execute-src-block
20841 current-prefix-arg (org-babel-get-src-block-info nil context))))
20842 ((guard (org-match-line "[ \t]*$"))
20843 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20844 (user-error
20845 (substitute-command-keys
20846 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20847 ((or `babel-call `inline-babel-call)
20848 (let ((info (org-babel-lob-get-info context)))
20849 (when info (org-babel-execute-src-block nil info))))
20850 (`clock (org-clock-update-time-maybe))
20851 (`dynamic-block
20852 (save-excursion
20853 (goto-char (org-element-property :post-affiliated context))
20854 (org-update-dblock)))
20855 (`footnote-definition
20856 (goto-char (org-element-property :post-affiliated context))
20857 (call-interactively 'org-footnote-action))
20858 (`footnote-reference (call-interactively #'org-footnote-action))
20859 ((or `headline `inlinetask)
20860 (save-excursion (goto-char (org-element-property :begin context))
20861 (call-interactively #'org-set-tags)))
20862 (`item
20863 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20864 ;; unconditionally, whereas `C-u' will toggle its presence.
20865 ;; Without a universal argument, if the item has a checkbox,
20866 ;; toggle it. Otherwise repair the list.
20867 (let* ((box (org-element-property :checkbox context))
20868 (struct (org-element-property :structure context))
20869 (old-struct (copy-tree struct))
20870 (parents (org-list-parents-alist struct))
20871 (prevs (org-list-prevs-alist struct))
20872 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20873 (org-list-set-checkbox
20874 (org-element-property :begin context) struct
20875 (cond ((equal arg '(16)) "[-]")
20876 ((and (not box) (equal arg '(4))) "[ ]")
20877 ((or (not box) (equal arg '(4))) nil)
20878 ((eq box 'on) "[ ]")
20879 (t "[X]")))
20880 ;; Mimic `org-list-write-struct' but with grabbing a return
20881 ;; value from `org-list-struct-fix-box'.
20882 (org-list-struct-fix-ind struct parents 2)
20883 (org-list-struct-fix-item-end struct)
20884 (org-list-struct-fix-bul struct prevs)
20885 (org-list-struct-fix-ind struct parents)
20886 (let ((block-item
20887 (org-list-struct-fix-box struct parents prevs orderedp)))
20888 (if (and box (equal struct old-struct))
20889 (if (equal arg '(16))
20890 (message "Checkboxes already reset")
20891 (user-error "Cannot toggle this checkbox: %s"
20892 (if (eq box 'on)
20893 "all subitems checked"
20894 "unchecked subitems")))
20895 (org-list-struct-apply-struct struct old-struct)
20896 (org-update-checkbox-count-maybe))
20897 (when block-item
20898 (message "Checkboxes were removed due to empty box at line %d"
20899 (org-current-line block-item))))))
20900 (`keyword
20901 (let ((org-inhibit-startup-visibility-stuff t)
20902 (org-startup-align-all-tables nil))
20903 (when (boundp 'org-table-coordinate-overlays)
20904 (mapc #'delete-overlay org-table-coordinate-overlays)
20905 (setq org-table-coordinate-overlays nil))
20906 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20907 (message "Local setup has been refreshed"))
20908 (`plain-list
20909 ;; At a plain list, with a double C-u argument, set
20910 ;; checkboxes of each item to "[-]", whereas a single one
20911 ;; will toggle their presence according to the state of the
20912 ;; first item in the list. Without an argument, repair the
20913 ;; list.
20914 (let* ((begin (org-element-property :contents-begin context))
20915 (beginm (move-marker (make-marker) begin))
20916 (struct (org-element-property :structure context))
20917 (old-struct (copy-tree struct))
20918 (first-box (save-excursion
20919 (goto-char begin)
20920 (looking-at org-list-full-item-re)
20921 (match-string-no-properties 3)))
20922 (new-box (cond ((equal arg '(16)) "[-]")
20923 ((equal arg '(4)) (unless first-box "[ ]"))
20924 ((equal first-box "[X]") "[ ]")
20925 (t "[X]"))))
20926 (cond
20927 (arg
20928 (dolist (pos
20929 (org-list-get-all-items
20930 begin struct (org-list-prevs-alist struct)))
20931 (org-list-set-checkbox pos struct new-box)))
20932 ((and first-box (eq (point) begin))
20933 ;; For convenience, when point is at bol on the first
20934 ;; item of the list and no argument is provided, simply
20935 ;; toggle checkbox of that item, if any.
20936 (org-list-set-checkbox begin struct new-box)))
20937 (org-list-write-struct
20938 struct (org-list-parents-alist struct) old-struct)
20939 (org-update-checkbox-count-maybe)
20940 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20941 ((or `property-drawer `node-property)
20942 (call-interactively #'org-property-action))
20943 (`radio-target
20944 (call-interactively #'org-update-radio-target-regexp))
20945 (`statistics-cookie
20946 (call-interactively #'org-update-statistics-cookies))
20947 ((or `table `table-cell `table-row)
20948 ;; At a table, recalculate every field and align it. Also
20949 ;; send the table if necessary. If the table has
20950 ;; a `table.el' type, just give up. At a table row or cell,
20951 ;; maybe recalculate line but always align table.
20952 (if (eq (org-element-property :type context) 'table.el)
20953 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20954 Use `\\[org-edit-special]' to edit table.el tables"))
20955 (let ((org-enable-table-editor t))
20956 (if (or (eq type 'table)
20957 ;; Check if point is at a TBLFM line.
20958 (and (eq type 'table-row)
20959 (= (point) (org-element-property :end context))))
20960 (save-excursion
20961 (if (org-at-TBLFM-p)
20962 (progn (require 'org-table)
20963 (org-table-calc-current-TBLFM))
20964 (goto-char (org-element-property :contents-begin context))
20965 (org-call-with-arg 'org-table-recalculate (or arg t))
20966 (orgtbl-send-table 'maybe)))
20967 (org-table-maybe-eval-formula)
20968 (cond (arg (call-interactively #'org-table-recalculate))
20969 ((org-table-maybe-recalculate-line))
20970 (t (org-table-align)))))))
20971 (`timestamp (org-timestamp-change 0 'day))
20972 ((and `nil (guard (org-at-heading-p)))
20973 ;; When point is on an unsupported object type, we can miss
20974 ;; the fact that it also is at a heading. Handle it here.
20975 (call-interactively #'org-set-tags))
20976 ((guard
20977 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20979 (user-error
20980 (substitute-command-keys
20981 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20983 (defun org-mode-restart ()
20984 (interactive)
20985 (let ((indent-status (bound-and-true-p org-indent-mode)))
20986 (funcall major-mode)
20987 (hack-local-variables)
20988 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20989 (org-indent-mode -1))
20990 (org-reset-file-cache))
20991 (message "%s restarted" major-mode))
20993 (defun org-kill-note-or-show-branches ()
20994 "Abort storing current note, or call `outline-show-branches'."
20995 (interactive)
20996 (if (not org-finish-function)
20997 (progn
20998 (outline-hide-subtree)
20999 (call-interactively 'outline-show-branches))
21000 (let ((org-note-abort t))
21001 (funcall org-finish-function))))
21003 (defun org-delete-indentation (&optional arg)
21004 "Join current line to previous and fix whitespace at join.
21006 If previous line is a headline add to headline title. Otherwise
21007 the function calls `delete-indentation'.
21009 With a non-nil optional argument, join it to the following one."
21010 (interactive "*P")
21011 (if (save-excursion
21012 (beginning-of-line (if arg 1 0))
21013 (let ((case-fold-search nil))
21014 (looking-at org-complex-heading-regexp)))
21015 ;; At headline.
21016 (let ((tags-column (when (match-beginning 5)
21017 (save-excursion (goto-char (match-beginning 5))
21018 (current-column))))
21019 (string (concat " " (progn (when arg (forward-line 1))
21020 (org-trim (delete-and-extract-region
21021 (line-beginning-position)
21022 (line-end-position)))))))
21023 (unless (bobp) (delete-region (point) (1- (point))))
21024 (goto-char (or (match-end 4)
21025 (match-beginning 5)
21026 (match-end 0)))
21027 (skip-chars-backward " \t")
21028 (save-excursion (insert string))
21029 ;; Adjust alignment of tags.
21030 (cond
21031 ((not tags-column)) ;no tags
21032 (org-auto-align-tags (org-set-tags nil t))
21033 (t (org--align-tags-here tags-column)))) ;preserve tags column
21034 (delete-indentation arg)))
21036 (defun org-open-line (n)
21037 "Insert a new row in tables, call `open-line' elsewhere.
21038 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21039 As a special case, when a document starts with a table, allow to
21040 call `open-line' on the very first character."
21041 (interactive "*p")
21042 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21043 (org-table-insert-row)
21044 (open-line n)))
21046 (defun org-return (&optional indent)
21047 "Goto next table row or insert a newline.
21049 Calls `org-table-next-row' or `newline', depending on context.
21051 When optional INDENT argument is non-nil, call
21052 `newline-and-indent' instead of `newline'.
21054 When `org-return-follows-link' is non-nil and point is on
21055 a timestamp or a link, call `org-open-at-point'. However, it
21056 will not happen if point is in a table or on a \"dead\"
21057 object (e.g., within a comment). In these case, you need to use
21058 `org-open-at-point' directly."
21059 (interactive)
21060 (let ((context (if org-return-follows-link (org-element-context)
21061 (org-element-at-point))))
21062 (cond
21063 ;; In a table, call `org-table-next-row'.
21064 ((or (and (eq (org-element-type context) 'table)
21065 (>= (point) (org-element-property :contents-begin context))
21066 (< (point) (org-element-property :contents-end context)))
21067 (org-element-lineage context '(table-row table-cell) t))
21068 (org-table-justify-field-maybe)
21069 (call-interactively #'org-table-next-row))
21070 ;; On a link or a timestamp, call `org-open-at-point' if
21071 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21072 ;; locations, e.g., in a comment, as `org-open-at-point'.
21073 ((and org-return-follows-link
21074 (or (org-in-regexp org-ts-regexp-both nil t)
21075 (org-in-regexp org-tsr-regexp-both nil t)
21076 (org-in-regexp org-any-link-re nil t)))
21077 (call-interactively #'org-open-at-point))
21078 ;; Insert newline in heading, but preserve tags.
21079 ((and (not (bolp))
21080 (save-excursion (beginning-of-line)
21081 (let ((case-fold-search nil))
21082 (looking-at org-complex-heading-regexp))))
21083 ;; At headline. Split line. However, if point is on keyword,
21084 ;; priority cookie or tags, do not break any of them: add
21085 ;; a newline after the headline instead.
21086 (let ((tags-column (and (match-beginning 5)
21087 (save-excursion (goto-char (match-beginning 5))
21088 (current-column))))
21089 (string
21090 (when (and (match-end 4) (org-point-in-group (point) 4))
21091 (delete-and-extract-region (point) (match-end 4)))))
21092 ;; Adjust tag alignment.
21093 (cond
21094 ((not (and tags-column string)))
21095 (org-auto-align-tags (org-set-tags nil t))
21096 (t (org--align-tags-here tags-column))) ;preserve tags column
21097 (end-of-line)
21098 (org-show-entry)
21099 (if indent (newline-and-indent) (newline))
21100 (when string (save-excursion (insert (org-trim string))))))
21101 ;; In a list, make sure indenting keeps trailing text within.
21102 ((and indent
21103 (not (eolp))
21104 (org-element-lineage context '(item)))
21105 (let ((trailing-data
21106 (delete-and-extract-region (point) (line-end-position))))
21107 (newline-and-indent)
21108 (save-excursion (insert trailing-data))))
21109 (t (if indent (newline-and-indent) (newline))))))
21111 (defun org-return-indent ()
21112 "Goto next table row or insert a newline and indent.
21113 Calls `org-table-next-row' or `newline-and-indent', depending on
21114 context. See the individual commands for more information."
21115 (interactive)
21116 (org-return t))
21118 (defun org-ctrl-c-star ()
21119 "Compute table, or change heading status of lines.
21120 Calls `org-table-recalculate' or `org-toggle-heading',
21121 depending on context."
21122 (interactive)
21123 (cond
21124 ((org-at-table-p)
21125 (call-interactively 'org-table-recalculate))
21127 ;; Convert all lines in region to list items
21128 (call-interactively 'org-toggle-heading))))
21130 (defun org-ctrl-c-minus ()
21131 "Insert separator line in table or modify bullet status of line.
21132 Also turns a plain line or a region of lines into list items.
21133 Calls `org-table-insert-hline', `org-toggle-item', or
21134 `org-cycle-list-bullet', depending on context."
21135 (interactive)
21136 (cond
21137 ((org-at-table-p)
21138 (call-interactively 'org-table-insert-hline))
21139 ((org-region-active-p)
21140 (call-interactively 'org-toggle-item))
21141 ((org-in-item-p)
21142 (call-interactively 'org-cycle-list-bullet))
21144 (call-interactively 'org-toggle-item))))
21146 (defun org-toggle-heading (&optional nstars)
21147 "Convert headings to normal text, or items or text to headings.
21148 If there is no active region, only convert the current line.
21150 With a `\\[universal-argument]' prefix, convert the whole list at
21151 point into heading.
21153 In a region:
21155 - If the first non blank line is a headline, remove the stars
21156 from all headlines in the region.
21158 - If it is a normal line, turn each and every normal line (i.e.,
21159 not an heading or an item) in the region into headings. If you
21160 want to convert only the first line of this region, use one
21161 universal prefix argument.
21163 - If it is a plain list item, turn all plain list items into headings.
21165 When converting a line into a heading, the number of stars is chosen
21166 such that the lines become children of the current entry. However,
21167 when a numeric prefix argument is given, its value determines the
21168 number of stars to add."
21169 (interactive "P")
21170 (let ((skip-blanks
21171 (function
21172 ;; Return beginning of first non-blank line, starting from
21173 ;; line at POS.
21174 (lambda (pos)
21175 (save-excursion
21176 (goto-char pos)
21177 (while (org-at-comment-p) (forward-line))
21178 (skip-chars-forward " \r\t\n")
21179 (point-at-bol)))))
21180 beg end toggled)
21181 ;; Determine boundaries of changes. If a universal prefix has
21182 ;; been given, put the list in a region. If region ends at a bol,
21183 ;; do not consider the last line to be in the region.
21185 (when (and current-prefix-arg (org-at-item-p))
21186 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21187 (org-mark-element))
21189 (if (org-region-active-p)
21190 (setq beg (funcall skip-blanks (region-beginning))
21191 end (copy-marker (save-excursion
21192 (goto-char (region-end))
21193 (if (bolp) (point) (point-at-eol)))))
21194 (setq beg (funcall skip-blanks (point-at-bol))
21195 end (copy-marker (point-at-eol))))
21196 ;; Ensure inline tasks don't count as headings.
21197 (org-with-limited-levels
21198 (save-excursion
21199 (goto-char beg)
21200 (cond
21201 ;; Case 1. Started at an heading: de-star headings.
21202 ((org-at-heading-p)
21203 (while (< (point) end)
21204 (when (org-at-heading-p t)
21205 (looking-at org-outline-regexp) (replace-match "")
21206 (setq toggled t))
21207 (forward-line)))
21208 ;; Case 2. Started at an item: change items into headlines.
21209 ;; One star will be added by `org-list-to-subtree'.
21210 ((org-at-item-p)
21211 (while (< (point) end)
21212 (when (org-at-item-p)
21213 ;; Pay attention to cases when region ends before list.
21214 (let* ((struct (org-list-struct))
21215 (list-end
21216 (min (org-list-get-bottom-point struct) (1+ end))))
21217 (save-restriction
21218 (narrow-to-region (point) list-end)
21219 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21220 (setq toggled t))
21221 (forward-line)))
21222 ;; Case 3. Started at normal text: make every line an heading,
21223 ;; skipping headlines and items.
21224 (t (let* ((stars
21225 (make-string
21226 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21227 (add-stars
21228 (cond (nstars "") ; stars from prefix only
21229 ((equal stars "") "*") ; before first heading
21230 (org-odd-levels-only "**") ; inside heading, odd
21231 (t "*"))) ; inside heading, oddeven
21232 (rpl (concat stars add-stars " "))
21233 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21234 (while (< (point) (if (equal nstars '(4)) lend end))
21235 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21236 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21237 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21238 (forward-line)))))))
21239 (unless toggled (message "Cannot toggle heading from here"))))
21241 (defun org-meta-return (&optional arg)
21242 "Insert a new heading or wrap a region in a table.
21243 Calls `org-insert-heading', `org-insert-item' or
21244 `org-table-wrap-region', depending on context. When called with
21245 an argument, unconditionally call `org-insert-heading'."
21246 (interactive "P")
21247 (org-check-before-invisible-edit 'insert)
21248 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21249 (call-interactively (cond (arg #'org-insert-heading)
21250 ((org-at-table-p) #'org-table-wrap-region)
21251 ((org-in-item-p) #'org-insert-item)
21252 (t #'org-insert-heading)))))
21254 ;;; Menu entries
21256 (defsubst org-in-subtree-not-table-p ()
21257 "Are we in a subtree and not in a table?"
21258 (and (not (org-before-first-heading-p))
21259 (not (org-at-table-p))))
21261 ;; Define the Org mode menus
21262 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21263 '("Tbl"
21264 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21265 ["Next Field" org-cycle (org-at-table-p)]
21266 ["Previous Field" org-shifttab (org-at-table-p)]
21267 ["Next Row" org-return (org-at-table-p)]
21268 "--"
21269 ["Blank Field" org-table-blank-field (org-at-table-p)]
21270 ["Edit Field" org-table-edit-field (org-at-table-p)]
21271 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21272 "--"
21273 ("Column"
21274 ["Move Column Left" org-metaleft (org-at-table-p)]
21275 ["Move Column Right" org-metaright (org-at-table-p)]
21276 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21277 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21278 ("Row"
21279 ["Move Row Up" org-metaup (org-at-table-p)]
21280 ["Move Row Down" org-metadown (org-at-table-p)]
21281 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21282 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21283 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21284 "--"
21285 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21286 ("Rectangle"
21287 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21288 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21289 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21290 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21291 "--"
21292 ("Calculate"
21293 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21294 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21295 ["Edit Formulas" org-edit-special (org-at-table-p)]
21296 "--"
21297 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21298 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21299 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21300 "--"
21301 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21302 "--"
21303 ["Sum Column/Rectangle" org-table-sum
21304 (or (org-at-table-p) (org-region-active-p))]
21305 ["Which Column?" org-table-current-column (org-at-table-p)])
21306 ["Debug Formulas"
21307 org-table-toggle-formula-debugger
21308 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21309 ["Show Col/Row Numbers"
21310 org-table-toggle-coordinate-overlays
21311 :style toggle
21312 :selected (bound-and-true-p org-table-overlay-coordinates)]
21313 "--"
21314 ["Create" org-table-create (and (not (org-at-table-p))
21315 org-enable-table-editor)]
21316 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21317 ["Import from File" org-table-import (not (org-at-table-p))]
21318 ["Export to File" org-table-export (org-at-table-p)]
21319 "--"
21320 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21321 "--"
21322 ("Plot"
21323 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21324 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21326 (easy-menu-define org-org-menu org-mode-map "Org menu"
21327 '("Org"
21328 ("Show/Hide"
21329 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21330 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21331 ["Sparse Tree..." org-sparse-tree t]
21332 ["Reveal Context" org-reveal t]
21333 ["Show All" outline-show-all t]
21334 "--"
21335 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21336 "--"
21337 ["New Heading" org-insert-heading t]
21338 ("Navigate Headings"
21339 ["Up" outline-up-heading t]
21340 ["Next" outline-next-visible-heading t]
21341 ["Previous" outline-previous-visible-heading t]
21342 ["Next Same Level" outline-forward-same-level t]
21343 ["Previous Same Level" outline-backward-same-level t]
21344 "--"
21345 ["Jump" org-goto t])
21346 ("Edit Structure"
21347 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21348 "--"
21349 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21350 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21351 "--"
21352 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21353 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21354 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21355 "--"
21356 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21357 "--"
21358 ["Copy visible text" org-copy-visible t]
21359 "--"
21360 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21361 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21362 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21363 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21364 "--"
21365 ["Sort Region/Children" org-sort t]
21366 "--"
21367 ["Convert to odd levels" org-convert-to-odd-levels t]
21368 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21369 ("Editing"
21370 ["Emphasis..." org-emphasize t]
21371 ["Edit Source Example" org-edit-special t]
21372 "--"
21373 ["Footnote new/jump" org-footnote-action t]
21374 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21375 ("Archive"
21376 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21377 "--"
21378 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21379 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21380 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21382 "--"
21383 ("Hyperlinks"
21384 ["Store Link (Global)" org-store-link t]
21385 ["Find existing link to here" org-occur-link-in-agenda-files t]
21386 ["Insert Link" org-insert-link t]
21387 ["Follow Link" org-open-at-point t]
21388 "--"
21389 ["Next link" org-next-link t]
21390 ["Previous link" org-previous-link t]
21391 "--"
21392 ["Descriptive Links"
21393 org-toggle-link-display
21394 :style radio
21395 :selected org-descriptive-links
21397 ["Literal Links"
21398 org-toggle-link-display
21399 :style radio
21400 :selected (not org-descriptive-links)])
21401 "--"
21402 ("TODO Lists"
21403 ["TODO/DONE/-" org-todo t]
21404 ("Select keyword"
21405 ["Next keyword" org-shiftright (org-at-heading-p)]
21406 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21407 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21408 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21409 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21410 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21411 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21412 "--"
21413 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21414 :selected org-enforce-todo-dependencies :style toggle :active t]
21415 "Settings for tree at point"
21416 ["Do Children sequentially" org-toggle-ordered-property :style radio
21417 :selected (org-entry-get nil "ORDERED")
21418 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21419 ["Do Children parallel" org-toggle-ordered-property :style radio
21420 :selected (not (org-entry-get nil "ORDERED"))
21421 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21422 "--"
21423 ["Set Priority" org-priority t]
21424 ["Priority Up" org-shiftup t]
21425 ["Priority Down" org-shiftdown t]
21426 "--"
21427 ["Get news from all feeds" org-feed-update-all t]
21428 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21429 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21430 ("TAGS and Properties"
21431 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21432 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21433 "--"
21434 ["Set property" org-set-property (not (org-before-first-heading-p))]
21435 ["Column view of properties" org-columns t]
21436 ["Insert Column View DBlock" org-columns-insert-dblock t])
21437 ("Dates and Scheduling"
21438 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21439 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21440 ("Change Date"
21441 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21442 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21443 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21444 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21445 ["Compute Time Range" org-evaluate-time-range t]
21446 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21447 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21448 "--"
21449 ["Custom time format" org-toggle-time-stamp-overlays
21450 :style radio :selected org-display-custom-times]
21451 "--"
21452 ["Goto Calendar" org-goto-calendar t]
21453 ["Date from Calendar" org-date-from-calendar t]
21454 "--"
21455 ["Start/Restart Timer" org-timer-start t]
21456 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21457 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21458 ["Insert Timer String" org-timer t]
21459 ["Insert Timer Item" org-timer-item t])
21460 ("Logging work"
21461 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21462 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21463 ["Clock out" org-clock-out t]
21464 ["Clock cancel" org-clock-cancel t]
21465 "--"
21466 ["Mark as default task" org-clock-mark-default-task t]
21467 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21468 ["Goto running clock" org-clock-goto t]
21469 "--"
21470 ["Display times" org-clock-display t]
21471 ["Create clock table" org-clock-report t]
21472 "--"
21473 ["Record DONE time"
21474 (progn (setq org-log-done (not org-log-done))
21475 (message "Switching to %s will %s record a timestamp"
21476 (car org-done-keywords)
21477 (if org-log-done "automatically" "not")))
21478 :style toggle :selected org-log-done])
21479 "--"
21480 ["Agenda Command..." org-agenda t]
21481 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21482 ("File List for Agenda")
21483 ("Special views current file"
21484 ["TODO Tree" org-show-todo-tree t]
21485 ["Check Deadlines" org-check-deadlines t]
21486 ["Tags/Property tree" org-match-sparse-tree t])
21487 "--"
21488 ["Export/Publish..." org-export-dispatch t]
21489 ("LaTeX"
21490 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21491 :selected org-cdlatex-mode]
21492 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21493 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21494 ["Modify math symbol" org-cdlatex-math-modify
21495 (org-inside-LaTeX-fragment-p)]
21496 ["Insert citation" org-reftex-citation t])
21497 "--"
21498 ("MobileOrg"
21499 ["Push Files and Views" org-mobile-push t]
21500 ["Get Captured and Flagged" org-mobile-pull t]
21501 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21502 "--"
21503 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21504 "--"
21505 ("Documentation"
21506 ["Show Version" org-version t]
21507 ["Info Documentation" org-info t])
21508 ("Customize"
21509 ["Browse Org Group" org-customize t]
21510 "--"
21511 ["Expand This Menu" org-create-customize-menu
21512 (fboundp 'customize-menu-create)])
21513 ["Send bug report" org-submit-bug-report t]
21514 "--"
21515 ("Refresh/Reload"
21516 ["Refresh setup current buffer" org-mode-restart t]
21517 ["Reload Org (after update)" org-reload t]
21518 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21521 (defun org-info (&optional node)
21522 "Read documentation for Org in the info system.
21523 With optional NODE, go directly to that node."
21524 (interactive)
21525 (info (format "(org)%s" (or node ""))))
21527 ;;;###autoload
21528 (defun org-submit-bug-report ()
21529 "Submit a bug report on Org via mail.
21531 Don't hesitate to report any problems or inaccurate documentation.
21533 If you don't have setup sending mail from (X)Emacs, please copy the
21534 output buffer into your mail program, as it gives us important
21535 information about your Org version and configuration."
21536 (interactive)
21537 (require 'reporter)
21538 (defvar reporter-prompt-for-summary-p)
21539 (org-load-modules-maybe)
21540 (org-require-autoloaded-modules)
21541 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21542 (reporter-submit-bug-report
21543 "emacs-orgmode@gnu.org"
21544 (org-version nil 'full)
21545 (let (list)
21546 (save-window-excursion
21547 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21548 (delete-other-windows)
21549 (erase-buffer)
21550 (insert "You are about to submit a bug report to the Org mailing list.
21552 We would like to add your full Org and Outline configuration to the
21553 bug report. This greatly simplifies the work of the maintainer and
21554 other experts on the mailing list.
21556 HOWEVER, some variables you have customized may contain private
21557 information. The names of customers, colleagues, or friends, might
21558 appear in the form of file names, tags, todo states, or search strings.
21559 If you answer yes to the prompt, you might want to check and remove
21560 such private information before sending the email.")
21561 (add-text-properties (point-min) (point-max) '(face org-warning))
21562 (when (yes-or-no-p "Include your Org configuration ")
21563 (mapatoms
21564 (lambda (v)
21565 (and (boundp v)
21566 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21567 (or (and (symbol-value v)
21568 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21569 (and
21570 (get v 'custom-type) (get v 'standard-value)
21571 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21572 (push v list)))))
21573 (kill-buffer (get-buffer "*Warn about privacy*"))
21574 list))
21575 nil nil
21576 "Remember to cover the basics, that is, what you expected to happen and
21577 what in fact did happen. You don't know how to make a good report? See
21579 http://orgmode.org/manual/Feedback.html#Feedback
21581 Your bug report will be posted to the Org mailing list.
21582 ------------------------------------------------------------------------")
21583 (save-excursion
21584 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21585 (replace-match "\\1Bug: \\3 [\\2]")))))
21588 (defun org-install-agenda-files-menu ()
21589 (let ((bl (buffer-list)))
21590 (save-excursion
21591 (while bl
21592 (set-buffer (pop bl))
21593 (when (derived-mode-p 'org-mode) (setq bl nil)))
21594 (when (derived-mode-p 'org-mode)
21595 (easy-menu-change
21596 '("Org") "File List for Agenda"
21597 (append
21598 (list
21599 ["Edit File List" (org-edit-agenda-file-list) t]
21600 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21601 ["Remove Current File from List" org-remove-file t]
21602 ["Cycle through agenda files" org-cycle-agenda-files t]
21603 ["Occur in all agenda files" org-occur-in-agenda-files t]
21604 "--")
21605 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21607 ;;;; Documentation
21609 (defun org-require-autoloaded-modules ()
21610 (interactive)
21611 (mapc #'require
21612 '(org-agenda org-archive org-attach org-clock org-colview org-id
21613 org-table org-timer)))
21615 ;;;###autoload
21616 (defun org-reload (&optional uncompiled)
21617 "Reload all org lisp files.
21618 With prefix arg UNCOMPILED, load the uncompiled versions."
21619 (interactive "P")
21620 (require 'loadhist)
21621 (let* ((org-dir (org-find-library-dir "org"))
21622 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21623 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21624 (remove-re (format "\\`%s\\'"
21625 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21626 (feats (delete-dups
21627 (mapcar 'file-name-sans-extension
21628 (mapcar 'file-name-nondirectory
21629 (delq nil
21630 (mapcar 'feature-file
21631 features))))))
21632 (lfeat (append
21633 (sort
21634 (setq feats
21635 (delq nil (mapcar
21636 (lambda (f)
21637 (if (and (string-match feature-re f)
21638 (not (string-match remove-re f)))
21639 f nil))
21640 feats)))
21641 'string-lessp)
21642 (list "org-version" "org")))
21643 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21644 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21645 load-uncore load-misses)
21646 (setq load-misses
21647 (delq 't
21648 (mapcar (lambda (f)
21649 (or (org-load-noerror-mustsuffix (concat org-dir f))
21650 (and (string= org-dir contrib-dir)
21651 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21652 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21653 (add-to-list 'load-uncore f 'append)
21656 lfeat)))
21657 (when load-uncore
21658 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21659 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21660 (if load-misses
21661 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21662 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21663 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21665 ;;;###autoload
21666 (defun org-customize ()
21667 "Call the customize function with org as argument."
21668 (interactive)
21669 (org-load-modules-maybe)
21670 (org-require-autoloaded-modules)
21671 (customize-browse 'org))
21673 (defun org-create-customize-menu ()
21674 "Create a full customization menu for Org mode, insert it into the menu."
21675 (interactive)
21676 (org-load-modules-maybe)
21677 (org-require-autoloaded-modules)
21678 (if (fboundp 'customize-menu-create)
21679 (progn
21680 (easy-menu-change
21681 '("Org") "Customize"
21682 `(["Browse Org group" org-customize t]
21683 "--"
21684 ,(customize-menu-create 'org)
21685 ["Set" Custom-set t]
21686 ["Save" Custom-save t]
21687 ["Reset to Current" Custom-reset-current t]
21688 ["Reset to Saved" Custom-reset-saved t]
21689 ["Reset to Standard Settings" Custom-reset-standard t]))
21690 (message "\"Org\"-menu now contains full customization menu"))
21691 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21693 ;;;; Miscellaneous stuff
21695 ;;; Generally useful functions
21697 (defun org-get-at-eol (property n)
21698 "Get text property PROPERTY at the end of line less N characters."
21699 (get-text-property (- (point-at-eol) n) property))
21701 (defun org-find-text-property-in-string (prop s)
21702 "Return the first non-nil value of property PROP in string S."
21703 (or (get-text-property 0 prop s)
21704 (get-text-property (or (next-single-property-change 0 prop s) 0)
21705 prop s)))
21707 (defun org-display-warning (message)
21708 "Display the given MESSAGE as a warning."
21709 (display-warning 'org message :warning))
21711 (defun org-eval (form)
21712 "Eval FORM and return result."
21713 (condition-case error
21714 (eval form)
21715 (error (format "%%![Error: %s]" error))))
21717 (defun org-in-clocktable-p ()
21718 "Check if the cursor is in a clocktable."
21719 (let ((pos (point)) start)
21720 (save-excursion
21721 (end-of-line 1)
21722 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21723 (setq start (match-beginning 0))
21724 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21725 (>= (match-end 0) pos)
21726 start))))
21728 (defun org-in-verbatim-emphasis ()
21729 (save-match-data
21730 (and (org-in-regexp org-verbatim-re 2)
21731 (>= (point) (match-beginning 3))
21732 (<= (point) (match-end 4)))))
21734 (defun org-overlay-display (ovl text &optional face evap)
21735 "Make overlay OVL display TEXT with face FACE."
21736 (overlay-put ovl 'display text)
21737 (if face (overlay-put ovl 'face face))
21738 (if evap (overlay-put ovl 'evaporate t)))
21740 (defun org-overlay-before-string (ovl text &optional face evap)
21741 "Make overlay OVL display TEXT with face FACE."
21742 (if face (org-add-props text nil 'face face))
21743 (overlay-put ovl 'before-string text)
21744 (if evap (overlay-put ovl 'evaporate t)))
21746 (defun org-find-overlays (prop &optional pos delete)
21747 "Find all overlays specifying PROP at POS or point.
21748 If DELETE is non-nil, delete all those overlays."
21749 (let (found)
21750 (dolist (ov (overlays-at (or pos (point))) found)
21751 (cond ((not (overlay-get ov prop)))
21752 (delete (delete-overlay ov))
21753 (t (push ov found))))))
21755 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21756 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21757 (if (and marker (marker-buffer marker)
21758 (buffer-live-p (marker-buffer marker)))
21759 (progn
21760 (pop-to-buffer-same-window (marker-buffer marker))
21761 (when (or (> marker (point-max)) (< marker (point-min)))
21762 (widen))
21763 (goto-char marker)
21764 (org-show-context 'org-goto))
21765 (if bookmark
21766 (bookmark-jump bookmark)
21767 (error "Cannot find location"))))
21769 (defun org-quote-csv-field (s)
21770 "Quote field for inclusion in CSV material."
21771 (if (string-match "[\",]" s)
21772 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21775 (defun org-force-self-insert (N)
21776 "Needed to enforce self-insert under remapping."
21777 (interactive "p")
21778 (self-insert-command N))
21780 (defun org-shorten-string (s maxlength)
21781 "Shorten string S so that it is no longer than MAXLENGTH characters.
21782 If the string is shorter or has length MAXLENGTH, just return the
21783 original string. If it is longer, the functions finds a space in the
21784 string, breaks this string off at that locations and adds three dots
21785 as ellipsis. Including the ellipsis, the string will not be longer
21786 than MAXLENGTH. If finding a good breaking point in the string does
21787 not work, the string is just chopped off in the middle of a word
21788 if necessary."
21789 (if (<= (length s) maxlength)
21791 (let* ((n (max (- maxlength 4) 1))
21792 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21793 (if (string-match re s)
21794 (concat (match-string 1 s) "...")
21795 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21797 (defun org-get-indentation (&optional line)
21798 "Get the indentation of the current line, interpreting tabs.
21799 When LINE is given, assume it represents a line and compute its indentation."
21800 (if line
21801 (when (string-match "^ *" (org-remove-tabs line))
21802 (match-end 0))
21803 (save-excursion
21804 (beginning-of-line 1)
21805 (skip-chars-forward " \t")
21806 (current-column))))
21808 (defun org-get-string-indentation (s)
21809 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21810 (let ((n -1) (i 0) (w tab-width) c)
21811 (catch 'exit
21812 (while (< (setq n (1+ n)) (length s))
21813 (setq c (aref s n))
21814 (cond ((= c ?\ ) (setq i (1+ i)))
21815 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21816 (t (throw 'exit t)))))
21819 (defun org-remove-tabs (s &optional width)
21820 "Replace tabulators in S with spaces.
21821 Assumes that s is a single line, starting in column 0."
21822 (setq width (or width tab-width))
21823 (while (string-match "\t" s)
21824 (setq s (replace-match
21825 (make-string
21826 (- (* width (/ (+ (match-beginning 0) width) width))
21827 (match-beginning 0)) ?\ )
21828 t t s)))
21831 (defun org-fix-indentation (line ind)
21832 "Fix indentation in LINE.
21833 IND is a cons cell with target and minimum indentation.
21834 If the current indentation in LINE is smaller than the minimum,
21835 leave it alone. If it is larger than ind, set it to the target."
21836 (let* ((l (org-remove-tabs line))
21837 (i (org-get-indentation l))
21838 (i1 (car ind)) (i2 (cdr ind)))
21839 (when (>= i i2) (setq l (substring line i2)))
21840 (if (> i1 0)
21841 (concat (make-string i1 ?\ ) l)
21842 l)))
21844 (defun org-remove-indentation (code &optional n)
21845 "Remove maximum common indentation in string CODE and return it.
21846 N may optionally be the number of columns to remove. Return CODE
21847 as-is if removal failed."
21848 (with-temp-buffer
21849 (insert code)
21850 (if (org-do-remove-indentation n) (buffer-string) code)))
21852 (defun org-do-remove-indentation (&optional n)
21853 "Remove the maximum common indentation from the buffer.
21854 When optional argument N is a positive integer, remove exactly
21855 that much characters from indentation, if possible. Return nil
21856 if it fails."
21857 (catch :exit
21858 (goto-char (point-min))
21859 ;; Find maximum common indentation, if not specified.
21860 (let ((n (or n
21861 (let ((min-ind (point-max)))
21862 (save-excursion
21863 (while (re-search-forward "^[ \t]*\\S-" nil t)
21864 (let ((ind (1- (current-column))))
21865 (if (zerop ind) (throw :exit nil)
21866 (setq min-ind (min min-ind ind))))))
21867 min-ind))))
21868 (if (zerop n) (throw :exit nil)
21869 ;; Remove exactly N indentation, but give up if not possible.
21870 (while (not (eobp))
21871 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21872 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21873 ((< ind n) (throw :exit nil))
21874 (t (indent-line-to (- ind n))))
21875 (forward-line)))
21876 ;; Signal success.
21877 t))))
21879 (defun org-fill-template (template alist)
21880 "Find each %key of ALIST in TEMPLATE and replace it."
21881 (let ((case-fold-search nil))
21882 (dolist (entry (sort (copy-sequence alist)
21883 (lambda (a b) (< (length (car a)) (length (car b))))))
21884 (setq template
21885 (replace-regexp-in-string
21886 (concat "%" (regexp-quote (car entry)))
21887 (or (cdr entry) "") template t t)))
21888 template))
21890 (defun org-base-buffer (buffer)
21891 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21892 (if (not buffer)
21893 buffer
21894 (or (buffer-base-buffer buffer)
21895 buffer)))
21897 (defun org-wrap (string &optional width lines)
21898 "Wrap string to either a number of lines, or a width in characters.
21899 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21900 that costs. If there is a word longer than WIDTH, the text is actually
21901 wrapped to the length of that word.
21902 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21903 many lines, whatever width that takes.
21904 The return value is a list of lines, without newlines at the end."
21905 (let* ((words (org-split-string string "[ \t\n]+"))
21906 (maxword (apply 'max (mapcar 'org-string-width words)))
21907 w ll)
21908 (cond (width
21909 (org-do-wrap words (max maxword width)))
21910 (lines
21911 (setq w maxword)
21912 (setq ll (org-do-wrap words maxword))
21913 (if (<= (length ll) lines)
21915 (setq ll words)
21916 (while (> (length ll) lines)
21917 (setq w (1+ w))
21918 (setq ll (org-do-wrap words w)))
21919 ll))
21920 (t (error "Cannot wrap this")))))
21922 (defun org-do-wrap (words width)
21923 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21924 (let (lines line)
21925 (while words
21926 (setq line (pop words))
21927 (while (and words (< (+ (length line) (length (car words))) width))
21928 (setq line (concat line " " (pop words))))
21929 (setq lines (push line lines)))
21930 (nreverse lines)))
21932 (defun org-quote-vert (s)
21933 "Replace \"|\" with \"\\vert\"."
21934 (while (string-match "|" s)
21935 (setq s (replace-match "\\vert" t t s)))
21938 (defun org-uuidgen-p (s)
21939 "Is S an ID created by UUIDGEN?"
21940 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21942 (defun org-in-src-block-p (&optional inside)
21943 "Whether point is in a code source block.
21944 When INSIDE is non-nil, don't consider we are within a src block
21945 when point is at #+BEGIN_SRC or #+END_SRC."
21946 (let ((case-fold-search t))
21947 (or (and (eq (get-char-property (point) 'src-block) t))
21948 (and (not inside)
21949 (save-match-data
21950 (save-excursion
21951 (beginning-of-line)
21952 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21954 (defun org-context ()
21955 "Return a list of contexts of the current cursor position.
21956 If several contexts apply, all are returned.
21957 Each context entry is a list with a symbol naming the context, and
21958 two positions indicating start and end of the context. Possible
21959 contexts are:
21961 :headline anywhere in a headline
21962 :headline-stars on the leading stars in a headline
21963 :todo-keyword on a TODO keyword (including DONE) in a headline
21964 :tags on the TAGS in a headline
21965 :priority on the priority cookie in a headline
21966 :item on the first line of a plain list item
21967 :item-bullet on the bullet/number of a plain list item
21968 :checkbox on the checkbox in a plain list item
21969 :table in an Org table
21970 :table-special on a special filed in a table
21971 :table-table in a table.el table
21972 :clocktable in a clocktable
21973 :src-block in a source block
21974 :link on a hyperlink
21975 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21976 :target on a <<target>>
21977 :radio-target on a <<<radio-target>>>
21978 :latex-fragment on a LaTeX fragment
21979 :latex-preview on a LaTeX fragment with overlaid preview image
21981 This function expects the position to be visible because it uses font-lock
21982 faces as a help to recognize the following contexts: :table-special, :link,
21983 and :keyword."
21984 (let* ((f (get-text-property (point) 'face))
21985 (faces (if (listp f) f (list f)))
21986 (case-fold-search t)
21987 (p (point)) clist o)
21988 ;; First the large context
21989 (cond
21990 ((org-at-heading-p t)
21991 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21992 (when (progn
21993 (beginning-of-line 1)
21994 (looking-at org-todo-line-tags-regexp))
21995 (push (org-point-in-group p 1 :headline-stars) clist)
21996 (push (org-point-in-group p 2 :todo-keyword) clist)
21997 (push (org-point-in-group p 4 :tags) clist))
21998 (goto-char p)
21999 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22000 (when (looking-at "\\[#[A-Z0-9]\\]")
22001 (push (org-point-in-group p 0 :priority) clist)))
22003 ((org-at-item-p)
22004 (push (org-point-in-group p 2 :item-bullet) clist)
22005 (push (list :item (point-at-bol)
22006 (save-excursion (org-end-of-item) (point)))
22007 clist)
22008 (and (org-at-item-checkbox-p)
22009 (push (org-point-in-group p 0 :checkbox) clist)))
22011 ((org-at-table-p)
22012 (push (list :table (org-table-begin) (org-table-end)) clist)
22013 (when (memq 'org-formula faces)
22014 (push (list :table-special
22015 (previous-single-property-change p 'face)
22016 (next-single-property-change p 'face)) clist)))
22017 ((org-at-table-p 'any)
22018 (push (list :table-table) clist)))
22019 (goto-char p)
22021 (let ((case-fold-search t))
22022 ;; New the "medium" contexts: clocktables, source blocks
22023 (cond ((org-in-clocktable-p)
22024 (push (list :clocktable
22025 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22026 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22027 (match-beginning 1))
22028 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22029 (match-end 0))) clist))
22030 ((org-in-src-block-p)
22031 (push (list :src-block
22032 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22033 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22034 (match-beginning 1))
22035 (and (search-forward "#+END_SRC" nil t)
22036 (match-beginning 0))) clist))))
22037 (goto-char p)
22039 ;; Now the small context
22040 (cond
22041 ((org-at-timestamp-p)
22042 (push (org-point-in-group p 0 :timestamp) clist))
22043 ((memq 'org-link faces)
22044 (push (list :link
22045 (previous-single-property-change p 'face)
22046 (next-single-property-change p 'face)) clist))
22047 ((memq 'org-special-keyword faces)
22048 (push (list :keyword
22049 (previous-single-property-change p 'face)
22050 (next-single-property-change p 'face)) clist))
22051 ((org-at-target-p)
22052 (push (org-point-in-group p 0 :target) clist)
22053 (goto-char (1- (match-beginning 0)))
22054 (when (looking-at org-radio-target-regexp)
22055 (push (org-point-in-group p 0 :radio-target) clist))
22056 (goto-char p))
22057 ((setq o (cl-some
22058 (lambda (o)
22059 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22061 (overlays-at (point))))
22062 (push (list :latex-fragment
22063 (overlay-start o) (overlay-end o)) clist)
22064 (push (list :latex-preview
22065 (overlay-start o) (overlay-end o)) clist))
22066 ((org-inside-LaTeX-fragment-p)
22067 ;; FIXME: positions wrong.
22068 (push (list :latex-fragment (point) (point)) clist)))
22070 (setq clist (nreverse (delq nil clist)))
22071 clist))
22073 (defun org-in-regexp (regexp &optional nlines visually)
22074 "Check if point is inside a match of REGEXP.
22076 Normally only the current line is checked, but you can include
22077 NLINES extra lines around point into the search. If VISUALLY is
22078 set, require that the cursor is not after the match but really
22079 on, so that the block visually is on the match.
22081 Return nil or a cons cell (BEG . END) where BEG and END are,
22082 respectively, the positions at the beginning and the end of the
22083 match."
22084 (catch :exit
22085 (let ((pos (point))
22086 (eol (line-end-position (if nlines (1+ nlines) 1))))
22087 (save-excursion
22088 (beginning-of-line (- 1 (or nlines 0)))
22089 (while (and (re-search-forward regexp eol t)
22090 (<= (match-beginning 0) pos))
22091 (let ((end (match-end 0)))
22092 (when (or (> end pos) (and (= end pos) (not visually)))
22093 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22095 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22096 "Non-nil when point is between matches of START-RE and END-RE.
22098 Also return a non-nil value when point is on one of the matches.
22100 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22101 buffer positions. Default values are the positions of headlines
22102 surrounding the point.
22104 The functions returns a cons cell whose car (resp. cdr) is the
22105 position before START-RE (resp. after END-RE)."
22106 (save-match-data
22107 (let ((pos (point))
22108 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22109 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22110 beg end)
22111 (save-excursion
22112 ;; Point is on a block when on START-RE or if START-RE can be
22113 ;; found before it...
22114 (and (or (org-in-regexp start-re)
22115 (re-search-backward start-re limit-up t))
22116 (setq beg (match-beginning 0))
22117 ;; ... and END-RE after it...
22118 (goto-char (match-end 0))
22119 (re-search-forward end-re limit-down t)
22120 (> (setq end (match-end 0)) pos)
22121 ;; ... without another START-RE in-between.
22122 (goto-char (match-beginning 0))
22123 (not (re-search-backward start-re (1+ beg) t))
22124 ;; Return value.
22125 (cons beg end))))))
22127 (defun org-in-block-p (names)
22128 "Non-nil when point belongs to a block whose name belongs to NAMES.
22130 NAMES is a list of strings containing names of blocks.
22132 Return first block name matched, or nil. Beware that in case of
22133 nested blocks, the returned name may not belong to the closest
22134 block from point."
22135 (save-match-data
22136 (catch 'exit
22137 (let ((case-fold-search t)
22138 (lim-up (save-excursion (outline-previous-heading)))
22139 (lim-down (save-excursion (outline-next-heading))))
22140 (dolist (name names)
22141 (let ((n (regexp-quote name)))
22142 (when (org-between-regexps-p
22143 (concat "^[ \t]*#\\+begin_" n)
22144 (concat "^[ \t]*#\\+end_" n)
22145 lim-up lim-down)
22146 (throw 'exit n)))))
22147 nil)))
22149 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22150 "Call `multi-occur' with buffers for all agenda files."
22151 (interactive "sOrg-files matching: ")
22152 (let* ((files (org-agenda-files))
22153 (tnames (mapcar #'file-truename files))
22154 (extra org-agenda-text-search-extra-files))
22155 (when (eq (car extra) 'agenda-archives)
22156 (setq extra (cdr extra))
22157 (setq files (org-add-archive-files files)))
22158 (dolist (f extra)
22159 (unless (member (file-truename f) tnames)
22160 (unless (member f files) (setq files (append files (list f))))
22161 (setq tnames (append tnames (list (file-truename f))))))
22162 (multi-occur
22163 (mapcar (lambda (x)
22164 (with-current-buffer
22165 ;; FIXME: Why not just (find-file-noselect x)?
22166 ;; Is it to avoid the "revert buffer" prompt?
22167 (or (get-file-buffer x) (find-file-noselect x))
22168 (widen)
22169 (current-buffer)))
22170 files)
22171 regexp)))
22173 (add-hook 'occur-mode-find-occurrence-hook
22174 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22176 (defun org-occur-link-in-agenda-files ()
22177 "Create a link and search for it in the agendas.
22178 The link is not stored in `org-stored-links', it is just created
22179 for the search purpose."
22180 (interactive)
22181 (let ((link (condition-case nil
22182 (org-store-link nil)
22183 (error "Unable to create a link to here"))))
22184 (org-occur-in-agenda-files (regexp-quote link))))
22186 (defun org-reverse-string (string)
22187 "Return the reverse of STRING."
22188 (apply 'string (reverse (string-to-list string))))
22190 ;; defsubst org-uniquify must be defined before first use
22192 (defun org-uniquify-alist (alist)
22193 "Merge elements of ALIST with the same key.
22195 For example, in this alist:
22197 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22198 => \\='((a 1 3) (b 2))
22200 merge (a 1) and (a 3) into (a 1 3).
22202 The function returns the new ALIST."
22203 (let (rtn)
22204 (dolist (e alist rtn)
22205 (let (n)
22206 (if (not (assoc (car e) rtn))
22207 (push e rtn)
22208 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22209 (setq rtn (assq-delete-all (car e) rtn))
22210 (push n rtn))))))
22212 (defun org-delete-all (elts list)
22213 "Remove all elements in ELTS from LIST.
22214 Comparison is done with `equal'. It is a destructive operation
22215 that may remove elements by altering the list structure."
22216 (while elts
22217 (setq list (delete (pop elts) list)))
22218 list)
22220 (defun org-back-over-empty-lines ()
22221 "Move backwards over whitespace, to the beginning of the first empty line.
22222 Returns the number of empty lines passed."
22223 (let ((pos (point)))
22224 (if (cdr (assq 'heading org-blank-before-new-entry))
22225 (skip-chars-backward " \t\n\r")
22226 (unless (eobp)
22227 (forward-line -1)))
22228 (beginning-of-line 2)
22229 (goto-char (min (point) pos))
22230 (count-lines (point) pos)))
22232 (defun org-skip-whitespace ()
22233 (skip-chars-forward " \t\n\r"))
22235 (defun org-point-in-group (point group &optional context)
22236 "Check if POINT is in match-group GROUP.
22237 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22238 match. If the match group does not exist or point is not inside it,
22239 return nil."
22240 (and (match-beginning group)
22241 (>= point (match-beginning group))
22242 (<= point (match-end group))
22243 (if context
22244 (list context (match-beginning group) (match-end group))
22245 t)))
22247 (defun org-switch-to-buffer-other-window (&rest args)
22248 "Switch to buffer in a second window on the current frame.
22249 In particular, do not allow pop-up frames.
22250 Returns the newly created buffer."
22251 (org-no-popups
22252 (apply 'switch-to-buffer-other-window args)))
22254 (defun org-combine-plists (&rest plists)
22255 "Create a single property list from all plists in PLISTS.
22256 The process starts by copying the first list, and then setting properties
22257 from the other lists. Settings in the last list are the most significant
22258 ones and overrule settings in the other lists."
22259 (let ((rtn (copy-sequence (pop plists)))
22260 p v ls)
22261 (while plists
22262 (setq ls (pop plists))
22263 (while ls
22264 (setq p (pop ls) v (pop ls))
22265 (setq rtn (plist-put rtn p v))))
22266 rtn))
22268 (defun org-replace-escapes (string table)
22269 "Replace %-escapes in STRING with values in TABLE.
22270 TABLE is an association list with keys like \"%a\" and string values.
22271 The sequences in STRING may contain normal field width and padding information,
22272 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22273 so values can contain further %-escapes if they are define later in TABLE."
22274 (let ((tbl (copy-alist table))
22275 (case-fold-search nil)
22276 (pchg 0)
22277 re rpl)
22278 (dolist (e tbl)
22279 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22280 (when (and (cdr e) (string-match re (cdr e)))
22281 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22282 (safe "SREF"))
22283 (add-text-properties 0 3 (list 'sref sref) safe)
22284 (setcdr e (replace-match safe t t (cdr e)))))
22285 (while (string-match re string)
22286 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22287 (cdr e)))
22288 (setq string (replace-match rpl t t string))))
22289 (while (setq pchg (next-property-change pchg string))
22290 (let ((sref (get-text-property pchg 'sref string)))
22291 (when (and sref (string-match "SREF" string pchg))
22292 (setq string (replace-match sref t t string)))))
22293 string))
22295 (defun org-find-base-buffer-visiting (file)
22296 "Like `find-buffer-visiting' but always return the base buffer and
22297 not an indirect buffer."
22298 (let ((buf (or (get-file-buffer file)
22299 (find-buffer-visiting file))))
22300 (if buf
22301 (or (buffer-base-buffer buf) buf)
22302 nil)))
22304 ;;; TODO: Only called once, from ox-odt which should probably use
22305 ;;; org-export-inline-image-p or something.
22306 (defun org-file-image-p (file)
22307 "Return non-nil if FILE is an image."
22308 (save-match-data
22309 (string-match (image-file-name-regexp) file)))
22311 (defun org-get-cursor-date (&optional with-time)
22312 "Return the date at cursor in as a time.
22313 This works in the calendar and in the agenda, anywhere else it just
22314 returns the current time.
22315 If WITH-TIME is non-nil, returns the time of the event at point (in
22316 the agenda) or the current time of the day."
22317 (let (date day defd tp hod mod)
22318 (when with-time
22319 (setq tp (get-text-property (point) 'time))
22320 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22321 (setq hod (string-to-number (match-string 1 tp))
22322 mod (string-to-number (match-string 2 tp))))
22323 (or tp (let ((now (decode-time)))
22324 (setq hod (nth 2 now)
22325 mod (nth 1 now)))))
22326 (cond
22327 ((eq major-mode 'calendar-mode)
22328 (setq date (calendar-cursor-to-date)
22329 defd (encode-time 0 (or mod 0) (or hod 0)
22330 (nth 1 date) (nth 0 date) (nth 2 date))))
22331 ((eq major-mode 'org-agenda-mode)
22332 (setq day (get-text-property (point) 'day))
22333 (when day
22334 (setq date (calendar-gregorian-from-absolute day)
22335 defd (encode-time 0 (or mod 0) (or hod 0)
22336 (nth 1 date) (nth 0 date) (nth 2 date))))))
22337 (or defd (current-time))))
22339 (defun org-mark-subtree (&optional up)
22340 "Mark the current subtree.
22341 This puts point at the start of the current subtree, and mark at
22342 the end. If a numeric prefix UP is given, move up into the
22343 hierarchy of headlines by UP levels before marking the subtree."
22344 (interactive "P")
22345 (org-with-limited-levels
22346 (cond ((org-at-heading-p) (beginning-of-line))
22347 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22348 (t (outline-previous-visible-heading 1))))
22349 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22350 (if (called-interactively-p 'any)
22351 (call-interactively 'org-mark-element)
22352 (org-mark-element)))
22354 (defun org-file-newer-than-p (file time)
22355 "Non-nil if FILE is newer than TIME.
22356 FILE is a filename, as a string, TIME is a list of integers, as
22357 returned by, e.g., `current-time'."
22358 (and (file-exists-p file)
22359 ;; Only compare times up to whole seconds as some file-systems
22360 ;; (e.g. HFS+) do not retain any finer granularity. As
22361 ;; a consequence, make sure we return non-nil when the two
22362 ;; times are equal.
22363 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22364 (cl-subseq time 0 2)))))
22366 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22367 "Compile a SOURCE file using PROCESS.
22369 PROCESS is either a function or a list of shell commands, as
22370 strings. EXT is a file extension, without the leading dot, as
22371 a string. It is used to check if the process actually succeeded.
22373 PROCESS must create a file with the same base name and directory
22374 as SOURCE, but ending with EXT. The function then returns its
22375 filename. Otherwise, it raises an error. The error message can
22376 then be refined by providing string ERR-MSG, which is appended to
22377 the standard message.
22379 If PROCESS is a function, it is called with a single argument:
22380 the SOURCE file.
22382 If it is a list of commands, each of them is called using
22383 `shell-command'. By default, in each command, %b, %f, %F, %o and
22384 %O are replaced with, respectively, SOURCE base name, name, full
22385 name, directory and absolute output file name. It is possible,
22386 however, to use more place-holders by specifying them in optional
22387 argument SPEC, as an alist following the pattern
22389 (CHARACTER . REPLACEMENT-STRING).
22391 When PROCESS is a list of commands, optional argument LOG-BUF can
22392 be set to a buffer or a buffer name. `shell-command' then uses
22393 it for output."
22394 (let* ((base-name (file-name-base source))
22395 (full-name (file-truename source))
22396 (out-dir (or (file-name-directory source) "./"))
22397 (output (expand-file-name (concat base-name "." ext) out-dir))
22398 (time (current-time))
22399 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22400 (save-window-excursion
22401 (pcase process
22402 ((pred functionp) (funcall process (shell-quote-argument source)))
22403 ((pred consp)
22404 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22405 (spec (append spec
22406 `((?b . ,(shell-quote-argument base-name))
22407 (?f . ,(shell-quote-argument source))
22408 (?F . ,(shell-quote-argument full-name))
22409 (?o . ,(shell-quote-argument out-dir))
22410 (?O . ,(shell-quote-argument output))))))
22411 (dolist (command process)
22412 (shell-command (format-spec command spec) log-buf))
22413 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22414 (_ (error "No valid command to process %S%s" source err-msg))))
22415 ;; Check for process failure. Output file is expected to be
22416 ;; located in the same directory as SOURCE.
22417 (unless (org-file-newer-than-p output time)
22418 (error (format "File %S wasn't produced%s" output err-msg)))
22419 output))
22421 ;;; Indentation
22423 (defvar org-element-greater-elements)
22424 (defun org--get-expected-indentation (element contentsp)
22425 "Expected indentation column for current line, according to ELEMENT.
22426 ELEMENT is an element containing point. CONTENTSP is non-nil
22427 when indentation is to be computed according to contents of
22428 ELEMENT."
22429 (let ((type (org-element-type element))
22430 (start (org-element-property :begin element))
22431 (post-affiliated (org-element-property :post-affiliated element)))
22432 (org-with-wide-buffer
22433 (cond
22434 (contentsp
22435 (cl-case type
22436 ((diary-sexp footnote-definition) 0)
22437 ((headline inlinetask nil)
22438 (if (not org-adapt-indentation) 0
22439 (let ((level (org-current-level)))
22440 (if level (1+ level) 0))))
22441 ((item plain-list) (org-list-item-body-column post-affiliated))
22443 (goto-char start)
22444 (org-get-indentation))))
22445 ((memq type '(headline inlinetask nil))
22446 (if (org-match-line "[ \t]*$")
22447 (org--get-expected-indentation element t)
22449 ((memq type '(diary-sexp footnote-definition)) 0)
22450 ;; First paragraph of a footnote definition or an item.
22451 ;; Indent like parent.
22452 ((< (line-beginning-position) start)
22453 (org--get-expected-indentation
22454 (org-element-property :parent element) t))
22455 ;; At first line: indent according to previous sibling, if any,
22456 ;; ignoring footnote definitions and inline tasks, or parent's
22457 ;; contents.
22458 ((= (line-beginning-position) start)
22459 (catch 'exit
22460 (while t
22461 (if (= (point-min) start) (throw 'exit 0)
22462 (goto-char (1- start))
22463 (let* ((previous (org-element-at-point))
22464 (parent previous))
22465 (while (and parent (<= (org-element-property :end parent) start))
22466 (setq previous parent
22467 parent (org-element-property :parent parent)))
22468 (cond
22469 ((not previous) (throw 'exit 0))
22470 ((> (org-element-property :end previous) start)
22471 (throw 'exit (org--get-expected-indentation previous t)))
22472 ((memq (org-element-type previous)
22473 '(footnote-definition inlinetask))
22474 (setq start (org-element-property :begin previous)))
22475 (t (goto-char (org-element-property :begin previous))
22476 (throw 'exit
22477 (if (bolp) (org-get-indentation)
22478 ;; At first paragraph in an item or
22479 ;; a footnote definition.
22480 (org--get-expected-indentation
22481 (org-element-property :parent previous) t))))))))))
22482 ;; Otherwise, move to the first non-blank line above.
22484 (beginning-of-line)
22485 (let ((pos (point)))
22486 (skip-chars-backward " \r\t\n")
22487 (cond
22488 ;; Two blank lines end a footnote definition or a plain
22489 ;; list. When we indent an empty line after them, the
22490 ;; containing list or footnote definition is over, so it
22491 ;; qualifies as a previous sibling. Therefore, we indent
22492 ;; like its first line.
22493 ((and (memq type '(footnote-definition plain-list))
22494 (> (count-lines (point) pos) 2))
22495 (goto-char start)
22496 (org-get-indentation))
22497 ;; Line above is the first one of a paragraph at the
22498 ;; beginning of an item or a footnote definition. Indent
22499 ;; like parent.
22500 ((< (line-beginning-position) start)
22501 (org--get-expected-indentation
22502 (org-element-property :parent element) t))
22503 ;; Line above is the beginning of an element, i.e., point
22504 ;; was originally on the blank lines between element's start
22505 ;; and contents.
22506 ((= (line-beginning-position) post-affiliated)
22507 (org--get-expected-indentation element t))
22508 ;; POS is after contents in a greater element. Indent like
22509 ;; the beginning of the element.
22510 ((and (memq type org-element-greater-elements)
22511 (let ((cend (org-element-property :contents-end element)))
22512 (and cend (<= cend pos))))
22513 ;; As a special case, if point is at the end of a footnote
22514 ;; definition or an item, indent like the very last element
22515 ;; within. If that last element is an item, indent like
22516 ;; its contents.
22517 (if (memq type '(footnote-definition item plain-list))
22518 (let ((last (org-element-at-point)))
22519 (goto-char pos)
22520 (org--get-expected-indentation
22521 last (eq (org-element-type last) 'item)))
22522 (goto-char start)
22523 (org-get-indentation)))
22524 ;; In any other case, indent like the current line.
22525 (t (org-get-indentation)))))))))
22527 (defun org--align-node-property ()
22528 "Align node property at point.
22529 Alignment is done according to `org-property-format', which see."
22530 (when (save-excursion
22531 (beginning-of-line)
22532 (looking-at org-property-re))
22533 (replace-match
22534 (concat (match-string 4)
22535 (org-trim
22536 (format org-property-format (match-string 1) (match-string 3))))
22537 t t)))
22539 (defun org-indent-line ()
22540 "Indent line depending on context.
22542 Indentation is done according to the following rules:
22544 - Footnote definitions, diary sexps, headlines and inline tasks
22545 have to start at column 0.
22547 - On the very first line of an element, consider, in order, the
22548 next rules until one matches:
22550 1. If there's a sibling element before, ignoring footnote
22551 definitions and inline tasks, indent like its first line.
22553 2. If element has a parent, indent like its contents. More
22554 precisely, if parent is an item, indent after the
22555 description part, if any, or the bullet (see
22556 `org-list-description-max-indent'). Else, indent like
22557 parent's first line.
22559 3. Otherwise, indent relatively to current level, if
22560 `org-adapt-indentation' is non-nil, or to left margin.
22562 - On a blank line at the end of an element, indent according to
22563 the type of the element. More precisely
22565 1. If element is a plain list, an item, or a footnote
22566 definition, indent like the very last element within.
22568 2. If element is a paragraph, indent like its last non blank
22569 line.
22571 3. Otherwise, indent like its very first line.
22573 - In the code part of a source block, use language major mode
22574 to indent current line if `org-src-tab-acts-natively' is
22575 non-nil. If it is nil, do nothing.
22577 - Otherwise, indent like the first non-blank line above.
22579 The function doesn't indent an item as it could break the whole
22580 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22581 `\\[org-shiftmetaright]'.
22583 Also align node properties according to `org-property-format'."
22584 (interactive)
22585 (cond
22586 (orgstruct-is-++
22587 (let ((indent-line-function
22588 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22589 (indent-according-to-mode)))
22590 ((org-at-heading-p) 'noindent)
22592 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22593 (type (org-element-type element)))
22594 (cond ((and (memq type '(plain-list item))
22595 (= (line-beginning-position)
22596 (org-element-property :post-affiliated element)))
22597 'noindent)
22598 ((and (eq type 'latex-environment)
22599 (>= (point) (org-element-property :post-affiliated element))
22600 (< (point) (org-with-wide-buffer
22601 (goto-char (org-element-property :end element))
22602 (skip-chars-backward " \r\t\n")
22603 (line-beginning-position 2))))
22604 'noindent)
22605 ((and (eq type 'src-block)
22606 org-src-tab-acts-natively
22607 (> (line-beginning-position)
22608 (org-element-property :post-affiliated element))
22609 (< (line-beginning-position)
22610 (org-with-wide-buffer
22611 (goto-char (org-element-property :end element))
22612 (skip-chars-backward " \r\t\n")
22613 (line-beginning-position))))
22614 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22616 (let ((column (org--get-expected-indentation element nil)))
22617 ;; Preserve current column.
22618 (if (<= (current-column) (current-indentation))
22619 (indent-line-to column)
22620 (save-excursion (indent-line-to column))))
22621 ;; Align node property. Also preserve current column.
22622 (when (eq type 'node-property)
22623 (let ((column (current-column)))
22624 (org--align-node-property)
22625 (org-move-to-column column)))))))))
22627 (defun org-indent-region (start end)
22628 "Indent each non-blank line in the region.
22629 Called from a program, START and END specify the region to
22630 indent. The function will not indent contents of example blocks,
22631 verse blocks and export blocks as leading white spaces are
22632 assumed to be significant there."
22633 (interactive "r")
22634 (save-excursion
22635 (goto-char start)
22636 (skip-chars-forward " \r\t\n")
22637 (unless (eobp) (beginning-of-line))
22638 (let ((indent-to
22639 (lambda (ind pos)
22640 ;; Set IND as indentation for all lines between point and
22641 ;; POS. Blank lines are ignored. Leave point after POS
22642 ;; once done.
22643 (let ((limit (copy-marker pos)))
22644 (while (< (point) limit)
22645 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22646 (forward-line))
22647 (set-marker limit nil))))
22648 (end (copy-marker end)))
22649 (while (< (point) end)
22650 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22651 (let* ((element (org-element-at-point))
22652 (type (org-element-type element))
22653 (element-end (copy-marker (org-element-property :end element)))
22654 (ind (org--get-expected-indentation element nil)))
22655 (cond
22656 ;; Element indented as a single block. Example blocks
22657 ;; preserving indentation are a special case since the
22658 ;; "contents" must not be indented whereas the block
22659 ;; boundaries can.
22660 ((or (memq type '(export-block latex-environment))
22661 (and (eq type 'example-block)
22662 (not
22663 (or org-src-preserve-indentation
22664 (org-element-property :preserve-indent element)))))
22665 (let ((offset (- ind (org-get-indentation))))
22666 (unless (zerop offset)
22667 (indent-rigidly (org-element-property :begin element)
22668 (org-element-property :end element)
22669 offset)))
22670 (goto-char element-end))
22671 ;; Elements indented line wise. Be sure to exclude
22672 ;; example blocks (preserving indentation) and source
22673 ;; blocks from this category as they are treated
22674 ;; specially later.
22675 ((or (memq type '(paragraph table table-row))
22676 (not (or (org-element-property :contents-begin element)
22677 (memq type '(example-block src-block)))))
22678 (when (eq type 'node-property)
22679 (org--align-node-property)
22680 (beginning-of-line))
22681 (funcall indent-to ind (min element-end end)))
22682 ;; Elements consisting of three parts: before the
22683 ;; contents, the contents, and after the contents. The
22684 ;; contents are treated specially, according to the
22685 ;; element type, or not indented at all. Other parts are
22686 ;; indented as a single block.
22688 (let* ((post (copy-marker
22689 (org-element-property :post-affiliated element)))
22690 (cbeg
22691 (copy-marker
22692 (cond
22693 ((not (org-element-property :contents-begin element))
22694 ;; Fake contents for source blocks.
22695 (org-with-wide-buffer
22696 (goto-char post)
22697 (line-beginning-position 2)))
22698 ((memq type '(footnote-definition item plain-list))
22699 ;; Contents in these elements could start on
22700 ;; the same line as the beginning of the
22701 ;; element. Make sure we start indenting
22702 ;; from the second line.
22703 (org-with-wide-buffer
22704 (goto-char post)
22705 (end-of-line)
22706 (skip-chars-forward " \r\t\n")
22707 (if (eobp) (point) (line-beginning-position))))
22708 (t (org-element-property :contents-begin element)))))
22709 (cend (copy-marker
22710 (or (org-element-property :contents-end element)
22711 ;; Fake contents for source blocks.
22712 (org-with-wide-buffer
22713 (goto-char element-end)
22714 (skip-chars-backward " \r\t\n")
22715 (line-beginning-position)))
22716 t)))
22717 ;; Do not change items indentation individually as it
22718 ;; might break the list as a whole. On the other
22719 ;; hand, when at a plain list, indent it as a whole.
22720 (cond ((eq type 'plain-list)
22721 (let ((offset (- ind (org-get-indentation))))
22722 (unless (zerop offset)
22723 (indent-rigidly (org-element-property :begin element)
22724 (org-element-property :end element)
22725 offset))
22726 (goto-char cbeg)))
22727 ((eq type 'item) (goto-char cbeg))
22728 (t (funcall indent-to ind (min cbeg end))))
22729 (when (< (point) end)
22730 (cl-case type
22731 ((example-block verse-block))
22732 (src-block
22733 ;; In a source block, indent source code
22734 ;; according to language major mode, but only if
22735 ;; `org-src-tab-acts-natively' is non-nil.
22736 (when (and (< (point) end) org-src-tab-acts-natively)
22737 (ignore-errors
22738 (org-babel-do-in-edit-buffer
22739 (indent-region (point-min) (point-max))))))
22740 (t (org-indent-region (point) (min cend end))))
22741 (goto-char (min cend end))
22742 (when (< (point) end)
22743 (funcall indent-to ind (min element-end end))))
22744 (set-marker post nil)
22745 (set-marker cbeg nil)
22746 (set-marker cend nil))))
22747 (set-marker element-end nil))))
22748 (set-marker end nil))))
22750 (defun org-indent-drawer ()
22751 "Indent the drawer at point."
22752 (interactive)
22753 (unless (save-excursion
22754 (beginning-of-line)
22755 (looking-at-p org-drawer-regexp))
22756 (user-error "Not at a drawer"))
22757 (let ((element (org-element-at-point)))
22758 (unless (memq (org-element-type element) '(drawer property-drawer))
22759 (user-error "Not at a drawer"))
22760 (org-with-wide-buffer
22761 (org-indent-region (org-element-property :begin element)
22762 (org-element-property :end element))))
22763 (message "Drawer at point indented"))
22765 (defun org-indent-block ()
22766 "Indent the block at point."
22767 (interactive)
22768 (unless (save-excursion
22769 (beginning-of-line)
22770 (let ((case-fold-search t))
22771 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22772 (user-error "Not at a block"))
22773 (let ((element (org-element-at-point)))
22774 (unless (memq (org-element-type element)
22775 '(comment-block center-block dynamic-block example-block
22776 export-block quote-block special-block
22777 src-block verse-block))
22778 (user-error "Not at a block"))
22779 (org-with-wide-buffer
22780 (org-indent-region (org-element-property :begin element)
22781 (org-element-property :end element))))
22782 (message "Block at point indented"))
22785 ;;; Filling
22787 ;; We use our own fill-paragraph and auto-fill functions.
22789 ;; `org-fill-paragraph' relies on adaptive filling and context
22790 ;; checking. Appropriate `fill-prefix' is computed with
22791 ;; `org-adaptive-fill-function'.
22793 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22794 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22795 ;; `org-adaptive-fill-function' value. Internally,
22796 ;; `org-comment-line-break-function' breaks the line.
22798 ;; `org-setup-filling' installs filling and auto-filling related
22799 ;; variables during `org-mode' initialization.
22801 (defvar org-element-paragraph-separate) ; org-element.el
22802 (defun org-setup-filling ()
22803 (require 'org-element)
22804 ;; Prevent auto-fill from inserting unwanted new items.
22805 (when (boundp 'fill-nobreak-predicate)
22806 (setq-local
22807 fill-nobreak-predicate
22808 (org-uniquify
22809 (append fill-nobreak-predicate
22810 '(org-fill-line-break-nobreak-p
22811 org-fill-n-macro-as-item-nobreak-p
22812 org-fill-paragraph-with-timestamp-nobreak-p)))))
22813 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22814 (setq-local paragraph-start paragraph-ending)
22815 (setq-local paragraph-separate paragraph-ending))
22816 (setq-local fill-paragraph-function 'org-fill-paragraph)
22817 (setq-local auto-fill-inhibit-regexp nil)
22818 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22819 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22820 (setq-local comment-line-break-function 'org-comment-line-break-function))
22822 (defun org-fill-line-break-nobreak-p ()
22823 "Non-nil when a new line at point would create an Org line break."
22824 (save-excursion
22825 (skip-chars-backward "[ \t]")
22826 (skip-chars-backward "\\\\")
22827 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22829 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22830 "Non-nil when a new line at point would split a timestamp."
22831 (and (org-at-timestamp-p 'lax)
22832 (not (looking-at org-ts-regexp-both))))
22834 (defun org-fill-n-macro-as-item-nobreak-p ()
22835 "Non-nil when a new line at point would create a new list."
22836 ;; During export, a "n" macro followed by a dot or a closing
22837 ;; parenthesis can end up being parsed as a new list item.
22838 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22840 (declare-function message-in-body-p "message" ())
22841 (defvar orgtbl-line-start-regexp) ; From org-table.el
22842 (defun org-adaptive-fill-function ()
22843 "Compute a fill prefix for the current line.
22844 Return fill prefix, as a string, or nil if current line isn't
22845 meant to be filled. For convenience, if `adaptive-fill-regexp'
22846 matches in paragraphs or comments, use it."
22847 (catch 'exit
22848 (when (derived-mode-p 'message-mode)
22849 (save-excursion
22850 (beginning-of-line)
22851 (cond ((not (message-in-body-p)) (throw 'exit nil))
22852 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22853 ((looking-at message-cite-prefix-regexp)
22854 (throw 'exit (match-string-no-properties 0)))
22855 ((looking-at org-outline-regexp)
22856 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22857 (org-with-wide-buffer
22858 (unless (org-at-heading-p)
22859 (let* ((p (line-beginning-position))
22860 (element (save-excursion
22861 (beginning-of-line)
22862 (org-element-at-point)))
22863 (type (org-element-type element))
22864 (post-affiliated (org-element-property :post-affiliated element)))
22865 (unless (< p post-affiliated)
22866 (cl-case type
22867 (comment
22868 (save-excursion
22869 (beginning-of-line)
22870 (looking-at "[ \t]*")
22871 (concat (match-string 0) "# ")))
22872 (footnote-definition "")
22873 ((item plain-list)
22874 (make-string (org-list-item-body-column post-affiliated) ?\s))
22875 (paragraph
22876 ;; Fill prefix is usually the same as the current line,
22877 ;; unless the paragraph is at the beginning of an item.
22878 (let ((parent (org-element-property :parent element)))
22879 (save-excursion
22880 (beginning-of-line)
22881 (cond ((eq (org-element-type parent) 'item)
22882 (make-string (org-list-item-body-column
22883 (org-element-property :begin parent))
22884 ?\s))
22885 ((and adaptive-fill-regexp
22886 ;; Locally disable
22887 ;; `adaptive-fill-function' to let
22888 ;; `fill-context-prefix' handle
22889 ;; `adaptive-fill-regexp' variable.
22890 (let (adaptive-fill-function)
22891 (fill-context-prefix
22892 post-affiliated
22893 (org-element-property :end element)))))
22894 ((looking-at "[ \t]+") (match-string 0))
22895 (t "")))))
22896 (comment-block
22897 ;; Only fill contents if P is within block boundaries.
22898 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22899 (forward-line)
22900 (point)))
22901 (cend (save-excursion
22902 (goto-char (org-element-property :end element))
22903 (skip-chars-backward " \r\t\n")
22904 (line-beginning-position))))
22905 (when (and (>= p cbeg) (< p cend))
22906 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22907 (match-string 0)
22908 "")))))))))))
22910 (declare-function message-goto-body "message" ())
22911 (defvar message-cite-prefix-regexp) ; From message.el
22913 (defun org-fill-element (&optional justify)
22914 "Fill element at point, when applicable.
22916 This function only applies to comment blocks, comments, example
22917 blocks and paragraphs. Also, as a special case, re-align table
22918 when point is at one.
22920 If JUSTIFY is non-nil (interactively, with prefix argument),
22921 justify as well. If `sentence-end-double-space' is non-nil, then
22922 period followed by one space does not end a sentence, so don't
22923 break a line there. The variable `fill-column' controls the
22924 width for filling.
22926 For convenience, when point is at a plain list, an item or
22927 a footnote definition, try to fill the first paragraph within."
22928 (with-syntax-table org-mode-transpose-word-syntax-table
22929 ;; Move to end of line in order to get the first paragraph within
22930 ;; a plain list or a footnote definition.
22931 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22932 ;; First check if point is in a blank line at the beginning of
22933 ;; the buffer. In that case, ignore filling.
22934 (cl-case (org-element-type element)
22935 ;; Use major mode filling function is src blocks.
22936 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22937 ;; Align Org tables, leave table.el tables as-is.
22938 (table-row (org-table-align) t)
22939 (table
22940 (when (eq (org-element-property :type element) 'org)
22941 (save-excursion
22942 (goto-char (org-element-property :post-affiliated element))
22943 (org-table-align)))
22945 (paragraph
22946 ;; Paragraphs may contain `line-break' type objects.
22947 (let ((beg (max (point-min)
22948 (org-element-property :contents-begin element)))
22949 (end (min (point-max)
22950 (org-element-property :contents-end element))))
22951 ;; Do nothing if point is at an affiliated keyword.
22952 (if (< (line-end-position) beg) t
22953 (when (derived-mode-p 'message-mode)
22954 ;; In `message-mode', do not fill following citation
22955 ;; in current paragraph nor text before message body.
22956 (let ((body-start (save-excursion (message-goto-body))))
22957 (when body-start (setq beg (max body-start beg))))
22958 (when (save-excursion
22959 (re-search-forward
22960 (concat "^" message-cite-prefix-regexp) end t))
22961 (setq end (match-beginning 0))))
22962 ;; Fill paragraph, taking line breaks into account.
22963 (save-excursion
22964 (goto-char beg)
22965 (let ((cuts (list beg)))
22966 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22967 (when (eq 'line-break
22968 (org-element-type
22969 (save-excursion (backward-char)
22970 (org-element-context))))
22971 (push (point) cuts)))
22972 (dolist (c (delq end cuts))
22973 (fill-region-as-paragraph c end justify)
22974 (setq end c))))
22975 t)))
22976 ;; Contents of `comment-block' type elements should be
22977 ;; filled as plain text, but only if point is within block
22978 ;; markers.
22979 (comment-block
22980 (let* ((case-fold-search t)
22981 (beg (save-excursion
22982 (goto-char (org-element-property :begin element))
22983 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22984 (forward-line)
22985 (point)))
22986 (end (save-excursion
22987 (goto-char (org-element-property :end element))
22988 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22989 (line-beginning-position))))
22990 (if (or (< (point) beg) (> (point) end)) t
22991 (fill-region-as-paragraph
22992 (save-excursion (end-of-line)
22993 (re-search-backward "^[ \t]*$" beg 'move)
22994 (line-beginning-position))
22995 (save-excursion (beginning-of-line)
22996 (re-search-forward "^[ \t]*$" end 'move)
22997 (line-beginning-position))
22998 justify))))
22999 ;; Fill comments.
23000 (comment
23001 (let ((begin (org-element-property :post-affiliated element))
23002 (end (org-element-property :end element)))
23003 (when (and (>= (point) begin) (<= (point) end))
23004 (let ((begin (save-excursion
23005 (end-of-line)
23006 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23007 (progn (forward-line) (point))
23008 begin)))
23009 (end (save-excursion
23010 (end-of-line)
23011 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23012 (1- (line-beginning-position))
23013 (skip-chars-backward " \r\t\n")
23014 (line-end-position)))))
23015 ;; Do not fill comments when at a blank line.
23016 (when (> end begin)
23017 (let ((fill-prefix
23018 (save-excursion
23019 (beginning-of-line)
23020 (looking-at "[ \t]*#")
23021 (let ((comment-prefix (match-string 0)))
23022 (goto-char (match-end 0))
23023 (if (looking-at adaptive-fill-regexp)
23024 (concat comment-prefix (match-string 0))
23025 (concat comment-prefix " "))))))
23026 (save-excursion
23027 (fill-region-as-paragraph begin end justify))))))
23029 ;; Ignore every other element.
23030 (otherwise t)))))
23032 (defun org-fill-paragraph (&optional justify region)
23033 "Fill element at point, when applicable.
23035 This function only applies to comment blocks, comments, example
23036 blocks and paragraphs. Also, as a special case, re-align table
23037 when point is at one.
23039 For convenience, when point is at a plain list, an item or
23040 a footnote definition, try to fill the first paragraph within.
23042 If JUSTIFY is non-nil (interactively, with prefix argument),
23043 justify as well. If `sentence-end-double-space' is non-nil, then
23044 period followed by one space does not end a sentence, so don't
23045 break a line there. The variable `fill-column' controls the
23046 width for filling.
23048 The REGION argument is non-nil if called interactively; in that
23049 case, if Transient Mark mode is enabled and the mark is active,
23050 fill each of the elements in the active region, instead of just
23051 filling the current element."
23052 (interactive (progn
23053 (barf-if-buffer-read-only)
23054 (list (if current-prefix-arg 'full) t)))
23055 (cond
23056 ((and (derived-mode-p 'message-mode)
23057 (or (not (message-in-body-p))
23058 (save-excursion (move-beginning-of-line 1)
23059 (looking-at message-cite-prefix-regexp))))
23060 ;; First ensure filling is correct in message-mode.
23061 (let ((fill-paragraph-function
23062 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23063 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23064 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23065 (paragraph-separate
23066 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23067 (fill-paragraph nil)))
23068 ((and region transient-mark-mode mark-active
23069 (not (eq (region-beginning) (region-end))))
23070 (let ((origin (point-marker))
23071 (start (region-beginning)))
23072 (unwind-protect
23073 (progn
23074 (goto-char (region-end))
23075 (while (> (point) start)
23076 (org-backward-paragraph)
23077 (org-fill-element justify)))
23078 (goto-char origin)
23079 (set-marker origin nil))))
23080 (t (org-fill-element justify))))
23081 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23083 (defun org-auto-fill-function ()
23084 "Auto-fill function."
23085 ;; Check if auto-filling is meaningful.
23086 (let ((fc (current-fill-column)))
23087 (when (and fc (> (current-column) fc))
23088 (let* ((fill-prefix (org-adaptive-fill-function))
23089 ;; Enforce empty fill prefix, if required. Otherwise, it
23090 ;; will be computed again.
23091 (adaptive-fill-mode (not (equal fill-prefix ""))))
23092 (when fill-prefix (do-auto-fill))))))
23094 (defun org-comment-line-break-function (&optional soft)
23095 "Break line at point and indent, continuing comment if within one.
23096 The inserted newline is marked hard if variable
23097 `use-hard-newlines' is true, unless optional argument SOFT is
23098 non-nil."
23099 (if soft (insert-and-inherit ?\n) (newline 1))
23100 (save-excursion (forward-char -1) (delete-horizontal-space))
23101 (delete-horizontal-space)
23102 (indent-to-left-margin)
23103 (insert-before-markers-and-inherit fill-prefix))
23106 ;;; Fixed Width Areas
23108 (defun org-toggle-fixed-width ()
23109 "Toggle fixed-width markup.
23111 Add or remove fixed-width markup on current line, whenever it
23112 makes sense. Return an error otherwise.
23114 If a region is active and if it contains only fixed-width areas
23115 or blank lines, remove all fixed-width markup in it. If the
23116 region contains anything else, convert all non-fixed-width lines
23117 to fixed-width ones.
23119 Blank lines at the end of the region are ignored unless the
23120 region only contains such lines."
23121 (interactive)
23122 (if (not (org-region-active-p))
23123 ;; No region:
23125 ;; Remove fixed width marker only in a fixed-with element.
23127 ;; Add fixed width maker in paragraphs, in blank lines after
23128 ;; elements or at the beginning of a headline or an inlinetask,
23129 ;; and before any one-line elements (e.g., a clock).
23130 (progn
23131 (beginning-of-line)
23132 (let* ((element (org-element-at-point))
23133 (type (org-element-type element)))
23134 (cond
23135 ((and (eq type 'fixed-width)
23136 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23137 (replace-match
23138 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23139 ((and (memq type '(babel-call clock comment diary-sexp headline
23140 horizontal-rule keyword paragraph
23141 planning))
23142 (<= (org-element-property :post-affiliated element) (point)))
23143 (skip-chars-forward " \t")
23144 (insert ": "))
23145 ((and (looking-at-p "[ \t]*$")
23146 (or (eq type 'inlinetask)
23147 (save-excursion
23148 (skip-chars-forward " \r\t\n")
23149 (<= (org-element-property :end element) (point)))))
23150 (delete-region (point) (line-end-position))
23151 (org-indent-line)
23152 (insert ": "))
23153 (t (user-error "Cannot insert a fixed-width line here")))))
23154 ;; Region active.
23155 (let* ((begin (save-excursion
23156 (goto-char (region-beginning))
23157 (line-beginning-position)))
23158 (end (copy-marker
23159 (save-excursion
23160 (goto-char (region-end))
23161 (unless (eolp) (beginning-of-line))
23162 (if (save-excursion (re-search-backward "\\S-" begin t))
23163 (progn (skip-chars-backward " \r\t\n") (point))
23164 (point)))))
23165 (all-fixed-width-p
23166 (catch 'not-all-p
23167 (save-excursion
23168 (goto-char begin)
23169 (skip-chars-forward " \r\t\n")
23170 (when (eobp) (throw 'not-all-p nil))
23171 (while (< (point) end)
23172 (let ((element (org-element-at-point)))
23173 (if (eq (org-element-type element) 'fixed-width)
23174 (goto-char (org-element-property :end element))
23175 (throw 'not-all-p nil))))
23176 t))))
23177 (if all-fixed-width-p
23178 (save-excursion
23179 (goto-char begin)
23180 (while (< (point) end)
23181 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23182 (replace-match
23183 "" nil nil nil
23184 (if (= (line-end-position) (match-end 0)) 0 1)))
23185 (forward-line)))
23186 (let ((min-ind (point-max)))
23187 ;; Find minimum indentation across all lines.
23188 (save-excursion
23189 (goto-char begin)
23190 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23191 (setq min-ind 0)
23192 (catch 'zerop
23193 (while (< (point) end)
23194 (unless (looking-at-p "[ \t]*$")
23195 (let ((ind (org-get-indentation)))
23196 (setq min-ind (min min-ind ind))
23197 (when (zerop ind) (throw 'zerop t))))
23198 (forward-line)))))
23199 ;; Loop over all lines and add fixed-width markup everywhere
23200 ;; but in fixed-width lines.
23201 (save-excursion
23202 (goto-char begin)
23203 (while (< (point) end)
23204 (cond
23205 ((org-at-heading-p)
23206 (insert ": ")
23207 (forward-line)
23208 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23209 (insert ":")
23210 (forward-line)))
23211 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23212 (let* ((element (org-element-at-point))
23213 (element-end (org-element-property :end element)))
23214 (if (eq (org-element-type element) 'fixed-width)
23215 (progn (goto-char element-end)
23216 (skip-chars-backward " \r\t\n")
23217 (forward-line))
23218 (let ((limit (min end element-end)))
23219 (while (< (point) limit)
23220 (org-move-to-column min-ind t)
23221 (insert ": ")
23222 (forward-line))))))
23224 (org-move-to-column min-ind t)
23225 (insert ": ")
23226 (forward-line)))))))
23227 (set-marker end nil))))
23230 ;;; Comments
23232 ;; Org comments syntax is quite complex. It requires the entire line
23233 ;; to be just a comment. Also, even with the right syntax at the
23234 ;; beginning of line, some elements (e.g., verse-block or
23235 ;; example-block) don't accept comments. Usual Emacs comment commands
23236 ;; cannot cope with those requirements. Therefore, Org replaces them.
23238 ;; Org still relies on `comment-dwim', but cannot trust
23239 ;; `comment-only-p'. So, `comment-region-function' and
23240 ;; `uncomment-region-function' both point
23241 ;; to`org-comment-or-uncomment-region'. Eventually,
23242 ;; `org-insert-comment' takes care of insertion of comments at the
23243 ;; beginning of line.
23245 ;; `org-setup-comments-handling' install comments related variables
23246 ;; during `org-mode' initialization.
23248 (defun org-setup-comments-handling ()
23249 (interactive)
23250 (setq-local comment-use-syntax nil)
23251 (setq-local comment-start "# ")
23252 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23253 (setq-local comment-insert-comment-function 'org-insert-comment)
23254 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23255 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23257 (defun org-insert-comment ()
23258 "Insert an empty comment above current line.
23259 If the line is empty, insert comment at its beginning. When
23260 point is within a source block, comment according to the related
23261 major mode."
23262 (if (let ((element (org-element-at-point)))
23263 (and (eq (org-element-type element) 'src-block)
23264 (< (save-excursion
23265 (goto-char (org-element-property :post-affiliated element))
23266 (line-end-position))
23267 (point))
23268 (> (save-excursion
23269 (goto-char (org-element-property :end element))
23270 (skip-chars-backward " \r\t\n")
23271 (line-beginning-position))
23272 (point))))
23273 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23274 (beginning-of-line)
23275 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23276 (open-line 1))
23277 (org-indent-line)
23278 (insert "# ")))
23280 (defvar comment-empty-lines) ; From newcomment.el.
23281 (defun org-comment-or-uncomment-region (beg end &rest _)
23282 "Comment or uncomment each non-blank line in the region.
23283 Uncomment each non-blank line between BEG and END if it only
23284 contains commented lines. Otherwise, comment them. If region is
23285 strictly within a source block, use appropriate comment syntax."
23286 (if (let ((element (org-element-at-point)))
23287 (and (eq (org-element-type element) 'src-block)
23288 (< (save-excursion
23289 (goto-char (org-element-property :post-affiliated element))
23290 (line-end-position))
23291 beg)
23292 (>= (save-excursion
23293 (goto-char (org-element-property :end element))
23294 (skip-chars-backward " \r\t\n")
23295 (line-beginning-position))
23296 end)))
23297 ;; Translate region boundaries for the Org buffer to the source
23298 ;; buffer.
23299 (let ((offset (- end beg)))
23300 (save-excursion
23301 (goto-char beg)
23302 (org-babel-do-in-edit-buffer
23303 (comment-or-uncomment-region (point) (+ offset (point))))))
23304 (save-restriction
23305 ;; Restrict region
23306 (narrow-to-region (save-excursion (goto-char beg)
23307 (skip-chars-forward " \r\t\n" end)
23308 (line-beginning-position))
23309 (save-excursion (goto-char end)
23310 (skip-chars-backward " \r\t\n" beg)
23311 (line-end-position)))
23312 (let ((uncommentp
23313 ;; UNCOMMENTP is non-nil when every non blank line between
23314 ;; BEG and END is a comment.
23315 (save-excursion
23316 (goto-char (point-min))
23317 (while (and (not (eobp))
23318 (let ((element (org-element-at-point)))
23319 (and (eq (org-element-type element) 'comment)
23320 (goto-char (min (point-max)
23321 (org-element-property
23322 :end element)))))))
23323 (eobp))))
23324 (if uncommentp
23325 ;; Only blank lines and comments in region: uncomment it.
23326 (save-excursion
23327 (goto-char (point-min))
23328 (while (not (eobp))
23329 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23330 (replace-match "" nil nil nil 1))
23331 (forward-line)))
23332 ;; Comment each line in region.
23333 (let ((min-indent (point-max)))
23334 ;; First find the minimum indentation across all lines.
23335 (save-excursion
23336 (goto-char (point-min))
23337 (while (and (not (eobp)) (not (zerop min-indent)))
23338 (unless (looking-at "[ \t]*$")
23339 (setq min-indent (min min-indent (current-indentation))))
23340 (forward-line)))
23341 ;; Then loop over all lines.
23342 (save-excursion
23343 (goto-char (point-min))
23344 (while (not (eobp))
23345 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23346 ;; Don't get fooled by invisible text (e.g. link path)
23347 ;; when moving to column MIN-INDENT.
23348 (let ((buffer-invisibility-spec nil))
23349 (org-move-to-column min-indent t))
23350 (insert comment-start))
23351 (forward-line)))))))))
23353 (defun org-comment-dwim (_arg)
23354 "Call `comment-dwim' within a source edit buffer if needed."
23355 (interactive "*P")
23356 (if (org-in-src-block-p)
23357 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23358 (call-interactively 'comment-dwim)))
23361 ;;; Timestamps API
23363 ;; This section contains tools to operate on timestamp objects, as
23364 ;; returned by, e.g. `org-element-context'.
23366 (defun org-timestamp--to-internal-time (timestamp &optional end)
23367 "Encode TIMESTAMP object into Emacs internal time.
23368 Use end of date range or time range when END is non-nil."
23369 (apply #'encode-time
23370 (cons 0
23371 (mapcar
23372 (lambda (prop) (or (org-element-property prop timestamp) 0))
23373 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23374 '(:minute-start :hour-start :day-start :month-start
23375 :year-start))))))
23377 (defun org-timestamp-has-time-p (timestamp)
23378 "Non-nil when TIMESTAMP has a time specified."
23379 (org-element-property :hour-start timestamp))
23381 (defun org-timestamp-format (timestamp format &optional end utc)
23382 "Format a TIMESTAMP object into a string.
23384 FORMAT is a format specifier to be passed to
23385 `format-time-string'.
23387 When optional argument END is non-nil, use end of date-range or
23388 time-range, if possible.
23390 When optional argument UTC is non-nil, time will be expressed as
23391 Universal Time."
23392 (format-time-string
23393 format (org-timestamp--to-internal-time timestamp end)
23394 (and utc t)))
23396 (defun org-timestamp-split-range (timestamp &optional end)
23397 "Extract a TIMESTAMP object from a date or time range.
23399 END, when non-nil, means extract the end of the range.
23400 Otherwise, extract its start.
23402 Return a new timestamp object."
23403 (let ((type (org-element-property :type timestamp)))
23404 (if (memq type '(active inactive diary)) timestamp
23405 (let ((split-ts (org-element-copy timestamp)))
23406 ;; Set new type.
23407 (org-element-put-property
23408 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23409 ;; Copy start properties over end properties if END is
23410 ;; non-nil. Otherwise, copy end properties over `start' ones.
23411 (let ((p-alist '((:minute-start . :minute-end)
23412 (:hour-start . :hour-end)
23413 (:day-start . :day-end)
23414 (:month-start . :month-end)
23415 (:year-start . :year-end))))
23416 (dolist (p-cell p-alist)
23417 (org-element-put-property
23418 split-ts
23419 (funcall (if end #'car #'cdr) p-cell)
23420 (org-element-property
23421 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23422 ;; Eventually refresh `:raw-value'.
23423 (org-element-put-property split-ts :raw-value nil)
23424 (org-element-put-property
23425 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23427 (defun org-timestamp-translate (timestamp &optional boundary)
23428 "Translate TIMESTAMP object to custom format.
23430 Format string is defined in `org-time-stamp-custom-formats',
23431 which see.
23433 When optional argument BOUNDARY is non-nil, it is either the
23434 symbol `start' or `end'. In this case, only translate the
23435 starting or ending part of TIMESTAMP if it is a date or time
23436 range. Otherwise, translate both parts.
23438 Return timestamp as-is if `org-display-custom-times' is nil or if
23439 it has a `diary' type."
23440 (let ((type (org-element-property :type timestamp)))
23441 (if (or (not org-display-custom-times) (eq type 'diary))
23442 (org-element-interpret-data timestamp)
23443 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23444 org-time-stamp-custom-formats)))
23445 (if (and (not boundary) (memq type '(active-range inactive-range)))
23446 (concat (org-timestamp-format timestamp fmt)
23447 "--"
23448 (org-timestamp-format timestamp fmt t))
23449 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23453 ;;; Other stuff.
23455 (defvar reftex-docstruct-symbol)
23456 (defvar org--rds)
23458 (defun org-reftex-citation ()
23459 "Use reftex-citation to insert a citation into the buffer.
23460 This looks for a line like
23462 #+BIBLIOGRAPHY: foo plain option:-d
23464 and derives from it that foo.bib is the bibliography file relevant
23465 for this document. It then installs the necessary environment for RefTeX
23466 to work in this buffer and calls `reftex-citation' to insert a citation
23467 into the buffer.
23469 Export of such citations to both LaTeX and HTML is handled by the contributed
23470 package ox-bibtex by Taru Karttunen."
23471 (interactive)
23472 (let ((reftex-docstruct-symbol 'org--rds)
23473 org--rds bib)
23474 (org-with-wide-buffer
23475 (let ((case-fold-search t)
23476 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23477 (if (not (save-excursion
23478 (or (re-search-forward re nil t)
23479 (re-search-backward re nil t))))
23480 (user-error "No bibliography defined in file")
23481 (setq bib (concat (match-string 1) ".bib")
23482 org--rds (list (list 'bib bib))))))
23483 (call-interactively 'reftex-citation)))
23485 ;;;; Functions extending outline functionality
23487 (defun org-beginning-of-line (&optional n)
23488 "Go to the beginning of the current visible line.
23490 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23491 tags on the first attempt, and only move to after the tags when
23492 the cursor is already beyond the end of the headline.
23494 With argument N not nil or 1, move forward N - 1 lines first."
23495 (interactive "^p")
23496 (let ((origin (point))
23497 (special (pcase org-special-ctrl-a/e
23498 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23499 deactivate-mark)
23500 ;; First move to a visible line.
23501 (if (bound-and-true-p visual-line-mode)
23502 (beginning-of-visual-line n)
23503 (move-beginning-of-line n)
23504 ;; `move-beginning-of-line' may leave point after invisible
23505 ;; characters if line starts with such of these (e.g., with
23506 ;; a link at column 0). Really move to the beginning of the
23507 ;; current visible line.
23508 (beginning-of-line))
23509 (cond
23510 ;; No special behavior. Point is already at the beginning of
23511 ;; a line, logical or visual.
23512 ((not special))
23513 ;; `beginning-of-visual-line' left point before logical beginning
23514 ;; of line: point is at the beginning of a visual line. Bail
23515 ;; out.
23516 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23517 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23518 ;; At a headline, special position is before the title, but
23519 ;; after any TODO keyword or priority cookie.
23520 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23521 (line-end-position)))
23522 (bol (point)))
23523 (if (eq special 'reversed)
23524 (when (and (= origin bol) (eq last-command this-command))
23525 (goto-char refpos))
23526 (when (or (> origin refpos) (= origin bol))
23527 (goto-char refpos)))))
23528 ((and (looking-at org-list-full-item-re)
23529 (memq (org-element-type (save-match-data (org-element-at-point)))
23530 '(item plain-list)))
23531 ;; Set special position at first white space character after
23532 ;; bullet, and check-box, if any.
23533 (let ((after-bullet
23534 (let ((box (match-end 3)))
23535 (cond ((not box) (match-end 1))
23536 ((eq (char-after box) ?\s) (1+ box))
23537 (t box)))))
23538 (if (eq special 'reversed)
23539 (when (and (= (point) origin) (eq last-command this-command))
23540 (goto-char after-bullet))
23541 (when (or (> origin after-bullet) (= (point) origin))
23542 (goto-char after-bullet)))))
23543 ;; No special context. Point is already at beginning of line.
23544 (t nil))))
23546 (defun org-end-of-line (&optional n)
23547 "Go to the end of the line, but before ellipsis, if any.
23549 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23550 tags on the first attempt, and only move to after the tags when
23551 the cursor is already beyond the end of the headline.
23553 With argument N not nil or 1, move forward N - 1 lines first."
23554 (interactive "^p")
23555 (let ((origin (point))
23556 (special (pcase org-special-ctrl-a/e
23557 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23558 deactivate-mark)
23559 ;; First move to a visible line.
23560 (if (bound-and-true-p visual-line-mode)
23561 (beginning-of-visual-line n)
23562 (move-beginning-of-line n))
23563 (cond
23564 ;; At a headline, with tags.
23565 ((and special
23566 (save-excursion
23567 (beginning-of-line)
23568 (let ((case-fold-search nil))
23569 (looking-at org-complex-heading-regexp)))
23570 (match-end 5))
23571 (let ((tags (save-excursion
23572 (goto-char (match-beginning 5))
23573 (skip-chars-backward " \t")
23574 (point)))
23575 (visual-end (and (bound-and-true-p visual-line-mode)
23576 (save-excursion
23577 (end-of-visual-line)
23578 (point)))))
23579 ;; If `end-of-visual-line' brings us before end of line or
23580 ;; even tags, i.e., the headline spans over multiple visual
23581 ;; lines, move there.
23582 (cond ((and visual-end
23583 (< visual-end tags)
23584 (<= origin visual-end))
23585 (goto-char visual-end))
23586 ((eq special 'reversed)
23587 (if (and (= origin (line-end-position))
23588 (eq this-command last-command))
23589 (goto-char tags)
23590 (end-of-line)))
23592 (if (or (< origin tags) (= origin (line-end-position)))
23593 (goto-char tags)
23594 (end-of-line))))))
23595 ((bound-and-true-p visual-line-mode)
23596 (let ((bol (line-beginning-position)))
23597 (end-of-visual-line)
23598 ;; If `end-of-visual-line' gets us past the ellipsis at the
23599 ;; end of a line, backtrack and use `end-of-line' instead.
23600 (when (/= bol (line-beginning-position))
23601 (goto-char bol)
23602 (end-of-line))))
23603 (t (end-of-line)))))
23605 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23606 (define-key org-mode-map "\C-e" 'org-end-of-line)
23608 (defun org-backward-sentence (&optional _arg)
23609 "Go to beginning of sentence, or beginning of table field.
23610 This will call `backward-sentence' or `org-table-beginning-of-field',
23611 depending on context."
23612 (interactive)
23613 (let* ((element (org-element-at-point))
23614 (contents-begin (org-element-property :contents-begin element))
23615 (table (org-element-lineage element '(table) t)))
23616 (if (and table
23617 (> (point) contents-begin)
23618 (<= (point) (org-element-property :contents-end table)))
23619 (call-interactively #'org-table-beginning-of-field)
23620 (save-restriction
23621 (when (and contents-begin
23622 (< (point-min) contents-begin)
23623 (> (point) contents-begin))
23624 (narrow-to-region contents-begin
23625 (org-element-property :contents-end element)))
23626 (call-interactively #'backward-sentence)))))
23628 (defun org-forward-sentence (&optional _arg)
23629 "Go to end of sentence, or end of table field.
23630 This will call `forward-sentence' or `org-table-end-of-field',
23631 depending on context."
23632 (interactive)
23633 (let* ((element (org-element-at-point))
23634 (contents-end (org-element-property :contents-end element))
23635 (table (org-element-lineage element '(table) t)))
23636 (if (and table
23637 (>= (point) (org-element-property :contents-begin table))
23638 (< (point) contents-end))
23639 (call-interactively #'org-table-end-of-field)
23640 (save-restriction
23641 (when (and contents-end
23642 (> (point-max) contents-end)
23643 ;; Skip blank lines between elements.
23644 (< (org-element-property :end element)
23645 (save-excursion (goto-char contents-end)
23646 (skip-chars-forward " \r\t\n"))))
23647 (narrow-to-region (org-element-property :contents-begin element)
23648 contents-end))
23649 (call-interactively #'forward-sentence)))))
23651 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23652 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23654 (defun org-kill-line (&optional _arg)
23655 "Kill line, to tags or end of line."
23656 (interactive)
23657 (cond
23658 ((or (not org-special-ctrl-k)
23659 (bolp)
23660 (not (org-at-heading-p)))
23661 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23662 org-ctrl-k-protect-subtree
23663 (or (eq org-ctrl-k-protect-subtree 'error)
23664 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23665 (user-error "C-k aborted as it would kill a hidden subtree"))
23666 (call-interactively
23667 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23668 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23669 (kill-region (point) (match-beginning 1))
23670 (org-set-tags nil t))
23671 (t (kill-region (point) (point-at-eol)))))
23673 (define-key org-mode-map "\C-k" 'org-kill-line)
23675 (defun org-yank (&optional arg)
23676 "Yank. If the kill is a subtree, treat it specially.
23677 This command will look at the current kill and check if is a single
23678 subtree, or a series of subtrees[1]. If it passes the test, and if the
23679 cursor is at the beginning of a line or after the stars of a currently
23680 empty headline, then the yank is handled specially. How exactly depends
23681 on the value of the following variables.
23683 `org-yank-folded-subtrees'
23684 By default, this variable is non-nil, which results in
23685 subtree(s) being folded after insertion, except if doing so
23686 would swallow text after the yanked text.
23688 `org-yank-adjusted-subtrees'
23689 When non-nil (the default value is nil), the subtree will be
23690 promoted or demoted in order to fit into the local outline tree
23691 structure, which means that the level will be adjusted so that it
23692 becomes the smaller one of the two *visible* surrounding headings.
23694 Any prefix to this command will cause `yank' to be called directly with
23695 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23696 will just
23697 plainly yank the text as it is.
23699 \[1] The test checks if the first non-white line is a heading
23700 and if there are no other headings with fewer stars."
23701 (interactive "P")
23702 (org-yank-generic 'yank arg))
23704 (defun org-yank-generic (command arg)
23705 "Perform some yank-like command.
23707 This function implements the behavior described in the `org-yank'
23708 documentation. However, it has been generalized to work for any
23709 interactive command with similar behavior."
23711 ;; pretend to be command COMMAND
23712 (setq this-command command)
23714 (if arg
23715 (call-interactively command)
23717 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23718 (and (org-kill-is-subtree-p)
23719 (or (bolp)
23720 (and (looking-at "[ \t]*$")
23721 (string-match
23722 "\\`\\*+\\'"
23723 (buffer-substring (point-at-bol) (point)))))))
23724 swallowp)
23725 (cond
23726 ((and subtreep org-yank-folded-subtrees)
23727 (let ((beg (point))
23728 end)
23729 (if (and subtreep org-yank-adjusted-subtrees)
23730 (org-paste-subtree nil nil 'for-yank)
23731 (call-interactively command))
23733 (setq end (point))
23734 (goto-char beg)
23735 (when (and (bolp) subtreep
23736 (not (setq swallowp
23737 (org-yank-folding-would-swallow-text beg end))))
23738 (org-with-limited-levels
23739 (or (looking-at org-outline-regexp)
23740 (re-search-forward org-outline-regexp-bol end t))
23741 (while (and (< (point) end) (looking-at org-outline-regexp))
23742 (outline-hide-subtree)
23743 (org-cycle-show-empty-lines 'folded)
23744 (condition-case nil
23745 (outline-forward-same-level 1)
23746 (error (goto-char end))))))
23747 (when swallowp
23748 (message
23749 "Inserted text not folded because that would swallow text"))
23751 (goto-char end)
23752 (skip-chars-forward " \t\n\r")
23753 (beginning-of-line 1)
23754 (push-mark beg 'nomsg)))
23755 ((and subtreep org-yank-adjusted-subtrees)
23756 (let ((beg (point-at-bol)))
23757 (org-paste-subtree nil nil 'for-yank)
23758 (push-mark beg 'nomsg)))
23760 (call-interactively command))))))
23762 (defun org-yank-folding-would-swallow-text (beg end)
23763 "Would hide-subtree at BEG swallow any text after END?"
23764 (let (level)
23765 (org-with-limited-levels
23766 (save-excursion
23767 (goto-char beg)
23768 (when (or (looking-at org-outline-regexp)
23769 (re-search-forward org-outline-regexp-bol end t))
23770 (setq level (org-outline-level)))
23771 (goto-char end)
23772 (skip-chars-forward " \t\r\n\v\f")
23773 (not (or (eobp)
23774 (and (bolp) (looking-at-p org-outline-regexp)
23775 (<= (org-outline-level) level))))))))
23777 (define-key org-mode-map "\C-y" 'org-yank)
23779 (defun org-truely-invisible-p ()
23780 "Check if point is at a character currently not visible.
23781 This version does not only check the character property, but also
23782 `visible-mode'."
23783 (unless (bound-and-true-p visible-mode)
23784 (org-invisible-p)))
23786 (defun org-invisible-p2 ()
23787 "Check if point is at a character currently not visible.
23789 If the point is at EOL (and not at the beginning of a buffer too),
23790 move it back by one char before doing this check."
23791 (save-excursion
23792 (when (and (eolp) (not (bobp)))
23793 (backward-char 1))
23794 (org-invisible-p)))
23796 (defun org-back-to-heading (&optional invisible-ok)
23797 "Call `outline-back-to-heading', but provide a better error message."
23798 (condition-case nil
23799 (outline-back-to-heading invisible-ok)
23800 (error (error "Before first headline at position %d in buffer %s"
23801 (point) (current-buffer)))))
23803 (defun org-before-first-heading-p ()
23804 "Before first heading?"
23805 (save-excursion
23806 (end-of-line)
23807 (null (re-search-backward org-outline-regexp-bol nil t))))
23809 (defun org-at-heading-p (&optional ignored)
23810 (outline-on-heading-p t))
23812 (defun org-in-commented-heading-p (&optional no-inheritance)
23813 "Non-nil if point is under a commented heading.
23814 This function also checks ancestors of the current headline,
23815 unless optional argument NO-INHERITANCE is non-nil."
23816 (cond
23817 ((org-before-first-heading-p) nil)
23818 ((let ((headline (nth 4 (org-heading-components))))
23819 (and headline
23820 (let ((case-fold-search nil))
23821 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23822 headline)))))
23823 (no-inheritance nil)
23825 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23827 (defun org-at-comment-p nil
23828 "Is cursor in a commented line?"
23829 (save-excursion
23830 (save-match-data
23831 (beginning-of-line)
23832 (looking-at "^[ \t]*# "))))
23834 (defun org-at-drawer-p nil
23835 "Is cursor at a drawer keyword?"
23836 (save-excursion
23837 (move-beginning-of-line 1)
23838 (looking-at org-drawer-regexp)))
23840 (defun org-at-block-p nil
23841 "Is cursor at a block keyword?"
23842 (save-excursion
23843 (move-beginning-of-line 1)
23844 (looking-at org-block-regexp)))
23846 (defun org-point-at-end-of-empty-headline ()
23847 "If point is at the end of an empty headline, return t, else nil.
23848 If the heading only contains a TODO keyword, it is still still considered
23849 empty."
23850 (let ((case-fold-search nil))
23851 (and (looking-at "[ \t]*$")
23852 org-todo-line-regexp
23853 (save-excursion
23854 (beginning-of-line)
23855 (looking-at org-todo-line-regexp)
23856 (string= (match-string 3) "")))))
23858 (defun org-at-heading-or-item-p ()
23859 (or (org-at-heading-p) (org-at-item-p)))
23861 (defun org-at-target-p ()
23862 (or (org-in-regexp org-radio-target-regexp)
23863 (org-in-regexp org-target-regexp)))
23864 ;; Compatibility alias with Org versions < 7.8.03
23865 (defalias 'org-on-target-p 'org-at-target-p)
23867 (defun org-up-heading-all (arg)
23868 "Move to the heading line of which the present line is a subheading.
23869 This function considers both visible and invisible heading lines.
23870 With argument, move up ARG levels."
23871 (outline-up-heading arg t))
23873 (defun org-up-heading-safe ()
23874 "Move to the heading line of which the present line is a subheading.
23875 This version will not throw an error. It will return the level of the
23876 headline found, or nil if no higher level is found.
23878 Also, this function will be a lot faster than `outline-up-heading',
23879 because it relies on stars being the outline starters. This can really
23880 make a significant difference in outlines with very many siblings."
23881 (when (ignore-errors (org-back-to-heading t))
23882 (let ((level-up (1- (funcall outline-level))))
23883 (and (> level-up 0)
23884 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23885 (funcall outline-level)))))
23887 (defun org-first-sibling-p ()
23888 "Is this heading the first child of its parents?"
23889 (interactive)
23890 (let ((re org-outline-regexp-bol)
23891 level l)
23892 (unless (org-at-heading-p t)
23893 (user-error "Not at a heading"))
23894 (setq level (funcall outline-level))
23895 (save-excursion
23896 (if (not (re-search-backward re nil t))
23898 (setq l (funcall outline-level))
23899 (< l level)))))
23901 (defun org-goto-sibling (&optional previous)
23902 "Goto the next sibling, even if it is invisible.
23903 When PREVIOUS is set, go to the previous sibling instead. Returns t
23904 when a sibling was found. When none is found, return nil and don't
23905 move point."
23906 (let ((fun (if previous 're-search-backward 're-search-forward))
23907 (pos (point))
23908 (re org-outline-regexp-bol)
23909 level l)
23910 (when (ignore-errors (org-back-to-heading t))
23911 (setq level (funcall outline-level))
23912 (catch 'exit
23913 (or previous (forward-char 1))
23914 (while (funcall fun re nil t)
23915 (setq l (funcall outline-level))
23916 (when (< l level) (goto-char pos) (throw 'exit nil))
23917 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23918 (goto-char pos)
23919 nil))))
23921 (defun org-show-siblings ()
23922 "Show all siblings of the current headline."
23923 (save-excursion
23924 (while (org-goto-sibling) (org-flag-heading nil)))
23925 (save-excursion
23926 (while (org-goto-sibling 'previous)
23927 (org-flag-heading nil))))
23929 (defun org-goto-first-child ()
23930 "Goto the first child, even if it is invisible.
23931 Return t when a child was found. Otherwise don't move point and
23932 return nil."
23933 (let (level (pos (point)) (re org-outline-regexp-bol))
23934 (when (ignore-errors (org-back-to-heading t))
23935 (setq level (outline-level))
23936 (forward-char 1)
23937 (if (and (re-search-forward re nil t) (> (outline-level) level))
23938 (progn (goto-char (match-beginning 0)) t)
23939 (goto-char pos) nil))))
23941 (defun org-show-hidden-entry ()
23942 "Show an entry where even the heading is hidden."
23943 (save-excursion
23944 (org-show-entry)))
23946 (defun org-flag-heading (flag &optional entry)
23947 "Flag the current heading. FLAG non-nil means make invisible.
23948 When ENTRY is non-nil, show the entire entry."
23949 (save-excursion
23950 (org-back-to-heading t)
23951 ;; Check if we should show the entire entry
23952 (if entry
23953 (progn
23954 (org-show-entry)
23955 (save-excursion
23956 (and (outline-next-heading)
23957 (org-flag-heading nil))))
23958 (outline-flag-region (max (point-min) (1- (point)))
23959 (save-excursion (outline-end-of-heading) (point))
23960 flag))))
23962 (defun org-get-next-sibling ()
23963 "Move to next heading of the same level, and return point.
23964 If there is no such heading, return nil.
23965 This is like outline-next-sibling, but invisible headings are ok."
23966 (let ((level (funcall outline-level)))
23967 (outline-next-heading)
23968 (while (and (not (eobp)) (> (funcall outline-level) level))
23969 (outline-next-heading))
23970 (unless (or (eobp) (< (funcall outline-level) level))
23971 (point))))
23973 (defun org-get-last-sibling ()
23974 "Move to previous heading of the same level, and return point.
23975 If there is no such heading, return nil."
23976 (let ((opoint (point))
23977 (level (funcall outline-level)))
23978 (outline-previous-heading)
23979 (when (and (/= (point) opoint) (outline-on-heading-p t))
23980 (while (and (> (funcall outline-level) level)
23981 (not (bobp)))
23982 (outline-previous-heading))
23983 (unless (< (funcall outline-level) level)
23984 (point)))))
23986 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23987 "Goto to the end of a subtree."
23988 ;; This contains an exact copy of the original function, but it uses
23989 ;; `org-back-to-heading', to make it work also in invisible
23990 ;; trees. And is uses an invisible-ok argument.
23991 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23992 ;; Furthermore, when used inside Org, finding the end of a large subtree
23993 ;; with many children and grandchildren etc, this can be much faster
23994 ;; than the outline version.
23995 (org-back-to-heading invisible-ok)
23996 (let ((first t)
23997 (level (funcall outline-level)))
23998 (if (and (derived-mode-p 'org-mode) (< level 1000))
23999 ;; A true heading (not a plain list item), in Org
24000 ;; This means we can easily find the end by looking
24001 ;; only for the right number of stars. Using a regexp to do
24002 ;; this is so much faster than using a Lisp loop.
24003 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24004 (forward-char 1)
24005 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24006 ;; something else, do it the slow way
24007 (while (and (not (eobp))
24008 (or first (> (funcall outline-level) level)))
24009 (setq first nil)
24010 (outline-next-heading)))
24011 (unless to-heading
24012 (when (memq (preceding-char) '(?\n ?\^M))
24013 ;; Go to end of line before heading
24014 (forward-char -1)
24015 (when (memq (preceding-char) '(?\n ?\^M))
24016 ;; leave blank line before heading
24017 (forward-char -1)))))
24018 (point))
24020 (defun org-end-of-meta-data (&optional full)
24021 "Skip planning line and properties drawer in current entry.
24022 When optional argument FULL is non-nil, also skip empty lines,
24023 clocking lines and regular drawers at the beginning of the
24024 entry."
24025 (org-back-to-heading t)
24026 (forward-line)
24027 (when (looking-at-p org-planning-line-re) (forward-line))
24028 (when (looking-at org-property-drawer-re)
24029 (goto-char (match-end 0))
24030 (forward-line))
24031 (when (and full (not (org-at-heading-p)))
24032 (catch 'exit
24033 (let ((end (save-excursion (outline-next-heading) (point)))
24034 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24035 (while (not (eobp))
24036 (cond ((looking-at-p org-drawer-regexp)
24037 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24038 (forward-line)
24039 (throw 'exit t)))
24040 ((looking-at-p re) (forward-line))
24041 (t (throw 'exit t))))))))
24043 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24044 "Move forward to the ARG'th subheading at same level as this one.
24045 Stop at the first and last subheadings of a superior heading.
24046 Normally this only looks at visible headings, but when INVISIBLE-OK is
24047 non-nil it will also look at invisible ones."
24048 (interactive "p")
24049 (let ((backward? (and arg (< arg 0))))
24050 (if (org-before-first-heading-p)
24051 (if backward? (goto-char (point-min)) (outline-next-heading))
24052 (org-back-to-heading invisible-ok)
24053 (unless backward? (end-of-line)) ;do not match current headline
24054 (let ((level (- (match-end 0) (match-beginning 0) 1))
24055 (f (if backward? #'re-search-backward #'re-search-forward))
24056 (count (if arg (abs arg) 1))
24057 (result (point)))
24058 (while (and (> count 0)
24059 (funcall f org-outline-regexp-bol nil 'move))
24060 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24061 (cond ((< l level) (setq count 0))
24062 ((and (= l level)
24063 (or invisible-ok
24064 (not (org-invisible-p
24065 (line-beginning-position)))))
24066 (cl-decf count)
24067 (when (= l level) (setq result (point)))))))
24068 (goto-char result))
24069 (beginning-of-line))))
24071 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24072 "Move backward to the ARG'th subheading at same level as this one.
24073 Stop at the first and last subheadings of a superior heading."
24074 (interactive "p")
24075 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24077 (defun org-next-visible-heading (arg)
24078 "Move to the next visible heading.
24080 This function wraps `outline-next-visible-heading' with
24081 `org-with-limited-levels' in order to skip over inline tasks and
24082 respect customization of `org-odd-levels-only'."
24083 (interactive "p")
24084 (org-with-limited-levels
24085 (outline-next-visible-heading arg)))
24087 (defun org-previous-visible-heading (arg)
24088 "Move to the previous visible heading.
24090 This function wraps `outline-previous-visible-heading' with
24091 `org-with-limited-levels' in order to skip over inline tasks and
24092 respect customization of `org-odd-levels-only'."
24093 (interactive "p")
24094 (org-with-limited-levels
24095 (outline-previous-visible-heading arg)))
24097 (defun org-next-block (arg &optional backward block-regexp)
24098 "Jump to the next block.
24100 With a prefix argument ARG, jump forward ARG many blocks.
24102 When BACKWARD is non-nil, jump to the previous block.
24104 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24105 Match data is set according to this regexp when the function
24106 returns.
24108 Return point at beginning of the opening line of found block.
24109 Throw an error if no block is found."
24110 (interactive "p")
24111 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24112 (case-fold-search t)
24113 (search-fn (if backward #'re-search-backward #'re-search-forward))
24114 (count (or arg 1))
24115 (origin (point))
24116 last-element)
24117 (if backward (beginning-of-line) (end-of-line))
24118 (while (and (> count 0) (funcall search-fn re nil t))
24119 (let ((element (save-excursion
24120 (goto-char (match-beginning 0))
24121 (save-match-data (org-element-at-point)))))
24122 (when (and (memq (org-element-type element)
24123 '(center-block comment-block dynamic-block
24124 example-block export-block quote-block
24125 special-block src-block verse-block))
24126 (<= (match-beginning 0)
24127 (org-element-property :post-affiliated element)))
24128 (setq last-element element)
24129 (cl-decf count))))
24130 (if (= count 0)
24131 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24132 (save-match-data (org-show-context)))
24133 (goto-char origin)
24134 (user-error "No %s code blocks" (if backward "previous" "further")))))
24136 (defun org-previous-block (arg &optional block-regexp)
24137 "Jump to the previous block.
24138 With a prefix argument ARG, jump backward ARG many source blocks.
24139 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24140 (interactive "p")
24141 (org-next-block arg t block-regexp))
24143 (defun org-forward-paragraph ()
24144 "Move forward to beginning of next paragraph or equivalent.
24146 The function moves point to the beginning of the next visible
24147 structural element, which can be a paragraph, a table, a list
24148 item, etc. It also provides some special moves for convenience:
24150 - On an affiliated keyword, jump to the beginning of the
24151 relative element.
24152 - On an item or a footnote definition, move to the second
24153 element inside, if any.
24154 - On a table or a property drawer, jump after it.
24155 - On a verse or source block, stop after blank lines."
24156 (interactive)
24157 (unless (eobp)
24158 (let* ((deactivate-mark nil)
24159 (element (org-element-at-point))
24160 (type (org-element-type element))
24161 (post-affiliated (org-element-property :post-affiliated element))
24162 (contents-begin (org-element-property :contents-begin element))
24163 (contents-end (org-element-property :contents-end element))
24164 (end (let ((end (org-element-property :end element)) (parent element))
24165 (while (and (setq parent (org-element-property :parent parent))
24166 (= (org-element-property :contents-end parent) end))
24167 (setq end (org-element-property :end parent)))
24168 end)))
24169 (cond ((not element)
24170 (skip-chars-forward " \r\t\n")
24171 (or (eobp) (beginning-of-line)))
24172 ;; On affiliated keywords, move to element's beginning.
24173 ((< (point) post-affiliated)
24174 (goto-char post-affiliated))
24175 ;; At a table row, move to the end of the table. Similarly,
24176 ;; at a node property, move to the end of the property
24177 ;; drawer.
24178 ((memq type '(node-property table-row))
24179 (goto-char (org-element-property
24180 :end (org-element-property :parent element))))
24181 ((memq type '(property-drawer table)) (goto-char end))
24182 ;; Consider blank lines as separators in verse and source
24183 ;; blocks to ease editing.
24184 ((memq type '(src-block verse-block))
24185 (when (eq type 'src-block)
24186 (setq contents-end
24187 (save-excursion (goto-char end)
24188 (skip-chars-backward " \r\t\n")
24189 (line-beginning-position))))
24190 (beginning-of-line)
24191 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24192 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24193 (goto-char end)
24194 (skip-chars-forward " \r\t\n")
24195 (if (= (point) contents-end) (goto-char end)
24196 (beginning-of-line))))
24197 ;; With no contents, just skip element.
24198 ((not contents-begin) (goto-char end))
24199 ;; If contents are invisible, skip the element altogether.
24200 ((org-invisible-p (line-end-position))
24201 (cl-case type
24202 (headline
24203 (org-with-limited-levels (outline-next-visible-heading 1)))
24204 ;; At a plain list, make sure we move to the next item
24205 ;; instead of skipping the whole list.
24206 (plain-list (forward-char)
24207 (org-forward-paragraph))
24208 (otherwise (goto-char end))))
24209 ((>= (point) contents-end) (goto-char end))
24210 ((>= (point) contents-begin)
24211 ;; This can only happen on paragraphs and plain lists.
24212 (cl-case type
24213 (paragraph (goto-char end))
24214 ;; At a plain list, try to move to second element in
24215 ;; first item, if possible.
24216 (plain-list (end-of-line)
24217 (org-forward-paragraph))))
24218 ;; When contents start on the middle of a line (e.g. in
24219 ;; items and footnote definitions), try to reach first
24220 ;; element starting after current line.
24221 ((> (line-end-position) contents-begin)
24222 (end-of-line)
24223 (org-forward-paragraph))
24224 (t (goto-char contents-begin))))))
24226 (defun org-backward-paragraph ()
24227 "Move backward to start of previous paragraph or equivalent.
24229 The function moves point to the beginning of the current
24230 structural element, which can be a paragraph, a table, a list
24231 item, etc., or to the beginning of the previous visible one if
24232 point is already there. It also provides some special moves for
24233 convenience:
24235 - On an affiliated keyword, jump to the first one.
24236 - On a table or a property drawer, move to its beginning.
24237 - On a verse or source block, stop before blank lines."
24238 (interactive)
24239 (unless (bobp)
24240 (let* ((deactivate-mark nil)
24241 (element (org-element-at-point))
24242 (type (org-element-type element))
24243 (contents-begin (org-element-property :contents-begin element))
24244 (contents-end (org-element-property :contents-end element))
24245 (post-affiliated (org-element-property :post-affiliated element))
24246 (begin (org-element-property :begin element)))
24247 (cond
24248 ((not element) (goto-char (point-min)))
24249 ((= (point) begin)
24250 (backward-char)
24251 (org-backward-paragraph))
24252 ((<= (point) post-affiliated) (goto-char begin))
24253 ((memq type '(node-property table-row))
24254 (goto-char (org-element-property
24255 :post-affiliated (org-element-property :parent element))))
24256 ((memq type '(property-drawer table)) (goto-char begin))
24257 ((memq type '(src-block verse-block))
24258 (when (eq type 'src-block)
24259 (setq contents-begin
24260 (save-excursion (goto-char begin) (forward-line) (point))))
24261 (if (= (point) contents-begin) (goto-char post-affiliated)
24262 ;; Inside a verse block, see blank lines as paragraph
24263 ;; separators.
24264 (let ((origin (point)))
24265 (skip-chars-backward " \r\t\n" contents-begin)
24266 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24267 (skip-chars-forward " \r\t\n" origin)
24268 (if (= (point) origin) (goto-char contents-begin)
24269 (beginning-of-line))))))
24270 ((not contents-begin) (goto-char (or post-affiliated begin)))
24271 ((eq type 'paragraph)
24272 (goto-char contents-begin)
24273 ;; When at first paragraph in an item or a footnote definition,
24274 ;; move directly to beginning of line.
24275 (let ((parent-contents
24276 (org-element-property
24277 :contents-begin (org-element-property :parent element))))
24278 (when (and parent-contents (= parent-contents contents-begin))
24279 (beginning-of-line))))
24280 ;; At the end of a greater element, move to the beginning of the
24281 ;; last element within.
24282 ((>= (point) contents-end)
24283 (goto-char (1- contents-end))
24284 (org-backward-paragraph))
24285 (t (goto-char (or post-affiliated begin))))
24286 ;; Ensure we never leave point invisible.
24287 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24289 (defun org-forward-element ()
24290 "Move forward by one element.
24291 Move to the next element at the same level, when possible."
24292 (interactive)
24293 (cond ((eobp) (user-error "Cannot move further down"))
24294 ((org-with-limited-levels (org-at-heading-p))
24295 (let ((origin (point)))
24296 (goto-char (org-end-of-subtree nil t))
24297 (unless (org-with-limited-levels (org-at-heading-p))
24298 (goto-char origin)
24299 (user-error "Cannot move further down"))))
24301 (let* ((elem (org-element-at-point))
24302 (end (org-element-property :end elem))
24303 (parent (org-element-property :parent elem)))
24304 (cond ((and parent (= (org-element-property :contents-end parent) end))
24305 (goto-char (org-element-property :end parent)))
24306 ((integer-or-marker-p end) (goto-char end))
24307 (t (message "No element at point")))))))
24309 (defun org-backward-element ()
24310 "Move backward by one element.
24311 Move to the previous element at the same level, when possible."
24312 (interactive)
24313 (cond ((bobp) (user-error "Cannot move further up"))
24314 ((org-with-limited-levels (org-at-heading-p))
24315 ;; At a headline, move to the previous one, if any, or stay
24316 ;; here.
24317 (let ((origin (point)))
24318 (org-with-limited-levels (org-backward-heading-same-level 1))
24319 ;; When current headline has no sibling above, move to its
24320 ;; parent.
24321 (when (= (point) origin)
24322 (or (org-with-limited-levels (org-up-heading-safe))
24323 (progn (goto-char origin)
24324 (user-error "Cannot move further up"))))))
24326 (let* ((elem (org-element-at-point))
24327 (beg (org-element-property :begin elem)))
24328 (cond
24329 ;; Move to beginning of current element if point isn't
24330 ;; there already.
24331 ((null beg) (message "No element at point"))
24332 ((/= (point) beg) (goto-char beg))
24333 (t (goto-char beg)
24334 (skip-chars-backward " \r\t\n")
24335 (unless (bobp)
24336 (let ((prev (org-element-at-point)))
24337 (goto-char (org-element-property :begin prev))
24338 (while (and (setq prev (org-element-property :parent prev))
24339 (<= (org-element-property :end prev) beg))
24340 (goto-char (org-element-property :begin prev)))))))))))
24342 (defun org-up-element ()
24343 "Move to upper element."
24344 (interactive)
24345 (if (org-with-limited-levels (org-at-heading-p))
24346 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24347 (let* ((elem (org-element-at-point))
24348 (parent (org-element-property :parent elem)))
24349 (if parent (goto-char (org-element-property :begin parent))
24350 (if (org-with-limited-levels (org-before-first-heading-p))
24351 (user-error "No surrounding element")
24352 (org-with-limited-levels (org-back-to-heading)))))))
24354 (defun org-down-element ()
24355 "Move to inner element."
24356 (interactive)
24357 (let ((element (org-element-at-point)))
24358 (cond
24359 ((memq (org-element-type element) '(plain-list table))
24360 (goto-char (org-element-property :contents-begin element))
24361 (forward-char))
24362 ((memq (org-element-type element) org-element-greater-elements)
24363 ;; If contents are hidden, first disclose them.
24364 (when (org-invisible-p (line-end-position)) (org-cycle))
24365 (goto-char (or (org-element-property :contents-begin element)
24366 (user-error "No content for this element"))))
24367 (t (user-error "No inner element")))))
24369 (defun org-drag-element-backward ()
24370 "Move backward element at point."
24371 (interactive)
24372 (let ((elem (or (org-element-at-point)
24373 (user-error "No element at point"))))
24374 (if (eq (org-element-type elem) 'headline)
24375 ;; Preserve point when moving a whole tree, even if point was
24376 ;; on blank lines below the headline.
24377 (let ((offset (skip-chars-backward " \t\n")))
24378 (unwind-protect (org-move-subtree-up)
24379 (forward-char (- offset))))
24380 (let ((prev-elem
24381 (save-excursion
24382 (goto-char (org-element-property :begin elem))
24383 (skip-chars-backward " \r\t\n")
24384 (unless (bobp)
24385 (let* ((beg (org-element-property :begin elem))
24386 (prev (org-element-at-point))
24387 (up prev))
24388 (while (and (setq up (org-element-property :parent up))
24389 (<= (org-element-property :end up) beg))
24390 (setq prev up))
24391 prev)))))
24392 ;; Error out if no previous element or previous element is
24393 ;; a parent of the current one.
24394 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24395 (user-error "Cannot drag element backward")
24396 (let ((pos (point)))
24397 (org-element-swap-A-B prev-elem elem)
24398 (goto-char (+ (org-element-property :begin prev-elem)
24399 (- pos (org-element-property :begin elem))))))))))
24401 (defun org-drag-element-forward ()
24402 "Move forward element at point."
24403 (interactive)
24404 (let* ((pos (point))
24405 (elem (or (org-element-at-point)
24406 (user-error "No element at point"))))
24407 (when (= (point-max) (org-element-property :end elem))
24408 (user-error "Cannot drag element forward"))
24409 (goto-char (org-element-property :end elem))
24410 (let ((next-elem (org-element-at-point)))
24411 (when (or (org-element-nested-p elem next-elem)
24412 (and (eq (org-element-type next-elem) 'headline)
24413 (not (eq (org-element-type elem) 'headline))))
24414 (goto-char pos)
24415 (user-error "Cannot drag element forward"))
24416 ;; Compute new position of point: it's shifted by NEXT-ELEM
24417 ;; body's length (without final blanks) and by the length of
24418 ;; blanks between ELEM and NEXT-ELEM.
24419 (let ((size-next (- (save-excursion
24420 (goto-char (org-element-property :end next-elem))
24421 (skip-chars-backward " \r\t\n")
24422 (forward-line)
24423 ;; Small correction if buffer doesn't end
24424 ;; with a newline character.
24425 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24426 (org-element-property :begin next-elem)))
24427 (size-blank (- (org-element-property :end elem)
24428 (save-excursion
24429 (goto-char (org-element-property :end elem))
24430 (skip-chars-backward " \r\t\n")
24431 (forward-line)
24432 (point)))))
24433 (org-element-swap-A-B elem next-elem)
24434 (goto-char (+ pos size-next size-blank))))))
24436 (defun org-drag-line-forward (arg)
24437 "Drag the line at point ARG lines forward."
24438 (interactive "p")
24439 (dotimes (_ (abs arg))
24440 (let ((c (current-column)))
24441 (if (< 0 arg)
24442 (progn
24443 (beginning-of-line 2)
24444 (transpose-lines 1)
24445 (beginning-of-line 0))
24446 (transpose-lines 1)
24447 (beginning-of-line -1))
24448 (org-move-to-column c))))
24450 (defun org-drag-line-backward (arg)
24451 "Drag the line at point ARG lines backward."
24452 (interactive "p")
24453 (org-drag-line-forward (- arg)))
24455 (defun org-mark-element ()
24456 "Put point at beginning of this element, mark at end.
24458 Interactively, if this command is repeated or (in Transient Mark
24459 mode) if the mark is active, it marks the next element after the
24460 ones already marked."
24461 (interactive)
24462 (let (deactivate-mark)
24463 (if (and (called-interactively-p 'any)
24464 (or (and (eq last-command this-command) (mark t))
24465 (and transient-mark-mode mark-active)))
24466 (set-mark
24467 (save-excursion
24468 (goto-char (mark))
24469 (goto-char (org-element-property :end (org-element-at-point)))))
24470 (let ((element (org-element-at-point)))
24471 (end-of-line)
24472 (push-mark (org-element-property :end element) t t)
24473 (goto-char (org-element-property :begin element))))))
24475 (defun org-narrow-to-element ()
24476 "Narrow buffer to current element."
24477 (interactive)
24478 (let ((elem (org-element-at-point)))
24479 (cond
24480 ((eq (car elem) 'headline)
24481 (narrow-to-region
24482 (org-element-property :begin elem)
24483 (org-element-property :end elem)))
24484 ((memq (car elem) org-element-greater-elements)
24485 (narrow-to-region
24486 (org-element-property :contents-begin elem)
24487 (org-element-property :contents-end elem)))
24489 (narrow-to-region
24490 (org-element-property :begin elem)
24491 (org-element-property :end elem))))))
24493 (defun org-transpose-element ()
24494 "Transpose current and previous elements, keeping blank lines between.
24495 Point is moved after both elements."
24496 (interactive)
24497 (org-skip-whitespace)
24498 (let ((end (org-element-property :end (org-element-at-point))))
24499 (org-drag-element-backward)
24500 (goto-char end)))
24502 (defun org-unindent-buffer ()
24503 "Un-indent the visible part of the buffer.
24504 Relative indentation (between items, inside blocks, etc.) isn't
24505 modified."
24506 (interactive)
24507 (unless (eq major-mode 'org-mode)
24508 (user-error "Cannot un-indent a buffer not in Org mode"))
24509 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24510 (unindent-tree
24511 (lambda (contents)
24512 (dolist (element (reverse contents))
24513 (if (memq (org-element-type element) '(headline section))
24514 (funcall unindent-tree (org-element-contents element))
24515 (save-excursion
24516 (save-restriction
24517 (narrow-to-region
24518 (org-element-property :begin element)
24519 (org-element-property :end element))
24520 (org-do-remove-indentation))))))))
24521 (funcall unindent-tree (org-element-contents parse-tree))))
24523 (defun org-show-children (&optional level)
24524 "Show all direct subheadings of this heading.
24525 Prefix arg LEVEL is how many levels below the current level
24526 should be shown. Default is enough to cause the following
24527 heading to appear."
24528 (interactive "p")
24529 ;; If `orgstruct-mode' is active, use the slower version.
24530 (if orgstruct-mode (call-interactively #'outline-show-children)
24531 (save-excursion
24532 (org-back-to-heading t)
24533 (let* ((current-level (funcall outline-level))
24534 (max-level (org-get-valid-level
24535 current-level
24536 (if level (prefix-numeric-value level) 1)))
24537 (end (save-excursion (org-end-of-subtree t t)))
24538 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24539 (past-first-child nil)
24540 ;; Make sure to skip inlinetasks.
24541 (re (format regexp-fmt
24542 current-level
24543 (cond
24544 ((not (featurep 'org-inlinetask)) "")
24545 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24547 (t (1- org-inlinetask-min-level))))))
24548 ;; Display parent heading.
24549 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24550 (forward-line)
24551 ;; Display children. First child may be deeper than expected
24552 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24553 ;; MAX-LEVEL accordingly.
24554 (while (re-search-forward re end t)
24555 (unless past-first-child
24556 (setq re (format regexp-fmt
24557 current-level
24558 (max (funcall outline-level) max-level)))
24559 (setq past-first-child t))
24560 (outline-flag-region
24561 (line-end-position 0) (line-end-position) nil))))))
24563 (defun org-show-subtree ()
24564 "Show everything after this heading at deeper levels."
24565 (interactive)
24566 (outline-flag-region
24567 (point)
24568 (save-excursion
24569 (org-end-of-subtree t t))
24570 nil))
24572 (defun org-show-entry ()
24573 "Show the body directly following this heading.
24574 Show the heading too, if it is currently invisible."
24575 (interactive)
24576 (save-excursion
24577 (ignore-errors
24578 (org-back-to-heading t)
24579 (outline-flag-region
24580 (max (point-min) (1- (point)))
24581 (save-excursion
24582 (if (re-search-forward
24583 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24584 (match-beginning 1)
24585 (point-max)))
24586 nil)
24587 (org-cycle-hide-drawers 'children))))
24589 (defun org-make-options-regexp (kwds &optional extra)
24590 "Make a regular expression for keyword lines.
24591 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24592 when non-nil, is a regexp matching keywords names."
24593 (concat "^[ \t]*#\\+\\("
24594 (regexp-opt kwds)
24595 (and extra (concat (and kwds "\\|") extra))
24596 "\\):[ \t]*\\(.*\\)"))
24598 ;;;; Integration with and fixes for other packages
24600 ;;; Imenu support
24602 (defvar-local org-imenu-markers nil
24603 "All markers currently used by Imenu.")
24605 (defun org-imenu-new-marker (&optional pos)
24606 "Return a new marker for use by Imenu, and remember the marker."
24607 (let ((m (make-marker)))
24608 (move-marker m (or pos (point)))
24609 (push m org-imenu-markers)
24612 (defun org-imenu-get-tree ()
24613 "Produce the index for Imenu."
24614 (dolist (x org-imenu-markers) (move-marker x nil))
24615 (setq org-imenu-markers nil)
24616 (let* ((case-fold-search nil)
24617 (n org-imenu-depth)
24618 (re (concat "^" (org-get-limited-outline-regexp)))
24619 (subs (make-vector (1+ n) nil))
24620 (last-level 0)
24621 m level head0 head)
24622 (org-with-wide-buffer
24623 (goto-char (point-max))
24624 (while (re-search-backward re nil t)
24625 (setq level (org-reduced-level (funcall outline-level)))
24626 (when (and (<= level n)
24627 (looking-at org-complex-heading-regexp)
24628 (setq head0 (match-string-no-properties 4)))
24629 (setq head (org-link-display-format head0)
24630 m (org-imenu-new-marker))
24631 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24632 (if (>= level last-level)
24633 (push (cons head m) (aref subs level))
24634 (push (cons head (aref subs (1+ level))) (aref subs level))
24635 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24636 (setq last-level level))))
24637 (aref subs 1)))
24639 (eval-after-load "imenu"
24640 '(progn
24641 (add-hook 'imenu-after-jump-hook
24642 (lambda ()
24643 (when (derived-mode-p 'org-mode)
24644 (org-show-context 'org-goto))))))
24646 (defun org-link-display-format (s)
24647 "Replace links in string S with their description.
24648 If there is no description, use the link target."
24649 (save-match-data
24650 (replace-regexp-in-string
24651 org-bracket-link-analytic-regexp
24652 (lambda (m)
24653 (if (match-end 5) (match-string 5 m)
24654 (concat (match-string 1 m) (match-string 3 m))))
24655 s nil t)))
24657 (defun org-toggle-link-display ()
24658 "Toggle the literal or descriptive display of links."
24659 (interactive)
24660 (if org-descriptive-links
24661 (progn (org-remove-from-invisibility-spec '(org-link))
24662 (org-restart-font-lock)
24663 (setq org-descriptive-links nil))
24664 (progn (add-to-invisibility-spec '(org-link))
24665 (org-restart-font-lock)
24666 (setq org-descriptive-links t))))
24668 ;; Speedbar support
24670 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24671 "Overlay marking the agenda restriction line in speedbar.")
24672 (overlay-put org-speedbar-restriction-lock-overlay
24673 'face 'org-agenda-restriction-lock)
24674 (overlay-put org-speedbar-restriction-lock-overlay
24675 'help-echo "Agendas are currently limited to this item.")
24676 (delete-overlay org-speedbar-restriction-lock-overlay)
24678 (defun org-speedbar-set-agenda-restriction ()
24679 "Restrict future agenda commands to the location at point in speedbar.
24680 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24681 (interactive)
24682 (require 'org-agenda)
24683 (let (p m tp np dir txt)
24684 (cond
24685 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24686 'org-imenu t))
24687 (setq m (get-text-property p 'org-imenu-marker))
24688 (with-current-buffer (marker-buffer m)
24689 (goto-char m)
24690 (org-agenda-set-restriction-lock 'subtree)))
24691 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24692 'speedbar-function 'speedbar-find-file))
24693 (setq tp (previous-single-property-change
24694 (1+ p) 'speedbar-function)
24695 np (next-single-property-change
24696 tp 'speedbar-function)
24697 dir (speedbar-line-directory)
24698 txt (buffer-substring-no-properties (or tp (point-min))
24699 (or np (point-max))))
24700 (with-current-buffer (find-file-noselect
24701 (let ((default-directory dir))
24702 (expand-file-name txt)))
24703 (unless (derived-mode-p 'org-mode)
24704 (user-error "Cannot restrict to non-Org mode file"))
24705 (org-agenda-set-restriction-lock 'file)))
24706 (t (user-error "Don't know how to restrict Org mode agenda")))
24707 (move-overlay org-speedbar-restriction-lock-overlay
24708 (point-at-bol) (point-at-eol))
24709 (setq current-prefix-arg nil)
24710 (org-agenda-maybe-redo)))
24712 (defvar speedbar-file-key-map)
24713 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24714 (eval-after-load "speedbar"
24715 '(progn
24716 (speedbar-add-supported-extension ".org")
24717 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24718 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24719 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24720 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24721 (add-hook 'speedbar-visiting-tag-hook
24722 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24724 ;;; Fixes and Hacks for problems with other packages
24726 (defun org--flyspell-object-check-p (element)
24727 "Non-nil when Flyspell can check object at point.
24728 ELEMENT is the element at point."
24729 (let ((object (save-excursion
24730 (when (looking-at-p "\\>") (backward-char))
24731 (org-element-context element))))
24732 (cl-case (org-element-type object)
24733 ;; Prevent checks in links due to keybinding conflict with
24734 ;; Flyspell.
24735 ((code entity export-snippet inline-babel-call
24736 inline-src-block line-break latex-fragment link macro
24737 statistics-cookie target timestamp verbatim)
24738 nil)
24739 (footnote-reference
24740 ;; Only in inline footnotes, within the definition.
24741 (and (eq (org-element-property :type object) 'inline)
24742 (< (save-excursion
24743 (goto-char (org-element-property :begin object))
24744 (search-forward ":" nil t 2))
24745 (point))))
24746 (otherwise t))))
24748 (defun org-mode-flyspell-verify ()
24749 "Function used for `flyspell-generic-check-word-predicate'."
24750 (if (org-at-heading-p)
24751 ;; At a headline or an inlinetask, check title only. This is
24752 ;; faster than relying on `org-element-at-point'.
24753 (and (save-excursion (beginning-of-line)
24754 (and (let ((case-fold-search t))
24755 (not (looking-at-p "\\*+ END[ \t]*$")))
24756 (let ((case-fold-search nil))
24757 (looking-at org-complex-heading-regexp))))
24758 (match-beginning 4)
24759 (>= (point) (match-beginning 4))
24760 (or (not (match-beginning 5))
24761 (< (point) (match-beginning 5))))
24762 (let* ((element (org-element-at-point))
24763 (post-affiliated (org-element-property :post-affiliated element)))
24764 (cond
24765 ;; Ignore checks in all affiliated keywords but captions.
24766 ((< (point) post-affiliated)
24767 (and (save-excursion
24768 (beginning-of-line)
24769 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24770 (> (point) (match-end 0))
24771 (org--flyspell-object-check-p element)))
24772 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24773 ((let ((log (org-log-into-drawer)))
24774 (and log
24775 (let ((drawer (org-element-lineage element '(drawer))))
24776 (and drawer
24777 (eq (compare-strings
24778 log nil nil
24779 (org-element-property :drawer-name drawer) nil nil t)
24780 t)))))
24781 nil)
24783 (cl-case (org-element-type element)
24784 ((comment quote-section) t)
24785 (comment-block
24786 ;; Allow checks between block markers, not on them.
24787 (and (> (line-beginning-position) post-affiliated)
24788 (save-excursion
24789 (end-of-line)
24790 (skip-chars-forward " \r\t\n")
24791 (< (point) (org-element-property :end element)))))
24792 ;; Arbitrary list of keywords where checks are meaningful.
24793 ;; Make sure point is on the value part of the element.
24794 (keyword
24795 (and (member (org-element-property :key element)
24796 '("DESCRIPTION" "TITLE"))
24797 (save-excursion
24798 (search-backward ":" (line-beginning-position) t))))
24799 ;; Check is globally allowed in paragraphs verse blocks and
24800 ;; table rows (after affiliated keywords) but some objects
24801 ;; must not be affected.
24802 ((paragraph table-row verse-block)
24803 (let ((cbeg (org-element-property :contents-begin element))
24804 (cend (org-element-property :contents-end element)))
24805 (and cbeg (>= (point) cbeg) (< (point) cend)
24806 (org--flyspell-object-check-p element))))))))))
24807 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24809 (defun org-remove-flyspell-overlays-in (beg end)
24810 "Remove flyspell overlays in region."
24811 (and (bound-and-true-p flyspell-mode)
24812 (fboundp 'flyspell-delete-region-overlays)
24813 (flyspell-delete-region-overlays beg end)))
24815 (defvar flyspell-delayed-commands)
24816 (eval-after-load "flyspell"
24817 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24819 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24820 (eval-after-load "bookmark"
24821 '(if (boundp 'bookmark-after-jump-hook)
24822 ;; We can use the hook
24823 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24824 ;; Hook not available, use advice
24825 (defadvice bookmark-jump (after org-make-visible activate)
24826 "Make the position visible."
24827 (org-bookmark-jump-unhide))))
24829 ;; Make sure saveplace shows the location if it was hidden
24830 (eval-after-load "saveplace"
24831 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24832 "Make the position visible."
24833 (org-bookmark-jump-unhide)))
24835 ;; Make sure ecb shows the location if it was hidden
24836 (eval-after-load "ecb"
24837 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24838 "Make hierarchy visible when jumping into location from ECB tree buffer."
24839 (when (derived-mode-p 'org-mode)
24840 (org-show-context))))
24842 (defun org-bookmark-jump-unhide ()
24843 "Unhide the current position, to show the bookmark location."
24844 (and (derived-mode-p 'org-mode)
24845 (or (org-invisible-p)
24846 (save-excursion (goto-char (max (point-min) (1- (point))))
24847 (org-invisible-p)))
24848 (org-show-context 'bookmark-jump)))
24850 (defun org-mark-jump-unhide ()
24851 "Make the point visible with `org-show-context' after jumping to the mark."
24852 (when (and (derived-mode-p 'org-mode)
24853 (org-invisible-p))
24854 (org-show-context 'mark-goto)))
24856 (eval-after-load "simple"
24857 '(defadvice pop-to-mark-command (after org-make-visible activate)
24858 "Make the point visible with `org-show-context'."
24859 (org-mark-jump-unhide)))
24861 (eval-after-load "simple"
24862 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24863 "Make the point visible with `org-show-context'."
24864 (org-mark-jump-unhide)))
24866 (eval-after-load "simple"
24867 '(defadvice pop-global-mark (after org-make-visible activate)
24868 "Make the point visible with `org-show-context'."
24869 (org-mark-jump-unhide)))
24871 ;; Make session.el ignore our circular variable
24872 (defvar session-globals-exclude)
24873 (eval-after-load "session"
24874 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24876 ;;;; Finish up
24878 (provide 'org)
24880 (run-hooks 'org-load-hook)
24882 ;;; org.el ends here