Use ‘eq’ instead of ‘equal’ for symbols
[org-mode.git] / lisp / org.el
blob71013eec957a5190165feba0f9f8b476bc1aaae7
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-2016 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"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (defsubst org-uniquify (list)
176 "Non-destructively remove duplicate elements from LIST."
177 (let ((res (copy-sequence list))) (delete-dups res)))
179 (defsubst org-get-at-bol (property)
180 "Get text property PROPERTY at the beginning of line."
181 (get-text-property (point-at-bol) property))
183 (defsubst org-trim (s &optional keep-lead)
184 "Remove whitespace at the beginning and the end of string S.
185 When optional argument KEEP-LEAD is non-nil, removing blank lines
186 at the beginning of the string does not affect leading indentation."
187 (replace-regexp-in-string
188 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
189 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
191 ;; load languages based on value of `org-babel-load-languages'
192 (defvar org-babel-load-languages)
194 ;;;###autoload
195 (defun org-babel-do-load-languages (sym value)
196 "Load the languages defined in `org-babel-load-languages'."
197 (set-default sym value)
198 (dolist (pair org-babel-load-languages)
199 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
200 (if active
201 (require (intern (concat "ob-" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-execute:" lang)))
204 (funcall 'fmakunbound
205 (intern (concat "org-babel-expand-body:" lang)))))))
207 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
208 ;;;###autoload
209 (defun org-babel-load-file (file &optional compile)
210 "Load Emacs Lisp source code blocks in the Org FILE.
211 This function exports the source code using `org-babel-tangle'
212 and then loads the resulting file using `load-file'. With prefix
213 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
214 file to byte-code before it is loaded."
215 (interactive "fFile to load: \nP")
216 (let* ((age (lambda (file)
217 (float-time
218 (time-subtract (current-time)
219 (nth 5 (or (file-attributes (file-truename file))
220 (file-attributes file)))))))
221 (base-name (file-name-sans-extension file))
222 (exported-file (concat base-name ".el")))
223 ;; tangle if the Org file is newer than the elisp file
224 (unless (and (file-exists-p exported-file)
225 (> (funcall age file) (funcall age exported-file)))
226 ;; Tangle-file traversal returns reversed list of tangled files
227 ;; and we want to evaluate the first target.
228 (setq exported-file
229 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
230 (message "%s %s"
231 (if compile
232 (progn (byte-compile-file exported-file 'load)
233 "Compiled and loaded")
234 (progn (load-file exported-file) "Loaded"))
235 exported-file)))
237 (defcustom org-babel-load-languages '((emacs-lisp . t))
238 "Languages which can be evaluated in Org buffers.
239 This list can be used to load support for any of the languages
240 below, note that each language will depend on a different set of
241 system executables and/or Emacs modes. When a language is
242 \"loaded\", then code blocks in that language can be evaluated
243 with `org-babel-execute-src-block' bound by default to C-c
244 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
245 be set to remove code block evaluation from the C-c C-c
246 keybinding. By default only Emacs Lisp (which has no
247 requirements) is loaded."
248 :group 'org-babel
249 :set 'org-babel-do-load-languages
250 :version "24.1"
251 :type '(alist :tag "Babel Languages"
252 :key-type
253 (choice
254 (const :tag "Awk" awk)
255 (const :tag "C" C)
256 (const :tag "R" R)
257 (const :tag "Asymptote" asymptote)
258 (const :tag "Calc" calc)
259 (const :tag "Clojure" clojure)
260 (const :tag "CSS" css)
261 (const :tag "Ditaa" ditaa)
262 (const :tag "Dot" dot)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "ebnf2ps" ebnf2ps))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org-mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 A deadline is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-deadline].")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 A schedule is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-schedule].")
385 (defconst org-ds-keyword-length
386 (+ 2
387 (apply #'max
388 (mapcar #'length
389 (list org-deadline-string org-scheduled-string
390 org-clock-string org-closed-string))))
391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
393 (defconst org-planning-line-re
394 (concat "^[ \t]*"
395 (regexp-opt
396 (list org-closed-string org-deadline-string org-scheduled-string)
398 "Matches a line with planning info.
399 Matched keyword is in group 1.")
401 (defconst org-clock-line-re
402 (concat "^[ \t]*" org-clock-string)
403 "Matches a line with clock info.")
405 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
406 "Matches the DEADLINE keyword.")
408 (defconst org-deadline-time-regexp
409 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
410 "Matches the DEADLINE keyword together with a time stamp.")
412 (defconst org-deadline-time-hour-regexp
413 (concat "\\<" org-deadline-string
414 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
415 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
417 (defconst org-deadline-line-regexp
418 (concat "\\<\\(" org-deadline-string "\\).*")
419 "Matches the DEADLINE keyword and the rest of the line.")
421 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
422 "Matches the SCHEDULED keyword.")
424 (defconst org-scheduled-time-regexp
425 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
426 "Matches the SCHEDULED keyword together with a time stamp.")
428 (defconst org-scheduled-time-hour-regexp
429 (concat "\\<" org-scheduled-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
433 (defconst org-closed-time-regexp
434 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
435 "Matches the CLOSED keyword together with a time stamp.")
437 (defconst org-keyword-time-regexp
438 (concat "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string
441 org-clock-string)
443 " *[[<]\\([^]>]+\\)[]>]")
444 "Matches any of the 4 keywords, together with the time stamp.")
446 (defconst org-keyword-time-not-clock-regexp
447 (concat
448 "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string) t)
451 " *[[<]\\([^]>]+\\)[]>]")
452 "Matches any of the 3 keywords, together with the time stamp.")
454 (defconst org-maybe-keyword-time-regexp
455 (concat "\\(\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string
458 org-clock-string)
460 "\\)?"
461 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
462 "\\|"
463 "<%%([^\r\n>]*>\\)")
464 "Matches a timestamp, possibly preceded by a keyword.")
466 (defconst org-all-time-keywords
467 (mapcar (lambda (w) (substring w 0 -1))
468 (list org-scheduled-string org-deadline-string
469 org-clock-string org-closed-string))
470 "List of time keywords.")
472 ;;;; Drawer
474 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
475 "Matches first or last line of a hidden block.
476 Group 1 contains drawer's name or \"END\".")
478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
479 "Regular expression matching the first line of a property drawer.")
481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a property drawer.")
484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
485 "Regular expression matching the first line of a clock drawer.")
487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a clock drawer.")
490 (defconst org-property-drawer-re
491 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
492 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
493 "[ \t]*:END:[ \t]*$")
494 "Matches an entire property drawer.")
496 (defconst org-clock-drawer-re
497 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
498 org-clock-drawer-end-re "\\)\n?")
499 "Matches an entire clock drawer.")
501 ;;;; Headline
503 (defconst org-heading-keyword-regexp-format
504 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
505 "Printf format for a regexp matching a headline with some keyword.
506 This regexp will match the headline of any node which has the
507 exact keyword that is put into the format. The keyword isn't in
508 any group by default, but the stars and the body are.")
510 (defconst org-heading-keyword-maybe-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline, possibly with some keyword.
513 This regexp can match any headline with the specified keyword, or
514 without a keyword. The keyword isn't in any group by default,
515 but the stars and the body are.")
517 (defconst org-archive-tag "ARCHIVE"
518 "The tag that marks a subtree as archived.
519 An archived subtree does not open during visibility cycling, and does
520 not contribute to the agenda listings.")
522 (defconst org-comment-string "COMMENT"
523 "Entries starting with this keyword will never be exported.
524 An entry can be toggled between COMMENT and normal with
525 \\[org-toggle-comment].")
528 ;;;; LaTeX Environments and Fragments
530 (defconst org-latex-regexps
531 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
532 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
533 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
534 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
535 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
536 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
537 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
538 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
539 "Regular expressions for matching embedded LaTeX.")
541 ;;;; Node Property
543 (defconst org-effort-property "Effort"
544 "The property that is being used to keep track of effort estimates.
545 Effort estimates given in this property need to have the format H:MM.")
547 ;;;; Table
549 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
550 "Detect an org-type or table-type table.")
552 (defconst org-table-line-regexp "^[ \t]*|"
553 "Detect an org-type table line.")
555 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
556 "Detect an org-type table line.")
558 (defconst org-table-hline-regexp "^[ \t]*|-"
559 "Detect an org-type table hline.")
561 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
562 "Detect a table-type table hline.")
564 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
565 "Detect the first line outside a table when searching from within it.
566 This works for both table types.")
568 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
569 "Detect a #+TBLFM line.")
571 ;;;; Timestamp
573 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
574 "Regular expression for fast time stamp matching.")
576 (defconst org-ts-regexp-inactive
577 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
578 "Regular expression for fast inactive time stamp matching.")
580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp0
584 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
585 "Regular expression matching time strings for analysis.
586 This one does not require the space after the date, so it can be used
587 on a string that terminates immediately after the date.")
589 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.")
592 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
593 "Regular expression matching time stamps, with groups.")
595 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
596 "Regular expression matching time stamps (also [..]), with groups.")
598 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tr-regexp-both
602 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
606 org-ts-regexp "\\)?")
607 "Regular expression matching a time stamp or time stamp range.")
609 (defconst org-tsr-regexp-both
610 (concat org-ts-regexp-both "\\(--?-?"
611 org-ts-regexp-both "\\)?")
612 "Regular expression matching a time stamp or time stamp range.
613 The time stamps may be either active or inactive.")
615 (defconst org-repeat-re
616 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
617 "Regular expression for specifying repeated events.
618 After a match, group 1 contains the repeat expression.")
620 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
621 "Formats for `format-time-string' which are used for time stamps.")
624 ;;; The custom variables
626 (defgroup org nil
627 "Outline-based notes management and organizer."
628 :tag "Org"
629 :group 'outlines
630 :group 'calendar)
632 (defcustom org-mode-hook nil
633 "Mode hook for Org-mode, run after the mode was turned on."
634 :group 'org
635 :type 'hook)
637 (defcustom org-load-hook nil
638 "Hook that is run after org.el has been loaded."
639 :group 'org
640 :type 'hook)
642 (defcustom org-log-buffer-setup-hook nil
643 "Hook that is run after an Org log buffer is created."
644 :group 'org
645 :version "24.1"
646 :type 'hook)
648 (defvar org-modules) ; defined below
649 (defvar org-modules-loaded nil
650 "Have the modules been loaded already?")
652 (defun org-load-modules-maybe (&optional force)
653 "Load all extensions listed in `org-modules'."
654 (when (or force (not org-modules-loaded))
655 (dolist (ext org-modules)
656 (condition-case nil (require ext)
657 (error (message "Problems while trying to load feature `%s'" ext))))
658 (setq org-modules-loaded t)))
660 (defun org-set-modules (var value)
661 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
662 (set var value)
663 (when (featurep 'org)
664 (org-load-modules-maybe 'force)
665 (org-element-cache-reset 'all)))
667 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
668 "Modules that should always be loaded together with org.el.
670 If a description starts with <C>, the file is not part of Emacs
671 and loading it will require that you have downloaded and properly
672 installed the Org mode distribution.
674 You can also use this system to load external packages (i.e. neither Org
675 core modules, nor modules from the CONTRIB directory). Just add symbols
676 to the end of the list. If the package is called org-xyz.el, then you need
677 to add the symbol `xyz', and the package must have a call to:
679 (provide \\='org-xyz)
681 For export specific modules, see also `org-export-backends'."
682 :group 'org
683 :set 'org-set-modules
684 :version "24.4"
685 :package-version '(Org . "8.0")
686 :type
687 '(set :greedy t
688 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
689 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
690 (const :tag " crypt: Encryption of subtrees" org-crypt)
691 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
692 (const :tag " docview: Links to doc-view buffers" org-docview)
693 (const :tag " eww: Store link to url of eww" org-eww)
694 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
695 (const :tag " habit: Track your consistency with habits" org-habit)
696 (const :tag " id: Global IDs for identifying entries" org-id)
697 (const :tag " info: Links to Info nodes" org-info)
698 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
699 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
700 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
701 (const :tag " mouse: Additional mouse support" org-mouse)
702 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
703 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
704 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
706 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
707 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
708 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
709 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
710 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
711 (const :tag "C collector: Collect properties into tables" org-collector)
712 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
713 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
714 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
715 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
716 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
717 (const :tag "C eval: Include command output as text" org-eval)
718 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
719 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
720 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
721 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
722 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
723 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
724 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
725 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
726 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
727 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
728 (const :tag "C mew: Links to Mew folders/messages" org-mew)
729 (const :tag "C mtags: Support for muse-like tags" org-mtags)
730 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
731 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
732 (const :tag "C registry: A registry for Org links" org-registry)
733 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
734 (const :tag "C secretary: Team management with org-mode" org-secretary)
735 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
736 (const :tag "C toc: Table of contents for Org buffer" org-toc)
737 (const :tag "C track: Keep up with Org mode development" org-track)
738 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
739 (const :tag "C vm: Links to VM folders/messages" org-vm)
740 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
741 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
742 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
744 (defvar org-export-registered-backends) ; From ox.el.
745 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
746 (declare-function org-export-backend-name "ox" (backend) t)
747 (defcustom org-export-backends '(ascii html icalendar latex odt)
748 "List of export back-ends that should be always available.
750 If a description starts with <C>, the file is not part of Emacs
751 and loading it will require that you have downloaded and properly
752 installed the Org mode distribution.
754 Unlike to `org-modules', libraries in this list will not be
755 loaded along with Org, but only once the export framework is
756 needed.
758 This variable needs to be set before org.el is loaded. If you
759 need to make a change while Emacs is running, use the customize
760 interface or run the following code, where VAL stands for the new
761 value of the variable, after updating it:
763 (progn
764 (setq org-export-registered-backends
765 (cl-remove-if-not
766 (lambda (backend)
767 (let ((name (org-export-backend-name backend)))
768 (or (memq name val)
769 (catch \\='parentp
770 (dolist (b val)
771 (and (org-export-derived-backend-p b name)
772 (throw \\='parentp t)))))))
773 org-export-registered-backends))
774 (let ((new-list (mapcar #\\='org-export-backend-name
775 org-export-registered-backends)))
776 (dolist (backend val)
777 (cond
778 ((not (load (format \"ox-%s\" backend) t t))
779 (message \"Problems while trying to load export back-end \\=`%s\\='\"
780 backend))
781 ((not (memq backend new-list)) (push backend new-list))))
782 (set-default \\='org-export-backends new-list)))
784 Adding a back-end to this list will also pull the back-end it
785 depends on, if any."
786 :group 'org
787 :group 'org-export
788 :version "25.1"
789 :package-version '(Org . "9.0")
790 :initialize 'custom-initialize-set
791 :set (lambda (var val)
792 (if (not (featurep 'ox)) (set-default var val)
793 ;; Any back-end not required anymore (not present in VAL and not
794 ;; a parent of any back-end in the new value) is removed from the
795 ;; list of registered back-ends.
796 (setq org-export-registered-backends
797 (cl-remove-if-not
798 (lambda (backend)
799 (let ((name (org-export-backend-name backend)))
800 (or (memq name val)
801 (catch 'parentp
802 (dolist (b val)
803 (and (org-export-derived-backend-p b name)
804 (throw 'parentp t)))))))
805 org-export-registered-backends))
806 ;; Now build NEW-LIST of both new back-ends and required
807 ;; parents.
808 (let ((new-list (mapcar #'org-export-backend-name
809 org-export-registered-backends)))
810 (dolist (backend val)
811 (cond
812 ((not (load (format "ox-%s" backend) t t))
813 (message "Problems while trying to load export back-end `%s'"
814 backend))
815 ((not (memq backend new-list)) (push backend new-list))))
816 ;; Set VAR to that list with fixed dependencies.
817 (set-default var new-list))))
818 :type '(set :greedy t
819 (const :tag " ascii Export buffer to ASCII format" ascii)
820 (const :tag " beamer Export buffer to Beamer presentation" beamer)
821 (const :tag " html Export buffer to HTML format" html)
822 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
823 (const :tag " latex Export buffer to LaTeX format" latex)
824 (const :tag " man Export buffer to MAN format" man)
825 (const :tag " md Export buffer to Markdown format" md)
826 (const :tag " odt Export buffer to ODT format" odt)
827 (const :tag " org Export buffer to Org format" org)
828 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
829 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
830 (const :tag "C deck Export buffer to deck.js presentations" deck)
831 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
832 (const :tag "C groff Export buffer to Groff format" groff)
833 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
834 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
835 (const :tag "C s5 Export buffer to s5 presentations" s5)
836 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
838 (eval-after-load 'ox
839 '(dolist (backend org-export-backends)
840 (condition-case nil (require (intern (format "ox-%s" backend)))
841 (error (message "Problems while trying to load export back-end `%s'"
842 backend)))))
844 (defcustom org-support-shift-select nil
845 "Non-nil means make shift-cursor commands select text when possible.
846 \\<org-mode-map>\
848 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
849 start selecting a region, or enlarge regions started in this way.
850 In Org-mode, in special contexts, these same keys are used for
851 other purposes, important enough to compete with shift selection.
852 Org tries to balance these needs by supporting `shift-select-mode'
853 outside these special contexts, under control of this variable.
855 The default of this variable is nil, to avoid confusing behavior. Shifted
856 cursor keys will then execute Org commands in the following contexts:
857 - on a headline, changing TODO state (left/right) and priority (up/down)
858 - on a time stamp, changing the time
859 - in a plain list item, changing the bullet type
860 - in a property definition line, switching between allowed values
861 - in the BEGIN line of a clock table (changing the time block).
862 Outside these contexts, the commands will throw an error.
864 When this variable is t and the cursor is not in a special
865 context, Org mode will support shift-selection for making and
866 enlarging regions. To make this more effective, the bullet
867 cycling will no longer happen anywhere in an item line, but only
868 if the cursor is exactly on the bullet.
870 If you set this variable to the symbol `always', then the keys
871 will not be special in headlines, property lines, and item lines,
872 to make shift selection work there as well. If this is what you
873 want, you can use the following alternative commands:
874 `\\[org-todo]' and `\\[org-priority]' \
875 to change TODO state and priority,
876 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
877 can be used to switch TODO sets,
878 `\\[org-ctrl-c-minus]' to cycle item bullet types,
879 and properties can be edited by hand or in column view.
881 However, when the cursor is on a timestamp, shift-cursor commands
882 will still edit the time stamp - this is just too good to give up."
883 :group 'org
884 :type '(choice
885 (const :tag "Never" nil)
886 (const :tag "When outside special context" t)
887 (const :tag "Everywhere except timestamps" always)))
889 (defcustom org-loop-over-headlines-in-active-region nil
890 "Shall some commands act upon headlines in the active region?
892 When set to t, some commands will be performed in all headlines
893 within the active region.
895 When set to `start-level', some commands will be performed in all
896 headlines within the active region, provided that these headlines
897 are of the same level than the first one.
899 When set to a string, those commands will be performed on the
900 matching headlines within the active region. Such string must be
901 a tags/property/todo match as it is used in the agenda tags view.
903 The list of commands is: `org-schedule', `org-deadline',
904 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
905 `org-archive-to-archive-sibling'. The archiving commands skip
906 already archived entries."
907 :type '(choice (const :tag "Don't loop" nil)
908 (const :tag "All headlines in active region" t)
909 (const :tag "In active region, headlines at the same level than the first one" start-level)
910 (string :tag "Tags/Property/Todo matcher"))
911 :version "24.1"
912 :group 'org-todo
913 :group 'org-archive)
915 (defgroup org-startup nil
916 "Options concerning startup of Org-mode."
917 :tag "Org Startup"
918 :group 'org)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
922 This can also be configured on a per-file basis by adding one of
923 the following lines anywhere in the buffer:
925 #+STARTUP: fold (or `overview', this is equivalent)
926 #+STARTUP: nofold (or `showall', this is equivalent)
927 #+STARTUP: content
928 #+STARTUP: showeverything
930 By default, this option is ignored when Org opens agenda files
931 for the first time. If you want the agenda to honor the startup
932 option, set `org-agenda-inhibit-startup' to nil."
933 :group 'org-startup
934 :type '(choice
935 (const :tag "nofold: show all" nil)
936 (const :tag "fold: overview" t)
937 (const :tag "content: all headlines" content)
938 (const :tag "show everything, even drawers" showeverything)))
940 (defcustom org-startup-truncated t
941 "Non-nil means entering Org mode will set `truncate-lines'.
942 This is useful since some lines containing links can be very long and
943 uninteresting. Also tables look terrible when wrapped.
945 The variable `org-startup-truncated' allows to configure
946 truncation for Org mode different to the other modes that use the
947 variable `truncate-lines' and as a shortcut instead of putting
948 the variable `truncate-lines' into the `org-mode-hook'. If one
949 wants to configure truncation for Org mode not statically but
950 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
951 the variable `truncate-lines' has to be used because in such a
952 case it is too late to set the variable `org-startup-truncated'."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org mode.
1048 To ensure that the file will always be in Org mode in the future, a
1049 line enforcing Org mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org mode together with one of these other modes,
1060 or more generally if you would like to move some Org mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org-mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if `window-system' is nil. This
1073 variable lets you do the same manually. You must set it before
1074 loading Org."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1080 (defcustom org-disputed-keys
1081 '(([(shift up)] . [(meta p)])
1082 ([(shift down)] . [(meta n)])
1083 ([(shift left)] . [(meta -)])
1084 ([(shift right)] . [(meta +)])
1085 ([(control shift right)] . [(meta shift +)])
1086 ([(control shift left)] . [(meta shift -)]))
1087 "Keys for which Org mode and other modes compete.
1088 This is an alist, cars are the default keys, second element specifies
1089 the alternative to use when `org-replace-disputed-keys' is t.
1091 Keys can be specified in any syntax supported by `define-key'.
1092 The value of this option takes effect only at Org-mode's startup,
1093 therefore you'll have to restart Emacs to apply it after changing."
1094 :group 'org-startup
1095 :type 'alist)
1097 (defun org-key (key)
1098 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1099 Or return the original if not disputed."
1100 (when org-replace-disputed-keys
1101 (let* ((nkey (key-description key))
1102 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1103 org-disputed-keys)))
1104 (setq key (if x (cdr x) key))))
1105 key)
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org-mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((agenda . local)
1151 (bookmark-jump . lineage)
1152 (isearch . lineage)
1153 (default . ancestors))
1154 "Alist between context and visibility span when revealing a location.
1156 \\<org-mode-map>Some actions may move point into invisible
1157 locations. As a consequence, Org always expose a neighborhood
1158 around point. How much is shown depends on the initial action,
1159 or context. Valid contexts are
1161 agenda when exposing an entry from the agenda
1162 org-goto when using the command `org-goto' (\\[org-goto])
1163 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1164 tags-tree when constructing a sparse tree based on tags matches
1165 link-search when exposing search matches associated with a link
1166 mark-goto when exposing the jump goal of a mark
1167 bookmark-jump when exposing a bookmark location
1168 isearch when exiting from an incremental search
1169 default default for all contexts not set explicitly
1171 Allowed visibility spans are
1173 minimal show current headline; if point is not on headline,
1174 also show entry
1176 local show current headline, entry and next headline
1178 ancestors show current headline and its direct ancestors; if
1179 point is not on headline, also show entry
1181 lineage show current headline, its direct ancestors and all
1182 their children; if point is not on headline, also show
1183 entry and first child
1185 tree show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and all children
1189 canonical show current headline, its direct ancestors along with
1190 their entries and children; if point is not located on
1191 the headline, also show current entry and all children
1193 As special cases, a nil or t value means show all contexts in
1194 `minimal' or `canonical' view, respectively.
1196 Some views can make displayed information very compact, but also
1197 make it harder to edit the location of the match. In such
1198 a case, use the command `org-reveal' (\\[org-reveal]) to show
1199 more context."
1200 :group 'org-reveal-location
1201 :version "25.2"
1202 :package-version '(Org . "9.0")
1203 :type '(choice
1204 (const :tag "Canonical" t)
1205 (const :tag "Minimal" nil)
1206 (repeat :greedy t :tag "Individual contexts"
1207 (cons
1208 (choice :tag "Context"
1209 (const agenda)
1210 (const org-goto)
1211 (const occur-tree)
1212 (const tags-tree)
1213 (const link-search)
1214 (const mark-goto)
1215 (const bookmark-jump)
1216 (const isearch)
1217 (const default))
1218 (choice :tag "Detail level"
1219 (const minimal)
1220 (const local)
1221 (const ancestors)
1222 (const lineage)
1223 (const tree)
1224 (const canonical))))))
1226 (defcustom org-indirect-buffer-display 'other-window
1227 "How should indirect tree buffers be displayed?
1228 This applies to indirect buffers created with the commands
1229 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1230 Valid values are:
1231 current-window Display in the current window
1232 other-window Just display in another window.
1233 dedicated-frame Create one new frame, and re-use it each time.
1234 new-frame Make a new frame each time. Note that in this case
1235 previously-made indirect buffers are kept, and you need to
1236 kill these buffers yourself."
1237 :group 'org-structure
1238 :group 'org-agenda-windows
1239 :type '(choice
1240 (const :tag "In current window" current-window)
1241 (const :tag "In current frame, other window" other-window)
1242 (const :tag "Each time a new frame" new-frame)
1243 (const :tag "One dedicated frame" dedicated-frame)))
1245 (defcustom org-use-speed-commands nil
1246 "Non-nil means activate single letter commands at beginning of a headline.
1247 This may also be a function to test for appropriate locations where speed
1248 commands should be active.
1250 For example, to activate speed commands when the point is on any
1251 star at the beginning of the headline, you can do this:
1253 (setq org-use-speed-commands
1254 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1255 :group 'org-structure
1256 :type '(choice
1257 (const :tag "Never" nil)
1258 (const :tag "At beginning of headline stars" t)
1259 (function)))
1261 (defcustom org-speed-commands-user nil
1262 "Alist of additional speed commands.
1263 This list will be checked before `org-speed-commands-default'
1264 when the variable `org-use-speed-commands' is non-nil
1265 and when the cursor is at the beginning of a headline.
1266 The car if each entry is a string with a single letter, which must
1267 be assigned to `self-insert-command' in the global map.
1268 The cdr is either a command to be called interactively, a function
1269 to be called, or a form to be evaluated.
1270 An entry that is just a list with a single string will be interpreted
1271 as a descriptive headline that will be added when listing the speed
1272 commands in the Help buffer using the `?' speed command."
1273 :group 'org-structure
1274 :type '(repeat :value ("k" . ignore)
1275 (choice :value ("k" . ignore)
1276 (list :tag "Descriptive Headline" (string :tag "Headline"))
1277 (cons :tag "Letter and Command"
1278 (string :tag "Command letter")
1279 (choice
1280 (function)
1281 (sexp))))))
1283 (defcustom org-bookmark-names-plist
1284 '(:last-capture "org-capture-last-stored"
1285 :last-refile "org-refile-last-stored"
1286 :last-capture-marker "org-capture-last-stored-marker")
1287 "Names for bookmarks automatically set by some Org commands.
1288 This can provide strings as names for a number of bookmarks Org sets
1289 automatically. The following keys are currently implemented:
1290 :last-capture
1291 :last-capture-marker
1292 :last-refile
1293 When a key does not show up in the property list, the corresponding bookmark
1294 is not set."
1295 :group 'org-structure
1296 :type 'plist)
1298 (defgroup org-cycle nil
1299 "Options concerning visibility cycling in Org-mode."
1300 :tag "Org Cycle"
1301 :group 'org-structure)
1303 (defcustom org-cycle-skip-children-state-if-no-children t
1304 "Non-nil means skip CHILDREN state in entries that don't have any."
1305 :group 'org-cycle
1306 :type 'boolean)
1308 (defcustom org-cycle-max-level nil
1309 "Maximum level which should still be subject to visibility cycling.
1310 Levels higher than this will, for cycling, be treated as text, not a headline.
1311 When `org-odd-levels-only' is set, a value of N in this variable actually
1312 means 2N-1 stars as the limiting headline.
1313 When nil, cycle all levels.
1314 Note that the limiting level of cycling is also influenced by
1315 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1316 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1317 than its value."
1318 :group 'org-cycle
1319 :type '(choice
1320 (const :tag "No limit" nil)
1321 (integer :tag "Maximum level")))
1323 (defcustom org-hide-block-startup nil
1324 "Non-nil means entering Org mode will fold all blocks.
1325 This can also be set in on a per-file basis with
1327 #+STARTUP: hideblocks
1328 #+STARTUP: showblocks"
1329 :group 'org-startup
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-global-at-bob nil
1334 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1335 This makes it possible to do global cycling without having to use S-TAB or
1336 \\[universal-argument] TAB. For this special case to work, the first line
1337 of the buffer must not be a headline -- it may be empty or some other text.
1338 When used in this way, `org-cycle-hook' is disabled temporarily to make
1339 sure the cursor stays at the beginning of the buffer. When this option is
1340 nil, don't do anything special at the beginning of the buffer."
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-level-after-item/entry-creation t
1345 "Non-nil means cycle entry level or item indentation in new empty entries.
1347 When the cursor is at the end of an empty headline, i.e., with only stars
1348 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1349 and then all possible ancestor states, before returning to the original state.
1350 This makes data entry extremely fast: M-RET to create a new headline,
1351 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1353 When the cursor is at the end of an empty plain list item, one TAB will
1354 make it a subitem, two or more tabs will back up to make this an item
1355 higher up in the item hierarchy."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-emulate-tab t
1360 "Where should `org-cycle' emulate TAB.
1361 nil Never
1362 white Only in completely white lines
1363 whitestart Only at the beginning of lines, before the first non-white char
1364 t Everywhere except in headlines
1365 exc-hl-bol Everywhere except at the start of a headline
1366 If TAB is used in a place where it does not emulate TAB, the current subtree
1367 visibility is cycled."
1368 :group 'org-cycle
1369 :type '(choice (const :tag "Never" nil)
1370 (const :tag "Only in completely white lines" white)
1371 (const :tag "Before first char in a line" whitestart)
1372 (const :tag "Everywhere except in headlines" t)
1373 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1375 (defcustom org-cycle-separator-lines 2
1376 "Number of empty lines needed to keep an empty line between collapsed trees.
1377 If you leave an empty line between the end of a subtree and the following
1378 headline, this empty line is hidden when the subtree is folded.
1379 Org mode will leave (exactly) one empty line visible if the number of
1380 empty lines is equal or larger to the number given in this variable.
1381 So the default 2 means at least 2 empty lines after the end of a subtree
1382 are needed to produce free space between a collapsed subtree and the
1383 following headline.
1385 If the number is negative, and the number of empty lines is at least -N,
1386 all empty lines are shown.
1388 Special case: when 0, never leave empty lines in collapsed view."
1389 :group 'org-cycle
1390 :type 'integer)
1391 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1393 (defcustom org-pre-cycle-hook nil
1394 "Hook that is run before visibility cycling is happening.
1395 The function(s) in this hook must accept a single argument which indicates
1396 the new state that will be set right after running this hook. The
1397 argument is a symbol. Before a global state change, it can have the values
1398 `overview', `content', or `all'. Before a local state change, it can have
1399 the values `folded', `children', or `subtree'."
1400 :group 'org-cycle
1401 :type 'hook)
1403 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1404 org-cycle-hide-drawers
1405 org-cycle-show-empty-lines
1406 org-optimize-window-after-visibility-change)
1407 "Hook that is run after `org-cycle' has changed the buffer visibility.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that was set by the most recent `org-cycle' command. The
1410 argument is a symbol. After a global state change, it can have the values
1411 `overview', `contents', or `all'. After a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook
1415 :version "25.1"
1416 :package-version '(Org . "8.3"))
1418 (defgroup org-edit-structure nil
1419 "Options concerning structure editing in Org-mode."
1420 :tag "Org Edit Structure"
1421 :group 'org-structure)
1423 (defcustom org-odd-levels-only nil
1424 "Non-nil means skip even levels and only use odd levels for the outline.
1425 This has the effect that two stars are being added/taken away in
1426 promotion/demotion commands. It also influences how levels are
1427 handled by the exporters.
1428 Changing it requires restart of `font-lock-mode' to become effective
1429 for fontification also in regions already fontified.
1430 You may also set this on a per-file basis by adding one of the following
1431 lines to the buffer:
1433 #+STARTUP: odd
1434 #+STARTUP: oddeven"
1435 :group 'org-edit-structure
1436 :group 'org-appearance
1437 :type 'boolean)
1439 (defcustom org-adapt-indentation t
1440 "Non-nil means adapt indentation to outline node level.
1442 When this variable is set, Org assumes that you write outlines by
1443 indenting text in each node to align with the headline (after the
1444 stars). The following issues are influenced by this variable:
1446 - The indentation is increased by one space in a demotion
1447 command, and decreased by one in a promotion command. However,
1448 in the latter case, if shifting some line in the entry body
1449 would alter document structure (e.g., insert a new headline),
1450 indentation is not changed at all.
1452 - Property drawers and planning information is inserted indented
1453 when this variable is set. When nil, they will not be indented.
1455 - TAB indents a line relative to current level. The lines below
1456 a headline will be indented when this variable is set.
1458 Note that this is all about true indentation, by adding and
1459 removing space characters. See also `org-indent.el' which does
1460 level-dependent indentation in a virtual way, i.e. at display
1461 time in Emacs."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-special-ctrl-a/e nil
1466 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1468 When t, `C-a' will bring back the cursor to the beginning of the
1469 headline text, i.e. after the stars and after a possible TODO
1470 keyword. In an item, this will be the position after bullet and
1471 check-box, if any. When the cursor is already at that position,
1472 another `C-a' will bring it to the beginning of the line.
1474 `C-e' will jump to the end of the headline, ignoring the presence
1475 of tags in the headline. A second `C-e' will then jump to the
1476 true end of the line, after any tags. This also means that, when
1477 this variable is non-nil, `C-e' also will never jump beyond the
1478 end of the heading of a folded section, i.e. not after the
1479 ellipses.
1481 When set to the symbol `reversed', the first `C-a' or `C-e' works
1482 normally, going to the true line boundary first. Only a directly
1483 following, identical keypress will bring the cursor to the
1484 special positions.
1486 This may also be a cons cell where the behavior for `C-a' and
1487 `C-e' is set separately."
1488 :group 'org-edit-structure
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on: after stars/bullet and before tags first" t)
1492 (const :tag "reversed: true line boundary first" reversed)
1493 (cons :tag "Set C-a and C-e separately"
1494 (choice :tag "Special C-a"
1495 (const :tag "off" nil)
1496 (const :tag "on: after stars/bullet first" t)
1497 (const :tag "reversed: before stars/bullet first" reversed))
1498 (choice :tag "Special C-e"
1499 (const :tag "off" nil)
1500 (const :tag "on: before tags first" t)
1501 (const :tag "reversed: after tags first" reversed)))))
1502 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1504 (defcustom org-special-ctrl-k nil
1505 "Non-nil means `C-k' will behave specially in headlines.
1506 When nil, `C-k' will call the default `kill-line' command.
1507 When t, the following will happen while the cursor is in the headline:
1509 - When the cursor is at the beginning of a headline, kill the entire
1510 line and possible the folded subtree below the line.
1511 - When in the middle of the headline text, kill the headline up to the tags.
1512 - When after the headline text, kill the tags."
1513 :group 'org-edit-structure
1514 :type 'boolean)
1516 (defcustom org-ctrl-k-protect-subtree nil
1517 "Non-nil means, do not delete a hidden subtree with C-k.
1518 When set to the symbol `error', simply throw an error when C-k is
1519 used to kill (part-of) a headline that has hidden text behind it.
1520 Any other non-nil value will result in a query to the user, if it is
1521 OK to kill that hidden subtree. When nil, kill without remorse."
1522 :group 'org-edit-structure
1523 :version "24.1"
1524 :type '(choice
1525 (const :tag "Do not protect hidden subtrees" nil)
1526 (const :tag "Protect hidden subtrees with a security query" t)
1527 (const :tag "Never kill a hidden subtree with C-k" error)))
1529 (defcustom org-special-ctrl-o t
1530 "Non-nil means, make `C-o' insert a row in tables."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-catch-invisible-edits nil
1535 "Check if in invisible region before inserting or deleting a character.
1536 Valid values are:
1538 nil Do not check, so just do invisible edits.
1539 error Throw an error and do nothing.
1540 show Make point visible, and do the requested edit.
1541 show-and-error Make point visible, then throw an error and abort the edit.
1542 smart Make point visible, and do insertion/deletion if it is
1543 adjacent to visible text and the change feels predictable.
1544 Never delete a previously invisible character or add in the
1545 middle or right after an invisible region. Basically, this
1546 allows insertion and backward-delete right before ellipses.
1547 FIXME: maybe in this case we should not even show?"
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not check" nil)
1552 (const :tag "Throw error when trying to edit" error)
1553 (const :tag "Unhide, but do not do the edit" show-and-error)
1554 (const :tag "Show invisible part and do the edit" show)
1555 (const :tag "Be smart and do the right thing" smart)))
1557 (defcustom org-yank-folded-subtrees t
1558 "Non-nil means when yanking subtrees, fold them.
1559 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1560 it starts with a heading and all other headings in it are either children
1561 or siblings, then fold all the subtrees. However, do this only if no
1562 text after the yank would be swallowed into a folded tree by this action."
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defcustom org-yank-adjusted-subtrees nil
1567 "Non-nil means when yanking subtrees, adjust the level.
1568 With this setting, `org-paste-subtree' is used to insert the subtree, see
1569 this function for details."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-M-RET-may-split-line '((default . t))
1574 "Non-nil means M-RET will split the line at the cursor position.
1575 When nil, it will go to the end of the line before making a
1576 new line.
1577 You may also set this option in a different way for different
1578 contexts. Valid contexts are:
1580 headline when creating a new headline
1581 item when creating a new item
1582 table in a table field
1583 default the value to be used for all contexts not explicitly
1584 customized"
1585 :group 'org-structure
1586 :group 'org-table
1587 :type '(choice
1588 (const :tag "Always" t)
1589 (const :tag "Never" nil)
1590 (repeat :greedy t :tag "Individual contexts"
1591 (cons
1592 (choice :tag "Context"
1593 (const headline)
1594 (const item)
1595 (const table)
1596 (const default))
1597 (boolean)))))
1600 (defcustom org-insert-heading-respect-content nil
1601 "Non-nil means insert new headings after the current subtree.
1602 When nil, the new heading is created directly after the current line.
1603 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1604 this variable on for the duration of the command."
1605 :group 'org-structure
1606 :type 'boolean)
1608 (defcustom org-blank-before-new-entry '((heading . auto)
1609 (plain-list-item . auto))
1610 "Should `org-insert-heading' leave a blank line before new heading/item?
1611 The value is an alist, with `heading' and `plain-list-item' as CAR,
1612 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1613 which case Org will look at the surrounding headings/items and try to
1614 make an intelligent decision whether to insert a blank line or not."
1615 :group 'org-edit-structure
1616 :type '(list
1617 (cons (const heading)
1618 (choice (const :tag "Never" nil)
1619 (const :tag "Always" t)
1620 (const :tag "Auto" auto)))
1621 (cons (const plain-list-item)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))))
1626 (defcustom org-insert-heading-hook nil
1627 "Hook being run after inserting a new heading."
1628 :group 'org-edit-structure
1629 :type 'hook)
1631 (defcustom org-enable-fixed-width-editor t
1632 "Non-nil means lines starting with \":\" are treated as fixed-width.
1633 This currently only means they are never auto-wrapped.
1634 When nil, such lines will be treated like ordinary lines."
1635 :group 'org-edit-structure
1636 :type 'boolean)
1638 (defcustom org-goto-auto-isearch t
1639 "Non-nil means typing characters in `org-goto' starts incremental search.
1640 When nil, you can use these keybindings to navigate the buffer:
1642 q Quit the org-goto interface
1643 n Go to the next visible heading
1644 p Go to the previous visible heading
1645 f Go one heading forward on same level
1646 b Go one heading backward on same level
1647 u Go one heading up"
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defgroup org-sparse-trees nil
1652 "Options concerning sparse trees in Org-mode."
1653 :tag "Org Sparse Trees"
1654 :group 'org-structure)
1656 (defcustom org-highlight-sparse-tree-matches t
1657 "Non-nil means highlight all matches that define a sparse tree.
1658 The highlights will automatically disappear the next time the buffer is
1659 changed by an edit command."
1660 :group 'org-sparse-trees
1661 :type 'boolean)
1663 (defcustom org-remove-highlights-with-change t
1664 "Non-nil means any change to the buffer will remove temporary highlights.
1665 \\<org-mode-map>\
1666 Such highlights are created by `org-occur' and `org-clock-display'.
1667 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1668 to get rid of the highlights.
1669 The highlights created by `org-toggle-latex-fragment' always need
1670 `\\[org-toggle-latex-fragment]' to be removed."
1671 :group 'org-sparse-trees
1672 :group 'org-time
1673 :type 'boolean)
1675 (defcustom org-occur-case-fold-search t
1676 "Non-nil means `org-occur' should be case-insensitive.
1677 If set to `smart' the search will be case-insensitive only if it
1678 doesn't specify any upper case character."
1679 :group 'org-sparse-trees
1680 :version "25.1"
1681 :type '(choice
1682 (const :tag "Case-sensitive" nil)
1683 (const :tag "Case-insensitive" t)
1684 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1686 (defcustom org-occur-hook '(org-first-headline-recenter)
1687 "Hook that is run after `org-occur' has constructed a sparse tree.
1688 This can be used to recenter the window to show as much of the structure
1689 as possible."
1690 :group 'org-sparse-trees
1691 :type 'hook)
1693 (defgroup org-imenu-and-speedbar nil
1694 "Options concerning imenu and speedbar in Org-mode."
1695 :tag "Org Imenu and Speedbar"
1696 :group 'org-structure)
1698 (defcustom org-imenu-depth 2
1699 "The maximum level for Imenu access to Org headlines.
1700 This also applied for speedbar access."
1701 :group 'org-imenu-and-speedbar
1702 :type 'integer)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org-mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-enable-table-editor 'optimized
1710 "Non-nil means lines starting with \"|\" are handled by the table editor.
1711 When nil, such lines will be treated like ordinary lines.
1713 When equal to the symbol `optimized', the table editor will be optimized to
1714 do the following:
1715 - Automatic overwrite mode in front of whitespace in table fields.
1716 This makes the structure of the table stay in tact as long as the edited
1717 field does not exceed the column width.
1718 - Minimize the number of realigns. Normally, the table is aligned each time
1719 TAB or RET are pressed to move to another field. With optimization this
1720 happens only if changes to a field might have changed the column width.
1721 Optimization requires replacing the functions `self-insert-command',
1722 `delete-char', and `backward-delete-char' in Org buffers, with a
1723 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1724 good at guessing when a re-align will be necessary, but you can always
1725 force one with \\[org-ctrl-c-ctrl-c].
1727 If you would like to use the optimized version in Org-mode, but the
1728 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1730 This variable can be used to turn on and off the table editor during a session,
1731 but in order to toggle optimization, a restart is required.
1733 See also the variable `org-table-auto-blank-field'."
1734 :group 'org-table
1735 :type '(choice
1736 (const :tag "off" nil)
1737 (const :tag "on" t)
1738 (const :tag "on, optimized" optimized)))
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org-mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-parameters
1765 '(("doi" :follow org--open-doi-link)
1766 ("elisp" :follow org--open-elisp-link)
1767 ("file" :complete org-file-complete-link)
1768 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1769 ("help" :follow org--open-help-link)
1770 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1771 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1772 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1773 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1774 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1775 ("shell" :follow org--open-shell-link))
1776 "An alist of properties that defines all the links in Org mode.
1777 The key in each association is a string of the link type.
1778 Subsequent optional elements make up a p-list of link properties.
1780 :follow - A function that takes the link path as an argument.
1782 :export - A function that takes the link path, description and
1783 export-backend as arguments.
1785 :store - A function responsible for storing the link. See the
1786 function `org-store-link-functions'.
1788 :complete - A function that inserts a link with completion. The
1789 function takes one optional prefix arg.
1791 :face - A face for the link, or a function that returns a face.
1792 The function takes one argument which is the link path. The
1793 default face is `org-link'.
1795 :mouse-face - The mouse-face. The default is `highlight'.
1797 :display - `full' will not fold the link in descriptive
1798 display. Default is `org-link'.
1800 :help-echo - A string or function that takes (window object position)
1801 as arguments and returns a string.
1803 :keymap - A keymap that is active on the link. The default is
1804 `org-mouse-map'.
1806 :htmlize-link - A function for the htmlize-link. Defaults
1807 to (list :uri \"type:path\")
1809 :activate-func - A function to run at the end of font-lock
1810 activation. The function must accept (link-start link-end path bracketp)
1811 as arguments."
1812 :group 'org-link
1813 :type '(alist :tag "Link display parameters"
1814 :value-type plist))
1816 (defun org-link-get-parameter (type key)
1817 "Get TYPE link property for KEY.
1818 TYPE is a string and KEY is a plist keyword."
1819 (plist-get
1820 (cdr (assoc type org-link-parameters))
1821 key))
1823 (defun org-link-set-parameters (type &rest parameters)
1824 "Set link TYPE properties to PARAMETERS.
1825 PARAMETERS should be :key val pairs."
1826 (let ((data (assoc type org-link-parameters)))
1827 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1828 (push (cons type parameters) org-link-parameters)
1829 (org-make-link-regexps)
1830 (org-element-update-syntax))))
1832 (defun org-link-types ()
1833 "Return a list of known link types."
1834 (mapcar #'car org-link-parameters))
1836 (defcustom org-link-abbrev-alist nil
1837 "Alist of link abbreviations.
1838 The car of each element is a string, to be replaced at the start of a link.
1839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1840 links in Org buffers can have an optional tag after a double colon, e.g.,
1842 [[linkkey:tag][description]]
1844 The `linkkey' must be a single word, starting with a letter, followed
1845 by letters, numbers, `-' or `_'.
1847 If REPLACE is a string, the tag will simply be appended to create the link.
1848 If the string contains \"%s\", the tag will be inserted there. If the string
1849 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1850 at that point (see the function `url-hexify-string'). If the string contains
1851 the specifier \"%(my-function)\", then the custom function `my-function' will
1852 be invoked: this function takes the tag as its only argument and must return
1853 a string.
1855 REPLACE may also be a function that will be called with the tag as the
1856 only argument to create the link, which should be returned as a string.
1858 See the manual for examples."
1859 :group 'org-link
1860 :type '(repeat
1861 (cons
1862 (string :tag "Protocol")
1863 (choice
1864 (string :tag "Format")
1865 (function)))))
1867 (defcustom org-descriptive-links t
1868 "Non-nil means Org will display descriptive links.
1869 E.g. [[http://orgmode.org][Org website]] will be displayed as
1870 \"Org Website\", hiding the link itself and just displaying its
1871 description. When set to nil, Org will display the full links
1872 literally.
1874 You can interactively set the value of this variable by calling
1875 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1876 :group 'org-link
1877 :type 'boolean)
1879 (defcustom org-link-file-path-type 'adaptive
1880 "How the path name in file links should be stored.
1881 Valid values are:
1883 relative Relative to the current directory, i.e. the directory of the file
1884 into which the link is being inserted.
1885 absolute Absolute path, if possible with ~ for home directory.
1886 noabbrev Absolute path, no abbreviation of home directory.
1887 adaptive Use relative path for files in the current directory and sub-
1888 directories of it. For other files, use an absolute path."
1889 :group 'org-link
1890 :type '(choice
1891 (const relative)
1892 (const absolute)
1893 (const noabbrev)
1894 (const adaptive)))
1896 (defvaralias 'org-activate-links 'org-highlight-links)
1897 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1898 "Types of links that should be highlighted in Org files.
1900 This is a list of symbols, each one of them leading to the
1901 highlighting of a certain link type.
1903 You can still open links that are not highlighted.
1905 In principle, it does not hurt to turn on highlighting for all
1906 link types. There may be a small gain when turning off unused
1907 link types. The types are:
1909 bracket The recommended [[link][description]] or [[link]] links with hiding.
1910 angle Links in angular brackets that may contain whitespace like
1911 <bbdb:Carsten Dominik>.
1912 plain Plain links in normal text, no whitespace, like http://google.com.
1913 radio Text that is matched by a radio target, see manual for details.
1914 tag Tag settings in a headline (link to tag search).
1915 date Time stamps (link to calendar).
1916 footnote Footnote labels.
1918 If you set this variable during an Emacs session, use `org-mode-restart'
1919 in the Org buffer so that the change takes effect."
1920 :group 'org-link
1921 :group 'org-appearance
1922 :type '(set :greedy t
1923 (const :tag "Double bracket links" bracket)
1924 (const :tag "Angular bracket links" angle)
1925 (const :tag "Plain text links" plain)
1926 (const :tag "Radio target matches" radio)
1927 (const :tag "Tags" tag)
1928 (const :tag "Timestamps" date)
1929 (const :tag "Footnotes" footnote)))
1931 (defcustom org-make-link-description-function nil
1932 "Function to use for generating link descriptions from links.
1933 When nil, the link location will be used. This function must take
1934 two parameters: the first one is the link, the second one is the
1935 description generated by `org-insert-link'. The function should
1936 return the description to use."
1937 :group 'org-link
1938 :type '(choice (const nil) (function)))
1940 (defgroup org-link-store nil
1941 "Options concerning storing links in Org-mode."
1942 :tag "Org Store Link"
1943 :group 'org-link)
1945 (defcustom org-url-hexify-p t
1946 "When non-nil, hexify URL when creating a link."
1947 :type 'boolean
1948 :version "24.3"
1949 :group 'org-link-store)
1951 (defcustom org-email-link-description-format "Email %c: %.30s"
1952 "Format of the description part of a link to an email or usenet message.
1953 The following %-escapes will be replaced by corresponding information:
1955 %F full \"From\" field
1956 %f name, taken from \"From\" field, address if no name
1957 %T full \"To\" field
1958 %t first name in \"To\" field, address if no name
1959 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1960 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1961 %s subject
1962 %d date
1963 %m message-id.
1965 You may use normal field width specification between the % and the letter.
1966 This is for example useful to limit the length of the subject.
1968 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1969 :group 'org-link-store
1970 :type 'string)
1972 (defcustom org-from-is-user-regexp
1973 (let (r1 r2)
1974 (when (and user-mail-address (not (string= user-mail-address "")))
1975 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1976 (when (and user-full-name (not (string= user-full-name "")))
1977 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1978 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1979 "Regexp matched against the \"From:\" header of an email or usenet message.
1980 It should match if the message is from the user him/herself."
1981 :group 'org-link-store
1982 :type 'regexp)
1984 (defcustom org-context-in-file-links t
1985 "Non-nil means file links from `org-store-link' contain context.
1986 A search string will be added to the file name with :: as separator and
1987 used to find the context when the link is activated by the command
1988 `org-open-at-point'. When this option is t, the entire active region
1989 will be placed in the search string of the file link. If set to a
1990 positive integer, only the first n lines of context will be stored.
1992 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links). When this option
2004 is nil, every link which has been inserted once using \\[org-insert-link]
2005 will be removed from the list, to make completing the unused links
2006 more efficient."
2007 :group 'org-link-store
2008 :type 'boolean)
2010 (defgroup org-link-follow nil
2011 "Options concerning following links in Org-mode."
2012 :tag "Org Follow Link"
2013 :group 'org-link)
2015 (defcustom org-link-translation-function nil
2016 "Function to translate links with different syntax to Org syntax.
2017 This can be used to translate links created for example by the Planner
2018 or emacs-wiki packages to Org syntax.
2019 The function must accept two parameters, a TYPE containing the link
2020 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2021 which is everything after the link protocol. It should return a cons
2022 with possibly modified values of type and path.
2023 Org contains a function for this, so if you set this variable to
2024 `org-translate-link-from-planner', you should be able follow many
2025 links created by planner."
2026 :group 'org-link-follow
2027 :type '(choice (const nil) (function)))
2029 (defcustom org-follow-link-hook nil
2030 "Hook that is run after a link has been followed."
2031 :group 'org-link-follow
2032 :type 'hook)
2034 (defcustom org-tab-follows-link nil
2035 "Non-nil means on links TAB will follow the link.
2036 Needs to be set before org.el is loaded.
2037 This really should not be used, it does not make sense, and the
2038 implementation is bad."
2039 :group 'org-link-follow
2040 :type 'boolean)
2042 (defcustom org-return-follows-link nil
2043 "Non-nil means on links RET will follow the link.
2044 In tables, the special behavior of RET has precedence."
2045 :group 'org-link-follow
2046 :type 'boolean)
2048 (defcustom org-mouse-1-follows-link
2049 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2050 "Non-nil means mouse-1 on a link will follow the link.
2051 A longer mouse click will still set point. Needs to be set
2052 before org.el is loaded."
2053 :group 'org-link-follow
2054 :version "24.4"
2055 :package-version '(Org . "8.3")
2056 :type '(choice
2057 (const :tag "A double click follows the link" double)
2058 (const :tag "Unconditionally follow the link with mouse-1" t)
2059 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2061 (defcustom org-mark-ring-length 4
2062 "Number of different positions to be recorded in the ring.
2063 Changing this requires a restart of Emacs to work correctly."
2064 :group 'org-link-follow
2065 :type 'integer)
2067 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2068 "Non-nil means internal links in Org files must exactly match a headline.
2069 When nil, the link search tries to match a phrase with all words
2070 in the search text."
2071 :group 'org-link-follow
2072 :version "24.1"
2073 :type '(choice
2074 (const :tag "Use fuzzy text search" nil)
2075 (const :tag "Match only exact headline" t)
2076 (const :tag "Match exact headline or query to create it"
2077 query-to-create)))
2079 (defcustom org-link-frame-setup
2080 '((vm . vm-visit-folder-other-frame)
2081 (vm-imap . vm-visit-imap-folder-other-frame)
2082 (gnus . org-gnus-no-new-news)
2083 (file . find-file-other-window)
2084 (wl . wl-other-frame))
2085 "Setup the frame configuration for following links.
2086 When following a link with Emacs, it may often be useful to display
2087 this link in another window or frame. This variable can be used to
2088 set this up for the different types of links.
2089 For VM, use any of
2090 `vm-visit-folder'
2091 `vm-visit-folder-other-window'
2092 `vm-visit-folder-other-frame'
2093 For Gnus, use any of
2094 `gnus'
2095 `gnus-other-frame'
2096 `org-gnus-no-new-news'
2097 For FILE, use any of
2098 `find-file'
2099 `find-file-other-window'
2100 `find-file-other-frame'
2101 For Wanderlust use any of
2102 `wl'
2103 `wl-other-frame'
2104 For the calendar, use the variable `calendar-setup'.
2105 For BBDB, it is currently only possible to display the matches in
2106 another window."
2107 :group 'org-link-follow
2108 :type '(list
2109 (cons (const vm)
2110 (choice
2111 (const vm-visit-folder)
2112 (const vm-visit-folder-other-window)
2113 (const vm-visit-folder-other-frame)))
2114 (cons (const vm-imap)
2115 (choice
2116 (const vm-visit-imap-folder)
2117 (const vm-visit-imap-folder-other-window)
2118 (const vm-visit-imap-folder-other-frame)))
2119 (cons (const gnus)
2120 (choice
2121 (const gnus)
2122 (const gnus-other-frame)
2123 (const org-gnus-no-new-news)))
2124 (cons (const file)
2125 (choice
2126 (const find-file)
2127 (const find-file-other-window)
2128 (const find-file-other-frame)))
2129 (cons (const wl)
2130 (choice
2131 (const wl)
2132 (const wl-other-frame)))))
2134 (defcustom org-display-internal-link-with-indirect-buffer nil
2135 "Non-nil means use indirect buffer to display infile links.
2136 Activating internal links (from one location in a file to another location
2137 in the same file) normally just jumps to the location. When the link is
2138 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2139 is displayed in
2140 another window. When this option is set, the other window actually displays
2141 an indirect buffer clone of the current buffer, to avoid any visibility
2142 changes to the current buffer."
2143 :group 'org-link-follow
2144 :type 'boolean)
2146 (defcustom org-open-non-existing-files nil
2147 "Non-nil means `org-open-file' will open non-existing files.
2148 When nil, an error will be generated.
2149 This variable applies only to external applications because they
2150 might choke on non-existing files. If the link is to a file that
2151 will be opened in Emacs, the variable is ignored."
2152 :group 'org-link-follow
2153 :type 'boolean)
2155 (defcustom org-open-directory-means-index-dot-org nil
2156 "Non-nil means a link to a directory really means to index.org.
2157 When nil, following a directory link will run dired or open a finder/explorer
2158 window on that directory."
2159 :group 'org-link-follow
2160 :type 'boolean)
2162 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing shell links.
2164 Shell links can be dangerous: just think about a link
2166 [[shell:rm -rf ~/*][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-shell-link-not-regexp ""
2183 "A regexp to skip confirmation for shell links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2189 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2190 Elisp links can be dangerous: just think about a link
2192 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2194 This link would show up in your Org document as \"Google Search\",
2195 but really it would remove your entire home directory.
2196 Therefore we advise against setting this variable to nil.
2197 Just change it to `y-or-n-p' if you want to confirm with a
2198 single keystroke rather than having to type \"yes\"."
2199 :group 'org-link-follow
2200 :type '(choice
2201 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2202 (const :tag "with y-or-n (faster)" y-or-n-p)
2203 (const :tag "no confirmation (dangerous)" nil)))
2204 (put 'org-confirm-shell-link-function
2205 'safe-local-variable
2206 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2208 (defcustom org-confirm-elisp-link-not-regexp ""
2209 "A regexp to skip confirmation for Elisp links."
2210 :group 'org-link-follow
2211 :version "24.1"
2212 :type 'regexp)
2214 (defconst org-file-apps-defaults-gnu
2215 '((remote . emacs)
2216 (system . mailcap)
2217 (t . mailcap))
2218 "Default file applications on a UNIX or GNU/Linux system.
2219 See `org-file-apps'.")
2221 (defconst org-file-apps-defaults-macosx
2222 '((remote . emacs)
2223 (system . "open %s")
2224 ("ps.gz" . "gv %s")
2225 ("eps.gz" . "gv %s")
2226 ("dvi" . "xdvi %s")
2227 ("fig" . "xfig %s")
2228 (t . "open %s"))
2229 "Default file applications on a MacOS X system.
2230 The system \"open\" is known as a default, but we use X11 applications
2231 for some files for which the OS does not have a good default.
2232 See `org-file-apps'.")
2234 (defconst org-file-apps-defaults-windowsnt
2235 (list '(remote . emacs)
2236 (cons 'system (lambda (file _path)
2237 (with-no-warnings (w32-shell-execute "open" file))))
2238 (cons t (lambda (file _path)
2239 (with-no-warnings (w32-shell-execute "open" file)))))
2240 "Default file applications on a Windows NT system.
2241 The system \"open\" is used for most files.
2242 See `org-file-apps'.")
2244 (defcustom org-file-apps
2245 '((auto-mode . emacs)
2246 ("\\.mm\\'" . default)
2247 ("\\.x?html?\\'" . default)
2248 ("\\.pdf\\'" . default))
2249 "External applications for opening `file:path' items in a document.
2250 \\<org-mode-map>\
2252 Org mode uses system defaults for different file types, but
2253 you can use this variable to set the application for a given file
2254 extension. The entries in this list are cons cells where the car identifies
2255 files and the cdr the corresponding command.
2257 Possible values for the file identifier are:
2259 \"string\" A string as a file identifier can be interpreted in different
2260 ways, depending on its contents:
2262 - Alphanumeric characters only:
2263 Match links with this file extension.
2264 Example: (\"pdf\" . \"evince %s\")
2265 to open PDFs with evince.
2267 - Regular expression: Match links where the
2268 filename matches the regexp. If you want to
2269 use groups here, use shy groups.
2271 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2272 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2273 to open *.html and *.xhtml with firefox.
2275 - Regular expression which contains (non-shy) groups:
2276 Match links where the whole link, including \"::\", and
2277 anything after that, matches the regexp.
2278 In a custom command string, %1, %2, etc. are replaced with
2279 the parts of the link that were matched by the groups.
2280 For backwards compatibility, if a command string is given
2281 that does not use any of the group matches, this case is
2282 handled identically to the second one (i.e. match against
2283 file name only).
2284 In a custom function, you can access the group matches with
2285 \(match-string n link).
2287 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2288 \"evince -p %1 %s\")
2289 to open [[file:document.pdf::5]] with evince at page 5.
2291 `directory' Matches a directory
2292 `remote' Matches a remote file, accessible through tramp or efs.
2293 Remote files most likely should be visited through Emacs
2294 because external applications cannot handle such paths.
2295 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2296 so all files Emacs knows how to handle. Using this with
2297 command `emacs' will open most files in Emacs. Beware that this
2298 will also open html files inside Emacs, unless you add
2299 \(\"html\" . default) to the list as well.
2300 `system' The system command to open files, like `open' on Windows
2301 and Mac OS X, and mailcap under GNU/Linux. This is the command
2302 that will be selected if you call \\[org-open-at-point] with a double
2303 \\[universal-argument] \\[universal-argument] prefix.
2304 t Default for files not matched by any of the other options.
2306 Possible values for the command are:
2308 `emacs' The file will be visited by the current Emacs process.
2309 `default' Use the default application for this file type, which is the
2310 association for t in the list, most likely in the system-specific
2311 part. This can be used to overrule an unwanted setting in the
2312 system-specific variable.
2313 `system' Use the system command for opening files, like \"open\".
2314 This command is specified by the entry whose car is `system'.
2315 Most likely, the system-specific version of this variable
2316 does define this command, but you can overrule/replace it
2317 here.
2318 `mailcap' Use command specified in the mailcaps.
2319 string A command to be executed by a shell; %s will be replaced
2320 by the path to the file.
2321 function A Lisp function, which will be called with two arguments:
2322 the file path and the original link string, without the
2323 \"file:\" prefix.
2325 For more examples, see the system specific constants
2326 `org-file-apps-defaults-macosx'
2327 `org-file-apps-defaults-windowsnt'
2328 `org-file-apps-defaults-gnu'."
2329 :group 'org-link-follow
2330 :type '(repeat
2331 (cons (choice :value ""
2332 (string :tag "Extension")
2333 (const :tag "System command to open files" system)
2334 (const :tag "Default for unrecognized files" t)
2335 (const :tag "Remote file" remote)
2336 (const :tag "Links to a directory" directory)
2337 (const :tag "Any files that have Emacs modes"
2338 auto-mode))
2339 (choice :value ""
2340 (const :tag "Visit with Emacs" emacs)
2341 (const :tag "Use default" default)
2342 (const :tag "Use the system command" system)
2343 (string :tag "Command")
2344 (function :tag "Function")))))
2346 (defcustom org-doi-server-url "http://dx.doi.org/"
2347 "The URL of the DOI server."
2348 :type 'string
2349 :version "24.3"
2350 :group 'org-link-follow)
2352 (defgroup org-refile nil
2353 "Options concerning refiling entries in Org-mode."
2354 :tag "Org Refile"
2355 :group 'org)
2357 (defcustom org-directory "~/org"
2358 "Directory with Org files.
2359 This is just a default location to look for Org files. There is no need
2360 at all to put your files into this directory. It is used in the
2361 following situations:
2363 1. When a capture template specifies a target file that is not an
2364 absolute path. The path will then be interpreted relative to
2365 `org-directory'
2366 2. When the value of variable `org-agenda-files' is a single file, any
2367 relative paths in this file will be taken as relative to
2368 `org-directory'."
2369 :group 'org-refile
2370 :group 'org-capture
2371 :type 'directory)
2373 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2374 "Default target for storing notes.
2375 Used as a fall back file for org-capture.el, for templates that
2376 do not specify a target file."
2377 :group 'org-refile
2378 :group 'org-capture
2379 :type 'file)
2381 (defcustom org-goto-interface 'outline
2382 "The default interface to be used for `org-goto'.
2383 Allowed values are:
2384 outline The interface shows an outline of the relevant file
2385 and the correct heading is found by moving through
2386 the outline or by searching with incremental search.
2387 outline-path-completion Headlines in the current buffer are offered via
2388 completion. This is the interface also used by
2389 the refile command."
2390 :group 'org-refile
2391 :type '(choice
2392 (const :tag "Outline" outline)
2393 (const :tag "Outline-path-completion" outline-path-completion)))
2395 (defcustom org-goto-max-level 5
2396 "Maximum target level when running `org-goto' with refile interface."
2397 :group 'org-refile
2398 :type 'integer)
2400 (defcustom org-reverse-note-order nil
2401 "Non-nil means store new notes at the beginning of a file or entry.
2402 When nil, new notes will be filed to the end of a file or entry.
2403 This can also be a list with cons cells of regular expressions that
2404 are matched against file names, and values."
2405 :group 'org-capture
2406 :group 'org-refile
2407 :type '(choice
2408 (const :tag "Reverse always" t)
2409 (const :tag "Reverse never" nil)
2410 (repeat :tag "By file name regexp"
2411 (cons regexp boolean))))
2413 (defcustom org-log-refile nil
2414 "Information to record when a task is refiled.
2416 Possible values are:
2418 nil Don't add anything
2419 time Add a time stamp to the task
2420 note Prompt for a note and add it with template `org-log-note-headings'
2422 This option can also be set with on a per-file-basis with
2424 #+STARTUP: nologrefile
2425 #+STARTUP: logrefile
2426 #+STARTUP: lognoterefile
2428 You can have local logging settings for a subtree by setting the LOGGING
2429 property to one or more of these keywords.
2431 When bulk-refiling from the agenda, the value `note' is forbidden and
2432 will temporarily be changed to `time'."
2433 :group 'org-refile
2434 :group 'org-progress
2435 :version "24.1"
2436 :type '(choice
2437 (const :tag "No logging" nil)
2438 (const :tag "Record timestamp" time)
2439 (const :tag "Record timestamp with note." note)))
2441 (defcustom org-refile-targets nil
2442 "Targets for refiling entries with \\[org-refile].
2443 This is a list of cons cells. Each cell contains:
2444 - a specification of the files to be considered, either a list of files,
2445 or a symbol whose function or variable value will be used to retrieve
2446 a file name or a list of file names. If you use `org-agenda-files' for
2447 that, all agenda files will be scanned for targets. Nil means consider
2448 headings in the current buffer.
2449 - A specification of how to find candidate refile targets. This may be
2450 any of:
2451 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2452 This tag has to be present in all target headlines, inheritance will
2453 not be considered.
2454 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2455 todo keyword.
2456 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2457 headlines that are refiling targets.
2458 - a cons cell (:level . N). Any headline of level N is considered a target.
2459 Note that, when `org-odd-levels-only' is set, level corresponds to
2460 order in hierarchy, not to the number of stars.
2461 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2462 Note that, when `org-odd-levels-only' is set, level corresponds to
2463 order in hierarchy, not to the number of stars.
2465 Each element of this list generates a set of possible targets.
2466 The union of these sets is presented (with completion) to
2467 the user by `org-refile'.
2469 You can set the variable `org-refile-target-verify-function' to a function
2470 to verify each headline found by the simple criteria above.
2472 When this variable is nil, all top-level headlines in the current buffer
2473 are used, equivalent to the value `((nil . (:level . 1))'."
2474 :group 'org-refile
2475 :type '(repeat
2476 (cons
2477 (choice :value org-agenda-files
2478 (const :tag "All agenda files" org-agenda-files)
2479 (const :tag "Current buffer" nil)
2480 (function) (variable) (file))
2481 (choice :tag "Identify target headline by"
2482 (cons :tag "Specific tag" (const :value :tag) (string))
2483 (cons :tag "TODO keyword" (const :value :todo) (string))
2484 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2485 (cons :tag "Level number" (const :value :level) (integer))
2486 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2488 (defcustom org-refile-target-verify-function nil
2489 "Function to verify if the headline at point should be a refile target.
2490 The function will be called without arguments, with point at the
2491 beginning of the headline. It should return t and leave point
2492 where it is if the headline is a valid target for refiling.
2494 If the target should not be selected, the function must return nil.
2495 In addition to this, it may move point to a place from where the search
2496 should be continued. For example, the function may decide that the entire
2497 subtree of the current entry should be excluded and move point to the end
2498 of the subtree."
2499 :group 'org-refile
2500 :type '(choice
2501 (const nil)
2502 (function)))
2504 (defcustom org-refile-use-cache nil
2505 "Non-nil means cache refile targets to speed up the process.
2506 \\<org-mode-map>\
2507 The cache for a particular file will be updated automatically when
2508 the buffer has been killed, or when any of the marker used for flagging
2509 refile targets no longer points at a live buffer.
2510 If you have added new entries to a buffer that might themselves be targets,
2511 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2512 if you find that easier, \
2513 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2514 \\[org-refile]'."
2515 :group 'org-refile
2516 :version "24.1"
2517 :type 'boolean)
2519 (defcustom org-refile-use-outline-path nil
2520 "Non-nil means provide refile targets as paths.
2521 So a level 3 headline will be available as level1/level2/level3.
2523 When the value is `file', also include the file name (without directory)
2524 into the path. In this case, you can also stop the completion after
2525 the file name, to get entries inserted as top level in the file.
2527 When `full-file-path', include the full file path."
2528 :group 'org-refile
2529 :type '(choice
2530 (const :tag "Not" nil)
2531 (const :tag "Yes" t)
2532 (const :tag "Start with file name" file)
2533 (const :tag "Start with full file path" full-file-path)))
2535 (defcustom org-outline-path-complete-in-steps t
2536 "Non-nil means complete the outline path in hierarchical steps.
2537 When Org uses the refile interface to select an outline path (see
2538 `org-refile-use-outline-path'), the completion of the path can be
2539 done in a single go, or it can be done in steps down the headline
2540 hierarchy. Going in steps is probably the best if you do not use
2541 a special completion package like `ido' or `icicles'. However,
2542 when using these packages, going in one step can be very fast,
2543 while still showing the whole path to the entry."
2544 :group 'org-refile
2545 :type 'boolean)
2547 (defcustom org-refile-allow-creating-parent-nodes nil
2548 "Non-nil means allow the creation of new nodes as refile targets.
2549 New nodes are then created by adding \"/new node name\" to the completion
2550 of an existing node. When the value of this variable is `confirm',
2551 new node creation must be confirmed by the user (recommended).
2552 When nil, the completion must match an existing entry.
2554 Note that, if the new heading is not seen by the criteria
2555 listed in `org-refile-targets', multiple instances of the same
2556 heading would be created by trying again to file under the new
2557 heading."
2558 :group 'org-refile
2559 :type '(choice
2560 (const :tag "Never" nil)
2561 (const :tag "Always" t)
2562 (const :tag "Prompt for confirmation" confirm)))
2564 (defcustom org-refile-active-region-within-subtree nil
2565 "Non-nil means also refile active region within a subtree.
2567 By default `org-refile' doesn't allow refiling regions if they
2568 don't contain a set of subtrees, but it might be convenient to
2569 do so sometimes: in that case, the first line of the region is
2570 converted to a headline before refiling."
2571 :group 'org-refile
2572 :version "24.1"
2573 :type 'boolean)
2575 (defgroup org-todo nil
2576 "Options concerning TODO items in Org-mode."
2577 :tag "Org TODO"
2578 :group 'org)
2580 (defgroup org-progress nil
2581 "Options concerning Progress logging in Org-mode."
2582 :tag "Org Progress"
2583 :group 'org-time)
2585 (defvar org-todo-interpretation-widgets
2586 '((:tag "Sequence (cycling hits every state)" sequence)
2587 (:tag "Type (cycling directly to DONE)" type))
2588 "The available interpretation symbols for customizing `org-todo-keywords'.
2589 Interested libraries should add to this list.")
2591 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2592 "List of TODO entry keyword sequences and their interpretation.
2593 \\<org-mode-map>This is a list of sequences.
2595 Each sequence starts with a symbol, either `sequence' or `type',
2596 indicating if the keywords should be interpreted as a sequence of
2597 action steps, or as different types of TODO items. The first
2598 keywords are states requiring action - these states will select a headline
2599 for inclusion into the global TODO list Org produces. If one of the
2600 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2601 signify that no further action is necessary. If \"|\" is not found,
2602 the last keyword is treated as the only DONE state of the sequence.
2604 The command \\[org-todo] cycles an entry through these states, and one
2605 additional state where no keyword is present. For details about this
2606 cycling, see the manual.
2608 TODO keywords and interpretation can also be set on a per-file basis with
2609 the special #+SEQ_TODO and #+TYP_TODO lines.
2611 Each keyword can optionally specify a character for fast state selection
2612 \(in combination with the variable `org-use-fast-todo-selection')
2613 and specifiers for state change logging, using the same syntax that
2614 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2615 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2616 indicates to record a time stamp each time this state is selected.
2618 Each keyword may also specify if a timestamp or a note should be
2619 recorded when entering or leaving the state, by adding additional
2620 characters in the parenthesis after the keyword. This looks like this:
2621 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2622 record only the time of the state change. With X and Y being either
2623 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2624 Y when leaving the state if and only if the *target* state does not
2625 define X. You may omit any of the fast-selection key or X or /Y,
2626 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2628 For backward compatibility, this variable may also be just a list
2629 of keywords. In this case the interpretation (sequence or type) will be
2630 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2631 :group 'org-todo
2632 :group 'org-keywords
2633 :type '(choice
2634 (repeat :tag "Old syntax, just keywords"
2635 (string :tag "Keyword"))
2636 (repeat :tag "New syntax"
2637 (cons
2638 (choice
2639 :tag "Interpretation"
2640 ;;Quick and dirty way to see
2641 ;;`org-todo-interpretations'. This takes the
2642 ;;place of item arguments
2643 :convert-widget
2644 (lambda (widget)
2645 (widget-put widget
2646 :args (mapcar
2647 (lambda (x)
2648 (widget-convert
2649 (cons 'const x)))
2650 org-todo-interpretation-widgets))
2651 widget))
2652 (repeat
2653 (string :tag "Keyword"))))))
2655 (defvar-local org-todo-keywords-1 nil
2656 "All TODO and DONE keywords active in a buffer.")
2657 (defvar org-todo-keywords-for-agenda nil)
2658 (defvar org-done-keywords-for-agenda nil)
2659 (defvar org-todo-keyword-alist-for-agenda nil)
2660 (defvar org-tag-alist-for-agenda nil
2661 "Alist of all tags from all agenda files.")
2662 (defvar org-tag-groups-alist-for-agenda nil
2663 "Alist of all groups tags from all current agenda files.")
2664 (defvar-local org-tag-groups-alist nil)
2665 (defvar org-agenda-contributing-files nil)
2666 (defvar-local org-current-tag-alist nil
2667 "Alist of all tag groups in current buffer.
2668 This variable takes into consideration `org-tag-alist',
2669 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2670 (defvar-local org-not-done-keywords nil)
2671 (defvar-local org-done-keywords nil)
2672 (defvar-local org-todo-heads nil)
2673 (defvar-local org-todo-sets nil)
2674 (defvar-local org-todo-log-states nil)
2675 (defvar-local org-todo-kwd-alist nil)
2676 (defvar-local org-todo-key-alist nil)
2677 (defvar-local org-todo-key-trigger nil)
2679 (defcustom org-todo-interpretation 'sequence
2680 "Controls how TODO keywords are interpreted.
2681 This variable is in principle obsolete and is only used for
2682 backward compatibility, if the interpretation of todo keywords is
2683 not given already in `org-todo-keywords'. See that variable for
2684 more information."
2685 :group 'org-todo
2686 :group 'org-keywords
2687 :type '(choice (const sequence)
2688 (const type)))
2690 (defcustom org-use-fast-todo-selection t
2691 "\\<org-mode-map>\
2692 Non-nil means use the fast todo selection scheme with \\[org-todo].
2693 This variable describes if and under what circumstances the cycling
2694 mechanism for TODO keywords will be replaced by a single-key, direct
2695 selection scheme.
2697 When nil, fast selection is never used.
2699 When the symbol `prefix', it will be used when `org-todo' is called
2700 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2701 in an Org buffer, and
2702 `\\[universal-argument] t' in an agenda buffer.
2704 When t, fast selection is used by default. In this case, the prefix
2705 argument forces cycling instead.
2707 In all cases, the special interface is only used if access keys have
2708 actually been assigned by the user, i.e. if keywords in the configuration
2709 are followed by a letter in parenthesis, like TODO(t)."
2710 :group 'org-todo
2711 :type '(choice
2712 (const :tag "Never" nil)
2713 (const :tag "By default" t)
2714 (const :tag "Only with C-u C-c C-t" prefix)))
2716 (defcustom org-provide-todo-statistics t
2717 "Non-nil means update todo statistics after insert and toggle.
2718 ALL-HEADLINES means update todo statistics by including headlines
2719 with no TODO keyword as well, counting them as not done.
2720 A list of TODO keywords means the same, but skip keywords that are
2721 not in this list.
2722 When set to a list of two lists, the first list contains keywords
2723 to consider as TODO keywords, the second list contains keywords
2724 to consider as DONE keywords.
2726 When this is set, todo statistics is updated in the parent of the
2727 current entry each time a todo state is changed."
2728 :group 'org-todo
2729 :type '(choice
2730 (const :tag "Yes, only for TODO entries" t)
2731 (const :tag "Yes, including all entries" all-headlines)
2732 (repeat :tag "Yes, for TODOs in this list"
2733 (string :tag "TODO keyword"))
2734 (list :tag "Yes, for TODOs and DONEs in these lists"
2735 (repeat (string :tag "TODO keyword"))
2736 (repeat (string :tag "DONE keyword")))
2737 (other :tag "No TODO statistics" nil)))
2739 (defcustom org-hierarchical-todo-statistics t
2740 "Non-nil means TODO statistics covers just direct children.
2741 When nil, all entries in the subtree are considered.
2742 This has only an effect if `org-provide-todo-statistics' is set.
2743 To set this to nil for only a single subtree, use a COOKIE_DATA
2744 property and include the word \"recursive\" into the value."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-after-todo-state-change-hook nil
2749 "Hook which is run after the state of a TODO item was changed.
2750 The new state (a string with a TODO keyword, or nil) is available in the
2751 Lisp variable `org-state'."
2752 :group 'org-todo
2753 :type 'hook)
2755 (defvar org-blocker-hook nil
2756 "Hook for functions that are allowed to block a state change.
2758 Functions in this hook should not modify the buffer.
2759 Each function gets as its single argument a property list,
2760 see `org-trigger-hook' for more information about this list.
2762 If any of the functions in this hook returns nil, the state change
2763 is blocked.")
2765 (defvar org-trigger-hook nil
2766 "Hook for functions that are triggered by a state change.
2768 Each function gets as its single argument a property list with at
2769 least the following elements:
2771 (:type type-of-change :position pos-at-entry-start
2772 :from old-state :to new-state)
2774 Depending on the type, more properties may be present.
2776 This mechanism is currently implemented for:
2778 TODO state changes
2779 ------------------
2780 :type todo-state-change
2781 :from previous state (keyword as a string), or nil, or a symbol
2782 `todo' or `done', to indicate the general type of state.
2783 :to new state, like in :from")
2785 (defcustom org-enforce-todo-dependencies nil
2786 "Non-nil means undone TODO entries will block switching the parent to DONE.
2787 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2788 be blocked if any prior sibling is not yet done.
2789 Finally, if the parent is blocked because of ordered siblings of its own,
2790 the child will also be blocked."
2791 :set (lambda (var val)
2792 (set var val)
2793 (if val
2794 (add-hook 'org-blocker-hook
2795 'org-block-todo-from-children-or-siblings-or-parent)
2796 (remove-hook 'org-blocker-hook
2797 'org-block-todo-from-children-or-siblings-or-parent)))
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-enforce-todo-checkbox-dependencies nil
2802 "Non-nil means unchecked boxes will block switching the parent to DONE.
2803 When this is nil, checkboxes have no influence on switching TODO states.
2804 When non-nil, you first need to check off all check boxes before the TODO
2805 entry can be switched to DONE.
2806 This variable needs to be set before org.el is loaded, and you need to
2807 restart Emacs after a change to make the change effective. The only way
2808 to change is while Emacs is running is through the customize interface."
2809 :set (lambda (var val)
2810 (set var val)
2811 (if val
2812 (add-hook 'org-blocker-hook
2813 'org-block-todo-from-checkboxes)
2814 (remove-hook 'org-blocker-hook
2815 'org-block-todo-from-checkboxes)))
2816 :group 'org-todo
2817 :type 'boolean)
2819 (defcustom org-treat-insert-todo-heading-as-state-change nil
2820 "Non-nil means inserting a TODO heading is treated as state change.
2821 So when the command \\[org-insert-todo-heading] is used, state change
2822 logging will apply if appropriate. When nil, the new TODO item will
2823 be inserted directly, and no logging will take place."
2824 :group 'org-todo
2825 :type 'boolean)
2827 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2828 "Non-nil means switching TODO states with S-cursor counts as state change.
2829 This is the default behavior. However, setting this to nil allows a
2830 convenient way to select a TODO state and bypass any logging associated
2831 with that."
2832 :group 'org-todo
2833 :type 'boolean)
2835 (defcustom org-todo-state-tags-triggers nil
2836 "Tag changes that should be triggered by TODO state changes.
2837 This is a list. Each entry is
2839 (state-change (tag . flag) .......)
2841 State-change can be a string with a state, and empty string to indicate the
2842 state that has no TODO keyword, or it can be one of the symbols `todo'
2843 or `done', meaning any not-done or done state, respectively."
2844 :group 'org-todo
2845 :group 'org-tags
2846 :type '(repeat
2847 (cons (choice :tag "When changing to"
2848 (const :tag "Not-done state" todo)
2849 (const :tag "Done state" done)
2850 (string :tag "State"))
2851 (repeat
2852 (cons :tag "Tag action"
2853 (string :tag "Tag")
2854 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2856 (defcustom org-log-done nil
2857 "Information to record when a task moves to the DONE state.
2859 Possible values are:
2861 nil Don't add anything, just change the keyword
2862 time Add a time stamp to the task
2863 note Prompt for a note and add it with template `org-log-note-headings'
2865 This option can also be set with on a per-file-basis with
2867 #+STARTUP: nologdone
2868 #+STARTUP: logdone
2869 #+STARTUP: lognotedone
2871 You can have local logging settings for a subtree by setting the LOGGING
2872 property to one or more of these keywords."
2873 :group 'org-todo
2874 :group 'org-progress
2875 :type '(choice
2876 (const :tag "No logging" nil)
2877 (const :tag "Record CLOSED timestamp" time)
2878 (const :tag "Record CLOSED timestamp with note." note)))
2880 ;; Normalize old uses of org-log-done.
2881 (cond
2882 ((eq org-log-done t) (setq org-log-done 'time))
2883 ((and (listp org-log-done) (memq 'done org-log-done))
2884 (setq org-log-done 'note)))
2886 (defcustom org-log-reschedule nil
2887 "Information to record when the scheduling date of a tasks is modified.
2889 Possible values are:
2891 nil Don't add anything, just change the date
2892 time Add a time stamp to the task
2893 note Prompt for a note and add it with template `org-log-note-headings'
2895 This option can also be set with on a per-file-basis with
2897 #+STARTUP: nologreschedule
2898 #+STARTUP: logreschedule
2899 #+STARTUP: lognotereschedule"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type '(choice
2903 (const :tag "No logging" nil)
2904 (const :tag "Record timestamp" time)
2905 (const :tag "Record timestamp with note." note)))
2907 (defcustom org-log-redeadline nil
2908 "Information to record when the deadline date of a tasks is modified.
2910 Possible values are:
2912 nil Don't add anything, just change the date
2913 time Add a time stamp to the task
2914 note Prompt for a note and add it with template `org-log-note-headings'
2916 This option can also be set with on a per-file-basis with
2918 #+STARTUP: nologredeadline
2919 #+STARTUP: logredeadline
2920 #+STARTUP: lognoteredeadline
2922 You can have local logging settings for a subtree by setting the LOGGING
2923 property to one or more of these keywords."
2924 :group 'org-todo
2925 :group 'org-progress
2926 :type '(choice
2927 (const :tag "No logging" nil)
2928 (const :tag "Record timestamp" time)
2929 (const :tag "Record timestamp with note." note)))
2931 (defcustom org-log-note-clock-out nil
2932 "Non-nil means record a note when clocking out of an item.
2933 This can also be configured on a per-file basis by adding one of
2934 the following lines anywhere in the buffer:
2936 #+STARTUP: lognoteclock-out
2937 #+STARTUP: nolognoteclock-out"
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type 'boolean)
2942 (defcustom org-log-done-with-time t
2943 "Non-nil means the CLOSED time stamp will contain date and time.
2944 When nil, only the date will be recorded."
2945 :group 'org-progress
2946 :type 'boolean)
2948 (defcustom org-log-note-headings
2949 '((done . "CLOSING NOTE %t")
2950 (state . "State %-12s from %-12S %t")
2951 (note . "Note taken on %t")
2952 (reschedule . "Rescheduled from %S on %t")
2953 (delschedule . "Not scheduled, was %S on %t")
2954 (redeadline . "New deadline from %S on %t")
2955 (deldeadline . "Removed deadline, was %S on %t")
2956 (refile . "Refiled on %t")
2957 (clock-out . ""))
2958 "Headings for notes added to entries.
2960 The value is an alist, with the car being a symbol indicating the
2961 note context, and the cdr is the heading to be used. The heading
2962 may also be the empty string. The following placeholders can be
2963 used:
2965 %t a time stamp.
2966 %T an active time stamp instead the default inactive one
2967 %d a short-format time stamp.
2968 %D an active short-format time stamp.
2969 %s the new TODO state or time stamp (inactive), in double quotes.
2970 %S the old TODO state or time stamp (inactive), in double quotes.
2971 %u the user name.
2972 %U full user name.
2974 In fact, it is not a good idea to change the `state' entry,
2975 because Agenda Log mode depends on the format of these entries."
2976 :group 'org-todo
2977 :group 'org-progress
2978 :type '(list :greedy t
2979 (cons (const :tag "Heading when closing an item" done) string)
2980 (cons (const :tag
2981 "Heading when changing todo state (todo sequence only)"
2982 state) string)
2983 (cons (const :tag "Heading when just taking a note" note) string)
2984 (cons (const :tag "Heading when rescheduling" reschedule) string)
2985 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2986 (cons (const :tag "Heading when changing deadline" redeadline) string)
2987 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2988 (cons (const :tag "Heading when refiling" refile) string)
2989 (cons (const :tag "Heading when clocking out" clock-out) string)))
2991 (unless (assq 'note org-log-note-headings)
2992 (push '(note . "%t") org-log-note-headings))
2994 (defcustom org-log-into-drawer nil
2995 "Non-nil means insert state change notes and time stamps into a drawer.
2996 When nil, state changes notes will be inserted after the headline and
2997 any scheduling and clock lines, but not inside a drawer.
2999 The value of this variable should be the name of the drawer to use.
3000 LOGBOOK is proposed as the default drawer for this purpose, you can
3001 also set this to a string to define the drawer of your choice.
3003 A value of t is also allowed, representing \"LOGBOOK\".
3005 A value of t or nil can also be set with on a per-file-basis with
3007 #+STARTUP: logdrawer
3008 #+STARTUP: nologdrawer
3010 If this variable is set, `org-log-state-notes-insert-after-drawers'
3011 will be ignored.
3013 You can set the property LOG_INTO_DRAWER to overrule this setting for
3014 a subtree.
3016 Do not check directly this variable in a Lisp program. Call
3017 function `org-log-into-drawer' instead."
3018 :group 'org-todo
3019 :group 'org-progress
3020 :type '(choice
3021 (const :tag "Not into a drawer" nil)
3022 (const :tag "LOGBOOK" t)
3023 (string :tag "Other")))
3025 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3027 (defun org-log-into-drawer ()
3028 "Name of the log drawer, as a string, or nil.
3029 This is the value of `org-log-into-drawer'. However, if the
3030 current entry has or inherits a LOG_INTO_DRAWER property, it will
3031 be used instead of the default value."
3032 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3033 (cond ((equal p "nil") nil)
3034 ((equal p "t") "LOGBOOK")
3035 ((stringp p) p)
3036 (p "LOGBOOK")
3037 ((stringp org-log-into-drawer) org-log-into-drawer)
3038 (org-log-into-drawer "LOGBOOK"))))
3040 (defcustom org-log-state-notes-insert-after-drawers nil
3041 "Non-nil means insert state change notes after any drawers in entry.
3042 Only the drawers that *immediately* follow the headline and the
3043 deadline/scheduled line are skipped.
3044 When nil, insert notes right after the heading and perhaps the line
3045 with deadline/scheduling if present.
3047 This variable will have no effect if `org-log-into-drawer' is
3048 set."
3049 :group 'org-todo
3050 :group 'org-progress
3051 :type 'boolean)
3053 (defcustom org-log-states-order-reversed t
3054 "Non-nil means the latest state note will be directly after heading.
3055 When nil, the state change notes will be ordered according to time.
3057 This option can also be set with on a per-file-basis with
3059 #+STARTUP: logstatesreversed
3060 #+STARTUP: nologstatesreversed"
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-todo-repeat-to-state nil
3066 "The TODO state to which a repeater should return the repeating task.
3067 By default this is the first task in a TODO sequence, or the previous state
3068 in a TODO_TYP set. But you can specify another task here.
3069 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3070 :group 'org-todo
3071 :version "24.1"
3072 :type '(choice (const :tag "Head of sequence" nil)
3073 (string :tag "Specific state")))
3075 (defcustom org-log-repeat 'time
3076 "Non-nil means record moving through the DONE state when triggering repeat.
3077 An auto-repeating task is immediately switched back to TODO when
3078 marked DONE. If you are not logging state changes (by adding \"@\"
3079 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3080 record a closing note, there will be no record of the task moving
3081 through DONE. This variable forces taking a note anyway.
3083 nil Don't force a record
3084 time Record a time stamp
3085 note Prompt for a note and add it with template `org-log-note-headings'
3087 This option can also be set with on a per-file-basis with
3089 #+STARTUP: nologrepeat
3090 #+STARTUP: logrepeat
3091 #+STARTUP: lognoterepeat
3093 You can have local logging settings for a subtree by setting the LOGGING
3094 property to one or more of these keywords."
3095 :group 'org-todo
3096 :group 'org-progress
3097 :type '(choice
3098 (const :tag "Don't force a record" nil)
3099 (const :tag "Force recording the DONE state" time)
3100 (const :tag "Force recording a note with the DONE state" note)))
3103 (defgroup org-priorities nil
3104 "Priorities in Org-mode."
3105 :tag "Org Priorities"
3106 :group 'org-todo)
3108 (defcustom org-enable-priority-commands t
3109 "Non-nil means priority commands are active.
3110 When nil, these commands will be disabled, so that you never accidentally
3111 set a priority."
3112 :group 'org-priorities
3113 :type 'boolean)
3115 (defcustom org-highest-priority ?A
3116 "The highest priority of TODO items. A character like ?A, ?B etc.
3117 Must have a smaller ASCII number than `org-lowest-priority'."
3118 :group 'org-priorities
3119 :type 'character)
3121 (defcustom org-lowest-priority ?C
3122 "The lowest priority of TODO items. A character like ?A, ?B etc.
3123 Must have a larger ASCII number than `org-highest-priority'."
3124 :group 'org-priorities
3125 :type 'character)
3127 (defcustom org-default-priority ?B
3128 "The default priority of TODO items.
3129 This is the priority an item gets if no explicit priority is given.
3130 When starting to cycle on an empty priority the first step in the cycle
3131 depends on `org-priority-start-cycle-with-default'. The resulting first
3132 step priority must not exceed the range from `org-highest-priority' to
3133 `org-lowest-priority' which means that `org-default-priority' has to be
3134 in this range exclusive or inclusive the range boundaries. Else the
3135 first step refuses to set the default and the second will fall back
3136 to (depending on the command used) the highest or lowest priority."
3137 :group 'org-priorities
3138 :type 'character)
3140 (defcustom org-priority-start-cycle-with-default t
3141 "Non-nil means start with default priority when starting to cycle.
3142 When this is nil, the first step in the cycle will be (depending on the
3143 command used) one higher or lower than the default priority.
3144 See also `org-default-priority'."
3145 :group 'org-priorities
3146 :type 'boolean)
3148 (defcustom org-get-priority-function nil
3149 "Function to extract the priority from a string.
3150 The string is normally the headline. If this is nil Org computes the
3151 priority from the priority cookie like [#A] in the headline. It returns
3152 an integer, increasing by 1000 for each priority level.
3153 The user can set a different function here, which should take a string
3154 as an argument and return the numeric priority."
3155 :group 'org-priorities
3156 :version "24.1"
3157 :type '(choice
3158 (const nil)
3159 (function)))
3161 (defgroup org-time nil
3162 "Options concerning time stamps and deadlines in Org-mode."
3163 :tag "Org Time"
3164 :group 'org)
3166 (defcustom org-time-stamp-rounding-minutes '(0 5)
3167 "Number of minutes to round time stamps to.
3168 \\<org-mode-map>\
3169 These are two values, the first applies when first creating a time stamp.
3170 The second applies when changing it with the commands `S-up' and `S-down'.
3171 When changing the time stamp, this means that it will change in steps
3172 of N minutes, as given by the second value.
3174 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3175 numbers should be factors of 60, so for example 5, 10, 15.
3177 When this is larger than 1, you can still force an exact time stamp by using
3178 a double prefix argument to a time stamp command like \
3179 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3180 and by using a prefix arg to `S-up/down' to specify the exact number
3181 of minutes to shift."
3182 :group 'org-time
3183 :get (lambda (var) ; Make sure both elements are there
3184 (if (integerp (default-value var))
3185 (list (default-value var) 5)
3186 (default-value var)))
3187 :type '(list
3188 (integer :tag "when inserting times")
3189 (integer :tag "when modifying times")))
3191 ;; Normalize old customizations of this variable.
3192 (when (integerp org-time-stamp-rounding-minutes)
3193 (setq org-time-stamp-rounding-minutes
3194 (list org-time-stamp-rounding-minutes
3195 org-time-stamp-rounding-minutes)))
3197 (defcustom org-display-custom-times nil
3198 "Non-nil means overlay custom formats over all time stamps.
3199 The formats are defined through the variable `org-time-stamp-custom-formats'.
3200 To turn this on on a per-file basis, insert anywhere in the file:
3201 #+STARTUP: customtime"
3202 :group 'org-time
3203 :set 'set-default
3204 :type 'sexp)
3205 (make-variable-buffer-local 'org-display-custom-times)
3207 (defcustom org-time-stamp-custom-formats
3208 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3209 "Custom formats for time stamps. See `format-time-string' for the syntax.
3210 These are overlaid over the default ISO format if the variable
3211 `org-display-custom-times' is set. Time like %H:%M should be at the
3212 end of the second format. The custom formats are also honored by export
3213 commands, if custom time display is turned on at the time of export."
3214 :group 'org-time
3215 :type 'sexp)
3217 (defun org-time-stamp-format (&optional long inactive)
3218 "Get the right format for a time string."
3219 (let ((f (if long (cdr org-time-stamp-formats)
3220 (car org-time-stamp-formats))))
3221 (if inactive
3222 (concat "[" (substring f 1 -1) "]")
3223 f)))
3225 (defcustom org-time-clocksum-format
3226 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3227 "The format string used when creating CLOCKSUM lines.
3228 This is also used when Org mode generates a time duration.
3230 The value can be a single format string containing two
3231 %-sequences, which will be filled with the number of hours and
3232 minutes in that order.
3234 Alternatively, the value can be a plist associating any of the
3235 keys :years, :months, :weeks, :days, :hours or :minutes with
3236 format strings. The time duration is formatted using only the
3237 time components that are needed and concatenating the results.
3238 If a time unit in absent, it falls back to the next smallest
3239 unit.
3241 The keys :require-years, :require-months, :require-days,
3242 :require-weeks, :require-hours, :require-minutes are also
3243 meaningful. A non-nil value for these keys indicates that the
3244 corresponding time component should always be included, even if
3245 its value is 0.
3248 For example,
3250 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3251 :require-minutes t)
3253 means durations longer than a day will be expressed in days,
3254 hours and minutes, and durations less than a day will always be
3255 expressed in hours and minutes (even for durations less than an
3256 hour).
3258 The value
3260 (:days \"%dd\" :minutes \"%dm\")
3262 means durations longer than a day will be expressed in days and
3263 minutes, and durations less than a day will be expressed entirely
3264 in minutes (even for durations longer than an hour)."
3265 :group 'org-time
3266 :group 'org-clock
3267 :version "24.4"
3268 :package-version '(Org . "8.0")
3269 :type '(choice (string :tag "Format string")
3270 (set :tag "Plist"
3271 (group :inline t (const :tag "Years" :years)
3272 (string :tag "Format string"))
3273 (group :inline t
3274 (const :tag "Always show years" :require-years)
3275 (const t))
3276 (group :inline t (const :tag "Months" :months)
3277 (string :tag "Format string"))
3278 (group :inline t
3279 (const :tag "Always show months" :require-months)
3280 (const t))
3281 (group :inline t (const :tag "Weeks" :weeks)
3282 (string :tag "Format string"))
3283 (group :inline t
3284 (const :tag "Always show weeks" :require-weeks)
3285 (const t))
3286 (group :inline t (const :tag "Days" :days)
3287 (string :tag "Format string"))
3288 (group :inline t
3289 (const :tag "Always show days" :require-days)
3290 (const t))
3291 (group :inline t (const :tag "Hours" :hours)
3292 (string :tag "Format string"))
3293 (group :inline t
3294 (const :tag "Always show hours" :require-hours)
3295 (const t))
3296 (group :inline t (const :tag "Minutes" :minutes)
3297 (string :tag "Format string"))
3298 (group :inline t
3299 (const :tag "Always show minutes" :require-minutes)
3300 (const t)))))
3302 (defcustom org-time-clocksum-use-fractional nil
3303 "When non-nil, \\[org-clock-display] uses fractional times.
3304 See `org-time-clocksum-format' for more on time clock formats."
3305 :group 'org-time
3306 :group 'org-clock
3307 :version "24.3"
3308 :type 'boolean)
3310 (defcustom org-time-clocksum-use-effort-durations nil
3311 "When non-nil, \\[org-clock-display] uses effort durations.
3312 E.g. by default, one day is considered to be a 8 hours effort,
3313 so a task that has been clocked for 16 hours will be displayed
3314 as during 2 days in the clock display or in the clocktable.
3316 See `org-effort-durations' on how to set effort durations
3317 and `org-time-clocksum-format' for more on time clock formats."
3318 :group 'org-time
3319 :group 'org-clock
3320 :version "24.4"
3321 :package-version '(Org . "8.0")
3322 :type 'boolean)
3324 (defcustom org-time-clocksum-fractional-format "%.2f"
3325 "The format string used when creating CLOCKSUM lines,
3326 or when Org mode generates a time duration, if
3327 `org-time-clocksum-use-fractional' is enabled.
3329 The value can be a single format string containing one
3330 %-sequence, which will be filled with the number of hours as
3331 a float.
3333 Alternatively, the value can be a plist associating any of the
3334 keys :years, :months, :weeks, :days, :hours or :minutes with
3335 a format string. The time duration is formatted using the
3336 largest time unit which gives a non-zero integer part. If all
3337 specified formats have zero integer part, the smallest time unit
3338 is used."
3339 :group 'org-time
3340 :type '(choice (string :tag "Format string")
3341 (set (group :inline t (const :tag "Years" :years)
3342 (string :tag "Format string"))
3343 (group :inline t (const :tag "Months" :months)
3344 (string :tag "Format string"))
3345 (group :inline t (const :tag "Weeks" :weeks)
3346 (string :tag "Format string"))
3347 (group :inline t (const :tag "Days" :days)
3348 (string :tag "Format string"))
3349 (group :inline t (const :tag "Hours" :hours)
3350 (string :tag "Format string"))
3351 (group :inline t (const :tag "Minutes" :minutes)
3352 (string :tag "Format string")))))
3354 (defcustom org-deadline-warning-days 14
3355 "Number of days before expiration during which a deadline becomes active.
3356 This variable governs the display in sparse trees and in the agenda.
3357 When 0 or negative, it means use this number (the absolute value of it)
3358 even if a deadline has a different individual lead time specified.
3360 Custom commands can set this variable in the options section."
3361 :group 'org-time
3362 :group 'org-agenda-daily/weekly
3363 :type 'integer)
3365 (defcustom org-scheduled-delay-days 0
3366 "Number of days before a scheduled item becomes active.
3367 This variable governs the display in sparse trees and in the agenda.
3368 The default value (i.e. 0) means: don't delay scheduled item.
3369 When negative, it means use this number (the absolute value of it)
3370 even if a scheduled item has a different individual delay time
3371 specified.
3373 Custom commands can set this variable in the options section."
3374 :group 'org-time
3375 :group 'org-agenda-daily/weekly
3376 :version "24.4"
3377 :package-version '(Org . "8.0")
3378 :type 'integer)
3380 (defcustom org-read-date-prefer-future t
3381 "Non-nil means assume future for incomplete date input from user.
3382 This affects the following situations:
3383 1. The user gives a month but not a year.
3384 For example, if it is April and you enter \"feb 2\", this will be read
3385 as Feb 2, *next* year. \"May 5\", however, will be this year.
3386 2. The user gives a day, but no month.
3387 For example, if today is the 15th, and you enter \"3\", Org will read
3388 this as the third of *next* month. However, if you enter \"17\",
3389 it will be considered as *this* month.
3391 If you set this variable to the symbol `time', then also the following
3392 will work:
3394 3. If the user gives a time.
3395 If the time is before now, it will be interpreted as tomorrow.
3397 Currently none of this works for ISO week specifications.
3399 When this option is nil, the current day, month and year will always be
3400 used as defaults.
3402 See also `org-agenda-jump-prefer-future'."
3403 :group 'org-time
3404 :type '(choice
3405 (const :tag "Never" nil)
3406 (const :tag "Check month and day" t)
3407 (const :tag "Check month, day, and time" time)))
3409 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3410 "Should the agenda jump command prefer the future for incomplete dates?
3411 The default is to do the same as configured in `org-read-date-prefer-future'.
3412 But you can also set a deviating value here.
3413 This may t or nil, or the symbol `org-read-date-prefer-future'."
3414 :group 'org-agenda
3415 :group 'org-time
3416 :version "24.1"
3417 :type '(choice
3418 (const :tag "Use org-read-date-prefer-future"
3419 org-read-date-prefer-future)
3420 (const :tag "Never" nil)
3421 (const :tag "Always" t)))
3423 (defcustom org-read-date-force-compatible-dates t
3424 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3426 Depending on the system Emacs is running on, certain dates cannot
3427 be represented with the type used internally to represent time.
3428 Dates between 1970-1-1 and 2038-1-1 can always be represented
3429 correctly. Some systems allow for earlier dates, some for later,
3430 some for both. One way to find out it to insert any date into an
3431 Org buffer, putting the cursor on the year and hitting S-up and
3432 S-down to test the range.
3434 When this variable is set to t, the date/time prompt will not let
3435 you specify dates outside the 1970-2037 range, so it is certain that
3436 these dates will work in whatever version of Emacs you are
3437 running, and also that you can move a file from one Emacs implementation
3438 to another. WHenever Org is forcing the year for you, it will display
3439 a message and beep.
3441 When this variable is nil, Org will check if the date is
3442 representable in the specific Emacs implementation you are using.
3443 If not, it will force a year, usually the current year, and beep
3444 to remind you. Currently this setting is not recommended because
3445 the likelihood that you will open your Org files in an Emacs that
3446 has limited date range is not negligible.
3448 A workaround for this problem is to use diary sexp dates for time
3449 stamps outside of this range."
3450 :group 'org-time
3451 :version "24.1"
3452 :type 'boolean)
3454 (defcustom org-read-date-display-live t
3455 "Non-nil means display current interpretation of date prompt live.
3456 This display will be in an overlay, in the minibuffer."
3457 :group 'org-time
3458 :type 'boolean)
3460 (defcustom org-read-date-popup-calendar t
3461 "Non-nil means pop up a calendar when prompting for a date.
3462 In the calendar, the date can be selected with mouse-1. However, the
3463 minibuffer will also be active, and you can simply enter the date as well.
3464 When nil, only the minibuffer will be available."
3465 :group 'org-time
3466 :type 'boolean)
3467 (defvaralias 'org-popup-calendar-for-date-prompt
3468 'org-read-date-popup-calendar)
3470 (defcustom org-extend-today-until 0
3471 "The hour when your day really ends. Must be an integer.
3472 This has influence for the following applications:
3473 - When switching the agenda to \"today\". It it is still earlier than
3474 the time given here, the day recognized as TODAY is actually yesterday.
3475 - When a date is read from the user and it is still before the time given
3476 here, the current date and time will be assumed to be yesterday, 23:59.
3477 Also, timestamps inserted in capture templates follow this rule.
3479 IMPORTANT: This is a feature whose implementation is and likely will
3480 remain incomplete. Really, it is only here because past midnight seems to
3481 be the favorite working time of John Wiegley :-)"
3482 :group 'org-time
3483 :type 'integer)
3485 (defcustom org-use-effective-time nil
3486 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3487 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3488 \"effective time\" of any timestamps between midnight and 8am will be
3489 23:59 of the previous day."
3490 :group 'org-time
3491 :version "24.1"
3492 :type 'boolean)
3494 (defcustom org-use-last-clock-out-time-as-effective-time nil
3495 "When non-nil, use the last clock out time for `org-todo'.
3496 Note that this option has precedence over the combined use of
3497 `org-use-effective-time' and `org-extend-today-until'."
3498 :group 'org-time
3499 :version "24.4"
3500 :package-version '(Org . "8.0")
3501 :type 'boolean)
3503 (defcustom org-edit-timestamp-down-means-later nil
3504 "Non-nil means S-down will increase the time in a time stamp.
3505 When nil, S-up will increase."
3506 :group 'org-time
3507 :type 'boolean)
3509 (defcustom org-calendar-follow-timestamp-change t
3510 "Non-nil means make the calendar window follow timestamp changes.
3511 When a timestamp is modified and the calendar window is visible, it will be
3512 moved to the new date."
3513 :group 'org-time
3514 :type 'boolean)
3516 (defgroup org-tags nil
3517 "Options concerning tags in Org-mode."
3518 :tag "Org Tags"
3519 :group 'org)
3521 (defcustom org-tag-alist nil
3522 "Default tags available in Org files.
3524 The value of this variable is an alist. Associations either:
3526 (TAG)
3527 (TAG . SELECT)
3528 (SPECIAL)
3530 where TAG is a tag as a string, SELECT is a character, used to
3531 select that tag through the fast tag selection interface, and
3532 SPECIAL is one of the following keywords: `:startgroup',
3533 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3534 `:newline'. These keywords are used to define a hierarchy of
3535 tags. See manual for details.
3537 When this variable is nil, Org mode bases tag input on what is
3538 already in the buffer. The value can be overridden locally by
3539 using a TAGS keyword, e.g.,
3541 #+TAGS: tag1 tag2
3543 See also `org-tag-persistent-alist' to sidestep this behavior."
3544 :group 'org-tags
3545 :type '(repeat
3546 (choice
3547 (cons (string :tag "Tag name")
3548 (character :tag "Access char"))
3549 (const :tag "Start radio group" (:startgroup))
3550 (const :tag "Start tag group, non distinct" (:startgrouptag))
3551 (const :tag "Group tags delimiter" (:grouptags))
3552 (const :tag "End radio group" (:endgroup))
3553 (const :tag "End tag group, non distinct" (:endgrouptag))
3554 (const :tag "New line" (:newline)))))
3556 (defcustom org-tag-persistent-alist nil
3557 "Tags always available in Org files.
3559 The value of this variable is an alist. Associations either:
3561 (TAG)
3562 (TAG . SELECT)
3563 (SPECIAL)
3565 where TAG is a tag as a string, SELECT is a character, used to
3566 select that tag through the fast tag selection interface, and
3567 SPECIAL is one of the following keywords: `:startgroup',
3568 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3569 `:newline'. These keywords are used to define a hierarchy of
3570 tags. See manual for details.
3572 Unlike to `org-tag-alist', tags defined in this variable do not
3573 depend on a local TAGS keyword. Instead, to disable these tags
3574 on a per-file basis, insert anywhere in the file:
3576 #+STARTUP: noptag"
3577 :group 'org-tags
3578 :type '(repeat
3579 (choice
3580 (cons (string :tag "Tag name")
3581 (character :tag "Access char"))
3582 (const :tag "Start radio group" (:startgroup))
3583 (const :tag "Start tag group, non distinct" (:startgrouptag))
3584 (const :tag "Group tags delimiter" (:grouptags))
3585 (const :tag "End radio group" (:endgroup))
3586 (const :tag "End tag group, non distinct" (:endgrouptag))
3587 (const :tag "New line" (:newline)))))
3589 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3590 "If non-nil, always offer completion for all tags of all agenda files.
3591 Instead of customizing this variable directly, you might want to
3592 set it locally for capture buffers, because there no list of
3593 tags in that file can be created dynamically (there are none).
3595 (add-hook \\='org-capture-mode-hook
3596 (lambda ()
3597 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3598 :group 'org-tags
3599 :version "24.1"
3600 :type 'boolean)
3602 (defvar org-file-tags nil
3603 "List of tags that can be inherited by all entries in the file.
3604 The tags will be inherited if the variable `org-use-tag-inheritance'
3605 says they should be.
3606 This variable is populated from #+FILETAGS lines.")
3608 (defcustom org-use-fast-tag-selection 'auto
3609 "Non-nil means use fast tag selection scheme.
3610 This is a special interface to select and deselect tags with single keys.
3611 When nil, fast selection is never used.
3612 When the symbol `auto', fast selection is used if and only if selection
3613 characters for tags have been configured, either through the variable
3614 `org-tag-alist' or through a #+TAGS line in the buffer.
3615 When t, fast selection is always used and selection keys are assigned
3616 automatically if necessary."
3617 :group 'org-tags
3618 :type '(choice
3619 (const :tag "Always" t)
3620 (const :tag "Never" nil)
3621 (const :tag "When selection characters are configured" auto)))
3623 (defcustom org-fast-tag-selection-single-key nil
3624 "Non-nil means fast tag selection exits after first change.
3625 When nil, you have to press RET to exit it.
3626 During fast tag selection, you can toggle this flag with `C-c'.
3627 This variable can also have the value `expert'. In this case, the window
3628 displaying the tags menu is not even shown, until you press C-c again."
3629 :group 'org-tags
3630 :type '(choice
3631 (const :tag "No" nil)
3632 (const :tag "Yes" t)
3633 (const :tag "Expert" expert)))
3635 (defvar org-fast-tag-selection-include-todo nil
3636 "Non-nil means fast tags selection interface will also offer TODO states.
3637 This is an undocumented feature, you should not rely on it.")
3639 (defcustom org-tags-column -77
3640 "The column to which tags should be indented in a headline.
3641 If this number is positive, it specifies the column. If it is negative,
3642 it means that the tags should be flushright to that column. For example,
3643 -80 works well for a normal 80 character screen.
3644 When 0, place tags directly after headline text, with only one space in
3645 between."
3646 :group 'org-tags
3647 :type 'integer)
3649 (defcustom org-auto-align-tags t
3650 "Non-nil keeps tags aligned when modifying headlines.
3651 Some operations (i.e. demoting) change the length of a headline and
3652 therefore shift the tags around. With this option turned on, after
3653 each such operation the tags are again aligned to `org-tags-column'."
3654 :group 'org-tags
3655 :type 'boolean)
3657 (defcustom org-use-tag-inheritance t
3658 "Non-nil means tags in levels apply also for sublevels.
3659 When nil, only the tags directly given in a specific line apply there.
3660 This may also be a list of tags that should be inherited, or a regexp that
3661 matches tags that should be inherited. Additional control is possible
3662 with the variable `org-tags-exclude-from-inheritance' which gives an
3663 explicit list of tags to be excluded from inheritance, even if the value of
3664 `org-use-tag-inheritance' would select it for inheritance.
3666 If this option is t, a match early-on in a tree can lead to a large
3667 number of matches in the subtree when constructing the agenda or creating
3668 a sparse tree. If you only want to see the first match in a tree during
3669 a search, check out the variable `org-tags-match-list-sublevels'."
3670 :group 'org-tags
3671 :type '(choice
3672 (const :tag "Not" nil)
3673 (const :tag "Always" t)
3674 (repeat :tag "Specific tags" (string :tag "Tag"))
3675 (regexp :tag "Tags matched by regexp")))
3677 (defcustom org-tags-exclude-from-inheritance nil
3678 "List of tags that should never be inherited.
3679 This is a way to exclude a few tags from inheritance. For way to do
3680 the opposite, to actively allow inheritance for selected tags,
3681 see the variable `org-use-tag-inheritance'."
3682 :group 'org-tags
3683 :type '(repeat (string :tag "Tag")))
3685 (defun org-tag-inherit-p (tag)
3686 "Check if TAG is one that should be inherited."
3687 (cond
3688 ((member tag org-tags-exclude-from-inheritance) nil)
3689 ((eq org-use-tag-inheritance t) t)
3690 ((not org-use-tag-inheritance) nil)
3691 ((stringp org-use-tag-inheritance)
3692 (string-match org-use-tag-inheritance tag))
3693 ((listp org-use-tag-inheritance)
3694 (member tag org-use-tag-inheritance))
3695 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3697 (defcustom org-tags-match-list-sublevels t
3698 "Non-nil means list also sublevels of headlines matching a search.
3699 This variable applies to tags/property searches, and also to stuck
3700 projects because this search is based on a tags match as well.
3702 When set to the symbol `indented', sublevels are indented with
3703 leading dots.
3705 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3706 the sublevels of a headline matching a tag search often also match
3707 the same search. Listing all of them can create very long lists.
3708 Setting this variable to nil causes subtrees of a match to be skipped.
3710 This variable is semi-obsolete and probably should always be true. It
3711 is better to limit inheritance to certain tags using the variables
3712 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3713 :group 'org-tags
3714 :type '(choice
3715 (const :tag "No, don't list them" nil)
3716 (const :tag "Yes, do list them" t)
3717 (const :tag "List them, indented with leading dots" indented)))
3719 (defcustom org-tags-sort-function nil
3720 "When set, tags are sorted using this function as a comparator."
3721 :group 'org-tags
3722 :type '(choice
3723 (const :tag "No sorting" nil)
3724 (const :tag "Alphabetical" string<)
3725 (const :tag "Reverse alphabetical" string>)
3726 (function :tag "Custom function" nil)))
3728 (defvar org-tags-history nil
3729 "History of minibuffer reads for tags.")
3730 (defvar org-last-tags-completion-table nil
3731 "The last used completion table for tags.")
3732 (defvar org-after-tags-change-hook nil
3733 "Hook that is run after the tags in a line have changed.")
3735 (defgroup org-properties nil
3736 "Options concerning properties in Org-mode."
3737 :tag "Org Properties"
3738 :group 'org)
3740 (defcustom org-property-format "%-10s %s"
3741 "How property key/value pairs should be formatted by `indent-line'.
3742 When `indent-line' hits a property definition, it will format the line
3743 according to this format, mainly to make sure that the values are
3744 lined-up with respect to each other."
3745 :group 'org-properties
3746 :type 'string)
3748 (defcustom org-properties-postprocess-alist nil
3749 "Alist of properties and functions to adjust inserted values.
3750 Elements of this alist must be of the form
3752 ([string] [function])
3754 where [string] must be a property name and [function] must be a
3755 lambda expression: this lambda expression must take one argument,
3756 the value to adjust, and return the new value as a string.
3758 For example, this element will allow the property \"Remaining\"
3759 to be updated wrt the relation between the \"Effort\" property
3760 and the clock summary:
3762 ((\"Remaining\" (lambda(value)
3763 (let ((clocksum (org-clock-sum-current-item))
3764 (effort (org-duration-string-to-minutes
3765 (org-entry-get (point) \"Effort\"))))
3766 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3767 :group 'org-properties
3768 :version "24.1"
3769 :type '(alist :key-type (string :tag "Property")
3770 :value-type (function :tag "Function")))
3772 (defcustom org-use-property-inheritance nil
3773 "Non-nil means properties apply also for sublevels.
3775 This setting is chiefly used during property searches. Turning it on can
3776 cause significant overhead when doing a search, which is why it is not
3777 on by default.
3779 When nil, only the properties directly given in the current entry count.
3780 When t, every property is inherited. The value may also be a list of
3781 properties that should have inheritance, or a regular expression matching
3782 properties that should be inherited.
3784 However, note that some special properties use inheritance under special
3785 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3786 and the properties ending in \"_ALL\" when they are used as descriptor
3787 for valid values of a property.
3789 Note for programmers:
3790 When querying an entry with `org-entry-get', you can control if inheritance
3791 should be used. By default, `org-entry-get' looks only at the local
3792 properties. You can request inheritance by setting the inherit argument
3793 to t (to force inheritance) or to `selective' (to respect the setting
3794 in this variable)."
3795 :group 'org-properties
3796 :type '(choice
3797 (const :tag "Not" nil)
3798 (const :tag "Always" t)
3799 (repeat :tag "Specific properties" (string :tag "Property"))
3800 (regexp :tag "Properties matched by regexp")))
3802 (defun org-property-inherit-p (property)
3803 "Check if PROPERTY is one that should be inherited."
3804 (cond
3805 ((eq org-use-property-inheritance t) t)
3806 ((not org-use-property-inheritance) nil)
3807 ((stringp org-use-property-inheritance)
3808 (string-match org-use-property-inheritance property))
3809 ((listp org-use-property-inheritance)
3810 (member property org-use-property-inheritance))
3811 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3813 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3814 "The default column format, if no other format has been defined.
3815 This variable can be set on the per-file basis by inserting a line
3817 #+COLUMNS: %25ITEM ....."
3818 :group 'org-properties
3819 :type 'string)
3821 (defcustom org-columns-ellipses ".."
3822 "The ellipses to be used when a field in column view is truncated.
3823 When this is the empty string, as many characters as possible are shown,
3824 but then there will be no visual indication that the field has been truncated.
3825 When this is a string of length N, the last N characters of a truncated
3826 field are replaced by this string. If the column is narrower than the
3827 ellipses string, only part of the ellipses string will be shown."
3828 :group 'org-properties
3829 :type 'string)
3831 (defconst org-global-properties-fixed
3832 '(("VISIBILITY_ALL" . "folded children content all")
3833 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3834 "List of property/value pairs that can be inherited by any entry.
3836 These are fixed values, for the preset properties. The user variable
3837 that can be used to add to this list is `org-global-properties'.
3839 The entries in this list are cons cells where the car is a property
3840 name and cdr is a string with the value. If the value represents
3841 multiple items like an \"_ALL\" property, separate the items by
3842 spaces.")
3844 (defcustom org-global-properties nil
3845 "List of property/value pairs that can be inherited by any entry.
3847 This list will be combined with the constant `org-global-properties-fixed'.
3849 The entries in this list are cons cells where the car is a property
3850 name and cdr is a string with the value.
3852 You can set buffer-local values for the same purpose in the variable
3853 `org-file-properties' this by adding lines like
3855 #+PROPERTY: NAME VALUE"
3856 :group 'org-properties
3857 :type '(repeat
3858 (cons (string :tag "Property")
3859 (string :tag "Value"))))
3861 (defvar-local org-file-properties nil
3862 "List of property/value pairs that can be inherited by any entry.
3863 Valid for the current buffer.
3864 This variable is populated from #+PROPERTY lines.")
3866 (defgroup org-agenda nil
3867 "Options concerning agenda views in Org-mode."
3868 :tag "Org Agenda"
3869 :group 'org)
3871 (defvar-local org-category nil
3872 "Variable used by org files to set a category for agenda display.
3873 Such files should use a file variable to set it, for example
3875 # -*- mode: org; org-category: \"ELisp\"
3877 or contain a special line
3879 #+CATEGORY: ELisp
3881 If the file does not specify a category, then file's base name
3882 is used instead.")
3883 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3885 (defcustom org-agenda-files nil
3886 "The files to be used for agenda display.
3887 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3888 \\[org-remove-file]. You can also use customize to edit the list.
3890 If an entry is a directory, all files in that directory that are matched by
3891 `org-agenda-file-regexp' will be part of the file list.
3893 If the value of the variable is not a list but a single file name, then
3894 the list of agenda files is actually stored and maintained in that file, one
3895 agenda file per line. In this file paths can be given relative to
3896 `org-directory'. Tilde expansion and environment variable substitution
3897 are also made."
3898 :group 'org-agenda
3899 :type '(choice
3900 (repeat :tag "List of files and directories" file)
3901 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3903 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3904 "Regular expression to match files for `org-agenda-files'.
3905 If any element in the list in that variable contains a directory instead
3906 of a normal file, all files in that directory that are matched by this
3907 regular expression will be included."
3908 :group 'org-agenda
3909 :type 'regexp)
3911 (defcustom org-agenda-text-search-extra-files nil
3912 "List of extra files to be searched by text search commands.
3913 These files will be searched in addition to the agenda files by the
3914 commands `org-search-view' (`\\[org-agenda] s') \
3915 and `org-occur-in-agenda-files'.
3916 Note that these files will only be searched for text search commands,
3917 not for the other agenda views like todo lists, tag searches or the weekly
3918 agenda. This variable is intended to list notes and possibly archive files
3919 that should also be searched by these two commands.
3920 In fact, if the first element in the list is the symbol `agenda-archives',
3921 then all archive files of all agenda files will be added to the search
3922 scope."
3923 :group 'org-agenda
3924 :type '(set :greedy t
3925 (const :tag "Agenda Archives" agenda-archives)
3926 (repeat :inline t (file))))
3928 (defvaralias 'org-agenda-multi-occur-extra-files
3929 'org-agenda-text-search-extra-files)
3931 (defcustom org-agenda-skip-unavailable-files nil
3932 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3933 A nil value means to remove them, after a query, from the list."
3934 :group 'org-agenda
3935 :type 'boolean)
3937 (defcustom org-calendar-to-agenda-key [?c]
3938 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3939 The command `org-calendar-goto-agenda' will be bound to this key. The
3940 default is the character `c' because then `c' can be used to switch back and
3941 forth between agenda and calendar."
3942 :group 'org-agenda
3943 :type 'sexp)
3945 (defcustom org-calendar-insert-diary-entry-key [?i]
3946 "The key to be installed in `calendar-mode-map' for adding diary entries.
3947 This option is irrelevant until `org-agenda-diary-file' has been configured
3948 to point to an Org file. When that is the case, the command
3949 `org-agenda-diary-entry' will be bound to the key given here, by default
3950 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3951 if you want to continue doing this, you need to change this to a different
3952 key."
3953 :group 'org-agenda
3954 :type 'sexp)
3956 (defcustom org-agenda-diary-file 'diary-file
3957 "File to which to add new entries with the `i' key in agenda and calendar.
3958 When this is the symbol `diary-file', the functionality in the Emacs
3959 calendar will be used to add entries to the `diary-file'. But when this
3960 points to a file, `org-agenda-diary-entry' will be used instead."
3961 :group 'org-agenda
3962 :type '(choice
3963 (const :tag "The standard Emacs diary file" diary-file)
3964 (file :tag "Special Org file diary entries")))
3966 (eval-after-load "calendar"
3967 '(progn
3968 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3969 'org-calendar-goto-agenda)
3970 (add-hook 'calendar-mode-hook
3971 (lambda ()
3972 (unless (eq org-agenda-diary-file 'diary-file)
3973 (define-key calendar-mode-map
3974 org-calendar-insert-diary-entry-key
3975 'org-agenda-diary-entry))))))
3977 (defgroup org-latex nil
3978 "Options for embedding LaTeX code into Org-mode."
3979 :tag "Org LaTeX"
3980 :group 'org)
3982 (defcustom org-format-latex-options
3983 '(:foreground default :background default :scale 1.0
3984 :html-foreground "Black" :html-background "Transparent"
3985 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3986 "Options for creating images from LaTeX fragments.
3987 This is a property list with the following properties:
3988 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3989 `default' means use the foreground of the default face.
3990 `auto' means use the foreground from the text face.
3991 :background the background color, or \"Transparent\".
3992 `default' means use the background of the default face.
3993 `auto' means use the background from the text face.
3994 :scale a scaling factor for the size of the images, to get more pixels
3995 :html-foreground, :html-background, :html-scale
3996 the same numbers for HTML export.
3997 :matchers a list indicating which matchers should be used to
3998 find LaTeX fragments. Valid members of this list are:
3999 \"begin\" find environments
4000 \"$1\" find single characters surrounded by $.$
4001 \"$\" find math expressions surrounded by $...$
4002 \"$$\" find math expressions surrounded by $$....$$
4003 \"\\(\" find math expressions surrounded by \\(...\\)
4004 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4005 :group 'org-latex
4006 :type 'plist)
4008 (defcustom org-format-latex-signal-error t
4009 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4010 When nil, just push out a message."
4011 :group 'org-latex
4012 :version "24.1"
4013 :type 'boolean)
4015 (defcustom org-latex-to-mathml-jar-file nil
4016 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4017 Use this to specify additional executable file say a jar file.
4019 When using MathToWeb as the converter, specify the full-path to
4020 your mathtoweb.jar file."
4021 :group 'org-latex
4022 :version "24.1"
4023 :type '(choice
4024 (const :tag "None" nil)
4025 (file :tag "JAR file" :must-match t)))
4027 (defcustom org-latex-to-mathml-convert-command nil
4028 "Command to convert LaTeX fragments to MathML.
4029 Replace format-specifiers in the command as noted below and use
4030 `shell-command' to convert LaTeX to MathML.
4031 %j: Executable file in fully expanded form as specified by
4032 `org-latex-to-mathml-jar-file'.
4033 %I: Input LaTeX file in fully expanded form.
4034 %i: The latex fragment to be converted.
4035 %o: Output MathML file.
4037 This command is used by `org-create-math-formula'.
4039 When using MathToWeb as the converter, set this option to
4040 \"java -jar %j -unicode -force -df %o %I\".
4042 When using LaTeXML set this option to
4043 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4044 :group 'org-latex
4045 :version "24.1"
4046 :type '(choice
4047 (const :tag "None" nil)
4048 (string :tag "\nShell command")))
4050 (defcustom org-preview-latex-default-process 'dvipng
4051 "The default process to convert LaTeX fragments to image files.
4052 All available processes and theirs documents can be found in
4053 `org-preview-latex-process-alist', which see."
4054 :group 'org-latex
4055 :version "25.2"
4056 :package-version '(Org . "9.0")
4057 :type 'symbol)
4059 (defcustom org-preview-latex-process-alist
4060 '((dvipng
4061 :programs ("latex" "dvipng" "gs")
4062 :description "dvi > png"
4063 :message "you need to install the programs: latex, dvipng and ghostscript."
4064 :image-input-type "dvi"
4065 :image-output-type "png"
4066 :image-size-adjust (1.0 . 1.0)
4067 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4068 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4069 (dvisvgm
4070 :programs ("latex" "dvisvgm" "gs")
4071 :description "dvi > svg"
4072 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4073 :use-xcolor t
4074 :image-input-type "dvi"
4075 :image-output-type "svg"
4076 :image-size-adjust (1.7 . 1.5)
4077 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4078 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4079 (imagemagick
4080 :programs ("latex" "convert" "gs")
4081 :description "pdf > png"
4082 :message
4083 "you need to install the programs: latex, imagemagick and ghostscript."
4084 :use-xcolor t
4085 :image-input-type "pdf"
4086 :image-output-type "png"
4087 :image-size-adjust (1.0 . 1.0)
4088 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4089 :image-converter
4090 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4091 "Definitions of external processes for LaTeX previewing.
4092 Org mode can use some external commands to generate TeX snippet's images for
4093 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4094 `org-create-formula-image' how to call them.
4096 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4097 PROPERTIES accepts the following attributes:
4099 :programs list of strings, required programs.
4100 :description string, describe the process.
4101 :message string, message it when required programs cannot be found.
4102 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4103 :image-output-type string, output file type of image converter (e.g., \"png\").
4104 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4105 deal with background and foreground color of image.
4106 Otherwise, dvipng style background and foregroud color
4107 format are generated. You may then refer to them in
4108 command options with \"%F\" and \"%B\".
4109 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4110 image size showed in buffer and the cdr element is for
4111 HTML file. This option is only useful for process
4112 developers, users should use variable
4113 `org-format-latex-options' instead.
4114 :post-clean list of strings, files matched are to be cleaned up once
4115 the image is generated. When nil, the files with \".dvi\",
4116 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4117 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4118 be cleaned up.
4119 :latex-header list of strings, the LaTeX header of the snippet file.
4120 When nil, the fallback value is used instead, which is
4121 controlled by `org-format-latex-header',
4122 `org-latex-default-packages-alist' and
4123 `org-latex-packages-alist', which see.
4124 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4125 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4126 replaced with values defined below.
4127 :image-converter list of image converter commands strings. Each of them is
4128 given to the shell and supports any of the following
4129 place-holders defined below.
4131 Place-holders used by `:image-converter' and `:latex-compiler':
4133 %f input file name.
4134 %b base name of input file.
4135 %o base directory of input file.
4137 Place-holders only used by `:image-converter':
4139 %F foreground of image
4140 %B background of image
4141 %D dpi, which is used to adjust image size by some processing commands.
4142 %S the image size scale ratio, which is used to adjust image size by some
4143 processing commands."
4144 :group 'org-latex
4145 :version "25.2"
4146 :package-version '(Org . "9.0")
4147 :type '(alist :tag "LaTeX to image backends"
4148 :value-type (plist)))
4150 (defcustom org-preview-latex-image-directory "ltximg/"
4151 "Path to store latex preview images.
4152 A relative path here creates many directories relative to the
4153 processed org files paths. An absolute path puts all preview
4154 images at the same place."
4155 :group 'org-latex
4156 :version "25.1"
4157 :package-version '(Org . "9.0")
4158 :type 'string)
4160 (defun org-format-latex-mathml-available-p ()
4161 "Return t if `org-latex-to-mathml-convert-command' is usable."
4162 (save-match-data
4163 (when (and (boundp 'org-latex-to-mathml-convert-command)
4164 org-latex-to-mathml-convert-command)
4165 (let ((executable (car (split-string
4166 org-latex-to-mathml-convert-command))))
4167 (when (executable-find executable)
4168 (if (string-match
4169 "%j" org-latex-to-mathml-convert-command)
4170 (file-readable-p org-latex-to-mathml-jar-file)
4171 t))))))
4173 (defcustom org-format-latex-header "\\documentclass{article}
4174 \\usepackage[usenames]{color}
4175 \[PACKAGES]
4176 \[DEFAULT-PACKAGES]
4177 \\pagestyle{empty} % do not remove
4178 % The settings below are copied from fullpage.sty
4179 \\setlength{\\textwidth}{\\paperwidth}
4180 \\addtolength{\\textwidth}{-3cm}
4181 \\setlength{\\oddsidemargin}{1.5cm}
4182 \\addtolength{\\oddsidemargin}{-2.54cm}
4183 \\setlength{\\evensidemargin}{\\oddsidemargin}
4184 \\setlength{\\textheight}{\\paperheight}
4185 \\addtolength{\\textheight}{-\\headheight}
4186 \\addtolength{\\textheight}{-\\headsep}
4187 \\addtolength{\\textheight}{-\\footskip}
4188 \\addtolength{\\textheight}{-3cm}
4189 \\setlength{\\topmargin}{1.5cm}
4190 \\addtolength{\\topmargin}{-2.54cm}"
4191 "The document header used for processing LaTeX fragments.
4192 It is imperative that this header make sure that no page number
4193 appears on the page. The package defined in the variables
4194 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4195 will either replace the placeholder \"[PACKAGES]\" in this
4196 header, or they will be appended."
4197 :group 'org-latex
4198 :type 'string)
4200 (defun org-set-packages-alist (var val)
4201 "Set the packages alist and make sure it has 3 elements per entry."
4202 (set var (mapcar (lambda (x)
4203 (if (and (consp x) (= (length x) 2))
4204 (list (car x) (nth 1 x) t)
4206 val)))
4208 (defun org-get-packages-alist (var)
4209 "Get the packages alist and make sure it has 3 elements per entry."
4210 (mapcar (lambda (x)
4211 (if (and (consp x) (= (length x) 2))
4212 (list (car x) (nth 1 x) t)
4214 (default-value var)))
4216 (defcustom org-latex-default-packages-alist
4217 '(("AUTO" "inputenc" t ("pdflatex"))
4218 ("T1" "fontenc" t ("pdflatex"))
4219 ("" "graphicx" t)
4220 ("" "grffile" t)
4221 ("" "longtable" nil)
4222 ("" "wrapfig" nil)
4223 ("" "rotating" nil)
4224 ("normalem" "ulem" t)
4225 ("" "amsmath" t)
4226 ("" "textcomp" t)
4227 ("" "amssymb" t)
4228 ("" "capt-of" nil)
4229 ("" "hyperref" nil))
4230 "Alist of default packages to be inserted in the header.
4232 Change this only if one of the packages here causes an
4233 incompatibility with another package you are using.
4235 The packages in this list are needed by one part or another of
4236 Org mode to function properly:
4238 - inputenc, fontenc: for basic font and character selection
4239 - graphicx: for including images
4240 - grffile: allow periods and spaces in graphics file names
4241 - longtable: For multipage tables
4242 - wrapfig: for figure placement
4243 - rotating: for sideways figures and tables
4244 - ulem: for underline and strike-through
4245 - amsmath: for subscript and superscript and math environments
4246 - textcomp, amssymb: for various symbols used
4247 for interpreting the entities in `org-entities'. You can skip
4248 some of these packages if you don't use any of their symbols.
4249 - capt-of: for captions outside of floats
4250 - hyperref: for cross references
4252 Therefore you should not modify this variable unless you know
4253 what you are doing. The one reason to change it anyway is that
4254 you might be loading some other package that conflicts with one
4255 of the default packages. Each element is either a cell or
4256 a string.
4258 A cell is of the format
4260 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4262 If SNIPPET-FLAG is non-nil, the package also needs to be included
4263 when compiling LaTeX snippets into images for inclusion into
4264 non-LaTeX output. COMPILERS is a list of compilers that should
4265 include the package, see `org-latex-compiler'. If the document
4266 compiler is not in the list, and the list is non-nil, the package
4267 will not be inserted in the final document.
4269 A string will be inserted as-is in the header of the document."
4270 :group 'org-latex
4271 :group 'org-export-latex
4272 :set 'org-set-packages-alist
4273 :get 'org-get-packages-alist
4274 :version "25.1"
4275 :package-version '(Org . "8.3")
4276 :type '(repeat
4277 (choice
4278 (list :tag "options/package pair"
4279 (string :tag "options")
4280 (string :tag "package")
4281 (boolean :tag "Snippet"))
4282 (string :tag "A line of LaTeX"))))
4284 (defcustom org-latex-packages-alist nil
4285 "Alist of packages to be inserted in every LaTeX header.
4287 These will be inserted after `org-latex-default-packages-alist'.
4288 Each element is either a cell or a string.
4290 A cell is of the format:
4292 (\"options\" \"package\" SNIPPET-FLAG)
4294 SNIPPET-FLAG, when non-nil, indicates that this package is also
4295 needed when turning LaTeX snippets into images for inclusion into
4296 non-LaTeX output.
4298 A string will be inserted as-is in the header of the document.
4300 Make sure that you only list packages here which:
4302 - you want in every file;
4303 - do not conflict with the setup in `org-format-latex-header';
4304 - do not conflict with the default packages in
4305 `org-latex-default-packages-alist'."
4306 :group 'org-latex
4307 :group 'org-export-latex
4308 :set 'org-set-packages-alist
4309 :get 'org-get-packages-alist
4310 :type '(repeat
4311 (choice
4312 (list :tag "options/package pair"
4313 (string :tag "options")
4314 (string :tag "package")
4315 (boolean :tag "Snippet"))
4316 (string :tag "A line of LaTeX"))))
4318 (defgroup org-appearance nil
4319 "Settings for Org mode appearance."
4320 :tag "Org Appearance"
4321 :group 'org)
4323 (defcustom org-level-color-stars-only nil
4324 "Non-nil means fontify only the stars in each headline.
4325 When nil, the entire headline is fontified.
4326 Changing it requires restart of `font-lock-mode' to become effective
4327 also in regions already fontified."
4328 :group 'org-appearance
4329 :type 'boolean)
4331 (defcustom org-hide-leading-stars nil
4332 "Non-nil means hide the first N-1 stars in a headline.
4333 This works by using the face `org-hide' for these stars. This
4334 face is white for a light background, and black for a dark
4335 background. You may have to customize the face `org-hide' to
4336 make this work.
4337 Changing it requires restart of `font-lock-mode' to become effective
4338 also in regions already fontified.
4339 You may also set this on a per-file basis by adding one of the following
4340 lines to the buffer:
4342 #+STARTUP: hidestars
4343 #+STARTUP: showstars"
4344 :group 'org-appearance
4345 :type 'boolean)
4347 (defcustom org-hidden-keywords nil
4348 "List of symbols corresponding to keywords to be hidden the org buffer.
4349 For example, a value \\='(title) for this list will make the document's title
4350 appear in the buffer without the initial #+TITLE: keyword."
4351 :group 'org-appearance
4352 :version "24.1"
4353 :type '(set (const :tag "#+AUTHOR" author)
4354 (const :tag "#+DATE" date)
4355 (const :tag "#+EMAIL" email)
4356 (const :tag "#+TITLE" title)))
4358 (defcustom org-custom-properties nil
4359 "List of properties (as strings) with a special meaning.
4360 The default use of these custom properties is to let the user
4361 hide them with `org-toggle-custom-properties-visibility'."
4362 :group 'org-properties
4363 :group 'org-appearance
4364 :version "24.3"
4365 :type '(repeat (string :tag "Property Name")))
4367 (defcustom org-fontify-done-headline nil
4368 "Non-nil means change the face of a headline if it is marked DONE.
4369 Normally, only the TODO/DONE keyword indicates the state of a headline.
4370 When this is non-nil, the headline after the keyword is set to the
4371 `org-headline-done' as an additional indication."
4372 :group 'org-appearance
4373 :type 'boolean)
4375 (defcustom org-fontify-emphasized-text t
4376 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4377 Changing this variable requires a restart of Emacs to take effect."
4378 :group 'org-appearance
4379 :type 'boolean)
4381 (defcustom org-fontify-whole-heading-line nil
4382 "Non-nil means fontify the whole line for headings.
4383 This is useful when setting a background color for the
4384 org-level-* faces."
4385 :group 'org-appearance
4386 :type 'boolean)
4388 (defcustom org-highlight-latex-and-related nil
4389 "Non-nil means highlight LaTeX related syntax in the buffer.
4390 When non nil, the value should be a list containing any of the
4391 following symbols:
4392 `latex' Highlight LaTeX snippets and environments.
4393 `script' Highlight subscript and superscript.
4394 `entities' Highlight entities."
4395 :group 'org-appearance
4396 :version "24.4"
4397 :package-version '(Org . "8.0")
4398 :type '(choice
4399 (const :tag "No highlighting" nil)
4400 (set :greedy t :tag "Highlight"
4401 (const :tag "LaTeX snippets and environments" latex)
4402 (const :tag "Subscript and superscript" script)
4403 (const :tag "Entities" entities))))
4405 (defcustom org-hide-emphasis-markers nil
4406 "Non-nil mean font-lock should hide the emphasis marker characters."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-hide-macro-markers nil
4411 "Non-nil mean font-lock should hide the brackets marking macro calls."
4412 :group 'org-appearance
4413 :type 'boolean)
4415 (defcustom org-pretty-entities nil
4416 "Non-nil means show entities as UTF8 characters.
4417 When nil, the \\name form remains in the buffer."
4418 :group 'org-appearance
4419 :version "24.1"
4420 :type 'boolean)
4422 (defcustom org-pretty-entities-include-sub-superscripts t
4423 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4424 :group 'org-appearance
4425 :version "24.1"
4426 :type 'boolean)
4428 (defvar org-emph-re nil
4429 "Regular expression for matching emphasis.
4430 After a match, the match groups contain these elements:
4431 0 The match of the full regular expression, including the characters
4432 before and after the proper match
4433 1 The character before the proper match, or empty at beginning of line
4434 2 The proper match, including the leading and trailing markers
4435 3 The leading marker like * or /, indicating the type of highlighting
4436 4 The text between the emphasis markers, not including the markers
4437 5 The character after the match, empty at the end of a line")
4438 (defvar org-verbatim-re nil
4439 "Regular expression for matching verbatim text.")
4440 (defvar org-emphasis-regexp-components) ; defined just below
4441 (defvar org-emphasis-alist) ; defined just below
4442 (defun org-set-emph-re (var val)
4443 "Set variable and compute the emphasis regular expression."
4444 (set var val)
4445 (when (and (boundp 'org-emphasis-alist)
4446 (boundp 'org-emphasis-regexp-components)
4447 org-emphasis-alist org-emphasis-regexp-components)
4448 (let* ((e org-emphasis-regexp-components)
4449 (pre (car e))
4450 (post (nth 1 e))
4451 (border (nth 2 e))
4452 (body (nth 3 e))
4453 (nl (nth 4 e))
4454 (body1 (concat body "*?"))
4455 (markers (mapconcat 'car org-emphasis-alist ""))
4456 (vmarkers (mapconcat
4457 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4458 org-emphasis-alist "")))
4459 ;; make sure special characters appear at the right position in the class
4460 (if (string-match "\\^" markers)
4461 (setq markers (concat (replace-match "" t t markers) "^")))
4462 (if (string-match "-" markers)
4463 (setq markers (concat (replace-match "" t t markers) "-")))
4464 (if (string-match "\\^" vmarkers)
4465 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4466 (if (string-match "-" vmarkers)
4467 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4468 (if (> nl 0)
4469 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4470 (int-to-string nl) "\\}")))
4471 ;; Make the regexp
4472 (setq org-emph-re
4473 (concat "\\([" pre "]\\|^\\)"
4474 "\\("
4475 "\\([" markers "]\\)"
4476 "\\("
4477 "[^" border "]\\|"
4478 "[^" border "]"
4479 body1
4480 "[^" border "]"
4481 "\\)"
4482 "\\3\\)"
4483 "\\([" post "]\\|$\\)"))
4484 (setq org-verbatim-re
4485 (concat "\\([" pre "]\\|^\\)"
4486 "\\("
4487 "\\([" vmarkers "]\\)"
4488 "\\("
4489 "[^" border "]\\|"
4490 "[^" border "]"
4491 body1
4492 "[^" border "]"
4493 "\\)"
4494 "\\3\\)"
4495 "\\([" post "]\\|$\\)")))))
4497 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4498 ;; set this option proved cumbersome. See this message/thread:
4499 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4500 (defvar org-emphasis-regexp-components
4501 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4502 "Components used to build the regular expression for emphasis.
4503 This is a list with five entries. Terminology: In an emphasis string
4504 like \" *strong word* \", we call the initial space PREMATCH, the final
4505 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4506 and \"trong wor\" is the body. The different components in this variable
4507 specify what is allowed/forbidden in each part:
4509 pre Chars allowed as prematch. Beginning of line will be allowed too.
4510 post Chars allowed as postmatch. End of line will be allowed too.
4511 border The chars *forbidden* as border characters.
4512 body-regexp A regexp like \".\" to match a body character. Don't use
4513 non-shy groups here, and don't allow newline here.
4514 newline The maximum number of newlines allowed in an emphasis exp.
4516 You need to reload Org or to restart Emacs after customizing this.")
4518 (defcustom org-emphasis-alist
4519 '(("*" bold)
4520 ("/" italic)
4521 ("_" underline)
4522 ("=" org-verbatim verbatim)
4523 ("~" org-code verbatim)
4524 ("+" (:strike-through t)))
4525 "Alist of characters and faces to emphasize text.
4526 Text starting and ending with a special character will be emphasized,
4527 for example *bold*, _underlined_ and /italic/. This variable sets the
4528 marker characters and the face to be used by font-lock for highlighting
4529 in Org buffers.
4531 You need to reload Org or to restart Emacs after customizing this."
4532 :group 'org-appearance
4533 :set 'org-set-emph-re
4534 :version "24.4"
4535 :package-version '(Org . "8.0")
4536 :type '(repeat
4537 (list
4538 (string :tag "Marker character")
4539 (choice
4540 (face :tag "Font-lock-face")
4541 (plist :tag "Face property list"))
4542 (option (const verbatim)))))
4544 (defvar org-protecting-blocks '("src" "example" "export")
4545 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4546 This is needed for font-lock setup.")
4548 ;;; Functions and variables from their packages
4549 ;; Declared here to avoid compiler warnings
4550 (defvar mark-active)
4552 ;; Various packages
4553 (declare-function calc-eval "calc" (str &optional separator &rest args))
4554 (declare-function calendar-forward-day "cal-move" (arg))
4555 (declare-function calendar-goto-date "cal-move" (date))
4556 (declare-function calendar-goto-today "cal-move" ())
4557 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4558 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4559 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4560 (declare-function cdlatex-tab "ext:cdlatex" ())
4561 (declare-function dired-get-filename
4562 "dired"
4563 (&optional localp no-error-if-not-filep))
4564 (declare-function iswitchb-read-buffer
4565 "iswitchb"
4566 (prompt &optional
4567 default require-match _predicate start matches-set))
4568 (declare-function org-agenda-change-all-lines
4569 "org-agenda"
4570 (newhead hdmarker &optional fixface just-this))
4571 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4572 "org-agenda"
4573 (&optional end))
4574 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4575 (declare-function org-agenda-format-item
4576 "org-agenda"
4577 (extra txt &optional level category tags dotime
4578 remove-re habitp))
4579 (declare-function org-agenda-maybe-redo "org-agenda" ())
4580 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4581 (declare-function org-agenda-save-markers-for-cut-and-paste
4582 "org-agenda"
4583 (beg end))
4584 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4585 (declare-function org-agenda-skip "org-agenda" ())
4586 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4587 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4588 (declare-function org-indent-mode "org-indent" (&optional arg))
4589 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4590 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4591 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4592 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4593 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4594 (declare-function parse-time-string "parse-time" (string))
4595 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4597 (defvar align-mode-rules-list)
4598 (defvar calc-embedded-close-formula)
4599 (defvar calc-embedded-open-formula)
4600 (defvar calc-embedded-open-mode)
4601 (defvar font-lock-unfontify-region-function)
4602 (defvar iswitchb-temp-buflist)
4603 (defvar org-agenda-tags-todo-honor-ignore-options)
4604 (defvar remember-data-file)
4605 (defvar texmathp-why)
4607 ;;;###autoload
4608 (defun turn-on-orgtbl ()
4609 "Unconditionally turn on `orgtbl-mode'."
4610 (require 'org-table)
4611 (orgtbl-mode 1))
4613 (defun org-at-table-p (&optional table-type)
4614 "Non-nil if the cursor is inside an Org table.
4615 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4616 If `org-enable-table-editor' is nil, return nil unconditionally."
4617 (and
4618 org-enable-table-editor
4619 (save-excursion
4620 (beginning-of-line)
4621 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4622 (or (not (derived-mode-p 'org-mode))
4623 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4624 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4626 (defun org-at-table.el-p ()
4627 "Non-nil when point is at a table.el table."
4628 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4629 (let ((element (org-element-at-point)))
4630 (and (eq (org-element-type element) 'table)
4631 (eq (org-element-property :type element) 'table.el)))))
4633 (defun org-at-table-hline-p ()
4634 "Non-nil when point is inside a hline in a table.
4635 Assume point is already in a table. If `org-enable-table-editor'
4636 is nil, return nil unconditionally."
4637 (and org-enable-table-editor
4638 (save-excursion
4639 (beginning-of-line)
4640 (looking-at org-table-hline-regexp))))
4642 (defun org-table-map-tables (function &optional quietly)
4643 "Apply FUNCTION to the start of all tables in the buffer."
4644 (org-with-wide-buffer
4645 (goto-char (point-min))
4646 (while (re-search-forward org-table-any-line-regexp nil t)
4647 (unless quietly
4648 (message "Mapping tables: %d%%"
4649 (floor (* 100.0 (point)) (buffer-size))))
4650 (beginning-of-line 1)
4651 (when (and (looking-at org-table-line-regexp)
4652 ;; Exclude tables in src/example/verbatim/clocktable blocks
4653 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4654 (save-excursion (funcall function))
4655 (or (looking-at org-table-line-regexp)
4656 (forward-char 1)))
4657 (re-search-forward org-table-any-border-regexp nil 1)))
4658 (unless quietly (message "Mapping tables: done")))
4660 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4661 (declare-function org-clock-update-mode-line "org-clock" ())
4662 (declare-function org-resolve-clocks "org-clock"
4663 (&optional also-non-dangling-p prompt last-valid))
4665 (defun org-at-TBLFM-p (&optional pos)
4666 "Non-nil when point (or POS) is in #+TBLFM line."
4667 (save-excursion
4668 (goto-char (or pos (point)))
4669 (beginning-of-line)
4670 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4671 (eq (org-element-type (org-element-at-point)) 'table))))
4673 (defvar org-clock-start-time)
4674 (defvar org-clock-marker (make-marker)
4675 "Marker recording the last clock-in.")
4676 (defvar org-clock-hd-marker (make-marker)
4677 "Marker recording the last clock-in, but the headline position.")
4678 (defvar org-clock-heading ""
4679 "The heading of the current clock entry.")
4680 (defun org-clock-is-active ()
4681 "Return the buffer where the clock is currently running.
4682 Return nil if no clock is running."
4683 (marker-buffer org-clock-marker))
4685 (defun org-check-running-clock ()
4686 "Check if the current buffer contains the running clock.
4687 If yes, offer to stop it and to save the buffer with the changes."
4688 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4689 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4690 (buffer-name))))
4691 (org-clock-out)
4692 (when (y-or-n-p "Save changed buffer?")
4693 (save-buffer))))
4695 (defun org-clocktable-try-shift (dir n)
4696 "Check if this line starts a clock table, if yes, shift the time block."
4697 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4698 (org-clocktable-shift dir n)))
4700 ;;;###autoload
4701 (defun org-clock-persistence-insinuate ()
4702 "Set up hooks for clock persistence."
4703 (require 'org-clock)
4704 (add-hook 'org-mode-hook 'org-clock-load)
4705 (add-hook 'kill-emacs-hook 'org-clock-save))
4707 (defgroup org-archive nil
4708 "Options concerning archiving in Org-mode."
4709 :tag "Org Archive"
4710 :group 'org-structure)
4712 (defcustom org-archive-location "%s_archive::"
4713 "The location where subtrees should be archived.
4715 The value of this variable is a string, consisting of two parts,
4716 separated by a double-colon. The first part is a filename and
4717 the second part is a headline.
4719 When the filename is omitted, archiving happens in the same file.
4720 %s in the filename will be replaced by the current file
4721 name (without the directory part). Archiving to a different file
4722 is useful to keep archived entries from contributing to the
4723 Org Agenda.
4725 The archived entries will be filed as subtrees of the specified
4726 headline. When the headline is omitted, the subtrees are simply
4727 filed away at the end of the file, as top-level entries. Also in
4728 the heading you can use %s to represent the file name, this can be
4729 useful when using the same archive for a number of different files.
4731 Here are a few examples:
4732 \"%s_archive::\"
4733 If the current file is Projects.org, archive in file
4734 Projects.org_archive, as top-level trees. This is the default.
4736 \"::* Archived Tasks\"
4737 Archive in the current file, under the top-level headline
4738 \"* Archived Tasks\".
4740 \"~/org/archive.org::\"
4741 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4743 \"~/org/archive.org::* From %s\"
4744 Archive in file ~/org/archive.org (absolute path), under headlines
4745 \"From FILENAME\" where file name is the current file name.
4747 \"~/org/datetree.org::datetree/* Finished Tasks\"
4748 The \"datetree/\" string is special, signifying to archive
4749 items to the datetree. Items are placed in either the CLOSED
4750 date of the item, or the current date if there is no CLOSED date.
4751 The heading will be a subentry to the current date. There doesn't
4752 need to be a heading, but there always needs to be a slash after
4753 datetree. For example, to store archived items directly in the
4754 datetree, use \"~/org/datetree.org::datetree/\".
4756 \"basement::** Finished Tasks\"
4757 Archive in file ./basement (relative path), as level 3 trees
4758 below the level 2 heading \"** Finished Tasks\".
4760 You may set this option on a per-file basis by adding to the buffer a
4761 line like
4763 #+ARCHIVE: basement::** Finished Tasks
4765 You may also define it locally for a subtree by setting an ARCHIVE property
4766 in the entry. If such a property is found in an entry, or anywhere up
4767 the hierarchy, it will be used."
4768 :group 'org-archive
4769 :type 'string)
4771 (defcustom org-agenda-skip-archived-trees t
4772 "Non-nil means the agenda will skip any items located in archived trees.
4773 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4774 variable is no longer recommended, you should leave it at the value t.
4775 Instead, use the key `v' to cycle the archives-mode in the agenda."
4776 :group 'org-archive
4777 :group 'org-agenda-skip
4778 :type 'boolean)
4780 (defcustom org-columns-skip-archived-trees t
4781 "Non-nil means ignore archived trees when creating column view."
4782 :group 'org-archive
4783 :group 'org-properties
4784 :type 'boolean)
4786 (defcustom org-cycle-open-archived-trees nil
4787 "Non-nil means `org-cycle' will open archived trees.
4788 An archived tree is a tree marked with the tag ARCHIVE.
4789 When nil, archived trees will stay folded. You can still open them with
4790 normal outline commands like `show-all', but not with the cycling commands."
4791 :group 'org-archive
4792 :group 'org-cycle
4793 :type 'boolean)
4795 (defcustom org-sparse-tree-open-archived-trees nil
4796 "Non-nil means sparse tree construction shows matches in archived trees.
4797 When nil, matches in these trees are highlighted, but the trees are kept in
4798 collapsed state."
4799 :group 'org-archive
4800 :group 'org-sparse-trees
4801 :type 'boolean)
4803 (defcustom org-sparse-tree-default-date-type nil
4804 "The default date type when building a sparse tree.
4805 When this is nil, a date is a scheduled or a deadline timestamp.
4806 Otherwise, these types are allowed:
4808 all: all timestamps
4809 active: only active timestamps (<...>)
4810 inactive: only inactive timestamps ([...])
4811 scheduled: only scheduled timestamps
4812 deadline: only deadline timestamps"
4813 :type '(choice (const :tag "Scheduled or deadline" nil)
4814 (const :tag "All timestamps" all)
4815 (const :tag "Only active timestamps" active)
4816 (const :tag "Only inactive timestamps" inactive)
4817 (const :tag "Only scheduled timestamps" scheduled)
4818 (const :tag "Only deadline timestamps" deadline)
4819 (const :tag "Only closed timestamps" closed))
4820 :version "25.1"
4821 :package-version '(Org . "8.3")
4822 :group 'org-sparse-trees)
4824 (defun org-cycle-hide-archived-subtrees (state)
4825 "Re-hide all archived subtrees after a visibility state change."
4826 (when (and (not org-cycle-open-archived-trees)
4827 (not (memq state '(overview folded))))
4828 (save-excursion
4829 (let* ((globalp (memq state '(contents all)))
4830 (beg (if globalp (point-min) (point)))
4831 (end (if globalp (point-max) (org-end-of-subtree t))))
4832 (org-hide-archived-subtrees beg end)
4833 (goto-char beg)
4834 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4835 (message "%s" (substitute-command-keys
4836 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4838 (defun org-force-cycle-archived ()
4839 "Cycle subtree even if it is archived."
4840 (interactive)
4841 (setq this-command 'org-cycle)
4842 (let ((org-cycle-open-archived-trees t))
4843 (call-interactively 'org-cycle)))
4845 (defun org-hide-archived-subtrees (beg end)
4846 "Re-hide all archived subtrees after a visibility state change."
4847 (org-with-wide-buffer
4848 (let ((case-fold-search nil)
4849 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4850 (goto-char beg)
4851 ;; Include headline point is currently on.
4852 (beginning-of-line)
4853 (while (and (< (point) end) (re-search-forward re end t))
4854 (when (member org-archive-tag (org-get-tags))
4855 (org-flag-subtree t)
4856 (org-end-of-subtree t))))))
4858 (declare-function outline-end-of-heading "outline" ())
4859 (declare-function outline-flag-region "outline" (from to flag))
4860 (defun org-flag-subtree (flag)
4861 (save-excursion
4862 (org-back-to-heading t)
4863 (outline-end-of-heading)
4864 (outline-flag-region (point)
4865 (progn (org-end-of-subtree t) (point))
4866 flag)))
4868 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4870 ;; Declare Column View Code
4872 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4873 (declare-function org-columns-compute "org-colview" (property))
4875 ;; Declare ID code
4877 (declare-function org-id-store-link "org-id")
4878 (declare-function org-id-locations-load "org-id")
4879 (declare-function org-id-locations-save "org-id")
4880 (defvar org-id-track-globally)
4882 ;;; Variables for pre-computed regular expressions, all buffer local
4884 (defvar-local org-todo-regexp nil
4885 "Matches any of the TODO state keywords.")
4886 (defvar-local org-not-done-regexp nil
4887 "Matches any of the TODO state keywords except the last one.")
4888 (defvar-local org-not-done-heading-regexp nil
4889 "Matches a TODO headline that is not done.")
4890 (defvar-local org-todo-line-regexp nil
4891 "Matches a headline and puts TODO state into group 2 if present.")
4892 (defvar-local org-complex-heading-regexp nil
4893 "Matches a headline and puts everything into groups:
4894 group 1: the stars
4895 group 2: The todo keyword, maybe
4896 group 3: Priority cookie
4897 group 4: True headline
4898 group 5: Tags")
4899 (defvar-local org-complex-heading-regexp-format nil
4900 "Printf format to make regexp to match an exact headline.
4901 This regexp will match the headline of any node which has the
4902 exact headline text that is put into the format, but may have any
4903 TODO state, priority and tags.")
4904 (defvar-local org-todo-line-tags-regexp nil
4905 "Matches a headline and puts TODO state into group 2 if present.
4906 Also put tags into group 4 if tags are present.")
4908 (defconst org-plain-time-of-day-regexp
4909 (concat
4910 "\\(\\<[012]?[0-9]"
4911 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4912 "\\(--?"
4913 "\\(\\<[012]?[0-9]"
4914 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4915 "\\)?")
4916 "Regular expression to match a plain time or time range.
4917 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4918 groups carry important information:
4919 0 the full match
4920 1 the first time, range or not
4921 8 the second time, if it is a range.")
4923 (defconst org-plain-time-extension-regexp
4924 (concat
4925 "\\(\\<[012]?[0-9]"
4926 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4927 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4928 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4929 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4930 groups carry important information:
4931 0 the full match
4932 7 hours of duration
4933 9 minutes of duration")
4935 (defconst org-stamp-time-of-day-regexp
4936 (concat
4937 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4938 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4939 "\\(--?"
4940 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4941 "Regular expression to match a timestamp time or time range.
4942 After a match, the following groups carry important information:
4943 0 the full match
4944 1 date plus weekday, for back referencing to make sure both times are on the same day
4945 2 the first time, range or not
4946 4 the second time, if it is a range.")
4948 (defconst org-startup-options
4949 '(("fold" org-startup-folded t)
4950 ("overview" org-startup-folded t)
4951 ("nofold" org-startup-folded nil)
4952 ("showall" org-startup-folded nil)
4953 ("showeverything" org-startup-folded showeverything)
4954 ("content" org-startup-folded content)
4955 ("indent" org-startup-indented t)
4956 ("noindent" org-startup-indented nil)
4957 ("hidestars" org-hide-leading-stars t)
4958 ("showstars" org-hide-leading-stars nil)
4959 ("odd" org-odd-levels-only t)
4960 ("oddeven" org-odd-levels-only nil)
4961 ("align" org-startup-align-all-tables t)
4962 ("noalign" org-startup-align-all-tables nil)
4963 ("inlineimages" org-startup-with-inline-images t)
4964 ("noinlineimages" org-startup-with-inline-images nil)
4965 ("latexpreview" org-startup-with-latex-preview t)
4966 ("nolatexpreview" org-startup-with-latex-preview nil)
4967 ("customtime" org-display-custom-times t)
4968 ("logdone" org-log-done time)
4969 ("lognotedone" org-log-done note)
4970 ("nologdone" org-log-done nil)
4971 ("lognoteclock-out" org-log-note-clock-out t)
4972 ("nolognoteclock-out" org-log-note-clock-out nil)
4973 ("logrepeat" org-log-repeat state)
4974 ("lognoterepeat" org-log-repeat note)
4975 ("logdrawer" org-log-into-drawer t)
4976 ("nologdrawer" org-log-into-drawer nil)
4977 ("logstatesreversed" org-log-states-order-reversed t)
4978 ("nologstatesreversed" org-log-states-order-reversed nil)
4979 ("nologrepeat" org-log-repeat nil)
4980 ("logreschedule" org-log-reschedule time)
4981 ("lognotereschedule" org-log-reschedule note)
4982 ("nologreschedule" org-log-reschedule nil)
4983 ("logredeadline" org-log-redeadline time)
4984 ("lognoteredeadline" org-log-redeadline note)
4985 ("nologredeadline" org-log-redeadline nil)
4986 ("logrefile" org-log-refile time)
4987 ("lognoterefile" org-log-refile note)
4988 ("nologrefile" org-log-refile nil)
4989 ("fninline" org-footnote-define-inline t)
4990 ("nofninline" org-footnote-define-inline nil)
4991 ("fnlocal" org-footnote-section nil)
4992 ("fnauto" org-footnote-auto-label t)
4993 ("fnprompt" org-footnote-auto-label nil)
4994 ("fnconfirm" org-footnote-auto-label confirm)
4995 ("fnplain" org-footnote-auto-label plain)
4996 ("fnadjust" org-footnote-auto-adjust t)
4997 ("nofnadjust" org-footnote-auto-adjust nil)
4998 ("constcgs" constants-unit-system cgs)
4999 ("constSI" constants-unit-system SI)
5000 ("noptag" org-tag-persistent-alist nil)
5001 ("hideblocks" org-hide-block-startup t)
5002 ("nohideblocks" org-hide-block-startup nil)
5003 ("beamer" org-startup-with-beamer-mode t)
5004 ("entitiespretty" org-pretty-entities t)
5005 ("entitiesplain" org-pretty-entities nil))
5006 "Variable associated with STARTUP options for org-mode.
5007 Each element is a list of three items: the startup options (as written
5008 in the #+STARTUP line), the corresponding variable, and the value to set
5009 this variable to if the option is found. An optional forth element PUSH
5010 means to push this value onto the list in the variable.")
5012 (defcustom org-group-tags t
5013 "When non-nil (the default), use group tags.
5014 This can be turned on/off through `org-toggle-tags-groups'."
5015 :group 'org-tags
5016 :group 'org-startup
5017 :type 'boolean)
5019 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5021 (defun org-toggle-tags-groups ()
5022 "Toggle support for group tags.
5023 Support for group tags is controlled by the option
5024 `org-group-tags', which is non-nil by default."
5025 (interactive)
5026 (setq org-group-tags (not org-group-tags))
5027 (cond ((and (derived-mode-p 'org-agenda-mode)
5028 org-group-tags)
5029 (org-agenda-redo))
5030 ((derived-mode-p 'org-mode)
5031 (let ((org-inhibit-startup t)) (org-mode))))
5032 (message "Groups tags support has been turned %s"
5033 (if org-group-tags "on" "off")))
5035 (defun org-set-regexps-and-options (&optional tags-only)
5036 "Precompute regular expressions used in the current buffer.
5037 When optional argument TAGS-ONLY is non-nil, only compute tags
5038 related expressions."
5039 (when (derived-mode-p 'org-mode)
5040 (let ((alist (org--setup-collect-keywords
5041 (org-make-options-regexp
5042 (append '("FILETAGS" "TAGS" "SETUPFILE")
5043 (and (not tags-only)
5044 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5045 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5046 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5047 ;; Startup options. Get this early since it does change
5048 ;; behavior for other options (e.g., tags).
5049 (let ((startup (cdr (assq 'startup alist))))
5050 (dolist (option startup)
5051 (let ((entry (assoc-string option org-startup-options t)))
5052 (when entry
5053 (let ((var (nth 1 entry))
5054 (val (nth 2 entry)))
5055 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5056 (unless (listp (symbol-value var))
5057 (set (make-local-variable var) nil))
5058 (add-to-list var val)))))))
5059 (setq-local org-file-tags
5060 (mapcar #'org-add-prop-inherited
5061 (cdr (assq 'filetags alist))))
5062 (setq org-current-tag-alist
5063 (append org-tag-persistent-alist
5064 (let ((tags (cdr (assq 'tags alist))))
5065 (if tags (org-tag-string-to-alist tags)
5066 org-tag-alist))))
5067 (setq org-tag-groups-alist
5068 (org-tag-alist-to-groups org-current-tag-alist))
5069 (unless tags-only
5070 ;; File properties.
5071 (setq-local org-file-properties (cdr (assq 'property alist)))
5072 ;; Archive location.
5073 (let ((archive (cdr (assq 'archive alist))))
5074 (when archive (setq-local org-archive-location archive)))
5075 ;; Category.
5076 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5077 (when cat
5078 (setq-local org-category (intern cat))
5079 (setq-local org-file-properties
5080 (org--update-property-plist
5081 "CATEGORY" cat org-file-properties))))
5082 ;; Columns.
5083 (let ((column (cdr (assq 'columns alist))))
5084 (when column (setq-local org-columns-default-format column)))
5085 ;; Constants.
5086 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5087 ;; Link abbreviations.
5088 (let ((links (cdr (assq 'link alist))))
5089 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5090 ;; Priorities.
5091 (let ((priorities (cdr (assq 'priorities alist))))
5092 (when priorities
5093 (setq-local org-highest-priority (nth 0 priorities))
5094 (setq-local org-lowest-priority (nth 1 priorities))
5095 (setq-local org-default-priority (nth 2 priorities))))
5096 ;; Scripts.
5097 (let ((scripts (assq 'scripts alist)))
5098 (when scripts
5099 (setq-local org-use-sub-superscripts (cdr scripts))))
5100 ;; TODO keywords.
5101 (setq-local org-todo-kwd-alist nil)
5102 (setq-local org-todo-key-alist nil)
5103 (setq-local org-todo-key-trigger nil)
5104 (setq-local org-todo-keywords-1 nil)
5105 (setq-local org-done-keywords nil)
5106 (setq-local org-todo-heads nil)
5107 (setq-local org-todo-sets nil)
5108 (setq-local org-todo-log-states nil)
5109 (let ((todo-sequences
5110 (or (nreverse (cdr (assq 'todo alist)))
5111 (let ((d (default-value 'org-todo-keywords)))
5112 (if (not (stringp (car d))) d
5113 ;; XXX: Backward compatibility code.
5114 (list (cons org-todo-interpretation d)))))))
5115 (dolist (sequence todo-sequences)
5116 (let* ((sequence (or (run-hook-with-args-until-success
5117 'org-todo-setup-filter-hook sequence)
5118 sequence))
5119 (sequence-type (car sequence))
5120 (keywords (cdr sequence))
5121 (sep (member "|" keywords))
5122 names alist)
5123 (dolist (k (remove "|" keywords))
5124 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5126 (error "Invalid TODO keyword %s" k))
5127 (let ((name (match-string 1 k))
5128 (key (match-string 2 k))
5129 (log (org-extract-log-state-settings k)))
5130 (push name names)
5131 (push (cons name (and key (string-to-char key))) alist)
5132 (when log (push log org-todo-log-states))))
5133 (let* ((names (nreverse names))
5134 (done (if sep (org-remove-keyword-keys (cdr sep))
5135 (last names)))
5136 (head (car names))
5137 (tail (list sequence-type head (car done) (org-last done))))
5138 (add-to-list 'org-todo-heads head 'append)
5139 (push names org-todo-sets)
5140 (setq org-done-keywords (append org-done-keywords done nil))
5141 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5142 (setq org-todo-key-alist
5143 (append org-todo-key-alist
5144 (and alist
5145 (append '((:startgroup))
5146 (nreverse alist)
5147 '((:endgroup))))))
5148 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5149 (setq org-todo-sets (nreverse org-todo-sets)
5150 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5151 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5152 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5153 ;; Compute the regular expressions and other local variables.
5154 ;; Using `org-outline-regexp-bol' would complicate them much,
5155 ;; because of the fixed white space at the end of that string.
5156 (unless org-done-keywords
5157 (setq org-done-keywords
5158 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5159 (setq org-not-done-keywords
5160 (org-delete-all org-done-keywords
5161 (copy-sequence org-todo-keywords-1))
5162 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5163 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5164 org-not-done-heading-regexp
5165 (format org-heading-keyword-regexp-format org-not-done-regexp)
5166 org-todo-line-regexp
5167 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5168 org-complex-heading-regexp
5169 (concat "^\\(\\*+\\)"
5170 "\\(?: +" org-todo-regexp "\\)?"
5171 "\\(?: +\\(\\[#.\\]\\)\\)?"
5172 "\\(?: +\\(.*?\\)\\)??"
5173 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5174 "[ \t]*$")
5175 org-complex-heading-regexp-format
5176 (concat "^\\(\\*+\\)"
5177 "\\(?: +" org-todo-regexp "\\)?"
5178 "\\(?: +\\(\\[#.\\]\\)\\)?"
5179 "\\(?: +"
5180 ;; Stats cookies can be stuck to body.
5181 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5182 "\\(%s\\)"
5183 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5184 "\\)"
5185 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5186 "[ \t]*$")
5187 org-todo-line-tags-regexp
5188 (concat "^\\(\\*+\\)"
5189 "\\(?: +" org-todo-regexp "\\)?"
5190 "\\(?: +\\(.*?\\)\\)??"
5191 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5192 "[ \t]*$"))
5193 (org-compute-latex-and-related-regexp)))))
5195 (defun org--setup-collect-keywords (regexp &optional files alist)
5196 "Return setup keywords values as an alist.
5198 REGEXP matches a subset of setup keywords. FILES is a list of
5199 file names already visited. It is used to avoid circular setup
5200 files. ALIST, when non-nil, is the alist computed so far.
5202 Return value contains the following keys: `archive', `category',
5203 `columns', `constants', `filetags', `link', `priorities',
5204 `property', `scripts', `startup', `tags' and `todo'."
5205 (org-with-wide-buffer
5206 (goto-char (point-min))
5207 (let ((case-fold-search t))
5208 (while (re-search-forward regexp nil t)
5209 (let ((element (org-element-at-point)))
5210 (when (eq (org-element-type element) 'keyword)
5211 (let ((key (org-element-property :key element))
5212 (value (org-element-property :value element)))
5213 (cond
5214 ((equal key "ARCHIVE")
5215 (when (org-string-nw-p value)
5216 (push (cons 'archive value) alist)))
5217 ((equal key "CATEGORY") (push (cons 'category value) alist))
5218 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5219 ((equal key "CONSTANTS")
5220 (let* ((constants (assq 'constants alist))
5221 (store (cdr constants)))
5222 (dolist (pair (org-split-string value))
5223 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5224 pair)
5225 (let* ((name (match-string 1 pair))
5226 (value (match-string 2 pair))
5227 (old (assoc name store)))
5228 (if old (setcdr old value)
5229 (push (cons name value) store)))))
5230 (if constants (setcdr constants store)
5231 (push (cons 'constants store) alist))))
5232 ((equal key "FILETAGS")
5233 (when (org-string-nw-p value)
5234 (let ((old (assq 'filetags alist))
5235 (new (apply #'nconc
5236 (mapcar (lambda (x) (org-split-string x ":"))
5237 (org-split-string value)))))
5238 (if old (setcdr old (append new (cdr old)))
5239 (push (cons 'filetags new) alist)))))
5240 ((equal key "LINK")
5241 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5242 (let ((links (assq 'link alist))
5243 (pair (cons (match-string-no-properties 1 value)
5244 (match-string-no-properties 2 value))))
5245 (if links (push pair (cdr links))
5246 (push (list 'link pair) alist)))))
5247 ((equal key "OPTIONS")
5248 (when (and (org-string-nw-p value)
5249 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5250 (push (cons 'scripts (read (match-string 1 value))) alist)))
5251 ((equal key "PRIORITIES")
5252 (push (cons 'priorities
5253 (let ((prio (org-split-string value)))
5254 (if (< (length prio) 3) '(?A ?C ?B)
5255 (mapcar #'string-to-char prio))))
5256 alist))
5257 ((equal key "PROPERTY")
5258 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5259 (let* ((property (assq 'property alist))
5260 (value (org--update-property-plist
5261 (match-string-no-properties 1 value)
5262 (match-string-no-properties 2 value)
5263 (cdr property))))
5264 (if property (setcdr property value)
5265 (push (cons 'property value) alist)))))
5266 ((equal key "STARTUP")
5267 (let ((startup (assq 'startup alist)))
5268 (if startup
5269 (setcdr startup
5270 (append (cdr startup) (org-split-string value)))
5271 (push (cons 'startup (org-split-string value)) alist))))
5272 ((equal key "TAGS")
5273 (let ((tag-cell (assq 'tags alist)))
5274 (if tag-cell
5275 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5276 (push (cons 'tags value) alist))))
5277 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5278 (let ((todo (assq 'todo alist))
5279 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5280 (org-split-string value))))
5281 (if todo (push value (cdr todo))
5282 (push (list 'todo value) alist))))
5283 ((equal key "SETUPFILE")
5284 (unless buffer-read-only ; Do not check in Gnus messages.
5285 (let ((f (and (org-string-nw-p value)
5286 (expand-file-name
5287 (org-unbracket-string "\"" "\"" value)))))
5288 (when (and f (file-readable-p f) (not (member f files)))
5289 (with-temp-buffer
5290 (setq default-directory (file-name-directory f))
5291 (insert-file-contents f)
5292 (setq alist
5293 ;; Fake Org mode to benefit from cache
5294 ;; without recurring needlessly.
5295 (let ((major-mode 'org-mode))
5296 (org--setup-collect-keywords
5297 regexp (cons f files) alist)))))))))))))))
5298 alist)
5300 (defun org-tag-string-to-alist (s)
5301 "Return tag alist associated to string S.
5302 S is a value for TAGS keyword or produced with
5303 `org-tag-alist-to-string'. Return value is an alist suitable for
5304 `org-tag-alist' or `org-tag-persistent-alist'."
5305 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5306 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5307 "\\|{.+?}\\)" ; regular expression
5308 "\\(?:(\\(.\\))\\)?\\'"))
5309 alist group-flag)
5310 (dolist (tokens lines (cdr (nreverse alist)))
5311 (push '(:newline) alist)
5312 (while tokens
5313 (let ((token (pop tokens)))
5314 (pcase token
5315 ("{"
5316 (push '(:startgroup) alist)
5317 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5318 ("}"
5319 (push '(:endgroup) alist)
5320 (setq group-flag nil))
5321 ("["
5322 (push '(:startgrouptag) alist)
5323 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5324 ("]"
5325 (push '(:endgrouptag) alist)
5326 (setq group-flag nil))
5327 (":"
5328 (push '(:grouptags) alist))
5329 ((guard (string-match tag-re token))
5330 (let ((tag (match-string 1 token))
5331 (key (and (match-beginning 2)
5332 (string-to-char (match-string 2 token)))))
5333 ;; Push all tags in groups, no matter if they already
5334 ;; appear somewhere else in the list.
5335 (when (or group-flag (not (assoc tag alist)))
5336 (push (cons tag key) alist))))))))))
5338 (defun org-tag-alist-to-string (alist &optional skip-key)
5339 "Return tag string associated to ALIST.
5341 ALIST is an alist, as defined in `org-tag-alist' or
5342 `org-tag-persistent-alist', or produced with
5343 `org-tag-string-to-alist'.
5345 Return value is a string suitable as a value for \"TAGS\"
5346 keyword.
5348 When optional argument SKIP-KEY is non-nil, skip selection keys
5349 next to tags."
5350 (mapconcat (lambda (token)
5351 (pcase token
5352 (`(:startgroup) "{")
5353 (`(:endgroup) "}")
5354 (`(:startgrouptag) "[")
5355 (`(:endgrouptag) "]")
5356 (`(:grouptags) ":")
5357 (`(:newline) "\\n")
5358 ((and
5359 (guard (not skip-key))
5360 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5361 (format "%s(%c)" tag key))
5362 (`(,(and tag (pred stringp)) . ,_) tag)
5363 (_ (user-error "Invalid tag token: %S" token))))
5364 alist
5365 " "))
5367 (defun org-tag-alist-to-groups (alist)
5368 "Return group alist from tag ALIST.
5369 ALIST is an alist, as defined in `org-tag-alist' or
5370 `org-tag-persistent-alist', or produced with
5371 `org-tag-string-to-alist'. Return value is an alist following
5372 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5373 a string, summarizing TAGS, as a list of strings."
5374 (let (groups group-status current-group)
5375 (dolist (token alist (nreverse groups))
5376 (pcase token
5377 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5378 (`(,(or :endgroup :endgrouptag))
5379 (when (eq group-status 'append)
5380 (push (nreverse current-group) groups))
5381 (setq group-status nil))
5382 (`(:grouptags) (setq group-status 'append))
5383 ((and `(,tag . ,_) (guard group-status))
5384 (if (eq group-status 'append) (push tag current-group)
5385 (setq current-group (list tag))))
5386 (_ nil)))))
5388 (defun org-file-contents (file &optional noerror)
5389 "Return the contents of FILE, as a string."
5390 (if (and file (file-readable-p file))
5391 (with-temp-buffer
5392 (insert-file-contents file)
5393 (buffer-string))
5394 (funcall (if noerror 'message 'error)
5395 "Cannot read file \"%s\"%s"
5396 file
5397 (let ((from (buffer-file-name (buffer-base-buffer))))
5398 (if from (concat " (referenced in file \"" from "\")") "")))))
5400 (defun org-extract-log-state-settings (x)
5401 "Extract the log state setting from a TODO keyword string.
5402 This will extract info from a string like \"WAIT(w@/!)\"."
5403 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5404 (let ((kw (match-string 1 x))
5405 (log1 (and (match-end 3) (match-string 3 x)))
5406 (log2 (and (match-end 4) (match-string 4 x))))
5407 (and (or log1 log2)
5408 (list kw
5409 (and log1 (if (equal log1 "!") 'time 'note))
5410 (and log2 (if (equal log2 "!") 'time 'note)))))))
5412 (defun org-remove-keyword-keys (list)
5413 "Remove a pair of parenthesis at the end of each string in LIST."
5414 (mapcar (lambda (x)
5415 (if (string-match "(.*)$" x)
5416 (substring x 0 (match-beginning 0))
5418 list))
5420 (defun org-assign-fast-keys (alist)
5421 "Assign fast keys to a keyword-key alist.
5422 Respect keys that are already there."
5423 (let (new e (alt ?0))
5424 (while (setq e (pop alist))
5425 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5426 (cdr e)) ;; Key already assigned.
5427 (push e new)
5428 (let ((clist (string-to-list (downcase (car e))))
5429 (used (append new alist)))
5430 (when (= (car clist) ?@)
5431 (pop clist))
5432 (while (and clist (rassoc (car clist) used))
5433 (pop clist))
5434 (unless clist
5435 (while (rassoc alt used)
5436 (cl-incf alt)))
5437 (push (cons (car e) (or (car clist) alt)) new))))
5438 (nreverse new)))
5440 ;;; Some variables used in various places
5442 (defvar org-window-configuration nil
5443 "Used in various places to store a window configuration.")
5444 (defvar org-selected-window nil
5445 "Used in various places to store a window configuration.")
5446 (defvar org-finish-function nil
5447 "Function to be called when `C-c C-c' is used.
5448 This is for getting out of special buffers like capture.")
5449 (defvar org-last-state)
5451 ;; Defined somewhere in this file, but used before definition.
5452 (defvar org-entities) ;; defined in org-entities.el
5453 (defvar org-struct-menu)
5454 (defvar org-org-menu)
5455 (defvar org-tbl-menu)
5457 ;;;; Define the Org mode
5459 ;; We use a before-change function to check if a table might need
5460 ;; an update.
5461 (defvar org-table-may-need-update t
5462 "Indicates that a table might need an update.
5463 This variable is set by `org-before-change-function'.
5464 `org-table-align' sets it back to nil.")
5465 (defun org-before-change-function (_beg _end)
5466 "Every change indicates that a table might need an update."
5467 (setq org-table-may-need-update t))
5468 (defvar org-mode-map)
5469 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5470 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5471 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5472 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5473 (defvar org-table-buffer-is-an nil)
5475 (defvar bidi-paragraph-direction)
5476 (defvar buffer-face-mode-face)
5478 (require 'outline)
5480 ;; Other stuff we need.
5481 (require 'time-date)
5482 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5483 (require 'easymenu)
5484 (autoload 'easy-menu-add "easymenu")
5485 (require 'overlay)
5487 ;; (require 'org-macs) moved higher up in the file before it is first used
5488 (require 'org-entities)
5489 ;; (require 'org-compat) moved higher up in the file before it is first used
5490 (require 'org-faces)
5491 (require 'org-list)
5492 (require 'org-pcomplete)
5493 (require 'org-src)
5494 (require 'org-footnote)
5495 (require 'org-macro)
5497 ;; babel
5498 (require 'ob)
5500 ;;;###autoload
5501 (define-derived-mode org-mode outline-mode "Org"
5502 "Outline-based notes management and organizer, alias
5503 \"Carsten's outline-mode for keeping track of everything.\"
5505 Org mode develops organizational tasks around a NOTES file which
5506 contains information about projects as plain text. Org mode is
5507 implemented on top of Outline mode, which is ideal to keep the content
5508 of large files well structured. It supports ToDo items, deadlines and
5509 time stamps, which magically appear in the diary listing of the Emacs
5510 calendar. Tables are easily created with a built-in table editor.
5511 Plain text URL-like links connect to websites, emails (VM), Usenet
5512 messages (Gnus), BBDB entries, and any files related to the project.
5513 For printing and sharing of notes, an Org file (or a part of it)
5514 can be exported as a structured ASCII or HTML file.
5516 The following commands are available:
5518 \\{org-mode-map}"
5520 ;; Get rid of Outline menus, they are not needed
5521 ;; Need to do this here because define-derived-mode sets up
5522 ;; the keymap so late. Still, it is a waste to call this each time
5523 ;; we switch another buffer into Org mode.
5524 (define-key org-mode-map [menu-bar headings] 'undefined)
5525 (define-key org-mode-map [menu-bar hide] 'undefined)
5526 (define-key org-mode-map [menu-bar show] 'undefined)
5528 (org-load-modules-maybe)
5529 (org-install-agenda-files-menu)
5530 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5531 (add-to-invisibility-spec '(org-cwidth))
5532 (add-to-invisibility-spec '(org-hide-block . t))
5533 (setq-local outline-regexp org-outline-regexp)
5534 (setq-local outline-level 'org-outline-level)
5535 (setq bidi-paragraph-direction 'left-to-right)
5536 (when (and org-ellipsis
5537 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5538 (fboundp 'make-glyph-code))
5539 (unless org-display-table
5540 (setq org-display-table (make-display-table)))
5541 (set-display-table-slot
5542 org-display-table 4
5543 (vconcat (mapcar
5544 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5545 org-ellipsis)))
5546 (if (stringp org-ellipsis) org-ellipsis "..."))))
5547 (setq buffer-display-table org-display-table))
5548 (org-set-regexps-and-options)
5549 (org-set-font-lock-defaults)
5550 (when (and org-tag-faces (not org-tags-special-faces-re))
5551 ;; tag faces set outside customize.... force initialization.
5552 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5553 ;; Calc embedded
5554 (setq-local calc-embedded-open-mode "# ")
5555 ;; Modify a few syntax entries
5556 (modify-syntax-entry ?@ "w")
5557 (modify-syntax-entry ?\" "\"")
5558 (modify-syntax-entry ?\\ "_")
5559 (modify-syntax-entry ?~ "_")
5560 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5561 ;; Activate before-change-function
5562 (setq-local org-table-may-need-update t)
5563 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5564 ;; Check for running clock before killing a buffer
5565 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5566 ;; Initialize macros templates.
5567 (org-macro-initialize-templates)
5568 ;; Initialize radio targets.
5569 (org-update-radio-target-regexp)
5570 ;; Indentation.
5571 (setq-local indent-line-function 'org-indent-line)
5572 (setq-local indent-region-function 'org-indent-region)
5573 ;; Filling and auto-filling.
5574 (org-setup-filling)
5575 ;; Comments.
5576 (org-setup-comments-handling)
5577 ;; Initialize cache.
5578 (org-element-cache-reset)
5579 ;; Beginning/end of defun
5580 (setq-local beginning-of-defun-function 'org-backward-element)
5581 (setq-local end-of-defun-function
5582 (lambda ()
5583 (if (not (org-at-heading-p))
5584 (org-forward-element)
5585 (org-forward-element)
5586 (forward-char -1))))
5587 ;; Next error for sparse trees
5588 (setq-local next-error-function 'org-occur-next-match)
5589 ;; Make sure dependence stuff works reliably, even for users who set it
5590 ;; too late :-(
5591 (if org-enforce-todo-dependencies
5592 (add-hook 'org-blocker-hook
5593 'org-block-todo-from-children-or-siblings-or-parent)
5594 (remove-hook 'org-blocker-hook
5595 'org-block-todo-from-children-or-siblings-or-parent))
5596 (if org-enforce-todo-checkbox-dependencies
5597 (add-hook 'org-blocker-hook
5598 'org-block-todo-from-checkboxes)
5599 (remove-hook 'org-blocker-hook
5600 'org-block-todo-from-checkboxes))
5602 ;; Align options lines
5603 (setq-local
5604 align-mode-rules-list
5605 '((org-in-buffer-settings
5606 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5607 (modes . '(org-mode)))))
5609 ;; Imenu
5610 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5612 ;; Make isearch reveal context
5613 (setq-local outline-isearch-open-invisible-function
5614 (lambda (&rest _) (org-show-context 'isearch)))
5616 ;; Setup the pcomplete hooks
5617 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5618 (setq-local pcomplete-command-name-function 'org-command-at-point)
5619 (setq-local pcomplete-default-completion-function 'ignore)
5620 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5621 (setq-local pcomplete-termination-string "")
5622 (setq-local buffer-face-mode-face 'org-default)
5624 ;; If empty file that did not turn on Org mode automatically, make
5625 ;; it to.
5626 (when (and org-insert-mode-line-in-empty-file
5627 (called-interactively-p 'any)
5628 (= (point-min) (point-max)))
5629 (insert "# -*- mode: org -*-\n\n"))
5630 (unless org-inhibit-startup
5631 (org-unmodified
5632 (when org-startup-with-beamer-mode (org-beamer-mode))
5633 (when org-startup-align-all-tables
5634 (org-table-map-tables #'org-table-align t))
5635 (when org-startup-with-inline-images (org-display-inline-images))
5636 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5637 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5638 (when org-startup-truncated (setq truncate-lines t))
5639 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5640 (org-refresh-effort-properties)))
5641 ;; Try to set `org-hide' face correctly.
5642 (let ((foreground (org-find-invisible-foreground)))
5643 (when foreground
5644 (set-face-foreground 'org-hide foreground))))
5646 ;; Update `customize-package-emacs-version-alist'
5647 (add-to-list 'customize-package-emacs-version-alist
5648 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5649 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5650 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5652 (defvar org-mode-transpose-word-syntax-table
5653 (let ((st (make-syntax-table text-mode-syntax-table)))
5654 (dolist (c org-emphasis-alist st)
5655 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5657 (when (fboundp 'abbrev-table-put)
5658 (abbrev-table-put org-mode-abbrev-table
5659 :parents (list text-mode-abbrev-table)))
5661 (defun org-find-invisible-foreground ()
5662 (let ((candidates (remove
5663 "unspecified-bg"
5664 (nconc
5665 (list (face-background 'default)
5666 (face-background 'org-default))
5667 (mapcar
5668 (lambda (alist)
5669 (when (boundp alist)
5670 (cdr (assq 'background-color (symbol-value alist)))))
5671 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5672 (list (face-foreground 'org-hide))))))
5673 (car (remove nil candidates))))
5675 (defun org-current-time (&optional rounding-minutes past)
5676 "Current time, possibly rounded to ROUNDING-MINUTES.
5677 When ROUNDING-MINUTES is not an integer, fall back on the car of
5678 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5679 the rounding returns a past time."
5680 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5681 (car org-time-stamp-rounding-minutes)))
5682 (time (decode-time)) res)
5683 (if (< r 1)
5684 (current-time)
5685 (setq res
5686 (apply 'encode-time
5687 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5688 (nthcdr 2 time))))
5689 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5690 (seconds-to-time (- (float-time res) (* r 60)))
5691 res))))
5693 (defun org-today ()
5694 "Return today date, considering `org-extend-today-until'."
5695 (time-to-days
5696 (time-subtract (current-time)
5697 (list 0 (* 3600 org-extend-today-until) 0))))
5699 ;;;; Font-Lock stuff, including the activators
5701 (defvar org-mouse-map (make-sparse-keymap))
5702 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5703 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5704 (when org-mouse-1-follows-link
5705 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5706 (when org-tab-follows-link
5707 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5708 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5710 (require 'font-lock)
5712 (defconst org-non-link-chars "]\t\n\r<>")
5713 (defvar org-link-types-re nil
5714 "Matches a link that has a url-like prefix like \"http:\"")
5715 (defvar org-link-re-with-space nil
5716 "Matches a link with spaces, optional angular brackets around it.")
5717 (defvar org-link-re-with-space2 nil
5718 "Matches a link with spaces, optional angular brackets around it.")
5719 (defvar org-link-re-with-space3 nil
5720 "Matches a link with spaces, only for internal part in bracket links.")
5721 (defvar org-angle-link-re nil
5722 "Matches link with angular brackets, spaces are allowed.")
5723 (defvar org-plain-link-re nil
5724 "Matches plain link, without spaces.")
5725 (defvar org-bracket-link-regexp nil
5726 "Matches a link in double brackets.")
5727 (defvar org-bracket-link-analytic-regexp nil
5728 "Regular expression used to analyze links.
5729 Here is what the match groups contain after a match:
5730 1: http:
5731 2: http
5732 3: path
5733 4: [desc]
5734 5: desc")
5735 (defvar org-bracket-link-analytic-regexp++ nil
5736 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5737 (defvar org-any-link-re nil
5738 "Regular expression matching any link.")
5740 (defconst org-match-sexp-depth 3
5741 "Number of stacked braces for sub/superscript matching.")
5743 (defun org-create-multibrace-regexp (left right n)
5744 "Create a regular expression which will match a balanced sexp.
5745 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5746 as single character strings.
5747 The regexp returned will match the entire expression including the
5748 delimiters. It will also define a single group which contains the
5749 match except for the outermost delimiters. The maximum depth of
5750 stacked delimiters is N. Escaping delimiters is not possible."
5751 (let* ((nothing (concat "[^" left right "]*?"))
5752 (or "\\|")
5753 (re nothing)
5754 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5755 (while (> n 1)
5756 (setq n (1- n)
5757 re (concat re or next)
5758 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5759 (concat left "\\(" re "\\)" right)))
5761 (defconst org-match-substring-regexp
5762 (concat
5763 "\\(\\S-\\)\\([_^]\\)\\("
5764 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5765 "\\|"
5766 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5767 "\\|"
5768 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5769 "The regular expression matching a sub- or superscript.")
5771 (defconst org-match-substring-with-braces-regexp
5772 (concat
5773 "\\(\\S-\\)\\([_^]\\)"
5774 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5775 "The regular expression matching a sub- or superscript, forcing braces.")
5777 (defun org-make-link-regexps ()
5778 "Update the link regular expressions.
5779 This should be called after the variable `org-link-parameters' has changed."
5780 (let ((types-re (regexp-opt (org-link-types) t)))
5781 (setq org-link-types-re
5782 (concat "\\`" types-re ":")
5783 org-link-re-with-space
5784 (concat "<?" types-re ":"
5785 "\\([^" org-non-link-chars " ]"
5786 "[^" org-non-link-chars "]*"
5787 "[^" org-non-link-chars " ]\\)>?")
5788 org-link-re-with-space2
5789 (concat "<?" types-re ":"
5790 "\\([^" org-non-link-chars " ]"
5791 "[^\t\n\r]*"
5792 "[^" org-non-link-chars " ]\\)>?")
5793 org-link-re-with-space3
5794 (concat "<?" types-re ":"
5795 "\\([^" org-non-link-chars " ]"
5796 "[^\t\n\r]*\\)")
5797 org-angle-link-re
5798 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5799 types-re)
5800 org-plain-link-re
5801 (concat
5802 "\\<" types-re ":"
5803 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5804 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5805 org-bracket-link-regexp
5806 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5807 org-bracket-link-analytic-regexp
5808 (concat
5809 "\\[\\["
5810 "\\(" types-re ":\\)?"
5811 "\\([^]]+\\)"
5812 "\\]"
5813 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5814 "\\]")
5815 org-bracket-link-analytic-regexp++
5816 (concat
5817 "\\[\\["
5818 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5819 "\\([^]]+\\)"
5820 "\\]"
5821 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5822 "\\]")
5823 org-any-link-re
5824 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5825 org-angle-link-re "\\)\\|\\("
5826 org-plain-link-re "\\)"))))
5828 (org-make-link-regexps)
5830 (defvar org-emph-face nil)
5832 (defun org-do-emphasis-faces (limit)
5833 "Run through the buffer and emphasize strings."
5834 (let (rtn a)
5835 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5836 (let* ((border (char-after (match-beginning 3)))
5837 (bre (regexp-quote (char-to-string border))))
5838 (when (and (not (= border (char-after (match-beginning 4))))
5839 (not (string-match-p (concat bre ".*" bre)
5840 (replace-regexp-in-string
5841 "\n" " "
5842 (substring (match-string 2) 1 -1)))))
5843 (setq rtn t)
5844 (setq a (assoc (match-string 3) org-emphasis-alist))
5845 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5846 'face
5847 (nth 1 a))
5848 (and (nth 2 a)
5849 (org-remove-flyspell-overlays-in
5850 (match-beginning 0) (match-end 0)))
5851 (add-text-properties (match-beginning 2) (match-end 2)
5852 '(font-lock-multiline t org-emphasis t))
5853 (when org-hide-emphasis-markers
5854 (add-text-properties (match-end 4) (match-beginning 5)
5855 '(invisible org-link))
5856 (add-text-properties (match-beginning 3) (match-end 3)
5857 '(invisible org-link)))))
5858 (goto-char (1+ (match-beginning 0))))
5859 rtn))
5861 (defun org-emphasize (&optional char)
5862 "Insert or change an emphasis, i.e. a font like bold or italic.
5863 If there is an active region, change that region to a new emphasis.
5864 If there is no region, just insert the marker characters and position
5865 the cursor between them.
5866 CHAR should be the marker character. If it is a space, it means to
5867 remove the emphasis of the selected region.
5868 If CHAR is not given (for example in an interactive call) it will be
5869 prompted for."
5870 (interactive)
5871 (let ((erc org-emphasis-regexp-components)
5872 (string "") beg end move s)
5873 (if (org-region-active-p)
5874 (setq beg (region-beginning)
5875 end (region-end)
5876 string (buffer-substring beg end))
5877 (setq move t))
5879 (unless char
5880 (message "Emphasis marker or tag: [%s]"
5881 (mapconcat #'car org-emphasis-alist ""))
5882 (setq char (read-char-exclusive)))
5883 (if (equal char ?\s)
5884 (setq s ""
5885 move nil)
5886 (unless (assoc (char-to-string char) org-emphasis-alist)
5887 (user-error "No such emphasis marker: \"%c\"" char))
5888 (setq s (char-to-string char)))
5889 (while (and (> (length string) 1)
5890 (equal (substring string 0 1) (substring string -1))
5891 (assoc (substring string 0 1) org-emphasis-alist))
5892 (setq string (substring string 1 -1)))
5893 (setq string (concat s string s))
5894 (when beg (delete-region beg end))
5895 (unless (or (bolp)
5896 (string-match (concat "[" (nth 0 erc) "\n]")
5897 (char-to-string (char-before (point)))))
5898 (insert " "))
5899 (unless (or (eobp)
5900 (string-match (concat "[" (nth 1 erc) "\n]")
5901 (char-to-string (char-after (point)))))
5902 (insert " ") (backward-char 1))
5903 (insert string)
5904 (and move (backward-char 1))))
5906 (defconst org-nonsticky-props
5907 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5909 (defsubst org-rear-nonsticky-at (pos)
5910 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5912 (defun org-activate-plain-links (limit)
5913 "Add link properties for plain links."
5914 (when (and (re-search-forward org-plain-link-re limit t)
5915 (not (org-in-src-block-p)))
5917 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5918 'face))
5919 (link (match-string-no-properties 0))
5920 (type (match-string-no-properties 1))
5921 (path (match-string-no-properties 2))
5922 (link-start (match-beginning 0))
5923 (link-end (match-end 0))
5924 (link-face (org-link-get-parameter type :face))
5925 (help-echo (org-link-get-parameter type :help-echo))
5926 (htmlize-link (org-link-get-parameter type :htmlize-link))
5927 (activate-func (org-link-get-parameter type :activate-func)))
5928 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5929 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5930 (add-text-properties (match-beginning 0) (match-end 0)
5931 (list
5932 'mouse-face (or (org-link-get-parameter type :mouse-face)
5933 'highlight)
5934 'face (cond
5935 ;; A function that returns a face
5936 ((functionp link-face)
5937 (funcall link-face path))
5938 ;; a face
5939 ((facep link-face)
5940 link-face)
5941 ;; An anonymous face
5942 ((consp link-face)
5943 link-face)
5944 ;; default
5946 'org-link))
5947 'help-echo (cond
5948 ((stringp help-echo)
5949 help-echo)
5950 ((functionp help-echo)
5951 help-echo)
5953 (concat "LINK: "
5954 (save-match-data
5955 (org-link-unescape link)))))
5956 'htmlize-link (cond
5957 ((functionp htmlize-link)
5958 (funcall htmlize-link path))
5960 `(:uri ,link)))
5961 'keymap (or (org-link-get-parameter type :keymap)
5962 org-mouse-map)
5963 'org-link-start (match-beginning 0)))
5964 (org-rear-nonsticky-at (match-end 0))
5965 (when activate-func
5966 (funcall activate-func link-start link-end path nil))
5967 t))))
5969 (defun org-activate-code (limit)
5970 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (remove-text-properties (match-beginning 0) (match-end 0)
5973 '(display t invisible t intangible t))
5976 (defcustom org-src-fontify-natively t
5977 "When non-nil, fontify code in code blocks.
5978 See also the `org-block' face."
5979 :type 'boolean
5980 :version "24.4"
5981 :package-version '(Org . "8.3")
5982 :group 'org-appearance
5983 :group 'org-babel)
5985 (defcustom org-allow-promoting-top-level-subtree nil
5986 "When non-nil, allow promoting a top level subtree.
5987 The leading star of the top level headline will be replaced
5988 by a #."
5989 :type 'boolean
5990 :version "24.1"
5991 :group 'org-appearance)
5993 (defun org-fontify-meta-lines-and-blocks (limit)
5994 (condition-case nil
5995 (org-fontify-meta-lines-and-blocks-1 limit)
5996 (error (message "org-mode fontification error in %S at %d"
5997 (current-buffer)
5998 (line-number-at-pos)))))
6000 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6001 "Fontify #+ lines and blocks."
6002 (let ((case-fold-search t))
6003 (when (re-search-forward
6004 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6005 limit t)
6006 (let ((beg (match-beginning 0))
6007 (block-start (match-end 0))
6008 (block-end nil)
6009 (lang (match-string 7))
6010 (beg1 (line-beginning-position 2))
6011 (dc1 (downcase (match-string 2)))
6012 (dc3 (downcase (match-string 3)))
6013 end end1 quoting block-type)
6014 (cond
6015 ((and (match-end 4) (equal dc3 "+begin"))
6016 ;; Truly a block
6017 (setq block-type (downcase (match-string 5))
6018 quoting (member block-type org-protecting-blocks))
6019 (when (re-search-forward
6020 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6021 nil t) ;; on purpose, we look further than LIMIT
6022 (setq end (min (point-max) (match-end 0))
6023 end1 (min (point-max) (1- (match-beginning 0))))
6024 (setq block-end (match-beginning 0))
6025 (when quoting
6026 (org-remove-flyspell-overlays-in beg1 end1)
6027 (remove-text-properties beg end
6028 '(display t invisible t intangible t)))
6029 (add-text-properties
6030 beg end '(font-lock-fontified t font-lock-multiline t))
6031 (add-text-properties beg beg1 '(face org-meta-line))
6032 (org-remove-flyspell-overlays-in beg beg1)
6033 (add-text-properties ; For end_src
6034 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6035 (org-remove-flyspell-overlays-in end1 end)
6036 (cond
6037 ((and lang (not (string= lang "")) org-src-fontify-natively)
6038 (org-src-font-lock-fontify-block lang block-start block-end)
6039 (add-text-properties beg1 block-end '(src-block t)))
6040 (quoting
6041 (add-text-properties beg1 (min (point-max) (1+ end1))
6042 (list 'face
6043 (list :inherit
6044 (let ((face-name
6045 (intern (format "org-block-%s" lang))))
6046 (append (and (facep face-name) (list face-name))
6047 '(org-block))))))) ; end of source block
6048 ((not org-fontify-quote-and-verse-blocks))
6049 ((string= block-type "quote")
6050 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6051 ((string= block-type "verse")
6052 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6053 (add-text-properties beg beg1 '(face org-block-begin-line))
6054 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6055 '(face org-block-end-line))
6057 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6058 (org-remove-flyspell-overlays-in
6059 (match-beginning 0)
6060 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6061 (add-text-properties
6062 beg (match-end 3)
6063 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6064 '(font-lock-fontified t invisible t)
6065 '(font-lock-fontified t face org-document-info-keyword)))
6066 (add-text-properties
6067 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6068 (if (string-equal dc1 "+title:")
6069 '(font-lock-fontified t face org-document-title)
6070 '(font-lock-fontified t face org-document-info))))
6071 ((equal dc1 "+caption:")
6072 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6073 (remove-text-properties (match-beginning 0) (match-end 0)
6074 '(display t invisible t intangible t))
6075 (add-text-properties (match-beginning 1) (match-end 3)
6076 '(font-lock-fontified t face org-meta-line))
6077 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6078 '(font-lock-fontified t face org-block))
6080 ((member dc3 '(" " ""))
6081 (org-remove-flyspell-overlays-in beg (match-end 0))
6082 (add-text-properties
6083 beg (match-end 0)
6084 '(font-lock-fontified t face font-lock-comment-face)))
6085 (t ;; just any other in-buffer setting, but not indented
6086 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6087 (remove-text-properties (match-beginning 0) (match-end 0)
6088 '(display t invisible t intangible t))
6089 (add-text-properties beg (match-end 0)
6090 '(font-lock-fontified t face org-meta-line))
6091 t))))))
6093 (defun org-fontify-drawers (limit)
6094 "Fontify drawers."
6095 (when (re-search-forward org-drawer-regexp limit t)
6096 (add-text-properties
6097 (match-beginning 0) (match-end 0)
6098 '(font-lock-fontified t face org-special-keyword))
6099 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6102 (defun org-fontify-macros (limit)
6103 "Fontify macros."
6104 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6105 (add-text-properties
6106 (match-beginning 0) (match-end 0)
6107 '(font-lock-fontified t face org-macro))
6108 (when org-hide-macro-markers
6109 (add-text-properties (match-end 2) (match-beginning 2)
6110 '(invisible t))
6111 (add-text-properties (match-beginning 1) (match-end 1)
6112 '(invisible t)))
6113 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6116 (defun org-activate-angle-links (limit)
6117 "Add text properties for angle links."
6118 (when (and (re-search-forward org-angle-link-re limit t)
6119 (not (org-in-src-block-p)))
6120 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6121 (add-text-properties (match-beginning 0) (match-end 0)
6122 (list 'mouse-face 'highlight
6123 'keymap org-mouse-map
6124 'font-lock-multiline t))
6125 (org-rear-nonsticky-at (match-end 0))
6128 (defun org-activate-footnote-links (limit)
6129 "Add text properties for footnotes."
6130 (let ((fn (org-footnote-next-reference-or-definition limit)))
6131 (when fn
6132 (let* ((beg (nth 1 fn))
6133 (end (nth 2 fn))
6134 (label (car fn))
6135 (referencep (/= (line-beginning-position) beg)))
6136 (when (and referencep (nth 3 fn))
6137 (save-excursion
6138 (goto-char beg)
6139 (search-forward (or label "fn:"))
6140 (org-remove-flyspell-overlays-in beg (match-end 0))))
6141 (add-text-properties beg end
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map
6144 'help-echo
6145 (if referencep "Footnote reference"
6146 "Footnote definition")
6147 'font-lock-fontified t
6148 'font-lock-multiline t
6149 'face 'org-footnote))))))
6151 (defun org-activate-bracket-links (limit)
6152 "Add text properties for bracketed links."
6153 (when (and (re-search-forward org-bracket-link-regexp limit t)
6154 (not (org-in-src-block-p)))
6155 (let* ((hl (save-match-data
6156 (org-link-expand-abbrev (match-string-no-properties 1))))
6157 (type (save-match-data
6158 (and (string-match org-plain-link-re hl)
6159 (match-string-no-properties 1 hl))))
6160 (path (save-match-data
6161 (and (string-match org-plain-link-re hl)
6162 (match-string-no-properties 2 hl))))
6163 (link-start (match-beginning 0))
6164 (link-end (match-end 0))
6165 (bracketp t)
6166 (help-echo (org-link-get-parameter type :help-echo))
6167 (help (cond
6168 ((stringp help-echo)
6169 help-echo)
6170 ((functionp help-echo)
6171 help-echo)
6173 (concat "LINK: "
6174 (save-match-data
6175 (org-link-unescape hl))))))
6176 (link-face (org-link-get-parameter type :face))
6177 (face (cond
6178 ;; A function that returns a face
6179 ((functionp link-face)
6180 (funcall link-face path))
6181 ;; a face
6182 ((facep link-face)
6183 link-face)
6184 ;; An anonymous face
6185 ((consp link-face)
6186 link-face)
6187 ;; default
6189 'org-link)))
6190 (keymap (or (org-link-get-parameter type :keymap)
6191 org-mouse-map))
6192 (mouse-face (or (org-link-get-parameter type :mouse-face)
6193 'highlight))
6194 (htmlize (org-link-get-parameter type :htmlize-link))
6195 (htmlize-link (cond
6196 ((functionp htmlize)
6197 (funcall htmlize))
6199 `(:uri ,(format "%s:%s" type path)))))
6200 (activate-func (org-link-get-parameter type :activate-func))
6201 ;; invisible part
6202 (ip (list 'invisible (or
6203 (org-link-get-parameter type :display)
6204 'org-link)
6205 'face face
6206 'keymap keymap
6207 'mouse-face mouse-face
6208 'font-lock-multiline t
6209 'help-echo help
6210 'htmlize-link htmlize-link))
6211 ;; visible part
6212 (vp (list 'keymap keymap
6213 'face face
6214 'mouse-face mouse-face
6215 'font-lock-multiline t
6216 'help-echo help
6217 'htmlize-link htmlize-link)))
6218 ;; We need to remove the invisible property here. Table narrowing
6219 ;; may have made some of this invisible.
6220 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6221 (remove-text-properties (match-beginning 0) (match-end 0)
6222 '(invisible nil))
6223 (if (match-end 3)
6224 (progn
6225 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6226 (org-rear-nonsticky-at (match-beginning 3))
6227 (add-text-properties (match-beginning 3) (match-end 3) vp)
6228 (org-rear-nonsticky-at (match-end 3))
6229 (add-text-properties (match-end 3) (match-end 0) ip)
6230 (org-rear-nonsticky-at (match-end 0)))
6231 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6232 (org-rear-nonsticky-at (match-beginning 1))
6233 (add-text-properties (match-beginning 1) (match-end 1) vp)
6234 (org-rear-nonsticky-at (match-end 1))
6235 (add-text-properties (match-end 1) (match-end 0) ip)
6236 (org-rear-nonsticky-at (match-end 0)))
6237 (when activate-func
6238 (funcall activate-func link-start link-end path bracketp))
6239 t)))
6241 (defun org-activate-dates (limit)
6242 "Add text properties for dates."
6243 (when (and (re-search-forward org-tsr-regexp-both limit t)
6244 (not (equal (char-before (match-beginning 0)) 91)))
6245 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6246 (add-text-properties (match-beginning 0) (match-end 0)
6247 (list 'mouse-face 'highlight
6248 'keymap org-mouse-map))
6249 (org-rear-nonsticky-at (match-end 0))
6250 (when org-display-custom-times
6251 (if (match-end 3)
6252 (org-display-custom-time (match-beginning 3) (match-end 3))
6253 (org-display-custom-time (match-beginning 1) (match-end 1))))
6256 (defvar-local org-target-link-regexp nil
6257 "Regular expression matching radio targets in plain text.")
6259 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6260 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6261 border border border))
6262 "Regular expression matching a link target.")
6264 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6265 "Regular expression matching a radio target.")
6267 (defconst org-any-target-regexp
6268 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6269 "Regular expression matching any target.")
6271 (defun org-activate-target-links (limit)
6272 "Add text properties for target matches."
6273 (when org-target-link-regexp
6274 (let ((case-fold-search t))
6275 (when (re-search-forward org-target-link-regexp limit t)
6276 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6277 (add-text-properties (match-beginning 1) (match-end 1)
6278 (list 'mouse-face 'highlight
6279 'keymap org-mouse-map
6280 'help-echo "Radio target link"
6281 'org-linked-text t))
6282 (org-rear-nonsticky-at (match-end 1))
6283 t))))
6285 (defun org-update-radio-target-regexp ()
6286 "Find all radio targets in this file and update the regular expression.
6287 Also refresh fontification if needed."
6288 (interactive)
6289 (let ((old-regexp org-target-link-regexp)
6290 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6291 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6292 (targets
6293 (org-with-wide-buffer
6294 (goto-char (point-min))
6295 (let (rtn)
6296 (while (re-search-forward org-radio-target-regexp nil t)
6297 ;; Make sure point is really within the object.
6298 (backward-char)
6299 (let ((obj (org-element-context)))
6300 (when (eq (org-element-type obj) 'radio-target)
6301 (cl-pushnew (org-element-property :value obj) rtn
6302 :test #'equal))))
6303 rtn))))
6304 (setq org-target-link-regexp
6305 (and targets
6306 (concat before-re
6307 (mapconcat
6308 (lambda (x)
6309 (replace-regexp-in-string
6310 " +" "\\s-+" (regexp-quote x) t t))
6311 targets
6312 "\\|")
6313 after-re)))
6314 (unless (equal old-regexp org-target-link-regexp)
6315 ;; Clean-up cache.
6316 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6317 ((not org-target-link-regexp) old-regexp)
6319 (concat before-re
6320 (mapconcat
6321 (lambda (re)
6322 (substring re (length before-re)
6323 (- (length after-re))))
6324 (list old-regexp org-target-link-regexp)
6325 "\\|")
6326 after-re)))))
6327 (org-with-wide-buffer
6328 (goto-char (point-min))
6329 (while (re-search-forward regexp nil t)
6330 (org-element-cache-refresh (match-beginning 1)))))
6331 ;; Re fontify buffer.
6332 (when (memq 'radio org-highlight-links)
6333 (org-restart-font-lock)))))
6335 (defun org-hide-wide-columns (limit)
6336 (let (s e)
6337 (setq s (text-property-any (point) (or limit (point-max))
6338 'org-cwidth t))
6339 (when s
6340 (setq e (next-single-property-change s 'org-cwidth))
6341 (add-text-properties s e '(invisible org-cwidth))
6342 (goto-char e)
6343 t)))
6345 (defvar org-latex-and-related-regexp nil
6346 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6348 (defun org-compute-latex-and-related-regexp ()
6349 "Compute regular expression for LaTeX, entities and sub/superscript.
6350 Result depends on variable `org-highlight-latex-and-related'."
6351 (setq-local
6352 org-latex-and-related-regexp
6353 (let* ((re-sub
6354 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6355 ((eq org-use-sub-superscripts '{})
6356 (list org-match-substring-with-braces-regexp))
6357 (org-use-sub-superscripts (list org-match-substring-regexp))))
6358 (re-latex
6359 (when (memq 'latex org-highlight-latex-and-related)
6360 (let ((matchers (plist-get org-format-latex-options :matchers)))
6361 (delq nil
6362 (mapcar (lambda (x)
6363 (and (member (car x) matchers) (nth 1 x)))
6364 org-latex-regexps)))))
6365 (re-entities
6366 (when (memq 'entities org-highlight-latex-and-related)
6367 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6368 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6370 (defun org-do-latex-and-related (limit)
6371 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6372 LIMIT bounds the search for syntax to highlight. Stop at first
6373 highlighted object, if any. Return t if some highlighting was
6374 done, nil otherwise."
6375 (when (org-string-nw-p org-latex-and-related-regexp)
6376 (catch 'found
6377 (while (re-search-forward org-latex-and-related-regexp limit t)
6378 (unless
6379 (cl-some
6380 (lambda (f)
6381 (memq f '(org-code org-verbatim underline org-special-keyword)))
6382 (save-excursion
6383 (goto-char (1+ (match-beginning 0)))
6384 (face-at-point nil t)))
6385 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6386 '(?_ ?^))
6388 0)))
6389 (font-lock-prepend-text-property
6390 (+ offset (match-beginning 0)) (match-end 0)
6391 'face 'org-latex-and-related)
6392 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6393 '(font-lock-multiline t)))
6394 (throw 'found t)))
6395 nil)))
6397 (defun org-restart-font-lock ()
6398 "Restart `font-lock-mode', to force refontification."
6399 (when (and (boundp 'font-lock-mode) font-lock-mode)
6400 (font-lock-mode -1)
6401 (font-lock-mode 1)))
6403 (defun org-activate-tags (limit)
6404 (when (re-search-forward
6405 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6406 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6407 (add-text-properties (match-beginning 1) (match-end 1)
6408 (list 'mouse-face 'highlight
6409 'keymap org-mouse-map))
6410 (org-rear-nonsticky-at (match-end 1))
6413 (defun org-outline-level ()
6414 "Compute the outline level of the heading at point.
6416 If this is called at a normal headline, the level is the number
6417 of stars. Use `org-reduced-level' to remove the effect of
6418 `org-odd-levels'. Unlike to `org-current-level', this function
6419 takes into consideration inlinetasks."
6420 (org-with-wide-buffer
6421 (end-of-line)
6422 (if (re-search-backward org-outline-regexp-bol nil t)
6423 (1- (- (match-end 0) (match-beginning 0)))
6424 0)))
6426 (defvar org-font-lock-keywords nil)
6428 (defsubst org-re-property (property &optional literal allow-null value)
6429 "Return a regexp matching a PROPERTY line.
6431 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6432 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6433 non-nil, match properties even without a value.
6435 Match group 3 is set to the value when it exists. If there is no
6436 value and ALLOW-NULL is non-nil, it is set to the empty string.
6438 With optional argument VALUE, match only property lines with
6439 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6440 unless LITERAL is non-nil."
6441 (concat
6442 "^\\(?4:[ \t]*\\)"
6443 (format "\\(?1::\\(?2:%s\\):\\)"
6444 (if literal property (regexp-quote property)))
6445 (cond (value
6446 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6447 (if literal value (regexp-quote value))))
6448 (allow-null
6449 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6451 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6453 (defconst org-property-re
6454 (org-re-property "\\S-+" 'literal t)
6455 "Regular expression matching a property line.
6456 There are four matching groups:
6457 1: :PROPKEY: including the leading and trailing colon,
6458 2: PROPKEY without the leading and trailing colon,
6459 3: PROPVAL without leading or trailing spaces,
6460 4: the indentation of the current line,
6461 5: trailing whitespace.")
6463 (defvar org-font-lock-hook nil
6464 "Functions to be called for special font lock stuff.")
6466 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6468 (defvar org-font-lock-set-keywords-hook nil
6469 "Functions that can manipulate `org-font-lock-extra-keywords'.
6470 This is called after `org-font-lock-extra-keywords' is defined, but before
6471 it is installed to be used by font lock. This can be useful if something
6472 needs to be inserted at a specific position in the font-lock sequence.")
6474 (defun org-font-lock-hook (limit)
6475 "Run `org-font-lock-hook' within LIMIT."
6476 (run-hook-with-args 'org-font-lock-hook limit))
6478 (defun org-set-font-lock-defaults ()
6479 "Set font lock defaults for the current buffer."
6480 (let* ((em org-fontify-emphasized-text)
6481 (lk org-highlight-links)
6482 (org-font-lock-extra-keywords
6483 (list
6484 ;; Call the hook
6485 '(org-font-lock-hook)
6486 ;; Headlines
6487 `(,(if org-fontify-whole-heading-line
6488 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6489 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6490 (1 (org-get-level-face 1))
6491 (2 (org-get-level-face 2))
6492 (3 (org-get-level-face 3)))
6493 ;; Table lines
6494 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6495 (1 'org-table t))
6496 ;; Table internals
6497 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6498 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6499 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6500 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6501 ;; Drawers
6502 '(org-fontify-drawers)
6503 ;; Properties
6504 (list org-property-re
6505 '(1 'org-special-keyword t)
6506 '(3 'org-property-value t))
6507 ;; Links
6508 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6509 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6510 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6511 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6512 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6513 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6514 (when (memq 'footnote lk) '(org-activate-footnote-links))
6515 ;; Targets.
6516 (list org-any-target-regexp '(0 'org-target t))
6517 ;; Diary sexps.
6518 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6519 ;; Macro
6520 '(org-fontify-macros)
6521 '(org-hide-wide-columns (0 nil append))
6522 ;; TODO keyword
6523 (list (format org-heading-keyword-regexp-format
6524 org-todo-regexp)
6525 '(2 (org-get-todo-face 2) t))
6526 ;; DONE
6527 (if org-fontify-done-headline
6528 (list (format org-heading-keyword-regexp-format
6529 (concat
6530 "\\(?:"
6531 (mapconcat 'regexp-quote org-done-keywords "\\|")
6532 "\\)"))
6533 '(2 'org-headline-done t))
6534 nil)
6535 ;; Priorities
6536 '(org-font-lock-add-priority-faces)
6537 ;; Tags
6538 '(org-font-lock-add-tag-faces)
6539 ;; Tags groups
6540 (when (and org-group-tags org-tag-groups-alist)
6541 (list (concat org-outline-regexp-bol ".+\\(:"
6542 (regexp-opt (mapcar 'car org-tag-groups-alist))
6543 ":\\).*$")
6544 '(1 'org-tag-group prepend)))
6545 ;; Special keywords
6546 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6547 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6548 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6549 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6550 ;; Emphasis
6551 (when em '(org-do-emphasis-faces))
6552 ;; Checkboxes
6553 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6554 1 'org-checkbox prepend)
6555 (when (cdr (assq 'checkbox org-list-automatic-rules))
6556 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6557 (0 (org-get-checkbox-statistics-face) t)))
6558 ;; Description list items
6559 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6560 1 'org-list-dt prepend)
6561 ;; ARCHIVEd headings
6562 (list (concat
6563 org-outline-regexp-bol
6564 "\\(.*:" org-archive-tag ":.*\\)")
6565 '(1 'org-archived prepend))
6566 ;; Specials
6567 '(org-do-latex-and-related)
6568 '(org-fontify-entities)
6569 '(org-raise-scripts)
6570 ;; Code
6571 '(org-activate-code (1 'org-code t))
6572 ;; COMMENT
6573 (list (format
6574 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6575 org-todo-regexp
6576 org-comment-string)
6577 '(9 'org-special-keyword t))
6578 ;; Blocks and meta lines
6579 '(org-fontify-meta-lines-and-blocks))))
6580 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6581 (run-hooks 'org-font-lock-set-keywords-hook)
6582 ;; Now set the full font-lock-keywords
6583 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6584 (setq-local font-lock-defaults
6585 '(org-font-lock-keywords t nil nil backward-paragraph))
6586 (kill-local-variable 'font-lock-keywords)
6587 nil))
6589 (defun org-toggle-pretty-entities ()
6590 "Toggle the composition display of entities as UTF8 characters."
6591 (interactive)
6592 (setq-local org-pretty-entities (not org-pretty-entities))
6593 (org-restart-font-lock)
6594 (if org-pretty-entities
6595 (message "Entities are now displayed as UTF8 characters")
6596 (save-restriction
6597 (widen)
6598 (decompose-region (point-min) (point-max))
6599 (message "Entities are now displayed as plain text"))))
6601 (defvar-local org-custom-properties-overlays nil
6602 "List of overlays used for custom properties.")
6604 (defun org-toggle-custom-properties-visibility ()
6605 "Display or hide properties in `org-custom-properties'."
6606 (interactive)
6607 (if org-custom-properties-overlays
6608 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6609 (setq org-custom-properties-overlays nil))
6610 (when org-custom-properties
6611 (org-with-wide-buffer
6612 (goto-char (point-min))
6613 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6614 (while (re-search-forward regexp nil t)
6615 (let ((end (cdr (save-match-data (org-get-property-block)))))
6616 (when (and end (< (point) end))
6617 ;; Hide first custom property in current drawer.
6618 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6619 (overlay-put o 'invisible t)
6620 (overlay-put o 'org-custom-property t)
6621 (push o org-custom-properties-overlays))
6622 ;; Hide additional custom properties in the same drawer.
6623 (while (re-search-forward regexp end t)
6624 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6625 (overlay-put o 'invisible t)
6626 (overlay-put o 'org-custom-property t)
6627 (push o org-custom-properties-overlays)))))
6628 ;; Each entry is limited to a single property drawer.
6629 (outline-next-heading)))))))
6631 (defun org-fontify-entities (limit)
6632 "Find an entity to fontify."
6633 (let (ee)
6634 (when org-pretty-entities
6635 (catch 'match
6636 ;; "\_ "-family is left out on purpose. Only the first one,
6637 ;; i.e., "\_ ", could be fontified anyway, and it would be
6638 ;; confusing when adding a second white space character.
6639 (while (re-search-forward
6640 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6641 limit t)
6642 (when (and (not (org-at-comment-p))
6643 (setq ee (org-entity-get (match-string 1)))
6644 (= (length (nth 6 ee)) 1))
6645 (let* ((end (if (equal (match-string 2) "{}")
6646 (match-end 2)
6647 (match-end 1))))
6648 (add-text-properties
6649 (match-beginning 0) end
6650 (list 'font-lock-fontified t))
6651 (compose-region (match-beginning 0) end
6652 (nth 6 ee) nil)
6653 (backward-char 1)
6654 (throw 'match t))))
6655 nil))))
6657 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6658 "Fontify string S like in Org-mode."
6659 (with-temp-buffer
6660 (insert s)
6661 (let ((org-odd-levels-only odd-levels))
6662 (org-mode)
6663 (org-font-lock-ensure)
6664 (buffer-string))))
6666 (defvar org-m nil)
6667 (defvar org-l nil)
6668 (defvar org-f nil)
6669 (defun org-get-level-face (n)
6670 "Get the right face for match N in font-lock matching of headlines."
6671 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6672 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6673 (if org-cycle-level-faces
6674 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6675 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6676 (cond
6677 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6678 ((eq n 2) org-f)
6679 (t (unless org-level-color-stars-only org-f))))
6681 (defun org-face-from-face-or-color (context inherit face-or-color)
6682 "Create a face list that inherits INHERIT, but sets the foreground color.
6683 When FACE-OR-COLOR is not a string, just return it."
6684 (if (stringp face-or-color)
6685 (list :inherit inherit
6686 (cdr (assoc context org-faces-easy-properties))
6687 face-or-color)
6688 face-or-color))
6690 (defun org-get-todo-face (kwd)
6691 "Get the right face for a TODO keyword KWD.
6692 If KWD is a number, get the corresponding match group."
6693 (when (numberp kwd) (setq kwd (match-string kwd)))
6694 (or (org-face-from-face-or-color
6695 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6696 (and (member kwd org-done-keywords) 'org-done)
6697 'org-todo))
6699 (defun org-get-priority-face (priority)
6700 "Get the right face for PRIORITY.
6701 PRIORITY is a character."
6702 (or (org-face-from-face-or-color
6703 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6704 'org-priority))
6706 (defun org-get-tag-face (tag)
6707 "Get the right face for TAG.
6708 If TAG is a number, get the corresponding match group."
6709 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6710 (or (org-face-from-face-or-color
6711 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6712 'org-tag)))
6714 (defun org-font-lock-add-priority-faces (limit)
6715 "Add the special priority faces."
6716 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6717 (add-text-properties
6718 (match-beginning 1) (match-end 1)
6719 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6720 'font-lock-fontified t))))
6722 (defun org-font-lock-add-tag-faces (limit)
6723 "Add the special tag faces."
6724 (when (and org-tag-faces org-tags-special-faces-re)
6725 (while (re-search-forward org-tags-special-faces-re limit t)
6726 (add-text-properties (match-beginning 1) (match-end 1)
6727 (list 'face (org-get-tag-face 1)
6728 'font-lock-fontified t))
6729 (backward-char 1))))
6731 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6732 "Remove fontification and activation overlays from links."
6733 (font-lock-default-unfontify-region beg end)
6734 (let* ((buffer-undo-list t)
6735 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6736 (inhibit-modification-hooks t)
6737 deactivate-mark buffer-file-name buffer-file-truename)
6738 (decompose-region beg end)
6739 (remove-text-properties beg end
6740 '(mouse-face t keymap t org-linked-text t
6741 invisible t intangible t
6742 org-emphasis t))
6743 (org-remove-font-lock-display-properties beg end)))
6745 (defconst org-script-display '(((raise -0.3) (height 0.7))
6746 ((raise 0.3) (height 0.7))
6747 ((raise -0.5))
6748 ((raise 0.5)))
6749 "Display properties for showing superscripts and subscripts.")
6751 (defun org-remove-font-lock-display-properties (beg end)
6752 "Remove specific display properties that have been added by font lock.
6753 The will remove the raise properties that are used to show superscripts
6754 and subscripts."
6755 (let (next prop)
6756 (while (< beg end)
6757 (setq next (next-single-property-change beg 'display nil end)
6758 prop (get-text-property beg 'display))
6759 (when (member prop org-script-display)
6760 (put-text-property beg next 'display nil))
6761 (setq beg next))))
6763 (defun org-raise-scripts (limit)
6764 "Add raise properties to sub/superscripts."
6765 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6766 (re-search-forward
6767 (if (eq org-use-sub-superscripts t)
6768 org-match-substring-regexp
6769 org-match-substring-with-braces-regexp)
6770 limit t))
6771 (let* ((pos (point)) table-p comment-p
6772 (mpos (match-beginning 3))
6773 (emph-p (get-text-property mpos 'org-emphasis))
6774 (link-p (get-text-property mpos 'mouse-face))
6775 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6776 (goto-char (point-at-bol))
6777 (setq table-p (looking-at-p org-table-dataline-regexp)
6778 comment-p (looking-at-p "^[ \t]*#[ +]"))
6779 (goto-char pos)
6780 ;; Handle a_b^c
6781 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6782 (unless (or comment-p emph-p link-p keyw-p)
6783 (put-text-property (match-beginning 3) (match-end 0)
6784 'display
6785 (if (equal (char-after (match-beginning 2)) ?^)
6786 (nth (if table-p 3 1) org-script-display)
6787 (nth (if table-p 2 0) org-script-display)))
6788 (add-text-properties (match-beginning 2) (match-end 2)
6789 (list 'invisible t
6790 'org-dwidth t 'org-dwidth-n 1))
6791 (if (and (eq (char-after (match-beginning 3)) ?{)
6792 (eq (char-before (match-end 3)) ?}))
6793 (progn
6794 (add-text-properties
6795 (match-beginning 3) (1+ (match-beginning 3))
6796 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6797 (add-text-properties
6798 (1- (match-end 3)) (match-end 3)
6799 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6800 t)))
6802 ;;;; Visibility cycling, including org-goto and indirect buffer
6804 ;;; Cycling
6806 (defvar-local org-cycle-global-status nil)
6807 (put 'org-cycle-global-status 'org-state t)
6808 (defvar-local org-cycle-subtree-status nil)
6809 (put 'org-cycle-subtree-status 'org-state t)
6811 (defvar org-inlinetask-min-level)
6813 (defun org-unlogged-message (&rest args)
6814 "Display a message, but avoid logging it in the *Messages* buffer."
6815 (let ((message-log-max nil))
6816 (apply 'message args)))
6818 ;;;###autoload
6819 (defun org-cycle (&optional arg)
6820 "TAB-action and visibility cycling for Org-mode.
6822 This is the command invoked in Org mode by the TAB key. Its main purpose
6823 is outline visibility cycling, but it also invokes other actions
6824 in special contexts.
6826 - When this function is called with a prefix argument, rotate the entire
6827 buffer through 3 states (global cycling)
6828 1. OVERVIEW: Show only top-level headlines.
6829 2. CONTENTS: Show all headlines of all levels, but no body text.
6830 3. SHOW ALL: Show everything.
6831 With a double \\[universal-argument] prefix argument, \
6832 switch to the startup visibility,
6833 determined by the variable `org-startup-folded', and by any VISIBILITY
6834 properties in the buffer.
6835 With a triple \\[universal-argument] prefix argument, \
6836 show the entire buffer, including any drawers.
6838 - When inside a table, re-align the table and move to the next field.
6840 - When point is at the beginning of a headline, rotate the subtree started
6841 by this line through 3 different states (local cycling)
6842 1. FOLDED: Only the main headline is shown.
6843 2. CHILDREN: The main headline and the direct children are shown.
6844 From this state, you can move to one of the children
6845 and zoom in further.
6846 3. SUBTREE: Show the entire subtree, including body text.
6847 If there is no subtree, switch directly from CHILDREN to FOLDED.
6849 - When point is at the beginning of an empty headline and the variable
6850 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6851 of the headline by demoting and promoting it to likely levels. This
6852 speeds up creation document structure by pressing TAB once or several
6853 times right after creating a new headline.
6855 - When there is a numeric prefix, go up to a heading with level ARG, do
6856 a `show-subtree' and return to the previous cursor position. If ARG
6857 is negative, go up that many levels.
6859 - When point is not at the beginning of a headline, execute the global
6860 binding for TAB, which is re-indenting the line. See the option
6861 `org-cycle-emulate-tab' for details.
6863 - Special case: if point is at the beginning of the buffer and there is
6864 no headline in line 1, this function will act as if called with prefix arg
6865 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6866 But only if also the variable `org-cycle-global-at-bob' is t."
6867 (interactive "P")
6868 (org-load-modules-maybe)
6869 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6870 (and org-cycle-level-after-item/entry-creation
6871 (or (org-cycle-level)
6872 (org-cycle-item-indentation))))
6873 (let* ((limit-level
6874 (or org-cycle-max-level
6875 (and (boundp 'org-inlinetask-min-level)
6876 org-inlinetask-min-level
6877 (1- org-inlinetask-min-level))))
6878 (nstars (and limit-level
6879 (if org-odd-levels-only
6880 (and limit-level (1- (* limit-level 2)))
6881 limit-level)))
6882 (org-outline-regexp
6883 (if (not (derived-mode-p 'org-mode))
6884 outline-regexp
6885 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6886 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6887 (not (looking-at org-outline-regexp))))
6888 (org-cycle-hook
6889 (if bob-special
6890 (delq 'org-optimize-window-after-visibility-change
6891 (copy-sequence org-cycle-hook))
6892 org-cycle-hook))
6893 (pos (point)))
6895 (when (or bob-special (equal arg '(4)))
6896 ;; special case: use global cycling
6897 (setq arg t))
6899 (cond
6901 ((equal arg '(16))
6902 (setq last-command 'dummy)
6903 (org-set-startup-visibility)
6904 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6906 ((equal arg '(64))
6907 (outline-show-all)
6908 (org-unlogged-message "Entire buffer visible, including drawers"))
6910 ;; Try cdlatex TAB completion
6911 ((org-try-cdlatex-tab))
6913 ;; Table: enter it or move to the next field.
6914 ((org-at-table-p 'any)
6915 (if (org-at-table.el-p)
6916 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6917 Use \\[org-edit-special] to edit table.el tables"))
6918 (if arg (org-table-edit-field t)
6919 (org-table-justify-field-maybe)
6920 (call-interactively 'org-table-next-field))))
6922 ((run-hook-with-args-until-success
6923 'org-tab-after-check-for-table-hook))
6925 ;; Global cycling: delegate to `org-cycle-internal-global'.
6926 ((eq arg t) (org-cycle-internal-global))
6928 ;; Drawers: delegate to `org-flag-drawer'.
6929 ((save-excursion
6930 (beginning-of-line 1)
6931 (looking-at org-drawer-regexp))
6932 (org-flag-drawer ; toggle block visibility
6933 (not (get-char-property (match-end 0) 'invisible))))
6935 ;; Show-subtree, ARG levels up from here.
6936 ((integerp arg)
6937 (save-excursion
6938 (org-back-to-heading)
6939 (outline-up-heading (if (< arg 0) (- arg)
6940 (- (funcall outline-level) arg)))
6941 (org-show-subtree)))
6943 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6944 ((and (featurep 'org-inlinetask)
6945 (org-inlinetask-at-task-p)
6946 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6947 (org-inlinetask-toggle-visibility))
6949 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6950 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6951 (save-excursion (move-beginning-of-line 1)
6952 (looking-at org-outline-regexp)))
6953 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6954 (org-cycle-internal-local))
6956 ;; From there: TAB emulation and template completion.
6957 (buffer-read-only (org-back-to-heading))
6959 ((run-hook-with-args-until-success
6960 'org-tab-after-check-for-cycling-hook))
6962 ((org-try-structure-completion))
6964 ((run-hook-with-args-until-success
6965 'org-tab-before-tab-emulation-hook))
6967 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6968 (or (not (bolp))
6969 (not (looking-at org-outline-regexp))))
6970 (call-interactively (global-key-binding "\t")))
6972 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6973 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6974 (or (and (eq org-cycle-emulate-tab 'white)
6975 (= (match-end 0) (point-at-eol)))
6976 (and (eq org-cycle-emulate-tab 'whitestart)
6977 (>= (match-end 0) pos))))
6979 (eq org-cycle-emulate-tab t))
6980 (call-interactively (global-key-binding "\t")))
6982 (t (save-excursion
6983 (org-back-to-heading)
6984 (org-cycle)))))))
6986 (defun org-cycle-internal-global ()
6987 "Do the global cycling action."
6988 ;; Hack to avoid display of messages for .org attachments in Gnus
6989 (let ((ga (string-match "\\*fontification" (buffer-name))))
6990 (cond
6991 ((and (eq last-command this-command)
6992 (eq org-cycle-global-status 'overview))
6993 ;; We just created the overview - now do table of contents
6994 ;; This can be slow in very large buffers, so indicate action
6995 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6996 (unless ga (org-unlogged-message "CONTENTS..."))
6997 (org-content)
6998 (unless ga (org-unlogged-message "CONTENTS...done"))
6999 (setq org-cycle-global-status 'contents)
7000 (run-hook-with-args 'org-cycle-hook 'contents))
7002 ((and (eq last-command this-command)
7003 (eq org-cycle-global-status 'contents))
7004 ;; We just showed the table of contents - now show everything
7005 (run-hook-with-args 'org-pre-cycle-hook 'all)
7006 (outline-show-all)
7007 (unless ga (org-unlogged-message "SHOW ALL"))
7008 (setq org-cycle-global-status 'all)
7009 (run-hook-with-args 'org-cycle-hook 'all))
7012 ;; Default action: go to overview
7013 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7014 (org-overview)
7015 (unless ga (org-unlogged-message "OVERVIEW"))
7016 (setq org-cycle-global-status 'overview)
7017 (run-hook-with-args 'org-cycle-hook 'overview)))))
7019 (defvar org-called-with-limited-levels nil
7020 "Non-nil when `org-with-limited-levels' is currently active.")
7022 (defun org-cycle-internal-local ()
7023 "Do the local cycling action."
7024 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7025 ;; First, determine end of headline (EOH), end of subtree or item
7026 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7027 (save-excursion
7028 (if (org-at-item-p)
7029 (progn
7030 (beginning-of-line)
7031 (setq struct (org-list-struct))
7032 (setq eoh (point-at-eol))
7033 (setq eos (org-list-get-item-end-before-blank (point) struct))
7034 (setq has-children (org-list-has-child-p (point) struct)))
7035 (org-back-to-heading)
7036 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7037 (setq eos (save-excursion (org-end-of-subtree t t)
7038 (when (bolp) (backward-char)) (point)))
7039 (setq has-children
7040 (or (save-excursion
7041 (let ((level (funcall outline-level)))
7042 (outline-next-heading)
7043 (and (org-at-heading-p t)
7044 (> (funcall outline-level) level))))
7045 (save-excursion
7046 (org-list-search-forward (org-item-beginning-re) eos t)))))
7047 ;; Determine end invisible part of buffer (EOL)
7048 (beginning-of-line 2)
7049 (while (and (not (eobp)) ;This is like `next-line'.
7050 (get-char-property (1- (point)) 'invisible))
7051 (goto-char (next-single-char-property-change (point) 'invisible))
7052 (and (eolp) (beginning-of-line 2)))
7053 (setq eol (point)))
7054 ;; Find out what to do next and set `this-command'
7055 (cond
7056 ((= eos eoh)
7057 ;; Nothing is hidden behind this heading
7058 (unless (org-before-first-heading-p)
7059 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7060 (org-unlogged-message "EMPTY ENTRY")
7061 (setq org-cycle-subtree-status nil)
7062 (save-excursion
7063 (goto-char eos)
7064 (outline-next-heading)
7065 (when (outline-invisible-p) (org-flag-heading nil))))
7066 ((and (or (>= eol eos)
7067 (not (string-match "\\S-" (buffer-substring eol eos))))
7068 (or has-children
7069 (not (setq children-skipped
7070 org-cycle-skip-children-state-if-no-children))))
7071 ;; Entire subtree is hidden in one line: children view
7072 (unless (org-before-first-heading-p)
7073 (run-hook-with-args 'org-pre-cycle-hook 'children))
7074 (if (org-at-item-p)
7075 (org-list-set-item-visibility (point-at-bol) struct 'children)
7076 (org-show-entry)
7077 (org-with-limited-levels (org-show-children))
7078 ;; FIXME: This slows down the func way too much.
7079 ;; How keep drawers hidden in subtree anyway?
7080 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7081 ;; (org-cycle-hide-drawers 'subtree))
7083 ;; Fold every list in subtree to top-level items.
7084 (when (eq org-cycle-include-plain-lists 'integrate)
7085 (save-excursion
7086 (org-back-to-heading)
7087 (while (org-list-search-forward (org-item-beginning-re) eos t)
7088 (beginning-of-line 1)
7089 (let* ((struct (org-list-struct))
7090 (prevs (org-list-prevs-alist struct))
7091 (end (org-list-get-bottom-point struct)))
7092 (dolist (e (org-list-get-all-items (point) struct prevs))
7093 (org-list-set-item-visibility e struct 'folded))
7094 (goto-char (if (< end eos) end eos)))))))
7095 (org-unlogged-message "CHILDREN")
7096 (save-excursion
7097 (goto-char eos)
7098 (outline-next-heading)
7099 (when (outline-invisible-p) (org-flag-heading nil)))
7100 (setq org-cycle-subtree-status 'children)
7101 (unless (org-before-first-heading-p)
7102 (run-hook-with-args 'org-cycle-hook 'children)))
7103 ((or children-skipped
7104 (and (eq last-command this-command)
7105 (eq org-cycle-subtree-status 'children)))
7106 ;; We just showed the children, or no children are there,
7107 ;; now show everything.
7108 (unless (org-before-first-heading-p)
7109 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7110 (outline-flag-region eoh eos nil)
7111 (org-unlogged-message
7112 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7113 (setq org-cycle-subtree-status 'subtree)
7114 (unless (org-before-first-heading-p)
7115 (run-hook-with-args 'org-cycle-hook 'subtree)))
7117 ;; Default action: hide the subtree.
7118 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7119 (outline-flag-region eoh eos t)
7120 (org-unlogged-message "FOLDED")
7121 (setq org-cycle-subtree-status 'folded)
7122 (unless (org-before-first-heading-p)
7123 (run-hook-with-args 'org-cycle-hook 'folded))))))
7125 ;;;###autoload
7126 (defun org-global-cycle (&optional arg)
7127 "Cycle the global visibility. For details see `org-cycle'.
7128 With \\[universal-argument] prefix arg, switch to startup visibility.
7129 With a numeric prefix, show all headlines up to that level."
7130 (interactive "P")
7131 (let ((org-cycle-include-plain-lists
7132 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7133 (cond
7134 ((integerp arg)
7135 (outline-show-all)
7136 (outline-hide-sublevels arg)
7137 (setq org-cycle-global-status 'contents))
7138 ((equal arg '(4))
7139 (org-set-startup-visibility)
7140 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7142 (org-cycle '(4))))))
7144 (defun org-set-startup-visibility ()
7145 "Set the visibility required by startup options and properties."
7146 (cond
7147 ((eq org-startup-folded t)
7148 (org-overview))
7149 ((eq org-startup-folded 'content)
7150 (org-content))
7151 ((or (eq org-startup-folded 'showeverything)
7152 (eq org-startup-folded nil))
7153 (outline-show-all)))
7154 (unless (eq org-startup-folded 'showeverything)
7155 (when org-hide-block-startup (org-hide-block-all))
7156 (org-set-visibility-according-to-property 'no-cleanup)
7157 (org-cycle-hide-archived-subtrees 'all)
7158 (org-cycle-hide-drawers 'all)
7159 (org-cycle-show-empty-lines t)))
7161 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7162 "Switch subtree visibilities according to :VISIBILITY: property."
7163 (interactive)
7164 (org-with-wide-buffer
7165 (goto-char (point-min))
7166 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7167 (if (not (org-at-property-p)) (outline-next-heading)
7168 (let ((state (match-string 3)))
7169 (save-excursion
7170 (org-back-to-heading t)
7171 (outline-hide-subtree)
7172 (org-reveal)
7173 (cond
7174 ((equal state "folded")
7175 (outline-hide-subtree))
7176 ((equal state "children")
7177 (org-show-hidden-entry)
7178 (org-show-children))
7179 ((equal state "content")
7180 (save-excursion
7181 (save-restriction
7182 (org-narrow-to-subtree)
7183 (org-content))))
7184 ((member state '("all" "showall"))
7185 (outline-show-subtree)))))))
7186 (unless no-cleanup
7187 (org-cycle-hide-archived-subtrees 'all)
7188 (org-cycle-hide-drawers 'all)
7189 (org-cycle-show-empty-lines 'all))))
7191 ;; This function uses outline-regexp instead of the more fundamental
7192 ;; org-outline-regexp so that org-cycle-global works outside of Org
7193 ;; buffers, where outline-regexp is needed.
7194 (defun org-overview ()
7195 "Switch to overview mode, showing only top-level headlines.
7196 This shows all headlines with a level equal or greater than the level
7197 of the first headline in the buffer. This is important, because if the
7198 first headline is not level one, then (hide-sublevels 1) gives confusing
7199 results."
7200 (interactive)
7201 (save-excursion
7202 (let ((level
7203 (save-excursion
7204 (goto-char (point-min))
7205 (when (re-search-forward (concat "^" outline-regexp) nil t)
7206 (goto-char (match-beginning 0))
7207 (funcall outline-level)))))
7208 (and level (outline-hide-sublevels level)))))
7210 (defun org-content (&optional arg)
7211 "Show all headlines in the buffer, like a table of contents.
7212 With numerical argument N, show content up to level N."
7213 (interactive "P")
7214 (org-overview)
7215 (save-excursion
7216 ;; Visit all headings and show their offspring
7217 (and (integerp arg) (org-overview))
7218 (goto-char (point-max))
7219 (catch 'exit
7220 (while (and (progn (condition-case nil
7221 (outline-previous-visible-heading 1)
7222 (error (goto-char (point-min))))
7224 (looking-at org-outline-regexp))
7225 (if (integerp arg)
7226 (org-show-children (1- arg))
7227 (outline-show-branches))
7228 (when (bobp) (throw 'exit nil))))))
7230 (defun org-optimize-window-after-visibility-change (state)
7231 "Adjust the window after a change in outline visibility.
7232 This function is the default value of the hook `org-cycle-hook'."
7233 (when (get-buffer-window (current-buffer))
7234 (cond
7235 ((eq state 'content) nil)
7236 ((eq state 'all) nil)
7237 ((eq state 'folded) nil)
7238 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7239 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7241 (defun org-remove-empty-overlays-at (pos)
7242 "Remove outline overlays that do not contain non-white stuff."
7243 (dolist (o (overlays-at pos))
7244 (and (eq 'outline (overlay-get o 'invisible))
7245 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7246 (overlay-end o))))
7247 (delete-overlay o))))
7249 (defun org-clean-visibility-after-subtree-move ()
7250 "Fix visibility issues after moving a subtree."
7251 ;; First, find a reasonable region to look at:
7252 ;; Start two siblings above, end three below
7253 (let* ((beg (save-excursion
7254 (and (org-get-last-sibling)
7255 (org-get-last-sibling))
7256 (point)))
7257 (end (save-excursion
7258 (and (org-get-next-sibling)
7259 (org-get-next-sibling)
7260 (org-get-next-sibling))
7261 (if (org-at-heading-p)
7262 (point-at-eol)
7263 (point))))
7264 (level (looking-at "\\*+"))
7265 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7266 (save-excursion
7267 (save-restriction
7268 (narrow-to-region beg end)
7269 (when re
7270 ;; Properly fold already folded siblings
7271 (goto-char (point-min))
7272 (while (re-search-forward re nil t)
7273 (when (and (not (outline-invisible-p))
7274 (save-excursion
7275 (goto-char (point-at-eol)) (outline-invisible-p)))
7276 (outline-hide-entry))))
7277 (org-cycle-show-empty-lines 'overview)
7278 (org-cycle-hide-drawers 'overview)))))
7280 (defun org-cycle-show-empty-lines (state)
7281 "Show empty lines above all visible headlines.
7282 The region to be covered depends on STATE when called through
7283 `org-cycle-hook'. Lisp program can use t for STATE to get the
7284 entire buffer covered. Note that an empty line is only shown if there
7285 are at least `org-cycle-separator-lines' empty lines before the headline."
7286 (when (/= org-cycle-separator-lines 0)
7287 (save-excursion
7288 (let* ((n (abs org-cycle-separator-lines))
7289 (re (cond
7290 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7291 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7292 (t (let ((ns (number-to-string (- n 2))))
7293 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7294 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7295 beg end)
7296 (cond
7297 ((memq state '(overview contents t))
7298 (setq beg (point-min) end (point-max)))
7299 ((memq state '(children folded))
7300 (setq beg (point)
7301 end (progn (org-end-of-subtree t t)
7302 (line-beginning-position 2)))))
7303 (when beg
7304 (goto-char beg)
7305 (while (re-search-forward re end t)
7306 (unless (get-char-property (match-end 1) 'invisible)
7307 (let ((e (match-end 1))
7308 (b (if (>= org-cycle-separator-lines 0)
7309 (match-beginning 1)
7310 (save-excursion
7311 (goto-char (match-beginning 0))
7312 (skip-chars-backward " \t\n")
7313 (line-end-position)))))
7314 (outline-flag-region b e nil))))))))
7315 ;; Never hide empty lines at the end of the file.
7316 (save-excursion
7317 (goto-char (point-max))
7318 (outline-previous-heading)
7319 (outline-end-of-heading)
7320 (when (and (looking-at "[ \t\n]+")
7321 (= (match-end 0) (point-max)))
7322 (outline-flag-region (point) (match-end 0) nil))))
7324 (defun org-show-empty-lines-in-parent ()
7325 "Move to the parent and re-show empty lines before visible headlines."
7326 (save-excursion
7327 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7328 (org-cycle-show-empty-lines context))))
7330 (defun org-files-list ()
7331 "Return `org-agenda-files' list, plus all open Org files.
7332 This is useful for operations that need to scan all of a user's
7333 open and agenda-wise Org files."
7334 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7335 (dolist (buf (buffer-list))
7336 (with-current-buffer buf
7337 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7338 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7339 files))
7341 (defsubst org-entry-beginning-position ()
7342 "Return the beginning position of the current entry."
7343 (save-excursion (org-back-to-heading t) (point)))
7345 (defsubst org-entry-end-position ()
7346 "Return the end position of the current entry."
7347 (save-excursion (outline-next-heading) (point)))
7349 (defun org-cycle-hide-drawers (state &optional exceptions)
7350 "Re-hide all drawers after a visibility state change.
7351 When non-nil, optional argument EXCEPTIONS is a list of strings
7352 specifying which drawers should not be hidden."
7353 (when (and (derived-mode-p 'org-mode)
7354 (not (memq state '(overview folded contents))))
7355 (save-excursion
7356 (let* ((globalp (memq state '(contents all)))
7357 (beg (if globalp (point-min) (point)))
7358 (end (if globalp (point-max)
7359 (if (eq state 'children)
7360 (save-excursion (outline-next-heading) (point))
7361 (org-end-of-subtree t)))))
7362 (goto-char beg)
7363 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7364 (unless (member-ignore-case (match-string 1) exceptions)
7365 (let ((drawer (org-element-at-point)))
7366 (when (memq (org-element-type drawer) '(drawer property-drawer))
7367 (org-flag-drawer t drawer)
7368 ;; Make sure to skip drawer entirely or we might flag
7369 ;; it another time when matching its ending line with
7370 ;; `org-drawer-regexp'.
7371 (goto-char (org-element-property :end drawer))))))))))
7373 (defun org-flag-drawer (flag &optional element)
7374 "When FLAG is non-nil, hide the drawer we are at.
7375 Otherwise make it visible. When optional argument ELEMENT is
7376 a parsed drawer, as returned by `org-element-at-point', hide or
7377 show that drawer instead."
7378 (let ((drawer (or element
7379 (and (save-excursion
7380 (beginning-of-line)
7381 (looking-at-p org-drawer-regexp))
7382 (org-element-at-point)))))
7383 (when (memq (org-element-type drawer) '(drawer property-drawer))
7384 (let ((post (org-element-property :post-affiliated drawer)))
7385 (save-excursion
7386 (outline-flag-region
7387 (progn (goto-char post) (line-end-position))
7388 (progn (goto-char (org-element-property :end drawer))
7389 (skip-chars-backward " \r\t\n")
7390 (line-end-position))
7391 flag))
7392 ;; When the drawer is hidden away, make sure point lies in
7393 ;; a visible part of the buffer.
7394 (when (and flag (> (line-beginning-position) post))
7395 (goto-char post))))))
7397 (defun org-subtree-end-visible-p ()
7398 "Is the end of the current subtree visible?"
7399 (pos-visible-in-window-p
7400 (save-excursion (org-end-of-subtree t) (point))))
7402 (defun org-first-headline-recenter ()
7403 "Move cursor to the first headline and recenter the headline."
7404 (let ((window (get-buffer-window)))
7405 (when window
7406 (goto-char (point-min))
7407 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7408 (set-window-start window (line-beginning-position))))))
7410 ;;; Saving and restoring visibility
7412 (defun org-outline-overlay-data (&optional use-markers)
7413 "Return a list of the locations of all outline overlays.
7414 These are overlays with the `invisible' property value `outline'.
7415 The return value is a list of cons cells, with start and stop
7416 positions for each overlay.
7417 If USE-MARKERS is set, return the positions as markers."
7418 (let (beg end)
7419 (org-with-wide-buffer
7420 (delq nil
7421 (mapcar (lambda (o)
7422 (when (eq (overlay-get o 'invisible) 'outline)
7423 (setq beg (overlay-start o)
7424 end (overlay-end o))
7425 (and beg end (> end beg)
7426 (if use-markers
7427 (cons (copy-marker beg)
7428 (copy-marker end t))
7429 (cons beg end)))))
7430 (overlays-in (point-min) (point-max)))))))
7432 (defun org-set-outline-overlay-data (data)
7433 "Create visibility overlays for all positions in DATA.
7434 DATA should have been made by `org-outline-overlay-data'."
7435 (org-with-wide-buffer
7436 (outline-show-all)
7437 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7439 ;;; Folding of blocks
7441 (defvar-local org-hide-block-overlays nil
7442 "Overlays hiding blocks.")
7444 (defun org-block-map (function &optional start end)
7445 "Call FUNCTION at the head of all source blocks in the current buffer.
7446 Optional arguments START and END can be used to limit the range."
7447 (let ((start (or start (point-min)))
7448 (end (or end (point-max))))
7449 (save-excursion
7450 (goto-char start)
7451 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7452 (save-excursion
7453 (save-match-data
7454 (goto-char (match-beginning 0))
7455 (funcall function)))))))
7457 (defun org-hide-block-toggle-all ()
7458 "Toggle the visibility of all blocks in the current buffer."
7459 (org-block-map 'org-hide-block-toggle))
7461 (defun org-hide-block-all ()
7462 "Fold all blocks in the current buffer."
7463 (interactive)
7464 (org-show-block-all)
7465 (org-block-map 'org-hide-block-toggle-maybe))
7467 (defun org-show-block-all ()
7468 "Unfold all blocks in the current buffer."
7469 (interactive)
7470 (mapc #'delete-overlay org-hide-block-overlays)
7471 (setq org-hide-block-overlays nil))
7473 (defun org-hide-block-toggle-maybe ()
7474 "Toggle visibility of block at point.
7475 Unlike to `org-hide-block-toggle', this function does not throw
7476 an error. Return a non-nil value when toggling is successful."
7477 (interactive)
7478 (ignore-errors (org-hide-block-toggle)))
7480 (defun org-hide-block-toggle (&optional force)
7481 "Toggle the visibility of the current block.
7482 When optional argument FORCE is `off', make block visible. If it
7483 is non-nil, hide it unconditionally. Throw an error when not at
7484 a block. Return a non-nil value when toggling is successful."
7485 (interactive)
7486 (let ((element (org-element-at-point)))
7487 (unless (memq (org-element-type element)
7488 '(center-block comment-block dynamic-block example-block
7489 export-block quote-block special-block
7490 src-block verse-block))
7491 (user-error "Not at a block"))
7492 (let* ((start (save-excursion
7493 (goto-char (org-element-property :post-affiliated element))
7494 (line-end-position)))
7495 (end (save-excursion
7496 (goto-char (org-element-property :end element))
7497 (skip-chars-backward " \r\t\n")
7498 (line-end-position)))
7499 (overlays (overlays-at start)))
7500 (cond
7501 ;; Do nothing when not before or at the block opening line or
7502 ;; at the block closing line.
7503 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7504 ((and (not (eq force 'off))
7505 (not (memq t (mapcar
7506 (lambda (o)
7507 (eq (overlay-get o 'invisible) 'org-hide-block))
7508 overlays))))
7509 (let ((ov (make-overlay start end)))
7510 (overlay-put ov 'invisible 'org-hide-block)
7511 ;; Make the block accessible to `isearch'.
7512 (overlay-put
7513 ov 'isearch-open-invisible
7514 (lambda (ov)
7515 (when (memq ov org-hide-block-overlays)
7516 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7517 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7518 (delete-overlay ov))))
7519 (push ov org-hide-block-overlays)
7520 ;; When the block is hidden away, make sure point is left in
7521 ;; a visible part of the buffer.
7522 (when (> (line-beginning-position) start)
7523 (goto-char start)
7524 (beginning-of-line))
7525 ;; Signal successful toggling.
7527 ((or (not force) (eq force 'off))
7528 (dolist (ov overlays t)
7529 (when (memq ov org-hide-block-overlays)
7530 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7531 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7532 (delete-overlay ov))))))))
7534 ;; org-tab-after-check-for-cycling-hook
7535 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7536 ;; Remove overlays when changing major mode
7537 (add-hook 'org-mode-hook
7538 (lambda () (add-hook 'change-major-mode-hook
7539 'org-show-block-all 'append 'local)))
7541 ;;; Org-goto
7543 (defvar org-goto-window-configuration nil)
7544 (defvar org-goto-marker nil)
7545 (defvar org-goto-map)
7546 (defun org-goto-map ()
7547 "Set the keymap `org-goto'."
7548 (setq org-goto-map
7549 (let ((map (make-sparse-keymap)))
7550 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7551 mouse-drag-region universal-argument org-occur)))
7552 (dolist (cmd cmds)
7553 (substitute-key-definition cmd cmd map global-map)))
7554 (suppress-keymap map)
7555 (org-defkey map "\C-m" 'org-goto-ret)
7556 (org-defkey map [(return)] 'org-goto-ret)
7557 (org-defkey map [(left)] 'org-goto-left)
7558 (org-defkey map [(right)] 'org-goto-right)
7559 (org-defkey map [(control ?g)] 'org-goto-quit)
7560 (org-defkey map "\C-i" 'org-cycle)
7561 (org-defkey map [(tab)] 'org-cycle)
7562 (org-defkey map [(down)] 'outline-next-visible-heading)
7563 (org-defkey map [(up)] 'outline-previous-visible-heading)
7564 (if org-goto-auto-isearch
7565 (if (fboundp 'define-key-after)
7566 (define-key-after map [t] 'org-goto-local-auto-isearch)
7567 nil)
7568 (org-defkey map "q" 'org-goto-quit)
7569 (org-defkey map "n" 'outline-next-visible-heading)
7570 (org-defkey map "p" 'outline-previous-visible-heading)
7571 (org-defkey map "f" 'outline-forward-same-level)
7572 (org-defkey map "b" 'outline-backward-same-level)
7573 (org-defkey map "u" 'outline-up-heading))
7574 (org-defkey map "/" 'org-occur)
7575 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7576 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7577 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7578 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7579 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7580 map)))
7582 (defconst org-goto-help
7583 "Browse buffer copy, to find location or copy text.%s
7584 RET=jump to location C-g=quit and return to previous location
7585 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7587 (defvar org-goto-start-pos) ; dynamically scoped parameter
7589 (defun org-goto (&optional alternative-interface)
7590 "Look up a different location in the current file, keeping current visibility.
7592 When you want look-up or go to a different location in a
7593 document, the fastest way is often to fold the entire buffer and
7594 then dive into the tree. This method has the disadvantage, that
7595 the previous location will be folded, which may not be what you
7596 want.
7598 This command works around this by showing a copy of the current
7599 buffer in an indirect buffer, in overview mode. You can dive
7600 into the tree in that copy, use org-occur and incremental search
7601 to find a location. When pressing RET or `Q', the command
7602 returns to the original buffer in which the visibility is still
7603 unchanged. After RET it will also jump to the location selected
7604 in the indirect buffer and expose the headline hierarchy above.
7606 With a prefix argument, use the alternative interface: e.g., if
7607 `org-goto-interface' is `outline' use `outline-path-completion'."
7608 (interactive "P")
7609 (org-goto-map)
7610 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7611 (org-refile-use-outline-path t)
7612 (org-refile-target-verify-function nil)
7613 (interface
7614 (if (not alternative-interface)
7615 org-goto-interface
7616 (if (eq org-goto-interface 'outline)
7617 'outline-path-completion
7618 'outline)))
7619 (org-goto-start-pos (point))
7620 (selected-point
7621 (if (eq interface 'outline)
7622 (car (org-get-location (current-buffer) org-goto-help))
7623 (let ((pa (org-refile-get-location "Goto")))
7624 (org-refile-check-position pa)
7625 (nth 3 pa)))))
7626 (if selected-point
7627 (progn
7628 (org-mark-ring-push org-goto-start-pos)
7629 (goto-char selected-point)
7630 (when (or (outline-invisible-p) (org-invisible-p2))
7631 (org-show-context 'org-goto)))
7632 (message "Quit"))))
7634 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7635 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7636 (defvar org-goto-local-auto-isearch-map) ; defined below
7638 (defun org-get-location (_buf help)
7639 "Let the user select a location in current buffer.
7640 This function uses a recursive edit. It returns the selected position
7641 or nil."
7642 (org-no-popups
7643 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7644 (isearch-hide-immediately nil)
7645 (isearch-search-fun-function
7646 (lambda () 'org-goto-local-search-headings))
7647 (org-goto-selected-point org-goto-exit-command))
7648 (save-excursion
7649 (save-window-excursion
7650 (delete-other-windows)
7651 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7652 (pop-to-buffer-same-window
7653 (condition-case nil
7654 (make-indirect-buffer (current-buffer) "*org-goto*")
7655 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7656 (with-output-to-temp-buffer "*Org Help*"
7657 (princ (format help (if org-goto-auto-isearch
7658 " Just type for auto-isearch."
7659 " n/p/f/b/u to navigate, q to quit."))))
7660 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7661 (setq buffer-read-only nil)
7662 (let ((org-startup-truncated t)
7663 (org-startup-folded nil)
7664 (org-startup-align-all-tables nil))
7665 (org-mode)
7666 (org-overview))
7667 (setq buffer-read-only t)
7668 (if (and (boundp 'org-goto-start-pos)
7669 (integer-or-marker-p org-goto-start-pos))
7670 (progn (goto-char org-goto-start-pos)
7671 (when (outline-invisible-p)
7672 (org-show-set-visibility 'lineage)))
7673 (goto-char (point-min)))
7674 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7675 (message "Select location and press RET")
7676 (use-local-map org-goto-map)
7677 (recursive-edit)))
7678 (kill-buffer "*org-goto*")
7679 (cons org-goto-selected-point org-goto-exit-command))))
7681 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7682 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7683 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7684 (if (fboundp 'isearch-other-control-char)
7685 (progn
7686 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7687 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7688 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7689 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7690 (define-key org-goto-local-auto-isearch-map [return] nil))
7692 (defun org-goto-local-search-headings (string bound noerror)
7693 "Search and make sure that any matches are in headlines."
7694 (catch 'return
7695 (while (if isearch-forward
7696 (search-forward string bound noerror)
7697 (search-backward string bound noerror))
7698 (when (save-match-data
7699 (and (save-excursion
7700 (beginning-of-line)
7701 (looking-at org-complex-heading-regexp))
7702 (or (not (match-beginning 5))
7703 (< (point) (match-beginning 5)))))
7704 (throw 'return (point))))))
7706 (defun org-goto-local-auto-isearch ()
7707 "Start isearch."
7708 (interactive)
7709 (goto-char (point-min))
7710 (let ((keys (this-command-keys)))
7711 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7712 (isearch-mode t)
7713 (isearch-process-search-char (string-to-char keys)))))
7715 (defun org-goto-ret (&optional _arg)
7716 "Finish `org-goto' by going to the new location."
7717 (interactive "P")
7718 (setq org-goto-selected-point (point))
7719 (setq org-goto-exit-command 'return)
7720 (throw 'exit nil))
7722 (defun org-goto-left ()
7723 "Finish `org-goto' by going to the new location."
7724 (interactive)
7725 (if (org-at-heading-p)
7726 (progn
7727 (beginning-of-line 1)
7728 (setq org-goto-selected-point (point)
7729 org-goto-exit-command 'left)
7730 (throw 'exit nil))
7731 (user-error "Not on a heading")))
7733 (defun org-goto-right ()
7734 "Finish `org-goto' by going to the new location."
7735 (interactive)
7736 (if (org-at-heading-p)
7737 (progn
7738 (setq org-goto-selected-point (point)
7739 org-goto-exit-command 'right)
7740 (throw 'exit nil))
7741 (user-error "Not on a heading")))
7743 (defun org-goto-quit ()
7744 "Finish `org-goto' without cursor motion."
7745 (interactive)
7746 (setq org-goto-selected-point nil)
7747 (setq org-goto-exit-command 'quit)
7748 (throw 'exit nil))
7750 ;;; Indirect buffer display of subtrees
7752 (defvar org-indirect-dedicated-frame nil
7753 "This is the frame being used for indirect tree display.")
7754 (defvar org-last-indirect-buffer nil)
7756 (defun org-tree-to-indirect-buffer (&optional arg)
7757 "Create indirect buffer and narrow it to current subtree.
7758 With a numerical prefix ARG, go up to this level and then take that tree.
7759 If ARG is negative, go up that many levels.
7761 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7762 indirect buffer previously made with this command, to avoid proliferation of
7763 indirect buffers. However, when you call the command with a \
7764 \\[universal-argument] prefix, or
7765 when `org-indirect-buffer-display' is `new-frame', the last buffer
7766 is kept so that you can work with several indirect buffers at the same time.
7767 If `org-indirect-buffer-display' is `dedicated-frame', the \
7768 \\[universal-argument] prefix also
7769 requests that a new frame be made for the new buffer, so that the dedicated
7770 frame is not changed."
7771 (interactive "P")
7772 (let ((cbuf (current-buffer))
7773 (cwin (selected-window))
7774 (pos (point))
7775 beg end level heading ibuf)
7776 (save-excursion
7777 (org-back-to-heading t)
7778 (when (numberp arg)
7779 (setq level (org-outline-level))
7780 (when (< arg 0) (setq arg (+ level arg)))
7781 (while (> (setq level (org-outline-level)) arg)
7782 (org-up-heading-safe)))
7783 (setq beg (point)
7784 heading (org-get-heading 'no-tags))
7785 (org-end-of-subtree t t)
7786 (when (org-at-heading-p) (backward-char 1))
7787 (setq end (point)))
7788 (when (and (buffer-live-p org-last-indirect-buffer)
7789 (not (eq org-indirect-buffer-display 'new-frame))
7790 (not arg))
7791 (kill-buffer org-last-indirect-buffer))
7792 (setq ibuf (org-get-indirect-buffer cbuf heading)
7793 org-last-indirect-buffer ibuf)
7794 (cond
7795 ((or (eq org-indirect-buffer-display 'new-frame)
7796 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7797 (select-frame (make-frame))
7798 (delete-other-windows)
7799 (pop-to-buffer-same-window ibuf)
7800 (org-set-frame-title heading))
7801 ((eq org-indirect-buffer-display 'dedicated-frame)
7802 (raise-frame
7803 (select-frame (or (and org-indirect-dedicated-frame
7804 (frame-live-p org-indirect-dedicated-frame)
7805 org-indirect-dedicated-frame)
7806 (setq org-indirect-dedicated-frame (make-frame)))))
7807 (delete-other-windows)
7808 (pop-to-buffer-same-window ibuf)
7809 (org-set-frame-title (concat "Indirect: " heading)))
7810 ((eq org-indirect-buffer-display 'current-window)
7811 (pop-to-buffer-same-window ibuf))
7812 ((eq org-indirect-buffer-display 'other-window)
7813 (pop-to-buffer ibuf))
7814 (t (error "Invalid value")))
7815 (narrow-to-region beg end)
7816 (outline-show-all)
7817 (goto-char pos)
7818 (run-hook-with-args 'org-cycle-hook 'all)
7819 (and (window-live-p cwin) (select-window cwin))))
7821 (defun org-get-indirect-buffer (&optional buffer heading)
7822 (setq buffer (or buffer (current-buffer)))
7823 (let ((n 1) (base (buffer-name buffer)) bname)
7824 (while (buffer-live-p
7825 (get-buffer
7826 (setq bname
7827 (concat base "-"
7828 (if heading (concat heading "-" (number-to-string n))
7829 (number-to-string n))))))
7830 (setq n (1+ n)))
7831 (condition-case nil
7832 (make-indirect-buffer buffer bname 'clone)
7833 (error (make-indirect-buffer buffer bname)))))
7835 (defun org-set-frame-title (title)
7836 "Set the title of the current frame to the string TITLE."
7837 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7839 ;;;; Structure editing
7841 ;;; Inserting headlines
7843 (defun org--line-empty-p (n)
7844 "Is the Nth next line empty?
7846 Counts the current line as N = 1 and the previous line as N = 0;
7847 see `beginning-of-line'."
7848 (save-excursion
7849 (and (not (bobp))
7850 (or (beginning-of-line n) t)
7851 (save-match-data
7852 (looking-at "[ \t]*$")))))
7854 (defun org-previous-line-empty-p ()
7855 "Is the previous line a blank line?
7856 When NEXT is non-nil, check the next line instead."
7857 (org--line-empty-p 0))
7859 (defun org-next-line-empty-p ()
7860 "Is the previous line a blank line?
7861 When NEXT is non-nil, check the next line instead."
7862 (org--line-empty-p 2))
7864 (defun org-insert-heading (&optional arg invisible-ok top)
7865 "Insert a new heading or an item with the same depth at point.
7867 If point is at the beginning of a heading or a list item, insert
7868 a new heading or a new item above the current one. If point is
7869 at the beginning of a normal line, turn the line into a heading.
7871 If point is in the middle of a headline or a list item, split the
7872 headline or the item and create a new headline/item with the text
7873 in the current line after point \(see `org-M-RET-may-split-line'
7874 on how to modify this behavior).
7876 With one universal prefix argument, set the user option
7877 `org-insert-heading-respect-content' to t for the duration of
7878 the command. This modifies the behavior described above in this
7879 ways: on list items and at the beginning of normal lines, force
7880 the insertion of a heading after the current subtree.
7882 With two universal prefix arguments, insert the heading at the
7883 end of the grandparent subtree. For example, if point is within
7884 a 2nd-level heading, then it will insert a 2nd-level heading at
7885 the end of the 1st-level parent heading.
7887 If point is at the beginning of a headline, insert a sibling
7888 before the current headline. If point is not at the beginning,
7889 split the line and create a new headline with the text in the
7890 current line after point \(see `org-M-RET-may-split-line' on how
7891 to modify this behavior).
7893 If point is at the beginning of a normal line, turn this line
7894 into a heading.
7896 When INVISIBLE-OK is set, stop at invisible headlines when going
7897 back. This is important for non-interactive uses of the
7898 command.
7900 When optional argument TOP is non-nil, insert a level 1 heading,
7901 unconditionally."
7902 (interactive "P")
7903 (let ((itemp (and (not top) (org-in-item-p)))
7904 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7905 (respect-content (or org-insert-heading-respect-content
7906 (equal arg '(4))))
7907 (initial-content ""))
7909 (cond
7911 ((or (= (buffer-size) 0)
7912 (and (not (save-excursion
7913 (and (ignore-errors (org-back-to-heading invisible-ok))
7914 (org-at-heading-p))))
7915 (or arg (not itemp))))
7916 ;; At beginning of buffer or so high up that only a heading
7917 ;; makes sense.
7918 (cond ((and (bolp) (not respect-content)) (insert "* "))
7919 ((not respect-content)
7920 (unless may-split (end-of-line))
7921 (insert "\n* "))
7922 ((re-search-forward org-outline-regexp-bol nil t)
7923 (beginning-of-line)
7924 (insert "* \n")
7925 (backward-char))
7926 (t (goto-char (point-max))
7927 (insert "\n* ")))
7928 (run-hooks 'org-insert-heading-hook))
7930 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7933 ;; Maybe move at the end of the subtree
7934 (when (equal arg '(16))
7935 (org-up-heading-safe)
7936 (org-end-of-subtree t))
7937 ;; Insert a heading
7938 (save-restriction
7939 (widen)
7940 (let* ((level nil)
7941 (on-heading (org-at-heading-p))
7942 (empty-line-p (if on-heading
7943 (org-previous-line-empty-p)
7944 ;; We will decide later
7945 nil))
7946 ;; Get a level string to fall back on.
7947 (fix-level
7948 (if (org-before-first-heading-p) "*"
7949 (save-excursion
7950 (org-back-to-heading t)
7951 (when (org-previous-line-empty-p) (setq empty-line-p t))
7952 (looking-at org-outline-regexp)
7953 (make-string (1- (length (match-string 0))) ?*))))
7954 (stars
7955 (save-excursion
7956 (condition-case nil
7957 (if top "* "
7958 (org-back-to-heading invisible-ok)
7959 (when (and (not on-heading)
7960 (featurep 'org-inlinetask)
7961 (integerp org-inlinetask-min-level)
7962 (>= (length (match-string 0))
7963 org-inlinetask-min-level))
7964 ;; Find a heading level before the inline
7965 ;; task.
7966 (while (and (setq level (org-up-heading-safe))
7967 (>= level org-inlinetask-min-level)))
7968 (if (org-at-heading-p)
7969 (org-back-to-heading invisible-ok)
7970 (error "This should not happen")))
7971 (unless (and (save-excursion
7972 (save-match-data
7973 (org-backward-heading-same-level
7974 1 invisible-ok))
7975 (= (point) (match-beginning 0)))
7976 (not (org-next-line-empty-p)))
7977 (setq empty-line-p (or empty-line-p
7978 (org-previous-line-empty-p))))
7979 (match-string 0))
7980 (error (or fix-level "* ")))))
7981 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7982 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7984 ;; If we insert after content, move there and clean up
7985 ;; whitespace.
7986 (when (and respect-content
7987 (not (looking-at-p org-outline-regexp-bol)))
7988 (if (not (org-before-first-heading-p))
7989 (org-end-of-subtree nil t)
7990 (re-search-forward org-outline-regexp-bol)
7991 (beginning-of-line 0))
7992 (skip-chars-backward " \r\t\n")
7993 (and (not (looking-back "^\\*+" (line-beginning-position)))
7994 (looking-at "[ \t]+") (replace-match ""))
7995 (unless (eobp) (forward-char 1))
7996 (when (looking-at "^\\*")
7997 (unless (bobp) (backward-char 1))
7998 (insert "\n")))
8000 ;; If we are splitting, grab the text that should be moved
8001 ;; to the new headline.
8002 (when may-split
8003 (if (org-at-heading-p)
8004 ;; This is a heading: split intelligently (keeping
8005 ;; tags).
8006 (let ((pos (point)))
8007 (beginning-of-line)
8008 (unless (looking-at org-complex-heading-regexp)
8009 (error "This should not happen"))
8010 (when (and (match-beginning 4)
8011 (> pos (match-beginning 4))
8012 (< pos (match-end 4)))
8013 (setq initial-content (buffer-substring pos (match-end 4)))
8014 (goto-char pos)
8015 (delete-region (point) (match-end 4))
8016 (if (looking-at "[ \t]*$")
8017 (replace-match "")
8018 (insert (make-string (length initial-content) ?\s)))
8019 (setq initial-content (org-trim initial-content)))
8020 (goto-char pos))
8021 ;; A normal line.
8022 (setq initial-content
8023 (org-trim
8024 (delete-and-extract-region (point) (line-end-position))))))
8026 ;; If we are at the beginning of the line, insert before it.
8027 ;; Otherwise, after it.
8028 (cond
8029 ((and (bolp) (looking-at "[ \t]*$")))
8030 ((bolp) (save-excursion (insert "\n")))
8031 (t (end-of-line)
8032 (insert "\n")))
8034 ;; Insert the new heading
8035 (insert stars)
8036 (just-one-space)
8037 (insert initial-content)
8038 (unless (and blank (org-previous-line-empty-p))
8039 (org-N-empty-lines-before-current (if blank 1 0)))
8040 ;; Adjust visibility, which may be messed up if we removed
8041 ;; blank lines while previous entry was hidden.
8042 (let ((bol (line-beginning-position)))
8043 (dolist (o (overlays-at (1- bol)))
8044 (when (and (eq (overlay-get o 'invisible) 'outline)
8045 (eq (overlay-end o) bol))
8046 (move-overlay o (overlay-start o) (1- bol)))))
8047 (run-hooks 'org-insert-heading-hook)))))))
8049 (defun org-N-empty-lines-before-current (N)
8050 "Make the number of empty lines before current exactly N.
8051 So this will delete or add empty lines."
8052 (save-excursion
8053 (beginning-of-line)
8054 (let ((p (point)))
8055 (skip-chars-backward " \r\t\n")
8056 (unless (bolp) (forward-line))
8057 (delete-region (point) p))
8058 (when (> N 0) (insert (make-string N ?\n)))))
8060 (defun org-get-heading (&optional no-tags no-todo)
8061 "Return the heading of the current entry, without the stars.
8062 When NO-TAGS is non-nil, don't include tags.
8063 When NO-TODO is non-nil, don't include TODO keywords."
8064 (save-excursion
8065 (org-back-to-heading t)
8066 (let ((case-fold-search nil))
8067 (cond
8068 ((and no-tags no-todo)
8069 (looking-at org-complex-heading-regexp)
8070 ;; Return value has to be a string, but match group 4 is
8071 ;; optional.
8072 (or (match-string 4) ""))
8073 (no-tags
8074 (looking-at (concat org-outline-regexp
8075 "\\(.*?\\)"
8076 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8077 (match-string 1))
8078 (no-todo
8079 (looking-at org-todo-line-regexp)
8080 (match-string 3))
8081 (t (looking-at org-heading-regexp)
8082 (match-string 2))))))
8084 (defvar orgstruct-mode) ; defined below
8086 (defun org-heading-components ()
8087 "Return the components of the current heading.
8088 This is a list with the following elements:
8089 - the level as an integer
8090 - the reduced level, different if `org-odd-levels-only' is set.
8091 - the TODO keyword, or nil
8092 - the priority character, like ?A, or nil if no priority is given
8093 - the headline text itself, or the tags string if no headline text
8094 - the tags string, or nil."
8095 (save-excursion
8096 (org-back-to-heading t)
8097 (when (let (case-fold-search)
8098 (looking-at
8099 (if orgstruct-mode
8100 org-heading-regexp
8101 org-complex-heading-regexp)))
8102 (if orgstruct-mode
8103 (list (length (match-string 1))
8104 (org-reduced-level (length (match-string 1)))
8107 (match-string 2)
8108 nil)
8109 (list (length (match-string 1))
8110 (org-reduced-level (length (match-string 1)))
8111 (match-string-no-properties 2)
8112 (and (match-end 3) (aref (match-string 3) 2))
8113 (match-string-no-properties 4)
8114 (match-string-no-properties 5))))))
8116 (defun org-get-entry ()
8117 "Get the entry text, after heading, entire subtree."
8118 (save-excursion
8119 (org-back-to-heading t)
8120 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8122 (defun org-edit-headline (&optional heading)
8123 "Edit the current headline.
8124 Set it to HEADING when provided."
8125 (interactive)
8126 (org-with-wide-buffer
8127 (org-back-to-heading t)
8128 (when (looking-at org-complex-heading-regexp)
8129 (let* ((old (match-string-no-properties 4))
8130 (new (save-match-data
8131 (org-trim (or heading (read-string "Edit: " old))))))
8132 (unless (equal old new)
8133 (if old (replace-match new t t nil 4)
8134 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8135 (insert " " new))
8136 (org-set-tags nil t)
8137 (when (looking-at "[ \t]*$") (replace-match "")))))))
8139 (defun org-insert-heading-after-current ()
8140 "Insert a new heading with same level as current, after current subtree."
8141 (interactive)
8142 (org-back-to-heading)
8143 (org-insert-heading)
8144 (org-move-subtree-down)
8145 (end-of-line 1))
8147 (defun org-insert-heading-respect-content (&optional invisible-ok)
8148 "Insert heading with `org-insert-heading-respect-content' set to t."
8149 (interactive)
8150 (org-insert-heading '(4) invisible-ok))
8152 (defun org-insert-todo-heading-respect-content (&optional force-state)
8153 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8154 (interactive)
8155 (org-insert-todo-heading force-state '(4)))
8157 (defun org-insert-todo-heading (arg &optional force-heading)
8158 "Insert a new heading with the same level and TODO state as current heading.
8159 If the heading has no TODO state, or if the state is DONE, use the first
8160 state (TODO by default). Also with one prefix arg, force first state. With
8161 two prefix args, force inserting at the end of the parent subtree."
8162 (interactive "P")
8163 (when (or force-heading (not (org-insert-item 'checkbox)))
8164 (org-insert-heading (or (and (equal arg '(16)) '(16))
8165 force-heading))
8166 (save-excursion
8167 (org-back-to-heading)
8168 (outline-previous-heading)
8169 (looking-at org-todo-line-regexp))
8170 (let*
8171 ((new-mark-x
8172 (if (or (equal arg '(4))
8173 (not (match-beginning 2))
8174 (member (match-string 2) org-done-keywords))
8175 (car org-todo-keywords-1)
8176 (match-string 2)))
8177 (new-mark
8179 (run-hook-with-args-until-success
8180 'org-todo-get-default-hook new-mark-x nil)
8181 new-mark-x)))
8182 (beginning-of-line 1)
8183 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8184 (if org-treat-insert-todo-heading-as-state-change
8185 (org-todo new-mark)
8186 (insert new-mark " "))))
8187 (when org-provide-todo-statistics
8188 (org-update-parent-todo-statistics))))
8190 (defun org-insert-subheading (arg)
8191 "Insert a new subheading and demote it.
8192 Works for outline headings and for plain lists alike."
8193 (interactive "P")
8194 (org-insert-heading arg)
8195 (cond
8196 ((org-at-heading-p) (org-do-demote))
8197 ((org-at-item-p) (org-indent-item))))
8199 (defun org-insert-todo-subheading (arg)
8200 "Insert a new subheading with TODO keyword or checkbox and demote it.
8201 Works for outline headings and for plain lists alike."
8202 (interactive "P")
8203 (org-insert-todo-heading arg)
8204 (cond
8205 ((org-at-heading-p) (org-do-demote))
8206 ((org-at-item-p) (org-indent-item))))
8208 ;;; Promotion and Demotion
8210 (defvar org-after-demote-entry-hook nil
8211 "Hook run after an entry has been demoted.
8212 The cursor will be at the beginning of the entry.
8213 When a subtree is being demoted, the hook will be called for each node.")
8215 (defvar org-after-promote-entry-hook nil
8216 "Hook run after an entry has been promoted.
8217 The cursor will be at the beginning of the entry.
8218 When a subtree is being promoted, the hook will be called for each node.")
8220 (defun org-promote-subtree ()
8221 "Promote the entire subtree.
8222 See also `org-promote'."
8223 (interactive)
8224 (save-excursion
8225 (org-with-limited-levels (org-map-tree 'org-promote)))
8226 (org-fix-position-after-promote))
8228 (defun org-demote-subtree ()
8229 "Demote the entire subtree.
8230 See `org-demote' and `org-promote'."
8231 (interactive)
8232 (save-excursion
8233 (org-with-limited-levels (org-map-tree 'org-demote)))
8234 (org-fix-position-after-promote))
8236 (defun org-do-promote ()
8237 "Promote the current heading higher up the tree.
8238 If the region is active in `transient-mark-mode', promote all
8239 headings in the region."
8240 (interactive)
8241 (save-excursion
8242 (if (org-region-active-p)
8243 (org-map-region 'org-promote (region-beginning) (region-end))
8244 (org-promote)))
8245 (org-fix-position-after-promote))
8247 (defun org-do-demote ()
8248 "Demote the current heading lower down the tree.
8249 If the region is active in `transient-mark-mode', demote all
8250 headings in the region."
8251 (interactive)
8252 (save-excursion
8253 (if (org-region-active-p)
8254 (org-map-region 'org-demote (region-beginning) (region-end))
8255 (org-demote)))
8256 (org-fix-position-after-promote))
8258 (defun org-fix-position-after-promote ()
8259 "Fix cursor position and indentation after demoting/promoting."
8260 (let ((pos (point)))
8261 (when (save-excursion
8262 (beginning-of-line 1)
8263 (looking-at org-todo-line-regexp)
8264 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8265 (cond ((eobp) (insert " "))
8266 ((eolp) (insert " "))
8267 ((equal (char-after) ?\ ) (forward-char 1))))))
8269 (defun org-current-level ()
8270 "Return the level of the current entry, or nil if before the first headline.
8271 The level is the number of stars at the beginning of the
8272 headline. Use `org-reduced-level' to remove the effect of
8273 `org-odd-levels'. Unlike to `org-outline-level', this function
8274 ignores inlinetasks."
8275 (let ((level (org-with-limited-levels (org-outline-level))))
8276 (and (> level 0) level)))
8278 (defun org-get-previous-line-level ()
8279 "Return the outline depth of the last headline before the current line.
8280 Returns 0 for the first headline in the buffer, and nil if before the
8281 first headline."
8282 (and (org-current-level)
8283 (or (and (/= (line-beginning-position) (point-min))
8284 (save-excursion (beginning-of-line 0) (org-current-level)))
8285 0)))
8287 (defun org-reduced-level (l)
8288 "Compute the effective level of a heading.
8289 This takes into account the setting of `org-odd-levels-only'."
8290 (cond
8291 ((zerop l) 0)
8292 (org-odd-levels-only (1+ (floor (/ l 2))))
8293 (t l)))
8295 (defun org-level-increment ()
8296 "Return the number of stars that will be added or removed at a
8297 time to headlines when structure editing, based on the value of
8298 `org-odd-levels-only'."
8299 (if org-odd-levels-only 2 1))
8301 (defun org-get-valid-level (level &optional change)
8302 "Rectify a level change under the influence of `org-odd-levels-only'
8303 LEVEL is a current level, CHANGE is by how much the level should be
8304 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8305 even level numbers will become the next higher odd number."
8306 (if org-odd-levels-only
8307 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8308 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8309 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8310 (max 1 (+ level (or change 0)))))
8312 (defun org-promote ()
8313 "Promote the current heading higher up the tree."
8314 (org-with-wide-buffer
8315 (org-back-to-heading t)
8316 (let* ((after-change-functions (remq 'flyspell-after-change-function
8317 after-change-functions))
8318 (level (save-match-data (funcall outline-level)))
8319 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8320 (diff (abs (- level (length up-head) -1))))
8321 (cond
8322 ((and (= level 1) org-allow-promoting-top-level-subtree)
8323 (replace-match "# " nil t))
8324 ((= level 1)
8325 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8326 (t (replace-match up-head nil t)))
8327 (unless (= level 1)
8328 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8329 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8330 (run-hooks 'org-after-promote-entry-hook))))
8332 (defun org-demote ()
8333 "Demote the current heading lower down the tree."
8334 (org-with-wide-buffer
8335 (org-back-to-heading t)
8336 (let* ((after-change-functions (remq 'flyspell-after-change-function
8337 after-change-functions))
8338 (level (save-match-data (funcall outline-level)))
8339 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8340 (diff (abs (- level (length down-head) -1))))
8341 (replace-match down-head nil t)
8342 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8343 (when org-adapt-indentation (org-fixup-indentation diff))
8344 (run-hooks 'org-after-demote-entry-hook))))
8346 (defun org-cycle-level ()
8347 "Cycle the level of an empty headline through possible states.
8348 This goes first to child, then to parent, level, then up the hierarchy.
8349 After top level, it switches back to sibling level."
8350 (interactive)
8351 (let ((org-adapt-indentation nil))
8352 (when (org-point-at-end-of-empty-headline)
8353 (setq this-command 'org-cycle-level) ; Only needed for caching
8354 (let ((cur-level (org-current-level))
8355 (prev-level (org-get-previous-line-level)))
8356 (cond
8357 ;; If first headline in file, promote to top-level.
8358 ((= prev-level 0)
8359 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8360 do (org-do-promote)))
8361 ;; If same level as prev, demote one.
8362 ((= prev-level cur-level)
8363 (org-do-demote))
8364 ;; If parent is top-level, promote to top level if not already.
8365 ((= prev-level 1)
8366 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8367 do (org-do-promote)))
8368 ;; If top-level, return to prev-level.
8369 ((= cur-level 1)
8370 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8371 do (org-do-demote)))
8372 ;; If less than prev-level, promote one.
8373 ((< cur-level prev-level)
8374 (org-do-promote))
8375 ;; If deeper than prev-level, promote until higher than
8376 ;; prev-level.
8377 ((> cur-level prev-level)
8378 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8379 do (org-do-promote))))
8380 t))))
8382 (defun org-map-tree (fun)
8383 "Call FUN for every heading underneath the current one."
8384 (org-back-to-heading t)
8385 (let ((level (funcall outline-level)))
8386 (save-excursion
8387 (funcall fun)
8388 (while (and (progn
8389 (outline-next-heading)
8390 (> (funcall outline-level) level))
8391 (not (eobp)))
8392 (funcall fun)))))
8394 (defun org-map-region (fun beg end)
8395 "Call FUN for every heading between BEG and END."
8396 (let ((org-ignore-region t))
8397 (save-excursion
8398 (setq end (copy-marker end))
8399 (goto-char beg)
8400 (when (and (re-search-forward org-outline-regexp-bol nil t)
8401 (< (point) end))
8402 (funcall fun))
8403 (while (and (progn
8404 (outline-next-heading)
8405 (< (point) end))
8406 (not (eobp)))
8407 (funcall fun)))))
8409 (defun org-fixup-indentation (diff)
8410 "Change the indentation in the current entry by DIFF.
8412 DIFF is an integer. Indentation is done according to the
8413 following rules:
8415 - Planning information and property drawers are always indented
8416 according to the new level of the headline;
8418 - Footnote definitions and their contents are ignored;
8420 - Inlinetasks' boundaries are not shifted;
8422 - Empty lines are ignored;
8424 - Other lines' indentation are shifted by DIFF columns, unless
8425 it would introduce a structural change in the document, in
8426 which case no shifting is done at all.
8428 Assume point is at a heading or an inlinetask beginning."
8429 (org-with-wide-buffer
8430 (narrow-to-region (line-beginning-position)
8431 (save-excursion
8432 (if (org-with-limited-levels (org-at-heading-p))
8433 (org-with-limited-levels (outline-next-heading))
8434 (org-inlinetask-goto-end))
8435 (point)))
8436 (forward-line)
8437 ;; Indent properly planning info and property drawer.
8438 (when (looking-at-p org-planning-line-re)
8439 (org-indent-line)
8440 (forward-line))
8441 (when (looking-at org-property-drawer-re)
8442 (goto-char (match-end 0))
8443 (forward-line)
8444 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8445 (catch 'no-shift
8446 (when (zerop diff) (throw 'no-shift nil))
8447 ;; If DIFF is negative, first check if a shift is possible at all
8448 ;; (e.g., it doesn't break structure). This can only happen if
8449 ;; some contents are not properly indented.
8450 (let ((case-fold-search t))
8451 (when (< diff 0)
8452 (let ((diff (- diff))
8453 (forbidden-re (concat org-outline-regexp
8454 "\\|"
8455 (substring org-footnote-definition-re 1))))
8456 (save-excursion
8457 (while (not (eobp))
8458 (cond
8459 ((looking-at-p "[ \t]*$") (forward-line))
8460 ((and (looking-at-p org-footnote-definition-re)
8461 (let ((e (org-element-at-point)))
8462 (and (eq (org-element-type e) 'footnote-definition)
8463 (goto-char (org-element-property :end e))))))
8464 ((looking-at-p org-outline-regexp) (forward-line))
8465 ;; Give up if shifting would move before column 0 or
8466 ;; if it would introduce a headline or a footnote
8467 ;; definition.
8469 (skip-chars-forward " \t")
8470 (let ((ind (current-column)))
8471 (when (or (< ind diff)
8472 (and (= ind diff) (looking-at-p forbidden-re)))
8473 (throw 'no-shift nil)))
8474 ;; Ignore contents of example blocks and source
8475 ;; blocks if their indentation is meant to be
8476 ;; preserved. Jump to block's closing line.
8477 (beginning-of-line)
8478 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8479 (let ((e (org-element-at-point)))
8480 (and (memq (org-element-type e)
8481 '(example-block src-block))
8482 (or org-src-preserve-indentation
8483 (org-element-property :preserve-indent e))
8484 (goto-char (org-element-property :end e))
8485 (progn (skip-chars-backward " \r\t\n")
8486 (beginning-of-line)
8487 t))))
8488 (forward-line))))))))
8489 ;; Shift lines but footnote definitions, inlinetasks boundaries
8490 ;; by DIFF. Also skip contents of source or example blocks
8491 ;; when indentation is meant to be preserved.
8492 (while (not (eobp))
8493 (cond
8494 ((and (looking-at-p org-footnote-definition-re)
8495 (let ((e (org-element-at-point)))
8496 (and (eq (org-element-type e) 'footnote-definition)
8497 (goto-char (org-element-property :end e))))))
8498 ((looking-at-p org-outline-regexp) (forward-line))
8499 ((looking-at-p "[ \t]*$") (forward-line))
8501 (indent-line-to (+ (org-get-indentation) diff))
8502 (beginning-of-line)
8503 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8504 (let ((e (org-element-at-point)))
8505 (and (memq (org-element-type e)
8506 '(example-block src-block))
8507 (or org-src-preserve-indentation
8508 (org-element-property :preserve-indent e))
8509 (goto-char (org-element-property :end e))
8510 (progn (skip-chars-backward " \r\t\n")
8511 (beginning-of-line)
8512 t))))
8513 (forward-line)))))))))
8515 (defun org-convert-to-odd-levels ()
8516 "Convert an Org file with all levels allowed to one with odd levels.
8517 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8518 level 5 etc."
8519 (interactive)
8520 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8521 (let ((outline-level 'org-outline-level)
8522 (org-odd-levels-only nil) n)
8523 (save-excursion
8524 (goto-char (point-min))
8525 (while (re-search-forward "^\\*\\*+ " nil t)
8526 (setq n (- (length (match-string 0)) 2))
8527 (while (>= (setq n (1- n)) 0)
8528 (org-demote))
8529 (end-of-line 1))))))
8531 (defun org-convert-to-oddeven-levels ()
8532 "Convert an Org file with only odd levels to one with odd/even levels.
8533 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8534 file contains a section with an even level, conversion would
8535 destroy the structure of the file. An error is signaled in this
8536 case."
8537 (interactive)
8538 (goto-char (point-min))
8539 ;; First check if there are no even levels
8540 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8541 (org-show-set-visibility 'canonical)
8542 (error "Not all levels are odd in this file. Conversion not possible"))
8543 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8544 (let ((outline-regexp org-outline-regexp)
8545 (outline-level 'org-outline-level)
8546 (org-odd-levels-only nil) n)
8547 (save-excursion
8548 (goto-char (point-min))
8549 (while (re-search-forward "^\\*\\*+ " nil t)
8550 (setq n (/ (1- (length (match-string 0))) 2))
8551 (while (>= (setq n (1- n)) 0)
8552 (org-promote))
8553 (end-of-line 1))))))
8555 (defun org-tr-level (n)
8556 "Make N odd if required."
8557 (if org-odd-levels-only (1+ (/ n 2)) n))
8559 ;;; Vertical tree motion, cutting and pasting of subtrees
8561 (defun org-move-subtree-up (&optional arg)
8562 "Move the current subtree up past ARG headlines of the same level."
8563 (interactive "p")
8564 (org-move-subtree-down (- (prefix-numeric-value arg))))
8566 (defun org-move-subtree-down (&optional arg)
8567 "Move the current subtree down past ARG headlines of the same level."
8568 (interactive "p")
8569 (setq arg (prefix-numeric-value arg))
8570 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8571 'org-get-last-sibling))
8572 (ins-point (make-marker))
8573 (cnt (abs arg))
8574 (col (current-column))
8575 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8576 ;; Select the tree
8577 (org-back-to-heading)
8578 (setq beg0 (point))
8579 (save-excursion
8580 (setq ne-beg (org-back-over-empty-lines))
8581 (setq beg (point)))
8582 (save-match-data
8583 (save-excursion (outline-end-of-heading)
8584 (setq folded (outline-invisible-p)))
8585 (progn (org-end-of-subtree nil t)
8586 (unless (eobp) (backward-char))))
8587 (outline-next-heading)
8588 (setq ne-end (org-back-over-empty-lines))
8589 (setq end (point))
8590 (goto-char beg0)
8591 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8592 ;; include less whitespace
8593 (save-excursion
8594 (goto-char beg)
8595 (forward-line (- ne-beg ne-end))
8596 (setq beg (point))))
8597 ;; Find insertion point, with error handling
8598 (while (> cnt 0)
8599 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8600 (progn (goto-char beg0)
8601 (user-error "Cannot move past superior level or buffer limit")))
8602 (setq cnt (1- cnt)))
8603 (when (> arg 0)
8604 ;; Moving forward - still need to move over subtree
8605 (org-end-of-subtree t t)
8606 (save-excursion
8607 (org-back-over-empty-lines)
8608 (or (bolp) (newline))))
8609 (setq ne-ins (org-back-over-empty-lines))
8610 (move-marker ins-point (point))
8611 (setq txt (buffer-substring beg end))
8612 (org-save-markers-in-region beg end)
8613 (delete-region beg end)
8614 (org-remove-empty-overlays-at beg)
8615 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8616 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8617 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8618 (let ((bbb (point)))
8619 (insert-before-markers txt)
8620 (org-reinstall-markers-in-region bbb)
8621 (move-marker ins-point bbb))
8622 (or (bolp) (insert "\n"))
8623 (setq ins-end (point))
8624 (goto-char ins-point)
8625 (org-skip-whitespace)
8626 (when (and (< arg 0)
8627 (org-first-sibling-p)
8628 (> ne-ins ne-beg))
8629 ;; Move whitespace back to beginning
8630 (save-excursion
8631 (goto-char ins-end)
8632 (let ((kill-whole-line t))
8633 (kill-line (- ne-ins ne-beg)) (point)))
8634 (insert (make-string (- ne-ins ne-beg) ?\n)))
8635 (move-marker ins-point nil)
8636 (if folded
8637 (outline-hide-subtree)
8638 (org-show-entry)
8639 (org-show-children)
8640 (org-cycle-hide-drawers 'children))
8641 (org-clean-visibility-after-subtree-move)
8642 ;; move back to the initial column we were at
8643 (move-to-column col)))
8645 (defvar org-subtree-clip ""
8646 "Clipboard for cut and paste of subtrees.
8647 This is actually only a copy of the kill, because we use the normal kill
8648 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8650 (defvar org-subtree-clip-folded nil
8651 "Was the last copied subtree folded?
8652 This is used to fold the tree back after pasting.")
8654 (defun org-cut-subtree (&optional n)
8655 "Cut the current subtree into the clipboard.
8656 With prefix arg N, cut this many sequential subtrees.
8657 This is a short-hand for marking the subtree and then cutting it."
8658 (interactive "p")
8659 (org-copy-subtree n 'cut))
8661 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8662 "Copy the current subtree it in the clipboard.
8663 With prefix arg N, copy this many sequential subtrees.
8664 This is a short-hand for marking the subtree and then copying it.
8665 If CUT is non-nil, actually cut the subtree.
8666 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8667 of some markers in the region, even if CUT is non-nil. This is
8668 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8669 (interactive "p")
8670 (let (beg end folded (beg0 (point)))
8671 (if (called-interactively-p 'any)
8672 (org-back-to-heading nil) ; take what looks like a subtree
8673 (org-back-to-heading t)) ; take what is really there
8674 (setq beg (point))
8675 (skip-chars-forward " \t\r\n")
8676 (save-match-data
8677 (if nosubtrees
8678 (outline-next-heading)
8679 (save-excursion (outline-end-of-heading)
8680 (setq folded (outline-invisible-p)))
8681 (ignore-errors (org-forward-heading-same-level (1- n) t))
8682 (org-end-of-subtree t t)))
8683 ;; Include the end of an inlinetask
8684 (when (and (featurep 'org-inlinetask)
8685 (looking-at-p (concat (org-inlinetask-outline-regexp)
8686 "END[ \t]*$")))
8687 (end-of-line))
8688 (setq end (point))
8689 (goto-char beg0)
8690 (when (> end beg)
8691 (setq org-subtree-clip-folded folded)
8692 (when (or cut force-store-markers)
8693 (org-save-markers-in-region beg end))
8694 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8695 (setq org-subtree-clip (current-kill 0))
8696 (message "%s: Subtree(s) with %d characters"
8697 (if cut "Cut" "Copied")
8698 (length org-subtree-clip)))))
8700 (defun org-paste-subtree (&optional level tree for-yank remove)
8701 "Paste the clipboard as a subtree, with modification of headline level.
8702 The entire subtree is promoted or demoted in order to match a new headline
8703 level.
8705 If the cursor is at the beginning of a headline, the same level as
8706 that headline is used to paste the tree.
8708 If not, the new level is derived from the *visible* headings
8709 before and after the insertion point, and taken to be the inferior headline
8710 level of the two. So if the previous visible heading is level 3 and the
8711 next is level 4 (or vice versa), level 4 will be used for insertion.
8712 This makes sure that the subtree remains an independent subtree and does
8713 not swallow low level entries.
8715 You can also force a different level, either by using a numeric prefix
8716 argument, or by inserting the heading marker by hand. For example, if the
8717 cursor is after \"*****\", then the tree will be shifted to level 5.
8719 If optional TREE is given, use this text instead of the kill ring.
8721 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8722 move back over whitespace before inserting, and move point to the end of
8723 the inserted text when done.
8725 When REMOVE is non-nil, remove the subtree from the clipboard."
8726 (interactive "P")
8727 (setq tree (or tree (and kill-ring (current-kill 0))))
8728 (unless (org-kill-is-subtree-p tree)
8729 (user-error "%s"
8730 (substitute-command-keys
8731 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8732 (org-with-limited-levels
8733 (let* ((visp (not (outline-invisible-p)))
8734 (txt tree)
8735 (^re_ "\\(\\*+\\)[ \t]*")
8736 (old-level (if (string-match org-outline-regexp-bol txt)
8737 (- (match-end 0) (match-beginning 0) 1)
8738 -1))
8739 (force-level (cond (level (prefix-numeric-value level))
8740 ((and (looking-at "[ \t]*$")
8741 (string-match
8742 "^\\*+$" (buffer-substring
8743 (point-at-bol) (point))))
8744 (- (match-end 0) (match-beginning 0)))
8745 ((and (bolp)
8746 (looking-at org-outline-regexp))
8747 (- (match-end 0) (point) 1))))
8748 (previous-level (save-excursion
8749 (condition-case nil
8750 (progn
8751 (outline-previous-visible-heading 1)
8752 (if (looking-at ^re_)
8753 (- (match-end 0) (match-beginning 0) 1)
8755 (error 1))))
8756 (next-level (save-excursion
8757 (condition-case nil
8758 (progn
8759 (or (looking-at org-outline-regexp)
8760 (outline-next-visible-heading 1))
8761 (if (looking-at ^re_)
8762 (- (match-end 0) (match-beginning 0) 1)
8764 (error 1))))
8765 (new-level (or force-level (max previous-level next-level)))
8766 (shift (if (or (= old-level -1)
8767 (= new-level -1)
8768 (= old-level new-level))
8770 (- new-level old-level)))
8771 (delta (if (> shift 0) -1 1))
8772 (func (if (> shift 0) 'org-demote 'org-promote))
8773 (org-odd-levels-only nil)
8774 beg end newend)
8775 ;; Remove the forced level indicator
8776 (when force-level
8777 (delete-region (point-at-bol) (point)))
8778 ;; Paste
8779 (beginning-of-line (if (bolp) 1 2))
8780 (setq beg (point))
8781 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8782 (insert-before-markers txt)
8783 (unless (string-suffix-p "\n" txt) (insert "\n"))
8784 (setq newend (point))
8785 (org-reinstall-markers-in-region beg)
8786 (setq end (point))
8787 (goto-char beg)
8788 (skip-chars-forward " \t\n\r")
8789 (setq beg (point))
8790 (when (and (outline-invisible-p) visp)
8791 (save-excursion (outline-show-heading)))
8792 ;; Shift if necessary
8793 (unless (= shift 0)
8794 (save-restriction
8795 (narrow-to-region beg end)
8796 (while (not (= shift 0))
8797 (org-map-region func (point-min) (point-max))
8798 (setq shift (+ delta shift)))
8799 (goto-char (point-min))
8800 (setq newend (point-max))))
8801 (when (or (called-interactively-p 'interactive) for-yank)
8802 (message "Clipboard pasted as level %d subtree" new-level))
8803 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8804 kill-ring
8805 (eq org-subtree-clip (current-kill 0))
8806 org-subtree-clip-folded)
8807 ;; The tree was folded before it was killed/copied
8808 (outline-hide-subtree))
8809 (and for-yank (goto-char newend))
8810 (and remove (setq kill-ring (cdr kill-ring))))))
8812 (defun org-kill-is-subtree-p (&optional txt)
8813 "Check if the current kill is an outline subtree, or a set of trees.
8814 Returns nil if kill does not start with a headline, or if the first
8815 headline level is not the largest headline level in the tree.
8816 So this will actually accept several entries of equal levels as well,
8817 which is OK for `org-paste-subtree'.
8818 If optional TXT is given, check this string instead of the current kill."
8819 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8820 (re (org-get-limited-outline-regexp))
8821 (^re (concat "^" re))
8822 (start-level (and kill
8823 (string-match
8824 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8825 kill)
8826 (- (match-end 2) (match-beginning 2) 1)))
8827 (start (1+ (or (match-beginning 2) -1))))
8828 (if (not start-level)
8829 (progn
8830 nil) ;; does not even start with a heading
8831 (catch 'exit
8832 (while (setq start (string-match ^re kill (1+ start)))
8833 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8834 (throw 'exit nil)))
8835 t))))
8837 (defvar org-markers-to-move nil
8838 "Markers that should be moved with a cut-and-paste operation.
8839 Those markers are stored together with their positions relative to
8840 the start of the region.")
8842 (defun org-save-markers-in-region (beg end)
8843 "Check markers in region.
8844 If these markers are between BEG and END, record their position relative
8845 to BEG, so that after moving the block of text, we can put the markers back
8846 into place.
8847 This function gets called just before an entry or tree gets cut from the
8848 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8849 called immediately, to move the markers with the entries."
8850 (setq org-markers-to-move nil)
8851 (when (featurep 'org-clock)
8852 (org-clock-save-markers-for-cut-and-paste beg end))
8853 (when (featurep 'org-agenda)
8854 (org-agenda-save-markers-for-cut-and-paste beg end)))
8856 (defun org-check-and-save-marker (marker beg end)
8857 "Check if MARKER is between BEG and END.
8858 If yes, remember the marker and the distance to BEG."
8859 (when (and (marker-buffer marker)
8860 (equal (marker-buffer marker) (current-buffer))
8861 (>= marker beg) (< marker end))
8862 (push (cons marker (- marker beg)) org-markers-to-move)))
8864 (defun org-reinstall-markers-in-region (beg)
8865 "Move all remembered markers to their position relative to BEG."
8866 (dolist (x org-markers-to-move)
8867 (move-marker (car x) (+ beg (cdr x))))
8868 (setq org-markers-to-move nil))
8870 (defun org-narrow-to-subtree ()
8871 "Narrow buffer to the current subtree."
8872 (interactive)
8873 (save-excursion
8874 (save-match-data
8875 (org-with-limited-levels
8876 (narrow-to-region
8877 (progn (org-back-to-heading t) (point))
8878 (progn (org-end-of-subtree t t)
8879 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8880 (point)))))))
8882 (defun org-narrow-to-block ()
8883 "Narrow buffer to the current block."
8884 (interactive)
8885 (let* ((case-fold-search t)
8886 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8887 "^[ \t]*#\\+end_.*")))
8888 (if blockp
8889 (narrow-to-region (car blockp) (cdr blockp))
8890 (user-error "Not in a block"))))
8892 (defun org-clone-subtree-with-time-shift (n &optional shift)
8893 "Clone the task (subtree) at point N times.
8894 The clones will be inserted as siblings.
8896 In interactive use, the user will be prompted for the number of
8897 clones to be produced. If the entry has a timestamp, the user
8898 will also be prompted for a time shift, which may be a repeater
8899 as used in time stamps, for example `+3d'. To disable this,
8900 you can call the function with a universal prefix argument.
8902 When a valid repeater is given and the entry contains any time
8903 stamps, the clones will become a sequence in time, with time
8904 stamps in the subtree shifted for each clone produced. If SHIFT
8905 is nil or the empty string, time stamps will be left alone. The
8906 ID property of the original subtree is removed.
8908 In each clone, all the CLOCK entries will be removed. This
8909 prevents Org from considering that the clocked times overlap.
8911 If the original subtree did contain time stamps with a repeater,
8912 the following will happen:
8913 - the repeater will be removed in each clone
8914 - an additional clone will be produced, with the current, unshifted
8915 date(s) in the entry.
8916 - the original entry will be placed *after* all the clones, with
8917 repeater intact.
8918 - the start days in the repeater in the original entry will be shifted
8919 to past the last clone.
8920 In this way you can spell out a number of instances of a repeating task,
8921 and still retain the repeater to cover future instances of the task.
8923 As described above, N+1 clones are produced when the original
8924 subtree has a repeater. Setting N to 0, then, can be used to
8925 remove the repeater from a subtree and create a shifted clone
8926 with the original repeater."
8927 (interactive "nNumber of clones to produce: ")
8928 (let ((shift
8929 (or shift
8930 (if (and (not (equal current-prefix-arg '(4)))
8931 (save-excursion
8932 (re-search-forward org-ts-regexp-both
8933 (save-excursion
8934 (org-end-of-subtree t)
8935 (point)) t)))
8936 (read-from-minibuffer
8937 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8938 ""))) ;; No time shift
8939 (n-no-remove -1)
8940 (drawer-re org-drawer-regexp)
8941 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8942 beg end template task idprop
8943 shift-n shift-what doshift nmin nmax)
8944 (unless (wholenump n)
8945 (user-error "Invalid number of replications %s" n))
8946 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8947 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8948 shift)))
8949 (user-error "Invalid shift specification %s" shift))
8950 (when doshift
8951 (setq shift-n (string-to-number (match-string 1 shift))
8952 shift-what (cdr (assoc (match-string 2 shift)
8953 '(("d" . day) ("w" . week)
8954 ("m" . month) ("y" . year))))))
8955 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8956 (setq nmin 1 nmax n)
8957 (org-back-to-heading t)
8958 (setq beg (point))
8959 (setq idprop (org-entry-get nil "ID"))
8960 (org-end-of-subtree t t)
8961 (or (bolp) (insert "\n"))
8962 (setq end (point))
8963 (setq template (buffer-substring beg end))
8964 (when (and doshift
8965 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8966 (delete-region beg end)
8967 (setq end beg)
8968 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8969 (goto-char end)
8970 (cl-loop for n from nmin to nmax do
8971 ;; prepare clone
8972 (with-temp-buffer
8973 (insert template)
8974 (org-mode)
8975 (goto-char (point-min))
8976 (org-show-subtree)
8977 (and idprop (if org-clone-delete-id
8978 (org-entry-delete nil "ID")
8979 (org-id-get-create t)))
8980 (unless (= n 0)
8981 (while (re-search-forward org-clock-re nil t)
8982 (kill-whole-line))
8983 (goto-char (point-min))
8984 (while (re-search-forward drawer-re nil t)
8985 (org-remove-empty-drawer-at (point))))
8986 (goto-char (point-min))
8987 (when doshift
8988 (while (re-search-forward org-ts-regexp-both nil t)
8989 (org-timestamp-change (* n shift-n) shift-what))
8990 (unless (= n n-no-remove)
8991 (goto-char (point-min))
8992 (while (re-search-forward org-ts-regexp nil t)
8993 (save-excursion
8994 (goto-char (match-beginning 0))
8995 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8996 (delete-region (match-beginning 1) (match-end 1)))))))
8997 (setq task (buffer-string)))
8998 (insert task))
8999 (goto-char beg)))
9001 ;;; Outline Sorting
9003 (defun org-sort (with-case)
9004 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9005 Optional argument WITH-CASE means sort case-sensitively."
9006 (interactive "P")
9007 (cond
9008 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9009 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9011 (org-call-with-arg 'org-sort-entries with-case))))
9013 (defun org-sort-remove-invisible (s)
9014 "Remove invisible links from string S."
9015 (remove-text-properties 0 (length s) org-rm-props s)
9016 (while (string-match org-bracket-link-regexp s)
9017 (setq s (replace-match (if (match-end 2)
9018 (match-string 3 s)
9019 (match-string 1 s))
9020 t t s)))
9021 (let ((st (format " %s " s)))
9022 (while (string-match org-emph-re st)
9023 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9024 (setq s (substring st 1 -1)))
9027 (defvar org-priority-regexp) ; defined later in the file
9029 (defvar org-after-sorting-entries-or-items-hook nil
9030 "Hook that is run after a bunch of entries or items have been sorted.
9031 When children are sorted, the cursor is in the parent line when this
9032 hook gets called. When a region or a plain list is sorted, the cursor
9033 will be in the first entry of the sorted region/list.")
9035 (defun org-sort-entries
9036 (&optional with-case sorting-type getkey-func compare-func property)
9037 "Sort entries on a certain level of an outline tree.
9038 If there is an active region, the entries in the region are sorted.
9039 Else, if the cursor is before the first entry, sort the top-level items.
9040 Else, the children of the entry at point are sorted.
9042 Sorting can be alphabetically, numerically, by date/time as given by
9043 a time stamp, by a property, by priority order, or by a custom function.
9045 The command prompts for the sorting type unless it has been given to the
9046 function through the SORTING-TYPE argument, which needs to be a character,
9047 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9048 the precise meaning of each character:
9050 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9051 c By creation time, which is assumed to be the first inactive time stamp
9052 at the beginning of a line.
9053 d By deadline date/time.
9054 k By clocking time.
9055 n Numerically, by converting the beginning of the entry/item to a number.
9056 o By order of TODO keywords.
9057 p By priority according to the cookie.
9058 r By the value of a property.
9059 s By scheduled date/time.
9060 t By date/time, either the first active time stamp in the entry, or, if
9061 none exist, by the first inactive one.
9063 Capital letters will reverse the sort order.
9065 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9066 called with point at the beginning of the record. It must return either
9067 a string or a number that should serve as the sorting key for that record.
9069 Comparing entries ignores case by default. However, with an optional argument
9070 WITH-CASE, the sorting considers case as well.
9072 Sorting is done against the visible part of the headlines, it ignores hidden
9073 links.
9075 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9076 (interactive "P")
9077 (let ((case-func (if with-case 'identity 'downcase))
9078 (cmstr
9079 ;; The clock marker is lost when using `sort-subr', let's
9080 ;; store the clocking string.
9081 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9082 (save-excursion
9083 (goto-char org-clock-marker)
9084 (buffer-substring-no-properties (line-beginning-position)
9085 (point)))))
9086 start beg end stars re re2
9087 txt what tmp)
9088 ;; Find beginning and end of region to sort
9089 (cond
9090 ((org-region-active-p)
9091 ;; we will sort the region
9092 (setq end (region-end)
9093 what "region")
9094 (goto-char (region-beginning))
9095 (unless (org-at-heading-p) (outline-next-heading))
9096 (setq start (point)))
9097 ((or (org-at-heading-p)
9098 (ignore-errors (progn (org-back-to-heading) t)))
9099 ;; we will sort the children of the current headline
9100 (org-back-to-heading)
9101 (setq start (point)
9102 end (progn (org-end-of-subtree t t)
9103 (or (bolp) (insert "\n"))
9104 (when (>= (org-back-over-empty-lines) 1)
9105 (forward-line 1))
9106 (point))
9107 what "children")
9108 (goto-char start)
9109 (outline-show-subtree)
9110 (outline-next-heading))
9112 ;; we will sort the top-level entries in this file
9113 (goto-char (point-min))
9114 (or (org-at-heading-p) (outline-next-heading))
9115 (setq start (point))
9116 (goto-char (point-max))
9117 (beginning-of-line 1)
9118 (when (looking-at ".*?\\S-")
9119 ;; File ends in a non-white line
9120 (end-of-line 1)
9121 (insert "\n"))
9122 (setq end (point-max))
9123 (setq what "top-level")
9124 (goto-char start)
9125 (outline-show-all)))
9127 (setq beg (point))
9128 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9130 (looking-at "\\(\\*+\\)")
9131 (setq stars (match-string 1)
9132 re (concat "^" (regexp-quote stars) " +")
9133 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9134 txt (buffer-substring beg end))
9135 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9136 (when (and (not (equal stars "*")) (string-match re2 txt))
9137 (user-error "Region to sort contains a level above the first entry"))
9139 (unless sorting-type
9140 (message
9141 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9142 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9143 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9144 what)
9145 (setq sorting-type (read-char-exclusive))
9147 (unless getkey-func
9148 (and (= (downcase sorting-type) ?f)
9149 (setq getkey-func
9150 (completing-read "Sort using function: "
9151 obarray 'fboundp t nil nil))
9152 (setq getkey-func (intern getkey-func))))
9154 (and (= (downcase sorting-type) ?r)
9155 (not property)
9156 (setq property
9157 (completing-read "Property: "
9158 (mapcar #'list (org-buffer-property-keys t))
9159 nil t))))
9161 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9162 (message "Sorting entries...")
9164 (save-restriction
9165 (narrow-to-region start end)
9166 (let ((dcst (downcase sorting-type))
9167 (case-fold-search nil)
9168 (now (current-time)))
9169 (sort-subr
9170 (/= dcst sorting-type)
9171 ;; This function moves to the beginning character of the "record" to
9172 ;; be sorted.
9173 (lambda nil
9174 (if (re-search-forward re nil t)
9175 (goto-char (match-beginning 0))
9176 (goto-char (point-max))))
9177 ;; This function moves to the last character of the "record" being
9178 ;; sorted.
9179 (lambda nil
9180 (save-match-data
9181 (condition-case nil
9182 (outline-forward-same-level 1)
9183 (error
9184 (goto-char (point-max))))))
9185 ;; This function returns the value that gets sorted against.
9186 (lambda nil
9187 (cond
9188 ((= dcst ?n)
9189 (if (looking-at org-complex-heading-regexp)
9190 (string-to-number (org-sort-remove-invisible (match-string 4)))
9191 nil))
9192 ((= dcst ?a)
9193 (if (looking-at org-complex-heading-regexp)
9194 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9195 nil))
9196 ((= dcst ?k)
9197 (or (get-text-property (point) :org-clock-minutes) 0))
9198 ((= dcst ?t)
9199 (let ((end (save-excursion (outline-next-heading) (point))))
9200 (if (or (re-search-forward org-ts-regexp end t)
9201 (re-search-forward org-ts-regexp-both end t))
9202 (org-time-string-to-seconds (match-string 0))
9203 (float-time now))))
9204 ((= dcst ?c)
9205 (let ((end (save-excursion (outline-next-heading) (point))))
9206 (if (re-search-forward
9207 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9208 end t)
9209 (org-time-string-to-seconds (match-string 0))
9210 (float-time now))))
9211 ((= dcst ?s)
9212 (let ((end (save-excursion (outline-next-heading) (point))))
9213 (if (re-search-forward org-scheduled-time-regexp end t)
9214 (org-time-string-to-seconds (match-string 1))
9215 (float-time now))))
9216 ((= dcst ?d)
9217 (let ((end (save-excursion (outline-next-heading) (point))))
9218 (if (re-search-forward org-deadline-time-regexp end t)
9219 (org-time-string-to-seconds (match-string 1))
9220 (float-time now))))
9221 ((= dcst ?p)
9222 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9223 (string-to-char (match-string 2))
9224 org-default-priority))
9225 ((= dcst ?r)
9226 (or (org-entry-get nil property) ""))
9227 ((= dcst ?o)
9228 (when (looking-at org-complex-heading-regexp)
9229 (let* ((m (match-string 2))
9230 (s (if (member m org-done-keywords) '- '+)))
9231 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9232 ((= dcst ?f)
9233 (if getkey-func
9234 (progn
9235 (setq tmp (funcall getkey-func))
9236 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9237 tmp)
9238 (error "Invalid key function `%s'" getkey-func)))
9239 (t (error "Invalid sorting type `%c'" sorting-type))))
9241 (cond
9242 ((= dcst ?a) 'string<)
9243 ((= dcst ?f) compare-func)
9244 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9245 (run-hooks 'org-after-sorting-entries-or-items-hook)
9246 ;; Reset the clock marker if needed
9247 (when cmstr
9248 (save-excursion
9249 (goto-char start)
9250 (search-forward cmstr nil t)
9251 (move-marker org-clock-marker (point))))
9252 (message "Sorting entries...done")))
9254 ;;; The orgstruct minor mode
9256 ;; Define a minor mode which can be used in other modes in order to
9257 ;; integrate the Org mode structure editing commands.
9259 ;; This is really a hack, because the Org mode structure commands use
9260 ;; keys which normally belong to the major mode. Here is how it
9261 ;; works: The minor mode defines all the keys necessary to operate the
9262 ;; structure commands, but wraps the commands into a function which
9263 ;; tests if the cursor is currently at a headline or a plain list
9264 ;; item. If that is the case, the structure command is used,
9265 ;; temporarily setting many Org mode variables like regular
9266 ;; expressions for filling etc. However, when any of those keys is
9267 ;; used at a different location, function uses `key-binding' to look
9268 ;; up if the key has an associated command in another currently active
9269 ;; keymap (minor modes, major mode, global), and executes that
9270 ;; command. There might be problems if any of the keys is otherwise
9271 ;; used as a prefix key.
9273 (defcustom orgstruct-heading-prefix-regexp ""
9274 "Regexp that matches the custom prefix of Org headlines in
9275 orgstruct(++)-mode."
9276 :group 'org
9277 :version "24.4"
9278 :package-version '(Org . "8.3")
9279 :type 'regexp)
9280 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9282 (defcustom orgstruct-setup-hook nil
9283 "Hook run after orgstruct-mode-map is filled."
9284 :group 'org
9285 :version "24.4"
9286 :package-version '(Org . "8.0")
9287 :type 'hook)
9289 (defvar orgstruct-initialized nil)
9291 (defvar org-local-vars nil
9292 "List of local variables, for use by `orgstruct-mode'.")
9294 ;;;###autoload
9295 (define-minor-mode orgstruct-mode
9296 "Toggle the minor mode `orgstruct-mode'.
9297 This mode is for using Org mode structure commands in other
9298 modes. The following keys behave as if Org mode were active, if
9299 the cursor is on a headline, or on a plain list item (both as
9300 defined by Org-mode)."
9301 nil " OrgStruct" (make-sparse-keymap)
9302 (funcall (if orgstruct-mode
9303 'add-to-invisibility-spec
9304 'remove-from-invisibility-spec)
9305 '(outline . t))
9306 (when orgstruct-mode
9307 (org-load-modules-maybe)
9308 (unless orgstruct-initialized
9309 (orgstruct-setup)
9310 (setq orgstruct-initialized t))))
9312 ;;;###autoload
9313 (defun turn-on-orgstruct ()
9314 "Unconditionally turn on `orgstruct-mode'."
9315 (orgstruct-mode 1))
9317 (defvar-local orgstruct-is-++ nil
9318 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9319 (defvar-local org-fb-vars nil)
9320 (defun orgstruct++-mode (&optional arg)
9321 "Toggle `orgstruct-mode', the enhanced version of it.
9322 In addition to setting orgstruct-mode, this also exports all
9323 indentation and autofilling variables from Org mode into the
9324 buffer. It will also recognize item context in multiline items."
9325 (interactive "P")
9326 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9327 (if (< arg 1)
9328 (progn (orgstruct-mode -1)
9329 (dolist (v org-fb-vars)
9330 (set (make-local-variable (car v))
9331 (if (eq (car-safe (cadr v)) 'quote)
9332 (cl-cadadr v)
9333 (nth 1 v)))))
9334 (orgstruct-mode 1)
9335 (setq org-fb-vars nil)
9336 (unless org-local-vars
9337 (setq org-local-vars (org-get-local-variables)))
9338 (let (var val)
9339 (dolist (x org-local-vars)
9340 (when (string-match
9341 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9342 \\|fill-prefix\\|indent-\\)"
9343 (symbol-name (car x)))
9344 (setq var (car x) val (nth 1 x))
9345 (push (list var `(quote ,(eval var))) org-fb-vars)
9346 (set (make-local-variable var)
9347 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9348 (setq-local orgstruct-is-++ t))))
9350 ;;;###autoload
9351 (defun turn-on-orgstruct++ ()
9352 "Unconditionally turn on `orgstruct++-mode'."
9353 (orgstruct++-mode 1))
9355 (defun orgstruct-error ()
9356 "Error when there is no default binding for a structure key."
9357 (interactive)
9358 (funcall (if (fboundp 'user-error)
9359 'user-error
9360 'error)
9361 "This key has no function outside structure elements"))
9363 (defun orgstruct-setup ()
9364 "Setup orgstruct keymap."
9365 (dolist (cell '((org-demote . t)
9366 (org-metaleft . t)
9367 (org-metaright . t)
9368 (org-promote . t)
9369 (org-shiftmetaleft . t)
9370 (org-shiftmetaright . t)
9371 org-backward-element
9372 org-backward-heading-same-level
9373 org-ctrl-c-ret
9374 org-ctrl-c-minus
9375 org-ctrl-c-star
9376 org-cycle
9377 org-force-cycle-archived
9378 org-forward-heading-same-level
9379 org-insert-heading
9380 org-insert-heading-respect-content
9381 org-kill-note-or-show-branches
9382 org-mark-subtree
9383 org-meta-return
9384 org-metadown
9385 org-metaup
9386 org-narrow-to-subtree
9387 org-promote-subtree
9388 org-reveal
9389 org-shiftdown
9390 org-shiftleft
9391 org-shiftmetadown
9392 org-shiftmetaup
9393 org-shiftright
9394 org-shifttab
9395 org-shifttab
9396 org-shiftup
9397 org-show-children
9398 org-show-subtree
9399 org-sort
9400 org-up-element
9401 outline-demote
9402 outline-next-visible-heading
9403 outline-previous-visible-heading
9404 outline-promote
9405 outline-up-heading))
9406 (let ((f (or (car-safe cell) cell))
9407 (disable-when-heading-prefix (cdr-safe cell)))
9408 (when (fboundp f)
9409 (let ((new-bindings))
9410 (dolist (binding (nconc (where-is-internal f org-mode-map)
9411 (where-is-internal f outline-mode-map)))
9412 (push binding new-bindings)
9413 ;; TODO use local-function-key-map
9414 (dolist (rep '(("<tab>" . "TAB")
9415 ("<return>" . "RET")
9416 ("<escape>" . "ESC")
9417 ("<delete>" . "DEL")))
9418 (setq binding (read-kbd-macro
9419 (let ((case-fold-search))
9420 (replace-regexp-in-string
9421 (regexp-quote (cdr rep))
9422 (car rep)
9423 (key-description binding)))))
9424 (cl-pushnew binding new-bindings :test 'equal)))
9425 (dolist (binding new-bindings)
9426 (let ((key (lookup-key orgstruct-mode-map binding)))
9427 (when (or (not key) (numberp key))
9428 (ignore-errors
9429 (org-defkey orgstruct-mode-map
9430 binding
9431 (orgstruct-make-binding
9432 f binding disable-when-heading-prefix))))))))))
9433 (run-hooks 'orgstruct-setup-hook))
9435 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9436 "Create a function for binding in the structure minor mode.
9437 FUN is the command to call inside a table. KEY is the key that
9438 should be checked in for a command to execute outside of tables.
9439 Non-nil `disable-when-heading-prefix' means to disable the command
9440 if `orgstruct-heading-prefix-regexp' is not empty."
9441 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9442 (let ((nname name)
9443 (i 0))
9444 (while (fboundp (intern nname))
9445 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9446 (setq name (intern nname)))
9447 (eval
9448 (let ((bindings '((org-heading-regexp
9449 (concat "^"
9450 orgstruct-heading-prefix-regexp
9451 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9452 (org-outline-regexp
9453 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9454 (org-outline-regexp-bol
9455 (concat "^" org-outline-regexp))
9456 (outline-regexp org-outline-regexp)
9457 (outline-heading-end-regexp "\n")
9458 (outline-level 'org-outline-level)
9459 (outline-heading-alist))))
9460 `(defun ,name (arg)
9461 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9462 "Outside of structure, run the binding of `"
9463 (key-description key) "'."
9464 (when disable-when-heading-prefix
9465 (concat
9466 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9467 "back to the default binding due to limitations of Org's implementation of\n"
9468 "`" (symbol-name fun) "'.")))
9469 (interactive "p")
9470 (let* ((disable
9471 ,(and disable-when-heading-prefix
9472 '(not (string= orgstruct-heading-prefix-regexp ""))))
9473 (fallback
9474 (or disable
9475 (not
9476 (let* ,bindings
9477 (org-context-p 'headline 'item
9478 ,(when (memq fun
9479 '(org-insert-heading
9480 org-insert-heading-respect-content
9481 org-meta-return))
9482 '(when orgstruct-is-++
9483 'item-body))))))))
9484 (if fallback
9485 (let* ((orgstruct-mode)
9486 (binding
9487 (let ((key ,key))
9488 (catch 'exit
9489 (dolist
9490 (rep
9491 '(nil
9492 ("<\\([^>]*\\)tab>" . "\\1TAB")
9493 ("<\\([^>]*\\)return>" . "\\1RET")
9494 ("<\\([^>]*\\)escape>" . "\\1ESC")
9495 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9496 nil)
9497 (when rep
9498 (setq key (read-kbd-macro
9499 (let ((case-fold-search))
9500 (replace-regexp-in-string
9501 (car rep)
9502 (cdr rep)
9503 (key-description key))))))
9504 (when (key-binding key)
9505 (throw 'exit (key-binding key))))))))
9506 (if (keymapp binding)
9507 (org-set-transient-map binding)
9508 (let ((func (or binding
9509 (unless disable
9510 'orgstruct-error))))
9511 (when func
9512 (call-interactively func)))))
9513 (org-run-like-in-org-mode
9514 (lambda ()
9515 (interactive)
9516 (let* ,bindings
9517 (call-interactively ',fun)))))))))
9518 name))
9520 (defun org-contextualize-keys (alist contexts)
9521 "Return valid elements in ALIST depending on CONTEXTS.
9523 `org-agenda-custom-commands' or `org-capture-templates' are the
9524 values used for ALIST, and `org-agenda-custom-commands-contexts'
9525 or `org-capture-templates-contexts' are the associated contexts
9526 definitions."
9527 (let ((contexts
9528 ;; normalize contexts
9529 (mapcar
9530 (lambda(c) (cond ((listp (cadr c))
9531 (list (car c) (car c) (nth 1 c)))
9532 ((string= "" (cadr c))
9533 (list (car c) (car c) (nth 2 c)))
9534 (t c)))
9535 contexts))
9536 (a alist) r s)
9537 ;; loop over all commands or templates
9538 (dolist (c a)
9539 (let (vrules repl)
9540 (cond
9541 ((not (assoc (car c) contexts))
9542 (push c r))
9543 ((and (assoc (car c) contexts)
9544 (setq vrules (org-contextualize-validate-key
9545 (car c) contexts)))
9546 (mapc (lambda (vr)
9547 (unless (equal (car vr) (cadr vr))
9548 (setq repl vr)))
9549 vrules)
9550 (if (not repl) (push c r)
9551 (push (cadr repl) s)
9552 (push
9553 (cons (car c)
9554 (cdr (or (assoc (cadr repl) alist)
9555 (error "Undefined key `%s' as contextual replacement for `%s'"
9556 (cadr repl) (car c)))))
9557 r))))))
9558 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9559 (delq
9561 (delete-dups
9562 (mapcar (lambda (x)
9563 (let ((tpl (car x)))
9564 (unless (delq
9566 (mapcar (lambda (y)
9567 (equal y tpl))
9569 x)))
9570 (reverse r))))))
9572 (defun org-contextualize-validate-key (key contexts)
9573 "Check CONTEXTS for agenda or capture KEY."
9574 (let (res)
9575 (dolist (r contexts)
9576 (dolist (rr (car (last r)))
9577 (when
9578 (and (equal key (car r))
9579 (if (functionp rr) (funcall rr)
9580 (or (and (eq (car rr) 'in-file)
9581 (buffer-file-name)
9582 (string-match (cdr rr) (buffer-file-name)))
9583 (and (eq (car rr) 'in-mode)
9584 (string-match (cdr rr) (symbol-name major-mode)))
9585 (and (eq (car rr) 'in-buffer)
9586 (string-match (cdr rr) (buffer-name)))
9587 (when (and (eq (car rr) 'not-in-file)
9588 (buffer-file-name))
9589 (not (string-match (cdr rr) (buffer-file-name))))
9590 (when (eq (car rr) 'not-in-mode)
9591 (not (string-match (cdr rr) (symbol-name major-mode))))
9592 (when (eq (car rr) 'not-in-buffer)
9593 (not (string-match (cdr rr) (buffer-name)))))))
9594 (push r res))))
9595 (delete-dups (delq nil res))))
9597 (defun org-context-p (&rest contexts)
9598 "Check if local context is any of CONTEXTS.
9599 Possible values in the list of contexts are `table', `headline', and `item'."
9600 (let ((pos (point)))
9601 (goto-char (point-at-bol))
9602 (prog1 (or (and (memq 'table contexts)
9603 (looking-at "[ \t]*|"))
9604 (and (memq 'headline contexts)
9605 (looking-at org-outline-regexp))
9606 (and (memq 'item contexts)
9607 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9608 (and (memq 'item-body contexts)
9609 (org-in-item-p)))
9610 (goto-char pos))))
9612 (defconst org-unique-local-variables
9613 '(org-element--cache
9614 org-element--cache-objects
9615 org-element--cache-sync-keys
9616 org-element--cache-sync-requests
9617 org-element--cache-sync-timer)
9618 "List of local variables that cannot be transferred to another buffer.")
9620 (defun org-get-local-variables ()
9621 "Return a list of all local variables in an Org mode buffer."
9622 (delq nil
9623 (mapcar
9624 (lambda (x)
9625 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9626 (name (car binding)))
9627 (and (not (get name 'org-state))
9628 (not (memq name org-unique-local-variables))
9629 (string-match-p
9630 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9631 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9632 (symbol-name name))
9633 binding)))
9634 (with-temp-buffer
9635 (org-mode)
9636 (buffer-local-variables)))))
9638 (defun org-clone-local-variables (from-buffer &optional regexp)
9639 "Clone local variables from FROM-BUFFER.
9640 Optional argument REGEXP selects variables to clone."
9641 (dolist (pair (buffer-local-variables from-buffer))
9642 (let ((name (car pair)))
9643 (when (and (symbolp name)
9644 (not (memq name org-unique-local-variables))
9645 (or (null regexp) (string-match regexp (symbol-name name))))
9646 (set (make-local-variable name) (cdr pair))))))
9648 ;;;###autoload
9649 (defun org-run-like-in-org-mode (cmd)
9650 "Run a command, pretending that the current buffer is in Org-mode.
9651 This will temporarily bind local variables that are typically bound in
9652 Org mode to the values they have in Org-mode, and then interactively
9653 call CMD."
9654 (org-load-modules-maybe)
9655 (unless org-local-vars
9656 (setq org-local-vars (org-get-local-variables)))
9657 (let (binds)
9658 (dolist (var org-local-vars)
9659 (when (or (not (boundp (car var)))
9660 (eq (symbol-value (car var))
9661 (default-value (car var))))
9662 (push (list (car var) `(quote ,(cadr var))) binds)))
9663 (eval `(let ,binds
9664 (call-interactively (quote ,cmd))))))
9666 (defun org-get-category (&optional pos force-refresh)
9667 "Get the category applying to position POS."
9668 (save-match-data
9669 (when force-refresh (org-refresh-category-properties))
9670 (let ((pos (or pos (point))))
9671 (or (get-text-property pos 'org-category)
9672 (progn (org-refresh-category-properties)
9673 (get-text-property pos 'org-category))))))
9675 ;;; Refresh properties
9677 (defun org-refresh-properties (dprop tprop)
9678 "Refresh buffer text properties.
9679 DPROP is the drawer property and TPROP is either the
9680 corresponding text property to set, or an alist with each element
9681 being a text property (as a symbol) and a function to apply to
9682 the value of the drawer property."
9683 (let ((case-fold-search t)
9684 (inhibit-read-only t))
9685 (org-with-silent-modifications
9686 (org-with-wide-buffer
9687 (goto-char (point-min))
9688 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9689 (org-refresh-property tprop (match-string-no-properties 1)))))))
9691 (defun org-refresh-property (tprop p)
9692 "Refresh the buffer text property TPROP from the drawer property P.
9693 The refresh happens only for the current tree (not subtree)."
9694 (unless (org-before-first-heading-p)
9695 (save-excursion
9696 (org-back-to-heading t)
9697 (if (symbolp tprop)
9698 ;; TPROP is a text property symbol
9699 (put-text-property
9700 (point) (or (outline-next-heading) (point-max)) tprop p)
9701 ;; TPROP is an alist with (properties . function) elements
9702 (dolist (al tprop)
9703 (save-excursion
9704 (put-text-property
9705 (line-beginning-position) (or (outline-next-heading) (point-max))
9706 (car al)
9707 (funcall (cdr al) p))))))))
9709 (defun org-refresh-category-properties ()
9710 "Refresh category text properties in the buffer."
9711 (let ((case-fold-search t)
9712 (inhibit-read-only t)
9713 (default-category
9714 (cond ((null org-category)
9715 (if buffer-file-name
9716 (file-name-sans-extension
9717 (file-name-nondirectory buffer-file-name))
9718 "???"))
9719 ((symbolp org-category) (symbol-name org-category))
9720 (t org-category))))
9721 (org-with-silent-modifications
9722 (org-with-wide-buffer
9723 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9724 ;; This is the default category for the buffer. If none is
9725 ;; found, fall-back to `org-category' or buffer file name.
9726 (put-text-property
9727 (point-min) (point-max)
9728 'org-category
9729 (catch 'buffer-category
9730 (goto-char (point-max))
9731 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9732 (let ((element (org-element-at-point)))
9733 (when (eq (org-element-type element) 'keyword)
9734 (throw 'buffer-category
9735 (org-element-property :value element)))))
9736 default-category))
9737 ;; Set sub-tree specific categories.
9738 (goto-char (point-min))
9739 (let ((regexp (org-re-property "CATEGORY")))
9740 (while (re-search-forward regexp nil t)
9741 (let ((value (match-string-no-properties 3)))
9742 (when (org-at-property-p)
9743 (put-text-property
9744 (save-excursion (org-back-to-heading t) (point))
9745 (save-excursion (org-end-of-subtree t t) (point))
9746 'org-category
9747 value)))))))))
9749 (defun org-refresh-stats-properties ()
9750 "Refresh stats text properties in the buffer."
9751 (let (stats)
9752 (org-with-silent-modifications
9753 (org-with-wide-buffer
9754 (goto-char (point-min))
9755 (while (re-search-forward
9756 (concat org-outline-regexp-bol ".*"
9757 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9758 nil t)
9759 (setq stats (cond ((equal (match-string 3) "0") 0)
9760 ((match-string 2)
9761 (/ (* (string-to-number (match-string 2)) 100)
9762 (string-to-number (match-string 3))))
9763 (t (string-to-number (match-string 1)))))
9764 (org-back-to-heading t)
9765 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9766 'org-stats stats))))))
9768 (defun org-refresh-effort-properties ()
9769 "Refresh effort properties"
9770 (org-refresh-properties
9771 org-effort-property
9772 '((effort . identity)
9773 (effort-minutes . org-duration-string-to-minutes))))
9775 ;;;; Link Stuff
9777 ;;; Link abbreviations
9779 (defun org-link-expand-abbrev (link)
9780 "Apply replacements as defined in `org-link-abbrev-alist'."
9781 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9782 (let* ((key (match-string 1 link))
9783 (as (or (assoc key org-link-abbrev-alist-local)
9784 (assoc key org-link-abbrev-alist)))
9785 (tag (and (match-end 2) (match-string 3 link)))
9786 rpl)
9787 (if (not as)
9788 link
9789 (setq rpl (cdr as))
9790 (cond
9791 ((symbolp rpl) (funcall rpl tag))
9792 ((string-match "%(\\([^)]+\\))" rpl)
9793 (replace-match
9794 (save-match-data
9795 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9796 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9797 ((string-match "%h" rpl)
9798 (replace-match (url-hexify-string (or tag "")) t t rpl))
9799 (t (concat rpl tag)))))
9800 link))
9802 ;;; Storing and inserting links
9804 (defvar org-insert-link-history nil
9805 "Minibuffer history for links inserted with `org-insert-link'.")
9807 (defvar org-stored-links nil
9808 "Contains the links stored with `org-store-link'.")
9810 (defvar org-store-link-plist nil
9811 "Plist with info about the most recently link created with `org-store-link'.")
9813 (defun org-store-link-functions ()
9814 "Return a list of functions that are called to create and store a link.
9815 The functions defined in the :store property of
9816 `org-link-parameters'.
9818 Each function will be called in turn until one returns a non-nil
9819 value. Each function should check if it is responsible for
9820 creating this link (for example by looking at the major mode).
9821 If not, it must exit and return nil. If yes, it should return
9822 a non-nil value after calling `org-store-link-props' with a list
9823 of properties and values. Special properties are:
9825 :type The link prefix, like \"http\". This must be given.
9826 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9827 This is obligatory as well.
9828 :description Optional default description for the second pair
9829 of brackets in an Org mode link. The user can still change
9830 this when inserting this link into an Org mode buffer.
9832 In addition to these, any additional properties can be specified
9833 and then used in capture templates."
9834 (cl-loop for link in org-link-parameters
9835 with store-func
9836 do (setq store-func (org-link-get-parameter (car link) :store))
9837 if store-func
9838 collect store-func))
9840 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9841 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9843 ;;;###autoload
9844 (defun org-store-link (arg)
9845 "\\<org-mode-map>Store an org-link to the current location.
9846 This link is added to `org-stored-links' and can later be inserted
9847 into an Org buffer with \\[org-insert-link].
9849 For some link types, a prefix ARG is interpreted.
9850 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9851 For file links, ARG negates `org-context-in-file-links'.
9853 A double prefix ARG force skipping storing functions that are not
9854 part of Org's core.
9856 A triple prefix ARG force storing a link for each line in the
9857 active region."
9858 (interactive "P")
9859 (org-load-modules-maybe)
9860 (if (and (equal arg '(64)) (org-region-active-p))
9861 (save-excursion
9862 (let ((end (region-end)))
9863 (goto-char (region-beginning))
9864 (set-mark (point))
9865 (while (< (point-at-eol) end)
9866 (move-end-of-line 1) (activate-mark)
9867 (let (current-prefix-arg)
9868 (call-interactively 'org-store-link))
9869 (move-beginning-of-line 2)
9870 (set-mark (point)))))
9871 (setq org-store-link-plist nil)
9872 (let (link cpltxt desc description search
9873 txt custom-id agenda-link sfuns sfunsn)
9874 (cond
9876 ;; Store a link using an external link type
9877 ((and (not (equal arg '(16)))
9878 (setq sfuns
9879 (delq
9880 nil (mapcar (lambda (f)
9881 (let (fs) (if (funcall f) (push f fs))))
9882 (org-store-link-functions)))
9883 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9884 (or (and (cdr sfuns)
9885 (funcall (intern
9886 (completing-read
9887 "Which function for creating the link? "
9888 sfunsn nil t (car sfunsn)))))
9889 (funcall (caar sfuns)))
9890 (setq link (plist-get org-store-link-plist :link)
9891 desc (or (plist-get org-store-link-plist
9892 :description)
9893 link))))
9895 ;; Store a link from a source code buffer.
9896 ((org-src-edit-buffer-p)
9897 (let ((coderef-format (org-src-coderef-format)))
9898 (cond ((save-excursion
9899 (beginning-of-line)
9900 (looking-at (org-src-coderef-regexp coderef-format)))
9901 (setq link (format "(%s)" (match-string-no-properties 3))))
9902 ((called-interactively-p 'any)
9903 (let ((label (read-string "Code line label: ")))
9904 (end-of-line)
9905 (setq link (format coderef-format label))
9906 (let ((gc (- 79 (length link))))
9907 (if (< (current-column) gc)
9908 (org-move-to-column gc t)
9909 (insert " ")))
9910 (insert link)
9911 (setq link (concat "(" label ")"))
9912 (setq desc nil)))
9913 (t (setq link nil)))))
9915 ;; We are in the agenda, link to referenced location
9916 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9917 (let ((m (or (get-text-property (point) 'org-hd-marker)
9918 (get-text-property (point) 'org-marker))))
9919 (when m
9920 (org-with-point-at m
9921 (setq agenda-link
9922 (if (called-interactively-p 'any)
9923 (call-interactively 'org-store-link)
9924 (org-store-link nil)))))))
9926 ((eq major-mode 'calendar-mode)
9927 (let ((cd (calendar-cursor-to-date)))
9928 (setq link
9929 (format-time-string
9930 (car org-time-stamp-formats)
9931 (apply 'encode-time
9932 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9933 nil nil nil))))
9934 (org-store-link-props :type "calendar" :date cd)))
9936 ((eq major-mode 'help-mode)
9937 (setq link (concat "help:" (save-excursion
9938 (goto-char (point-min))
9939 (looking-at "^[^ ]+")
9940 (match-string 0))))
9941 (org-store-link-props :type "help"))
9943 ((eq major-mode 'w3-mode)
9944 (setq cpltxt (if (and (buffer-name)
9945 (not (string-match "Untitled" (buffer-name))))
9946 (buffer-name)
9947 (url-view-url t))
9948 link (url-view-url t))
9949 (org-store-link-props :type "w3" :url (url-view-url t)))
9951 ((eq major-mode 'image-mode)
9952 (setq cpltxt (concat "file:"
9953 (abbreviate-file-name buffer-file-name))
9954 link cpltxt)
9955 (org-store-link-props :type "image" :file buffer-file-name))
9957 ;; In dired, store a link to the file of the current line
9958 ((derived-mode-p 'dired-mode)
9959 (let ((file (dired-get-filename nil t)))
9960 (setq file (if file
9961 (abbreviate-file-name
9962 (expand-file-name (dired-get-filename nil t)))
9963 ;; otherwise, no file so use current directory.
9964 default-directory))
9965 (setq cpltxt (concat "file:" file)
9966 link cpltxt)))
9968 ((setq search (run-hook-with-args-until-success
9969 'org-create-file-search-functions))
9970 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9971 "::" search))
9972 (setq cpltxt (or description link)))
9974 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9975 (org-with-limited-levels
9976 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9977 (cond
9978 ;; Store a link using the target at point
9979 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9980 (setq cpltxt
9981 (concat "file:"
9982 (abbreviate-file-name
9983 (buffer-file-name (buffer-base-buffer)))
9984 "::" (match-string 1))
9985 link cpltxt))
9986 ((and (featurep 'org-id)
9987 (or (eq org-id-link-to-org-use-id t)
9988 (and (called-interactively-p 'any)
9989 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9990 (and (eq org-id-link-to-org-use-id
9991 'create-if-interactive-and-no-custom-id)
9992 (not custom-id))))
9993 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9994 ;; Store a link using the ID at point
9995 (setq link (condition-case nil
9996 (prog1 (org-id-store-link)
9997 (setq desc (or (plist-get org-store-link-plist
9998 :description)
9999 "")))
10000 (error
10001 ;; Probably before first headline, link only to file
10002 (concat "file:"
10003 (abbreviate-file-name
10004 (buffer-file-name (buffer-base-buffer))))))))
10006 ;; Just link to current headline
10007 (setq cpltxt (concat "file:"
10008 (abbreviate-file-name
10009 (buffer-file-name (buffer-base-buffer)))))
10010 ;; Add a context search string
10011 (when (org-xor org-context-in-file-links arg)
10012 (let* ((element (org-element-at-point))
10013 (name (org-element-property :name element)))
10014 (setq txt (cond
10015 ((org-at-heading-p) nil)
10016 (name)
10017 ((org-region-active-p)
10018 (buffer-substring (region-beginning) (region-end)))))
10019 (when (or (null txt) (string-match "\\S-" txt))
10020 (setq cpltxt
10021 (concat cpltxt "::"
10022 (condition-case nil
10023 (org-make-org-heading-search-string txt)
10024 (error "")))
10025 desc (or name
10026 (nth 4 (ignore-errors (org-heading-components)))
10027 "NONE")))))
10028 (when (string-match "::\\'" cpltxt)
10029 (setq cpltxt (substring cpltxt 0 -2)))
10030 (setq link cpltxt)))))
10032 ((buffer-file-name (buffer-base-buffer))
10033 ;; Just link to this file here.
10034 (setq cpltxt (concat "file:"
10035 (abbreviate-file-name
10036 (buffer-file-name (buffer-base-buffer)))))
10037 ;; Add a context string.
10038 (when (org-xor org-context-in-file-links arg)
10039 (setq txt (if (org-region-active-p)
10040 (buffer-substring (region-beginning) (region-end))
10041 (buffer-substring (point-at-bol) (point-at-eol))))
10042 ;; Only use search option if there is some text.
10043 (when (string-match "\\S-" txt)
10044 (setq cpltxt
10045 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10046 desc "NONE")))
10047 (setq link cpltxt))
10049 ((called-interactively-p 'interactive)
10050 (user-error "No method for storing a link from this buffer"))
10052 (t (setq link nil)))
10054 ;; We're done setting link and desc, clean up
10055 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10056 (setq link (or link cpltxt)
10057 desc (or desc cpltxt))
10058 (cond ((not desc))
10059 ((equal desc "NONE") (setq desc nil))
10060 (t (setq desc
10061 (replace-regexp-in-string
10062 org-bracket-link-analytic-regexp
10063 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10064 desc))))
10065 ;; Return the link
10066 (if (not (and (or (called-interactively-p 'any)
10067 executing-kbd-macro)
10068 link))
10069 (or agenda-link (and link (org-make-link-string link desc)))
10070 (push (list link desc) org-stored-links)
10071 (message "Stored: %s" (or desc link))
10072 (when custom-id
10073 (setq link (concat "file:" (abbreviate-file-name
10074 (buffer-file-name)) "::#" custom-id))
10075 (push (list link desc) org-stored-links))
10076 (car org-stored-links)))))
10078 (defun org-store-link-props (&rest plist)
10079 "Store link properties, extract names, addresses and dates."
10080 (let ((x (plist-get plist :from)))
10081 (when x
10082 (let ((adr (mail-extract-address-components x)))
10083 (setq plist (plist-put plist :fromname (car adr)))
10084 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10085 (let ((x (plist-get plist :to)))
10086 (when x
10087 (let ((adr (mail-extract-address-components x)))
10088 (setq plist (plist-put plist :toname (car adr)))
10089 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10090 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10091 (when x
10092 (setq plist (plist-put plist :date-timestamp
10093 (format-time-string
10094 (org-time-stamp-format t) x)))
10095 (setq plist (plist-put plist :date-timestamp-inactive
10096 (format-time-string
10097 (org-time-stamp-format t t) x)))))
10098 (let ((from (plist-get plist :from))
10099 (to (plist-get plist :to)))
10100 (when (and from to org-from-is-user-regexp)
10101 (setq plist
10102 (plist-put plist :fromto
10103 (if (string-match org-from-is-user-regexp from)
10104 (concat "to %t")
10105 (concat "from %f"))))))
10106 (setq org-store-link-plist plist))
10108 (defun org-add-link-props (&rest plist)
10109 "Add these properties to the link property list."
10110 (let (key value)
10111 (while plist
10112 (setq key (pop plist) value (pop plist))
10113 (setq org-store-link-plist
10114 (plist-put org-store-link-plist key value)))))
10116 (defun org-email-link-description (&optional fmt)
10117 "Return the description part of an email link.
10118 This takes information from `org-store-link-plist' and formats it
10119 according to FMT (default from `org-email-link-description-format')."
10120 (setq fmt (or fmt org-email-link-description-format))
10121 (let* ((p org-store-link-plist)
10122 (to (plist-get p :toaddress))
10123 (from (plist-get p :fromaddress))
10124 (table
10125 (list
10126 (cons "%c" (plist-get p :fromto))
10127 (cons "%F" (plist-get p :from))
10128 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10129 (cons "%T" (plist-get p :to))
10130 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10131 (cons "%s" (plist-get p :subject))
10132 (cons "%d" (plist-get p :date))
10133 (cons "%m" (plist-get p :message-id)))))
10134 (when (string-match "%c" fmt)
10135 ;; Check if the user wrote this message
10136 (if (and org-from-is-user-regexp from to
10137 (save-match-data (string-match org-from-is-user-regexp from)))
10138 (setq fmt (replace-match "to %t" t t fmt))
10139 (setq fmt (replace-match "from %f" t t fmt))))
10140 (org-replace-escapes fmt table)))
10142 (defun org-make-org-heading-search-string (&optional string)
10143 "Make search string for the current headline or STRING."
10144 (let ((s (or string
10145 (and (derived-mode-p 'org-mode)
10146 (save-excursion
10147 (org-back-to-heading t)
10148 (org-element-property :raw-value (org-element-at-point))))))
10149 (lines org-context-in-file-links))
10150 (or string (setq s (concat "*" s))) ; Add * for headlines
10151 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10152 (when (and string (integerp lines) (> lines 0))
10153 (let ((slines (org-split-string s "\n")))
10154 (when (< lines (length slines))
10155 (setq s (mapconcat
10156 'identity
10157 (reverse (nthcdr (- (length slines) lines)
10158 (reverse slines))) "\n")))))
10159 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10161 (defun org-make-link-string (link &optional description)
10162 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10163 (unless (org-string-nw-p link) (error "Empty link"))
10164 (let ((uri (cond ((string-match org-link-types-re link)
10165 (concat (match-string 1 link)
10166 (org-link-escape (substring link (match-end 1)))))
10167 ;; For readability, url-encode internal links only
10168 ;; when absolutely needed (i.e, when they contain
10169 ;; square brackets). File links however, are
10170 ;; encoded since, e.g., spaces are significant.
10171 ((or (file-name-absolute-p link)
10172 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10173 (org-link-escape link))
10174 (t link)))
10175 (description
10176 (and (org-string-nw-p description)
10177 ;; Remove brackets from description, as they are fatal.
10178 (replace-regexp-in-string
10179 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10180 (org-trim description)))))
10181 (format "[[%s]%s]"
10183 (if description (format "[%s]" description) ""))))
10185 (defconst org-link-escape-chars
10186 ;;%20 %5B %5D %25
10187 '(?\s ?\[ ?\] ?%)
10188 "List of characters that should be escaped in a link when stored to Org.
10189 This is the list that is used for internal purposes.")
10191 (defun org-link-escape (text &optional table merge)
10192 "Return percent escaped representation of TEXT.
10193 TEXT is a string with the text to escape.
10194 Optional argument TABLE is a list with characters that should be
10195 escaped. When nil, `org-link-escape-chars' is used.
10196 If optional argument MERGE is set, merge TABLE into
10197 `org-link-escape-chars'."
10198 (let ((characters-to-encode
10199 (cond ((null table) org-link-escape-chars)
10200 (merge (append org-link-escape-chars table))
10201 (t table))))
10202 (mapconcat
10203 (lambda (c)
10204 (if (or (memq c characters-to-encode)
10205 (and org-url-hexify-p (or (< c 32) (> c 126))))
10206 (mapconcat (lambda (e) (format "%%%.2X" e))
10207 (or (encode-coding-char c 'utf-8)
10208 (error "Unable to percent escape character: %c" c))
10210 (char-to-string c)))
10211 text "")))
10213 (defun org-link-unescape (str)
10214 "Unhex hexified Unicode parts in string STR.
10215 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10216 reciprocal of `org-link-escape', which see."
10217 (if (org-string-nw-p str)
10218 (replace-regexp-in-string
10219 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10220 str))
10222 (defun org-link-unescape-compound (hex)
10223 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10224 Note: this function also decodes single byte encodings like
10225 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10226 (save-match-data
10227 (let* ((bytes (cdr (split-string hex "%")))
10228 (ret "")
10229 (eat 0)
10230 (sum 0))
10231 (while bytes
10232 (let* ((val (string-to-number (pop bytes) 16))
10233 (shift-xor
10234 (if (= 0 eat)
10235 (cond
10236 ((>= val 252) (cons 6 252))
10237 ((>= val 248) (cons 5 248))
10238 ((>= val 240) (cons 4 240))
10239 ((>= val 224) (cons 3 224))
10240 ((>= val 192) (cons 2 192))
10241 (t (cons 0 0)))
10242 (cons 6 128))))
10243 (when (>= val 192) (setq eat (car shift-xor)))
10244 (setq val (logxor val (cdr shift-xor)))
10245 (setq sum (+ (lsh sum (car shift-xor)) val))
10246 (when (> eat 0) (setq eat (- eat 1)))
10247 (cond
10248 ((= 0 eat) ;multi byte
10249 (setq ret (concat ret (char-to-string sum)))
10250 (setq sum 0))
10251 ((not bytes) ; single byte(s)
10252 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10253 ret)))
10255 (defun org-link-unescape-single-byte-sequence (hex)
10256 "Unhexify hex-encoded single byte character sequences."
10257 (mapconcat (lambda (byte)
10258 (char-to-string (string-to-number byte 16)))
10259 (cdr (split-string hex "%")) ""))
10261 (defun org-xor (a b)
10262 "Exclusive or."
10263 (if a (not b) b))
10265 (defun org-fixup-message-id-for-http (s)
10266 "Replace special characters in a message id, so it can be used in an http query."
10267 (when (string-match "%" s)
10268 (setq s (mapconcat (lambda (c)
10269 (if (eq c ?%)
10270 "%25"
10271 (char-to-string c)))
10272 s "")))
10273 (while (string-match "<" s)
10274 (setq s (replace-match "%3C" t t s)))
10275 (while (string-match ">" s)
10276 (setq s (replace-match "%3E" t t s)))
10277 (while (string-match "@" s)
10278 (setq s (replace-match "%40" t t s)))
10281 (defun org-link-prettify (link)
10282 "Return a human-readable representation of LINK.
10283 The car of LINK must be a raw link.
10284 The cdr of LINK must be either a link description or nil."
10285 (let ((desc (or (cadr link) "<no description>")))
10286 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10287 "<" (car link) ">")))
10289 ;;;###autoload
10290 (defun org-insert-link-global ()
10291 "Insert a link like Org mode does.
10292 This command can be called in any mode to insert a link in Org syntax."
10293 (interactive)
10294 (org-load-modules-maybe)
10295 (org-run-like-in-org-mode 'org-insert-link))
10297 (defun org-insert-all-links (arg &optional pre post)
10298 "Insert all links in `org-stored-links'.
10299 When a universal prefix, do not delete the links from `org-stored-links'.
10300 When `ARG' is a number, insert the last N link(s).
10301 `PRE' and `POST' are optional arguments to define a string to
10302 prepend or to append."
10303 (interactive "P")
10304 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10305 (links (copy-sequence org-stored-links))
10306 (pr (or pre "- "))
10307 (po (or post "\n"))
10308 (cnt 1) l)
10309 (if (null org-stored-links)
10310 (message "No link to insert")
10311 (while (and (or (listp arg) (>= arg cnt))
10312 (setq l (if (listp arg)
10313 (pop links)
10314 (pop org-stored-links))))
10315 (setq cnt (1+ cnt))
10316 (insert pr)
10317 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10318 (insert po)))))
10320 (defun org-insert-last-stored-link (arg)
10321 "Insert the last link stored in `org-stored-links'."
10322 (interactive "p")
10323 (org-insert-all-links arg "" "\n"))
10325 (defun org-link-fontify-links-to-this-file ()
10326 "Fontify links to the current file in `org-stored-links'."
10327 (let ((f (buffer-file-name)) a b)
10328 (setq a (mapcar (lambda(l)
10329 (let ((ll (car l)))
10330 (when (and (string-match "^file:\\(.+\\)::" ll)
10331 (equal f (expand-file-name (match-string 1 ll))))
10332 ll)))
10333 org-stored-links))
10334 (when (featurep 'org-id)
10335 (setq b (mapcar (lambda(l)
10336 (let ((ll (car l)))
10337 (when (and (string-match "^id:\\(.+\\)$" ll)
10338 (equal f (expand-file-name
10339 (or (org-id-find-id-file
10340 (match-string 1 ll)) ""))))
10341 ll)))
10342 org-stored-links)))
10343 (mapcar (lambda(l)
10344 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10345 (delq nil (append a b)))))
10347 (defvar org--links-history nil)
10348 (defun org-insert-link (&optional complete-file link-location default-description)
10349 "Insert a link. At the prompt, enter the link.
10351 Completion can be used to insert any of the link protocol prefixes like
10352 http or ftp in use.
10354 The history can be used to select a link previously stored with
10355 `org-store-link'. When the empty string is entered (i.e. if you just
10356 press RET at the prompt), the link defaults to the most recently
10357 stored link. As SPC triggers completion in the minibuffer, you need to
10358 use M-SPC or C-q SPC to force the insertion of a space character.
10360 You will also be prompted for a description, and if one is given, it will
10361 be displayed in the buffer instead of the link.
10363 If there is already a link at point, this command will allow you to edit link
10364 and description parts.
10366 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10367 be selected using completion. The path to the file will be relative to the
10368 current directory if the file is in the current directory or a subdirectory.
10369 Otherwise, the link will be the absolute path as completed in the minibuffer
10370 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10371 option `org-link-file-path-type'.
10373 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10374 the current directory or below.
10376 With three \\[universal-argument] prefixes, negate the meaning of
10377 `org-keep-stored-link-after-insertion'.
10379 If `org-make-link-description-function' is non-nil, this function will be
10380 called with the link target, and the result will be the default
10381 link description.
10383 If the LINK-LOCATION parameter is non-nil, this value will be
10384 used as the link location instead of reading one interactively.
10386 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10387 be used as the default description."
10388 (interactive "P")
10389 (let* ((wcf (current-window-configuration))
10390 (origbuf (current-buffer))
10391 (region (when (org-region-active-p)
10392 (buffer-substring (region-beginning) (region-end))))
10393 (remove (and region (list (region-beginning) (region-end))))
10394 (desc region)
10395 (link link-location)
10396 (abbrevs org-link-abbrev-alist-local)
10397 entry all-prefixes auto-desc)
10398 (cond
10399 (link-location) ; specified by arg, just use it.
10400 ((org-in-regexp org-bracket-link-regexp 1)
10401 ;; We do have a link at point, and we are going to edit it.
10402 (setq remove (list (match-beginning 0) (match-end 0)))
10403 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10404 (setq link (read-string "Link: "
10405 (org-link-unescape
10406 (match-string-no-properties 1)))))
10407 ((or (org-in-regexp org-angle-link-re)
10408 (org-in-regexp org-plain-link-re))
10409 ;; Convert to bracket link
10410 (setq remove (list (match-beginning 0) (match-end 0))
10411 link (read-string "Link: "
10412 (org-unbracket-string "<" ">" (match-string 0)))))
10413 ((member complete-file '((4) (16)))
10414 ;; Completing read for file names.
10415 (setq link (org-file-complete-link complete-file)))
10417 ;; Read link, with completion for stored links.
10418 (org-link-fontify-links-to-this-file)
10419 (org-switch-to-buffer-other-window "*Org Links*")
10420 (with-current-buffer "*Org Links*"
10421 (erase-buffer)
10422 (insert "Insert a link.
10423 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10424 (when org-stored-links
10425 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10426 (insert (mapconcat 'org-link-prettify
10427 (reverse org-stored-links) "\n")))
10428 (goto-char (point-min)))
10429 (let ((cw (selected-window)))
10430 (select-window (get-buffer-window "*Org Links*" 'visible))
10431 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10432 (unless (pos-visible-in-window-p (point-max))
10433 (org-fit-window-to-buffer))
10434 (and (window-live-p cw) (select-window cw)))
10435 (setq all-prefixes (append (mapcar 'car abbrevs)
10436 (mapcar 'car org-link-abbrev-alist)
10437 (org-link-types)))
10438 (unwind-protect
10439 ;; Fake a link history, containing the stored links.
10440 (let ((org--links-history
10441 (append (mapcar #'car org-stored-links)
10442 org-insert-link-history)))
10443 (setq link
10444 (org-completing-read
10445 "Link: "
10446 (append
10447 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10448 (mapcar #'car org-stored-links))
10449 nil nil nil
10450 'org--links-history
10451 (caar org-stored-links)))
10452 (unless (org-string-nw-p link) (user-error "No link selected"))
10453 (dolist (l org-stored-links)
10454 (when (equal link (cadr l))
10455 (setq link (car l))
10456 (setq auto-desc t)))
10457 (when (or (member link all-prefixes)
10458 (and (equal ":" (substring link -1))
10459 (member (substring link 0 -1) all-prefixes)
10460 (setq link (substring link 0 -1))))
10461 (setq link (with-current-buffer origbuf
10462 (org-link-try-special-completion link)))))
10463 (set-window-configuration wcf)
10464 (kill-buffer "*Org Links*"))
10465 (setq entry (assoc link org-stored-links))
10466 (or entry (push link org-insert-link-history))
10467 (setq desc (or desc (nth 1 entry)))))
10469 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10470 (not org-keep-stored-link-after-insertion))
10471 (setq org-stored-links (delq (assoc link org-stored-links)
10472 org-stored-links)))
10474 (when (and (string-match org-plain-link-re link)
10475 (not (string-match org-ts-regexp link)))
10476 ;; URL-like link, normalize the use of angular brackets.
10477 (setq link (org-unbracket-string "<" ">" link)))
10479 ;; Check if we are linking to the current file with a search
10480 ;; option If yes, simplify the link by using only the search
10481 ;; option.
10482 (when (and buffer-file-name
10483 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10484 (let* ((path (match-string 1 link))
10485 (case-fold-search nil)
10486 (search (match-string 2 link)))
10487 (save-match-data
10488 (when (equal (file-truename buffer-file-name) (file-truename path))
10489 ;; We are linking to this same file, with a search option
10490 (setq link search)))))
10492 ;; Check if we can/should use a relative path. If yes, simplify the link
10493 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10494 (let* ((type (match-string 1 link))
10495 (path (match-string 2 link))
10496 (origpath path)
10497 (case-fold-search nil))
10498 (cond
10499 ((or (eq org-link-file-path-type 'absolute)
10500 (equal complete-file '(16)))
10501 (setq path (abbreviate-file-name (expand-file-name path))))
10502 ((eq org-link-file-path-type 'noabbrev)
10503 (setq path (expand-file-name path)))
10504 ((eq org-link-file-path-type 'relative)
10505 (setq path (file-relative-name path)))
10507 (save-match-data
10508 (if (string-match (concat "^" (regexp-quote
10509 (expand-file-name
10510 (file-name-as-directory
10511 default-directory))))
10512 (expand-file-name path))
10513 ;; We are linking a file with relative path name.
10514 (setq path (substring (expand-file-name path)
10515 (match-end 0)))
10516 (setq path (abbreviate-file-name (expand-file-name path)))))))
10517 (setq link (concat type path))
10518 (when (equal desc origpath)
10519 (setq desc path))))
10521 (if org-make-link-description-function
10522 (setq desc
10523 (or (condition-case nil
10524 (funcall org-make-link-description-function link desc)
10525 (error (progn (message "Can't get link description from `%s'"
10526 (symbol-name org-make-link-description-function))
10527 (sit-for 2) nil)))
10528 (read-string "Description: " default-description)))
10529 (if default-description (setq desc default-description)
10530 (setq desc (or (and auto-desc desc)
10531 (read-string "Description: " desc)))))
10533 (unless (string-match "\\S-" desc) (setq desc nil))
10534 (when remove (apply 'delete-region remove))
10535 (insert (org-make-link-string link desc))
10536 ;; Redisplay so as the new link has proper invisible characters.
10537 (sit-for 0)))
10539 (defun org-link-try-special-completion (type)
10540 "If there is completion support for link type TYPE, offer it."
10541 (let ((fun (org-link-get-parameter type :complete)))
10542 (if (functionp fun)
10543 (funcall fun)
10544 (read-string "Link (no completion support): " (concat type ":")))))
10546 (defun org-file-complete-link (&optional arg)
10547 "Create a file link using completion."
10548 (let ((file (read-file-name "File: "))
10549 (pwd (file-name-as-directory (expand-file-name ".")))
10550 (pwd1 (file-name-as-directory (abbreviate-file-name
10551 (expand-file-name ".")))))
10552 (cond ((equal arg '(16))
10553 (concat "file:"
10554 (abbreviate-file-name (expand-file-name file))))
10555 ((string-match
10556 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10557 (concat "file:" (match-string 1 file)))
10558 ((string-match
10559 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10560 (expand-file-name file))
10561 (concat "file:"
10562 (match-string 1 (expand-file-name file))))
10563 (t (concat "file:" file)))))
10565 (defun org-completing-read (&rest args)
10566 "Completing-read with SPACE being a normal character."
10567 (let ((enable-recursive-minibuffers t)
10568 (minibuffer-local-completion-map
10569 (copy-keymap minibuffer-local-completion-map)))
10570 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10571 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10572 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10573 'org-time-stamp-inactive)
10574 (apply #'completing-read args)))
10576 ;;; Opening/following a link
10578 (defvar org-link-search-failed nil)
10580 (defvar org-open-link-functions nil
10581 "Hook for functions finding a plain text link.
10582 These functions must take a single argument, the link content.
10583 They will be called for links that look like [[link text][description]]
10584 when LINK TEXT does not have a protocol like \"http:\" and does not look
10585 like a filename (e.g. \"./blue.png\").
10587 These functions will be called *before* Org attempts to resolve the
10588 link by doing text searches in the current buffer - so if you want a
10589 link \"[[target]]\" to still find \"<<target>>\", your function should
10590 handle this as a special case.
10592 When the function does handle the link, it must return a non-nil value.
10593 If it decides that it is not responsible for this link, it must return
10594 nil to indicate that that Org can continue with other options like
10595 exact and fuzzy text search.")
10597 (defun org-next-link (&optional search-backward)
10598 "Move forward to the next link.
10599 If the link is in hidden text, expose it."
10600 (interactive "P")
10601 (when (and org-link-search-failed (eq this-command last-command))
10602 (goto-char (point-min))
10603 (message "Link search wrapped back to beginning of buffer"))
10604 (setq org-link-search-failed nil)
10605 (let* ((pos (point))
10606 (ct (org-context))
10607 (a (assq :link ct))
10608 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10609 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10610 ((looking-at org-any-link-re)
10611 ;; Don't stay stuck at link without an org-link face
10612 (forward-char (if search-backward -1 1))))
10613 (if (funcall srch-fun org-any-link-re nil t)
10614 (progn
10615 (goto-char (match-beginning 0))
10616 (when (outline-invisible-p) (org-show-context)))
10617 (goto-char pos)
10618 (setq org-link-search-failed t)
10619 (message "No further link found"))))
10621 (defun org-previous-link ()
10622 "Move backward to the previous link.
10623 If the link is in hidden text, expose it."
10624 (interactive)
10625 (funcall 'org-next-link t))
10627 (defun org-translate-link (s)
10628 "Translate a link string if a translation function has been defined."
10629 (with-temp-buffer
10630 (insert (org-trim s))
10631 (org-trim (org-element-interpret-data (org-element-context)))))
10633 (defun org-translate-link-from-planner (type path)
10634 "Translate a link from Emacs Planner syntax so that Org can follow it.
10635 This is still an experimental function, your mileage may vary."
10636 (cond
10637 ((member type '("http" "https" "news" "ftp"))
10638 ;; standard Internet links are the same.
10639 nil)
10640 ((and (equal type "irc") (string-match "^//" path))
10641 ;; Planner has two / at the beginning of an irc link, we have 1.
10642 ;; We should have zero, actually....
10643 (setq path (substring path 1)))
10644 ((and (equal type "lisp") (string-match "^/" path))
10645 ;; Planner has a slash, we do not.
10646 (setq type "elisp" path (substring path 1)))
10647 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10648 ;; A typical message link. Planner has the id after the final slash,
10649 ;; we separate it with a hash mark
10650 (setq path (concat (match-string 1 path) "#"
10651 (org-unbracket-string "<" ">" (match-string 2 path))))))
10652 (cons type path))
10654 (defun org-find-file-at-mouse (ev)
10655 "Open file link or URL at mouse."
10656 (interactive "e")
10657 (mouse-set-point ev)
10658 (org-open-at-point 'in-emacs))
10660 (defun org-open-at-mouse (ev)
10661 "Open file link or URL at mouse.
10662 See the docstring of `org-open-file' for details."
10663 (interactive "e")
10664 (mouse-set-point ev)
10665 (when (eq major-mode 'org-agenda-mode)
10666 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10667 (org-open-at-point))
10669 (defvar org-window-config-before-follow-link nil
10670 "The window configuration before following a link.
10671 This is saved in case the need arises to restore it.")
10673 ;;;###autoload
10674 (defun org-open-at-point-global ()
10675 "Follow a link or time-stamp like Org mode does.
10676 This command can be called in any mode to follow an external link
10677 or a time-stamp that has Org mode syntax. Its behavior is
10678 undefined when called on internal links (e.g., fuzzy links).
10679 Raise an error when there is nothing to follow. "
10680 (interactive)
10681 (cond ((org-in-regexp org-any-link-re)
10682 (org-open-link-from-string (match-string-no-properties 0)))
10683 ((or (org-in-regexp org-ts-regexp-both nil t)
10684 (org-in-regexp org-tsr-regexp-both nil t))
10685 (org-follow-timestamp-link))
10686 (t (user-error "No link found"))))
10688 ;;;###autoload
10689 (defun org-open-link-from-string (s &optional arg reference-buffer)
10690 "Open a link in the string S, as if it was in Org-mode."
10691 (interactive "sLink: \nP")
10692 (let ((reference-buffer (or reference-buffer (current-buffer))))
10693 (with-temp-buffer
10694 (let ((org-inhibit-startup (not reference-buffer)))
10695 (org-mode)
10696 (insert s)
10697 (goto-char (point-min))
10698 (when reference-buffer
10699 (setq org-link-abbrev-alist-local
10700 (with-current-buffer reference-buffer
10701 org-link-abbrev-alist-local)))
10702 (org-open-at-point arg reference-buffer)))))
10704 (defvar org-open-at-point-functions nil
10705 "Hook that is run when following a link at point.
10707 Functions in this hook must return t if they identify and follow
10708 a link at point. If they don't find anything interesting at point,
10709 they must return nil.")
10711 (defvar org-link-search-inhibit-query nil)
10712 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10713 (defun org--open-doi-link (path)
10714 "Open a \"doi\" type link.
10715 PATH is a the path to search for, as a string."
10716 (browse-url (url-encode-url (concat org-doi-server-url path))))
10718 (defun org--open-elisp-link (path)
10719 "Open a \"elisp\" type link.
10720 PATH is the sexp to evaluate, as a string."
10721 (let ((cmd path))
10722 (if (or (and (org-string-nw-p
10723 org-confirm-elisp-link-not-regexp)
10724 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10725 (not org-confirm-elisp-link-function)
10726 (funcall org-confirm-elisp-link-function
10727 (format "Execute \"%s\" as elisp? "
10728 (org-add-props cmd nil 'face 'org-warning))))
10729 (message "%s => %s" cmd
10730 (if (eq (string-to-char cmd) ?\()
10731 (eval (read cmd))
10732 (call-interactively (read cmd))))
10733 (user-error "Abort"))))
10735 (defun org--open-help-link (path)
10736 "Open a \"help\" type link.
10737 PATH is a symbol name, as a string."
10738 (pcase (intern path)
10739 ((and (pred fboundp) variable) (describe-function variable))
10740 ((and (pred boundp) function) (describe-variable function))
10741 (name (user-error "Unknown function or variable: %s" name))))
10743 (defun org--open-shell-link (path)
10744 "Open a \"shell\" type link.
10745 PATH is the command to execute, as a string."
10746 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10747 (cmd path))
10748 (if (or (and (org-string-nw-p
10749 org-confirm-shell-link-not-regexp)
10750 (string-match
10751 org-confirm-shell-link-not-regexp cmd))
10752 (not org-confirm-shell-link-function)
10753 (funcall org-confirm-shell-link-function
10754 (format "Execute \"%s\" in shell? "
10755 (org-add-props cmd nil
10756 'face 'org-warning))))
10757 (progn
10758 (message "Executing %s" cmd)
10759 (shell-command cmd buf)
10760 (when (featurep 'midnight)
10761 (setq clean-buffer-list-kill-buffer-names
10762 (cons (buffer-name buf)
10763 clean-buffer-list-kill-buffer-names))))
10764 (user-error "Abort"))))
10766 (defun org-open-at-point (&optional arg reference-buffer)
10767 "Open link, timestamp, footnote or tags at point.
10769 When point is on a link, follow it. Normally, files will be
10770 opened by an appropriate application. If the optional prefix
10771 argument ARG is non-nil, Emacs will visit the file. With
10772 a double prefix argument, try to open outside of Emacs, in the
10773 application the system uses for this file type.
10775 When point is on a timestamp, open the agenda at the day
10776 specified.
10778 When point is a footnote definition, move to the first reference
10779 found. If it is on a reference, move to the associated
10780 definition.
10782 When point is on a headline, display a list of every link in the
10783 entry, so it is possible to pick one, or all, of them. If point
10784 is on a tag, call `org-tags-view' instead.
10786 When optional argument REFERENCE-BUFFER is non-nil, it should
10787 specify a buffer from where the link search should happen. This
10788 is used internally by `org-open-link-from-string'.
10790 On top of syntactically correct links, this function will open
10791 the link at point in comments or comment blocks and the first
10792 link in a property drawer line."
10793 (interactive "P")
10794 ;; On a code block, open block's results.
10795 (unless (call-interactively 'org-babel-open-src-block-result)
10796 (org-load-modules-maybe)
10797 (setq org-window-config-before-follow-link (current-window-configuration))
10798 (org-remove-occur-highlights nil nil t)
10799 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10800 (let* ((context
10801 ;; Only consider supported types, even if they are not
10802 ;; the closest one.
10803 (org-element-lineage
10804 (org-element-context)
10805 '(clock comment comment-block footnote-definition
10806 footnote-reference headline inlinetask keyword link
10807 node-property timestamp)
10809 (type (org-element-type context))
10810 (value (org-element-property :value context)))
10811 (cond
10812 ((not context) (user-error "No link found"))
10813 ;; Exception: open timestamps and links in properties
10814 ;; drawers, keywords and comments.
10815 ((memq type '(comment comment-block keyword node-property))
10816 (call-interactively #'org-open-at-point-global))
10817 ;; On a headline or an inlinetask, but not on a timestamp,
10818 ;; a link, a footnote reference or on tags.
10819 ((and (memq type '(headline inlinetask))
10820 ;; Not on tags.
10821 (progn (save-excursion (beginning-of-line)
10822 (looking-at org-complex-heading-regexp))
10823 (or (not (match-beginning 5))
10824 (< (point) (match-beginning 5)))))
10825 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10826 (links (car data))
10827 (links-end (cdr data)))
10828 (if links
10829 (dolist (link (if (stringp links) (list links) links))
10830 (search-forward link nil links-end)
10831 (goto-char (match-beginning 0))
10832 (org-open-at-point))
10833 (require 'org-attach)
10834 (org-attach-reveal 'if-exists))))
10835 ;; On a clock line, make sure point is on the timestamp
10836 ;; before opening it.
10837 ((and (eq type 'clock)
10838 value
10839 (>= (point) (org-element-property :begin value))
10840 (<= (point) (org-element-property :end value)))
10841 (org-follow-timestamp-link))
10842 ;; Do nothing on white spaces after an object.
10843 ((>= (point)
10844 (save-excursion
10845 (goto-char (org-element-property :end context))
10846 (skip-chars-backward " \t")
10847 (point)))
10848 (user-error "No link found"))
10849 ((eq type 'timestamp) (org-follow-timestamp-link))
10850 ;; On tags within a headline or an inlinetask.
10851 ((and (memq type '(headline inlinetask))
10852 (progn (save-excursion (beginning-of-line)
10853 (looking-at org-complex-heading-regexp))
10854 (and (match-beginning 5)
10855 (>= (point) (match-beginning 5)))))
10856 (org-tags-view arg (substring (match-string 5) 0 -1)))
10857 ((eq type 'link)
10858 ;; When link is located within the description of another
10859 ;; link (e.g., an inline image), always open the parent
10860 ;; link.
10861 (let* ((link (let ((up (org-element-property :parent context)))
10862 (if (eq (org-element-type up) 'link) up context)))
10863 (type (org-element-property :type link))
10864 (path (org-link-unescape (org-element-property :path link))))
10865 ;; Switch back to REFERENCE-BUFFER needed when called in
10866 ;; a temporary buffer through `org-open-link-from-string'.
10867 (with-current-buffer (or reference-buffer (current-buffer))
10868 (cond
10869 ((equal type "file")
10870 (if (string-match "[*?{]" (file-name-nondirectory path))
10871 (dired path)
10872 ;; Look into `org-link-parameters' in order to find
10873 ;; a DEDICATED-FUNCTION to open file. The function
10874 ;; will be applied on raw link instead of parsed
10875 ;; link due to the limitation in `org-add-link-type'
10876 ;; ("open" function called with a single argument).
10877 ;; If no such function is found, fallback to
10878 ;; `org-open-file'.
10879 (let* ((option (org-element-property :search-option link))
10880 (app (org-element-property :application link))
10881 (dedicated-function
10882 (org-link-get-parameter
10883 (if app (concat type "+" app) type)
10884 :follow)))
10885 (if dedicated-function
10886 (funcall dedicated-function
10887 (concat path
10888 (and option (concat "::" option))))
10889 (apply #'org-open-file
10890 path
10891 (cond (arg)
10892 ((equal app "emacs") 'emacs)
10893 ((equal app "sys") 'system))
10894 (cond ((not option) nil)
10895 ((string-match-p "\\`[0-9]+\\'" option)
10896 (list (string-to-number option)))
10897 (t (list nil
10898 (org-link-unescape option)))))))))
10899 ((functionp (org-link-get-parameter type :follow))
10900 (funcall (org-link-get-parameter type :follow) path))
10901 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10902 (unless (run-hook-with-args-until-success
10903 'org-open-link-functions path)
10904 (if (not arg) (org-mark-ring-push)
10905 (switch-to-buffer-other-window
10906 (org-get-buffer-for-internal-link (current-buffer))))
10907 (let ((destination
10908 (org-with-wide-buffer
10909 (if (equal type "radio")
10910 (org-search-radio-target
10911 (org-element-property :path link))
10912 (org-link-search
10913 (if (member type '("custom-id" "coderef"))
10914 (org-element-property :raw-link link)
10915 path)
10916 ;; Prevent fuzzy links from matching
10917 ;; themselves.
10918 (and (equal type "fuzzy")
10919 (+ 2 (org-element-property :begin link)))))
10920 (point))))
10921 (unless (and (<= (point-min) destination)
10922 (>= (point-max) destination))
10923 (widen))
10924 (goto-char destination))))
10925 (t (browse-url-at-point))))))
10926 ;; On a footnote reference or at a footnote definition's label.
10927 ((or (eq type 'footnote-reference)
10928 (and (eq type 'footnote-definition)
10929 (save-excursion
10930 ;; Do not validate action when point is on the
10931 ;; spaces right after the footnote label, in
10932 ;; order to be on par with behaviour on links.
10933 (skip-chars-forward " \t")
10934 (let ((begin
10935 (org-element-property :contents-begin context)))
10936 (if begin (< (point) begin)
10937 (= (org-element-property :post-affiliated context)
10938 (line-beginning-position)))))))
10939 (org-footnote-action))
10940 (t (user-error "No link found")))))
10941 (run-hook-with-args 'org-follow-link-hook)))
10943 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10944 "Offer links in the current entry and return the selected link.
10945 If there is only one link, return it.
10946 If NTH is an integer, return the NTH link found.
10947 If ZERO is a string, check also this string for a link, and if
10948 there is one, return it."
10949 (with-current-buffer buffer
10950 (org-with-wide-buffer
10951 (goto-char marker)
10952 (let ((cnt ?0)
10953 have-zero end links link c)
10954 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10955 (push (match-string 0 zero) links)
10956 (setq cnt (1- cnt) have-zero t))
10957 (save-excursion
10958 (org-back-to-heading t)
10959 (setq end (save-excursion (outline-next-heading) (point)))
10960 (while (re-search-forward org-any-link-re end t)
10961 (push (match-string 0) links))
10962 (setq links (org-uniquify (reverse links))))
10963 (cond
10964 ((null links)
10965 (message "No links"))
10966 ((equal (length links) 1)
10967 (setq link (car links)))
10968 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10969 (setq link (nth (if have-zero nth (1- nth)) links)))
10970 (t ; we have to select a link
10971 (save-excursion
10972 (save-window-excursion
10973 (delete-other-windows)
10974 (with-output-to-temp-buffer "*Select Link*"
10975 (dolist (l links)
10976 (cond
10977 ((not (string-match org-bracket-link-regexp l))
10978 (princ (format "[%c] %s\n" (cl-incf cnt)
10979 (org-unbracket-string "<" ">" l))))
10980 ((match-end 3)
10981 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10982 (match-string 3 l) (match-string 1 l))))
10983 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10984 (match-string 1 l)))))))
10985 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10986 (message "Select link to open, RET to open all:")
10987 (setq c (read-char-exclusive))
10988 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10989 (when (equal c ?q) (user-error "Abort"))
10990 (if (equal c ?\C-m)
10991 (setq link links)
10992 (setq nth (- c ?0))
10993 (when have-zero (setq nth (1+ nth)))
10994 (unless (and (integerp nth) (>= (length links) nth))
10995 (user-error "Invalid link selection"))
10996 (setq link (nth (1- nth) links)))))
10997 (cons link end)))))
10999 ;; TODO: These functions are deprecated since `org-open-at-point'
11000 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11001 (defun org-open-file-with-system (path)
11002 "Open file at PATH using the system way of opening it."
11003 (org-open-file path 'system))
11004 (defun org-open-file-with-emacs (path)
11005 "Open file at PATH in Emacs."
11006 (org-open-file path 'emacs))
11009 ;;; File search
11011 (defvar org-create-file-search-functions nil
11012 "List of functions to construct the right search string for a file link.
11013 These functions are called in turn with point at the location to
11014 which the link should point.
11016 A function in the hook should first test if it would like to
11017 handle this file type, for example by checking the `major-mode'
11018 or the file extension. If it decides not to handle this file, it
11019 should just return nil to give other functions a chance. If it
11020 does handle the file, it must return the search string to be used
11021 when following the link. The search string will be part of the
11022 file link, given after a double colon, and `org-open-at-point'
11023 will automatically search for it. If special measures must be
11024 taken to make the search successful, another function should be
11025 added to the companion hook `org-execute-file-search-functions',
11026 which see.
11028 A function in this hook may also use `setq' to set the variable
11029 `description' to provide a suggestion for the descriptive text to
11030 be used for this link when it gets inserted into an Org buffer
11031 with \\[org-insert-link].")
11033 (defvar org-execute-file-search-functions nil
11034 "List of functions to execute a file search triggered by a link.
11036 Functions added to this hook must accept a single argument, the
11037 search string that was part of the file link, the part after the
11038 double colon. The function must first check if it would like to
11039 handle this search, for example by checking the `major-mode' or
11040 the file extension. If it decides not to handle this search, it
11041 should just return nil to give other functions a chance. If it
11042 does handle the search, it must return a non-nil value to keep
11043 other functions from trying.
11045 Each function can access the current prefix argument through the
11046 variable `current-prefix-arg'. Note that a single prefix is used
11047 to force opening a link in Emacs, so it may be good to only use a
11048 numeric or double prefix to guide the search function.
11050 In case this is needed, a function in this hook can also restore
11051 the window configuration before `org-open-at-point' was called using:
11053 \(set-window-configuration org-window-config-before-follow-link)")
11055 (defun org-search-radio-target (target)
11056 "Search a radio target matching TARGET in current buffer.
11057 White spaces are not significant."
11058 (let ((re (format "<<<%s>>>"
11059 (mapconcat #'regexp-quote
11060 (org-split-string target "[ \t\n]+")
11061 "[ \t]+\\(?:\n[ \t]*\\)?")))
11062 (origin (point)))
11063 (goto-char (point-min))
11064 (catch :radio-match
11065 (while (re-search-forward re nil t)
11066 (backward-char)
11067 (let ((object (org-element-context)))
11068 (when (eq (org-element-type object) 'radio-target)
11069 (goto-char (org-element-property :begin object))
11070 (org-show-context 'link-search)
11071 (throw :radio-match nil))))
11072 (goto-char origin)
11073 (user-error "No match for radio target: %s" target))))
11075 (defun org-link-search (s &optional avoid-pos stealth)
11076 "Search for a search string S.
11078 If S starts with \"#\", it triggers a custom ID search.
11080 If S is enclosed within parenthesis, it initiates a coderef
11081 search.
11083 If S is surrounded by forward slashes, it is interpreted as
11084 a regular expression. In Org mode files, this will create an
11085 `org-occur' sparse tree. In ordinary files, `occur' will be used
11086 to list matches. If the current buffer is in `dired-mode', grep
11087 will be used to search in all files.
11089 When AVOID-POS is given, ignore matches near that position.
11091 When optional argument STEALTH is non-nil, do not modify
11092 visibility around point, thus ignoring `org-show-context-detail'
11093 variable.
11095 Search is case-insensitive and ignores white spaces. Return type
11096 of matched result, with is either `dedicated' or `fuzzy'."
11097 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11098 (let* ((case-fold-search t)
11099 (origin (point))
11100 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11101 (words (org-split-string s "[ \t\n]+"))
11102 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11103 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11104 type)
11105 (cond
11106 ;; Check if there are any special search functions.
11107 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11108 ((eq (string-to-char s) ?#)
11109 ;; Look for a custom ID S if S starts with "#".
11110 (let* ((id (substring normalized 1))
11111 (match (org-find-property "CUSTOM_ID" id)))
11112 (if match (progn (goto-char match) (setf type 'dedicated))
11113 (error "No match for custom ID: %s" id))))
11114 ((string-match "\\`(\\(.*\\))\\'" normalized)
11115 ;; Look for coderef targets if S is enclosed within parenthesis.
11116 (let ((coderef (match-string-no-properties 1 normalized))
11117 (re (substring s-single-re 1 -1)))
11118 (goto-char (point-min))
11119 (catch :coderef-match
11120 (while (re-search-forward re nil t)
11121 (let ((element (org-element-at-point)))
11122 (when (and (memq (org-element-type element)
11123 '(example-block src-block))
11124 ;; Build proper regexp according to current
11125 ;; block's label format.
11126 (let ((label-fmt
11127 (regexp-quote
11128 (or (org-element-property :label-fmt element)
11129 org-coderef-label-format))))
11130 (save-excursion
11131 (beginning-of-line)
11132 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11133 (format label-fmt coderef))))))
11134 (setq type 'dedicated)
11135 (goto-char (match-beginning 1))
11136 (throw :coderef-match nil))))
11137 (goto-char origin)
11138 (error "No match for coderef: %s" coderef))))
11139 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11140 ;; Look for a regular expression.
11141 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11142 (match-string 1 s)))
11143 ;; Fuzzy links.
11145 (let ((starred (eq (string-to-char normalized) ?*)))
11146 (cond
11147 ;; Look for targets, only if not in a headline search.
11148 ((and (not starred)
11149 (let ((target (format "<<%s>>" s-multi-re)))
11150 (catch :target-match
11151 (goto-char (point-min))
11152 (while (re-search-forward target nil t)
11153 (backward-char)
11154 (let ((context (org-element-context)))
11155 (when (eq (org-element-type context) 'target)
11156 (setq type 'dedicated)
11157 (goto-char (org-element-property :begin context))
11158 (throw :target-match t))))
11159 nil))))
11160 ;; Look for elements named after S, only if not in a headline
11161 ;; search.
11162 ((and (not starred)
11163 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11164 (catch :name-match
11165 (goto-char (point-min))
11166 (while (re-search-forward name nil t)
11167 (let ((element (org-element-at-point)))
11168 (when (equal (org-split-string
11169 (org-element-property :name element)
11170 "[ \t]+")
11171 words)
11172 (setq type 'dedicated)
11173 (beginning-of-line)
11174 (throw :name-match t))))
11175 nil))))
11176 ;; Regular text search. Prefer headlines in Org mode
11177 ;; buffers.
11178 ((and (derived-mode-p 'org-mode)
11179 (let* ((wspace "[ \t]")
11180 (wspaceopt (concat wspace "*"))
11181 (cookie (concat "\\(?:"
11182 wspaceopt
11183 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11184 wspaceopt
11185 "\\)"))
11186 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11187 (re (concat
11188 org-outline-regexp-bol
11189 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11190 "\\(?:\\[#.\\][ \t]+\\)?"
11191 "\\(?:" org-comment-string "[ \t]+\\)?"
11192 sep "?"
11193 (let ((title (mapconcat #'regexp-quote
11194 words
11195 sep)))
11196 (if starred (substring title 1) title))
11197 sep "?"
11198 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11199 "[ \t]*$")))
11200 (goto-char (point-min))
11201 (re-search-forward re nil t)))
11202 (goto-char (match-beginning 0))
11203 (setq type 'dedicated))
11204 ;; Offer to create non-existent headline depending on
11205 ;; `org-link-search-must-match-exact-headline'.
11206 ((and (derived-mode-p 'org-mode)
11207 (not org-link-search-inhibit-query)
11208 (eq org-link-search-must-match-exact-headline 'query-to-create)
11209 (yes-or-no-p "No match - create this as a new heading? "))
11210 (goto-char (point-max))
11211 (unless (bolp) (newline))
11212 (org-insert-heading nil t t)
11213 (insert s "\n")
11214 (beginning-of-line 0))
11215 ;; Only headlines are looked after. No need to process
11216 ;; further: throw an error.
11217 ((and (derived-mode-p 'org-mode)
11218 (or starred org-link-search-must-match-exact-headline))
11219 (goto-char origin)
11220 (error "No match for fuzzy expression: %s" normalized))
11221 ;; Regular text search.
11222 ((catch :fuzzy-match
11223 (goto-char (point-min))
11224 (while (re-search-forward s-multi-re nil t)
11225 ;; Skip match if it contains AVOID-POS or it is included
11226 ;; in a link with a description but outside the
11227 ;; description.
11228 (unless (or (and avoid-pos
11229 (<= (match-beginning 0) avoid-pos)
11230 (> (match-end 0) avoid-pos))
11231 (and (save-match-data
11232 (org-in-regexp org-bracket-link-regexp))
11233 (match-beginning 3)
11234 (or (> (match-beginning 3) (point))
11235 (<= (match-end 3) (point)))
11236 (org-element-lineage
11237 (save-match-data (org-element-context))
11238 '(link) t)))
11239 (goto-char (match-beginning 0))
11240 (setq type 'fuzzy)
11241 (throw :fuzzy-match t)))
11242 nil))
11243 ;; All failed. Throw an error.
11244 (t (goto-char origin)
11245 (error "No match for fuzzy expression: %s" normalized))))))
11246 ;; Disclose surroundings of match, if appropriate.
11247 (when (and (derived-mode-p 'org-mode) (not stealth))
11248 (org-show-context 'link-search))
11249 type))
11251 (defun org-get-buffer-for-internal-link (buffer)
11252 "Return a buffer to be used for displaying the link target of internal links."
11253 (cond
11254 ((not org-display-internal-link-with-indirect-buffer)
11255 buffer)
11256 ((string-suffix-p "(Clone)" (buffer-name buffer))
11257 (message "Buffer is already a clone, not making another one")
11258 ;; we also do not modify visibility in this case
11259 buffer)
11260 (t ; make a new indirect buffer for displaying the link
11261 (let* ((bn (buffer-name buffer))
11262 (ibn (concat bn "(Clone)"))
11263 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11264 (with-current-buffer ib (org-overview))
11265 ib))))
11267 (defun org-do-occur (regexp &optional cleanup)
11268 "Call the Emacs command `occur'.
11269 If CLEANUP is non-nil, remove the printout of the regular expression
11270 in the *Occur* buffer. This is useful if the regex is long and not useful
11271 to read."
11272 (occur regexp)
11273 (when cleanup
11274 (let ((cwin (selected-window)) win beg end)
11275 (when (setq win (get-buffer-window "*Occur*"))
11276 (select-window win))
11277 (goto-char (point-min))
11278 (when (re-search-forward "match[a-z]+" nil t)
11279 (setq beg (match-end 0))
11280 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11281 (setq end (1- (match-beginning 0)))))
11282 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11283 (goto-char (point-min))
11284 (select-window cwin))))
11286 ;;; The mark ring for links jumps
11288 (defvar org-mark-ring nil
11289 "Mark ring for positions before jumps in Org-mode.")
11290 (defvar org-mark-ring-last-goto nil
11291 "Last position in the mark ring used to go back.")
11292 ;; Fill and close the ring
11293 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11294 (dotimes (_ org-mark-ring-length)
11295 (push (make-marker) org-mark-ring))
11296 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11297 org-mark-ring)
11299 (defun org-mark-ring-push (&optional pos buffer)
11300 "Put the current position or POS into the mark ring and rotate it."
11301 (interactive)
11302 (setq pos (or pos (point)))
11303 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11304 (move-marker (car org-mark-ring)
11305 (or pos (point))
11306 (or buffer (current-buffer)))
11307 (message "%s"
11308 (substitute-command-keys
11309 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11311 (defun org-mark-ring-goto (&optional n)
11312 "Jump to the previous position in the mark ring.
11313 With prefix arg N, jump back that many stored positions. When
11314 called several times in succession, walk through the entire ring.
11315 Org mode commands jumping to a different position in the current file,
11316 or to another Org file, automatically push the old position onto the ring."
11317 (interactive "p")
11318 (let (p m)
11319 (if (eq last-command this-command)
11320 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11321 (setq p org-mark-ring))
11322 (setq org-mark-ring-last-goto p)
11323 (setq m (car p))
11324 (pop-to-buffer-same-window (marker-buffer m))
11325 (goto-char m)
11326 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11328 (defun org-add-angle-brackets (s)
11329 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11330 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11333 ;;; Following specific links
11335 (defvar org-agenda-buffer-tmp-name)
11336 (defvar org-agenda-start-on-weekday)
11337 (defun org-follow-timestamp-link ()
11338 "Open an agenda view for the time-stamp date/range at point."
11339 (cond
11340 ((org-at-date-range-p t)
11341 (let ((org-agenda-start-on-weekday)
11342 (t1 (match-string 1))
11343 (t2 (match-string 2)) tt1 tt2)
11344 (setq tt1 (time-to-days (org-time-string-to-time t1))
11345 tt2 (time-to-days (org-time-string-to-time t2)))
11346 (let ((org-agenda-buffer-tmp-name
11347 (format "*Org Agenda(a:%s)"
11348 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11349 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11350 ((org-at-timestamp-p t)
11351 (let ((org-agenda-buffer-tmp-name
11352 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11353 (org-agenda-list nil (time-to-days (org-time-string-to-time
11354 (substring (match-string 1) 0 10)))
11355 1)))
11356 (t (error "This should not happen"))))
11359 ;;; Following file links
11360 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11361 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11362 (declare-function mailcap-mime-info
11363 "mailcap" (string &optional request no-decode))
11364 (defvar org-wait nil)
11365 (defun org-open-file (path &optional in-emacs line search)
11366 "Open the file at PATH.
11367 First, this expands any special file name abbreviations. Then the
11368 configuration variable `org-file-apps' is checked if it contains an
11369 entry for this file type, and if yes, the corresponding command is launched.
11371 If no application is found, Emacs simply visits the file.
11373 With optional prefix argument IN-EMACS, Emacs will visit the file.
11374 With a double \\[universal-argument] \\[universal-argument] \
11375 prefix arg, Org tries to avoid opening in Emacs
11376 and to use an external application to visit the file.
11378 Optional LINE specifies a line to go to, optional SEARCH a string
11379 to search for. If LINE or SEARCH is given, the file will be
11380 opened in Emacs, unless an entry from org-file-apps that makes
11381 use of groups in a regexp matches.
11383 If you want to change the way frames are used when following a
11384 link, please customize `org-link-frame-setup'.
11386 If the file does not exist, an error is thrown."
11387 (let* ((file (if (equal path "")
11388 buffer-file-name
11389 (substitute-in-file-name (expand-file-name path))))
11390 (file-apps (append org-file-apps (org-default-apps)))
11391 (apps (cl-remove-if
11392 'org-file-apps-entry-match-against-dlink-p file-apps))
11393 (apps-dlink (cl-remove-if-not
11394 'org-file-apps-entry-match-against-dlink-p file-apps))
11395 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11396 (dirp (unless remp (file-directory-p file)))
11397 (file (if (and dirp org-open-directory-means-index-dot-org)
11398 (concat (file-name-as-directory file) "index.org")
11399 file))
11400 (a-m-a-p (assq 'auto-mode apps))
11401 (dfile (downcase file))
11402 ;; Reconstruct the original link from the PATH, LINE and
11403 ;; SEARCH args.
11404 (link (cond (line (concat file "::" (number-to-string line)))
11405 (search (concat file "::" search))
11406 (t file)))
11407 (dlink (downcase link))
11408 (old-buffer (current-buffer))
11409 (old-pos (point))
11410 (old-mode major-mode)
11411 (ext
11412 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11413 (match-string 1 dfile)))
11414 cmd link-match-data)
11415 (cond
11416 ((member in-emacs '((16) system))
11417 (setq cmd (cdr (assq 'system apps))))
11418 (in-emacs (setq cmd 'emacs))
11420 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11421 (and dirp (cdr (assq 'directory apps)))
11422 ;; First, try matching against apps-dlink if we
11423 ;; get a match here, store the match data for
11424 ;; later.
11425 (let ((match (assoc-default dlink apps-dlink
11426 'string-match)))
11427 (if match
11428 (progn (setq link-match-data (match-data))
11429 match)
11430 (progn (setq in-emacs (or in-emacs line search))
11431 nil))) ; if we have no match in apps-dlink,
11432 ; always open the file in emacs if line or search
11433 ; is given (for backwards compatibility)
11434 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11435 'string-match)
11436 (cdr (assoc ext apps))
11437 (cdr (assq t apps))))))
11438 (when (eq cmd 'system)
11439 (setq cmd (cdr (assq 'system apps))))
11440 (when (eq cmd 'default)
11441 (setq cmd (cdr (assoc t apps))))
11442 (when (eq cmd 'mailcap)
11443 (require 'mailcap)
11444 (mailcap-parse-mailcaps)
11445 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11446 (command (mailcap-mime-info mime-type)))
11447 (if (stringp command)
11448 (setq cmd command)
11449 (setq cmd 'emacs))))
11450 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11451 (not (file-exists-p file))
11452 (not org-open-non-existing-files))
11453 (user-error "No such file: %s" file))
11454 (cond
11455 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11456 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11457 (while (string-match "['\"]%s['\"]" cmd)
11458 (setq cmd (replace-match "%s" t t cmd)))
11459 (setq cmd (replace-regexp-in-string
11460 "%s"
11461 (shell-quote-argument (convert-standard-filename file))
11463 nil t))
11465 ;; Replace "%1", "%2" etc. in command with group matches from regex
11466 (save-match-data
11467 (let ((match-index 1)
11468 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11469 (set-match-data link-match-data)
11470 (while (<= match-index number-of-groups)
11471 (let ((regex (concat "%" (number-to-string match-index)))
11472 (replace-with (match-string match-index dlink)))
11473 (while (string-match regex cmd)
11474 (setq cmd (replace-match replace-with t t cmd))))
11475 (setq match-index (+ match-index 1)))))
11477 (save-window-excursion
11478 (message "Running %s...done" cmd)
11479 (start-process-shell-command cmd nil cmd)
11480 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11481 ((or (stringp cmd)
11482 (eq cmd 'emacs))
11483 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11484 (widen)
11485 (cond (line (org-goto-line line)
11486 (when (derived-mode-p 'org-mode) (org-reveal)))
11487 (search (org-link-search search))))
11488 ((functionp cmd)
11489 (save-match-data
11490 (set-match-data link-match-data)
11491 (condition-case nil
11492 (funcall cmd file link)
11493 ;; FIXME: Remove this check when most default installations
11494 ;; of Emacs have at least Org 9.0.
11495 ((debug wrong-number-of-arguments wrong-type-argument
11496 invalid-function)
11497 (user-error "Please see Org News for version 9.0 about \
11498 `org-file-apps'--Lisp error: %S" cmd)))))
11499 ((consp cmd)
11500 ;; FIXME: Remove this check when most default installations of
11501 ;; Emacs have at least Org 9.0.
11502 ;; Heads-up instead of silently fall back to
11503 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11504 ;; with sexp instead of a function for `cmd'.
11505 (user-error "Please see Org News for version 9.0 about \
11506 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11507 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11508 (and (derived-mode-p 'org-mode)
11509 (eq old-mode 'org-mode)
11510 (or (not (eq old-buffer (current-buffer)))
11511 (not (eq old-pos (point))))
11512 (org-mark-ring-push old-pos old-buffer))))
11514 (defun org-file-apps-entry-match-against-dlink-p (entry)
11515 "This function returns non-nil if `entry' uses a regular
11516 expression which should be matched against the whole link by
11517 org-open-file.
11519 It assumes that is the case when the entry uses a regular
11520 expression which has at least one grouping construct and the
11521 action is either a lisp form or a command string containing
11522 `%1', i.e. using at least one subexpression match as a
11523 parameter."
11524 (let ((selector (car entry))
11525 (action (cdr entry)))
11526 (if (stringp selector)
11527 (and (> (regexp-opt-depth selector) 0)
11528 (or (and (stringp action)
11529 (string-match "%[0-9]" action))
11530 (consp action)))
11531 nil)))
11533 (defun org-default-apps ()
11534 "Return the default applications for this operating system."
11535 (cond
11536 ((eq system-type 'darwin)
11537 org-file-apps-defaults-macosx)
11538 ((eq system-type 'windows-nt)
11539 org-file-apps-defaults-windowsnt)
11540 (t org-file-apps-defaults-gnu)))
11542 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11543 "Convert extensions to regular expressions in the cars of LIST.
11544 Also, weed out any non-string entries, because the return value is used
11545 only for regexp matching.
11546 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11547 point to the symbol `emacs', indicating that the file should
11548 be opened in Emacs."
11549 (append
11550 (delq nil
11551 (mapcar (lambda (x)
11552 (unless (not (stringp (car x)))
11553 (if (string-match "\\W" (car x))
11555 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11556 list))
11557 (when add-auto-mode
11558 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11560 (defvar ange-ftp-name-format)
11561 (defun org-file-remote-p (file)
11562 "Test whether FILE specifies a location on a remote system.
11563 Return non-nil if the location is indeed remote.
11565 For example, the filename \"/user@host:/foo\" specifies a location
11566 on the system \"/user@host:\"."
11567 (cond ((fboundp 'file-remote-p)
11568 (file-remote-p file))
11569 ((fboundp 'tramp-handle-file-remote-p)
11570 (tramp-handle-file-remote-p file))
11571 ((and (boundp 'ange-ftp-name-format)
11572 (string-match (car ange-ftp-name-format) file))
11573 t)))
11576 ;;;; Refiling
11578 (defun org-get-org-file ()
11579 "Read a filename, with default directory `org-directory'."
11580 (let ((default (or org-default-notes-file remember-data-file)))
11581 (read-file-name (format "File name [%s]: " default)
11582 (file-name-as-directory org-directory)
11583 default)))
11585 (defun org-notes-order-reversed-p ()
11586 "Check if the current file should receive notes in reversed order."
11587 (cond
11588 ((not org-reverse-note-order) nil)
11589 ((eq t org-reverse-note-order) t)
11590 ((not (listp org-reverse-note-order)) nil)
11591 (t (catch 'exit
11592 (dolist (entry org-reverse-note-order)
11593 (when (string-match (car entry) buffer-file-name)
11594 (throw 'exit (cdr entry))))))))
11596 (defvar org-refile-target-table nil
11597 "The list of refile targets, created by `org-refile'.")
11599 (defvar org-agenda-new-buffers nil
11600 "Buffers created to visit agenda files.")
11602 (defvar org-refile-cache nil
11603 "Cache for refile targets.")
11605 (defvar org-refile-markers nil
11606 "All the markers used for caching refile locations.")
11608 (defun org-refile-marker (pos)
11609 "Get a new refile marker, but only if caching is in use."
11610 (if (not org-refile-use-cache)
11612 (let ((m (make-marker)))
11613 (move-marker m pos)
11614 (push m org-refile-markers)
11615 m)))
11617 (defun org-refile-cache-clear ()
11618 "Clear the refile cache and disable all the markers."
11619 (dolist (m org-refile-markers) (move-marker m nil))
11620 (setq org-refile-markers nil)
11621 (setq org-refile-cache nil)
11622 (message "Refile cache has been cleared"))
11624 (defun org-refile-cache-check-set (set)
11625 "Check if all the markers in the cache still have live buffers."
11626 (let (marker)
11627 (catch 'exit
11628 (while (and set (setq marker (nth 3 (pop set))))
11629 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11630 (when (and marker (null (marker-buffer marker)))
11631 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11632 (sit-for 3)
11633 (throw 'exit nil)))
11634 t)))
11636 (defun org-refile-cache-put (set &rest identifiers)
11637 "Push the refile targets SET into the cache, under IDENTIFIERS."
11638 (let* ((key (sha1 (prin1-to-string identifiers)))
11639 (entry (assoc key org-refile-cache)))
11640 (if entry
11641 (setcdr entry set)
11642 (push (cons key set) org-refile-cache))))
11644 (defun org-refile-cache-get (&rest identifiers)
11645 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11646 (cond
11647 ((not org-refile-cache) nil)
11648 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11650 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11651 org-refile-cache))))
11652 (and set (org-refile-cache-check-set set) set)))))
11654 (defvar org-outline-path-cache nil
11655 "Alist between buffer positions and outline paths.
11656 It value is an alist (POSITION . PATH) where POSITION is the
11657 buffer position at the beginning of an entry and PATH is a list
11658 of strings describing the outline path for that entry, in reverse
11659 order.")
11661 (defun org-refile-get-targets (&optional default-buffer)
11662 "Produce a table with refile targets."
11663 (let ((case-fold-search nil)
11664 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11665 (entries (or org-refile-targets '((nil . (:level . 1)))))
11666 targets tgs files desc descre)
11667 (message "Getting targets...")
11668 (with-current-buffer (or default-buffer (current-buffer))
11669 (dolist (entry entries)
11670 (setq files (car entry) desc (cdr entry))
11671 (cond
11672 ((null files) (setq files (list (current-buffer))))
11673 ((eq files 'org-agenda-files)
11674 (setq files (org-agenda-files 'unrestricted)))
11675 ((and (symbolp files) (fboundp files))
11676 (setq files (funcall files)))
11677 ((and (symbolp files) (boundp files))
11678 (setq files (symbol-value files))))
11679 (when (stringp files) (setq files (list files)))
11680 (cond
11681 ((eq (car desc) :tag)
11682 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11683 ((eq (car desc) :todo)
11684 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11685 ((eq (car desc) :regexp)
11686 (setq descre (cdr desc)))
11687 ((eq (car desc) :level)
11688 (setq descre (concat "^\\*\\{" (number-to-string
11689 (if org-odd-levels-only
11690 (1- (* 2 (cdr desc)))
11691 (cdr desc)))
11692 "\\}[ \t]")))
11693 ((eq (car desc) :maxlevel)
11694 (setq descre (concat "^\\*\\{1," (number-to-string
11695 (if org-odd-levels-only
11696 (1- (* 2 (cdr desc)))
11697 (cdr desc)))
11698 "\\}[ \t]")))
11699 (t (error "Bad refiling target description %s" desc)))
11700 (dolist (f files)
11701 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11703 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11704 (progn
11705 (when (bufferp f)
11706 (setq f (buffer-file-name (buffer-base-buffer f))))
11707 (setq f (and f (expand-file-name f)))
11708 (when (eq org-refile-use-outline-path 'file)
11709 (push (list (file-name-nondirectory f) f nil nil) tgs))
11710 (org-with-wide-buffer
11711 (goto-char (point-min))
11712 (setq org-outline-path-cache nil)
11713 (while (re-search-forward descre nil t)
11714 (beginning-of-line)
11715 (looking-at org-complex-heading-regexp)
11716 (let ((begin (point))
11717 (heading (match-string-no-properties 4)))
11718 (unless (or (and
11719 org-refile-target-verify-function
11720 (not
11721 (funcall org-refile-target-verify-function)))
11722 (not heading))
11723 (let ((re (format org-complex-heading-regexp-format
11724 (regexp-quote heading)))
11725 (target
11726 (if (not org-refile-use-outline-path) heading
11727 (mapconcat
11728 #'org-protect-slash
11729 (append
11730 (pcase org-refile-use-outline-path
11731 (`file (list (file-name-nondirectory
11732 (buffer-file-name
11733 (buffer-base-buffer)))))
11734 (`full-file-path
11735 (list (buffer-file-name
11736 (buffer-base-buffer))))
11737 (_ nil))
11738 (org-get-outline-path t t))
11739 "/"))))
11740 (push (list target f re (org-refile-marker (point)))
11741 tgs)))
11742 (when (= (point) begin)
11743 ;; Verification function has not moved point.
11744 (end-of-line)))))))
11745 (when org-refile-use-cache
11746 (org-refile-cache-put tgs (buffer-file-name) descre))
11747 (setq targets (append tgs targets))))))
11748 (message "Getting targets...done")
11749 (nreverse targets)))
11751 (defun org-protect-slash (s)
11752 (replace-regexp-in-string "/" "\\/" s nil t))
11754 (defun org--get-outline-path-1 (&optional use-cache)
11755 "Return outline path to current headline.
11757 Outline path is a list of strings, in reverse order. When
11758 optional argument USE-CACHE is non-nil, make use of a cache. See
11759 `org-get-outline-path' for details.
11761 Assume buffer is widened and point is on a headline."
11762 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11763 (let ((p (point))
11764 (heading (progn
11765 (looking-at org-complex-heading-regexp)
11766 (if (not (match-end 4)) ""
11767 ;; Remove statistics cookies.
11768 (org-trim
11769 (org-link-display-format
11770 (replace-regexp-in-string
11771 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11772 (match-string-no-properties 4))))))))
11773 (if (org-up-heading-safe)
11774 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11775 (when use-cache
11776 (push (cons p path) org-outline-path-cache))
11777 path)
11778 ;; This is a new root node. Since we assume we are moving
11779 ;; forward, we can drop previous cache so as to limit number
11780 ;; of associations there.
11781 (let ((path (list heading)))
11782 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11783 path)))))
11785 (defun org-get-outline-path (&optional with-self use-cache)
11786 "Return the outline path to the current entry.
11788 An outline path is a list of ancestors for current headline, as
11789 a list of strings. Statistics cookies are removed and links are
11790 replaced with their description, if any, or their path otherwise.
11792 When optional argument WITH-SELF is non-nil, the path also
11793 includes the current headline.
11795 When optional argument USE-CACHE is non-nil, cache outline paths
11796 between calls to this function so as to avoid backtracking. This
11797 argument is useful when planning to find more than one outline
11798 path in the same document. In that case, there are two
11799 conditions to satisfy:
11800 - `org-outline-path-cache' is set to nil before starting the
11801 process;
11802 - outline paths are computed by increasing buffer positions."
11803 (org-with-wide-buffer
11804 (and (or (and with-self (org-back-to-heading t))
11805 (org-up-heading-safe))
11806 (reverse (org--get-outline-path-1 use-cache)))))
11808 (defun org-format-outline-path (path &optional width prefix separator)
11809 "Format the outline path PATH for display.
11810 WIDTH is the maximum number of characters that is available.
11811 PREFIX is a prefix to be included in the returned string,
11812 such as the file name.
11813 SEPARATOR is inserted between the different parts of the path,
11814 the default is \"/\"."
11815 (setq width (or width 79))
11816 (setq path (delq nil path))
11817 (unless (> width 0)
11818 (user-error "Argument `width' must be positive"))
11819 (setq separator (or separator "/"))
11820 (let* ((org-odd-levels-only nil)
11821 (fpath (concat
11822 prefix (and prefix path separator)
11823 (mapconcat
11824 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11825 (cl-loop for head in path
11826 for n from 0
11827 collect (org-add-props
11828 head nil 'face
11829 (nth (% n org-n-level-faces) org-level-faces)))
11830 separator))))
11831 (when (> (length fpath) width)
11832 (if (< width 7)
11833 ;; It's unlikely that `width' will be this small, but don't
11834 ;; waste characters by adding ".." if it is.
11835 (setq fpath (substring fpath 0 width))
11836 (setf (substring fpath (- width 2)) "..")))
11837 fpath))
11839 (defun org-display-outline-path (&optional file current separator just-return-string)
11840 "Display the current outline path in the echo area.
11842 If FILE is non-nil, prepend the output with the file name.
11843 If CURRENT is non-nil, append the current heading to the output.
11844 SEPARATOR is passed through to `org-format-outline-path'. It separates
11845 the different parts of the path and defaults to \"/\".
11846 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11847 (interactive "P")
11848 (let* (case-fold-search
11849 (bfn (buffer-file-name (buffer-base-buffer)))
11850 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11851 res)
11852 (when current (setq path (append path
11853 (save-excursion
11854 (org-back-to-heading t)
11855 (when (looking-at org-complex-heading-regexp)
11856 (list (match-string 4)))))))
11857 (setq res
11858 (org-format-outline-path
11859 path
11860 (1- (frame-width))
11861 (and file bfn (concat (file-name-nondirectory bfn) separator))
11862 separator))
11863 (if just-return-string
11864 (org-no-properties res)
11865 (org-unlogged-message "%s" res))))
11867 (defvar org-refile-history nil
11868 "History for refiling operations.")
11870 (defvar org-after-refile-insert-hook nil
11871 "Hook run after `org-refile' has inserted its stuff at the new location.
11872 Note that this is still *before* the stuff will be removed from
11873 the *old* location.")
11875 (defvar org-capture-last-stored-marker)
11876 (defvar org-refile-keep nil
11877 "Non-nil means `org-refile' will copy instead of refile.")
11879 (defun org-copy ()
11880 "Like `org-refile', but copy."
11881 (interactive)
11882 (let ((org-refile-keep t))
11883 (funcall 'org-refile nil nil nil "Copy")))
11885 (defun org-refile (&optional arg default-buffer rfloc msg)
11886 "Move the entry or entries at point to another heading.
11887 The list of target headings is compiled using the information in
11888 `org-refile-targets', which see.
11890 At the target location, the entry is filed as a subitem of the
11891 target heading. Depending on `org-reverse-note-order', the new
11892 subitem will either be the first or the last subitem.
11894 If there is an active region, all entries in that region will be
11895 refiled. However, the region must fulfill the requirement that
11896 the first heading sets the top-level of the moved text.
11898 With prefix arg ARG, the command will only visit the target
11899 location and not actually move anything.
11901 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11902 refiling operation has put the subtree.
11904 With a numeric prefix argument of `2', refile to the running clock.
11906 With a numeric prefix argument of `3', emulate `org-refile-keep'
11907 being set to t and copy to the target location, don't move it.
11908 Beware that keeping refiled entries may result in duplicated ID
11909 properties.
11911 RFLOC can be a refile location obtained in a different way.
11913 MSG is a string to replace \"Refile\" in the default prompt with
11914 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11916 See also `org-refile-use-outline-path'.
11918 If you are using target caching (see `org-refile-use-cache'), you
11919 have to clear the target cache in order to find new targets.
11920 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11921 prefix argument (`C-u C-u C-u C-c C-w')."
11922 (interactive "P")
11923 (if (member arg '(0 (64)))
11924 (org-refile-cache-clear)
11925 (let* ((actionmsg (cond (msg msg)
11926 ((equal arg 3) "Refile (and keep)")
11927 (t "Refile")))
11928 (regionp (org-region-active-p))
11929 (region-start (and regionp (region-beginning)))
11930 (region-end (and regionp (region-end)))
11931 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11932 pos it nbuf file level reversed)
11933 (setq last-command nil)
11934 (when regionp
11935 (goto-char region-start)
11936 (or (bolp) (goto-char (point-at-bol)))
11937 (setq region-start (point))
11938 (unless (or (org-kill-is-subtree-p
11939 (buffer-substring region-start region-end))
11940 (prog1 org-refile-active-region-within-subtree
11941 (let ((s (point-at-eol)))
11942 (org-toggle-heading)
11943 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11944 (user-error "The region is not a (sequence of) subtree(s)")))
11945 (if (equal arg '(16))
11946 (org-refile-goto-last-stored)
11947 (when (or
11948 (and (equal arg 2)
11949 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11950 (prog1
11951 (setq it (list (or org-clock-heading "running clock")
11952 (buffer-file-name
11953 (marker-buffer org-clock-hd-marker))
11955 (marker-position org-clock-hd-marker)))
11956 (setq arg nil)))
11957 (setq it
11958 (or rfloc
11959 (let (heading-text)
11960 (save-excursion
11961 (unless (and arg (listp arg))
11962 (org-back-to-heading t)
11963 (setq heading-text
11964 (replace-regexp-in-string
11965 org-bracket-link-regexp
11966 "\\3"
11967 (or (nth 4 (org-heading-components))
11968 ""))))
11969 (org-refile-get-location
11970 (cond ((and arg (listp arg)) "Goto")
11971 (regionp (concat actionmsg " region to"))
11972 (t (concat actionmsg " subtree \""
11973 heading-text "\" to")))
11974 default-buffer
11975 (and (not (equal '(4) arg))
11976 org-refile-allow-creating-parent-nodes)))))))
11977 (setq file (nth 1 it)
11978 pos (nth 3 it))
11979 (when (and (not arg)
11981 (equal (buffer-file-name) file)
11982 (if regionp
11983 (and (>= pos region-start)
11984 (<= pos region-end))
11985 (and (>= pos (point))
11986 (< pos (save-excursion
11987 (org-end-of-subtree t t))))))
11988 (error "Cannot refile to position inside the tree or region"))
11989 (setq nbuf (or (find-buffer-visiting file)
11990 (find-file-noselect file)))
11991 (if (and arg (not (equal arg 3)))
11992 (progn
11993 (pop-to-buffer-same-window nbuf)
11994 (goto-char pos)
11995 (org-show-context 'org-goto))
11996 (if regionp
11997 (progn
11998 (org-kill-new (buffer-substring region-start region-end))
11999 (org-save-markers-in-region region-start region-end))
12000 (org-copy-subtree 1 nil t))
12001 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12002 (find-file-noselect file)))
12003 (setq reversed (org-notes-order-reversed-p))
12004 (org-with-wide-buffer
12005 (if pos
12006 (progn
12007 (goto-char pos)
12008 (looking-at org-outline-regexp)
12009 (setq level (org-get-valid-level (funcall outline-level) 1))
12010 (goto-char
12011 (if reversed
12012 (or (outline-next-heading) (point-max))
12013 (or (save-excursion (org-get-next-sibling))
12014 (org-end-of-subtree t t)
12015 (point-max)))))
12016 (setq level 1)
12017 (if (not reversed)
12018 (goto-char (point-max))
12019 (goto-char (point-min))
12020 (or (outline-next-heading) (goto-char (point-max)))))
12021 (unless (bolp) (newline))
12022 (org-paste-subtree level nil nil t)
12023 (when org-log-refile
12024 (org-add-log-setup 'refile nil nil org-log-refile)
12025 (unless (eq org-log-refile 'note)
12026 (save-excursion (org-add-log-note))))
12027 (and org-auto-align-tags
12028 (let ((org-loop-over-headlines-in-active-region nil))
12029 (org-set-tags nil t)))
12030 (let ((bookmark-name (plist-get org-bookmark-names-plist
12031 :last-refile)))
12032 (when bookmark-name
12033 (with-demoted-errors
12034 (bookmark-set bookmark-name))))
12035 ;; If we are refiling for capture, make sure that the
12036 ;; last-capture pointers point here
12037 (when (bound-and-true-p org-capture-is-refiling)
12038 (let ((bookmark-name (plist-get org-bookmark-names-plist
12039 :last-capture-marker)))
12040 (when bookmark-name
12041 (with-demoted-errors
12042 (bookmark-set bookmark-name))))
12043 (move-marker org-capture-last-stored-marker (point)))
12044 (when (fboundp 'deactivate-mark) (deactivate-mark))
12045 (run-hooks 'org-after-refile-insert-hook)))
12046 (unless org-refile-keep
12047 (if regionp
12048 (delete-region (point) (+ (point) (- region-end region-start)))
12049 (delete-region
12050 (and (org-back-to-heading t) (point))
12051 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12052 (when (featurep 'org-inlinetask)
12053 (org-inlinetask-remove-END-maybe))
12054 (setq org-markers-to-move nil)
12055 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12057 (defun org-refile-goto-last-stored ()
12058 "Go to the location where the last refile was stored."
12059 (interactive)
12060 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12061 (message "This is the location of the last refile"))
12063 (defun org-refile--get-location (refloc tbl)
12064 "When user refile to REFLOC, find the associated target in TBL.
12065 Also check `org-refile-target-table'."
12066 (car (delq
12068 (mapcar
12069 (lambda (r) (or (assoc r tbl)
12070 (assoc r org-refile-target-table)))
12071 (list (replace-regexp-in-string "/$" "" refloc)
12072 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12074 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12075 "Prompt the user for a refile location, using PROMPT.
12076 PROMPT should not be suffixed with a colon and a space, because
12077 this function appends the default value from
12078 `org-refile-history' automatically, if that is not empty."
12079 (let ((org-refile-targets org-refile-targets)
12080 (org-refile-use-outline-path org-refile-use-outline-path))
12081 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12082 (unless org-refile-target-table
12083 (user-error "No refile targets"))
12084 (let* ((cbuf (current-buffer))
12085 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12086 (cfunc (if (and org-refile-use-outline-path
12087 org-outline-path-complete-in-steps)
12088 #'org-olpath-completing-read
12089 #'completing-read))
12090 (extra (if org-refile-use-outline-path "/" ""))
12091 (cbnex (concat (buffer-name) extra))
12092 (filename (and cfn (expand-file-name cfn)))
12093 (tbl (mapcar
12094 (lambda (x)
12095 (if (and (not (member org-refile-use-outline-path
12096 '(file full-file-path)))
12097 (not (equal filename (nth 1 x))))
12098 (cons (concat (car x) extra " ("
12099 (file-name-nondirectory (nth 1 x)) ")")
12100 (cdr x))
12101 (cons (concat (car x) extra) (cdr x))))
12102 org-refile-target-table))
12103 (completion-ignore-case t)
12104 cdef
12105 (prompt (concat prompt
12106 (or (and (car org-refile-history)
12107 (concat " (default " (car org-refile-history) ")"))
12108 (and (assoc cbnex tbl) (setq cdef cbnex)
12109 (concat " (default " cbnex ")"))) ": "))
12110 pa answ parent-target child parent old-hist)
12111 (setq old-hist org-refile-history)
12112 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12113 nil 'org-refile-history (or cdef (car org-refile-history))))
12114 (if (setq pa (org-refile--get-location answ tbl))
12115 (progn
12116 (org-refile-check-position pa)
12117 (when (or (not org-refile-history)
12118 (not (eq old-hist org-refile-history))
12119 (not (equal (car pa) (car org-refile-history))))
12120 (setq org-refile-history
12121 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12122 org-refile-history
12123 (cdr org-refile-history))))
12124 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12125 (pop org-refile-history)))
12127 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12128 (progn
12129 (setq parent (match-string 1 answ)
12130 child (match-string 2 answ))
12131 (setq parent-target (org-refile--get-location parent tbl))
12132 (when (and parent-target
12133 (or (eq new-nodes t)
12134 (and (eq new-nodes 'confirm)
12135 (y-or-n-p (format "Create new node \"%s\"? "
12136 child)))))
12137 (org-refile-new-child parent-target child)))
12138 (user-error "Invalid target location")))))
12140 (declare-function org-string-nw-p "org-macs" (s))
12141 (defun org-refile-check-position (refile-pointer)
12142 "Check if the refile pointer matches the headline to which it points."
12143 (let* ((file (nth 1 refile-pointer))
12144 (re (nth 2 refile-pointer))
12145 (pos (nth 3 refile-pointer))
12146 buffer)
12147 (if (and (not (markerp pos)) (not file))
12148 (user-error "Please indicate a target file in the refile path")
12149 (when (org-string-nw-p re)
12150 (setq buffer (if (markerp pos)
12151 (marker-buffer pos)
12152 (or (find-buffer-visiting file)
12153 (find-file-noselect file))))
12154 (with-current-buffer buffer
12155 (org-with-wide-buffer
12156 (goto-char pos)
12157 (beginning-of-line 1)
12158 (unless (looking-at-p re)
12159 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12161 (defun org-refile-new-child (parent-target child)
12162 "Use refile target PARENT-TARGET to add new CHILD below it."
12163 (unless parent-target
12164 (error "Cannot find parent for new node"))
12165 (let ((file (nth 1 parent-target))
12166 (pos (nth 3 parent-target))
12167 level)
12168 (with-current-buffer (or (find-buffer-visiting file)
12169 (find-file-noselect file))
12170 (org-with-wide-buffer
12171 (if pos
12172 (goto-char pos)
12173 (goto-char (point-max))
12174 (unless (bolp) (newline)))
12175 (when (looking-at org-outline-regexp)
12176 (setq level (funcall outline-level))
12177 (org-end-of-subtree t t))
12178 (org-back-over-empty-lines)
12179 (insert "\n" (make-string
12180 (if pos (org-get-valid-level level 1) 1) ?*)
12181 " " child "\n")
12182 (beginning-of-line 0)
12183 (list (concat (car parent-target) "/" child) file "" (point))))))
12185 (defun org-olpath-completing-read (prompt collection &rest args)
12186 "Read an outline path like a file name."
12187 (let ((thetable collection))
12188 (apply #'completing-read
12189 prompt
12190 (lambda (string predicate &optional flag)
12191 (cond
12192 ((eq flag nil) (try-completion string thetable))
12193 ((eq flag t)
12194 (let ((l (length string)))
12195 (mapcar (lambda (x)
12196 (let ((r (substring x l))
12197 (f (if (string-match " ([^)]*)$" x)
12198 (match-string 0 x)
12199 "")))
12200 (if (string-match "/" r)
12201 (concat string (substring r 0 (match-end 0)) f)
12202 x)))
12203 (all-completions string thetable predicate))))
12204 ;; Exact match?
12205 ((eq flag 'lambda) (assoc string thetable))))
12206 args)))
12208 ;;;; Dynamic blocks
12210 (defun org-find-dblock (name)
12211 "Find the first dynamic block with name NAME in the buffer.
12212 If not found, stay at current position and return nil."
12213 (let ((case-fold-search t) pos)
12214 (save-excursion
12215 (goto-char (point-min))
12216 (setq pos (and (re-search-forward
12217 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12218 (match-beginning 0))))
12219 (when pos (goto-char pos))
12220 pos))
12222 (defun org-create-dblock (plist)
12223 "Create a dynamic block section, with parameters taken from PLIST.
12224 PLIST must contain a :name entry which is used as the name of the block."
12225 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12226 (end-of-line 1)
12227 (newline))
12228 (let ((col (current-column))
12229 (name (plist-get plist :name)))
12230 (insert "#+BEGIN: " name)
12231 (while plist
12232 (if (eq (car plist) :name)
12233 (setq plist (cddr plist))
12234 (insert " " (prin1-to-string (pop plist)))))
12235 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12236 (beginning-of-line -2)))
12238 (defun org-prepare-dblock ()
12239 "Prepare dynamic block for refresh.
12240 This empties the block, puts the cursor at the insert position and returns
12241 the property list including an extra property :name with the block name."
12242 (unless (looking-at org-dblock-start-re)
12243 (user-error "Not at a dynamic block"))
12244 (let* ((begdel (1+ (match-end 0)))
12245 (name (org-no-properties (match-string 1)))
12246 (params (append (list :name name)
12247 (read (concat "(" (match-string 3) ")")))))
12248 (save-excursion
12249 (beginning-of-line 1)
12250 (skip-chars-forward " \t")
12251 (setq params (plist-put params :indentation-column (current-column))))
12252 (unless (re-search-forward org-dblock-end-re nil t)
12253 (error "Dynamic block not terminated"))
12254 (setq params
12255 (append params
12256 (list :content (buffer-substring
12257 begdel (match-beginning 0)))))
12258 (delete-region begdel (match-beginning 0))
12259 (goto-char begdel)
12260 (open-line 1)
12261 params))
12263 (defun org-map-dblocks (&optional command)
12264 "Apply COMMAND to all dynamic blocks in the current buffer.
12265 If COMMAND is not given, use `org-update-dblock'."
12266 (let ((cmd (or command 'org-update-dblock)))
12267 (save-excursion
12268 (goto-char (point-min))
12269 (while (re-search-forward org-dblock-start-re nil t)
12270 (goto-char (match-beginning 0))
12271 (save-excursion
12272 (condition-case nil
12273 (funcall cmd)
12274 (error (message "Error during update of dynamic block"))))
12275 (unless (re-search-forward org-dblock-end-re nil t)
12276 (error "Dynamic block not terminated"))))))
12278 (defun org-dblock-update (&optional arg)
12279 "User command for updating dynamic blocks.
12280 Update the dynamic block at point. With prefix ARG, update all dynamic
12281 blocks in the buffer."
12282 (interactive "P")
12283 (if arg
12284 (org-update-all-dblocks)
12285 (or (looking-at org-dblock-start-re)
12286 (org-beginning-of-dblock))
12287 (org-update-dblock)))
12289 (defun org-update-dblock ()
12290 "Update the dynamic block at point.
12291 This means to empty the block, parse for parameters and then call
12292 the correct writing function."
12293 (interactive)
12294 (save-excursion
12295 (let* ((win (selected-window))
12296 (pos (point))
12297 (line (org-current-line))
12298 (params (org-prepare-dblock))
12299 (name (plist-get params :name))
12300 (indent (plist-get params :indentation-column))
12301 (cmd (intern (concat "org-dblock-write:" name))))
12302 (message "Updating dynamic block `%s' at line %d..." name line)
12303 (funcall cmd params)
12304 (message "Updating dynamic block `%s' at line %d...done" name line)
12305 (goto-char pos)
12306 (when (and indent (> indent 0))
12307 (setq indent (make-string indent ?\ ))
12308 (save-excursion
12309 (select-window win)
12310 (org-beginning-of-dblock)
12311 (forward-line 1)
12312 (while (not (looking-at org-dblock-end-re))
12313 (insert indent)
12314 (beginning-of-line 2))
12315 (when (looking-at org-dblock-end-re)
12316 (and (looking-at "[ \t]+")
12317 (replace-match ""))
12318 (insert indent)))))))
12320 (defun org-beginning-of-dblock ()
12321 "Find the beginning of the dynamic block at point.
12322 Error if there is no such block at point."
12323 (let ((pos (point))
12324 beg)
12325 (end-of-line 1)
12326 (if (and (re-search-backward org-dblock-start-re nil t)
12327 (setq beg (match-beginning 0))
12328 (re-search-forward org-dblock-end-re nil t)
12329 (> (match-end 0) pos))
12330 (goto-char beg)
12331 (goto-char pos)
12332 (error "Not in a dynamic block"))))
12334 (defun org-update-all-dblocks ()
12335 "Update all dynamic blocks in the buffer.
12336 This function can be used in a hook."
12337 (interactive)
12338 (when (derived-mode-p 'org-mode)
12339 (org-map-dblocks 'org-update-dblock)))
12342 ;;;; Completion
12344 (declare-function org-export-backend-options "ox" (cl-x) t)
12345 (defun org-get-export-keywords ()
12346 "Return a list of all currently understood export keywords.
12347 Export keywords include options, block names, attributes and
12348 keywords relative to each registered export back-end."
12349 (let (keywords)
12350 (dolist (backend
12351 (bound-and-true-p org-export-registered-backends)
12352 (delq nil keywords))
12353 ;; Back-end name (for keywords, like #+LATEX:)
12354 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12355 (dolist (option-entry (org-export-backend-options backend))
12356 ;; Back-end options.
12357 (push (nth 1 option-entry) keywords)))))
12359 (defconst org-options-keywords
12360 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12361 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12362 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12363 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12364 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12366 (defcustom org-structure-template-alist
12367 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12368 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12369 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12370 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12371 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12372 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12373 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12374 ("L" "#+LaTeX: ")
12375 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12376 ("H" "#+HTML: ")
12377 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12378 ("A" "#+ASCII: ")
12379 ("i" "#+INDEX: ?")
12380 ("I" "#+INCLUDE: %file ?"))
12381 "Structure completion elements.
12382 This is a list of abbreviation keys and values. The value gets inserted
12383 if you type `<' followed by the key and then press the completion key,
12384 usually `TAB'. %file will be replaced by a file name after prompting
12385 for the file using completion. The cursor will be placed at the position
12386 of the `?' in the template.
12387 There are two templates for each key, the first uses the original Org syntax,
12388 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12389 the default when the /org-mtags.el/ module has been loaded. See also the
12390 variable `org-mtags-prefer-muse-templates'."
12391 :group 'org-completion
12392 :type '(repeat
12393 (list
12394 (string :tag "Key")
12395 (string :tag "Template")))
12396 :version "25.1"
12397 :package-version '(Org . "8.3"))
12399 (defun org-try-structure-completion ()
12400 "Try to complete a structure template before point.
12401 This looks for strings like \"<e\" on an otherwise empty line and
12402 expands them."
12403 (let ((l (buffer-substring (point-at-bol) (point)))
12405 (when (and (looking-at "[ \t]*$")
12406 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12407 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12408 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12409 (match-beginning 1)) a)
12410 t)))
12412 (defun org-complete-expand-structure-template (start cell)
12413 "Expand a structure template."
12414 (let ((rpl (nth 1 cell))
12415 (ind ""))
12416 (delete-region start (point))
12417 (when (string-match "\\`[ \t]*#\\+" rpl)
12418 (cond
12419 ((bolp))
12420 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12421 (setq ind (buffer-substring (point-at-bol) (point))))
12422 (t (newline))))
12423 (setq start (point))
12424 (when (string-match "%file" rpl)
12425 (setq rpl (replace-match
12426 (concat
12427 "\""
12428 (save-match-data
12429 (abbreviate-file-name (read-file-name "Include file: ")))
12430 "\"")
12431 t t rpl)))
12432 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12433 (concat "\n" ind)))
12434 (insert rpl)
12435 (when (re-search-backward "\\?" start t) (delete-char 1))))
12437 ;;;; TODO, DEADLINE, Comments
12439 (defun org-toggle-comment ()
12440 "Change the COMMENT state of an entry."
12441 (interactive)
12442 (save-excursion
12443 (org-back-to-heading)
12444 (looking-at org-complex-heading-regexp)
12445 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12446 (skip-chars-forward " \t")
12447 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12448 (if (org-in-commented-heading-p t)
12449 (delete-region (point)
12450 (progn (search-forward " " (line-end-position) 'move)
12451 (skip-chars-forward " \t")
12452 (point)))
12453 (insert org-comment-string)
12454 (unless (eolp) (insert " ")))))
12456 (defvar org-last-todo-state-is-todo nil
12457 "This is non-nil when the last TODO state change led to a TODO state.
12458 If the last change removed the TODO tag or switched to DONE, then
12459 this is nil.")
12461 (defvar org-setting-tags nil) ; dynamically skipped
12463 (defvar org-todo-setup-filter-hook nil
12464 "Hook for functions that pre-filter todo specs.
12465 Each function takes a todo spec and returns either nil or the spec
12466 transformed into canonical form." )
12468 (defvar org-todo-get-default-hook nil
12469 "Hook for functions that get a default item for todo.
12470 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12471 nil or a string to be used for the todo mark." )
12473 (defvar org-agenda-headline-snapshot-before-repeat)
12475 (defun org-current-effective-time ()
12476 "Return current time adjusted for `org-extend-today-until' variable."
12477 (let* ((ct (org-current-time))
12478 (dct (decode-time ct))
12479 (ct1
12480 (cond
12481 (org-use-last-clock-out-time-as-effective-time
12482 (or (org-clock-get-last-clock-out-time) ct))
12483 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12484 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12485 (t ct))))
12486 ct1))
12488 (defun org-todo-yesterday (&optional arg)
12489 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12490 (interactive "P")
12491 (if (eq major-mode 'org-agenda-mode)
12492 (apply 'org-agenda-todo-yesterday arg)
12493 (let* ((org-use-effective-time t)
12494 (hour (nth 2 (decode-time (org-current-time))))
12495 (org-extend-today-until (1+ hour)))
12496 (org-todo arg))))
12498 (defvar org-block-entry-blocking ""
12499 "First entry preventing the TODO state change.")
12501 (defun org-cancel-repeater ()
12502 "Cancel a repeater by setting its numeric value to zero."
12503 (interactive)
12504 (save-excursion
12505 (org-back-to-heading t)
12506 (let ((bound1 (point))
12507 (bound0 (save-excursion (outline-next-heading) (point))))
12508 (when (and (re-search-forward
12509 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12510 org-deadline-time-regexp "\\)\\|\\("
12511 org-ts-regexp "\\)")
12512 bound0 t)
12513 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12514 bound1 t))
12515 (replace-match "0" t nil nil 1)))))
12517 (defvar org-state) ;; dynamically scoped into this function
12518 (defun org-todo (&optional arg)
12519 "Change the TODO state of an item.
12520 The state of an item is given by a keyword at the start of the heading,
12521 like
12522 *** TODO Write paper
12523 *** DONE Call mom
12525 The different keywords are specified in the variable `org-todo-keywords'.
12526 By default the available states are \"TODO\" and \"DONE\".
12527 So for this example: when the item starts with TODO, it is changed to DONE.
12528 When it starts with DONE, the DONE is removed. And when neither TODO nor
12529 DONE are present, add TODO at the beginning of the heading.
12531 With \\[universal-argument] prefix arg, use completion to determine the new \
12532 state.
12533 With numeric prefix arg, switch to that state.
12534 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12535 keywords (nextset).
12536 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12537 With a numeric prefix arg of 0, inhibit note taking for the change.
12538 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12540 When called through ELisp, arg is also interpreted in the following way:
12541 `none' -> empty state
12542 \"\"(empty string) -> switch to empty state
12543 `done' -> switch to DONE
12544 `nextset' -> switch to the next set of keywords
12545 `previousset' -> switch to the previous set of keywords
12546 \"WAITING\" -> switch to the specified keyword, but only if it
12547 really is a member of `org-todo-keywords'."
12548 (interactive "P")
12549 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12550 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12551 'region-start-level 'region))
12552 org-loop-over-headlines-in-active-region)
12553 (org-map-entries
12554 `(org-todo ,arg)
12555 org-loop-over-headlines-in-active-region
12556 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12557 (when (equal arg '(16)) (setq arg 'nextset))
12558 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12559 (let ((org-blocker-hook org-blocker-hook)
12560 commentp
12561 case-fold-search)
12562 (when (equal arg '(64))
12563 (setq arg nil org-blocker-hook nil))
12564 (when (and org-blocker-hook
12565 (or org-inhibit-blocking
12566 (org-entry-get nil "NOBLOCKING")))
12567 (setq org-blocker-hook nil))
12568 (save-excursion
12569 (catch 'exit
12570 (org-back-to-heading t)
12571 (when (org-in-commented-heading-p t)
12572 (org-toggle-comment)
12573 (setq commentp t))
12574 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12575 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12576 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12577 (let* ((match-data (match-data))
12578 (startpos (point-at-bol))
12579 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12580 (org-log-done org-log-done)
12581 (org-log-repeat org-log-repeat)
12582 (org-todo-log-states org-todo-log-states)
12583 (org-inhibit-logging
12584 (if (equal arg 0)
12585 (progn (setq arg nil) 'note) org-inhibit-logging))
12586 (this (match-string 1))
12587 (hl-pos (match-beginning 0))
12588 (head (org-get-todo-sequence-head this))
12589 (ass (assoc head org-todo-kwd-alist))
12590 (interpret (nth 1 ass))
12591 (done-word (nth 3 ass))
12592 (final-done-word (nth 4 ass))
12593 (org-last-state (or this ""))
12594 (completion-ignore-case t)
12595 (member (member this org-todo-keywords-1))
12596 (tail (cdr member))
12597 (org-state (cond
12598 ((and org-todo-key-trigger
12599 (or (and (equal arg '(4))
12600 (eq org-use-fast-todo-selection 'prefix))
12601 (and (not arg) org-use-fast-todo-selection
12602 (not (eq org-use-fast-todo-selection
12603 'prefix)))))
12604 ;; Use fast selection
12605 (org-fast-todo-selection))
12606 ((and (equal arg '(4))
12607 (or (not org-use-fast-todo-selection)
12608 (not org-todo-key-trigger)))
12609 ;; Read a state with completion
12610 (completing-read
12611 "State: " (mapcar #'list org-todo-keywords-1)
12612 nil t))
12613 ((eq arg 'right)
12614 (if this
12615 (if tail (car tail) nil)
12616 (car org-todo-keywords-1)))
12617 ((eq arg 'left)
12618 (unless (equal member org-todo-keywords-1)
12619 (if this
12620 (nth (- (length org-todo-keywords-1)
12621 (length tail) 2)
12622 org-todo-keywords-1)
12623 (org-last org-todo-keywords-1))))
12624 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12625 (setq arg nil))) ; hack to fall back to cycling
12626 (arg
12627 ;; user or caller requests a specific state
12628 (cond
12629 ((equal arg "") nil)
12630 ((eq arg 'none) nil)
12631 ((eq arg 'done) (or done-word (car org-done-keywords)))
12632 ((eq arg 'nextset)
12633 (or (car (cdr (member head org-todo-heads)))
12634 (car org-todo-heads)))
12635 ((eq arg 'previousset)
12636 (let ((org-todo-heads (reverse org-todo-heads)))
12637 (or (car (cdr (member head org-todo-heads)))
12638 (car org-todo-heads))))
12639 ((car (member arg org-todo-keywords-1)))
12640 ((stringp arg)
12641 (user-error "State `%s' not valid in this file" arg))
12642 ((nth (1- (prefix-numeric-value arg))
12643 org-todo-keywords-1))))
12644 ((null member) (or head (car org-todo-keywords-1)))
12645 ((equal this final-done-word) nil) ;; -> make empty
12646 ((null tail) nil) ;; -> first entry
12647 ((memq interpret '(type priority))
12648 (if (eq this-command last-command)
12649 (car tail)
12650 (if (> (length tail) 0)
12651 (or done-word (car org-done-keywords))
12652 nil)))
12654 (car tail))))
12655 (org-state (or
12656 (run-hook-with-args-until-success
12657 'org-todo-get-default-hook org-state org-last-state)
12658 org-state))
12659 (next (if org-state (concat " " org-state " ") " "))
12660 (change-plist (list :type 'todo-state-change :from this :to org-state
12661 :position startpos))
12662 dolog now-done-p)
12663 (when org-blocker-hook
12664 (setq org-last-todo-state-is-todo
12665 (not (member this org-done-keywords)))
12666 (unless (save-excursion
12667 (save-match-data
12668 (org-with-wide-buffer
12669 (run-hook-with-args-until-failure
12670 'org-blocker-hook change-plist))))
12671 (if (called-interactively-p 'interactive)
12672 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12673 this org-state org-block-entry-blocking)
12674 ;; fail silently
12675 (message "TODO state change from %s to %s blocked (by \"%s\")"
12676 this org-state org-block-entry-blocking)
12677 (throw 'exit nil))))
12678 (store-match-data match-data)
12679 (replace-match next t t)
12680 (cond ((equal this org-state)
12681 (message "TODO state was already %s" (org-trim next)))
12682 ((pos-visible-in-window-p hl-pos)
12683 (message "TODO state changed to %s" (org-trim next))))
12684 (unless head
12685 (setq head (org-get-todo-sequence-head org-state)
12686 ass (assoc head org-todo-kwd-alist)
12687 interpret (nth 1 ass)
12688 done-word (nth 3 ass)
12689 final-done-word (nth 4 ass)))
12690 (when (memq arg '(nextset previousset))
12691 (message "Keyword-Set %d/%d: %s"
12692 (- (length org-todo-sets) -1
12693 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12694 (length org-todo-sets)
12695 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12696 (setq org-last-todo-state-is-todo
12697 (not (member org-state org-done-keywords)))
12698 (setq now-done-p (and (member org-state org-done-keywords)
12699 (not (member this org-done-keywords))))
12700 (and logging (org-local-logging logging))
12701 (when (and (or org-todo-log-states org-log-done)
12702 (not (eq org-inhibit-logging t))
12703 (not (memq arg '(nextset previousset))))
12704 ;; we need to look at recording a time and note
12705 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12706 (nth 2 (assoc this org-todo-log-states))))
12707 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12708 (setq dolog 'time))
12709 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12710 (and org-state
12711 (member org-state org-not-done-keywords)
12712 (not (member this org-not-done-keywords))))
12713 ;; This is now a todo state and was not one before
12714 ;; If there was a CLOSED time stamp, get rid of it.
12715 (org-add-planning-info nil nil 'closed))
12716 (when (and now-done-p org-log-done)
12717 ;; It is now done, and it was not done before
12718 (org-add-planning-info 'closed (org-current-effective-time))
12719 (when (and (not dolog) (eq 'note org-log-done))
12720 (org-add-log-setup 'done org-state this 'note)))
12721 (when (and org-state dolog)
12722 ;; This is a non-nil state, and we need to log it
12723 (org-add-log-setup 'state org-state this dolog)))
12724 ;; Fixup tag positioning
12725 (org-todo-trigger-tag-changes org-state)
12726 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12727 (when org-provide-todo-statistics
12728 (org-update-parent-todo-statistics))
12729 (run-hooks 'org-after-todo-state-change-hook)
12730 (when (and arg (not (member org-state org-done-keywords)))
12731 (setq head (org-get-todo-sequence-head org-state)))
12732 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12733 ;; Do we need to trigger a repeat?
12734 (when now-done-p
12735 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12736 ;; This is for the agenda, take a snapshot of the headline.
12737 (save-match-data
12738 (setq org-agenda-headline-snapshot-before-repeat
12739 (org-get-heading))))
12740 (org-auto-repeat-maybe org-state))
12741 ;; Fixup cursor location if close to the keyword
12742 (when (and (outline-on-heading-p)
12743 (not (bolp))
12744 (save-excursion (beginning-of-line 1)
12745 (looking-at org-todo-line-regexp))
12746 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12747 (goto-char (or (match-end 2) (match-end 1)))
12748 (and (looking-at " ") (just-one-space)))
12749 (when org-trigger-hook
12750 (save-excursion
12751 (run-hook-with-args 'org-trigger-hook change-plist)))
12752 (when commentp (org-toggle-comment))))))))
12754 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12755 "Block turning an entry into a TODO, using the hierarchy.
12756 This checks whether the current task should be blocked from state
12757 changes. Such blocking occurs when:
12759 1. The task has children which are not all in a completed state.
12761 2. A task has a parent with the property :ORDERED:, and there
12762 are siblings prior to the current task with incomplete
12763 status.
12765 3. The parent of the task is blocked because it has siblings that should
12766 be done first, or is child of a block grandparent TODO entry."
12768 (if (not org-enforce-todo-dependencies)
12769 t ; if locally turned off don't block
12770 (catch 'dont-block
12771 ;; If this is not a todo state change, or if this entry is already DONE,
12772 ;; do not block
12773 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12774 (member (plist-get change-plist :from)
12775 (cons 'done org-done-keywords))
12776 (member (plist-get change-plist :to)
12777 (cons 'todo org-not-done-keywords))
12778 (not (plist-get change-plist :to)))
12779 (throw 'dont-block t))
12780 ;; If this task has children, and any are undone, it's blocked
12781 (save-excursion
12782 (org-back-to-heading t)
12783 (let ((this-level (funcall outline-level)))
12784 (outline-next-heading)
12785 (let ((child-level (funcall outline-level)))
12786 (while (and (not (eobp))
12787 (> child-level this-level))
12788 ;; this todo has children, check whether they are all
12789 ;; completed
12790 (when (and (not (org-entry-is-done-p))
12791 (org-entry-is-todo-p))
12792 (setq org-block-entry-blocking (org-get-heading))
12793 (throw 'dont-block nil))
12794 (outline-next-heading)
12795 (setq child-level (funcall outline-level))))))
12796 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12797 ;; any previous siblings are undone, it's blocked
12798 (save-excursion
12799 (org-back-to-heading t)
12800 (let* ((pos (point))
12801 (parent-pos (and (org-up-heading-safe) (point))))
12802 (unless parent-pos (throw 'dont-block t)) ; no parent
12803 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12804 (forward-line 1)
12805 (re-search-forward org-not-done-heading-regexp pos t))
12806 (setq org-block-entry-blocking (match-string 0))
12807 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12808 ;; Search further up the hierarchy, to see if an ancestor is blocked
12809 (while t
12810 (goto-char parent-pos)
12811 (unless (looking-at org-not-done-heading-regexp)
12812 (throw 'dont-block t)) ; do not block, parent is not a TODO
12813 (setq pos (point))
12814 (setq parent-pos (and (org-up-heading-safe) (point)))
12815 (unless parent-pos (throw 'dont-block t)) ; no parent
12816 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12817 (forward-line 1)
12818 (re-search-forward org-not-done-heading-regexp pos t)
12819 (setq org-block-entry-blocking (org-get-heading)))
12820 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12822 (defcustom org-track-ordered-property-with-tag nil
12823 "Should the ORDERED property also be shown as a tag?
12824 The ORDERED property decides if an entry should require subtasks to be
12825 completed in sequence. Since a property is not very visible, setting
12826 this option means that toggling the ORDERED property with the command
12827 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12828 not relevant for the behavior, but it makes things more visible.
12830 Note that toggling the tag with tags commands will not change the property
12831 and therefore not influence behavior!
12833 This can be t, meaning the tag ORDERED should be used, It can also be a
12834 string to select a different tag for this task."
12835 :group 'org-todo
12836 :type '(choice
12837 (const :tag "No tracking" nil)
12838 (const :tag "Track with ORDERED tag" t)
12839 (string :tag "Use other tag")))
12841 (defun org-toggle-ordered-property ()
12842 "Toggle the ORDERED property of the current entry.
12843 For better visibility, you can track the value of this property with a tag.
12844 See variable `org-track-ordered-property-with-tag'."
12845 (interactive)
12846 (let* ((t1 org-track-ordered-property-with-tag)
12847 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12848 (save-excursion
12849 (org-back-to-heading)
12850 (if (org-entry-get nil "ORDERED")
12851 (progn
12852 (org-delete-property "ORDERED")
12853 (and tag (org-toggle-tag tag 'off))
12854 (message "Subtasks can be completed in arbitrary order"))
12855 (org-entry-put nil "ORDERED" "t")
12856 (and tag (org-toggle-tag tag 'on))
12857 (message "Subtasks must be completed in sequence")))))
12859 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12860 (defun org-block-todo-from-checkboxes (change-plist)
12861 "Block turning an entry into a TODO, using checkboxes.
12862 This checks whether the current task should be blocked from state
12863 changes because there are unchecked boxes in this entry."
12864 (if (not org-enforce-todo-checkbox-dependencies)
12865 t ; if locally turned off don't block
12866 (catch 'dont-block
12867 ;; If this is not a todo state change, or if this entry is already DONE,
12868 ;; do not block
12869 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12870 (member (plist-get change-plist :from)
12871 (cons 'done org-done-keywords))
12872 (member (plist-get change-plist :to)
12873 (cons 'todo org-not-done-keywords))
12874 (not (plist-get change-plist :to)))
12875 (throw 'dont-block t))
12876 ;; If this task has checkboxes that are not checked, it's blocked
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (let ((beg (point)) end)
12880 (outline-next-heading)
12881 (setq end (point))
12882 (goto-char beg)
12883 (when (org-list-search-forward
12884 (concat (org-item-beginning-re)
12885 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12886 "\\[[- ]\\]")
12887 end t)
12888 (when (boundp 'org-blocked-by-checkboxes)
12889 (setq org-blocked-by-checkboxes t))
12890 (throw 'dont-block nil))))
12891 t))) ; do not block
12893 (defun org-entry-blocked-p ()
12894 "Non-nil if entry at point is blocked."
12895 (and (not (org-entry-get nil "NOBLOCKING"))
12896 (member (org-entry-get nil "TODO") org-not-done-keywords)
12897 (not (run-hook-with-args-until-failure
12898 'org-blocker-hook
12899 (list :type 'todo-state-change
12900 :position (point)
12901 :from 'todo
12902 :to 'done)))))
12904 (defun org-update-statistics-cookies (all)
12905 "Update the statistics cookie, either from TODO or from checkboxes.
12906 This should be called with the cursor in a line with a statistics cookie."
12907 (interactive "P")
12908 (if all
12909 (progn
12910 (org-update-checkbox-count 'all)
12911 (org-map-entries 'org-update-parent-todo-statistics))
12912 (if (not (org-at-heading-p))
12913 (org-update-checkbox-count)
12914 (let ((pos (point-marker))
12915 end l1 l2)
12916 (ignore-errors (org-back-to-heading t))
12917 (if (not (org-at-heading-p))
12918 (org-update-checkbox-count)
12919 (setq l1 (org-outline-level))
12920 (setq end (save-excursion
12921 (outline-next-heading)
12922 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12923 (point)))
12924 (if (and (save-excursion
12925 (re-search-forward
12926 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12927 (not (save-excursion (re-search-forward
12928 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12929 (org-update-checkbox-count)
12930 (if (and l2 (> l2 l1))
12931 (progn
12932 (goto-char end)
12933 (org-update-parent-todo-statistics))
12934 (goto-char pos)
12935 (beginning-of-line 1)
12936 (while (re-search-forward
12937 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12938 (point-at-eol) t)
12939 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12940 (goto-char pos)
12941 (move-marker pos nil)))))
12943 (defvar org-entry-property-inherited-from) ;; defined below
12944 (defun org-update-parent-todo-statistics ()
12945 "Update any statistics cookie in the parent of the current headline.
12946 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12947 the entire subtree and this will travel up the hierarchy and update
12948 statistics everywhere."
12949 (let* ((prop (save-excursion (org-up-heading-safe)
12950 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12951 (recursive (or (not org-hierarchical-todo-statistics)
12952 (and prop (string-match "\\<recursive\\>" prop))))
12953 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12955 (first t)
12956 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12957 level ltoggle l1 new ndel
12958 (cnt-all 0) (cnt-done 0) is-percent kwd
12959 checkbox-beg cookie-present)
12960 (catch 'exit
12961 (save-excursion
12962 (beginning-of-line 1)
12963 (setq ltoggle (funcall outline-level))
12964 ;; Three situations are to consider:
12966 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12967 ;; to the top-level ancestor on the headline;
12969 ;; 2. If parent has "recursive" property, repeat up to the
12970 ;; headline setting that property, taking inheritance into
12971 ;; account;
12973 ;; 3. Else, move up to direct parent and proceed only once.
12974 (while (and (setq level (org-up-heading-safe))
12975 (or recursive first)
12976 (>= (point) lim))
12977 (setq first nil cookie-present nil)
12978 (unless (and level
12979 (not (string-match
12980 "\\<checkbox\\>"
12981 (downcase (or (org-entry-get nil "COOKIE_DATA")
12982 "")))))
12983 (throw 'exit nil))
12984 (while (re-search-forward box-re (point-at-eol) t)
12985 (setq cnt-all 0 cnt-done 0 cookie-present t)
12986 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12987 (save-match-data
12988 (unless (outline-next-heading) (throw 'exit nil))
12989 (while (and (looking-at org-complex-heading-regexp)
12990 (> (setq l1 (length (match-string 1))) level))
12991 (setq kwd (and (or recursive (= l1 ltoggle))
12992 (match-string 2)))
12993 (if (or (eq org-provide-todo-statistics 'all-headlines)
12994 (and (eq org-provide-todo-statistics t)
12995 (or (member kwd org-done-keywords)))
12996 (and (listp org-provide-todo-statistics)
12997 (stringp (car org-provide-todo-statistics))
12998 (or (member kwd org-provide-todo-statistics)
12999 (member kwd org-done-keywords)))
13000 (and (listp org-provide-todo-statistics)
13001 (listp (car org-provide-todo-statistics))
13002 (or (member kwd (car org-provide-todo-statistics))
13003 (and (member kwd org-done-keywords)
13004 (member kwd (cadr org-provide-todo-statistics))))))
13005 (setq cnt-all (1+ cnt-all))
13006 (and (eq org-provide-todo-statistics t)
13008 (setq cnt-all (1+ cnt-all))))
13009 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13010 (member kwd org-done-keywords))
13011 (and (listp org-provide-todo-statistics)
13012 (listp (car org-provide-todo-statistics))
13013 (member kwd org-done-keywords)
13014 (member kwd (cadr org-provide-todo-statistics)))
13015 (and (listp org-provide-todo-statistics)
13016 (stringp (car org-provide-todo-statistics))
13017 (member kwd org-done-keywords)))
13018 (setq cnt-done (1+ cnt-done)))
13019 (outline-next-heading)))
13020 (setq new
13021 (if is-percent
13022 (format "[%d%%]" (floor (* 100.0 cnt-done)
13023 (max 1 cnt-all)))
13024 (format "[%d/%d]" cnt-done cnt-all))
13025 ndel (- (match-end 0) checkbox-beg))
13026 (goto-char checkbox-beg)
13027 (insert new)
13028 (delete-region (point) (+ (point) ndel))
13029 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13030 (when cookie-present
13031 (run-hook-with-args 'org-after-todo-statistics-hook
13032 cnt-done (- cnt-all cnt-done))))))
13033 (run-hooks 'org-todo-statistics-hook)))
13035 (defvar org-after-todo-statistics-hook nil
13036 "Hook that is called after a TODO statistics cookie has been updated.
13037 Each function is called with two arguments: the number of not-done entries
13038 and the number of done entries.
13040 For example, the following function, when added to this hook, will switch
13041 an entry to DONE when all children are done, and back to TODO when new
13042 entries are set to a TODO status. Note that this hook is only called
13043 when there is a statistics cookie in the headline!
13045 \(defun org-summary-todo (n-done n-not-done)
13046 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13047 \(let (org-log-done org-log-states) ; turn off logging
13048 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13051 (defvar org-todo-statistics-hook nil
13052 "Hook that is run whenever Org thinks TODO statistics should be updated.
13053 This hook runs even if there is no statistics cookie present, in which case
13054 `org-after-todo-statistics-hook' would not run.")
13056 (defun org-todo-trigger-tag-changes (state)
13057 "Apply the changes defined in `org-todo-state-tags-triggers'."
13058 (let ((l org-todo-state-tags-triggers)
13059 changes)
13060 (when (or (not state) (equal state ""))
13061 (setq changes (append changes (cdr (assoc "" l)))))
13062 (when (and (stringp state) (> (length state) 0))
13063 (setq changes (append changes (cdr (assoc state l)))))
13064 (when (member state org-not-done-keywords)
13065 (setq changes (append changes (cdr (assq 'todo l)))))
13066 (when (member state org-done-keywords)
13067 (setq changes (append changes (cdr (assq 'done l)))))
13068 (dolist (c changes)
13069 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13071 (defun org-local-logging (value)
13072 "Get logging settings from a property VALUE."
13073 ;; Directly set the variables, they are already local.
13074 (setq org-log-done nil
13075 org-log-repeat nil
13076 org-todo-log-states nil)
13077 (dolist (w (org-split-string value))
13078 (let (a)
13079 (cond
13080 ((setq a (assoc w org-startup-options))
13081 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13082 (set (nth 1 a) (nth 2 a))))
13083 ((setq a (org-extract-log-state-settings w))
13084 (and (member (car a) org-todo-keywords-1)
13085 (push a org-todo-log-states)))))))
13087 (defun org-get-todo-sequence-head (kwd)
13088 "Return the head of the TODO sequence to which KWD belongs.
13089 If KWD is not set, check if there is a text property remembering the
13090 right sequence."
13091 (let (p)
13092 (cond
13093 ((not kwd)
13094 (or (get-text-property (point-at-bol) 'org-todo-head)
13095 (progn
13096 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13097 nil (point-at-eol)))
13098 (get-text-property p 'org-todo-head))))
13099 ((not (member kwd org-todo-keywords-1))
13100 (car org-todo-keywords-1))
13101 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13103 (defun org-fast-todo-selection ()
13104 "Fast TODO keyword selection with single keys.
13105 Returns the new TODO keyword, or nil if no state change should occur."
13106 (let* ((fulltable org-todo-key-alist)
13107 (done-keywords org-done-keywords) ;; needed for the faces.
13108 (maxlen (apply 'max (mapcar
13109 (lambda (x)
13110 (if (stringp (car x)) (string-width (car x)) 0))
13111 fulltable)))
13112 (expert nil)
13113 (fwidth (+ maxlen 3 1 3))
13114 (ncol (/ (- (window-width) 4) fwidth))
13115 tg cnt e c tbl
13116 groups ingroup)
13117 (save-excursion
13118 (save-window-excursion
13119 (if expert
13120 (set-buffer (get-buffer-create " *Org todo*"))
13121 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13122 (erase-buffer)
13123 (setq-local org-done-keywords done-keywords)
13124 (setq tbl fulltable cnt 0)
13125 (while (setq e (pop tbl))
13126 (cond
13127 ((equal e '(:startgroup))
13128 (push '() groups) (setq ingroup t)
13129 (unless (= cnt 0)
13130 (setq cnt 0)
13131 (insert "\n"))
13132 (insert "{ "))
13133 ((equal e '(:endgroup))
13134 (setq ingroup nil cnt 0)
13135 (insert "}\n"))
13136 ((equal e '(:newline))
13137 (unless (= cnt 0)
13138 (setq cnt 0)
13139 (insert "\n")
13140 (setq e (car tbl))
13141 (while (equal (car tbl) '(:newline))
13142 (insert "\n")
13143 (setq tbl (cdr tbl)))))
13145 (setq tg (car e) c (cdr e))
13146 (when ingroup (push tg (car groups)))
13147 (setq tg (org-add-props tg nil 'face
13148 (org-get-todo-face tg)))
13149 (when (and (= cnt 0) (not ingroup)) (insert " "))
13150 (insert "[" c "] " tg (make-string
13151 (- fwidth 4 (length tg)) ?\ ))
13152 (when (= (setq cnt (1+ cnt)) ncol)
13153 (insert "\n")
13154 (when ingroup (insert " "))
13155 (setq cnt 0)))))
13156 (insert "\n")
13157 (goto-char (point-min))
13158 (unless expert (org-fit-window-to-buffer))
13159 (message "[a-z..]:Set [SPC]:clear")
13160 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13161 (cond
13162 ((or (= c ?\C-g)
13163 (and (= c ?q) (not (rassoc c fulltable))))
13164 (setq quit-flag t))
13165 ((= c ?\ ) nil)
13166 ((setq e (rassoc c fulltable) tg (car e))
13168 (t (setq quit-flag t)))))))
13170 (defun org-entry-is-todo-p ()
13171 (member (org-get-todo-state) org-not-done-keywords))
13173 (defun org-entry-is-done-p ()
13174 (member (org-get-todo-state) org-done-keywords))
13176 (defun org-get-todo-state ()
13177 "Return the TODO keyword of the current subtree."
13178 (save-excursion
13179 (org-back-to-heading t)
13180 (and (looking-at org-todo-line-regexp)
13181 (match-end 2)
13182 (match-string 2))))
13184 (defun org-at-date-range-p (&optional inactive-ok)
13185 "Non-nil if point is inside a date range.
13187 When optional argument INACTIVE-OK is non-nil, also consider
13188 inactive time ranges.
13190 When this function returns a non-nil value, match data is set
13191 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13192 on INACTIVE-OK."
13193 (interactive)
13194 (save-excursion
13195 (catch 'exit
13196 (let ((pos (point)))
13197 (skip-chars-backward "^[<\r\n")
13198 (skip-chars-backward "<[")
13199 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13200 (>= (match-end 0) pos)
13201 (throw 'exit t))
13202 (skip-chars-backward "^<[\r\n")
13203 (skip-chars-backward "<[")
13204 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13205 (>= (match-end 0) pos)
13206 (throw 'exit t)))
13207 nil)))
13209 (defun org-get-repeat (&optional tagline)
13210 "Check if there is a deadline/schedule with repeater in this entry."
13211 (save-match-data
13212 (save-excursion
13213 (org-back-to-heading t)
13214 (and (re-search-forward (if tagline
13215 (concat tagline "\\s-*" org-repeat-re)
13216 org-repeat-re)
13217 (org-entry-end-position) t)
13218 (match-string-no-properties 1)))))
13220 (defvar org-last-changed-timestamp)
13221 (defvar org-last-inserted-timestamp)
13222 (defvar org-log-post-message)
13223 (defvar org-log-note-purpose)
13224 (defvar org-log-note-how nil)
13225 (defvar org-log-note-extra)
13226 (defun org-auto-repeat-maybe (done-word)
13227 "Check if the current headline contains a repeated time-stamp.
13229 If yes, set TODO state back to what it was and change the base date
13230 of repeating deadline/scheduled time stamps to new date.
13232 This function is run automatically after each state change to a DONE state."
13233 (let* ((repeat (org-get-repeat))
13234 (aa (assoc org-last-state org-todo-kwd-alist))
13235 (interpret (nth 1 aa))
13236 (head (nth 2 aa))
13237 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13238 (msg "Entry repeats: ")
13239 (org-log-done nil)
13240 (org-todo-log-states nil))
13241 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13242 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13243 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13244 org-todo-repeat-to-state)))
13245 (unless (and to-state (member to-state org-todo-keywords-1))
13246 (setq to-state (if (eq interpret 'type) org-last-state head)))
13247 (org-todo to-state))
13248 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13249 (org-entry-put nil "LAST_REPEAT" (format-time-string
13250 (org-time-stamp-format t t))))
13251 (when org-log-repeat
13252 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13253 (memq 'org-add-log-note post-command-hook))
13254 ;; We are already setup for some record.
13255 (when (eq org-log-repeat 'note)
13256 ;; Make sure we take a note, not only a time stamp.
13257 (setq org-log-note-how 'note))
13258 ;; Set up for taking a record.
13259 (org-add-log-setup 'state
13260 (or done-word (car org-done-keywords))
13261 org-last-state
13262 org-log-repeat)))
13263 (org-back-to-heading t)
13264 (org-add-planning-info nil nil 'closed)
13265 (let ((end (save-excursion (outline-next-heading) (point))))
13266 (while (re-search-forward org-ts-regexp end t)
13267 (when (save-match-data
13268 (or (org-at-planning-p)
13269 (org-at-property-p)
13270 (eq (org-element-type (save-excursion
13271 (backward-char)
13272 (org-element-context)))
13273 'timestamp)))
13274 (let ((type (cond ((match-end 1) org-scheduled-string)
13275 ((match-end 3) org-deadline-string)
13276 (t "Plain:")))
13277 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13278 (cond
13279 ((not
13280 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13281 ;; Time-stamps without a repeater are usually skipped.
13282 ;; However, a SCHEDULED time-stamp without one is
13283 ;; removed, as it is considered as no longer relevant.
13284 (when (equal type org-scheduled-string)
13285 (org-remove-timestamp-with-keyword type)))
13287 (let ((n (string-to-number (match-string 2 ts)))
13288 (what (match-string 3 ts)))
13289 (when (equal what "w") (setq n (* n 7) what "d"))
13290 (when (and (equal what "h")
13291 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13292 ts)))
13293 (user-error
13294 "Cannot repeat in Repeat in %d hour(s) because no hour \
13295 has been set"
13297 ;; Preparation, see if we need to modify the start
13298 ;; date for the change.
13299 (when (match-end 1)
13300 (let ((time (save-match-data (org-time-string-to-time ts))))
13301 (cond
13302 ((equal (match-string 1 ts) ".")
13303 ;; Shift starting date to today
13304 (org-timestamp-change
13305 (- (org-today) (time-to-days time))
13306 'day))
13307 ((equal (match-string 1 ts) "+")
13308 (let ((nshiftmax 10)
13309 (nshift 0))
13310 (while (or (= nshift 0)
13311 (not (time-less-p (current-time) time)))
13312 (when (= (cl-incf nshift) nshiftmax)
13313 (or (y-or-n-p
13314 (format "%d repeater intervals were not \
13315 enough to shift date past today. Continue? "
13316 nshift))
13317 (user-error "Abort")))
13318 (org-timestamp-change n (cdr (assoc what whata)))
13319 (org-at-timestamp-p t)
13320 (setq ts (match-string 1))
13321 (setq time
13322 (save-match-data
13323 (org-time-string-to-time ts)))))
13324 (org-timestamp-change (- n) (cdr (assoc what whata)))
13325 ;; Rematch, so that we have everything in
13326 ;; place for the real shift.
13327 (org-at-timestamp-p t)
13328 (setq ts (match-string 1))
13329 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13330 ts)))))
13331 (save-excursion
13332 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13333 (setq msg
13334 (concat
13335 msg type " " org-last-changed-timestamp " ")))))))))
13336 (setq org-log-post-message msg)
13337 (message "%s" msg))))
13339 (defun org-show-todo-tree (arg)
13340 "Make a compact tree which shows all headlines marked with TODO.
13341 The tree will show the lines where the regexp matches, and all higher
13342 headlines above the match.
13343 With a \\[universal-argument] prefix, prompt for a regexp to match.
13344 With a numeric prefix N, construct a sparse tree for the Nth element
13345 of `org-todo-keywords-1'."
13346 (interactive "P")
13347 (let ((case-fold-search nil)
13348 (kwd-re
13349 (cond ((null arg) org-not-done-regexp)
13350 ((equal arg '(4))
13351 (let ((kwd
13352 (completing-read "Keyword (or KWD1|KWD2|...): "
13353 (mapcar #'list org-todo-keywords-1))))
13354 (concat "\\("
13355 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13356 "\\)\\>")))
13357 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13358 (regexp-quote (nth (1- (prefix-numeric-value arg))
13359 org-todo-keywords-1)))
13360 (t (user-error "Invalid prefix argument: %s" arg)))))
13361 (message "%d TODO entries found"
13362 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13364 (defun org-deadline (arg &optional time)
13365 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13366 With one universal prefix argument, remove any deadline from the item.
13367 With two universal prefix arguments, prompt for a warning delay.
13368 With argument TIME, set the deadline at the corresponding date. TIME
13369 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13370 (interactive "P")
13371 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13372 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13373 'region-start-level 'region))
13374 org-loop-over-headlines-in-active-region)
13375 (org-map-entries
13376 `(org-deadline ',arg ,time)
13377 org-loop-over-headlines-in-active-region
13378 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13379 (let* ((old-date (org-entry-get nil "DEADLINE"))
13380 (old-date-time (when old-date (org-time-string-to-time old-date)))
13381 (repeater (and old-date
13382 (string-match
13383 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13384 old-date)
13385 (match-string 1 old-date))))
13386 (cond
13387 ((equal arg '(4))
13388 (when (and old-date org-log-redeadline)
13389 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13390 (org-remove-timestamp-with-keyword org-deadline-string)
13391 (message "Item no longer has a deadline."))
13392 ((equal arg '(16))
13393 (save-excursion
13394 (org-back-to-heading t)
13395 (if (re-search-forward
13396 org-deadline-time-regexp
13397 (save-excursion (outline-next-heading) (point)) t)
13398 (let* ((rpl0 (match-string 1))
13399 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13400 (replace-match
13401 (concat org-deadline-string
13402 " <" rpl
13403 (format " -%dd"
13404 (abs
13405 (- (time-to-days
13406 (save-match-data
13407 (org-read-date nil t nil "Warn starting from" old-date-time)))
13408 (time-to-days old-date-time))))
13409 ">") t t))
13410 (user-error "No deadline information to update"))))
13412 (org-add-planning-info 'deadline time 'closed)
13413 (when (and old-date
13414 org-log-redeadline
13415 (not (equal old-date org-last-inserted-timestamp)))
13416 (org-add-log-setup
13417 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13418 (when repeater
13419 (save-excursion
13420 (org-back-to-heading t)
13421 (when (re-search-forward (concat org-deadline-string " "
13422 org-last-inserted-timestamp)
13423 (save-excursion
13424 (outline-next-heading) (point)) t)
13425 (goto-char (1- (match-end 0)))
13426 (insert " " repeater)
13427 (setq org-last-inserted-timestamp
13428 (concat (substring org-last-inserted-timestamp 0 -1)
13429 " " repeater
13430 (substring org-last-inserted-timestamp -1))))))
13431 (message "Deadline on %s" org-last-inserted-timestamp))))))
13433 (defun org-schedule (arg &optional time)
13434 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13435 With one universal prefix argument, remove any scheduling date from the item.
13436 With two universal prefix arguments, prompt for a delay cookie.
13437 With argument TIME, scheduled at the corresponding date. TIME can
13438 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13439 (interactive "P")
13440 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13441 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13442 'region-start-level 'region))
13443 org-loop-over-headlines-in-active-region)
13444 (org-map-entries
13445 `(org-schedule ',arg ,time)
13446 org-loop-over-headlines-in-active-region
13447 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13448 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13449 (old-date-time (when old-date (org-time-string-to-time old-date)))
13450 (repeater (and old-date
13451 (string-match
13452 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13453 old-date)
13454 (match-string 1 old-date))))
13455 (cond
13456 ((equal arg '(4))
13457 (progn
13458 (when (and old-date org-log-reschedule)
13459 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13460 (org-remove-timestamp-with-keyword org-scheduled-string)
13461 (message "Item is no longer scheduled.")))
13462 ((equal arg '(16))
13463 (save-excursion
13464 (org-back-to-heading t)
13465 (if (re-search-forward
13466 org-scheduled-time-regexp
13467 (save-excursion (outline-next-heading) (point)) t)
13468 (let* ((rpl0 (match-string 1))
13469 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13470 (replace-match
13471 (concat org-scheduled-string
13472 " <" rpl
13473 (format " -%dd"
13474 (abs
13475 (- (time-to-days
13476 (save-match-data
13477 (org-read-date nil t nil "Delay until" old-date-time)))
13478 (time-to-days old-date-time))))
13479 ">") t t))
13480 (user-error "No scheduled information to update"))))
13482 (org-add-planning-info 'scheduled time 'closed)
13483 (when (and old-date
13484 org-log-reschedule
13485 (not (equal old-date org-last-inserted-timestamp)))
13486 (org-add-log-setup
13487 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13488 (when repeater
13489 (save-excursion
13490 (org-back-to-heading t)
13491 (when (re-search-forward (concat org-scheduled-string " "
13492 org-last-inserted-timestamp)
13493 (save-excursion
13494 (outline-next-heading) (point)) t)
13495 (goto-char (1- (match-end 0)))
13496 (insert " " repeater)
13497 (setq org-last-inserted-timestamp
13498 (concat (substring org-last-inserted-timestamp 0 -1)
13499 " " repeater
13500 (substring org-last-inserted-timestamp -1))))))
13501 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13503 (defun org-get-scheduled-time (pom &optional inherit)
13504 "Get the scheduled time as a time tuple, of a format suitable
13505 for calling org-schedule with, or if there is no scheduling,
13506 returns nil."
13507 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13508 (when time
13509 (apply 'encode-time (org-parse-time-string time)))))
13511 (defun org-get-deadline-time (pom &optional inherit)
13512 "Get the deadline as a time tuple, of a format suitable for
13513 calling org-deadline with, or if there is no scheduling, returns
13514 nil."
13515 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13516 (when time
13517 (apply 'encode-time (org-parse-time-string time)))))
13519 (defun org-remove-timestamp-with-keyword (keyword)
13520 "Remove all time stamps with KEYWORD in the current entry."
13521 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13522 beg)
13523 (save-excursion
13524 (org-back-to-heading t)
13525 (setq beg (point))
13526 (outline-next-heading)
13527 (while (re-search-backward re beg t)
13528 (replace-match "")
13529 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13530 (equal (char-before) ?\ ))
13531 (backward-delete-char 1)
13532 (when (string-match "^[ \t]*$" (buffer-substring
13533 (point-at-bol) (point-at-eol)))
13534 (delete-region (point-at-bol)
13535 (min (point-max) (1+ (point-at-eol))))))))))
13537 (defvar org-time-was-given) ; dynamically scoped parameter
13538 (defvar org-end-time-was-given) ; dynamically scoped parameter
13540 (defun org-at-planning-p ()
13541 "Non-nil when point is on a planning info line."
13542 ;; This is as accurate and faster than `org-element-at-point' since
13543 ;; planning info location is fixed in the section.
13544 (org-with-wide-buffer
13545 (beginning-of-line)
13546 (and (looking-at-p org-planning-line-re)
13547 (eq (point)
13548 (ignore-errors
13549 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13550 (org-back-to-heading t)
13551 (org-with-limited-levels (org-back-to-heading t)))
13552 (line-beginning-position 2))))))
13554 (defun org-add-planning-info (what &optional time &rest remove)
13555 "Insert new timestamp with keyword in the planning line.
13556 WHAT indicates what kind of time stamp to add. It is a symbol
13557 among `closed', `deadline', `scheduled' and nil. TIME indicates
13558 the time to use. If none is given, the user is prompted for
13559 a date. REMOVE indicates what kind of entries to remove. An old
13560 WHAT entry will also be removed."
13561 (let (org-time-was-given org-end-time-was-given default-time default-input)
13562 (catch 'exit
13563 (when (and (memq what '(scheduled deadline))
13564 (or (not time)
13565 (and (stringp time)
13566 (string-match "^[-+]+[0-9]" time))))
13567 ;; Try to get a default date/time from existing timestamp
13568 (save-excursion
13569 (org-back-to-heading t)
13570 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13571 (when (re-search-forward (if (eq what 'scheduled)
13572 org-scheduled-time-regexp
13573 org-deadline-time-regexp)
13574 end t)
13575 (setq ts (match-string 1)
13576 default-time (apply 'encode-time (org-parse-time-string ts))
13577 default-input (and ts (org-get-compact-tod ts)))))))
13578 (when what
13579 (setq time
13580 (if (stringp time)
13581 ;; This is a string (relative or absolute), set
13582 ;; proper date.
13583 (apply #'encode-time
13584 (org-read-date-analyze
13585 time default-time (decode-time default-time)))
13586 ;; If necessary, get the time from the user
13587 (or time (org-read-date nil 'to-time nil nil
13588 default-time default-input)))))
13590 (org-with-wide-buffer
13591 (org-back-to-heading t)
13592 (forward-line)
13593 (unless (bolp) (insert "\n"))
13594 (cond ((looking-at-p org-planning-line-re)
13595 ;; Move to current indentation.
13596 (skip-chars-forward " \t")
13597 ;; Check if we have to remove something.
13598 (dolist (type (if what (cons what remove) remove))
13599 (save-excursion
13600 (when (re-search-forward
13601 (cl-case type
13602 (closed org-closed-time-regexp)
13603 (deadline org-deadline-time-regexp)
13604 (scheduled org-scheduled-time-regexp)
13605 (otherwise
13606 (error "Invalid planning type: %s" type)))
13607 (line-end-position) t)
13608 ;; Delete until next keyword or end of line.
13609 (delete-region
13610 (match-beginning 0)
13611 (if (re-search-forward org-keyword-time-not-clock-regexp
13612 (line-end-position)
13614 (match-beginning 0)
13615 (line-end-position))))))
13616 ;; If there is nothing more to add and no more keyword
13617 ;; is left, remove the line completely.
13618 (if (and (looking-at-p "[ \t]*$") (not what))
13619 (delete-region (line-beginning-position)
13620 (line-beginning-position 2))
13621 ;; If we removed last keyword, do not leave trailing
13622 ;; white space at the end of line.
13623 (let ((p (point)))
13624 (save-excursion
13625 (end-of-line)
13626 (unless (= (skip-chars-backward " \t" p) 0)
13627 (delete-region (point) (line-end-position)))))))
13628 ((not what) (throw 'exit nil)) ; Nothing to do.
13629 (t (insert-before-markers "\n")
13630 (backward-char 1)
13631 (when org-adapt-indentation
13632 (indent-to-column (1+ (org-outline-level))))))
13633 (when what
13634 ;; Insert planning keyword.
13635 (insert (cl-case what
13636 (closed org-closed-string)
13637 (deadline org-deadline-string)
13638 (scheduled org-scheduled-string)
13639 (otherwise (error "Invalid planning type: %s" what)))
13640 " ")
13641 ;; Insert associated timestamp.
13642 (let ((ts (org-insert-time-stamp
13643 time
13644 (or org-time-was-given
13645 (and (eq what 'closed) org-log-done-with-time))
13646 (eq what 'closed)
13647 nil nil (list org-end-time-was-given))))
13648 (unless (eolp) (insert " "))
13649 ts))))))
13651 (defvar org-log-note-marker (make-marker)
13652 "Marker pointing at the entry where the note is to be inserted.")
13653 (defvar org-log-note-purpose nil)
13654 (defvar org-log-note-state nil)
13655 (defvar org-log-note-previous-state nil)
13656 (defvar org-log-note-extra nil)
13657 (defvar org-log-note-window-configuration nil)
13658 (defvar org-log-note-return-to (make-marker))
13659 (defvar org-log-note-effective-time nil
13660 "Remembered current time so that dynamically scoped
13661 `org-extend-today-until' affects timestamps in state change log")
13663 (defvar org-log-post-message nil
13664 "Message to be displayed after a log note has been stored.
13665 The auto-repeater uses this.")
13667 (defun org-add-note ()
13668 "Add a note to the current entry.
13669 This is done in the same way as adding a state change note."
13670 (interactive)
13671 (org-add-log-setup 'note))
13673 (defun org-log-beginning (&optional create)
13674 "Return expected start of log notes in current entry.
13675 When optional argument CREATE is non-nil, the function creates
13676 a drawer to store notes, if necessary. Returned position ignores
13677 narrowing."
13678 (org-with-wide-buffer
13679 (let ((drawer (org-log-into-drawer)))
13680 (cond
13681 (drawer
13682 (org-end-of-meta-data)
13683 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13684 (end (if (org-at-heading-p) (point)
13685 (save-excursion (outline-next-heading) (point))))
13686 (case-fold-search t))
13687 (catch 'exit
13688 ;; Try to find existing drawer.
13689 (while (re-search-forward regexp end t)
13690 (let ((element (org-element-at-point)))
13691 (when (eq (org-element-type element) 'drawer)
13692 (let ((cend (org-element-property :contents-end element)))
13693 (when (and (not org-log-states-order-reversed) cend)
13694 (goto-char cend)))
13695 (throw 'exit nil))))
13696 ;; No drawer found. Create one, if permitted.
13697 (when create
13698 (unless (bolp) (insert "\n"))
13699 (let ((beg (point)))
13700 (insert ":" drawer ":\n:END:\n")
13701 (org-indent-region beg (point)))
13702 (end-of-line -1)))))
13704 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13705 (skip-chars-forward " \t\n")
13706 (beginning-of-line)
13707 (unless org-log-states-order-reversed
13708 (org-skip-over-state-notes)
13709 (skip-chars-backward " \t\n")
13710 (forward-line)))))
13711 (if (bolp) (point) (line-beginning-position 2))))
13713 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13714 "Set up the post command hook to take a note.
13715 If this is about to TODO state change, the new state is expected in STATE.
13716 HOW is an indicator what kind of note should be created.
13717 EXTRA is additional text that will be inserted into the notes buffer."
13718 (move-marker org-log-note-marker (point))
13719 (setq org-log-note-purpose purpose
13720 org-log-note-state state
13721 org-log-note-previous-state prev-state
13722 org-log-note-how how
13723 org-log-note-extra extra
13724 org-log-note-effective-time (org-current-effective-time))
13725 (add-hook 'post-command-hook 'org-add-log-note 'append))
13727 (defun org-skip-over-state-notes ()
13728 "Skip past the list of State notes in an entry."
13729 (when (ignore-errors (goto-char (org-in-item-p)))
13730 (let* ((struct (org-list-struct))
13731 (prevs (org-list-prevs-alist struct))
13732 (regexp
13733 (concat "[ \t]*- +"
13734 (replace-regexp-in-string
13735 " +" " +"
13736 (org-replace-escapes
13737 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13738 `(("%d" . ,org-ts-regexp-inactive)
13739 ("%D" . ,org-ts-regexp)
13740 ("%s" . "\"\\S-+\"")
13741 ("%S" . "\"\\S-+\"")
13742 ("%t" . ,org-ts-regexp-inactive)
13743 ("%T" . ,org-ts-regexp)
13744 ("%u" . ".*?")
13745 ("%U" . ".*?")))))))
13746 (while (looking-at-p regexp)
13747 (goto-char (or (org-list-get-next-item (point) struct prevs)
13748 (org-list-get-item-end (point) struct)))))))
13750 (defun org-add-log-note (&optional _purpose)
13751 "Pop up a window for taking a note, and add this note later."
13752 (remove-hook 'post-command-hook 'org-add-log-note)
13753 (setq org-log-note-window-configuration (current-window-configuration))
13754 (delete-other-windows)
13755 (move-marker org-log-note-return-to (point))
13756 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13757 (goto-char org-log-note-marker)
13758 (org-switch-to-buffer-other-window "*Org Note*")
13759 (erase-buffer)
13760 (if (memq org-log-note-how '(time state))
13761 (let (current-prefix-arg) (org-store-log-note))
13762 (let ((org-inhibit-startup t)) (org-mode))
13763 (insert (format "# Insert note for %s.
13764 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13765 (cond
13766 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13767 ((eq org-log-note-purpose 'done) "closed todo item")
13768 ((eq org-log-note-purpose 'state)
13769 (format "state change from \"%s\" to \"%s\""
13770 (or org-log-note-previous-state "")
13771 (or org-log-note-state "")))
13772 ((eq org-log-note-purpose 'reschedule)
13773 "rescheduling")
13774 ((eq org-log-note-purpose 'delschedule)
13775 "no longer scheduled")
13776 ((eq org-log-note-purpose 'redeadline)
13777 "changing deadline")
13778 ((eq org-log-note-purpose 'deldeadline)
13779 "removing deadline")
13780 ((eq org-log-note-purpose 'refile)
13781 "refiling")
13782 ((eq org-log-note-purpose 'note)
13783 "this entry")
13784 (t (error "This should not happen")))))
13785 (when org-log-note-extra (insert org-log-note-extra))
13786 (setq-local org-finish-function 'org-store-log-note)
13787 (run-hooks 'org-log-buffer-setup-hook)))
13789 (defvar org-note-abort nil) ; dynamically scoped
13790 (defun org-store-log-note ()
13791 "Finish taking a log note, and insert it to where it belongs."
13792 (let ((txt (prog1 (buffer-string)
13793 (kill-buffer)))
13794 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13795 lines)
13796 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13797 (setq txt (replace-match "" t t txt)))
13798 (when (string-match "\\s-+\\'" txt)
13799 (setq txt (replace-match "" t t txt)))
13800 (setq lines (org-split-string txt "\n"))
13801 (when (org-string-nw-p note)
13802 (setq note
13803 (org-replace-escapes
13804 note
13805 (list (cons "%u" (user-login-name))
13806 (cons "%U" user-full-name)
13807 (cons "%t" (format-time-string
13808 (org-time-stamp-format 'long 'inactive)
13809 org-log-note-effective-time))
13810 (cons "%T" (format-time-string
13811 (org-time-stamp-format 'long nil)
13812 org-log-note-effective-time))
13813 (cons "%d" (format-time-string
13814 (org-time-stamp-format nil 'inactive)
13815 org-log-note-effective-time))
13816 (cons "%D" (format-time-string
13817 (org-time-stamp-format nil nil)
13818 org-log-note-effective-time))
13819 (cons "%s" (cond
13820 ((not org-log-note-state) "")
13821 ((string-match-p org-ts-regexp
13822 org-log-note-state)
13823 (format "\"[%s]\""
13824 (substring org-log-note-state 1 -1)))
13825 (t (format "\"%s\"" org-log-note-state))))
13826 (cons "%S"
13827 (cond
13828 ((not org-log-note-previous-state) "")
13829 ((string-match-p org-ts-regexp
13830 org-log-note-previous-state)
13831 (format "\"[%s]\""
13832 (substring
13833 org-log-note-previous-state 1 -1)))
13834 (t (format "\"%s\""
13835 org-log-note-previous-state)))))))
13836 (when lines (setq note (concat note " \\\\")))
13837 (push note lines))
13838 (when (and lines (not (or current-prefix-arg org-note-abort)))
13839 (with-current-buffer (marker-buffer org-log-note-marker)
13840 (org-with-wide-buffer
13841 ;; Find location for the new note.
13842 (goto-char org-log-note-marker)
13843 (set-marker org-log-note-marker nil)
13844 (goto-char (org-log-beginning t))
13845 ;; Make sure point is at the beginning of an empty line.
13846 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13847 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13848 ;; In an existing list, add a new item at the top level.
13849 ;; Otherwise, indent line like a regular one.
13850 (let ((itemp (org-in-item-p)))
13851 (if itemp
13852 (indent-line-to
13853 (let ((struct (save-excursion
13854 (goto-char itemp) (org-list-struct))))
13855 (org-list-get-ind (org-list-get-top-point struct) struct)))
13856 (org-indent-line)))
13857 (insert (org-list-bullet-string "-") (pop lines))
13858 (let ((ind (org-list-item-body-column (line-beginning-position))))
13859 (dolist (line lines)
13860 (insert "\n")
13861 (indent-line-to ind)
13862 (insert line)))
13863 (message "Note stored")
13864 (org-back-to-heading t)
13865 (org-cycle-hide-drawers 'children))
13866 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13867 ;; from within `org-add-log-note' because `buffer-undo-list'
13868 ;; is then modified outside of `org-with-remote-undo'.
13869 (when (eq this-command 'org-agenda-todo)
13870 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13871 ;; Don't add undo information when called from `org-agenda-todo'.
13872 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13873 (set-window-configuration org-log-note-window-configuration)
13874 (with-current-buffer (marker-buffer org-log-note-return-to)
13875 (goto-char org-log-note-return-to))
13876 (move-marker org-log-note-return-to nil)
13877 (when org-log-post-message (message "%s" org-log-post-message))))
13879 (defun org-remove-empty-drawer-at (pos)
13880 "Remove an empty drawer at position POS.
13881 POS may also be a marker."
13882 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13883 (org-with-wide-buffer
13884 (goto-char pos)
13885 (let ((drawer (org-element-at-point)))
13886 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13887 (not (org-element-property :contents-begin drawer)))
13888 (delete-region (org-element-property :begin drawer)
13889 (progn (goto-char (org-element-property :end drawer))
13890 (skip-chars-backward " \r\t\n")
13891 (forward-line)
13892 (point))))))))
13894 (defvar org-ts-type nil)
13895 (defun org-sparse-tree (&optional arg type)
13896 "Create a sparse tree, prompt for the details.
13897 This command can create sparse trees. You first need to select the type
13898 of match used to create the tree:
13900 t Show all TODO entries.
13901 T Show entries with a specific TODO keyword.
13902 m Show entries selected by a tags/property match.
13903 p Enter a property name and its value (both with completion on existing
13904 names/values) and show entries with that property.
13905 r Show entries matching a regular expression (`/' can be used as well).
13906 b Show deadlines and scheduled items before a date.
13907 a Show deadlines and scheduled items after a date.
13908 d Show deadlines due within `org-deadline-warning-days'.
13909 D Show deadlines and scheduled items between a date range."
13910 (interactive "P")
13911 (setq type (or type org-sparse-tree-default-date-type))
13912 (setq org-ts-type type)
13913 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13914 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13915 \[c]ycle through date types: %s"
13916 (cl-case type
13917 (all "all timestamps")
13918 (scheduled "only scheduled")
13919 (deadline "only deadline")
13920 (active "only active timestamps")
13921 (inactive "only inactive timestamps")
13922 (closed "with a closed time-stamp")
13923 (otherwise "scheduled/deadline")))
13924 (let ((answer (read-char-exclusive)))
13925 (cl-case answer
13927 (org-sparse-tree
13929 (cadr
13930 (memq type '(nil all scheduled deadline active inactive closed)))))
13931 (?d (call-interactively 'org-check-deadlines))
13932 (?b (call-interactively 'org-check-before-date))
13933 (?a (call-interactively 'org-check-after-date))
13934 (?D (call-interactively 'org-check-dates-range))
13935 (?t (call-interactively 'org-show-todo-tree))
13936 (?T (org-show-todo-tree '(4)))
13937 (?m (call-interactively 'org-match-sparse-tree))
13938 ((?p ?P)
13939 (let* ((kwd (completing-read
13940 "Property: " (mapcar #'list (org-buffer-property-keys))))
13941 (value (completing-read
13942 "Value: " (mapcar #'list (org-property-values kwd)))))
13943 (unless (string-match "\\`{.*}\\'" value)
13944 (setq value (concat "\"" value "\"")))
13945 (org-match-sparse-tree arg (concat kwd "=" value))))
13946 ((?r ?R ?/) (call-interactively 'org-occur))
13947 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13949 (defvar-local org-occur-highlights nil
13950 "List of overlays used for occur matches.")
13951 (defvar-local org-occur-parameters nil
13952 "Parameters of the active org-occur calls.
13953 This is a list, each call to org-occur pushes as cons cell,
13954 containing the regular expression and the callback, onto the list.
13955 The list can contain several entries if `org-occur' has been called
13956 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13957 will only contain one set of parameters. When the highlights are
13958 removed (for example with `C-c C-c', or with the next edit (depending
13959 on `org-remove-highlights-with-change'), this variable is emptied
13960 as well.")
13962 (defun org-occur (regexp &optional keep-previous callback)
13963 "Make a compact tree which shows all matches of REGEXP.
13965 The tree will show the lines where the regexp matches, and any other context
13966 defined in `org-show-context-detail', which see.
13968 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13969 done by a previous call to `org-occur' will be kept, to allow stacking of
13970 calls to this command.
13972 Optional argument CALLBACK can be a function of no argument. In this case,
13973 it is called with point at the end of the match, match data being set
13974 accordingly. Current match is shown only if the return value is non-nil.
13975 The function must neither move point nor alter narrowing."
13976 (interactive "sRegexp: \nP")
13977 (when (equal regexp "")
13978 (user-error "Regexp cannot be empty"))
13979 (unless keep-previous
13980 (org-remove-occur-highlights nil nil t))
13981 (push (cons regexp callback) org-occur-parameters)
13982 (let ((cnt 0))
13983 (save-excursion
13984 (goto-char (point-min))
13985 (when (or (not keep-previous) ; do not want to keep
13986 (not org-occur-highlights)) ; no previous matches
13987 ;; hide everything
13988 (org-overview))
13989 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13990 (isearch-no-upper-case-p regexp t)
13991 org-occur-case-fold-search)))
13992 (while (re-search-forward regexp nil t)
13993 (when (or (not callback)
13994 (save-match-data (funcall callback)))
13995 (setq cnt (1+ cnt))
13996 (when org-highlight-sparse-tree-matches
13997 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13998 (org-show-context 'occur-tree)))))
13999 (when org-remove-highlights-with-change
14000 (add-hook 'before-change-functions 'org-remove-occur-highlights
14001 nil 'local))
14002 (unless org-sparse-tree-open-archived-trees
14003 (org-hide-archived-subtrees (point-min) (point-max)))
14004 (run-hooks 'org-occur-hook)
14005 (when (called-interactively-p 'interactive)
14006 (message "%d match(es) for regexp %s" cnt regexp))
14007 cnt))
14009 (defun org-occur-next-match (&optional n _reset)
14010 "Function for `next-error-function' to find sparse tree matches.
14011 N is the number of matches to move, when negative move backwards.
14012 This function always goes back to the starting point when no
14013 match is found."
14014 (let* ((limit (if (< n 0) (point-min) (point-max)))
14015 (search-func (if (< n 0)
14016 'previous-single-char-property-change
14017 'next-single-char-property-change))
14018 (n (abs n))
14019 (pos (point))
14021 (catch 'exit
14022 (while (setq p1 (funcall search-func (point) 'org-type))
14023 (when (equal p1 limit)
14024 (goto-char pos)
14025 (user-error "No more matches"))
14026 (when (equal (get-char-property p1 'org-type) 'org-occur)
14027 (setq n (1- n))
14028 (when (= n 0)
14029 (goto-char p1)
14030 (throw 'exit (point))))
14031 (goto-char p1))
14032 (goto-char p1)
14033 (user-error "No more matches"))))
14035 (defun org-show-context (&optional key)
14036 "Make sure point and context are visible.
14037 Optional argument KEY, when non-nil, is a symbol. See
14038 `org-show-context-detail' for allowed values and how much is to
14039 be shown."
14040 (org-show-set-visibility
14041 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14042 ((cdr (assq key org-show-context-detail)))
14043 (t (cdr (assq 'default org-show-context-detail))))))
14045 (defun org-show-set-visibility (detail)
14046 "Set visibility around point according to DETAIL.
14047 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14048 `tree', `canonical' or t. See `org-show-context-detail' for more
14049 information."
14050 ;; Show current heading and possibly its entry, following headline
14051 ;; or all children.
14052 (if (and (org-at-heading-p) (not (eq detail 'local)))
14053 (org-flag-heading nil)
14054 (org-show-entry)
14055 ;; If point is hidden within a drawer or a block, make sure to
14056 ;; expose it.
14057 (dolist (o (overlays-at (point)))
14058 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14059 (delete-overlay o)))
14060 (unless (org-before-first-heading-p)
14061 (org-with-limited-levels
14062 (cl-case detail
14063 ((tree canonical t) (org-show-children))
14064 ((nil minimal ancestors))
14065 (t (save-excursion
14066 (outline-next-heading)
14067 (org-flag-heading nil)))))))
14068 ;; Show all siblings.
14069 (when (eq detail 'lineage) (org-show-siblings))
14070 ;; Show ancestors, possibly with their children.
14071 (when (memq detail '(ancestors lineage tree canonical t))
14072 (save-excursion
14073 (while (org-up-heading-safe)
14074 (org-flag-heading nil)
14075 (when (memq detail '(canonical t)) (org-show-entry))
14076 (when (memq detail '(tree canonical t)) (org-show-children))))))
14078 (defvar org-reveal-start-hook nil
14079 "Hook run before revealing a location.")
14081 (defun org-reveal (&optional siblings)
14082 "Show current entry, hierarchy above it, and the following headline.
14084 This can be used to show a consistent set of context around
14085 locations exposed with `org-show-context'.
14087 With optional argument SIBLINGS, on each level of the hierarchy all
14088 siblings are shown. This repairs the tree structure to what it would
14089 look like when opened with hierarchical calls to `org-cycle'.
14091 With double optional argument \\[universal-argument] \\[universal-argument], \
14092 go to the parent and show the
14093 entire tree."
14094 (interactive "P")
14095 (run-hooks 'org-reveal-start-hook)
14096 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14097 ((equal siblings '(16))
14098 (save-excursion
14099 (when (org-up-heading-safe)
14100 (org-show-subtree)
14101 (run-hook-with-args 'org-cycle-hook 'subtree))))
14102 (t (org-show-set-visibility 'lineage))))
14104 (defun org-highlight-new-match (beg end)
14105 "Highlight from BEG to END and mark the highlight is an occur headline."
14106 (let ((ov (make-overlay beg end)))
14107 (overlay-put ov 'face 'secondary-selection)
14108 (overlay-put ov 'org-type 'org-occur)
14109 (push ov org-occur-highlights)))
14111 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14112 "Remove the occur highlights from the buffer.
14113 BEG and END are ignored. If NOREMOVE is nil, remove this function
14114 from the `before-change-functions' in the current buffer."
14115 (interactive)
14116 (unless org-inhibit-highlight-removal
14117 (mapc #'delete-overlay org-occur-highlights)
14118 (setq org-occur-highlights nil)
14119 (setq org-occur-parameters nil)
14120 (unless noremove
14121 (remove-hook 'before-change-functions
14122 'org-remove-occur-highlights 'local))))
14124 ;;;; Priorities
14126 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14127 "Regular expression matching the priority indicator.")
14129 (defvar org-remove-priority-next-time nil)
14131 (defun org-priority-up ()
14132 "Increase the priority of the current item."
14133 (interactive)
14134 (org-priority 'up))
14136 (defun org-priority-down ()
14137 "Decrease the priority of the current item."
14138 (interactive)
14139 (org-priority 'down))
14141 (defun org-priority (&optional action _show)
14142 "Change the priority of an item.
14143 ACTION can be `set', `up', `down', or a character."
14144 (interactive "P")
14145 (if (equal action '(4))
14146 (org-show-priority)
14147 (unless org-enable-priority-commands
14148 (user-error "Priority commands are disabled"))
14149 (setq action (or action 'set))
14150 (let (current new news have remove)
14151 (save-excursion
14152 (org-back-to-heading t)
14153 (when (looking-at org-priority-regexp)
14154 (setq current (string-to-char (match-string 2))
14155 have t))
14156 (cond
14157 ((eq action 'remove)
14158 (setq remove t new ?\ ))
14159 ((or (eq action 'set)
14160 (integerp action))
14161 (if (not (eq action 'set))
14162 (setq new action)
14163 (message "Priority %c-%c, SPC to remove: "
14164 org-highest-priority org-lowest-priority)
14165 (save-match-data
14166 (setq new (read-char-exclusive))))
14167 (when (and (= (upcase org-highest-priority) org-highest-priority)
14168 (= (upcase org-lowest-priority) org-lowest-priority))
14169 (setq new (upcase new)))
14170 (cond ((equal new ?\ ) (setq remove t))
14171 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14172 (user-error "Priority must be between `%c' and `%c'"
14173 org-highest-priority org-lowest-priority))))
14174 ((eq action 'up)
14175 (setq new (if have
14176 (1- current) ; normal cycling
14177 ;; last priority was empty
14178 (if (eq last-command this-command)
14179 org-lowest-priority ; wrap around empty to lowest
14180 ;; default
14181 (if org-priority-start-cycle-with-default
14182 org-default-priority
14183 (1- org-default-priority))))))
14184 ((eq action 'down)
14185 (setq new (if have
14186 (1+ current) ; normal cycling
14187 ;; last priority was empty
14188 (if (eq last-command this-command)
14189 org-highest-priority ; wrap around empty to highest
14190 ;; default
14191 (if org-priority-start-cycle-with-default
14192 org-default-priority
14193 (1+ org-default-priority))))))
14194 (t (user-error "Invalid action")))
14195 (when (or (< (upcase new) org-highest-priority)
14196 (> (upcase new) org-lowest-priority))
14197 (if (and (memq action '(up down))
14198 (not have) (not (eq last-command this-command)))
14199 ;; `new' is from default priority
14200 (error
14201 "The default can not be set, see `org-default-priority' why")
14202 ;; normal cycling: `new' is beyond highest/lowest priority
14203 ;; and is wrapped around to the empty priority
14204 (setq remove t)))
14205 (setq news (format "%c" new))
14206 (if have
14207 (if remove
14208 (replace-match "" t t nil 1)
14209 (replace-match news t t nil 2))
14210 (if remove
14211 (user-error "No priority cookie found in line")
14212 (let ((case-fold-search nil))
14213 (looking-at org-todo-line-regexp))
14214 (if (match-end 2)
14215 (progn
14216 (goto-char (match-end 2))
14217 (insert " [#" news "]"))
14218 (goto-char (match-beginning 3))
14219 (insert "[#" news "] "))))
14220 (org-set-tags nil 'align))
14221 (if remove
14222 (message "Priority removed")
14223 (message "Priority of current item set to %s" news)))))
14225 (defun org-show-priority ()
14226 "Show the priority of the current item.
14227 This priority is composed of the main priority given with the [#A] cookies,
14228 and by additional input from the age of a schedules or deadline entry."
14229 (interactive)
14230 (let ((pri (if (eq major-mode 'org-agenda-mode)
14231 (org-get-at-bol 'priority)
14232 (save-excursion
14233 (save-match-data
14234 (beginning-of-line)
14235 (and (looking-at org-heading-regexp)
14236 (org-get-priority (match-string 0))))))))
14237 (message "Priority is %d" (if pri pri -1000))))
14239 (defun org-get-priority (s)
14240 "Find priority cookie and return priority."
14241 (save-match-data
14242 (if (functionp org-get-priority-function)
14243 (funcall org-get-priority-function)
14244 (if (not (string-match org-priority-regexp s))
14245 (* 1000 (- org-lowest-priority org-default-priority))
14246 (* 1000 (- org-lowest-priority
14247 (string-to-char (match-string 2 s))))))))
14249 ;;;; Tags
14251 (defvar org-agenda-archives-mode)
14252 (defvar org-map-continue-from nil
14253 "Position from where mapping should continue.
14254 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14256 (defvar org-scanner-tags nil
14257 "The current tag list while the tags scanner is running.")
14259 (defvar org-trust-scanner-tags nil
14260 "Should `org-get-tags-at' use the tags for the scanner.
14261 This is for internal dynamical scoping only.
14262 When this is non-nil, the function `org-get-tags-at' will return the value
14263 of `org-scanner-tags' instead of building the list by itself. This
14264 can lead to large speed-ups when the tags scanner is used in a file with
14265 many entries, and when the list of tags is retrieved, for example to
14266 obtain a list of properties. Building the tags list for each entry in such
14267 a file becomes an N^2 operation - but with this variable set, it scales
14268 as N.")
14270 (defvar org--matcher-tags-todo-only nil)
14272 (defun org-scan-tags (action matcher todo-only &optional start-level)
14273 "Scan headline tags with inheritance and produce output ACTION.
14275 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14276 or `agenda' to produce an entry list for an agenda view. It can also be
14277 a Lisp form or a function that should be called at each matched headline, in
14278 this case the return value is a list of all return values from these calls.
14280 MATCHER is a function accepting three arguments, returning
14281 a non-nil value whenever a given set of tags qualifies a headline
14282 for inclusion. See `org-make-tags-matcher' for more information.
14283 As a special case, it can also be set to t (respectively nil) in
14284 order to match all (respectively none) headline.
14286 When TODO-ONLY is non-nil, only lines with a not-done TODO
14287 keyword are included in the output.
14289 START-LEVEL can be a string with asterisks, reducing the scope to
14290 headlines matching this string."
14291 (require 'org-agenda)
14292 (let* ((re (concat "^"
14293 (if start-level
14294 ;; Get the correct level to match
14295 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14296 org-outline-regexp)
14297 " *\\(\\<\\("
14298 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14299 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14300 (props (list 'face 'default
14301 'done-face 'org-agenda-done
14302 'undone-face 'default
14303 'mouse-face 'highlight
14304 'org-not-done-regexp org-not-done-regexp
14305 'org-todo-regexp org-todo-regexp
14306 'org-complex-heading-regexp org-complex-heading-regexp
14307 'help-echo
14308 (format "mouse-2 or RET jump to org file %s"
14309 (abbreviate-file-name
14310 (or (buffer-file-name (buffer-base-buffer))
14311 (buffer-name (buffer-base-buffer)))))))
14312 (org-map-continue-from nil)
14313 lspos tags tags-list
14314 (tags-alist (list (cons 0 org-file-tags)))
14315 (llast 0) rtn rtn1 level category i txt
14316 todo marker entry priority
14317 ts-date ts-date-type ts-date-pair)
14318 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14319 (setq action (list 'lambda nil action)))
14320 (save-excursion
14321 (goto-char (point-min))
14322 (when (eq action 'sparse-tree)
14323 (org-overview)
14324 (org-remove-occur-highlights))
14325 (while (let (case-fold-search)
14326 (re-search-forward re nil t))
14327 (setq org-map-continue-from nil)
14328 (catch :skip
14329 (setq todo
14330 ;; TODO: is the 1-2 difference a bug?
14331 (when (match-end 1) (match-string-no-properties 2))
14332 tags (when (match-end 4) (match-string-no-properties 4)))
14333 (goto-char (setq lspos (match-beginning 0)))
14334 (setq level (org-reduced-level (org-outline-level))
14335 category (org-get-category))
14336 (when (eq action 'agenda)
14337 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14338 ts-date (car ts-date-pair)
14339 ts-date-type (cdr ts-date-pair)))
14340 (setq i llast llast level)
14341 ;; remove tag lists from same and sublevels
14342 (while (>= i level)
14343 (when (setq entry (assoc i tags-alist))
14344 (setq tags-alist (delete entry tags-alist)))
14345 (setq i (1- i)))
14346 ;; add the next tags
14347 (when tags
14348 (setq tags (org-split-string tags ":")
14349 tags-alist
14350 (cons (cons level tags) tags-alist)))
14351 ;; compile tags for current headline
14352 (setq tags-list
14353 (if org-use-tag-inheritance
14354 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14355 tags)
14356 org-scanner-tags tags-list)
14357 (when org-use-tag-inheritance
14358 (setcdr (car tags-alist)
14359 (mapcar (lambda (x)
14360 (setq x (copy-sequence x))
14361 (org-add-prop-inherited x))
14362 (cdar tags-alist))))
14363 (when (and tags org-use-tag-inheritance
14364 (or (not (eq t org-use-tag-inheritance))
14365 org-tags-exclude-from-inheritance))
14366 ;; Selective inheritance, remove uninherited ones.
14367 (setcdr (car tags-alist)
14368 (org-remove-uninherited-tags (cdar tags-alist))))
14369 (when (and
14371 ;; eval matcher only when the todo condition is OK
14372 (and (or (not todo-only) (member todo org-not-done-keywords))
14373 (if (functionp matcher)
14374 (let ((case-fold-search t) (org-trust-scanner-tags t))
14375 (funcall matcher todo tags-list level))
14376 matcher))
14378 ;; Call the skipper, but return t if it does not
14379 ;; skip, so that the `and' form continues evaluating.
14380 (progn
14381 (unless (eq action 'sparse-tree) (org-agenda-skip))
14384 ;; Check if timestamps are deselecting this entry
14385 (or (not todo-only)
14386 (and (member todo org-not-done-keywords)
14387 (or (not org-agenda-tags-todo-honor-ignore-options)
14388 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14390 ;; select this headline
14391 (cond
14392 ((eq action 'sparse-tree)
14393 (and org-highlight-sparse-tree-matches
14394 (org-get-heading) (match-end 0)
14395 (org-highlight-new-match
14396 (match-beginning 1) (match-end 1)))
14397 (org-show-context 'tags-tree))
14398 ((eq action 'agenda)
14399 (setq txt (org-agenda-format-item
14401 (concat
14402 (if (eq org-tags-match-list-sublevels 'indented)
14403 (make-string (1- level) ?.) "")
14404 (org-get-heading))
14405 (make-string level ?\s)
14406 category
14407 tags-list)
14408 priority (org-get-priority txt))
14409 (goto-char lspos)
14410 (setq marker (org-agenda-new-marker))
14411 (org-add-props txt props
14412 'org-marker marker 'org-hd-marker marker 'org-category category
14413 'todo-state todo
14414 'ts-date ts-date
14415 'priority priority
14416 'type (concat "tagsmatch" ts-date-type))
14417 (push txt rtn))
14418 ((functionp action)
14419 (setq org-map-continue-from nil)
14420 (save-excursion
14421 (setq rtn1 (funcall action))
14422 (push rtn1 rtn)))
14423 (t (user-error "Invalid action")))
14425 ;; if we are to skip sublevels, jump to end of subtree
14426 (unless org-tags-match-list-sublevels
14427 (org-end-of-subtree t)
14428 (backward-char 1))))
14429 ;; Get the correct position from where to continue
14430 (if org-map-continue-from
14431 (goto-char org-map-continue-from)
14432 (and (= (point) lspos) (end-of-line 1)))))
14433 (when (and (eq action 'sparse-tree)
14434 (not org-sparse-tree-open-archived-trees))
14435 (org-hide-archived-subtrees (point-min) (point-max)))
14436 (nreverse rtn)))
14438 (defun org-remove-uninherited-tags (tags)
14439 "Remove all tags that are not inherited from the list TAGS."
14440 (cond
14441 ((eq org-use-tag-inheritance t)
14442 (if org-tags-exclude-from-inheritance
14443 (org-delete-all org-tags-exclude-from-inheritance tags)
14444 tags))
14445 ((not org-use-tag-inheritance) nil)
14446 ((stringp org-use-tag-inheritance)
14447 (delq nil (mapcar
14448 (lambda (x)
14449 (if (and (string-match org-use-tag-inheritance x)
14450 (not (member x org-tags-exclude-from-inheritance)))
14451 x nil))
14452 tags)))
14453 ((listp org-use-tag-inheritance)
14454 (delq nil (mapcar
14455 (lambda (x)
14456 (if (member x org-use-tag-inheritance) x nil))
14457 tags)))))
14459 (defun org-match-sparse-tree (&optional todo-only match)
14460 "Create a sparse tree according to tags string MATCH.
14461 MATCH can contain positive and negative selection of tags, like
14462 \"+WORK+URGENT-WITHBOSS\".
14463 If optional argument TODO-ONLY is non-nil, only select lines that are
14464 also TODO lines."
14465 (interactive "P")
14466 (org-agenda-prepare-buffers (list (current-buffer)))
14467 (let ((org--matcher-tags-todo-only todo-only))
14468 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14469 org--matcher-tags-todo-only)))
14471 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14473 (defvar org-cached-props nil)
14474 (defun org-cached-entry-get (pom property)
14475 (if (or (eq t org-use-property-inheritance)
14476 (and (stringp org-use-property-inheritance)
14477 (let ((case-fold-search t))
14478 (string-match-p org-use-property-inheritance property)))
14479 (and (listp org-use-property-inheritance)
14480 (member-ignore-case property org-use-property-inheritance)))
14481 ;; Caching is not possible, check it directly.
14482 (org-entry-get pom property 'inherit)
14483 ;; Get all properties, so we can do complicated checks easily.
14484 (cdr (assoc-string property
14485 (or org-cached-props
14486 (setq org-cached-props (org-entry-properties pom)))
14487 t))))
14489 (defun org-global-tags-completion-table (&optional files)
14490 "Return the list of all tags in all agenda buffer/files.
14491 Optional FILES argument is a list of files which can be used
14492 instead of the agenda files."
14493 (save-excursion
14494 (org-uniquify
14495 (delq nil
14496 (apply #'append
14497 (mapcar
14498 (lambda (file)
14499 (set-buffer (find-file-noselect file))
14500 (mapcar (lambda (x)
14501 (and (stringp (car-safe x))
14502 (list (car-safe x))))
14503 (or org-current-tag-alist (org-get-buffer-tags))))
14504 (if (car-safe files) files
14505 (org-agenda-files))))))))
14507 (defun org-make-tags-matcher (match)
14508 "Create the TAGS/TODO matcher form for the selection string MATCH.
14510 Returns a cons of the selection string MATCH and a function
14511 implementing the matcher.
14513 The matcher is to be called at an Org entry, with point on the
14514 headline, and returns non-nil if the entry matches the selection
14515 string MATCH. It must be called with three arguments: the TODO
14516 keyword at the entry (or nil if none), the list of all tags at
14517 the entry including inherited ones and the reduced level of the
14518 headline. Additionally, the category of the entry, if any, must
14519 be specified as the text property `org-category' on the headline.
14521 This function sets the variable `org--matcher-tags-todo-only' to
14522 a non-nil value if the matcher restricts matching to TODO
14523 entries, otherwise it is not touched.
14525 See also `org-scan-tags'."
14526 (unless match
14527 ;; Get a new match request, with completion against the global
14528 ;; tags table and the local tags in current buffer.
14529 (let ((org-last-tags-completion-table
14530 (org-uniquify
14531 (delq nil (append (org-get-buffer-tags)
14532 (org-global-tags-completion-table))))))
14533 (setq match
14534 (completing-read
14535 "Match: "
14536 'org-tags-completion-function nil nil nil 'org-tags-history))))
14538 (let ((match0 match)
14539 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14540 (start 0)
14541 tagsmatch todomatch tagsmatcher todomatcher)
14543 ;; Expand group tags.
14544 (setq match (org-tags-expand match))
14546 ;; Check if there is a TODO part of this match, which would be the
14547 ;; part after a "/". To make sure that this slash is not part of
14548 ;; a property value to be matched against, we also check that
14549 ;; there is no / after that slash. First, find the last slash.
14550 (let ((s 0))
14551 (while (string-match "/+" match s)
14552 (setq start (match-beginning 0))
14553 (setq s (match-end 0))))
14554 (if (and (string-match "/+" match start)
14555 (not (string-match-p "\"" match start)))
14556 ;; Match contains also a TODO-matching request.
14557 (progn
14558 (setq tagsmatch (substring match 0 (match-beginning 0)))
14559 (setq todomatch (substring match (match-end 0)))
14560 (when (string-prefix-p "!" todomatch)
14561 (setq org--matcher-tags-todo-only t)
14562 (setq todomatch (substring todomatch 1)))
14563 (when (string-match "\\`\\s-*\\'" todomatch)
14564 (setq todomatch nil)))
14565 ;; Only matching tags.
14566 (setq tagsmatch match)
14567 (setq todomatch nil))
14569 ;; Make the tags matcher.
14570 (when (org-string-nw-p tagsmatch)
14571 (let ((orlist nil)
14572 (orterms (org-split-string tagsmatch "|"))
14573 term)
14574 (while (setq term (pop orterms))
14575 (while (and (equal (substring term -1) "\\") orterms)
14576 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14577 (while (string-match re term)
14578 (let* ((rest (substring term (match-end 0)))
14579 (minus (and (match-end 1)
14580 (equal (match-string 1 term) "-")))
14581 (tag (save-match-data
14582 (replace-regexp-in-string
14583 "\\\\-" "-" (match-string 2 term))))
14584 (regexp (eq (string-to-char tag) ?{))
14585 (levelp (match-end 4))
14586 (propp (match-end 5))
14588 (cond
14589 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14590 (levelp
14591 `(,(org-op-to-function (match-string 3 term))
14592 level
14593 ,(string-to-number (match-string 4 term))))
14594 (propp
14595 (let* ((gv (pcase (upcase (match-string 5 term))
14596 ("CATEGORY"
14597 '(get-text-property (point) 'org-category))
14598 ("TODO" 'todo)
14599 (p `(org-cached-entry-get nil ,p))))
14600 (pv (match-string 7 term))
14601 (regexp (eq (string-to-char pv) ?{))
14602 (strp (eq (string-to-char pv) ?\"))
14603 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14604 (po (org-op-to-function (match-string 6 term)
14605 (if timep 'time strp))))
14606 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14607 (when timep (setq pv (org-matcher-time pv)))
14608 (cond ((and regexp (eq po 'org<>))
14609 `(not (string-match ,pv (or ,gv ""))))
14610 (regexp `(string-match ,pv (or ,gv "")))
14611 (strp `(,po (or ,gv "") ,pv))
14613 `(,po
14614 (string-to-number (or ,gv ""))
14615 ,(string-to-number pv))))))
14616 (t `(member ,tag tags-list)))))
14617 (push (if minus `(not ,mm) mm) tagsmatcher)
14618 (setq term rest)))
14619 (push `(and ,@tagsmatcher) orlist)
14620 (setq tagsmatcher nil))
14621 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14623 ;; Make the TODO matcher.
14624 (when (org-string-nw-p todomatch)
14625 (let ((orlist nil))
14626 (dolist (term (org-split-string todomatch "|"))
14627 (while (string-match re term)
14628 (let* ((minus (and (match-end 1)
14629 (equal (match-string 1 term) "-")))
14630 (kwd (match-string 2 term))
14631 (regexp (eq (string-to-char kwd) ?{))
14632 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14633 `(equal todo ,kwd))))
14634 (push (if minus `(not ,mm) mm) todomatcher))
14635 (setq term (substring term (match-end 0))))
14636 (push (if (> (length todomatcher) 1)
14637 (cons 'and todomatcher)
14638 (car todomatcher))
14639 orlist)
14640 (setq todomatcher nil))
14641 (setq todomatcher (cons 'or orlist))))
14643 ;; Return the string and function of the matcher. If no
14644 ;; tags-specific or todo-specific matcher exists, match
14645 ;; everything.
14646 (let ((matcher (if (and tagsmatcher todomatcher)
14647 `(and ,tagsmatcher ,todomatcher)
14648 (or tagsmatcher todomatcher t))))
14649 (when org--matcher-tags-todo-only
14650 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14651 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14653 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14654 "Expand group tags in MATCH.
14656 This replaces every group tag in MATCH with a regexp tag search.
14657 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14658 will be replaced like this:
14660 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14661 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14662 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14664 Replacing by a regexp preserves the structure of the match.
14665 E.g., this expansion
14667 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14669 will match anything tagged with \"Lab\" and \"Home\", or tagged
14670 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14672 A group tag in MATCH can contain regular expressions of its own.
14673 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14674 will be replaced like this:
14676 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14678 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14679 assumed to be a single group tag, and the function will return
14680 the list of tags in this group.
14682 When DOWNCASE is non-nil, expand downcased TAGS."
14683 (if org-group-tags
14684 (let* ((case-fold-search t)
14685 (stable org-mode-syntax-table)
14686 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14687 (taggroups (if downcased
14688 (mapcar (lambda (tg) (mapcar #'downcase tg))
14689 taggroups)
14690 taggroups))
14691 (taggroups-keys (mapcar #'car taggroups))
14692 (return-match (if downcased (downcase match) match))
14693 (count 0)
14694 (work-already-expanded tags-already-expanded)
14695 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14696 ;; @ and _ are allowed as word-components in tags.
14697 (modify-syntax-entry ?@ "w" stable)
14698 (modify-syntax-entry ?_ "w" stable)
14699 ;; Temporarily replace regexp-expressions in the match-expression.
14700 (while (string-match "{.+?}" return-match)
14701 (cl-incf count)
14702 (push (match-string 0 return-match) regexps-in-match)
14703 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14704 (while (and taggroups-keys
14705 (with-syntax-table stable
14706 (string-match
14707 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14708 (regexp-opt taggroups-keys) "\\>\\)")
14709 return-match)))
14710 (let* ((dir (match-string 1 return-match))
14711 (tag (match-string 2 return-match))
14712 (tag (if downcased (downcase tag) tag)))
14713 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14714 (member tag work-already-expanded))
14715 (setq tags-in-group (assoc tag taggroups))
14716 (push tag work-already-expanded)
14717 ;; Recursively expand each tag in the group, if the tag hasn't
14718 ;; already been expanded. Restore the match-data after all recursive calls.
14719 (save-match-data
14720 (let (tags-expanded)
14721 (dolist (x (cdr tags-in-group))
14722 (if (and (member x taggroups-keys)
14723 (not (member x work-already-expanded)))
14724 (setq tags-expanded
14725 (delete-dups
14726 (append
14727 (org-tags-expand x t downcased
14728 work-already-expanded)
14729 tags-expanded)))
14730 (setq tags-expanded
14731 (append (list x) tags-expanded)))
14732 (setq work-already-expanded
14733 (delete-dups
14734 (append tags-expanded
14735 work-already-expanded))))
14736 (setq tags-in-group
14737 (delete-dups (cons (car tags-in-group)
14738 tags-expanded)))))
14739 ;; Filter tag-regexps from tags.
14740 (setq regexp-in-group-escaped
14741 (delq nil (mapcar (lambda (x)
14742 (if (stringp x)
14743 (and (equal "{" (substring x 0 1))
14744 (equal "}" (substring x -1))
14747 tags-in-group))
14748 regexp-in-group
14749 (mapcar (lambda (x)
14750 (substring x 1 -1))
14751 regexp-in-group-escaped)
14752 tags-in-group
14753 (delq nil (mapcar (lambda (x)
14754 (if (stringp x)
14755 (and (not (equal "{" (substring x 0 1)))
14756 (not (equal "}" (substring x -1)))
14759 tags-in-group)))
14760 ;; If single-as-list, do no more in the while-loop.
14761 (if (not single-as-list)
14762 (progn
14763 (when regexp-in-group
14764 (setq regexp-in-group
14765 (concat "\\|"
14766 (mapconcat 'identity regexp-in-group
14767 "\\|"))))
14768 (setq tags-in-group
14769 (concat dir
14770 "{\\<"
14771 (regexp-opt tags-in-group)
14772 "\\>"
14773 regexp-in-group
14774 "}"))
14775 (when (stringp tags-in-group)
14776 (org-add-props tags-in-group '(grouptag t)))
14777 (setq return-match
14778 (replace-match tags-in-group t t return-match)))
14779 (setq tags-in-group
14780 (append regexp-in-group-escaped tags-in-group))))
14781 (setq taggroups-keys (delete tag taggroups-keys))))
14782 ;; Add the regular expressions back into the match-expression again.
14783 (while regexps-in-match
14784 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14785 (pop regexps-in-match)
14786 return-match t t))
14787 (cl-decf count))
14788 (if single-as-list
14789 (if tags-in-group tags-in-group (list return-match))
14790 return-match))
14791 (if single-as-list
14792 (list (if downcased (downcase match) match))
14793 match)))
14795 (defun org-op-to-function (op &optional stringp)
14796 "Turn an operator into the appropriate function."
14797 (setq op
14798 (cond
14799 ((equal op "<" ) '(< string< org-time<))
14800 ((equal op ">" ) '(> org-string> org-time>))
14801 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14802 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14803 ((member op '("=" "==")) '(= string= org-time=))
14804 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14805 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14807 (defun org<> (a b) (not (= a b)))
14808 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14809 (defun org-string>= (a b) (not (string< a b)))
14810 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14811 (defun org-string<> (a b) (not (string= a b)))
14812 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14813 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14814 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14815 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14816 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14817 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14818 (defun org-2ft (s)
14819 "Convert S to a floating point time.
14820 If S is already a number, just return it. If it is a string, parse
14821 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14822 (cond
14823 ((numberp s) s)
14824 ((stringp s)
14825 (condition-case nil
14826 (float-time (apply 'encode-time (org-parse-time-string s)))
14827 (error 0.)))
14828 (t 0.)))
14830 (defun org-time-today ()
14831 "Time in seconds today at 0:00.
14832 Returns the float number of seconds since the beginning of the
14833 epoch to the beginning of today (00:00)."
14834 (float-time (apply 'encode-time
14835 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14837 (defun org-matcher-time (s)
14838 "Interpret a time comparison value."
14839 (save-match-data
14840 (cond
14841 ((string= s "<now>") (float-time))
14842 ((string= s "<today>") (org-time-today))
14843 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14844 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14845 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14846 (+ (org-time-today)
14847 (* (string-to-number (match-string 1 s))
14848 (cdr (assoc (match-string 2 s)
14849 '(("d" . 86400.0) ("w" . 604800.0)
14850 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14851 (t (org-2ft s)))))
14853 (defun org-match-any-p (re list)
14854 "Does re match any element of list?"
14855 (setq list (mapcar (lambda (x) (string-match re x)) list))
14856 (delq nil list))
14858 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14859 (defvar org-tags-overlay (make-overlay 1 1))
14860 (delete-overlay org-tags-overlay)
14862 (defun org-get-local-tags-at (&optional pos)
14863 "Get a list of tags defined in the current headline."
14864 (org-get-tags-at pos 'local))
14866 (defun org-get-local-tags ()
14867 "Get a list of tags defined in the current headline."
14868 (org-get-tags-at nil 'local))
14870 (defun org-get-tags-at (&optional pos local)
14871 "Get a list of all headline tags applicable at POS.
14872 POS defaults to point. If tags are inherited, the list contains
14873 the targets in the same sequence as the headlines appear, i.e.
14874 the tags of the current headline come last.
14875 When LOCAL is non-nil, only return tags from the current headline,
14876 ignore inherited ones."
14877 (interactive)
14878 (if (and org-trust-scanner-tags
14879 (or (not pos) (equal pos (point)))
14880 (not local))
14881 org-scanner-tags
14882 (let (tags ltags lastpos parent)
14883 (save-excursion
14884 (save-restriction
14885 (widen)
14886 (goto-char (or pos (point)))
14887 (save-match-data
14888 (catch 'done
14889 (condition-case nil
14890 (progn
14891 (org-back-to-heading t)
14892 (while (not (equal lastpos (point)))
14893 (setq lastpos (point))
14894 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14895 (setq ltags (org-split-string
14896 (match-string-no-properties 1) ":"))
14897 (when parent
14898 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14899 (setq tags (append
14900 (if parent
14901 (org-remove-uninherited-tags ltags)
14902 ltags)
14903 tags)))
14904 (or org-use-tag-inheritance (throw 'done t))
14905 (when local (throw 'done t))
14906 (or (org-up-heading-safe) (error nil))
14907 (setq parent t)))
14908 (error nil)))))
14909 (if local
14910 tags
14911 (reverse (delete-dups
14912 (reverse (append
14913 (org-remove-uninherited-tags
14914 org-file-tags)
14915 tags)))))))))
14917 (defun org-add-prop-inherited (s)
14918 (add-text-properties 0 (length s) '(inherited t) s)
14921 (defun org-toggle-tag (tag &optional onoff)
14922 "Toggle the tag TAG for the current line.
14923 If ONOFF is `on' or `off', don't toggle but set to this state."
14924 (let (res current)
14925 (save-excursion
14926 (org-back-to-heading t)
14927 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14928 (point-at-eol) t)
14929 (progn
14930 (setq current (match-string 1))
14931 (replace-match ""))
14932 (setq current ""))
14933 (setq current (nreverse (org-split-string current ":")))
14934 (cond
14935 ((eq onoff 'on)
14936 (setq res t)
14937 (or (member tag current) (push tag current)))
14938 ((eq onoff 'off)
14939 (or (not (member tag current)) (setq current (delete tag current))))
14940 (t (if (member tag current)
14941 (setq current (delete tag current))
14942 (setq res t)
14943 (push tag current))))
14944 (end-of-line 1)
14945 (if current
14946 (progn
14947 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14948 (org-set-tags nil t))
14949 (delete-horizontal-space))
14950 (run-hooks 'org-after-tags-change-hook))
14951 res))
14953 (defun org-align-tags-here (to-col)
14954 ;; Assumes that this is a headline
14955 "Align tags on the current headline to TO-COL."
14956 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14957 (beginning-of-line 1)
14958 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14959 (< pos (match-beginning 2)))
14960 (progn
14961 (setq tags-l (string-width (match-string 2)))
14962 (goto-char (match-beginning 1))
14963 (insert " ")
14964 (delete-region (point) (1+ (match-beginning 2)))
14965 (setq ncol (max (current-column)
14966 (1+ col)
14967 (if (> to-col 0)
14968 to-col
14969 (- (abs to-col) tags-l))))
14970 (setq p (point))
14971 (insert (make-string (- ncol (current-column)) ?\ ))
14972 (setq ncol (current-column))
14973 (when indent-tabs-mode (tabify p (point-at-eol)))
14974 (org-move-to-column (min ncol col)))
14975 (goto-char pos))))
14977 (defun org-set-tags-command (&optional arg just-align)
14978 "Call the set-tags command for the current entry."
14979 (interactive "P")
14980 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14981 (org-set-tags arg just-align)
14982 (save-excursion
14983 (unless (and (org-region-active-p)
14984 org-loop-over-headlines-in-active-region)
14985 (org-back-to-heading t))
14986 (org-set-tags arg just-align))))
14988 (defun org-set-tags-to (data)
14989 "Set the tags of the current entry to DATA, replacing the current tags.
14990 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14991 If DATA is nil or the empty string, any tags will be removed."
14992 (interactive "sTags: ")
14993 (setq data
14994 (cond
14995 ((eq data nil) "")
14996 ((equal data "") "")
14997 ((stringp data)
14998 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14999 ":"))
15000 ((listp data)
15001 (concat ":" (mapconcat 'identity data ":") ":"))))
15002 (when data
15003 (save-excursion
15004 (org-back-to-heading t)
15005 (when (looking-at org-complex-heading-regexp)
15006 (if (match-end 5)
15007 (progn
15008 (goto-char (match-beginning 5))
15009 (insert data)
15010 (delete-region (point) (point-at-eol))
15011 (org-set-tags nil 'align))
15012 (goto-char (point-at-eol))
15013 (insert " " data)
15014 (org-set-tags nil 'align)))
15015 (beginning-of-line 1)
15016 (when (looking-at ".*?\\([ \t]+\\)$")
15017 (delete-region (match-beginning 1) (match-end 1))))))
15019 (defun org-align-all-tags ()
15020 "Align the tags in all headings."
15021 (interactive)
15022 (save-excursion
15023 (or (ignore-errors (org-back-to-heading t))
15024 (outline-next-heading))
15025 (if (org-at-heading-p)
15026 (org-set-tags t)
15027 (message "No headings"))))
15029 (defvar org-indent-indentation-per-level)
15030 (defun org-set-tags (&optional arg just-align)
15031 "Set the tags for the current headline.
15032 With prefix ARG, realign all tags in headings in the current buffer.
15033 When JUST-ALIGN is non-nil, only align tags."
15034 (interactive "P")
15035 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15036 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15037 'region-start-level
15038 'region))
15039 org-loop-over-headlines-in-active-region)
15040 (org-map-entries
15041 ;; We don't use ARG and JUST-ALIGN here because these args
15042 ;; are not useful when looping over headlines.
15043 #'org-set-tags
15044 org-loop-over-headlines-in-active-region
15046 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15047 (let ((org-setting-tags t))
15048 (if arg
15049 (save-excursion
15050 (goto-char (point-min))
15051 (while (re-search-forward org-outline-regexp-bol nil t)
15052 (org-set-tags nil t)
15053 (end-of-line))
15054 (message "All tags realigned to column %d" org-tags-column))
15055 (let* ((current (org-get-tags-string))
15056 (col (current-column))
15057 (tags
15058 (if just-align current
15059 ;; Get a new set of tags from the user.
15060 (save-excursion
15061 (let* ((seen)
15062 (table
15063 (setq
15064 org-last-tags-completion-table
15065 ;; Uniquify tags in alists, yet preserve
15066 ;; structure (i.e., keywords).
15067 (delq nil
15068 (mapcar
15069 (lambda (pair)
15070 (let ((head (car pair)))
15071 (cond ((symbolp head) pair)
15072 ((member head seen) nil)
15073 (t (push head seen)
15074 pair))))
15075 (append
15076 (or org-current-tag-alist
15077 (org-get-buffer-tags))
15078 (and
15079 org-complete-tags-always-offer-all-agenda-tags
15080 (org-global-tags-completion-table
15081 (org-agenda-files))))))))
15082 (current-tags (org-split-string current ":"))
15083 (inherited-tags
15084 (nreverse (nthcdr (length current-tags)
15085 (nreverse (org-get-tags-at))))))
15086 (replace-regexp-in-string
15087 "\\([-+&]+\\|,\\)"
15089 (if (or (eq t org-use-fast-tag-selection)
15090 (and org-use-fast-tag-selection
15091 (delq nil (mapcar #'cdr table))))
15092 (org-fast-tag-selection
15093 current-tags inherited-tags table
15094 (and org-fast-tag-selection-include-todo
15095 org-todo-key-alist))
15096 (let ((org-add-colon-after-tag-completion
15097 (< 1 (length table))))
15098 (org-trim
15099 (completing-read
15100 "Tags: "
15101 #'org-tags-completion-function
15102 nil nil current 'org-tags-history))))))))))
15104 (when org-tags-sort-function
15105 (setq tags
15106 (mapconcat
15107 #'identity
15108 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15109 org-tags-sort-function)
15110 ":")))
15112 (if (not (org-string-nw-p tags)) (setq tags "")
15113 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15114 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15116 ;; Insert new tags at the correct column
15117 (beginning-of-line)
15118 (let ((level (if (looking-at org-outline-regexp)
15119 (- (match-end 0) (point) 1)
15120 1)))
15121 (cond
15122 ((and (equal current "") (equal tags "")))
15123 ((re-search-forward
15124 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15125 (line-end-position)
15127 (if (equal tags "") (replace-match "" t t)
15128 (goto-char (match-beginning 0))
15129 (let* ((c0 (current-column))
15130 ;; Compute offset for the case of org-indent-mode
15131 ;; active.
15132 (di (if (bound-and-true-p org-indent-mode)
15133 (* (1- org-indent-indentation-per-level)
15134 (1- level))
15136 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15137 (tc (+ org-tags-column
15138 (if (> org-tags-column 0) (- di) di)))
15139 (c1 (max (1+ c0)
15140 (if (> tc 0) tc
15141 (- (- tc) (string-width tags)))))
15142 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15143 (replace-match rpl t t)
15144 (when indent-tabs-mode (tabify p0 (point))))))
15145 (t (error "Tags alignment failed"))))
15146 (org-move-to-column col))
15147 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15149 (defun org-change-tag-in-region (beg end tag off)
15150 "Add or remove TAG for each entry in the region.
15151 This works in the agenda, and also in an Org buffer."
15152 (interactive
15153 (list (region-beginning) (region-end)
15154 (let ((org-last-tags-completion-table
15155 (if (derived-mode-p 'org-mode)
15156 (org-uniquify
15157 (delq nil (append (org-get-buffer-tags)
15158 (org-global-tags-completion-table))))
15159 (org-global-tags-completion-table))))
15160 (completing-read
15161 "Tag: " 'org-tags-completion-function nil nil nil
15162 'org-tags-history))
15163 (progn
15164 (message "[s]et or [r]emove? ")
15165 (equal (read-char-exclusive) ?r))))
15166 (when (fboundp 'deactivate-mark) (deactivate-mark))
15167 (let ((agendap (equal major-mode 'org-agenda-mode))
15168 l1 l2 m buf pos newhead (cnt 0))
15169 (goto-char end)
15170 (setq l2 (1- (org-current-line)))
15171 (goto-char beg)
15172 (setq l1 (org-current-line))
15173 (cl-loop for l from l1 to l2 do
15174 (org-goto-line l)
15175 (setq m (get-text-property (point) 'org-hd-marker))
15176 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15177 (and agendap m))
15178 (setq buf (if agendap (marker-buffer m) (current-buffer))
15179 pos (if agendap m (point)))
15180 (with-current-buffer buf
15181 (save-excursion
15182 (save-restriction
15183 (goto-char pos)
15184 (setq cnt (1+ cnt))
15185 (org-toggle-tag tag (if off 'off 'on))
15186 (setq newhead (org-get-heading)))))
15187 (and agendap (org-agenda-change-all-lines newhead m))))
15188 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15190 (defun org-tags-completion-function (string _predicate &optional flag)
15191 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15192 (confirm (lambda (x) (stringp (car x)))))
15193 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15194 (setq s1 (match-string 1 string)
15195 s2 (match-string 2 string))
15196 (setq s1 "" s2 string))
15197 (cond
15198 ((eq flag nil)
15199 ;; try completion
15200 (setq rtn (try-completion s2 ctable confirm))
15201 (when (stringp rtn)
15202 (setq rtn
15203 (concat s1 s2 (substring rtn (length s2))
15204 (if (and org-add-colon-after-tag-completion
15205 (assoc rtn ctable))
15206 ":" ""))))
15207 rtn)
15208 ((eq flag t)
15209 ;; all-completions
15210 (all-completions s2 ctable confirm))
15211 ((eq flag 'lambda)
15212 ;; exact match?
15213 (assoc s2 ctable)))))
15215 (defun org-fast-tag-insert (kwd tags face &optional end)
15216 "Insert KDW, and the TAGS, the latter with face FACE.
15217 Also insert END."
15218 (insert (format "%-12s" (concat kwd ":"))
15219 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15220 (or end "")))
15222 (defun org-fast-tag-show-exit (flag)
15223 (save-excursion
15224 (org-goto-line 3)
15225 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15226 (replace-match ""))
15227 (when flag
15228 (end-of-line 1)
15229 (org-move-to-column (- (window-width) 19) t)
15230 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15232 (defun org-set-current-tags-overlay (current prefix)
15233 "Add an overlay to CURRENT tag with PREFIX."
15234 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15235 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15236 (org-overlay-display org-tags-overlay (concat prefix s))))
15238 (defvar org-last-tag-selection-key nil)
15239 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15240 "Fast tag selection with single keys.
15241 CURRENT is the current list of tags in the headline, INHERITED is the
15242 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15243 possibly with grouping information. TODO-TABLE is a similar table with
15244 TODO keywords, should these have keys assigned to them.
15245 If the keys are nil, a-z are automatically assigned.
15246 Returns the new tags string, or nil to not change the current settings."
15247 (let* ((fulltable (append table todo-table))
15248 (maxlen (apply 'max (mapcar
15249 (lambda (x)
15250 (if (stringp (car x)) (string-width (car x)) 0))
15251 fulltable)))
15252 (buf (current-buffer))
15253 (expert (eq org-fast-tag-selection-single-key 'expert))
15254 (buffer-tags nil)
15255 (fwidth (+ maxlen 3 1 3))
15256 (ncol (/ (- (window-width) 4) fwidth))
15257 (i-face 'org-done)
15258 (c-face 'org-todo)
15259 tg cnt e c char c1 c2 ntable tbl rtn
15260 ov-start ov-end ov-prefix
15261 (exit-after-next org-fast-tag-selection-single-key)
15262 (done-keywords org-done-keywords)
15263 groups ingroup intaggroup)
15264 (save-excursion
15265 (beginning-of-line 1)
15266 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15267 (setq ov-start (match-beginning 1)
15268 ov-end (match-end 1)
15269 ov-prefix "")
15270 (setq ov-start (1- (point-at-eol))
15271 ov-end (1+ ov-start))
15272 (skip-chars-forward "^\n\r")
15273 (setq ov-prefix
15274 (concat
15275 (buffer-substring (1- (point)) (point))
15276 (if (> (current-column) org-tags-column)
15278 (make-string (- org-tags-column (current-column)) ?\ ))))))
15279 (move-overlay org-tags-overlay ov-start ov-end)
15280 (save-window-excursion
15281 (if expert
15282 (set-buffer (get-buffer-create " *Org tags*"))
15283 (delete-other-windows)
15284 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15285 (org-switch-to-buffer-other-window " *Org tags*"))
15286 (erase-buffer)
15287 (setq-local org-done-keywords done-keywords)
15288 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15289 (org-fast-tag-insert "Current" current c-face "\n\n")
15290 (org-fast-tag-show-exit exit-after-next)
15291 (org-set-current-tags-overlay current ov-prefix)
15292 (setq tbl fulltable char ?a cnt 0)
15293 (while (setq e (pop tbl))
15294 (cond
15295 ((eq (car e) :startgroup)
15296 (push '() groups) (setq ingroup t)
15297 (unless (zerop cnt)
15298 (setq cnt 0)
15299 (insert "\n"))
15300 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15301 ((eq (car e) :endgroup)
15302 (setq ingroup nil cnt 0)
15303 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15304 ((eq (car e) :startgrouptag)
15305 (setq intaggroup t)
15306 (unless (zerop cnt)
15307 (setq cnt 0)
15308 (insert "\n"))
15309 (insert "[ "))
15310 ((eq (car e) :endgrouptag)
15311 (setq intaggroup nil cnt 0)
15312 (insert "]\n"))
15313 ((equal e '(:newline))
15314 (unless (zerop cnt)
15315 (setq cnt 0)
15316 (insert "\n")
15317 (setq e (car tbl))
15318 (while (equal (car tbl) '(:newline))
15319 (insert "\n")
15320 (setq tbl (cdr tbl)))))
15321 ((equal e '(:grouptags)) (insert " : "))
15323 (setq tg (copy-sequence (car e)) c2 nil)
15324 (if (cdr e)
15325 (setq c (cdr e))
15326 ;; automatically assign a character.
15327 (setq c1 (string-to-char
15328 (downcase (substring
15329 tg (if (= (string-to-char tg) ?@) 1 0)))))
15330 (if (or (rassoc c1 ntable) (rassoc c1 table))
15331 (while (or (rassoc char ntable) (rassoc char table))
15332 (setq char (1+ char)))
15333 (setq c2 c1))
15334 (setq c (or c2 char)))
15335 (when ingroup (push tg (car groups)))
15336 (setq tg (org-add-props tg nil 'face
15337 (cond
15338 ((not (assoc tg table))
15339 (org-get-todo-face tg))
15340 ((member tg current) c-face)
15341 ((member tg inherited) i-face))))
15342 (when (equal (caar tbl) :grouptags)
15343 (org-add-props tg nil 'face 'org-tag-group))
15344 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15345 (insert "[" c "] " tg (make-string
15346 (- fwidth 4 (length tg)) ?\ ))
15347 (push (cons tg c) ntable)
15348 (when (= (cl-incf cnt) ncol)
15349 (insert "\n")
15350 (when (or ingroup intaggroup) (insert " "))
15351 (setq cnt 0)))))
15352 (setq ntable (nreverse ntable))
15353 (insert "\n")
15354 (goto-char (point-min))
15355 (unless expert (org-fit-window-to-buffer))
15356 (setq rtn
15357 (catch 'exit
15358 (while t
15359 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15360 (if (not groups) "no " "")
15361 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15362 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15363 (setq org-last-tag-selection-key c)
15364 (cond
15365 ((= c ?\r) (throw 'exit t))
15366 ((= c ?!)
15367 (setq groups (not groups))
15368 (goto-char (point-min))
15369 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15370 ((= c ?\C-c)
15371 (if (not expert)
15372 (org-fast-tag-show-exit
15373 (setq exit-after-next (not exit-after-next)))
15374 (setq expert nil)
15375 (delete-other-windows)
15376 (set-window-buffer (split-window-vertically) " *Org tags*")
15377 (org-switch-to-buffer-other-window " *Org tags*")
15378 (org-fit-window-to-buffer)))
15379 ((or (= c ?\C-g)
15380 (and (= c ?q) (not (rassoc c ntable))))
15381 (delete-overlay org-tags-overlay)
15382 (setq quit-flag t))
15383 ((= c ?\ )
15384 (setq current nil)
15385 (when exit-after-next (setq exit-after-next 'now)))
15386 ((= c ?\t)
15387 (condition-case nil
15388 (setq tg (completing-read
15389 "Tag: "
15390 (or buffer-tags
15391 (with-current-buffer buf
15392 (setq buffer-tags
15393 (org-get-buffer-tags))))))
15394 (quit (setq tg "")))
15395 (when (string-match "\\S-" tg)
15396 (cl-pushnew (list tg) buffer-tags :test #'equal)
15397 (if (member tg current)
15398 (setq current (delete tg current))
15399 (push tg current)))
15400 (when exit-after-next (setq exit-after-next 'now)))
15401 ((setq e (rassoc c todo-table) tg (car e))
15402 (with-current-buffer buf
15403 (save-excursion (org-todo tg)))
15404 (when exit-after-next (setq exit-after-next 'now)))
15405 ((setq e (rassoc c ntable) tg (car e))
15406 (if (member tg current)
15407 (setq current (delete tg current))
15408 (cl-loop for g in groups do
15409 (when (member tg g)
15410 (dolist (x g) (setq current (delete x current)))))
15411 (push tg current))
15412 (when exit-after-next (setq exit-after-next 'now))))
15414 ;; Create a sorted list
15415 (setq current
15416 (sort current
15417 (lambda (a b)
15418 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15419 (when (eq exit-after-next 'now) (throw 'exit t))
15420 (goto-char (point-min))
15421 (beginning-of-line 2)
15422 (delete-region (point) (point-at-eol))
15423 (org-fast-tag-insert "Current" current c-face)
15424 (org-set-current-tags-overlay current ov-prefix)
15425 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15426 (setq tg (match-string 1))
15427 (add-text-properties
15428 (match-beginning 1) (match-end 1)
15429 (list 'face
15430 (cond
15431 ((member tg current) c-face)
15432 ((member tg inherited) i-face)
15433 (t (get-text-property (match-beginning 1) 'face))))))
15434 (goto-char (point-min)))))
15435 (delete-overlay org-tags-overlay)
15436 (if rtn
15437 (mapconcat 'identity current ":")
15438 nil))))
15440 (defun org-get-tags-string ()
15441 "Get the TAGS string in the current headline."
15442 (unless (org-at-heading-p t)
15443 (user-error "Not on a heading"))
15444 (save-excursion
15445 (beginning-of-line 1)
15446 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15447 (match-string-no-properties 1)
15448 "")))
15450 (defun org-get-tags ()
15451 "Get the list of tags specified in the current headline."
15452 (org-split-string (org-get-tags-string) ":"))
15454 (defun org-get-buffer-tags ()
15455 "Get a table of all tags used in the buffer, for completion."
15456 (org-with-wide-buffer
15457 (goto-char (point-min))
15458 (let ((tag-re (concat org-outline-regexp-bol
15459 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15460 tags)
15461 (while (re-search-forward tag-re nil t)
15462 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15463 (push tag tags)))
15464 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15466 ;;;; The mapping API
15468 (defvar org-agenda-skip-comment-trees)
15469 (defvar org-agenda-skip-function)
15470 (defun org-map-entries (func &optional match scope &rest skip)
15471 "Call FUNC at each headline selected by MATCH in SCOPE.
15473 FUNC is a function or a lisp form. The function will be called without
15474 arguments, with the cursor positioned at the beginning of the headline.
15475 The return values of all calls to the function will be collected and
15476 returned as a list.
15478 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15479 does not need to preserve point. After evaluation, the cursor will be
15480 moved to the end of the line (presumably of the headline of the
15481 processed entry) and search continues from there. Under some
15482 circumstances, this may not produce the wanted results. For example,
15483 if you have removed (e.g. archived) the current (sub)tree it could
15484 mean that the next entry will be skipped entirely. In such cases, you
15485 can specify the position from where search should continue by making
15486 FUNC set the variable `org-map-continue-from' to the desired buffer
15487 position.
15489 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15490 Only headlines that are matched by this query will be considered during
15491 the iteration. When MATCH is nil or t, all headlines will be
15492 visited by the iteration.
15494 SCOPE determines the scope of this command. It can be any of:
15496 nil The current buffer, respecting the restriction if any
15497 tree The subtree started with the entry at point
15498 region The entries within the active region, if any
15499 region-start-level
15500 The entries within the active region, but only those at
15501 the same level than the first one.
15502 file The current buffer, without restriction
15503 file-with-archives
15504 The current buffer, and any archives associated with it
15505 agenda All agenda files
15506 agenda-with-archives
15507 All agenda files with any archive files associated with them
15508 \(file1 file2 ...)
15509 If this is a list, all files in the list will be scanned
15511 The remaining args are treated as settings for the skipping facilities of
15512 the scanner. The following items can be given here:
15514 archive skip trees with the archive tag
15515 comment skip trees with the COMMENT keyword
15516 function or Emacs Lisp form:
15517 will be used as value for `org-agenda-skip-function', so
15518 whenever the function returns a position, FUNC will not be
15519 called for that entry and search will continue from the
15520 position returned
15522 If your function needs to retrieve the tags including inherited tags
15523 at the *current* entry, you can use the value of the variable
15524 `org-scanner-tags' which will be much faster than getting the value
15525 with `org-get-tags-at'. If your function gets properties with
15526 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15527 to t around the call to `org-entry-properties' to get the same speedup.
15528 Note that if your function moves around to retrieve tags and properties at
15529 a *different* entry, you cannot use these techniques."
15530 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15531 (not (org-region-active-p)))
15532 (let* ((org-agenda-archives-mode nil) ; just to make sure
15533 (org-agenda-skip-archived-trees (memq 'archive skip))
15534 (org-agenda-skip-comment-trees (memq 'comment skip))
15535 (org-agenda-skip-function
15536 (car (org-delete-all '(comment archive) skip)))
15537 (org-tags-match-list-sublevels t)
15538 (start-level (eq scope 'region-start-level))
15539 matcher res
15540 org-todo-keywords-for-agenda
15541 org-done-keywords-for-agenda
15542 org-todo-keyword-alist-for-agenda
15543 org-tag-alist-for-agenda
15544 org--matcher-tags-todo-only)
15546 (cond
15547 ((eq match t) (setq matcher t))
15548 ((eq match nil) (setq matcher t))
15549 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15551 (save-excursion
15552 (save-restriction
15553 (cond ((eq scope 'tree)
15554 (org-back-to-heading t)
15555 (org-narrow-to-subtree)
15556 (setq scope nil))
15557 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15558 (org-region-active-p))
15559 ;; If needed, set start-level to a string like "2"
15560 (when start-level
15561 (save-excursion
15562 (goto-char (region-beginning))
15563 (unless (org-at-heading-p) (outline-next-heading))
15564 (setq start-level (org-current-level))))
15565 (narrow-to-region (region-beginning)
15566 (save-excursion
15567 (goto-char (region-end))
15568 (unless (and (bolp) (org-at-heading-p))
15569 (outline-next-heading))
15570 (point)))
15571 (setq scope nil)))
15573 (if (not scope)
15574 (progn
15575 (org-agenda-prepare-buffers
15576 (and buffer-file-name (list buffer-file-name)))
15577 (setq res
15578 (org-scan-tags
15579 func matcher org--matcher-tags-todo-only start-level)))
15580 ;; Get the right scope
15581 (cond
15582 ((and scope (listp scope) (symbolp (car scope)))
15583 (setq scope (eval scope)))
15584 ((eq scope 'agenda)
15585 (setq scope (org-agenda-files t)))
15586 ((eq scope 'agenda-with-archives)
15587 (setq scope (org-agenda-files t))
15588 (setq scope (org-add-archive-files scope)))
15589 ((eq scope 'file)
15590 (setq scope (and buffer-file-name (list buffer-file-name))))
15591 ((eq scope 'file-with-archives)
15592 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15593 (org-agenda-prepare-buffers scope)
15594 (dolist (file scope)
15595 (with-current-buffer (org-find-base-buffer-visiting file)
15596 (org-with-wide-buffer
15597 (goto-char (point-min))
15598 (setq res
15599 (append
15601 (org-scan-tags
15602 func matcher org--matcher-tags-todo-only)))))))))
15603 res)))
15605 ;;; Properties API
15607 (defconst org-special-properties
15608 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15609 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15610 "The special properties valid in Org mode.
15611 These are properties that are not defined in the property drawer,
15612 but in some other way.")
15614 (defconst org-default-properties
15615 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15616 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15617 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15618 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15619 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15620 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15621 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15622 "Some properties that are used by Org mode for various purposes.
15623 Being in this list makes sure that they are offered for completion.")
15625 (defun org--valid-property-p (property)
15626 "Non nil when string PROPERTY is a valid property name."
15627 (not
15628 (or (equal property "")
15629 (string-match-p "\\s-" property))))
15631 (defun org--update-property-plist (key val props)
15632 "Associate KEY to VAL in alist PROPS.
15633 Modifications are made by side-effect. Return new alist."
15634 (let* ((appending (string= (substring key -1) "+"))
15635 (key (if appending (substring key 0 -1) key))
15636 (old (assoc-string key props t)))
15637 (if (not old) (cons (cons key val) props)
15638 (setcdr old (if appending (concat (cdr old) " " val) val))
15639 props)))
15641 (defun org-get-property-block (&optional beg force)
15642 "Return the (beg . end) range of the body of the property drawer.
15643 BEG is the beginning of the current subtree, or of the part
15644 before the first headline. If it is not given, it will be found.
15645 If the drawer does not exist, create it if FORCE is non-nil, or
15646 return nil."
15647 (org-with-wide-buffer
15648 (when beg (goto-char beg))
15649 (unless (org-before-first-heading-p)
15650 (let ((beg (cond (beg)
15651 ((or (not (featurep 'org-inlinetask))
15652 (org-inlinetask-in-task-p))
15653 (org-back-to-heading t))
15654 (t (org-with-limited-levels (org-back-to-heading t))))))
15655 (forward-line)
15656 (when (looking-at-p org-planning-line-re) (forward-line))
15657 (cond ((looking-at org-property-drawer-re)
15658 (forward-line)
15659 (cons (point) (progn (goto-char (match-end 0))
15660 (line-beginning-position))))
15661 (force
15662 (goto-char beg)
15663 (org-insert-property-drawer)
15664 (let ((pos (save-excursion (search-forward ":END:")
15665 (line-beginning-position))))
15666 (cons pos pos))))))))
15668 (defun org-at-property-p ()
15669 "Non-nil when point is inside a property drawer.
15670 See `org-property-re' for match data, if applicable."
15671 (save-excursion
15672 (beginning-of-line)
15673 (and (looking-at org-property-re)
15674 (let ((property-drawer (save-match-data (org-get-property-block))))
15675 (and property-drawer
15676 (>= (point) (car property-drawer))
15677 (< (point) (cdr property-drawer)))))))
15679 (defun org-property-action ()
15680 "Do an action on properties."
15681 (interactive)
15682 (unless (org-at-property-p) (user-error "Not at a property"))
15683 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15684 (let ((c (read-char-exclusive)))
15685 (cl-case c
15686 (?s (call-interactively #'org-set-property))
15687 (?d (call-interactively #'org-delete-property))
15688 (?D (call-interactively #'org-delete-property-globally))
15689 (?c (call-interactively #'org-compute-property-at-point))
15690 (otherwise (user-error "No such property action %c" c)))))
15692 (defun org-inc-effort ()
15693 "Increment the value of the effort property in the current entry."
15694 (interactive)
15695 (org-set-effort nil t))
15697 (defvar org-clock-effort) ; Defined in org-clock.el.
15698 (defvar org-clock-current-task) ; Defined in org-clock.el.
15699 (defun org-set-effort (&optional value increment)
15700 "Set the effort property of the current entry.
15701 With numerical prefix arg, use the nth allowed value, 0 stands for the
15702 10th allowed value.
15704 When INCREMENT is non-nil, set the property to the next allowed value."
15705 (interactive "P")
15706 (when (equal value 0) (setq value 10))
15707 (let* ((completion-ignore-case t)
15708 (prop org-effort-property)
15709 (cur (org-entry-get nil prop))
15710 (allowed (org-property-get-allowed-values nil prop 'table))
15711 (existing (mapcar 'list (org-property-values prop)))
15712 (heading (nth 4 (org-heading-components)))
15714 (val (cond
15715 ((stringp value) value)
15716 ((and allowed (integerp value))
15717 (or (car (nth (1- value) allowed))
15718 (car (org-last allowed))))
15719 ((and allowed increment)
15720 (or (cl-caadr (member (list cur) allowed))
15721 (user-error "Allowed effort values are not set")))
15722 (allowed
15723 (message "Select 1-9,0, [RET%s]: %s"
15724 (if cur (concat "=" cur) "")
15725 (mapconcat 'car allowed " "))
15726 (setq rpl (read-char-exclusive))
15727 (if (equal rpl ?\r)
15729 (setq rpl (- rpl ?0))
15730 (when (equal rpl 0) (setq rpl 10))
15731 (if (and (> rpl 0) (<= rpl (length allowed)))
15732 (car (nth (1- rpl) allowed))
15733 (org-completing-read "Effort: " allowed nil))))
15735 (org-completing-read
15736 (concat "Effort" (and cur (string-match "\\S-" cur)
15737 (concat " [" cur "]"))
15738 ": ")
15739 existing nil nil "" nil cur)))))
15740 (unless (equal (org-entry-get nil prop) val)
15741 (org-entry-put nil prop val))
15742 (org-refresh-property
15743 '((effort . identity)
15744 (effort-minutes . org-duration-string-to-minutes))
15745 val)
15746 (when (equal heading (bound-and-true-p org-clock-current-task))
15747 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15748 (org-clock-update-mode-line))
15749 (message "%s is now %s" prop val)))
15751 (defun org-entry-properties (&optional pom which)
15752 "Get all properties of the current entry.
15754 When POM is a buffer position, get all properties from the entry
15755 there instead.
15757 This includes the TODO keyword, the tags, time strings for
15758 deadline, scheduled, and clocking, and any additional properties
15759 defined in the entry.
15761 If WHICH is nil or `all', get all properties. If WHICH is
15762 `special' or `standard', only get that subclass. If WHICH is
15763 a string, only get that property.
15765 Return value is an alist. Keys are properties, as upcased
15766 strings."
15767 (org-with-point-at pom
15768 (when (and (derived-mode-p 'org-mode)
15769 (ignore-errors (org-back-to-heading t)))
15770 (catch 'exit
15771 (let* ((beg (point))
15772 (specific (and (stringp which) (upcase which)))
15773 (which (cond ((not specific) which)
15774 ((member specific org-special-properties) 'special)
15775 (t 'standard)))
15776 props)
15777 ;; Get the special properties, like TODO and TAGS.
15778 (when (memq which '(nil all special))
15779 (when (or (not specific) (string= specific "CLOCKSUM"))
15780 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15781 (when clocksum
15782 (push (cons "CLOCKSUM"
15783 (org-minutes-to-clocksum-string clocksum))
15784 props)))
15785 (when specific (throw 'exit props)))
15786 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15787 (let ((clocksumt (get-text-property (point)
15788 :org-clock-minutes-today)))
15789 (when clocksumt
15790 (push (cons "CLOCKSUM_T"
15791 (org-minutes-to-clocksum-string clocksumt))
15792 props)))
15793 (when specific (throw 'exit props)))
15794 (when (or (not specific) (string= specific "ITEM"))
15795 (when (looking-at org-complex-heading-regexp)
15796 (push (cons "ITEM"
15797 (let ((title (match-string-no-properties 4)))
15798 (if (org-string-nw-p title)
15799 (org-remove-tabs title)
15800 "")))
15801 props))
15802 (when specific (throw 'exit props)))
15803 (when (or (not specific) (string= specific "TODO"))
15804 (let ((case-fold-search nil))
15805 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15806 (push (cons "TODO" (match-string-no-properties 2)) props)))
15807 (when specific (throw 'exit props)))
15808 (when (or (not specific) (string= specific "PRIORITY"))
15809 (push (cons "PRIORITY"
15810 (if (looking-at org-priority-regexp)
15811 (match-string-no-properties 2)
15812 (char-to-string org-default-priority)))
15813 props)
15814 (when specific (throw 'exit props)))
15815 (when (or (not specific) (string= specific "FILE"))
15816 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15817 props)
15818 (when specific (throw 'exit props)))
15819 (when (or (not specific) (string= specific "TAGS"))
15820 (let ((value (org-string-nw-p (org-get-tags-string))))
15821 (when value (push (cons "TAGS" value) props)))
15822 (when specific (throw 'exit props)))
15823 (when (or (not specific) (string= specific "ALLTAGS"))
15824 (let ((value (org-get-tags-at)))
15825 (when value
15826 (push (cons "ALLTAGS"
15827 (format ":%s:" (mapconcat #'identity value ":")))
15828 props)))
15829 (when specific (throw 'exit props)))
15830 (when (or (not specific) (string= specific "BLOCKED"))
15831 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15832 (when specific (throw 'exit props)))
15833 (when (or (not specific)
15834 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15835 (forward-line)
15836 (when (looking-at-p org-planning-line-re)
15837 (end-of-line)
15838 (let ((bol (line-beginning-position))
15839 ;; Backward compatibility: time keywords used to
15840 ;; be configurable (before 8.3). Make sure we
15841 ;; get the correct keyword.
15842 (key-assoc `(("CLOSED" . ,org-closed-string)
15843 ("DEADLINE" . ,org-deadline-string)
15844 ("SCHEDULED" . ,org-scheduled-string))))
15845 (dolist (pair (if specific (list (assoc specific key-assoc))
15846 key-assoc))
15847 (save-excursion
15848 (when (search-backward (cdr pair) bol t)
15849 (goto-char (match-end 0))
15850 (skip-chars-forward " \t")
15851 (and (looking-at org-ts-regexp-both)
15852 (push (cons (car pair)
15853 (match-string-no-properties 0))
15854 props)))))))
15855 (when specific (throw 'exit props)))
15856 (when (or (not specific)
15857 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15858 (let ((find-ts
15859 (lambda (end ts)
15860 ;; Fix next time-stamp before END. TS is the
15861 ;; list of time-stamps found so far.
15862 (let ((ts ts)
15863 (regexp (cond
15864 ((string= specific "TIMESTAMP")
15865 org-ts-regexp)
15866 ((string= specific "TIMESTAMP_IA")
15867 org-ts-regexp-inactive)
15868 ((assoc "TIMESTAMP_IA" ts)
15869 org-ts-regexp)
15870 ((assoc "TIMESTAMP" ts)
15871 org-ts-regexp-inactive)
15872 (t org-ts-regexp-both))))
15873 (catch 'next
15874 (while (re-search-forward regexp end t)
15875 (backward-char)
15876 (let ((object (org-element-context)))
15877 ;; Accept to match timestamps in node
15878 ;; properties, too.
15879 (when (memq (org-element-type object)
15880 '(node-property timestamp))
15881 (let ((type
15882 (org-element-property :type object)))
15883 (cond
15884 ((and (memq type '(active active-range))
15885 (not (equal specific "TIMESTAMP_IA")))
15886 (unless (assoc "TIMESTAMP" ts)
15887 (push (cons "TIMESTAMP"
15888 (org-element-property
15889 :raw-value object))
15891 (when specific (throw 'exit ts))))
15892 ((and (memq type '(inactive inactive-range))
15893 (not (string= specific "TIMESTAMP")))
15894 (unless (assoc "TIMESTAMP_IA" ts)
15895 (push (cons "TIMESTAMP_IA"
15896 (org-element-property
15897 :raw-value object))
15899 (when specific (throw 'exit ts))))))
15900 ;; Both timestamp types are found,
15901 ;; move to next part.
15902 (when (= (length ts) 2) (throw 'next ts)))))
15903 ts)))))
15904 (goto-char beg)
15905 ;; First look for timestamps within headline.
15906 (let ((ts (funcall find-ts (line-end-position) nil)))
15907 (if (= (length ts) 2) (setq props (nconc ts props))
15908 (forward-line)
15909 ;; Then find timestamps in the section, skipping
15910 ;; planning line.
15911 (when (looking-at-p org-planning-line-re)
15912 (forward-line))
15913 (let ((end (save-excursion (outline-next-heading))))
15914 (setq props (nconc (funcall find-ts end ts) props))))))))
15915 ;; Get the standard properties, like :PROP:.
15916 (when (memq which '(nil all standard))
15917 ;; If we are looking after a specific property, delegate
15918 ;; to `org-entry-get', which is faster. However, make an
15919 ;; exception for "CATEGORY", since it can be also set
15920 ;; through keywords (i.e. #+CATEGORY).
15921 (if (and specific (not (equal specific "CATEGORY")))
15922 (let ((value (org-entry-get beg specific nil t)))
15923 (throw 'exit (and value (list (cons specific value)))))
15924 (let ((range (org-get-property-block beg)))
15925 (when range
15926 (let ((end (cdr range)) seen-base)
15927 (goto-char (car range))
15928 ;; Unlike to `org--update-property-plist', we
15929 ;; handle the case where base values is found
15930 ;; after its extension. We also forbid standard
15931 ;; properties to be named as special properties.
15932 (while (re-search-forward org-property-re end t)
15933 (let* ((key (upcase (match-string-no-properties 2)))
15934 (extendp (string-match-p "\\+\\'" key))
15935 (key-base (if extendp (substring key 0 -1) key))
15936 (value (match-string-no-properties 3)))
15937 (cond
15938 ((member-ignore-case key-base org-special-properties))
15939 (extendp
15940 (setq props
15941 (org--update-property-plist key value props)))
15942 ((member key seen-base))
15943 (t (push key seen-base)
15944 (let ((p (assoc-string key props t)))
15945 (if p (setcdr p (concat value " " (cdr p)))
15946 (push (cons key value) props))))))))))))
15947 (unless (assoc "CATEGORY" props)
15948 (push (cons "CATEGORY" (org-get-category beg)) props)
15949 (when (string= specific "CATEGORY") (throw 'exit props)))
15950 ;; Return value.
15951 props)))))
15953 (defun org-property--local-values (property literal-nil)
15954 "Return value for PROPERTY in current entry.
15955 Value is a list whose car is the base value for PROPERTY and cdr
15956 a list of accumulated values. Return nil if neither is found in
15957 the entry. Also return nil when PROPERTY is set to \"nil\",
15958 unless LITERAL-NIL is non-nil."
15959 (let ((range (org-get-property-block)))
15960 (when range
15961 (goto-char (car range))
15962 (let* ((case-fold-search t)
15963 (end (cdr range))
15964 (value
15965 ;; Base value.
15966 (save-excursion
15967 (let ((v (and (re-search-forward
15968 (org-re-property property nil t) end t)
15969 (match-string-no-properties 3))))
15970 (list (if literal-nil v (org-not-nil v)))))))
15971 ;; Find additional values.
15972 (let* ((property+ (org-re-property (concat property "+") nil t)))
15973 (while (re-search-forward property+ end t)
15974 (push (match-string-no-properties 3) value)))
15975 ;; Return final values.
15976 (and (not (equal value '(nil))) (nreverse value))))))
15978 (defun org-entry-get (pom property &optional inherit literal-nil)
15979 "Get value of PROPERTY for entry or content at point-or-marker POM.
15981 If INHERIT is non-nil and the entry does not have the property,
15982 then also check higher levels of the hierarchy. If INHERIT is
15983 the symbol `selective', use inheritance only if the setting in
15984 `org-use-property-inheritance' selects PROPERTY for inheritance.
15986 If the property is present but empty, the return value is the
15987 empty string. If the property is not present at all, nil is
15988 returned. In any other case, return the value as a string.
15989 Search is case-insensitive.
15991 If LITERAL-NIL is set, return the string value \"nil\" as
15992 a string, do not interpret it as the list atom nil. This is used
15993 for inheritance when a \"nil\" value can supersede a non-nil
15994 value higher up the hierarchy."
15995 (org-with-point-at pom
15996 (cond
15997 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15998 ;; We need a special property. Use `org-entry-properties' to
15999 ;; retrieve it, but specify the wanted property.
16000 (cdr (assoc-string property (org-entry-properties nil property))))
16001 ((and inherit
16002 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16003 (org-entry-get-with-inheritance property literal-nil))
16005 (let* ((local (org-property--local-values property literal-nil))
16006 (value (and local (mapconcat #'identity (delq nil local) " "))))
16007 (if literal-nil value (org-not-nil value)))))))
16009 (defun org-property-or-variable-value (var &optional inherit)
16010 "Check if there is a property fixing the value of VAR.
16011 If yes, return this value. If not, return the current value of the variable."
16012 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16013 (if (and prop (stringp prop) (string-match "\\S-" prop))
16014 (read prop)
16015 (symbol-value var))))
16017 (defun org-entry-delete (pom property)
16018 "Delete PROPERTY from entry at point-or-marker POM.
16019 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16020 non-nil when a property was removed."
16021 (unless (member property org-special-properties)
16022 (org-with-point-at pom
16023 (let ((range (org-get-property-block)))
16024 (when range
16025 (let* ((begin (car range))
16026 (origin (cdr range))
16027 (end (copy-marker origin))
16028 (re (org-re-property
16029 (concat (regexp-quote property) "\\+?") t t)))
16030 (goto-char begin)
16031 (while (re-search-forward re end t)
16032 (delete-region (match-beginning 0) (line-beginning-position 2)))
16033 ;; If drawer is empty, remove it altogether.
16034 (when (= begin end)
16035 (delete-region (line-beginning-position 0)
16036 (line-beginning-position 2)))
16037 ;; Return non-nil if some property was removed.
16038 (prog1 (/= end origin) (set-marker end nil))))))))
16040 ;; Multi-values properties are properties that contain multiple values
16041 ;; These values are assumed to be single words, separated by whitespace.
16042 (defun org-entry-add-to-multivalued-property (pom property value)
16043 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16044 (let* ((old (org-entry-get pom property))
16045 (values (and old (org-split-string old "[ \t]"))))
16046 (setq value (org-entry-protect-space value))
16047 (unless (member value values)
16048 (setq values (append values (list value)))
16049 (org-entry-put pom property
16050 (mapconcat 'identity values " ")))))
16052 (defun org-entry-remove-from-multivalued-property (pom property value)
16053 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16054 (let* ((old (org-entry-get pom property))
16055 (values (and old (org-split-string old "[ \t]"))))
16056 (setq value (org-entry-protect-space value))
16057 (when (member value values)
16058 (setq values (delete value values))
16059 (org-entry-put pom property
16060 (mapconcat 'identity values " ")))))
16062 (defun org-entry-member-in-multivalued-property (pom property value)
16063 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16064 (let* ((old (org-entry-get pom property))
16065 (values (and old (org-split-string old "[ \t]"))))
16066 (setq value (org-entry-protect-space value))
16067 (member value values)))
16069 (defun org-entry-get-multivalued-property (pom property)
16070 "Return a list of values in a multivalued property."
16071 (let* ((value (org-entry-get pom property))
16072 (values (and value (org-split-string value "[ \t]"))))
16073 (mapcar 'org-entry-restore-space values)))
16075 (defun org-entry-put-multivalued-property (pom property &rest values)
16076 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16077 VALUES should be a list of strings. Spaces will be protected."
16078 (org-entry-put pom property
16079 (mapconcat 'org-entry-protect-space values " "))
16080 (let* ((value (org-entry-get pom property))
16081 (values (and value (org-split-string value "[ \t]"))))
16082 (mapcar 'org-entry-restore-space values)))
16084 (defun org-entry-protect-space (s)
16085 "Protect spaces and newline in string S."
16086 (while (string-match " " s)
16087 (setq s (replace-match "%20" t t s)))
16088 (while (string-match "\n" s)
16089 (setq s (replace-match "%0A" t t s)))
16092 (defun org-entry-restore-space (s)
16093 "Restore spaces and newline in string S."
16094 (while (string-match "%20" s)
16095 (setq s (replace-match " " t t s)))
16096 (while (string-match "%0A" s)
16097 (setq s (replace-match "\n" t t s)))
16100 (defvar org-entry-property-inherited-from (make-marker)
16101 "Marker pointing to the entry from where a property was inherited.
16102 Each call to `org-entry-get-with-inheritance' will set this marker to the
16103 location of the entry where the inheritance search matched. If there was
16104 no match, the marker will point nowhere.
16105 Note that also `org-entry-get' calls this function, if the INHERIT flag
16106 is set.")
16108 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16109 "Get PROPERTY of entry or content at point, search higher levels if needed.
16110 The search will stop at the first ancestor which has the property defined.
16111 If the value found is \"nil\", return nil to show that the property
16112 should be considered as undefined (this is the meaning of nil here).
16113 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16114 (move-marker org-entry-property-inherited-from nil)
16115 (org-with-wide-buffer
16116 (let (value)
16117 (catch 'exit
16118 (while t
16119 (let ((v (org-property--local-values property literal-nil)))
16120 (when v
16121 (setq value
16122 (concat (mapconcat #'identity (delq nil v) " ")
16123 (and value " ")
16124 value)))
16125 (cond
16126 ((car v)
16127 (org-back-to-heading t)
16128 (move-marker org-entry-property-inherited-from (point))
16129 (throw 'exit nil))
16130 ((org-up-heading-safe))
16132 (let ((global
16133 (cdr (or (assoc-string property org-file-properties t)
16134 (assoc-string property org-global-properties t)
16135 (assoc-string property org-global-properties-fixed t)))))
16136 (cond ((not global))
16137 (value (setq value (concat global " " value)))
16138 (t (setq value global))))
16139 (throw 'exit nil))))))
16140 (if literal-nil value (org-not-nil value)))))
16142 (defvar org-property-changed-functions nil
16143 "Hook called when the value of a property has changed.
16144 Each hook function should accept two arguments, the name of the property
16145 and the new value.")
16147 (defun org-entry-put (pom property value)
16148 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16150 If the value is nil, it is converted to the empty string. If it
16151 is not a string, an error is raised. Also raise an error on
16152 invalid property names.
16154 PROPERTY can be any regular property (see
16155 `org-special-properties'). It can also be \"TODO\",
16156 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16158 For the last two properties, VALUE may have any of the special
16159 values \"earlier\" and \"later\". The function then increases or
16160 decreases scheduled or deadline date by one day."
16161 (cond ((null value) (setq value ""))
16162 ((not (stringp value)) (error "Properties values should be strings"))
16163 ((not (org--valid-property-p property))
16164 (user-error "Invalid property name: \"%s\"" property)))
16165 (org-with-point-at pom
16166 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16167 (org-back-to-heading t)
16168 (org-with-limited-levels (org-back-to-heading t)))
16169 (let ((beg (point)))
16170 (cond
16171 ((equal property "TODO")
16172 (cond ((not (org-string-nw-p value)) (setq value 'none))
16173 ((not (member value org-todo-keywords-1))
16174 (user-error "\"%s\" is not a valid TODO state" value)))
16175 (org-todo value)
16176 (org-set-tags nil 'align))
16177 ((equal property "PRIORITY")
16178 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16179 (org-set-tags nil 'align))
16180 ((equal property "SCHEDULED")
16181 (forward-line)
16182 (if (and (looking-at-p org-planning-line-re)
16183 (re-search-forward
16184 org-scheduled-time-regexp (line-end-position) t))
16185 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16186 ((string= value "later") (org-timestamp-change 1 'day))
16187 ((string= value "") (org-schedule '(4)))
16188 (t (org-schedule nil value)))
16189 (if (member value '("earlier" "later" ""))
16190 (call-interactively #'org-schedule)
16191 (org-schedule nil value))))
16192 ((equal property "DEADLINE")
16193 (forward-line)
16194 (if (and (looking-at-p org-planning-line-re)
16195 (re-search-forward
16196 org-deadline-time-regexp (line-end-position) t))
16197 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16198 ((string= value "later") (org-timestamp-change 1 'day))
16199 ((string= value "") (org-deadline '(4)))
16200 (t (org-deadline nil value)))
16201 (if (member value '("earlier" "later" ""))
16202 (call-interactively #'org-deadline)
16203 (org-deadline nil value))))
16204 ((member property org-special-properties)
16205 (error "The %s property cannot be set with `org-entry-put'" property))
16207 (let* ((range (org-get-property-block beg 'force))
16208 (end (cdr range))
16209 (case-fold-search t))
16210 (goto-char (car range))
16211 (if (re-search-forward (org-re-property property nil t) end t)
16212 (progn (delete-region (match-beginning 0) (match-end 0))
16213 (goto-char (match-beginning 0)))
16214 (goto-char end)
16215 (insert "\n")
16216 (backward-char))
16217 (insert ":" property ":")
16218 (when value (insert " " value))
16219 (org-indent-line)))))
16220 (run-hook-with-args 'org-property-changed-functions property value)))
16222 (defun org-buffer-property-keys
16223 (&optional specials defaults columns ignore-malformed)
16224 "Get all property keys in the current buffer.
16226 When SPECIALS is non-nil, also list the special properties that
16227 reflect things like tags and TODO state.
16229 When DEFAULTS is non-nil, also include properties that has
16230 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16231 DESCRIPTION, LOCATION, and LOGGING and others.
16233 When COLUMNS in non-nil, also include property names given in
16234 COLUMN formats in the current buffer.
16236 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16237 automatically performed, such drawers will be silently ignored."
16238 (let ((case-fold-search t)
16239 (props (append
16240 (and specials org-special-properties)
16241 (and defaults (cons org-effort-property org-default-properties))
16242 nil)))
16243 (org-with-wide-buffer
16244 (goto-char (point-min))
16245 (while (re-search-forward org-property-start-re nil t)
16246 (let ((range (org-get-property-block)))
16247 (catch 'skip
16248 (unless range
16249 (when (and (not ignore-malformed)
16250 (not (org-before-first-heading-p))
16251 (y-or-n-p (format "Malformed drawer at %d, repair?"
16252 (line-beginning-position))))
16253 (org-get-property-block nil t))
16254 (throw 'skip nil))
16255 (goto-char (car range))
16256 (let ((begin (car range))
16257 (end (cdr range)))
16258 ;; Make sure that found property block is not located
16259 ;; before current point, as it would generate an infloop.
16260 ;; It can happen, for example, in the following
16261 ;; situation:
16263 ;; * Headline
16264 ;; :PROPERTIES:
16265 ;; ...
16266 ;; :END:
16267 ;; *************** Inlinetask
16268 ;; #+BEGIN_EXAMPLE
16269 ;; :PROPERTIES:
16270 ;; #+END_EXAMPLE
16272 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16273 (while (< (point) end)
16274 (let ((p (progn (looking-at org-property-re)
16275 (match-string-no-properties 2))))
16276 ;; Only add true property name, not extension symbol.
16277 (push (if (not (string-match-p "\\+\\'" p)) p
16278 (substring p 0 -1))
16279 props))
16280 (forward-line))))
16281 (outline-next-heading)))
16282 (when columns
16283 (goto-char (point-min))
16284 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16285 (let ((element (org-element-at-point)))
16286 (when (memq (org-element-type element) '(keyword node-property))
16287 (let ((value (org-element-property :value element))
16288 (start 0))
16289 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16290 (setq start (match-end 0))
16291 (let ((p (match-string-no-properties 1 value)))
16292 (unless (member-ignore-case p org-special-properties)
16293 (push p props))))))))))
16294 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16296 (defun org-property-values (key)
16297 "List all non-nil values of property KEY in current buffer."
16298 (org-with-wide-buffer
16299 (goto-char (point-min))
16300 (let ((case-fold-search t)
16301 (re (org-re-property key))
16302 values)
16303 (while (re-search-forward re nil t)
16304 (push (org-entry-get (point) key) values))
16305 (delete-dups values))))
16307 (defun org-insert-property-drawer ()
16308 "Insert a property drawer into the current entry."
16309 (org-with-wide-buffer
16310 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16311 (org-back-to-heading t)
16312 (org-with-limited-levels (org-back-to-heading t)))
16313 (forward-line)
16314 (when (looking-at-p org-planning-line-re) (forward-line))
16315 (unless (looking-at-p org-property-drawer-re)
16316 ;; Make sure we start editing a line from current entry, not from
16317 ;; next one. It prevents extending text properties or overlays
16318 ;; belonging to the latter.
16319 (when (bolp) (backward-char))
16320 (let ((begin (1+ (point)))
16321 (inhibit-read-only t))
16322 (insert "\n:PROPERTIES:\n:END:")
16323 (when (eobp) (insert "\n"))
16324 (org-indent-region begin (point))))))
16326 (defun org-insert-drawer (&optional arg drawer)
16327 "Insert a drawer at point.
16329 When optional argument ARG is non-nil, insert a property drawer.
16331 Optional argument DRAWER, when non-nil, is a string representing
16332 drawer's name. Otherwise, the user is prompted for a name.
16334 If a region is active, insert the drawer around that region
16335 instead.
16337 Point is left between drawer's boundaries."
16338 (interactive "P")
16339 (let* ((drawer (if arg "PROPERTIES"
16340 (or drawer (read-from-minibuffer "Drawer: ")))))
16341 (cond
16342 ;; With C-u, fall back on `org-insert-property-drawer'
16343 (arg (org-insert-property-drawer))
16344 ;; Check validity of suggested drawer's name.
16345 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16346 (user-error "Invalid drawer name"))
16347 ;; With an active region, insert a drawer at point.
16348 ((not (org-region-active-p))
16349 (progn
16350 (unless (bolp) (insert "\n"))
16351 (insert (format ":%s:\n\n:END:\n" drawer))
16352 (forward-line -2)))
16353 ;; Otherwise, insert the drawer at point
16355 (let ((rbeg (region-beginning))
16356 (rend (copy-marker (region-end))))
16357 (unwind-protect
16358 (progn
16359 (goto-char rbeg)
16360 (beginning-of-line)
16361 (when (save-excursion
16362 (re-search-forward org-outline-regexp-bol rend t))
16363 (user-error "Drawers cannot contain headlines"))
16364 ;; Position point at the beginning of the first
16365 ;; non-blank line in region. Insert drawer's opening
16366 ;; there, then indent it.
16367 (org-skip-whitespace)
16368 (beginning-of-line)
16369 (insert ":" drawer ":\n")
16370 (forward-line -1)
16371 (indent-for-tab-command)
16372 ;; Move point to the beginning of the first blank line
16373 ;; after the last non-blank line in region. Insert
16374 ;; drawer's closing, then indent it.
16375 (goto-char rend)
16376 (skip-chars-backward " \r\t\n")
16377 (insert "\n:END:")
16378 (deactivate-mark t)
16379 (indent-for-tab-command)
16380 (unless (eolp) (insert "\n")))
16381 ;; Clear marker, whatever the outcome of insertion is.
16382 (set-marker rend nil)))))))
16384 (defvar org-property-set-functions-alist nil
16385 "Property set function alist.
16386 Each entry should have the following format:
16388 (PROPERTY . READ-FUNCTION)
16390 The read function will be called with the same argument as
16391 `org-completing-read'.")
16393 (defun org-set-property-function (property)
16394 "Get the function that should be used to set PROPERTY.
16395 This is computed according to `org-property-set-functions-alist'."
16396 (or (cdr (assoc property org-property-set-functions-alist))
16397 'org-completing-read))
16399 (defun org-read-property-value (property)
16400 "Read PROPERTY value from user."
16401 (let* ((completion-ignore-case t)
16402 (allowed (org-property-get-allowed-values nil property 'table))
16403 (cur (org-entry-get nil property))
16404 (prompt (concat property " value"
16405 (if (and cur (string-match "\\S-" cur))
16406 (concat " [" cur "]") "") ": "))
16407 (set-function (org-set-property-function property))
16408 (val (if allowed
16409 (funcall set-function prompt allowed nil
16410 (not (get-text-property 0 'org-unrestricted
16411 (caar allowed))))
16412 (funcall set-function prompt
16413 (mapcar 'list (org-property-values property))
16414 nil nil "" nil cur))))
16415 (org-trim val)))
16417 (defvar org-last-set-property nil)
16418 (defvar org-last-set-property-value nil)
16419 (defun org-read-property-name ()
16420 "Read a property name."
16421 (let ((completion-ignore-case t)
16422 (default-prop (or (and (org-at-property-p)
16423 (match-string-no-properties 2))
16424 org-last-set-property)))
16425 (org-completing-read
16426 (concat "Property"
16427 (if default-prop (concat " [" default-prop "]") "")
16428 ": ")
16429 (mapcar #'list (org-buffer-property-keys nil t t))
16430 nil nil nil nil default-prop)))
16432 (defun org-set-property-and-value (use-last)
16433 "Allow to set [PROPERTY]: [value] direction from prompt.
16434 When use-default, don't even ask, just use the last
16435 \"[PROPERTY]: [value]\" string from the history."
16436 (interactive "P")
16437 (let* ((completion-ignore-case t)
16438 (pv (or (and use-last org-last-set-property-value)
16439 (org-completing-read
16440 "Enter a \"[Property]: [value]\" pair: "
16441 nil nil nil nil nil
16442 org-last-set-property-value)))
16443 prop val)
16444 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16445 (setq prop (match-string 1 pv)
16446 val (match-string 2 pv))
16447 (org-set-property prop val))))
16449 (defun org-set-property (property value)
16450 "In the current entry, set PROPERTY to VALUE.
16452 When called interactively, this will prompt for a property name, offering
16453 completion on existing and default properties. And then it will prompt
16454 for a value, offering completion either on allowed values (via an inherited
16455 xxx_ALL property) or on existing values in other instances of this property
16456 in the current file.
16458 Throw an error when trying to set a property with an invalid name."
16459 (interactive (list nil nil))
16460 (let ((property (or property (org-read-property-name))))
16461 ;; `org-entry-put' also makes the following check, but this one
16462 ;; avoids polluting `org-last-set-property' and
16463 ;; `org-last-set-property-value' needlessly.
16464 (unless (org--valid-property-p property)
16465 (user-error "Invalid property name: \"%s\"" property))
16466 (let ((value (or value (org-read-property-value property)))
16467 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16468 (setq org-last-set-property property)
16469 (setq org-last-set-property-value (concat property ": " value))
16470 ;; Possibly postprocess the inserted value:
16471 (when fn (setq value (funcall fn value)))
16472 (unless (equal (org-entry-get nil property) value)
16473 (org-entry-put nil property value)))))
16475 (defun org-find-property (property &optional value)
16476 "Find first entry in buffer that sets PROPERTY.
16478 When optional argument VALUE is non-nil, only consider an entry
16479 if it contains PROPERTY set to this value. If PROPERTY should be
16480 explicitly set to nil, use string \"nil\" for VALUE.
16482 Return position where the entry begins, or nil if there is no
16483 such entry. If narrowing is in effect, only search the visible
16484 part of the buffer."
16485 (save-excursion
16486 (goto-char (point-min))
16487 (let ((case-fold-search t)
16488 (re (org-re-property property nil (not value) value)))
16489 (catch 'exit
16490 (while (re-search-forward re nil t)
16491 (when (if value (org-at-property-p)
16492 (org-entry-get (point) property nil t))
16493 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16495 (defun org-delete-property (property)
16496 "In the current entry, delete PROPERTY."
16497 (interactive
16498 (let* ((completion-ignore-case t)
16499 (cat (org-entry-get (point) "CATEGORY"))
16500 (props0 (org-entry-properties nil 'standard))
16501 (props (if cat props0
16502 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16503 (prop (if (< 1 (length props))
16504 (completing-read "Property: " props nil t)
16505 (caar props))))
16506 (list prop)))
16507 (if (not property)
16508 (message "No property to delete in this entry")
16509 (org-entry-delete nil property)
16510 (message "Property \"%s\" deleted" property)))
16512 (defun org-delete-property-globally (property)
16513 "Remove PROPERTY globally, from all entries.
16514 This function ignores narrowing, if any."
16515 (interactive
16516 (let* ((completion-ignore-case t)
16517 (prop (completing-read
16518 "Globally remove property: "
16519 (mapcar #'list (org-buffer-property-keys)))))
16520 (list prop)))
16521 (org-with-wide-buffer
16522 (goto-char (point-min))
16523 (let ((count 0)
16524 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16525 (while (re-search-forward re nil t)
16526 (when (org-entry-delete (point) property) (cl-incf count)))
16527 (message "Property \"%s\" removed from %d entries" property count))))
16529 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16531 (defun org-compute-property-at-point ()
16532 "Compute the property at point.
16533 This looks for an enclosing column format, extracts the operator and
16534 then applies it to the property in the column format's scope."
16535 (interactive)
16536 (unless (org-at-property-p)
16537 (user-error "Not at a property"))
16538 (let ((prop (match-string-no-properties 2)))
16539 (org-columns-get-format-and-top-level)
16540 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16541 (user-error "No operator defined for property %s" prop))
16542 (org-columns-compute prop)))
16544 (defvar org-property-allowed-value-functions nil
16545 "Hook for functions supplying allowed values for a specific property.
16546 The functions must take a single argument, the name of the property, and
16547 return a flat list of allowed values. If \":ETC\" is one of
16548 the values, this means that these values are intended as defaults for
16549 completion, but that other values should be allowed too.
16550 The functions must return nil if they are not responsible for this
16551 property.")
16553 (defun org-property-get-allowed-values (pom property &optional table)
16554 "Get allowed values for the property PROPERTY.
16555 When TABLE is non-nil, return an alist that can directly be used for
16556 completion."
16557 (let (vals)
16558 (cond
16559 ((equal property "TODO")
16560 (setq vals (org-with-point-at pom
16561 (append org-todo-keywords-1 '("")))))
16562 ((equal property "PRIORITY")
16563 (let ((n org-lowest-priority))
16564 (while (>= n org-highest-priority)
16565 (push (char-to-string n) vals)
16566 (setq n (1- n)))))
16567 ((equal property "CATEGORY"))
16568 ((member property org-special-properties))
16569 ((setq vals (run-hook-with-args-until-success
16570 'org-property-allowed-value-functions property)))
16572 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16573 (when (and vals (string-match "\\S-" vals))
16574 (setq vals (car (read-from-string (concat "(" vals ")"))))
16575 (setq vals (mapcar (lambda (x)
16576 (cond ((stringp x) x)
16577 ((numberp x) (number-to-string x))
16578 ((symbolp x) (symbol-name x))
16579 (t "???")))
16580 vals)))))
16581 (when (member ":ETC" vals)
16582 (setq vals (remove ":ETC" vals))
16583 (org-add-props (car vals) '(org-unrestricted t)))
16584 (if table (mapcar 'list vals) vals)))
16586 (defun org-property-previous-allowed-value (&optional _previous)
16587 "Switch to the next allowed value for this property."
16588 (interactive)
16589 (org-property-next-allowed-value t))
16591 (defun org-property-next-allowed-value (&optional previous)
16592 "Switch to the next allowed value for this property."
16593 (interactive)
16594 (unless (org-at-property-p)
16595 (user-error "Not at a property"))
16596 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16597 (key (match-string 2))
16598 (value (match-string 3))
16599 (allowed (or (org-property-get-allowed-values (point) key)
16600 (and (member value '("[ ]" "[-]" "[X]"))
16601 '("[ ]" "[X]"))))
16602 (heading (save-match-data (nth 4 (org-heading-components))))
16603 nval)
16604 (unless allowed
16605 (user-error "Allowed values for this property have not been defined"))
16606 (when previous (setq allowed (reverse allowed)))
16607 (when (member value allowed)
16608 (setq nval (car (cdr (member value allowed)))))
16609 (setq nval (or nval (car allowed)))
16610 (when (equal nval value)
16611 (user-error "Only one allowed value for this property"))
16612 (org-at-property-p)
16613 (replace-match (concat " :" key ": " nval) t t)
16614 (org-indent-line)
16615 (beginning-of-line 1)
16616 (skip-chars-forward " \t")
16617 (when (equal prop org-effort-property)
16618 (org-refresh-property
16619 '((effort . identity)
16620 (effort-minutes . org-duration-string-to-minutes))
16621 nval)
16622 (when (string= org-clock-current-task heading)
16623 (setq org-clock-effort nval)
16624 (org-clock-update-mode-line)))
16625 (run-hook-with-args 'org-property-changed-functions key nval)))
16627 (defun org-find-olp (path &optional this-buffer)
16628 "Return a marker pointing to the entry at outline path OLP.
16629 If anything goes wrong, throw an error.
16630 You can wrap this call to catch the error like this:
16632 \(condition-case msg
16633 \(org-mobile-locate-entry (match-string 4))
16634 \(error (nth 1 msg)))
16636 The return value will then be either a string with the error message,
16637 or a marker if everything is OK.
16639 If THIS-BUFFER is set, the outline path does not contain a file,
16640 only headings."
16641 (let* ((file (if this-buffer buffer-file-name (pop path)))
16642 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16643 (level 1)
16644 (lmin 1)
16645 (lmax 1)
16646 end found flevel)
16647 (unless buffer (error "File not found :%s" file))
16648 (with-current-buffer buffer
16649 (org-with-wide-buffer
16650 (goto-char (point-min))
16651 (dolist (heading path)
16652 (let ((re (format org-complex-heading-regexp-format
16653 (regexp-quote heading)))
16654 (cnt 0))
16655 (while (re-search-forward re end t)
16656 (setq level (- (match-end 1) (match-beginning 1)))
16657 (when (and (>= level lmin) (<= level lmax))
16658 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16659 (when (= cnt 0)
16660 (error "Heading not found on level %d: %s" lmax heading))
16661 (when (> cnt 1)
16662 (error "Heading not unique on level %d: %s" lmax heading))
16663 (goto-char found)
16664 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16665 (setq end (save-excursion (org-end-of-subtree t t)))))
16666 (when (org-at-heading-p)
16667 (point-marker))))))
16669 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16670 "Find node HEADING in BUFFER.
16671 Return a marker to the heading if it was found, or nil if not.
16672 If POS-ONLY is set, return just the position instead of a marker.
16674 The heading text must match exact, but it may have a TODO keyword,
16675 a priority cookie and tags in the standard locations."
16676 (with-current-buffer (or buffer (current-buffer))
16677 (org-with-wide-buffer
16678 (goto-char (point-min))
16679 (let (case-fold-search)
16680 (when (re-search-forward
16681 (format org-complex-heading-regexp-format
16682 (regexp-quote heading)) nil t)
16683 (if pos-only
16684 (match-beginning 0)
16685 (move-marker (make-marker) (match-beginning 0))))))))
16687 (defun org-find-exact-heading-in-directory (heading &optional dir)
16688 "Find Org node headline HEADING in all .org files in directory DIR.
16689 When the target headline is found, return a marker to this location."
16690 (let ((files (directory-files (or dir default-directory)
16691 t "\\`[^.#].*\\.org\\'"))
16692 visiting m buffer)
16693 (catch 'found
16694 (dolist (file files)
16695 (message "trying %s" file)
16696 (setq visiting (org-find-base-buffer-visiting file))
16697 (setq buffer (or visiting (find-file-noselect file)))
16698 (setq m (org-find-exact-headline-in-buffer
16699 heading buffer))
16700 (when (and (not m) (not visiting)) (kill-buffer buffer))
16701 (and m (throw 'found m))))))
16703 (defun org-find-entry-with-id (ident)
16704 "Locate the entry that contains the ID property with exact value IDENT.
16705 IDENT can be a string, a symbol or a number, this function will search for
16706 the string representation of it.
16707 Return the position where this entry starts, or nil if there is no such entry."
16708 (interactive "sID: ")
16709 (let ((id (cond
16710 ((stringp ident) ident)
16711 ((symbolp ident) (symbol-name ident))
16712 ((numberp ident) (number-to-string ident))
16713 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16714 (org-with-wide-buffer (org-find-property "ID" id))))
16716 ;;;; Timestamps
16718 (defvar org-last-changed-timestamp nil)
16719 (defvar org-last-inserted-timestamp nil
16720 "The last time stamp inserted with `org-insert-time-stamp'.")
16721 (defvar org-ts-what) ; dynamically scoped parameter
16723 (defun org-time-stamp (arg &optional inactive)
16724 "Prompt for a date/time and insert a time stamp.
16726 If the user specifies a time like HH:MM or if this command is
16727 called with at least one prefix argument, the time stamp contains
16728 the date and the time. Otherwise, only the date is included.
16730 All parts of a date not specified by the user are filled in from
16731 the timestamp at point, if any, or the current date/time
16732 otherwise.
16734 If there is already a timestamp at the cursor, it is replaced.
16736 With two universal prefix arguments, insert an active timestamp
16737 with the current time without prompting the user.
16739 When called from lisp, the timestamp is inactive if INACTIVE is
16740 non-nil."
16741 (interactive "P")
16742 (let* ((ts (cond
16743 ((org-at-date-range-p t)
16744 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16745 ((org-at-timestamp-p t) (match-string 0))))
16746 ;; Default time is either the timestamp at point or today.
16747 ;; When entering a range, only the range start is considered.
16748 (default-time (if (not ts) (current-time)
16749 (apply #'encode-time (org-parse-time-string ts))))
16750 (default-input (and ts (org-get-compact-tod ts)))
16751 (repeater (and ts
16752 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16753 (match-string 0 ts)))
16754 org-time-was-given
16755 org-end-time-was-given
16756 (time
16757 (and (if (equal arg '(16)) (current-time)
16758 ;; Preserve `this-command' and `last-command'.
16759 (let ((this-command this-command)
16760 (last-command last-command))
16761 (org-read-date
16762 arg 'totime nil nil default-time default-input
16763 inactive))))))
16764 (cond
16765 ((and ts
16766 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16767 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16768 (insert "--")
16769 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16771 ;; Make sure we're on a timestamp. When in the middle of a date
16772 ;; range, move arbitrarily to range end.
16773 (unless (org-at-timestamp-p t)
16774 (skip-chars-forward "-")
16775 (org-at-timestamp-p t))
16776 (replace-match "")
16777 (setq org-last-changed-timestamp
16778 (org-insert-time-stamp
16779 time (or org-time-was-given arg)
16780 inactive nil nil (list org-end-time-was-given)))
16781 (when repeater
16782 (backward-char)
16783 (insert " " repeater)
16784 (setq org-last-changed-timestamp
16785 (concat (substring org-last-inserted-timestamp 0 -1)
16786 " " repeater ">")))
16787 (message "Timestamp updated"))
16788 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16789 (t (org-insert-time-stamp
16790 time (or org-time-was-given arg) inactive nil nil
16791 (list org-end-time-was-given))))))
16793 ;; FIXME: can we use this for something else, like computing time differences?
16794 (defun org-get-compact-tod (s)
16795 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16796 (let* ((t1 (match-string 1 s))
16797 (h1 (string-to-number (match-string 2 s)))
16798 (m1 (string-to-number (match-string 3 s)))
16799 (t2 (and (match-end 4) (match-string 5 s)))
16800 (h2 (and t2 (string-to-number (match-string 6 s))))
16801 (m2 (and t2 (string-to-number (match-string 7 s))))
16802 dh dm)
16803 (if (not t2)
16805 (setq dh (- h2 h1) dm (- m2 m1))
16806 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16807 (concat t1 "+" (number-to-string dh)
16808 (and (/= 0 dm) (format ":%02d" dm)))))))
16810 (defun org-time-stamp-inactive (&optional arg)
16811 "Insert an inactive time stamp.
16812 An inactive time stamp is enclosed in square brackets instead of angle
16813 brackets. It is inactive in the sense that it does not trigger agenda entries,
16814 does not link to the calendar and cannot be changed with the S-cursor keys.
16815 So these are more for recording a certain time/date."
16816 (interactive "P")
16817 (org-time-stamp arg 'inactive))
16819 (defvar org-date-ovl (make-overlay 1 1))
16820 (overlay-put org-date-ovl 'face 'org-date-selected)
16821 (delete-overlay org-date-ovl)
16823 (defvar org-ans1) ; dynamically scoped parameter
16824 (defvar org-ans2) ; dynamically scoped parameter
16826 (defvar org-plain-time-of-day-regexp) ; defined below
16828 (defvar org-overriding-default-time nil) ; dynamically scoped
16829 (defvar org-read-date-overlay nil)
16830 (defvar org-dcst nil) ; dynamically scoped
16831 (defvar org-read-date-history nil)
16832 (defvar org-read-date-final-answer nil)
16833 (defvar org-read-date-analyze-futurep nil)
16834 (defvar org-read-date-analyze-forced-year nil)
16835 (defvar org-read-date-inactive)
16837 (defvar org-read-date-minibuffer-local-map
16838 (let* ((map (make-sparse-keymap)))
16839 (set-keymap-parent map minibuffer-local-map)
16840 (org-defkey map (kbd ".")
16841 (lambda () (interactive)
16842 ;; Are we at the beginning of the prompt?
16843 (if (looking-back "^[^:]+: "
16844 (let ((inhibit-field-text-motion t))
16845 (line-beginning-position)))
16846 (org-eval-in-calendar '(calendar-goto-today))
16847 (insert "."))))
16848 (org-defkey map (kbd "C-.")
16849 (lambda () (interactive)
16850 (org-eval-in-calendar '(calendar-goto-today))))
16851 (org-defkey map [(meta shift left)]
16852 (lambda () (interactive)
16853 (org-eval-in-calendar '(calendar-backward-month 1))))
16854 (org-defkey map [(meta shift right)]
16855 (lambda () (interactive)
16856 (org-eval-in-calendar '(calendar-forward-month 1))))
16857 (org-defkey map [(meta shift up)]
16858 (lambda () (interactive)
16859 (org-eval-in-calendar '(calendar-backward-year 1))))
16860 (org-defkey map [(meta shift down)]
16861 (lambda () (interactive)
16862 (org-eval-in-calendar '(calendar-forward-year 1))))
16863 (org-defkey map [?\e (shift left)]
16864 (lambda () (interactive)
16865 (org-eval-in-calendar '(calendar-backward-month 1))))
16866 (org-defkey map [?\e (shift right)]
16867 (lambda () (interactive)
16868 (org-eval-in-calendar '(calendar-forward-month 1))))
16869 (org-defkey map [?\e (shift up)]
16870 (lambda () (interactive)
16871 (org-eval-in-calendar '(calendar-backward-year 1))))
16872 (org-defkey map [?\e (shift down)]
16873 (lambda () (interactive)
16874 (org-eval-in-calendar '(calendar-forward-year 1))))
16875 (org-defkey map [(shift up)]
16876 (lambda () (interactive)
16877 (org-eval-in-calendar '(calendar-backward-week 1))))
16878 (org-defkey map [(shift down)]
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(calendar-forward-week 1))))
16881 (org-defkey map [(shift left)]
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-backward-day 1))))
16884 (org-defkey map [(shift right)]
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-forward-day 1))))
16887 (org-defkey map "!"
16888 (lambda () (interactive)
16889 (org-eval-in-calendar '(diary-view-entries))
16890 (message "")))
16891 (org-defkey map ">"
16892 (lambda () (interactive)
16893 (org-eval-in-calendar '(calendar-scroll-left 1))))
16894 (org-defkey map "<"
16895 (lambda () (interactive)
16896 (org-eval-in-calendar '(calendar-scroll-right 1))))
16897 (org-defkey map "\C-v"
16898 (lambda () (interactive)
16899 (org-eval-in-calendar
16900 '(calendar-scroll-left-three-months 1))))
16901 (org-defkey map "\M-v"
16902 (lambda () (interactive)
16903 (org-eval-in-calendar
16904 '(calendar-scroll-right-three-months 1))))
16905 map)
16906 "Keymap for minibuffer commands when using `org-read-date'.")
16908 (defvar org-def)
16909 (defvar org-defdecode)
16910 (defvar org-with-time)
16912 (defvar calendar-setup) ; Dynamically scoped.
16913 (defun org-read-date (&optional with-time to-time from-string prompt
16914 default-time default-input inactive)
16915 "Read a date, possibly a time, and make things smooth for the user.
16916 The prompt will suggest to enter an ISO date, but you can also enter anything
16917 which will at least partially be understood by `parse-time-string'.
16918 Unrecognized parts of the date will default to the current day, month, year,
16919 hour and minute. If this command is called to replace a timestamp at point,
16920 or to enter the second timestamp of a range, the default time is taken
16921 from the existing stamp. Furthermore, the command prefers the future,
16922 so if you are giving a date where the year is not given, and the day-month
16923 combination is already past in the current year, it will assume you
16924 mean next year. For details, see the manual. A few examples:
16926 3-2-5 --> 2003-02-05
16927 feb 15 --> currentyear-02-15
16928 2/15 --> currentyear-02-15
16929 sep 12 9 --> 2009-09-12
16930 12:45 --> today 12:45
16931 22 sept 0:34 --> currentyear-09-22 0:34
16932 12 --> currentyear-currentmonth-12
16933 Fri --> nearest Friday after today
16934 -Tue --> last Tuesday
16935 etc.
16937 Furthermore you can specify a relative date by giving, as the *first* thing
16938 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16939 change in days weeks, months, years.
16940 With a single plus or minus, the date is relative to today. With a double
16941 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16942 +4d --> four days from today
16943 +4 --> same as above
16944 +2w --> two weeks from today
16945 ++5 --> five days from default date
16947 The function understands only English month and weekday abbreviations.
16949 While prompting, a calendar is popped up - you can also select the
16950 date with the mouse (button 1). The calendar shows a period of three
16951 months. To scroll it to other months, use the keys `>' and `<'.
16952 If you don't like the calendar, turn it off with
16953 (setq org-read-date-popup-calendar nil)
16955 With optional argument TO-TIME, the date will immediately be converted
16956 to an internal time.
16957 With an optional argument WITH-TIME, the prompt will suggest to
16958 also insert a time. Note that when WITH-TIME is not set, you can
16959 still enter a time, and this function will inform the calling routine
16960 about this change. The calling routine may then choose to change the
16961 format used to insert the time stamp into the buffer to include the time.
16962 With optional argument FROM-STRING, read from this string instead from
16963 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16964 the time/date that is used for everything that is not specified by the
16965 user."
16966 (require 'parse-time)
16967 (let* ((org-with-time with-time)
16968 (org-time-stamp-rounding-minutes
16969 (if (equal org-with-time '(16))
16970 '(0 0)
16971 org-time-stamp-rounding-minutes))
16972 (org-dcst org-display-custom-times)
16973 (ct (org-current-time))
16974 (org-def (or org-overriding-default-time default-time ct))
16975 (org-defdecode (decode-time org-def))
16976 (cur-frame (selected-frame))
16977 (mouse-autoselect-window nil) ; Don't let the mouse jump
16978 (calendar-setup
16979 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16980 (calendar-move-hook nil)
16981 (calendar-view-diary-initially-flag nil)
16982 (calendar-view-holidays-initially-flag nil)
16983 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16984 ;; Rationalize `org-def' and `org-defdecode', if required.
16985 (when (< (nth 2 org-defdecode) org-extend-today-until)
16986 (setf (nth 2 org-defdecode) -1)
16987 (setf (nth 1 org-defdecode) 59)
16988 (setq org-def (apply #'encode-time org-defdecode))
16989 (setq org-defdecode (decode-time org-def)))
16990 (let* ((timestr (format-time-string
16991 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16992 org-def))
16993 (prompt (concat (if prompt (concat prompt " ") "")
16994 (format "Date+time [%s]: " timestr))))
16995 (cond
16996 (from-string (setq ans from-string))
16997 (org-read-date-popup-calendar
16998 (save-excursion
16999 (save-window-excursion
17000 (calendar)
17001 (when (eq calendar-setup 'calendar-only)
17002 (setq cal-frame
17003 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17004 (select-frame cal-frame))
17005 (org-eval-in-calendar '(setq cursor-type nil) t)
17006 (unwind-protect
17007 (progn
17008 (calendar-forward-day (- (time-to-days org-def)
17009 (calendar-absolute-from-gregorian
17010 (calendar-current-date))))
17011 (org-eval-in-calendar nil t)
17012 (let* ((old-map (current-local-map))
17013 (map (copy-keymap calendar-mode-map))
17014 (minibuffer-local-map
17015 (copy-keymap org-read-date-minibuffer-local-map)))
17016 (org-defkey map (kbd "RET") 'org-calendar-select)
17017 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17018 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17019 (unwind-protect
17020 (progn
17021 (use-local-map map)
17022 (setq org-read-date-inactive inactive)
17023 (add-hook 'post-command-hook 'org-read-date-display)
17024 (setq org-ans0
17025 (read-string prompt
17026 default-input
17027 'org-read-date-history
17028 nil))
17029 ;; org-ans0: from prompt
17030 ;; org-ans1: from mouse click
17031 ;; org-ans2: from calendar motion
17032 (setq ans
17033 (concat org-ans0 " " (or org-ans1 org-ans2))))
17034 (remove-hook 'post-command-hook 'org-read-date-display)
17035 (use-local-map old-map)
17036 (when org-read-date-overlay
17037 (delete-overlay org-read-date-overlay)
17038 (setq org-read-date-overlay nil)))))
17039 (bury-buffer "*Calendar*")
17040 (when cal-frame
17041 (delete-frame cal-frame)
17042 (select-frame-set-input-focus cur-frame))))))
17044 (t ; Naked prompt only
17045 (unwind-protect
17046 (setq ans (read-string prompt default-input
17047 'org-read-date-history timestr))
17048 (when org-read-date-overlay
17049 (delete-overlay org-read-date-overlay)
17050 (setq org-read-date-overlay nil))))))
17052 (setq final (org-read-date-analyze ans org-def org-defdecode))
17054 (when org-read-date-analyze-forced-year
17055 (message "Year was forced into %s"
17056 (if org-read-date-force-compatible-dates
17057 "compatible range (1970-2037)"
17058 "range representable on this machine"))
17059 (ding))
17061 ;; One round trip to get rid of 34th of August and stuff like that....
17062 (setq final (decode-time (apply 'encode-time final)))
17064 (setq org-read-date-final-answer ans)
17066 (if to-time
17067 (apply 'encode-time final)
17068 (if (and (boundp 'org-time-was-given) org-time-was-given)
17069 (format "%04d-%02d-%02d %02d:%02d"
17070 (nth 5 final) (nth 4 final) (nth 3 final)
17071 (nth 2 final) (nth 1 final))
17072 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17074 (defun org-read-date-display ()
17075 "Display the current date prompt interpretation in the minibuffer."
17076 (when org-read-date-display-live
17077 (when org-read-date-overlay
17078 (delete-overlay org-read-date-overlay))
17079 (when (minibufferp (current-buffer))
17080 (save-excursion
17081 (end-of-line 1)
17082 (while (not (equal (buffer-substring
17083 (max (point-min) (- (point) 4)) (point))
17084 " "))
17085 (insert " ")))
17086 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17087 " " (or org-ans1 org-ans2)))
17088 (org-end-time-was-given nil)
17089 (f (org-read-date-analyze ans org-def org-defdecode))
17090 (fmts (if org-dcst
17091 org-time-stamp-custom-formats
17092 org-time-stamp-formats))
17093 (fmt (if (or org-with-time
17094 (and (boundp 'org-time-was-given) org-time-was-given))
17095 (cdr fmts)
17096 (car fmts)))
17097 (txt (format-time-string fmt (apply 'encode-time f)))
17098 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17099 (txt (concat "=> " txt)))
17100 (when (and org-end-time-was-given
17101 (string-match org-plain-time-of-day-regexp txt))
17102 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17103 org-end-time-was-given
17104 (substring txt (match-end 0)))))
17105 (when org-read-date-analyze-futurep
17106 (setq txt (concat txt " (=>F)")))
17107 (setq org-read-date-overlay
17108 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17109 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17111 (defun org-read-date-analyze (ans def defdecode)
17112 "Analyze the combined answer of the date prompt."
17113 ;; FIXME: cleanup and comment
17114 ;; Pass `current-time' result to `decode-time' (instead of calling
17115 ;; without arguments) so that only `current-time' has to be
17116 ;; overriden in tests.
17117 (let ((org-def def)
17118 (org-defdecode defdecode)
17119 (nowdecode (decode-time (current-time)))
17120 delta deltan deltaw deltadef year month day
17121 hour minute second wday pm h2 m2 tl wday1
17122 iso-year iso-weekday iso-week iso-date futurep kill-year)
17123 (setq org-read-date-analyze-futurep nil
17124 org-read-date-analyze-forced-year nil)
17125 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17126 (setq ans "+0"))
17128 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17129 (setq ans (replace-match "" t t ans)
17130 deltan (car delta)
17131 deltaw (nth 1 delta)
17132 deltadef (nth 2 delta)))
17134 ;; Check if there is an iso week date in there. If yes, store the
17135 ;; info and postpone interpreting it until the rest of the parsing
17136 ;; is done.
17137 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17138 (setq iso-year (when (match-end 1)
17139 (org-small-year-to-year
17140 (string-to-number (match-string 1 ans))))
17141 iso-weekday (when (match-end 3)
17142 (string-to-number (match-string 3 ans)))
17143 iso-week (string-to-number (match-string 2 ans)))
17144 (setq ans (replace-match "" t t ans)))
17146 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17147 (when (string-match
17148 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17149 (setq year (if (match-end 2)
17150 (string-to-number (match-string 2 ans))
17151 (progn (setq kill-year t)
17152 (string-to-number (format-time-string "%Y"))))
17153 month (string-to-number (match-string 3 ans))
17154 day (string-to-number (match-string 4 ans)))
17155 (setq year (org-small-year-to-year year))
17156 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17157 t nil ans)))
17159 ;; Help matching dotted european dates
17160 (when (string-match
17161 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17162 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17163 (setq kill-year t)
17164 (string-to-number (format-time-string "%Y")))
17165 day (string-to-number (match-string 1 ans))
17166 month (string-to-number (match-string 2 ans))
17167 ans (replace-match (format "%04d-%02d-%02d" year month day)
17168 t nil ans)))
17170 ;; Help matching american dates, like 5/30 or 5/30/7
17171 (when (string-match
17172 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17173 (setq year (if (match-end 4)
17174 (string-to-number (match-string 4 ans))
17175 (progn (setq kill-year t)
17176 (string-to-number (format-time-string "%Y"))))
17177 month (string-to-number (match-string 1 ans))
17178 day (string-to-number (match-string 2 ans)))
17179 (setq year (org-small-year-to-year year))
17180 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17181 t nil ans)))
17182 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17183 ;; If there is a time with am/pm, and *no* time without it, we convert
17184 ;; so that matching will be successful.
17185 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17186 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17187 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17188 (setq hour (string-to-number (match-string 1 ans))
17189 minute (if (match-end 3)
17190 (string-to-number (match-string 3 ans))
17192 pm (equal ?p
17193 (string-to-char (downcase (match-string 4 ans)))))
17194 (if (and (= hour 12) (not pm))
17195 (setq hour 0)
17196 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17197 (setq ans (replace-match (format "%02d:%02d" hour minute)
17198 t t ans))))
17200 ;; Check if a time range is given as a duration
17201 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17202 (setq hour (string-to-number (match-string 1 ans))
17203 h2 (+ hour (string-to-number (match-string 3 ans)))
17204 minute (string-to-number (match-string 2 ans))
17205 m2 (+ minute (if (match-end 5) (string-to-number
17206 (match-string 5 ans))0)))
17207 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17208 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17209 t t ans)))
17211 ;; Check if there is a time range
17212 (when (boundp 'org-end-time-was-given)
17213 (setq org-time-was-given nil)
17214 (when (and (string-match org-plain-time-of-day-regexp ans)
17215 (match-end 8))
17216 (setq org-end-time-was-given (match-string 8 ans))
17217 (setq ans (concat (substring ans 0 (match-beginning 7))
17218 (substring ans (match-end 7))))))
17220 (setq tl (parse-time-string ans)
17221 day (or (nth 3 tl) (nth 3 org-defdecode))
17222 month
17223 (cond ((nth 4 tl))
17224 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17225 ;; Day was specified. Make sure DAY+MONTH
17226 ;; combination happens in the future.
17227 ((nth 3 tl)
17228 (setq futurep t)
17229 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17230 (nth 4 nowdecode)))
17231 (t (nth 4 org-defdecode)))
17232 year
17233 (cond ((and (not kill-year) (nth 5 tl)))
17234 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17235 ;; Month was guessed in the future and is at least
17236 ;; equal to NOWDECODE's. Fix year accordingly.
17237 (futurep
17238 (if (or (> month (nth 4 nowdecode))
17239 (>= day (nth 3 nowdecode)))
17240 (nth 5 nowdecode)
17241 (1+ (nth 5 nowdecode))))
17242 ;; Month was specified. Make sure MONTH+YEAR
17243 ;; combination happens in the future.
17244 ((nth 4 tl)
17245 (setq futurep t)
17246 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17247 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17248 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17249 (t (nth 5 nowdecode))))
17250 (t (nth 5 org-defdecode)))
17251 hour (or (nth 2 tl) (nth 2 org-defdecode))
17252 minute (or (nth 1 tl) (nth 1 org-defdecode))
17253 second (or (nth 0 tl) 0)
17254 wday (nth 6 tl))
17256 (when (and (eq org-read-date-prefer-future 'time)
17257 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17258 (equal day (nth 3 nowdecode))
17259 (equal month (nth 4 nowdecode))
17260 (equal year (nth 5 nowdecode))
17261 (nth 2 tl)
17262 (or (< (nth 2 tl) (nth 2 nowdecode))
17263 (and (= (nth 2 tl) (nth 2 nowdecode))
17264 (nth 1 tl)
17265 (< (nth 1 tl) (nth 1 nowdecode)))))
17266 (setq day (1+ day)
17267 futurep t))
17269 ;; Special date definitions below
17270 (cond
17271 (iso-week
17272 ;; There was an iso week
17273 (require 'cal-iso)
17274 (setq futurep nil)
17275 (setq year (or iso-year year)
17276 day (or iso-weekday wday 1)
17277 wday nil ; to make sure that the trigger below does not match
17278 iso-date (calendar-gregorian-from-absolute
17279 (calendar-iso-to-absolute
17280 (list iso-week day year))))
17281 ; FIXME: Should we also push ISO weeks into the future?
17282 ; (when (and org-read-date-prefer-future
17283 ; (not iso-year)
17284 ; (< (calendar-absolute-from-gregorian iso-date)
17285 ; (time-to-days (current-time))))
17286 ; (setq year (1+ year)
17287 ; iso-date (calendar-gregorian-from-absolute
17288 ; (calendar-iso-to-absolute
17289 ; (list iso-week day year)))))
17290 (setq month (car iso-date)
17291 year (nth 2 iso-date)
17292 day (nth 1 iso-date)))
17293 (deltan
17294 (setq futurep nil)
17295 (unless deltadef
17296 ;; Pass `current-time' result to `decode-time' (instead of
17297 ;; calling without arguments) so that only `current-time' has
17298 ;; to be overriden in tests.
17299 (let ((now (decode-time (current-time))))
17300 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17301 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17302 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17303 ((equal deltaw "m") (setq month (+ month deltan)))
17304 ((equal deltaw "y") (setq year (+ year deltan)))))
17305 ((and wday (not (nth 3 tl)))
17306 ;; Weekday was given, but no day, so pick that day in the week
17307 ;; on or after the derived date.
17308 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17309 (unless (equal wday wday1)
17310 (setq day (+ day (% (- wday wday1 -7) 7))))))
17311 (when (and (boundp 'org-time-was-given)
17312 (nth 2 tl))
17313 (setq org-time-was-given t))
17314 (when (< year 100) (setq year (+ 2000 year)))
17315 ;; Check of the date is representable
17316 (if org-read-date-force-compatible-dates
17317 (progn
17318 (when (< year 1970)
17319 (setq year 1970 org-read-date-analyze-forced-year t))
17320 (when (> year 2037)
17321 (setq year 2037 org-read-date-analyze-forced-year t)))
17322 (condition-case nil
17323 (ignore (encode-time second minute hour day month year))
17324 (error
17325 (setq year (nth 5 org-defdecode))
17326 (setq org-read-date-analyze-forced-year t))))
17327 (setq org-read-date-analyze-futurep futurep)
17328 (list second minute hour day month year)))
17330 (defvar parse-time-weekdays)
17331 (defun org-read-date-get-relative (s today default)
17332 "Check string S for special relative date string.
17333 TODAY and DEFAULT are internal times, for today and for a default.
17334 Return shift list (N what def-flag)
17335 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17336 N is the number of WHATs to shift.
17337 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17338 the DEFAULT date rather than TODAY."
17339 (require 'parse-time)
17340 (when (and
17341 (string-match
17342 (concat
17343 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17344 "\\([0-9]+\\)?"
17345 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17346 "\\([ \t]\\|$\\)") s)
17347 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17348 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17349 (string-to-char (substring (match-string 1 s) -1))
17350 ?+))
17351 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17352 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17353 (what (if (match-end 3) (match-string 3 s) "d"))
17354 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17355 (date (if rel default today))
17356 (wday (nth 6 (decode-time date)))
17357 delta)
17358 (if wday1
17359 (progn
17360 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17361 (when (= delta 0) (setq delta 7))
17362 (when (= dir ?-)
17363 (setq delta (- delta 7))
17364 (when (= delta 0) (setq delta -7)))
17365 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17366 (list delta "d" rel))
17367 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17369 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17370 "Turn a user-specified date into the internal representation.
17371 The internal representation needed by the calendar is (month day year).
17372 This is a wrapper to handle the brain-dead convention in calendar that
17373 user function argument order change dependent on argument order."
17374 (pcase calendar-date-style
17375 (`american (list arg1 arg2 arg3))
17376 (`european (list arg2 arg1 arg3))
17377 (`iso (list arg2 arg3 arg1))))
17379 (defun org-eval-in-calendar (form &optional keepdate)
17380 "Eval FORM in the calendar window and return to current window.
17381 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17382 (let ((sf (selected-frame))
17383 (sw (selected-window)))
17384 (select-window (get-buffer-window "*Calendar*" t))
17385 (eval form)
17386 (when (and (not keepdate) (calendar-cursor-to-date))
17387 (let* ((date (calendar-cursor-to-date))
17388 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17389 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17390 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17391 (select-window sw)
17392 (select-frame-set-input-focus sf)))
17394 (defun org-calendar-select ()
17395 "Return to `org-read-date' with the date currently selected.
17396 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17397 (interactive)
17398 (when (calendar-cursor-to-date)
17399 (let* ((date (calendar-cursor-to-date))
17400 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17401 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17402 (when (active-minibuffer-window) (exit-minibuffer))))
17404 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17405 "Insert a date stamp for the date given by the internal TIME.
17406 See `format-time-string' for the format of TIME.
17407 WITH-HM means use the stamp format that includes the time of the day.
17408 INACTIVE means use square brackets instead of angular ones, so that the
17409 stamp will not contribute to the agenda.
17410 PRE and POST are optional strings to be inserted before and after the
17411 stamp.
17412 The command returns the inserted time stamp."
17413 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17414 stamp)
17415 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17416 (insert-before-markers (or pre ""))
17417 (when (listp extra)
17418 (setq extra (car extra))
17419 (if (and (stringp extra)
17420 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17421 (setq extra (format "-%02d:%02d"
17422 (string-to-number (match-string 1 extra))
17423 (string-to-number (match-string 2 extra))))
17424 (setq extra nil)))
17425 (when extra
17426 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17427 (insert-before-markers (setq stamp (format-time-string fmt time)))
17428 (insert-before-markers (or post ""))
17429 (setq org-last-inserted-timestamp stamp)))
17431 (defun org-toggle-time-stamp-overlays ()
17432 "Toggle the use of custom time stamp formats."
17433 (interactive)
17434 (setq org-display-custom-times (not org-display-custom-times))
17435 (unless org-display-custom-times
17436 (let ((p (point-min)) (bmp (buffer-modified-p)))
17437 (while (setq p (next-single-property-change p 'display))
17438 (when (and (get-text-property p 'display)
17439 (eq (get-text-property p 'face) 'org-date))
17440 (remove-text-properties
17441 p (setq p (next-single-property-change p 'display))
17442 '(display t))))
17443 (set-buffer-modified-p bmp)))
17444 (org-restart-font-lock)
17445 (setq org-table-may-need-update t)
17446 (if org-display-custom-times
17447 (message "Time stamps are overlaid with custom format")
17448 (message "Time stamp overlays removed")))
17450 (defun org-display-custom-time (beg end)
17451 "Overlay modified time stamp format over timestamp between BEG and END."
17452 (let* ((ts (buffer-substring beg end))
17453 t1 w1 with-hm tf time str w2 (off 0))
17454 (save-match-data
17455 (setq t1 (org-parse-time-string ts t))
17456 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17457 (setq off (- (match-end 0) (match-beginning 0)))))
17458 (setq end (- end off))
17459 (setq w1 (- end beg)
17460 with-hm (and (nth 1 t1) (nth 2 t1))
17461 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17462 time (org-fix-decoded-time t1)
17463 str (org-add-props
17464 (format-time-string
17465 (substring tf 1 -1) (apply 'encode-time time))
17466 nil 'mouse-face 'highlight)
17467 w2 (length str))
17468 (unless (= w2 w1)
17469 (add-text-properties (1+ beg) (+ 2 beg)
17470 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17471 (put-text-property beg end 'display str)))
17473 (defun org-fix-decoded-time (time)
17474 "Set 0 instead of nil for the first 6 elements of time.
17475 Don't touch the rest."
17476 (let ((n 0))
17477 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17479 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17480 "Difference between TIMESTAMP-STRING and now in days.
17481 If SECONDS is non-nil, return the difference in seconds."
17482 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17483 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17484 (funcall fdiff (current-time)))))
17486 (defun org-deadline-close-p (timestamp-string &optional ndays)
17487 "Is the time in TIMESTAMP-STRING close to the current date?"
17488 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17489 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17490 (not (org-entry-is-done-p))))
17492 (defun org-get-wdays (ts &optional delay zero-delay)
17493 "Get the deadline lead time appropriate for timestring TS.
17494 When DELAY is non-nil, get the delay time for scheduled items
17495 instead of the deadline lead time. When ZERO-DELAY is non-nil
17496 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17497 don't try to find the delay cookie in the scheduled timestamp."
17498 (let ((tv (if delay org-scheduled-delay-days
17499 org-deadline-warning-days)))
17500 (cond
17501 ((or (and delay (< tv 0))
17502 (and delay zero-delay (<= tv 0))
17503 (and (not delay) (<= tv 0)))
17504 ;; Enforce this value no matter what
17505 (- tv))
17506 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17507 ;; lead time is specified.
17508 (floor (* (string-to-number (match-string 1 ts))
17509 (cdr (assoc (match-string 2 ts)
17510 '(("d" . 1) ("w" . 7)
17511 ("m" . 30.4) ("y" . 365.25)
17512 ("h" . 0.041667)))))))
17513 ;; go for the default.
17514 (t tv))))
17516 (defun org-calendar-select-mouse (ev)
17517 "Return to `org-read-date' with the date currently selected.
17518 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17519 (interactive "e")
17520 (mouse-set-point ev)
17521 (when (calendar-cursor-to-date)
17522 (let* ((date (calendar-cursor-to-date))
17523 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17524 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17525 (when (active-minibuffer-window) (exit-minibuffer))))
17527 (defun org-check-deadlines (ndays)
17528 "Check if there are any deadlines due or past due.
17529 A deadline is considered due if it happens within `org-deadline-warning-days'
17530 days from today's date. If the deadline appears in an entry marked DONE,
17531 it is not shown. The prefix arg NDAYS can be used to test that many
17532 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17533 (interactive "P")
17534 (let* ((org-warn-days
17535 (cond
17536 ((equal ndays '(4)) 100000)
17537 (ndays (prefix-numeric-value ndays))
17538 (t (abs org-deadline-warning-days))))
17539 (case-fold-search nil)
17540 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17541 (callback
17542 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17543 (message "%d deadlines past-due or due within %d days"
17544 (org-occur regexp nil callback)
17545 org-warn-days)))
17547 (defsubst org-re-timestamp (type)
17548 "Return a regexp for timestamp TYPE.
17549 Allowed values for TYPE are:
17551 all: all timestamps
17552 active: only active timestamps (<...>)
17553 inactive: only inactive timestamps ([...])
17554 scheduled: only scheduled timestamps
17555 deadline: only deadline timestamps
17556 closed: only closed time-stamps
17558 When TYPE is nil, fall back on returning a regexp that matches
17559 both scheduled and deadline timestamps."
17560 (cl-case type
17561 (all org-ts-regexp-both)
17562 (active org-ts-regexp)
17563 (inactive org-ts-regexp-inactive)
17564 (scheduled org-scheduled-time-regexp)
17565 (deadline org-deadline-time-regexp)
17566 (closed org-closed-time-regexp)
17567 (otherwise
17568 (concat "\\<"
17569 (regexp-opt (list org-deadline-string org-scheduled-string))
17570 " *<\\([^>]+\\)>"))))
17572 (defun org-check-before-date (d)
17573 "Check if there are deadlines or scheduled entries before date D."
17574 (interactive (list (org-read-date)))
17575 (let* ((case-fold-search nil)
17576 (regexp (org-re-timestamp org-ts-type))
17577 (ts-type org-ts-type)
17578 (callback
17579 (lambda ()
17580 (let ((match (match-string 1)))
17581 (and (if (memq ts-type '(active inactive all))
17582 (eq (org-element-type (save-excursion
17583 (backward-char)
17584 (org-element-context)))
17585 'timestamp)
17586 (org-at-planning-p))
17587 (time-less-p
17588 (org-time-string-to-time match)
17589 (org-time-string-to-time d)))))))
17590 (message "%d entries before %s"
17591 (org-occur regexp nil callback)
17592 d)))
17594 (defun org-check-after-date (d)
17595 "Check if there are deadlines or scheduled entries after date D."
17596 (interactive (list (org-read-date)))
17597 (let* ((case-fold-search nil)
17598 (regexp (org-re-timestamp org-ts-type))
17599 (ts-type org-ts-type)
17600 (callback
17601 (lambda ()
17602 (let ((match (match-string 1)))
17603 (and (if (memq ts-type '(active inactive all))
17604 (eq (org-element-type (save-excursion
17605 (backward-char)
17606 (org-element-context)))
17607 'timestamp)
17608 (org-at-planning-p))
17609 (not (time-less-p
17610 (org-time-string-to-time match)
17611 (org-time-string-to-time d))))))))
17612 (message "%d entries after %s"
17613 (org-occur regexp nil callback)
17614 d)))
17616 (defun org-check-dates-range (start-date end-date)
17617 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17618 (interactive (list (org-read-date nil nil nil "Range starts")
17619 (org-read-date nil nil nil "Range end")))
17620 (let ((case-fold-search nil)
17621 (regexp (org-re-timestamp org-ts-type))
17622 (callback
17623 (let ((type org-ts-type))
17624 (lambda ()
17625 (let ((match (match-string 1)))
17626 (and
17627 (if (memq type '(active inactive all))
17628 (eq (org-element-type (save-excursion
17629 (backward-char)
17630 (org-element-context)))
17631 'timestamp)
17632 (org-at-planning-p))
17633 (not (time-less-p
17634 (org-time-string-to-time match)
17635 (org-time-string-to-time start-date)))
17636 (time-less-p
17637 (org-time-string-to-time match)
17638 (org-time-string-to-time end-date))))))))
17639 (message "%d entries between %s and %s"
17640 (org-occur regexp nil callback) start-date end-date)))
17642 (defun org-evaluate-time-range (&optional to-buffer)
17643 "Evaluate a time range by computing the difference between start and end.
17644 Normally the result is just printed in the echo area, but with prefix arg
17645 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17646 If the time range is actually in a table, the result is inserted into the
17647 next column.
17648 For time difference computation, a year is assumed to be exactly 365
17649 days in order to avoid rounding problems."
17650 (interactive "P")
17652 (org-clock-update-time-maybe)
17653 (save-excursion
17654 (unless (org-at-date-range-p t)
17655 (goto-char (point-at-bol))
17656 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17657 (unless (org-at-date-range-p t)
17658 (user-error "Not at a time-stamp range, and none found in current line")))
17659 (let* ((ts1 (match-string 1))
17660 (ts2 (match-string 2))
17661 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17662 (match-end (match-end 0))
17663 (time1 (org-time-string-to-time ts1))
17664 (time2 (org-time-string-to-time ts2))
17665 (t1 (float-time time1))
17666 (t2 (float-time time2))
17667 (diff (abs (- t2 t1)))
17668 (negative (< (- t2 t1) 0))
17669 ;; (ys (floor (* 365 24 60 60)))
17670 (ds (* 24 60 60))
17671 (hs (* 60 60))
17672 (fy "%dy %dd %02d:%02d")
17673 (fy1 "%dy %dd")
17674 (fd "%dd %02d:%02d")
17675 (fd1 "%dd")
17676 (fh "%02d:%02d")
17677 y d h m align)
17678 (if havetime
17679 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17681 d (floor (/ diff ds)) diff (mod diff ds)
17682 h (floor (/ diff hs)) diff (mod diff hs)
17683 m (floor (/ diff 60)))
17684 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17686 d (floor (+ (/ diff ds) 0.5))
17687 h 0 m 0))
17688 (if (not to-buffer)
17689 (message "%s" (org-make-tdiff-string y d h m))
17690 (if (org-at-table-p)
17691 (progn
17692 (goto-char match-end)
17693 (setq align t)
17694 (and (looking-at " *|") (goto-char (match-end 0))))
17695 (goto-char match-end))
17696 (when (looking-at
17697 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17698 (replace-match ""))
17699 (when negative (insert " -"))
17700 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17701 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17702 (insert " " (format fh h m))))
17703 (when align (org-table-align))
17704 (message "Time difference inserted")))))
17706 (defun org-make-tdiff-string (y d h m)
17707 (let ((fmt "")
17708 (l nil))
17709 (when (> y 0)
17710 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17711 (push y l))
17712 (when (> d 0)
17713 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17714 (push d l))
17715 (when (> h 0)
17716 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17717 (push h l))
17718 (when (> m 0)
17719 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17720 (push m l))
17721 (apply 'format fmt (nreverse l))))
17723 (defun org-time-string-to-time (s &optional buffer pos)
17724 "Convert a timestamp string into internal time."
17725 (condition-case errdata
17726 (apply 'encode-time (org-parse-time-string s))
17727 (error (error "Bad timestamp `%s'%s\nError was: %s"
17728 s (if (not (and buffer pos))
17730 (format-message " at %d in buffer `%s'" pos buffer))
17731 (cdr errdata)))))
17733 (defun org-time-string-to-seconds (s)
17734 "Convert a timestamp string to a number of seconds."
17735 (float-time (org-time-string-to-time s)))
17737 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17739 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17740 "Convert time stamp S to an absolute day number.
17742 If DAYNR in non-nil, and there is a specifier for a cyclic time
17743 stamp, get the closest date to DAYNR. If PREFER is
17744 `past' (respectively `future') return a date past (respectively
17745 after) or equal to DAYNR.
17747 POS is the location of time stamp S, as a buffer position in
17748 BUFFER.
17750 Diary sexp timestamps are matched against DAYNR, when non-nil.
17751 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17752 signalled."
17753 (cond
17754 ((string-match "\\`%%\\((.*)\\)" s)
17755 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17756 ;; only able to match individual dates. If it fails, raise an
17757 ;; error.
17758 (if (and daynr
17759 (org-diary-sexp-entry
17760 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17761 daynr
17762 (signal 'org-diary-sexp-no-match (list s))))
17763 ((and daynr show-all) (org-closest-date s daynr prefer))
17764 (t (time-to-days
17765 (condition-case errdata
17766 (apply #'encode-time (org-parse-time-string s))
17767 (error (error "Bad timestamp `%s'%s\nError was: %s"
17769 (if (not (and buffer pos)) ""
17770 (format-message " at %d in buffer `%s'" pos buffer))
17771 (cdr errdata))))))))
17773 (defun org-days-to-iso-week (days)
17774 "Return the iso week number."
17775 (require 'cal-iso)
17776 (car (calendar-iso-from-absolute days)))
17778 (defun org-small-year-to-year (year)
17779 "Convert 2-digit years into 4-digit years.
17780 YEAR is expanded into one of the 30 next years, if possible, or
17781 into a past one. Any year larger than 99 is returned unchanged."
17782 (if (>= year 100) year
17783 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17784 (century (/ current 100))
17785 (offset (- year (% current 100))))
17786 (cond ((> offset 30) (+ (* (1- century) 100) year))
17787 ((> offset -70) (+ (* century 100) year))
17788 (t (+ (* (1+ century) 100) year))))))
17790 (defun org-time-from-absolute (d)
17791 "Return the time corresponding to date D.
17792 D may be an absolute day number, or a calendar-type list (month day year)."
17793 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17794 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17796 (defvar org-agenda-current-date)
17797 (defun org-calendar-holiday ()
17798 "List of holidays, for Diary display in Org mode."
17799 (require 'holidays)
17800 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17801 (and hl (mapconcat #'identity hl "; "))))
17803 (defun org-diary-sexp-entry (sexp entry d)
17804 "Process a SEXP diary ENTRY for date D."
17805 (require 'diary-lib)
17806 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17807 ;; dynamically.
17808 (let* ((sexp `(let ((entry ,entry)
17809 (date ',d))
17810 ,(car (read-from-string sexp))))
17811 (result (if calendar-debug-sexp (eval sexp)
17812 (condition-case nil
17813 (eval sexp)
17814 (error
17815 (beep)
17816 (message "Bad sexp at line %d in %s: %s"
17817 (org-current-line)
17818 (buffer-file-name) sexp)
17819 (sleep-for 2))))))
17820 (cond ((stringp result) (split-string result "; "))
17821 ((and (consp result)
17822 (not (consp (cdr result)))
17823 (stringp (cdr result))) (cdr result))
17824 ((and (consp result)
17825 (stringp (car result))) result)
17826 (result entry))))
17828 (defun org-diary-to-ical-string (frombuf)
17829 "Get iCalendar entries from diary entries in buffer FROMBUF.
17830 This uses the icalendar.el library."
17831 (let* ((tmpdir temporary-file-directory)
17832 (tmpfile (make-temp-name
17833 (expand-file-name "orgics" tmpdir)))
17834 buf rtn b e)
17835 (with-current-buffer frombuf
17836 (icalendar-export-region (point-min) (point-max) tmpfile)
17837 (setq buf (find-buffer-visiting tmpfile))
17838 (set-buffer buf)
17839 (goto-char (point-min))
17840 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17841 (setq b (match-beginning 0)))
17842 (goto-char (point-max))
17843 (when (re-search-backward "^END:VEVENT" nil t)
17844 (setq e (match-end 0)))
17845 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17846 (kill-buffer buf)
17847 (delete-file tmpfile)
17848 rtn))
17850 (defun org-closest-date (start current prefer)
17851 "Return closest date to CURRENT starting from START.
17853 CURRENT and START are both time stamps.
17855 When PREFER is `past', return a date that is either CURRENT or
17856 past. When PREFER is `future', return a date that is either
17857 CURRENT or future.
17859 Only time stamps with a repeater are modified. Any other time
17860 stamp stay unchanged. In any case, return value is an absolute
17861 day number."
17862 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17863 ;; No repeater. Do not shift time stamp.
17864 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17865 (let ((value (string-to-number (match-string 1 start)))
17866 (type (match-string 2 start)))
17867 (if (= 0 value)
17868 ;; Repeater with a 0-value is considered as void.
17869 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17870 (let* ((base (org-date-to-gregorian start))
17871 (target (org-date-to-gregorian current))
17872 (sday (calendar-absolute-from-gregorian base))
17873 (cday (calendar-absolute-from-gregorian target))
17874 n1 n2)
17875 ;; If START is already past CURRENT, just return START.
17876 (if (<= cday sday) sday
17877 ;; Compute closest date before (N1) and closest date past
17878 ;; (N2) CURRENT.
17879 (pcase type
17880 ("h"
17881 (let ((missing-hours
17882 (mod (+ (- (* 24 (- cday sday))
17883 (nth 2 (org-parse-time-string start)))
17884 org-extend-today-until)
17885 value)))
17886 (setf n1 (if (= missing-hours 0) cday
17887 (- cday (1+ (/ missing-hours 24)))))
17888 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17889 ((or "d" "w")
17890 (let ((value (if (equal type "w") (* 7 value) value)))
17891 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17892 (setf n2 (+ n1 value))))
17893 ("m"
17894 (let* ((add-months
17895 (lambda (d n)
17896 ;; Add N months to gregorian date D, i.e.,
17897 ;; a list (MONTH DAY YEAR). Return a valid
17898 ;; gregorian date.
17899 (let ((m (+ (nth 0 d) n)))
17900 (list (mod m 12)
17901 (nth 1 d)
17902 (+ (/ m 12) (nth 2 d))))))
17903 (months ; Complete months to TARGET.
17904 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17905 (- (nth 0 target) (nth 0 base))
17906 ;; If START's day is greater than
17907 ;; TARGET's, remove incomplete month.
17908 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17909 value)
17910 value))
17911 (before (funcall add-months base months)))
17912 (setf n1 (calendar-absolute-from-gregorian before))
17913 (setf n2
17914 (calendar-absolute-from-gregorian
17915 (funcall add-months before value)))))
17917 (let* ((d (nth 1 base))
17918 (m (nth 0 base))
17919 (y (nth 2 base))
17920 (years ; Complete years to TARGET.
17921 (* (/ (- (nth 2 target)
17923 ;; If START's month and day are
17924 ;; greater than TARGET's, remove
17925 ;; incomplete year.
17926 (if (or (> (nth 0 target) m)
17927 (and (= (nth 0 target) m)
17928 (> (nth 1 target) d)))
17931 value)
17932 value))
17933 (before (list m d (+ y years))))
17934 (setf n1 (calendar-absolute-from-gregorian before))
17935 (setf n2 (calendar-absolute-from-gregorian
17936 (list m d (+ (nth 2 before) value)))))))
17937 ;; Handle PREFER parameter, if any.
17938 (cond
17939 ((eq prefer 'past) (if (= cday n2) n2 n1))
17940 ((eq prefer 'future) (if (= cday n1) n1 n2))
17941 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17943 (defun org-date-to-gregorian (d)
17944 "Turn any specification of date D into a Gregorian date for the calendar."
17945 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17946 ((and (listp d) (= (length d) 3)) d)
17947 ((stringp d)
17948 (let ((d (org-parse-time-string d)))
17949 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17950 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17952 (defun org-parse-time-string (s &optional nodefault)
17953 "Parse the standard Org time string.
17954 This should be a lot faster than the normal `parse-time-string'.
17955 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17956 hour and minute fields will be nil if not given."
17957 (cond ((string-match org-ts-regexp0 s)
17958 (list 0
17959 (when (or (match-beginning 8) (not nodefault))
17960 (string-to-number (or (match-string 8 s) "0")))
17961 (when (or (match-beginning 7) (not nodefault))
17962 (string-to-number (or (match-string 7 s) "0")))
17963 (string-to-number (match-string 4 s))
17964 (string-to-number (match-string 3 s))
17965 (string-to-number (match-string 2 s))
17966 nil nil nil))
17967 ((string-match "^<[^>]+>$" s)
17968 (decode-time (seconds-to-time (org-matcher-time s))))
17969 (t (error "Not a standard Org time string: %s" s))))
17971 (defun org-timestamp-up (&optional arg)
17972 "Increase the date item at the cursor by one.
17973 If the cursor is on the year, change the year. If it is on the month,
17974 the day or the time, change that.
17975 With prefix ARG, change by that many units."
17976 (interactive "p")
17977 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17979 (defun org-timestamp-down (&optional arg)
17980 "Decrease the date item at the cursor by one.
17981 If the cursor is on the year, change the year. If it is on the month,
17982 the day or the time, change that.
17983 With prefix ARG, change by that many units."
17984 (interactive "p")
17985 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17987 (defun org-timestamp-up-day (&optional arg)
17988 "Increase the date in the time stamp by one day.
17989 With prefix ARG, change that many days."
17990 (interactive "p")
17991 (if (and (not (org-at-timestamp-p t))
17992 (org-at-heading-p))
17993 (org-todo 'up)
17994 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17996 (defun org-timestamp-down-day (&optional arg)
17997 "Decrease the date in the time stamp by one day.
17998 With prefix ARG, change that many days."
17999 (interactive "p")
18000 (if (and (not (org-at-timestamp-p t))
18001 (org-at-heading-p))
18002 (org-todo 'down)
18003 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18005 (defun org-at-timestamp-p (&optional inactive-ok)
18006 "Non-nil if point is inside a timestamp.
18008 When optional argument INACTIVE-OK is non-nil, also consider
18009 inactive timestamps.
18011 When this function returns a non-nil value, match data is set
18012 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18013 INACTIVE-OK."
18014 (interactive)
18015 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18016 (pos (point))
18017 (ans (or (looking-at tsr)
18018 (save-excursion
18019 (skip-chars-backward "^[<\n\r\t")
18020 (when (> (point) (point-min)) (backward-char 1))
18021 (and (looking-at tsr)
18022 (> (- (match-end 0) pos) -1))))))
18023 (and ans
18024 (boundp 'org-ts-what)
18025 (setq org-ts-what
18026 (cond
18027 ((= pos (match-beginning 0)) 'bracket)
18028 ;; Point is considered to be "on the bracket" whether
18029 ;; it's really on it or right after it.
18030 ((= pos (1- (match-end 0))) 'bracket)
18031 ((= pos (match-end 0)) 'after)
18032 ((org-pos-in-match-range pos 2) 'year)
18033 ((org-pos-in-match-range pos 3) 'month)
18034 ((org-pos-in-match-range pos 7) 'hour)
18035 ((org-pos-in-match-range pos 8) 'minute)
18036 ((or (org-pos-in-match-range pos 4)
18037 (org-pos-in-match-range pos 5)) 'day)
18038 ((and (> pos (or (match-end 8) (match-end 5)))
18039 (< pos (match-end 0)))
18040 (- pos (or (match-end 8) (match-end 5))))
18041 (t 'day))))
18042 ans))
18044 (defun org-toggle-timestamp-type ()
18045 "Toggle the type (<active> or [inactive]) of a time stamp."
18046 (interactive)
18047 (when (org-at-timestamp-p t)
18048 (let ((beg (match-beginning 0)) (end (match-end 0))
18049 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18050 (save-excursion
18051 (goto-char beg)
18052 (while (re-search-forward "[][<>]" end t)
18053 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18054 t t)))
18055 (message "Timestamp is now %sactive"
18056 (if (equal (char-after beg) ?<) "" "in")))))
18058 (defun org-at-clock-log-p nil
18059 "Is the cursor on the clock log line?"
18060 (save-excursion
18061 (move-beginning-of-line 1)
18062 (looking-at org-clock-line-re)))
18064 (defvar org-clock-history) ; defined in org-clock.el
18065 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18066 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18067 "Change the date in the time stamp at point.
18068 The date will be changed by N times WHAT. WHAT can be `day', `month',
18069 `year', `minute', `second'. If WHAT is not given, the cursor position
18070 in the timestamp determines what will be changed.
18071 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18072 (let ((origin (point)) origin-cat
18073 with-hm inactive
18074 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18075 org-ts-what
18076 extra rem
18077 ts time time0 fixnext clrgx)
18078 (unless (org-at-timestamp-p t)
18079 (user-error "Not at a timestamp"))
18080 (if (and (not what) (eq org-ts-what 'bracket))
18081 (org-toggle-timestamp-type)
18082 ;; Point isn't on brackets. Remember the part of the time-stamp
18083 ;; the point was in. Indeed, size of time-stamps may change,
18084 ;; but point must be kept in the same category nonetheless.
18085 (setq origin-cat org-ts-what)
18086 (when (and (not what) (not (eq org-ts-what 'day))
18087 org-display-custom-times
18088 (get-text-property (point) 'display)
18089 (not (get-text-property (1- (point)) 'display)))
18090 (setq org-ts-what 'day))
18091 (setq org-ts-what (or what org-ts-what)
18092 inactive (= (char-after (match-beginning 0)) ?\[)
18093 ts (match-string 0))
18094 (replace-match "")
18095 (when (string-match
18096 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18098 (setq extra (match-string 1 ts))
18099 (when suppress-tmp-delay
18100 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18101 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18102 (setq with-hm t))
18103 (setq time0 (org-parse-time-string ts))
18104 (when (and updown
18105 (eq org-ts-what 'minute)
18106 (not current-prefix-arg))
18107 ;; This looks like s-up and s-down. Change by one rounding step.
18108 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18109 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18110 (setcar (cdr time0) (+ (nth 1 time0)
18111 (if (> n 0) (- rem) (- dm rem))))))
18112 (setq time
18113 (apply #'encode-time
18114 (or (car time0) 0)
18115 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18116 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18117 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18118 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18119 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18120 (nthcdr 6 time0)))
18121 (when (and (member org-ts-what '(hour minute))
18122 extra
18123 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18124 (setq extra (org-modify-ts-extra
18125 extra
18126 (if (eq org-ts-what 'hour) 2 5)
18127 n dm)))
18128 (when (integerp org-ts-what)
18129 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18130 (when (eq what 'calendar)
18131 (let ((cal-date (org-get-date-from-calendar)))
18132 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18133 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18134 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18135 (setcar time0 (or (car time0) 0))
18136 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18137 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18138 (setq time (apply 'encode-time time0))))
18139 ;; Insert the new time-stamp, and ensure point stays in the same
18140 ;; category as before (i.e. not after the last position in that
18141 ;; category).
18142 (let ((pos (point)))
18143 ;; Stay before inserted string. `save-excursion' is of no use.
18144 (setq org-last-changed-timestamp
18145 (org-insert-time-stamp time with-hm inactive nil nil extra))
18146 (goto-char pos))
18147 (save-match-data
18148 (looking-at org-ts-regexp3)
18149 (goto-char (cond
18150 ;; `day' category ends before `hour' if any, or at
18151 ;; the end of the day name.
18152 ((eq origin-cat 'day)
18153 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18154 ((eq origin-cat 'hour) (min (match-end 7) origin))
18155 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18156 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18157 ;; `year' and `month' have both fixed size: point
18158 ;; couldn't have moved into another part.
18159 (t origin))))
18160 ;; Update clock if on a CLOCK line.
18161 (org-clock-update-time-maybe)
18162 ;; Maybe adjust the closest clock in `org-clock-history'
18163 (when org-clock-adjust-closest
18164 (if (not (and (org-at-clock-log-p)
18165 (< 1 (length (delq nil (mapcar 'marker-position
18166 org-clock-history))))))
18167 (message "No clock to adjust")
18168 (cond ((save-excursion ; fix previous clock?
18169 (re-search-backward org-ts-regexp0 nil t)
18170 (looking-back (concat org-clock-string " \\[")
18171 (line-beginning-position)))
18172 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18173 ((save-excursion ; fix next clock?
18174 (re-search-backward org-ts-regexp0 nil t)
18175 (looking-at (concat org-ts-regexp0 "\\] =>")))
18176 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18177 (save-window-excursion
18178 ;; Find closest clock to point, adjust the previous/next one in history
18179 (let* ((p (save-excursion (org-back-to-heading t)))
18180 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18181 (clfixnth
18182 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18183 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18184 (if (not clfixpos)
18185 (message "No clock to adjust")
18186 (save-excursion
18187 (org-goto-marker-or-bmk clfixpos)
18188 (org-show-subtree)
18189 (when (re-search-forward clrgx nil t)
18190 (goto-char (match-beginning 1))
18191 (let (org-clock-adjust-closest)
18192 (org-timestamp-change n org-ts-what updown))
18193 (message "Clock adjusted in %s for heading: %s"
18194 (file-name-nondirectory (buffer-file-name))
18195 (org-get-heading t t)))))))))
18196 ;; Try to recenter the calendar window, if any.
18197 (when (and org-calendar-follow-timestamp-change
18198 (get-buffer-window "*Calendar*" t)
18199 (memq org-ts-what '(day month year)))
18200 (org-recenter-calendar (time-to-days time))))))
18202 (defun org-modify-ts-extra (s pos n dm)
18203 "Change the different parts of the lead-time and repeat fields in timestamp."
18204 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18205 ng h m new rem)
18206 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18207 (cond
18208 ((or (org-pos-in-match-range pos 2)
18209 (org-pos-in-match-range pos 3))
18210 (setq m (string-to-number (match-string 3 s))
18211 h (string-to-number (match-string 2 s)))
18212 (if (org-pos-in-match-range pos 2)
18213 (setq h (+ h n))
18214 (setq n (* dm (with-no-warnings (signum n))))
18215 (unless (= 0 (setq rem (% m dm)))
18216 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18217 (setq m (+ m n)))
18218 (when (< m 0) (setq m (+ m 60) h (1- h)))
18219 (when (> m 59) (setq m (- m 60) h (1+ h)))
18220 (setq h (mod h 24))
18221 (setq ng 1 new (format "-%02d:%02d" h m)))
18222 ((org-pos-in-match-range pos 6)
18223 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18224 ((org-pos-in-match-range pos 5)
18225 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18227 ((org-pos-in-match-range pos 9)
18228 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18229 ((org-pos-in-match-range pos 8)
18230 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18232 (when ng
18233 (setq s (concat
18234 (substring s 0 (match-beginning ng))
18236 (substring s (match-end ng))))))
18239 (defun org-recenter-calendar (d)
18240 "If the calendar is visible, recenter it to date D."
18241 (let ((cwin (get-buffer-window "*Calendar*" t)))
18242 (when cwin
18243 (let ((calendar-move-hook nil))
18244 (with-selected-window cwin
18245 (calendar-goto-date
18246 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18248 (defun org-goto-calendar (&optional arg)
18249 "Go to the Emacs calendar at the current date.
18250 If there is a time stamp in the current line, go to that date.
18251 A prefix ARG can be used to force the current date."
18252 (interactive "P")
18253 (let ((tsr org-ts-regexp) diff
18254 (calendar-move-hook nil)
18255 (calendar-view-holidays-initially-flag nil)
18256 (calendar-view-diary-initially-flag nil))
18257 (when (or (org-at-timestamp-p)
18258 (save-excursion
18259 (beginning-of-line 1)
18260 (looking-at (concat ".*" tsr))))
18261 (let ((d1 (time-to-days (current-time)))
18262 (d2 (time-to-days
18263 (org-time-string-to-time (match-string 1)))))
18264 (setq diff (- d2 d1))))
18265 (calendar)
18266 (calendar-goto-today)
18267 (when (and diff (not arg)) (calendar-forward-day diff))))
18269 (defun org-get-date-from-calendar ()
18270 "Return a list (month day year) of date at point in calendar."
18271 (with-current-buffer "*Calendar*"
18272 (save-match-data
18273 (calendar-cursor-to-date))))
18275 (defun org-date-from-calendar ()
18276 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18277 If there is already a time stamp at the cursor position, update it."
18278 (interactive)
18279 (if (org-at-timestamp-p t)
18280 (org-timestamp-change 0 'calendar)
18281 (let ((cal-date (org-get-date-from-calendar)))
18282 (org-insert-time-stamp
18283 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18285 (defcustom org-effort-durations
18286 `(("min" . 1)
18287 ("h" . 60)
18288 ("d" . ,(* 60 8))
18289 ("w" . ,(* 60 8 5))
18290 ("m" . ,(* 60 8 5 4))
18291 ("y" . ,(* 60 8 5 40)))
18292 "Conversion factor to minutes for an effort modifier.
18294 Each entry has the form (MODIFIER . MINUTES).
18296 In an effort string, a number followed by MODIFIER is multiplied
18297 by the specified number of MINUTES to obtain an effort in
18298 minutes.
18300 For example, if the value of this variable is ((\"hours\" . 60)), then an
18301 effort string \"2hours\" is equivalent to 120 minutes."
18302 :group 'org-agenda
18303 :version "25.1"
18304 :package-version '(Org . "8.3")
18305 :type '(alist :key-type (string :tag "Modifier")
18306 :value-type (number :tag "Minutes")))
18308 (defun org-minutes-to-clocksum-string (m)
18309 "Format number of minutes as a clocksum string.
18310 The format is determined by `org-time-clocksum-format',
18311 `org-time-clocksum-use-fractional' and
18312 `org-time-clocksum-fractional-format' and
18313 `org-time-clocksum-use-effort-durations'."
18314 (let ((clocksum "")
18315 (m (round m)) ; Don't allow fractions of minutes
18316 h d w mo y fmt n)
18317 (setq h (if org-time-clocksum-use-effort-durations
18318 (cdr (assoc "h" org-effort-durations)) 60)
18319 d (if org-time-clocksum-use-effort-durations
18320 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18321 w (if org-time-clocksum-use-effort-durations
18322 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18323 mo (if org-time-clocksum-use-effort-durations
18324 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18325 y (if org-time-clocksum-use-effort-durations
18326 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18327 ;; fractional format
18328 (if org-time-clocksum-use-fractional
18329 (cond
18330 ;; single format string
18331 ((stringp org-time-clocksum-fractional-format)
18332 (format org-time-clocksum-fractional-format (/ m (float h))))
18333 ;; choice of fractional formats for different time units
18334 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18335 (> (/ (truncate m) (* y d h)) 0))
18336 (format fmt (/ m (* y d (float h)))))
18337 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18338 (> (/ (truncate m) (* mo d h)) 0))
18339 (format fmt (/ m (* mo d (float h)))))
18340 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18341 (> (/ (truncate m) (* w d h)) 0))
18342 (format fmt (/ m (* w d (float h)))))
18343 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18344 (> (/ (truncate m) (* d h)) 0))
18345 (format fmt (/ m (* d (float h)))))
18346 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18347 (> (/ (truncate m) h) 0))
18348 (format fmt (/ m (float h))))
18349 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18350 (format fmt m))
18351 ;; fall back to smallest time unit with a format
18352 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18353 (format fmt (/ m (float h))))
18354 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18355 (format fmt (/ m (* d (float h)))))
18356 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18357 (format fmt (/ m (* w d (float h)))))
18358 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18359 (format fmt (/ m (* mo d (float h)))))
18360 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18361 (format fmt (/ m (* y d (float h))))))
18362 ;; standard (non-fractional) format, with single format string
18363 (if (stringp org-time-clocksum-format)
18364 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18365 ;; separate formats components
18366 (and (setq fmt (plist-get org-time-clocksum-format :years))
18367 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18368 (plist-get org-time-clocksum-format :require-years))
18369 (setq clocksum (concat clocksum (format fmt n))
18370 m (- m (* n y d h))))
18371 (and (setq fmt (plist-get org-time-clocksum-format :months))
18372 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18373 (plist-get org-time-clocksum-format :require-months))
18374 (setq clocksum (concat clocksum (format fmt n))
18375 m (- m (* n mo d h))))
18376 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18377 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18378 (plist-get org-time-clocksum-format :require-weeks))
18379 (setq clocksum (concat clocksum (format fmt n))
18380 m (- m (* n w d h))))
18381 (and (setq fmt (plist-get org-time-clocksum-format :days))
18382 (or (> (setq n (/ (truncate m) (* d h))) 0)
18383 (plist-get org-time-clocksum-format :require-days))
18384 (setq clocksum (concat clocksum (format fmt n))
18385 m (- m (* n d h))))
18386 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18387 (or (> (setq n (/ (truncate m) h)) 0)
18388 (plist-get org-time-clocksum-format :require-hours))
18389 (setq clocksum (concat clocksum (format fmt n))
18390 m (- m (* n h))))
18391 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18392 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18393 (setq clocksum (concat clocksum (format fmt m))))
18394 ;; return formatted time duration
18395 clocksum))))
18397 (defun org-hours-to-clocksum-string (n)
18398 (org-minutes-to-clocksum-string (* n 60)))
18400 (defun org-hh:mm-string-to-minutes (s)
18401 "Convert a string H:MM to a number of minutes.
18402 If the string is just a number, interpret it as minutes.
18403 In fact, the first hh:mm or number in the string will be taken,
18404 there can be extra stuff in the string.
18405 If no number is found, the return value is 0."
18406 (cond
18407 ((integerp s) s)
18408 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18409 (+ (* (string-to-number (match-string 1 s)) 60)
18410 (string-to-number (match-string 2 s))))
18411 ((string-match "\\([0-9]+\\)" s)
18412 (string-to-number (match-string 1 s)))
18413 (t 0)))
18415 (defcustom org-image-actual-width t
18416 "Should we use the actual width of images when inlining them?
18418 When set to t, always use the image width.
18420 When set to a number, use imagemagick (when available) to set
18421 the image's width to this value.
18423 When set to a number in a list, try to get the width from any
18424 #+ATTR.* keyword if it matches a width specification like
18426 #+ATTR_HTML: :width 300px
18428 and fall back on that number if none is found.
18430 When set to nil, try to get the width from an #+ATTR.* keyword
18431 and fall back on the original width if none is found.
18433 This requires Emacs >= 24.1, build with imagemagick support."
18434 :group 'org-appearance
18435 :version "24.4"
18436 :package-version '(Org . "8.0")
18437 :type '(choice
18438 (const :tag "Use the image width" t)
18439 (integer :tag "Use a number of pixels")
18440 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18441 (const :tag "Use #+ATTR* or don't resize" nil)))
18443 (defcustom org-agenda-inhibit-startup nil
18444 "Inhibit startup when preparing agenda buffers.
18445 When this variable is t, the initialization of the Org agenda
18446 buffers is inhibited: e.g. the visibility state is not set, the
18447 tables are not re-aligned, etc."
18448 :type 'boolean
18449 :version "24.3"
18450 :group 'org-agenda)
18452 (defcustom org-agenda-ignore-properties nil
18453 "Avoid updating text properties when building the agenda.
18454 Properties are used to prepare buffers for effort estimates,
18455 appointments, statistics and subtree-local categories.
18456 If you don't use these in the agenda, you can add them to this
18457 list and agenda building will be a bit faster.
18458 The value is a list, with zero or more of the symbols `effort', `appt',
18459 `stats' or `category'."
18460 :type '(set :greedy t
18461 (const effort)
18462 (const appt)
18463 (const stats)
18464 (const category))
18465 :version "25.1"
18466 :package-version '(Org . "8.3")
18467 :group 'org-agenda)
18469 (defun org-duration-string-to-minutes (s &optional output-to-string)
18470 "Convert a duration string S to minutes.
18472 A bare number is interpreted as minutes, modifiers can be set by
18473 customizing `org-effort-durations' (which see).
18475 Entries containing a colon are interpreted as H:MM by
18476 `org-hh:mm-string-to-minutes'."
18477 (let ((result 0)
18478 (re (concat "\\([0-9.]+\\) *\\("
18479 (regexp-opt (mapcar 'car org-effort-durations))
18480 "\\)")))
18481 (while (string-match re s)
18482 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18483 (string-to-number (match-string 1 s))))
18484 (setq s (replace-match "" nil t s)))
18485 (setq result (floor result))
18486 (cl-incf result (org-hh:mm-string-to-minutes s))
18487 (if output-to-string (number-to-string result) result)))
18489 ;;;; Files
18491 (defun org-save-all-org-buffers ()
18492 "Save all Org buffers without user confirmation."
18493 (interactive)
18494 (message "Saving all Org buffers...")
18495 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18496 (when (featurep 'org-id) (org-id-locations-save))
18497 (message "Saving all Org buffers... done"))
18499 (defun org-revert-all-org-buffers ()
18500 "Revert all Org buffers.
18501 Prompt for confirmation when there are unsaved changes.
18502 Be sure you know what you are doing before letting this function
18503 overwrite your changes.
18505 This function is useful in a setup where one tracks org files
18506 with a version control system, to revert on one machine after pulling
18507 changes from another. I believe the procedure must be like this:
18509 1. M-x org-save-all-org-buffers
18510 2. Pull changes from the other machine, resolve conflicts
18511 3. M-x org-revert-all-org-buffers"
18512 (interactive)
18513 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18514 (user-error "Abort"))
18515 (save-excursion
18516 (save-window-excursion
18517 (dolist (b (buffer-list))
18518 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18519 (with-current-buffer b buffer-file-name))
18520 (pop-to-buffer-same-window b)
18521 (revert-buffer t 'no-confirm)))
18522 (when (and (featurep 'org-id) org-id-track-globally)
18523 (org-id-locations-load)))))
18525 ;;;; Agenda files
18527 ;;;###autoload
18528 (defun org-switchb (&optional arg)
18529 "Switch between Org buffers.
18531 With \\[universal-argument] prefix, restrict available buffers to files.
18533 With \\[universal-argument] \\[universal-argument] \
18534 prefix, restrict available buffers to agenda files."
18535 (interactive "P")
18536 (let ((blist (org-buffer-list
18537 (cond ((equal arg '(4)) 'files)
18538 ((equal arg '(16)) 'agenda)))))
18539 (pop-to-buffer-same-window
18540 (completing-read "Org buffer: "
18541 (mapcar #'list (mapcar #'buffer-name blist))
18542 nil t))))
18544 (defun org-buffer-list (&optional predicate exclude-tmp)
18545 "Return a list of Org buffers.
18546 PREDICATE can be `export', `files' or `agenda'.
18548 export restrict the list to Export buffers.
18549 files restrict the list to buffers visiting Org files.
18550 agenda restrict the list to buffers visiting agenda files.
18552 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18553 (let* ((bfn nil)
18554 (agenda-files (and (eq predicate 'agenda)
18555 (mapcar 'file-truename (org-agenda-files t))))
18556 (filter
18557 (cond
18558 ((eq predicate 'files)
18559 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18560 ((eq predicate 'export)
18561 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18562 ((eq predicate 'agenda)
18563 (lambda (b)
18564 (with-current-buffer b
18565 (and (derived-mode-p 'org-mode)
18566 (setq bfn (buffer-file-name b))
18567 (member (file-truename bfn) agenda-files)))))
18568 (t (lambda (b) (with-current-buffer b
18569 (or (derived-mode-p 'org-mode)
18570 (string-match "\\*Org .*Export"
18571 (buffer-name b)))))))))
18572 (delq nil
18573 (mapcar
18574 (lambda(b)
18575 (if (and (funcall filter b)
18576 (or (not exclude-tmp)
18577 (not (string-match "tmp" (buffer-name b)))))
18579 nil))
18580 (buffer-list)))))
18582 (defun org-agenda-files (&optional unrestricted archives)
18583 "Get the list of agenda files.
18584 Optional UNRESTRICTED means return the full list even if a restriction
18585 is currently in place.
18586 When ARCHIVES is t, include all archive files that are really being
18587 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18588 `org-agenda-archives-mode' is t."
18589 (let ((files
18590 (cond
18591 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18592 ((stringp org-agenda-files) (org-read-agenda-file-list))
18593 ((listp org-agenda-files) org-agenda-files)
18594 (t (error "Invalid value of `org-agenda-files'")))))
18595 (setq files (apply 'append
18596 (mapcar (lambda (f)
18597 (if (file-directory-p f)
18598 (directory-files
18599 f t org-agenda-file-regexp)
18600 (list f)))
18601 files)))
18602 (when org-agenda-skip-unavailable-files
18603 (setq files (delq nil
18604 (mapcar (function
18605 (lambda (file)
18606 (and (file-readable-p file) file)))
18607 files))))
18608 (when (or (eq archives t)
18609 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18610 (setq files (org-add-archive-files files)))
18611 files))
18613 (defun org-agenda-file-p (&optional file)
18614 "Return non-nil, if FILE is an agenda file.
18615 If FILE is omitted, use the file associated with the current
18616 buffer."
18617 (let ((fname (or file (buffer-file-name))))
18618 (and fname
18619 (member (file-truename fname)
18620 (mapcar #'file-truename (org-agenda-files t))))))
18622 (defun org-edit-agenda-file-list ()
18623 "Edit the list of agenda files.
18624 Depending on setup, this either uses customize to edit the variable
18625 `org-agenda-files', or it visits the file that is holding the list. In the
18626 latter case, the buffer is set up in a way that saving it automatically kills
18627 the buffer and restores the previous window configuration."
18628 (interactive)
18629 (if (stringp org-agenda-files)
18630 (let ((cw (current-window-configuration)))
18631 (find-file org-agenda-files)
18632 (setq-local org-window-configuration cw)
18633 (add-hook 'after-save-hook
18634 (lambda ()
18635 (set-window-configuration
18636 (prog1 org-window-configuration
18637 (kill-buffer (current-buffer))))
18638 (org-install-agenda-files-menu)
18639 (message "New agenda file list installed"))
18640 nil 'local)
18641 (message "%s" (substitute-command-keys
18642 "Edit list and finish with \\[save-buffer]")))
18643 (customize-variable 'org-agenda-files)))
18645 (defun org-store-new-agenda-file-list (list)
18646 "Set new value for the agenda file list and save it correctly."
18647 (if (stringp org-agenda-files)
18648 (let ((fe (org-read-agenda-file-list t)) b u)
18649 (while (setq b (find-buffer-visiting org-agenda-files))
18650 (kill-buffer b))
18651 (with-temp-file org-agenda-files
18652 (insert
18653 (mapconcat
18654 (lambda (f) ;; Keep un-expanded entries.
18655 (if (setq u (assoc f fe))
18656 (cdr u)
18658 list "\n")
18659 "\n")))
18660 (let ((org-mode-hook nil) (org-inhibit-startup t)
18661 (org-insert-mode-line-in-empty-file nil))
18662 (setq org-agenda-files list)
18663 (customize-save-variable 'org-agenda-files org-agenda-files))))
18665 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18666 "Read the list of agenda files from a file.
18667 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18668 filenames, used by `org-store-new-agenda-file-list' to write back
18669 un-expanded file names."
18670 (when (file-directory-p org-agenda-files)
18671 (error "`org-agenda-files' cannot be a single directory"))
18672 (when (stringp org-agenda-files)
18673 (with-temp-buffer
18674 (insert-file-contents org-agenda-files)
18675 (mapcar
18676 (lambda (f)
18677 (let ((e (expand-file-name (substitute-in-file-name f)
18678 org-directory)))
18679 (if pair-with-expansion
18680 (cons e f)
18681 e)))
18682 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18684 ;;;###autoload
18685 (defun org-cycle-agenda-files ()
18686 "Cycle through the files in `org-agenda-files'.
18687 If the current buffer visits an agenda file, find the next one in the list.
18688 If the current buffer does not, find the first agenda file."
18689 (interactive)
18690 (let* ((fs (or (org-agenda-files t)
18691 (user-error "No agenda files")))
18692 (files (copy-sequence fs))
18693 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18694 file)
18695 (when tcf
18696 (while (and (setq file (pop files))
18697 (not (equal (file-truename file) tcf)))))
18698 (find-file (car (or files fs)))
18699 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18701 (defun org-agenda-file-to-front (&optional to-end)
18702 "Move/add the current file to the top of the agenda file list.
18703 If the file is not present in the list, it is added to the front. If it is
18704 present, it is moved there. With optional argument TO-END, add/move to the
18705 end of the list."
18706 (interactive "P")
18707 (let ((org-agenda-skip-unavailable-files nil)
18708 (file-alist (mapcar (lambda (x)
18709 (cons (file-truename x) x))
18710 (org-agenda-files t)))
18711 (ctf (file-truename
18712 (or buffer-file-name
18713 (user-error "Please save the current buffer to a file"))))
18714 x had)
18715 (setq x (assoc ctf file-alist) had x)
18717 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18718 (if to-end
18719 (setq file-alist (append (delq x file-alist) (list x)))
18720 (setq file-alist (cons x (delq x file-alist))))
18721 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18722 (org-install-agenda-files-menu)
18723 (message "File %s to %s of agenda file list"
18724 (if had "moved" "added") (if to-end "end" "front"))))
18726 (defun org-remove-file (&optional file)
18727 "Remove current file from the list of files in variable `org-agenda-files'.
18728 These are the files which are being checked for agenda entries.
18729 Optional argument FILE means use this file instead of the current."
18730 (interactive)
18731 (let* ((org-agenda-skip-unavailable-files nil)
18732 (file (or file buffer-file-name
18733 (user-error "Current buffer does not visit a file")))
18734 (true-file (file-truename file))
18735 (afile (abbreviate-file-name file))
18736 (files (delq nil (mapcar
18737 (lambda (x)
18738 (unless (equal true-file
18739 (file-truename x))
18741 (org-agenda-files t)))))
18742 (if (not (= (length files) (length (org-agenda-files t))))
18743 (progn
18744 (org-store-new-agenda-file-list files)
18745 (org-install-agenda-files-menu)
18746 (message "Removed from Org Agenda list: %s" afile))
18747 (message "File was not in list: %s (not removed)" afile))))
18749 (defun org-file-menu-entry (file)
18750 (vector file (list 'find-file file) t))
18752 (defun org-check-agenda-file (file)
18753 "Make sure FILE exists. If not, ask user what to do."
18754 (unless (file-exists-p file)
18755 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18756 (abbreviate-file-name file))
18757 (let ((r (downcase (read-char-exclusive))))
18758 (cond
18759 ((equal r ?r)
18760 (org-remove-file file)
18761 (throw 'nextfile t))
18762 (t (user-error "Abort"))))))
18764 (defun org-get-agenda-file-buffer (file)
18765 "Get an agenda buffer visiting FILE.
18766 If the buffer needs to be created, add it to the list of buffers
18767 which might be released later."
18768 (let ((buf (org-find-base-buffer-visiting file)))
18769 (if buf
18770 buf ; just return it
18771 ;; Make a new buffer and remember it
18772 (setq buf (find-file-noselect file))
18773 (when buf (push buf org-agenda-new-buffers))
18774 buf)))
18776 (defun org-release-buffers (blist)
18777 "Release all buffers in list, asking the user for confirmation when needed.
18778 When a buffer is unmodified, it is just killed. When modified, it is saved
18779 \(if the user agrees) and then killed."
18780 (let (file)
18781 (dolist (buf blist)
18782 (setq file (buffer-file-name buf))
18783 (when (and (buffer-modified-p buf)
18784 file
18785 (y-or-n-p (format "Save file %s? " file)))
18786 (with-current-buffer buf (save-buffer)))
18787 (kill-buffer buf))))
18789 (defun org-agenda-prepare-buffers (files)
18790 "Create buffers for all agenda files, protect archived trees and comments."
18791 (interactive)
18792 (let ((pa '(:org-archived t))
18793 (pc '(:org-comment t))
18794 (pall '(:org-archived t :org-comment t))
18795 (inhibit-read-only t)
18796 (org-inhibit-startup org-agenda-inhibit-startup)
18797 (rea (concat ":" org-archive-tag ":"))
18798 re pos)
18799 (setq org-tag-alist-for-agenda nil
18800 org-tag-groups-alist-for-agenda nil)
18801 (save-excursion
18802 (save-restriction
18803 (dolist (file files)
18804 (catch 'nextfile
18805 (if (bufferp file)
18806 (set-buffer file)
18807 (org-check-agenda-file file)
18808 (set-buffer (org-get-agenda-file-buffer file)))
18809 (widen)
18810 (org-set-regexps-and-options 'tags-only)
18811 (setq pos (point))
18812 (or (memq 'category org-agenda-ignore-properties)
18813 (org-refresh-category-properties))
18814 (or (memq 'stats org-agenda-ignore-properties)
18815 (org-refresh-stats-properties))
18816 (or (memq 'effort org-agenda-ignore-properties)
18817 (org-refresh-effort-properties))
18818 (or (memq 'appt org-agenda-ignore-properties)
18819 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18820 (setq org-todo-keywords-for-agenda
18821 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18822 (setq org-done-keywords-for-agenda
18823 (append org-done-keywords-for-agenda org-done-keywords))
18824 (setq org-todo-keyword-alist-for-agenda
18825 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18826 (setq org-tag-alist-for-agenda
18827 (org-uniquify
18828 (append org-tag-alist-for-agenda
18829 org-current-tag-alist)))
18830 ;; Merge current file's tag groups into global
18831 ;; `org-tag-groups-alist-for-agenda'.
18832 (when org-group-tags
18833 (dolist (alist org-tag-groups-alist)
18834 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18835 (if old
18836 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18837 (push alist org-tag-groups-alist-for-agenda)))))
18838 (org-with-silent-modifications
18839 (save-excursion
18840 (remove-text-properties (point-min) (point-max) pall)
18841 (when org-agenda-skip-archived-trees
18842 (goto-char (point-min))
18843 (while (re-search-forward rea nil t)
18844 (when (org-at-heading-p t)
18845 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18846 (goto-char (point-min))
18847 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18848 (while (re-search-forward re nil t)
18849 (when (save-match-data (org-in-commented-heading-p t))
18850 (add-text-properties
18851 (match-beginning 0) (org-end-of-subtree t) pc)))))
18852 (goto-char pos)))))
18853 (setq org-todo-keywords-for-agenda
18854 (org-uniquify org-todo-keywords-for-agenda))
18855 (setq org-todo-keyword-alist-for-agenda
18856 (org-uniquify org-todo-keyword-alist-for-agenda))))
18859 ;;;; CDLaTeX minor mode
18861 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18862 "Keymap for the minor `org-cdlatex-mode'.")
18864 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18865 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18866 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18867 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18868 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18870 (defvar org-cdlatex-texmathp-advice-is-done nil
18871 "Flag remembering if we have applied the advice to texmathp already.")
18873 (define-minor-mode org-cdlatex-mode
18874 "Toggle the minor `org-cdlatex-mode'.
18875 This mode supports entering LaTeX environment and math in LaTeX fragments
18876 in Org-mode.
18877 \\{org-cdlatex-mode-map}"
18878 nil " OCDL" nil
18879 (when org-cdlatex-mode
18880 (require 'cdlatex)
18881 (run-hooks 'cdlatex-mode-hook)
18882 (cdlatex-compute-tables))
18883 (unless org-cdlatex-texmathp-advice-is-done
18884 (setq org-cdlatex-texmathp-advice-is-done t)
18885 (defadvice texmathp (around org-math-always-on activate)
18886 "Always return t in Org buffers.
18887 This is because we want to insert math symbols without dollars even outside
18888 the LaTeX math segments. If Orgmode thinks that point is actually inside
18889 an embedded LaTeX fragment, let texmathp do its job.
18890 \\[org-cdlatex-mode-map]"
18891 (interactive)
18892 (let (p)
18893 (cond
18894 ((not (derived-mode-p 'org-mode)) ad-do-it)
18895 ((eq this-command 'cdlatex-math-symbol)
18896 (setq ad-return-value t
18897 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18899 (let ((p (org-inside-LaTeX-fragment-p)))
18900 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18901 (setq ad-return-value t
18902 texmathp-why '("Org-mode embedded math" . 0))
18903 (when p ad-do-it)))))))))
18905 (defun turn-on-org-cdlatex ()
18906 "Unconditionally turn on `org-cdlatex-mode'."
18907 (org-cdlatex-mode 1))
18909 (defun org-try-cdlatex-tab ()
18910 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18911 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18912 - inside a LaTeX fragment, or
18913 - after the first word in a line, where an abbreviation expansion could
18914 insert a LaTeX environment."
18915 (when org-cdlatex-mode
18916 (cond
18917 ;; Before any word on the line: No expansion possible.
18918 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18919 ;; Just after first word on the line: Expand it. Make sure it
18920 ;; cannot happen on headlines, though.
18921 ((save-excursion
18922 (skip-chars-backward "a-zA-Z0-9*")
18923 (skip-chars-backward " \t")
18924 (and (bolp) (not (org-at-heading-p))))
18925 (cdlatex-tab) t)
18926 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18928 (defun org-cdlatex-underscore-caret (&optional _arg)
18929 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18930 Revert to the normal definition outside of these fragments."
18931 (interactive "P")
18932 (if (org-inside-LaTeX-fragment-p)
18933 (call-interactively 'cdlatex-sub-superscript)
18934 (let (org-cdlatex-mode)
18935 (call-interactively (key-binding (vector last-input-event))))))
18937 (defun org-cdlatex-math-modify (&optional _arg)
18938 "Execute `cdlatex-math-modify' in LaTeX fragments.
18939 Revert to the normal definition outside of these fragments."
18940 (interactive "P")
18941 (if (org-inside-LaTeX-fragment-p)
18942 (call-interactively 'cdlatex-math-modify)
18943 (let (org-cdlatex-mode)
18944 (call-interactively (key-binding (vector last-input-event))))))
18946 (defun org-cdlatex-environment-indent (&optional environment item)
18947 "Execute `cdlatex-environment' and indent the inserted environment.
18949 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18951 The inserted environment is indented to current indentation
18952 unless point is at the beginning of the line, in which the
18953 environment remains unintended."
18954 (interactive)
18955 ;; cdlatex-environment always return nil. Therefore, capture output
18956 ;; first and determine if an environment was selected.
18957 (let* ((beg (point-marker))
18958 (end (copy-marker (point) t))
18959 (inserted (progn
18960 (ignore-errors (cdlatex-environment environment item))
18961 (< beg end)))
18962 ;; Figure out how many lines to move forward after the
18963 ;; environment has been inserted.
18964 (lines (when inserted
18965 (save-excursion
18966 (- (cl-loop while (< beg (point))
18967 with x = 0
18968 do (forward-line -1)
18969 (cl-incf x)
18970 finally return x)
18971 (if (progn (goto-char beg)
18972 (and (progn (skip-chars-forward " \t") (eolp))
18973 (progn (skip-chars-backward " \t") (bolp))))
18974 1 0)))))
18975 (env (org-trim (delete-and-extract-region beg end))))
18976 (when inserted
18977 ;; Get indentation of next line unless at column 0.
18978 (let ((ind (if (bolp) 0
18979 (save-excursion
18980 (org-return-indent)
18981 (prog1 (org-get-indentation)
18982 (when (progn (skip-chars-forward " \t") (eolp))
18983 (delete-region beg (point)))))))
18984 (bol (progn (skip-chars-backward " \t") (bolp))))
18985 ;; Insert a newline before environment unless at column zero
18986 ;; to "escape" the current line. Insert a newline if
18987 ;; something is one the same line as \end{ENVIRONMENT}.
18988 (insert
18989 (concat (unless bol "\n") env
18990 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18991 (unless (zerop ind)
18992 (save-excursion
18993 (goto-char beg)
18994 (while (< (point) end)
18995 (unless (eolp) (indent-line-to ind))
18996 (forward-line))))
18997 (goto-char beg)
18998 (forward-line lines)
18999 (indent-line-to ind)))
19000 (set-marker beg nil)
19001 (set-marker end nil)))
19004 ;;;; LaTeX fragments
19006 (defun org-inside-LaTeX-fragment-p ()
19007 "Test if point is inside a LaTeX fragment.
19008 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19009 sequence appearing also before point.
19010 Even though the matchers for math are configurable, this function assumes
19011 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19012 delimiters are skipped when they have been removed by customization.
19013 The return value is nil, or a cons cell with the delimiter and the
19014 position of this delimiter.
19016 This function does a reasonably good job, but can locally be fooled by
19017 for example currency specifications. For example it will assume being in
19018 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19019 fragments that are properly closed, but during editing, we have to live
19020 with the uncertainty caused by missing closing delimiters. This function
19021 looks only before point, not after."
19022 (catch 'exit
19023 (let ((pos (point))
19024 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19025 (lim (progn
19026 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19027 (point)))
19028 dd-on str (start 0) m re)
19029 (goto-char pos)
19030 (when dodollar
19031 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19032 re (nth 1 (assoc "$" org-latex-regexps)))
19033 (while (string-match re str start)
19034 (cond
19035 ((= (match-end 0) (length str))
19036 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19037 ((= (match-end 0) (- (length str) 5))
19038 (throw 'exit nil))
19039 (t (setq start (match-end 0))))))
19040 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19041 (goto-char pos)
19042 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19043 (and (match-beginning 2) (throw 'exit nil))
19044 ;; count $$
19045 (while (re-search-backward "\\$\\$" lim t)
19046 (setq dd-on (not dd-on)))
19047 (goto-char pos)
19048 (when dd-on (cons "$$" m))))))
19050 (defun org-inside-latex-macro-p ()
19051 "Is point inside a LaTeX macro or its arguments?"
19052 (save-match-data
19053 (org-in-regexp
19054 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19056 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19057 "Build an overlay between BEG and END using IMAGE file.
19058 Argument IMAGETYPE is the extension of the displayed image,
19059 as a string. It defaults to \"png\"."
19060 (let ((ov (make-overlay beg end))
19061 (imagetype (or (intern imagetype) 'png)))
19062 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19063 (overlay-put ov 'evaporate t)
19064 (overlay-put ov
19065 'modification-hooks
19066 (list (lambda (o _flag _beg _end &optional _l)
19067 (delete-overlay o))))
19068 (overlay-put ov
19069 'display
19070 (list 'image :type imagetype :file image :ascent 'center))))
19072 (defun org--list-latex-overlays (&optional beg end)
19073 "List all Org LaTeX overlays in current buffer.
19074 Limit to overlays between BEG and END when those are provided."
19075 (cl-remove-if-not
19076 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19077 (overlays-in (or beg (point-min)) (or end (point-max)))))
19079 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19080 "Remove all overlays with LaTeX fragment images in current buffer.
19081 When optional arguments BEG and END are non-nil, remove all
19082 overlays between them instead. Return a non-nil value when some
19083 overlays were removed, nil otherwise."
19084 (let ((overlays (org--list-latex-overlays beg end)))
19085 (mapc #'delete-overlay overlays)
19086 overlays))
19088 (defun org-toggle-latex-fragment (&optional arg)
19089 "Preview the LaTeX fragment at point, or all locally or globally.
19091 If the cursor is on a LaTeX fragment, create the image and overlay
19092 it over the source code, if there is none. Remove it otherwise.
19093 If there is no fragment at point, display all fragments in the
19094 current section.
19096 With prefix ARG, preview or clear image for all fragments in the
19097 current subtree or in the whole buffer when used before the first
19098 headline. With a double prefix ARG \\[universal-argument] \
19099 \\[universal-argument] preview or clear images
19100 for all fragments in the buffer."
19101 (interactive "P")
19102 (when (display-graphic-p)
19103 (catch 'exit
19104 (save-excursion
19105 (let (beg end msg)
19106 (cond
19107 ((or (equal arg '(16))
19108 (and (equal arg '(4))
19109 (org-with-limited-levels (org-before-first-heading-p))))
19110 (if (org-remove-latex-fragment-image-overlays)
19111 (progn (message "LaTeX fragments images removed from buffer")
19112 (throw 'exit nil))
19113 (setq msg "Creating images for buffer...")))
19114 ((equal arg '(4))
19115 (org-with-limited-levels (org-back-to-heading t))
19116 (setq beg (point))
19117 (setq end (progn (org-end-of-subtree t) (point)))
19118 (if (org-remove-latex-fragment-image-overlays beg end)
19119 (progn
19120 (message "LaTeX fragment images removed from subtree")
19121 (throw 'exit nil))
19122 (setq msg "Creating images for subtree...")))
19123 ((let ((datum (org-element-context)))
19124 (when (memq (org-element-type datum)
19125 '(latex-environment latex-fragment))
19126 (setq beg (org-element-property :begin datum))
19127 (setq end (org-element-property :end datum))
19128 (if (org-remove-latex-fragment-image-overlays beg end)
19129 (progn (message "LaTeX fragment image removed")
19130 (throw 'exit nil))
19131 (setq msg "Creating image...")))))
19133 (org-with-limited-levels
19134 (setq beg (if (org-at-heading-p) (line-beginning-position)
19135 (outline-previous-heading)
19136 (point)))
19137 (setq end (progn (outline-next-heading) (point)))
19138 (if (org-remove-latex-fragment-image-overlays beg end)
19139 (progn
19140 (message "LaTeX fragment images removed from section")
19141 (throw 'exit nil))
19142 (setq msg "Creating images for section...")))))
19143 (let ((file (buffer-file-name (buffer-base-buffer))))
19144 (org-format-latex
19145 (concat org-preview-latex-image-directory "org-ltximg")
19146 beg end
19147 ;; Emacs cannot overlay images from remote hosts. Create
19148 ;; it in `temporary-file-directory' instead.
19149 (if (or (not file) (file-remote-p file))
19150 temporary-file-directory
19151 default-directory)
19152 'overlays msg 'forbuffer org-preview-latex-default-process))
19153 (message (concat msg "done")))))))
19155 (defun org-format-latex
19156 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19157 "Replace LaTeX fragments with links to an image.
19159 The function takes care of creating the replacement image.
19161 Only consider fragments between BEG and END when those are
19162 provided.
19164 When optional argument OVERLAYS is non-nil, display the image on
19165 top of the fragment instead of replacing it.
19167 PROCESSING-TYPE is the conversion method to use, as a symbol.
19169 Some of the options can be changed using the variable
19170 `org-format-latex-options', which see."
19171 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19172 (unless (eq processing-type 'verbatim)
19173 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19174 (cnt 0)
19175 checkdir-flag)
19176 (goto-char (or beg (point-min)))
19177 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19178 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19179 (overlay-recenter (or end (point-max))))
19180 (while (re-search-forward math-regexp end t)
19181 (unless (and overlays
19182 (eq (get-char-property (point) 'org-overlay-type)
19183 'org-latex-overlay))
19184 (let* ((context (org-element-context))
19185 (type (org-element-type context)))
19186 (when (memq type '(latex-environment latex-fragment))
19187 (let ((block-type (eq type 'latex-environment))
19188 (value (org-element-property :value context))
19189 (beg (org-element-property :begin context))
19190 (end (save-excursion
19191 (goto-char (org-element-property :end context))
19192 (skip-chars-backward " \r\t\n")
19193 (point))))
19194 (cond
19195 ((eq processing-type 'mathjax)
19196 ;; Prepare for MathJax processing.
19197 (if (not (string-match "\\`\\$\\$?" value))
19198 (goto-char end)
19199 (delete-region beg end)
19200 (if (string= (match-string 0 value) "$$")
19201 (insert "\\[" (substring value 2 -2) "\\]")
19202 (insert "\\(" (substring value 1 -1) "\\)"))))
19203 ((assq processing-type org-preview-latex-process-alist)
19204 ;; Process to an image.
19205 (cl-incf cnt)
19206 (goto-char beg)
19207 (let* ((processing-info
19208 (cdr (assq processing-type org-preview-latex-process-alist)))
19209 (face (face-at-point))
19210 ;; Get the colors from the face at point.
19212 (let ((color (plist-get org-format-latex-options
19213 :foreground)))
19214 (if (and forbuffer (eq color 'auto))
19215 (face-attribute face :foreground nil 'default)
19216 color)))
19218 (let ((color (plist-get org-format-latex-options
19219 :background)))
19220 (if (and forbuffer (eq color 'auto))
19221 (face-attribute face :background nil 'default)
19222 color)))
19223 (hash (sha1 (prin1-to-string
19224 (list org-format-latex-header
19225 org-latex-default-packages-alist
19226 org-latex-packages-alist
19227 org-format-latex-options
19228 forbuffer value fg bg))))
19229 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19230 (absprefix (expand-file-name prefix dir))
19231 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19232 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19233 (sep (and block-type "\n\n"))
19234 (link (concat sep "[[file:" linkfile "]]" sep))
19235 (options
19236 (org-combine-plists
19237 org-format-latex-options
19238 `(:foreground ,fg :background ,bg))))
19239 (when msg (message msg cnt))
19240 (unless checkdir-flag ; Ensure the directory exists.
19241 (setq checkdir-flag t)
19242 (let ((todir (file-name-directory absprefix)))
19243 (unless (file-directory-p todir)
19244 (make-directory todir t))))
19245 (unless (file-exists-p movefile)
19246 (org-create-formula-image
19247 value movefile options forbuffer processing-type))
19248 (if overlays
19249 (progn
19250 (dolist (o (overlays-in beg end))
19251 (when (eq (overlay-get o 'org-overlay-type)
19252 'org-latex-overlay)
19253 (delete-overlay o)))
19254 (org--format-latex-make-overlay beg end movefile imagetype)
19255 (goto-char end))
19256 (delete-region beg end)
19257 (insert
19258 (org-add-props link
19259 (list 'org-latex-src
19260 (replace-regexp-in-string "\"" "" value)
19261 'org-latex-src-embed-type
19262 (if block-type 'paragraph 'character)))))))
19263 ((eq processing-type 'mathml)
19264 ;; Process to MathML.
19265 (unless (org-format-latex-mathml-available-p)
19266 (user-error "LaTeX to MathML converter not configured"))
19267 (cl-incf cnt)
19268 (when msg (message msg cnt))
19269 (goto-char beg)
19270 (delete-region beg end)
19271 (insert (org-format-latex-as-mathml
19272 value block-type prefix dir)))
19274 (error "Unknown conversion process %s for LaTeX fragments"
19275 processing-type)))))))))))
19277 (defun org-create-math-formula (latex-frag &optional mathml-file)
19278 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19279 Use `org-latex-to-mathml-convert-command'. If the conversion is
19280 sucessful, return the portion between \"<math...> </math>\"
19281 elements otherwise return nil. When MATHML-FILE is specified,
19282 write the results in to that file. When invoked as an
19283 interactive command, prompt for LATEX-FRAG, with initial value
19284 set to the current active region and echo the results for user
19285 inspection."
19286 (interactive (list (let ((frag (when (org-region-active-p)
19287 (buffer-substring-no-properties
19288 (region-beginning) (region-end)))))
19289 (read-string "LaTeX Fragment: " frag nil frag))))
19290 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19291 (let* ((tmp-in-file
19292 (let ((file (file-relative-name
19293 (make-temp-name (expand-file-name "ltxmathml-in")))))
19294 (write-region latex-frag nil file)
19295 file))
19296 (tmp-out-file (file-relative-name
19297 (make-temp-name (expand-file-name "ltxmathml-out"))))
19298 (cmd (format-spec
19299 org-latex-to-mathml-convert-command
19300 `((?j . ,(and org-latex-to-mathml-jar-file
19301 (shell-quote-argument
19302 (expand-file-name
19303 org-latex-to-mathml-jar-file))))
19304 (?I . ,(shell-quote-argument tmp-in-file))
19305 (?i . ,latex-frag)
19306 (?o . ,(shell-quote-argument tmp-out-file)))))
19307 mathml shell-command-output)
19308 (when (called-interactively-p 'any)
19309 (unless (org-format-latex-mathml-available-p)
19310 (user-error "LaTeX to MathML converter not configured")))
19311 (message "Running %s" cmd)
19312 (setq shell-command-output (shell-command-to-string cmd))
19313 (setq mathml
19314 (when (file-readable-p tmp-out-file)
19315 (with-current-buffer (find-file-noselect tmp-out-file t)
19316 (goto-char (point-min))
19317 (when (re-search-forward
19318 (concat
19319 (regexp-quote
19320 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19321 "[^>]*?>"
19322 "\\(.\\|\n\\)*"
19323 "</math>")
19324 nil t)
19325 (prog1 (match-string 0) (kill-buffer))))))
19326 (cond
19327 (mathml
19328 (setq mathml
19329 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19330 (when mathml-file
19331 (write-region mathml nil mathml-file))
19332 (when (called-interactively-p 'any)
19333 (message mathml)))
19334 ((message "LaTeX to MathML conversion failed")
19335 (message shell-command-output)))
19336 (delete-file tmp-in-file)
19337 (when (file-exists-p tmp-out-file)
19338 (delete-file tmp-out-file))
19339 mathml))
19341 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19342 prefix &optional dir)
19343 "Use `org-create-math-formula' but check local cache first."
19344 (let* ((absprefix (expand-file-name prefix dir))
19345 (print-length nil) (print-level nil)
19346 (formula-id (concat
19347 "formula-"
19348 (sha1
19349 (prin1-to-string
19350 (list latex-frag
19351 org-latex-to-mathml-convert-command)))))
19352 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19353 (formula-cache-dir (file-name-directory formula-cache)))
19355 (unless (file-directory-p formula-cache-dir)
19356 (make-directory formula-cache-dir t))
19358 (unless (file-exists-p formula-cache)
19359 (org-create-math-formula latex-frag formula-cache))
19361 (if (file-exists-p formula-cache)
19362 ;; Successful conversion. Return the link to MathML file.
19363 (org-add-props
19364 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19365 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19366 'org-latex-src-embed-type (if latex-frag-type
19367 'paragraph 'character)))
19368 ;; Failed conversion. Return the LaTeX fragment verbatim
19369 latex-frag)))
19371 (declare-function org-export-get-backend "ox" (name))
19372 (declare-function org-export--get-global-options "ox" (&optional backend))
19373 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19374 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19375 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19376 (defun org-create-formula--latex-header ()
19377 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19378 (let ((info (org-combine-plists (org-export--get-global-options
19379 (org-export-get-backend 'latex))
19380 (org-export--get-inbuffer-options
19381 (org-export-get-backend 'latex)))))
19382 (org-latex-guess-babel-language
19383 (org-latex-guess-inputenc
19384 (org-splice-latex-header
19385 org-format-latex-header
19386 org-latex-default-packages-alist
19387 org-latex-packages-alist t
19388 (plist-get info :latex-header)))
19389 info)))
19391 (defun org--get-display-dpi ()
19392 "Get the DPI of the display.
19394 Assumes that the display has the same pixel width in the
19395 horizontal and vertical directions."
19396 (if (display-graphic-p)
19397 (round (/ (display-pixel-height)
19398 (/ (display-mm-height) 25.4)))
19399 (error "Attempt to calculate the dpi of a non-graphic display")))
19401 (defun org-create-formula-image
19402 (string tofile options buffer &optional processing-type)
19403 "Create an image from LaTeX source using external processes.
19405 The LaTeX STRING is saved to a temporary LaTeX file, then
19406 converted to an image file by process PROCESSING-TYPE defined in
19407 `org-preview-latex-process-alist'. A nil value defaults to
19408 `org-preview-latex-default-process'.
19410 The generated image file is eventually moved to TOFILE.
19412 The OPTIONS argument controls the size, foreground color and
19413 background color of the generated image.
19415 When BUFFER non-nil, this function is used for LaTeX previewing.
19416 Otherwise, it is used to deal with LaTeX snippets showed in
19417 a HTML file."
19418 (let* ((processing-type (or processing-type
19419 org-preview-latex-default-process))
19420 (processing-info
19421 (cdr (assq processing-type org-preview-latex-process-alist)))
19422 (programs (plist-get processing-info :programs))
19423 (error-message (or (plist-get processing-info :message) ""))
19424 (use-xcolor (plist-get processing-info :use-xcolor))
19425 (image-input-type (plist-get processing-info :image-input-type))
19426 (image-output-type (plist-get processing-info :image-output-type))
19427 (post-clean (or (plist-get processing-info :post-clean)
19428 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19429 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19430 (latex-header (or (plist-get processing-info :latex-header)
19431 (org-create-formula--latex-header)))
19432 (latex-compiler (plist-get processing-info :latex-compiler))
19433 (image-converter (plist-get processing-info :image-converter))
19434 (tmpdir temporary-file-directory)
19435 (texfilebase (make-temp-name
19436 (expand-file-name "orgtex" tmpdir)))
19437 (texfile (concat texfilebase ".tex"))
19438 (font-height (face-attribute 'default :height nil))
19439 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19440 '(1.0 . 1.0)))
19441 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19442 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19443 (dpi (* scale (floor (if buffer font-height 140.0))))
19444 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19445 "Black"))
19446 (bg (or (plist-get options (if buffer :background :html-background))
19447 "Transparent"))
19448 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19449 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19450 (dolist (program programs)
19451 (org-check-external-command program error-message))
19452 (if use-xcolor
19453 (progn (if (eq fg 'default)
19454 (setq fg (org-latex-color :foreground))
19455 (setq fg (org-latex-color-format fg)))
19456 (if (eq bg 'default)
19457 (setq bg (org-latex-color :background))
19458 (setq bg (org-latex-color-format
19459 (if (string= bg "Transparent") "white" bg))))
19460 (with-temp-file texfile
19461 (insert latex-header)
19462 (insert "\n\\begin{document}\n"
19463 "\\definecolor{fg}{rgb}{" fg "}\n"
19464 "\\definecolor{bg}{rgb}{" bg "}\n"
19465 "\n\\pagecolor{bg}\n"
19466 "\n{\\color{fg}\n"
19467 string
19468 "\n}\n"
19469 "\n\\end{document}\n")))
19470 (if (eq fg 'default)
19471 (setq fg (org-dvipng-color :foreground))
19472 (unless (string= fg "Transparent")
19473 (setq fg (org-dvipng-color-format fg))))
19474 (if (eq bg 'default)
19475 (setq bg (org-dvipng-color :background))
19476 (unless (string= bg "Transparent")
19477 (setq bg (org-dvipng-color-format bg))))
19478 (with-temp-file texfile
19479 (insert latex-header)
19480 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19482 (let* ((err-msg (format "Please adjust '%s' part of \
19483 `org-preview-latex-process-alist'."
19484 processing-type))
19485 (image-input-file
19486 (org-compile-file
19487 texfile latex-compiler image-input-type err-msg log-buf))
19488 (image-output-file
19489 (org-compile-file
19490 image-input-file image-converter image-output-type err-msg log-buf
19491 `((?F . ,(shell-quote-argument fg))
19492 (?B . ,(shell-quote-argument bg))
19493 (?D . ,(shell-quote-argument (format "%s" dpi)))
19494 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19495 (copy-file image-output-file tofile 'replace)
19496 (dolist (e post-clean)
19497 (when (file-exists-p (concat texfilebase e))
19498 (delete-file (concat texfilebase e))))
19499 image-output-file)))
19501 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19502 "Fill a LaTeX header template TPL.
19503 In the template, the following place holders will be recognized:
19505 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19506 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19507 [PACKAGES] \\usepackage statements for PKG
19508 [NO-PACKAGES] do not include PKG
19509 [EXTRA] the string EXTRA
19510 [NO-EXTRA] do not include EXTRA
19512 For backward compatibility, if both the positive and the negative place
19513 holder is missing, the positive one (without the \"NO-\") will be
19514 assumed to be present at the end of the template.
19515 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19516 EXTRA is a string.
19517 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19518 (let (rpl (end ""))
19519 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19520 (setq rpl (if (or (match-end 1) (not def-pkg))
19521 "" (org-latex-packages-to-string def-pkg snippets-p t))
19522 tpl (replace-match rpl t t tpl))
19523 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19525 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19526 (setq rpl (if (or (match-end 1) (not pkg))
19527 "" (org-latex-packages-to-string pkg snippets-p t))
19528 tpl (replace-match rpl t t tpl))
19529 (when pkg (setq end
19530 (concat end "\n"
19531 (org-latex-packages-to-string pkg snippets-p)))))
19533 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19534 (setq rpl (if (or (match-end 1) (not extra))
19535 "" (concat extra "\n"))
19536 tpl (replace-match rpl t t tpl))
19537 (when (and extra (string-match "\\S-" extra))
19538 (setq end (concat end "\n" extra))))
19540 (if (string-match "\\S-" end)
19541 (concat tpl "\n" end)
19542 tpl)))
19544 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19545 "Turn an alist of packages into a string with the \\usepackage macros."
19546 (setq pkg (mapconcat (lambda(p)
19547 (cond
19548 ((stringp p) p)
19549 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19550 (format "%% Package %s omitted" (cadr p)))
19551 ((equal "" (car p))
19552 (format "\\usepackage{%s}" (cadr p)))
19554 (format "\\usepackage[%s]{%s}"
19555 (car p) (cadr p)))))
19557 "\n"))
19558 (if newline (concat pkg "\n") pkg))
19560 (defun org-dvipng-color (attr)
19561 "Return a RGB color specification for dvipng."
19562 (apply #'format "rgb %s %s %s"
19563 (mapcar #'org-normalize-color
19564 (color-values (face-attribute 'default attr nil)))))
19566 (defun org-dvipng-color-format (color-name)
19567 "Convert COLOR-NAME to a RGB color value for dvipng."
19568 (apply 'format "rgb %s %s %s"
19569 (mapcar 'org-normalize-color
19570 (color-values color-name))))
19572 (defun org-latex-color (attr)
19573 "Return a RGB color for the LaTeX color package."
19574 (apply #'format "%s,%s,%s"
19575 (mapcar #'org-normalize-color
19576 (color-values (face-attribute 'default attr nil)))))
19578 (defun org-latex-color-format (color-name)
19579 "Convert COLOR-NAME to a RGB color value."
19580 (apply 'format "%s,%s,%s"
19581 (mapcar 'org-normalize-color
19582 (color-values color-name))))
19584 (defun org-normalize-color (value)
19585 "Return string to be used as color value for an RGB component."
19586 (format "%g" (/ value 65535.0)))
19590 ;; Image display
19592 (defvar-local org-inline-image-overlays nil)
19594 (defun org-toggle-inline-images (&optional include-linked)
19595 "Toggle the display of inline images.
19596 INCLUDE-LINKED is passed to `org-display-inline-images'."
19597 (interactive "P")
19598 (if org-inline-image-overlays
19599 (progn
19600 (org-remove-inline-images)
19601 (when (called-interactively-p 'interactive)
19602 (message "Inline image display turned off")))
19603 (org-display-inline-images include-linked)
19604 (when (called-interactively-p 'interactive)
19605 (message (if org-inline-image-overlays
19606 (format "%d images displayed inline"
19607 (length org-inline-image-overlays))
19608 "No images to display inline")))))
19610 (defun org-redisplay-inline-images ()
19611 "Refresh the display of inline images."
19612 (interactive)
19613 (if (not org-inline-image-overlays)
19614 (org-toggle-inline-images)
19615 (org-toggle-inline-images)
19616 (org-toggle-inline-images)))
19618 (defun org-display-inline-images (&optional include-linked refresh beg end)
19619 "Display inline images.
19621 An inline image is a link which follows either of these
19622 conventions:
19624 1. Its path is a file with an extension matching return value
19625 from `image-file-name-regexp' and it has no contents.
19627 2. Its description consists in a single link of the previous
19628 type.
19630 When optional argument INCLUDE-LINKED is non-nil, also links with
19631 a text description part will be inlined. This can be nice for
19632 a quick look at those images, but it does not reflect what
19633 exported files will look like.
19635 When optional argument REFRESH is non-nil, refresh existing
19636 images between BEG and END. This will create new image displays
19637 only if necessary. BEG and END default to the buffer
19638 boundaries."
19639 (interactive "P")
19640 (when (display-graphic-p)
19641 (unless refresh
19642 (org-remove-inline-images)
19643 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19644 (org-with-wide-buffer
19645 (goto-char (or beg (point-min)))
19646 (let ((case-fold-search t)
19647 (file-extension-re (image-file-name-regexp)))
19648 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19649 (let ((link (save-match-data (org-element-context))))
19650 ;; Check if we're at an inline image.
19651 (when (and (equal (org-element-property :type link) "file")
19652 (or include-linked
19653 (not (org-element-property :contents-begin link)))
19654 (let ((parent (org-element-property :parent link)))
19655 (or (not (eq (org-element-type parent) 'link))
19656 (not (cdr (org-element-contents parent)))))
19657 (string-match-p file-extension-re
19658 (org-element-property :path link)))
19659 (let ((file (expand-file-name
19660 (org-link-unescape
19661 (org-element-property :path link)))))
19662 (when (file-exists-p file)
19663 (let ((width
19664 ;; Apply `org-image-actual-width' specifications.
19665 (cond
19666 ((not (image-type-available-p 'imagemagick)) nil)
19667 ((eq org-image-actual-width t) nil)
19668 ((listp org-image-actual-width)
19670 ;; First try to find a width among
19671 ;; attributes associated to the paragraph
19672 ;; containing link.
19673 (let ((paragraph
19674 (let ((e link))
19675 (while (and (setq e (org-element-property
19676 :parent e))
19677 (not (eq (org-element-type e)
19678 'paragraph))))
19679 e)))
19680 (when paragraph
19681 (save-excursion
19682 (goto-char (org-element-property :begin paragraph))
19683 (when
19684 (re-search-forward
19685 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19686 (org-element-property
19687 :post-affiliated paragraph)
19689 (string-to-number (match-string 1))))))
19690 ;; Otherwise, fall-back to provided number.
19691 (car org-image-actual-width)))
19692 ((numberp org-image-actual-width)
19693 org-image-actual-width)))
19694 (old (get-char-property-and-overlay
19695 (org-element-property :begin link)
19696 'org-image-overlay)))
19697 (if (and (car-safe old) refresh)
19698 (image-refresh (overlay-get (cdr old) 'display))
19699 (let ((image (create-image file
19700 (and width 'imagemagick)
19702 :width width)))
19703 (when image
19704 (let* ((link
19705 ;; If inline image is the description
19706 ;; of another link, be sure to
19707 ;; consider the latter as the one to
19708 ;; apply the overlay on.
19709 (let ((parent
19710 (org-element-property :parent link)))
19711 (if (eq (org-element-type parent) 'link)
19712 parent
19713 link)))
19714 (ov (make-overlay
19715 (org-element-property :begin link)
19716 (progn
19717 (goto-char
19718 (org-element-property :end link))
19719 (skip-chars-backward " \t")
19720 (point)))))
19721 (overlay-put ov 'display image)
19722 (overlay-put ov 'face 'default)
19723 (overlay-put ov 'org-image-overlay t)
19724 (overlay-put
19725 ov 'modification-hooks
19726 (list 'org-display-inline-remove-overlay))
19727 (push ov org-inline-image-overlays)))))))))))))))
19729 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19730 "Remove inline-display overlay if a corresponding region is modified."
19731 (let ((inhibit-modification-hooks t))
19732 (when (and ov after)
19733 (delete ov org-inline-image-overlays)
19734 (delete-overlay ov))))
19736 (defun org-remove-inline-images ()
19737 "Remove inline display of images."
19738 (interactive)
19739 (mapc #'delete-overlay org-inline-image-overlays)
19740 (setq org-inline-image-overlays nil))
19742 ;;;; Key bindings
19744 ;; Outline functions from `outline-mode-prefix-map'
19745 ;; that can be remapped in Org:
19746 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19747 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19748 (define-key org-mode-map [remap outline-forward-same-level]
19749 'org-forward-heading-same-level)
19750 (define-key org-mode-map [remap outline-backward-same-level]
19751 'org-backward-heading-same-level)
19752 (define-key org-mode-map [remap outline-show-branches]
19753 'org-kill-note-or-show-branches)
19754 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19755 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19756 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19757 (define-key org-mode-map [remap outline-next-visible-heading]
19758 'org-next-visible-heading)
19759 (define-key org-mode-map [remap outline-previous-visible-heading]
19760 'org-previous-visible-heading)
19761 (define-key org-mode-map [remap show-children] 'org-show-children)
19763 ;; Outline functions from `outline-mode-prefix-map' that can not
19764 ;; be remapped in Org:
19766 ;; - the column "key binding" shows whether the Outline function is still
19767 ;; available in Org mode on the same key that it has been bound to in
19768 ;; Outline mode:
19769 ;; - "overridden": key used for a different functionality in Org mode
19770 ;; - else: key still bound to the same Outline function in Org mode
19772 ;; | Outline function | key binding | Org replacement |
19773 ;; |------------------------------------+-------------+--------------------------|
19774 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19775 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19776 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19777 ;; | `show-entry' | overridden | no replacement |
19778 ;; | `show-branches' | `C-c C-k' | still same function |
19779 ;; | `show-subtree' | overridden | visibility cycling |
19780 ;; | `show-all' | overridden | no replacement |
19781 ;; | `hide-subtree' | overridden | visibility cycling |
19782 ;; | `hide-body' | overridden | no replacement |
19783 ;; | `hide-entry' | overridden | visibility cycling |
19784 ;; | `hide-leaves' | overridden | no replacement |
19785 ;; | `hide-sublevels' | overridden | no replacement |
19786 ;; | `hide-other' | overridden | no replacement |
19788 ;; Make `C-c C-x' a prefix key
19789 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19791 ;; TAB key with modifiers
19792 (org-defkey org-mode-map "\C-i" 'org-cycle)
19793 (org-defkey org-mode-map [(tab)] 'org-cycle)
19794 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19795 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19796 ;; The following line is necessary under Suse GNU/Linux
19797 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19798 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19799 (define-key org-mode-map [backtab] 'org-shifttab)
19801 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19802 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19803 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19805 ;; Cursor keys with modifiers
19806 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19807 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19808 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19809 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19811 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19812 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19813 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19814 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19815 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19816 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19818 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19819 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19820 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19821 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19823 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19824 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19825 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19826 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19828 ;; Babel keys
19829 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19830 (dolist (pair org-babel-key-bindings)
19831 (define-key org-babel-map (car pair) (cdr pair)))
19833 ;;; Extra keys for tty access.
19834 ;; We only set them when really needed because otherwise the
19835 ;; menus don't show the simple keys
19837 (when (or org-use-extra-keys (not window-system))
19838 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19839 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19840 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19841 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19842 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19843 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19844 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19845 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19846 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19847 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19848 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19849 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19850 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19851 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19852 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19853 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19854 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19855 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19856 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19857 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19858 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19859 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19860 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19861 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19862 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19863 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19864 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19865 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19867 ;; All the other keys
19869 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19870 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19871 (if (boundp 'narrow-map)
19872 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19873 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19874 (if (boundp 'narrow-map)
19875 (org-defkey narrow-map "b" 'org-narrow-to-block)
19876 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19877 (if (boundp 'narrow-map)
19878 (org-defkey narrow-map "e" 'org-narrow-to-element)
19879 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19880 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19881 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19882 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19883 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19884 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19885 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19886 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19887 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19888 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19889 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19890 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19891 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19892 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19893 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19894 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19895 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19896 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19897 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19898 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19899 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19900 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19901 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19902 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19903 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19904 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19905 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19906 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19907 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19908 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19909 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19910 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19911 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19912 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19913 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19914 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19915 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19916 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19917 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19918 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19919 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19920 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19921 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19922 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19923 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19924 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19925 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19926 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19927 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19928 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19929 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19930 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19931 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19932 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19933 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19934 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19935 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19936 (org-defkey org-mode-map "\C-c^" 'org-sort)
19937 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19938 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19939 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19940 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19941 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19942 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19943 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19944 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19945 (org-defkey org-mode-map "\C-m" 'org-return)
19946 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19947 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19948 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19949 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19950 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19951 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19952 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19953 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19954 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19955 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19956 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19957 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19958 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19959 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19960 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19961 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19962 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19963 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19964 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19965 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19966 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19967 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19968 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19969 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19970 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19972 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19973 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19974 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19976 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19977 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19978 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19979 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19980 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19981 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19982 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19983 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19984 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19985 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19986 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19987 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19988 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19989 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19990 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19991 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19992 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19993 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19994 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19995 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19996 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19997 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19999 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20000 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20001 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20002 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20003 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20005 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20007 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20009 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20010 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20012 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20015 (defconst org-speed-commands-default
20017 ("Outline Navigation")
20018 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20019 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20020 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20021 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20022 ("F" . org-next-block)
20023 ("B" . org-previous-block)
20024 ("u" . (org-speed-move-safe 'outline-up-heading))
20025 ("j" . org-goto)
20026 ("g" . (org-refile t))
20027 ("Outline Visibility")
20028 ("c" . org-cycle)
20029 ("C" . org-shifttab)
20030 (" " . org-display-outline-path)
20031 ("s" . org-narrow-to-subtree)
20032 ("=" . org-columns)
20033 ("Outline Structure Editing")
20034 ("U" . org-metaup)
20035 ("D" . org-metadown)
20036 ("r" . org-metaright)
20037 ("l" . org-metaleft)
20038 ("R" . org-shiftmetaright)
20039 ("L" . org-shiftmetaleft)
20040 ("i" . (progn (forward-char 1) (call-interactively
20041 'org-insert-heading-respect-content)))
20042 ("^" . org-sort)
20043 ("w" . org-refile)
20044 ("a" . org-archive-subtree-default-with-confirmation)
20045 ("@" . org-mark-subtree)
20046 ("#" . org-toggle-comment)
20047 ("Clock Commands")
20048 ("I" . org-clock-in)
20049 ("O" . org-clock-out)
20050 ("Meta Data Editing")
20051 ("t" . org-todo)
20052 ("," . (org-priority))
20053 ("0" . (org-priority ?\ ))
20054 ("1" . (org-priority ?A))
20055 ("2" . (org-priority ?B))
20056 ("3" . (org-priority ?C))
20057 (":" . org-set-tags-command)
20058 ("e" . org-set-effort)
20059 ("E" . org-inc-effort)
20060 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20061 (org-entry-put (point) "APPT_WARNTIME" m)))
20062 ("Agenda Views etc")
20063 ("v" . org-agenda)
20064 ("/" . org-sparse-tree)
20065 ("Misc")
20066 ("o" . org-open-at-point)
20067 ("?" . org-speed-command-help)
20068 ("<" . (org-agenda-set-restriction-lock 'subtree))
20069 (">" . (org-agenda-remove-restriction-lock))
20071 "The default speed commands.")
20073 (defun org-print-speed-command (e)
20074 (if (> (length (car e)) 1)
20075 (progn
20076 (princ "\n")
20077 (princ (car e))
20078 (princ "\n")
20079 (princ (make-string (length (car e)) ?-))
20080 (princ "\n"))
20081 (princ (car e))
20082 (princ " ")
20083 (if (symbolp (cdr e))
20084 (princ (symbol-name (cdr e)))
20085 (prin1 (cdr e)))
20086 (princ "\n")))
20088 (defun org-speed-command-help ()
20089 "Show the available speed commands."
20090 (interactive)
20091 (if (not org-use-speed-commands)
20092 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20093 (with-output-to-temp-buffer "*Help*"
20094 (princ "User-defined Speed commands\n===========================\n")
20095 (mapc #'org-print-speed-command org-speed-commands-user)
20096 (princ "\n")
20097 (princ "Built-in Speed commands\n=======================\n")
20098 (mapc #'org-print-speed-command org-speed-commands-default))
20099 (with-current-buffer "*Help*"
20100 (setq truncate-lines t))))
20102 (defun org-speed-move-safe (cmd)
20103 "Execute CMD, but make sure that the cursor always ends up in a headline.
20104 If not, return to the original position and throw an error."
20105 (interactive)
20106 (let ((pos (point)))
20107 (call-interactively cmd)
20108 (unless (and (bolp) (org-at-heading-p))
20109 (goto-char pos)
20110 (error "Boundary reached while executing %s" cmd))))
20112 (defvar org-self-insert-command-undo-counter 0)
20114 (defvar org-table-auto-blank-field) ; defined in org-table.el
20115 (defvar org-speed-command nil)
20117 (defun org-speed-command-activate (keys)
20118 "Hook for activating single-letter speed commands.
20119 `org-speed-commands-default' specifies a minimal command set.
20120 Use `org-speed-commands-user' for further customization."
20121 (when (or (and (bolp) (looking-at org-outline-regexp))
20122 (and (functionp org-use-speed-commands)
20123 (funcall org-use-speed-commands)))
20124 (cdr (assoc keys (append org-speed-commands-user
20125 org-speed-commands-default)))))
20127 (defun org-babel-speed-command-activate (keys)
20128 "Hook for activating single-letter code block commands."
20129 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20130 (cdr (assoc keys org-babel-key-bindings))))
20132 (defcustom org-speed-command-hook
20133 '(org-speed-command-default-hook org-babel-speed-command-hook)
20134 "Hook for activating speed commands at strategic locations.
20135 Hook functions are called in sequence until a valid handler is
20136 found.
20138 Each hook takes a single argument, a user-pressed command key
20139 which is also a `self-insert-command' from the global map.
20141 Within the hook, examine the cursor position and the command key
20142 and return nil or a valid handler as appropriate. Handler could
20143 be one of an interactive command, a function, or a form.
20145 Set `org-use-speed-commands' to non-nil value to enable this
20146 hook. The default setting is `org-speed-command-activate'."
20147 :group 'org-structure
20148 :version "24.1"
20149 :type 'hook)
20151 (defun org-self-insert-command (N)
20152 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20153 If the cursor is in a table looking at whitespace, the whitespace is
20154 overwritten, and the table is not marked as requiring realignment."
20155 (interactive "p")
20156 (org-check-before-invisible-edit 'insert)
20157 (cond
20158 ((and org-use-speed-commands
20159 (let ((kv (this-command-keys-vector)))
20160 (setq org-speed-command
20161 (run-hook-with-args-until-success
20162 'org-speed-command-hook
20163 (make-string 1 (aref kv (1- (length kv))))))))
20164 (cond
20165 ((commandp org-speed-command)
20166 (setq this-command org-speed-command)
20167 (call-interactively org-speed-command))
20168 ((functionp org-speed-command)
20169 (funcall org-speed-command))
20170 ((and org-speed-command (listp org-speed-command))
20171 (eval org-speed-command))
20172 (t (let (org-use-speed-commands)
20173 (call-interactively 'org-self-insert-command)))))
20174 ((and
20175 (org-at-table-p)
20176 (progn
20177 ;; Check if we blank the field, and if that triggers align.
20178 (and (featurep 'org-table) org-table-auto-blank-field
20179 (memq last-command
20180 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20181 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20182 ;; Got extra space, this field does not determine
20183 ;; column width.
20184 (let (org-table-may-need-update) (org-table-blank-field))
20185 ;; No extra space, this field may determine column
20186 ;; width.
20187 (org-table-blank-field)))
20189 (eq N 1)
20190 (looking-at "[^|\n]* \\( \\)|"))
20191 ;; There is room for insertion without re-aligning the table.
20192 (delete-region (match-beginning 1) (match-end 1))
20193 (self-insert-command N))
20195 (setq org-table-may-need-update t)
20196 (self-insert-command N)
20197 (org-fix-tags-on-the-fly)
20198 (when org-self-insert-cluster-for-undo
20199 (if (not (eq last-command 'org-self-insert-command))
20200 (setq org-self-insert-command-undo-counter 1)
20201 (if (>= org-self-insert-command-undo-counter 20)
20202 (setq org-self-insert-command-undo-counter 1)
20203 (and (> org-self-insert-command-undo-counter 0)
20204 buffer-undo-list (listp buffer-undo-list)
20205 (not (cadr buffer-undo-list)) ; remove nil entry
20206 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20207 (setq org-self-insert-command-undo-counter
20208 (1+ org-self-insert-command-undo-counter))))))))
20210 (defun org-check-before-invisible-edit (kind)
20211 "Check is editing if kind KIND would be dangerous with invisible text around.
20212 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20213 ;; First, try to get out of here as quickly as possible, to reduce overhead
20214 (when (and org-catch-invisible-edits
20215 (or (not (boundp 'visible-mode)) (not visible-mode))
20216 (or (get-char-property (point) 'invisible)
20217 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20218 ;; OK, we need to take a closer look
20219 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20220 (invisible-before-point (unless (bobp) (get-char-property
20221 (1- (point)) 'invisible)))
20222 (border-and-ok-direction
20224 ;; Check if we are acting predictably before invisible text
20225 (and invisible-at-point (not invisible-before-point)
20226 (memq kind '(insert delete-backward)))
20227 ;; Check if we are acting predictably after invisible text
20228 ;; This works not well, and I have turned it off. It seems
20229 ;; better to always show and stop after invisible text.
20230 ;; (and (not invisible-at-point) invisible-before-point
20231 ;; (memq kind '(insert delete)))
20233 (when (or (memq invisible-at-point '(outline org-hide-block t))
20234 (memq invisible-before-point '(outline org-hide-block t)))
20235 (when (eq org-catch-invisible-edits 'error)
20236 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20237 (if (and org-custom-properties-overlays
20238 (y-or-n-p "Display invisible properties in this buffer? "))
20239 (org-toggle-custom-properties-visibility)
20240 ;; Make the area visible
20241 (save-excursion
20242 (when invisible-before-point
20243 (goto-char (previous-single-char-property-change
20244 (point) 'invisible)))
20245 (outline-show-subtree))
20246 (cond
20247 ((eq org-catch-invisible-edits 'show)
20248 ;; That's it, we do the edit after showing
20249 (message
20250 "Unfolding invisible region around point before editing")
20251 (sit-for 1))
20252 ((and (eq org-catch-invisible-edits 'smart)
20253 border-and-ok-direction)
20254 (message "Unfolding invisible region around point before editing"))
20256 ;; Don't do the edit, make the user repeat it in full visibility
20257 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20259 (defun org-fix-tags-on-the-fly ()
20260 (when (and (equal (char-after (point-at-bol)) ?*)
20261 (org-at-heading-p))
20262 (org-align-tags-here org-tags-column)))
20264 (defun org-delete-backward-char (N)
20265 "Like `delete-backward-char', insert whitespace at field end in tables.
20266 When deleting backwards, in tables this function will insert whitespace in
20267 front of the next \"|\" separator, to keep the table aligned. The table will
20268 still be marked for re-alignment if the field did fill the entire column,
20269 because, in this case the deletion might narrow the column."
20270 (interactive "p")
20271 (save-match-data
20272 (org-check-before-invisible-edit 'delete-backward)
20273 (if (and (org-at-table-p)
20274 (eq N 1)
20275 (string-match "|" (buffer-substring (point-at-bol) (point)))
20276 (looking-at ".*?|"))
20277 (let ((pos (point))
20278 (noalign (looking-at "[^|\n\r]* |"))
20279 (c org-table-may-need-update))
20280 (backward-delete-char N)
20281 (unless overwrite-mode
20282 (skip-chars-forward "^|")
20283 (insert " ")
20284 (goto-char (1- pos)))
20285 ;; noalign: if there were two spaces at the end, this field
20286 ;; does not determine the width of the column.
20287 (when noalign (setq org-table-may-need-update c)))
20288 (backward-delete-char N)
20289 (org-fix-tags-on-the-fly))))
20291 (defun org-delete-char (N)
20292 "Like `delete-char', but insert whitespace at field end in tables.
20293 When deleting characters, in tables this function will insert whitespace in
20294 front of the next \"|\" separator, to keep the table aligned. The table will
20295 still be marked for re-alignment if the field did fill the entire column,
20296 because, in this case the deletion might narrow the column."
20297 (interactive "p")
20298 (save-match-data
20299 (org-check-before-invisible-edit 'delete)
20300 (if (and (org-at-table-p)
20301 (not (bolp))
20302 (not (= (char-after) ?|))
20303 (eq N 1))
20304 (if (looking-at ".*?|")
20305 (let ((pos (point))
20306 (noalign (looking-at "[^|\n\r]* |"))
20307 (c org-table-may-need-update))
20308 (replace-match
20309 (concat (substring (match-string 0) 1 -1) " |") nil t)
20310 (goto-char pos)
20311 ;; noalign: if there were two spaces at the end, this field
20312 ;; does not determine the width of the column.
20313 (when noalign (setq org-table-may-need-update c)))
20314 (delete-char N))
20315 (delete-char N)
20316 (org-fix-tags-on-the-fly))))
20318 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20319 (put 'org-self-insert-command 'delete-selection
20320 (lambda ()
20321 (not (run-hook-with-args-until-success
20322 'self-insert-uses-region-functions))))
20323 (put 'orgtbl-self-insert-command 'delete-selection
20324 (lambda ()
20325 (not (run-hook-with-args-until-success
20326 'self-insert-uses-region-functions))))
20327 (put 'org-delete-char 'delete-selection 'supersede)
20328 (put 'org-delete-backward-char 'delete-selection 'supersede)
20329 (put 'org-yank 'delete-selection 'yank)
20331 ;; Make `flyspell-mode' delay after some commands
20332 (put 'org-self-insert-command 'flyspell-delayed t)
20333 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20334 (put 'org-delete-char 'flyspell-delayed t)
20335 (put 'org-delete-backward-char 'flyspell-delayed t)
20337 ;; Make pabbrev-mode expand after Org mode commands
20338 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20339 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20341 (defun org-remap (map &rest commands)
20342 "In MAP, remap the functions given in COMMANDS.
20343 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20344 (let (new old)
20345 (while commands
20346 (setq old (pop commands) new (pop commands))
20347 (if (fboundp 'command-remapping)
20348 (org-defkey map (vector 'remap old) new)
20349 (substitute-key-definition old new map global-map)))))
20351 (defun org-transpose-words ()
20352 "Transpose words for Org.
20353 This uses the `org-mode-transpose-word-syntax-table' syntax
20354 table, which interprets characters in `org-emphasis-alist' as
20355 word constituents."
20356 (interactive)
20357 (with-syntax-table org-mode-transpose-word-syntax-table
20358 (call-interactively 'transpose-words)))
20359 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20361 (when (eq org-enable-table-editor 'optimized)
20362 ;; If the user wants maximum table support, we need to hijack
20363 ;; some standard editing functions
20364 (org-remap org-mode-map
20365 'self-insert-command 'org-self-insert-command
20366 'delete-char 'org-delete-char
20367 'delete-backward-char 'org-delete-backward-char)
20368 (org-defkey org-mode-map "|" 'org-force-self-insert))
20370 (defvar org-ctrl-c-ctrl-c-hook nil
20371 "Hook for functions attaching themselves to `C-c C-c'.
20373 This can be used to add additional functionality to the C-c C-c
20374 key which executes context-dependent commands. This hook is run
20375 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20376 run after the last test.
20378 Each function will be called with no arguments. The function
20379 must check if the context is appropriate for it to act. If yes,
20380 it should do its thing and then return a non-nil value. If the
20381 context is wrong, just do nothing and return nil.")
20383 (defvar org-ctrl-c-ctrl-c-final-hook nil
20384 "Hook for functions attaching themselves to `C-c C-c'.
20386 This can be used to add additional functionality to the C-c C-c
20387 key which executes context-dependent commands. This hook is run
20388 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20389 before the first test.
20391 Each function will be called with no arguments. The function
20392 must check if the context is appropriate for it to act. If yes,
20393 it should do its thing and then return a non-nil value. If the
20394 context is wrong, just do nothing and return nil.")
20396 (defvar org-tab-first-hook nil
20397 "Hook for functions to attach themselves to TAB.
20398 See `org-ctrl-c-ctrl-c-hook' for more information.
20399 This hook runs as the first action when TAB is pressed, even before
20400 `org-cycle' messes around with the `outline-regexp' to cater for
20401 inline tasks and plain list item folding.
20402 If any function in this hook returns t, any other actions that
20403 would have been caused by TAB (such as table field motion or visibility
20404 cycling) will not occur.")
20406 (defvar org-tab-after-check-for-table-hook nil
20407 "Hook for functions to attach themselves to TAB.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.
20409 This hook runs after it has been established that the cursor is not in a
20410 table, but before checking if the cursor is in a headline or if global cycling
20411 should be done.
20412 If any function in this hook returns t, not other actions like visibility
20413 cycling will be done.")
20415 (defvar org-tab-after-check-for-cycling-hook nil
20416 "Hook for functions to attach themselves to TAB.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.
20418 This hook runs after it has been established that not table field motion and
20419 not visibility should be done because of current context. This is probably
20420 the place where a package like yasnippets can hook in.")
20422 (defvar org-tab-before-tab-emulation-hook nil
20423 "Hook for functions to attach themselves to TAB.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.
20425 This hook runs after every other options for TAB have been exhausted, but
20426 before indentation and \t insertion takes place.")
20428 (defvar org-metaleft-hook nil
20429 "Hook for functions attaching themselves to `M-left'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-metaright-hook nil
20432 "Hook for functions attaching themselves to `M-right'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-metaup-hook nil
20435 "Hook for functions attaching themselves to `M-up'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-metadown-hook nil
20438 "Hook for functions attaching themselves to `M-down'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-shiftmetaleft-hook nil
20441 "Hook for functions attaching themselves to `M-S-left'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftmetaright-hook nil
20444 "Hook for functions attaching themselves to `M-S-right'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftmetaup-hook nil
20447 "Hook for functions attaching themselves to `M-S-up'.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-shiftmetadown-hook nil
20450 "Hook for functions attaching themselves to `M-S-down'.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-metareturn-hook nil
20453 "Hook for functions attaching themselves to `M-RET'.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-shiftup-hook nil
20456 "Hook for functions attaching themselves to `S-up'.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftup-final-hook nil
20459 "Hook for functions attaching themselves to `S-up'.
20460 This one runs after all other options except shift-select have been excluded.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftdown-hook nil
20463 "Hook for functions attaching themselves to `S-down'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftdown-final-hook nil
20466 "Hook for functions attaching themselves to `S-down'.
20467 This one runs after all other options except shift-select have been excluded.
20468 See `org-ctrl-c-ctrl-c-hook' for more information.")
20469 (defvar org-shiftleft-hook nil
20470 "Hook for functions attaching themselves to `S-left'.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftleft-final-hook nil
20473 "Hook for functions attaching themselves to `S-left'.
20474 This one runs after all other options except shift-select have been excluded.
20475 See `org-ctrl-c-ctrl-c-hook' for more information.")
20476 (defvar org-shiftright-hook nil
20477 "Hook for functions attaching themselves to `S-right'.
20478 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defvar org-shiftright-final-hook nil
20480 "Hook for functions attaching themselves to `S-right'.
20481 This one runs after all other options except shift-select have been excluded.
20482 See `org-ctrl-c-ctrl-c-hook' for more information.")
20484 (defun org-modifier-cursor-error ()
20485 "Throw an error, a modified cursor command was applied in wrong context."
20486 (user-error "This command is active in special context like tables, headlines or items"))
20488 (defun org-shiftselect-error ()
20489 "Throw an error because Shift-Cursor command was applied in wrong context."
20490 (if (and (boundp 'shift-select-mode) shift-select-mode)
20491 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20492 (user-error "This command works only in special context like headlines or timestamps")))
20494 (defun org-call-for-shift-select (cmd)
20495 (let ((this-command-keys-shift-translated t))
20496 (call-interactively cmd)))
20498 (defun org-shifttab (&optional arg)
20499 "Global visibility cycling or move to previous table field.
20500 Call `org-table-previous-field' within a table.
20501 When ARG is nil, cycle globally through visibility states.
20502 When ARG is a numeric prefix, show contents of this level."
20503 (interactive "P")
20504 (cond
20505 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20506 ((integerp arg)
20507 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20508 (message "Content view to level: %d" arg)
20509 (org-content (prefix-numeric-value arg2))
20510 (org-cycle-show-empty-lines t)
20511 (setq org-cycle-global-status 'overview)))
20512 (t (call-interactively 'org-global-cycle))))
20514 (defun org-shiftmetaleft ()
20515 "Promote subtree or delete table column.
20516 Calls `org-promote-subtree', `org-outdent-item-tree', or
20517 `org-table-delete-column', depending on context. See the
20518 individual commands for more information."
20519 (interactive)
20520 (cond
20521 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20522 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20523 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20524 ((if (not (org-region-active-p)) (org-at-item-p)
20525 (save-excursion (goto-char (region-beginning))
20526 (org-at-item-p)))
20527 (call-interactively 'org-outdent-item-tree))
20528 (t (org-modifier-cursor-error))))
20530 (defun org-shiftmetaright ()
20531 "Demote subtree or insert table column.
20532 Calls `org-demote-subtree', `org-indent-item-tree', or
20533 `org-table-insert-column', depending on context. See the
20534 individual commands for more information."
20535 (interactive)
20536 (cond
20537 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20538 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20539 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20540 ((if (not (org-region-active-p)) (org-at-item-p)
20541 (save-excursion (goto-char (region-beginning))
20542 (org-at-item-p)))
20543 (call-interactively 'org-indent-item-tree))
20544 (t (org-modifier-cursor-error))))
20546 (defun org-shiftmetaup (&optional _arg)
20547 "Drag the line at point up.
20548 In a table, kill the current row.
20549 On a clock timestamp, update the value of the timestamp like `S-<up>'
20550 but also adjust the previous clocked item in the clock history.
20551 Everywhere else, drag the line at point up."
20552 (interactive "P")
20553 (cond
20554 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20555 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20556 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20557 (call-interactively 'org-timestamp-up)))
20558 (t (call-interactively 'org-drag-line-backward))))
20560 (defun org-shiftmetadown (&optional _arg)
20561 "Drag the line at point down.
20562 In a table, insert an empty row at the current line.
20563 On a clock timestamp, update the value of the timestamp like `S-<down>'
20564 but also adjust the previous clocked item in the clock history.
20565 Everywhere else, drag the line at point down."
20566 (interactive "P")
20567 (cond
20568 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20569 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20570 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20571 (call-interactively 'org-timestamp-down)))
20572 (t (call-interactively 'org-drag-line-forward))))
20574 (defsubst org-hidden-tree-error ()
20575 (user-error
20576 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20578 (defun org-metaleft (&optional _arg)
20579 "Promote heading, list item at point or move table column left.
20581 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20582 depending on context. With no specific context, calls the Emacs
20583 default `backward-word'. See the individual commands for more
20584 information.
20586 This function runs the hook `org-metaleft-hook' as a first step,
20587 and returns at first non-nil value."
20588 (interactive "P")
20589 (cond
20590 ((run-hook-with-args-until-success 'org-metaleft-hook))
20591 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20592 ((org-with-limited-levels
20593 (or (org-at-heading-p)
20594 (and (org-region-active-p)
20595 (save-excursion
20596 (goto-char (region-beginning))
20597 (org-at-heading-p)))))
20598 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20599 (call-interactively 'org-do-promote))
20600 ;; At an inline task.
20601 ((org-at-heading-p)
20602 (call-interactively 'org-inlinetask-promote))
20603 ((or (org-at-item-p)
20604 (and (org-region-active-p)
20605 (save-excursion
20606 (goto-char (region-beginning))
20607 (org-at-item-p))))
20608 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20609 (call-interactively 'org-outdent-item))
20610 (t (call-interactively 'backward-word))))
20612 (defun org-metaright (&optional _arg)
20613 "Demote heading, list item at point or move table column right.
20615 In front of a drawer or a block keyword, indent it correctly.
20617 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20618 `org-indnet-drawer' or `org-indent-block' depending on context.
20619 With no specific context, calls the Emacs default `forward-word'.
20620 See the individual commands for more information.
20622 This function runs the hook `org-metaright-hook' as a first step,
20623 and returns at first non-nil value."
20624 (interactive "P")
20625 (cond
20626 ((run-hook-with-args-until-success 'org-metaright-hook))
20627 ((org-at-table-p) (call-interactively 'org-table-move-column))
20628 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20629 ((org-at-block-p) (call-interactively 'org-indent-block))
20630 ((org-with-limited-levels
20631 (or (org-at-heading-p)
20632 (and (org-region-active-p)
20633 (save-excursion
20634 (goto-char (region-beginning))
20635 (org-at-heading-p)))))
20636 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20637 (call-interactively 'org-do-demote))
20638 ;; At an inline task.
20639 ((org-at-heading-p)
20640 (call-interactively 'org-inlinetask-demote))
20641 ((or (org-at-item-p)
20642 (and (org-region-active-p)
20643 (save-excursion
20644 (goto-char (region-beginning))
20645 (org-at-item-p))))
20646 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20647 (call-interactively 'org-indent-item))
20648 (t (call-interactively 'forward-word))))
20650 (defun org-check-for-hidden (what)
20651 "Check if there are hidden headlines/items in the current visual line.
20652 WHAT can be either `headlines' or `items'. If the current line is
20653 an outline or item heading and it has a folded subtree below it,
20654 this function returns t, nil otherwise."
20655 (let ((re (cond
20656 ((eq what 'headlines) org-outline-regexp-bol)
20657 ((eq what 'items) (org-item-beginning-re))
20658 (t (error "This should not happen"))))
20659 beg end)
20660 (save-excursion
20661 (catch 'exit
20662 (unless (org-region-active-p)
20663 (setq beg (point-at-bol))
20664 (beginning-of-line 2)
20665 (while (and (not (eobp)) ;; this is like `next-line'
20666 (get-char-property (1- (point)) 'invisible))
20667 (beginning-of-line 2))
20668 (setq end (point))
20669 (goto-char beg)
20670 (goto-char (point-at-eol))
20671 (setq end (max end (point)))
20672 (while (re-search-forward re end t)
20673 (when (get-char-property (match-beginning 0) 'invisible)
20674 (throw 'exit t))))
20675 nil))))
20677 (defun org-metaup (&optional _arg)
20678 "Move subtree up or move table row up.
20679 Calls `org-move-subtree-up' or `org-table-move-row' or
20680 `org-move-item-up', depending on context. See the individual commands
20681 for more information."
20682 (interactive "P")
20683 (cond
20684 ((run-hook-with-args-until-success 'org-metaup-hook))
20685 ((org-region-active-p)
20686 (let* ((a (min (region-beginning) (region-end)))
20687 (b (1- (max (region-beginning) (region-end))))
20688 (c (save-excursion (goto-char a)
20689 (move-beginning-of-line 0)))
20690 (d (save-excursion (goto-char a)
20691 (move-end-of-line 0) (point))))
20692 (transpose-regions a b c d)
20693 (goto-char c)))
20694 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20695 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20696 ((org-at-item-p) (call-interactively 'org-move-item-up))
20697 (t (org-drag-element-backward))))
20699 (defun org-metadown (&optional _arg)
20700 "Move subtree down or move table row down.
20701 Calls `org-move-subtree-down' or `org-table-move-row' or
20702 `org-move-item-down', depending on context. See the individual
20703 commands for more information."
20704 (interactive "P")
20705 (cond
20706 ((run-hook-with-args-until-success 'org-metadown-hook))
20707 ((org-region-active-p)
20708 (let* ((a (min (region-beginning) (region-end)))
20709 (b (max (region-beginning) (region-end)))
20710 (c (save-excursion (goto-char b)
20711 (move-beginning-of-line 1)))
20712 (d (save-excursion (goto-char b)
20713 (move-end-of-line 1) (1+ (point)))))
20714 (transpose-regions a b c d)
20715 (goto-char d)))
20716 ((org-at-table-p) (call-interactively 'org-table-move-row))
20717 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20718 ((org-at-item-p) (call-interactively 'org-move-item-down))
20719 (t (org-drag-element-forward))))
20721 (defun org-shiftup (&optional arg)
20722 "Increase item in timestamp or increase priority of current headline.
20723 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20724 depending on context. See the individual commands for more information."
20725 (interactive "P")
20726 (cond
20727 ((run-hook-with-args-until-success 'org-shiftup-hook))
20728 ((and org-support-shift-select (org-region-active-p))
20729 (org-call-for-shift-select 'previous-line))
20730 ((org-at-timestamp-p t)
20731 (call-interactively (if org-edit-timestamp-down-means-later
20732 'org-timestamp-down 'org-timestamp-up)))
20733 ((and (not (eq org-support-shift-select 'always))
20734 org-enable-priority-commands
20735 (org-at-heading-p))
20736 (call-interactively 'org-priority-up))
20737 ((and (not org-support-shift-select) (org-at-item-p))
20738 (call-interactively 'org-previous-item))
20739 ((org-clocktable-try-shift 'up arg))
20740 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20741 (org-support-shift-select
20742 (org-call-for-shift-select 'previous-line))
20743 (t (org-shiftselect-error))))
20745 (defun org-shiftdown (&optional arg)
20746 "Decrease item in timestamp or decrease priority of current headline.
20747 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20748 depending on context. See the individual commands for more information."
20749 (interactive "P")
20750 (cond
20751 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20752 ((and org-support-shift-select (org-region-active-p))
20753 (org-call-for-shift-select 'next-line))
20754 ((org-at-timestamp-p t)
20755 (call-interactively (if org-edit-timestamp-down-means-later
20756 'org-timestamp-up 'org-timestamp-down)))
20757 ((and (not (eq org-support-shift-select 'always))
20758 org-enable-priority-commands
20759 (org-at-heading-p))
20760 (call-interactively 'org-priority-down))
20761 ((and (not org-support-shift-select) (org-at-item-p))
20762 (call-interactively 'org-next-item))
20763 ((org-clocktable-try-shift 'down arg))
20764 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20765 (org-support-shift-select
20766 (org-call-for-shift-select 'next-line))
20767 (t (org-shiftselect-error))))
20769 (defun org-shiftright (&optional arg)
20770 "Cycle the thing at point or in the current line, depending on context.
20771 Depending on context, this does one of the following:
20773 - switch a timestamp at point one day into the future
20774 - on a headline, switch to the next TODO keyword.
20775 - on an item, switch entire list to the next bullet type
20776 - on a property line, switch to the next allowed value
20777 - on a clocktable definition line, move time block into the future"
20778 (interactive "P")
20779 (cond
20780 ((run-hook-with-args-until-success 'org-shiftright-hook))
20781 ((and org-support-shift-select (org-region-active-p))
20782 (org-call-for-shift-select 'forward-char))
20783 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20784 ((and (not (eq org-support-shift-select 'always))
20785 (org-at-heading-p))
20786 (let ((org-inhibit-logging
20787 (not org-treat-S-cursor-todo-selection-as-state-change))
20788 (org-inhibit-blocking
20789 (not org-treat-S-cursor-todo-selection-as-state-change)))
20790 (org-call-with-arg 'org-todo 'right)))
20791 ((or (and org-support-shift-select
20792 (not (eq org-support-shift-select 'always))
20793 (org-at-item-bullet-p))
20794 (and (not org-support-shift-select) (org-at-item-p)))
20795 (org-call-with-arg 'org-cycle-list-bullet nil))
20796 ((and (not (eq org-support-shift-select 'always))
20797 (org-at-property-p))
20798 (call-interactively 'org-property-next-allowed-value))
20799 ((org-clocktable-try-shift 'right arg))
20800 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20801 (org-support-shift-select
20802 (org-call-for-shift-select 'forward-char))
20803 (t (org-shiftselect-error))))
20805 (defun org-shiftleft (&optional arg)
20806 "Cycle the thing at point or in the current line, depending on context.
20807 Depending on context, this does one of the following:
20809 - switch a timestamp at point one day into the past
20810 - on a headline, switch to the previous TODO keyword.
20811 - on an item, switch entire list to the previous bullet type
20812 - on a property line, switch to the previous allowed value
20813 - on a clocktable definition line, move time block into the past"
20814 (interactive "P")
20815 (cond
20816 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20817 ((and org-support-shift-select (org-region-active-p))
20818 (org-call-for-shift-select 'backward-char))
20819 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20820 ((and (not (eq org-support-shift-select 'always))
20821 (org-at-heading-p))
20822 (let ((org-inhibit-logging
20823 (not org-treat-S-cursor-todo-selection-as-state-change))
20824 (org-inhibit-blocking
20825 (not org-treat-S-cursor-todo-selection-as-state-change)))
20826 (org-call-with-arg 'org-todo 'left)))
20827 ((or (and org-support-shift-select
20828 (not (eq org-support-shift-select 'always))
20829 (org-at-item-bullet-p))
20830 (and (not org-support-shift-select) (org-at-item-p)))
20831 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20832 ((and (not (eq org-support-shift-select 'always))
20833 (org-at-property-p))
20834 (call-interactively 'org-property-previous-allowed-value))
20835 ((org-clocktable-try-shift 'left arg))
20836 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20837 (org-support-shift-select
20838 (org-call-for-shift-select 'backward-char))
20839 (t (org-shiftselect-error))))
20841 (defun org-shiftcontrolright ()
20842 "Switch to next TODO set."
20843 (interactive)
20844 (cond
20845 ((and org-support-shift-select (org-region-active-p))
20846 (org-call-for-shift-select 'forward-word))
20847 ((and (not (eq org-support-shift-select 'always))
20848 (org-at-heading-p))
20849 (org-call-with-arg 'org-todo 'nextset))
20850 (org-support-shift-select
20851 (org-call-for-shift-select 'forward-word))
20852 (t (org-shiftselect-error))))
20854 (defun org-shiftcontrolleft ()
20855 "Switch to previous TODO set."
20856 (interactive)
20857 (cond
20858 ((and org-support-shift-select (org-region-active-p))
20859 (org-call-for-shift-select 'backward-word))
20860 ((and (not (eq org-support-shift-select 'always))
20861 (org-at-heading-p))
20862 (org-call-with-arg 'org-todo 'previousset))
20863 (org-support-shift-select
20864 (org-call-for-shift-select 'backward-word))
20865 (t (org-shiftselect-error))))
20867 (defun org-shiftcontrolup (&optional n)
20868 "Change timestamps synchronously up in CLOCK log lines.
20869 Optional argument N tells to change by that many units."
20870 (interactive "P")
20871 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20872 (let (org-support-shift-select)
20873 (org-clock-timestamps-up n))
20874 (user-error "Not at a clock log")))
20876 (defun org-shiftcontroldown (&optional n)
20877 "Change timestamps synchronously down in CLOCK log lines.
20878 Optional argument N tells to change by that many units."
20879 (interactive "P")
20880 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20881 (let (org-support-shift-select)
20882 (org-clock-timestamps-down n))
20883 (user-error "Not at a clock log")))
20885 (defun org-increase-number-at-point (&optional inc)
20886 "Increment the number at point.
20887 With an optional prefix numeric argument INC, increment using
20888 this numeric value."
20889 (interactive "p")
20890 (if (not (number-at-point))
20891 (user-error "Not on a number")
20892 (unless inc (setq inc 1))
20893 (let ((pos (point))
20894 (beg (skip-chars-backward "-+^/*0-9eE."))
20895 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20896 (setq nap (buffer-substring-no-properties
20897 (+ pos beg) (+ pos beg end)))
20898 (delete-region (+ pos beg) (+ pos beg end))
20899 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20900 (when (org-at-table-p)
20901 (org-table-align)
20902 (org-table-end-of-field 1))))
20904 (defun org-decrease-number-at-point (&optional inc)
20905 "Decrement the number at point.
20906 With an optional prefix numeric argument INC, decrement using
20907 this numeric value."
20908 (interactive "p")
20909 (org-increase-number-at-point (- (or inc 1))))
20911 (defun org-ctrl-c-ret ()
20912 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20913 (interactive)
20914 (cond
20915 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20916 (t (call-interactively 'org-insert-heading))))
20918 (defun org-find-visible ()
20919 (let ((s (point)))
20920 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20921 (get-char-property s 'invisible)))
20923 (defun org-find-invisible ()
20924 (let ((s (point)))
20925 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20926 (not (get-char-property s 'invisible))))
20929 (defun org-copy-visible (beg end)
20930 "Copy the visible parts of the region."
20931 (interactive "r")
20932 (let (snippets s)
20933 (save-excursion
20934 (save-restriction
20935 (narrow-to-region beg end)
20936 (setq s (goto-char (point-min)))
20937 (while (not (= (point) (point-max)))
20938 (goto-char (org-find-invisible))
20939 (push (buffer-substring s (point)) snippets)
20940 (setq s (goto-char (org-find-visible))))))
20941 (kill-new (apply 'concat (nreverse snippets)))))
20943 (defun org-copy-special ()
20944 "Copy region in table or copy current subtree.
20945 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20946 context. See the individual commands for more information."
20947 (interactive)
20948 (call-interactively
20949 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20951 (defun org-cut-special ()
20952 "Cut region in table or cut current subtree.
20953 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20954 context. See the individual commands for more information."
20955 (interactive)
20956 (call-interactively
20957 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20959 (defun org-paste-special (arg)
20960 "Paste rectangular region into table, or past subtree relative to level.
20961 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20962 See the individual commands for more information."
20963 (interactive "P")
20964 (if (org-at-table-p)
20965 (org-table-paste-rectangle)
20966 (org-paste-subtree arg)))
20968 (defsubst org-in-fixed-width-region-p ()
20969 "Is point in a fixed-width region?"
20970 (save-match-data
20971 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20973 (defun org-edit-special (&optional arg)
20974 "Call a special editor for the element at point.
20975 When at a table, call the formula editor with `org-table-edit-formulas'.
20976 When in a source code block, call `org-edit-src-code'.
20977 When in a fixed-width region, call `org-edit-fixed-width-region'.
20978 When in an export block, call `org-edit-export-block'.
20979 When at an #+INCLUDE keyword, visit the included file.
20980 When at a footnote reference, call `org-edit-footnote-reference'
20981 On a link, call `ffap' to visit the link at point.
20982 Otherwise, return a user error."
20983 (interactive "P")
20984 (let ((element (org-element-at-point)))
20985 (barf-if-buffer-read-only)
20986 (pcase (org-element-type element)
20987 (`src-block
20988 (if (not arg) (org-edit-src-code)
20989 (let* ((info (org-babel-get-src-block-info))
20990 (lang (nth 0 info))
20991 (params (nth 2 info))
20992 (session (cdr (assq :session params))))
20993 (if (not session) (org-edit-src-code)
20994 ;; At a src-block with a session and function called with
20995 ;; an ARG: switch to the buffer related to the inferior
20996 ;; process.
20997 (switch-to-buffer
20998 (funcall (intern (concat "org-babel-prep-session:" lang))
20999 session params))))))
21000 (`keyword
21001 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21002 (org-open-link-from-string
21003 (format "[[%s]]"
21004 (expand-file-name
21005 (let ((value (org-element-property :value element)))
21006 (cond ((not (org-string-nw-p value))
21007 (user-error "No file to edit"))
21008 ((string-match "\\`\"\\(.*?\\)\"" value)
21009 (match-string 1 value))
21010 ((string-match "\\`[^ \t\"]\\S-*" value)
21011 (match-string 0 value))
21012 (t (user-error "No valid file specified")))))))
21013 (user-error "No special environment to edit here")))
21014 (`table
21015 (if (eq (org-element-property :type element) 'table.el)
21016 (org-edit-table.el)
21017 (call-interactively 'org-table-edit-formulas)))
21018 ;; Only Org tables contain `table-row' type elements.
21019 (`table-row (call-interactively 'org-table-edit-formulas))
21020 (`example-block (org-edit-src-code))
21021 (`export-block (org-edit-export-block))
21022 (`fixed-width (org-edit-fixed-width-region))
21024 ;; No notable element at point. Though, we may be at a link or
21025 ;; a footnote reference, which are objects. Thus, scan deeper.
21026 (let ((context (org-element-context element)))
21027 (pcase (org-element-type context)
21028 (`footnote-reference (org-edit-footnote-reference))
21029 (`inline-src-block (org-edit-inline-src-code))
21030 (`link (call-interactively #'ffap))
21031 (_ (user-error "No special environment to edit here"))))))))
21033 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21034 (defun org-ctrl-c-ctrl-c (&optional arg)
21035 "Set tags in headline, or update according to changed information at point.
21037 This command does many different things, depending on context:
21039 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21040 this is what we do.
21042 - If the cursor is on a statistics cookie, update it.
21044 - If the cursor is in a headline, prompt for tags and insert them
21045 into the current line, aligned to `org-tags-column'. When called
21046 with prefix arg, realign all tags in the current buffer.
21048 - If the cursor is in one of the special #+KEYWORD lines, this
21049 triggers scanning the buffer for these lines and updating the
21050 information.
21052 - If the cursor is inside a table, realign the table. This command
21053 works even if the automatic table editor has been turned off.
21055 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21056 the entire table.
21058 - If the cursor is at a footnote reference or definition, jump to
21059 the corresponding definition or references, respectively.
21061 - If the cursor is a the beginning of a dynamic block, update it.
21063 - If the current buffer is a capture buffer, close note and file it.
21065 - If the cursor is on a <<<target>>>, update radio targets and
21066 corresponding links in this buffer.
21068 - If the cursor is on a numbered item in a plain list, renumber the
21069 ordered list.
21071 - If the cursor is on a checkbox, toggle it.
21073 - If the cursor is on a code block, evaluate it. The variable
21074 `org-confirm-babel-evaluate' can be used to control prompting
21075 before code block evaluation, by default every code block
21076 evaluation requires confirmation. Code block evaluation can be
21077 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21078 (interactive "P")
21079 (cond
21080 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21081 org-occur-highlights)
21082 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21083 (org-remove-occur-highlights)
21084 (message "Temporary highlights/overlays removed from current buffer"))
21085 ((and (local-variable-p 'org-finish-function (current-buffer))
21086 (fboundp org-finish-function))
21087 (funcall org-finish-function))
21088 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21090 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21091 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21092 (user-error "C-c C-c can do nothing useful at this location"))
21093 (let* ((context (org-element-context))
21094 (type (org-element-type context)))
21095 (cl-case type
21096 ;; When at a link, act according to the parent instead.
21097 (link (setq context (org-element-property :parent context))
21098 (setq type (org-element-type context)))
21099 ;; Unsupported object types: refer to the first supported
21100 ;; element or object containing it.
21101 ((bold code entity export-snippet inline-babel-call inline-src-block
21102 italic latex-fragment line-break macro strike-through subscript
21103 superscript underline verbatim)
21104 (setq context
21105 (org-element-lineage
21106 context '(radio-target paragraph verse-block table-cell)))))
21107 ;; For convenience: at the first line of a paragraph on the
21108 ;; same line as an item, apply function on that item instead.
21109 (when (eq type 'paragraph)
21110 (let ((parent (org-element-property :parent context)))
21111 (when (and (eq (org-element-type parent) 'item)
21112 (= (line-beginning-position)
21113 (org-element-property :begin parent)))
21114 (setq context parent type 'item))))
21115 ;; Act according to type of element or object at point.
21116 (cl-case type
21117 (clock (org-clock-update-time-maybe))
21118 (dynamic-block
21119 (save-excursion
21120 (goto-char (org-element-property :post-affiliated context))
21121 (org-update-dblock)))
21122 (footnote-definition
21123 (goto-char (org-element-property :post-affiliated context))
21124 (call-interactively 'org-footnote-action))
21125 (footnote-reference (call-interactively 'org-footnote-action))
21126 ((headline inlinetask)
21127 (save-excursion (goto-char (org-element-property :begin context))
21128 (call-interactively 'org-set-tags)))
21129 (item
21130 ;; At an item: a double C-u set checkbox to "[-]"
21131 ;; unconditionally, whereas a single one will toggle its
21132 ;; presence. Without a universal argument, if the item
21133 ;; has a checkbox, toggle it. Otherwise repair the list.
21134 (let* ((box (org-element-property :checkbox context))
21135 (struct (org-element-property :structure context))
21136 (old-struct (copy-tree struct))
21137 (parents (org-list-parents-alist struct))
21138 (prevs (org-list-prevs-alist struct))
21139 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21140 (org-list-set-checkbox
21141 (org-element-property :begin context) struct
21142 (cond ((equal arg '(16)) "[-]")
21143 ((and (not box) (equal arg '(4))) "[ ]")
21144 ((or (not box) (equal arg '(4))) nil)
21145 ((eq box 'on) "[ ]")
21146 (t "[X]")))
21147 ;; Mimic `org-list-write-struct' but with grabbing
21148 ;; a return value from `org-list-struct-fix-box'.
21149 (org-list-struct-fix-ind struct parents 2)
21150 (org-list-struct-fix-item-end struct)
21151 (org-list-struct-fix-bul struct prevs)
21152 (org-list-struct-fix-ind struct parents)
21153 (let ((block-item
21154 (org-list-struct-fix-box struct parents prevs orderedp)))
21155 (if (and box (equal struct old-struct))
21156 (if (equal arg '(16))
21157 (message "Checkboxes already reset")
21158 (user-error "Cannot toggle this checkbox: %s"
21159 (if (eq box 'on)
21160 "all subitems checked"
21161 "unchecked subitems")))
21162 (org-list-struct-apply-struct struct old-struct)
21163 (org-update-checkbox-count-maybe))
21164 (when block-item
21165 (message "Checkboxes were removed due to empty box at line %d"
21166 (org-current-line block-item))))))
21167 (keyword
21168 (let ((org-inhibit-startup-visibility-stuff t)
21169 (org-startup-align-all-tables nil))
21170 (when (boundp 'org-table-coordinate-overlays)
21171 (mapc #'delete-overlay org-table-coordinate-overlays)
21172 (setq org-table-coordinate-overlays nil))
21173 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21174 (message "Local setup has been refreshed"))
21175 (plain-list
21176 ;; At a plain list, with a double C-u argument, set
21177 ;; checkboxes of each item to "[-]", whereas a single one
21178 ;; will toggle their presence according to the state of the
21179 ;; first item in the list. Without an argument, repair the
21180 ;; list.
21181 (let* ((begin (org-element-property :contents-begin context))
21182 (beginm (move-marker (make-marker) begin))
21183 (struct (org-element-property :structure context))
21184 (old-struct (copy-tree struct))
21185 (first-box (save-excursion
21186 (goto-char begin)
21187 (looking-at org-list-full-item-re)
21188 (match-string-no-properties 3)))
21189 (new-box (cond ((equal arg '(16)) "[-]")
21190 ((equal arg '(4)) (unless first-box "[ ]"))
21191 ((equal first-box "[X]") "[ ]")
21192 (t "[X]"))))
21193 (cond
21194 (arg
21195 (dolist (pos
21196 (org-list-get-all-items
21197 begin struct (org-list-prevs-alist struct)))
21198 (org-list-set-checkbox pos struct new-box)))
21199 ((and first-box (eq (point) begin))
21200 ;; For convenience, when point is at bol on the first
21201 ;; item of the list and no argument is provided, simply
21202 ;; toggle checkbox of that item, if any.
21203 (org-list-set-checkbox begin struct new-box)))
21204 (org-list-write-struct
21205 struct (org-list-parents-alist struct) old-struct)
21206 (org-update-checkbox-count-maybe)
21207 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21208 ((property-drawer node-property)
21209 (call-interactively 'org-property-action))
21210 ((radio-target target)
21211 (call-interactively 'org-update-radio-target-regexp))
21212 (statistics-cookie
21213 (call-interactively 'org-update-statistics-cookies))
21214 ((table table-cell table-row)
21215 ;; At a table, recalculate every field and align it. Also
21216 ;; send the table if necessary. If the table has
21217 ;; a `table.el' type, just give up. At a table row or
21218 ;; cell, maybe recalculate line but always align table.
21219 (if (eq (org-element-property :type context) 'table.el)
21220 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21221 Use \\[org-edit-special] to edit table.el tables"))
21222 (let ((org-enable-table-editor t))
21223 (if (or (eq type 'table)
21224 ;; Check if point is at a TBLFM line.
21225 (and (eq type 'table-row)
21226 (= (point) (org-element-property :end context))))
21227 (save-excursion
21228 (if (org-at-TBLFM-p)
21229 (progn (require 'org-table)
21230 (org-table-calc-current-TBLFM))
21231 (goto-char (org-element-property :contents-begin context))
21232 (org-call-with-arg 'org-table-recalculate (or arg t))
21233 (orgtbl-send-table 'maybe)))
21234 (org-table-maybe-eval-formula)
21235 (cond (arg (call-interactively 'org-table-recalculate))
21236 ((org-table-maybe-recalculate-line))
21237 (t (org-table-align)))))))
21238 (timestamp (org-timestamp-change 0 'day))
21239 (otherwise
21240 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21241 (user-error
21242 "C-c C-c can do nothing useful at this location")))))))))
21244 (defun org-mode-restart ()
21245 (interactive)
21246 (let ((indent-status (bound-and-true-p org-indent-mode)))
21247 (funcall major-mode)
21248 (hack-local-variables)
21249 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21250 (org-indent-mode -1)))
21251 (message "%s restarted" major-mode))
21253 (defun org-kill-note-or-show-branches ()
21254 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21255 (interactive)
21256 (if (not org-finish-function)
21257 (progn
21258 (outline-hide-subtree)
21259 (call-interactively 'outline-show-branches))
21260 (let ((org-note-abort t))
21261 (funcall org-finish-function))))
21263 (defun org-delete-indentation (&optional ARG)
21264 "Join current line to previous and fix whitespace at join.
21266 If previous line is a headline add to headline title. Otherwise
21267 the function calls `delete-indentation'.
21269 With argument, join this line to following line."
21270 (interactive "*P")
21271 (if (save-excursion
21272 (if ARG (beginning-of-line)
21273 (forward-line -1))
21274 (looking-at org-complex-heading-regexp))
21275 ;; At headline.
21276 (let ((tags-column (when (match-beginning 5)
21277 (save-excursion (goto-char (match-beginning 5))
21278 (current-column))))
21279 (string (concat " " (progn (when ARG (forward-line 1))
21280 (org-trim (delete-and-extract-region
21281 (line-beginning-position)
21282 (line-end-position)))))))
21283 (unless (bobp) (delete-region (point) (1- (point))))
21284 (goto-char (or (match-end 4)
21285 (match-beginning 5)
21286 (match-end 0)))
21287 (skip-chars-backward " \t")
21288 (save-excursion (insert string))
21289 ;; Adjust alignment of tags.
21290 (when tags-column
21291 (org-align-tags-here (if org-auto-align-tags
21292 org-tags-column
21293 tags-column))))
21294 (delete-indentation ARG)))
21296 (defun org-open-line (n)
21297 "Insert a new row in tables, call `open-line' elsewhere.
21298 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21299 As a special case, when a document starts with a table, allow to
21300 call `open-line' on the very first character."
21301 (interactive "*p")
21302 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21303 (org-table-insert-row)
21304 (open-line n)))
21306 (defun org-return (&optional indent)
21307 "Goto next table row or insert a newline.
21309 Calls `org-table-next-row' or `newline', depending on context.
21311 When optional INDENT argument is non-nil, call
21312 `newline-and-indent' instead of `newline'.
21314 When `org-return-follows-link' is non-nil and point is on
21315 a timestamp or a link, call `org-open-at-point'. However, it
21316 will not happen if point is in a table or on a \"dead\"
21317 object (e.g., within a comment). In these case, you need to use
21318 `org-open-at-point' directly."
21319 (interactive)
21320 (let ((context (if org-return-follows-link (org-element-context)
21321 (org-element-at-point))))
21322 (cond
21323 ;; In a table, call `org-table-next-row'.
21324 ((or (and (eq (org-element-type context) 'table)
21325 (>= (point) (org-element-property :contents-begin context))
21326 (< (point) (org-element-property :contents-end context)))
21327 (org-element-lineage context '(table-row table-cell) t))
21328 (org-table-justify-field-maybe)
21329 (call-interactively #'org-table-next-row))
21330 ;; On a link or a timestamp, call `org-open-at-point' if
21331 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21332 ;; locations, e.g., in a comment, as `org-open-at-point'.
21333 ((and org-return-follows-link
21334 (or (org-in-regexp org-ts-regexp-both nil t)
21335 (org-in-regexp org-tsr-regexp-both nil t)
21336 (org-in-regexp org-any-link-re nil t)))
21337 (call-interactively #'org-open-at-point))
21338 ;; Insert newline in heading, but preserve tags.
21339 ((and (not (bolp))
21340 (save-excursion (beginning-of-line)
21341 (looking-at org-complex-heading-regexp)))
21342 ;; At headline. Split line. However, if point is on keyword,
21343 ;; priority cookie or tags, do not break any of them: add
21344 ;; a newline after the headline instead.
21345 (let ((tags-column (and (match-beginning 5)
21346 (save-excursion (goto-char (match-beginning 5))
21347 (current-column))))
21348 (string
21349 (when (and (match-end 4)
21350 (>= (point)
21351 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21352 (<= (point) (match-end 4)))
21353 (delete-and-extract-region (point) (match-end 4)))))
21354 (when (and tags-column string) ; Adjust tag alignment.
21355 (org-align-tags-here
21356 (if org-auto-align-tags org-tags-column tags-column)))
21357 (end-of-line)
21358 (org-show-entry)
21359 (if indent (newline-and-indent) (newline))
21360 (when string (save-excursion (insert (org-trim string))))))
21361 ;; In a list, make sure indenting keeps trailing text within.
21362 ((and indent
21363 (not (eolp))
21364 (org-element-lineage context '(item)))
21365 (let ((trailing-data
21366 (delete-and-extract-region (point) (line-end-position))))
21367 (newline-and-indent)
21368 (save-excursion (insert trailing-data))))
21369 (t (if indent (newline-and-indent) (newline))))))
21371 (defun org-return-indent ()
21372 "Goto next table row or insert a newline and indent.
21373 Calls `org-table-next-row' or `newline-and-indent', depending on
21374 context. See the individual commands for more information."
21375 (interactive)
21376 (org-return t))
21378 (defun org-ctrl-c-star ()
21379 "Compute table, or change heading status of lines.
21380 Calls `org-table-recalculate' or `org-toggle-heading',
21381 depending on context."
21382 (interactive)
21383 (cond
21384 ((org-at-table-p)
21385 (call-interactively 'org-table-recalculate))
21387 ;; Convert all lines in region to list items
21388 (call-interactively 'org-toggle-heading))))
21390 (defun org-ctrl-c-minus ()
21391 "Insert separator line in table or modify bullet status of line.
21392 Also turns a plain line or a region of lines into list items.
21393 Calls `org-table-insert-hline', `org-toggle-item', or
21394 `org-cycle-list-bullet', depending on context."
21395 (interactive)
21396 (cond
21397 ((org-at-table-p)
21398 (call-interactively 'org-table-insert-hline))
21399 ((org-region-active-p)
21400 (call-interactively 'org-toggle-item))
21401 ((org-in-item-p)
21402 (call-interactively 'org-cycle-list-bullet))
21404 (call-interactively 'org-toggle-item))))
21406 (defun org-toggle-heading (&optional nstars)
21407 "Convert headings to normal text, or items or text to headings.
21408 If there is no active region, only convert the current line.
21410 With a \\[universal-argument] prefix, convert the whole list at
21411 point into heading.
21413 In a region:
21415 - If the first non blank line is a headline, remove the stars
21416 from all headlines in the region.
21418 - If it is a normal line, turn each and every normal line (i.e.,
21419 not an heading or an item) in the region into headings. If you
21420 want to convert only the first line of this region, use one
21421 universal prefix argument.
21423 - If it is a plain list item, turn all plain list items into headings.
21425 When converting a line into a heading, the number of stars is chosen
21426 such that the lines become children of the current entry. However,
21427 when a numeric prefix argument is given, its value determines the
21428 number of stars to add."
21429 (interactive "P")
21430 (let ((skip-blanks
21431 (function
21432 ;; Return beginning of first non-blank line, starting from
21433 ;; line at POS.
21434 (lambda (pos)
21435 (save-excursion
21436 (goto-char pos)
21437 (while (org-at-comment-p) (forward-line))
21438 (skip-chars-forward " \r\t\n")
21439 (point-at-bol)))))
21440 beg end toggled)
21441 ;; Determine boundaries of changes. If a universal prefix has
21442 ;; been given, put the list in a region. If region ends at a bol,
21443 ;; do not consider the last line to be in the region.
21445 (when (and current-prefix-arg (org-at-item-p))
21446 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21447 (org-mark-element))
21449 (if (org-region-active-p)
21450 (setq beg (funcall skip-blanks (region-beginning))
21451 end (copy-marker (save-excursion
21452 (goto-char (region-end))
21453 (if (bolp) (point) (point-at-eol)))))
21454 (setq beg (funcall skip-blanks (point-at-bol))
21455 end (copy-marker (point-at-eol))))
21456 ;; Ensure inline tasks don't count as headings.
21457 (org-with-limited-levels
21458 (save-excursion
21459 (goto-char beg)
21460 (cond
21461 ;; Case 1. Started at an heading: de-star headings.
21462 ((org-at-heading-p)
21463 (while (< (point) end)
21464 (when (org-at-heading-p t)
21465 (looking-at org-outline-regexp) (replace-match "")
21466 (setq toggled t))
21467 (forward-line)))
21468 ;; Case 2. Started at an item: change items into headlines.
21469 ;; One star will be added by `org-list-to-subtree'.
21470 ((org-at-item-p)
21471 (while (< (point) end)
21472 (when (org-at-item-p)
21473 ;; Pay attention to cases when region ends before list.
21474 (let* ((struct (org-list-struct))
21475 (list-end
21476 (min (org-list-get-bottom-point struct) (1+ end))))
21477 (save-restriction
21478 (narrow-to-region (point) list-end)
21479 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21480 (setq toggled t))
21481 (forward-line)))
21482 ;; Case 3. Started at normal text: make every line an heading,
21483 ;; skipping headlines and items.
21484 (t (let* ((stars
21485 (make-string
21486 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21487 (add-stars
21488 (cond (nstars "") ; stars from prefix only
21489 ((equal stars "") "*") ; before first heading
21490 (org-odd-levels-only "**") ; inside heading, odd
21491 (t "*"))) ; inside heading, oddeven
21492 (rpl (concat stars add-stars " "))
21493 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21494 (while (< (point) (if (equal nstars '(4)) lend end))
21495 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21496 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21497 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21498 (forward-line)))))))
21499 (unless toggled (message "Cannot toggle heading from here"))))
21501 (defun org-meta-return (&optional _arg)
21502 "Insert a new heading or wrap a region in a table.
21503 Calls `org-insert-heading' or `org-table-wrap-region', depending
21504 on context. See the individual commands for more information."
21505 (interactive)
21506 (org-check-before-invisible-edit 'insert)
21507 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21508 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21509 #'org-insert-heading))))
21511 ;;; Menu entries
21513 (defsubst org-in-subtree-not-table-p ()
21514 "Are we in a subtree and not in a table?"
21515 (and (not (org-before-first-heading-p))
21516 (not (org-at-table-p))))
21518 ;; Define the Org mode menus
21519 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21520 '("Tbl"
21521 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21522 ["Next Field" org-cycle (org-at-table-p)]
21523 ["Previous Field" org-shifttab (org-at-table-p)]
21524 ["Next Row" org-return (org-at-table-p)]
21525 "--"
21526 ["Blank Field" org-table-blank-field (org-at-table-p)]
21527 ["Edit Field" org-table-edit-field (org-at-table-p)]
21528 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21529 "--"
21530 ("Column"
21531 ["Move Column Left" org-metaleft (org-at-table-p)]
21532 ["Move Column Right" org-metaright (org-at-table-p)]
21533 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21534 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21535 ("Row"
21536 ["Move Row Up" org-metaup (org-at-table-p)]
21537 ["Move Row Down" org-metadown (org-at-table-p)]
21538 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21539 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21540 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21541 "--"
21542 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21543 ("Rectangle"
21544 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21545 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21546 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21547 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21548 "--"
21549 ("Calculate"
21550 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21551 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21552 ["Edit Formulas" org-edit-special (org-at-table-p)]
21553 "--"
21554 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21555 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21556 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21557 "--"
21558 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21559 "--"
21560 ["Sum Column/Rectangle" org-table-sum
21561 (or (org-at-table-p) (org-region-active-p))]
21562 ["Which Column?" org-table-current-column (org-at-table-p)])
21563 ["Debug Formulas"
21564 org-table-toggle-formula-debugger
21565 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21566 ["Show Col/Row Numbers"
21567 org-table-toggle-coordinate-overlays
21568 :style toggle
21569 :selected (bound-and-true-p org-table-overlay-coordinates)]
21570 "--"
21571 ["Create" org-table-create (and (not (org-at-table-p))
21572 org-enable-table-editor)]
21573 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21574 ["Import from File" org-table-import (not (org-at-table-p))]
21575 ["Export to File" org-table-export (org-at-table-p)]
21576 "--"
21577 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21578 "--"
21579 ("Plot"
21580 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21581 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21583 (easy-menu-define org-org-menu org-mode-map "Org menu"
21584 '("Org"
21585 ("Show/Hide"
21586 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21587 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21588 ["Sparse Tree..." org-sparse-tree t]
21589 ["Reveal Context" org-reveal t]
21590 ["Show All" outline-show-all t]
21591 "--"
21592 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21593 "--"
21594 ["New Heading" org-insert-heading t]
21595 ("Navigate Headings"
21596 ["Up" outline-up-heading t]
21597 ["Next" outline-next-visible-heading t]
21598 ["Previous" outline-previous-visible-heading t]
21599 ["Next Same Level" outline-forward-same-level t]
21600 ["Previous Same Level" outline-backward-same-level t]
21601 "--"
21602 ["Jump" org-goto t])
21603 ("Edit Structure"
21604 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21605 "--"
21606 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21607 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21608 "--"
21609 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21610 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21611 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21612 "--"
21613 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21614 "--"
21615 ["Copy visible text" org-copy-visible t]
21616 "--"
21617 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21618 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21619 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21620 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21621 "--"
21622 ["Sort Region/Children" org-sort t]
21623 "--"
21624 ["Convert to odd levels" org-convert-to-odd-levels t]
21625 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21626 ("Editing"
21627 ["Emphasis..." org-emphasize t]
21628 ["Edit Source Example" org-edit-special t]
21629 "--"
21630 ["Footnote new/jump" org-footnote-action t]
21631 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21632 ("Archive"
21633 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21634 "--"
21635 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21636 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21637 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21639 "--"
21640 ("Hyperlinks"
21641 ["Store Link (Global)" org-store-link t]
21642 ["Find existing link to here" org-occur-link-in-agenda-files t]
21643 ["Insert Link" org-insert-link t]
21644 ["Follow Link" org-open-at-point t]
21645 "--"
21646 ["Next link" org-next-link t]
21647 ["Previous link" org-previous-link t]
21648 "--"
21649 ["Descriptive Links"
21650 org-toggle-link-display
21651 :style radio
21652 :selected org-descriptive-links
21654 ["Literal Links"
21655 org-toggle-link-display
21656 :style radio
21657 :selected (not org-descriptive-links)])
21658 "--"
21659 ("TODO Lists"
21660 ["TODO/DONE/-" org-todo t]
21661 ("Select keyword"
21662 ["Next keyword" org-shiftright (org-at-heading-p)]
21663 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21664 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21665 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21666 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21667 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21668 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21669 "--"
21670 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21671 :selected org-enforce-todo-dependencies :style toggle :active t]
21672 "Settings for tree at point"
21673 ["Do Children sequentially" org-toggle-ordered-property :style radio
21674 :selected (org-entry-get nil "ORDERED")
21675 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21676 ["Do Children parallel" org-toggle-ordered-property :style radio
21677 :selected (not (org-entry-get nil "ORDERED"))
21678 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21679 "--"
21680 ["Set Priority" org-priority t]
21681 ["Priority Up" org-shiftup t]
21682 ["Priority Down" org-shiftdown t]
21683 "--"
21684 ["Get news from all feeds" org-feed-update-all t]
21685 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21686 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21687 ("TAGS and Properties"
21688 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21689 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21690 "--"
21691 ["Set property" org-set-property (not (org-before-first-heading-p))]
21692 ["Column view of properties" org-columns t]
21693 ["Insert Column View DBlock" org-columns-insert-dblock t])
21694 ("Dates and Scheduling"
21695 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21696 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21697 ("Change Date"
21698 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21699 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21700 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21701 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21702 ["Compute Time Range" org-evaluate-time-range t]
21703 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21704 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21705 "--"
21706 ["Custom time format" org-toggle-time-stamp-overlays
21707 :style radio :selected org-display-custom-times]
21708 "--"
21709 ["Goto Calendar" org-goto-calendar t]
21710 ["Date from Calendar" org-date-from-calendar t]
21711 "--"
21712 ["Start/Restart Timer" org-timer-start t]
21713 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21714 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21715 ["Insert Timer String" org-timer t]
21716 ["Insert Timer Item" org-timer-item t])
21717 ("Logging work"
21718 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21719 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21720 ["Clock out" org-clock-out t]
21721 ["Clock cancel" org-clock-cancel t]
21722 "--"
21723 ["Mark as default task" org-clock-mark-default-task t]
21724 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21725 ["Goto running clock" org-clock-goto t]
21726 "--"
21727 ["Display times" org-clock-display t]
21728 ["Create clock table" org-clock-report t]
21729 "--"
21730 ["Record DONE time"
21731 (progn (setq org-log-done (not org-log-done))
21732 (message "Switching to %s will %s record a timestamp"
21733 (car org-done-keywords)
21734 (if org-log-done "automatically" "not")))
21735 :style toggle :selected org-log-done])
21736 "--"
21737 ["Agenda Command..." org-agenda t]
21738 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21739 ("File List for Agenda")
21740 ("Special views current file"
21741 ["TODO Tree" org-show-todo-tree t]
21742 ["Check Deadlines" org-check-deadlines t]
21743 ["Timeline" org-timeline t]
21744 ["Tags/Property tree" org-match-sparse-tree t])
21745 "--"
21746 ["Export/Publish..." org-export-dispatch t]
21747 ("LaTeX"
21748 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21749 :selected org-cdlatex-mode]
21750 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21751 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21752 ["Modify math symbol" org-cdlatex-math-modify
21753 (org-inside-LaTeX-fragment-p)]
21754 ["Insert citation" org-reftex-citation t])
21755 "--"
21756 ("MobileOrg"
21757 ["Push Files and Views" org-mobile-push t]
21758 ["Get Captured and Flagged" org-mobile-pull t]
21759 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21760 "--"
21761 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21762 "--"
21763 ("Documentation"
21764 ["Show Version" org-version t]
21765 ["Info Documentation" org-info t])
21766 ("Customize"
21767 ["Browse Org Group" org-customize t]
21768 "--"
21769 ["Expand This Menu" org-create-customize-menu
21770 (fboundp 'customize-menu-create)])
21771 ["Send bug report" org-submit-bug-report t]
21772 "--"
21773 ("Refresh/Reload"
21774 ["Refresh setup current buffer" org-mode-restart t]
21775 ["Reload Org (after update)" org-reload t]
21776 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21779 (defun org-info (&optional node)
21780 "Read documentation for Org in the info system.
21781 With optional NODE, go directly to that node."
21782 (interactive)
21783 (info (format "(org)%s" (or node ""))))
21785 ;;;###autoload
21786 (defun org-submit-bug-report ()
21787 "Submit a bug report on Org via mail.
21789 Don't hesitate to report any problems or inaccurate documentation.
21791 If you don't have setup sending mail from (X)Emacs, please copy the
21792 output buffer into your mail program, as it gives us important
21793 information about your Org version and configuration."
21794 (interactive)
21795 (require 'reporter)
21796 (defvar reporter-prompt-for-summary-p)
21797 (org-load-modules-maybe)
21798 (org-require-autoloaded-modules)
21799 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21800 (reporter-submit-bug-report
21801 "emacs-orgmode@gnu.org"
21802 (org-version nil 'full)
21803 (let (list)
21804 (save-window-excursion
21805 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21806 (delete-other-windows)
21807 (erase-buffer)
21808 (insert "You are about to submit a bug report to the Org mailing list.
21810 We would like to add your full Org and Outline configuration to the
21811 bug report. This greatly simplifies the work of the maintainer and
21812 other experts on the mailing list.
21814 HOWEVER, some variables you have customized may contain private
21815 information. The names of customers, colleagues, or friends, might
21816 appear in the form of file names, tags, todo states, or search strings.
21817 If you answer yes to the prompt, you might want to check and remove
21818 such private information before sending the email.")
21819 (add-text-properties (point-min) (point-max) '(face org-warning))
21820 (when (yes-or-no-p "Include your Org configuration ")
21821 (mapatoms
21822 (lambda (v)
21823 (and (boundp v)
21824 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21825 (or (and (symbol-value v)
21826 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21827 (and
21828 (get v 'custom-type) (get v 'standard-value)
21829 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21830 (push v list)))))
21831 (kill-buffer (get-buffer "*Warn about privacy*"))
21832 list))
21833 nil nil
21834 "Remember to cover the basics, that is, what you expected to happen and
21835 what in fact did happen. You don't know how to make a good report? See
21837 http://orgmode.org/manual/Feedback.html#Feedback
21839 Your bug report will be posted to the Org mailing list.
21840 ------------------------------------------------------------------------")
21841 (save-excursion
21842 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21843 (replace-match "\\1Bug: \\3 [\\2]")))))
21846 (defun org-install-agenda-files-menu ()
21847 (let ((bl (buffer-list)))
21848 (save-excursion
21849 (while bl
21850 (set-buffer (pop bl))
21851 (when (derived-mode-p 'org-mode) (setq bl nil)))
21852 (when (derived-mode-p 'org-mode)
21853 (easy-menu-change
21854 '("Org") "File List for Agenda"
21855 (append
21856 (list
21857 ["Edit File List" (org-edit-agenda-file-list) t]
21858 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21859 ["Remove Current File from List" org-remove-file t]
21860 ["Cycle through agenda files" org-cycle-agenda-files t]
21861 ["Occur in all agenda files" org-occur-in-agenda-files t]
21862 "--")
21863 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21865 ;;;; Documentation
21867 (defun org-require-autoloaded-modules ()
21868 (interactive)
21869 (mapc #'require
21870 '(org-agenda org-archive org-attach org-clock org-colview org-id
21871 org-table org-timer)))
21873 ;;;###autoload
21874 (defun org-reload (&optional uncompiled)
21875 "Reload all org lisp files.
21876 With prefix arg UNCOMPILED, load the uncompiled versions."
21877 (interactive "P")
21878 (require 'loadhist)
21879 (let* ((org-dir (org-find-library-dir "org"))
21880 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21881 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21882 (remove-re (format "\\`%s\\'"
21883 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21884 (feats (delete-dups
21885 (mapcar 'file-name-sans-extension
21886 (mapcar 'file-name-nondirectory
21887 (delq nil
21888 (mapcar 'feature-file
21889 features))))))
21890 (lfeat (append
21891 (sort
21892 (setq feats
21893 (delq nil (mapcar
21894 (lambda (f)
21895 (if (and (string-match feature-re f)
21896 (not (string-match remove-re f)))
21897 f nil))
21898 feats)))
21899 'string-lessp)
21900 (list "org-version" "org")))
21901 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21902 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21903 load-uncore load-misses)
21904 (setq load-misses
21905 (delq 't
21906 (mapcar (lambda (f)
21907 (or (org-load-noerror-mustsuffix (concat org-dir f))
21908 (and (string= org-dir contrib-dir)
21909 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21910 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21911 (add-to-list 'load-uncore f 'append)
21914 lfeat)))
21915 (when load-uncore
21916 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21917 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21918 (if load-misses
21919 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21920 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21921 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21923 ;;;###autoload
21924 (defun org-customize ()
21925 "Call the customize function with org as argument."
21926 (interactive)
21927 (org-load-modules-maybe)
21928 (org-require-autoloaded-modules)
21929 (customize-browse 'org))
21931 (defun org-create-customize-menu ()
21932 "Create a full customization menu for Org-mode, insert it into the menu."
21933 (interactive)
21934 (org-load-modules-maybe)
21935 (org-require-autoloaded-modules)
21936 (if (fboundp 'customize-menu-create)
21937 (progn
21938 (easy-menu-change
21939 '("Org") "Customize"
21940 `(["Browse Org group" org-customize t]
21941 "--"
21942 ,(customize-menu-create 'org)
21943 ["Set" Custom-set t]
21944 ["Save" Custom-save t]
21945 ["Reset to Current" Custom-reset-current t]
21946 ["Reset to Saved" Custom-reset-saved t]
21947 ["Reset to Standard Settings" Custom-reset-standard t]))
21948 (message "\"Org\"-menu now contains full customization menu"))
21949 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21951 ;;;; Miscellaneous stuff
21953 ;;; Generally useful functions
21955 (defun org-get-at-eol (property n)
21956 "Get text property PROPERTY at the end of line less N characters."
21957 (get-text-property (- (point-at-eol) n) property))
21959 (defun org-find-text-property-in-string (prop s)
21960 "Return the first non-nil value of property PROP in string S."
21961 (or (get-text-property 0 prop s)
21962 (get-text-property (or (next-single-property-change 0 prop s) 0)
21963 prop s)))
21965 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21966 "Display the given MESSAGE as a warning."
21967 (if (fboundp 'display-warning)
21968 (display-warning 'org message :warning)
21969 (let ((buf (get-buffer-create "*Org warnings*")))
21970 (with-current-buffer buf
21971 (goto-char (point-max))
21972 (insert "Warning (Org): " message)
21973 (unless (bolp)
21974 (newline)))
21975 (display-buffer buf)
21976 (sit-for 0))))
21978 (defun org-eval (form)
21979 "Eval FORM and return result."
21980 (condition-case error
21981 (eval form)
21982 (error (format "%%![Error: %s]" error))))
21984 (defun org-in-clocktable-p ()
21985 "Check if the cursor is in a clocktable."
21986 (let ((pos (point)) start)
21987 (save-excursion
21988 (end-of-line 1)
21989 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21990 (setq start (match-beginning 0))
21991 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21992 (>= (match-end 0) pos)
21993 start))))
21995 (defun org-in-verbatim-emphasis ()
21996 (save-match-data
21997 (and (org-in-regexp org-emph-re 2)
21998 (>= (point) (match-beginning 3))
21999 (<= (point) (match-end 4))
22000 (member (match-string 3) '("=" "~")))))
22002 (defun org-overlay-display (ovl text &optional face evap)
22003 "Make overlay OVL display TEXT with face FACE."
22004 (overlay-put ovl 'display text)
22005 (if face (overlay-put ovl 'face face))
22006 (if evap (overlay-put ovl 'evaporate t)))
22008 (defun org-overlay-before-string (ovl text &optional face evap)
22009 "Make overlay OVL display TEXT with face FACE."
22010 (if face (org-add-props text nil 'face face))
22011 (overlay-put ovl 'before-string text)
22012 (if evap (overlay-put ovl 'evaporate t)))
22014 (defun org-find-overlays (prop &optional pos delete)
22015 "Find all overlays specifying PROP at POS or point.
22016 If DELETE is non-nil, delete all those overlays."
22017 (let (found)
22018 (dolist (ov (overlays-at (or pos (point))) found)
22019 (cond ((not (overlay-get ov prop)))
22020 (delete (delete-overlay ov))
22021 (t (push ov found))))))
22023 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22024 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22025 (if (and marker (marker-buffer marker)
22026 (buffer-live-p (marker-buffer marker)))
22027 (progn
22028 (pop-to-buffer-same-window (marker-buffer marker))
22029 (when (or (> marker (point-max)) (< marker (point-min)))
22030 (widen))
22031 (goto-char marker)
22032 (org-show-context 'org-goto))
22033 (if bookmark
22034 (bookmark-jump bookmark)
22035 (error "Cannot find location"))))
22037 (defun org-quote-csv-field (s)
22038 "Quote field for inclusion in CSV material."
22039 (if (string-match "[\",]" s)
22040 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22043 (defun org-force-self-insert (N)
22044 "Needed to enforce self-insert under remapping."
22045 (interactive "p")
22046 (self-insert-command N))
22048 (defun org-string-width (s)
22049 "Compute width of string, ignoring invisible characters.
22050 This ignores character with invisibility property `org-link', and also
22051 characters with property `org-cwidth', because these will become invisible
22052 upon the next fontification round."
22053 (let (b l)
22054 (when (or (eq t buffer-invisibility-spec)
22055 (assq 'org-link buffer-invisibility-spec))
22056 (while (setq b (text-property-any 0 (length s)
22057 'invisible 'org-link s))
22058 (setq s (concat (substring s 0 b)
22059 (substring s (or (next-single-property-change
22060 b 'invisible s)
22061 (length s)))))))
22062 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22063 (setq s (concat (substring s 0 b)
22064 (substring s (or (next-single-property-change
22065 b 'org-cwidth s)
22066 (length s))))))
22067 (setq l (string-width s) b -1)
22068 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22069 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22072 (defun org-shorten-string (s maxlength)
22073 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22074 If the string is shorter or has length MAXLENGTH, just return the
22075 original string. If it is longer, the functions finds a space in the
22076 string, breaks this string off at that locations and adds three dots
22077 as ellipsis. Including the ellipsis, the string will not be longer
22078 than MAXLENGTH. If finding a good breaking point in the string does
22079 not work, the string is just chopped off in the middle of a word
22080 if necessary."
22081 (if (<= (length s) maxlength)
22083 (let* ((n (max (- maxlength 4) 1))
22084 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22085 (if (string-match re s)
22086 (concat (match-string 1 s) "...")
22087 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22089 (defun org-get-indentation (&optional line)
22090 "Get the indentation of the current line, interpreting tabs.
22091 When LINE is given, assume it represents a line and compute its indentation."
22092 (if line
22093 (when (string-match "^ *" (org-remove-tabs line))
22094 (match-end 0))
22095 (save-excursion
22096 (beginning-of-line 1)
22097 (skip-chars-forward " \t")
22098 (current-column))))
22100 (defun org-get-string-indentation (s)
22101 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22102 (let ((n -1) (i 0) (w tab-width) c)
22103 (catch 'exit
22104 (while (< (setq n (1+ n)) (length s))
22105 (setq c (aref s n))
22106 (cond ((= c ?\ ) (setq i (1+ i)))
22107 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22108 (t (throw 'exit t)))))
22111 (defun org-remove-tabs (s &optional width)
22112 "Replace tabulators in S with spaces.
22113 Assumes that s is a single line, starting in column 0."
22114 (setq width (or width tab-width))
22115 (while (string-match "\t" s)
22116 (setq s (replace-match
22117 (make-string
22118 (- (* width (/ (+ (match-beginning 0) width) width))
22119 (match-beginning 0)) ?\ )
22120 t t s)))
22123 (defun org-fix-indentation (line ind)
22124 "Fix indentation in LINE.
22125 IND is a cons cell with target and minimum indentation.
22126 If the current indentation in LINE is smaller than the minimum,
22127 leave it alone. If it is larger than ind, set it to the target."
22128 (let* ((l (org-remove-tabs line))
22129 (i (org-get-indentation l))
22130 (i1 (car ind)) (i2 (cdr ind)))
22131 (when (>= i i2) (setq l (substring line i2)))
22132 (if (> i1 0)
22133 (concat (make-string i1 ?\ ) l)
22134 l)))
22136 (defun org-remove-indentation (code &optional n)
22137 "Remove maximum common indentation in string CODE and return it.
22138 N may optionally be the number of columns to remove. Return CODE
22139 as-is if removal failed."
22140 (with-temp-buffer
22141 (insert code)
22142 (if (org-do-remove-indentation n) (buffer-string) code)))
22144 (defun org-do-remove-indentation (&optional n)
22145 "Remove the maximum common indentation from the buffer.
22146 When optional argument N is a positive integer, remove exactly
22147 that much characters from indentation, if possible. Return nil
22148 if it fails."
22149 (catch :exit
22150 (goto-char (point-min))
22151 ;; Find maximum common indentation, if not specified.
22152 (let ((n (or n
22153 (let ((min-ind (point-max)))
22154 (save-excursion
22155 (while (re-search-forward "^[ \t]*\\S-" nil t)
22156 (let ((ind (1- (current-column))))
22157 (if (zerop ind) (throw :exit nil)
22158 (setq min-ind (min min-ind ind))))))
22159 min-ind))))
22160 (if (zerop n) (throw :exit nil)
22161 ;; Remove exactly N indentation, but give up if not possible.
22162 (while (not (eobp))
22163 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22164 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22165 ((< ind n) (throw :exit nil))
22166 (t (indent-line-to (- ind n))))
22167 (forward-line)))
22168 ;; Signal success.
22169 t))))
22171 (defun org-fill-template (template alist)
22172 "Find each %key of ALIST in TEMPLATE and replace it."
22173 (let ((case-fold-search nil))
22174 (dolist (entry (sort (copy-sequence alist)
22175 (lambda (a b) (< (length (car a)) (length (car b))))))
22176 (setq template
22177 (replace-regexp-in-string
22178 (concat "%" (regexp-quote (car entry)))
22179 (or (cdr entry) "") template t t)))
22180 template))
22182 (defun org-base-buffer (buffer)
22183 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22184 (if (not buffer)
22185 buffer
22186 (or (buffer-base-buffer buffer)
22187 buffer)))
22189 (defun org-wrap (string &optional width lines)
22190 "Wrap string to either a number of lines, or a width in characters.
22191 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22192 that costs. If there is a word longer than WIDTH, the text is actually
22193 wrapped to the length of that word.
22194 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22195 many lines, whatever width that takes.
22196 The return value is a list of lines, without newlines at the end."
22197 (let* ((words (org-split-string string "[ \t\n]+"))
22198 (maxword (apply 'max (mapcar 'org-string-width words)))
22199 w ll)
22200 (cond (width
22201 (org-do-wrap words (max maxword width)))
22202 (lines
22203 (setq w maxword)
22204 (setq ll (org-do-wrap words maxword))
22205 (if (<= (length ll) lines)
22207 (setq ll words)
22208 (while (> (length ll) lines)
22209 (setq w (1+ w))
22210 (setq ll (org-do-wrap words w)))
22211 ll))
22212 (t (error "Cannot wrap this")))))
22214 (defun org-do-wrap (words width)
22215 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22216 (let (lines line)
22217 (while words
22218 (setq line (pop words))
22219 (while (and words (< (+ (length line) (length (car words))) width))
22220 (setq line (concat line " " (pop words))))
22221 (setq lines (push line lines)))
22222 (nreverse lines)))
22224 (defun org-split-string (string &optional separators)
22225 "Splits STRING into substrings at SEPARATORS.
22226 SEPARATORS is a regular expression.
22227 No empty strings are returned if there are matches at the beginning
22228 and end of string."
22229 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22230 (let ((start 0) notfirst list)
22231 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22232 (if (and notfirst
22233 (= start (match-beginning 0))
22234 (< start (length string)))
22235 (1+ start) start))
22236 (< (match-beginning 0) (length string)))
22237 (setq notfirst t)
22238 (or (eq (match-beginning 0) 0)
22239 (and (eq (match-beginning 0) (match-end 0))
22240 (eq (match-beginning 0) start))
22241 (push (substring string start (match-beginning 0)) list))
22242 (setq start (match-end 0)))
22243 (or (eq start (length string))
22244 (push (substring string start) list))
22245 (nreverse list)))
22247 (defun org-quote-vert (s)
22248 "Replace \"|\" with \"\\vert\"."
22249 (while (string-match "|" s)
22250 (setq s (replace-match "\\vert" t t s)))
22253 (defun org-uuidgen-p (s)
22254 "Is S an ID created by UUIDGEN?"
22255 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22257 (defun org-in-src-block-p (&optional inside)
22258 "Whether point is in a code source block.
22259 When INSIDE is non-nil, don't consider we are within a src block
22260 when point is at #+BEGIN_SRC or #+END_SRC."
22261 (let ((case-fold-search t))
22262 (or (and (eq (get-char-property (point) 'src-block) t))
22263 (and (not inside)
22264 (save-match-data
22265 (save-excursion
22266 (beginning-of-line)
22267 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22269 (defun org-context ()
22270 "Return a list of contexts of the current cursor position.
22271 If several contexts apply, all are returned.
22272 Each context entry is a list with a symbol naming the context, and
22273 two positions indicating start and end of the context. Possible
22274 contexts are:
22276 :headline anywhere in a headline
22277 :headline-stars on the leading stars in a headline
22278 :todo-keyword on a TODO keyword (including DONE) in a headline
22279 :tags on the TAGS in a headline
22280 :priority on the priority cookie in a headline
22281 :item on the first line of a plain list item
22282 :item-bullet on the bullet/number of a plain list item
22283 :checkbox on the checkbox in a plain list item
22284 :table in an Org table
22285 :table-special on a special filed in a table
22286 :table-table in a table.el table
22287 :clocktable in a clocktable
22288 :src-block in a source block
22289 :link on a hyperlink
22290 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22291 :target on a <<target>>
22292 :radio-target on a <<<radio-target>>>
22293 :latex-fragment on a LaTeX fragment
22294 :latex-preview on a LaTeX fragment with overlaid preview image
22296 This function expects the position to be visible because it uses font-lock
22297 faces as a help to recognize the following contexts: :table-special, :link,
22298 and :keyword."
22299 (let* ((f (get-text-property (point) 'face))
22300 (faces (if (listp f) f (list f)))
22301 (case-fold-search t)
22302 (p (point)) clist o)
22303 ;; First the large context
22304 (cond
22305 ((org-at-heading-p t)
22306 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22307 (when (progn
22308 (beginning-of-line 1)
22309 (looking-at org-todo-line-tags-regexp))
22310 (push (org-point-in-group p 1 :headline-stars) clist)
22311 (push (org-point-in-group p 2 :todo-keyword) clist)
22312 (push (org-point-in-group p 4 :tags) clist))
22313 (goto-char p)
22314 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22315 (when (looking-at "\\[#[A-Z0-9]\\]")
22316 (push (org-point-in-group p 0 :priority) clist)))
22318 ((org-at-item-p)
22319 (push (org-point-in-group p 2 :item-bullet) clist)
22320 (push (list :item (point-at-bol)
22321 (save-excursion (org-end-of-item) (point)))
22322 clist)
22323 (and (org-at-item-checkbox-p)
22324 (push (org-point-in-group p 0 :checkbox) clist)))
22326 ((org-at-table-p)
22327 (push (list :table (org-table-begin) (org-table-end)) clist)
22328 (when (memq 'org-formula faces)
22329 (push (list :table-special
22330 (previous-single-property-change p 'face)
22331 (next-single-property-change p 'face)) clist)))
22332 ((org-at-table-p 'any)
22333 (push (list :table-table) clist)))
22334 (goto-char p)
22336 (let ((case-fold-search t))
22337 ;; New the "medium" contexts: clocktables, source blocks
22338 (cond ((org-in-clocktable-p)
22339 (push (list :clocktable
22340 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22341 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22342 (match-beginning 1))
22343 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22344 (match-end 0))) clist))
22345 ((org-in-src-block-p)
22346 (push (list :src-block
22347 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22348 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22349 (match-beginning 1))
22350 (and (search-forward "#+END_SRC" nil t)
22351 (match-beginning 0))) clist))))
22352 (goto-char p)
22354 ;; Now the small context
22355 (cond
22356 ((org-at-timestamp-p)
22357 (push (org-point-in-group p 0 :timestamp) clist))
22358 ((memq 'org-link faces)
22359 (push (list :link
22360 (previous-single-property-change p 'face)
22361 (next-single-property-change p 'face)) clist))
22362 ((memq 'org-special-keyword faces)
22363 (push (list :keyword
22364 (previous-single-property-change p 'face)
22365 (next-single-property-change p 'face)) clist))
22366 ((org-at-target-p)
22367 (push (org-point-in-group p 0 :target) clist)
22368 (goto-char (1- (match-beginning 0)))
22369 (when (looking-at org-radio-target-regexp)
22370 (push (org-point-in-group p 0 :radio-target) clist))
22371 (goto-char p))
22372 ((setq o (cl-some
22373 (lambda (o)
22374 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22376 (overlays-at (point))))
22377 (push (list :latex-fragment
22378 (overlay-start o) (overlay-end o)) clist)
22379 (push (list :latex-preview
22380 (overlay-start o) (overlay-end o)) clist))
22381 ((org-inside-LaTeX-fragment-p)
22382 ;; FIXME: positions wrong.
22383 (push (list :latex-fragment (point) (point)) clist)))
22385 (setq clist (nreverse (delq nil clist)))
22386 clist))
22388 (defun org-in-regexp (regexp &optional nlines visually)
22389 "Check if point is inside a match of REGEXP.
22391 Normally only the current line is checked, but you can include
22392 NLINES extra lines around point into the search. If VISUALLY is
22393 set, require that the cursor is not after the match but really
22394 on, so that the block visually is on the match.
22396 Return nil or a cons cell (BEG . END) where BEG and END are,
22397 respectively, the positions at the beginning and the end of the
22398 match."
22399 (catch :exit
22400 (let ((pos (point))
22401 (eol (line-end-position (if nlines (1+ nlines) 1))))
22402 (save-excursion
22403 (beginning-of-line (- 1 (or nlines 0)))
22404 (while (and (re-search-forward regexp eol t)
22405 (<= (match-beginning 0) pos))
22406 (let ((end (match-end 0)))
22407 (when (or (> end pos) (and (= end pos) (not visually)))
22408 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22410 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22411 "Non-nil when point is between matches of START-RE and END-RE.
22413 Also return a non-nil value when point is on one of the matches.
22415 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22416 buffer positions. Default values are the positions of headlines
22417 surrounding the point.
22419 The functions returns a cons cell whose car (resp. cdr) is the
22420 position before START-RE (resp. after END-RE)."
22421 (save-match-data
22422 (let ((pos (point))
22423 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22424 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22425 beg end)
22426 (save-excursion
22427 ;; Point is on a block when on START-RE or if START-RE can be
22428 ;; found before it...
22429 (and (or (org-in-regexp start-re)
22430 (re-search-backward start-re limit-up t))
22431 (setq beg (match-beginning 0))
22432 ;; ... and END-RE after it...
22433 (goto-char (match-end 0))
22434 (re-search-forward end-re limit-down t)
22435 (> (setq end (match-end 0)) pos)
22436 ;; ... without another START-RE in-between.
22437 (goto-char (match-beginning 0))
22438 (not (re-search-backward start-re (1+ beg) t))
22439 ;; Return value.
22440 (cons beg end))))))
22442 (defun org-in-block-p (names)
22443 "Non-nil when point belongs to a block whose name belongs to NAMES.
22445 NAMES is a list of strings containing names of blocks.
22447 Return first block name matched, or nil. Beware that in case of
22448 nested blocks, the returned name may not belong to the closest
22449 block from point."
22450 (save-match-data
22451 (catch 'exit
22452 (let ((case-fold-search t)
22453 (lim-up (save-excursion (outline-previous-heading)))
22454 (lim-down (save-excursion (outline-next-heading))))
22455 (dolist (name names)
22456 (let ((n (regexp-quote name)))
22457 (when (org-between-regexps-p
22458 (concat "^[ \t]*#\\+begin_" n)
22459 (concat "^[ \t]*#\\+end_" n)
22460 lim-up lim-down)
22461 (throw 'exit n)))))
22462 nil)))
22464 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22465 "Call `multi-occur' with buffers for all agenda files."
22466 (interactive "sOrg-files matching: ")
22467 (let* ((files (org-agenda-files))
22468 (tnames (mapcar #'file-truename files))
22469 (extra org-agenda-text-search-extra-files))
22470 (when (eq (car extra) 'agenda-archives)
22471 (setq extra (cdr extra))
22472 (setq files (org-add-archive-files files)))
22473 (dolist (f extra)
22474 (unless (member (file-truename f) tnames)
22475 (unless (member f files) (setq files (append files (list f))))
22476 (setq tnames (append tnames (list (file-truename f))))))
22477 (multi-occur
22478 (mapcar (lambda (x)
22479 (with-current-buffer
22480 ;; FIXME: Why not just (find-file-noselect x)?
22481 ;; Is it to avoid the "revert buffer" prompt?
22482 (or (get-file-buffer x) (find-file-noselect x))
22483 (widen)
22484 (current-buffer)))
22485 files)
22486 regexp)))
22488 (add-hook 'occur-mode-find-occurrence-hook
22489 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22491 (defun org-occur-link-in-agenda-files ()
22492 "Create a link and search for it in the agendas.
22493 The link is not stored in `org-stored-links', it is just created
22494 for the search purpose."
22495 (interactive)
22496 (let ((link (condition-case nil
22497 (org-store-link nil)
22498 (error "Unable to create a link to here"))))
22499 (org-occur-in-agenda-files (regexp-quote link))))
22501 (defun org-reverse-string (string)
22502 "Return the reverse of STRING."
22503 (apply 'string (reverse (string-to-list string))))
22505 ;; defsubst org-uniquify must be defined before first use
22507 (defun org-uniquify-alist (alist)
22508 "Merge elements of ALIST with the same key.
22510 For example, in this alist:
22512 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22513 => \\='((a 1 3) (b 2))
22515 merge (a 1) and (a 3) into (a 1 3).
22517 The function returns the new ALIST."
22518 (let (rtn)
22519 (dolist (e alist rtn)
22520 (let (n)
22521 (if (not (assoc (car e) rtn))
22522 (push e rtn)
22523 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22524 (setq rtn (assq-delete-all (car e) rtn))
22525 (push n rtn))))))
22527 (defun org-delete-all (elts list)
22528 "Remove all elements in ELTS from LIST.
22529 Comparison is done with `equal'. It is a destructive operation
22530 that may remove elements by altering the list structure."
22531 (while elts
22532 (setq list (delete (pop elts) list)))
22533 list)
22535 (defun org-back-over-empty-lines ()
22536 "Move backwards over whitespace, to the beginning of the first empty line.
22537 Returns the number of empty lines passed."
22538 (let ((pos (point)))
22539 (if (cdr (assq 'heading org-blank-before-new-entry))
22540 (skip-chars-backward " \t\n\r")
22541 (unless (eobp)
22542 (forward-line -1)))
22543 (beginning-of-line 2)
22544 (goto-char (min (point) pos))
22545 (count-lines (point) pos)))
22547 (defun org-skip-whitespace ()
22548 (skip-chars-forward " \t\n\r"))
22550 (defun org-point-in-group (point group &optional context)
22551 "Check if POINT is in match-group GROUP.
22552 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22553 match. If the match group does not exist or point is not inside it,
22554 return nil."
22555 (and (match-beginning group)
22556 (>= point (match-beginning group))
22557 (<= point (match-end group))
22558 (if context
22559 (list context (match-beginning group) (match-end group))
22560 t)))
22562 (defun org-switch-to-buffer-other-window (&rest args)
22563 "Switch to buffer in a second window on the current frame.
22564 In particular, do not allow pop-up frames.
22565 Returns the newly created buffer."
22566 (org-no-popups
22567 (apply 'switch-to-buffer-other-window args)))
22569 (defun org-combine-plists (&rest plists)
22570 "Create a single property list from all plists in PLISTS.
22571 The process starts by copying the first list, and then setting properties
22572 from the other lists. Settings in the last list are the most significant
22573 ones and overrule settings in the other lists."
22574 (let ((rtn (copy-sequence (pop plists)))
22575 p v ls)
22576 (while plists
22577 (setq ls (pop plists))
22578 (while ls
22579 (setq p (pop ls) v (pop ls))
22580 (setq rtn (plist-put rtn p v))))
22581 rtn))
22583 (defun org-replace-escapes (string table)
22584 "Replace %-escapes in STRING with values in TABLE.
22585 TABLE is an association list with keys like \"%a\" and string values.
22586 The sequences in STRING may contain normal field width and padding information,
22587 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22588 so values can contain further %-escapes if they are define later in TABLE."
22589 (let ((tbl (copy-alist table))
22590 (case-fold-search nil)
22591 (pchg 0)
22592 re rpl)
22593 (dolist (e tbl)
22594 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22595 (when (and (cdr e) (string-match re (cdr e)))
22596 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22597 (safe "SREF"))
22598 (add-text-properties 0 3 (list 'sref sref) safe)
22599 (setcdr e (replace-match safe t t (cdr e)))))
22600 (while (string-match re string)
22601 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22602 (cdr e)))
22603 (setq string (replace-match rpl t t string))))
22604 (while (setq pchg (next-property-change pchg string))
22605 (let ((sref (get-text-property pchg 'sref string)))
22606 (when (and sref (string-match "SREF" string pchg))
22607 (setq string (replace-match sref t t string)))))
22608 string))
22610 (defun org-find-base-buffer-visiting (file)
22611 "Like `find-buffer-visiting' but always return the base buffer and
22612 not an indirect buffer."
22613 (let ((buf (or (get-file-buffer file)
22614 (find-buffer-visiting file))))
22615 (if buf
22616 (or (buffer-base-buffer buf) buf)
22617 nil)))
22619 ;;; TODO: Only called once, from ox-odt which should probably use
22620 ;;; org-export-inline-image-p or something.
22621 (defun org-file-image-p (file)
22622 "Return non-nil if FILE is an image."
22623 (save-match-data
22624 (string-match (image-file-name-regexp) file)))
22626 (defun org-get-cursor-date (&optional with-time)
22627 "Return the date at cursor in as a time.
22628 This works in the calendar and in the agenda, anywhere else it just
22629 returns the current time.
22630 If WITH-TIME is non-nil, returns the time of the event at point (in
22631 the agenda) or the current time of the day."
22632 (let (date day defd tp hod mod)
22633 (when with-time
22634 (setq tp (get-text-property (point) 'time))
22635 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22636 (setq hod (string-to-number (match-string 1 tp))
22637 mod (string-to-number (match-string 2 tp))))
22638 (or tp (let ((now (decode-time)))
22639 (setq hod (nth 2 now)
22640 mod (nth 1 now)))))
22641 (cond
22642 ((eq major-mode 'calendar-mode)
22643 (setq date (calendar-cursor-to-date)
22644 defd (encode-time 0 (or mod 0) (or hod 0)
22645 (nth 1 date) (nth 0 date) (nth 2 date))))
22646 ((eq major-mode 'org-agenda-mode)
22647 (setq day (get-text-property (point) 'day))
22648 (when day
22649 (setq date (calendar-gregorian-from-absolute day)
22650 defd (encode-time 0 (or mod 0) (or hod 0)
22651 (nth 1 date) (nth 0 date) (nth 2 date))))))
22652 (or defd (current-time))))
22654 (defun org-mark-subtree (&optional up)
22655 "Mark the current subtree.
22656 This puts point at the start of the current subtree, and mark at
22657 the end. If a numeric prefix UP is given, move up into the
22658 hierarchy of headlines by UP levels before marking the subtree."
22659 (interactive "P")
22660 (org-with-limited-levels
22661 (cond ((org-at-heading-p) (beginning-of-line))
22662 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22663 (t (outline-previous-visible-heading 1))))
22664 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22665 (if (called-interactively-p 'any)
22666 (call-interactively 'org-mark-element)
22667 (org-mark-element)))
22669 (defun org-file-newer-than-p (file time)
22670 "Non-nil if FILE is newer than TIME.
22671 FILE is a filename, as a string, TIME is a list of integers, as
22672 returned by, e.g., `current-time'."
22673 (and (file-exists-p file)
22674 ;; Only compare times up to whole seconds as some file-systems
22675 ;; (e.g. HFS+) do not retain any finer granularity. As
22676 ;; a consequence, make sure we return non-nil when the two
22677 ;; times are equal.
22678 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22679 (cl-subseq time 0 2)))))
22681 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22682 "Compile a SOURCE file using PROCESS.
22684 PROCESS is either a function or a list of shell commands, as
22685 strings. EXT is a file extension, without the leading dot, as
22686 a string. It is used to check if the process actually succeeded.
22688 PROCESS must create a file with the same base name and directory
22689 as SOURCE, but ending with EXT. The function then returns its
22690 filename. Otherwise, it raises an error. The error message can
22691 then be refined by providing string ERR-MSG, which is appended to
22692 the standard message.
22694 If PROCESS is a function, it is called with a single argument:
22695 the SOURCE file.
22697 If it is a list of commands, each of them is called using
22698 `shell-command'. By default, in each command, %b, %f, %F and %o
22699 are replaced with, respectively, SOURCE base name, name, full
22700 name and directory. It is possible, however, to use more
22701 place-holders by specifying them in optional argument SPEC, as an
22702 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22704 When PROCESS is a list of commands, optional argument LOG-BUF can
22705 be set to a buffer or a buffer name. `shell-command' then uses
22706 it for output.
22708 `default-directory' is set to SOURCE directory during the whole
22709 process."
22710 (let* ((source-name (file-name-nondirectory source))
22711 (base-name (file-name-sans-extension source-name))
22712 (full-name (file-truename source))
22713 (out-dir (file-name-directory source))
22714 (time (current-time))
22715 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22716 (save-window-excursion
22717 (let ((default-directory (file-name-directory full-name)))
22718 (pcase process
22719 ((pred functionp) (funcall process (shell-quote-argument source)))
22720 ((pred consp)
22721 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22722 (spec (append spec
22723 `((?b . ,(shell-quote-argument base-name))
22724 (?f . ,(shell-quote-argument source-name))
22725 (?F . ,(shell-quote-argument full-name))
22726 (?o . ,(shell-quote-argument out-dir))))))
22727 (dolist (command process)
22728 (shell-command (format-spec command spec) log-buf))))
22729 (_ (error "No valid command to process %S%s" source err-msg)))))
22730 ;; Check for process failure.
22731 (let ((output (concat out-dir base-name "." ext)))
22732 (unless (org-file-newer-than-p output time)
22733 (error (format "File %S wasn't produced%s" output err-msg)))
22734 output)))
22736 ;;; Indentation
22738 (defun org--get-expected-indentation (element contentsp)
22739 "Expected indentation column for current line, according to ELEMENT.
22740 ELEMENT is an element containing point. CONTENTSP is non-nil
22741 when indentation is to be computed according to contents of
22742 ELEMENT."
22743 (let ((type (org-element-type element))
22744 (start (org-element-property :begin element))
22745 (post-affiliated (org-element-property :post-affiliated element)))
22746 (org-with-wide-buffer
22747 (cond
22748 (contentsp
22749 (cl-case type
22750 ((diary-sexp footnote-definition) 0)
22751 ((headline inlinetask nil)
22752 (if (not org-adapt-indentation) 0
22753 (let ((level (org-current-level)))
22754 (if level (1+ level) 0))))
22755 ((item plain-list) (org-list-item-body-column post-affiliated))
22757 (goto-char start)
22758 (org-get-indentation))))
22759 ((memq type '(headline inlinetask nil))
22760 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22761 (org--get-expected-indentation element t)
22763 ((memq type '(diary-sexp footnote-definition)) 0)
22764 ;; First paragraph of a footnote definition or an item.
22765 ;; Indent like parent.
22766 ((< (line-beginning-position) start)
22767 (org--get-expected-indentation
22768 (org-element-property :parent element) t))
22769 ;; At first line: indent according to previous sibling, if any,
22770 ;; ignoring footnote definitions and inline tasks, or parent's
22771 ;; contents.
22772 ((= (line-beginning-position) start)
22773 (catch 'exit
22774 (while t
22775 (if (= (point-min) start) (throw 'exit 0)
22776 (goto-char (1- start))
22777 (let* ((previous (org-element-at-point))
22778 (parent previous))
22779 (while (and parent (<= (org-element-property :end parent) start))
22780 (setq previous parent
22781 parent (org-element-property :parent parent)))
22782 (cond
22783 ((not previous) (throw 'exit 0))
22784 ((> (org-element-property :end previous) start)
22785 (throw 'exit (org--get-expected-indentation previous t)))
22786 ((memq (org-element-type previous)
22787 '(footnote-definition inlinetask))
22788 (setq start (org-element-property :begin previous)))
22789 (t (goto-char (org-element-property :begin previous))
22790 (throw 'exit
22791 (if (bolp) (org-get-indentation)
22792 ;; At first paragraph in an item or
22793 ;; a footnote definition.
22794 (org--get-expected-indentation
22795 (org-element-property :parent previous) t))))))))))
22796 ;; Otherwise, move to the first non-blank line above.
22798 (beginning-of-line)
22799 (let ((pos (point)))
22800 (skip-chars-backward " \r\t\n")
22801 (cond
22802 ;; Two blank lines end a footnote definition or a plain
22803 ;; list. When we indent an empty line after them, the
22804 ;; containing list or footnote definition is over, so it
22805 ;; qualifies as a previous sibling. Therefore, we indent
22806 ;; like its first line.
22807 ((and (memq type '(footnote-definition plain-list))
22808 (> (count-lines (point) pos) 2))
22809 (goto-char start)
22810 (org-get-indentation))
22811 ;; Line above is the first one of a paragraph at the
22812 ;; beginning of an item or a footnote definition. Indent
22813 ;; like parent.
22814 ((< (line-beginning-position) start)
22815 (org--get-expected-indentation
22816 (org-element-property :parent element) t))
22817 ;; Line above is the beginning of an element, i.e., point
22818 ;; was originally on the blank lines between element's start
22819 ;; and contents.
22820 ((= (line-beginning-position) post-affiliated)
22821 (org--get-expected-indentation element t))
22822 ;; POS is after contents in a greater element. Indent like
22823 ;; the beginning of the element.
22825 ;; As a special case, if point is at the end of a footnote
22826 ;; definition or an item, indent like the very last element
22827 ;; within. If that last element is an item, indent like its
22828 ;; contents.
22829 ((and (not (eq type 'paragraph))
22830 (let ((cend (org-element-property :contents-end element)))
22831 (and cend (<= cend pos))))
22832 (if (memq type '(footnote-definition item plain-list))
22833 (let ((last (org-element-at-point)))
22834 (org--get-expected-indentation
22835 last (eq (org-element-type last) 'item)))
22836 (goto-char start)
22837 (org-get-indentation)))
22838 ;; In any other case, indent like the current line.
22839 (t (org-get-indentation)))))))))
22841 (defun org--align-node-property ()
22842 "Align node property at point.
22843 Alignment is done according to `org-property-format', which see."
22844 (when (save-excursion
22845 (beginning-of-line)
22846 (looking-at org-property-re))
22847 (replace-match
22848 (concat (match-string 4)
22849 (org-trim
22850 (format org-property-format (match-string 1) (match-string 3))))
22851 t t)))
22853 (defun org-indent-line ()
22854 "Indent line depending on context.
22856 Indentation is done according to the following rules:
22858 - Footnote definitions, diary sexps, headlines and inline tasks
22859 have to start at column 0.
22861 - On the very first line of an element, consider, in order, the
22862 next rules until one matches:
22864 1. If there's a sibling element before, ignoring footnote
22865 definitions and inline tasks, indent like its first line.
22867 2. If element has a parent, indent like its contents. More
22868 precisely, if parent is an item, indent after the
22869 description part, if any, or the bullet (see
22870 `org-list-description-max-indent'). Else, indent like
22871 parent's first line.
22873 3. Otherwise, indent relatively to current level, if
22874 `org-adapt-indentation' is non-nil, or to left margin.
22876 - On a blank line at the end of an element, indent according to
22877 the type of the element. More precisely
22879 1. If element is a plain list, an item, or a footnote
22880 definition, indent like the very last element within.
22882 2. If element is a paragraph, indent like its last non blank
22883 line.
22885 3. Otherwise, indent like its very first line.
22887 - In the code part of a source block, use language major mode
22888 to indent current line if `org-src-tab-acts-natively' is
22889 non-nil. If it is nil, do nothing.
22891 - Otherwise, indent like the first non-blank line above.
22893 The function doesn't indent an item as it could break the whole
22894 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22895 \\[org-shiftmetaright].
22897 Also align node properties according to `org-property-format'."
22898 (interactive)
22899 (cond
22900 (orgstruct-is-++
22901 (let ((indent-line-function
22902 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22903 (indent-according-to-mode)))
22904 ((org-at-heading-p) 'noindent)
22906 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22907 (type (org-element-type element)))
22908 (cond ((and (memq type '(plain-list item))
22909 (= (line-beginning-position)
22910 (org-element-property :post-affiliated element)))
22911 'noindent)
22912 ((and (eq type 'src-block)
22913 org-src-tab-acts-natively
22914 (> (line-beginning-position)
22915 (org-element-property :post-affiliated element))
22916 (< (line-beginning-position)
22917 (org-with-wide-buffer
22918 (goto-char (org-element-property :end element))
22919 (skip-chars-backward " \r\t\n")
22920 (line-beginning-position))))
22921 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22923 (let ((column (org--get-expected-indentation element nil)))
22924 ;; Preserve current column.
22925 (if (<= (current-column) (current-indentation))
22926 (indent-line-to column)
22927 (save-excursion (indent-line-to column))))
22928 ;; Align node property. Also preserve current column.
22929 (when (eq type 'node-property)
22930 (let ((column (current-column)))
22931 (org--align-node-property)
22932 (org-move-to-column column)))))))))
22934 (defun org-indent-region (start end)
22935 "Indent each non-blank line in the region.
22936 Called from a program, START and END specify the region to
22937 indent. The function will not indent contents of example blocks,
22938 verse blocks and export blocks as leading white spaces are
22939 assumed to be significant there."
22940 (interactive "r")
22941 (save-excursion
22942 (goto-char start)
22943 (skip-chars-forward " \r\t\n")
22944 (unless (eobp) (beginning-of-line))
22945 (let ((indent-to
22946 (lambda (ind pos)
22947 ;; Set IND as indentation for all lines between point and
22948 ;; POS. Blank lines are ignored. Leave point after POS
22949 ;; once done.
22950 (let ((limit (copy-marker pos)))
22951 (while (< (point) limit)
22952 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22953 (forward-line))
22954 (set-marker limit nil))))
22955 (end (copy-marker end)))
22956 (while (< (point) end)
22957 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22958 (let* ((element (org-element-at-point))
22959 (type (org-element-type element))
22960 (element-end (copy-marker (org-element-property :end element)))
22961 (ind (org--get-expected-indentation element nil)))
22962 (cond
22963 ((or (memq type '(paragraph table table-row))
22964 (not (or (org-element-property :contents-begin element)
22965 (memq type
22966 '(example-block export-block src-block)))))
22967 ;; Elements here are indented as a single block. Also
22968 ;; align node properties.
22969 (when (eq type 'node-property)
22970 (org--align-node-property)
22971 (beginning-of-line))
22972 (funcall indent-to ind (min element-end end)))
22974 ;; Elements in this category consist of three parts:
22975 ;; before the contents, the contents, and after the
22976 ;; contents. The contents are treated specially,
22977 ;; according to the element type, or not indented at
22978 ;; all. Other parts are indented as a single block.
22979 (let* ((post (copy-marker
22980 (org-element-property :post-affiliated element)))
22981 (cbeg
22982 (copy-marker
22983 (cond
22984 ((not (org-element-property :contents-begin element))
22985 ;; Fake contents for source blocks.
22986 (org-with-wide-buffer
22987 (goto-char post)
22988 (forward-line)
22989 (point)))
22990 ((memq type '(footnote-definition item plain-list))
22991 ;; Contents in these elements could start on
22992 ;; the same line as the beginning of the
22993 ;; element. Make sure we start indenting
22994 ;; from the second line.
22995 (org-with-wide-buffer
22996 (goto-char post)
22997 (end-of-line)
22998 (skip-chars-forward " \r\t\n")
22999 (if (eobp) (point) (line-beginning-position))))
23000 (t (org-element-property :contents-begin element)))))
23001 (cend (copy-marker
23002 (or (org-element-property :contents-end element)
23003 ;; Fake contents for source blocks.
23004 (org-with-wide-buffer
23005 (goto-char element-end)
23006 (skip-chars-backward " \r\t\n")
23007 (line-beginning-position)))
23008 t)))
23009 ;; Do not change items indentation individually as it
23010 ;; might break the list as a whole. On the other
23011 ;; hand, when at a plain list, indent it as a whole.
23012 (cond ((eq type 'plain-list)
23013 (let ((offset (- ind (org-get-indentation))))
23014 (unless (zerop offset)
23015 (indent-rigidly (org-element-property :begin element)
23016 (org-element-property :end element)
23017 offset))
23018 (goto-char cbeg)))
23019 ((eq type 'item) (goto-char cbeg))
23020 (t (funcall indent-to ind (min cbeg end))))
23021 (when (< (point) end)
23022 (cl-case type
23023 ((example-block export-block verse-block))
23024 (src-block
23025 ;; In a source block, indent source code
23026 ;; according to language major mode, but only if
23027 ;; `org-src-tab-acts-natively' is non-nil.
23028 (when (and (< (point) end) org-src-tab-acts-natively)
23029 (ignore-errors
23030 (org-babel-do-in-edit-buffer
23031 (indent-region (point-min) (point-max))))))
23032 (t (org-indent-region (point) (min cend end))))
23033 (goto-char (min cend end))
23034 (when (< (point) end)
23035 (funcall indent-to ind (min element-end end))))
23036 (set-marker post nil)
23037 (set-marker cbeg nil)
23038 (set-marker cend nil))))
23039 (set-marker element-end nil))))
23040 (set-marker end nil))))
23042 (defun org-indent-drawer ()
23043 "Indent the drawer at point."
23044 (interactive)
23045 (unless (save-excursion
23046 (beginning-of-line)
23047 (looking-at-p org-drawer-regexp))
23048 (user-error "Not at a drawer"))
23049 (let ((element (org-element-at-point)))
23050 (unless (memq (org-element-type element) '(drawer property-drawer))
23051 (user-error "Not at a drawer"))
23052 (org-with-wide-buffer
23053 (org-indent-region (org-element-property :begin element)
23054 (org-element-property :end element))))
23055 (message "Drawer at point indented"))
23057 (defun org-indent-block ()
23058 "Indent the block at point."
23059 (interactive)
23060 (unless (save-excursion
23061 (beginning-of-line)
23062 (let ((case-fold-search t))
23063 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23064 (user-error "Not at a block"))
23065 (let ((element (org-element-at-point)))
23066 (unless (memq (org-element-type element)
23067 '(comment-block center-block dynamic-block example-block
23068 export-block quote-block special-block
23069 src-block verse-block))
23070 (user-error "Not at a block"))
23071 (org-with-wide-buffer
23072 (org-indent-region (org-element-property :begin element)
23073 (org-element-property :end element))))
23074 (message "Block at point indented"))
23077 ;;; Filling
23079 ;; We use our own fill-paragraph and auto-fill functions.
23081 ;; `org-fill-paragraph' relies on adaptive filling and context
23082 ;; checking. Appropriate `fill-prefix' is computed with
23083 ;; `org-adaptive-fill-function'.
23085 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23086 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23087 ;; `org-adaptive-fill-function' value. Internally,
23088 ;; `org-comment-line-break-function' breaks the line.
23090 ;; `org-setup-filling' installs filling and auto-filling related
23091 ;; variables during `org-mode' initialization.
23093 (defvar org-element-paragraph-separate) ; org-element.el
23094 (defun org-setup-filling ()
23095 (require 'org-element)
23096 ;; Prevent auto-fill from inserting unwanted new items.
23097 (when (boundp 'fill-nobreak-predicate)
23098 (setq-local
23099 fill-nobreak-predicate
23100 (org-uniquify
23101 (append fill-nobreak-predicate
23102 '(org-fill-line-break-nobreak-p
23103 org-fill-paragraph-with-timestamp-nobreak-p)))))
23104 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23105 (setq-local paragraph-start paragraph-ending)
23106 (setq-local paragraph-separate paragraph-ending))
23107 (setq-local fill-paragraph-function 'org-fill-paragraph)
23108 (setq-local auto-fill-inhibit-regexp nil)
23109 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23110 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23111 (setq-local comment-line-break-function 'org-comment-line-break-function))
23113 (defun org-fill-line-break-nobreak-p ()
23114 "Non-nil when a new line at point would create an Org line break."
23115 (save-excursion
23116 (skip-chars-backward "[ \t]")
23117 (skip-chars-backward "\\\\")
23118 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23120 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23121 "Non-nil when a new line at point would split a timestamp."
23122 (and (org-at-timestamp-p t)
23123 (not (looking-at org-ts-regexp-both))))
23125 (declare-function message-in-body-p "message" ())
23126 (defvar orgtbl-line-start-regexp) ; From org-table.el
23127 (defun org-adaptive-fill-function ()
23128 "Compute a fill prefix for the current line.
23129 Return fill prefix, as a string, or nil if current line isn't
23130 meant to be filled. For convenience, if `adaptive-fill-regexp'
23131 matches in paragraphs or comments, use it."
23132 (catch 'exit
23133 (when (derived-mode-p 'message-mode)
23134 (save-excursion
23135 (beginning-of-line)
23136 (cond ((not (message-in-body-p)) (throw 'exit nil))
23137 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23138 ((looking-at message-cite-prefix-regexp)
23139 (throw 'exit (match-string-no-properties 0)))
23140 ((looking-at org-outline-regexp)
23141 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23142 (org-with-wide-buffer
23143 (unless (org-at-heading-p)
23144 (let* ((p (line-beginning-position))
23145 (element (save-excursion
23146 (beginning-of-line)
23147 (org-element-at-point)))
23148 (type (org-element-type element))
23149 (post-affiliated (org-element-property :post-affiliated element)))
23150 (unless (< p post-affiliated)
23151 (cl-case type
23152 (comment
23153 (save-excursion
23154 (beginning-of-line)
23155 (looking-at "[ \t]*")
23156 (concat (match-string 0) "# ")))
23157 (footnote-definition "")
23158 ((item plain-list)
23159 (make-string (org-list-item-body-column post-affiliated) ?\s))
23160 (paragraph
23161 ;; Fill prefix is usually the same as the current line,
23162 ;; unless the paragraph is at the beginning of an item.
23163 (let ((parent (org-element-property :parent element)))
23164 (save-excursion
23165 (beginning-of-line)
23166 (cond ((eq (org-element-type parent) 'item)
23167 (make-string (org-list-item-body-column
23168 (org-element-property :begin parent))
23169 ?\s))
23170 ((and adaptive-fill-regexp
23171 ;; Locally disable
23172 ;; `adaptive-fill-function' to let
23173 ;; `fill-context-prefix' handle
23174 ;; `adaptive-fill-regexp' variable.
23175 (let (adaptive-fill-function)
23176 (fill-context-prefix
23177 post-affiliated
23178 (org-element-property :end element)))))
23179 ((looking-at "[ \t]+") (match-string 0))
23180 (t "")))))
23181 (comment-block
23182 ;; Only fill contents if P is within block boundaries.
23183 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23184 (forward-line)
23185 (point)))
23186 (cend (save-excursion
23187 (goto-char (org-element-property :end element))
23188 (skip-chars-backward " \r\t\n")
23189 (line-beginning-position))))
23190 (when (and (>= p cbeg) (< p cend))
23191 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23192 (match-string 0)
23193 "")))))))))))
23195 (declare-function message-goto-body "message" ())
23196 (defvar message-cite-prefix-regexp) ; From message.el
23197 (defun org-fill-paragraph (&optional justify)
23198 "Fill element at point, when applicable.
23200 This function only applies to comment blocks, comments, example
23201 blocks and paragraphs. Also, as a special case, re-align table
23202 when point is at one.
23204 If JUSTIFY is non-nil (interactively, with prefix argument),
23205 justify as well. If `sentence-end-double-space' is non-nil, then
23206 period followed by one space does not end a sentence, so don't
23207 break a line there. The variable `fill-column' controls the
23208 width for filling.
23210 For convenience, when point is at a plain list, an item or
23211 a footnote definition, try to fill the first paragraph within."
23212 (interactive)
23213 (if (and (derived-mode-p 'message-mode)
23214 (or (not (message-in-body-p))
23215 (save-excursion (move-beginning-of-line 1)
23216 (looking-at message-cite-prefix-regexp))))
23217 ;; First ensure filling is correct in message-mode.
23218 (let ((fill-paragraph-function
23219 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23220 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23221 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23222 (paragraph-separate
23223 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23224 (fill-paragraph nil))
23225 (with-syntax-table org-mode-transpose-word-syntax-table
23226 ;; Move to end of line in order to get the first paragraph
23227 ;; within a plain list or a footnote definition.
23228 (let ((element (save-excursion
23229 (end-of-line)
23230 (or (ignore-errors (org-element-at-point))
23231 (user-error "An element cannot be parsed line %d"
23232 (line-number-at-pos (point)))))))
23233 ;; First check if point is in a blank line at the beginning of
23234 ;; the buffer. In that case, ignore filling.
23235 (cl-case (org-element-type element)
23236 ;; Use major mode filling function is src blocks.
23237 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23238 ;; Align Org tables, leave table.el tables as-is.
23239 (table-row (org-table-align) t)
23240 (table
23241 (when (eq (org-element-property :type element) 'org)
23242 (save-excursion
23243 (goto-char (org-element-property :post-affiliated element))
23244 (org-table-align)))
23246 (paragraph
23247 ;; Paragraphs may contain `line-break' type objects.
23248 (let ((beg (max (point-min)
23249 (org-element-property :contents-begin element)))
23250 (end (min (point-max)
23251 (org-element-property :contents-end element))))
23252 ;; Do nothing if point is at an affiliated keyword.
23253 (if (< (line-end-position) beg) t
23254 (when (derived-mode-p 'message-mode)
23255 ;; In `message-mode', do not fill following citation
23256 ;; in current paragraph nor text before message body.
23257 (let ((body-start (save-excursion (message-goto-body))))
23258 (when body-start (setq beg (max body-start beg))))
23259 (when (save-excursion
23260 (re-search-forward
23261 (concat "^" message-cite-prefix-regexp) end t))
23262 (setq end (match-beginning 0))))
23263 ;; Fill paragraph, taking line breaks into account.
23264 (save-excursion
23265 (goto-char beg)
23266 (let ((cuts (list beg)))
23267 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23268 (when (eq 'line-break
23269 (org-element-type
23270 (save-excursion (backward-char)
23271 (org-element-context))))
23272 (push (point) cuts)))
23273 (dolist (c (delq end cuts))
23274 (fill-region-as-paragraph c end justify)
23275 (setq end c))))
23276 t)))
23277 ;; Contents of `comment-block' type elements should be
23278 ;; filled as plain text, but only if point is within block
23279 ;; markers.
23280 (comment-block
23281 (let* ((case-fold-search t)
23282 (beg (save-excursion
23283 (goto-char (org-element-property :begin element))
23284 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23285 (forward-line)
23286 (point)))
23287 (end (save-excursion
23288 (goto-char (org-element-property :end element))
23289 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23290 (line-beginning-position))))
23291 (if (or (< (point) beg) (> (point) end)) t
23292 (fill-region-as-paragraph
23293 (save-excursion (end-of-line)
23294 (re-search-backward "^[ \t]*$" beg 'move)
23295 (line-beginning-position))
23296 (save-excursion (beginning-of-line)
23297 (re-search-forward "^[ \t]*$" end 'move)
23298 (line-beginning-position))
23299 justify))))
23300 ;; Fill comments.
23301 (comment
23302 (let ((begin (org-element-property :post-affiliated element))
23303 (end (org-element-property :end element)))
23304 (when (and (>= (point) begin) (<= (point) end))
23305 (let ((begin (save-excursion
23306 (end-of-line)
23307 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23308 (progn (forward-line) (point))
23309 begin)))
23310 (end (save-excursion
23311 (end-of-line)
23312 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23313 (1- (line-beginning-position))
23314 (skip-chars-backward " \r\t\n")
23315 (line-end-position)))))
23316 ;; Do not fill comments when at a blank line.
23317 (when (> end begin)
23318 (let ((fill-prefix
23319 (save-excursion
23320 (beginning-of-line)
23321 (looking-at "[ \t]*#")
23322 (let ((comment-prefix (match-string 0)))
23323 (goto-char (match-end 0))
23324 (if (looking-at adaptive-fill-regexp)
23325 (concat comment-prefix (match-string 0))
23326 (concat comment-prefix " "))))))
23327 (save-excursion
23328 (fill-region-as-paragraph begin end justify))))))
23330 ;; Ignore every other element.
23331 (otherwise t))))))
23333 (defun org-auto-fill-function ()
23334 "Auto-fill function."
23335 ;; Check if auto-filling is meaningful.
23336 (let ((fc (current-fill-column)))
23337 (when (and fc (> (current-column) fc))
23338 (let* ((fill-prefix (org-adaptive-fill-function))
23339 ;; Enforce empty fill prefix, if required. Otherwise, it
23340 ;; will be computed again.
23341 (adaptive-fill-mode (not (equal fill-prefix ""))))
23342 (when fill-prefix (do-auto-fill))))))
23344 (defun org-comment-line-break-function (&optional soft)
23345 "Break line at point and indent, continuing comment if within one.
23346 The inserted newline is marked hard if variable
23347 `use-hard-newlines' is true, unless optional argument SOFT is
23348 non-nil."
23349 (if soft (insert-and-inherit ?\n) (newline 1))
23350 (save-excursion (forward-char -1) (delete-horizontal-space))
23351 (delete-horizontal-space)
23352 (indent-to-left-margin)
23353 (insert-before-markers-and-inherit fill-prefix))
23356 ;;; Fixed Width Areas
23358 (defun org-toggle-fixed-width ()
23359 "Toggle fixed-width markup.
23361 Add or remove fixed-width markup on current line, whenever it
23362 makes sense. Return an error otherwise.
23364 If a region is active and if it contains only fixed-width areas
23365 or blank lines, remove all fixed-width markup in it. If the
23366 region contains anything else, convert all non-fixed-width lines
23367 to fixed-width ones.
23369 Blank lines at the end of the region are ignored unless the
23370 region only contains such lines."
23371 (interactive)
23372 (if (not (org-region-active-p))
23373 ;; No region:
23375 ;; Remove fixed width marker only in a fixed-with element.
23377 ;; Add fixed width maker in paragraphs, in blank lines after
23378 ;; elements or at the beginning of a headline or an inlinetask,
23379 ;; and before any one-line elements (e.g., a clock).
23380 (progn
23381 (beginning-of-line)
23382 (let* ((element (org-element-at-point))
23383 (type (org-element-type element)))
23384 (cond
23385 ((and (eq type 'fixed-width)
23386 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23387 (replace-match
23388 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23389 ((and (memq type '(babel-call clock comment diary-sexp headline
23390 horizontal-rule keyword paragraph
23391 planning))
23392 (<= (org-element-property :post-affiliated element) (point)))
23393 (skip-chars-forward " \t")
23394 (insert ": "))
23395 ((and (looking-at-p "[ \t]*$")
23396 (or (eq type 'inlinetask)
23397 (save-excursion
23398 (skip-chars-forward " \r\t\n")
23399 (<= (org-element-property :end element) (point)))))
23400 (delete-region (point) (line-end-position))
23401 (org-indent-line)
23402 (insert ": "))
23403 (t (user-error "Cannot insert a fixed-width line here")))))
23404 ;; Region active.
23405 (let* ((begin (save-excursion
23406 (goto-char (region-beginning))
23407 (line-beginning-position)))
23408 (end (copy-marker
23409 (save-excursion
23410 (goto-char (region-end))
23411 (unless (eolp) (beginning-of-line))
23412 (if (save-excursion (re-search-backward "\\S-" begin t))
23413 (progn (skip-chars-backward " \r\t\n") (point))
23414 (point)))))
23415 (all-fixed-width-p
23416 (catch 'not-all-p
23417 (save-excursion
23418 (goto-char begin)
23419 (skip-chars-forward " \r\t\n")
23420 (when (eobp) (throw 'not-all-p nil))
23421 (while (< (point) end)
23422 (let ((element (org-element-at-point)))
23423 (if (eq (org-element-type element) 'fixed-width)
23424 (goto-char (org-element-property :end element))
23425 (throw 'not-all-p nil))))
23426 t))))
23427 (if all-fixed-width-p
23428 (save-excursion
23429 (goto-char begin)
23430 (while (< (point) end)
23431 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23432 (replace-match
23433 "" nil nil nil
23434 (if (= (line-end-position) (match-end 0)) 0 1)))
23435 (forward-line)))
23436 (let ((min-ind (point-max)))
23437 ;; Find minimum indentation across all lines.
23438 (save-excursion
23439 (goto-char begin)
23440 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23441 (setq min-ind 0)
23442 (catch 'zerop
23443 (while (< (point) end)
23444 (unless (looking-at-p "[ \t]*$")
23445 (let ((ind (org-get-indentation)))
23446 (setq min-ind (min min-ind ind))
23447 (when (zerop ind) (throw 'zerop t))))
23448 (forward-line)))))
23449 ;; Loop over all lines and add fixed-width markup everywhere
23450 ;; but in fixed-width lines.
23451 (save-excursion
23452 (goto-char begin)
23453 (while (< (point) end)
23454 (cond
23455 ((org-at-heading-p)
23456 (insert ": ")
23457 (forward-line)
23458 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23459 (insert ":")
23460 (forward-line)))
23461 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23462 (let* ((element (org-element-at-point))
23463 (element-end (org-element-property :end element)))
23464 (if (eq (org-element-type element) 'fixed-width)
23465 (progn (goto-char element-end)
23466 (skip-chars-backward " \r\t\n")
23467 (forward-line))
23468 (let ((limit (min end element-end)))
23469 (while (< (point) limit)
23470 (org-move-to-column min-ind t)
23471 (insert ": ")
23472 (forward-line))))))
23474 (org-move-to-column min-ind t)
23475 (insert ": ")
23476 (forward-line)))))))
23477 (set-marker end nil))))
23480 ;;; Comments
23482 ;; Org comments syntax is quite complex. It requires the entire line
23483 ;; to be just a comment. Also, even with the right syntax at the
23484 ;; beginning of line, some some elements (i.e. verse-block or
23485 ;; example-block) don't accept comments. Usual Emacs comment commands
23486 ;; cannot cope with those requirements. Therefore, Org replaces them.
23488 ;; Org still relies on `comment-dwim', but cannot trust
23489 ;; `comment-only-p'. So, `comment-region-function' and
23490 ;; `uncomment-region-function' both point
23491 ;; to`org-comment-or-uncomment-region'. Eventually,
23492 ;; `org-insert-comment' takes care of insertion of comments at the
23493 ;; beginning of line.
23495 ;; `org-setup-comments-handling' install comments related variables
23496 ;; during `org-mode' initialization.
23498 (defun org-setup-comments-handling ()
23499 (interactive)
23500 (setq-local comment-use-syntax nil)
23501 (setq-local comment-start "# ")
23502 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23503 (setq-local comment-insert-comment-function 'org-insert-comment)
23504 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23505 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23507 (defun org-insert-comment ()
23508 "Insert an empty comment above current line.
23509 If the line is empty, insert comment at its beginning. When
23510 point is within a source block, comment according to the related
23511 major mode."
23512 (if (let ((element (org-element-at-point)))
23513 (and (eq (org-element-type element) 'src-block)
23514 (< (save-excursion
23515 (goto-char (org-element-property :post-affiliated element))
23516 (line-end-position))
23517 (point))
23518 (> (save-excursion
23519 (goto-char (org-element-property :end element))
23520 (skip-chars-backward " \r\t\n")
23521 (line-beginning-position))
23522 (point))))
23523 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23524 (beginning-of-line)
23525 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23526 (open-line 1))
23527 (org-indent-line)
23528 (insert "# ")))
23530 (defvar comment-empty-lines) ; From newcomment.el.
23531 (defun org-comment-or-uncomment-region (beg end &rest _)
23532 "Comment or uncomment each non-blank line in the region.
23533 Uncomment each non-blank line between BEG and END if it only
23534 contains commented lines. Otherwise, comment them. If region is
23535 strictly within a source block, use appropriate comment syntax."
23536 (if (let ((element (org-element-at-point)))
23537 (and (eq (org-element-type element) 'src-block)
23538 (< (save-excursion
23539 (goto-char (org-element-property :post-affiliated element))
23540 (line-end-position))
23541 beg)
23542 (>= (save-excursion
23543 (goto-char (org-element-property :end element))
23544 (skip-chars-backward " \r\t\n")
23545 (line-beginning-position))
23546 end)))
23547 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23548 (save-restriction
23549 ;; Restrict region
23550 (narrow-to-region (save-excursion (goto-char beg)
23551 (skip-chars-forward " \r\t\n" end)
23552 (line-beginning-position))
23553 (save-excursion (goto-char end)
23554 (skip-chars-backward " \r\t\n" beg)
23555 (line-end-position)))
23556 (let ((uncommentp
23557 ;; UNCOMMENTP is non-nil when every non blank line between
23558 ;; BEG and END is a comment.
23559 (save-excursion
23560 (goto-char (point-min))
23561 (while (and (not (eobp))
23562 (let ((element (org-element-at-point)))
23563 (and (eq (org-element-type element) 'comment)
23564 (goto-char (min (point-max)
23565 (org-element-property
23566 :end element)))))))
23567 (eobp))))
23568 (if uncommentp
23569 ;; Only blank lines and comments in region: uncomment it.
23570 (save-excursion
23571 (goto-char (point-min))
23572 (while (not (eobp))
23573 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23574 (replace-match "" nil nil nil 1))
23575 (forward-line)))
23576 ;; Comment each line in region.
23577 (let ((min-indent (point-max)))
23578 ;; First find the minimum indentation across all lines.
23579 (save-excursion
23580 (goto-char (point-min))
23581 (while (and (not (eobp)) (not (zerop min-indent)))
23582 (unless (looking-at "[ \t]*$")
23583 (setq min-indent (min min-indent (current-indentation))))
23584 (forward-line)))
23585 ;; Then loop over all lines.
23586 (save-excursion
23587 (goto-char (point-min))
23588 (while (not (eobp))
23589 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23590 ;; Don't get fooled by invisible text (e.g. link path)
23591 ;; when moving to column MIN-INDENT.
23592 (let ((buffer-invisibility-spec nil))
23593 (org-move-to-column min-indent t))
23594 (insert comment-start))
23595 (forward-line)))))))))
23597 (defun org-comment-dwim (_arg)
23598 "Call `comment-dwim' within a source edit buffer if needed."
23599 (interactive "*P")
23600 (if (org-in-src-block-p)
23601 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23602 (call-interactively 'comment-dwim)))
23605 ;;; Timestamps API
23607 ;; This section contains tools to operate on timestamp objects, as
23608 ;; returned by, e.g. `org-element-context'.
23610 (defun org-timestamp--to-internal-time (timestamp &optional end)
23611 "Encode TIMESTAMP object into Emacs internal time.
23612 Use end of date range or time range when END is non-nil."
23613 (apply #'encode-time
23614 (cons 0
23615 (mapcar
23616 (lambda (prop) (or (org-element-property prop timestamp) 0))
23617 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23618 '(:minute-start :hour-start :day-start :month-start
23619 :year-start))))))
23621 (defun org-timestamp-has-time-p (timestamp)
23622 "Non-nil when TIMESTAMP has a time specified."
23623 (org-element-property :hour-start timestamp))
23625 (defun org-timestamp-format (timestamp format &optional end utc)
23626 "Format a TIMESTAMP object into a string.
23628 FORMAT is a format specifier to be passed to
23629 `format-time-string'.
23631 When optional argument END is non-nil, use end of date-range or
23632 time-range, if possible.
23634 When optional argument UTC is non-nil, time will be expressed as
23635 Universal Time."
23636 (format-time-string
23637 format (org-timestamp--to-internal-time timestamp end)
23638 (and utc t)))
23640 (defun org-timestamp-split-range (timestamp &optional end)
23641 "Extract a TIMESTAMP object from a date or time range.
23643 END, when non-nil, means extract the end of the range.
23644 Otherwise, extract its start.
23646 Return a new timestamp object."
23647 (let ((type (org-element-property :type timestamp)))
23648 (if (memq type '(active inactive diary)) timestamp
23649 (let ((split-ts (org-element-copy timestamp)))
23650 ;; Set new type.
23651 (org-element-put-property
23652 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23653 ;; Copy start properties over end properties if END is
23654 ;; non-nil. Otherwise, copy end properties over `start' ones.
23655 (let ((p-alist '((:minute-start . :minute-end)
23656 (:hour-start . :hour-end)
23657 (:day-start . :day-end)
23658 (:month-start . :month-end)
23659 (:year-start . :year-end))))
23660 (dolist (p-cell p-alist)
23661 (org-element-put-property
23662 split-ts
23663 (funcall (if end #'car #'cdr) p-cell)
23664 (org-element-property
23665 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23666 ;; Eventually refresh `:raw-value'.
23667 (org-element-put-property split-ts :raw-value nil)
23668 (org-element-put-property
23669 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23671 (defun org-timestamp-translate (timestamp &optional boundary)
23672 "Translate TIMESTAMP object to custom format.
23674 Format string is defined in `org-time-stamp-custom-formats',
23675 which see.
23677 When optional argument BOUNDARY is non-nil, it is either the
23678 symbol `start' or `end'. In this case, only translate the
23679 starting or ending part of TIMESTAMP if it is a date or time
23680 range. Otherwise, translate both parts.
23682 Return timestamp as-is if `org-display-custom-times' is nil or if
23683 it has a `diary' type."
23684 (let ((type (org-element-property :type timestamp)))
23685 (if (or (not org-display-custom-times) (eq type 'diary))
23686 (org-element-interpret-data timestamp)
23687 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23688 org-time-stamp-custom-formats)))
23689 (if (and (not boundary) (memq type '(active-range inactive-range)))
23690 (concat (org-timestamp-format timestamp fmt)
23691 "--"
23692 (org-timestamp-format timestamp fmt t))
23693 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23697 ;;; Other stuff.
23699 (defvar reftex-docstruct-symbol)
23700 (defvar org--rds)
23702 (defun org-reftex-citation ()
23703 "Use reftex-citation to insert a citation into the buffer.
23704 This looks for a line like
23706 #+BIBLIOGRAPHY: foo plain option:-d
23708 and derives from it that foo.bib is the bibliography file relevant
23709 for this document. It then installs the necessary environment for RefTeX
23710 to work in this buffer and calls `reftex-citation' to insert a citation
23711 into the buffer.
23713 Export of such citations to both LaTeX and HTML is handled by the contributed
23714 package ox-bibtex by Taru Karttunen."
23715 (interactive)
23716 (let ((reftex-docstruct-symbol 'org--rds)
23717 org--rds bib)
23718 (org-with-wide-buffer
23719 (let ((case-fold-search t)
23720 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23721 (if (not (save-excursion
23722 (or (re-search-forward re nil t)
23723 (re-search-backward re nil t))))
23724 (user-error "No bibliography defined in file")
23725 (setq bib (concat (match-string 1) ".bib")
23726 org--rds (list (list 'bib bib))))))
23727 (call-interactively 'reftex-citation)))
23729 ;;;; Functions extending outline functionality
23731 (defun org-beginning-of-line (&optional arg)
23732 "Go to the beginning of the current line. If that is invisible, continue
23733 to a visible line beginning. This makes the function of C-a more intuitive.
23734 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23735 first attempt, and only move to after the tags when the cursor is already
23736 beyond the end of the headline."
23737 (interactive "P")
23738 (let ((pos (point))
23739 (special (if (consp org-special-ctrl-a/e)
23740 (car org-special-ctrl-a/e)
23741 org-special-ctrl-a/e))
23742 deactivate-mark refpos)
23743 (call-interactively (if (bound-and-true-p visual-line-mode)
23744 #'beginning-of-visual-line
23745 #'move-beginning-of-line))
23746 (cond
23747 ((or arg (not special)))
23748 ((and (looking-at org-complex-heading-regexp)
23749 (eq (char-after (match-end 1)) ?\s))
23750 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23751 (point-at-eol)))
23752 (goto-char
23753 (if (eq special t)
23754 (cond ((> pos refpos) refpos)
23755 ((= pos (point)) refpos)
23756 (t (point)))
23757 (cond ((> pos (point)) (point))
23758 ((not (eq last-command this-command)) (point))
23759 (t refpos)))))
23760 ((org-at-item-p)
23761 ;; Being at an item and not looking at an the item means point
23762 ;; was previously moved to beginning of a visual line, which
23763 ;; doesn't contain the item. Therefore, do nothing special,
23764 ;; just stay here.
23765 (when (looking-at org-list-full-item-re)
23766 ;; Set special position at first white space character after
23767 ;; bullet, and check-box, if any.
23768 (let ((after-bullet
23769 (let ((box (match-end 3)))
23770 (if (not box) (match-end 1)
23771 (let ((after (char-after box)))
23772 (if (and after (= after ? )) (1+ box) box))))))
23773 ;; Special case: Move point to special position when
23774 ;; currently after it or at beginning of line.
23775 (if (eq special t)
23776 (when (or (> pos after-bullet) (= (point) pos))
23777 (goto-char after-bullet))
23778 ;; Reversed case: Move point to special position when
23779 ;; point was already at beginning of line and command is
23780 ;; repeated.
23781 (when (and (= (point) pos) (eq last-command this-command))
23782 (goto-char after-bullet))))))))
23783 (setq disable-point-adjustment
23784 (or (not (invisible-p (point)))
23785 (not (invisible-p (max (point-min) (1- (point))))))))
23787 (defun org-end-of-line (&optional arg)
23788 "Go to the end of the line.
23789 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23790 tags on the first attempt, and only move to after the tags when
23791 the cursor is already beyond the end of the headline."
23792 (interactive "P")
23793 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23794 org-special-ctrl-a/e))
23795 (move-fun (cond ((bound-and-true-p visual-line-mode)
23796 'end-of-visual-line)
23797 ((fboundp 'move-end-of-line) 'move-end-of-line)
23798 (t 'end-of-line)))
23799 deactivate-mark)
23800 (if (or (not special) arg) (call-interactively move-fun)
23801 (let* ((element (save-excursion (beginning-of-line)
23802 (org-element-at-point)))
23803 (type (org-element-type element)))
23804 (cond
23805 ((memq type '(headline inlinetask))
23806 (let ((pos (point)))
23807 (beginning-of-line 1)
23808 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23809 (if (eq special t)
23810 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23811 (goto-char (match-beginning 1))
23812 (goto-char (match-end 0)))
23813 (if (or (< pos (match-end 0))
23814 (not (eq this-command last-command)))
23815 (goto-char (match-end 0))
23816 (goto-char (match-beginning 1))))
23817 (call-interactively move-fun))))
23818 ((outline-invisible-p (line-end-position))
23819 ;; If element is hidden, `move-end-of-line' would put point
23820 ;; after it. Use `end-of-line' to stay on current line.
23821 (call-interactively 'end-of-line))
23822 (t (call-interactively move-fun))))))
23823 (setq disable-point-adjustment
23824 (or (not (invisible-p (point)))
23825 (not (invisible-p (max (point-min) (1- (point))))))))
23827 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23828 (define-key org-mode-map "\C-e" 'org-end-of-line)
23830 (defun org-backward-sentence (&optional _arg)
23831 "Go to beginning of sentence, or beginning of table field.
23832 This will call `backward-sentence' or `org-table-beginning-of-field',
23833 depending on context."
23834 (interactive)
23835 (let* ((element (org-element-at-point))
23836 (contents-begin (org-element-property :contents-begin element))
23837 (table (org-element-lineage element '(table) t)))
23838 (if (and table
23839 (> (point) contents-begin)
23840 (<= (point) (org-element-property :contents-end table)))
23841 (call-interactively #'org-table-beginning-of-field)
23842 (save-restriction
23843 (when (and contents-begin
23844 (< (point-min) contents-begin)
23845 (> (point) contents-begin))
23846 (narrow-to-region contents-begin
23847 (org-element-property :contents-end element)))
23848 (call-interactively #'backward-sentence)))))
23850 (defun org-forward-sentence (&optional _arg)
23851 "Go to end of sentence, or end of table field.
23852 This will call `forward-sentence' or `org-table-end-of-field',
23853 depending on context."
23854 (interactive)
23855 (let* ((element (org-element-at-point))
23856 (contents-end (org-element-property :contents-end element))
23857 (table (org-element-lineage element '(table) t)))
23858 (if (and table
23859 (>= (point) (org-element-property :contents-begin table))
23860 (< (point) contents-end))
23861 (call-interactively #'org-table-end-of-field)
23862 (save-restriction
23863 (when (and contents-end
23864 (> (point-max) contents-end)
23865 ;; Skip blank lines between elements.
23866 (< (org-element-property :end element)
23867 (save-excursion (goto-char contents-end)
23868 (skip-chars-forward " \r\t\n"))))
23869 (narrow-to-region (org-element-property :contents-begin element)
23870 contents-end))
23871 (call-interactively #'forward-sentence)))))
23873 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23874 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23876 (defun org-kill-line (&optional _arg)
23877 "Kill line, to tags or end of line."
23878 (interactive)
23879 (cond
23880 ((or (not org-special-ctrl-k)
23881 (bolp)
23882 (not (org-at-heading-p)))
23883 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23884 org-ctrl-k-protect-subtree
23885 (or (eq org-ctrl-k-protect-subtree 'error)
23886 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23887 (user-error "C-k aborted as it would kill a hidden subtree"))
23888 (call-interactively
23889 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23890 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23891 (kill-region (point) (match-beginning 1))
23892 (org-set-tags nil t))
23893 (t (kill-region (point) (point-at-eol)))))
23895 (define-key org-mode-map "\C-k" 'org-kill-line)
23897 (defun org-yank (&optional arg)
23898 "Yank. If the kill is a subtree, treat it specially.
23899 This command will look at the current kill and check if is a single
23900 subtree, or a series of subtrees[1]. If it passes the test, and if the
23901 cursor is at the beginning of a line or after the stars of a currently
23902 empty headline, then the yank is handled specially. How exactly depends
23903 on the value of the following variables.
23905 `org-yank-folded-subtrees'
23906 By default, this variable is non-nil, which results in subtree(s)
23907 being folded after insertion, but only if doing so would now
23908 swallow text after the yanked text.
23910 `org-yank-adjusted-subtrees'
23911 When non-nil (the default value is nil), the subtree will be
23912 promoted or demoted in order to fit into the local outline tree
23913 structure, which means that the level will be adjusted so that it
23914 becomes the smaller one of the two *visible* surrounding headings.
23916 Any prefix to this command will cause `yank' to be called directly with
23917 no special treatment. In particular, a simple \\[universal-argument] prefix \
23918 will just
23919 plainly yank the text as it is.
23921 \[1] The test checks if the first non-white line is a heading
23922 and if there are no other headings with fewer stars."
23923 (interactive "P")
23924 (org-yank-generic 'yank arg))
23926 (defun org-yank-generic (command arg)
23927 "Perform some yank-like command.
23929 This function implements the behavior described in the `org-yank'
23930 documentation. However, it has been generalized to work for any
23931 interactive command with similar behavior."
23933 ;; pretend to be command COMMAND
23934 (setq this-command command)
23936 (if arg
23937 (call-interactively command)
23939 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23940 (and (org-kill-is-subtree-p)
23941 (or (bolp)
23942 (and (looking-at "[ \t]*$")
23943 (string-match
23944 "\\`\\*+\\'"
23945 (buffer-substring (point-at-bol) (point)))))))
23946 swallowp)
23947 (cond
23948 ((and subtreep org-yank-folded-subtrees)
23949 (let ((beg (point))
23950 end)
23951 (if (and subtreep org-yank-adjusted-subtrees)
23952 (org-paste-subtree nil nil 'for-yank)
23953 (call-interactively command))
23955 (setq end (point))
23956 (goto-char beg)
23957 (when (and (bolp) subtreep
23958 (not (setq swallowp
23959 (org-yank-folding-would-swallow-text beg end))))
23960 (org-with-limited-levels
23961 (or (looking-at org-outline-regexp)
23962 (re-search-forward org-outline-regexp-bol end t))
23963 (while (and (< (point) end) (looking-at org-outline-regexp))
23964 (outline-hide-subtree)
23965 (org-cycle-show-empty-lines 'folded)
23966 (condition-case nil
23967 (outline-forward-same-level 1)
23968 (error (goto-char end))))))
23969 (when swallowp
23970 (message
23971 "Inserted text not folded because that would swallow text"))
23973 (goto-char end)
23974 (skip-chars-forward " \t\n\r")
23975 (beginning-of-line 1)
23976 (push-mark beg 'nomsg)))
23977 ((and subtreep org-yank-adjusted-subtrees)
23978 (let ((beg (point-at-bol)))
23979 (org-paste-subtree nil nil 'for-yank)
23980 (push-mark beg 'nomsg)))
23982 (call-interactively command))))))
23984 (defun org-yank-folding-would-swallow-text (beg end)
23985 "Would hide-subtree at BEG swallow any text after END?"
23986 (let (level)
23987 (org-with-limited-levels
23988 (save-excursion
23989 (goto-char beg)
23990 (when (or (looking-at org-outline-regexp)
23991 (re-search-forward org-outline-regexp-bol end t))
23992 (setq level (org-outline-level)))
23993 (goto-char end)
23994 (skip-chars-forward " \t\r\n\v\f")
23995 (not (or (eobp)
23996 (and (bolp) (looking-at-p org-outline-regexp)
23997 (<= (org-outline-level) level))))))))
23999 (define-key org-mode-map "\C-y" 'org-yank)
24001 (defun org-truely-invisible-p ()
24002 "Check if point is at a character currently not visible.
24003 This version does not only check the character property, but also
24004 `visible-mode'."
24005 ;; Early versions of noutline don't have `outline-invisible-p'.
24006 (unless (bound-and-true-p visible-mode)
24007 (outline-invisible-p)))
24009 (defun org-invisible-p2 ()
24010 "Check if point is at a character currently not visible."
24011 (save-excursion
24012 (when (and (eolp) (not (bobp))) (backward-char 1))
24013 ;; Early versions of noutline don't have `outline-invisible-p'.
24014 (outline-invisible-p)))
24016 (defun org-back-to-heading (&optional invisible-ok)
24017 "Call `outline-back-to-heading', but provide a better error message."
24018 (condition-case nil
24019 (outline-back-to-heading invisible-ok)
24020 (error (error "Before first headline at position %d in buffer %s"
24021 (point) (current-buffer)))))
24023 (defun org-before-first-heading-p ()
24024 "Before first heading?"
24025 (save-excursion
24026 (end-of-line)
24027 (null (re-search-backward org-outline-regexp-bol nil t))))
24029 (defun org-at-heading-p (&optional ignored)
24030 (outline-on-heading-p t))
24032 (defun org-in-commented-heading-p (&optional no-inheritance)
24033 "Non-nil if point is under a commented heading.
24034 This function also checks ancestors of the current headline,
24035 unless optional argument NO-INHERITANCE is non-nil."
24036 (cond
24037 ((org-before-first-heading-p) nil)
24038 ((let ((headline (nth 4 (org-heading-components))))
24039 (and headline
24040 (let ((case-fold-search nil))
24041 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24042 headline)))))
24043 (no-inheritance nil)
24045 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24047 (defun org-at-comment-p nil
24048 "Is cursor in a commented line?"
24049 (save-excursion
24050 (save-match-data
24051 (beginning-of-line)
24052 (looking-at "^[ \t]*# "))))
24054 (defun org-at-drawer-p nil
24055 "Is cursor at a drawer keyword?"
24056 (save-excursion
24057 (move-beginning-of-line 1)
24058 (looking-at org-drawer-regexp)))
24060 (defun org-at-block-p nil
24061 "Is cursor at a block keyword?"
24062 (save-excursion
24063 (move-beginning-of-line 1)
24064 (looking-at org-block-regexp)))
24066 (defun org-point-at-end-of-empty-headline ()
24067 "If point is at the end of an empty headline, return t, else nil.
24068 If the heading only contains a TODO keyword, it is still still considered
24069 empty."
24070 (and (looking-at "[ \t]*$")
24071 (when org-todo-line-regexp
24072 (save-excursion
24073 (beginning-of-line 1)
24074 (let ((case-fold-search nil))
24075 (looking-at org-todo-line-regexp)
24076 (string= (match-string 3) ""))))))
24078 (defun org-at-heading-or-item-p ()
24079 (or (org-at-heading-p) (org-at-item-p)))
24081 (defun org-at-target-p ()
24082 (or (org-in-regexp org-radio-target-regexp)
24083 (org-in-regexp org-target-regexp)))
24084 ;; Compatibility alias with Org versions < 7.8.03
24085 (defalias 'org-on-target-p 'org-at-target-p)
24087 (defun org-up-heading-all (arg)
24088 "Move to the heading line of which the present line is a subheading.
24089 This function considers both visible and invisible heading lines.
24090 With argument, move up ARG levels."
24091 (outline-up-heading arg t))
24093 (defun org-up-heading-safe ()
24094 "Move to the heading line of which the present line is a subheading.
24095 This version will not throw an error. It will return the level of the
24096 headline found, or nil if no higher level is found.
24098 Also, this function will be a lot faster than `outline-up-heading',
24099 because it relies on stars being the outline starters. This can really
24100 make a significant difference in outlines with very many siblings."
24101 (when (ignore-errors (org-back-to-heading t))
24102 (let ((level-up (1- (funcall outline-level))))
24103 (and (> level-up 0)
24104 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24105 (funcall outline-level)))))
24107 (defun org-first-sibling-p ()
24108 "Is this heading the first child of its parents?"
24109 (interactive)
24110 (let ((re org-outline-regexp-bol)
24111 level l)
24112 (unless (org-at-heading-p t)
24113 (user-error "Not at a heading"))
24114 (setq level (funcall outline-level))
24115 (save-excursion
24116 (if (not (re-search-backward re nil t))
24118 (setq l (funcall outline-level))
24119 (< l level)))))
24121 (defun org-goto-sibling (&optional previous)
24122 "Goto the next sibling, even if it is invisible.
24123 When PREVIOUS is set, go to the previous sibling instead. Returns t
24124 when a sibling was found. When none is found, return nil and don't
24125 move point."
24126 (let ((fun (if previous 're-search-backward 're-search-forward))
24127 (pos (point))
24128 (re org-outline-regexp-bol)
24129 level l)
24130 (when (ignore-errors (org-back-to-heading t))
24131 (setq level (funcall outline-level))
24132 (catch 'exit
24133 (or previous (forward-char 1))
24134 (while (funcall fun re nil t)
24135 (setq l (funcall outline-level))
24136 (when (< l level) (goto-char pos) (throw 'exit nil))
24137 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24138 (goto-char pos)
24139 nil))))
24141 (defun org-show-siblings ()
24142 "Show all siblings of the current headline."
24143 (save-excursion
24144 (while (org-goto-sibling) (org-flag-heading nil)))
24145 (save-excursion
24146 (while (org-goto-sibling 'previous)
24147 (org-flag-heading nil))))
24149 (defun org-goto-first-child ()
24150 "Goto the first child, even if it is invisible.
24151 Return t when a child was found. Otherwise don't move point and
24152 return nil."
24153 (let (level (pos (point)) (re org-outline-regexp-bol))
24154 (when (ignore-errors (org-back-to-heading t))
24155 (setq level (outline-level))
24156 (forward-char 1)
24157 (if (and (re-search-forward re nil t) (> (outline-level) level))
24158 (progn (goto-char (match-beginning 0)) t)
24159 (goto-char pos) nil))))
24161 (defun org-show-hidden-entry ()
24162 "Show an entry where even the heading is hidden."
24163 (save-excursion
24164 (org-show-entry)))
24166 (defun org-flag-heading (flag &optional entry)
24167 "Flag the current heading. FLAG non-nil means make invisible.
24168 When ENTRY is non-nil, show the entire entry."
24169 (save-excursion
24170 (org-back-to-heading t)
24171 ;; Check if we should show the entire entry
24172 (if entry
24173 (progn
24174 (org-show-entry)
24175 (save-excursion
24176 (and (outline-next-heading)
24177 (org-flag-heading nil))))
24178 (outline-flag-region (max (point-min) (1- (point)))
24179 (save-excursion (outline-end-of-heading) (point))
24180 flag))))
24182 (defun org-get-next-sibling ()
24183 "Move to next heading of the same level, and return point.
24184 If there is no such heading, return nil.
24185 This is like outline-next-sibling, but invisible headings are ok."
24186 (let ((level (funcall outline-level)))
24187 (outline-next-heading)
24188 (while (and (not (eobp)) (> (funcall outline-level) level))
24189 (outline-next-heading))
24190 (unless (or (eobp) (< (funcall outline-level) level))
24191 (point))))
24193 (defun org-get-last-sibling ()
24194 "Move to previous heading of the same level, and return point.
24195 If there is no such heading, return nil."
24196 (let ((opoint (point))
24197 (level (funcall outline-level)))
24198 (outline-previous-heading)
24199 (when (and (/= (point) opoint) (outline-on-heading-p t))
24200 (while (and (> (funcall outline-level) level)
24201 (not (bobp)))
24202 (outline-previous-heading))
24203 (unless (< (funcall outline-level) level)
24204 (point)))))
24206 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24207 "Goto to the end of a subtree."
24208 ;; This contains an exact copy of the original function, but it uses
24209 ;; `org-back-to-heading', to make it work also in invisible
24210 ;; trees. And is uses an invisible-ok argument.
24211 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24212 ;; Furthermore, when used inside Org, finding the end of a large subtree
24213 ;; with many children and grandchildren etc, this can be much faster
24214 ;; than the outline version.
24215 (org-back-to-heading invisible-ok)
24216 (let ((first t)
24217 (level (funcall outline-level)))
24218 (if (and (derived-mode-p 'org-mode) (< level 1000))
24219 ;; A true heading (not a plain list item), in Org
24220 ;; This means we can easily find the end by looking
24221 ;; only for the right number of stars. Using a regexp to do
24222 ;; this is so much faster than using a Lisp loop.
24223 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24224 (forward-char 1)
24225 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24226 ;; something else, do it the slow way
24227 (while (and (not (eobp))
24228 (or first (> (funcall outline-level) level)))
24229 (setq first nil)
24230 (outline-next-heading)))
24231 (unless to-heading
24232 (when (memq (preceding-char) '(?\n ?\^M))
24233 ;; Go to end of line before heading
24234 (forward-char -1)
24235 (when (memq (preceding-char) '(?\n ?\^M))
24236 ;; leave blank line before heading
24237 (forward-char -1)))))
24238 (point))
24240 (defun org-end-of-meta-data (&optional full)
24241 "Skip planning line and properties drawer in current entry.
24242 When optional argument FULL is non-nil, also skip empty lines,
24243 clocking lines and regular drawers at the beginning of the
24244 entry."
24245 (org-back-to-heading t)
24246 (forward-line)
24247 (when (looking-at-p org-planning-line-re) (forward-line))
24248 (when (looking-at org-property-drawer-re)
24249 (goto-char (match-end 0))
24250 (forward-line))
24251 (when (and full (not (org-at-heading-p)))
24252 (catch 'exit
24253 (let ((end (save-excursion (outline-next-heading) (point)))
24254 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24255 (while (not (eobp))
24256 (cond ((looking-at-p org-drawer-regexp)
24257 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24258 (forward-line)
24259 (throw 'exit t)))
24260 ((looking-at-p re) (forward-line))
24261 (t (throw 'exit t))))))))
24263 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24264 "Move forward to the ARG'th subheading at same level as this one.
24265 Stop at the first and last subheadings of a superior heading.
24266 Normally this only looks at visible headings, but when INVISIBLE-OK is
24267 non-nil it will also look at invisible ones."
24268 (interactive "p")
24269 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24270 (if (and arg (< arg 0))
24271 (goto-char (point-min))
24272 (outline-next-heading))
24273 (org-at-heading-p)
24274 (let ((level (- (match-end 0) (match-beginning 0) 1))
24275 (f (if (and arg (< arg 0))
24276 're-search-backward
24277 're-search-forward))
24278 (count (if arg (abs arg) 1))
24279 (result (point)))
24280 (while (and (prog1 (> count 0)
24281 (forward-char (if (and arg (< arg 0)) -1 1)))
24282 (funcall f org-outline-regexp-bol nil 'move))
24283 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24284 (cond ((< l level) (setq count 0))
24285 ((and (= l level)
24286 (or invisible-ok
24287 (progn
24288 (goto-char (line-beginning-position))
24289 (not (outline-invisible-p)))))
24290 (setq count (1- count))
24291 (when (eq l level)
24292 (setq result (point)))))))
24293 (goto-char result))
24294 (beginning-of-line 1)))
24296 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24297 "Move backward to the ARG'th subheading at same level as this one.
24298 Stop at the first and last subheadings of a superior heading."
24299 (interactive "p")
24300 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24302 (defun org-next-visible-heading (arg)
24303 "Move to the next visible heading.
24305 This function wraps `outline-next-visible-heading' with
24306 `org-with-limited-levels' in order to skip over inline tasks and
24307 respect customization of `org-odd-levels-only'."
24308 (interactive "p")
24309 (org-with-limited-levels
24310 (outline-next-visible-heading arg)))
24312 (defun org-previous-visible-heading (arg)
24313 "Move to the previous visible heading.
24315 This function wraps `outline-previous-visible-heading' with
24316 `org-with-limited-levels' in order to skip over inline tasks and
24317 respect customization of `org-odd-levels-only'."
24318 (interactive "p")
24319 (org-with-limited-levels
24320 (outline-previous-visible-heading arg)))
24322 (defun org-next-block (arg &optional backward block-regexp)
24323 "Jump to the next block.
24325 With a prefix argument ARG, jump forward ARG many blocks.
24327 When BACKWARD is non-nil, jump to the previous block.
24329 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24330 Match data is set according to this regexp when the function
24331 returns.
24333 Return point at beginning of the opening line of found block.
24334 Throw an error if no block is found."
24335 (interactive "p")
24336 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24337 (case-fold-search t)
24338 (search-fn (if backward #'re-search-backward #'re-search-forward))
24339 (count (or arg 1))
24340 (origin (point))
24341 last-element)
24342 (if backward (beginning-of-line) (end-of-line))
24343 (while (and (> count 0) (funcall search-fn re nil t))
24344 (let ((element (save-excursion
24345 (goto-char (match-beginning 0))
24346 (save-match-data (org-element-at-point)))))
24347 (when (and (memq (org-element-type element)
24348 '(center-block comment-block dynamic-block
24349 example-block export-block quote-block
24350 special-block src-block verse-block))
24351 (<= (match-beginning 0)
24352 (org-element-property :post-affiliated element)))
24353 (setq last-element element)
24354 (cl-decf count))))
24355 (if (= count 0)
24356 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24357 (save-match-data (org-show-context)))
24358 (goto-char origin)
24359 (user-error "No %s code blocks" (if backward "previous" "further")))))
24361 (defun org-previous-block (arg &optional block-regexp)
24362 "Jump to the previous block.
24363 With a prefix argument ARG, jump backward ARG many source blocks.
24364 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24365 (interactive "p")
24366 (org-next-block arg t block-regexp))
24368 (defun org-forward-paragraph ()
24369 "Move forward to beginning of next paragraph or equivalent.
24371 The function moves point to the beginning of the next visible
24372 structural element, which can be a paragraph, a table, a list
24373 item, etc. It also provides some special moves for convenience:
24375 - On an affiliated keyword, jump to the beginning of the
24376 relative element.
24377 - On an item or a footnote definition, move to the second
24378 element inside, if any.
24379 - On a table or a property drawer, jump after it.
24380 - On a verse or source block, stop after blank lines."
24381 (interactive)
24382 (when (eobp) (user-error "Cannot move further down"))
24383 (let* ((deactivate-mark nil)
24384 (element (org-element-at-point))
24385 (type (org-element-type element))
24386 (post-affiliated (org-element-property :post-affiliated element))
24387 (contents-begin (org-element-property :contents-begin element))
24388 (contents-end (org-element-property :contents-end element))
24389 (end (let ((end (org-element-property :end element)) (parent element))
24390 (while (and (setq parent (org-element-property :parent parent))
24391 (= (org-element-property :contents-end parent) end))
24392 (setq end (org-element-property :end parent)))
24393 end)))
24394 (cond ((not element)
24395 (skip-chars-forward " \r\t\n")
24396 (or (eobp) (beginning-of-line)))
24397 ;; On affiliated keywords, move to element's beginning.
24398 ((< (point) post-affiliated)
24399 (goto-char post-affiliated))
24400 ;; At a table row, move to the end of the table. Similarly,
24401 ;; at a node property, move to the end of the property
24402 ;; drawer.
24403 ((memq type '(node-property table-row))
24404 (goto-char (org-element-property
24405 :end (org-element-property :parent element))))
24406 ((memq type '(property-drawer table)) (goto-char end))
24407 ;; Consider blank lines as separators in verse and source
24408 ;; blocks to ease editing.
24409 ((memq type '(src-block verse-block))
24410 (when (eq type 'src-block)
24411 (setq contents-end
24412 (save-excursion (goto-char end)
24413 (skip-chars-backward " \r\t\n")
24414 (line-beginning-position))))
24415 (beginning-of-line)
24416 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24417 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24418 (goto-char end)
24419 (skip-chars-forward " \r\t\n")
24420 (if (= (point) contents-end) (goto-char end)
24421 (beginning-of-line))))
24422 ;; With no contents, just skip element.
24423 ((not contents-begin) (goto-char end))
24424 ;; If contents are invisible, skip the element altogether.
24425 ((outline-invisible-p (line-end-position))
24426 (cl-case type
24427 (headline
24428 (org-with-limited-levels (outline-next-visible-heading 1)))
24429 ;; At a plain list, make sure we move to the next item
24430 ;; instead of skipping the whole list.
24431 (plain-list (forward-char)
24432 (org-forward-paragraph))
24433 (otherwise (goto-char end))))
24434 ((>= (point) contents-end) (goto-char end))
24435 ((>= (point) contents-begin)
24436 ;; This can only happen on paragraphs and plain lists.
24437 (cl-case type
24438 (paragraph (goto-char end))
24439 ;; At a plain list, try to move to second element in
24440 ;; first item, if possible.
24441 (plain-list (end-of-line)
24442 (org-forward-paragraph))))
24443 ;; When contents start on the middle of a line (e.g. in
24444 ;; items and footnote definitions), try to reach first
24445 ;; element starting after current line.
24446 ((> (line-end-position) contents-begin)
24447 (end-of-line)
24448 (org-forward-paragraph))
24449 (t (goto-char contents-begin)))))
24451 (defun org-backward-paragraph ()
24452 "Move backward to start of previous paragraph or equivalent.
24454 The function moves point to the beginning of the current
24455 structural element, which can be a paragraph, a table, a list
24456 item, etc., or to the beginning of the previous visible one if
24457 point is already there. It also provides some special moves for
24458 convenience:
24460 - On an affiliated keyword, jump to the first one.
24461 - On a table or a property drawer, move to its beginning.
24462 - On a verse or source block, stop before blank lines."
24463 (interactive)
24464 (when (bobp) (user-error "Cannot move further up"))
24465 (let* ((deactivate-mark nil)
24466 (element (org-element-at-point))
24467 (type (org-element-type element))
24468 (contents-begin (org-element-property :contents-begin element))
24469 (contents-end (org-element-property :contents-end element))
24470 (post-affiliated (org-element-property :post-affiliated element))
24471 (begin (org-element-property :begin element)))
24472 (cond
24473 ((not element) (goto-char (point-min)))
24474 ((= (point) begin)
24475 (backward-char)
24476 (org-backward-paragraph))
24477 ((<= (point) post-affiliated) (goto-char begin))
24478 ((memq type '(node-property table-row))
24479 (goto-char (org-element-property
24480 :post-affiliated (org-element-property :parent element))))
24481 ((memq type '(property-drawer table)) (goto-char begin))
24482 ((memq type '(src-block verse-block))
24483 (when (eq type 'src-block)
24484 (setq contents-begin
24485 (save-excursion (goto-char begin) (forward-line) (point))))
24486 (if (= (point) contents-begin) (goto-char post-affiliated)
24487 ;; Inside a verse block, see blank lines as paragraph
24488 ;; separators.
24489 (let ((origin (point)))
24490 (skip-chars-backward " \r\t\n" contents-begin)
24491 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24492 (skip-chars-forward " \r\t\n" origin)
24493 (if (= (point) origin) (goto-char contents-begin)
24494 (beginning-of-line))))))
24495 ((not contents-begin) (goto-char (or post-affiliated begin)))
24496 ((eq type 'paragraph)
24497 (goto-char contents-begin)
24498 ;; When at first paragraph in an item or a footnote definition,
24499 ;; move directly to beginning of line.
24500 (let ((parent-contents
24501 (org-element-property
24502 :contents-begin (org-element-property :parent element))))
24503 (when (and parent-contents (= parent-contents contents-begin))
24504 (beginning-of-line))))
24505 ;; At the end of a greater element, move to the beginning of the
24506 ;; last element within.
24507 ((>= (point) contents-end)
24508 (goto-char (1- contents-end))
24509 (org-backward-paragraph))
24510 (t (goto-char (or post-affiliated begin))))
24511 ;; Ensure we never leave point invisible.
24512 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24514 (defun org-forward-element ()
24515 "Move forward by one element.
24516 Move to the next element at the same level, when possible."
24517 (interactive)
24518 (cond ((eobp) (user-error "Cannot move further down"))
24519 ((org-with-limited-levels (org-at-heading-p))
24520 (let ((origin (point)))
24521 (goto-char (org-end-of-subtree nil t))
24522 (unless (org-with-limited-levels (org-at-heading-p))
24523 (goto-char origin)
24524 (user-error "Cannot move further down"))))
24526 (let* ((elem (org-element-at-point))
24527 (end (org-element-property :end elem))
24528 (parent (org-element-property :parent elem)))
24529 (cond ((and parent (= (org-element-property :contents-end parent) end))
24530 (goto-char (org-element-property :end parent)))
24531 ((integer-or-marker-p end) (goto-char end))
24532 (t (message "No element at point")))))))
24534 (defun org-backward-element ()
24535 "Move backward by one element.
24536 Move to the previous element at the same level, when possible."
24537 (interactive)
24538 (cond ((bobp) (user-error "Cannot move further up"))
24539 ((org-with-limited-levels (org-at-heading-p))
24540 ;; At a headline, move to the previous one, if any, or stay
24541 ;; here.
24542 (let ((origin (point)))
24543 (org-with-limited-levels (org-backward-heading-same-level 1))
24544 ;; When current headline has no sibling above, move to its
24545 ;; parent.
24546 (when (= (point) origin)
24547 (or (org-with-limited-levels (org-up-heading-safe))
24548 (progn (goto-char origin)
24549 (user-error "Cannot move further up"))))))
24551 (let* ((elem (org-element-at-point))
24552 (beg (org-element-property :begin elem)))
24553 (cond
24554 ;; Move to beginning of current element if point isn't
24555 ;; there already.
24556 ((null beg) (message "No element at point"))
24557 ((/= (point) beg) (goto-char beg))
24558 (t (goto-char beg)
24559 (skip-chars-backward " \r\t\n")
24560 (unless (bobp)
24561 (let ((prev (org-element-at-point)))
24562 (goto-char (org-element-property :begin prev))
24563 (while (and (setq prev (org-element-property :parent prev))
24564 (<= (org-element-property :end prev) beg))
24565 (goto-char (org-element-property :begin prev)))))))))))
24567 (defun org-up-element ()
24568 "Move to upper element."
24569 (interactive)
24570 (if (org-with-limited-levels (org-at-heading-p))
24571 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24572 (let* ((elem (org-element-at-point))
24573 (parent (org-element-property :parent elem)))
24574 (if parent (goto-char (org-element-property :begin parent))
24575 (if (org-with-limited-levels (org-before-first-heading-p))
24576 (user-error "No surrounding element")
24577 (org-with-limited-levels (org-back-to-heading)))))))
24579 (defvar org-element-greater-elements)
24580 (defun org-down-element ()
24581 "Move to inner element."
24582 (interactive)
24583 (let ((element (org-element-at-point)))
24584 (cond
24585 ((memq (org-element-type element) '(plain-list table))
24586 (goto-char (org-element-property :contents-begin element))
24587 (forward-char))
24588 ((memq (org-element-type element) org-element-greater-elements)
24589 ;; If contents are hidden, first disclose them.
24590 (when (outline-invisible-p (line-end-position)) (org-cycle))
24591 (goto-char (or (org-element-property :contents-begin element)
24592 (user-error "No content for this element"))))
24593 (t (user-error "No inner element")))))
24595 (defun org-drag-element-backward ()
24596 "Move backward element at point."
24597 (interactive)
24598 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24599 (let* ((elem (org-element-at-point))
24600 (prev-elem
24601 (save-excursion
24602 (goto-char (org-element-property :begin elem))
24603 (skip-chars-backward " \r\t\n")
24604 (unless (bobp)
24605 (let* ((beg (org-element-property :begin elem))
24606 (prev (org-element-at-point))
24607 (up prev))
24608 (while (and (setq up (org-element-property :parent up))
24609 (<= (org-element-property :end up) beg))
24610 (setq prev up))
24611 prev)))))
24612 ;; Error out if no previous element or previous element is
24613 ;; a parent of the current one.
24614 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24615 (user-error "Cannot drag element backward")
24616 (let ((pos (point)))
24617 (org-element-swap-A-B prev-elem elem)
24618 (goto-char (+ (org-element-property :begin prev-elem)
24619 (- pos (org-element-property :begin elem)))))))))
24621 (defun org-drag-element-forward ()
24622 "Move forward element at point."
24623 (interactive)
24624 (let* ((pos (point))
24625 (elem (org-element-at-point)))
24626 (when (= (point-max) (org-element-property :end elem))
24627 (user-error "Cannot drag element forward"))
24628 (goto-char (org-element-property :end elem))
24629 (let ((next-elem (org-element-at-point)))
24630 (when (or (org-element-nested-p elem next-elem)
24631 (and (eq (org-element-type next-elem) 'headline)
24632 (not (eq (org-element-type elem) 'headline))))
24633 (goto-char pos)
24634 (user-error "Cannot drag element forward"))
24635 ;; Compute new position of point: it's shifted by NEXT-ELEM
24636 ;; body's length (without final blanks) and by the length of
24637 ;; blanks between ELEM and NEXT-ELEM.
24638 (let ((size-next (- (save-excursion
24639 (goto-char (org-element-property :end next-elem))
24640 (skip-chars-backward " \r\t\n")
24641 (forward-line)
24642 ;; Small correction if buffer doesn't end
24643 ;; with a newline character.
24644 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24645 (org-element-property :begin next-elem)))
24646 (size-blank (- (org-element-property :end elem)
24647 (save-excursion
24648 (goto-char (org-element-property :end elem))
24649 (skip-chars-backward " \r\t\n")
24650 (forward-line)
24651 (point)))))
24652 (org-element-swap-A-B elem next-elem)
24653 (goto-char (+ pos size-next size-blank))))))
24655 (defun org-drag-line-forward (arg)
24656 "Drag the line at point ARG lines forward."
24657 (interactive "p")
24658 (dotimes (_ (abs arg))
24659 (let ((c (current-column)))
24660 (if (< 0 arg)
24661 (progn
24662 (beginning-of-line 2)
24663 (transpose-lines 1)
24664 (beginning-of-line 0))
24665 (transpose-lines 1)
24666 (beginning-of-line -1))
24667 (org-move-to-column c))))
24669 (defun org-drag-line-backward (arg)
24670 "Drag the line at point ARG lines backward."
24671 (interactive "p")
24672 (org-drag-line-forward (- arg)))
24674 (defun org-mark-element ()
24675 "Put point at beginning of this element, mark at end.
24677 Interactively, if this command is repeated or (in Transient Mark
24678 mode) if the mark is active, it marks the next element after the
24679 ones already marked."
24680 (interactive)
24681 (let (deactivate-mark)
24682 (if (and (called-interactively-p 'any)
24683 (or (and (eq last-command this-command) (mark t))
24684 (and transient-mark-mode mark-active)))
24685 (set-mark
24686 (save-excursion
24687 (goto-char (mark))
24688 (goto-char (org-element-property :end (org-element-at-point)))))
24689 (let ((element (org-element-at-point)))
24690 (end-of-line)
24691 (push-mark (org-element-property :end element) t t)
24692 (goto-char (org-element-property :begin element))))))
24694 (defun org-narrow-to-element ()
24695 "Narrow buffer to current element."
24696 (interactive)
24697 (let ((elem (org-element-at-point)))
24698 (cond
24699 ((eq (car elem) 'headline)
24700 (narrow-to-region
24701 (org-element-property :begin elem)
24702 (org-element-property :end elem)))
24703 ((memq (car elem) org-element-greater-elements)
24704 (narrow-to-region
24705 (org-element-property :contents-begin elem)
24706 (org-element-property :contents-end elem)))
24708 (narrow-to-region
24709 (org-element-property :begin elem)
24710 (org-element-property :end elem))))))
24712 (defun org-transpose-element ()
24713 "Transpose current and previous elements, keeping blank lines between.
24714 Point is moved after both elements."
24715 (interactive)
24716 (org-skip-whitespace)
24717 (let ((end (org-element-property :end (org-element-at-point))))
24718 (org-drag-element-backward)
24719 (goto-char end)))
24721 (defun org-unindent-buffer ()
24722 "Un-indent the visible part of the buffer.
24723 Relative indentation (between items, inside blocks, etc.) isn't
24724 modified."
24725 (interactive)
24726 (unless (eq major-mode 'org-mode)
24727 (user-error "Cannot un-indent a buffer not in Org mode"))
24728 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24729 (unindent-tree
24730 (lambda (contents)
24731 (dolist (element (reverse contents))
24732 (if (memq (org-element-type element) '(headline section))
24733 (funcall unindent-tree (org-element-contents element))
24734 (save-excursion
24735 (save-restriction
24736 (narrow-to-region
24737 (org-element-property :begin element)
24738 (org-element-property :end element))
24739 (org-do-remove-indentation))))))))
24740 (funcall unindent-tree (org-element-contents parse-tree))))
24742 (defun org-show-children (&optional level)
24743 "Show all direct subheadings of this heading.
24744 Prefix arg LEVEL is how many levels below the current level
24745 should be shown. Default is enough to cause the following
24746 heading to appear."
24747 (interactive "p")
24748 ;; If `orgstruct-mode' is active, use the slower version.
24749 (if orgstruct-mode (call-interactively #'outline-show-children)
24750 (save-excursion
24751 (org-back-to-heading t)
24752 (let* ((current-level (funcall outline-level))
24753 (max-level (org-get-valid-level
24754 current-level
24755 (if level (prefix-numeric-value level) 1)))
24756 (end (save-excursion (org-end-of-subtree t t)))
24757 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24758 (past-first-child nil)
24759 ;; Make sure to skip inlinetasks.
24760 (re (format regexp-fmt
24761 current-level
24762 (cond
24763 ((not (featurep 'org-inlinetask)) "")
24764 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24766 (t (1- org-inlinetask-min-level))))))
24767 ;; Display parent heading.
24768 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24769 (forward-line)
24770 ;; Display children. First child may be deeper than expected
24771 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24772 ;; MAX-LEVEL accordingly.
24773 (while (re-search-forward re end t)
24774 (unless past-first-child
24775 (setq re (format regexp-fmt
24776 current-level
24777 (max (funcall outline-level) max-level)))
24778 (setq past-first-child t))
24779 (outline-flag-region
24780 (line-end-position 0) (line-end-position) nil))))))
24782 (defun org-show-subtree ()
24783 "Show everything after this heading at deeper levels."
24784 (interactive)
24785 (outline-flag-region
24786 (point)
24787 (save-excursion
24788 (org-end-of-subtree t t))
24789 nil))
24791 (defun org-show-entry ()
24792 "Show the body directly following this heading.
24793 Show the heading too, if it is currently invisible."
24794 (interactive)
24795 (save-excursion
24796 (ignore-errors
24797 (org-back-to-heading t)
24798 (outline-flag-region
24799 (max (point-min) (1- (point)))
24800 (save-excursion
24801 (if (re-search-forward
24802 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24803 (match-beginning 1)
24804 (point-max)))
24805 nil)
24806 (org-cycle-hide-drawers 'children))))
24808 (defun org-make-options-regexp (kwds &optional extra)
24809 "Make a regular expression for keyword lines.
24810 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24811 when non-nil, is a regexp matching keywords names."
24812 (concat "^[ \t]*#\\+\\("
24813 (regexp-opt kwds)
24814 (and extra (concat (and kwds "\\|") extra))
24815 "\\):[ \t]*\\(.*\\)"))
24817 ;;;; Integration with and fixes for other packages
24819 ;;; Imenu support
24821 (defvar-local org-imenu-markers nil
24822 "All markers currently used by Imenu.")
24824 (defun org-imenu-new-marker (&optional pos)
24825 "Return a new marker for use by Imenu, and remember the marker."
24826 (let ((m (make-marker)))
24827 (move-marker m (or pos (point)))
24828 (push m org-imenu-markers)
24831 (defun org-imenu-get-tree ()
24832 "Produce the index for Imenu."
24833 (dolist (x org-imenu-markers) (move-marker x nil))
24834 (setq org-imenu-markers nil)
24835 (let* ((case-fold-search nil)
24836 (n org-imenu-depth)
24837 (re (concat "^" (org-get-limited-outline-regexp)))
24838 (subs (make-vector (1+ n) nil))
24839 (last-level 0)
24840 m level head0 head)
24841 (org-with-wide-buffer
24842 (goto-char (point-max))
24843 (while (re-search-backward re nil t)
24844 (setq level (org-reduced-level (funcall outline-level)))
24845 (when (and (<= level n)
24846 (looking-at org-complex-heading-regexp)
24847 (setq head0 (match-string-no-properties 4)))
24848 (setq head (org-link-display-format head0)
24849 m (org-imenu-new-marker))
24850 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24851 (if (>= level last-level)
24852 (push (cons head m) (aref subs level))
24853 (push (cons head (aref subs (1+ level))) (aref subs level))
24854 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24855 (setq last-level level))))
24856 (aref subs 1)))
24858 (eval-after-load "imenu"
24859 '(progn
24860 (add-hook 'imenu-after-jump-hook
24861 (lambda ()
24862 (when (derived-mode-p 'org-mode)
24863 (org-show-context 'org-goto))))))
24865 (defun org-link-display-format (s)
24866 "Replace links in string S with their description.
24867 If there is no description, use the link target."
24868 (save-match-data
24869 (replace-regexp-in-string
24870 org-bracket-link-analytic-regexp
24871 (lambda (m)
24872 (if (match-end 5) (match-string 5 m)
24873 (concat (match-string 1 m) (match-string 3 m))))
24874 s nil t)))
24876 (defun org-toggle-link-display ()
24877 "Toggle the literal or descriptive display of links."
24878 (interactive)
24879 (if org-descriptive-links
24880 (progn (org-remove-from-invisibility-spec '(org-link))
24881 (org-restart-font-lock)
24882 (setq org-descriptive-links nil))
24883 (progn (add-to-invisibility-spec '(org-link))
24884 (org-restart-font-lock)
24885 (setq org-descriptive-links t))))
24887 ;; Speedbar support
24889 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24890 "Overlay marking the agenda restriction line in speedbar.")
24891 (overlay-put org-speedbar-restriction-lock-overlay
24892 'face 'org-agenda-restriction-lock)
24893 (overlay-put org-speedbar-restriction-lock-overlay
24894 'help-echo "Agendas are currently limited to this item.")
24895 (delete-overlay org-speedbar-restriction-lock-overlay)
24897 (defun org-speedbar-set-agenda-restriction ()
24898 "Restrict future agenda commands to the location at point in speedbar.
24899 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24900 (interactive)
24901 (require 'org-agenda)
24902 (let (p m tp np dir txt)
24903 (cond
24904 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24905 'org-imenu t))
24906 (setq m (get-text-property p 'org-imenu-marker))
24907 (with-current-buffer (marker-buffer m)
24908 (goto-char m)
24909 (org-agenda-set-restriction-lock 'subtree)))
24910 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24911 'speedbar-function 'speedbar-find-file))
24912 (setq tp (previous-single-property-change
24913 (1+ p) 'speedbar-function)
24914 np (next-single-property-change
24915 tp 'speedbar-function)
24916 dir (speedbar-line-directory)
24917 txt (buffer-substring-no-properties (or tp (point-min))
24918 (or np (point-max))))
24919 (with-current-buffer (find-file-noselect
24920 (let ((default-directory dir))
24921 (expand-file-name txt)))
24922 (unless (derived-mode-p 'org-mode)
24923 (user-error "Cannot restrict to non-Org-mode file"))
24924 (org-agenda-set-restriction-lock 'file)))
24925 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24926 (move-overlay org-speedbar-restriction-lock-overlay
24927 (point-at-bol) (point-at-eol))
24928 (setq current-prefix-arg nil)
24929 (org-agenda-maybe-redo)))
24931 (defvar speedbar-file-key-map)
24932 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24933 (eval-after-load "speedbar"
24934 '(progn
24935 (speedbar-add-supported-extension ".org")
24936 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24937 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24938 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24939 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24940 (add-hook 'speedbar-visiting-tag-hook
24941 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24943 ;;; Fixes and Hacks for problems with other packages
24945 (defun org--flyspell-object-check-p (element)
24946 "Non-nil when Flyspell can check object at point.
24947 ELEMENT is the element at point."
24948 (let ((object (save-excursion
24949 (when (looking-at-p "\\>") (backward-char))
24950 (org-element-context element))))
24951 (cl-case (org-element-type object)
24952 ;; Prevent checks in links due to keybinding conflict with
24953 ;; Flyspell.
24954 ((code entity export-snippet inline-babel-call
24955 inline-src-block line-break latex-fragment link macro
24956 statistics-cookie target timestamp verbatim)
24957 nil)
24958 (footnote-reference
24959 ;; Only in inline footnotes, within the definition.
24960 (and (eq (org-element-property :type object) 'inline)
24961 (< (save-excursion
24962 (goto-char (org-element-property :begin object))
24963 (search-forward ":" nil t 2))
24964 (point))))
24965 (otherwise t))))
24967 (defun org-mode-flyspell-verify ()
24968 "Function used for `flyspell-generic-check-word-predicate'."
24969 (if (org-at-heading-p)
24970 ;; At a headline or an inlinetask, check title only. This is
24971 ;; faster than relying on `org-element-at-point'.
24972 (and (save-excursion (beginning-of-line)
24973 (and (let ((case-fold-search t))
24974 (not (looking-at "\\*+ END[ \t]*$")))
24975 (looking-at org-complex-heading-regexp)))
24976 (match-beginning 4)
24977 (>= (point) (match-beginning 4))
24978 (or (not (match-beginning 5))
24979 (< (point) (match-beginning 5))))
24980 (let* ((element (org-element-at-point))
24981 (post-affiliated (org-element-property :post-affiliated element)))
24982 (cond
24983 ;; Ignore checks in all affiliated keywords but captions.
24984 ((< (point) post-affiliated)
24985 (and (save-excursion
24986 (beginning-of-line)
24987 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24988 (> (point) (match-end 0))
24989 (org--flyspell-object-check-p element)))
24990 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24991 ((let ((log (org-log-into-drawer)))
24992 (and log
24993 (let ((drawer (org-element-lineage element '(drawer))))
24994 (and drawer
24995 (eq (compare-strings
24996 log nil nil
24997 (org-element-property :drawer-name drawer) nil nil t)
24998 t)))))
24999 nil)
25001 (cl-case (org-element-type element)
25002 ((comment quote-section) t)
25003 (comment-block
25004 ;; Allow checks between block markers, not on them.
25005 (and (> (line-beginning-position) post-affiliated)
25006 (save-excursion
25007 (end-of-line)
25008 (skip-chars-forward " \r\t\n")
25009 (< (point) (org-element-property :end element)))))
25010 ;; Arbitrary list of keywords where checks are meaningful.
25011 ;; Make sure point is on the value part of the element.
25012 (keyword
25013 (and (member (org-element-property :key element)
25014 '("DESCRIPTION" "TITLE"))
25015 (save-excursion
25016 (search-backward ":" (line-beginning-position) t))))
25017 ;; Check is globally allowed in paragraphs verse blocks and
25018 ;; table rows (after affiliated keywords) but some objects
25019 ;; must not be affected.
25020 ((paragraph table-row verse-block)
25021 (let ((cbeg (org-element-property :contents-begin element))
25022 (cend (org-element-property :contents-end element)))
25023 (and cbeg (>= (point) cbeg) (< (point) cend)
25024 (org--flyspell-object-check-p element))))))))))
25025 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25027 (defun org-remove-flyspell-overlays-in (beg end)
25028 "Remove flyspell overlays in region."
25029 (and (bound-and-true-p flyspell-mode)
25030 (fboundp 'flyspell-delete-region-overlays)
25031 (flyspell-delete-region-overlays beg end)))
25033 (defvar flyspell-delayed-commands)
25034 (eval-after-load "flyspell"
25035 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25037 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25038 (eval-after-load "bookmark"
25039 '(if (boundp 'bookmark-after-jump-hook)
25040 ;; We can use the hook
25041 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25042 ;; Hook not available, use advice
25043 (defadvice bookmark-jump (after org-make-visible activate)
25044 "Make the position visible."
25045 (org-bookmark-jump-unhide))))
25047 ;; Make sure saveplace shows the location if it was hidden
25048 (eval-after-load "saveplace"
25049 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25050 "Make the position visible."
25051 (org-bookmark-jump-unhide)))
25053 ;; Make sure ecb shows the location if it was hidden
25054 (eval-after-load "ecb"
25055 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25056 "Make hierarchy visible when jumping into location from ECB tree buffer."
25057 (when (derived-mode-p 'org-mode)
25058 (org-show-context))))
25060 (defun org-bookmark-jump-unhide ()
25061 "Unhide the current position, to show the bookmark location."
25062 (and (derived-mode-p 'org-mode)
25063 (or (outline-invisible-p)
25064 (save-excursion (goto-char (max (point-min) (1- (point))))
25065 (outline-invisible-p)))
25066 (org-show-context 'bookmark-jump)))
25068 (defun org-mark-jump-unhide ()
25069 "Make the point visible with `org-show-context' after jumping to the mark."
25070 (when (and (derived-mode-p 'org-mode)
25071 (outline-invisible-p))
25072 (org-show-context 'mark-goto)))
25074 (eval-after-load "simple"
25075 '(defadvice pop-to-mark-command (after org-make-visible activate)
25076 "Make the point visible with `org-show-context'."
25077 (org-mark-jump-unhide)))
25079 (eval-after-load "simple"
25080 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25081 "Make the point visible with `org-show-context'."
25082 (org-mark-jump-unhide)))
25084 (eval-after-load "simple"
25085 '(defadvice pop-global-mark (after org-make-visible activate)
25086 "Make the point visible with `org-show-context'."
25087 (org-mark-jump-unhide)))
25089 ;; Make session.el ignore our circular variable
25090 (defvar session-globals-exclude)
25091 (eval-after-load "session"
25092 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25094 ;;;; Finish up
25096 (provide 'org)
25098 (run-hooks 'org-load-hook)
25100 ;;; org.el ends here