org-compat: Silence byte-compiler
[org-mode.git] / lisp / org.el
bloba3b3b0133ccdc25d26aa386c9a5d0ad33773a718
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 (equal 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-edit-field "org-table" (arg))
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function org-table-next-row "org-table" ())
167 (declare-function org-table-paste-rectangle "org-table" ())
168 (declare-function org-table-wrap-region "org-table" (arg))
169 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
170 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
171 (declare-function orgtbl-mode "org-table" (&optional arg))
173 (defsubst org-uniquify (list)
174 "Non-destructively remove duplicate elements from LIST."
175 (let ((res (copy-sequence list))) (delete-dups res)))
177 (defsubst org-get-at-bol (property)
178 "Get text property PROPERTY at the beginning of line."
179 (get-text-property (point-at-bol) property))
181 (defsubst org-trim (s &optional keep-lead)
182 "Remove whitespace at the beginning and the end of string S.
183 When optional argument KEEP-LEAD is non-nil, removing blank lines
184 at the beginning of the string does not affect leading indentation."
185 (replace-regexp-in-string
186 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
187 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "IO" io)
267 (const :tag "J" J)
268 (const :tag "Java" java)
269 (const :tag "Javascript" js)
270 (const :tag "LaTeX" latex)
271 (const :tag "Ledger" ledger)
272 (const :tag "Lilypond" lilypond)
273 (const :tag "Lisp" lisp)
274 (const :tag "Makefile" makefile)
275 (const :tag "Maxima" maxima)
276 (const :tag "Matlab" matlab)
277 (const :tag "Mscgen" mscgen)
278 (const :tag "Ocaml" ocaml)
279 (const :tag "Octave" octave)
280 (const :tag "Org" org)
281 (const :tag "Perl" perl)
282 (const :tag "Pico Lisp" picolisp)
283 (const :tag "PlantUML" plantuml)
284 (const :tag "Python" python)
285 (const :tag "Ruby" ruby)
286 (const :tag "Sass" sass)
287 (const :tag "Scala" scala)
288 (const :tag "Scheme" scheme)
289 (const :tag "Screen" screen)
290 (const :tag "Shell Script" shell)
291 (const :tag "Shen" shen)
292 (const :tag "Sql" sql)
293 (const :tag "Sqlite" sqlite)
294 (const :tag "Stan" stan)
295 (const :tag "ebnf2ps" ebnf2ps))
296 :value-type (boolean :tag "Activate" :value t)))
298 ;;;; Customization variables
299 (defcustom org-clone-delete-id nil
300 "Remove ID property of clones of a subtree.
301 When non-nil, clones of a subtree don't inherit the ID property.
302 Otherwise they inherit the ID property with a new unique
303 identifier."
304 :type 'boolean
305 :version "24.1"
306 :group 'org-id)
308 ;;; Version
309 (org-check-version)
311 ;;;###autoload
312 (defun org-version (&optional here full message)
313 "Show the Org version.
314 Interactively, or when MESSAGE is non-nil, show it in echo area.
315 With prefix argument, or when HERE is non-nil, insert it at point.
316 In non-interactive uses, a reduced version string is output unless
317 FULL is given."
318 (interactive (list current-prefix-arg t (not current-prefix-arg)))
319 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
320 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
321 (load-suffixes (list ".el"))
322 (org-install-dir
323 (ignore-errors (org-find-library-dir "org-loaddefs"))))
324 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
325 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
326 (let* ((load-suffixes save-load-suffixes)
327 (release (org-release))
328 (git-version (org-git-version))
329 (version (format "Org-mode version %s (%s @ %s)"
330 release
331 git-version
332 (if org-install-dir
333 (if (string= org-dir org-install-dir)
334 org-install-dir
335 (concat "mixed installation! "
336 org-install-dir
337 " and "
338 org-dir))
339 "org-loaddefs.el can not be found!")))
340 (version1 (if full version release)))
341 (when here (insert version1))
342 (when message (message "%s" version1))
343 version1)))
345 (defconst org-version (org-version))
348 ;;; Syntax Constants
350 ;;;; Block
352 (defconst org-block-regexp
353 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
354 "Regular expression for hiding blocks.")
356 (defconst org-dblock-start-re
357 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
358 "Matches the start line of a dynamic block, with parameters.")
360 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
361 "Matches the end of a dynamic block.")
363 ;;;; Clock and Planning
365 (defconst org-clock-string "CLOCK:"
366 "String used as prefix for timestamps clocking work hours on an item.")
368 (defvar org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry.")
371 (defvar org-deadline-string "DEADLINE:"
372 "String to mark deadline entries.
373 A deadline is this string, followed by a time stamp. Should be a word,
374 terminated by a colon. You can insert a schedule keyword and
375 a timestamp with \\[org-deadline].")
377 (defvar org-scheduled-string "SCHEDULED:"
378 "String to mark scheduled TODO entries.
379 A schedule is this string, followed by a time stamp. Should be a word,
380 terminated by a colon. You can insert a schedule keyword and
381 a timestamp with \\[org-schedule].")
383 (defconst org-ds-keyword-length
384 (+ 2
385 (apply #'max
386 (mapcar #'length
387 (list org-deadline-string org-scheduled-string
388 org-clock-string org-closed-string))))
389 "Maximum length of the DEADLINE and SCHEDULED keywords.")
391 (defconst org-planning-line-re
392 (concat "^[ \t]*"
393 (regexp-opt
394 (list org-closed-string org-deadline-string org-scheduled-string)
396 "Matches a line with planning info.
397 Matched keyword is in group 1.")
399 (defconst org-clock-line-re
400 (concat "^[ \t]*" org-clock-string)
401 "Matches a line with clock info.")
403 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
404 "Matches the DEADLINE keyword.")
406 (defconst org-deadline-time-regexp
407 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
408 "Matches the DEADLINE keyword together with a time stamp.")
410 (defconst org-deadline-time-hour-regexp
411 (concat "\\<" org-deadline-string
412 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
413 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
415 (defconst org-deadline-line-regexp
416 (concat "\\<\\(" org-deadline-string "\\).*")
417 "Matches the DEADLINE keyword and the rest of the line.")
419 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
420 "Matches the SCHEDULED keyword.")
422 (defconst org-scheduled-time-regexp
423 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
424 "Matches the SCHEDULED keyword together with a time stamp.")
426 (defconst org-scheduled-time-hour-regexp
427 (concat "\\<" org-scheduled-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
431 (defconst org-closed-time-regexp
432 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
433 "Matches the CLOSED keyword together with a time stamp.")
435 (defconst org-keyword-time-regexp
436 (concat "\\<"
437 (regexp-opt
438 (list org-scheduled-string org-deadline-string org-closed-string
439 org-clock-string)
441 " *[[<]\\([^]>]+\\)[]>]")
442 "Matches any of the 4 keywords, together with the time stamp.")
444 (defconst org-keyword-time-not-clock-regexp
445 (concat
446 "\\<"
447 (regexp-opt
448 (list org-scheduled-string org-deadline-string org-closed-string) t)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 3 keywords, together with the time stamp.")
452 (defconst org-maybe-keyword-time-regexp
453 (concat "\\(\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string
456 org-clock-string)
458 "\\)?"
459 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
460 "\\|"
461 "<%%([^\r\n>]*>\\)")
462 "Matches a timestamp, possibly preceded by a keyword.")
464 (defconst org-all-time-keywords
465 (mapcar (lambda (w) (substring w 0 -1))
466 (list org-scheduled-string org-deadline-string
467 org-clock-string org-closed-string))
468 "List of time keywords.")
470 ;;;; Drawer
472 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
473 "Matches first or last line of a hidden block.
474 Group 1 contains drawer's name or \"END\".")
476 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
477 "Regular expression matching the first line of a property drawer.")
479 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
480 "Regular expression matching the last line of a property drawer.")
482 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
483 "Regular expression matching the first line of a clock drawer.")
485 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
486 "Regular expression matching the last line of a clock drawer.")
488 (defconst org-property-drawer-re
489 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
490 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
491 "[ \t]*:END:[ \t]*$")
492 "Matches an entire property drawer.")
494 (defconst org-clock-drawer-re
495 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
496 org-clock-drawer-end-re "\\)\n?")
497 "Matches an entire clock drawer.")
499 ;;;; Headline
501 (defconst org-heading-keyword-regexp-format
502 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
503 "Printf format for a regexp matching a headline with some keyword.
504 This regexp will match the headline of any node which has the
505 exact keyword that is put into the format. The keyword isn't in
506 any group by default, but the stars and the body are.")
508 (defconst org-heading-keyword-maybe-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline, possibly with some keyword.
511 This regexp can match any headline with the specified keyword, or
512 without a keyword. The keyword isn't in any group by default,
513 but the stars and the body are.")
515 (defconst org-archive-tag "ARCHIVE"
516 "The tag that marks a subtree as archived.
517 An archived subtree does not open during visibility cycling, and does
518 not contribute to the agenda listings.")
520 (defconst org-comment-string "COMMENT"
521 "Entries starting with this keyword will never be exported.
522 An entry can be toggled between COMMENT and normal with
523 \\[org-toggle-comment].")
526 ;;;; LaTeX Environments and Fragments
528 (defconst org-latex-regexps
529 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
530 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
531 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
532 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
533 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
534 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
535 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
536 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
537 "Regular expressions for matching embedded LaTeX.")
539 ;;;; Node Property
541 (defconst org-effort-property "Effort"
542 "The property that is being used to keep track of effort estimates.
543 Effort estimates given in this property need to have the format H:MM.")
545 ;;;; Table
547 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
548 "Detect an org-type or table-type table.")
550 (defconst org-table-line-regexp "^[ \t]*|"
551 "Detect an org-type table line.")
553 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
554 "Detect an org-type table line.")
556 (defconst org-table-hline-regexp "^[ \t]*|-"
557 "Detect an org-type table hline.")
559 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
560 "Detect a table-type table hline.")
562 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
563 "Detect the first line outside a table when searching from within it.
564 This works for both table types.")
566 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
567 "Detect a #+TBLFM line.")
569 ;;;; Timestamp
571 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
572 "Regular expression for fast time stamp matching.")
574 (defconst org-ts-regexp-inactive
575 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
576 "Regular expression for fast inactive time stamp matching.")
578 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
579 "Regular expression for fast time stamp matching.")
581 (defconst org-ts-regexp0
582 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
583 "Regular expression matching time strings for analysis.
584 This one does not require the space after the date, so it can be used
585 on a string that terminates immediately after the date.")
587 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.")
590 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
591 "Regular expression matching time stamps, with groups.")
593 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
594 "Regular expression matching time stamps (also [..]), with groups.")
596 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tr-regexp-both
600 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
601 "Regular expression matching a time stamp range.")
603 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
604 org-ts-regexp "\\)?")
605 "Regular expression matching a time stamp or time stamp range.")
607 (defconst org-tsr-regexp-both
608 (concat org-ts-regexp-both "\\(--?-?"
609 org-ts-regexp-both "\\)?")
610 "Regular expression matching a time stamp or time stamp range.
611 The time stamps may be either active or inactive.")
613 (defconst org-repeat-re
614 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
615 "Regular expression for specifying repeated events.
616 After a match, group 1 contains the repeat expression.")
618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
619 "Formats for `format-time-string' which are used for time stamps.")
622 ;;; The custom variables
624 (defgroup org nil
625 "Outline-based notes management and organizer."
626 :tag "Org"
627 :group 'outlines
628 :group 'calendar)
630 (defcustom org-mode-hook nil
631 "Mode hook for Org-mode, run after the mode was turned on."
632 :group 'org
633 :type 'hook)
635 (defcustom org-load-hook nil
636 "Hook that is run after org.el has been loaded."
637 :group 'org
638 :type 'hook)
640 (defcustom org-log-buffer-setup-hook nil
641 "Hook that is run after an Org log buffer is created."
642 :group 'org
643 :version "24.1"
644 :type 'hook)
646 (defvar org-modules) ; defined below
647 (defvar org-modules-loaded nil
648 "Have the modules been loaded already?")
650 (defun org-load-modules-maybe (&optional force)
651 "Load all extensions listed in `org-modules'."
652 (when (or force (not org-modules-loaded))
653 (dolist (ext org-modules)
654 (condition-case nil (require ext)
655 (error (message "Problems while trying to load feature `%s'" ext))))
656 (setq org-modules-loaded t)))
658 (defun org-set-modules (var value)
659 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
660 (set var value)
661 (when (featurep 'org)
662 (org-load-modules-maybe 'force)
663 (org-element-cache-reset 'all)))
665 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
666 "Modules that should always be loaded together with org.el.
668 If a description starts with <C>, the file is not part of Emacs
669 and loading it will require that you have downloaded and properly
670 installed the Org mode distribution.
672 You can also use this system to load external packages (i.e. neither Org
673 core modules, nor modules from the CONTRIB directory). Just add symbols
674 to the end of the list. If the package is called org-xyz.el, then you need
675 to add the symbol `xyz', and the package must have a call to:
677 (provide \\='org-xyz)
679 For export specific modules, see also `org-export-backends'."
680 :group 'org
681 :set 'org-set-modules
682 :version "24.4"
683 :package-version '(Org . "8.0")
684 :type
685 '(set :greedy t
686 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
687 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
688 (const :tag " crypt: Encryption of subtrees" org-crypt)
689 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
690 (const :tag " docview: Links to doc-view buffers" org-docview)
691 (const :tag " eww: Store link to url of eww" org-eww)
692 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
693 (const :tag " habit: Track your consistency with habits" org-habit)
694 (const :tag " id: Global IDs for identifying entries" org-id)
695 (const :tag " info: Links to Info nodes" org-info)
696 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
697 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
698 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
699 (const :tag " mouse: Additional mouse support" org-mouse)
700 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
701 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
702 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
704 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
705 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
706 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
707 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
708 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
709 (const :tag "C collector: Collect properties into tables" org-collector)
710 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
711 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
712 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
713 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
714 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
715 (const :tag "C eval: Include command output as text" org-eval)
716 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
717 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
718 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
719 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
720 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
721 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
722 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
723 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
724 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
725 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
726 (const :tag "C mew: Links to Mew folders/messages" org-mew)
727 (const :tag "C mtags: Support for muse-like tags" org-mtags)
728 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
729 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
730 (const :tag "C registry: A registry for Org links" org-registry)
731 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
732 (const :tag "C secretary: Team management with org-mode" org-secretary)
733 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
734 (const :tag "C toc: Table of contents for Org buffer" org-toc)
735 (const :tag "C track: Keep up with Org mode development" org-track)
736 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
737 (const :tag "C vm: Links to VM folders/messages" org-vm)
738 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
739 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
740 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
742 (defvar org-export-registered-backends) ; From ox.el.
743 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
744 (declare-function org-export-backend-name "ox" (backend) t)
745 (defcustom org-export-backends '(ascii html icalendar latex odt)
746 "List of export back-ends that should be always available.
748 If a description starts with <C>, the file is not part of Emacs
749 and loading it will require that you have downloaded and properly
750 installed the Org mode distribution.
752 Unlike to `org-modules', libraries in this list will not be
753 loaded along with Org, but only once the export framework is
754 needed.
756 This variable needs to be set before org.el is loaded. If you
757 need to make a change while Emacs is running, use the customize
758 interface or run the following code, where VAL stands for the new
759 value of the variable, after updating it:
761 (progn
762 (setq org-export-registered-backends
763 (cl-remove-if-not
764 (lambda (backend)
765 (let ((name (org-export-backend-name backend)))
766 (or (memq name val)
767 (catch \\='parentp
768 (dolist (b val)
769 (and (org-export-derived-backend-p b name)
770 (throw \\='parentp t)))))))
771 org-export-registered-backends))
772 (let ((new-list (mapcar #\\='org-export-backend-name
773 org-export-registered-backends)))
774 (dolist (backend val)
775 (cond
776 ((not (load (format \"ox-%s\" backend) t t))
777 (message \"Problems while trying to load export back-end \\=`%s\\='\"
778 backend))
779 ((not (memq backend new-list)) (push backend new-list))))
780 (set-default \\='org-export-backends new-list)))
782 Adding a back-end to this list will also pull the back-end it
783 depends on, if any."
784 :group 'org
785 :group 'org-export
786 :version "25.1"
787 :package-version '(Org . "9.0")
788 :initialize 'custom-initialize-set
789 :set (lambda (var val)
790 (if (not (featurep 'ox)) (set-default var val)
791 ;; Any back-end not required anymore (not present in VAL and not
792 ;; a parent of any back-end in the new value) is removed from the
793 ;; list of registered back-ends.
794 (setq org-export-registered-backends
795 (cl-remove-if-not
796 (lambda (backend)
797 (let ((name (org-export-backend-name backend)))
798 (or (memq name val)
799 (catch 'parentp
800 (dolist (b val)
801 (and (org-export-derived-backend-p b name)
802 (throw 'parentp t)))))))
803 org-export-registered-backends))
804 ;; Now build NEW-LIST of both new back-ends and required
805 ;; parents.
806 (let ((new-list (mapcar #'org-export-backend-name
807 org-export-registered-backends)))
808 (dolist (backend val)
809 (cond
810 ((not (load (format "ox-%s" backend) t t))
811 (message "Problems while trying to load export back-end `%s'"
812 backend))
813 ((not (memq backend new-list)) (push backend new-list))))
814 ;; Set VAR to that list with fixed dependencies.
815 (set-default var new-list))))
816 :type '(set :greedy t
817 (const :tag " ascii Export buffer to ASCII format" ascii)
818 (const :tag " beamer Export buffer to Beamer presentation" beamer)
819 (const :tag " html Export buffer to HTML format" html)
820 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
821 (const :tag " latex Export buffer to LaTeX format" latex)
822 (const :tag " man Export buffer to MAN format" man)
823 (const :tag " md Export buffer to Markdown format" md)
824 (const :tag " odt Export buffer to ODT format" odt)
825 (const :tag " org Export buffer to Org format" org)
826 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
827 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
828 (const :tag "C deck Export buffer to deck.js presentations" deck)
829 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
830 (const :tag "C groff Export buffer to Groff format" groff)
831 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
832 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
833 (const :tag "C s5 Export buffer to s5 presentations" s5)
834 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
836 (eval-after-load 'ox
837 '(dolist (backend org-export-backends)
838 (condition-case nil (require (intern (format "ox-%s" backend)))
839 (error (message "Problems while trying to load export back-end `%s'"
840 backend)))))
842 (defcustom org-support-shift-select nil
843 "Non-nil means make shift-cursor commands select text when possible.
844 \\<org-mode-map>\
846 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
847 start selecting a region, or enlarge regions started in this way.
848 In Org-mode, in special contexts, these same keys are used for
849 other purposes, important enough to compete with shift selection.
850 Org tries to balance these needs by supporting `shift-select-mode'
851 outside these special contexts, under control of this variable.
853 The default of this variable is nil, to avoid confusing behavior. Shifted
854 cursor keys will then execute Org commands in the following contexts:
855 - on a headline, changing TODO state (left/right) and priority (up/down)
856 - on a time stamp, changing the time
857 - in a plain list item, changing the bullet type
858 - in a property definition line, switching between allowed values
859 - in the BEGIN line of a clock table (changing the time block).
860 Outside these contexts, the commands will throw an error.
862 When this variable is t and the cursor is not in a special
863 context, Org mode will support shift-selection for making and
864 enlarging regions. To make this more effective, the bullet
865 cycling will no longer happen anywhere in an item line, but only
866 if the cursor is exactly on the bullet.
868 If you set this variable to the symbol `always', then the keys
869 will not be special in headlines, property lines, and item lines,
870 to make shift selection work there as well. If this is what you
871 want, you can use the following alternative commands:
872 `\\[org-todo]' and `\\[org-priority]' \
873 to change TODO state and priority,
874 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
875 can be used to switch TODO sets,
876 `\\[org-ctrl-c-minus]' to cycle item bullet types,
877 and properties can be edited by hand or in column view.
879 However, when the cursor is on a timestamp, shift-cursor commands
880 will still edit the time stamp - this is just too good to give up."
881 :group 'org
882 :type '(choice
883 (const :tag "Never" nil)
884 (const :tag "When outside special context" t)
885 (const :tag "Everywhere except timestamps" always)))
887 (defcustom org-loop-over-headlines-in-active-region nil
888 "Shall some commands act upon headlines in the active region?
890 When set to t, some commands will be performed in all headlines
891 within the active region.
893 When set to `start-level', some commands will be performed in all
894 headlines within the active region, provided that these headlines
895 are of the same level than the first one.
897 When set to a string, those commands will be performed on the
898 matching headlines within the active region. Such string must be
899 a tags/property/todo match as it is used in the agenda tags view.
901 The list of commands is: `org-schedule', `org-deadline',
902 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
903 `org-archive-to-archive-sibling'. The archiving commands skip
904 already archived entries."
905 :type '(choice (const :tag "Don't loop" nil)
906 (const :tag "All headlines in active region" t)
907 (const :tag "In active region, headlines at the same level than the first one" start-level)
908 (string :tag "Tags/Property/Todo matcher"))
909 :version "24.1"
910 :group 'org-todo
911 :group 'org-archive)
913 (defgroup org-startup nil
914 "Options concerning startup of Org-mode."
915 :tag "Org Startup"
916 :group 'org)
918 (defcustom org-startup-folded t
919 "Non-nil means entering Org mode will switch to OVERVIEW.
920 This can also be configured on a per-file basis by adding one of
921 the following lines anywhere in the buffer:
923 #+STARTUP: fold (or `overview', this is equivalent)
924 #+STARTUP: nofold (or `showall', this is equivalent)
925 #+STARTUP: content
926 #+STARTUP: showeverything
928 By default, this option is ignored when Org opens agenda files
929 for the first time. If you want the agenda to honor the startup
930 option, set `org-agenda-inhibit-startup' to nil."
931 :group 'org-startup
932 :type '(choice
933 (const :tag "nofold: show all" nil)
934 (const :tag "fold: overview" t)
935 (const :tag "content: all headlines" content)
936 (const :tag "show everything, even drawers" showeverything)))
938 (defcustom org-startup-truncated t
939 "Non-nil means entering Org mode will set `truncate-lines'.
940 This is useful since some lines containing links can be very long and
941 uninteresting. Also tables look terrible when wrapped.
943 The variable `org-startup-truncated' allows to configure
944 truncation for Org mode different to the other modes that use the
945 variable `truncate-lines' and as a shortcut instead of putting
946 the variable `truncate-lines' into the `org-mode-hook'. If one
947 wants to configure truncation for Org mode not statically but
948 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
949 the variable `truncate-lines' has to be used because in such a
950 case it is too late to set the variable `org-startup-truncated'."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-startup-indented nil
955 "Non-nil means turn on `org-indent-mode' on startup.
956 This can also be configured on a per-file basis by adding one of
957 the following lines anywhere in the buffer:
959 #+STARTUP: indent
960 #+STARTUP: noindent"
961 :group 'org-structure
962 :type '(choice
963 (const :tag "Not" nil)
964 (const :tag "Globally (slow on startup in large files)" t)))
966 (defcustom org-use-sub-superscripts t
967 "Non-nil means interpret \"_\" and \"^\" for display.
969 If you want to control how Org exports those characters, see
970 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
971 used to be an alias for `org-export-with-sub-superscripts' in
972 Org <8.0, it is not anymore.
974 When this option is turned on, you can use TeX-like syntax for
975 sub- and superscripts within the buffer. Several characters after
976 \"_\" or \"^\" will be considered as a single item - so grouping
977 with {} is normally not needed. For example, the following things
978 will be parsed as single sub- or superscripts:
980 10^24 or 10^tau several digits will be considered 1 item.
981 10^-12 or 10^-tau a leading sign with digits or a word
982 x^2-y^3 will be read as x^2 - y^3, because items are
983 terminated by almost any nonword/nondigit char.
984 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
986 Still, ambiguity is possible. So when in doubt, use {} to enclose
987 the sub/superscript. If you set this variable to the symbol `{}',
988 the braces are *required* in order to trigger interpretations as
989 sub/superscript. This can be helpful in documents that need \"_\"
990 frequently in plain text."
991 :group 'org-startup
992 :version "24.4"
993 :package-version '(Org . "8.0")
994 :type '(choice
995 (const :tag "Always interpret" t)
996 (const :tag "Only with braces" {})
997 (const :tag "Never interpret" nil)))
999 (defcustom org-startup-with-beamer-mode nil
1000 "Non-nil means turn on `org-beamer-mode' on startup.
1001 This can also be configured on a per-file basis by adding one of
1002 the following lines anywhere in the buffer:
1004 #+STARTUP: beamer"
1005 :group 'org-startup
1006 :version "24.1"
1007 :type 'boolean)
1009 (defcustom org-startup-align-all-tables nil
1010 "Non-nil means align all tables when visiting a file.
1011 This is useful when the column width in tables is forced with <N> cookies
1012 in table fields. Such tables will look correct only after the first re-align.
1013 This can also be configured on a per-file basis by adding one of
1014 the following lines anywhere in the buffer:
1015 #+STARTUP: align
1016 #+STARTUP: noalign"
1017 :group 'org-startup
1018 :type 'boolean)
1020 (defcustom org-startup-with-inline-images nil
1021 "Non-nil means show inline images when loading a new Org file.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: inlineimages
1025 #+STARTUP: noinlineimages"
1026 :group 'org-startup
1027 :version "24.1"
1028 :type 'boolean)
1030 (defcustom org-startup-with-latex-preview nil
1031 "Non-nil means preview LaTeX fragments when loading a new Org file.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: latexpreview
1036 #+STARTUP: nolatexpreview"
1037 :group 'org-startup
1038 :version "24.4"
1039 :package-version '(Org . "8.0")
1040 :type 'boolean)
1042 (defcustom org-insert-mode-line-in-empty-file nil
1043 "Non-nil means insert the first line setting Org mode in empty files.
1044 When the function `org-mode' is called interactively in an empty file, this
1045 normally means that the file name does not automatically trigger Org mode.
1046 To ensure that the file will always be in Org mode in the future, a
1047 line enforcing Org mode will be inserted into the buffer, if this option
1048 has been set."
1049 :group 'org-startup
1050 :type 'boolean)
1052 (defcustom org-replace-disputed-keys nil
1053 "Non-nil means use alternative key bindings for some keys.
1054 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1055 These keys are also used by other packages like shift-selection-mode'
1056 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1057 If you want to use Org mode together with one of these other modes,
1058 or more generally if you would like to move some Org mode commands to
1059 other keys, set this variable and configure the keys with the variable
1060 `org-disputed-keys'.
1062 This option is only relevant at load-time of Org-mode, and must be set
1063 *before* org.el is loaded. Changing it requires a restart of Emacs to
1064 become effective."
1065 :group 'org-startup
1066 :type 'boolean)
1068 (defcustom org-use-extra-keys nil
1069 "Non-nil means use extra key sequence definitions for certain commands.
1070 This happens automatically if `window-system' is nil. This
1071 variable lets you do the same manually. You must set it before
1072 loading Org."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1078 (defcustom org-disputed-keys
1079 '(([(shift up)] . [(meta p)])
1080 ([(shift down)] . [(meta n)])
1081 ([(shift left)] . [(meta -)])
1082 ([(shift right)] . [(meta +)])
1083 ([(control shift right)] . [(meta shift +)])
1084 ([(control shift left)] . [(meta shift -)]))
1085 "Keys for which Org mode and other modes compete.
1086 This is an alist, cars are the default keys, second element specifies
1087 the alternative to use when `org-replace-disputed-keys' is t.
1089 Keys can be specified in any syntax supported by `define-key'.
1090 The value of this option takes effect only at Org-mode's startup,
1091 therefore you'll have to restart Emacs to apply it after changing."
1092 :group 'org-startup
1093 :type 'alist)
1095 (defun org-key (key)
1096 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1097 Or return the original if not disputed."
1098 (when org-replace-disputed-keys
1099 (let* ((nkey (key-description key))
1100 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1101 org-disputed-keys)))
1102 (setq key (if x (cdr x) key))))
1103 key)
1105 (defun org-defkey (keymap key def)
1106 "Define a key, possibly translated, as returned by `org-key'."
1107 (define-key keymap (org-key key) def))
1109 (defcustom org-ellipsis nil
1110 "The ellipsis to use in the Org mode outline.
1111 When nil, just use the standard three dots.
1112 When a string, use that string instead.
1113 When a face, use the standard 3 dots, but with the specified face.
1114 The change affects only Org mode (which will then use its own display table).
1115 Changing this requires executing \\[org-mode] in a buffer to become
1116 effective."
1117 :group 'org-startup
1118 :type '(choice (const :tag "Default" nil)
1119 (face :tag "Face" :value org-warning)
1120 (string :tag "String" :value "...#")))
1122 (defvar org-display-table nil
1123 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1125 (defgroup org-keywords nil
1126 "Keywords in Org-mode."
1127 :tag "Org Keywords"
1128 :group 'org)
1130 (defcustom org-closed-keep-when-no-todo nil
1131 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1132 :group 'org-todo
1133 :group 'org-keywords
1134 :version "24.4"
1135 :package-version '(Org . "8.0")
1136 :type 'boolean)
1138 (defgroup org-structure nil
1139 "Options concerning the general structure of Org files."
1140 :tag "Org Structure"
1141 :group 'org)
1143 (defgroup org-reveal-location nil
1144 "Options about how to make context of a location visible."
1145 :tag "Org Reveal Location"
1146 :group 'org-structure)
1148 (defcustom org-show-context-detail '((agenda . local)
1149 (bookmark-jump . lineage)
1150 (isearch . lineage)
1151 (default . ancestors))
1152 "Alist between context and visibility span when revealing a location.
1154 \\<org-mode-map>Some actions may move point into invisible
1155 locations. As a consequence, Org always expose a neighborhood
1156 around point. How much is shown depends on the initial action,
1157 or context. Valid contexts are
1159 agenda when exposing an entry from the agenda
1160 org-goto when using the command `org-goto' (\\[org-goto])
1161 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1162 tags-tree when constructing a sparse tree based on tags matches
1163 link-search when exposing search matches associated with a link
1164 mark-goto when exposing the jump goal of a mark
1165 bookmark-jump when exposing a bookmark location
1166 isearch when exiting from an incremental search
1167 default default for all contexts not set explicitly
1169 Allowed visibility spans are
1171 minimal show current headline; if point is not on headline,
1172 also show entry
1174 local show current headline, entry and next headline
1176 ancestors show current headline and its direct ancestors; if
1177 point is not on headline, also show entry
1179 lineage show current headline, its direct ancestors and all
1180 their children; if point is not on headline, also show
1181 entry and first child
1183 tree show current headline, its direct ancestors and all
1184 their children; if point is not on headline, also show
1185 entry and all children
1187 canonical show current headline, its direct ancestors along with
1188 their entries and children; if point is not located on
1189 the headline, also show current entry and all children
1191 As special cases, a nil or t value means show all contexts in
1192 `minimal' or `canonical' view, respectively.
1194 Some views can make displayed information very compact, but also
1195 make it harder to edit the location of the match. In such
1196 a case, use the command `org-reveal' (\\[org-reveal]) to show
1197 more context."
1198 :group 'org-reveal-location
1199 :version "25.2"
1200 :package-version '(Org . "9.0")
1201 :type '(choice
1202 (const :tag "Canonical" t)
1203 (const :tag "Minimal" nil)
1204 (repeat :greedy t :tag "Individual contexts"
1205 (cons
1206 (choice :tag "Context"
1207 (const agenda)
1208 (const org-goto)
1209 (const occur-tree)
1210 (const tags-tree)
1211 (const link-search)
1212 (const mark-goto)
1213 (const bookmark-jump)
1214 (const isearch)
1215 (const default))
1216 (choice :tag "Detail level"
1217 (const minimal)
1218 (const local)
1219 (const ancestors)
1220 (const lineage)
1221 (const tree)
1222 (const canonical))))))
1224 (defcustom org-indirect-buffer-display 'other-window
1225 "How should indirect tree buffers be displayed?
1226 This applies to indirect buffers created with the commands
1227 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1228 Valid values are:
1229 current-window Display in the current window
1230 other-window Just display in another window.
1231 dedicated-frame Create one new frame, and re-use it each time.
1232 new-frame Make a new frame each time. Note that in this case
1233 previously-made indirect buffers are kept, and you need to
1234 kill these buffers yourself."
1235 :group 'org-structure
1236 :group 'org-agenda-windows
1237 :type '(choice
1238 (const :tag "In current window" current-window)
1239 (const :tag "In current frame, other window" other-window)
1240 (const :tag "Each time a new frame" new-frame)
1241 (const :tag "One dedicated frame" dedicated-frame)))
1243 (defcustom org-use-speed-commands nil
1244 "Non-nil means activate single letter commands at beginning of a headline.
1245 This may also be a function to test for appropriate locations where speed
1246 commands should be active.
1248 For example, to activate speed commands when the point is on any
1249 star at the beginning of the headline, you can do this:
1251 (setq org-use-speed-commands
1252 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1253 :group 'org-structure
1254 :type '(choice
1255 (const :tag "Never" nil)
1256 (const :tag "At beginning of headline stars" t)
1257 (function)))
1259 (defcustom org-speed-commands-user nil
1260 "Alist of additional speed commands.
1261 This list will be checked before `org-speed-commands-default'
1262 when the variable `org-use-speed-commands' is non-nil
1263 and when the cursor is at the beginning of a headline.
1264 The car if each entry is a string with a single letter, which must
1265 be assigned to `self-insert-command' in the global map.
1266 The cdr is either a command to be called interactively, a function
1267 to be called, or a form to be evaluated.
1268 An entry that is just a list with a single string will be interpreted
1269 as a descriptive headline that will be added when listing the speed
1270 commands in the Help buffer using the `?' speed command."
1271 :group 'org-structure
1272 :type '(repeat :value ("k" . ignore)
1273 (choice :value ("k" . ignore)
1274 (list :tag "Descriptive Headline" (string :tag "Headline"))
1275 (cons :tag "Letter and Command"
1276 (string :tag "Command letter")
1277 (choice
1278 (function)
1279 (sexp))))))
1281 (defcustom org-bookmark-names-plist
1282 '(:last-capture "org-capture-last-stored"
1283 :last-refile "org-refile-last-stored"
1284 :last-capture-marker "org-capture-last-stored-marker")
1285 "Names for bookmarks automatically set by some Org commands.
1286 This can provide strings as names for a number of bookmarks Org sets
1287 automatically. The following keys are currently implemented:
1288 :last-capture
1289 :last-capture-marker
1290 :last-refile
1291 When a key does not show up in the property list, the corresponding bookmark
1292 is not set."
1293 :group 'org-structure
1294 :type 'plist)
1296 (defgroup org-cycle nil
1297 "Options concerning visibility cycling in Org-mode."
1298 :tag "Org Cycle"
1299 :group 'org-structure)
1301 (defcustom org-cycle-skip-children-state-if-no-children t
1302 "Non-nil means skip CHILDREN state in entries that don't have any."
1303 :group 'org-cycle
1304 :type 'boolean)
1306 (defcustom org-cycle-max-level nil
1307 "Maximum level which should still be subject to visibility cycling.
1308 Levels higher than this will, for cycling, be treated as text, not a headline.
1309 When `org-odd-levels-only' is set, a value of N in this variable actually
1310 means 2N-1 stars as the limiting headline.
1311 When nil, cycle all levels.
1312 Note that the limiting level of cycling is also influenced by
1313 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1314 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1315 than its value."
1316 :group 'org-cycle
1317 :type '(choice
1318 (const :tag "No limit" nil)
1319 (integer :tag "Maximum level")))
1321 (defcustom org-hide-block-startup nil
1322 "Non-nil means entering Org mode will fold all blocks.
1323 This can also be set in on a per-file basis with
1325 #+STARTUP: hideblocks
1326 #+STARTUP: showblocks"
1327 :group 'org-startup
1328 :group 'org-cycle
1329 :type 'boolean)
1331 (defcustom org-cycle-global-at-bob nil
1332 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1333 This makes it possible to do global cycling without having to use S-TAB or
1334 \\[universal-argument] TAB. For this special case to work, the first line
1335 of the buffer must not be a headline -- it may be empty or some other text.
1336 When used in this way, `org-cycle-hook' is disabled temporarily to make
1337 sure the cursor stays at the beginning of the buffer. When this option is
1338 nil, don't do anything special at the beginning of the buffer."
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-level-after-item/entry-creation t
1343 "Non-nil means cycle entry level or item indentation in new empty entries.
1345 When the cursor is at the end of an empty headline, i.e., with only stars
1346 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1347 and then all possible ancestor states, before returning to the original state.
1348 This makes data entry extremely fast: M-RET to create a new headline,
1349 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1351 When the cursor is at the end of an empty plain list item, one TAB will
1352 make it a subitem, two or more tabs will back up to make this an item
1353 higher up in the item hierarchy."
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-emulate-tab t
1358 "Where should `org-cycle' emulate TAB.
1359 nil Never
1360 white Only in completely white lines
1361 whitestart Only at the beginning of lines, before the first non-white char
1362 t Everywhere except in headlines
1363 exc-hl-bol Everywhere except at the start of a headline
1364 If TAB is used in a place where it does not emulate TAB, the current subtree
1365 visibility is cycled."
1366 :group 'org-cycle
1367 :type '(choice (const :tag "Never" nil)
1368 (const :tag "Only in completely white lines" white)
1369 (const :tag "Before first char in a line" whitestart)
1370 (const :tag "Everywhere except in headlines" t)
1371 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1373 (defcustom org-cycle-separator-lines 2
1374 "Number of empty lines needed to keep an empty line between collapsed trees.
1375 If you leave an empty line between the end of a subtree and the following
1376 headline, this empty line is hidden when the subtree is folded.
1377 Org mode will leave (exactly) one empty line visible if the number of
1378 empty lines is equal or larger to the number given in this variable.
1379 So the default 2 means at least 2 empty lines after the end of a subtree
1380 are needed to produce free space between a collapsed subtree and the
1381 following headline.
1383 If the number is negative, and the number of empty lines is at least -N,
1384 all empty lines are shown.
1386 Special case: when 0, never leave empty lines in collapsed view."
1387 :group 'org-cycle
1388 :type 'integer)
1389 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1391 (defcustom org-pre-cycle-hook nil
1392 "Hook that is run before visibility cycling is happening.
1393 The function(s) in this hook must accept a single argument which indicates
1394 the new state that will be set right after running this hook. The
1395 argument is a symbol. Before a global state change, it can have the values
1396 `overview', `content', or `all'. Before a local state change, it can have
1397 the values `folded', `children', or `subtree'."
1398 :group 'org-cycle
1399 :type 'hook)
1401 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1402 org-cycle-hide-drawers
1403 org-cycle-show-empty-lines
1404 org-optimize-window-after-visibility-change)
1405 "Hook that is run after `org-cycle' has changed the buffer visibility.
1406 The function(s) in this hook must accept a single argument which indicates
1407 the new state that was set by the most recent `org-cycle' command. The
1408 argument is a symbol. After a global state change, it can have the values
1409 `overview', `contents', or `all'. After a local state change, it can have
1410 the values `folded', `children', or `subtree'."
1411 :group 'org-cycle
1412 :type 'hook
1413 :version "25.1"
1414 :package-version '(Org . "8.3"))
1416 (defgroup org-edit-structure nil
1417 "Options concerning structure editing in Org-mode."
1418 :tag "Org Edit Structure"
1419 :group 'org-structure)
1421 (defcustom org-odd-levels-only nil
1422 "Non-nil means skip even levels and only use odd levels for the outline.
1423 This has the effect that two stars are being added/taken away in
1424 promotion/demotion commands. It also influences how levels are
1425 handled by the exporters.
1426 Changing it requires restart of `font-lock-mode' to become effective
1427 for fontification also in regions already fontified.
1428 You may also set this on a per-file basis by adding one of the following
1429 lines to the buffer:
1431 #+STARTUP: odd
1432 #+STARTUP: oddeven"
1433 :group 'org-edit-structure
1434 :group 'org-appearance
1435 :type 'boolean)
1437 (defcustom org-adapt-indentation t
1438 "Non-nil means adapt indentation to outline node level.
1440 When this variable is set, Org assumes that you write outlines by
1441 indenting text in each node to align with the headline (after the
1442 stars). The following issues are influenced by this variable:
1444 - The indentation is increased by one space in a demotion
1445 command, and decreased by one in a promotion command. However,
1446 in the latter case, if shifting some line in the entry body
1447 would alter document structure (e.g., insert a new headline),
1448 indentation is not changed at all.
1450 - Property drawers and planning information is inserted indented
1451 when this variable is set. When nil, they will not be indented.
1453 - TAB indents a line relative to current level. The lines below
1454 a headline will be indented when this variable is set.
1456 Note that this is all about true indentation, by adding and
1457 removing space characters. See also `org-indent.el' which does
1458 level-dependent indentation in a virtual way, i.e. at display
1459 time in Emacs."
1460 :group 'org-edit-structure
1461 :type 'boolean)
1463 (defcustom org-special-ctrl-a/e nil
1464 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1466 When t, `C-a' will bring back the cursor to the beginning of the
1467 headline text, i.e. after the stars and after a possible TODO
1468 keyword. In an item, this will be the position after bullet and
1469 check-box, if any. When the cursor is already at that position,
1470 another `C-a' will bring it to the beginning of the line.
1472 `C-e' will jump to the end of the headline, ignoring the presence
1473 of tags in the headline. A second `C-e' will then jump to the
1474 true end of the line, after any tags. This also means that, when
1475 this variable is non-nil, `C-e' also will never jump beyond the
1476 end of the heading of a folded section, i.e. not after the
1477 ellipses.
1479 When set to the symbol `reversed', the first `C-a' or `C-e' works
1480 normally, going to the true line boundary first. Only a directly
1481 following, identical keypress will bring the cursor to the
1482 special positions.
1484 This may also be a cons cell where the behavior for `C-a' and
1485 `C-e' is set separately."
1486 :group 'org-edit-structure
1487 :type '(choice
1488 (const :tag "off" nil)
1489 (const :tag "on: after stars/bullet and before tags first" t)
1490 (const :tag "reversed: true line boundary first" reversed)
1491 (cons :tag "Set C-a and C-e separately"
1492 (choice :tag "Special C-a"
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet first" t)
1495 (const :tag "reversed: before stars/bullet first" reversed))
1496 (choice :tag "Special C-e"
1497 (const :tag "off" nil)
1498 (const :tag "on: before tags first" t)
1499 (const :tag "reversed: after tags first" reversed)))))
1500 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1502 (defcustom org-special-ctrl-k nil
1503 "Non-nil means `C-k' will behave specially in headlines.
1504 When nil, `C-k' will call the default `kill-line' command.
1505 When t, the following will happen while the cursor is in the headline:
1507 - When the cursor is at the beginning of a headline, kill the entire
1508 line and possible the folded subtree below the line.
1509 - When in the middle of the headline text, kill the headline up to the tags.
1510 - When after the headline text, kill the tags."
1511 :group 'org-edit-structure
1512 :type 'boolean)
1514 (defcustom org-ctrl-k-protect-subtree nil
1515 "Non-nil means, do not delete a hidden subtree with C-k.
1516 When set to the symbol `error', simply throw an error when C-k is
1517 used to kill (part-of) a headline that has hidden text behind it.
1518 Any other non-nil value will result in a query to the user, if it is
1519 OK to kill that hidden subtree. When nil, kill without remorse."
1520 :group 'org-edit-structure
1521 :version "24.1"
1522 :type '(choice
1523 (const :tag "Do not protect hidden subtrees" nil)
1524 (const :tag "Protect hidden subtrees with a security query" t)
1525 (const :tag "Never kill a hidden subtree with C-k" error)))
1527 (defcustom org-special-ctrl-o t
1528 "Non-nil means, make `C-o' insert a row in tables."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-catch-invisible-edits nil
1533 "Check if in invisible region before inserting or deleting a character.
1534 Valid values are:
1536 nil Do not check, so just do invisible edits.
1537 error Throw an error and do nothing.
1538 show Make point visible, and do the requested edit.
1539 show-and-error Make point visible, then throw an error and abort the edit.
1540 smart Make point visible, and do insertion/deletion if it is
1541 adjacent to visible text and the change feels predictable.
1542 Never delete a previously invisible character or add in the
1543 middle or right after an invisible region. Basically, this
1544 allows insertion and backward-delete right before ellipses.
1545 FIXME: maybe in this case we should not even show?"
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not check" nil)
1550 (const :tag "Throw error when trying to edit" error)
1551 (const :tag "Unhide, but do not do the edit" show-and-error)
1552 (const :tag "Show invisible part and do the edit" show)
1553 (const :tag "Be smart and do the right thing" smart)))
1555 (defcustom org-yank-folded-subtrees t
1556 "Non-nil means when yanking subtrees, fold them.
1557 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1558 it starts with a heading and all other headings in it are either children
1559 or siblings, then fold all the subtrees. However, do this only if no
1560 text after the yank would be swallowed into a folded tree by this action."
1561 :group 'org-edit-structure
1562 :type 'boolean)
1564 (defcustom org-yank-adjusted-subtrees nil
1565 "Non-nil means when yanking subtrees, adjust the level.
1566 With this setting, `org-paste-subtree' is used to insert the subtree, see
1567 this function for details."
1568 :group 'org-edit-structure
1569 :type 'boolean)
1571 (defcustom org-M-RET-may-split-line '((default . t))
1572 "Non-nil means M-RET will split the line at the cursor position.
1573 When nil, it will go to the end of the line before making a
1574 new line.
1575 You may also set this option in a different way for different
1576 contexts. Valid contexts are:
1578 headline when creating a new headline
1579 item when creating a new item
1580 table in a table field
1581 default the value to be used for all contexts not explicitly
1582 customized"
1583 :group 'org-structure
1584 :group 'org-table
1585 :type '(choice
1586 (const :tag "Always" t)
1587 (const :tag "Never" nil)
1588 (repeat :greedy t :tag "Individual contexts"
1589 (cons
1590 (choice :tag "Context"
1591 (const headline)
1592 (const item)
1593 (const table)
1594 (const default))
1595 (boolean)))))
1598 (defcustom org-insert-heading-respect-content nil
1599 "Non-nil means insert new headings after the current subtree.
1600 When nil, the new heading is created directly after the current line.
1601 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1602 this variable on for the duration of the command."
1603 :group 'org-structure
1604 :type 'boolean)
1606 (defcustom org-blank-before-new-entry '((heading . auto)
1607 (plain-list-item . auto))
1608 "Should `org-insert-heading' leave a blank line before new heading/item?
1609 The value is an alist, with `heading' and `plain-list-item' as CAR,
1610 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1611 which case Org will look at the surrounding headings/items and try to
1612 make an intelligent decision whether to insert a blank line or not."
1613 :group 'org-edit-structure
1614 :type '(list
1615 (cons (const heading)
1616 (choice (const :tag "Never" nil)
1617 (const :tag "Always" t)
1618 (const :tag "Auto" auto)))
1619 (cons (const plain-list-item)
1620 (choice (const :tag "Never" nil)
1621 (const :tag "Always" t)
1622 (const :tag "Auto" auto)))))
1624 (defcustom org-insert-heading-hook nil
1625 "Hook being run after inserting a new heading."
1626 :group 'org-edit-structure
1627 :type 'hook)
1629 (defcustom org-enable-fixed-width-editor t
1630 "Non-nil means lines starting with \":\" are treated as fixed-width.
1631 This currently only means they are never auto-wrapped.
1632 When nil, such lines will be treated like ordinary lines."
1633 :group 'org-edit-structure
1634 :type 'boolean)
1636 (defcustom org-goto-auto-isearch t
1637 "Non-nil means typing characters in `org-goto' starts incremental search.
1638 When nil, you can use these keybindings to navigate the buffer:
1640 q Quit the org-goto interface
1641 n Go to the next visible heading
1642 p Go to the previous visible heading
1643 f Go one heading forward on same level
1644 b Go one heading backward on same level
1645 u Go one heading up"
1646 :group 'org-edit-structure
1647 :type 'boolean)
1649 (defgroup org-sparse-trees nil
1650 "Options concerning sparse trees in Org-mode."
1651 :tag "Org Sparse Trees"
1652 :group 'org-structure)
1654 (defcustom org-highlight-sparse-tree-matches t
1655 "Non-nil means highlight all matches that define a sparse tree.
1656 The highlights will automatically disappear the next time the buffer is
1657 changed by an edit command."
1658 :group 'org-sparse-trees
1659 :type 'boolean)
1661 (defcustom org-remove-highlights-with-change t
1662 "Non-nil means any change to the buffer will remove temporary highlights.
1663 \\<org-mode-map>\
1664 Such highlights are created by `org-occur' and `org-clock-display'.
1665 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1666 to get rid of the highlights.
1667 The highlights created by `org-toggle-latex-fragment' always need
1668 `\\[org-toggle-latex-fragment]' to be removed."
1669 :group 'org-sparse-trees
1670 :group 'org-time
1671 :type 'boolean)
1673 (defcustom org-occur-case-fold-search t
1674 "Non-nil means `org-occur' should be case-insensitive.
1675 If set to `smart' the search will be case-insensitive only if it
1676 doesn't specify any upper case character."
1677 :group 'org-sparse-trees
1678 :version "25.1"
1679 :type '(choice
1680 (const :tag "Case-sensitive" nil)
1681 (const :tag "Case-insensitive" t)
1682 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1684 (defcustom org-occur-hook '(org-first-headline-recenter)
1685 "Hook that is run after `org-occur' has constructed a sparse tree.
1686 This can be used to recenter the window to show as much of the structure
1687 as possible."
1688 :group 'org-sparse-trees
1689 :type 'hook)
1691 (defgroup org-imenu-and-speedbar nil
1692 "Options concerning imenu and speedbar in Org-mode."
1693 :tag "Org Imenu and Speedbar"
1694 :group 'org-structure)
1696 (defcustom org-imenu-depth 2
1697 "The maximum level for Imenu access to Org headlines.
1698 This also applied for speedbar access."
1699 :group 'org-imenu-and-speedbar
1700 :type 'integer)
1702 (defgroup org-table nil
1703 "Options concerning tables in Org-mode."
1704 :tag "Org Table"
1705 :group 'org)
1707 (defcustom org-enable-table-editor 'optimized
1708 "Non-nil means lines starting with \"|\" are handled by the table editor.
1709 When nil, such lines will be treated like ordinary lines.
1711 When equal to the symbol `optimized', the table editor will be optimized to
1712 do the following:
1713 - Automatic overwrite mode in front of whitespace in table fields.
1714 This makes the structure of the table stay in tact as long as the edited
1715 field does not exceed the column width.
1716 - Minimize the number of realigns. Normally, the table is aligned each time
1717 TAB or RET are pressed to move to another field. With optimization this
1718 happens only if changes to a field might have changed the column width.
1719 Optimization requires replacing the functions `self-insert-command',
1720 `delete-char', and `backward-delete-char' in Org buffers, with a
1721 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1722 good at guessing when a re-align will be necessary, but you can always
1723 force one with \\[org-ctrl-c-ctrl-c].
1725 If you would like to use the optimized version in Org-mode, but the
1726 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1728 This variable can be used to turn on and off the table editor during a session,
1729 but in order to toggle optimization, a restart is required.
1731 See also the variable `org-table-auto-blank-field'."
1732 :group 'org-table
1733 :type '(choice
1734 (const :tag "off" nil)
1735 (const :tag "on" t)
1736 (const :tag "on, optimized" optimized)))
1738 (defcustom org-self-insert-cluster-for-undo nil
1739 "Non-nil means cluster self-insert commands for undo when possible.
1740 If this is set, then, like in the Emacs command loop, 20 consecutive
1741 characters will be undone together.
1742 This is configurable, because there is some impact on typing performance."
1743 :group 'org-table
1744 :type 'boolean)
1746 (defcustom org-table-tab-recognizes-table.el t
1747 "Non-nil means TAB will automatically notice a table.el table.
1748 When it sees such a table, it moves point into it and - if necessary -
1749 calls `table-recognize-table'."
1750 :group 'org-table-editing
1751 :type 'boolean)
1753 (defgroup org-link nil
1754 "Options concerning links in Org-mode."
1755 :tag "Org Link"
1756 :group 'org)
1758 (defvar-local org-link-abbrev-alist-local nil
1759 "Buffer-local version of `org-link-abbrev-alist', which see.
1760 The value of this is taken from the #+LINK lines.")
1762 (defcustom org-link-parameters
1763 '(("doi" :follow org--open-doi-link)
1764 ("elisp" :follow org--open-elisp-link)
1765 ("file" :complete org-file-complete-link)
1766 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1767 ("help" :follow org--open-help-link)
1768 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1769 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1770 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1771 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1772 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1773 ("shell" :follow org--open-shell-link))
1774 "An alist of properties that defines all the links in Org mode.
1775 The key in each association is a string of the link type.
1776 Subsequent optional elements make up a p-list of link properties.
1778 :follow - A function that takes the link path as an argument.
1780 :export - A function that takes the link path, description and
1781 export-backend as arguments.
1783 :store - A function responsible for storing the link. See the
1784 function `org-store-link-functions'.
1786 :complete - A function that inserts a link with completion. The
1787 function takes one optional prefix arg.
1789 :face - A face for the link, or a function that returns a face.
1790 The function takes one argument which is the link path. The
1791 default face is `org-link'.
1793 :mouse-face - The mouse-face. The default is `highlight'.
1795 :display - `full' will not fold the link in descriptive
1796 display. Default is `org-link'.
1798 :help-echo - A string or function that takes (window object position)
1799 as arguments and returns a string.
1801 :keymap - A keymap that is active on the link. The default is
1802 `org-mouse-map'.
1804 :htmlize-link - A function for the htmlize-link. Defaults
1805 to (list :uri \"type:path\")
1807 :activate-func - A function to run at the end of font-lock
1808 activation. The function must accept (link-start link-end path bracketp)
1809 as arguments."
1810 :group 'org-link
1811 :type '(alist :tag "Link display parameters"
1812 :value-type plist))
1814 (defun org-link-get-parameter (type key)
1815 "Get TYPE link property for KEY.
1816 TYPE is a string and KEY is a plist keyword."
1817 (plist-get
1818 (cdr (assoc type org-link-parameters))
1819 key))
1821 (defun org-link-set-parameters (type &rest parameters)
1822 "Set link TYPE properties to PARAMETERS.
1823 PARAMETERS should be :key val pairs."
1824 (let ((data (assoc type org-link-parameters)))
1825 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1826 (push (cons type parameters) org-link-parameters)
1827 (org-make-link-regexps)
1828 (org-element-update-syntax))))
1830 (defun org-link-types ()
1831 "Return a list of known link types."
1832 (mapcar #'car org-link-parameters))
1834 (defcustom org-link-abbrev-alist nil
1835 "Alist of link abbreviations.
1836 The car of each element is a string, to be replaced at the start of a link.
1837 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1838 links in Org buffers can have an optional tag after a double colon, e.g.,
1840 [[linkkey:tag][description]]
1842 The `linkkey' must be a single word, starting with a letter, followed
1843 by letters, numbers, `-' or `_'.
1845 If REPLACE is a string, the tag will simply be appended to create the link.
1846 If the string contains \"%s\", the tag will be inserted there. If the string
1847 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1848 at that point (see the function `url-hexify-string'). If the string contains
1849 the specifier \"%(my-function)\", then the custom function `my-function' will
1850 be invoked: this function takes the tag as its only argument and must return
1851 a string.
1853 REPLACE may also be a function that will be called with the tag as the
1854 only argument to create the link, which should be returned as a string.
1856 See the manual for examples."
1857 :group 'org-link
1858 :type '(repeat
1859 (cons
1860 (string :tag "Protocol")
1861 (choice
1862 (string :tag "Format")
1863 (function)))))
1865 (defcustom org-descriptive-links t
1866 "Non-nil means Org will display descriptive links.
1867 E.g. [[http://orgmode.org][Org website]] will be displayed as
1868 \"Org Website\", hiding the link itself and just displaying its
1869 description. When set to nil, Org will display the full links
1870 literally.
1872 You can interactively set the value of this variable by calling
1873 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1874 :group 'org-link
1875 :type 'boolean)
1877 (defcustom org-link-file-path-type 'adaptive
1878 "How the path name in file links should be stored.
1879 Valid values are:
1881 relative Relative to the current directory, i.e. the directory of the file
1882 into which the link is being inserted.
1883 absolute Absolute path, if possible with ~ for home directory.
1884 noabbrev Absolute path, no abbreviation of home directory.
1885 adaptive Use relative path for files in the current directory and sub-
1886 directories of it. For other files, use an absolute path."
1887 :group 'org-link
1888 :type '(choice
1889 (const relative)
1890 (const absolute)
1891 (const noabbrev)
1892 (const adaptive)))
1894 (defvaralias 'org-activate-links 'org-highlight-links)
1895 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1896 "Types of links that should be highlighted in Org files.
1898 This is a list of symbols, each one of them leading to the
1899 highlighting of a certain link type.
1901 You can still open links that are not highlighted.
1903 In principle, it does not hurt to turn on highlighting for all
1904 link types. There may be a small gain when turning off unused
1905 link types. The types are:
1907 bracket The recommended [[link][description]] or [[link]] links with hiding.
1908 angle Links in angular brackets that may contain whitespace like
1909 <bbdb:Carsten Dominik>.
1910 plain Plain links in normal text, no whitespace, like http://google.com.
1911 radio Text that is matched by a radio target, see manual for details.
1912 tag Tag settings in a headline (link to tag search).
1913 date Time stamps (link to calendar).
1914 footnote Footnote labels.
1916 If you set this variable during an Emacs session, use `org-mode-restart'
1917 in the Org buffer so that the change takes effect."
1918 :group 'org-link
1919 :group 'org-appearance
1920 :type '(set :greedy t
1921 (const :tag "Double bracket links" bracket)
1922 (const :tag "Angular bracket links" angle)
1923 (const :tag "Plain text links" plain)
1924 (const :tag "Radio target matches" radio)
1925 (const :tag "Tags" tag)
1926 (const :tag "Timestamps" date)
1927 (const :tag "Footnotes" footnote)))
1929 (defcustom org-make-link-description-function nil
1930 "Function to use for generating link descriptions from links.
1931 When nil, the link location will be used. This function must take
1932 two parameters: the first one is the link, the second one is the
1933 description generated by `org-insert-link'. The function should
1934 return the description to use."
1935 :group 'org-link
1936 :type '(choice (const nil) (function)))
1938 (defgroup org-link-store nil
1939 "Options concerning storing links in Org-mode."
1940 :tag "Org Store Link"
1941 :group 'org-link)
1943 (defcustom org-url-hexify-p t
1944 "When non-nil, hexify URL when creating a link."
1945 :type 'boolean
1946 :version "24.3"
1947 :group 'org-link-store)
1949 (defcustom org-email-link-description-format "Email %c: %.30s"
1950 "Format of the description part of a link to an email or usenet message.
1951 The following %-escapes will be replaced by corresponding information:
1953 %F full \"From\" field
1954 %f name, taken from \"From\" field, address if no name
1955 %T full \"To\" field
1956 %t first name in \"To\" field, address if no name
1957 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1958 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1959 %s subject
1960 %d date
1961 %m message-id.
1963 You may use normal field width specification between the % and the letter.
1964 This is for example useful to limit the length of the subject.
1966 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1967 :group 'org-link-store
1968 :type 'string)
1970 (defcustom org-from-is-user-regexp
1971 (let (r1 r2)
1972 (when (and user-mail-address (not (string= user-mail-address "")))
1973 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1974 (when (and user-full-name (not (string= user-full-name "")))
1975 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1976 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1977 "Regexp matched against the \"From:\" header of an email or usenet message.
1978 It should match if the message is from the user him/herself."
1979 :group 'org-link-store
1980 :type 'regexp)
1982 (defcustom org-context-in-file-links t
1983 "Non-nil means file links from `org-store-link' contain context.
1984 A search string will be added to the file name with :: as separator and
1985 used to find the context when the link is activated by the command
1986 `org-open-at-point'. When this option is t, the entire active region
1987 will be placed in the search string of the file link. If set to a
1988 positive integer, only the first n lines of context will be stored.
1990 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1991 negates this setting for the duration of the command."
1992 :group 'org-link-store
1993 :type '(choice boolean integer))
1995 (defcustom org-keep-stored-link-after-insertion nil
1996 "Non-nil means keep link in list for entire session.
1998 The command `org-store-link' adds a link pointing to the current
1999 location to an internal list. These links accumulate during a session.
2000 The command `org-insert-link' can be used to insert links into any
2001 Org file (offering completion for all stored links). When this option
2002 is nil, every link which has been inserted once using \\[org-insert-link]
2003 will be removed from the list, to make completing the unused links
2004 more efficient."
2005 :group 'org-link-store
2006 :type 'boolean)
2008 (defgroup org-link-follow nil
2009 "Options concerning following links in Org-mode."
2010 :tag "Org Follow Link"
2011 :group 'org-link)
2013 (defcustom org-link-translation-function nil
2014 "Function to translate links with different syntax to Org syntax.
2015 This can be used to translate links created for example by the Planner
2016 or emacs-wiki packages to Org syntax.
2017 The function must accept two parameters, a TYPE containing the link
2018 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2019 which is everything after the link protocol. It should return a cons
2020 with possibly modified values of type and path.
2021 Org contains a function for this, so if you set this variable to
2022 `org-translate-link-from-planner', you should be able follow many
2023 links created by planner."
2024 :group 'org-link-follow
2025 :type '(choice (const nil) (function)))
2027 (defcustom org-follow-link-hook nil
2028 "Hook that is run after a link has been followed."
2029 :group 'org-link-follow
2030 :type 'hook)
2032 (defcustom org-tab-follows-link nil
2033 "Non-nil means on links TAB will follow the link.
2034 Needs to be set before org.el is loaded.
2035 This really should not be used, it does not make sense, and the
2036 implementation is bad."
2037 :group 'org-link-follow
2038 :type 'boolean)
2040 (defcustom org-return-follows-link nil
2041 "Non-nil means on links RET will follow the link.
2042 In tables, the special behavior of RET has precedence."
2043 :group 'org-link-follow
2044 :type 'boolean)
2046 (defcustom org-mouse-1-follows-link
2047 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2048 "Non-nil means mouse-1 on a link will follow the link.
2049 A longer mouse click will still set point. Needs to be set
2050 before org.el is loaded."
2051 :group 'org-link-follow
2052 :version "24.4"
2053 :package-version '(Org . "8.3")
2054 :type '(choice
2055 (const :tag "A double click follows the link" double)
2056 (const :tag "Unconditionally follow the link with mouse-1" t)
2057 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2059 (defcustom org-mark-ring-length 4
2060 "Number of different positions to be recorded in the ring.
2061 Changing this requires a restart of Emacs to work correctly."
2062 :group 'org-link-follow
2063 :type 'integer)
2065 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2066 "Non-nil means internal links in Org files must exactly match a headline.
2067 When nil, the link search tries to match a phrase with all words
2068 in the search text."
2069 :group 'org-link-follow
2070 :version "24.1"
2071 :type '(choice
2072 (const :tag "Use fuzzy text search" nil)
2073 (const :tag "Match only exact headline" t)
2074 (const :tag "Match exact headline or query to create it"
2075 query-to-create)))
2077 (defcustom org-link-frame-setup
2078 '((vm . vm-visit-folder-other-frame)
2079 (vm-imap . vm-visit-imap-folder-other-frame)
2080 (gnus . org-gnus-no-new-news)
2081 (file . find-file-other-window)
2082 (wl . wl-other-frame))
2083 "Setup the frame configuration for following links.
2084 When following a link with Emacs, it may often be useful to display
2085 this link in another window or frame. This variable can be used to
2086 set this up for the different types of links.
2087 For VM, use any of
2088 `vm-visit-folder'
2089 `vm-visit-folder-other-window'
2090 `vm-visit-folder-other-frame'
2091 For Gnus, use any of
2092 `gnus'
2093 `gnus-other-frame'
2094 `org-gnus-no-new-news'
2095 For FILE, use any of
2096 `find-file'
2097 `find-file-other-window'
2098 `find-file-other-frame'
2099 For Wanderlust use any of
2100 `wl'
2101 `wl-other-frame'
2102 For the calendar, use the variable `calendar-setup'.
2103 For BBDB, it is currently only possible to display the matches in
2104 another window."
2105 :group 'org-link-follow
2106 :type '(list
2107 (cons (const vm)
2108 (choice
2109 (const vm-visit-folder)
2110 (const vm-visit-folder-other-window)
2111 (const vm-visit-folder-other-frame)))
2112 (cons (const vm-imap)
2113 (choice
2114 (const vm-visit-imap-folder)
2115 (const vm-visit-imap-folder-other-window)
2116 (const vm-visit-imap-folder-other-frame)))
2117 (cons (const gnus)
2118 (choice
2119 (const gnus)
2120 (const gnus-other-frame)
2121 (const org-gnus-no-new-news)))
2122 (cons (const file)
2123 (choice
2124 (const find-file)
2125 (const find-file-other-window)
2126 (const find-file-other-frame)))
2127 (cons (const wl)
2128 (choice
2129 (const wl)
2130 (const wl-other-frame)))))
2132 (defcustom org-display-internal-link-with-indirect-buffer nil
2133 "Non-nil means use indirect buffer to display infile links.
2134 Activating internal links (from one location in a file to another location
2135 in the same file) normally just jumps to the location. When the link is
2136 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2137 is displayed in
2138 another window. When this option is set, the other window actually displays
2139 an indirect buffer clone of the current buffer, to avoid any visibility
2140 changes to the current buffer."
2141 :group 'org-link-follow
2142 :type 'boolean)
2144 (defcustom org-open-non-existing-files nil
2145 "Non-nil means `org-open-file' will open non-existing files.
2146 When nil, an error will be generated.
2147 This variable applies only to external applications because they
2148 might choke on non-existing files. If the link is to a file that
2149 will be opened in Emacs, the variable is ignored."
2150 :group 'org-link-follow
2151 :type 'boolean)
2153 (defcustom org-open-directory-means-index-dot-org nil
2154 "Non-nil means a link to a directory really means to index.org.
2155 When nil, following a directory link will run dired or open a finder/explorer
2156 window on that directory."
2157 :group 'org-link-follow
2158 :type 'boolean)
2160 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2161 "Non-nil means ask for confirmation before executing shell links.
2162 Shell links can be dangerous: just think about a link
2164 [[shell:rm -rf ~/*][Google Search]]
2166 This link would show up in your Org document as \"Google Search\",
2167 but really it would remove your entire home directory.
2168 Therefore we advise against setting this variable to nil.
2169 Just change it to `y-or-n-p' if you want to confirm with a
2170 single keystroke rather than having to type \"yes\"."
2171 :group 'org-link-follow
2172 :type '(choice
2173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2174 (const :tag "with y-or-n (faster)" y-or-n-p)
2175 (const :tag "no confirmation (dangerous)" nil)))
2176 (put 'org-confirm-shell-link-function
2177 'safe-local-variable
2178 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2180 (defcustom org-confirm-shell-link-not-regexp ""
2181 "A regexp to skip confirmation for shell links."
2182 :group 'org-link-follow
2183 :version "24.1"
2184 :type 'regexp)
2186 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2187 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2188 Elisp links can be dangerous: just think about a link
2190 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2192 This link would show up in your Org document as \"Google Search\",
2193 but really it would remove your entire home directory.
2194 Therefore we advise against setting this variable to nil.
2195 Just change it to `y-or-n-p' if you want to confirm with a
2196 single keystroke rather than having to type \"yes\"."
2197 :group 'org-link-follow
2198 :type '(choice
2199 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2200 (const :tag "with y-or-n (faster)" y-or-n-p)
2201 (const :tag "no confirmation (dangerous)" nil)))
2202 (put 'org-confirm-shell-link-function
2203 'safe-local-variable
2204 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2206 (defcustom org-confirm-elisp-link-not-regexp ""
2207 "A regexp to skip confirmation for Elisp links."
2208 :group 'org-link-follow
2209 :version "24.1"
2210 :type 'regexp)
2212 (defconst org-file-apps-defaults-gnu
2213 '((remote . emacs)
2214 (system . mailcap)
2215 (t . mailcap))
2216 "Default file applications on a UNIX or GNU/Linux system.
2217 See `org-file-apps'.")
2219 (defconst org-file-apps-defaults-macosx
2220 '((remote . emacs)
2221 (system . "open %s")
2222 ("ps.gz" . "gv %s")
2223 ("eps.gz" . "gv %s")
2224 ("dvi" . "xdvi %s")
2225 ("fig" . "xfig %s")
2226 (t . "open %s"))
2227 "Default file applications on a MacOS X system.
2228 The system \"open\" is known as a default, but we use X11 applications
2229 for some files for which the OS does not have a good default.
2230 See `org-file-apps'.")
2232 (defconst org-file-apps-defaults-windowsnt
2233 (list '(remote . emacs)
2234 (cons 'system (lambda (file _path)
2235 (with-no-warnings (w32-shell-execute "open" file))))
2236 (cons t (lambda (file _path)
2237 (with-no-warnings (w32-shell-execute "open" file)))))
2238 "Default file applications on a Windows NT system.
2239 The system \"open\" is used for most files.
2240 See `org-file-apps'.")
2242 (defcustom org-file-apps
2243 '((auto-mode . emacs)
2244 ("\\.mm\\'" . default)
2245 ("\\.x?html?\\'" . default)
2246 ("\\.pdf\\'" . default))
2247 "External applications for opening `file:path' items in a document.
2248 \\<org-mode-map>\
2250 Org mode uses system defaults for different file types, but
2251 you can use this variable to set the application for a given file
2252 extension. The entries in this list are cons cells where the car identifies
2253 files and the cdr the corresponding command.
2255 Possible values for the file identifier are:
2257 \"string\" A string as a file identifier can be interpreted in different
2258 ways, depending on its contents:
2260 - Alphanumeric characters only:
2261 Match links with this file extension.
2262 Example: (\"pdf\" . \"evince %s\")
2263 to open PDFs with evince.
2265 - Regular expression: Match links where the
2266 filename matches the regexp. If you want to
2267 use groups here, use shy groups.
2269 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2270 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2271 to open *.html and *.xhtml with firefox.
2273 - Regular expression which contains (non-shy) groups:
2274 Match links where the whole link, including \"::\", and
2275 anything after that, matches the regexp.
2276 In a custom command string, %1, %2, etc. are replaced with
2277 the parts of the link that were matched by the groups.
2278 For backwards compatibility, if a command string is given
2279 that does not use any of the group matches, this case is
2280 handled identically to the second one (i.e. match against
2281 file name only).
2282 In a custom function, you can access the group matches with
2283 \(match-string n link).
2285 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2286 \"evince -p %1 %s\")
2287 to open [[file:document.pdf::5]] with evince at page 5.
2289 `directory' Matches a directory
2290 `remote' Matches a remote file, accessible through tramp or efs.
2291 Remote files most likely should be visited through Emacs
2292 because external applications cannot handle such paths.
2293 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2294 so all files Emacs knows how to handle. Using this with
2295 command `emacs' will open most files in Emacs. Beware that this
2296 will also open html files inside Emacs, unless you add
2297 \(\"html\" . default) to the list as well.
2298 `system' The system command to open files, like `open' on Windows
2299 and Mac OS X, and mailcap under GNU/Linux. This is the command
2300 that will be selected if you call \\[org-open-at-point] with a double
2301 \\[universal-argument] \\[universal-argument] prefix.
2302 t Default for files not matched by any of the other options.
2304 Possible values for the command are:
2306 `emacs' The file will be visited by the current Emacs process.
2307 `default' Use the default application for this file type, which is the
2308 association for t in the list, most likely in the system-specific
2309 part. This can be used to overrule an unwanted setting in the
2310 system-specific variable.
2311 `system' Use the system command for opening files, like \"open\".
2312 This command is specified by the entry whose car is `system'.
2313 Most likely, the system-specific version of this variable
2314 does define this command, but you can overrule/replace it
2315 here.
2316 `mailcap' Use command specified in the mailcaps.
2317 string A command to be executed by a shell; %s will be replaced
2318 by the path to the file.
2319 function A Lisp function, which will be called with two arguments:
2320 the file path and the original link string, without the
2321 \"file:\" prefix.
2323 For more examples, see the system specific constants
2324 `org-file-apps-defaults-macosx'
2325 `org-file-apps-defaults-windowsnt'
2326 `org-file-apps-defaults-gnu'."
2327 :group 'org-link-follow
2328 :type '(repeat
2329 (cons (choice :value ""
2330 (string :tag "Extension")
2331 (const :tag "System command to open files" system)
2332 (const :tag "Default for unrecognized files" t)
2333 (const :tag "Remote file" remote)
2334 (const :tag "Links to a directory" directory)
2335 (const :tag "Any files that have Emacs modes"
2336 auto-mode))
2337 (choice :value ""
2338 (const :tag "Visit with Emacs" emacs)
2339 (const :tag "Use default" default)
2340 (const :tag "Use the system command" system)
2341 (string :tag "Command")
2342 (function :tag "Function")))))
2344 (defcustom org-doi-server-url "http://dx.doi.org/"
2345 "The URL of the DOI server."
2346 :type 'string
2347 :version "24.3"
2348 :group 'org-link-follow)
2350 (defgroup org-refile nil
2351 "Options concerning refiling entries in Org-mode."
2352 :tag "Org Refile"
2353 :group 'org)
2355 (defcustom org-directory "~/org"
2356 "Directory with Org files.
2357 This is just a default location to look for Org files. There is no need
2358 at all to put your files into this directory. It is used in the
2359 following situations:
2361 1. When a capture template specifies a target file that is not an
2362 absolute path. The path will then be interpreted relative to
2363 `org-directory'
2364 2. When the value of variable `org-agenda-files' is a single file, any
2365 relative paths in this file will be taken as relative to
2366 `org-directory'."
2367 :group 'org-refile
2368 :group 'org-capture
2369 :type 'directory)
2371 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2372 "Default target for storing notes.
2373 Used as a fall back file for org-capture.el, for templates that
2374 do not specify a target file."
2375 :group 'org-refile
2376 :group 'org-capture
2377 :type 'file)
2379 (defcustom org-goto-interface 'outline
2380 "The default interface to be used for `org-goto'.
2381 Allowed values are:
2382 outline The interface shows an outline of the relevant file
2383 and the correct heading is found by moving through
2384 the outline or by searching with incremental search.
2385 outline-path-completion Headlines in the current buffer are offered via
2386 completion. This is the interface also used by
2387 the refile command."
2388 :group 'org-refile
2389 :type '(choice
2390 (const :tag "Outline" outline)
2391 (const :tag "Outline-path-completion" outline-path-completion)))
2393 (defcustom org-goto-max-level 5
2394 "Maximum target level when running `org-goto' with refile interface."
2395 :group 'org-refile
2396 :type 'integer)
2398 (defcustom org-reverse-note-order nil
2399 "Non-nil means store new notes at the beginning of a file or entry.
2400 When nil, new notes will be filed to the end of a file or entry.
2401 This can also be a list with cons cells of regular expressions that
2402 are matched against file names, and values."
2403 :group 'org-capture
2404 :group 'org-refile
2405 :type '(choice
2406 (const :tag "Reverse always" t)
2407 (const :tag "Reverse never" nil)
2408 (repeat :tag "By file name regexp"
2409 (cons regexp boolean))))
2411 (defcustom org-log-refile nil
2412 "Information to record when a task is refiled.
2414 Possible values are:
2416 nil Don't add anything
2417 time Add a time stamp to the task
2418 note Prompt for a note and add it with template `org-log-note-headings'
2420 This option can also be set with on a per-file-basis with
2422 #+STARTUP: nologrefile
2423 #+STARTUP: logrefile
2424 #+STARTUP: lognoterefile
2426 You can have local logging settings for a subtree by setting the LOGGING
2427 property to one or more of these keywords.
2429 When bulk-refiling from the agenda, the value `note' is forbidden and
2430 will temporarily be changed to `time'."
2431 :group 'org-refile
2432 :group 'org-progress
2433 :version "24.1"
2434 :type '(choice
2435 (const :tag "No logging" nil)
2436 (const :tag "Record timestamp" time)
2437 (const :tag "Record timestamp with note." note)))
2439 (defcustom org-refile-targets nil
2440 "Targets for refiling entries with \\[org-refile].
2441 This is a list of cons cells. Each cell contains:
2442 - a specification of the files to be considered, either a list of files,
2443 or a symbol whose function or variable value will be used to retrieve
2444 a file name or a list of file names. If you use `org-agenda-files' for
2445 that, all agenda files will be scanned for targets. Nil means consider
2446 headings in the current buffer.
2447 - A specification of how to find candidate refile targets. This may be
2448 any of:
2449 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2450 This tag has to be present in all target headlines, inheritance will
2451 not be considered.
2452 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2453 todo keyword.
2454 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2455 headlines that are refiling targets.
2456 - a cons cell (:level . N). Any headline of level N is considered a target.
2457 Note that, when `org-odd-levels-only' is set, level corresponds to
2458 order in hierarchy, not to the number of stars.
2459 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2460 Note that, when `org-odd-levels-only' is set, level corresponds to
2461 order in hierarchy, not to the number of stars.
2463 Each element of this list generates a set of possible targets.
2464 The union of these sets is presented (with completion) to
2465 the user by `org-refile'.
2467 You can set the variable `org-refile-target-verify-function' to a function
2468 to verify each headline found by the simple criteria above.
2470 When this variable is nil, all top-level headlines in the current buffer
2471 are used, equivalent to the value `((nil . (:level . 1))'."
2472 :group 'org-refile
2473 :type '(repeat
2474 (cons
2475 (choice :value org-agenda-files
2476 (const :tag "All agenda files" org-agenda-files)
2477 (const :tag "Current buffer" nil)
2478 (function) (variable) (file))
2479 (choice :tag "Identify target headline by"
2480 (cons :tag "Specific tag" (const :value :tag) (string))
2481 (cons :tag "TODO keyword" (const :value :todo) (string))
2482 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2483 (cons :tag "Level number" (const :value :level) (integer))
2484 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2486 (defcustom org-refile-target-verify-function nil
2487 "Function to verify if the headline at point should be a refile target.
2488 The function will be called without arguments, with point at the
2489 beginning of the headline. It should return t and leave point
2490 where it is if the headline is a valid target for refiling.
2492 If the target should not be selected, the function must return nil.
2493 In addition to this, it may move point to a place from where the search
2494 should be continued. For example, the function may decide that the entire
2495 subtree of the current entry should be excluded and move point to the end
2496 of the subtree."
2497 :group 'org-refile
2498 :type '(choice
2499 (const nil)
2500 (function)))
2502 (defcustom org-refile-use-cache nil
2503 "Non-nil means cache refile targets to speed up the process.
2504 \\<org-mode-map>\
2505 The cache for a particular file will be updated automatically when
2506 the buffer has been killed, or when any of the marker used for flagging
2507 refile targets no longer points at a live buffer.
2508 If you have added new entries to a buffer that might themselves be targets,
2509 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2510 if you find that easier, \
2511 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2512 \\[org-refile]'."
2513 :group 'org-refile
2514 :version "24.1"
2515 :type 'boolean)
2517 (defcustom org-refile-use-outline-path nil
2518 "Non-nil means provide refile targets as paths.
2519 So a level 3 headline will be available as level1/level2/level3.
2521 When the value is `file', also include the file name (without directory)
2522 into the path. In this case, you can also stop the completion after
2523 the file name, to get entries inserted as top level in the file.
2525 When `full-file-path', include the full file path."
2526 :group 'org-refile
2527 :type '(choice
2528 (const :tag "Not" nil)
2529 (const :tag "Yes" t)
2530 (const :tag "Start with file name" file)
2531 (const :tag "Start with full file path" full-file-path)))
2533 (defcustom org-outline-path-complete-in-steps t
2534 "Non-nil means complete the outline path in hierarchical steps.
2535 When Org uses the refile interface to select an outline path (see
2536 `org-refile-use-outline-path'), the completion of the path can be
2537 done in a single go, or it can be done in steps down the headline
2538 hierarchy. Going in steps is probably the best if you do not use
2539 a special completion package like `ido' or `icicles'. However,
2540 when using these packages, going in one step can be very fast,
2541 while still showing the whole path to the entry."
2542 :group 'org-refile
2543 :type 'boolean)
2545 (defcustom org-refile-allow-creating-parent-nodes nil
2546 "Non-nil means allow the creation of new nodes as refile targets.
2547 New nodes are then created by adding \"/new node name\" to the completion
2548 of an existing node. When the value of this variable is `confirm',
2549 new node creation must be confirmed by the user (recommended).
2550 When nil, the completion must match an existing entry.
2552 Note that, if the new heading is not seen by the criteria
2553 listed in `org-refile-targets', multiple instances of the same
2554 heading would be created by trying again to file under the new
2555 heading."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Never" nil)
2559 (const :tag "Always" t)
2560 (const :tag "Prompt for confirmation" confirm)))
2562 (defcustom org-refile-active-region-within-subtree nil
2563 "Non-nil means also refile active region within a subtree.
2565 By default `org-refile' doesn't allow refiling regions if they
2566 don't contain a set of subtrees, but it might be convenient to
2567 do so sometimes: in that case, the first line of the region is
2568 converted to a headline before refiling."
2569 :group 'org-refile
2570 :version "24.1"
2571 :type 'boolean)
2573 (defgroup org-todo nil
2574 "Options concerning TODO items in Org-mode."
2575 :tag "Org TODO"
2576 :group 'org)
2578 (defgroup org-progress nil
2579 "Options concerning Progress logging in Org-mode."
2580 :tag "Org Progress"
2581 :group 'org-time)
2583 (defvar org-todo-interpretation-widgets
2584 '((:tag "Sequence (cycling hits every state)" sequence)
2585 (:tag "Type (cycling directly to DONE)" type))
2586 "The available interpretation symbols for customizing `org-todo-keywords'.
2587 Interested libraries should add to this list.")
2589 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2590 "List of TODO entry keyword sequences and their interpretation.
2591 \\<org-mode-map>This is a list of sequences.
2593 Each sequence starts with a symbol, either `sequence' or `type',
2594 indicating if the keywords should be interpreted as a sequence of
2595 action steps, or as different types of TODO items. The first
2596 keywords are states requiring action - these states will select a headline
2597 for inclusion into the global TODO list Org produces. If one of the
2598 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2599 signify that no further action is necessary. If \"|\" is not found,
2600 the last keyword is treated as the only DONE state of the sequence.
2602 The command \\[org-todo] cycles an entry through these states, and one
2603 additional state where no keyword is present. For details about this
2604 cycling, see the manual.
2606 TODO keywords and interpretation can also be set on a per-file basis with
2607 the special #+SEQ_TODO and #+TYP_TODO lines.
2609 Each keyword can optionally specify a character for fast state selection
2610 \(in combination with the variable `org-use-fast-todo-selection')
2611 and specifiers for state change logging, using the same syntax that
2612 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2613 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2614 indicates to record a time stamp each time this state is selected.
2616 Each keyword may also specify if a timestamp or a note should be
2617 recorded when entering or leaving the state, by adding additional
2618 characters in the parenthesis after the keyword. This looks like this:
2619 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2620 record only the time of the state change. With X and Y being either
2621 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2622 Y when leaving the state if and only if the *target* state does not
2623 define X. You may omit any of the fast-selection key or X or /Y,
2624 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2626 For backward compatibility, this variable may also be just a list
2627 of keywords. In this case the interpretation (sequence or type) will be
2628 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2629 :group 'org-todo
2630 :group 'org-keywords
2631 :type '(choice
2632 (repeat :tag "Old syntax, just keywords"
2633 (string :tag "Keyword"))
2634 (repeat :tag "New syntax"
2635 (cons
2636 (choice
2637 :tag "Interpretation"
2638 ;;Quick and dirty way to see
2639 ;;`org-todo-interpretations'. This takes the
2640 ;;place of item arguments
2641 :convert-widget
2642 (lambda (widget)
2643 (widget-put widget
2644 :args (mapcar
2645 (lambda (x)
2646 (widget-convert
2647 (cons 'const x)))
2648 org-todo-interpretation-widgets))
2649 widget))
2650 (repeat
2651 (string :tag "Keyword"))))))
2653 (defvar-local org-todo-keywords-1 nil
2654 "All TODO and DONE keywords active in a buffer.")
2655 (defvar org-todo-keywords-for-agenda nil)
2656 (defvar org-done-keywords-for-agenda nil)
2657 (defvar org-todo-keyword-alist-for-agenda nil)
2658 (defvar org-tag-alist-for-agenda nil
2659 "Alist of all tags from all agenda files.")
2660 (defvar org-tag-groups-alist-for-agenda nil
2661 "Alist of all groups tags from all current agenda files.")
2662 (defvar-local org-tag-groups-alist nil)
2663 (defvar org-agenda-contributing-files nil)
2664 (defvar-local org-current-tag-alist nil
2665 "Alist of all tag groups in current buffer.
2666 This variable takes into consideration `org-tag-alist',
2667 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2668 (defvar-local org-not-done-keywords nil)
2669 (defvar-local org-done-keywords nil)
2670 (defvar-local org-todo-heads nil)
2671 (defvar-local org-todo-sets nil)
2672 (defvar-local org-todo-log-states nil)
2673 (defvar-local org-todo-kwd-alist nil)
2674 (defvar-local org-todo-key-alist nil)
2675 (defvar-local org-todo-key-trigger nil)
2677 (defcustom org-todo-interpretation 'sequence
2678 "Controls how TODO keywords are interpreted.
2679 This variable is in principle obsolete and is only used for
2680 backward compatibility, if the interpretation of todo keywords is
2681 not given already in `org-todo-keywords'. See that variable for
2682 more information."
2683 :group 'org-todo
2684 :group 'org-keywords
2685 :type '(choice (const sequence)
2686 (const type)))
2688 (defcustom org-use-fast-todo-selection t
2689 "\\<org-mode-map>\
2690 Non-nil means use the fast todo selection scheme with \\[org-todo].
2691 This variable describes if and under what circumstances the cycling
2692 mechanism for TODO keywords will be replaced by a single-key, direct
2693 selection scheme.
2695 When nil, fast selection is never used.
2697 When the symbol `prefix', it will be used when `org-todo' is called
2698 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2699 in an Org buffer, and
2700 `\\[universal-argument] t' in an agenda buffer.
2702 When t, fast selection is used by default. In this case, the prefix
2703 argument forces cycling instead.
2705 In all cases, the special interface is only used if access keys have
2706 actually been assigned by the user, i.e. if keywords in the configuration
2707 are followed by a letter in parenthesis, like TODO(t)."
2708 :group 'org-todo
2709 :type '(choice
2710 (const :tag "Never" nil)
2711 (const :tag "By default" t)
2712 (const :tag "Only with C-u C-c C-t" prefix)))
2714 (defcustom org-provide-todo-statistics t
2715 "Non-nil means update todo statistics after insert and toggle.
2716 ALL-HEADLINES means update todo statistics by including headlines
2717 with no TODO keyword as well, counting them as not done.
2718 A list of TODO keywords means the same, but skip keywords that are
2719 not in this list.
2720 When set to a list of two lists, the first list contains keywords
2721 to consider as TODO keywords, the second list contains keywords
2722 to consider as DONE keywords.
2724 When this is set, todo statistics is updated in the parent of the
2725 current entry each time a todo state is changed."
2726 :group 'org-todo
2727 :type '(choice
2728 (const :tag "Yes, only for TODO entries" t)
2729 (const :tag "Yes, including all entries" all-headlines)
2730 (repeat :tag "Yes, for TODOs in this list"
2731 (string :tag "TODO keyword"))
2732 (list :tag "Yes, for TODOs and DONEs in these lists"
2733 (repeat (string :tag "TODO keyword"))
2734 (repeat (string :tag "DONE keyword")))
2735 (other :tag "No TODO statistics" nil)))
2737 (defcustom org-hierarchical-todo-statistics t
2738 "Non-nil means TODO statistics covers just direct children.
2739 When nil, all entries in the subtree are considered.
2740 This has only an effect if `org-provide-todo-statistics' is set.
2741 To set this to nil for only a single subtree, use a COOKIE_DATA
2742 property and include the word \"recursive\" into the value."
2743 :group 'org-todo
2744 :type 'boolean)
2746 (defcustom org-after-todo-state-change-hook nil
2747 "Hook which is run after the state of a TODO item was changed.
2748 The new state (a string with a TODO keyword, or nil) is available in the
2749 Lisp variable `org-state'."
2750 :group 'org-todo
2751 :type 'hook)
2753 (defvar org-blocker-hook nil
2754 "Hook for functions that are allowed to block a state change.
2756 Functions in this hook should not modify the buffer.
2757 Each function gets as its single argument a property list,
2758 see `org-trigger-hook' for more information about this list.
2760 If any of the functions in this hook returns nil, the state change
2761 is blocked.")
2763 (defvar org-trigger-hook nil
2764 "Hook for functions that are triggered by a state change.
2766 Each function gets as its single argument a property list with at
2767 least the following elements:
2769 (:type type-of-change :position pos-at-entry-start
2770 :from old-state :to new-state)
2772 Depending on the type, more properties may be present.
2774 This mechanism is currently implemented for:
2776 TODO state changes
2777 ------------------
2778 :type todo-state-change
2779 :from previous state (keyword as a string), or nil, or a symbol
2780 `todo' or `done', to indicate the general type of state.
2781 :to new state, like in :from")
2783 (defcustom org-enforce-todo-dependencies nil
2784 "Non-nil means undone TODO entries will block switching the parent to DONE.
2785 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2786 be blocked if any prior sibling is not yet done.
2787 Finally, if the parent is blocked because of ordered siblings of its own,
2788 the child will also be blocked."
2789 :set (lambda (var val)
2790 (set var val)
2791 (if val
2792 (add-hook 'org-blocker-hook
2793 'org-block-todo-from-children-or-siblings-or-parent)
2794 (remove-hook 'org-blocker-hook
2795 'org-block-todo-from-children-or-siblings-or-parent)))
2796 :group 'org-todo
2797 :type 'boolean)
2799 (defcustom org-enforce-todo-checkbox-dependencies nil
2800 "Non-nil means unchecked boxes will block switching the parent to DONE.
2801 When this is nil, checkboxes have no influence on switching TODO states.
2802 When non-nil, you first need to check off all check boxes before the TODO
2803 entry can be switched to DONE.
2804 This variable needs to be set before org.el is loaded, and you need to
2805 restart Emacs after a change to make the change effective. The only way
2806 to change is while Emacs is running is through the customize interface."
2807 :set (lambda (var val)
2808 (set var val)
2809 (if val
2810 (add-hook 'org-blocker-hook
2811 'org-block-todo-from-checkboxes)
2812 (remove-hook 'org-blocker-hook
2813 'org-block-todo-from-checkboxes)))
2814 :group 'org-todo
2815 :type 'boolean)
2817 (defcustom org-treat-insert-todo-heading-as-state-change nil
2818 "Non-nil means inserting a TODO heading is treated as state change.
2819 So when the command \\[org-insert-todo-heading] is used, state change
2820 logging will apply if appropriate. When nil, the new TODO item will
2821 be inserted directly, and no logging will take place."
2822 :group 'org-todo
2823 :type 'boolean)
2825 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2826 "Non-nil means switching TODO states with S-cursor counts as state change.
2827 This is the default behavior. However, setting this to nil allows a
2828 convenient way to select a TODO state and bypass any logging associated
2829 with that."
2830 :group 'org-todo
2831 :type 'boolean)
2833 (defcustom org-todo-state-tags-triggers nil
2834 "Tag changes that should be triggered by TODO state changes.
2835 This is a list. Each entry is
2837 (state-change (tag . flag) .......)
2839 State-change can be a string with a state, and empty string to indicate the
2840 state that has no TODO keyword, or it can be one of the symbols `todo'
2841 or `done', meaning any not-done or done state, respectively."
2842 :group 'org-todo
2843 :group 'org-tags
2844 :type '(repeat
2845 (cons (choice :tag "When changing to"
2846 (const :tag "Not-done state" todo)
2847 (const :tag "Done state" done)
2848 (string :tag "State"))
2849 (repeat
2850 (cons :tag "Tag action"
2851 (string :tag "Tag")
2852 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2854 (defcustom org-log-done nil
2855 "Information to record when a task moves to the DONE state.
2857 Possible values are:
2859 nil Don't add anything, just change the keyword
2860 time Add a time stamp to the task
2861 note Prompt for a note and add it with template `org-log-note-headings'
2863 This option can also be set with on a per-file-basis with
2865 #+STARTUP: nologdone
2866 #+STARTUP: logdone
2867 #+STARTUP: lognotedone
2869 You can have local logging settings for a subtree by setting the LOGGING
2870 property to one or more of these keywords."
2871 :group 'org-todo
2872 :group 'org-progress
2873 :type '(choice
2874 (const :tag "No logging" nil)
2875 (const :tag "Record CLOSED timestamp" time)
2876 (const :tag "Record CLOSED timestamp with note." note)))
2878 ;; Normalize old uses of org-log-done.
2879 (cond
2880 ((eq org-log-done t) (setq org-log-done 'time))
2881 ((and (listp org-log-done) (memq 'done org-log-done))
2882 (setq org-log-done 'note)))
2884 (defcustom org-log-reschedule nil
2885 "Information to record when the scheduling date of a tasks is modified.
2887 Possible values are:
2889 nil Don't add anything, just change the date
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologreschedule
2896 #+STARTUP: logreschedule
2897 #+STARTUP: lognotereschedule"
2898 :group 'org-todo
2899 :group 'org-progress
2900 :type '(choice
2901 (const :tag "No logging" nil)
2902 (const :tag "Record timestamp" time)
2903 (const :tag "Record timestamp with note." note)))
2905 (defcustom org-log-redeadline nil
2906 "Information to record when the deadline date of a tasks is modified.
2908 Possible values are:
2910 nil Don't add anything, just change the date
2911 time Add a time stamp to the task
2912 note Prompt for a note and add it with template `org-log-note-headings'
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: nologredeadline
2917 #+STARTUP: logredeadline
2918 #+STARTUP: lognoteredeadline
2920 You can have local logging settings for a subtree by setting the LOGGING
2921 property to one or more of these keywords."
2922 :group 'org-todo
2923 :group 'org-progress
2924 :type '(choice
2925 (const :tag "No logging" nil)
2926 (const :tag "Record timestamp" time)
2927 (const :tag "Record timestamp with note." note)))
2929 (defcustom org-log-note-clock-out nil
2930 "Non-nil means record a note when clocking out of an item.
2931 This can also be configured on a per-file basis by adding one of
2932 the following lines anywhere in the buffer:
2934 #+STARTUP: lognoteclock-out
2935 #+STARTUP: nolognoteclock-out"
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type 'boolean)
2940 (defcustom org-log-done-with-time t
2941 "Non-nil means the CLOSED time stamp will contain date and time.
2942 When nil, only the date will be recorded."
2943 :group 'org-progress
2944 :type 'boolean)
2946 (defcustom org-log-note-headings
2947 '((done . "CLOSING NOTE %t")
2948 (state . "State %-12s from %-12S %t")
2949 (note . "Note taken on %t")
2950 (reschedule . "Rescheduled from %S on %t")
2951 (delschedule . "Not scheduled, was %S on %t")
2952 (redeadline . "New deadline from %S on %t")
2953 (deldeadline . "Removed deadline, was %S on %t")
2954 (refile . "Refiled on %t")
2955 (clock-out . ""))
2956 "Headings for notes added to entries.
2958 The value is an alist, with the car being a symbol indicating the
2959 note context, and the cdr is the heading to be used. The heading
2960 may also be the empty string. The following placeholders can be
2961 used:
2963 %t a time stamp.
2964 %T an active time stamp instead the default inactive one
2965 %d a short-format time stamp.
2966 %D an active short-format time stamp.
2967 %s the new TODO state or time stamp (inactive), in double quotes.
2968 %S the old TODO state or time stamp (inactive), in double quotes.
2969 %u the user name.
2970 %U full user name.
2972 In fact, it is not a good idea to change the `state' entry,
2973 because Agenda Log mode depends on the format of these entries."
2974 :group 'org-todo
2975 :group 'org-progress
2976 :type '(list :greedy t
2977 (cons (const :tag "Heading when closing an item" done) string)
2978 (cons (const :tag
2979 "Heading when changing todo state (todo sequence only)"
2980 state) string)
2981 (cons (const :tag "Heading when just taking a note" note) string)
2982 (cons (const :tag "Heading when rescheduling" reschedule) string)
2983 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2984 (cons (const :tag "Heading when changing deadline" redeadline) string)
2985 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2986 (cons (const :tag "Heading when refiling" refile) string)
2987 (cons (const :tag "Heading when clocking out" clock-out) string)))
2989 (unless (assq 'note org-log-note-headings)
2990 (push '(note . "%t") org-log-note-headings))
2992 (defcustom org-log-into-drawer nil
2993 "Non-nil means insert state change notes and time stamps into a drawer.
2994 When nil, state changes notes will be inserted after the headline and
2995 any scheduling and clock lines, but not inside a drawer.
2997 The value of this variable should be the name of the drawer to use.
2998 LOGBOOK is proposed as the default drawer for this purpose, you can
2999 also set this to a string to define the drawer of your choice.
3001 A value of t is also allowed, representing \"LOGBOOK\".
3003 A value of t or nil can also be set with on a per-file-basis with
3005 #+STARTUP: logdrawer
3006 #+STARTUP: nologdrawer
3008 If this variable is set, `org-log-state-notes-insert-after-drawers'
3009 will be ignored.
3011 You can set the property LOG_INTO_DRAWER to overrule this setting for
3012 a subtree.
3014 Do not check directly this variable in a Lisp program. Call
3015 function `org-log-into-drawer' instead."
3016 :group 'org-todo
3017 :group 'org-progress
3018 :type '(choice
3019 (const :tag "Not into a drawer" nil)
3020 (const :tag "LOGBOOK" t)
3021 (string :tag "Other")))
3023 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3025 (defun org-log-into-drawer ()
3026 "Name of the log drawer, as a string, or nil.
3027 This is the value of `org-log-into-drawer'. However, if the
3028 current entry has or inherits a LOG_INTO_DRAWER property, it will
3029 be used instead of the default value."
3030 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3031 (cond ((equal p "nil") nil)
3032 ((equal p "t") "LOGBOOK")
3033 ((stringp p) p)
3034 (p "LOGBOOK")
3035 ((stringp org-log-into-drawer) org-log-into-drawer)
3036 (org-log-into-drawer "LOGBOOK"))))
3038 (defcustom org-log-state-notes-insert-after-drawers nil
3039 "Non-nil means insert state change notes after any drawers in entry.
3040 Only the drawers that *immediately* follow the headline and the
3041 deadline/scheduled line are skipped.
3042 When nil, insert notes right after the heading and perhaps the line
3043 with deadline/scheduling if present.
3045 This variable will have no effect if `org-log-into-drawer' is
3046 set."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type 'boolean)
3051 (defcustom org-log-states-order-reversed t
3052 "Non-nil means the latest state note will be directly after heading.
3053 When nil, the state change notes will be ordered according to time.
3055 This option can also be set with on a per-file-basis with
3057 #+STARTUP: logstatesreversed
3058 #+STARTUP: nologstatesreversed"
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type 'boolean)
3063 (defcustom org-todo-repeat-to-state nil
3064 "The TODO state to which a repeater should return the repeating task.
3065 By default this is the first task in a TODO sequence, or the previous state
3066 in a TODO_TYP set. But you can specify another task here.
3067 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3068 :group 'org-todo
3069 :version "24.1"
3070 :type '(choice (const :tag "Head of sequence" nil)
3071 (string :tag "Specific state")))
3073 (defcustom org-log-repeat 'time
3074 "Non-nil means record moving through the DONE state when triggering repeat.
3075 An auto-repeating task is immediately switched back to TODO when
3076 marked DONE. If you are not logging state changes (by adding \"@\"
3077 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3078 record a closing note, there will be no record of the task moving
3079 through DONE. This variable forces taking a note anyway.
3081 nil Don't force a record
3082 time Record a time stamp
3083 note Prompt for a note and add it with template `org-log-note-headings'
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: nologrepeat
3088 #+STARTUP: logrepeat
3089 #+STARTUP: lognoterepeat
3091 You can have local logging settings for a subtree by setting the LOGGING
3092 property to one or more of these keywords."
3093 :group 'org-todo
3094 :group 'org-progress
3095 :type '(choice
3096 (const :tag "Don't force a record" nil)
3097 (const :tag "Force recording the DONE state" time)
3098 (const :tag "Force recording a note with the DONE state" note)))
3101 (defgroup org-priorities nil
3102 "Priorities in Org-mode."
3103 :tag "Org Priorities"
3104 :group 'org-todo)
3106 (defcustom org-enable-priority-commands t
3107 "Non-nil means priority commands are active.
3108 When nil, these commands will be disabled, so that you never accidentally
3109 set a priority."
3110 :group 'org-priorities
3111 :type 'boolean)
3113 (defcustom org-highest-priority ?A
3114 "The highest priority of TODO items. A character like ?A, ?B etc.
3115 Must have a smaller ASCII number than `org-lowest-priority'."
3116 :group 'org-priorities
3117 :type 'character)
3119 (defcustom org-lowest-priority ?C
3120 "The lowest priority of TODO items. A character like ?A, ?B etc.
3121 Must have a larger ASCII number than `org-highest-priority'."
3122 :group 'org-priorities
3123 :type 'character)
3125 (defcustom org-default-priority ?B
3126 "The default priority of TODO items.
3127 This is the priority an item gets if no explicit priority is given.
3128 When starting to cycle on an empty priority the first step in the cycle
3129 depends on `org-priority-start-cycle-with-default'. The resulting first
3130 step priority must not exceed the range from `org-highest-priority' to
3131 `org-lowest-priority' which means that `org-default-priority' has to be
3132 in this range exclusive or inclusive the range boundaries. Else the
3133 first step refuses to set the default and the second will fall back
3134 to (depending on the command used) the highest or lowest priority."
3135 :group 'org-priorities
3136 :type 'character)
3138 (defcustom org-priority-start-cycle-with-default t
3139 "Non-nil means start with default priority when starting to cycle.
3140 When this is nil, the first step in the cycle will be (depending on the
3141 command used) one higher or lower than the default priority.
3142 See also `org-default-priority'."
3143 :group 'org-priorities
3144 :type 'boolean)
3146 (defcustom org-get-priority-function nil
3147 "Function to extract the priority from a string.
3148 The string is normally the headline. If this is nil Org computes the
3149 priority from the priority cookie like [#A] in the headline. It returns
3150 an integer, increasing by 1000 for each priority level.
3151 The user can set a different function here, which should take a string
3152 as an argument and return the numeric priority."
3153 :group 'org-priorities
3154 :version "24.1"
3155 :type '(choice
3156 (const nil)
3157 (function)))
3159 (defgroup org-time nil
3160 "Options concerning time stamps and deadlines in Org-mode."
3161 :tag "Org Time"
3162 :group 'org)
3164 (defcustom org-time-stamp-rounding-minutes '(0 5)
3165 "Number of minutes to round time stamps to.
3166 \\<org-mode-map>\
3167 These are two values, the first applies when first creating a time stamp.
3168 The second applies when changing it with the commands `S-up' and `S-down'.
3169 When changing the time stamp, this means that it will change in steps
3170 of N minutes, as given by the second value.
3172 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3173 numbers should be factors of 60, so for example 5, 10, 15.
3175 When this is larger than 1, you can still force an exact time stamp by using
3176 a double prefix argument to a time stamp command like \
3177 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3178 and by using a prefix arg to `S-up/down' to specify the exact number
3179 of minutes to shift."
3180 :group 'org-time
3181 :get (lambda (var) ; Make sure both elements are there
3182 (if (integerp (default-value var))
3183 (list (default-value var) 5)
3184 (default-value var)))
3185 :type '(list
3186 (integer :tag "when inserting times")
3187 (integer :tag "when modifying times")))
3189 ;; Normalize old customizations of this variable.
3190 (when (integerp org-time-stamp-rounding-minutes)
3191 (setq org-time-stamp-rounding-minutes
3192 (list org-time-stamp-rounding-minutes
3193 org-time-stamp-rounding-minutes)))
3195 (defcustom org-display-custom-times nil
3196 "Non-nil means overlay custom formats over all time stamps.
3197 The formats are defined through the variable `org-time-stamp-custom-formats'.
3198 To turn this on on a per-file basis, insert anywhere in the file:
3199 #+STARTUP: customtime"
3200 :group 'org-time
3201 :set 'set-default
3202 :type 'sexp)
3203 (make-variable-buffer-local 'org-display-custom-times)
3205 (defcustom org-time-stamp-custom-formats
3206 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3207 "Custom formats for time stamps. See `format-time-string' for the syntax.
3208 These are overlaid over the default ISO format if the variable
3209 `org-display-custom-times' is set. Time like %H:%M should be at the
3210 end of the second format. The custom formats are also honored by export
3211 commands, if custom time display is turned on at the time of export."
3212 :group 'org-time
3213 :type 'sexp)
3215 (defun org-time-stamp-format (&optional long inactive)
3216 "Get the right format for a time string."
3217 (let ((f (if long (cdr org-time-stamp-formats)
3218 (car org-time-stamp-formats))))
3219 (if inactive
3220 (concat "[" (substring f 1 -1) "]")
3221 f)))
3223 (defcustom org-time-clocksum-format
3224 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3225 "The format string used when creating CLOCKSUM lines.
3226 This is also used when Org mode generates a time duration.
3228 The value can be a single format string containing two
3229 %-sequences, which will be filled with the number of hours and
3230 minutes in that order.
3232 Alternatively, the value can be a plist associating any of the
3233 keys :years, :months, :weeks, :days, :hours or :minutes with
3234 format strings. The time duration is formatted using only the
3235 time components that are needed and concatenating the results.
3236 If a time unit in absent, it falls back to the next smallest
3237 unit.
3239 The keys :require-years, :require-months, :require-days,
3240 :require-weeks, :require-hours, :require-minutes are also
3241 meaningful. A non-nil value for these keys indicates that the
3242 corresponding time component should always be included, even if
3243 its value is 0.
3246 For example,
3248 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3249 :require-minutes t)
3251 means durations longer than a day will be expressed in days,
3252 hours and minutes, and durations less than a day will always be
3253 expressed in hours and minutes (even for durations less than an
3254 hour).
3256 The value
3258 (:days \"%dd\" :minutes \"%dm\")
3260 means durations longer than a day will be expressed in days and
3261 minutes, and durations less than a day will be expressed entirely
3262 in minutes (even for durations longer than an hour)."
3263 :group 'org-time
3264 :group 'org-clock
3265 :version "24.4"
3266 :package-version '(Org . "8.0")
3267 :type '(choice (string :tag "Format string")
3268 (set :tag "Plist"
3269 (group :inline t (const :tag "Years" :years)
3270 (string :tag "Format string"))
3271 (group :inline t
3272 (const :tag "Always show years" :require-years)
3273 (const t))
3274 (group :inline t (const :tag "Months" :months)
3275 (string :tag "Format string"))
3276 (group :inline t
3277 (const :tag "Always show months" :require-months)
3278 (const t))
3279 (group :inline t (const :tag "Weeks" :weeks)
3280 (string :tag "Format string"))
3281 (group :inline t
3282 (const :tag "Always show weeks" :require-weeks)
3283 (const t))
3284 (group :inline t (const :tag "Days" :days)
3285 (string :tag "Format string"))
3286 (group :inline t
3287 (const :tag "Always show days" :require-days)
3288 (const t))
3289 (group :inline t (const :tag "Hours" :hours)
3290 (string :tag "Format string"))
3291 (group :inline t
3292 (const :tag "Always show hours" :require-hours)
3293 (const t))
3294 (group :inline t (const :tag "Minutes" :minutes)
3295 (string :tag "Format string"))
3296 (group :inline t
3297 (const :tag "Always show minutes" :require-minutes)
3298 (const t)))))
3300 (defcustom org-time-clocksum-use-fractional nil
3301 "When non-nil, \\[org-clock-display] uses fractional times.
3302 See `org-time-clocksum-format' for more on time clock formats."
3303 :group 'org-time
3304 :group 'org-clock
3305 :version "24.3"
3306 :type 'boolean)
3308 (defcustom org-time-clocksum-use-effort-durations nil
3309 "When non-nil, \\[org-clock-display] uses effort durations.
3310 E.g. by default, one day is considered to be a 8 hours effort,
3311 so a task that has been clocked for 16 hours will be displayed
3312 as during 2 days in the clock display or in the clocktable.
3314 See `org-effort-durations' on how to set effort durations
3315 and `org-time-clocksum-format' for more on time clock formats."
3316 :group 'org-time
3317 :group 'org-clock
3318 :version "24.4"
3319 :package-version '(Org . "8.0")
3320 :type 'boolean)
3322 (defcustom org-time-clocksum-fractional-format "%.2f"
3323 "The format string used when creating CLOCKSUM lines,
3324 or when Org mode generates a time duration, if
3325 `org-time-clocksum-use-fractional' is enabled.
3327 The value can be a single format string containing one
3328 %-sequence, which will be filled with the number of hours as
3329 a float.
3331 Alternatively, the value can be a plist associating any of the
3332 keys :years, :months, :weeks, :days, :hours or :minutes with
3333 a format string. The time duration is formatted using the
3334 largest time unit which gives a non-zero integer part. If all
3335 specified formats have zero integer part, the smallest time unit
3336 is used."
3337 :group 'org-time
3338 :type '(choice (string :tag "Format string")
3339 (set (group :inline t (const :tag "Years" :years)
3340 (string :tag "Format string"))
3341 (group :inline t (const :tag "Months" :months)
3342 (string :tag "Format string"))
3343 (group :inline t (const :tag "Weeks" :weeks)
3344 (string :tag "Format string"))
3345 (group :inline t (const :tag "Days" :days)
3346 (string :tag "Format string"))
3347 (group :inline t (const :tag "Hours" :hours)
3348 (string :tag "Format string"))
3349 (group :inline t (const :tag "Minutes" :minutes)
3350 (string :tag "Format string")))))
3352 (defcustom org-deadline-warning-days 14
3353 "Number of days before expiration during which a deadline becomes active.
3354 This variable governs the display in sparse trees and in the agenda.
3355 When 0 or negative, it means use this number (the absolute value of it)
3356 even if a deadline has a different individual lead time specified.
3358 Custom commands can set this variable in the options section."
3359 :group 'org-time
3360 :group 'org-agenda-daily/weekly
3361 :type 'integer)
3363 (defcustom org-scheduled-delay-days 0
3364 "Number of days before a scheduled item becomes active.
3365 This variable governs the display in sparse trees and in the agenda.
3366 The default value (i.e. 0) means: don't delay scheduled item.
3367 When negative, it means use this number (the absolute value of it)
3368 even if a scheduled item has a different individual delay time
3369 specified.
3371 Custom commands can set this variable in the options section."
3372 :group 'org-time
3373 :group 'org-agenda-daily/weekly
3374 :version "24.4"
3375 :package-version '(Org . "8.0")
3376 :type 'integer)
3378 (defcustom org-read-date-prefer-future t
3379 "Non-nil means assume future for incomplete date input from user.
3380 This affects the following situations:
3381 1. The user gives a month but not a year.
3382 For example, if it is April and you enter \"feb 2\", this will be read
3383 as Feb 2, *next* year. \"May 5\", however, will be this year.
3384 2. The user gives a day, but no month.
3385 For example, if today is the 15th, and you enter \"3\", Org will read
3386 this as the third of *next* month. However, if you enter \"17\",
3387 it will be considered as *this* month.
3389 If you set this variable to the symbol `time', then also the following
3390 will work:
3392 3. If the user gives a time.
3393 If the time is before now, it will be interpreted as tomorrow.
3395 Currently none of this works for ISO week specifications.
3397 When this option is nil, the current day, month and year will always be
3398 used as defaults.
3400 See also `org-agenda-jump-prefer-future'."
3401 :group 'org-time
3402 :type '(choice
3403 (const :tag "Never" nil)
3404 (const :tag "Check month and day" t)
3405 (const :tag "Check month, day, and time" time)))
3407 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3408 "Should the agenda jump command prefer the future for incomplete dates?
3409 The default is to do the same as configured in `org-read-date-prefer-future'.
3410 But you can also set a deviating value here.
3411 This may t or nil, or the symbol `org-read-date-prefer-future'."
3412 :group 'org-agenda
3413 :group 'org-time
3414 :version "24.1"
3415 :type '(choice
3416 (const :tag "Use org-read-date-prefer-future"
3417 org-read-date-prefer-future)
3418 (const :tag "Never" nil)
3419 (const :tag "Always" t)))
3421 (defcustom org-read-date-force-compatible-dates t
3422 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3424 Depending on the system Emacs is running on, certain dates cannot
3425 be represented with the type used internally to represent time.
3426 Dates between 1970-1-1 and 2038-1-1 can always be represented
3427 correctly. Some systems allow for earlier dates, some for later,
3428 some for both. One way to find out it to insert any date into an
3429 Org buffer, putting the cursor on the year and hitting S-up and
3430 S-down to test the range.
3432 When this variable is set to t, the date/time prompt will not let
3433 you specify dates outside the 1970-2037 range, so it is certain that
3434 these dates will work in whatever version of Emacs you are
3435 running, and also that you can move a file from one Emacs implementation
3436 to another. WHenever Org is forcing the year for you, it will display
3437 a message and beep.
3439 When this variable is nil, Org will check if the date is
3440 representable in the specific Emacs implementation you are using.
3441 If not, it will force a year, usually the current year, and beep
3442 to remind you. Currently this setting is not recommended because
3443 the likelihood that you will open your Org files in an Emacs that
3444 has limited date range is not negligible.
3446 A workaround for this problem is to use diary sexp dates for time
3447 stamps outside of this range."
3448 :group 'org-time
3449 :version "24.1"
3450 :type 'boolean)
3452 (defcustom org-read-date-display-live t
3453 "Non-nil means display current interpretation of date prompt live.
3454 This display will be in an overlay, in the minibuffer."
3455 :group 'org-time
3456 :type 'boolean)
3458 (defcustom org-read-date-popup-calendar t
3459 "Non-nil means pop up a calendar when prompting for a date.
3460 In the calendar, the date can be selected with mouse-1. However, the
3461 minibuffer will also be active, and you can simply enter the date as well.
3462 When nil, only the minibuffer will be available."
3463 :group 'org-time
3464 :type 'boolean)
3465 (defvaralias 'org-popup-calendar-for-date-prompt
3466 'org-read-date-popup-calendar)
3468 (defcustom org-extend-today-until 0
3469 "The hour when your day really ends. Must be an integer.
3470 This has influence for the following applications:
3471 - When switching the agenda to \"today\". It it is still earlier than
3472 the time given here, the day recognized as TODAY is actually yesterday.
3473 - When a date is read from the user and it is still before the time given
3474 here, the current date and time will be assumed to be yesterday, 23:59.
3475 Also, timestamps inserted in capture templates follow this rule.
3477 IMPORTANT: This is a feature whose implementation is and likely will
3478 remain incomplete. Really, it is only here because past midnight seems to
3479 be the favorite working time of John Wiegley :-)"
3480 :group 'org-time
3481 :type 'integer)
3483 (defcustom org-use-effective-time nil
3484 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3485 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3486 \"effective time\" of any timestamps between midnight and 8am will be
3487 23:59 of the previous day."
3488 :group 'org-time
3489 :version "24.1"
3490 :type 'boolean)
3492 (defcustom org-use-last-clock-out-time-as-effective-time nil
3493 "When non-nil, use the last clock out time for `org-todo'.
3494 Note that this option has precedence over the combined use of
3495 `org-use-effective-time' and `org-extend-today-until'."
3496 :group 'org-time
3497 :version "24.4"
3498 :package-version '(Org . "8.0")
3499 :type 'boolean)
3501 (defcustom org-edit-timestamp-down-means-later nil
3502 "Non-nil means S-down will increase the time in a time stamp.
3503 When nil, S-up will increase."
3504 :group 'org-time
3505 :type 'boolean)
3507 (defcustom org-calendar-follow-timestamp-change t
3508 "Non-nil means make the calendar window follow timestamp changes.
3509 When a timestamp is modified and the calendar window is visible, it will be
3510 moved to the new date."
3511 :group 'org-time
3512 :type 'boolean)
3514 (defgroup org-tags nil
3515 "Options concerning tags in Org-mode."
3516 :tag "Org Tags"
3517 :group 'org)
3519 (defcustom org-tag-alist nil
3520 "Default tags available in Org files.
3522 The value of this variable is an alist. Associations either:
3524 (TAG)
3525 (TAG . SELECT)
3526 (SPECIAL)
3528 where TAG is a tag as a string, SELECT is a character, used to
3529 select that tag through the fast tag selection interface, and
3530 SPECIAL is one of the following keywords: `:startgroup',
3531 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3532 `:newline'. These keywords are used to define a hierarchy of
3533 tags. See manual for details.
3535 When this variable is nil, Org mode bases tag input on what is
3536 already in the buffer. The value can be overridden locally by
3537 using a TAGS keyword, e.g.,
3539 #+TAGS: tag1 tag2
3541 See also `org-tag-persistent-alist' to sidestep this behavior."
3542 :group 'org-tags
3543 :type '(repeat
3544 (choice
3545 (cons (string :tag "Tag name")
3546 (character :tag "Access char"))
3547 (const :tag "Start radio group" (:startgroup))
3548 (const :tag "Start tag group, non distinct" (:startgrouptag))
3549 (const :tag "Group tags delimiter" (:grouptags))
3550 (const :tag "End radio group" (:endgroup))
3551 (const :tag "End tag group, non distinct" (:endgrouptag))
3552 (const :tag "New line" (:newline)))))
3554 (defcustom org-tag-persistent-alist nil
3555 "Tags always available in Org files.
3557 The value of this variable is an alist. Associations either:
3559 (TAG)
3560 (TAG . SELECT)
3561 (SPECIAL)
3563 where TAG is a tag as a string, SELECT is a character, used to
3564 select that tag through the fast tag selection interface, and
3565 SPECIAL is one of the following keywords: `:startgroup',
3566 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3567 `:newline'. These keywords are used to define a hierarchy of
3568 tags. See manual for details.
3570 Unlike to `org-tag-alist', tags defined in this variable do not
3571 depend on a local TAGS keyword. Instead, to disable these tags
3572 on a per-file basis, insert anywhere in the file:
3574 #+STARTUP: noptag"
3575 :group 'org-tags
3576 :type '(repeat
3577 (choice
3578 (cons (string :tag "Tag name")
3579 (character :tag "Access char"))
3580 (const :tag "Start radio group" (:startgroup))
3581 (const :tag "Start tag group, non distinct" (:startgrouptag))
3582 (const :tag "Group tags delimiter" (:grouptags))
3583 (const :tag "End radio group" (:endgroup))
3584 (const :tag "End tag group, non distinct" (:endgrouptag))
3585 (const :tag "New line" (:newline)))))
3587 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3588 "If non-nil, always offer completion for all tags of all agenda files.
3589 Instead of customizing this variable directly, you might want to
3590 set it locally for capture buffers, because there no list of
3591 tags in that file can be created dynamically (there are none).
3593 (add-hook \\='org-capture-mode-hook
3594 (lambda ()
3595 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3596 :group 'org-tags
3597 :version "24.1"
3598 :type 'boolean)
3600 (defvar org-file-tags nil
3601 "List of tags that can be inherited by all entries in the file.
3602 The tags will be inherited if the variable `org-use-tag-inheritance'
3603 says they should be.
3604 This variable is populated from #+FILETAGS lines.")
3606 (defcustom org-use-fast-tag-selection 'auto
3607 "Non-nil means use fast tag selection scheme.
3608 This is a special interface to select and deselect tags with single keys.
3609 When nil, fast selection is never used.
3610 When the symbol `auto', fast selection is used if and only if selection
3611 characters for tags have been configured, either through the variable
3612 `org-tag-alist' or through a #+TAGS line in the buffer.
3613 When t, fast selection is always used and selection keys are assigned
3614 automatically if necessary."
3615 :group 'org-tags
3616 :type '(choice
3617 (const :tag "Always" t)
3618 (const :tag "Never" nil)
3619 (const :tag "When selection characters are configured" auto)))
3621 (defcustom org-fast-tag-selection-single-key nil
3622 "Non-nil means fast tag selection exits after first change.
3623 When nil, you have to press RET to exit it.
3624 During fast tag selection, you can toggle this flag with `C-c'.
3625 This variable can also have the value `expert'. In this case, the window
3626 displaying the tags menu is not even shown, until you press C-c again."
3627 :group 'org-tags
3628 :type '(choice
3629 (const :tag "No" nil)
3630 (const :tag "Yes" t)
3631 (const :tag "Expert" expert)))
3633 (defvar org-fast-tag-selection-include-todo nil
3634 "Non-nil means fast tags selection interface will also offer TODO states.
3635 This is an undocumented feature, you should not rely on it.")
3637 (defcustom org-tags-column -77
3638 "The column to which tags should be indented in a headline.
3639 If this number is positive, it specifies the column. If it is negative,
3640 it means that the tags should be flushright to that column. For example,
3641 -80 works well for a normal 80 character screen.
3642 When 0, place tags directly after headline text, with only one space in
3643 between."
3644 :group 'org-tags
3645 :type 'integer)
3647 (defcustom org-auto-align-tags t
3648 "Non-nil keeps tags aligned when modifying headlines.
3649 Some operations (i.e. demoting) change the length of a headline and
3650 therefore shift the tags around. With this option turned on, after
3651 each such operation the tags are again aligned to `org-tags-column'."
3652 :group 'org-tags
3653 :type 'boolean)
3655 (defcustom org-use-tag-inheritance t
3656 "Non-nil means tags in levels apply also for sublevels.
3657 When nil, only the tags directly given in a specific line apply there.
3658 This may also be a list of tags that should be inherited, or a regexp that
3659 matches tags that should be inherited. Additional control is possible
3660 with the variable `org-tags-exclude-from-inheritance' which gives an
3661 explicit list of tags to be excluded from inheritance, even if the value of
3662 `org-use-tag-inheritance' would select it for inheritance.
3664 If this option is t, a match early-on in a tree can lead to a large
3665 number of matches in the subtree when constructing the agenda or creating
3666 a sparse tree. If you only want to see the first match in a tree during
3667 a search, check out the variable `org-tags-match-list-sublevels'."
3668 :group 'org-tags
3669 :type '(choice
3670 (const :tag "Not" nil)
3671 (const :tag "Always" t)
3672 (repeat :tag "Specific tags" (string :tag "Tag"))
3673 (regexp :tag "Tags matched by regexp")))
3675 (defcustom org-tags-exclude-from-inheritance nil
3676 "List of tags that should never be inherited.
3677 This is a way to exclude a few tags from inheritance. For way to do
3678 the opposite, to actively allow inheritance for selected tags,
3679 see the variable `org-use-tag-inheritance'."
3680 :group 'org-tags
3681 :type '(repeat (string :tag "Tag")))
3683 (defun org-tag-inherit-p (tag)
3684 "Check if TAG is one that should be inherited."
3685 (cond
3686 ((member tag org-tags-exclude-from-inheritance) nil)
3687 ((eq org-use-tag-inheritance t) t)
3688 ((not org-use-tag-inheritance) nil)
3689 ((stringp org-use-tag-inheritance)
3690 (string-match org-use-tag-inheritance tag))
3691 ((listp org-use-tag-inheritance)
3692 (member tag org-use-tag-inheritance))
3693 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3695 (defcustom org-tags-match-list-sublevels t
3696 "Non-nil means list also sublevels of headlines matching a search.
3697 This variable applies to tags/property searches, and also to stuck
3698 projects because this search is based on a tags match as well.
3700 When set to the symbol `indented', sublevels are indented with
3701 leading dots.
3703 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3704 the sublevels of a headline matching a tag search often also match
3705 the same search. Listing all of them can create very long lists.
3706 Setting this variable to nil causes subtrees of a match to be skipped.
3708 This variable is semi-obsolete and probably should always be true. It
3709 is better to limit inheritance to certain tags using the variables
3710 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3711 :group 'org-tags
3712 :type '(choice
3713 (const :tag "No, don't list them" nil)
3714 (const :tag "Yes, do list them" t)
3715 (const :tag "List them, indented with leading dots" indented)))
3717 (defcustom org-tags-sort-function nil
3718 "When set, tags are sorted using this function as a comparator."
3719 :group 'org-tags
3720 :type '(choice
3721 (const :tag "No sorting" nil)
3722 (const :tag "Alphabetical" string<)
3723 (const :tag "Reverse alphabetical" string>)
3724 (function :tag "Custom function" nil)))
3726 (defvar org-tags-history nil
3727 "History of minibuffer reads for tags.")
3728 (defvar org-last-tags-completion-table nil
3729 "The last used completion table for tags.")
3730 (defvar org-after-tags-change-hook nil
3731 "Hook that is run after the tags in a line have changed.")
3733 (defgroup org-properties nil
3734 "Options concerning properties in Org-mode."
3735 :tag "Org Properties"
3736 :group 'org)
3738 (defcustom org-property-format "%-10s %s"
3739 "How property key/value pairs should be formatted by `indent-line'.
3740 When `indent-line' hits a property definition, it will format the line
3741 according to this format, mainly to make sure that the values are
3742 lined-up with respect to each other."
3743 :group 'org-properties
3744 :type 'string)
3746 (defcustom org-properties-postprocess-alist nil
3747 "Alist of properties and functions to adjust inserted values.
3748 Elements of this alist must be of the form
3750 ([string] [function])
3752 where [string] must be a property name and [function] must be a
3753 lambda expression: this lambda expression must take one argument,
3754 the value to adjust, and return the new value as a string.
3756 For example, this element will allow the property \"Remaining\"
3757 to be updated wrt the relation between the \"Effort\" property
3758 and the clock summary:
3760 ((\"Remaining\" (lambda(value)
3761 (let ((clocksum (org-clock-sum-current-item))
3762 (effort (org-duration-string-to-minutes
3763 (org-entry-get (point) \"Effort\"))))
3764 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3765 :group 'org-properties
3766 :version "24.1"
3767 :type '(alist :key-type (string :tag "Property")
3768 :value-type (function :tag "Function")))
3770 (defcustom org-use-property-inheritance nil
3771 "Non-nil means properties apply also for sublevels.
3773 This setting is chiefly used during property searches. Turning it on can
3774 cause significant overhead when doing a search, which is why it is not
3775 on by default.
3777 When nil, only the properties directly given in the current entry count.
3778 When t, every property is inherited. The value may also be a list of
3779 properties that should have inheritance, or a regular expression matching
3780 properties that should be inherited.
3782 However, note that some special properties use inheritance under special
3783 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3784 and the properties ending in \"_ALL\" when they are used as descriptor
3785 for valid values of a property.
3787 Note for programmers:
3788 When querying an entry with `org-entry-get', you can control if inheritance
3789 should be used. By default, `org-entry-get' looks only at the local
3790 properties. You can request inheritance by setting the inherit argument
3791 to t (to force inheritance) or to `selective' (to respect the setting
3792 in this variable)."
3793 :group 'org-properties
3794 :type '(choice
3795 (const :tag "Not" nil)
3796 (const :tag "Always" t)
3797 (repeat :tag "Specific properties" (string :tag "Property"))
3798 (regexp :tag "Properties matched by regexp")))
3800 (defun org-property-inherit-p (property)
3801 "Check if PROPERTY is one that should be inherited."
3802 (cond
3803 ((eq org-use-property-inheritance t) t)
3804 ((not org-use-property-inheritance) nil)
3805 ((stringp org-use-property-inheritance)
3806 (string-match org-use-property-inheritance property))
3807 ((listp org-use-property-inheritance)
3808 (member property org-use-property-inheritance))
3809 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3811 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3812 "The default column format, if no other format has been defined.
3813 This variable can be set on the per-file basis by inserting a line
3815 #+COLUMNS: %25ITEM ....."
3816 :group 'org-properties
3817 :type 'string)
3819 (defcustom org-columns-ellipses ".."
3820 "The ellipses to be used when a field in column view is truncated.
3821 When this is the empty string, as many characters as possible are shown,
3822 but then there will be no visual indication that the field has been truncated.
3823 When this is a string of length N, the last N characters of a truncated
3824 field are replaced by this string. If the column is narrower than the
3825 ellipses string, only part of the ellipses string will be shown."
3826 :group 'org-properties
3827 :type 'string)
3829 (defconst org-global-properties-fixed
3830 '(("VISIBILITY_ALL" . "folded children content all")
3831 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3832 "List of property/value pairs that can be inherited by any entry.
3834 These are fixed values, for the preset properties. The user variable
3835 that can be used to add to this list is `org-global-properties'.
3837 The entries in this list are cons cells where the car is a property
3838 name and cdr is a string with the value. If the value represents
3839 multiple items like an \"_ALL\" property, separate the items by
3840 spaces.")
3842 (defcustom org-global-properties nil
3843 "List of property/value pairs that can be inherited by any entry.
3845 This list will be combined with the constant `org-global-properties-fixed'.
3847 The entries in this list are cons cells where the car is a property
3848 name and cdr is a string with the value.
3850 You can set buffer-local values for the same purpose in the variable
3851 `org-file-properties' this by adding lines like
3853 #+PROPERTY: NAME VALUE"
3854 :group 'org-properties
3855 :type '(repeat
3856 (cons (string :tag "Property")
3857 (string :tag "Value"))))
3859 (defvar-local org-file-properties nil
3860 "List of property/value pairs that can be inherited by any entry.
3861 Valid for the current buffer.
3862 This variable is populated from #+PROPERTY lines.")
3864 (defgroup org-agenda nil
3865 "Options concerning agenda views in Org-mode."
3866 :tag "Org Agenda"
3867 :group 'org)
3869 (defvar-local org-category nil
3870 "Variable used by org files to set a category for agenda display.
3871 Such files should use a file variable to set it, for example
3873 # -*- mode: org; org-category: \"ELisp\"
3875 or contain a special line
3877 #+CATEGORY: ELisp
3879 If the file does not specify a category, then file's base name
3880 is used instead.")
3881 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3883 (defcustom org-agenda-files nil
3884 "The files to be used for agenda display.
3885 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3886 \\[org-remove-file]. You can also use customize to edit the list.
3888 If an entry is a directory, all files in that directory that are matched by
3889 `org-agenda-file-regexp' will be part of the file list.
3891 If the value of the variable is not a list but a single file name, then
3892 the list of agenda files is actually stored and maintained in that file, one
3893 agenda file per line. In this file paths can be given relative to
3894 `org-directory'. Tilde expansion and environment variable substitution
3895 are also made."
3896 :group 'org-agenda
3897 :type '(choice
3898 (repeat :tag "List of files and directories" file)
3899 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3901 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3902 "Regular expression to match files for `org-agenda-files'.
3903 If any element in the list in that variable contains a directory instead
3904 of a normal file, all files in that directory that are matched by this
3905 regular expression will be included."
3906 :group 'org-agenda
3907 :type 'regexp)
3909 (defcustom org-agenda-text-search-extra-files nil
3910 "List of extra files to be searched by text search commands.
3911 These files will be searched in addition to the agenda files by the
3912 commands `org-search-view' (`\\[org-agenda] s') \
3913 and `org-occur-in-agenda-files'.
3914 Note that these files will only be searched for text search commands,
3915 not for the other agenda views like todo lists, tag searches or the weekly
3916 agenda. This variable is intended to list notes and possibly archive files
3917 that should also be searched by these two commands.
3918 In fact, if the first element in the list is the symbol `agenda-archives',
3919 then all archive files of all agenda files will be added to the search
3920 scope."
3921 :group 'org-agenda
3922 :type '(set :greedy t
3923 (const :tag "Agenda Archives" agenda-archives)
3924 (repeat :inline t (file))))
3926 (defvaralias 'org-agenda-multi-occur-extra-files
3927 'org-agenda-text-search-extra-files)
3929 (defcustom org-agenda-skip-unavailable-files nil
3930 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3931 A nil value means to remove them, after a query, from the list."
3932 :group 'org-agenda
3933 :type 'boolean)
3935 (defcustom org-calendar-to-agenda-key [?c]
3936 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3937 The command `org-calendar-goto-agenda' will be bound to this key. The
3938 default is the character `c' because then `c' can be used to switch back and
3939 forth between agenda and calendar."
3940 :group 'org-agenda
3941 :type 'sexp)
3943 (defcustom org-calendar-insert-diary-entry-key [?i]
3944 "The key to be installed in `calendar-mode-map' for adding diary entries.
3945 This option is irrelevant until `org-agenda-diary-file' has been configured
3946 to point to an Org file. When that is the case, the command
3947 `org-agenda-diary-entry' will be bound to the key given here, by default
3948 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3949 if you want to continue doing this, you need to change this to a different
3950 key."
3951 :group 'org-agenda
3952 :type 'sexp)
3954 (defcustom org-agenda-diary-file 'diary-file
3955 "File to which to add new entries with the `i' key in agenda and calendar.
3956 When this is the symbol `diary-file', the functionality in the Emacs
3957 calendar will be used to add entries to the `diary-file'. But when this
3958 points to a file, `org-agenda-diary-entry' will be used instead."
3959 :group 'org-agenda
3960 :type '(choice
3961 (const :tag "The standard Emacs diary file" diary-file)
3962 (file :tag "Special Org file diary entries")))
3964 (eval-after-load "calendar"
3965 '(progn
3966 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3967 'org-calendar-goto-agenda)
3968 (add-hook 'calendar-mode-hook
3969 (lambda ()
3970 (unless (eq org-agenda-diary-file 'diary-file)
3971 (define-key calendar-mode-map
3972 org-calendar-insert-diary-entry-key
3973 'org-agenda-diary-entry))))))
3975 (defgroup org-latex nil
3976 "Options for embedding LaTeX code into Org-mode."
3977 :tag "Org LaTeX"
3978 :group 'org)
3980 (defcustom org-format-latex-options
3981 '(:foreground default :background default :scale 1.0
3982 :html-foreground "Black" :html-background "Transparent"
3983 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3984 "Options for creating images from LaTeX fragments.
3985 This is a property list with the following properties:
3986 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3987 `default' means use the foreground of the default face.
3988 `auto' means use the foreground from the text face.
3989 :background the background color, or \"Transparent\".
3990 `default' means use the background of the default face.
3991 `auto' means use the background from the text face.
3992 :scale a scaling factor for the size of the images, to get more pixels
3993 :html-foreground, :html-background, :html-scale
3994 the same numbers for HTML export.
3995 :matchers a list indicating which matchers should be used to
3996 find LaTeX fragments. Valid members of this list are:
3997 \"begin\" find environments
3998 \"$1\" find single characters surrounded by $.$
3999 \"$\" find math expressions surrounded by $...$
4000 \"$$\" find math expressions surrounded by $$....$$
4001 \"\\(\" find math expressions surrounded by \\(...\\)
4002 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4003 :group 'org-latex
4004 :type 'plist)
4006 (defcustom org-format-latex-signal-error t
4007 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4008 When nil, just push out a message."
4009 :group 'org-latex
4010 :version "24.1"
4011 :type 'boolean)
4013 (defcustom org-latex-to-mathml-jar-file nil
4014 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4015 Use this to specify additional executable file say a jar file.
4017 When using MathToWeb as the converter, specify the full-path to
4018 your mathtoweb.jar file."
4019 :group 'org-latex
4020 :version "24.1"
4021 :type '(choice
4022 (const :tag "None" nil)
4023 (file :tag "JAR file" :must-match t)))
4025 (defcustom org-latex-to-mathml-convert-command nil
4026 "Command to convert LaTeX fragments to MathML.
4027 Replace format-specifiers in the command as noted below and use
4028 `shell-command' to convert LaTeX to MathML.
4029 %j: Executable file in fully expanded form as specified by
4030 `org-latex-to-mathml-jar-file'.
4031 %I: Input LaTeX file in fully expanded form.
4032 %i: The latex fragment to be converted.
4033 %o: Output MathML file.
4035 This command is used by `org-create-math-formula'.
4037 When using MathToWeb as the converter, set this option to
4038 \"java -jar %j -unicode -force -df %o %I\".
4040 When using LaTeXML set this option to
4041 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4042 :group 'org-latex
4043 :version "24.1"
4044 :type '(choice
4045 (const :tag "None" nil)
4046 (string :tag "\nShell command")))
4048 (defcustom org-preview-latex-default-process 'dvipng
4049 "The default process to convert LaTeX fragments to image files.
4050 All available processes and theirs documents can be found in
4051 `org-preview-latex-process-alist', which see."
4052 :group 'org-latex
4053 :version "25.2"
4054 :package-version '(Org . "9.0")
4055 :type 'symbol)
4057 (defcustom org-preview-latex-process-alist
4058 '((dvipng
4059 :programs ("latex" "dvipng" "gs")
4060 :description "dvi > png"
4061 :message "you need to install the programs: latex, dvipng and ghostscript."
4062 :image-input-type "dvi"
4063 :image-output-type "png"
4064 :image-size-adjust (1.0 . 1.0)
4065 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4066 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4067 (dvisvgm
4068 :programs ("latex" "dvisvgm" "gs")
4069 :description "dvi > svg"
4070 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4071 :use-xcolor t
4072 :image-input-type "dvi"
4073 :image-output-type "svg"
4074 :image-size-adjust (1.7 . 1.5)
4075 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4076 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4077 (imagemagick
4078 :programs ("latex" "convert" "gs")
4079 :description "pdf > png"
4080 :message
4081 "you need to install the programs: latex, imagemagick and ghostscript."
4082 :use-xcolor t
4083 :image-input-type "pdf"
4084 :image-output-type "png"
4085 :image-size-adjust (1.0 . 1.0)
4086 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4087 :image-converter
4088 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4089 "Definitions of external processes for LaTeX previewing.
4090 Org mode can use some external commands to generate TeX snippet's images for
4091 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4092 `org-create-formula-image' how to call them.
4094 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4095 PROPERTIES accepts the following attributes:
4097 :programs list of strings, required programs.
4098 :description string, describe the process.
4099 :message string, message it when required programs cannot be found.
4100 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4101 :image-output-type string, output file type of image converter (e.g., \"png\").
4102 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4103 deal with background and foreground color of image.
4104 Otherwise, dvipng style background and foregroud color
4105 format are generated. You may then refer to them in
4106 command options with \"%F\" and \"%B\".
4107 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4108 image size showed in buffer and the cdr element is for
4109 HTML file. This option is only useful for process
4110 developers, users should use variable
4111 `org-format-latex-options' instead.
4112 :post-clean list of strings, files matched are to be cleaned up once
4113 the image is generated. When nil, the files with \".dvi\",
4114 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4115 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4116 be cleaned up.
4117 :latex-header list of strings, the LaTeX header of the snippet file.
4118 When nil, the fallback value is used instead, which is
4119 controlled by `org-format-latex-header',
4120 `org-latex-default-packages-alist' and
4121 `org-latex-packages-alist', which see.
4122 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4123 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4124 replaced with values defined below.
4125 :image-converter list of image converter commands strings. Each of them is
4126 given to the shell and supports any of the following
4127 place-holders defined below.
4129 Place-holders used by `:image-converter' and `:latex-compiler':
4131 %f input file name.
4132 %b base name of input file.
4133 %o base directory of input file.
4135 Place-holders only used by `:image-converter':
4137 %F foreground of image
4138 %B background of image
4139 %D dpi, which is used to adjust image size by some processing commands.
4140 %S the image size scale ratio, which is used to adjust image size by some
4141 processing commands."
4142 :group 'org-latex
4143 :version "25.2"
4144 :package-version '(Org . "9.0")
4145 :type '(alist :tag "LaTeX to image backends"
4146 :value-type (plist)))
4148 (defcustom org-preview-latex-image-directory "ltximg/"
4149 "Path to store latex preview images.
4150 A relative path here creates many directories relative to the
4151 processed org files paths. An absolute path puts all preview
4152 images at the same place."
4153 :group 'org-latex
4154 :version "25.1"
4155 :package-version '(Org . "9.0")
4156 :type 'string)
4158 (defun org-format-latex-mathml-available-p ()
4159 "Return t if `org-latex-to-mathml-convert-command' is usable."
4160 (save-match-data
4161 (when (and (boundp 'org-latex-to-mathml-convert-command)
4162 org-latex-to-mathml-convert-command)
4163 (let ((executable (car (split-string
4164 org-latex-to-mathml-convert-command))))
4165 (when (executable-find executable)
4166 (if (string-match
4167 "%j" org-latex-to-mathml-convert-command)
4168 (file-readable-p org-latex-to-mathml-jar-file)
4169 t))))))
4171 (defcustom org-format-latex-header "\\documentclass{article}
4172 \\usepackage[usenames]{color}
4173 \[PACKAGES]
4174 \[DEFAULT-PACKAGES]
4175 \\pagestyle{empty} % do not remove
4176 % The settings below are copied from fullpage.sty
4177 \\setlength{\\textwidth}{\\paperwidth}
4178 \\addtolength{\\textwidth}{-3cm}
4179 \\setlength{\\oddsidemargin}{1.5cm}
4180 \\addtolength{\\oddsidemargin}{-2.54cm}
4181 \\setlength{\\evensidemargin}{\\oddsidemargin}
4182 \\setlength{\\textheight}{\\paperheight}
4183 \\addtolength{\\textheight}{-\\headheight}
4184 \\addtolength{\\textheight}{-\\headsep}
4185 \\addtolength{\\textheight}{-\\footskip}
4186 \\addtolength{\\textheight}{-3cm}
4187 \\setlength{\\topmargin}{1.5cm}
4188 \\addtolength{\\topmargin}{-2.54cm}"
4189 "The document header used for processing LaTeX fragments.
4190 It is imperative that this header make sure that no page number
4191 appears on the page. The package defined in the variables
4192 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4193 will either replace the placeholder \"[PACKAGES]\" in this
4194 header, or they will be appended."
4195 :group 'org-latex
4196 :type 'string)
4198 (defun org-set-packages-alist (var val)
4199 "Set the packages alist and make sure it has 3 elements per entry."
4200 (set var (mapcar (lambda (x)
4201 (if (and (consp x) (= (length x) 2))
4202 (list (car x) (nth 1 x) t)
4204 val)))
4206 (defun org-get-packages-alist (var)
4207 "Get the packages alist and make sure it has 3 elements per entry."
4208 (mapcar (lambda (x)
4209 (if (and (consp x) (= (length x) 2))
4210 (list (car x) (nth 1 x) t)
4212 (default-value var)))
4214 (defcustom org-latex-default-packages-alist
4215 '(("AUTO" "inputenc" t ("pdflatex"))
4216 ("T1" "fontenc" t ("pdflatex"))
4217 ("" "graphicx" t)
4218 ("" "grffile" t)
4219 ("" "longtable" nil)
4220 ("" "wrapfig" nil)
4221 ("" "rotating" nil)
4222 ("normalem" "ulem" t)
4223 ("" "amsmath" t)
4224 ("" "textcomp" t)
4225 ("" "amssymb" t)
4226 ("" "capt-of" nil)
4227 ("" "hyperref" nil))
4228 "Alist of default packages to be inserted in the header.
4230 Change this only if one of the packages here causes an
4231 incompatibility with another package you are using.
4233 The packages in this list are needed by one part or another of
4234 Org mode to function properly:
4236 - inputenc, fontenc: for basic font and character selection
4237 - graphicx: for including images
4238 - grffile: allow periods and spaces in graphics file names
4239 - longtable: For multipage tables
4240 - wrapfig: for figure placement
4241 - rotating: for sideways figures and tables
4242 - ulem: for underline and strike-through
4243 - amsmath: for subscript and superscript and math environments
4244 - textcomp, amssymb: for various symbols used
4245 for interpreting the entities in `org-entities'. You can skip
4246 some of these packages if you don't use any of their symbols.
4247 - capt-of: for captions outside of floats
4248 - hyperref: for cross references
4250 Therefore you should not modify this variable unless you know
4251 what you are doing. The one reason to change it anyway is that
4252 you might be loading some other package that conflicts with one
4253 of the default packages. Each element is either a cell or
4254 a string.
4256 A cell is of the format
4258 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4260 If SNIPPET-FLAG is non-nil, the package also needs to be included
4261 when compiling LaTeX snippets into images for inclusion into
4262 non-LaTeX output. COMPILERS is a list of compilers that should
4263 include the package, see `org-latex-compiler'. If the document
4264 compiler is not in the list, and the list is non-nil, the package
4265 will not be inserted in the final document.
4267 A string will be inserted as-is in the header of the document."
4268 :group 'org-latex
4269 :group 'org-export-latex
4270 :set 'org-set-packages-alist
4271 :get 'org-get-packages-alist
4272 :version "25.1"
4273 :package-version '(Org . "8.3")
4274 :type '(repeat
4275 (choice
4276 (list :tag "options/package pair"
4277 (string :tag "options")
4278 (string :tag "package")
4279 (boolean :tag "Snippet"))
4280 (string :tag "A line of LaTeX"))))
4282 (defcustom org-latex-packages-alist nil
4283 "Alist of packages to be inserted in every LaTeX header.
4285 These will be inserted after `org-latex-default-packages-alist'.
4286 Each element is either a cell or a string.
4288 A cell is of the format:
4290 (\"options\" \"package\" SNIPPET-FLAG)
4292 SNIPPET-FLAG, when non-nil, indicates that this package is also
4293 needed when turning LaTeX snippets into images for inclusion into
4294 non-LaTeX output.
4296 A string will be inserted as-is in the header of the document.
4298 Make sure that you only list packages here which:
4300 - you want in every file;
4301 - do not conflict with the setup in `org-format-latex-header';
4302 - do not conflict with the default packages in
4303 `org-latex-default-packages-alist'."
4304 :group 'org-latex
4305 :group 'org-export-latex
4306 :set 'org-set-packages-alist
4307 :get 'org-get-packages-alist
4308 :type '(repeat
4309 (choice
4310 (list :tag "options/package pair"
4311 (string :tag "options")
4312 (string :tag "package")
4313 (boolean :tag "Snippet"))
4314 (string :tag "A line of LaTeX"))))
4316 (defgroup org-appearance nil
4317 "Settings for Org mode appearance."
4318 :tag "Org Appearance"
4319 :group 'org)
4321 (defcustom org-level-color-stars-only nil
4322 "Non-nil means fontify only the stars in each headline.
4323 When nil, the entire headline is fontified.
4324 Changing it requires restart of `font-lock-mode' to become effective
4325 also in regions already fontified."
4326 :group 'org-appearance
4327 :type 'boolean)
4329 (defcustom org-hide-leading-stars nil
4330 "Non-nil means hide the first N-1 stars in a headline.
4331 This works by using the face `org-hide' for these stars. This
4332 face is white for a light background, and black for a dark
4333 background. You may have to customize the face `org-hide' to
4334 make this work.
4335 Changing it requires restart of `font-lock-mode' to become effective
4336 also in regions already fontified.
4337 You may also set this on a per-file basis by adding one of the following
4338 lines to the buffer:
4340 #+STARTUP: hidestars
4341 #+STARTUP: showstars"
4342 :group 'org-appearance
4343 :type 'boolean)
4345 (defcustom org-hidden-keywords nil
4346 "List of symbols corresponding to keywords to be hidden the org buffer.
4347 For example, a value \\='(title) for this list will make the document's title
4348 appear in the buffer without the initial #+TITLE: keyword."
4349 :group 'org-appearance
4350 :version "24.1"
4351 :type '(set (const :tag "#+AUTHOR" author)
4352 (const :tag "#+DATE" date)
4353 (const :tag "#+EMAIL" email)
4354 (const :tag "#+TITLE" title)))
4356 (defcustom org-custom-properties nil
4357 "List of properties (as strings) with a special meaning.
4358 The default use of these custom properties is to let the user
4359 hide them with `org-toggle-custom-properties-visibility'."
4360 :group 'org-properties
4361 :group 'org-appearance
4362 :version "24.3"
4363 :type '(repeat (string :tag "Property Name")))
4365 (defcustom org-fontify-done-headline nil
4366 "Non-nil means change the face of a headline if it is marked DONE.
4367 Normally, only the TODO/DONE keyword indicates the state of a headline.
4368 When this is non-nil, the headline after the keyword is set to the
4369 `org-headline-done' as an additional indication."
4370 :group 'org-appearance
4371 :type 'boolean)
4373 (defcustom org-fontify-emphasized-text t
4374 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4375 Changing this variable requires a restart of Emacs to take effect."
4376 :group 'org-appearance
4377 :type 'boolean)
4379 (defcustom org-fontify-whole-heading-line nil
4380 "Non-nil means fontify the whole line for headings.
4381 This is useful when setting a background color for the
4382 org-level-* faces."
4383 :group 'org-appearance
4384 :type 'boolean)
4386 (defcustom org-highlight-latex-and-related nil
4387 "Non-nil means highlight LaTeX related syntax in the buffer.
4388 When non nil, the value should be a list containing any of the
4389 following symbols:
4390 `latex' Highlight LaTeX snippets and environments.
4391 `script' Highlight subscript and superscript.
4392 `entities' Highlight entities."
4393 :group 'org-appearance
4394 :version "24.4"
4395 :package-version '(Org . "8.0")
4396 :type '(choice
4397 (const :tag "No highlighting" nil)
4398 (set :greedy t :tag "Highlight"
4399 (const :tag "LaTeX snippets and environments" latex)
4400 (const :tag "Subscript and superscript" script)
4401 (const :tag "Entities" entities))))
4403 (defcustom org-hide-emphasis-markers nil
4404 "Non-nil mean font-lock should hide the emphasis marker characters."
4405 :group 'org-appearance
4406 :type 'boolean)
4408 (defcustom org-hide-macro-markers nil
4409 "Non-nil mean font-lock should hide the brackets marking macro calls."
4410 :group 'org-appearance
4411 :type 'boolean)
4413 (defcustom org-pretty-entities nil
4414 "Non-nil means show entities as UTF8 characters.
4415 When nil, the \\name form remains in the buffer."
4416 :group 'org-appearance
4417 :version "24.1"
4418 :type 'boolean)
4420 (defcustom org-pretty-entities-include-sub-superscripts t
4421 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4422 :group 'org-appearance
4423 :version "24.1"
4424 :type 'boolean)
4426 (defvar org-emph-re nil
4427 "Regular expression for matching emphasis.
4428 After a match, the match groups contain these elements:
4429 0 The match of the full regular expression, including the characters
4430 before and after the proper match
4431 1 The character before the proper match, or empty at beginning of line
4432 2 The proper match, including the leading and trailing markers
4433 3 The leading marker like * or /, indicating the type of highlighting
4434 4 The text between the emphasis markers, not including the markers
4435 5 The character after the match, empty at the end of a line")
4436 (defvar org-verbatim-re nil
4437 "Regular expression for matching verbatim text.")
4438 (defvar org-emphasis-regexp-components) ; defined just below
4439 (defvar org-emphasis-alist) ; defined just below
4440 (defun org-set-emph-re (var val)
4441 "Set variable and compute the emphasis regular expression."
4442 (set var val)
4443 (when (and (boundp 'org-emphasis-alist)
4444 (boundp 'org-emphasis-regexp-components)
4445 org-emphasis-alist org-emphasis-regexp-components)
4446 (let* ((e org-emphasis-regexp-components)
4447 (pre (car e))
4448 (post (nth 1 e))
4449 (border (nth 2 e))
4450 (body (nth 3 e))
4451 (nl (nth 4 e))
4452 (body1 (concat body "*?"))
4453 (markers (mapconcat 'car org-emphasis-alist ""))
4454 (vmarkers (mapconcat
4455 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4456 org-emphasis-alist "")))
4457 ;; make sure special characters appear at the right position in the class
4458 (if (string-match "\\^" markers)
4459 (setq markers (concat (replace-match "" t t markers) "^")))
4460 (if (string-match "-" markers)
4461 (setq markers (concat (replace-match "" t t markers) "-")))
4462 (if (string-match "\\^" vmarkers)
4463 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4464 (if (string-match "-" vmarkers)
4465 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4466 (if (> nl 0)
4467 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4468 (int-to-string nl) "\\}")))
4469 ;; Make the regexp
4470 (setq org-emph-re
4471 (concat "\\([" pre "]\\|^\\)"
4472 "\\("
4473 "\\([" markers "]\\)"
4474 "\\("
4475 "[^" border "]\\|"
4476 "[^" border "]"
4477 body1
4478 "[^" border "]"
4479 "\\)"
4480 "\\3\\)"
4481 "\\([" post "]\\|$\\)"))
4482 (setq org-verbatim-re
4483 (concat "\\([" pre "]\\|^\\)"
4484 "\\("
4485 "\\([" vmarkers "]\\)"
4486 "\\("
4487 "[^" border "]\\|"
4488 "[^" border "]"
4489 body1
4490 "[^" border "]"
4491 "\\)"
4492 "\\3\\)"
4493 "\\([" post "]\\|$\\)")))))
4495 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4496 ;; set this option proved cumbersome. See this message/thread:
4497 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4498 (defvar org-emphasis-regexp-components
4499 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4500 "Components used to build the regular expression for emphasis.
4501 This is a list with five entries. Terminology: In an emphasis string
4502 like \" *strong word* \", we call the initial space PREMATCH, the final
4503 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4504 and \"trong wor\" is the body. The different components in this variable
4505 specify what is allowed/forbidden in each part:
4507 pre Chars allowed as prematch. Beginning of line will be allowed too.
4508 post Chars allowed as postmatch. End of line will be allowed too.
4509 border The chars *forbidden* as border characters.
4510 body-regexp A regexp like \".\" to match a body character. Don't use
4511 non-shy groups here, and don't allow newline here.
4512 newline The maximum number of newlines allowed in an emphasis exp.
4514 You need to reload Org or to restart Emacs after customizing this.")
4516 (defcustom org-emphasis-alist
4517 '(("*" bold)
4518 ("/" italic)
4519 ("_" underline)
4520 ("=" org-verbatim verbatim)
4521 ("~" org-code verbatim)
4522 ("+" (:strike-through t)))
4523 "Alist of characters and faces to emphasize text.
4524 Text starting and ending with a special character will be emphasized,
4525 for example *bold*, _underlined_ and /italic/. This variable sets the
4526 marker characters and the face to be used by font-lock for highlighting
4527 in Org buffers.
4529 You need to reload Org or to restart Emacs after customizing this."
4530 :group 'org-appearance
4531 :set 'org-set-emph-re
4532 :version "24.4"
4533 :package-version '(Org . "8.0")
4534 :type '(repeat
4535 (list
4536 (string :tag "Marker character")
4537 (choice
4538 (face :tag "Font-lock-face")
4539 (plist :tag "Face property list"))
4540 (option (const verbatim)))))
4542 (defvar org-protecting-blocks '("src" "example" "export")
4543 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4544 This is needed for font-lock setup.")
4546 ;;; Functions and variables from their packages
4547 ;; Declared here to avoid compiler warnings
4548 (defvar mark-active)
4550 ;; Various packages
4551 (declare-function calc-eval "calc" (str &optional separator &rest args))
4552 (declare-function calendar-forward-day "cal-move" (arg))
4553 (declare-function calendar-goto-date "cal-move" (date))
4554 (declare-function calendar-goto-today "cal-move" ())
4555 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4556 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4557 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4558 (declare-function cdlatex-tab "ext:cdlatex" ())
4559 (declare-function dired-get-filename
4560 "dired"
4561 (&optional localp no-error-if-not-filep))
4562 (declare-function iswitchb-read-buffer
4563 "iswitchb"
4564 (prompt &optional
4565 default require-match _predicate start matches-set))
4566 (declare-function org-agenda-change-all-lines
4567 "org-agenda"
4568 (newhead hdmarker &optional fixface just-this))
4569 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4570 "org-agenda"
4571 (&optional end))
4572 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4573 (declare-function org-agenda-format-item
4574 "org-agenda"
4575 (extra txt &optional level category tags dotime
4576 remove-re habitp))
4577 (declare-function org-agenda-maybe-redo "org-agenda" ())
4578 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4579 (declare-function org-agenda-save-markers-for-cut-and-paste
4580 "org-agenda"
4581 (beg end))
4582 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4583 (declare-function org-agenda-skip "org-agenda" ())
4584 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4585 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4586 (declare-function org-indent-mode "org-indent" (&optional arg))
4587 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4588 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4589 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4590 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4591 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4592 (declare-function parse-time-string "parse-time" (string))
4593 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4595 (defvar align-mode-rules-list)
4596 (defvar calc-embedded-close-formula)
4597 (defvar calc-embedded-open-formula)
4598 (defvar calc-embedded-open-mode)
4599 (defvar font-lock-unfontify-region-function)
4600 (defvar iswitchb-temp-buflist)
4601 (defvar org-agenda-tags-todo-honor-ignore-options)
4602 (defvar remember-data-file)
4603 (defvar texmathp-why)
4605 ;;;###autoload
4606 (defun turn-on-orgtbl ()
4607 "Unconditionally turn on `orgtbl-mode'."
4608 (require 'org-table)
4609 (orgtbl-mode 1))
4611 (defun org-at-table-p (&optional table-type)
4612 "Non-nil if the cursor is inside an Org table.
4613 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4614 If `org-enable-table-editor' is nil, return nil unconditionally."
4615 (and
4616 org-enable-table-editor
4617 (save-excursion
4618 (beginning-of-line)
4619 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4620 (or (not (derived-mode-p 'org-mode))
4621 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4622 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4624 (defun org-at-table.el-p ()
4625 "Non-nil when point is at a table.el table."
4626 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4627 (let ((element (org-element-at-point)))
4628 (and (eq (org-element-type element) 'table)
4629 (eq (org-element-property :type element) 'table.el)))))
4631 (defun org-at-table-hline-p ()
4632 "Non-nil when point is inside a hline in a table.
4633 Assume point is already in a table. If `org-enable-table-editor'
4634 is nil, return nil unconditionally."
4635 (and org-enable-table-editor
4636 (save-excursion
4637 (beginning-of-line)
4638 (looking-at org-table-hline-regexp))))
4640 (defun org-table-map-tables (function &optional quietly)
4641 "Apply FUNCTION to the start of all tables in the buffer."
4642 (org-with-wide-buffer
4643 (goto-char (point-min))
4644 (while (re-search-forward org-table-any-line-regexp nil t)
4645 (unless quietly
4646 (message "Mapping tables: %d%%"
4647 (floor (* 100.0 (point)) (buffer-size))))
4648 (beginning-of-line 1)
4649 (when (and (looking-at org-table-line-regexp)
4650 ;; Exclude tables in src/example/verbatim/clocktable blocks
4651 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4652 (save-excursion (funcall function))
4653 (or (looking-at org-table-line-regexp)
4654 (forward-char 1)))
4655 (re-search-forward org-table-any-border-regexp nil 1)))
4656 (unless quietly (message "Mapping tables: done")))
4658 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4659 (declare-function org-clock-update-mode-line "org-clock" ())
4660 (declare-function org-resolve-clocks "org-clock"
4661 (&optional also-non-dangling-p prompt last-valid))
4663 (defun org-at-TBLFM-p (&optional pos)
4664 "Non-nil when point (or POS) is in #+TBLFM line."
4665 (save-excursion
4666 (goto-char (or pos (point)))
4667 (beginning-of-line)
4668 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4669 (eq (org-element-type (org-element-at-point)) 'table))))
4671 (defvar org-clock-start-time)
4672 (defvar org-clock-marker (make-marker)
4673 "Marker recording the last clock-in.")
4674 (defvar org-clock-hd-marker (make-marker)
4675 "Marker recording the last clock-in, but the headline position.")
4676 (defvar org-clock-heading ""
4677 "The heading of the current clock entry.")
4678 (defun org-clock-is-active ()
4679 "Return the buffer where the clock is currently running.
4680 Return nil if no clock is running."
4681 (marker-buffer org-clock-marker))
4683 (defun org-check-running-clock ()
4684 "Check if the current buffer contains the running clock.
4685 If yes, offer to stop it and to save the buffer with the changes."
4686 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4687 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4688 (buffer-name))))
4689 (org-clock-out)
4690 (when (y-or-n-p "Save changed buffer?")
4691 (save-buffer))))
4693 (defun org-clocktable-try-shift (dir n)
4694 "Check if this line starts a clock table, if yes, shift the time block."
4695 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4696 (org-clocktable-shift dir n)))
4698 ;;;###autoload
4699 (defun org-clock-persistence-insinuate ()
4700 "Set up hooks for clock persistence."
4701 (require 'org-clock)
4702 (add-hook 'org-mode-hook 'org-clock-load)
4703 (add-hook 'kill-emacs-hook 'org-clock-save))
4705 (defgroup org-archive nil
4706 "Options concerning archiving in Org-mode."
4707 :tag "Org Archive"
4708 :group 'org-structure)
4710 (defcustom org-archive-location "%s_archive::"
4711 "The location where subtrees should be archived.
4713 The value of this variable is a string, consisting of two parts,
4714 separated by a double-colon. The first part is a filename and
4715 the second part is a headline.
4717 When the filename is omitted, archiving happens in the same file.
4718 %s in the filename will be replaced by the current file
4719 name (without the directory part). Archiving to a different file
4720 is useful to keep archived entries from contributing to the
4721 Org Agenda.
4723 The archived entries will be filed as subtrees of the specified
4724 headline. When the headline is omitted, the subtrees are simply
4725 filed away at the end of the file, as top-level entries. Also in
4726 the heading you can use %s to represent the file name, this can be
4727 useful when using the same archive for a number of different files.
4729 Here are a few examples:
4730 \"%s_archive::\"
4731 If the current file is Projects.org, archive in file
4732 Projects.org_archive, as top-level trees. This is the default.
4734 \"::* Archived Tasks\"
4735 Archive in the current file, under the top-level headline
4736 \"* Archived Tasks\".
4738 \"~/org/archive.org::\"
4739 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4741 \"~/org/archive.org::* From %s\"
4742 Archive in file ~/org/archive.org (absolute path), under headlines
4743 \"From FILENAME\" where file name is the current file name.
4745 \"~/org/datetree.org::datetree/* Finished Tasks\"
4746 The \"datetree/\" string is special, signifying to archive
4747 items to the datetree. Items are placed in either the CLOSED
4748 date of the item, or the current date if there is no CLOSED date.
4749 The heading will be a subentry to the current date. There doesn't
4750 need to be a heading, but there always needs to be a slash after
4751 datetree. For example, to store archived items directly in the
4752 datetree, use \"~/org/datetree.org::datetree/\".
4754 \"basement::** Finished Tasks\"
4755 Archive in file ./basement (relative path), as level 3 trees
4756 below the level 2 heading \"** Finished Tasks\".
4758 You may set this option on a per-file basis by adding to the buffer a
4759 line like
4761 #+ARCHIVE: basement::** Finished Tasks
4763 You may also define it locally for a subtree by setting an ARCHIVE property
4764 in the entry. If such a property is found in an entry, or anywhere up
4765 the hierarchy, it will be used."
4766 :group 'org-archive
4767 :type 'string)
4769 (defcustom org-agenda-skip-archived-trees t
4770 "Non-nil means the agenda will skip any items located in archived trees.
4771 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4772 variable is no longer recommended, you should leave it at the value t.
4773 Instead, use the key `v' to cycle the archives-mode in the agenda."
4774 :group 'org-archive
4775 :group 'org-agenda-skip
4776 :type 'boolean)
4778 (defcustom org-columns-skip-archived-trees t
4779 "Non-nil means ignore archived trees when creating column view."
4780 :group 'org-archive
4781 :group 'org-properties
4782 :type 'boolean)
4784 (defcustom org-cycle-open-archived-trees nil
4785 "Non-nil means `org-cycle' will open archived trees.
4786 An archived tree is a tree marked with the tag ARCHIVE.
4787 When nil, archived trees will stay folded. You can still open them with
4788 normal outline commands like `show-all', but not with the cycling commands."
4789 :group 'org-archive
4790 :group 'org-cycle
4791 :type 'boolean)
4793 (defcustom org-sparse-tree-open-archived-trees nil
4794 "Non-nil means sparse tree construction shows matches in archived trees.
4795 When nil, matches in these trees are highlighted, but the trees are kept in
4796 collapsed state."
4797 :group 'org-archive
4798 :group 'org-sparse-trees
4799 :type 'boolean)
4801 (defcustom org-sparse-tree-default-date-type nil
4802 "The default date type when building a sparse tree.
4803 When this is nil, a date is a scheduled or a deadline timestamp.
4804 Otherwise, these types are allowed:
4806 all: all timestamps
4807 active: only active timestamps (<...>)
4808 inactive: only inactive timestamps ([...])
4809 scheduled: only scheduled timestamps
4810 deadline: only deadline timestamps"
4811 :type '(choice (const :tag "Scheduled or deadline" nil)
4812 (const :tag "All timestamps" all)
4813 (const :tag "Only active timestamps" active)
4814 (const :tag "Only inactive timestamps" inactive)
4815 (const :tag "Only scheduled timestamps" scheduled)
4816 (const :tag "Only deadline timestamps" deadline)
4817 (const :tag "Only closed timestamps" closed))
4818 :version "25.1"
4819 :package-version '(Org . "8.3")
4820 :group 'org-sparse-trees)
4822 (defun org-cycle-hide-archived-subtrees (state)
4823 "Re-hide all archived subtrees after a visibility state change."
4824 (when (and (not org-cycle-open-archived-trees)
4825 (not (memq state '(overview folded))))
4826 (save-excursion
4827 (let* ((globalp (memq state '(contents all)))
4828 (beg (if globalp (point-min) (point)))
4829 (end (if globalp (point-max) (org-end-of-subtree t))))
4830 (org-hide-archived-subtrees beg end)
4831 (goto-char beg)
4832 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4833 (message "%s" (substitute-command-keys
4834 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4836 (defun org-force-cycle-archived ()
4837 "Cycle subtree even if it is archived."
4838 (interactive)
4839 (setq this-command 'org-cycle)
4840 (let ((org-cycle-open-archived-trees t))
4841 (call-interactively 'org-cycle)))
4843 (defun org-hide-archived-subtrees (beg end)
4844 "Re-hide all archived subtrees after a visibility state change."
4845 (org-with-wide-buffer
4846 (let ((case-fold-search nil)
4847 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4848 (goto-char beg)
4849 ;; Include headline point is currently on.
4850 (beginning-of-line)
4851 (while (and (< (point) end) (re-search-forward re end t))
4852 (when (member org-archive-tag (org-get-tags))
4853 (org-flag-subtree t)
4854 (org-end-of-subtree t))))))
4856 (declare-function outline-end-of-heading "outline" ())
4857 (declare-function outline-flag-region "outline" (from to flag))
4858 (defun org-flag-subtree (flag)
4859 (save-excursion
4860 (org-back-to-heading t)
4861 (outline-end-of-heading)
4862 (outline-flag-region (point)
4863 (progn (org-end-of-subtree t) (point))
4864 flag)))
4866 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4868 ;; Declare Column View Code
4870 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4871 (declare-function org-columns-compute "org-colview" (property))
4873 ;; Declare ID code
4875 (declare-function org-id-store-link "org-id")
4876 (declare-function org-id-locations-load "org-id")
4877 (declare-function org-id-locations-save "org-id")
4878 (defvar org-id-track-globally)
4880 ;;; Variables for pre-computed regular expressions, all buffer local
4882 (defvar-local org-todo-regexp nil
4883 "Matches any of the TODO state keywords.")
4884 (defvar-local org-not-done-regexp nil
4885 "Matches any of the TODO state keywords except the last one.")
4886 (defvar-local org-not-done-heading-regexp nil
4887 "Matches a TODO headline that is not done.")
4888 (defvar-local org-todo-line-regexp nil
4889 "Matches a headline and puts TODO state into group 2 if present.")
4890 (defvar-local org-complex-heading-regexp nil
4891 "Matches a headline and puts everything into groups:
4892 group 1: the stars
4893 group 2: The todo keyword, maybe
4894 group 3: Priority cookie
4895 group 4: True headline
4896 group 5: Tags")
4897 (defvar-local org-complex-heading-regexp-format nil
4898 "Printf format to make regexp to match an exact headline.
4899 This regexp will match the headline of any node which has the
4900 exact headline text that is put into the format, but may have any
4901 TODO state, priority and tags.")
4902 (defvar-local org-todo-line-tags-regexp nil
4903 "Matches a headline and puts TODO state into group 2 if present.
4904 Also put tags into group 4 if tags are present.")
4906 (defconst org-plain-time-of-day-regexp
4907 (concat
4908 "\\(\\<[012]?[0-9]"
4909 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4910 "\\(--?"
4911 "\\(\\<[012]?[0-9]"
4912 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4913 "\\)?")
4914 "Regular expression to match a plain time or time range.
4915 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4916 groups carry important information:
4917 0 the full match
4918 1 the first time, range or not
4919 8 the second time, if it is a range.")
4921 (defconst org-plain-time-extension-regexp
4922 (concat
4923 "\\(\\<[012]?[0-9]"
4924 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4925 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4926 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4927 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4928 groups carry important information:
4929 0 the full match
4930 7 hours of duration
4931 9 minutes of duration")
4933 (defconst org-stamp-time-of-day-regexp
4934 (concat
4935 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4936 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4937 "\\(--?"
4938 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4939 "Regular expression to match a timestamp time or time range.
4940 After a match, the following groups carry important information:
4941 0 the full match
4942 1 date plus weekday, for back referencing to make sure both times are on the same day
4943 2 the first time, range or not
4944 4 the second time, if it is a range.")
4946 (defconst org-startup-options
4947 '(("fold" org-startup-folded t)
4948 ("overview" org-startup-folded t)
4949 ("nofold" org-startup-folded nil)
4950 ("showall" org-startup-folded nil)
4951 ("showeverything" org-startup-folded showeverything)
4952 ("content" org-startup-folded content)
4953 ("indent" org-startup-indented t)
4954 ("noindent" org-startup-indented nil)
4955 ("hidestars" org-hide-leading-stars t)
4956 ("showstars" org-hide-leading-stars nil)
4957 ("odd" org-odd-levels-only t)
4958 ("oddeven" org-odd-levels-only nil)
4959 ("align" org-startup-align-all-tables t)
4960 ("noalign" org-startup-align-all-tables nil)
4961 ("inlineimages" org-startup-with-inline-images t)
4962 ("noinlineimages" org-startup-with-inline-images nil)
4963 ("latexpreview" org-startup-with-latex-preview t)
4964 ("nolatexpreview" org-startup-with-latex-preview nil)
4965 ("customtime" org-display-custom-times t)
4966 ("logdone" org-log-done time)
4967 ("lognotedone" org-log-done note)
4968 ("nologdone" org-log-done nil)
4969 ("lognoteclock-out" org-log-note-clock-out t)
4970 ("nolognoteclock-out" org-log-note-clock-out nil)
4971 ("logrepeat" org-log-repeat state)
4972 ("lognoterepeat" org-log-repeat note)
4973 ("logdrawer" org-log-into-drawer t)
4974 ("nologdrawer" org-log-into-drawer nil)
4975 ("logstatesreversed" org-log-states-order-reversed t)
4976 ("nologstatesreversed" org-log-states-order-reversed nil)
4977 ("nologrepeat" org-log-repeat nil)
4978 ("logreschedule" org-log-reschedule time)
4979 ("lognotereschedule" org-log-reschedule note)
4980 ("nologreschedule" org-log-reschedule nil)
4981 ("logredeadline" org-log-redeadline time)
4982 ("lognoteredeadline" org-log-redeadline note)
4983 ("nologredeadline" org-log-redeadline nil)
4984 ("logrefile" org-log-refile time)
4985 ("lognoterefile" org-log-refile note)
4986 ("nologrefile" org-log-refile nil)
4987 ("fninline" org-footnote-define-inline t)
4988 ("nofninline" org-footnote-define-inline nil)
4989 ("fnlocal" org-footnote-section nil)
4990 ("fnauto" org-footnote-auto-label t)
4991 ("fnprompt" org-footnote-auto-label nil)
4992 ("fnconfirm" org-footnote-auto-label confirm)
4993 ("fnplain" org-footnote-auto-label plain)
4994 ("fnadjust" org-footnote-auto-adjust t)
4995 ("nofnadjust" org-footnote-auto-adjust nil)
4996 ("constcgs" constants-unit-system cgs)
4997 ("constSI" constants-unit-system SI)
4998 ("noptag" org-tag-persistent-alist nil)
4999 ("hideblocks" org-hide-block-startup t)
5000 ("nohideblocks" org-hide-block-startup nil)
5001 ("beamer" org-startup-with-beamer-mode t)
5002 ("entitiespretty" org-pretty-entities t)
5003 ("entitiesplain" org-pretty-entities nil))
5004 "Variable associated with STARTUP options for org-mode.
5005 Each element is a list of three items: the startup options (as written
5006 in the #+STARTUP line), the corresponding variable, and the value to set
5007 this variable to if the option is found. An optional forth element PUSH
5008 means to push this value onto the list in the variable.")
5010 (defcustom org-group-tags t
5011 "When non-nil (the default), use group tags.
5012 This can be turned on/off through `org-toggle-tags-groups'."
5013 :group 'org-tags
5014 :group 'org-startup
5015 :type 'boolean)
5017 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5019 (defun org-toggle-tags-groups ()
5020 "Toggle support for group tags.
5021 Support for group tags is controlled by the option
5022 `org-group-tags', which is non-nil by default."
5023 (interactive)
5024 (setq org-group-tags (not org-group-tags))
5025 (cond ((and (derived-mode-p 'org-agenda-mode)
5026 org-group-tags)
5027 (org-agenda-redo))
5028 ((derived-mode-p 'org-mode)
5029 (let ((org-inhibit-startup t)) (org-mode))))
5030 (message "Groups tags support has been turned %s"
5031 (if org-group-tags "on" "off")))
5033 (defun org-set-regexps-and-options (&optional tags-only)
5034 "Precompute regular expressions used in the current buffer.
5035 When optional argument TAGS-ONLY is non-nil, only compute tags
5036 related expressions."
5037 (when (derived-mode-p 'org-mode)
5038 (let ((alist (org--setup-collect-keywords
5039 (org-make-options-regexp
5040 (append '("FILETAGS" "TAGS" "SETUPFILE")
5041 (and (not tags-only)
5042 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5043 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5044 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5045 ;; Startup options. Get this early since it does change
5046 ;; behavior for other options (e.g., tags).
5047 (let ((startup (cdr (assq 'startup alist))))
5048 (dolist (option startup)
5049 (let ((entry (assoc-string option org-startup-options t)))
5050 (when entry
5051 (let ((var (nth 1 entry))
5052 (val (nth 2 entry)))
5053 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5054 (unless (listp (symbol-value var))
5055 (set (make-local-variable var) nil))
5056 (add-to-list var val)))))))
5057 (setq-local org-file-tags
5058 (mapcar #'org-add-prop-inherited
5059 (cdr (assq 'filetags alist))))
5060 (setq org-current-tag-alist
5061 (append org-tag-persistent-alist
5062 (let ((tags (cdr (assq 'tags alist))))
5063 (if tags (org-tag-string-to-alist tags)
5064 org-tag-alist))))
5065 (setq org-tag-groups-alist
5066 (org-tag-alist-to-groups org-current-tag-alist))
5067 (unless tags-only
5068 ;; File properties.
5069 (setq-local org-file-properties (cdr (assq 'property alist)))
5070 ;; Archive location.
5071 (let ((archive (cdr (assq 'archive alist))))
5072 (when archive (setq-local org-archive-location archive)))
5073 ;; Category.
5074 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5075 (when cat
5076 (setq-local org-category (intern cat))
5077 (setq-local org-file-properties
5078 (org--update-property-plist
5079 "CATEGORY" cat org-file-properties))))
5080 ;; Columns.
5081 (let ((column (cdr (assq 'columns alist))))
5082 (when column (setq-local org-columns-default-format column)))
5083 ;; Constants.
5084 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5085 ;; Link abbreviations.
5086 (let ((links (cdr (assq 'link alist))))
5087 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5088 ;; Priorities.
5089 (let ((priorities (cdr (assq 'priorities alist))))
5090 (when priorities
5091 (setq-local org-highest-priority (nth 0 priorities))
5092 (setq-local org-lowest-priority (nth 1 priorities))
5093 (setq-local org-default-priority (nth 2 priorities))))
5094 ;; Scripts.
5095 (let ((scripts (assq 'scripts alist)))
5096 (when scripts
5097 (setq-local org-use-sub-superscripts (cdr scripts))))
5098 ;; TODO keywords.
5099 (setq-local org-todo-kwd-alist nil)
5100 (setq-local org-todo-key-alist nil)
5101 (setq-local org-todo-key-trigger nil)
5102 (setq-local org-todo-keywords-1 nil)
5103 (setq-local org-done-keywords nil)
5104 (setq-local org-todo-heads nil)
5105 (setq-local org-todo-sets nil)
5106 (setq-local org-todo-log-states nil)
5107 (let ((todo-sequences
5108 (or (nreverse (cdr (assq 'todo alist)))
5109 (let ((d (default-value 'org-todo-keywords)))
5110 (if (not (stringp (car d))) d
5111 ;; XXX: Backward compatibility code.
5112 (list (cons org-todo-interpretation d)))))))
5113 (dolist (sequence todo-sequences)
5114 (let* ((sequence (or (run-hook-with-args-until-success
5115 'org-todo-setup-filter-hook sequence)
5116 sequence))
5117 (sequence-type (car sequence))
5118 (keywords (cdr sequence))
5119 (sep (member "|" keywords))
5120 names alist)
5121 (dolist (k (remove "|" keywords))
5122 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5124 (error "Invalid TODO keyword %s" k))
5125 (let ((name (match-string 1 k))
5126 (key (match-string 2 k))
5127 (log (org-extract-log-state-settings k)))
5128 (push name names)
5129 (push (cons name (and key (string-to-char key))) alist)
5130 (when log (push log org-todo-log-states))))
5131 (let* ((names (nreverse names))
5132 (done (if sep (org-remove-keyword-keys (cdr sep))
5133 (last names)))
5134 (head (car names))
5135 (tail (list sequence-type head (car done) (org-last done))))
5136 (add-to-list 'org-todo-heads head 'append)
5137 (push names org-todo-sets)
5138 (setq org-done-keywords (append org-done-keywords done nil))
5139 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5140 (setq org-todo-key-alist
5141 (append org-todo-key-alist
5142 (and alist
5143 (append '((:startgroup))
5144 (nreverse alist)
5145 '((:endgroup))))))
5146 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5147 (setq org-todo-sets (nreverse org-todo-sets)
5148 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5149 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5150 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5151 ;; Compute the regular expressions and other local variables.
5152 ;; Using `org-outline-regexp-bol' would complicate them much,
5153 ;; because of the fixed white space at the end of that string.
5154 (unless org-done-keywords
5155 (setq org-done-keywords
5156 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5157 (setq org-not-done-keywords
5158 (org-delete-all org-done-keywords
5159 (copy-sequence org-todo-keywords-1))
5160 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5161 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5162 org-not-done-heading-regexp
5163 (format org-heading-keyword-regexp-format org-not-done-regexp)
5164 org-todo-line-regexp
5165 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5166 org-complex-heading-regexp
5167 (concat "^\\(\\*+\\)"
5168 "\\(?: +" org-todo-regexp "\\)?"
5169 "\\(?: +\\(\\[#.\\]\\)\\)?"
5170 "\\(?: +\\(.*?\\)\\)??"
5171 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5172 "[ \t]*$")
5173 org-complex-heading-regexp-format
5174 (concat "^\\(\\*+\\)"
5175 "\\(?: +" org-todo-regexp "\\)?"
5176 "\\(?: +\\(\\[#.\\]\\)\\)?"
5177 "\\(?: +"
5178 ;; Stats cookies can be stuck to body.
5179 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5180 "\\(%s\\)"
5181 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5182 "\\)"
5183 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5184 "[ \t]*$")
5185 org-todo-line-tags-regexp
5186 (concat "^\\(\\*+\\)"
5187 "\\(?: +" org-todo-regexp "\\)?"
5188 "\\(?: +\\(.*?\\)\\)??"
5189 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5190 "[ \t]*$"))
5191 (org-compute-latex-and-related-regexp)))))
5193 (defun org--setup-collect-keywords (regexp &optional files alist)
5194 "Return setup keywords values as an alist.
5196 REGEXP matches a subset of setup keywords. FILES is a list of
5197 file names already visited. It is used to avoid circular setup
5198 files. ALIST, when non-nil, is the alist computed so far.
5200 Return value contains the following keys: `archive', `category',
5201 `columns', `constants', `filetags', `link', `priorities',
5202 `property', `scripts', `startup', `tags' and `todo'."
5203 (org-with-wide-buffer
5204 (goto-char (point-min))
5205 (let ((case-fold-search t))
5206 (while (re-search-forward regexp nil t)
5207 (let ((element (org-element-at-point)))
5208 (when (eq (org-element-type element) 'keyword)
5209 (let ((key (org-element-property :key element))
5210 (value (org-element-property :value element)))
5211 (cond
5212 ((equal key "ARCHIVE")
5213 (when (org-string-nw-p value)
5214 (push (cons 'archive value) alist)))
5215 ((equal key "CATEGORY") (push (cons 'category value) alist))
5216 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5217 ((equal key "CONSTANTS")
5218 (let* ((constants (assq 'constants alist))
5219 (store (cdr constants)))
5220 (dolist (pair (org-split-string value))
5221 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5222 pair)
5223 (let* ((name (match-string 1 pair))
5224 (value (match-string 2 pair))
5225 (old (assoc name store)))
5226 (if old (setcdr old value)
5227 (push (cons name value) store)))))
5228 (if constants (setcdr constants store)
5229 (push (cons 'constants store) alist))))
5230 ((equal key "FILETAGS")
5231 (when (org-string-nw-p value)
5232 (let ((old (assq 'filetags alist))
5233 (new (apply #'nconc
5234 (mapcar (lambda (x) (org-split-string x ":"))
5235 (org-split-string value)))))
5236 (if old (setcdr old (append new (cdr old)))
5237 (push (cons 'filetags new) alist)))))
5238 ((equal key "LINK")
5239 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5240 (let ((links (assq 'link alist))
5241 (pair (cons (match-string-no-properties 1 value)
5242 (match-string-no-properties 2 value))))
5243 (if links (push pair (cdr links))
5244 (push (list 'link pair) alist)))))
5245 ((equal key "OPTIONS")
5246 (when (and (org-string-nw-p value)
5247 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5248 (push (cons 'scripts (read (match-string 1 value))) alist)))
5249 ((equal key "PRIORITIES")
5250 (push (cons 'priorities
5251 (let ((prio (org-split-string value)))
5252 (if (< (length prio) 3) '(?A ?C ?B)
5253 (mapcar #'string-to-char prio))))
5254 alist))
5255 ((equal key "PROPERTY")
5256 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5257 (let* ((property (assq 'property alist))
5258 (value (org--update-property-plist
5259 (match-string-no-properties 1 value)
5260 (match-string-no-properties 2 value)
5261 (cdr property))))
5262 (if property (setcdr property value)
5263 (push (cons 'property value) alist)))))
5264 ((equal key "STARTUP")
5265 (let ((startup (assq 'startup alist)))
5266 (if startup
5267 (setcdr startup
5268 (append (cdr startup) (org-split-string value)))
5269 (push (cons 'startup (org-split-string value)) alist))))
5270 ((equal key "TAGS")
5271 (let ((tag-cell (assq 'tags alist)))
5272 (if tag-cell
5273 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5274 (push (cons 'tags value) alist))))
5275 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5276 (let ((todo (assq 'todo alist))
5277 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5278 (org-split-string value))))
5279 (if todo (push value (cdr todo))
5280 (push (list 'todo value) alist))))
5281 ((equal key "SETUPFILE")
5282 (unless buffer-read-only ; Do not check in Gnus messages.
5283 (let ((f (and (org-string-nw-p value)
5284 (expand-file-name
5285 (org-unbracket-string "\"" "\"" value)))))
5286 (when (and f (file-readable-p f) (not (member f files)))
5287 (with-temp-buffer
5288 (setq default-directory (file-name-directory f))
5289 (insert-file-contents f)
5290 (setq alist
5291 ;; Fake Org mode to benefit from cache
5292 ;; without recurring needlessly.
5293 (let ((major-mode 'org-mode))
5294 (org--setup-collect-keywords
5295 regexp (cons f files) alist)))))))))))))))
5296 alist)
5298 (defun org-tag-string-to-alist (s)
5299 "Return tag alist associated to string S.
5300 S is a value for TAGS keyword or produced with
5301 `org-tag-alist-to-string'. Return value is an alist suitable for
5302 `org-tag-alist' or `org-tag-persistent-alist'."
5303 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5304 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5305 "\\|{.+?}\\)" ; regular expression
5306 "\\(?:(\\(.\\))\\)?\\'"))
5307 alist group-flag)
5308 (dolist (tokens lines (cdr (nreverse alist)))
5309 (push '(:newline) alist)
5310 (while tokens
5311 (let ((token (pop tokens)))
5312 (pcase token
5313 ("{"
5314 (push '(:startgroup) alist)
5315 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5316 ("}"
5317 (push '(:endgroup) alist)
5318 (setq group-flag nil))
5319 ("["
5320 (push '(:startgrouptag) alist)
5321 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5322 ("]"
5323 (push '(:endgrouptag) alist)
5324 (setq group-flag nil))
5325 (":"
5326 (push '(:grouptags) alist))
5327 ((guard (string-match tag-re token))
5328 (let ((tag (match-string 1 token))
5329 (key (and (match-beginning 2)
5330 (string-to-char (match-string 2 token)))))
5331 ;; Push all tags in groups, no matter if they already
5332 ;; appear somewhere else in the list.
5333 (when (or group-flag (not (assoc tag alist)))
5334 (push (cons tag key) alist))))))))))
5336 (defun org-tag-alist-to-string (alist &optional skip-key)
5337 "Return tag string associated to ALIST.
5339 ALIST is an alist, as defined in `org-tag-alist' or
5340 `org-tag-persistent-alist', or produced with
5341 `org-tag-string-to-alist'.
5343 Return value is a string suitable as a value for \"TAGS\"
5344 keyword.
5346 When optional argument SKIP-KEY is non-nil, skip selection keys
5347 next to tags."
5348 (mapconcat (lambda (token)
5349 (pcase token
5350 (`(:startgroup) "{")
5351 (`(:endgroup) "}")
5352 (`(:startgrouptag) "[")
5353 (`(:endgrouptag) "]")
5354 (`(:grouptags) ":")
5355 (`(:newline) "\\n")
5356 ((and
5357 (guard (not skip-key))
5358 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5359 (format "%s(%c)" tag key))
5360 (`(,(and tag (pred stringp)) . ,_) tag)
5361 (_ (user-error "Invalid tag token: %S" token))))
5362 alist
5363 " "))
5365 (defun org-tag-alist-to-groups (alist)
5366 "Return group alist from tag ALIST.
5367 ALIST is an alist, as defined in `org-tag-alist' or
5368 `org-tag-persistent-alist', or produced with
5369 `org-tag-string-to-alist'. Return value is an alist following
5370 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5371 a string, summarizing TAGS, as a list of strings."
5372 (let (groups group-status current-group)
5373 (dolist (token alist (nreverse groups))
5374 (pcase token
5375 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5376 (`(,(or :endgroup :endgrouptag))
5377 (when (eq group-status 'append)
5378 (push (nreverse current-group) groups))
5379 (setq group-status nil))
5380 (`(:grouptags) (setq group-status 'append))
5381 ((and `(,tag . ,_) (guard group-status))
5382 (if (eq group-status 'append) (push tag current-group)
5383 (setq current-group (list tag))))
5384 (_ nil)))))
5386 (defun org-file-contents (file &optional noerror)
5387 "Return the contents of FILE, as a string."
5388 (if (and file (file-readable-p file))
5389 (with-temp-buffer
5390 (insert-file-contents file)
5391 (buffer-string))
5392 (funcall (if noerror 'message 'error)
5393 "Cannot read file \"%s\"%s"
5394 file
5395 (let ((from (buffer-file-name (buffer-base-buffer))))
5396 (if from (concat " (referenced in file \"" from "\")") "")))))
5398 (defun org-extract-log-state-settings (x)
5399 "Extract the log state setting from a TODO keyword string.
5400 This will extract info from a string like \"WAIT(w@/!)\"."
5401 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5402 (let ((kw (match-string 1 x))
5403 (log1 (and (match-end 3) (match-string 3 x)))
5404 (log2 (and (match-end 4) (match-string 4 x))))
5405 (and (or log1 log2)
5406 (list kw
5407 (and log1 (if (equal log1 "!") 'time 'note))
5408 (and log2 (if (equal log2 "!") 'time 'note)))))))
5410 (defun org-remove-keyword-keys (list)
5411 "Remove a pair of parenthesis at the end of each string in LIST."
5412 (mapcar (lambda (x)
5413 (if (string-match "(.*)$" x)
5414 (substring x 0 (match-beginning 0))
5416 list))
5418 (defun org-assign-fast-keys (alist)
5419 "Assign fast keys to a keyword-key alist.
5420 Respect keys that are already there."
5421 (let (new e (alt ?0))
5422 (while (setq e (pop alist))
5423 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5424 (cdr e)) ;; Key already assigned.
5425 (push e new)
5426 (let ((clist (string-to-list (downcase (car e))))
5427 (used (append new alist)))
5428 (when (= (car clist) ?@)
5429 (pop clist))
5430 (while (and clist (rassoc (car clist) used))
5431 (pop clist))
5432 (unless clist
5433 (while (rassoc alt used)
5434 (cl-incf alt)))
5435 (push (cons (car e) (or (car clist) alt)) new))))
5436 (nreverse new)))
5438 ;;; Some variables used in various places
5440 (defvar org-window-configuration nil
5441 "Used in various places to store a window configuration.")
5442 (defvar org-selected-window nil
5443 "Used in various places to store a window configuration.")
5444 (defvar org-finish-function nil
5445 "Function to be called when `C-c C-c' is used.
5446 This is for getting out of special buffers like capture.")
5447 (defvar org-last-state)
5449 ;; Defined somewhere in this file, but used before definition.
5450 (defvar org-entities) ;; defined in org-entities.el
5451 (defvar org-struct-menu)
5452 (defvar org-org-menu)
5453 (defvar org-tbl-menu)
5455 ;;;; Define the Org mode
5457 ;; We use a before-change function to check if a table might need
5458 ;; an update.
5459 (defvar org-table-may-need-update t
5460 "Indicates that a table might need an update.
5461 This variable is set by `org-before-change-function'.
5462 `org-table-align' sets it back to nil.")
5463 (defun org-before-change-function (_beg _end)
5464 "Every change indicates that a table might need an update."
5465 (setq org-table-may-need-update t))
5466 (defvar org-mode-map)
5467 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5468 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5469 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5470 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5471 (defvar org-table-buffer-is-an nil)
5473 (defvar bidi-paragraph-direction)
5474 (defvar buffer-face-mode-face)
5476 (require 'outline)
5478 ;; Other stuff we need.
5479 (require 'time-date)
5480 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5481 (require 'easymenu)
5482 (autoload 'easy-menu-add "easymenu")
5483 (require 'overlay)
5485 ;; (require 'org-macs) moved higher up in the file before it is first used
5486 (require 'org-entities)
5487 ;; (require 'org-compat) moved higher up in the file before it is first used
5488 (require 'org-faces)
5489 (require 'org-list)
5490 (require 'org-pcomplete)
5491 (require 'org-src)
5492 (require 'org-footnote)
5493 (require 'org-macro)
5495 ;; babel
5496 (require 'ob)
5498 ;;;###autoload
5499 (define-derived-mode org-mode outline-mode "Org"
5500 "Outline-based notes management and organizer, alias
5501 \"Carsten's outline-mode for keeping track of everything.\"
5503 Org mode develops organizational tasks around a NOTES file which
5504 contains information about projects as plain text. Org mode is
5505 implemented on top of Outline mode, which is ideal to keep the content
5506 of large files well structured. It supports ToDo items, deadlines and
5507 time stamps, which magically appear in the diary listing of the Emacs
5508 calendar. Tables are easily created with a built-in table editor.
5509 Plain text URL-like links connect to websites, emails (VM), Usenet
5510 messages (Gnus), BBDB entries, and any files related to the project.
5511 For printing and sharing of notes, an Org file (or a part of it)
5512 can be exported as a structured ASCII or HTML file.
5514 The following commands are available:
5516 \\{org-mode-map}"
5518 ;; Get rid of Outline menus, they are not needed
5519 ;; Need to do this here because define-derived-mode sets up
5520 ;; the keymap so late. Still, it is a waste to call this each time
5521 ;; we switch another buffer into Org mode.
5522 (define-key org-mode-map [menu-bar headings] 'undefined)
5523 (define-key org-mode-map [menu-bar hide] 'undefined)
5524 (define-key org-mode-map [menu-bar show] 'undefined)
5526 (org-load-modules-maybe)
5527 (org-install-agenda-files-menu)
5528 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5529 (add-to-invisibility-spec '(org-cwidth))
5530 (add-to-invisibility-spec '(org-hide-block . t))
5531 (setq-local outline-regexp org-outline-regexp)
5532 (setq-local outline-level 'org-outline-level)
5533 (setq bidi-paragraph-direction 'left-to-right)
5534 (when (and org-ellipsis
5535 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5536 (fboundp 'make-glyph-code))
5537 (unless org-display-table
5538 (setq org-display-table (make-display-table)))
5539 (set-display-table-slot
5540 org-display-table 4
5541 (vconcat (mapcar
5542 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5543 org-ellipsis)))
5544 (if (stringp org-ellipsis) org-ellipsis "..."))))
5545 (setq buffer-display-table org-display-table))
5546 (org-set-regexps-and-options)
5547 (org-set-font-lock-defaults)
5548 (when (and org-tag-faces (not org-tags-special-faces-re))
5549 ;; tag faces set outside customize.... force initialization.
5550 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5551 ;; Calc embedded
5552 (setq-local calc-embedded-open-mode "# ")
5553 ;; Modify a few syntax entries
5554 (modify-syntax-entry ?@ "w")
5555 (modify-syntax-entry ?\" "\"")
5556 (modify-syntax-entry ?\\ "_")
5557 (modify-syntax-entry ?~ "_")
5558 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5559 ;; Activate before-change-function
5560 (setq-local org-table-may-need-update t)
5561 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5562 ;; Check for running clock before killing a buffer
5563 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5564 ;; Initialize macros templates.
5565 (org-macro-initialize-templates)
5566 ;; Initialize radio targets.
5567 (org-update-radio-target-regexp)
5568 ;; Indentation.
5569 (setq-local indent-line-function 'org-indent-line)
5570 (setq-local indent-region-function 'org-indent-region)
5571 ;; Filling and auto-filling.
5572 (org-setup-filling)
5573 ;; Comments.
5574 (org-setup-comments-handling)
5575 ;; Initialize cache.
5576 (org-element-cache-reset)
5577 ;; Beginning/end of defun
5578 (setq-local beginning-of-defun-function 'org-backward-element)
5579 (setq-local end-of-defun-function
5580 (lambda ()
5581 (if (not (org-at-heading-p))
5582 (org-forward-element)
5583 (org-forward-element)
5584 (forward-char -1))))
5585 ;; Next error for sparse trees
5586 (setq-local next-error-function 'org-occur-next-match)
5587 ;; Make sure dependence stuff works reliably, even for users who set it
5588 ;; too late :-(
5589 (if org-enforce-todo-dependencies
5590 (add-hook 'org-blocker-hook
5591 'org-block-todo-from-children-or-siblings-or-parent)
5592 (remove-hook 'org-blocker-hook
5593 'org-block-todo-from-children-or-siblings-or-parent))
5594 (if org-enforce-todo-checkbox-dependencies
5595 (add-hook 'org-blocker-hook
5596 'org-block-todo-from-checkboxes)
5597 (remove-hook 'org-blocker-hook
5598 'org-block-todo-from-checkboxes))
5600 ;; Align options lines
5601 (setq-local
5602 align-mode-rules-list
5603 '((org-in-buffer-settings
5604 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5605 (modes . '(org-mode)))))
5607 ;; Imenu
5608 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5610 ;; Make isearch reveal context
5611 (setq-local outline-isearch-open-invisible-function
5612 (lambda (&rest _) (org-show-context 'isearch)))
5614 ;; Setup the pcomplete hooks
5615 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5616 (setq-local pcomplete-command-name-function 'org-command-at-point)
5617 (setq-local pcomplete-default-completion-function 'ignore)
5618 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5619 (setq-local pcomplete-termination-string "")
5620 (setq-local buffer-face-mode-face 'org-default)
5622 ;; If empty file that did not turn on Org mode automatically, make
5623 ;; it to.
5624 (when (and org-insert-mode-line-in-empty-file
5625 (called-interactively-p 'any)
5626 (= (point-min) (point-max)))
5627 (insert "# -*- mode: org -*-\n\n"))
5628 (unless org-inhibit-startup
5629 (org-unmodified
5630 (when org-startup-with-beamer-mode (org-beamer-mode))
5631 (when org-startup-align-all-tables
5632 (org-table-map-tables #'org-table-align t))
5633 (when org-startup-with-inline-images (org-display-inline-images))
5634 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5635 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5636 (when org-startup-truncated (setq truncate-lines t))
5637 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5638 (org-refresh-effort-properties)))
5639 ;; Try to set `org-hide' face correctly.
5640 (let ((foreground (org-find-invisible-foreground)))
5641 (when foreground
5642 (set-face-foreground 'org-hide foreground))))
5644 ;; Update `customize-package-emacs-version-alist'
5645 (add-to-list 'customize-package-emacs-version-alist
5646 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5647 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5648 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5650 (defvar org-mode-transpose-word-syntax-table
5651 (let ((st (make-syntax-table text-mode-syntax-table)))
5652 (dolist (c org-emphasis-alist st)
5653 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5655 (when (fboundp 'abbrev-table-put)
5656 (abbrev-table-put org-mode-abbrev-table
5657 :parents (list text-mode-abbrev-table)))
5659 (defun org-find-invisible-foreground ()
5660 (let ((candidates (remove
5661 "unspecified-bg"
5662 (nconc
5663 (list (face-background 'default)
5664 (face-background 'org-default))
5665 (mapcar
5666 (lambda (alist)
5667 (when (boundp alist)
5668 (cdr (assoc 'background-color (symbol-value alist)))))
5669 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5670 (list (face-foreground 'org-hide))))))
5671 (car (remove nil candidates))))
5673 (defun org-current-time (&optional rounding-minutes past)
5674 "Current time, possibly rounded to ROUNDING-MINUTES.
5675 When ROUNDING-MINUTES is not an integer, fall back on the car of
5676 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5677 the rounding returns a past time."
5678 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5679 (car org-time-stamp-rounding-minutes)))
5680 (time (decode-time)) res)
5681 (if (< r 1)
5682 (current-time)
5683 (setq res
5684 (apply 'encode-time
5685 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5686 (nthcdr 2 time))))
5687 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5688 (seconds-to-time (- (float-time res) (* r 60)))
5689 res))))
5691 (defun org-today ()
5692 "Return today date, considering `org-extend-today-until'."
5693 (time-to-days
5694 (time-subtract (current-time)
5695 (list 0 (* 3600 org-extend-today-until) 0))))
5697 ;;;; Font-Lock stuff, including the activators
5699 (defvar org-mouse-map (make-sparse-keymap))
5700 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5701 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5702 (when org-mouse-1-follows-link
5703 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5704 (when org-tab-follows-link
5705 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5706 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5708 (require 'font-lock)
5710 (defconst org-non-link-chars "]\t\n\r<>")
5711 (defvar org-link-types-re nil
5712 "Matches a link that has a url-like prefix like \"http:\"")
5713 (defvar org-link-re-with-space nil
5714 "Matches a link with spaces, optional angular brackets around it.")
5715 (defvar org-link-re-with-space2 nil
5716 "Matches a link with spaces, optional angular brackets around it.")
5717 (defvar org-link-re-with-space3 nil
5718 "Matches a link with spaces, only for internal part in bracket links.")
5719 (defvar org-angle-link-re nil
5720 "Matches link with angular brackets, spaces are allowed.")
5721 (defvar org-plain-link-re nil
5722 "Matches plain link, without spaces.")
5723 (defvar org-bracket-link-regexp nil
5724 "Matches a link in double brackets.")
5725 (defvar org-bracket-link-analytic-regexp nil
5726 "Regular expression used to analyze links.
5727 Here is what the match groups contain after a match:
5728 1: http:
5729 2: http
5730 3: path
5731 4: [desc]
5732 5: desc")
5733 (defvar org-bracket-link-analytic-regexp++ nil
5734 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5735 (defvar org-any-link-re nil
5736 "Regular expression matching any link.")
5738 (defconst org-match-sexp-depth 3
5739 "Number of stacked braces for sub/superscript matching.")
5741 (defun org-create-multibrace-regexp (left right n)
5742 "Create a regular expression which will match a balanced sexp.
5743 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5744 as single character strings.
5745 The regexp returned will match the entire expression including the
5746 delimiters. It will also define a single group which contains the
5747 match except for the outermost delimiters. The maximum depth of
5748 stacked delimiters is N. Escaping delimiters is not possible."
5749 (let* ((nothing (concat "[^" left right "]*?"))
5750 (or "\\|")
5751 (re nothing)
5752 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5753 (while (> n 1)
5754 (setq n (1- n)
5755 re (concat re or next)
5756 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5757 (concat left "\\(" re "\\)" right)))
5759 (defconst org-match-substring-regexp
5760 (concat
5761 "\\(\\S-\\)\\([_^]\\)\\("
5762 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5763 "\\|"
5764 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5765 "\\|"
5766 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5767 "The regular expression matching a sub- or superscript.")
5769 (defconst org-match-substring-with-braces-regexp
5770 (concat
5771 "\\(\\S-\\)\\([_^]\\)"
5772 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5773 "The regular expression matching a sub- or superscript, forcing braces.")
5775 (defun org-make-link-regexps ()
5776 "Update the link regular expressions.
5777 This should be called after the variable `org-link-parameters' has changed."
5778 (let ((types-re (regexp-opt (org-link-types) t)))
5779 (setq org-link-types-re
5780 (concat "\\`" types-re ":")
5781 org-link-re-with-space
5782 (concat "<?" types-re ":"
5783 "\\([^" org-non-link-chars " ]"
5784 "[^" org-non-link-chars "]*"
5785 "[^" org-non-link-chars " ]\\)>?")
5786 org-link-re-with-space2
5787 (concat "<?" types-re ":"
5788 "\\([^" org-non-link-chars " ]"
5789 "[^\t\n\r]*"
5790 "[^" org-non-link-chars " ]\\)>?")
5791 org-link-re-with-space3
5792 (concat "<?" types-re ":"
5793 "\\([^" org-non-link-chars " ]"
5794 "[^\t\n\r]*\\)")
5795 org-angle-link-re
5796 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5797 types-re)
5798 org-plain-link-re
5799 (concat
5800 "\\<" types-re ":"
5801 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5802 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5803 org-bracket-link-regexp
5804 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5805 org-bracket-link-analytic-regexp
5806 (concat
5807 "\\[\\["
5808 "\\(" types-re ":\\)?"
5809 "\\([^]]+\\)"
5810 "\\]"
5811 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5812 "\\]")
5813 org-bracket-link-analytic-regexp++
5814 (concat
5815 "\\[\\["
5816 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5817 "\\([^]]+\\)"
5818 "\\]"
5819 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5820 "\\]")
5821 org-any-link-re
5822 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5823 org-angle-link-re "\\)\\|\\("
5824 org-plain-link-re "\\)"))))
5826 (org-make-link-regexps)
5828 (defvar org-emph-face nil)
5830 (defun org-do-emphasis-faces (limit)
5831 "Run through the buffer and emphasize strings."
5832 (let (rtn a)
5833 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5834 (let* ((border (char-after (match-beginning 3)))
5835 (bre (regexp-quote (char-to-string border))))
5836 (when (and (not (= border (char-after (match-beginning 4))))
5837 (not (string-match-p (concat bre ".*" bre)
5838 (replace-regexp-in-string
5839 "\n" " "
5840 (substring (match-string 2) 1 -1)))))
5841 (setq rtn t)
5842 (setq a (assoc (match-string 3) org-emphasis-alist))
5843 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5844 'face
5845 (nth 1 a))
5846 (and (nth 2 a)
5847 (org-remove-flyspell-overlays-in
5848 (match-beginning 0) (match-end 0)))
5849 (add-text-properties (match-beginning 2) (match-end 2)
5850 '(font-lock-multiline t org-emphasis t))
5851 (when org-hide-emphasis-markers
5852 (add-text-properties (match-end 4) (match-beginning 5)
5853 '(invisible org-link))
5854 (add-text-properties (match-beginning 3) (match-end 3)
5855 '(invisible org-link)))))
5856 (goto-char (1+ (match-beginning 0))))
5857 rtn))
5859 (defun org-emphasize (&optional char)
5860 "Insert or change an emphasis, i.e. a font like bold or italic.
5861 If there is an active region, change that region to a new emphasis.
5862 If there is no region, just insert the marker characters and position
5863 the cursor between them.
5864 CHAR should be the marker character. If it is a space, it means to
5865 remove the emphasis of the selected region.
5866 If CHAR is not given (for example in an interactive call) it will be
5867 prompted for."
5868 (interactive)
5869 (let ((erc org-emphasis-regexp-components)
5870 (string "") beg end move s)
5871 (if (org-region-active-p)
5872 (setq beg (region-beginning)
5873 end (region-end)
5874 string (buffer-substring beg end))
5875 (setq move t))
5877 (unless char
5878 (message "Emphasis marker or tag: [%s]"
5879 (mapconcat #'car org-emphasis-alist ""))
5880 (setq char (read-char-exclusive)))
5881 (if (equal char ?\s)
5882 (setq s ""
5883 move nil)
5884 (unless (assoc (char-to-string char) org-emphasis-alist)
5885 (user-error "No such emphasis marker: \"%c\"" char))
5886 (setq s (char-to-string char)))
5887 (while (and (> (length string) 1)
5888 (equal (substring string 0 1) (substring string -1))
5889 (assoc (substring string 0 1) org-emphasis-alist))
5890 (setq string (substring string 1 -1)))
5891 (setq string (concat s string s))
5892 (when beg (delete-region beg end))
5893 (unless (or (bolp)
5894 (string-match (concat "[" (nth 0 erc) "\n]")
5895 (char-to-string (char-before (point)))))
5896 (insert " "))
5897 (unless (or (eobp)
5898 (string-match (concat "[" (nth 1 erc) "\n]")
5899 (char-to-string (char-after (point)))))
5900 (insert " ") (backward-char 1))
5901 (insert string)
5902 (and move (backward-char 1))))
5904 (defconst org-nonsticky-props
5905 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5907 (defsubst org-rear-nonsticky-at (pos)
5908 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5910 (defun org-activate-plain-links (limit)
5911 "Add link properties for plain links."
5912 (when (and (re-search-forward org-plain-link-re limit t)
5913 (not (org-in-src-block-p)))
5915 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5916 'face))
5917 (link (match-string-no-properties 0))
5918 (type (match-string-no-properties 1))
5919 (path (match-string-no-properties 2))
5920 (link-start (match-beginning 0))
5921 (link-end (match-end 0))
5922 (link-face (org-link-get-parameter type :face))
5923 (help-echo (org-link-get-parameter type :help-echo))
5924 (htmlize-link (org-link-get-parameter type :htmlize-link))
5925 (activate-func (org-link-get-parameter type :activate-func)))
5926 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5927 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5928 (add-text-properties (match-beginning 0) (match-end 0)
5929 (list
5930 'mouse-face (or (org-link-get-parameter type :mouse-face)
5931 'highlight)
5932 'face (cond
5933 ;; A function that returns a face
5934 ((functionp link-face)
5935 (funcall link-face path))
5936 ;; a face
5937 ((facep link-face)
5938 link-face)
5939 ;; An anonymous face
5940 ((consp link-face)
5941 link-face)
5942 ;; default
5944 'org-link))
5945 'help-echo (cond
5946 ((stringp help-echo)
5947 help-echo)
5948 ((functionp help-echo)
5949 help-echo)
5951 (concat "LINK: "
5952 (save-match-data
5953 (org-link-unescape link)))))
5954 'htmlize-link (cond
5955 ((functionp htmlize-link)
5956 (funcall htmlize-link path))
5958 `(:uri ,link)))
5959 'keymap (or (org-link-get-parameter type :keymap)
5960 org-mouse-map)
5961 'org-link-start (match-beginning 0)))
5962 (org-rear-nonsticky-at (match-end 0))
5963 (when activate-func
5964 (funcall activate-func link-start link-end path nil))
5965 t))))
5967 (defun org-activate-code (limit)
5968 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (remove-text-properties (match-beginning 0) (match-end 0)
5971 '(display t invisible t intangible t))
5974 (defcustom org-src-fontify-natively t
5975 "When non-nil, fontify code in code blocks.
5976 See also the `org-block' face."
5977 :type 'boolean
5978 :version "24.4"
5979 :package-version '(Org . "8.3")
5980 :group 'org-appearance
5981 :group 'org-babel)
5983 (defcustom org-allow-promoting-top-level-subtree nil
5984 "When non-nil, allow promoting a top level subtree.
5985 The leading star of the top level headline will be replaced
5986 by a #."
5987 :type 'boolean
5988 :version "24.1"
5989 :group 'org-appearance)
5991 (defun org-fontify-meta-lines-and-blocks (limit)
5992 (condition-case nil
5993 (org-fontify-meta-lines-and-blocks-1 limit)
5994 (error (message "org-mode fontification error in %S at %d"
5995 (current-buffer)
5996 (line-number-at-pos)))))
5998 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5999 "Fontify #+ lines and blocks."
6000 (let ((case-fold-search t))
6001 (when (re-search-forward
6002 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6003 limit t)
6004 (let ((beg (match-beginning 0))
6005 (block-start (match-end 0))
6006 (block-end nil)
6007 (lang (match-string 7))
6008 (beg1 (line-beginning-position 2))
6009 (dc1 (downcase (match-string 2)))
6010 (dc3 (downcase (match-string 3)))
6011 end end1 quoting block-type)
6012 (cond
6013 ((and (match-end 4) (equal dc3 "+begin"))
6014 ;; Truly a block
6015 (setq block-type (downcase (match-string 5))
6016 quoting (member block-type org-protecting-blocks))
6017 (when (re-search-forward
6018 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6019 nil t) ;; on purpose, we look further than LIMIT
6020 (setq end (min (point-max) (match-end 0))
6021 end1 (min (point-max) (1- (match-beginning 0))))
6022 (setq block-end (match-beginning 0))
6023 (when quoting
6024 (org-remove-flyspell-overlays-in beg1 end1)
6025 (remove-text-properties beg end
6026 '(display t invisible t intangible t)))
6027 (add-text-properties
6028 beg end '(font-lock-fontified t font-lock-multiline t))
6029 (add-text-properties beg beg1 '(face org-meta-line))
6030 (org-remove-flyspell-overlays-in beg beg1)
6031 (add-text-properties ; For end_src
6032 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6033 (org-remove-flyspell-overlays-in end1 end)
6034 (cond
6035 ((and lang (not (string= lang "")) org-src-fontify-natively)
6036 (org-src-font-lock-fontify-block lang block-start block-end)
6037 (add-text-properties beg1 block-end '(src-block t)))
6038 (quoting
6039 (add-text-properties beg1 (min (point-max) (1+ end1))
6040 (list 'face
6041 (list :inherit
6042 (let ((face-name
6043 (intern (format "org-block-%s" lang))))
6044 (append (and (facep face-name) (list face-name))
6045 '(org-block))))))) ; end of source block
6046 ((not org-fontify-quote-and-verse-blocks))
6047 ((string= block-type "quote")
6048 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6049 ((string= block-type "verse")
6050 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6051 (add-text-properties beg beg1 '(face org-block-begin-line))
6052 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6053 '(face org-block-end-line))
6055 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6056 (org-remove-flyspell-overlays-in
6057 (match-beginning 0)
6058 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6059 (add-text-properties
6060 beg (match-end 3)
6061 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6062 '(font-lock-fontified t invisible t)
6063 '(font-lock-fontified t face org-document-info-keyword)))
6064 (add-text-properties
6065 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6066 (if (string-equal dc1 "+title:")
6067 '(font-lock-fontified t face org-document-title)
6068 '(font-lock-fontified t face org-document-info))))
6069 ((equal dc1 "+caption:")
6070 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6071 (remove-text-properties (match-beginning 0) (match-end 0)
6072 '(display t invisible t intangible t))
6073 (add-text-properties (match-beginning 1) (match-end 3)
6074 '(font-lock-fontified t face org-meta-line))
6075 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6076 '(font-lock-fontified t face org-block))
6078 ((member dc3 '(" " ""))
6079 (org-remove-flyspell-overlays-in beg (match-end 0))
6080 (add-text-properties
6081 beg (match-end 0)
6082 '(font-lock-fontified t face font-lock-comment-face)))
6083 (t ;; just any other in-buffer setting, but not indented
6084 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6085 (remove-text-properties (match-beginning 0) (match-end 0)
6086 '(display t invisible t intangible t))
6087 (add-text-properties beg (match-end 0)
6088 '(font-lock-fontified t face org-meta-line))
6089 t))))))
6091 (defun org-fontify-drawers (limit)
6092 "Fontify drawers."
6093 (when (re-search-forward org-drawer-regexp limit t)
6094 (add-text-properties
6095 (match-beginning 0) (match-end 0)
6096 '(font-lock-fontified t face org-special-keyword))
6097 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6100 (defun org-fontify-macros (limit)
6101 "Fontify macros."
6102 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6103 (add-text-properties
6104 (match-beginning 0) (match-end 0)
6105 '(font-lock-fontified t face org-macro))
6106 (when org-hide-macro-markers
6107 (add-text-properties (match-end 2) (match-beginning 2)
6108 '(invisible t))
6109 (add-text-properties (match-beginning 1) (match-end 1)
6110 '(invisible t)))
6111 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6114 (defun org-activate-angle-links (limit)
6115 "Add text properties for angle links."
6116 (when (and (re-search-forward org-angle-link-re limit t)
6117 (not (org-in-src-block-p)))
6118 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6119 (add-text-properties (match-beginning 0) (match-end 0)
6120 (list 'mouse-face 'highlight
6121 'keymap org-mouse-map
6122 'font-lock-multiline t))
6123 (org-rear-nonsticky-at (match-end 0))
6126 (defun org-activate-footnote-links (limit)
6127 "Add text properties for footnotes."
6128 (let ((fn (org-footnote-next-reference-or-definition limit)))
6129 (when fn
6130 (let* ((beg (nth 1 fn))
6131 (end (nth 2 fn))
6132 (label (car fn))
6133 (referencep (/= (line-beginning-position) beg)))
6134 (when (and referencep (nth 3 fn))
6135 (save-excursion
6136 (goto-char beg)
6137 (search-forward (or label "fn:"))
6138 (org-remove-flyspell-overlays-in beg (match-end 0))))
6139 (add-text-properties beg end
6140 (list 'mouse-face 'highlight
6141 'keymap org-mouse-map
6142 'help-echo
6143 (if referencep "Footnote reference"
6144 "Footnote definition")
6145 'font-lock-fontified t
6146 'font-lock-multiline t
6147 'face 'org-footnote))))))
6149 (defun org-activate-bracket-links (limit)
6150 "Add text properties for bracketed links."
6151 (when (and (re-search-forward org-bracket-link-regexp limit t)
6152 (not (org-in-src-block-p)))
6153 (let* ((hl (save-match-data
6154 (org-link-expand-abbrev (match-string-no-properties 1))))
6155 (type (save-match-data
6156 (and (string-match org-plain-link-re hl)
6157 (match-string-no-properties 1 hl))))
6158 (path (save-match-data
6159 (and (string-match org-plain-link-re hl)
6160 (match-string-no-properties 2 hl))))
6161 (link-start (match-beginning 0))
6162 (link-end (match-end 0))
6163 (bracketp t)
6164 (help-echo (org-link-get-parameter type :help-echo))
6165 (help (cond
6166 ((stringp help-echo)
6167 help-echo)
6168 ((functionp help-echo)
6169 help-echo)
6171 (concat "LINK: "
6172 (save-match-data
6173 (org-link-unescape hl))))))
6174 (link-face (org-link-get-parameter type :face))
6175 (face (cond
6176 ;; A function that returns a face
6177 ((functionp link-face)
6178 (funcall link-face path))
6179 ;; a face
6180 ((facep link-face)
6181 link-face)
6182 ;; An anonymous face
6183 ((consp link-face)
6184 link-face)
6185 ;; default
6187 'org-link)))
6188 (keymap (or (org-link-get-parameter type :keymap)
6189 org-mouse-map))
6190 (mouse-face (or (org-link-get-parameter type :mouse-face)
6191 'highlight))
6192 (htmlize (org-link-get-parameter type :htmlize-link))
6193 (htmlize-link (cond
6194 ((functionp htmlize)
6195 (funcall htmlize))
6197 `(:uri ,(format "%s:%s" type path)))))
6198 (activate-func (org-link-get-parameter type :activate-func))
6199 ;; invisible part
6200 (ip (list 'invisible (or
6201 (org-link-get-parameter type :display)
6202 'org-link)
6203 'face face
6204 'keymap keymap
6205 'mouse-face mouse-face
6206 'font-lock-multiline t
6207 'help-echo help
6208 'htmlize-link htmlize-link))
6209 ;; visible part
6210 (vp (list 'keymap keymap
6211 'face face
6212 'mouse-face mouse-face
6213 'font-lock-multiline t
6214 'help-echo help
6215 'htmlize-link htmlize-link)))
6216 ;; We need to remove the invisible property here. Table narrowing
6217 ;; may have made some of this invisible.
6218 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6219 (remove-text-properties (match-beginning 0) (match-end 0)
6220 '(invisible nil))
6221 (if (match-end 3)
6222 (progn
6223 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6224 (org-rear-nonsticky-at (match-beginning 3))
6225 (add-text-properties (match-beginning 3) (match-end 3) vp)
6226 (org-rear-nonsticky-at (match-end 3))
6227 (add-text-properties (match-end 3) (match-end 0) ip)
6228 (org-rear-nonsticky-at (match-end 0)))
6229 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6230 (org-rear-nonsticky-at (match-beginning 1))
6231 (add-text-properties (match-beginning 1) (match-end 1) vp)
6232 (org-rear-nonsticky-at (match-end 1))
6233 (add-text-properties (match-end 1) (match-end 0) ip)
6234 (org-rear-nonsticky-at (match-end 0)))
6235 (when activate-func
6236 (funcall activate-func link-start link-end path bracketp))
6237 t)))
6239 (defun org-activate-dates (limit)
6240 "Add text properties for dates."
6241 (when (and (re-search-forward org-tsr-regexp-both limit t)
6242 (not (equal (char-before (match-beginning 0)) 91)))
6243 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6244 (add-text-properties (match-beginning 0) (match-end 0)
6245 (list 'mouse-face 'highlight
6246 'keymap org-mouse-map))
6247 (org-rear-nonsticky-at (match-end 0))
6248 (when org-display-custom-times
6249 (if (match-end 3)
6250 (org-display-custom-time (match-beginning 3) (match-end 3))
6251 (org-display-custom-time (match-beginning 1) (match-end 1))))
6254 (defvar-local org-target-link-regexp nil
6255 "Regular expression matching radio targets in plain text.")
6257 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6258 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6259 border border border))
6260 "Regular expression matching a link target.")
6262 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6263 "Regular expression matching a radio target.")
6265 (defconst org-any-target-regexp
6266 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6267 "Regular expression matching any target.")
6269 (defun org-activate-target-links (limit)
6270 "Add text properties for target matches."
6271 (when org-target-link-regexp
6272 (let ((case-fold-search t))
6273 (when (re-search-forward org-target-link-regexp limit t)
6274 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6275 (add-text-properties (match-beginning 1) (match-end 1)
6276 (list 'mouse-face 'highlight
6277 'keymap org-mouse-map
6278 'help-echo "Radio target link"
6279 'org-linked-text t))
6280 (org-rear-nonsticky-at (match-end 1))
6281 t))))
6283 (defun org-update-radio-target-regexp ()
6284 "Find all radio targets in this file and update the regular expression.
6285 Also refresh fontification if needed."
6286 (interactive)
6287 (let ((old-regexp org-target-link-regexp)
6288 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6289 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6290 (targets
6291 (org-with-wide-buffer
6292 (goto-char (point-min))
6293 (let (rtn)
6294 (while (re-search-forward org-radio-target-regexp nil t)
6295 ;; Make sure point is really within the object.
6296 (backward-char)
6297 (let ((obj (org-element-context)))
6298 (when (eq (org-element-type obj) 'radio-target)
6299 (cl-pushnew (org-element-property :value obj) rtn
6300 :test #'equal))))
6301 rtn))))
6302 (setq org-target-link-regexp
6303 (and targets
6304 (concat before-re
6305 (mapconcat
6306 (lambda (x)
6307 (replace-regexp-in-string
6308 " +" "\\s-+" (regexp-quote x) t t))
6309 targets
6310 "\\|")
6311 after-re)))
6312 (unless (equal old-regexp org-target-link-regexp)
6313 ;; Clean-up cache.
6314 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6315 ((not org-target-link-regexp) old-regexp)
6317 (concat before-re
6318 (mapconcat
6319 (lambda (re)
6320 (substring re (length before-re)
6321 (- (length after-re))))
6322 (list old-regexp org-target-link-regexp)
6323 "\\|")
6324 after-re)))))
6325 (org-with-wide-buffer
6326 (goto-char (point-min))
6327 (while (re-search-forward regexp nil t)
6328 (org-element-cache-refresh (match-beginning 1)))))
6329 ;; Re fontify buffer.
6330 (when (memq 'radio org-highlight-links)
6331 (org-restart-font-lock)))))
6333 (defun org-hide-wide-columns (limit)
6334 (let (s e)
6335 (setq s (text-property-any (point) (or limit (point-max))
6336 'org-cwidth t))
6337 (when s
6338 (setq e (next-single-property-change s 'org-cwidth))
6339 (add-text-properties s e '(invisible org-cwidth))
6340 (goto-char e)
6341 t)))
6343 (defvar org-latex-and-related-regexp nil
6344 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6346 (defun org-compute-latex-and-related-regexp ()
6347 "Compute regular expression for LaTeX, entities and sub/superscript.
6348 Result depends on variable `org-highlight-latex-and-related'."
6349 (setq-local
6350 org-latex-and-related-regexp
6351 (let* ((re-sub
6352 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6353 ((eq org-use-sub-superscripts '{})
6354 (list org-match-substring-with-braces-regexp))
6355 (org-use-sub-superscripts (list org-match-substring-regexp))))
6356 (re-latex
6357 (when (memq 'latex org-highlight-latex-and-related)
6358 (let ((matchers (plist-get org-format-latex-options :matchers)))
6359 (delq nil
6360 (mapcar (lambda (x)
6361 (and (member (car x) matchers) (nth 1 x)))
6362 org-latex-regexps)))))
6363 (re-entities
6364 (when (memq 'entities org-highlight-latex-and-related)
6365 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6366 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6368 (defun org-do-latex-and-related (limit)
6369 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6370 LIMIT bounds the search for syntax to highlight. Stop at first
6371 highlighted object, if any. Return t if some highlighting was
6372 done, nil otherwise."
6373 (when (org-string-nw-p org-latex-and-related-regexp)
6374 (catch 'found
6375 (while (re-search-forward org-latex-and-related-regexp limit t)
6376 (unless
6377 (cl-some
6378 (lambda (f)
6379 (memq f '(org-code org-verbatim underline org-special-keyword)))
6380 (save-excursion
6381 (goto-char (1+ (match-beginning 0)))
6382 (face-at-point nil t)))
6383 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6384 '(?_ ?^))
6386 0)))
6387 (font-lock-prepend-text-property
6388 (+ offset (match-beginning 0)) (match-end 0)
6389 'face 'org-latex-and-related)
6390 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6391 '(font-lock-multiline t)))
6392 (throw 'found t)))
6393 nil)))
6395 (defun org-restart-font-lock ()
6396 "Restart `font-lock-mode', to force refontification."
6397 (when (and (boundp 'font-lock-mode) font-lock-mode)
6398 (font-lock-mode -1)
6399 (font-lock-mode 1)))
6401 (defun org-activate-tags (limit)
6402 (when (re-search-forward
6403 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6404 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6405 (add-text-properties (match-beginning 1) (match-end 1)
6406 (list 'mouse-face 'highlight
6407 'keymap org-mouse-map))
6408 (org-rear-nonsticky-at (match-end 1))
6411 (defun org-outline-level ()
6412 "Compute the outline level of the heading at point.
6414 If this is called at a normal headline, the level is the number
6415 of stars. Use `org-reduced-level' to remove the effect of
6416 `org-odd-levels'. Unlike to `org-current-level', this function
6417 takes into consideration inlinetasks."
6418 (org-with-wide-buffer
6419 (end-of-line)
6420 (if (re-search-backward org-outline-regexp-bol nil t)
6421 (1- (- (match-end 0) (match-beginning 0)))
6422 0)))
6424 (defvar org-font-lock-keywords nil)
6426 (defsubst org-re-property (property &optional literal allow-null value)
6427 "Return a regexp matching a PROPERTY line.
6429 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6430 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6431 non-nil, match properties even without a value.
6433 Match group 3 is set to the value when it exists. If there is no
6434 value and ALLOW-NULL is non-nil, it is set to the empty string.
6436 With optional argument VALUE, match only property lines with
6437 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6438 unless LITERAL is non-nil."
6439 (concat
6440 "^\\(?4:[ \t]*\\)"
6441 (format "\\(?1::\\(?2:%s\\):\\)"
6442 (if literal property (regexp-quote property)))
6443 (cond (value
6444 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6445 (if literal value (regexp-quote value))))
6446 (allow-null
6447 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6449 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6451 (defconst org-property-re
6452 (org-re-property "\\S-+" 'literal t)
6453 "Regular expression matching a property line.
6454 There are four matching groups:
6455 1: :PROPKEY: including the leading and trailing colon,
6456 2: PROPKEY without the leading and trailing colon,
6457 3: PROPVAL without leading or trailing spaces,
6458 4: the indentation of the current line,
6459 5: trailing whitespace.")
6461 (defvar org-font-lock-hook nil
6462 "Functions to be called for special font lock stuff.")
6464 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6466 (defvar org-font-lock-set-keywords-hook nil
6467 "Functions that can manipulate `org-font-lock-extra-keywords'.
6468 This is called after `org-font-lock-extra-keywords' is defined, but before
6469 it is installed to be used by font lock. This can be useful if something
6470 needs to be inserted at a specific position in the font-lock sequence.")
6472 (defun org-font-lock-hook (limit)
6473 "Run `org-font-lock-hook' within LIMIT."
6474 (run-hook-with-args 'org-font-lock-hook limit))
6476 (defun org-set-font-lock-defaults ()
6477 "Set font lock defaults for the current buffer."
6478 (let* ((em org-fontify-emphasized-text)
6479 (lk org-highlight-links)
6480 (org-font-lock-extra-keywords
6481 (list
6482 ;; Call the hook
6483 '(org-font-lock-hook)
6484 ;; Headlines
6485 `(,(if org-fontify-whole-heading-line
6486 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6487 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6488 (1 (org-get-level-face 1))
6489 (2 (org-get-level-face 2))
6490 (3 (org-get-level-face 3)))
6491 ;; Table lines
6492 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6493 (1 'org-table t))
6494 ;; Table internals
6495 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6496 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6497 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6498 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6499 ;; Drawers
6500 '(org-fontify-drawers)
6501 ;; Properties
6502 (list org-property-re
6503 '(1 'org-special-keyword t)
6504 '(3 'org-property-value t))
6505 ;; Links
6506 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6507 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6508 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6509 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6510 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6511 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6512 (when (memq 'footnote lk) '(org-activate-footnote-links))
6513 ;; Targets.
6514 (list org-any-target-regexp '(0 'org-target t))
6515 ;; Diary sexps.
6516 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6517 ;; Macro
6518 '(org-fontify-macros)
6519 '(org-hide-wide-columns (0 nil append))
6520 ;; TODO keyword
6521 (list (format org-heading-keyword-regexp-format
6522 org-todo-regexp)
6523 '(2 (org-get-todo-face 2) t))
6524 ;; DONE
6525 (if org-fontify-done-headline
6526 (list (format org-heading-keyword-regexp-format
6527 (concat
6528 "\\(?:"
6529 (mapconcat 'regexp-quote org-done-keywords "\\|")
6530 "\\)"))
6531 '(2 'org-headline-done t))
6532 nil)
6533 ;; Priorities
6534 '(org-font-lock-add-priority-faces)
6535 ;; Tags
6536 '(org-font-lock-add-tag-faces)
6537 ;; Tags groups
6538 (when (and org-group-tags org-tag-groups-alist)
6539 (list (concat org-outline-regexp-bol ".+\\(:"
6540 (regexp-opt (mapcar 'car org-tag-groups-alist))
6541 ":\\).*$")
6542 '(1 'org-tag-group prepend)))
6543 ;; Special keywords
6544 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6545 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6546 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6547 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6548 ;; Emphasis
6549 (when em '(org-do-emphasis-faces))
6550 ;; Checkboxes
6551 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6552 1 'org-checkbox prepend)
6553 (when (cdr (assq 'checkbox org-list-automatic-rules))
6554 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6555 (0 (org-get-checkbox-statistics-face) t)))
6556 ;; Description list items
6557 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6558 1 'org-list-dt prepend)
6559 ;; ARCHIVEd headings
6560 (list (concat
6561 org-outline-regexp-bol
6562 "\\(.*:" org-archive-tag ":.*\\)")
6563 '(1 'org-archived prepend))
6564 ;; Specials
6565 '(org-do-latex-and-related)
6566 '(org-fontify-entities)
6567 '(org-raise-scripts)
6568 ;; Code
6569 '(org-activate-code (1 'org-code t))
6570 ;; COMMENT
6571 (list (format
6572 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6573 org-todo-regexp
6574 org-comment-string)
6575 '(9 'org-special-keyword t))
6576 ;; Blocks and meta lines
6577 '(org-fontify-meta-lines-and-blocks))))
6578 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6579 (run-hooks 'org-font-lock-set-keywords-hook)
6580 ;; Now set the full font-lock-keywords
6581 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6582 (setq-local font-lock-defaults
6583 '(org-font-lock-keywords t nil nil backward-paragraph))
6584 (kill-local-variable 'font-lock-keywords)
6585 nil))
6587 (defun org-toggle-pretty-entities ()
6588 "Toggle the composition display of entities as UTF8 characters."
6589 (interactive)
6590 (setq-local org-pretty-entities (not org-pretty-entities))
6591 (org-restart-font-lock)
6592 (if org-pretty-entities
6593 (message "Entities are now displayed as UTF8 characters")
6594 (save-restriction
6595 (widen)
6596 (decompose-region (point-min) (point-max))
6597 (message "Entities are now displayed as plain text"))))
6599 (defvar-local org-custom-properties-overlays nil
6600 "List of overlays used for custom properties.")
6602 (defun org-toggle-custom-properties-visibility ()
6603 "Display or hide properties in `org-custom-properties'."
6604 (interactive)
6605 (if org-custom-properties-overlays
6606 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6607 (setq org-custom-properties-overlays nil))
6608 (when org-custom-properties
6609 (org-with-wide-buffer
6610 (goto-char (point-min))
6611 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6612 (while (re-search-forward regexp nil t)
6613 (let ((end (cdr (save-match-data (org-get-property-block)))))
6614 (when (and end (< (point) end))
6615 ;; Hide first custom property in current drawer.
6616 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6617 (overlay-put o 'invisible t)
6618 (overlay-put o 'org-custom-property t)
6619 (push o org-custom-properties-overlays))
6620 ;; Hide additional custom properties in the same drawer.
6621 (while (re-search-forward regexp end t)
6622 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6623 (overlay-put o 'invisible t)
6624 (overlay-put o 'org-custom-property t)
6625 (push o org-custom-properties-overlays)))))
6626 ;; Each entry is limited to a single property drawer.
6627 (outline-next-heading)))))))
6629 (defun org-fontify-entities (limit)
6630 "Find an entity to fontify."
6631 (let (ee)
6632 (when org-pretty-entities
6633 (catch 'match
6634 ;; "\_ "-family is left out on purpose. Only the first one,
6635 ;; i.e., "\_ ", could be fontified anyway, and it would be
6636 ;; confusing when adding a second white space character.
6637 (while (re-search-forward
6638 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6639 limit t)
6640 (when (and (not (org-at-comment-p))
6641 (setq ee (org-entity-get (match-string 1)))
6642 (= (length (nth 6 ee)) 1))
6643 (let* ((end (if (equal (match-string 2) "{}")
6644 (match-end 2)
6645 (match-end 1))))
6646 (add-text-properties
6647 (match-beginning 0) end
6648 (list 'font-lock-fontified t))
6649 (compose-region (match-beginning 0) end
6650 (nth 6 ee) nil)
6651 (backward-char 1)
6652 (throw 'match t))))
6653 nil))))
6655 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6656 "Fontify string S like in Org-mode."
6657 (with-temp-buffer
6658 (insert s)
6659 (let ((org-odd-levels-only odd-levels))
6660 (org-mode)
6661 (org-font-lock-ensure)
6662 (buffer-string))))
6664 (defvar org-m nil)
6665 (defvar org-l nil)
6666 (defvar org-f nil)
6667 (defun org-get-level-face (n)
6668 "Get the right face for match N in font-lock matching of headlines."
6669 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6670 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6671 (if org-cycle-level-faces
6672 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6673 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6674 (cond
6675 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6676 ((eq n 2) org-f)
6677 (t (unless org-level-color-stars-only org-f))))
6679 (defun org-face-from-face-or-color (context inherit face-or-color)
6680 "Create a face list that inherits INHERIT, but sets the foreground color.
6681 When FACE-OR-COLOR is not a string, just return it."
6682 (if (stringp face-or-color)
6683 (list :inherit inherit
6684 (cdr (assoc context org-faces-easy-properties))
6685 face-or-color)
6686 face-or-color))
6688 (defun org-get-todo-face (kwd)
6689 "Get the right face for a TODO keyword KWD.
6690 If KWD is a number, get the corresponding match group."
6691 (when (numberp kwd) (setq kwd (match-string kwd)))
6692 (or (org-face-from-face-or-color
6693 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6694 (and (member kwd org-done-keywords) 'org-done)
6695 'org-todo))
6697 (defun org-get-priority-face (priority)
6698 "Get the right face for PRIORITY.
6699 PRIORITY is a character."
6700 (or (org-face-from-face-or-color
6701 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6702 'org-priority))
6704 (defun org-get-tag-face (tag)
6705 "Get the right face for TAG.
6706 If TAG is a number, get the corresponding match group."
6707 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6708 (or (org-face-from-face-or-color
6709 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6710 'org-tag)))
6712 (defun org-font-lock-add-priority-faces (limit)
6713 "Add the special priority faces."
6714 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6715 (add-text-properties
6716 (match-beginning 1) (match-end 1)
6717 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6718 'font-lock-fontified t))))
6720 (defun org-font-lock-add-tag-faces (limit)
6721 "Add the special tag faces."
6722 (when (and org-tag-faces org-tags-special-faces-re)
6723 (while (re-search-forward org-tags-special-faces-re limit t)
6724 (add-text-properties (match-beginning 1) (match-end 1)
6725 (list 'face (org-get-tag-face 1)
6726 'font-lock-fontified t))
6727 (backward-char 1))))
6729 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6730 "Remove fontification and activation overlays from links."
6731 (font-lock-default-unfontify-region beg end)
6732 (let* ((buffer-undo-list t)
6733 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6734 (inhibit-modification-hooks t)
6735 deactivate-mark buffer-file-name buffer-file-truename)
6736 (decompose-region beg end)
6737 (remove-text-properties beg end
6738 '(mouse-face t keymap t org-linked-text t
6739 invisible t intangible t
6740 org-emphasis t))
6741 (org-remove-font-lock-display-properties beg end)))
6743 (defconst org-script-display '(((raise -0.3) (height 0.7))
6744 ((raise 0.3) (height 0.7))
6745 ((raise -0.5))
6746 ((raise 0.5)))
6747 "Display properties for showing superscripts and subscripts.")
6749 (defun org-remove-font-lock-display-properties (beg end)
6750 "Remove specific display properties that have been added by font lock.
6751 The will remove the raise properties that are used to show superscripts
6752 and subscripts."
6753 (let (next prop)
6754 (while (< beg end)
6755 (setq next (next-single-property-change beg 'display nil end)
6756 prop (get-text-property beg 'display))
6757 (when (member prop org-script-display)
6758 (put-text-property beg next 'display nil))
6759 (setq beg next))))
6761 (defun org-raise-scripts (limit)
6762 "Add raise properties to sub/superscripts."
6763 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6764 (re-search-forward
6765 (if (eq org-use-sub-superscripts t)
6766 org-match-substring-regexp
6767 org-match-substring-with-braces-regexp)
6768 limit t))
6769 (let* ((pos (point)) table-p comment-p
6770 (mpos (match-beginning 3))
6771 (emph-p (get-text-property mpos 'org-emphasis))
6772 (link-p (get-text-property mpos 'mouse-face))
6773 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6774 (goto-char (point-at-bol))
6775 (setq table-p (looking-at-p org-table-dataline-regexp)
6776 comment-p (looking-at-p "^[ \t]*#[ +]"))
6777 (goto-char pos)
6778 ;; Handle a_b^c
6779 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6780 (unless (or comment-p emph-p link-p keyw-p)
6781 (put-text-property (match-beginning 3) (match-end 0)
6782 'display
6783 (if (equal (char-after (match-beginning 2)) ?^)
6784 (nth (if table-p 3 1) org-script-display)
6785 (nth (if table-p 2 0) org-script-display)))
6786 (add-text-properties (match-beginning 2) (match-end 2)
6787 (list 'invisible t
6788 'org-dwidth t 'org-dwidth-n 1))
6789 (if (and (eq (char-after (match-beginning 3)) ?{)
6790 (eq (char-before (match-end 3)) ?}))
6791 (progn
6792 (add-text-properties
6793 (match-beginning 3) (1+ (match-beginning 3))
6794 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6795 (add-text-properties
6796 (1- (match-end 3)) (match-end 3)
6797 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6798 t)))
6800 ;;;; Visibility cycling, including org-goto and indirect buffer
6802 ;;; Cycling
6804 (defvar-local org-cycle-global-status nil)
6805 (put 'org-cycle-global-status 'org-state t)
6806 (defvar-local org-cycle-subtree-status nil)
6807 (put 'org-cycle-subtree-status 'org-state t)
6809 (defvar org-inlinetask-min-level)
6811 (defun org-unlogged-message (&rest args)
6812 "Display a message, but avoid logging it in the *Messages* buffer."
6813 (let ((message-log-max nil))
6814 (apply 'message args)))
6816 ;;;###autoload
6817 (defun org-cycle (&optional arg)
6818 "TAB-action and visibility cycling for Org-mode.
6820 This is the command invoked in Org mode by the TAB key. Its main purpose
6821 is outline visibility cycling, but it also invokes other actions
6822 in special contexts.
6824 - When this function is called with a prefix argument, rotate the entire
6825 buffer through 3 states (global cycling)
6826 1. OVERVIEW: Show only top-level headlines.
6827 2. CONTENTS: Show all headlines of all levels, but no body text.
6828 3. SHOW ALL: Show everything.
6829 With a double \\[universal-argument] prefix argument, \
6830 switch to the startup visibility,
6831 determined by the variable `org-startup-folded', and by any VISIBILITY
6832 properties in the buffer.
6833 With a triple \\[universal-argument] prefix argument, \
6834 show the entire buffer, including any drawers.
6836 - When inside a table, re-align the table and move to the next field.
6838 - When point is at the beginning of a headline, rotate the subtree started
6839 by this line through 3 different states (local cycling)
6840 1. FOLDED: Only the main headline is shown.
6841 2. CHILDREN: The main headline and the direct children are shown.
6842 From this state, you can move to one of the children
6843 and zoom in further.
6844 3. SUBTREE: Show the entire subtree, including body text.
6845 If there is no subtree, switch directly from CHILDREN to FOLDED.
6847 - When point is at the beginning of an empty headline and the variable
6848 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6849 of the headline by demoting and promoting it to likely levels. This
6850 speeds up creation document structure by pressing TAB once or several
6851 times right after creating a new headline.
6853 - When there is a numeric prefix, go up to a heading with level ARG, do
6854 a `show-subtree' and return to the previous cursor position. If ARG
6855 is negative, go up that many levels.
6857 - When point is not at the beginning of a headline, execute the global
6858 binding for TAB, which is re-indenting the line. See the option
6859 `org-cycle-emulate-tab' for details.
6861 - Special case: if point is at the beginning of the buffer and there is
6862 no headline in line 1, this function will act as if called with prefix arg
6863 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6864 But only if also the variable `org-cycle-global-at-bob' is t."
6865 (interactive "P")
6866 (org-load-modules-maybe)
6867 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6868 (and org-cycle-level-after-item/entry-creation
6869 (or (org-cycle-level)
6870 (org-cycle-item-indentation))))
6871 (let* ((limit-level
6872 (or org-cycle-max-level
6873 (and (boundp 'org-inlinetask-min-level)
6874 org-inlinetask-min-level
6875 (1- org-inlinetask-min-level))))
6876 (nstars (and limit-level
6877 (if org-odd-levels-only
6878 (and limit-level (1- (* limit-level 2)))
6879 limit-level)))
6880 (org-outline-regexp
6881 (if (not (derived-mode-p 'org-mode))
6882 outline-regexp
6883 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6884 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6885 (not (looking-at org-outline-regexp))))
6886 (org-cycle-hook
6887 (if bob-special
6888 (delq 'org-optimize-window-after-visibility-change
6889 (copy-sequence org-cycle-hook))
6890 org-cycle-hook))
6891 (pos (point)))
6893 (when (or bob-special (equal arg '(4)))
6894 ;; special case: use global cycling
6895 (setq arg t))
6897 (cond
6899 ((equal arg '(16))
6900 (setq last-command 'dummy)
6901 (org-set-startup-visibility)
6902 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6904 ((equal arg '(64))
6905 (outline-show-all)
6906 (org-unlogged-message "Entire buffer visible, including drawers"))
6908 ;; Try cdlatex TAB completion
6909 ((org-try-cdlatex-tab))
6911 ;; Table: enter it or move to the next field.
6912 ((org-at-table-p 'any)
6913 (if (org-at-table.el-p)
6914 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6915 Use \\[org-edit-special] to edit table.el tables"))
6916 (if arg (org-table-edit-field t)
6917 (org-table-justify-field-maybe)
6918 (call-interactively 'org-table-next-field))))
6920 ((run-hook-with-args-until-success
6921 'org-tab-after-check-for-table-hook))
6923 ;; Global cycling: delegate to `org-cycle-internal-global'.
6924 ((eq arg t) (org-cycle-internal-global))
6926 ;; Drawers: delegate to `org-flag-drawer'.
6927 ((save-excursion
6928 (beginning-of-line 1)
6929 (looking-at org-drawer-regexp))
6930 (org-flag-drawer ; toggle block visibility
6931 (not (get-char-property (match-end 0) 'invisible))))
6933 ;; Show-subtree, ARG levels up from here.
6934 ((integerp arg)
6935 (save-excursion
6936 (org-back-to-heading)
6937 (outline-up-heading (if (< arg 0) (- arg)
6938 (- (funcall outline-level) arg)))
6939 (org-show-subtree)))
6941 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6942 ((and (featurep 'org-inlinetask)
6943 (org-inlinetask-at-task-p)
6944 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6945 (org-inlinetask-toggle-visibility))
6947 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6948 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6949 (save-excursion (move-beginning-of-line 1)
6950 (looking-at org-outline-regexp)))
6951 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6952 (org-cycle-internal-local))
6954 ;; From there: TAB emulation and template completion.
6955 (buffer-read-only (org-back-to-heading))
6957 ((run-hook-with-args-until-success
6958 'org-tab-after-check-for-cycling-hook))
6960 ((org-try-structure-completion))
6962 ((run-hook-with-args-until-success
6963 'org-tab-before-tab-emulation-hook))
6965 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6966 (or (not (bolp))
6967 (not (looking-at org-outline-regexp))))
6968 (call-interactively (global-key-binding "\t")))
6970 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6971 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6972 (or (and (eq org-cycle-emulate-tab 'white)
6973 (= (match-end 0) (point-at-eol)))
6974 (and (eq org-cycle-emulate-tab 'whitestart)
6975 (>= (match-end 0) pos))))
6977 (eq org-cycle-emulate-tab t))
6978 (call-interactively (global-key-binding "\t")))
6980 (t (save-excursion
6981 (org-back-to-heading)
6982 (org-cycle)))))))
6984 (defun org-cycle-internal-global ()
6985 "Do the global cycling action."
6986 ;; Hack to avoid display of messages for .org attachments in Gnus
6987 (let ((ga (string-match "\\*fontification" (buffer-name))))
6988 (cond
6989 ((and (eq last-command this-command)
6990 (eq org-cycle-global-status 'overview))
6991 ;; We just created the overview - now do table of contents
6992 ;; This can be slow in very large buffers, so indicate action
6993 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6994 (unless ga (org-unlogged-message "CONTENTS..."))
6995 (org-content)
6996 (unless ga (org-unlogged-message "CONTENTS...done"))
6997 (setq org-cycle-global-status 'contents)
6998 (run-hook-with-args 'org-cycle-hook 'contents))
7000 ((and (eq last-command this-command)
7001 (eq org-cycle-global-status 'contents))
7002 ;; We just showed the table of contents - now show everything
7003 (run-hook-with-args 'org-pre-cycle-hook 'all)
7004 (outline-show-all)
7005 (unless ga (org-unlogged-message "SHOW ALL"))
7006 (setq org-cycle-global-status 'all)
7007 (run-hook-with-args 'org-cycle-hook 'all))
7010 ;; Default action: go to overview
7011 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7012 (org-overview)
7013 (unless ga (org-unlogged-message "OVERVIEW"))
7014 (setq org-cycle-global-status 'overview)
7015 (run-hook-with-args 'org-cycle-hook 'overview)))))
7017 (defvar org-called-with-limited-levels nil
7018 "Non-nil when `org-with-limited-levels' is currently active.")
7020 (defun org-cycle-internal-local ()
7021 "Do the local cycling action."
7022 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7023 ;; First, determine end of headline (EOH), end of subtree or item
7024 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7025 (save-excursion
7026 (if (org-at-item-p)
7027 (progn
7028 (beginning-of-line)
7029 (setq struct (org-list-struct))
7030 (setq eoh (point-at-eol))
7031 (setq eos (org-list-get-item-end-before-blank (point) struct))
7032 (setq has-children (org-list-has-child-p (point) struct)))
7033 (org-back-to-heading)
7034 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7035 (setq eos (save-excursion (org-end-of-subtree t t)
7036 (when (bolp) (backward-char)) (point)))
7037 (setq has-children
7038 (or (save-excursion
7039 (let ((level (funcall outline-level)))
7040 (outline-next-heading)
7041 (and (org-at-heading-p t)
7042 (> (funcall outline-level) level))))
7043 (save-excursion
7044 (org-list-search-forward (org-item-beginning-re) eos t)))))
7045 ;; Determine end invisible part of buffer (EOL)
7046 (beginning-of-line 2)
7047 (while (and (not (eobp)) ;This is like `next-line'.
7048 (get-char-property (1- (point)) 'invisible))
7049 (goto-char (next-single-char-property-change (point) 'invisible))
7050 (and (eolp) (beginning-of-line 2)))
7051 (setq eol (point)))
7052 ;; Find out what to do next and set `this-command'
7053 (cond
7054 ((= eos eoh)
7055 ;; Nothing is hidden behind this heading
7056 (unless (org-before-first-heading-p)
7057 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7058 (org-unlogged-message "EMPTY ENTRY")
7059 (setq org-cycle-subtree-status nil)
7060 (save-excursion
7061 (goto-char eos)
7062 (outline-next-heading)
7063 (when (outline-invisible-p) (org-flag-heading nil))))
7064 ((and (or (>= eol eos)
7065 (not (string-match "\\S-" (buffer-substring eol eos))))
7066 (or has-children
7067 (not (setq children-skipped
7068 org-cycle-skip-children-state-if-no-children))))
7069 ;; Entire subtree is hidden in one line: children view
7070 (unless (org-before-first-heading-p)
7071 (run-hook-with-args 'org-pre-cycle-hook 'children))
7072 (if (org-at-item-p)
7073 (org-list-set-item-visibility (point-at-bol) struct 'children)
7074 (org-show-entry)
7075 (org-with-limited-levels (org-show-children))
7076 ;; FIXME: This slows down the func way too much.
7077 ;; How keep drawers hidden in subtree anyway?
7078 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7079 ;; (org-cycle-hide-drawers 'subtree))
7081 ;; Fold every list in subtree to top-level items.
7082 (when (eq org-cycle-include-plain-lists 'integrate)
7083 (save-excursion
7084 (org-back-to-heading)
7085 (while (org-list-search-forward (org-item-beginning-re) eos t)
7086 (beginning-of-line 1)
7087 (let* ((struct (org-list-struct))
7088 (prevs (org-list-prevs-alist struct))
7089 (end (org-list-get-bottom-point struct)))
7090 (dolist (e (org-list-get-all-items (point) struct prevs))
7091 (org-list-set-item-visibility e struct 'folded))
7092 (goto-char (if (< end eos) end eos)))))))
7093 (org-unlogged-message "CHILDREN")
7094 (save-excursion
7095 (goto-char eos)
7096 (outline-next-heading)
7097 (when (outline-invisible-p) (org-flag-heading nil)))
7098 (setq org-cycle-subtree-status 'children)
7099 (unless (org-before-first-heading-p)
7100 (run-hook-with-args 'org-cycle-hook 'children)))
7101 ((or children-skipped
7102 (and (eq last-command this-command)
7103 (eq org-cycle-subtree-status 'children)))
7104 ;; We just showed the children, or no children are there,
7105 ;; now show everything.
7106 (unless (org-before-first-heading-p)
7107 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7108 (outline-flag-region eoh eos nil)
7109 (org-unlogged-message
7110 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7111 (setq org-cycle-subtree-status 'subtree)
7112 (unless (org-before-first-heading-p)
7113 (run-hook-with-args 'org-cycle-hook 'subtree)))
7115 ;; Default action: hide the subtree.
7116 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7117 (outline-flag-region eoh eos t)
7118 (org-unlogged-message "FOLDED")
7119 (setq org-cycle-subtree-status 'folded)
7120 (unless (org-before-first-heading-p)
7121 (run-hook-with-args 'org-cycle-hook 'folded))))))
7123 ;;;###autoload
7124 (defun org-global-cycle (&optional arg)
7125 "Cycle the global visibility. For details see `org-cycle'.
7126 With \\[universal-argument] prefix arg, switch to startup visibility.
7127 With a numeric prefix, show all headlines up to that level."
7128 (interactive "P")
7129 (let ((org-cycle-include-plain-lists
7130 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7131 (cond
7132 ((integerp arg)
7133 (outline-show-all)
7134 (outline-hide-sublevels arg)
7135 (setq org-cycle-global-status 'contents))
7136 ((equal arg '(4))
7137 (org-set-startup-visibility)
7138 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7140 (org-cycle '(4))))))
7142 (defun org-set-startup-visibility ()
7143 "Set the visibility required by startup options and properties."
7144 (cond
7145 ((eq org-startup-folded t)
7146 (org-overview))
7147 ((eq org-startup-folded 'content)
7148 (org-content))
7149 ((or (eq org-startup-folded 'showeverything)
7150 (eq org-startup-folded nil))
7151 (outline-show-all)))
7152 (unless (eq org-startup-folded 'showeverything)
7153 (when org-hide-block-startup (org-hide-block-all))
7154 (org-set-visibility-according-to-property 'no-cleanup)
7155 (org-cycle-hide-archived-subtrees 'all)
7156 (org-cycle-hide-drawers 'all)
7157 (org-cycle-show-empty-lines t)))
7159 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7160 "Switch subtree visibilities according to :VISIBILITY: property."
7161 (interactive)
7162 (org-with-wide-buffer
7163 (goto-char (point-min))
7164 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7165 (if (not (org-at-property-p)) (outline-next-heading)
7166 (let ((state (match-string 3)))
7167 (save-excursion
7168 (org-back-to-heading t)
7169 (outline-hide-subtree)
7170 (org-reveal)
7171 (cond
7172 ((equal state "folded")
7173 (outline-hide-subtree))
7174 ((equal state "children")
7175 (org-show-hidden-entry)
7176 (org-show-children))
7177 ((equal state "content")
7178 (save-excursion
7179 (save-restriction
7180 (org-narrow-to-subtree)
7181 (org-content))))
7182 ((member state '("all" "showall"))
7183 (outline-show-subtree)))))))
7184 (unless no-cleanup
7185 (org-cycle-hide-archived-subtrees 'all)
7186 (org-cycle-hide-drawers 'all)
7187 (org-cycle-show-empty-lines 'all))))
7189 ;; This function uses outline-regexp instead of the more fundamental
7190 ;; org-outline-regexp so that org-cycle-global works outside of Org
7191 ;; buffers, where outline-regexp is needed.
7192 (defun org-overview ()
7193 "Switch to overview mode, showing only top-level headlines.
7194 This shows all headlines with a level equal or greater than the level
7195 of the first headline in the buffer. This is important, because if the
7196 first headline is not level one, then (hide-sublevels 1) gives confusing
7197 results."
7198 (interactive)
7199 (save-excursion
7200 (let ((level
7201 (save-excursion
7202 (goto-char (point-min))
7203 (when (re-search-forward (concat "^" outline-regexp) nil t)
7204 (goto-char (match-beginning 0))
7205 (funcall outline-level)))))
7206 (and level (outline-hide-sublevels level)))))
7208 (defun org-content (&optional arg)
7209 "Show all headlines in the buffer, like a table of contents.
7210 With numerical argument N, show content up to level N."
7211 (interactive "P")
7212 (org-overview)
7213 (save-excursion
7214 ;; Visit all headings and show their offspring
7215 (and (integerp arg) (org-overview))
7216 (goto-char (point-max))
7217 (catch 'exit
7218 (while (and (progn (condition-case nil
7219 (outline-previous-visible-heading 1)
7220 (error (goto-char (point-min))))
7222 (looking-at org-outline-regexp))
7223 (if (integerp arg)
7224 (org-show-children (1- arg))
7225 (outline-show-branches))
7226 (when (bobp) (throw 'exit nil))))))
7228 (defun org-optimize-window-after-visibility-change (state)
7229 "Adjust the window after a change in outline visibility.
7230 This function is the default value of the hook `org-cycle-hook'."
7231 (when (get-buffer-window (current-buffer))
7232 (cond
7233 ((eq state 'content) nil)
7234 ((eq state 'all) nil)
7235 ((eq state 'folded) nil)
7236 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7237 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7239 (defun org-remove-empty-overlays-at (pos)
7240 "Remove outline overlays that do not contain non-white stuff."
7241 (dolist (o (overlays-at pos))
7242 (and (eq 'outline (overlay-get o 'invisible))
7243 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7244 (overlay-end o))))
7245 (delete-overlay o))))
7247 (defun org-clean-visibility-after-subtree-move ()
7248 "Fix visibility issues after moving a subtree."
7249 ;; First, find a reasonable region to look at:
7250 ;; Start two siblings above, end three below
7251 (let* ((beg (save-excursion
7252 (and (org-get-last-sibling)
7253 (org-get-last-sibling))
7254 (point)))
7255 (end (save-excursion
7256 (and (org-get-next-sibling)
7257 (org-get-next-sibling)
7258 (org-get-next-sibling))
7259 (if (org-at-heading-p)
7260 (point-at-eol)
7261 (point))))
7262 (level (looking-at "\\*+"))
7263 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7264 (save-excursion
7265 (save-restriction
7266 (narrow-to-region beg end)
7267 (when re
7268 ;; Properly fold already folded siblings
7269 (goto-char (point-min))
7270 (while (re-search-forward re nil t)
7271 (when (and (not (outline-invisible-p))
7272 (save-excursion
7273 (goto-char (point-at-eol)) (outline-invisible-p)))
7274 (outline-hide-entry))))
7275 (org-cycle-show-empty-lines 'overview)
7276 (org-cycle-hide-drawers 'overview)))))
7278 (defun org-cycle-show-empty-lines (state)
7279 "Show empty lines above all visible headlines.
7280 The region to be covered depends on STATE when called through
7281 `org-cycle-hook'. Lisp program can use t for STATE to get the
7282 entire buffer covered. Note that an empty line is only shown if there
7283 are at least `org-cycle-separator-lines' empty lines before the headline."
7284 (when (/= org-cycle-separator-lines 0)
7285 (save-excursion
7286 (let* ((n (abs org-cycle-separator-lines))
7287 (re (cond
7288 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7289 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7290 (t (let ((ns (number-to-string (- n 2))))
7291 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7292 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7293 beg end)
7294 (cond
7295 ((memq state '(overview contents t))
7296 (setq beg (point-min) end (point-max)))
7297 ((memq state '(children folded))
7298 (setq beg (point)
7299 end (progn (org-end-of-subtree t t)
7300 (line-beginning-position 2)))))
7301 (when beg
7302 (goto-char beg)
7303 (while (re-search-forward re end t)
7304 (unless (get-char-property (match-end 1) 'invisible)
7305 (let ((e (match-end 1))
7306 (b (if (>= org-cycle-separator-lines 0)
7307 (match-beginning 1)
7308 (save-excursion
7309 (goto-char (match-beginning 0))
7310 (skip-chars-backward " \t\n")
7311 (line-end-position)))))
7312 (outline-flag-region b e nil))))))))
7313 ;; Never hide empty lines at the end of the file.
7314 (save-excursion
7315 (goto-char (point-max))
7316 (outline-previous-heading)
7317 (outline-end-of-heading)
7318 (when (and (looking-at "[ \t\n]+")
7319 (= (match-end 0) (point-max)))
7320 (outline-flag-region (point) (match-end 0) nil))))
7322 (defun org-show-empty-lines-in-parent ()
7323 "Move to the parent and re-show empty lines before visible headlines."
7324 (save-excursion
7325 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7326 (org-cycle-show-empty-lines context))))
7328 (defun org-files-list ()
7329 "Return `org-agenda-files' list, plus all open Org files.
7330 This is useful for operations that need to scan all of a user's
7331 open and agenda-wise Org files."
7332 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7333 (dolist (buf (buffer-list))
7334 (with-current-buffer buf
7335 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7336 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7337 files))
7339 (defsubst org-entry-beginning-position ()
7340 "Return the beginning position of the current entry."
7341 (save-excursion (org-back-to-heading t) (point)))
7343 (defsubst org-entry-end-position ()
7344 "Return the end position of the current entry."
7345 (save-excursion (outline-next-heading) (point)))
7347 (defun org-cycle-hide-drawers (state &optional exceptions)
7348 "Re-hide all drawers after a visibility state change.
7349 When non-nil, optional argument EXCEPTIONS is a list of strings
7350 specifying which drawers should not be hidden."
7351 (when (and (derived-mode-p 'org-mode)
7352 (not (memq state '(overview folded contents))))
7353 (save-excursion
7354 (let* ((globalp (memq state '(contents all)))
7355 (beg (if globalp (point-min) (point)))
7356 (end (if globalp (point-max)
7357 (if (eq state 'children)
7358 (save-excursion (outline-next-heading) (point))
7359 (org-end-of-subtree t)))))
7360 (goto-char beg)
7361 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7362 (unless (member-ignore-case (match-string 1) exceptions)
7363 (let ((drawer (org-element-at-point)))
7364 (when (memq (org-element-type drawer) '(drawer property-drawer))
7365 (org-flag-drawer t drawer)
7366 ;; Make sure to skip drawer entirely or we might flag
7367 ;; it another time when matching its ending line with
7368 ;; `org-drawer-regexp'.
7369 (goto-char (org-element-property :end drawer))))))))))
7371 (defun org-flag-drawer (flag &optional element)
7372 "When FLAG is non-nil, hide the drawer we are at.
7373 Otherwise make it visible. When optional argument ELEMENT is
7374 a parsed drawer, as returned by `org-element-at-point', hide or
7375 show that drawer instead."
7376 (let ((drawer (or element
7377 (and (save-excursion
7378 (beginning-of-line)
7379 (looking-at-p org-drawer-regexp))
7380 (org-element-at-point)))))
7381 (when (memq (org-element-type drawer) '(drawer property-drawer))
7382 (let ((post (org-element-property :post-affiliated drawer)))
7383 (save-excursion
7384 (outline-flag-region
7385 (progn (goto-char post) (line-end-position))
7386 (progn (goto-char (org-element-property :end drawer))
7387 (skip-chars-backward " \r\t\n")
7388 (line-end-position))
7389 flag))
7390 ;; When the drawer is hidden away, make sure point lies in
7391 ;; a visible part of the buffer.
7392 (when (and flag (> (line-beginning-position) post))
7393 (goto-char post))))))
7395 (defun org-subtree-end-visible-p ()
7396 "Is the end of the current subtree visible?"
7397 (pos-visible-in-window-p
7398 (save-excursion (org-end-of-subtree t) (point))))
7400 (defun org-first-headline-recenter ()
7401 "Move cursor to the first headline and recenter the headline."
7402 (let ((window (get-buffer-window)))
7403 (when window
7404 (goto-char (point-min))
7405 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7406 (set-window-start window (line-beginning-position))))))
7408 ;;; Saving and restoring visibility
7410 (defun org-outline-overlay-data (&optional use-markers)
7411 "Return a list of the locations of all outline overlays.
7412 These are overlays with the `invisible' property value `outline'.
7413 The return value is a list of cons cells, with start and stop
7414 positions for each overlay.
7415 If USE-MARKERS is set, return the positions as markers."
7416 (let (beg end)
7417 (org-with-wide-buffer
7418 (delq nil
7419 (mapcar (lambda (o)
7420 (when (eq (overlay-get o 'invisible) 'outline)
7421 (setq beg (overlay-start o)
7422 end (overlay-end o))
7423 (and beg end (> end beg)
7424 (if use-markers
7425 (cons (copy-marker beg)
7426 (copy-marker end t))
7427 (cons beg end)))))
7428 (overlays-in (point-min) (point-max)))))))
7430 (defun org-set-outline-overlay-data (data)
7431 "Create visibility overlays for all positions in DATA.
7432 DATA should have been made by `org-outline-overlay-data'."
7433 (org-with-wide-buffer
7434 (outline-show-all)
7435 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7437 ;;; Folding of blocks
7439 (defvar-local org-hide-block-overlays nil
7440 "Overlays hiding blocks.")
7442 (defun org-block-map (function &optional start end)
7443 "Call FUNCTION at the head of all source blocks in the current buffer.
7444 Optional arguments START and END can be used to limit the range."
7445 (let ((start (or start (point-min)))
7446 (end (or end (point-max))))
7447 (save-excursion
7448 (goto-char start)
7449 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7450 (save-excursion
7451 (save-match-data
7452 (goto-char (match-beginning 0))
7453 (funcall function)))))))
7455 (defun org-hide-block-toggle-all ()
7456 "Toggle the visibility of all blocks in the current buffer."
7457 (org-block-map 'org-hide-block-toggle))
7459 (defun org-hide-block-all ()
7460 "Fold all blocks in the current buffer."
7461 (interactive)
7462 (org-show-block-all)
7463 (org-block-map 'org-hide-block-toggle-maybe))
7465 (defun org-show-block-all ()
7466 "Unfold all blocks in the current buffer."
7467 (interactive)
7468 (mapc #'delete-overlay org-hide-block-overlays)
7469 (setq org-hide-block-overlays nil))
7471 (defun org-hide-block-toggle-maybe ()
7472 "Toggle visibility of block at point.
7473 Unlike to `org-hide-block-toggle', this function does not throw
7474 an error. Return a non-nil value when toggling is successful."
7475 (interactive)
7476 (ignore-errors (org-hide-block-toggle)))
7478 (defun org-hide-block-toggle (&optional force)
7479 "Toggle the visibility of the current block.
7480 When optional argument FORCE is `off', make block visible. If it
7481 is non-nil, hide it unconditionally. Throw an error when not at
7482 a block. Return a non-nil value when toggling is successful."
7483 (interactive)
7484 (let ((element (org-element-at-point)))
7485 (unless (memq (org-element-type element)
7486 '(center-block comment-block dynamic-block example-block
7487 export-block quote-block special-block
7488 src-block verse-block))
7489 (user-error "Not at a block"))
7490 (let* ((start (save-excursion
7491 (goto-char (org-element-property :post-affiliated element))
7492 (line-end-position)))
7493 (end (save-excursion
7494 (goto-char (org-element-property :end element))
7495 (skip-chars-backward " \r\t\n")
7496 (line-end-position)))
7497 (overlays (overlays-at start)))
7498 (cond
7499 ;; Do nothing when not before or at the block opening line or
7500 ;; at the block closing line.
7501 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7502 ((and (not (eq force 'off))
7503 (not (memq t (mapcar
7504 (lambda (o)
7505 (eq (overlay-get o 'invisible) 'org-hide-block))
7506 overlays))))
7507 (let ((ov (make-overlay start end)))
7508 (overlay-put ov 'invisible 'org-hide-block)
7509 ;; Make the block accessible to `isearch'.
7510 (overlay-put
7511 ov 'isearch-open-invisible
7512 (lambda (ov)
7513 (when (memq ov org-hide-block-overlays)
7514 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7515 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7516 (delete-overlay ov))))
7517 (push ov org-hide-block-overlays)
7518 ;; When the block is hidden away, make sure point is left in
7519 ;; a visible part of the buffer.
7520 (when (> (line-beginning-position) start)
7521 (goto-char start)
7522 (beginning-of-line))
7523 ;; Signal successful toggling.
7525 ((or (not force) (eq force 'off))
7526 (dolist (ov overlays t)
7527 (when (memq ov org-hide-block-overlays)
7528 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7529 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7530 (delete-overlay ov))))))))
7532 ;; org-tab-after-check-for-cycling-hook
7533 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7534 ;; Remove overlays when changing major mode
7535 (add-hook 'org-mode-hook
7536 (lambda () (add-hook 'change-major-mode-hook
7537 'org-show-block-all 'append 'local)))
7539 ;;; Org-goto
7541 (defvar org-goto-window-configuration nil)
7542 (defvar org-goto-marker nil)
7543 (defvar org-goto-map)
7544 (defun org-goto-map ()
7545 "Set the keymap `org-goto'."
7546 (setq org-goto-map
7547 (let ((map (make-sparse-keymap)))
7548 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7549 mouse-drag-region universal-argument org-occur)))
7550 (dolist (cmd cmds)
7551 (substitute-key-definition cmd cmd map global-map)))
7552 (suppress-keymap map)
7553 (org-defkey map "\C-m" 'org-goto-ret)
7554 (org-defkey map [(return)] 'org-goto-ret)
7555 (org-defkey map [(left)] 'org-goto-left)
7556 (org-defkey map [(right)] 'org-goto-right)
7557 (org-defkey map [(control ?g)] 'org-goto-quit)
7558 (org-defkey map "\C-i" 'org-cycle)
7559 (org-defkey map [(tab)] 'org-cycle)
7560 (org-defkey map [(down)] 'outline-next-visible-heading)
7561 (org-defkey map [(up)] 'outline-previous-visible-heading)
7562 (if org-goto-auto-isearch
7563 (if (fboundp 'define-key-after)
7564 (define-key-after map [t] 'org-goto-local-auto-isearch)
7565 nil)
7566 (org-defkey map "q" 'org-goto-quit)
7567 (org-defkey map "n" 'outline-next-visible-heading)
7568 (org-defkey map "p" 'outline-previous-visible-heading)
7569 (org-defkey map "f" 'outline-forward-same-level)
7570 (org-defkey map "b" 'outline-backward-same-level)
7571 (org-defkey map "u" 'outline-up-heading))
7572 (org-defkey map "/" 'org-occur)
7573 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7574 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7575 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7576 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7577 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7578 map)))
7580 (defconst org-goto-help
7581 "Browse buffer copy, to find location or copy text.%s
7582 RET=jump to location C-g=quit and return to previous location
7583 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7585 (defvar org-goto-start-pos) ; dynamically scoped parameter
7587 (defun org-goto (&optional alternative-interface)
7588 "Look up a different location in the current file, keeping current visibility.
7590 When you want look-up or go to a different location in a
7591 document, the fastest way is often to fold the entire buffer and
7592 then dive into the tree. This method has the disadvantage, that
7593 the previous location will be folded, which may not be what you
7594 want.
7596 This command works around this by showing a copy of the current
7597 buffer in an indirect buffer, in overview mode. You can dive
7598 into the tree in that copy, use org-occur and incremental search
7599 to find a location. When pressing RET or `Q', the command
7600 returns to the original buffer in which the visibility is still
7601 unchanged. After RET it will also jump to the location selected
7602 in the indirect buffer and expose the headline hierarchy above.
7604 With a prefix argument, use the alternative interface: e.g., if
7605 `org-goto-interface' is `outline' use `outline-path-completion'."
7606 (interactive "P")
7607 (org-goto-map)
7608 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7609 (org-refile-use-outline-path t)
7610 (org-refile-target-verify-function nil)
7611 (interface
7612 (if (not alternative-interface)
7613 org-goto-interface
7614 (if (eq org-goto-interface 'outline)
7615 'outline-path-completion
7616 'outline)))
7617 (org-goto-start-pos (point))
7618 (selected-point
7619 (if (eq interface 'outline)
7620 (car (org-get-location (current-buffer) org-goto-help))
7621 (let ((pa (org-refile-get-location "Goto")))
7622 (org-refile-check-position pa)
7623 (nth 3 pa)))))
7624 (if selected-point
7625 (progn
7626 (org-mark-ring-push org-goto-start-pos)
7627 (goto-char selected-point)
7628 (when (or (outline-invisible-p) (org-invisible-p2))
7629 (org-show-context 'org-goto)))
7630 (message "Quit"))))
7632 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7633 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7634 (defvar org-goto-local-auto-isearch-map) ; defined below
7636 (defun org-get-location (_buf help)
7637 "Let the user select a location in current buffer.
7638 This function uses a recursive edit. It returns the selected position
7639 or nil."
7640 (org-no-popups
7641 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7642 (isearch-hide-immediately nil)
7643 (isearch-search-fun-function
7644 (lambda () 'org-goto-local-search-headings))
7645 (org-goto-selected-point org-goto-exit-command))
7646 (save-excursion
7647 (save-window-excursion
7648 (delete-other-windows)
7649 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7650 (pop-to-buffer-same-window
7651 (condition-case nil
7652 (make-indirect-buffer (current-buffer) "*org-goto*")
7653 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7654 (with-output-to-temp-buffer "*Org Help*"
7655 (princ (format help (if org-goto-auto-isearch
7656 " Just type for auto-isearch."
7657 " n/p/f/b/u to navigate, q to quit."))))
7658 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7659 (setq buffer-read-only nil)
7660 (let ((org-startup-truncated t)
7661 (org-startup-folded nil)
7662 (org-startup-align-all-tables nil))
7663 (org-mode)
7664 (org-overview))
7665 (setq buffer-read-only t)
7666 (if (and (boundp 'org-goto-start-pos)
7667 (integer-or-marker-p org-goto-start-pos))
7668 (progn (goto-char org-goto-start-pos)
7669 (when (outline-invisible-p)
7670 (org-show-set-visibility 'lineage)))
7671 (goto-char (point-min)))
7672 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7673 (message "Select location and press RET")
7674 (use-local-map org-goto-map)
7675 (recursive-edit)))
7676 (kill-buffer "*org-goto*")
7677 (cons org-goto-selected-point org-goto-exit-command))))
7679 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7680 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7681 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7682 (if (fboundp 'isearch-other-control-char)
7683 (progn
7684 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7685 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7686 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7687 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7688 (define-key org-goto-local-auto-isearch-map [return] nil))
7690 (defun org-goto-local-search-headings (string bound noerror)
7691 "Search and make sure that any matches are in headlines."
7692 (catch 'return
7693 (while (if isearch-forward
7694 (search-forward string bound noerror)
7695 (search-backward string bound noerror))
7696 (when (save-match-data
7697 (and (save-excursion
7698 (beginning-of-line)
7699 (looking-at org-complex-heading-regexp))
7700 (or (not (match-beginning 5))
7701 (< (point) (match-beginning 5)))))
7702 (throw 'return (point))))))
7704 (defun org-goto-local-auto-isearch ()
7705 "Start isearch."
7706 (interactive)
7707 (goto-char (point-min))
7708 (let ((keys (this-command-keys)))
7709 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7710 (isearch-mode t)
7711 (isearch-process-search-char (string-to-char keys)))))
7713 (defun org-goto-ret (&optional _arg)
7714 "Finish `org-goto' by going to the new location."
7715 (interactive "P")
7716 (setq org-goto-selected-point (point))
7717 (setq org-goto-exit-command 'return)
7718 (throw 'exit nil))
7720 (defun org-goto-left ()
7721 "Finish `org-goto' by going to the new location."
7722 (interactive)
7723 (if (org-at-heading-p)
7724 (progn
7725 (beginning-of-line 1)
7726 (setq org-goto-selected-point (point)
7727 org-goto-exit-command 'left)
7728 (throw 'exit nil))
7729 (user-error "Not on a heading")))
7731 (defun org-goto-right ()
7732 "Finish `org-goto' by going to the new location."
7733 (interactive)
7734 (if (org-at-heading-p)
7735 (progn
7736 (setq org-goto-selected-point (point)
7737 org-goto-exit-command 'right)
7738 (throw 'exit nil))
7739 (user-error "Not on a heading")))
7741 (defun org-goto-quit ()
7742 "Finish `org-goto' without cursor motion."
7743 (interactive)
7744 (setq org-goto-selected-point nil)
7745 (setq org-goto-exit-command 'quit)
7746 (throw 'exit nil))
7748 ;;; Indirect buffer display of subtrees
7750 (defvar org-indirect-dedicated-frame nil
7751 "This is the frame being used for indirect tree display.")
7752 (defvar org-last-indirect-buffer nil)
7754 (defun org-tree-to-indirect-buffer (&optional arg)
7755 "Create indirect buffer and narrow it to current subtree.
7756 With a numerical prefix ARG, go up to this level and then take that tree.
7757 If ARG is negative, go up that many levels.
7759 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7760 indirect buffer previously made with this command, to avoid proliferation of
7761 indirect buffers. However, when you call the command with a \
7762 \\[universal-argument] prefix, or
7763 when `org-indirect-buffer-display' is `new-frame', the last buffer
7764 is kept so that you can work with several indirect buffers at the same time.
7765 If `org-indirect-buffer-display' is `dedicated-frame', the \
7766 \\[universal-argument] prefix also
7767 requests that a new frame be made for the new buffer, so that the dedicated
7768 frame is not changed."
7769 (interactive "P")
7770 (let ((cbuf (current-buffer))
7771 (cwin (selected-window))
7772 (pos (point))
7773 beg end level heading ibuf)
7774 (save-excursion
7775 (org-back-to-heading t)
7776 (when (numberp arg)
7777 (setq level (org-outline-level))
7778 (when (< arg 0) (setq arg (+ level arg)))
7779 (while (> (setq level (org-outline-level)) arg)
7780 (org-up-heading-safe)))
7781 (setq beg (point)
7782 heading (org-get-heading 'no-tags))
7783 (org-end-of-subtree t t)
7784 (when (org-at-heading-p) (backward-char 1))
7785 (setq end (point)))
7786 (when (and (buffer-live-p org-last-indirect-buffer)
7787 (not (eq org-indirect-buffer-display 'new-frame))
7788 (not arg))
7789 (kill-buffer org-last-indirect-buffer))
7790 (setq ibuf (org-get-indirect-buffer cbuf heading)
7791 org-last-indirect-buffer ibuf)
7792 (cond
7793 ((or (eq org-indirect-buffer-display 'new-frame)
7794 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7795 (select-frame (make-frame))
7796 (delete-other-windows)
7797 (pop-to-buffer-same-window ibuf)
7798 (org-set-frame-title heading))
7799 ((eq org-indirect-buffer-display 'dedicated-frame)
7800 (raise-frame
7801 (select-frame (or (and org-indirect-dedicated-frame
7802 (frame-live-p org-indirect-dedicated-frame)
7803 org-indirect-dedicated-frame)
7804 (setq org-indirect-dedicated-frame (make-frame)))))
7805 (delete-other-windows)
7806 (pop-to-buffer-same-window ibuf)
7807 (org-set-frame-title (concat "Indirect: " heading)))
7808 ((eq org-indirect-buffer-display 'current-window)
7809 (pop-to-buffer-same-window ibuf))
7810 ((eq org-indirect-buffer-display 'other-window)
7811 (pop-to-buffer ibuf))
7812 (t (error "Invalid value")))
7813 (narrow-to-region beg end)
7814 (outline-show-all)
7815 (goto-char pos)
7816 (run-hook-with-args 'org-cycle-hook 'all)
7817 (and (window-live-p cwin) (select-window cwin))))
7819 (defun org-get-indirect-buffer (&optional buffer heading)
7820 (setq buffer (or buffer (current-buffer)))
7821 (let ((n 1) (base (buffer-name buffer)) bname)
7822 (while (buffer-live-p
7823 (get-buffer
7824 (setq bname
7825 (concat base "-"
7826 (if heading (concat heading "-" (number-to-string n))
7827 (number-to-string n))))))
7828 (setq n (1+ n)))
7829 (condition-case nil
7830 (make-indirect-buffer buffer bname 'clone)
7831 (error (make-indirect-buffer buffer bname)))))
7833 (defun org-set-frame-title (title)
7834 "Set the title of the current frame to the string TITLE."
7835 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7837 ;;;; Structure editing
7839 ;;; Inserting headlines
7841 (defun org--line-empty-p (n)
7842 "Is the Nth next line empty?
7844 Counts the current line as N = 1 and the previous line as N = 0;
7845 see `beginning-of-line'."
7846 (save-excursion
7847 (and (not (bobp))
7848 (or (beginning-of-line n) t)
7849 (save-match-data
7850 (looking-at "[ \t]*$")))))
7852 (defun org-previous-line-empty-p ()
7853 "Is the previous line a blank line?
7854 When NEXT is non-nil, check the next line instead."
7855 (org--line-empty-p 0))
7857 (defun org-next-line-empty-p ()
7858 "Is the previous line a blank line?
7859 When NEXT is non-nil, check the next line instead."
7860 (org--line-empty-p 2))
7862 (defun org-insert-heading (&optional arg invisible-ok top)
7863 "Insert a new heading or an item with the same depth at point.
7865 If point is at the beginning of a heading or a list item, insert
7866 a new heading or a new item above the current one. If point is
7867 at the beginning of a normal line, turn the line into a heading.
7869 If point is in the middle of a headline or a list item, split the
7870 headline or the item and create a new headline/item with the text
7871 in the current line after point \(see `org-M-RET-may-split-line'
7872 on how to modify this behavior).
7874 With one universal prefix argument, set the user option
7875 `org-insert-heading-respect-content' to t for the duration of
7876 the command. This modifies the behavior described above in this
7877 ways: on list items and at the beginning of normal lines, force
7878 the insertion of a heading after the current subtree.
7880 With two universal prefix arguments, insert the heading at the
7881 end of the grandparent subtree. For example, if point is within
7882 a 2nd-level heading, then it will insert a 2nd-level heading at
7883 the end of the 1st-level parent heading.
7885 If point is at the beginning of a headline, insert a sibling
7886 before the current headline. If point is not at the beginning,
7887 split the line and create a new headline with the text in the
7888 current line after point \(see `org-M-RET-may-split-line' on how
7889 to modify this behavior).
7891 If point is at the beginning of a normal line, turn this line
7892 into a heading.
7894 When INVISIBLE-OK is set, stop at invisible headlines when going
7895 back. This is important for non-interactive uses of the
7896 command.
7898 When optional argument TOP is non-nil, insert a level 1 heading,
7899 unconditionally."
7900 (interactive "P")
7901 (let ((itemp (and (not top) (org-in-item-p)))
7902 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7903 (respect-content (or org-insert-heading-respect-content
7904 (equal arg '(4))))
7905 (initial-content ""))
7907 (cond
7909 ((or (= (buffer-size) 0)
7910 (and (not (save-excursion
7911 (and (ignore-errors (org-back-to-heading invisible-ok))
7912 (org-at-heading-p))))
7913 (or arg (not itemp))))
7914 ;; At beginning of buffer or so high up that only a heading
7915 ;; makes sense.
7916 (cond ((and (bolp) (not respect-content)) (insert "* "))
7917 ((not respect-content)
7918 (unless may-split (end-of-line))
7919 (insert "\n* "))
7920 ((re-search-forward org-outline-regexp-bol nil t)
7921 (beginning-of-line)
7922 (insert "* \n")
7923 (backward-char))
7924 (t (goto-char (point-max))
7925 (insert "\n* ")))
7926 (run-hooks 'org-insert-heading-hook))
7928 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7931 ;; Maybe move at the end of the subtree
7932 (when (equal arg '(16))
7933 (org-up-heading-safe)
7934 (org-end-of-subtree t))
7935 ;; Insert a heading
7936 (save-restriction
7937 (widen)
7938 (let* ((level nil)
7939 (on-heading (org-at-heading-p))
7940 (empty-line-p (if on-heading
7941 (org-previous-line-empty-p)
7942 ;; We will decide later
7943 nil))
7944 ;; Get a level string to fall back on.
7945 (fix-level
7946 (if (org-before-first-heading-p) "*"
7947 (save-excursion
7948 (org-back-to-heading t)
7949 (when (org-previous-line-empty-p) (setq empty-line-p t))
7950 (looking-at org-outline-regexp)
7951 (make-string (1- (length (match-string 0))) ?*))))
7952 (stars
7953 (save-excursion
7954 (condition-case nil
7955 (if top "* "
7956 (org-back-to-heading invisible-ok)
7957 (when (and (not on-heading)
7958 (featurep 'org-inlinetask)
7959 (integerp org-inlinetask-min-level)
7960 (>= (length (match-string 0))
7961 org-inlinetask-min-level))
7962 ;; Find a heading level before the inline
7963 ;; task.
7964 (while (and (setq level (org-up-heading-safe))
7965 (>= level org-inlinetask-min-level)))
7966 (if (org-at-heading-p)
7967 (org-back-to-heading invisible-ok)
7968 (error "This should not happen")))
7969 (unless (and (save-excursion
7970 (save-match-data
7971 (org-backward-heading-same-level
7972 1 invisible-ok))
7973 (= (point) (match-beginning 0)))
7974 (not (org-next-line-empty-p)))
7975 (setq empty-line-p (or empty-line-p
7976 (org-previous-line-empty-p))))
7977 (match-string 0))
7978 (error (or fix-level "* ")))))
7979 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7980 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7982 ;; If we insert after content, move there and clean up
7983 ;; whitespace.
7984 (when (and respect-content
7985 (not (looking-at-p org-outline-regexp-bol)))
7986 (if (not (org-before-first-heading-p))
7987 (org-end-of-subtree nil t)
7988 (re-search-forward org-outline-regexp-bol)
7989 (beginning-of-line 0))
7990 (skip-chars-backward " \r\t\n")
7991 (and (not (looking-back "^\\*+" (line-beginning-position)))
7992 (looking-at "[ \t]+") (replace-match ""))
7993 (unless (eobp) (forward-char 1))
7994 (when (looking-at "^\\*")
7995 (unless (bobp) (backward-char 1))
7996 (insert "\n")))
7998 ;; If we are splitting, grab the text that should be moved
7999 ;; to the new headline.
8000 (when may-split
8001 (if (org-at-heading-p)
8002 ;; This is a heading: split intelligently (keeping
8003 ;; tags).
8004 (let ((pos (point)))
8005 (beginning-of-line)
8006 (unless (looking-at org-complex-heading-regexp)
8007 (error "This should not happen"))
8008 (when (and (match-beginning 4)
8009 (> pos (match-beginning 4))
8010 (< pos (match-end 4)))
8011 (setq initial-content (buffer-substring pos (match-end 4)))
8012 (goto-char pos)
8013 (delete-region (point) (match-end 4))
8014 (if (looking-at "[ \t]*$")
8015 (replace-match "")
8016 (insert (make-string (length initial-content) ?\s)))
8017 (setq initial-content (org-trim initial-content)))
8018 (goto-char pos))
8019 ;; A normal line.
8020 (setq initial-content
8021 (org-trim
8022 (delete-and-extract-region (point) (line-end-position))))))
8024 ;; If we are at the beginning of the line, insert before it.
8025 ;; Otherwise, after it.
8026 (cond
8027 ((and (bolp) (looking-at "[ \t]*$")))
8028 ((bolp) (save-excursion (insert "\n")))
8029 (t (end-of-line)
8030 (insert "\n")))
8032 ;; Insert the new heading
8033 (insert stars)
8034 (just-one-space)
8035 (insert initial-content)
8036 (unless (and blank (org-previous-line-empty-p))
8037 (org-N-empty-lines-before-current (if blank 1 0)))
8038 ;; Adjust visibility, which may be messed up if we removed
8039 ;; blank lines while previous entry was hidden.
8040 (let ((bol (line-beginning-position)))
8041 (dolist (o (overlays-at (1- bol)))
8042 (when (and (eq (overlay-get o 'invisible) 'outline)
8043 (eq (overlay-end o) bol))
8044 (move-overlay o (overlay-start o) (1- bol)))))
8045 (run-hooks 'org-insert-heading-hook)))))))
8047 (defun org-N-empty-lines-before-current (N)
8048 "Make the number of empty lines before current exactly N.
8049 So this will delete or add empty lines."
8050 (save-excursion
8051 (beginning-of-line)
8052 (let ((p (point)))
8053 (skip-chars-backward " \r\t\n")
8054 (unless (bolp) (forward-line))
8055 (delete-region (point) p))
8056 (when (> N 0) (insert (make-string N ?\n)))))
8058 (defun org-get-heading (&optional no-tags no-todo)
8059 "Return the heading of the current entry, without the stars.
8060 When NO-TAGS is non-nil, don't include tags.
8061 When NO-TODO is non-nil, don't include TODO keywords."
8062 (save-excursion
8063 (org-back-to-heading t)
8064 (let ((case-fold-search nil))
8065 (cond
8066 ((and no-tags no-todo)
8067 (looking-at org-complex-heading-regexp)
8068 ;; Return value has to be a string, but match group 4 is
8069 ;; optional.
8070 (or (match-string 4) ""))
8071 (no-tags
8072 (looking-at (concat org-outline-regexp
8073 "\\(.*?\\)"
8074 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8075 (match-string 1))
8076 (no-todo
8077 (looking-at org-todo-line-regexp)
8078 (match-string 3))
8079 (t (looking-at org-heading-regexp)
8080 (match-string 2))))))
8082 (defvar orgstruct-mode) ; defined below
8084 (defun org-heading-components ()
8085 "Return the components of the current heading.
8086 This is a list with the following elements:
8087 - the level as an integer
8088 - the reduced level, different if `org-odd-levels-only' is set.
8089 - the TODO keyword, or nil
8090 - the priority character, like ?A, or nil if no priority is given
8091 - the headline text itself, or the tags string if no headline text
8092 - the tags string, or nil."
8093 (save-excursion
8094 (org-back-to-heading t)
8095 (when (let (case-fold-search)
8096 (looking-at
8097 (if orgstruct-mode
8098 org-heading-regexp
8099 org-complex-heading-regexp)))
8100 (if orgstruct-mode
8101 (list (length (match-string 1))
8102 (org-reduced-level (length (match-string 1)))
8105 (match-string 2)
8106 nil)
8107 (list (length (match-string 1))
8108 (org-reduced-level (length (match-string 1)))
8109 (match-string-no-properties 2)
8110 (and (match-end 3) (aref (match-string 3) 2))
8111 (match-string-no-properties 4)
8112 (match-string-no-properties 5))))))
8114 (defun org-get-entry ()
8115 "Get the entry text, after heading, entire subtree."
8116 (save-excursion
8117 (org-back-to-heading t)
8118 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8120 (defun org-edit-headline (&optional heading)
8121 "Edit the current headline.
8122 Set it to HEADING when provided."
8123 (interactive)
8124 (org-with-wide-buffer
8125 (org-back-to-heading t)
8126 (when (looking-at org-complex-heading-regexp)
8127 (let* ((old (match-string-no-properties 4))
8128 (new (save-match-data
8129 (org-trim (or heading (read-string "Edit: " old))))))
8130 (unless (equal old new)
8131 (if old (replace-match new t t nil 4)
8132 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8133 (insert " " new))
8134 (org-set-tags nil t)
8135 (when (looking-at "[ \t]*$") (replace-match "")))))))
8137 (defun org-insert-heading-after-current ()
8138 "Insert a new heading with same level as current, after current subtree."
8139 (interactive)
8140 (org-back-to-heading)
8141 (org-insert-heading)
8142 (org-move-subtree-down)
8143 (end-of-line 1))
8145 (defun org-insert-heading-respect-content (&optional invisible-ok)
8146 "Insert heading with `org-insert-heading-respect-content' set to t."
8147 (interactive)
8148 (org-insert-heading '(4) invisible-ok))
8150 (defun org-insert-todo-heading-respect-content (&optional force-state)
8151 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8152 (interactive)
8153 (org-insert-todo-heading force-state '(4)))
8155 (defun org-insert-todo-heading (arg &optional force-heading)
8156 "Insert a new heading with the same level and TODO state as current heading.
8157 If the heading has no TODO state, or if the state is DONE, use the first
8158 state (TODO by default). Also with one prefix arg, force first state. With
8159 two prefix args, force inserting at the end of the parent subtree."
8160 (interactive "P")
8161 (when (or force-heading (not (org-insert-item 'checkbox)))
8162 (org-insert-heading (or (and (equal arg '(16)) '(16))
8163 force-heading))
8164 (save-excursion
8165 (org-back-to-heading)
8166 (outline-previous-heading)
8167 (looking-at org-todo-line-regexp))
8168 (let*
8169 ((new-mark-x
8170 (if (or (equal arg '(4))
8171 (not (match-beginning 2))
8172 (member (match-string 2) org-done-keywords))
8173 (car org-todo-keywords-1)
8174 (match-string 2)))
8175 (new-mark
8177 (run-hook-with-args-until-success
8178 'org-todo-get-default-hook new-mark-x nil)
8179 new-mark-x)))
8180 (beginning-of-line 1)
8181 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8182 (if org-treat-insert-todo-heading-as-state-change
8183 (org-todo new-mark)
8184 (insert new-mark " "))))
8185 (when org-provide-todo-statistics
8186 (org-update-parent-todo-statistics))))
8188 (defun org-insert-subheading (arg)
8189 "Insert a new subheading and demote it.
8190 Works for outline headings and for plain lists alike."
8191 (interactive "P")
8192 (org-insert-heading arg)
8193 (cond
8194 ((org-at-heading-p) (org-do-demote))
8195 ((org-at-item-p) (org-indent-item))))
8197 (defun org-insert-todo-subheading (arg)
8198 "Insert a new subheading with TODO keyword or checkbox and demote it.
8199 Works for outline headings and for plain lists alike."
8200 (interactive "P")
8201 (org-insert-todo-heading arg)
8202 (cond
8203 ((org-at-heading-p) (org-do-demote))
8204 ((org-at-item-p) (org-indent-item))))
8206 ;;; Promotion and Demotion
8208 (defvar org-after-demote-entry-hook nil
8209 "Hook run after an entry has been demoted.
8210 The cursor will be at the beginning of the entry.
8211 When a subtree is being demoted, the hook will be called for each node.")
8213 (defvar org-after-promote-entry-hook nil
8214 "Hook run after an entry has been promoted.
8215 The cursor will be at the beginning of the entry.
8216 When a subtree is being promoted, the hook will be called for each node.")
8218 (defun org-promote-subtree ()
8219 "Promote the entire subtree.
8220 See also `org-promote'."
8221 (interactive)
8222 (save-excursion
8223 (org-with-limited-levels (org-map-tree 'org-promote)))
8224 (org-fix-position-after-promote))
8226 (defun org-demote-subtree ()
8227 "Demote the entire subtree.
8228 See `org-demote' and `org-promote'."
8229 (interactive)
8230 (save-excursion
8231 (org-with-limited-levels (org-map-tree 'org-demote)))
8232 (org-fix-position-after-promote))
8234 (defun org-do-promote ()
8235 "Promote the current heading higher up the tree.
8236 If the region is active in `transient-mark-mode', promote all
8237 headings in the region."
8238 (interactive)
8239 (save-excursion
8240 (if (org-region-active-p)
8241 (org-map-region 'org-promote (region-beginning) (region-end))
8242 (org-promote)))
8243 (org-fix-position-after-promote))
8245 (defun org-do-demote ()
8246 "Demote the current heading lower down the tree.
8247 If the region is active in `transient-mark-mode', demote all
8248 headings in the region."
8249 (interactive)
8250 (save-excursion
8251 (if (org-region-active-p)
8252 (org-map-region 'org-demote (region-beginning) (region-end))
8253 (org-demote)))
8254 (org-fix-position-after-promote))
8256 (defun org-fix-position-after-promote ()
8257 "Fix cursor position and indentation after demoting/promoting."
8258 (let ((pos (point)))
8259 (when (save-excursion
8260 (beginning-of-line 1)
8261 (looking-at org-todo-line-regexp)
8262 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8263 (cond ((eobp) (insert " "))
8264 ((eolp) (insert " "))
8265 ((equal (char-after) ?\ ) (forward-char 1))))))
8267 (defun org-current-level ()
8268 "Return the level of the current entry, or nil if before the first headline.
8269 The level is the number of stars at the beginning of the
8270 headline. Use `org-reduced-level' to remove the effect of
8271 `org-odd-levels'. Unlike to `org-outline-level', this function
8272 ignores inlinetasks."
8273 (let ((level (org-with-limited-levels (org-outline-level))))
8274 (and (> level 0) level)))
8276 (defun org-get-previous-line-level ()
8277 "Return the outline depth of the last headline before the current line.
8278 Returns 0 for the first headline in the buffer, and nil if before the
8279 first headline."
8280 (and (org-current-level)
8281 (or (and (/= (line-beginning-position) (point-min))
8282 (save-excursion (beginning-of-line 0) (org-current-level)))
8283 0)))
8285 (defun org-reduced-level (l)
8286 "Compute the effective level of a heading.
8287 This takes into account the setting of `org-odd-levels-only'."
8288 (cond
8289 ((zerop l) 0)
8290 (org-odd-levels-only (1+ (floor (/ l 2))))
8291 (t l)))
8293 (defun org-level-increment ()
8294 "Return the number of stars that will be added or removed at a
8295 time to headlines when structure editing, based on the value of
8296 `org-odd-levels-only'."
8297 (if org-odd-levels-only 2 1))
8299 (defun org-get-valid-level (level &optional change)
8300 "Rectify a level change under the influence of `org-odd-levels-only'
8301 LEVEL is a current level, CHANGE is by how much the level should be
8302 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8303 even level numbers will become the next higher odd number."
8304 (if org-odd-levels-only
8305 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8306 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8307 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8308 (max 1 (+ level (or change 0)))))
8310 (defun org-promote ()
8311 "Promote the current heading higher up the tree."
8312 (org-with-wide-buffer
8313 (org-back-to-heading t)
8314 (let* ((after-change-functions (remq 'flyspell-after-change-function
8315 after-change-functions))
8316 (level (save-match-data (funcall outline-level)))
8317 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8318 (diff (abs (- level (length up-head) -1))))
8319 (cond
8320 ((and (= level 1) org-allow-promoting-top-level-subtree)
8321 (replace-match "# " nil t))
8322 ((= level 1)
8323 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8324 (t (replace-match up-head nil t)))
8325 (unless (= level 1)
8326 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8327 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8328 (run-hooks 'org-after-promote-entry-hook))))
8330 (defun org-demote ()
8331 "Demote the current heading lower down the tree."
8332 (org-with-wide-buffer
8333 (org-back-to-heading t)
8334 (let* ((after-change-functions (remq 'flyspell-after-change-function
8335 after-change-functions))
8336 (level (save-match-data (funcall outline-level)))
8337 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8338 (diff (abs (- level (length down-head) -1))))
8339 (replace-match down-head nil t)
8340 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8341 (when org-adapt-indentation (org-fixup-indentation diff))
8342 (run-hooks 'org-after-demote-entry-hook))))
8344 (defun org-cycle-level ()
8345 "Cycle the level of an empty headline through possible states.
8346 This goes first to child, then to parent, level, then up the hierarchy.
8347 After top level, it switches back to sibling level."
8348 (interactive)
8349 (let ((org-adapt-indentation nil))
8350 (when (org-point-at-end-of-empty-headline)
8351 (setq this-command 'org-cycle-level) ; Only needed for caching
8352 (let ((cur-level (org-current-level))
8353 (prev-level (org-get-previous-line-level)))
8354 (cond
8355 ;; If first headline in file, promote to top-level.
8356 ((= prev-level 0)
8357 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8358 do (org-do-promote)))
8359 ;; If same level as prev, demote one.
8360 ((= prev-level cur-level)
8361 (org-do-demote))
8362 ;; If parent is top-level, promote to top level if not already.
8363 ((= prev-level 1)
8364 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8365 do (org-do-promote)))
8366 ;; If top-level, return to prev-level.
8367 ((= cur-level 1)
8368 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8369 do (org-do-demote)))
8370 ;; If less than prev-level, promote one.
8371 ((< cur-level prev-level)
8372 (org-do-promote))
8373 ;; If deeper than prev-level, promote until higher than
8374 ;; prev-level.
8375 ((> cur-level prev-level)
8376 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8377 do (org-do-promote))))
8378 t))))
8380 (defun org-map-tree (fun)
8381 "Call FUN for every heading underneath the current one."
8382 (org-back-to-heading t)
8383 (let ((level (funcall outline-level)))
8384 (save-excursion
8385 (funcall fun)
8386 (while (and (progn
8387 (outline-next-heading)
8388 (> (funcall outline-level) level))
8389 (not (eobp)))
8390 (funcall fun)))))
8392 (defun org-map-region (fun beg end)
8393 "Call FUN for every heading between BEG and END."
8394 (let ((org-ignore-region t))
8395 (save-excursion
8396 (setq end (copy-marker end))
8397 (goto-char beg)
8398 (when (and (re-search-forward org-outline-regexp-bol nil t)
8399 (< (point) end))
8400 (funcall fun))
8401 (while (and (progn
8402 (outline-next-heading)
8403 (< (point) end))
8404 (not (eobp)))
8405 (funcall fun)))))
8407 (defun org-fixup-indentation (diff)
8408 "Change the indentation in the current entry by DIFF.
8410 DIFF is an integer. Indentation is done according to the
8411 following rules:
8413 - Planning information and property drawers are always indented
8414 according to the new level of the headline;
8416 - Footnote definitions and their contents are ignored;
8418 - Inlinetasks' boundaries are not shifted;
8420 - Empty lines are ignored;
8422 - Other lines' indentation are shifted by DIFF columns, unless
8423 it would introduce a structural change in the document, in
8424 which case no shifting is done at all.
8426 Assume point is at a heading or an inlinetask beginning."
8427 (org-with-wide-buffer
8428 (narrow-to-region (line-beginning-position)
8429 (save-excursion
8430 (if (org-with-limited-levels (org-at-heading-p))
8431 (org-with-limited-levels (outline-next-heading))
8432 (org-inlinetask-goto-end))
8433 (point)))
8434 (forward-line)
8435 ;; Indent properly planning info and property drawer.
8436 (when (looking-at-p org-planning-line-re)
8437 (org-indent-line)
8438 (forward-line))
8439 (when (looking-at org-property-drawer-re)
8440 (goto-char (match-end 0))
8441 (forward-line)
8442 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8443 (catch 'no-shift
8444 (when (zerop diff) (throw 'no-shift nil))
8445 ;; If DIFF is negative, first check if a shift is possible at all
8446 ;; (e.g., it doesn't break structure). This can only happen if
8447 ;; some contents are not properly indented.
8448 (let ((case-fold-search t))
8449 (when (< diff 0)
8450 (let ((diff (- diff))
8451 (forbidden-re (concat org-outline-regexp
8452 "\\|"
8453 (substring org-footnote-definition-re 1))))
8454 (save-excursion
8455 (while (not (eobp))
8456 (cond
8457 ((looking-at-p "[ \t]*$") (forward-line))
8458 ((and (looking-at-p org-footnote-definition-re)
8459 (let ((e (org-element-at-point)))
8460 (and (eq (org-element-type e) 'footnote-definition)
8461 (goto-char (org-element-property :end e))))))
8462 ((looking-at-p org-outline-regexp) (forward-line))
8463 ;; Give up if shifting would move before column 0 or
8464 ;; if it would introduce a headline or a footnote
8465 ;; definition.
8467 (skip-chars-forward " \t")
8468 (let ((ind (current-column)))
8469 (when (or (< ind diff)
8470 (and (= ind diff) (looking-at-p forbidden-re)))
8471 (throw 'no-shift nil)))
8472 ;; Ignore contents of example blocks and source
8473 ;; blocks if their indentation is meant to be
8474 ;; preserved. Jump to block's closing line.
8475 (beginning-of-line)
8476 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8477 (let ((e (org-element-at-point)))
8478 (and (memq (org-element-type e)
8479 '(example-block src-block))
8480 (or org-src-preserve-indentation
8481 (org-element-property :preserve-indent e))
8482 (goto-char (org-element-property :end e))
8483 (progn (skip-chars-backward " \r\t\n")
8484 (beginning-of-line)
8485 t))))
8486 (forward-line))))))))
8487 ;; Shift lines but footnote definitions, inlinetasks boundaries
8488 ;; by DIFF. Also skip contents of source or example blocks
8489 ;; when indentation is meant to be preserved.
8490 (while (not (eobp))
8491 (cond
8492 ((and (looking-at-p org-footnote-definition-re)
8493 (let ((e (org-element-at-point)))
8494 (and (eq (org-element-type e) 'footnote-definition)
8495 (goto-char (org-element-property :end e))))))
8496 ((looking-at-p org-outline-regexp) (forward-line))
8497 ((looking-at-p "[ \t]*$") (forward-line))
8499 (indent-line-to (+ (org-get-indentation) diff))
8500 (beginning-of-line)
8501 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8502 (let ((e (org-element-at-point)))
8503 (and (memq (org-element-type e)
8504 '(example-block src-block))
8505 (or org-src-preserve-indentation
8506 (org-element-property :preserve-indent e))
8507 (goto-char (org-element-property :end e))
8508 (progn (skip-chars-backward " \r\t\n")
8509 (beginning-of-line)
8510 t))))
8511 (forward-line)))))))))
8513 (defun org-convert-to-odd-levels ()
8514 "Convert an Org file with all levels allowed to one with odd levels.
8515 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8516 level 5 etc."
8517 (interactive)
8518 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8519 (let ((outline-level 'org-outline-level)
8520 (org-odd-levels-only nil) n)
8521 (save-excursion
8522 (goto-char (point-min))
8523 (while (re-search-forward "^\\*\\*+ " nil t)
8524 (setq n (- (length (match-string 0)) 2))
8525 (while (>= (setq n (1- n)) 0)
8526 (org-demote))
8527 (end-of-line 1))))))
8529 (defun org-convert-to-oddeven-levels ()
8530 "Convert an Org file with only odd levels to one with odd/even levels.
8531 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8532 file contains a section with an even level, conversion would
8533 destroy the structure of the file. An error is signaled in this
8534 case."
8535 (interactive)
8536 (goto-char (point-min))
8537 ;; First check if there are no even levels
8538 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8539 (org-show-set-visibility 'canonical)
8540 (error "Not all levels are odd in this file. Conversion not possible"))
8541 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8542 (let ((outline-regexp org-outline-regexp)
8543 (outline-level 'org-outline-level)
8544 (org-odd-levels-only nil) n)
8545 (save-excursion
8546 (goto-char (point-min))
8547 (while (re-search-forward "^\\*\\*+ " nil t)
8548 (setq n (/ (1- (length (match-string 0))) 2))
8549 (while (>= (setq n (1- n)) 0)
8550 (org-promote))
8551 (end-of-line 1))))))
8553 (defun org-tr-level (n)
8554 "Make N odd if required."
8555 (if org-odd-levels-only (1+ (/ n 2)) n))
8557 ;;; Vertical tree motion, cutting and pasting of subtrees
8559 (defun org-move-subtree-up (&optional arg)
8560 "Move the current subtree up past ARG headlines of the same level."
8561 (interactive "p")
8562 (org-move-subtree-down (- (prefix-numeric-value arg))))
8564 (defun org-move-subtree-down (&optional arg)
8565 "Move the current subtree down past ARG headlines of the same level."
8566 (interactive "p")
8567 (setq arg (prefix-numeric-value arg))
8568 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8569 'org-get-last-sibling))
8570 (ins-point (make-marker))
8571 (cnt (abs arg))
8572 (col (current-column))
8573 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8574 ;; Select the tree
8575 (org-back-to-heading)
8576 (setq beg0 (point))
8577 (save-excursion
8578 (setq ne-beg (org-back-over-empty-lines))
8579 (setq beg (point)))
8580 (save-match-data
8581 (save-excursion (outline-end-of-heading)
8582 (setq folded (outline-invisible-p)))
8583 (progn (org-end-of-subtree nil t)
8584 (unless (eobp) (backward-char))))
8585 (outline-next-heading)
8586 (setq ne-end (org-back-over-empty-lines))
8587 (setq end (point))
8588 (goto-char beg0)
8589 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8590 ;; include less whitespace
8591 (save-excursion
8592 (goto-char beg)
8593 (forward-line (- ne-beg ne-end))
8594 (setq beg (point))))
8595 ;; Find insertion point, with error handling
8596 (while (> cnt 0)
8597 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8598 (progn (goto-char beg0)
8599 (user-error "Cannot move past superior level or buffer limit")))
8600 (setq cnt (1- cnt)))
8601 (when (> arg 0)
8602 ;; Moving forward - still need to move over subtree
8603 (org-end-of-subtree t t)
8604 (save-excursion
8605 (org-back-over-empty-lines)
8606 (or (bolp) (newline))))
8607 (setq ne-ins (org-back-over-empty-lines))
8608 (move-marker ins-point (point))
8609 (setq txt (buffer-substring beg end))
8610 (org-save-markers-in-region beg end)
8611 (delete-region beg end)
8612 (org-remove-empty-overlays-at beg)
8613 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8614 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8615 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8616 (let ((bbb (point)))
8617 (insert-before-markers txt)
8618 (org-reinstall-markers-in-region bbb)
8619 (move-marker ins-point bbb))
8620 (or (bolp) (insert "\n"))
8621 (setq ins-end (point))
8622 (goto-char ins-point)
8623 (org-skip-whitespace)
8624 (when (and (< arg 0)
8625 (org-first-sibling-p)
8626 (> ne-ins ne-beg))
8627 ;; Move whitespace back to beginning
8628 (save-excursion
8629 (goto-char ins-end)
8630 (let ((kill-whole-line t))
8631 (kill-line (- ne-ins ne-beg)) (point)))
8632 (insert (make-string (- ne-ins ne-beg) ?\n)))
8633 (move-marker ins-point nil)
8634 (if folded
8635 (outline-hide-subtree)
8636 (org-show-entry)
8637 (org-show-children)
8638 (org-cycle-hide-drawers 'children))
8639 (org-clean-visibility-after-subtree-move)
8640 ;; move back to the initial column we were at
8641 (move-to-column col)))
8643 (defvar org-subtree-clip ""
8644 "Clipboard for cut and paste of subtrees.
8645 This is actually only a copy of the kill, because we use the normal kill
8646 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8648 (defvar org-subtree-clip-folded nil
8649 "Was the last copied subtree folded?
8650 This is used to fold the tree back after pasting.")
8652 (defun org-cut-subtree (&optional n)
8653 "Cut the current subtree into the clipboard.
8654 With prefix arg N, cut this many sequential subtrees.
8655 This is a short-hand for marking the subtree and then cutting it."
8656 (interactive "p")
8657 (org-copy-subtree n 'cut))
8659 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8660 "Copy the current subtree it in the clipboard.
8661 With prefix arg N, copy this many sequential subtrees.
8662 This is a short-hand for marking the subtree and then copying it.
8663 If CUT is non-nil, actually cut the subtree.
8664 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8665 of some markers in the region, even if CUT is non-nil. This is
8666 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8667 (interactive "p")
8668 (let (beg end folded (beg0 (point)))
8669 (if (called-interactively-p 'any)
8670 (org-back-to-heading nil) ; take what looks like a subtree
8671 (org-back-to-heading t)) ; take what is really there
8672 (setq beg (point))
8673 (skip-chars-forward " \t\r\n")
8674 (save-match-data
8675 (if nosubtrees
8676 (outline-next-heading)
8677 (save-excursion (outline-end-of-heading)
8678 (setq folded (outline-invisible-p)))
8679 (ignore-errors (org-forward-heading-same-level (1- n) t))
8680 (org-end-of-subtree t t)))
8681 ;; Include the end of an inlinetask
8682 (when (and (featurep 'org-inlinetask)
8683 (looking-at-p (concat (org-inlinetask-outline-regexp)
8684 "END[ \t]*$")))
8685 (end-of-line))
8686 (setq end (point))
8687 (goto-char beg0)
8688 (when (> end beg)
8689 (setq org-subtree-clip-folded folded)
8690 (when (or cut force-store-markers)
8691 (org-save-markers-in-region beg end))
8692 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8693 (setq org-subtree-clip (current-kill 0))
8694 (message "%s: Subtree(s) with %d characters"
8695 (if cut "Cut" "Copied")
8696 (length org-subtree-clip)))))
8698 (defun org-paste-subtree (&optional level tree for-yank remove)
8699 "Paste the clipboard as a subtree, with modification of headline level.
8700 The entire subtree is promoted or demoted in order to match a new headline
8701 level.
8703 If the cursor is at the beginning of a headline, the same level as
8704 that headline is used to paste the tree.
8706 If not, the new level is derived from the *visible* headings
8707 before and after the insertion point, and taken to be the inferior headline
8708 level of the two. So if the previous visible heading is level 3 and the
8709 next is level 4 (or vice versa), level 4 will be used for insertion.
8710 This makes sure that the subtree remains an independent subtree and does
8711 not swallow low level entries.
8713 You can also force a different level, either by using a numeric prefix
8714 argument, or by inserting the heading marker by hand. For example, if the
8715 cursor is after \"*****\", then the tree will be shifted to level 5.
8717 If optional TREE is given, use this text instead of the kill ring.
8719 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8720 move back over whitespace before inserting, and move point to the end of
8721 the inserted text when done.
8723 When REMOVE is non-nil, remove the subtree from the clipboard."
8724 (interactive "P")
8725 (setq tree (or tree (and kill-ring (current-kill 0))))
8726 (unless (org-kill-is-subtree-p tree)
8727 (user-error "%s"
8728 (substitute-command-keys
8729 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8730 (org-with-limited-levels
8731 (let* ((visp (not (outline-invisible-p)))
8732 (txt tree)
8733 (^re_ "\\(\\*+\\)[ \t]*")
8734 (old-level (if (string-match org-outline-regexp-bol txt)
8735 (- (match-end 0) (match-beginning 0) 1)
8736 -1))
8737 (force-level (cond (level (prefix-numeric-value level))
8738 ((and (looking-at "[ \t]*$")
8739 (string-match
8740 "^\\*+$" (buffer-substring
8741 (point-at-bol) (point))))
8742 (- (match-end 0) (match-beginning 0)))
8743 ((and (bolp)
8744 (looking-at org-outline-regexp))
8745 (- (match-end 0) (point) 1))))
8746 (previous-level (save-excursion
8747 (condition-case nil
8748 (progn
8749 (outline-previous-visible-heading 1)
8750 (if (looking-at ^re_)
8751 (- (match-end 0) (match-beginning 0) 1)
8753 (error 1))))
8754 (next-level (save-excursion
8755 (condition-case nil
8756 (progn
8757 (or (looking-at org-outline-regexp)
8758 (outline-next-visible-heading 1))
8759 (if (looking-at ^re_)
8760 (- (match-end 0) (match-beginning 0) 1)
8762 (error 1))))
8763 (new-level (or force-level (max previous-level next-level)))
8764 (shift (if (or (= old-level -1)
8765 (= new-level -1)
8766 (= old-level new-level))
8768 (- new-level old-level)))
8769 (delta (if (> shift 0) -1 1))
8770 (func (if (> shift 0) 'org-demote 'org-promote))
8771 (org-odd-levels-only nil)
8772 beg end newend)
8773 ;; Remove the forced level indicator
8774 (when force-level
8775 (delete-region (point-at-bol) (point)))
8776 ;; Paste
8777 (beginning-of-line (if (bolp) 1 2))
8778 (setq beg (point))
8779 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8780 (insert-before-markers txt)
8781 (unless (string-suffix-p "\n" txt) (insert "\n"))
8782 (setq newend (point))
8783 (org-reinstall-markers-in-region beg)
8784 (setq end (point))
8785 (goto-char beg)
8786 (skip-chars-forward " \t\n\r")
8787 (setq beg (point))
8788 (when (and (outline-invisible-p) visp)
8789 (save-excursion (outline-show-heading)))
8790 ;; Shift if necessary
8791 (unless (= shift 0)
8792 (save-restriction
8793 (narrow-to-region beg end)
8794 (while (not (= shift 0))
8795 (org-map-region func (point-min) (point-max))
8796 (setq shift (+ delta shift)))
8797 (goto-char (point-min))
8798 (setq newend (point-max))))
8799 (when (or (called-interactively-p 'interactive) for-yank)
8800 (message "Clipboard pasted as level %d subtree" new-level))
8801 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8802 kill-ring
8803 (eq org-subtree-clip (current-kill 0))
8804 org-subtree-clip-folded)
8805 ;; The tree was folded before it was killed/copied
8806 (outline-hide-subtree))
8807 (and for-yank (goto-char newend))
8808 (and remove (setq kill-ring (cdr kill-ring))))))
8810 (defun org-kill-is-subtree-p (&optional txt)
8811 "Check if the current kill is an outline subtree, or a set of trees.
8812 Returns nil if kill does not start with a headline, or if the first
8813 headline level is not the largest headline level in the tree.
8814 So this will actually accept several entries of equal levels as well,
8815 which is OK for `org-paste-subtree'.
8816 If optional TXT is given, check this string instead of the current kill."
8817 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8818 (re (org-get-limited-outline-regexp))
8819 (^re (concat "^" re))
8820 (start-level (and kill
8821 (string-match
8822 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8823 kill)
8824 (- (match-end 2) (match-beginning 2) 1)))
8825 (start (1+ (or (match-beginning 2) -1))))
8826 (if (not start-level)
8827 (progn
8828 nil) ;; does not even start with a heading
8829 (catch 'exit
8830 (while (setq start (string-match ^re kill (1+ start)))
8831 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8832 (throw 'exit nil)))
8833 t))))
8835 (defvar org-markers-to-move nil
8836 "Markers that should be moved with a cut-and-paste operation.
8837 Those markers are stored together with their positions relative to
8838 the start of the region.")
8840 (defun org-save-markers-in-region (beg end)
8841 "Check markers in region.
8842 If these markers are between BEG and END, record their position relative
8843 to BEG, so that after moving the block of text, we can put the markers back
8844 into place.
8845 This function gets called just before an entry or tree gets cut from the
8846 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8847 called immediately, to move the markers with the entries."
8848 (setq org-markers-to-move nil)
8849 (when (featurep 'org-clock)
8850 (org-clock-save-markers-for-cut-and-paste beg end))
8851 (when (featurep 'org-agenda)
8852 (org-agenda-save-markers-for-cut-and-paste beg end)))
8854 (defun org-check-and-save-marker (marker beg end)
8855 "Check if MARKER is between BEG and END.
8856 If yes, remember the marker and the distance to BEG."
8857 (when (and (marker-buffer marker)
8858 (equal (marker-buffer marker) (current-buffer))
8859 (>= marker beg) (< marker end))
8860 (push (cons marker (- marker beg)) org-markers-to-move)))
8862 (defun org-reinstall-markers-in-region (beg)
8863 "Move all remembered markers to their position relative to BEG."
8864 (dolist (x org-markers-to-move)
8865 (move-marker (car x) (+ beg (cdr x))))
8866 (setq org-markers-to-move nil))
8868 (defun org-narrow-to-subtree ()
8869 "Narrow buffer to the current subtree."
8870 (interactive)
8871 (save-excursion
8872 (save-match-data
8873 (org-with-limited-levels
8874 (narrow-to-region
8875 (progn (org-back-to-heading t) (point))
8876 (progn (org-end-of-subtree t t)
8877 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8878 (point)))))))
8880 (defun org-narrow-to-block ()
8881 "Narrow buffer to the current block."
8882 (interactive)
8883 (let* ((case-fold-search t)
8884 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8885 "^[ \t]*#\\+end_.*")))
8886 (if blockp
8887 (narrow-to-region (car blockp) (cdr blockp))
8888 (user-error "Not in a block"))))
8890 (defun org-clone-subtree-with-time-shift (n &optional shift)
8891 "Clone the task (subtree) at point N times.
8892 The clones will be inserted as siblings.
8894 In interactive use, the user will be prompted for the number of
8895 clones to be produced. If the entry has a timestamp, the user
8896 will also be prompted for a time shift, which may be a repeater
8897 as used in time stamps, for example `+3d'. To disable this,
8898 you can call the function with a universal prefix argument.
8900 When a valid repeater is given and the entry contains any time
8901 stamps, the clones will become a sequence in time, with time
8902 stamps in the subtree shifted for each clone produced. If SHIFT
8903 is nil or the empty string, time stamps will be left alone. The
8904 ID property of the original subtree is removed.
8906 If the original subtree did contain time stamps with a repeater,
8907 the following will happen:
8908 - the repeater will be removed in each clone
8909 - an additional clone will be produced, with the current, unshifted
8910 date(s) in the entry.
8911 - the original entry will be placed *after* all the clones, with
8912 repeater intact.
8913 - the start days in the repeater in the original entry will be shifted
8914 to past the last clone.
8915 In this way you can spell out a number of instances of a repeating task,
8916 and still retain the repeater to cover future instances of the task.
8918 As described above, N+1 clones are produced when the original
8919 subtree has a repeater. Setting N to 0, then, can be used to
8920 remove the repeater from a subtree and create a shifted clone
8921 with the original repeater."
8922 (interactive "nNumber of clones to produce: ")
8923 (let ((shift
8924 (or shift
8925 (if (and (not (equal current-prefix-arg '(4)))
8926 (save-excursion
8927 (re-search-forward org-ts-regexp-both
8928 (save-excursion
8929 (org-end-of-subtree t)
8930 (point)) t)))
8931 (read-from-minibuffer
8932 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8933 ""))) ;; No time shift
8934 (n-no-remove -1)
8935 (drawer-re org-drawer-regexp)
8936 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8937 beg end template task idprop
8938 shift-n shift-what doshift nmin nmax)
8939 (unless (wholenump n)
8940 (user-error "Invalid number of replications %s" n))
8941 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8942 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8943 shift)))
8944 (user-error "Invalid shift specification %s" shift))
8945 (when doshift
8946 (setq shift-n (string-to-number (match-string 1 shift))
8947 shift-what (cdr (assoc (match-string 2 shift)
8948 '(("d" . day) ("w" . week)
8949 ("m" . month) ("y" . year))))))
8950 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8951 (setq nmin 1 nmax n)
8952 (org-back-to-heading t)
8953 (setq beg (point))
8954 (setq idprop (org-entry-get nil "ID"))
8955 (org-end-of-subtree t t)
8956 (or (bolp) (insert "\n"))
8957 (setq end (point))
8958 (setq template (buffer-substring beg end))
8959 (when (and doshift
8960 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8961 (delete-region beg end)
8962 (setq end beg)
8963 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8964 (goto-char end)
8965 (cl-loop for n from nmin to nmax do
8966 ;; prepare clone
8967 (with-temp-buffer
8968 (insert template)
8969 (org-mode)
8970 (goto-char (point-min))
8971 (org-show-subtree)
8972 (and idprop (if org-clone-delete-id
8973 (org-entry-delete nil "ID")
8974 (org-id-get-create t)))
8975 (unless (= n 0)
8976 (while (re-search-forward org-clock-re nil t)
8977 (kill-whole-line))
8978 (goto-char (point-min))
8979 (while (re-search-forward drawer-re nil t)
8980 (org-remove-empty-drawer-at (point))))
8981 (goto-char (point-min))
8982 (when doshift
8983 (while (re-search-forward org-ts-regexp-both nil t)
8984 (org-timestamp-change (* n shift-n) shift-what))
8985 (unless (= n n-no-remove)
8986 (goto-char (point-min))
8987 (while (re-search-forward org-ts-regexp nil t)
8988 (save-excursion
8989 (goto-char (match-beginning 0))
8990 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8991 (delete-region (match-beginning 1) (match-end 1)))))))
8992 (setq task (buffer-string)))
8993 (insert task))
8994 (goto-char beg)))
8996 ;;; Outline Sorting
8998 (defun org-sort (with-case)
8999 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9000 Optional argument WITH-CASE means sort case-sensitively."
9001 (interactive "P")
9002 (cond
9003 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9004 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9006 (org-call-with-arg 'org-sort-entries with-case))))
9008 (defun org-sort-remove-invisible (s)
9009 "Remove invisible links from string S."
9010 (remove-text-properties 0 (length s) org-rm-props s)
9011 (while (string-match org-bracket-link-regexp s)
9012 (setq s (replace-match (if (match-end 2)
9013 (match-string 3 s)
9014 (match-string 1 s))
9015 t t s)))
9016 (let ((st (format " %s " s)))
9017 (while (string-match org-emph-re st)
9018 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9019 (setq s (substring st 1 -1)))
9022 (defvar org-priority-regexp) ; defined later in the file
9024 (defvar org-after-sorting-entries-or-items-hook nil
9025 "Hook that is run after a bunch of entries or items have been sorted.
9026 When children are sorted, the cursor is in the parent line when this
9027 hook gets called. When a region or a plain list is sorted, the cursor
9028 will be in the first entry of the sorted region/list.")
9030 (defun org-sort-entries
9031 (&optional with-case sorting-type getkey-func compare-func property)
9032 "Sort entries on a certain level of an outline tree.
9033 If there is an active region, the entries in the region are sorted.
9034 Else, if the cursor is before the first entry, sort the top-level items.
9035 Else, the children of the entry at point are sorted.
9037 Sorting can be alphabetically, numerically, by date/time as given by
9038 a time stamp, by a property, by priority order, or by a custom function.
9040 The command prompts for the sorting type unless it has been given to the
9041 function through the SORTING-TYPE argument, which needs to be a character,
9042 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9043 the precise meaning of each character:
9045 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9046 c By creation time, which is assumed to be the first inactive time stamp
9047 at the beginning of a line.
9048 d By deadline date/time.
9049 k By clocking time.
9050 n Numerically, by converting the beginning of the entry/item to a number.
9051 o By order of TODO keywords.
9052 p By priority according to the cookie.
9053 r By the value of a property.
9054 s By scheduled date/time.
9055 t By date/time, either the first active time stamp in the entry, or, if
9056 none exist, by the first inactive one.
9058 Capital letters will reverse the sort order.
9060 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9061 called with point at the beginning of the record. It must return either
9062 a string or a number that should serve as the sorting key for that record.
9064 Comparing entries ignores case by default. However, with an optional argument
9065 WITH-CASE, the sorting considers case as well.
9067 Sorting is done against the visible part of the headlines, it ignores hidden
9068 links.
9070 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9071 (interactive "P")
9072 (let ((case-func (if with-case 'identity 'downcase))
9073 (cmstr
9074 ;; The clock marker is lost when using `sort-subr', let's
9075 ;; store the clocking string.
9076 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9077 (save-excursion
9078 (goto-char org-clock-marker)
9079 (buffer-substring-no-properties (line-beginning-position)
9080 (point)))))
9081 start beg end stars re re2
9082 txt what tmp)
9083 ;; Find beginning and end of region to sort
9084 (cond
9085 ((org-region-active-p)
9086 ;; we will sort the region
9087 (setq end (region-end)
9088 what "region")
9089 (goto-char (region-beginning))
9090 (unless (org-at-heading-p) (outline-next-heading))
9091 (setq start (point)))
9092 ((or (org-at-heading-p)
9093 (ignore-errors (progn (org-back-to-heading) t)))
9094 ;; we will sort the children of the current headline
9095 (org-back-to-heading)
9096 (setq start (point)
9097 end (progn (org-end-of-subtree t t)
9098 (or (bolp) (insert "\n"))
9099 (when (>= (org-back-over-empty-lines) 1)
9100 (forward-line 1))
9101 (point))
9102 what "children")
9103 (goto-char start)
9104 (outline-show-subtree)
9105 (outline-next-heading))
9107 ;; we will sort the top-level entries in this file
9108 (goto-char (point-min))
9109 (or (org-at-heading-p) (outline-next-heading))
9110 (setq start (point))
9111 (goto-char (point-max))
9112 (beginning-of-line 1)
9113 (when (looking-at ".*?\\S-")
9114 ;; File ends in a non-white line
9115 (end-of-line 1)
9116 (insert "\n"))
9117 (setq end (point-max))
9118 (setq what "top-level")
9119 (goto-char start)
9120 (outline-show-all)))
9122 (setq beg (point))
9123 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9125 (looking-at "\\(\\*+\\)")
9126 (setq stars (match-string 1)
9127 re (concat "^" (regexp-quote stars) " +")
9128 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9129 txt (buffer-substring beg end))
9130 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9131 (when (and (not (equal stars "*")) (string-match re2 txt))
9132 (user-error "Region to sort contains a level above the first entry"))
9134 (unless sorting-type
9135 (message
9136 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9137 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9138 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9139 what)
9140 (setq sorting-type (read-char-exclusive))
9142 (unless getkey-func
9143 (and (= (downcase sorting-type) ?f)
9144 (setq getkey-func
9145 (completing-read "Sort using function: "
9146 obarray 'fboundp t nil nil))
9147 (setq getkey-func (intern getkey-func))))
9149 (and (= (downcase sorting-type) ?r)
9150 (not property)
9151 (setq property
9152 (completing-read "Property: "
9153 (mapcar #'list (org-buffer-property-keys t))
9154 nil t))))
9156 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9157 (message "Sorting entries...")
9159 (save-restriction
9160 (narrow-to-region start end)
9161 (let ((dcst (downcase sorting-type))
9162 (case-fold-search nil)
9163 (now (current-time)))
9164 (sort-subr
9165 (/= dcst sorting-type)
9166 ;; This function moves to the beginning character of the "record" to
9167 ;; be sorted.
9168 (lambda nil
9169 (if (re-search-forward re nil t)
9170 (goto-char (match-beginning 0))
9171 (goto-char (point-max))))
9172 ;; This function moves to the last character of the "record" being
9173 ;; sorted.
9174 (lambda nil
9175 (save-match-data
9176 (condition-case nil
9177 (outline-forward-same-level 1)
9178 (error
9179 (goto-char (point-max))))))
9180 ;; This function returns the value that gets sorted against.
9181 (lambda nil
9182 (cond
9183 ((= dcst ?n)
9184 (if (looking-at org-complex-heading-regexp)
9185 (string-to-number (org-sort-remove-invisible (match-string 4)))
9186 nil))
9187 ((= dcst ?a)
9188 (if (looking-at org-complex-heading-regexp)
9189 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9190 nil))
9191 ((= dcst ?k)
9192 (or (get-text-property (point) :org-clock-minutes) 0))
9193 ((= dcst ?t)
9194 (let ((end (save-excursion (outline-next-heading) (point))))
9195 (if (or (re-search-forward org-ts-regexp end t)
9196 (re-search-forward org-ts-regexp-both end t))
9197 (org-time-string-to-seconds (match-string 0))
9198 (float-time now))))
9199 ((= dcst ?c)
9200 (let ((end (save-excursion (outline-next-heading) (point))))
9201 (if (re-search-forward
9202 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9203 end t)
9204 (org-time-string-to-seconds (match-string 0))
9205 (float-time now))))
9206 ((= dcst ?s)
9207 (let ((end (save-excursion (outline-next-heading) (point))))
9208 (if (re-search-forward org-scheduled-time-regexp end t)
9209 (org-time-string-to-seconds (match-string 1))
9210 (float-time now))))
9211 ((= dcst ?d)
9212 (let ((end (save-excursion (outline-next-heading) (point))))
9213 (if (re-search-forward org-deadline-time-regexp end t)
9214 (org-time-string-to-seconds (match-string 1))
9215 (float-time now))))
9216 ((= dcst ?p)
9217 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9218 (string-to-char (match-string 2))
9219 org-default-priority))
9220 ((= dcst ?r)
9221 (or (org-entry-get nil property) ""))
9222 ((= dcst ?o)
9223 (when (looking-at org-complex-heading-regexp)
9224 (let* ((m (match-string 2))
9225 (s (if (member m org-done-keywords) '- '+)))
9226 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9227 ((= dcst ?f)
9228 (if getkey-func
9229 (progn
9230 (setq tmp (funcall getkey-func))
9231 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9232 tmp)
9233 (error "Invalid key function `%s'" getkey-func)))
9234 (t (error "Invalid sorting type `%c'" sorting-type))))
9236 (cond
9237 ((= dcst ?a) 'string<)
9238 ((= dcst ?f) compare-func)
9239 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9240 (run-hooks 'org-after-sorting-entries-or-items-hook)
9241 ;; Reset the clock marker if needed
9242 (when cmstr
9243 (save-excursion
9244 (goto-char start)
9245 (search-forward cmstr nil t)
9246 (move-marker org-clock-marker (point))))
9247 (message "Sorting entries...done")))
9249 ;;; The orgstruct minor mode
9251 ;; Define a minor mode which can be used in other modes in order to
9252 ;; integrate the Org mode structure editing commands.
9254 ;; This is really a hack, because the Org mode structure commands use
9255 ;; keys which normally belong to the major mode. Here is how it
9256 ;; works: The minor mode defines all the keys necessary to operate the
9257 ;; structure commands, but wraps the commands into a function which
9258 ;; tests if the cursor is currently at a headline or a plain list
9259 ;; item. If that is the case, the structure command is used,
9260 ;; temporarily setting many Org mode variables like regular
9261 ;; expressions for filling etc. However, when any of those keys is
9262 ;; used at a different location, function uses `key-binding' to look
9263 ;; up if the key has an associated command in another currently active
9264 ;; keymap (minor modes, major mode, global), and executes that
9265 ;; command. There might be problems if any of the keys is otherwise
9266 ;; used as a prefix key.
9268 (defcustom orgstruct-heading-prefix-regexp ""
9269 "Regexp that matches the custom prefix of Org headlines in
9270 orgstruct(++)-mode."
9271 :group 'org
9272 :version "24.4"
9273 :package-version '(Org . "8.3")
9274 :type 'regexp)
9275 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9277 (defcustom orgstruct-setup-hook nil
9278 "Hook run after orgstruct-mode-map is filled."
9279 :group 'org
9280 :version "24.4"
9281 :package-version '(Org . "8.0")
9282 :type 'hook)
9284 (defvar orgstruct-initialized nil)
9286 (defvar org-local-vars nil
9287 "List of local variables, for use by `orgstruct-mode'.")
9289 ;;;###autoload
9290 (define-minor-mode orgstruct-mode
9291 "Toggle the minor mode `orgstruct-mode'.
9292 This mode is for using Org mode structure commands in other
9293 modes. The following keys behave as if Org mode were active, if
9294 the cursor is on a headline, or on a plain list item (both as
9295 defined by Org-mode)."
9296 nil " OrgStruct" (make-sparse-keymap)
9297 (funcall (if orgstruct-mode
9298 'add-to-invisibility-spec
9299 'remove-from-invisibility-spec)
9300 '(outline . t))
9301 (when orgstruct-mode
9302 (org-load-modules-maybe)
9303 (unless orgstruct-initialized
9304 (orgstruct-setup)
9305 (setq orgstruct-initialized t))))
9307 ;;;###autoload
9308 (defun turn-on-orgstruct ()
9309 "Unconditionally turn on `orgstruct-mode'."
9310 (orgstruct-mode 1))
9312 (defvar-local orgstruct-is-++ nil
9313 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9314 (defvar-local org-fb-vars nil)
9315 (defun orgstruct++-mode (&optional arg)
9316 "Toggle `orgstruct-mode', the enhanced version of it.
9317 In addition to setting orgstruct-mode, this also exports all
9318 indentation and autofilling variables from Org mode into the
9319 buffer. It will also recognize item context in multiline items."
9320 (interactive "P")
9321 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9322 (if (< arg 1)
9323 (progn (orgstruct-mode -1)
9324 (dolist (v org-fb-vars)
9325 (set (make-local-variable (car v))
9326 (if (eq (car-safe (cadr v)) 'quote)
9327 (cl-cadadr v)
9328 (nth 1 v)))))
9329 (orgstruct-mode 1)
9330 (setq org-fb-vars nil)
9331 (unless org-local-vars
9332 (setq org-local-vars (org-get-local-variables)))
9333 (let (var val)
9334 (dolist (x org-local-vars)
9335 (when (string-match
9336 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9337 \\|fill-prefix\\|indent-\\)"
9338 (symbol-name (car x)))
9339 (setq var (car x) val (nth 1 x))
9340 (push (list var `(quote ,(eval var))) org-fb-vars)
9341 (set (make-local-variable var)
9342 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9343 (setq-local orgstruct-is-++ t))))
9345 ;;;###autoload
9346 (defun turn-on-orgstruct++ ()
9347 "Unconditionally turn on `orgstruct++-mode'."
9348 (orgstruct++-mode 1))
9350 (defun orgstruct-error ()
9351 "Error when there is no default binding for a structure key."
9352 (interactive)
9353 (funcall (if (fboundp 'user-error)
9354 'user-error
9355 'error)
9356 "This key has no function outside structure elements"))
9358 (defun orgstruct-setup ()
9359 "Setup orgstruct keymap."
9360 (dolist (cell '((org-demote . t)
9361 (org-metaleft . t)
9362 (org-metaright . t)
9363 (org-promote . t)
9364 (org-shiftmetaleft . t)
9365 (org-shiftmetaright . t)
9366 org-backward-element
9367 org-backward-heading-same-level
9368 org-ctrl-c-ret
9369 org-ctrl-c-minus
9370 org-ctrl-c-star
9371 org-cycle
9372 org-force-cycle-archived
9373 org-forward-heading-same-level
9374 org-insert-heading
9375 org-insert-heading-respect-content
9376 org-kill-note-or-show-branches
9377 org-mark-subtree
9378 org-meta-return
9379 org-metadown
9380 org-metaup
9381 org-narrow-to-subtree
9382 org-promote-subtree
9383 org-reveal
9384 org-shiftdown
9385 org-shiftleft
9386 org-shiftmetadown
9387 org-shiftmetaup
9388 org-shiftright
9389 org-shifttab
9390 org-shifttab
9391 org-shiftup
9392 org-show-children
9393 org-show-subtree
9394 org-sort
9395 org-up-element
9396 outline-demote
9397 outline-next-visible-heading
9398 outline-previous-visible-heading
9399 outline-promote
9400 outline-up-heading))
9401 (let ((f (or (car-safe cell) cell))
9402 (disable-when-heading-prefix (cdr-safe cell)))
9403 (when (fboundp f)
9404 (let ((new-bindings))
9405 (dolist (binding (nconc (where-is-internal f org-mode-map)
9406 (where-is-internal f outline-mode-map)))
9407 (push binding new-bindings)
9408 ;; TODO use local-function-key-map
9409 (dolist (rep '(("<tab>" . "TAB")
9410 ("<return>" . "RET")
9411 ("<escape>" . "ESC")
9412 ("<delete>" . "DEL")))
9413 (setq binding (read-kbd-macro
9414 (let ((case-fold-search))
9415 (replace-regexp-in-string
9416 (regexp-quote (cdr rep))
9417 (car rep)
9418 (key-description binding)))))
9419 (cl-pushnew binding new-bindings :test 'equal)))
9420 (dolist (binding new-bindings)
9421 (let ((key (lookup-key orgstruct-mode-map binding)))
9422 (when (or (not key) (numberp key))
9423 (ignore-errors
9424 (org-defkey orgstruct-mode-map
9425 binding
9426 (orgstruct-make-binding
9427 f binding disable-when-heading-prefix))))))))))
9428 (run-hooks 'orgstruct-setup-hook))
9430 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9431 "Create a function for binding in the structure minor mode.
9432 FUN is the command to call inside a table. KEY is the key that
9433 should be checked in for a command to execute outside of tables.
9434 Non-nil `disable-when-heading-prefix' means to disable the command
9435 if `orgstruct-heading-prefix-regexp' is not empty."
9436 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9437 (let ((nname name)
9438 (i 0))
9439 (while (fboundp (intern nname))
9440 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9441 (setq name (intern nname)))
9442 (eval
9443 (let ((bindings '((org-heading-regexp
9444 (concat "^"
9445 orgstruct-heading-prefix-regexp
9446 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9447 (org-outline-regexp
9448 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9449 (org-outline-regexp-bol
9450 (concat "^" org-outline-regexp))
9451 (outline-regexp org-outline-regexp)
9452 (outline-heading-end-regexp "\n")
9453 (outline-level 'org-outline-level)
9454 (outline-heading-alist))))
9455 `(defun ,name (arg)
9456 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9457 "Outside of structure, run the binding of `"
9458 (key-description key) "'."
9459 (when disable-when-heading-prefix
9460 (concat
9461 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9462 "back to the default binding due to limitations of Org's implementation of\n"
9463 "`" (symbol-name fun) "'.")))
9464 (interactive "p")
9465 (let* ((disable
9466 ,(and disable-when-heading-prefix
9467 '(not (string= orgstruct-heading-prefix-regexp ""))))
9468 (fallback
9469 (or disable
9470 (not
9471 (let* ,bindings
9472 (org-context-p 'headline 'item
9473 ,(when (memq fun
9474 '(org-insert-heading
9475 org-insert-heading-respect-content
9476 org-meta-return))
9477 '(when orgstruct-is-++
9478 'item-body))))))))
9479 (if fallback
9480 (let* ((orgstruct-mode)
9481 (binding
9482 (let ((key ,key))
9483 (catch 'exit
9484 (dolist
9485 (rep
9486 '(nil
9487 ("<\\([^>]*\\)tab>" . "\\1TAB")
9488 ("<\\([^>]*\\)return>" . "\\1RET")
9489 ("<\\([^>]*\\)escape>" . "\\1ESC")
9490 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9491 nil)
9492 (when rep
9493 (setq key (read-kbd-macro
9494 (let ((case-fold-search))
9495 (replace-regexp-in-string
9496 (car rep)
9497 (cdr rep)
9498 (key-description key))))))
9499 (when (key-binding key)
9500 (throw 'exit (key-binding key))))))))
9501 (if (keymapp binding)
9502 (org-set-transient-map binding)
9503 (let ((func (or binding
9504 (unless disable
9505 'orgstruct-error))))
9506 (when func
9507 (call-interactively func)))))
9508 (org-run-like-in-org-mode
9509 (lambda ()
9510 (interactive)
9511 (let* ,bindings
9512 (call-interactively ',fun)))))))))
9513 name))
9515 (defun org-contextualize-keys (alist contexts)
9516 "Return valid elements in ALIST depending on CONTEXTS.
9518 `org-agenda-custom-commands' or `org-capture-templates' are the
9519 values used for ALIST, and `org-agenda-custom-commands-contexts'
9520 or `org-capture-templates-contexts' are the associated contexts
9521 definitions."
9522 (let ((contexts
9523 ;; normalize contexts
9524 (mapcar
9525 (lambda(c) (cond ((listp (cadr c))
9526 (list (car c) (car c) (nth 1 c)))
9527 ((string= "" (cadr c))
9528 (list (car c) (car c) (nth 2 c)))
9529 (t c)))
9530 contexts))
9531 (a alist) r s)
9532 ;; loop over all commands or templates
9533 (dolist (c a)
9534 (let (vrules repl)
9535 (cond
9536 ((not (assoc (car c) contexts))
9537 (push c r))
9538 ((and (assoc (car c) contexts)
9539 (setq vrules (org-contextualize-validate-key
9540 (car c) contexts)))
9541 (mapc (lambda (vr)
9542 (unless (equal (car vr) (cadr vr))
9543 (setq repl vr)))
9544 vrules)
9545 (if (not repl) (push c r)
9546 (push (cadr repl) s)
9547 (push
9548 (cons (car c)
9549 (cdr (or (assoc (cadr repl) alist)
9550 (error "Undefined key `%s' as contextual replacement for `%s'"
9551 (cadr repl) (car c)))))
9552 r))))))
9553 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9554 (delq
9556 (delete-dups
9557 (mapcar (lambda (x)
9558 (let ((tpl (car x)))
9559 (unless (delq
9561 (mapcar (lambda (y)
9562 (equal y tpl))
9564 x)))
9565 (reverse r))))))
9567 (defun org-contextualize-validate-key (key contexts)
9568 "Check CONTEXTS for agenda or capture KEY."
9569 (let (res)
9570 (dolist (r contexts)
9571 (dolist (rr (car (last r)))
9572 (when
9573 (and (equal key (car r))
9574 (if (functionp rr) (funcall rr)
9575 (or (and (eq (car rr) 'in-file)
9576 (buffer-file-name)
9577 (string-match (cdr rr) (buffer-file-name)))
9578 (and (eq (car rr) 'in-mode)
9579 (string-match (cdr rr) (symbol-name major-mode)))
9580 (and (eq (car rr) 'in-buffer)
9581 (string-match (cdr rr) (buffer-name)))
9582 (when (and (eq (car rr) 'not-in-file)
9583 (buffer-file-name))
9584 (not (string-match (cdr rr) (buffer-file-name))))
9585 (when (eq (car rr) 'not-in-mode)
9586 (not (string-match (cdr rr) (symbol-name major-mode))))
9587 (when (eq (car rr) 'not-in-buffer)
9588 (not (string-match (cdr rr) (buffer-name)))))))
9589 (push r res))))
9590 (delete-dups (delq nil res))))
9592 (defun org-context-p (&rest contexts)
9593 "Check if local context is any of CONTEXTS.
9594 Possible values in the list of contexts are `table', `headline', and `item'."
9595 (let ((pos (point)))
9596 (goto-char (point-at-bol))
9597 (prog1 (or (and (memq 'table contexts)
9598 (looking-at "[ \t]*|"))
9599 (and (memq 'headline contexts)
9600 (looking-at org-outline-regexp))
9601 (and (memq 'item contexts)
9602 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9603 (and (memq 'item-body contexts)
9604 (org-in-item-p)))
9605 (goto-char pos))))
9607 (defconst org-unique-local-variables
9608 '(org-element--cache
9609 org-element--cache-objects
9610 org-element--cache-sync-keys
9611 org-element--cache-sync-requests
9612 org-element--cache-sync-timer)
9613 "List of local variables that cannot be transferred to another buffer.")
9615 (defun org-get-local-variables ()
9616 "Return a list of all local variables in an Org mode buffer."
9617 (delq nil
9618 (mapcar
9619 (lambda (x)
9620 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9621 (name (car binding)))
9622 (and (not (get name 'org-state))
9623 (not (memq name org-unique-local-variables))
9624 (string-match-p
9625 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9626 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9627 (symbol-name name))
9628 binding)))
9629 (with-temp-buffer
9630 (org-mode)
9631 (buffer-local-variables)))))
9633 (defun org-clone-local-variables (from-buffer &optional regexp)
9634 "Clone local variables from FROM-BUFFER.
9635 Optional argument REGEXP selects variables to clone."
9636 (dolist (pair (buffer-local-variables from-buffer))
9637 (let ((name (car pair)))
9638 (when (and (symbolp name)
9639 (not (memq name org-unique-local-variables))
9640 (or (null regexp) (string-match regexp (symbol-name name))))
9641 (set (make-local-variable name) (cdr pair))))))
9643 ;;;###autoload
9644 (defun org-run-like-in-org-mode (cmd)
9645 "Run a command, pretending that the current buffer is in Org-mode.
9646 This will temporarily bind local variables that are typically bound in
9647 Org mode to the values they have in Org-mode, and then interactively
9648 call CMD."
9649 (org-load-modules-maybe)
9650 (unless org-local-vars
9651 (setq org-local-vars (org-get-local-variables)))
9652 (let (binds)
9653 (dolist (var org-local-vars)
9654 (when (or (not (boundp (car var)))
9655 (eq (symbol-value (car var))
9656 (default-value (car var))))
9657 (push (list (car var) `(quote ,(cadr var))) binds)))
9658 (eval `(let ,binds
9659 (call-interactively (quote ,cmd))))))
9661 (defun org-get-category (&optional pos force-refresh)
9662 "Get the category applying to position POS."
9663 (save-match-data
9664 (when force-refresh (org-refresh-category-properties))
9665 (let ((pos (or pos (point))))
9666 (or (get-text-property pos 'org-category)
9667 (progn (org-refresh-category-properties)
9668 (get-text-property pos 'org-category))))))
9670 ;;; Refresh properties
9672 (defun org-refresh-properties (dprop tprop)
9673 "Refresh buffer text properties.
9674 DPROP is the drawer property and TPROP is either the
9675 corresponding text property to set, or an alist with each element
9676 being a text property (as a symbol) and a function to apply to
9677 the value of the drawer property."
9678 (let ((case-fold-search t)
9679 (inhibit-read-only t))
9680 (org-with-silent-modifications
9681 (org-with-wide-buffer
9682 (goto-char (point-min))
9683 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9684 (org-refresh-property tprop (match-string-no-properties 1)))))))
9686 (defun org-refresh-property (tprop p)
9687 "Refresh the buffer text property TPROP from the drawer property P.
9688 The refresh happens only for the current tree (not subtree)."
9689 (unless (org-before-first-heading-p)
9690 (save-excursion
9691 (org-back-to-heading t)
9692 (if (symbolp tprop)
9693 ;; TPROP is a text property symbol
9694 (put-text-property
9695 (point) (or (outline-next-heading) (point-max)) tprop p)
9696 ;; TPROP is an alist with (properties . function) elements
9697 (dolist (al tprop)
9698 (save-excursion
9699 (put-text-property
9700 (line-beginning-position) (or (outline-next-heading) (point-max))
9701 (car al)
9702 (funcall (cdr al) p))))))))
9704 (defun org-refresh-category-properties ()
9705 "Refresh category text properties in the buffer."
9706 (let ((case-fold-search t)
9707 (inhibit-read-only t)
9708 (default-category
9709 (cond ((null org-category)
9710 (if buffer-file-name
9711 (file-name-sans-extension
9712 (file-name-nondirectory buffer-file-name))
9713 "???"))
9714 ((symbolp org-category) (symbol-name org-category))
9715 (t org-category))))
9716 (org-with-silent-modifications
9717 (org-with-wide-buffer
9718 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9719 ;; This is the default category for the buffer. If none is
9720 ;; found, fall-back to `org-category' or buffer file name.
9721 (put-text-property
9722 (point-min) (point-max)
9723 'org-category
9724 (catch 'buffer-category
9725 (goto-char (point-max))
9726 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9727 (let ((element (org-element-at-point)))
9728 (when (eq (org-element-type element) 'keyword)
9729 (throw 'buffer-category
9730 (org-element-property :value element)))))
9731 default-category))
9732 ;; Set sub-tree specific categories.
9733 (goto-char (point-min))
9734 (let ((regexp (org-re-property "CATEGORY")))
9735 (while (re-search-forward regexp nil t)
9736 (let ((value (match-string-no-properties 3)))
9737 (when (org-at-property-p)
9738 (put-text-property
9739 (save-excursion (org-back-to-heading t) (point))
9740 (save-excursion (org-end-of-subtree t t) (point))
9741 'org-category
9742 value)))))))))
9744 (defun org-refresh-stats-properties ()
9745 "Refresh stats text properties in the buffer."
9746 (let (stats)
9747 (org-with-silent-modifications
9748 (org-with-wide-buffer
9749 (goto-char (point-min))
9750 (while (re-search-forward
9751 (concat org-outline-regexp-bol ".*"
9752 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9753 nil t)
9754 (setq stats (cond ((equal (match-string 3) "0") 0)
9755 ((match-string 2)
9756 (/ (* (string-to-number (match-string 2)) 100)
9757 (string-to-number (match-string 3))))
9758 (t (string-to-number (match-string 1)))))
9759 (org-back-to-heading t)
9760 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9761 'org-stats stats))))))
9763 (defun org-refresh-effort-properties ()
9764 "Refresh effort properties"
9765 (org-refresh-properties
9766 org-effort-property
9767 '((effort . identity)
9768 (effort-minutes . org-duration-string-to-minutes))))
9770 ;;;; Link Stuff
9772 ;;; Link abbreviations
9774 (defun org-link-expand-abbrev (link)
9775 "Apply replacements as defined in `org-link-abbrev-alist'."
9776 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9777 (let* ((key (match-string 1 link))
9778 (as (or (assoc key org-link-abbrev-alist-local)
9779 (assoc key org-link-abbrev-alist)))
9780 (tag (and (match-end 2) (match-string 3 link)))
9781 rpl)
9782 (if (not as)
9783 link
9784 (setq rpl (cdr as))
9785 (cond
9786 ((symbolp rpl) (funcall rpl tag))
9787 ((string-match "%(\\([^)]+\\))" rpl)
9788 (replace-match
9789 (save-match-data
9790 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9791 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9792 ((string-match "%h" rpl)
9793 (replace-match (url-hexify-string (or tag "")) t t rpl))
9794 (t (concat rpl tag)))))
9795 link))
9797 ;;; Storing and inserting links
9799 (defvar org-insert-link-history nil
9800 "Minibuffer history for links inserted with `org-insert-link'.")
9802 (defvar org-stored-links nil
9803 "Contains the links stored with `org-store-link'.")
9805 (defvar org-store-link-plist nil
9806 "Plist with info about the most recently link created with `org-store-link'.")
9808 (defun org-store-link-functions ()
9809 "Return a list of functions that are called to create and store a link.
9810 The functions defined in the :store property of
9811 `org-link-parameters'.
9813 Each function will be called in turn until one returns a non-nil
9814 value. Each function should check if it is responsible for
9815 creating this link (for example by looking at the major mode).
9816 If not, it must exit and return nil. If yes, it should return
9817 a non-nil value after calling `org-store-link-props' with a list
9818 of properties and values. Special properties are:
9820 :type The link prefix, like \"http\". This must be given.
9821 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9822 This is obligatory as well.
9823 :description Optional default description for the second pair
9824 of brackets in an Org mode link. The user can still change
9825 this when inserting this link into an Org mode buffer.
9827 In addition to these, any additional properties can be specified
9828 and then used in capture templates."
9829 (cl-loop for link in org-link-parameters
9830 with store-func
9831 do (setq store-func (org-link-get-parameter (car link) :store))
9832 if store-func
9833 collect store-func))
9835 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9836 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9838 ;;;###autoload
9839 (defun org-store-link (arg)
9840 "\\<org-mode-map>Store an org-link to the current location.
9841 This link is added to `org-stored-links' and can later be inserted
9842 into an Org buffer with \\[org-insert-link].
9844 For some link types, a prefix ARG is interpreted.
9845 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9846 For file links, ARG negates `org-context-in-file-links'.
9848 A double prefix ARG force skipping storing functions that are not
9849 part of Org's core.
9851 A triple prefix ARG force storing a link for each line in the
9852 active region."
9853 (interactive "P")
9854 (org-load-modules-maybe)
9855 (if (and (equal arg '(64)) (org-region-active-p))
9856 (save-excursion
9857 (let ((end (region-end)))
9858 (goto-char (region-beginning))
9859 (set-mark (point))
9860 (while (< (point-at-eol) end)
9861 (move-end-of-line 1) (activate-mark)
9862 (let (current-prefix-arg)
9863 (call-interactively 'org-store-link))
9864 (move-beginning-of-line 2)
9865 (set-mark (point)))))
9866 (setq org-store-link-plist nil)
9867 (let (link cpltxt desc description search
9868 txt custom-id agenda-link sfuns sfunsn)
9869 (cond
9871 ;; Store a link using an external link type
9872 ((and (not (equal arg '(16)))
9873 (setq sfuns
9874 (delq
9875 nil (mapcar (lambda (f)
9876 (let (fs) (if (funcall f) (push f fs))))
9877 (org-store-link-functions)))
9878 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9879 (or (and (cdr sfuns)
9880 (funcall (intern
9881 (completing-read
9882 "Which function for creating the link? "
9883 sfunsn nil t (car sfunsn)))))
9884 (funcall (caar sfuns)))
9885 (setq link (plist-get org-store-link-plist :link)
9886 desc (or (plist-get org-store-link-plist
9887 :description)
9888 link))))
9890 ;; Store a link from a source code buffer.
9891 ((org-src-edit-buffer-p)
9892 (let ((coderef-format (org-src-coderef-format)))
9893 (cond ((save-excursion
9894 (beginning-of-line)
9895 (looking-at (org-src-coderef-regexp coderef-format)))
9896 (setq link (format "(%s)" (match-string-no-properties 3))))
9897 ((called-interactively-p 'any)
9898 (let ((label (read-string "Code line label: ")))
9899 (end-of-line)
9900 (setq link (format coderef-format label))
9901 (let ((gc (- 79 (length link))))
9902 (if (< (current-column) gc)
9903 (org-move-to-column gc t)
9904 (insert " ")))
9905 (insert link)
9906 (setq link (concat "(" label ")"))
9907 (setq desc nil)))
9908 (t (setq link nil)))))
9910 ;; We are in the agenda, link to referenced location
9911 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9912 (let ((m (or (get-text-property (point) 'org-hd-marker)
9913 (get-text-property (point) 'org-marker))))
9914 (when m
9915 (org-with-point-at m
9916 (setq agenda-link
9917 (if (called-interactively-p 'any)
9918 (call-interactively 'org-store-link)
9919 (org-store-link nil)))))))
9921 ((eq major-mode 'calendar-mode)
9922 (let ((cd (calendar-cursor-to-date)))
9923 (setq link
9924 (format-time-string
9925 (car org-time-stamp-formats)
9926 (apply 'encode-time
9927 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9928 nil nil nil))))
9929 (org-store-link-props :type "calendar" :date cd)))
9931 ((eq major-mode 'help-mode)
9932 (setq link (concat "help:" (save-excursion
9933 (goto-char (point-min))
9934 (looking-at "^[^ ]+")
9935 (match-string 0))))
9936 (org-store-link-props :type "help"))
9938 ((eq major-mode 'w3-mode)
9939 (setq cpltxt (if (and (buffer-name)
9940 (not (string-match "Untitled" (buffer-name))))
9941 (buffer-name)
9942 (url-view-url t))
9943 link (url-view-url t))
9944 (org-store-link-props :type "w3" :url (url-view-url t)))
9946 ((eq major-mode 'image-mode)
9947 (setq cpltxt (concat "file:"
9948 (abbreviate-file-name buffer-file-name))
9949 link cpltxt)
9950 (org-store-link-props :type "image" :file buffer-file-name))
9952 ;; In dired, store a link to the file of the current line
9953 ((derived-mode-p 'dired-mode)
9954 (let ((file (dired-get-filename nil t)))
9955 (setq file (if file
9956 (abbreviate-file-name
9957 (expand-file-name (dired-get-filename nil t)))
9958 ;; otherwise, no file so use current directory.
9959 default-directory))
9960 (setq cpltxt (concat "file:" file)
9961 link cpltxt)))
9963 ((setq search (run-hook-with-args-until-success
9964 'org-create-file-search-functions))
9965 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9966 "::" search))
9967 (setq cpltxt (or description link)))
9969 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9970 (org-with-limited-levels
9971 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9972 (cond
9973 ;; Store a link using the target at point
9974 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9975 (setq cpltxt
9976 (concat "file:"
9977 (abbreviate-file-name
9978 (buffer-file-name (buffer-base-buffer)))
9979 "::" (match-string 1))
9980 link cpltxt))
9981 ((and (featurep 'org-id)
9982 (or (eq org-id-link-to-org-use-id t)
9983 (and (called-interactively-p 'any)
9984 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9985 (and (eq org-id-link-to-org-use-id
9986 'create-if-interactive-and-no-custom-id)
9987 (not custom-id))))
9988 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9989 ;; Store a link using the ID at point
9990 (setq link (condition-case nil
9991 (prog1 (org-id-store-link)
9992 (setq desc (or (plist-get org-store-link-plist
9993 :description)
9994 "")))
9995 (error
9996 ;; Probably before first headline, link only to file
9997 (concat "file:"
9998 (abbreviate-file-name
9999 (buffer-file-name (buffer-base-buffer))))))))
10001 ;; Just link to current headline
10002 (setq cpltxt (concat "file:"
10003 (abbreviate-file-name
10004 (buffer-file-name (buffer-base-buffer)))))
10005 ;; Add a context search string
10006 (when (org-xor org-context-in-file-links arg)
10007 (let* ((element (org-element-at-point))
10008 (name (org-element-property :name element)))
10009 (setq txt (cond
10010 ((org-at-heading-p) nil)
10011 (name)
10012 ((org-region-active-p)
10013 (buffer-substring (region-beginning) (region-end)))))
10014 (when (or (null txt) (string-match "\\S-" txt))
10015 (setq cpltxt
10016 (concat cpltxt "::"
10017 (condition-case nil
10018 (org-make-org-heading-search-string txt)
10019 (error "")))
10020 desc (or name
10021 (nth 4 (ignore-errors (org-heading-components)))
10022 "NONE")))))
10023 (when (string-match "::\\'" cpltxt)
10024 (setq cpltxt (substring cpltxt 0 -2)))
10025 (setq link cpltxt)))))
10027 ((buffer-file-name (buffer-base-buffer))
10028 ;; Just link to this file here.
10029 (setq cpltxt (concat "file:"
10030 (abbreviate-file-name
10031 (buffer-file-name (buffer-base-buffer)))))
10032 ;; Add a context string.
10033 (when (org-xor org-context-in-file-links arg)
10034 (setq txt (if (org-region-active-p)
10035 (buffer-substring (region-beginning) (region-end))
10036 (buffer-substring (point-at-bol) (point-at-eol))))
10037 ;; Only use search option if there is some text.
10038 (when (string-match "\\S-" txt)
10039 (setq cpltxt
10040 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10041 desc "NONE")))
10042 (setq link cpltxt))
10044 ((called-interactively-p 'interactive)
10045 (user-error "No method for storing a link from this buffer"))
10047 (t (setq link nil)))
10049 ;; We're done setting link and desc, clean up
10050 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10051 (setq link (or link cpltxt)
10052 desc (or desc cpltxt))
10053 (cond ((not desc))
10054 ((equal desc "NONE") (setq desc nil))
10055 (t (setq desc
10056 (replace-regexp-in-string
10057 org-bracket-link-analytic-regexp
10058 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10059 desc))))
10060 ;; Return the link
10061 (if (not (and (or (called-interactively-p 'any)
10062 executing-kbd-macro)
10063 link))
10064 (or agenda-link (and link (org-make-link-string link desc)))
10065 (push (list link desc) org-stored-links)
10066 (message "Stored: %s" (or desc link))
10067 (when custom-id
10068 (setq link (concat "file:" (abbreviate-file-name
10069 (buffer-file-name)) "::#" custom-id))
10070 (push (list link desc) org-stored-links))
10071 (car org-stored-links)))))
10073 (defun org-store-link-props (&rest plist)
10074 "Store link properties, extract names, addresses and dates."
10075 (let ((x (plist-get plist :from)))
10076 (when x
10077 (let ((adr (mail-extract-address-components x)))
10078 (setq plist (plist-put plist :fromname (car adr)))
10079 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10080 (let ((x (plist-get plist :to)))
10081 (when x
10082 (let ((adr (mail-extract-address-components x)))
10083 (setq plist (plist-put plist :toname (car adr)))
10084 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10085 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10086 (when x
10087 (setq plist (plist-put plist :date-timestamp
10088 (format-time-string
10089 (org-time-stamp-format t) x)))
10090 (setq plist (plist-put plist :date-timestamp-inactive
10091 (format-time-string
10092 (org-time-stamp-format t t) x)))))
10093 (let ((from (plist-get plist :from))
10094 (to (plist-get plist :to)))
10095 (when (and from to org-from-is-user-regexp)
10096 (setq plist
10097 (plist-put plist :fromto
10098 (if (string-match org-from-is-user-regexp from)
10099 (concat "to %t")
10100 (concat "from %f"))))))
10101 (setq org-store-link-plist plist))
10103 (defun org-add-link-props (&rest plist)
10104 "Add these properties to the link property list."
10105 (let (key value)
10106 (while plist
10107 (setq key (pop plist) value (pop plist))
10108 (setq org-store-link-plist
10109 (plist-put org-store-link-plist key value)))))
10111 (defun org-email-link-description (&optional fmt)
10112 "Return the description part of an email link.
10113 This takes information from `org-store-link-plist' and formats it
10114 according to FMT (default from `org-email-link-description-format')."
10115 (setq fmt (or fmt org-email-link-description-format))
10116 (let* ((p org-store-link-plist)
10117 (to (plist-get p :toaddress))
10118 (from (plist-get p :fromaddress))
10119 (table
10120 (list
10121 (cons "%c" (plist-get p :fromto))
10122 (cons "%F" (plist-get p :from))
10123 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10124 (cons "%T" (plist-get p :to))
10125 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10126 (cons "%s" (plist-get p :subject))
10127 (cons "%d" (plist-get p :date))
10128 (cons "%m" (plist-get p :message-id)))))
10129 (when (string-match "%c" fmt)
10130 ;; Check if the user wrote this message
10131 (if (and org-from-is-user-regexp from to
10132 (save-match-data (string-match org-from-is-user-regexp from)))
10133 (setq fmt (replace-match "to %t" t t fmt))
10134 (setq fmt (replace-match "from %f" t t fmt))))
10135 (org-replace-escapes fmt table)))
10137 (defun org-make-org-heading-search-string (&optional string)
10138 "Make search string for the current headline or STRING."
10139 (let ((s (or string
10140 (and (derived-mode-p 'org-mode)
10141 (save-excursion
10142 (org-back-to-heading t)
10143 (org-element-property :raw-value (org-element-at-point))))))
10144 (lines org-context-in-file-links))
10145 (or string (setq s (concat "*" s))) ; Add * for headlines
10146 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10147 (when (and string (integerp lines) (> lines 0))
10148 (let ((slines (org-split-string s "\n")))
10149 (when (< lines (length slines))
10150 (setq s (mapconcat
10151 'identity
10152 (reverse (nthcdr (- (length slines) lines)
10153 (reverse slines))) "\n")))))
10154 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10156 (defun org-make-link-string (link &optional description)
10157 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10158 (unless (org-string-nw-p link) (error "Empty link"))
10159 (let ((uri (cond ((string-match org-link-types-re link)
10160 (concat (match-string 1 link)
10161 (org-link-escape (substring link (match-end 1)))))
10162 ;; For readability, url-encode internal links only
10163 ;; when absolutely needed (i.e, when they contain
10164 ;; square brackets). File links however, are
10165 ;; encoded since, e.g., spaces are significant.
10166 ((or (file-name-absolute-p link)
10167 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10168 (org-link-escape link))
10169 (t link)))
10170 (description
10171 (and (org-string-nw-p description)
10172 ;; Remove brackets from description, as they are fatal.
10173 (replace-regexp-in-string
10174 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10175 (org-trim description)))))
10176 (format "[[%s]%s]"
10178 (if description (format "[%s]" description) ""))))
10180 (defconst org-link-escape-chars
10181 ;;%20 %5B %5D %25
10182 '(?\s ?\[ ?\] ?%)
10183 "List of characters that should be escaped in a link when stored to Org.
10184 This is the list that is used for internal purposes.")
10186 (defun org-link-escape (text &optional table merge)
10187 "Return percent escaped representation of TEXT.
10188 TEXT is a string with the text to escape.
10189 Optional argument TABLE is a list with characters that should be
10190 escaped. When nil, `org-link-escape-chars' is used.
10191 If optional argument MERGE is set, merge TABLE into
10192 `org-link-escape-chars'."
10193 (let ((characters-to-encode
10194 (cond ((null table) org-link-escape-chars)
10195 (merge (append org-link-escape-chars table))
10196 (t table))))
10197 (mapconcat
10198 (lambda (c)
10199 (if (or (memq c characters-to-encode)
10200 (and org-url-hexify-p (or (< c 32) (> c 126))))
10201 (mapconcat (lambda (e) (format "%%%.2X" e))
10202 (or (encode-coding-char c 'utf-8)
10203 (error "Unable to percent escape character: %c" c))
10205 (char-to-string c)))
10206 text "")))
10208 (defun org-link-unescape (str)
10209 "Unhex hexified Unicode parts in string STR.
10210 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10211 reciprocal of `org-link-escape', which see."
10212 (if (org-string-nw-p str)
10213 (replace-regexp-in-string
10214 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10215 str))
10217 (defun org-link-unescape-compound (hex)
10218 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10219 Note: this function also decodes single byte encodings like
10220 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10221 (save-match-data
10222 (let* ((bytes (cdr (split-string hex "%")))
10223 (ret "")
10224 (eat 0)
10225 (sum 0))
10226 (while bytes
10227 (let* ((val (string-to-number (pop bytes) 16))
10228 (shift-xor
10229 (if (= 0 eat)
10230 (cond
10231 ((>= val 252) (cons 6 252))
10232 ((>= val 248) (cons 5 248))
10233 ((>= val 240) (cons 4 240))
10234 ((>= val 224) (cons 3 224))
10235 ((>= val 192) (cons 2 192))
10236 (t (cons 0 0)))
10237 (cons 6 128))))
10238 (when (>= val 192) (setq eat (car shift-xor)))
10239 (setq val (logxor val (cdr shift-xor)))
10240 (setq sum (+ (lsh sum (car shift-xor)) val))
10241 (when (> eat 0) (setq eat (- eat 1)))
10242 (cond
10243 ((= 0 eat) ;multi byte
10244 (setq ret (concat ret (char-to-string sum)))
10245 (setq sum 0))
10246 ((not bytes) ; single byte(s)
10247 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10248 ret)))
10250 (defun org-link-unescape-single-byte-sequence (hex)
10251 "Unhexify hex-encoded single byte character sequences."
10252 (mapconcat (lambda (byte)
10253 (char-to-string (string-to-number byte 16)))
10254 (cdr (split-string hex "%")) ""))
10256 (defun org-xor (a b)
10257 "Exclusive or."
10258 (if a (not b) b))
10260 (defun org-fixup-message-id-for-http (s)
10261 "Replace special characters in a message id, so it can be used in an http query."
10262 (when (string-match "%" s)
10263 (setq s (mapconcat (lambda (c)
10264 (if (eq c ?%)
10265 "%25"
10266 (char-to-string c)))
10267 s "")))
10268 (while (string-match "<" s)
10269 (setq s (replace-match "%3C" t t s)))
10270 (while (string-match ">" s)
10271 (setq s (replace-match "%3E" t t s)))
10272 (while (string-match "@" s)
10273 (setq s (replace-match "%40" t t s)))
10276 (defun org-link-prettify (link)
10277 "Return a human-readable representation of LINK.
10278 The car of LINK must be a raw link.
10279 The cdr of LINK must be either a link description or nil."
10280 (let ((desc (or (cadr link) "<no description>")))
10281 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10282 "<" (car link) ">")))
10284 ;;;###autoload
10285 (defun org-insert-link-global ()
10286 "Insert a link like Org mode does.
10287 This command can be called in any mode to insert a link in Org syntax."
10288 (interactive)
10289 (org-load-modules-maybe)
10290 (org-run-like-in-org-mode 'org-insert-link))
10292 (defun org-insert-all-links (arg &optional pre post)
10293 "Insert all links in `org-stored-links'.
10294 When a universal prefix, do not delete the links from `org-stored-links'.
10295 When `ARG' is a number, insert the last N link(s).
10296 `PRE' and `POST' are optional arguments to define a string to
10297 prepend or to append."
10298 (interactive "P")
10299 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10300 (links (copy-sequence org-stored-links))
10301 (pr (or pre "- "))
10302 (po (or post "\n"))
10303 (cnt 1) l)
10304 (if (null org-stored-links)
10305 (message "No link to insert")
10306 (while (and (or (listp arg) (>= arg cnt))
10307 (setq l (if (listp arg)
10308 (pop links)
10309 (pop org-stored-links))))
10310 (setq cnt (1+ cnt))
10311 (insert pr)
10312 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10313 (insert po)))))
10315 (defun org-insert-last-stored-link (arg)
10316 "Insert the last link stored in `org-stored-links'."
10317 (interactive "p")
10318 (org-insert-all-links arg "" "\n"))
10320 (defun org-link-fontify-links-to-this-file ()
10321 "Fontify links to the current file in `org-stored-links'."
10322 (let ((f (buffer-file-name)) a b)
10323 (setq a (mapcar (lambda(l)
10324 (let ((ll (car l)))
10325 (when (and (string-match "^file:\\(.+\\)::" ll)
10326 (equal f (expand-file-name (match-string 1 ll))))
10327 ll)))
10328 org-stored-links))
10329 (when (featurep 'org-id)
10330 (setq b (mapcar (lambda(l)
10331 (let ((ll (car l)))
10332 (when (and (string-match "^id:\\(.+\\)$" ll)
10333 (equal f (expand-file-name
10334 (or (org-id-find-id-file
10335 (match-string 1 ll)) ""))))
10336 ll)))
10337 org-stored-links)))
10338 (mapcar (lambda(l)
10339 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10340 (delq nil (append a b)))))
10342 (defvar org--links-history nil)
10343 (defun org-insert-link (&optional complete-file link-location default-description)
10344 "Insert a link. At the prompt, enter the link.
10346 Completion can be used to insert any of the link protocol prefixes like
10347 http or ftp in use.
10349 The history can be used to select a link previously stored with
10350 `org-store-link'. When the empty string is entered (i.e. if you just
10351 press RET at the prompt), the link defaults to the most recently
10352 stored link. As SPC triggers completion in the minibuffer, you need to
10353 use M-SPC or C-q SPC to force the insertion of a space character.
10355 You will also be prompted for a description, and if one is given, it will
10356 be displayed in the buffer instead of the link.
10358 If there is already a link at point, this command will allow you to edit link
10359 and description parts.
10361 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10362 be selected using completion. The path to the file will be relative to the
10363 current directory if the file is in the current directory or a subdirectory.
10364 Otherwise, the link will be the absolute path as completed in the minibuffer
10365 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10366 option `org-link-file-path-type'.
10368 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10369 the current directory or below.
10371 With three \\[universal-argument] prefixes, negate the meaning of
10372 `org-keep-stored-link-after-insertion'.
10374 If `org-make-link-description-function' is non-nil, this function will be
10375 called with the link target, and the result will be the default
10376 link description.
10378 If the LINK-LOCATION parameter is non-nil, this value will be
10379 used as the link location instead of reading one interactively.
10381 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10382 be used as the default description."
10383 (interactive "P")
10384 (let* ((wcf (current-window-configuration))
10385 (origbuf (current-buffer))
10386 (region (when (org-region-active-p)
10387 (buffer-substring (region-beginning) (region-end))))
10388 (remove (and region (list (region-beginning) (region-end))))
10389 (desc region)
10390 (link link-location)
10391 (abbrevs org-link-abbrev-alist-local)
10392 entry all-prefixes auto-desc)
10393 (cond
10394 (link-location) ; specified by arg, just use it.
10395 ((org-in-regexp org-bracket-link-regexp 1)
10396 ;; We do have a link at point, and we are going to edit it.
10397 (setq remove (list (match-beginning 0) (match-end 0)))
10398 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10399 (setq link (read-string "Link: "
10400 (org-link-unescape
10401 (match-string-no-properties 1)))))
10402 ((or (org-in-regexp org-angle-link-re)
10403 (org-in-regexp org-plain-link-re))
10404 ;; Convert to bracket link
10405 (setq remove (list (match-beginning 0) (match-end 0))
10406 link (read-string "Link: "
10407 (org-unbracket-string "<" ">" (match-string 0)))))
10408 ((member complete-file '((4) (16)))
10409 ;; Completing read for file names.
10410 (setq link (org-file-complete-link complete-file)))
10412 ;; Read link, with completion for stored links.
10413 (org-link-fontify-links-to-this-file)
10414 (org-switch-to-buffer-other-window "*Org Links*")
10415 (with-current-buffer "*Org Links*"
10416 (erase-buffer)
10417 (insert "Insert a link.
10418 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10419 (when org-stored-links
10420 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10421 (insert (mapconcat 'org-link-prettify
10422 (reverse org-stored-links) "\n")))
10423 (goto-char (point-min)))
10424 (let ((cw (selected-window)))
10425 (select-window (get-buffer-window "*Org Links*" 'visible))
10426 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10427 (unless (pos-visible-in-window-p (point-max))
10428 (org-fit-window-to-buffer))
10429 (and (window-live-p cw) (select-window cw)))
10430 (setq all-prefixes (append (mapcar 'car abbrevs)
10431 (mapcar 'car org-link-abbrev-alist)
10432 (org-link-types)))
10433 (unwind-protect
10434 ;; Fake a link history, containing the stored links.
10435 (let ((org--links-history
10436 (append (mapcar #'car org-stored-links)
10437 org-insert-link-history)))
10438 (setq link
10439 (org-completing-read
10440 "Link: "
10441 (append
10442 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10443 (mapcar #'car org-stored-links))
10444 nil nil nil
10445 'org--links-history
10446 (caar org-stored-links)))
10447 (unless (org-string-nw-p link) (user-error "No link selected"))
10448 (dolist (l org-stored-links)
10449 (when (equal link (cadr l))
10450 (setq link (car l))
10451 (setq auto-desc t)))
10452 (when (or (member link all-prefixes)
10453 (and (equal ":" (substring link -1))
10454 (member (substring link 0 -1) all-prefixes)
10455 (setq link (substring link 0 -1))))
10456 (setq link (with-current-buffer origbuf
10457 (org-link-try-special-completion link)))))
10458 (set-window-configuration wcf)
10459 (kill-buffer "*Org Links*"))
10460 (setq entry (assoc link org-stored-links))
10461 (or entry (push link org-insert-link-history))
10462 (setq desc (or desc (nth 1 entry)))))
10464 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10465 (not org-keep-stored-link-after-insertion))
10466 (setq org-stored-links (delq (assoc link org-stored-links)
10467 org-stored-links)))
10469 (when (and (string-match org-plain-link-re link)
10470 (not (string-match org-ts-regexp link)))
10471 ;; URL-like link, normalize the use of angular brackets.
10472 (setq link (org-unbracket-string "<" ">" link)))
10474 ;; Check if we are linking to the current file with a search
10475 ;; option If yes, simplify the link by using only the search
10476 ;; option.
10477 (when (and buffer-file-name
10478 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10479 (let* ((path (match-string 1 link))
10480 (case-fold-search nil)
10481 (search (match-string 2 link)))
10482 (save-match-data
10483 (when (equal (file-truename buffer-file-name) (file-truename path))
10484 ;; We are linking to this same file, with a search option
10485 (setq link search)))))
10487 ;; Check if we can/should use a relative path. If yes, simplify the link
10488 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10489 (let* ((type (match-string 1 link))
10490 (path (match-string 2 link))
10491 (origpath path)
10492 (case-fold-search nil))
10493 (cond
10494 ((or (eq org-link-file-path-type 'absolute)
10495 (equal complete-file '(16)))
10496 (setq path (abbreviate-file-name (expand-file-name path))))
10497 ((eq org-link-file-path-type 'noabbrev)
10498 (setq path (expand-file-name path)))
10499 ((eq org-link-file-path-type 'relative)
10500 (setq path (file-relative-name path)))
10502 (save-match-data
10503 (if (string-match (concat "^" (regexp-quote
10504 (expand-file-name
10505 (file-name-as-directory
10506 default-directory))))
10507 (expand-file-name path))
10508 ;; We are linking a file with relative path name.
10509 (setq path (substring (expand-file-name path)
10510 (match-end 0)))
10511 (setq path (abbreviate-file-name (expand-file-name path)))))))
10512 (setq link (concat type path))
10513 (when (equal desc origpath)
10514 (setq desc path))))
10516 (if org-make-link-description-function
10517 (setq desc
10518 (or (condition-case nil
10519 (funcall org-make-link-description-function link desc)
10520 (error (progn (message "Can't get link description from `%s'"
10521 (symbol-name org-make-link-description-function))
10522 (sit-for 2) nil)))
10523 (read-string "Description: " default-description)))
10524 (if default-description (setq desc default-description)
10525 (setq desc (or (and auto-desc desc)
10526 (read-string "Description: " desc)))))
10528 (unless (string-match "\\S-" desc) (setq desc nil))
10529 (when remove (apply 'delete-region remove))
10530 (insert (org-make-link-string link desc))
10531 ;; Redisplay so as the new link has proper invisible characters.
10532 (sit-for 0)))
10534 (defun org-link-try-special-completion (type)
10535 "If there is completion support for link type TYPE, offer it."
10536 (let ((fun (org-link-get-parameter type :complete)))
10537 (if (functionp fun)
10538 (funcall fun)
10539 (read-string "Link (no completion support): " (concat type ":")))))
10541 (defun org-file-complete-link (&optional arg)
10542 "Create a file link using completion."
10543 (let ((file (read-file-name "File: "))
10544 (pwd (file-name-as-directory (expand-file-name ".")))
10545 (pwd1 (file-name-as-directory (abbreviate-file-name
10546 (expand-file-name ".")))))
10547 (cond ((equal arg '(16))
10548 (concat "file:"
10549 (abbreviate-file-name (expand-file-name file))))
10550 ((string-match
10551 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10552 (concat "file:" (match-string 1 file)))
10553 ((string-match
10554 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10555 (expand-file-name file))
10556 (concat "file:"
10557 (match-string 1 (expand-file-name file))))
10558 (t (concat "file:" file)))))
10560 (defun org-completing-read (&rest args)
10561 "Completing-read with SPACE being a normal character."
10562 (let ((enable-recursive-minibuffers t)
10563 (minibuffer-local-completion-map
10564 (copy-keymap minibuffer-local-completion-map)))
10565 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10566 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10567 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10568 'org-time-stamp-inactive)
10569 (apply #'completing-read args)))
10571 ;;; Opening/following a link
10573 (defvar org-link-search-failed nil)
10575 (defvar org-open-link-functions nil
10576 "Hook for functions finding a plain text link.
10577 These functions must take a single argument, the link content.
10578 They will be called for links that look like [[link text][description]]
10579 when LINK TEXT does not have a protocol like \"http:\" and does not look
10580 like a filename (e.g. \"./blue.png\").
10582 These functions will be called *before* Org attempts to resolve the
10583 link by doing text searches in the current buffer - so if you want a
10584 link \"[[target]]\" to still find \"<<target>>\", your function should
10585 handle this as a special case.
10587 When the function does handle the link, it must return a non-nil value.
10588 If it decides that it is not responsible for this link, it must return
10589 nil to indicate that that Org can continue with other options like
10590 exact and fuzzy text search.")
10592 (defun org-next-link (&optional search-backward)
10593 "Move forward to the next link.
10594 If the link is in hidden text, expose it."
10595 (interactive "P")
10596 (when (and org-link-search-failed (eq this-command last-command))
10597 (goto-char (point-min))
10598 (message "Link search wrapped back to beginning of buffer"))
10599 (setq org-link-search-failed nil)
10600 (let* ((pos (point))
10601 (ct (org-context))
10602 (a (assoc :link ct))
10603 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10604 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10605 ((looking-at org-any-link-re)
10606 ;; Don't stay stuck at link without an org-link face
10607 (forward-char (if search-backward -1 1))))
10608 (if (funcall srch-fun org-any-link-re nil t)
10609 (progn
10610 (goto-char (match-beginning 0))
10611 (when (outline-invisible-p) (org-show-context)))
10612 (goto-char pos)
10613 (setq org-link-search-failed t)
10614 (message "No further link found"))))
10616 (defun org-previous-link ()
10617 "Move backward to the previous link.
10618 If the link is in hidden text, expose it."
10619 (interactive)
10620 (funcall 'org-next-link t))
10622 (defun org-translate-link (s)
10623 "Translate a link string if a translation function has been defined."
10624 (with-temp-buffer
10625 (insert (org-trim s))
10626 (org-trim (org-element-interpret-data (org-element-context)))))
10628 (defun org-translate-link-from-planner (type path)
10629 "Translate a link from Emacs Planner syntax so that Org can follow it.
10630 This is still an experimental function, your mileage may vary."
10631 (cond
10632 ((member type '("http" "https" "news" "ftp"))
10633 ;; standard Internet links are the same.
10634 nil)
10635 ((and (equal type "irc") (string-match "^//" path))
10636 ;; Planner has two / at the beginning of an irc link, we have 1.
10637 ;; We should have zero, actually....
10638 (setq path (substring path 1)))
10639 ((and (equal type "lisp") (string-match "^/" path))
10640 ;; Planner has a slash, we do not.
10641 (setq type "elisp" path (substring path 1)))
10642 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10643 ;; A typical message link. Planner has the id after the final slash,
10644 ;; we separate it with a hash mark
10645 (setq path (concat (match-string 1 path) "#"
10646 (org-unbracket-string "<" ">" (match-string 2 path))))))
10647 (cons type path))
10649 (defun org-find-file-at-mouse (ev)
10650 "Open file link or URL at mouse."
10651 (interactive "e")
10652 (mouse-set-point ev)
10653 (org-open-at-point 'in-emacs))
10655 (defun org-open-at-mouse (ev)
10656 "Open file link or URL at mouse.
10657 See the docstring of `org-open-file' for details."
10658 (interactive "e")
10659 (mouse-set-point ev)
10660 (when (eq major-mode 'org-agenda-mode)
10661 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10662 (org-open-at-point))
10664 (defvar org-window-config-before-follow-link nil
10665 "The window configuration before following a link.
10666 This is saved in case the need arises to restore it.")
10668 ;;;###autoload
10669 (defun org-open-at-point-global ()
10670 "Follow a link or time-stamp like Org mode does.
10671 This command can be called in any mode to follow an external link
10672 or a time-stamp that has Org mode syntax. Its behavior is
10673 undefined when called on internal links (e.g., fuzzy links).
10674 Raise an error when there is nothing to follow. "
10675 (interactive)
10676 (cond ((org-in-regexp org-any-link-re)
10677 (org-open-link-from-string (match-string-no-properties 0)))
10678 ((or (org-in-regexp org-ts-regexp-both nil t)
10679 (org-in-regexp org-tsr-regexp-both nil t))
10680 (org-follow-timestamp-link))
10681 (t (user-error "No link found"))))
10683 ;;;###autoload
10684 (defun org-open-link-from-string (s &optional arg reference-buffer)
10685 "Open a link in the string S, as if it was in Org-mode."
10686 (interactive "sLink: \nP")
10687 (let ((reference-buffer (or reference-buffer (current-buffer))))
10688 (with-temp-buffer
10689 (let ((org-inhibit-startup (not reference-buffer)))
10690 (org-mode)
10691 (insert s)
10692 (goto-char (point-min))
10693 (when reference-buffer
10694 (setq org-link-abbrev-alist-local
10695 (with-current-buffer reference-buffer
10696 org-link-abbrev-alist-local)))
10697 (org-open-at-point arg reference-buffer)))))
10699 (defvar org-open-at-point-functions nil
10700 "Hook that is run when following a link at point.
10702 Functions in this hook must return t if they identify and follow
10703 a link at point. If they don't find anything interesting at point,
10704 they must return nil.")
10706 (defvar org-link-search-inhibit-query nil)
10707 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10708 (defun org--open-doi-link (path)
10709 "Open a \"doi\" type link.
10710 PATH is a the path to search for, as a string."
10711 (browse-url (url-encode-url (concat org-doi-server-url path))))
10713 (defun org--open-elisp-link (path)
10714 "Open a \"elisp\" type link.
10715 PATH is the sexp to evaluate, as a string."
10716 (let ((cmd path))
10717 (if (or (and (org-string-nw-p
10718 org-confirm-elisp-link-not-regexp)
10719 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10720 (not org-confirm-elisp-link-function)
10721 (funcall org-confirm-elisp-link-function
10722 (format "Execute \"%s\" as elisp? "
10723 (org-add-props cmd nil 'face 'org-warning))))
10724 (message "%s => %s" cmd
10725 (if (eq (string-to-char cmd) ?\()
10726 (eval (read cmd))
10727 (call-interactively (read cmd))))
10728 (user-error "Abort"))))
10730 (defun org--open-help-link (path)
10731 "Open a \"help\" type link.
10732 PATH is a symbol name, as a string."
10733 (pcase (intern path)
10734 ((and (pred fboundp) variable) (describe-function variable))
10735 ((and (pred boundp) function) (describe-variable function))
10736 (name (user-error "Unknown function or variable: %s" name))))
10738 (defun org--open-shell-link (path)
10739 "Open a \"shell\" type link.
10740 PATH is the command to execute, as a string."
10741 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10742 (cmd path))
10743 (if (or (and (org-string-nw-p
10744 org-confirm-shell-link-not-regexp)
10745 (string-match
10746 org-confirm-shell-link-not-regexp cmd))
10747 (not org-confirm-shell-link-function)
10748 (funcall org-confirm-shell-link-function
10749 (format "Execute \"%s\" in shell? "
10750 (org-add-props cmd nil
10751 'face 'org-warning))))
10752 (progn
10753 (message "Executing %s" cmd)
10754 (shell-command cmd buf)
10755 (when (featurep 'midnight)
10756 (setq clean-buffer-list-kill-buffer-names
10757 (cons (buffer-name buf)
10758 clean-buffer-list-kill-buffer-names))))
10759 (user-error "Abort"))))
10761 (defun org-open-at-point (&optional arg reference-buffer)
10762 "Open link, timestamp, footnote or tags at point.
10764 When point is on a link, follow it. Normally, files will be
10765 opened by an appropriate application. If the optional prefix
10766 argument ARG is non-nil, Emacs will visit the file. With
10767 a double prefix argument, try to open outside of Emacs, in the
10768 application the system uses for this file type.
10770 When point is on a timestamp, open the agenda at the day
10771 specified.
10773 When point is a footnote definition, move to the first reference
10774 found. If it is on a reference, move to the associated
10775 definition.
10777 When point is on a headline, display a list of every link in the
10778 entry, so it is possible to pick one, or all, of them. If point
10779 is on a tag, call `org-tags-view' instead.
10781 When optional argument REFERENCE-BUFFER is non-nil, it should
10782 specify a buffer from where the link search should happen. This
10783 is used internally by `org-open-link-from-string'.
10785 On top of syntactically correct links, this function will open
10786 the link at point in comments or comment blocks and the first
10787 link in a property drawer line."
10788 (interactive "P")
10789 ;; On a code block, open block's results.
10790 (unless (call-interactively 'org-babel-open-src-block-result)
10791 (org-load-modules-maybe)
10792 (setq org-window-config-before-follow-link (current-window-configuration))
10793 (org-remove-occur-highlights nil nil t)
10794 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10795 (let* ((context
10796 ;; Only consider supported types, even if they are not
10797 ;; the closest one.
10798 (org-element-lineage
10799 (org-element-context)
10800 '(clock comment comment-block footnote-definition
10801 footnote-reference headline inlinetask keyword link
10802 node-property timestamp)
10804 (type (org-element-type context))
10805 (value (org-element-property :value context)))
10806 (cond
10807 ((not context) (user-error "No link found"))
10808 ;; Exception: open timestamps and links in properties
10809 ;; drawers, keywords and comments.
10810 ((memq type '(comment comment-block keyword node-property))
10811 (call-interactively #'org-open-at-point-global))
10812 ;; On a headline or an inlinetask, but not on a timestamp,
10813 ;; a link, a footnote reference or on tags.
10814 ((and (memq type '(headline inlinetask))
10815 ;; Not on tags.
10816 (progn (save-excursion (beginning-of-line)
10817 (looking-at org-complex-heading-regexp))
10818 (or (not (match-beginning 5))
10819 (< (point) (match-beginning 5)))))
10820 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10821 (links (car data))
10822 (links-end (cdr data)))
10823 (if links
10824 (dolist (link (if (stringp links) (list links) links))
10825 (search-forward link nil links-end)
10826 (goto-char (match-beginning 0))
10827 (org-open-at-point))
10828 (require 'org-attach)
10829 (org-attach-reveal 'if-exists))))
10830 ;; On a clock line, make sure point is on the timestamp
10831 ;; before opening it.
10832 ((and (eq type 'clock)
10833 value
10834 (>= (point) (org-element-property :begin value))
10835 (<= (point) (org-element-property :end value)))
10836 (org-follow-timestamp-link))
10837 ;; Do nothing on white spaces after an object.
10838 ((>= (point)
10839 (save-excursion
10840 (goto-char (org-element-property :end context))
10841 (skip-chars-backward " \t")
10842 (point)))
10843 (user-error "No link found"))
10844 ((eq type 'timestamp) (org-follow-timestamp-link))
10845 ;; On tags within a headline or an inlinetask.
10846 ((and (memq type '(headline inlinetask))
10847 (progn (save-excursion (beginning-of-line)
10848 (looking-at org-complex-heading-regexp))
10849 (and (match-beginning 5)
10850 (>= (point) (match-beginning 5)))))
10851 (org-tags-view arg (substring (match-string 5) 0 -1)))
10852 ((eq type 'link)
10853 ;; When link is located within the description of another
10854 ;; link (e.g., an inline image), always open the parent
10855 ;; link.
10856 (let* ((link (let ((up (org-element-property :parent context)))
10857 (if (eq (org-element-type up) 'link) up context)))
10858 (type (org-element-property :type link))
10859 (path (org-link-unescape (org-element-property :path link))))
10860 ;; Switch back to REFERENCE-BUFFER needed when called in
10861 ;; a temporary buffer through `org-open-link-from-string'.
10862 (with-current-buffer (or reference-buffer (current-buffer))
10863 (cond
10864 ((equal type "file")
10865 (if (string-match "[*?{]" (file-name-nondirectory path))
10866 (dired path)
10867 ;; Look into `org-link-parameters' in order to find
10868 ;; a DEDICATED-FUNCTION to open file. The function
10869 ;; will be applied on raw link instead of parsed
10870 ;; link due to the limitation in `org-add-link-type'
10871 ;; ("open" function called with a single argument).
10872 ;; If no such function is found, fallback to
10873 ;; `org-open-file'.
10874 (let* ((option (org-element-property :search-option link))
10875 (app (org-element-property :application link))
10876 (dedicated-function
10877 (org-link-get-parameter
10878 (if app (concat type "+" app) type)
10879 :follow)))
10880 (if dedicated-function
10881 (funcall dedicated-function
10882 (concat path
10883 (and option (concat "::" option))))
10884 (apply #'org-open-file
10885 path
10886 (cond (arg)
10887 ((equal app "emacs") 'emacs)
10888 ((equal app "sys") 'system))
10889 (cond ((not option) nil)
10890 ((string-match-p "\\`[0-9]+\\'" option)
10891 (list (string-to-number option)))
10892 (t (list nil
10893 (org-link-unescape option)))))))))
10894 ((functionp (org-link-get-parameter type :follow))
10895 (funcall (org-link-get-parameter type :follow) path))
10896 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10897 (unless (run-hook-with-args-until-success
10898 'org-open-link-functions path)
10899 (if (not arg) (org-mark-ring-push)
10900 (switch-to-buffer-other-window
10901 (org-get-buffer-for-internal-link (current-buffer))))
10902 (let ((destination
10903 (org-with-wide-buffer
10904 (if (equal type "radio")
10905 (org-search-radio-target
10906 (org-element-property :path link))
10907 (org-link-search
10908 (if (member type '("custom-id" "coderef"))
10909 (org-element-property :raw-link link)
10910 path)
10911 ;; Prevent fuzzy links from matching
10912 ;; themselves.
10913 (and (equal type "fuzzy")
10914 (+ 2 (org-element-property :begin link)))))
10915 (point))))
10916 (unless (and (<= (point-min) destination)
10917 (>= (point-max) destination))
10918 (widen))
10919 (goto-char destination))))
10920 (t (browse-url-at-point))))))
10921 ;; On a footnote reference or at a footnote definition's label.
10922 ((or (eq type 'footnote-reference)
10923 (and (eq type 'footnote-definition)
10924 (save-excursion
10925 ;; Do not validate action when point is on the
10926 ;; spaces right after the footnote label, in
10927 ;; order to be on par with behaviour on links.
10928 (skip-chars-forward " \t")
10929 (let ((begin
10930 (org-element-property :contents-begin context)))
10931 (if begin (< (point) begin)
10932 (= (org-element-property :post-affiliated context)
10933 (line-beginning-position)))))))
10934 (org-footnote-action))
10935 (t (user-error "No link found")))))
10936 (run-hook-with-args 'org-follow-link-hook)))
10938 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10939 "Offer links in the current entry and return the selected link.
10940 If there is only one link, return it.
10941 If NTH is an integer, return the NTH link found.
10942 If ZERO is a string, check also this string for a link, and if
10943 there is one, return it."
10944 (with-current-buffer buffer
10945 (org-with-wide-buffer
10946 (goto-char marker)
10947 (let ((cnt ?0)
10948 have-zero end links link c)
10949 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10950 (push (match-string 0 zero) links)
10951 (setq cnt (1- cnt) have-zero t))
10952 (save-excursion
10953 (org-back-to-heading t)
10954 (setq end (save-excursion (outline-next-heading) (point)))
10955 (while (re-search-forward org-any-link-re end t)
10956 (push (match-string 0) links))
10957 (setq links (org-uniquify (reverse links))))
10958 (cond
10959 ((null links)
10960 (message "No links"))
10961 ((equal (length links) 1)
10962 (setq link (car links)))
10963 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10964 (setq link (nth (if have-zero nth (1- nth)) links)))
10965 (t ; we have to select a link
10966 (save-excursion
10967 (save-window-excursion
10968 (delete-other-windows)
10969 (with-output-to-temp-buffer "*Select Link*"
10970 (dolist (l links)
10971 (cond
10972 ((not (string-match org-bracket-link-regexp l))
10973 (princ (format "[%c] %s\n" (cl-incf cnt)
10974 (org-unbracket-string "<" ">" l))))
10975 ((match-end 3)
10976 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10977 (match-string 3 l) (match-string 1 l))))
10978 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10979 (match-string 1 l)))))))
10980 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10981 (message "Select link to open, RET to open all:")
10982 (setq c (read-char-exclusive))
10983 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10984 (when (equal c ?q) (user-error "Abort"))
10985 (if (equal c ?\C-m)
10986 (setq link links)
10987 (setq nth (- c ?0))
10988 (when have-zero (setq nth (1+ nth)))
10989 (unless (and (integerp nth) (>= (length links) nth))
10990 (user-error "Invalid link selection"))
10991 (setq link (nth (1- nth) links)))))
10992 (cons link end)))))
10994 ;; TODO: These functions are deprecated since `org-open-at-point'
10995 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10996 (defun org-open-file-with-system (path)
10997 "Open file at PATH using the system way of opening it."
10998 (org-open-file path 'system))
10999 (defun org-open-file-with-emacs (path)
11000 "Open file at PATH in Emacs."
11001 (org-open-file path 'emacs))
11004 ;;; File search
11006 (defvar org-create-file-search-functions nil
11007 "List of functions to construct the right search string for a file link.
11008 These functions are called in turn with point at the location to
11009 which the link should point.
11011 A function in the hook should first test if it would like to
11012 handle this file type, for example by checking the `major-mode'
11013 or the file extension. If it decides not to handle this file, it
11014 should just return nil to give other functions a chance. If it
11015 does handle the file, it must return the search string to be used
11016 when following the link. The search string will be part of the
11017 file link, given after a double colon, and `org-open-at-point'
11018 will automatically search for it. If special measures must be
11019 taken to make the search successful, another function should be
11020 added to the companion hook `org-execute-file-search-functions',
11021 which see.
11023 A function in this hook may also use `setq' to set the variable
11024 `description' to provide a suggestion for the descriptive text to
11025 be used for this link when it gets inserted into an Org buffer
11026 with \\[org-insert-link].")
11028 (defvar org-execute-file-search-functions nil
11029 "List of functions to execute a file search triggered by a link.
11031 Functions added to this hook must accept a single argument, the
11032 search string that was part of the file link, the part after the
11033 double colon. The function must first check if it would like to
11034 handle this search, for example by checking the `major-mode' or
11035 the file extension. If it decides not to handle this search, it
11036 should just return nil to give other functions a chance. If it
11037 does handle the search, it must return a non-nil value to keep
11038 other functions from trying.
11040 Each function can access the current prefix argument through the
11041 variable `current-prefix-arg'. Note that a single prefix is used
11042 to force opening a link in Emacs, so it may be good to only use a
11043 numeric or double prefix to guide the search function.
11045 In case this is needed, a function in this hook can also restore
11046 the window configuration before `org-open-at-point' was called using:
11048 \(set-window-configuration org-window-config-before-follow-link)")
11050 (defun org-search-radio-target (target)
11051 "Search a radio target matching TARGET in current buffer.
11052 White spaces are not significant."
11053 (let ((re (format "<<<%s>>>"
11054 (mapconcat #'regexp-quote
11055 (org-split-string target "[ \t\n]+")
11056 "[ \t]+\\(?:\n[ \t]*\\)?")))
11057 (origin (point)))
11058 (goto-char (point-min))
11059 (catch :radio-match
11060 (while (re-search-forward re nil t)
11061 (backward-char)
11062 (let ((object (org-element-context)))
11063 (when (eq (org-element-type object) 'radio-target)
11064 (goto-char (org-element-property :begin object))
11065 (org-show-context 'link-search)
11066 (throw :radio-match nil))))
11067 (goto-char origin)
11068 (user-error "No match for radio target: %s" target))))
11070 (defun org-link-search (s &optional avoid-pos stealth)
11071 "Search for a search string S.
11073 If S starts with \"#\", it triggers a custom ID search.
11075 If S is enclosed within parenthesis, it initiates a coderef
11076 search.
11078 If S is surrounded by forward slashes, it is interpreted as
11079 a regular expression. In Org mode files, this will create an
11080 `org-occur' sparse tree. In ordinary files, `occur' will be used
11081 to list matches. If the current buffer is in `dired-mode', grep
11082 will be used to search in all files.
11084 When AVOID-POS is given, ignore matches near that position.
11086 When optional argument STEALTH is non-nil, do not modify
11087 visibility around point, thus ignoring `org-show-context-detail'
11088 variable.
11090 Search is case-insensitive and ignores white spaces. Return type
11091 of matched result, with is either `dedicated' or `fuzzy'."
11092 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11093 (let* ((case-fold-search t)
11094 (origin (point))
11095 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11096 (words (org-split-string s "[ \t\n]+"))
11097 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11098 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11099 type)
11100 (cond
11101 ;; Check if there are any special search functions.
11102 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11103 ((eq (string-to-char s) ?#)
11104 ;; Look for a custom ID S if S starts with "#".
11105 (let* ((id (substring normalized 1))
11106 (match (org-find-property "CUSTOM_ID" id)))
11107 (if match (progn (goto-char match) (setf type 'dedicated))
11108 (error "No match for custom ID: %s" id))))
11109 ((string-match "\\`(\\(.*\\))\\'" normalized)
11110 ;; Look for coderef targets if S is enclosed within parenthesis.
11111 (let ((coderef (match-string-no-properties 1 normalized))
11112 (re (substring s-single-re 1 -1)))
11113 (goto-char (point-min))
11114 (catch :coderef-match
11115 (while (re-search-forward re nil t)
11116 (let ((element (org-element-at-point)))
11117 (when (and (memq (org-element-type element)
11118 '(example-block src-block))
11119 ;; Build proper regexp according to current
11120 ;; block's label format.
11121 (let ((label-fmt
11122 (regexp-quote
11123 (or (org-element-property :label-fmt element)
11124 org-coderef-label-format))))
11125 (save-excursion
11126 (beginning-of-line)
11127 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11128 (format label-fmt coderef))))))
11129 (setq type 'dedicated)
11130 (goto-char (match-beginning 1))
11131 (throw :coderef-match nil))))
11132 (goto-char origin)
11133 (error "No match for coderef: %s" coderef))))
11134 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11135 ;; Look for a regular expression.
11136 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11137 (match-string 1 s)))
11138 ;; Fuzzy links.
11140 (let ((starred (eq (string-to-char normalized) ?*)))
11141 (cond
11142 ;; Look for targets, only if not in a headline search.
11143 ((and (not starred)
11144 (let ((target (format "<<%s>>" s-multi-re)))
11145 (catch :target-match
11146 (goto-char (point-min))
11147 (while (re-search-forward target nil t)
11148 (backward-char)
11149 (let ((context (org-element-context)))
11150 (when (eq (org-element-type context) 'target)
11151 (setq type 'dedicated)
11152 (goto-char (org-element-property :begin context))
11153 (throw :target-match t))))
11154 nil))))
11155 ;; Look for elements named after S, only if not in a headline
11156 ;; search.
11157 ((and (not starred)
11158 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11159 (catch :name-match
11160 (goto-char (point-min))
11161 (while (re-search-forward name nil t)
11162 (let ((element (org-element-at-point)))
11163 (when (equal (org-split-string
11164 (org-element-property :name element)
11165 "[ \t]+")
11166 words)
11167 (setq type 'dedicated)
11168 (beginning-of-line)
11169 (throw :name-match t))))
11170 nil))))
11171 ;; Regular text search. Prefer headlines in Org mode
11172 ;; buffers.
11173 ((and (derived-mode-p 'org-mode)
11174 (let* ((wspace "[ \t]")
11175 (wspaceopt (concat wspace "*"))
11176 (cookie (concat "\\(?:"
11177 wspaceopt
11178 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11179 wspaceopt
11180 "\\)"))
11181 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11182 (re (concat
11183 org-outline-regexp-bol
11184 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11185 "\\(?:\\[#.\\][ \t]+\\)?"
11186 "\\(?:" org-comment-string "[ \t]+\\)?"
11187 sep "?"
11188 (let ((title (mapconcat #'regexp-quote
11189 words
11190 sep)))
11191 (if starred (substring title 1) title))
11192 sep "?"
11193 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11194 "[ \t]*$")))
11195 (goto-char (point-min))
11196 (re-search-forward re nil t)))
11197 (goto-char (match-beginning 0))
11198 (setq type 'dedicated))
11199 ;; Offer to create non-existent headline depending on
11200 ;; `org-link-search-must-match-exact-headline'.
11201 ((and (derived-mode-p 'org-mode)
11202 (not org-link-search-inhibit-query)
11203 (eq org-link-search-must-match-exact-headline 'query-to-create)
11204 (yes-or-no-p "No match - create this as a new heading? "))
11205 (goto-char (point-max))
11206 (unless (bolp) (newline))
11207 (org-insert-heading nil t t)
11208 (insert s "\n")
11209 (beginning-of-line 0))
11210 ;; Only headlines are looked after. No need to process
11211 ;; further: throw an error.
11212 ((and (derived-mode-p 'org-mode)
11213 (or starred org-link-search-must-match-exact-headline))
11214 (goto-char origin)
11215 (error "No match for fuzzy expression: %s" normalized))
11216 ;; Regular text search.
11217 ((catch :fuzzy-match
11218 (goto-char (point-min))
11219 (while (re-search-forward s-multi-re nil t)
11220 ;; Skip match if it contains AVOID-POS or it is included
11221 ;; in a link with a description but outside the
11222 ;; description.
11223 (unless (or (and avoid-pos
11224 (<= (match-beginning 0) avoid-pos)
11225 (> (match-end 0) avoid-pos))
11226 (and (save-match-data
11227 (org-in-regexp org-bracket-link-regexp))
11228 (match-beginning 3)
11229 (or (> (match-beginning 3) (point))
11230 (<= (match-end 3) (point)))
11231 (org-element-lineage
11232 (save-match-data (org-element-context))
11233 '(link) t)))
11234 (goto-char (match-beginning 0))
11235 (setq type 'fuzzy)
11236 (throw :fuzzy-match t)))
11237 nil))
11238 ;; All failed. Throw an error.
11239 (t (goto-char origin)
11240 (error "No match for fuzzy expression: %s" normalized))))))
11241 ;; Disclose surroundings of match, if appropriate.
11242 (when (and (derived-mode-p 'org-mode) (not stealth))
11243 (org-show-context 'link-search))
11244 type))
11246 (defun org-get-buffer-for-internal-link (buffer)
11247 "Return a buffer to be used for displaying the link target of internal links."
11248 (cond
11249 ((not org-display-internal-link-with-indirect-buffer)
11250 buffer)
11251 ((string-suffix-p "(Clone)" (buffer-name buffer))
11252 (message "Buffer is already a clone, not making another one")
11253 ;; we also do not modify visibility in this case
11254 buffer)
11255 (t ; make a new indirect buffer for displaying the link
11256 (let* ((bn (buffer-name buffer))
11257 (ibn (concat bn "(Clone)"))
11258 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11259 (with-current-buffer ib (org-overview))
11260 ib))))
11262 (defun org-do-occur (regexp &optional cleanup)
11263 "Call the Emacs command `occur'.
11264 If CLEANUP is non-nil, remove the printout of the regular expression
11265 in the *Occur* buffer. This is useful if the regex is long and not useful
11266 to read."
11267 (occur regexp)
11268 (when cleanup
11269 (let ((cwin (selected-window)) win beg end)
11270 (when (setq win (get-buffer-window "*Occur*"))
11271 (select-window win))
11272 (goto-char (point-min))
11273 (when (re-search-forward "match[a-z]+" nil t)
11274 (setq beg (match-end 0))
11275 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11276 (setq end (1- (match-beginning 0)))))
11277 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11278 (goto-char (point-min))
11279 (select-window cwin))))
11281 ;;; The mark ring for links jumps
11283 (defvar org-mark-ring nil
11284 "Mark ring for positions before jumps in Org-mode.")
11285 (defvar org-mark-ring-last-goto nil
11286 "Last position in the mark ring used to go back.")
11287 ;; Fill and close the ring
11288 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11289 (dotimes (_ org-mark-ring-length)
11290 (push (make-marker) org-mark-ring))
11291 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11292 org-mark-ring)
11294 (defun org-mark-ring-push (&optional pos buffer)
11295 "Put the current position or POS into the mark ring and rotate it."
11296 (interactive)
11297 (setq pos (or pos (point)))
11298 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11299 (move-marker (car org-mark-ring)
11300 (or pos (point))
11301 (or buffer (current-buffer)))
11302 (message "%s"
11303 (substitute-command-keys
11304 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11306 (defun org-mark-ring-goto (&optional n)
11307 "Jump to the previous position in the mark ring.
11308 With prefix arg N, jump back that many stored positions. When
11309 called several times in succession, walk through the entire ring.
11310 Org mode commands jumping to a different position in the current file,
11311 or to another Org file, automatically push the old position onto the ring."
11312 (interactive "p")
11313 (let (p m)
11314 (if (eq last-command this-command)
11315 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11316 (setq p org-mark-ring))
11317 (setq org-mark-ring-last-goto p)
11318 (setq m (car p))
11319 (pop-to-buffer-same-window (marker-buffer m))
11320 (goto-char m)
11321 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11323 (defun org-add-angle-brackets (s)
11324 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11325 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11328 ;;; Following specific links
11330 (defvar org-agenda-buffer-tmp-name)
11331 (defvar org-agenda-start-on-weekday)
11332 (defun org-follow-timestamp-link ()
11333 "Open an agenda view for the time-stamp date/range at point."
11334 (cond
11335 ((org-at-date-range-p t)
11336 (let ((org-agenda-start-on-weekday)
11337 (t1 (match-string 1))
11338 (t2 (match-string 2)) tt1 tt2)
11339 (setq tt1 (time-to-days (org-time-string-to-time t1))
11340 tt2 (time-to-days (org-time-string-to-time t2)))
11341 (let ((org-agenda-buffer-tmp-name
11342 (format "*Org Agenda(a:%s)"
11343 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11344 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11345 ((org-at-timestamp-p t)
11346 (let ((org-agenda-buffer-tmp-name
11347 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11348 (org-agenda-list nil (time-to-days (org-time-string-to-time
11349 (substring (match-string 1) 0 10)))
11350 1)))
11351 (t (error "This should not happen"))))
11354 ;;; Following file links
11355 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11356 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11357 (declare-function mailcap-mime-info
11358 "mailcap" (string &optional request no-decode))
11359 (defvar org-wait nil)
11360 (defun org-open-file (path &optional in-emacs line search)
11361 "Open the file at PATH.
11362 First, this expands any special file name abbreviations. Then the
11363 configuration variable `org-file-apps' is checked if it contains an
11364 entry for this file type, and if yes, the corresponding command is launched.
11366 If no application is found, Emacs simply visits the file.
11368 With optional prefix argument IN-EMACS, Emacs will visit the file.
11369 With a double \\[universal-argument] \\[universal-argument] \
11370 prefix arg, Org tries to avoid opening in Emacs
11371 and to use an external application to visit the file.
11373 Optional LINE specifies a line to go to, optional SEARCH a string
11374 to search for. If LINE or SEARCH is given, the file will be
11375 opened in Emacs, unless an entry from org-file-apps that makes
11376 use of groups in a regexp matches.
11378 If you want to change the way frames are used when following a
11379 link, please customize `org-link-frame-setup'.
11381 If the file does not exist, an error is thrown."
11382 (let* ((file (if (equal path "")
11383 buffer-file-name
11384 (substitute-in-file-name (expand-file-name path))))
11385 (file-apps (append org-file-apps (org-default-apps)))
11386 (apps (cl-remove-if
11387 'org-file-apps-entry-match-against-dlink-p file-apps))
11388 (apps-dlink (cl-remove-if-not
11389 'org-file-apps-entry-match-against-dlink-p file-apps))
11390 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11391 (dirp (unless remp (file-directory-p file)))
11392 (file (if (and dirp org-open-directory-means-index-dot-org)
11393 (concat (file-name-as-directory file) "index.org")
11394 file))
11395 (a-m-a-p (assq 'auto-mode apps))
11396 (dfile (downcase file))
11397 ;; Reconstruct the original link from the PATH, LINE and
11398 ;; SEARCH args.
11399 (link (cond (line (concat file "::" (number-to-string line)))
11400 (search (concat file "::" search))
11401 (t file)))
11402 (dlink (downcase link))
11403 (old-buffer (current-buffer))
11404 (old-pos (point))
11405 (old-mode major-mode)
11406 (ext
11407 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11408 (match-string 1 dfile)))
11409 cmd link-match-data)
11410 (cond
11411 ((member in-emacs '((16) system))
11412 (setq cmd (cdr (assq 'system apps))))
11413 (in-emacs (setq cmd 'emacs))
11415 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11416 (and dirp (cdr (assq 'directory apps)))
11417 ;; First, try matching against apps-dlink if we
11418 ;; get a match here, store the match data for
11419 ;; later.
11420 (let ((match (assoc-default dlink apps-dlink
11421 'string-match)))
11422 (if match
11423 (progn (setq link-match-data (match-data))
11424 match)
11425 (progn (setq in-emacs (or in-emacs line search))
11426 nil))) ; if we have no match in apps-dlink,
11427 ; always open the file in emacs if line or search
11428 ; is given (for backwards compatibility)
11429 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11430 'string-match)
11431 (cdr (assoc ext apps))
11432 (cdr (assq t apps))))))
11433 (when (eq cmd 'system)
11434 (setq cmd (cdr (assoc 'system apps))))
11435 (when (eq cmd 'default)
11436 (setq cmd (cdr (assoc t apps))))
11437 (when (eq cmd 'mailcap)
11438 (require 'mailcap)
11439 (mailcap-parse-mailcaps)
11440 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11441 (command (mailcap-mime-info mime-type)))
11442 (if (stringp command)
11443 (setq cmd command)
11444 (setq cmd 'emacs))))
11445 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11446 (not (file-exists-p file))
11447 (not org-open-non-existing-files))
11448 (user-error "No such file: %s" file))
11449 (cond
11450 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11451 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11452 (while (string-match "['\"]%s['\"]" cmd)
11453 (setq cmd (replace-match "%s" t t cmd)))
11454 (setq cmd (replace-regexp-in-string
11455 "%s"
11456 (shell-quote-argument (convert-standard-filename file))
11458 nil t))
11460 ;; Replace "%1", "%2" etc. in command with group matches from regex
11461 (save-match-data
11462 (let ((match-index 1)
11463 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11464 (set-match-data link-match-data)
11465 (while (<= match-index number-of-groups)
11466 (let ((regex (concat "%" (number-to-string match-index)))
11467 (replace-with (match-string match-index dlink)))
11468 (while (string-match regex cmd)
11469 (setq cmd (replace-match replace-with t t cmd))))
11470 (setq match-index (+ match-index 1)))))
11472 (save-window-excursion
11473 (message "Running %s...done" cmd)
11474 (start-process-shell-command cmd nil cmd)
11475 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11476 ((or (stringp cmd)
11477 (eq cmd 'emacs))
11478 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11479 (widen)
11480 (cond (line (org-goto-line line)
11481 (when (derived-mode-p 'org-mode) (org-reveal)))
11482 (search (org-link-search search))))
11483 ((functionp cmd)
11484 (save-match-data
11485 (set-match-data link-match-data)
11486 (condition-case nil
11487 (funcall cmd file link)
11488 ;; FIXME: Remove this check when most default installations
11489 ;; of Emacs have at least Org 9.0.
11490 ((debug wrong-number-of-arguments wrong-type-argument
11491 invalid-function)
11492 (user-error "Please see Org News for version 9.0 about \
11493 `org-file-apps'--Lisp error: %S" cmd)))))
11494 ((consp cmd)
11495 ;; FIXME: Remove this check when most default installations of
11496 ;; Emacs have at least Org 9.0.
11497 ;; Heads-up instead of silently fall back to
11498 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11499 ;; with sexp instead of a function for `cmd'.
11500 (user-error "Please see Org News for version 9.0 about \
11501 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11502 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11503 (and (derived-mode-p 'org-mode)
11504 (eq old-mode 'org-mode)
11505 (or (not (eq old-buffer (current-buffer)))
11506 (not (eq old-pos (point))))
11507 (org-mark-ring-push old-pos old-buffer))))
11509 (defun org-file-apps-entry-match-against-dlink-p (entry)
11510 "This function returns non-nil if `entry' uses a regular
11511 expression which should be matched against the whole link by
11512 org-open-file.
11514 It assumes that is the case when the entry uses a regular
11515 expression which has at least one grouping construct and the
11516 action is either a lisp form or a command string containing
11517 `%1', i.e. using at least one subexpression match as a
11518 parameter."
11519 (let ((selector (car entry))
11520 (action (cdr entry)))
11521 (if (stringp selector)
11522 (and (> (regexp-opt-depth selector) 0)
11523 (or (and (stringp action)
11524 (string-match "%[0-9]" action))
11525 (consp action)))
11526 nil)))
11528 (defun org-default-apps ()
11529 "Return the default applications for this operating system."
11530 (cond
11531 ((eq system-type 'darwin)
11532 org-file-apps-defaults-macosx)
11533 ((eq system-type 'windows-nt)
11534 org-file-apps-defaults-windowsnt)
11535 (t org-file-apps-defaults-gnu)))
11537 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11538 "Convert extensions to regular expressions in the cars of LIST.
11539 Also, weed out any non-string entries, because the return value is used
11540 only for regexp matching.
11541 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11542 point to the symbol `emacs', indicating that the file should
11543 be opened in Emacs."
11544 (append
11545 (delq nil
11546 (mapcar (lambda (x)
11547 (unless (not (stringp (car x)))
11548 (if (string-match "\\W" (car x))
11550 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11551 list))
11552 (when add-auto-mode
11553 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11555 (defvar ange-ftp-name-format)
11556 (defun org-file-remote-p (file)
11557 "Test whether FILE specifies a location on a remote system.
11558 Return non-nil if the location is indeed remote.
11560 For example, the filename \"/user@host:/foo\" specifies a location
11561 on the system \"/user@host:\"."
11562 (cond ((fboundp 'file-remote-p)
11563 (file-remote-p file))
11564 ((fboundp 'tramp-handle-file-remote-p)
11565 (tramp-handle-file-remote-p file))
11566 ((and (boundp 'ange-ftp-name-format)
11567 (string-match (car ange-ftp-name-format) file))
11568 t)))
11571 ;;;; Refiling
11573 (defun org-get-org-file ()
11574 "Read a filename, with default directory `org-directory'."
11575 (let ((default (or org-default-notes-file remember-data-file)))
11576 (read-file-name (format "File name [%s]: " default)
11577 (file-name-as-directory org-directory)
11578 default)))
11580 (defun org-notes-order-reversed-p ()
11581 "Check if the current file should receive notes in reversed order."
11582 (cond
11583 ((not org-reverse-note-order) nil)
11584 ((eq t org-reverse-note-order) t)
11585 ((not (listp org-reverse-note-order)) nil)
11586 (t (catch 'exit
11587 (dolist (entry org-reverse-note-order)
11588 (when (string-match (car entry) buffer-file-name)
11589 (throw 'exit (cdr entry))))))))
11591 (defvar org-refile-target-table nil
11592 "The list of refile targets, created by `org-refile'.")
11594 (defvar org-agenda-new-buffers nil
11595 "Buffers created to visit agenda files.")
11597 (defvar org-refile-cache nil
11598 "Cache for refile targets.")
11600 (defvar org-refile-markers nil
11601 "All the markers used for caching refile locations.")
11603 (defun org-refile-marker (pos)
11604 "Get a new refile marker, but only if caching is in use."
11605 (if (not org-refile-use-cache)
11607 (let ((m (make-marker)))
11608 (move-marker m pos)
11609 (push m org-refile-markers)
11610 m)))
11612 (defun org-refile-cache-clear ()
11613 "Clear the refile cache and disable all the markers."
11614 (dolist (m org-refile-markers) (move-marker m nil))
11615 (setq org-refile-markers nil)
11616 (setq org-refile-cache nil)
11617 (message "Refile cache has been cleared"))
11619 (defun org-refile-cache-check-set (set)
11620 "Check if all the markers in the cache still have live buffers."
11621 (let (marker)
11622 (catch 'exit
11623 (while (and set (setq marker (nth 3 (pop set))))
11624 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11625 (when (and marker (null (marker-buffer marker)))
11626 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11627 (sit-for 3)
11628 (throw 'exit nil)))
11629 t)))
11631 (defun org-refile-cache-put (set &rest identifiers)
11632 "Push the refile targets SET into the cache, under IDENTIFIERS."
11633 (let* ((key (sha1 (prin1-to-string identifiers)))
11634 (entry (assoc key org-refile-cache)))
11635 (if entry
11636 (setcdr entry set)
11637 (push (cons key set) org-refile-cache))))
11639 (defun org-refile-cache-get (&rest identifiers)
11640 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11641 (cond
11642 ((not org-refile-cache) nil)
11643 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11645 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11646 org-refile-cache))))
11647 (and set (org-refile-cache-check-set set) set)))))
11649 (defvar org-outline-path-cache nil
11650 "Alist between buffer positions and outline paths.
11651 It value is an alist (POSITION . PATH) where POSITION is the
11652 buffer position at the beginning of an entry and PATH is a list
11653 of strings describing the outline path for that entry, in reverse
11654 order.")
11656 (defun org-refile-get-targets (&optional default-buffer)
11657 "Produce a table with refile targets."
11658 (let ((case-fold-search nil)
11659 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11660 (entries (or org-refile-targets '((nil . (:level . 1)))))
11661 targets tgs files desc descre)
11662 (message "Getting targets...")
11663 (with-current-buffer (or default-buffer (current-buffer))
11664 (dolist (entry entries)
11665 (setq files (car entry) desc (cdr entry))
11666 (cond
11667 ((null files) (setq files (list (current-buffer))))
11668 ((eq files 'org-agenda-files)
11669 (setq files (org-agenda-files 'unrestricted)))
11670 ((and (symbolp files) (fboundp files))
11671 (setq files (funcall files)))
11672 ((and (symbolp files) (boundp files))
11673 (setq files (symbol-value files))))
11674 (when (stringp files) (setq files (list files)))
11675 (cond
11676 ((eq (car desc) :tag)
11677 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11678 ((eq (car desc) :todo)
11679 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11680 ((eq (car desc) :regexp)
11681 (setq descre (cdr desc)))
11682 ((eq (car desc) :level)
11683 (setq descre (concat "^\\*\\{" (number-to-string
11684 (if org-odd-levels-only
11685 (1- (* 2 (cdr desc)))
11686 (cdr desc)))
11687 "\\}[ \t]")))
11688 ((eq (car desc) :maxlevel)
11689 (setq descre (concat "^\\*\\{1," (number-to-string
11690 (if org-odd-levels-only
11691 (1- (* 2 (cdr desc)))
11692 (cdr desc)))
11693 "\\}[ \t]")))
11694 (t (error "Bad refiling target description %s" desc)))
11695 (dolist (f files)
11696 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11698 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11699 (progn
11700 (when (bufferp f)
11701 (setq f (buffer-file-name (buffer-base-buffer f))))
11702 (setq f (and f (expand-file-name f)))
11703 (when (eq org-refile-use-outline-path 'file)
11704 (push (list (file-name-nondirectory f) f nil nil) tgs))
11705 (org-with-wide-buffer
11706 (goto-char (point-min))
11707 (setq org-outline-path-cache nil)
11708 (while (re-search-forward descre nil t)
11709 (beginning-of-line)
11710 (looking-at org-complex-heading-regexp)
11711 (let ((begin (point))
11712 (heading (match-string-no-properties 4)))
11713 (unless (or (and
11714 org-refile-target-verify-function
11715 (not
11716 (funcall org-refile-target-verify-function)))
11717 (not heading))
11718 (let ((re (format org-complex-heading-regexp-format
11719 (regexp-quote heading)))
11720 (target
11721 (if (not org-refile-use-outline-path) heading
11722 (mapconcat
11723 #'org-protect-slash
11724 (append
11725 (pcase org-refile-use-outline-path
11726 (`file (list (file-name-nondirectory
11727 (buffer-file-name
11728 (buffer-base-buffer)))))
11729 (`full-file-path
11730 (list (buffer-file-name
11731 (buffer-base-buffer))))
11732 (_ nil))
11733 (org-get-outline-path t t))
11734 "/"))))
11735 (push (list target f re (org-refile-marker (point)))
11736 tgs)))
11737 (when (= (point) begin)
11738 ;; Verification function has not moved point.
11739 (end-of-line)))))))
11740 (when org-refile-use-cache
11741 (org-refile-cache-put tgs (buffer-file-name) descre))
11742 (setq targets (append tgs targets))))))
11743 (message "Getting targets...done")
11744 (nreverse targets)))
11746 (defun org-protect-slash (s)
11747 (replace-regexp-in-string "/" "\\/" s nil t))
11749 (defun org--get-outline-path-1 (&optional use-cache)
11750 "Return outline path to current headline.
11752 Outline path is a list of strings, in reverse order. When
11753 optional argument USE-CACHE is non-nil, make use of a cache. See
11754 `org-get-outline-path' for details.
11756 Assume buffer is widened and point is on a headline."
11757 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11758 (let ((p (point))
11759 (heading (progn
11760 (looking-at org-complex-heading-regexp)
11761 (if (not (match-end 4)) ""
11762 ;; Remove statistics cookies.
11763 (org-trim
11764 (org-link-display-format
11765 (replace-regexp-in-string
11766 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11767 (match-string-no-properties 4))))))))
11768 (if (org-up-heading-safe)
11769 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11770 (when use-cache
11771 (push (cons p path) org-outline-path-cache))
11772 path)
11773 ;; This is a new root node. Since we assume we are moving
11774 ;; forward, we can drop previous cache so as to limit number
11775 ;; of associations there.
11776 (let ((path (list heading)))
11777 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11778 path)))))
11780 (defun org-get-outline-path (&optional with-self use-cache)
11781 "Return the outline path to the current entry.
11783 An outline path is a list of ancestors for current headline, as
11784 a list of strings. Statistics cookies are removed and links are
11785 replaced with their description, if any, or their path otherwise.
11787 When optional argument WITH-SELF is non-nil, the path also
11788 includes the current headline.
11790 When optional argument USE-CACHE is non-nil, cache outline paths
11791 between calls to this function so as to avoid backtracking. This
11792 argument is useful when planning to find more than one outline
11793 path in the same document. In that case, there are two
11794 conditions to satisfy:
11795 - `org-outline-path-cache' is set to nil before starting the
11796 process;
11797 - outline paths are computed by increasing buffer positions."
11798 (org-with-wide-buffer
11799 (and (or (and with-self (org-back-to-heading t))
11800 (org-up-heading-safe))
11801 (reverse (org--get-outline-path-1 use-cache)))))
11803 (defun org-format-outline-path (path &optional width prefix separator)
11804 "Format the outline path PATH for display.
11805 WIDTH is the maximum number of characters that is available.
11806 PREFIX is a prefix to be included in the returned string,
11807 such as the file name.
11808 SEPARATOR is inserted between the different parts of the path,
11809 the default is \"/\"."
11810 (setq width (or width 79))
11811 (setq path (delq nil path))
11812 (unless (> width 0)
11813 (user-error "Argument `width' must be positive"))
11814 (setq separator (or separator "/"))
11815 (let* ((org-odd-levels-only nil)
11816 (fpath (concat
11817 prefix (and prefix path separator)
11818 (mapconcat
11819 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11820 (cl-loop for head in path
11821 for n from 0
11822 collect (org-add-props
11823 head nil 'face
11824 (nth (% n org-n-level-faces) org-level-faces)))
11825 separator))))
11826 (when (> (length fpath) width)
11827 (if (< width 7)
11828 ;; It's unlikely that `width' will be this small, but don't
11829 ;; waste characters by adding ".." if it is.
11830 (setq fpath (substring fpath 0 width))
11831 (setf (substring fpath (- width 2)) "..")))
11832 fpath))
11834 (defun org-display-outline-path (&optional file current separator just-return-string)
11835 "Display the current outline path in the echo area.
11837 If FILE is non-nil, prepend the output with the file name.
11838 If CURRENT is non-nil, append the current heading to the output.
11839 SEPARATOR is passed through to `org-format-outline-path'. It separates
11840 the different parts of the path and defaults to \"/\".
11841 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11842 (interactive "P")
11843 (let* (case-fold-search
11844 (bfn (buffer-file-name (buffer-base-buffer)))
11845 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11846 res)
11847 (when current (setq path (append path
11848 (save-excursion
11849 (org-back-to-heading t)
11850 (when (looking-at org-complex-heading-regexp)
11851 (list (match-string 4)))))))
11852 (setq res
11853 (org-format-outline-path
11854 path
11855 (1- (frame-width))
11856 (and file bfn (concat (file-name-nondirectory bfn) separator))
11857 separator))
11858 (if just-return-string
11859 (org-no-properties res)
11860 (org-unlogged-message "%s" res))))
11862 (defvar org-refile-history nil
11863 "History for refiling operations.")
11865 (defvar org-after-refile-insert-hook nil
11866 "Hook run after `org-refile' has inserted its stuff at the new location.
11867 Note that this is still *before* the stuff will be removed from
11868 the *old* location.")
11870 (defvar org-capture-last-stored-marker)
11871 (defvar org-refile-keep nil
11872 "Non-nil means `org-refile' will copy instead of refile.")
11874 (defun org-copy ()
11875 "Like `org-refile', but copy."
11876 (interactive)
11877 (let ((org-refile-keep t))
11878 (funcall 'org-refile nil nil nil "Copy")))
11880 (defun org-refile (&optional arg default-buffer rfloc msg)
11881 "Move the entry or entries at point to another heading.
11882 The list of target headings is compiled using the information in
11883 `org-refile-targets', which see.
11885 At the target location, the entry is filed as a subitem of the
11886 target heading. Depending on `org-reverse-note-order', the new
11887 subitem will either be the first or the last subitem.
11889 If there is an active region, all entries in that region will be
11890 refiled. However, the region must fulfill the requirement that
11891 the first heading sets the top-level of the moved text.
11893 With prefix arg ARG, the command will only visit the target
11894 location and not actually move anything.
11896 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11897 refiling operation has put the subtree.
11899 With a numeric prefix argument of `2', refile to the running clock.
11901 With a numeric prefix argument of `3', emulate `org-refile-keep'
11902 being set to t and copy to the target location, don't move it.
11903 Beware that keeping refiled entries may result in duplicated ID
11904 properties.
11906 RFLOC can be a refile location obtained in a different way.
11908 MSG is a string to replace \"Refile\" in the default prompt with
11909 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11911 See also `org-refile-use-outline-path'.
11913 If you are using target caching (see `org-refile-use-cache'), you
11914 have to clear the target cache in order to find new targets.
11915 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11916 prefix argument (`C-u C-u C-u C-c C-w')."
11917 (interactive "P")
11918 (if (member arg '(0 (64)))
11919 (org-refile-cache-clear)
11920 (let* ((actionmsg (cond (msg msg)
11921 ((equal arg 3) "Refile (and keep)")
11922 (t "Refile")))
11923 (regionp (org-region-active-p))
11924 (region-start (and regionp (region-beginning)))
11925 (region-end (and regionp (region-end)))
11926 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11927 pos it nbuf file level reversed)
11928 (setq last-command nil)
11929 (when regionp
11930 (goto-char region-start)
11931 (or (bolp) (goto-char (point-at-bol)))
11932 (setq region-start (point))
11933 (unless (or (org-kill-is-subtree-p
11934 (buffer-substring region-start region-end))
11935 (prog1 org-refile-active-region-within-subtree
11936 (let ((s (point-at-eol)))
11937 (org-toggle-heading)
11938 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11939 (user-error "The region is not a (sequence of) subtree(s)")))
11940 (if (equal arg '(16))
11941 (org-refile-goto-last-stored)
11942 (when (or
11943 (and (equal arg 2)
11944 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11945 (prog1
11946 (setq it (list (or org-clock-heading "running clock")
11947 (buffer-file-name
11948 (marker-buffer org-clock-hd-marker))
11950 (marker-position org-clock-hd-marker)))
11951 (setq arg nil)))
11952 (setq it
11953 (or rfloc
11954 (let (heading-text)
11955 (save-excursion
11956 (unless (and arg (listp arg))
11957 (org-back-to-heading t)
11958 (setq heading-text
11959 (replace-regexp-in-string
11960 org-bracket-link-regexp
11961 "\\3"
11962 (or (nth 4 (org-heading-components))
11963 ""))))
11964 (org-refile-get-location
11965 (cond ((and arg (listp arg)) "Goto")
11966 (regionp (concat actionmsg " region to"))
11967 (t (concat actionmsg " subtree \""
11968 heading-text "\" to")))
11969 default-buffer
11970 (and (not (equal '(4) arg))
11971 org-refile-allow-creating-parent-nodes)))))))
11972 (setq file (nth 1 it)
11973 pos (nth 3 it))
11974 (when (and (not arg)
11976 (equal (buffer-file-name) file)
11977 (if regionp
11978 (and (>= pos region-start)
11979 (<= pos region-end))
11980 (and (>= pos (point))
11981 (< pos (save-excursion
11982 (org-end-of-subtree t t))))))
11983 (error "Cannot refile to position inside the tree or region"))
11984 (setq nbuf (or (find-buffer-visiting file)
11985 (find-file-noselect file)))
11986 (if (and arg (not (equal arg 3)))
11987 (progn
11988 (pop-to-buffer-same-window nbuf)
11989 (goto-char pos)
11990 (org-show-context 'org-goto))
11991 (if regionp
11992 (progn
11993 (org-kill-new (buffer-substring region-start region-end))
11994 (org-save-markers-in-region region-start region-end))
11995 (org-copy-subtree 1 nil t))
11996 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11997 (find-file-noselect file)))
11998 (setq reversed (org-notes-order-reversed-p))
11999 (org-with-wide-buffer
12000 (if pos
12001 (progn
12002 (goto-char pos)
12003 (looking-at org-outline-regexp)
12004 (setq level (org-get-valid-level (funcall outline-level) 1))
12005 (goto-char
12006 (if reversed
12007 (or (outline-next-heading) (point-max))
12008 (or (save-excursion (org-get-next-sibling))
12009 (org-end-of-subtree t t)
12010 (point-max)))))
12011 (setq level 1)
12012 (if (not reversed)
12013 (goto-char (point-max))
12014 (goto-char (point-min))
12015 (or (outline-next-heading) (goto-char (point-max)))))
12016 (unless (bolp) (newline))
12017 (org-paste-subtree level nil nil t)
12018 (when org-log-refile
12019 (org-add-log-setup 'refile nil nil org-log-refile)
12020 (unless (eq org-log-refile 'note)
12021 (save-excursion (org-add-log-note))))
12022 (and org-auto-align-tags
12023 (let ((org-loop-over-headlines-in-active-region nil))
12024 (org-set-tags nil t)))
12025 (let ((bookmark-name (plist-get org-bookmark-names-plist
12026 :last-refile)))
12027 (when bookmark-name
12028 (with-demoted-errors
12029 (bookmark-set bookmark-name))))
12030 ;; If we are refiling for capture, make sure that the
12031 ;; last-capture pointers point here
12032 (when (bound-and-true-p org-capture-is-refiling)
12033 (let ((bookmark-name (plist-get org-bookmark-names-plist
12034 :last-capture-marker)))
12035 (when bookmark-name
12036 (with-demoted-errors
12037 (bookmark-set bookmark-name))))
12038 (move-marker org-capture-last-stored-marker (point)))
12039 (when (fboundp 'deactivate-mark) (deactivate-mark))
12040 (run-hooks 'org-after-refile-insert-hook)))
12041 (unless org-refile-keep
12042 (if regionp
12043 (delete-region (point) (+ (point) (- region-end region-start)))
12044 (delete-region
12045 (and (org-back-to-heading t) (point))
12046 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12047 (when (featurep 'org-inlinetask)
12048 (org-inlinetask-remove-END-maybe))
12049 (setq org-markers-to-move nil)
12050 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12052 (defun org-refile-goto-last-stored ()
12053 "Go to the location where the last refile was stored."
12054 (interactive)
12055 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12056 (message "This is the location of the last refile"))
12058 (defun org-refile--get-location (refloc tbl)
12059 "When user refile to REFLOC, find the associated target in TBL.
12060 Also check `org-refile-target-table'."
12061 (car (delq
12063 (mapcar
12064 (lambda (r) (or (assoc r tbl)
12065 (assoc r org-refile-target-table)))
12066 (list (replace-regexp-in-string "/$" "" refloc)
12067 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12069 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12070 "Prompt the user for a refile location, using PROMPT.
12071 PROMPT should not be suffixed with a colon and a space, because
12072 this function appends the default value from
12073 `org-refile-history' automatically, if that is not empty."
12074 (let ((org-refile-targets org-refile-targets)
12075 (org-refile-use-outline-path org-refile-use-outline-path))
12076 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12077 (unless org-refile-target-table
12078 (user-error "No refile targets"))
12079 (let* ((cbuf (current-buffer))
12080 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12081 (cfunc (if (and org-refile-use-outline-path
12082 org-outline-path-complete-in-steps)
12083 #'org-olpath-completing-read
12084 #'completing-read))
12085 (extra (if org-refile-use-outline-path "/" ""))
12086 (cbnex (concat (buffer-name) extra))
12087 (filename (and cfn (expand-file-name cfn)))
12088 (tbl (mapcar
12089 (lambda (x)
12090 (if (and (not (member org-refile-use-outline-path
12091 '(file full-file-path)))
12092 (not (equal filename (nth 1 x))))
12093 (cons (concat (car x) extra " ("
12094 (file-name-nondirectory (nth 1 x)) ")")
12095 (cdr x))
12096 (cons (concat (car x) extra) (cdr x))))
12097 org-refile-target-table))
12098 (completion-ignore-case t)
12099 cdef
12100 (prompt (concat prompt
12101 (or (and (car org-refile-history)
12102 (concat " (default " (car org-refile-history) ")"))
12103 (and (assoc cbnex tbl) (setq cdef cbnex)
12104 (concat " (default " cbnex ")"))) ": "))
12105 pa answ parent-target child parent old-hist)
12106 (setq old-hist org-refile-history)
12107 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12108 nil 'org-refile-history (or cdef (car org-refile-history))))
12109 (if (setq pa (org-refile--get-location answ tbl))
12110 (progn
12111 (org-refile-check-position pa)
12112 (when (or (not org-refile-history)
12113 (not (eq old-hist org-refile-history))
12114 (not (equal (car pa) (car org-refile-history))))
12115 (setq org-refile-history
12116 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12117 org-refile-history
12118 (cdr org-refile-history))))
12119 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12120 (pop org-refile-history)))
12122 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12123 (progn
12124 (setq parent (match-string 1 answ)
12125 child (match-string 2 answ))
12126 (setq parent-target (org-refile--get-location parent tbl))
12127 (when (and parent-target
12128 (or (eq new-nodes t)
12129 (and (eq new-nodes 'confirm)
12130 (y-or-n-p (format "Create new node \"%s\"? "
12131 child)))))
12132 (org-refile-new-child parent-target child)))
12133 (user-error "Invalid target location")))))
12135 (declare-function org-string-nw-p "org-macs" (s))
12136 (defun org-refile-check-position (refile-pointer)
12137 "Check if the refile pointer matches the headline to which it points."
12138 (let* ((file (nth 1 refile-pointer))
12139 (re (nth 2 refile-pointer))
12140 (pos (nth 3 refile-pointer))
12141 buffer)
12142 (if (and (not (markerp pos)) (not file))
12143 (user-error "Please indicate a target file in the refile path")
12144 (when (org-string-nw-p re)
12145 (setq buffer (if (markerp pos)
12146 (marker-buffer pos)
12147 (or (find-buffer-visiting file)
12148 (find-file-noselect file))))
12149 (with-current-buffer buffer
12150 (org-with-wide-buffer
12151 (goto-char pos)
12152 (beginning-of-line 1)
12153 (unless (looking-at-p re)
12154 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12156 (defun org-refile-new-child (parent-target child)
12157 "Use refile target PARENT-TARGET to add new CHILD below it."
12158 (unless parent-target
12159 (error "Cannot find parent for new node"))
12160 (let ((file (nth 1 parent-target))
12161 (pos (nth 3 parent-target))
12162 level)
12163 (with-current-buffer (or (find-buffer-visiting file)
12164 (find-file-noselect file))
12165 (org-with-wide-buffer
12166 (if pos
12167 (goto-char pos)
12168 (goto-char (point-max))
12169 (unless (bolp) (newline)))
12170 (when (looking-at org-outline-regexp)
12171 (setq level (funcall outline-level))
12172 (org-end-of-subtree t t))
12173 (org-back-over-empty-lines)
12174 (insert "\n" (make-string
12175 (if pos (org-get-valid-level level 1) 1) ?*)
12176 " " child "\n")
12177 (beginning-of-line 0)
12178 (list (concat (car parent-target) "/" child) file "" (point))))))
12180 (defun org-olpath-completing-read (prompt collection &rest args)
12181 "Read an outline path like a file name."
12182 (let ((thetable collection))
12183 (apply #'completing-read
12184 prompt
12185 (lambda (string predicate &optional flag)
12186 (cond
12187 ((eq flag nil) (try-completion string thetable))
12188 ((eq flag t)
12189 (let ((l (length string)))
12190 (mapcar (lambda (x)
12191 (let ((r (substring x l))
12192 (f (if (string-match " ([^)]*)$" x)
12193 (match-string 0 x)
12194 "")))
12195 (if (string-match "/" r)
12196 (concat string (substring r 0 (match-end 0)) f)
12197 x)))
12198 (all-completions string thetable predicate))))
12199 ;; Exact match?
12200 ((eq flag 'lambda) (assoc string thetable))))
12201 args)))
12203 ;;;; Dynamic blocks
12205 (defun org-find-dblock (name)
12206 "Find the first dynamic block with name NAME in the buffer.
12207 If not found, stay at current position and return nil."
12208 (let ((case-fold-search t) pos)
12209 (save-excursion
12210 (goto-char (point-min))
12211 (setq pos (and (re-search-forward
12212 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12213 (match-beginning 0))))
12214 (when pos (goto-char pos))
12215 pos))
12217 (defun org-create-dblock (plist)
12218 "Create a dynamic block section, with parameters taken from PLIST.
12219 PLIST must contain a :name entry which is used as the name of the block."
12220 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12221 (end-of-line 1)
12222 (newline))
12223 (let ((col (current-column))
12224 (name (plist-get plist :name)))
12225 (insert "#+BEGIN: " name)
12226 (while plist
12227 (if (eq (car plist) :name)
12228 (setq plist (cddr plist))
12229 (insert " " (prin1-to-string (pop plist)))))
12230 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12231 (beginning-of-line -2)))
12233 (defun org-prepare-dblock ()
12234 "Prepare dynamic block for refresh.
12235 This empties the block, puts the cursor at the insert position and returns
12236 the property list including an extra property :name with the block name."
12237 (unless (looking-at org-dblock-start-re)
12238 (user-error "Not at a dynamic block"))
12239 (let* ((begdel (1+ (match-end 0)))
12240 (name (org-no-properties (match-string 1)))
12241 (params (append (list :name name)
12242 (read (concat "(" (match-string 3) ")")))))
12243 (save-excursion
12244 (beginning-of-line 1)
12245 (skip-chars-forward " \t")
12246 (setq params (plist-put params :indentation-column (current-column))))
12247 (unless (re-search-forward org-dblock-end-re nil t)
12248 (error "Dynamic block not terminated"))
12249 (setq params
12250 (append params
12251 (list :content (buffer-substring
12252 begdel (match-beginning 0)))))
12253 (delete-region begdel (match-beginning 0))
12254 (goto-char begdel)
12255 (open-line 1)
12256 params))
12258 (defun org-map-dblocks (&optional command)
12259 "Apply COMMAND to all dynamic blocks in the current buffer.
12260 If COMMAND is not given, use `org-update-dblock'."
12261 (let ((cmd (or command 'org-update-dblock)))
12262 (save-excursion
12263 (goto-char (point-min))
12264 (while (re-search-forward org-dblock-start-re nil t)
12265 (goto-char (match-beginning 0))
12266 (save-excursion
12267 (condition-case nil
12268 (funcall cmd)
12269 (error (message "Error during update of dynamic block"))))
12270 (unless (re-search-forward org-dblock-end-re nil t)
12271 (error "Dynamic block not terminated"))))))
12273 (defun org-dblock-update (&optional arg)
12274 "User command for updating dynamic blocks.
12275 Update the dynamic block at point. With prefix ARG, update all dynamic
12276 blocks in the buffer."
12277 (interactive "P")
12278 (if arg
12279 (org-update-all-dblocks)
12280 (or (looking-at org-dblock-start-re)
12281 (org-beginning-of-dblock))
12282 (org-update-dblock)))
12284 (defun org-update-dblock ()
12285 "Update the dynamic block at point.
12286 This means to empty the block, parse for parameters and then call
12287 the correct writing function."
12288 (interactive)
12289 (save-excursion
12290 (let* ((win (selected-window))
12291 (pos (point))
12292 (line (org-current-line))
12293 (params (org-prepare-dblock))
12294 (name (plist-get params :name))
12295 (indent (plist-get params :indentation-column))
12296 (cmd (intern (concat "org-dblock-write:" name))))
12297 (message "Updating dynamic block `%s' at line %d..." name line)
12298 (funcall cmd params)
12299 (message "Updating dynamic block `%s' at line %d...done" name line)
12300 (goto-char pos)
12301 (when (and indent (> indent 0))
12302 (setq indent (make-string indent ?\ ))
12303 (save-excursion
12304 (select-window win)
12305 (org-beginning-of-dblock)
12306 (forward-line 1)
12307 (while (not (looking-at org-dblock-end-re))
12308 (insert indent)
12309 (beginning-of-line 2))
12310 (when (looking-at org-dblock-end-re)
12311 (and (looking-at "[ \t]+")
12312 (replace-match ""))
12313 (insert indent)))))))
12315 (defun org-beginning-of-dblock ()
12316 "Find the beginning of the dynamic block at point.
12317 Error if there is no such block at point."
12318 (let ((pos (point))
12319 beg)
12320 (end-of-line 1)
12321 (if (and (re-search-backward org-dblock-start-re nil t)
12322 (setq beg (match-beginning 0))
12323 (re-search-forward org-dblock-end-re nil t)
12324 (> (match-end 0) pos))
12325 (goto-char beg)
12326 (goto-char pos)
12327 (error "Not in a dynamic block"))))
12329 (defun org-update-all-dblocks ()
12330 "Update all dynamic blocks in the buffer.
12331 This function can be used in a hook."
12332 (interactive)
12333 (when (derived-mode-p 'org-mode)
12334 (org-map-dblocks 'org-update-dblock)))
12337 ;;;; Completion
12339 (declare-function org-export-backend-options "ox" (cl-x) t)
12340 (defun org-get-export-keywords ()
12341 "Return a list of all currently understood export keywords.
12342 Export keywords include options, block names, attributes and
12343 keywords relative to each registered export back-end."
12344 (let (keywords)
12345 (dolist (backend
12346 (bound-and-true-p org-export-registered-backends)
12347 (delq nil keywords))
12348 ;; Back-end name (for keywords, like #+LATEX:)
12349 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12350 (dolist (option-entry (org-export-backend-options backend))
12351 ;; Back-end options.
12352 (push (nth 1 option-entry) keywords)))))
12354 (defconst org-options-keywords
12355 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12356 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12357 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12358 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12359 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12361 (defcustom org-structure-template-alist
12362 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12363 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12364 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12365 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12366 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12367 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12368 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12369 ("L" "#+LaTeX: ")
12370 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12371 ("H" "#+HTML: ")
12372 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12373 ("A" "#+ASCII: ")
12374 ("i" "#+INDEX: ?")
12375 ("I" "#+INCLUDE: %file ?"))
12376 "Structure completion elements.
12377 This is a list of abbreviation keys and values. The value gets inserted
12378 if you type `<' followed by the key and then press the completion key,
12379 usually `TAB'. %file will be replaced by a file name after prompting
12380 for the file using completion. The cursor will be placed at the position
12381 of the `?' in the template.
12382 There are two templates for each key, the first uses the original Org syntax,
12383 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12384 the default when the /org-mtags.el/ module has been loaded. See also the
12385 variable `org-mtags-prefer-muse-templates'."
12386 :group 'org-completion
12387 :type '(repeat
12388 (list
12389 (string :tag "Key")
12390 (string :tag "Template")))
12391 :version "25.1"
12392 :package-version '(Org . "8.3"))
12394 (defun org-try-structure-completion ()
12395 "Try to complete a structure template before point.
12396 This looks for strings like \"<e\" on an otherwise empty line and
12397 expands them."
12398 (let ((l (buffer-substring (point-at-bol) (point)))
12400 (when (and (looking-at "[ \t]*$")
12401 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12402 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12403 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12404 (match-beginning 1)) a)
12405 t)))
12407 (defun org-complete-expand-structure-template (start cell)
12408 "Expand a structure template."
12409 (let ((rpl (nth 1 cell))
12410 (ind ""))
12411 (delete-region start (point))
12412 (when (string-match "\\`[ \t]*#\\+" rpl)
12413 (cond
12414 ((bolp))
12415 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12416 (setq ind (buffer-substring (point-at-bol) (point))))
12417 (t (newline))))
12418 (setq start (point))
12419 (when (string-match "%file" rpl)
12420 (setq rpl (replace-match
12421 (concat
12422 "\""
12423 (save-match-data
12424 (abbreviate-file-name (read-file-name "Include file: ")))
12425 "\"")
12426 t t rpl)))
12427 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12428 (concat "\n" ind)))
12429 (insert rpl)
12430 (when (re-search-backward "\\?" start t) (delete-char 1))))
12432 ;;;; TODO, DEADLINE, Comments
12434 (defun org-toggle-comment ()
12435 "Change the COMMENT state of an entry."
12436 (interactive)
12437 (save-excursion
12438 (org-back-to-heading)
12439 (looking-at org-complex-heading-regexp)
12440 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12441 (skip-chars-forward " \t")
12442 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12443 (if (org-in-commented-heading-p t)
12444 (delete-region (point)
12445 (progn (search-forward " " (line-end-position) 'move)
12446 (skip-chars-forward " \t")
12447 (point)))
12448 (insert org-comment-string)
12449 (unless (eolp) (insert " ")))))
12451 (defvar org-last-todo-state-is-todo nil
12452 "This is non-nil when the last TODO state change led to a TODO state.
12453 If the last change removed the TODO tag or switched to DONE, then
12454 this is nil.")
12456 (defvar org-setting-tags nil) ; dynamically skipped
12458 (defvar org-todo-setup-filter-hook nil
12459 "Hook for functions that pre-filter todo specs.
12460 Each function takes a todo spec and returns either nil or the spec
12461 transformed into canonical form." )
12463 (defvar org-todo-get-default-hook nil
12464 "Hook for functions that get a default item for todo.
12465 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12466 nil or a string to be used for the todo mark." )
12468 (defvar org-agenda-headline-snapshot-before-repeat)
12470 (defun org-current-effective-time ()
12471 "Return current time adjusted for `org-extend-today-until' variable."
12472 (let* ((ct (org-current-time))
12473 (dct (decode-time ct))
12474 (ct1
12475 (cond
12476 (org-use-last-clock-out-time-as-effective-time
12477 (or (org-clock-get-last-clock-out-time) ct))
12478 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12479 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12480 (t ct))))
12481 ct1))
12483 (defun org-todo-yesterday (&optional arg)
12484 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12485 (interactive "P")
12486 (if (eq major-mode 'org-agenda-mode)
12487 (apply 'org-agenda-todo-yesterday arg)
12488 (let* ((org-use-effective-time t)
12489 (hour (nth 2 (decode-time (org-current-time))))
12490 (org-extend-today-until (1+ hour)))
12491 (org-todo arg))))
12493 (defvar org-block-entry-blocking ""
12494 "First entry preventing the TODO state change.")
12496 (defun org-cancel-repeater ()
12497 "Cancel a repeater by setting its numeric value to zero."
12498 (interactive)
12499 (save-excursion
12500 (org-back-to-heading t)
12501 (let ((bound1 (point))
12502 (bound0 (save-excursion (outline-next-heading) (point))))
12503 (when (and (re-search-forward
12504 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12505 org-deadline-time-regexp "\\)\\|\\("
12506 org-ts-regexp "\\)")
12507 bound0 t)
12508 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12509 bound1 t))
12510 (replace-match "0" t nil nil 1)))))
12512 (defvar org-state) ;; dynamically scoped into this function
12513 (defun org-todo (&optional arg)
12514 "Change the TODO state of an item.
12515 The state of an item is given by a keyword at the start of the heading,
12516 like
12517 *** TODO Write paper
12518 *** DONE Call mom
12520 The different keywords are specified in the variable `org-todo-keywords'.
12521 By default the available states are \"TODO\" and \"DONE\".
12522 So for this example: when the item starts with TODO, it is changed to DONE.
12523 When it starts with DONE, the DONE is removed. And when neither TODO nor
12524 DONE are present, add TODO at the beginning of the heading.
12526 With \\[universal-argument] prefix arg, use completion to determine the new \
12527 state.
12528 With numeric prefix arg, switch to that state.
12529 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12530 keywords (nextset).
12531 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12532 With a numeric prefix arg of 0, inhibit note taking for the change.
12533 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12535 When called through ELisp, arg is also interpreted in the following way:
12536 `none' -> empty state
12537 \"\"(empty string) -> switch to empty state
12538 `done' -> switch to DONE
12539 `nextset' -> switch to the next set of keywords
12540 `previousset' -> switch to the previous set of keywords
12541 \"WAITING\" -> switch to the specified keyword, but only if it
12542 really is a member of `org-todo-keywords'."
12543 (interactive "P")
12544 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12545 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12546 'region-start-level 'region))
12547 org-loop-over-headlines-in-active-region)
12548 (org-map-entries
12549 `(org-todo ,arg)
12550 org-loop-over-headlines-in-active-region
12551 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12552 (when (equal arg '(16)) (setq arg 'nextset))
12553 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12554 (let ((org-blocker-hook org-blocker-hook)
12555 commentp
12556 case-fold-search)
12557 (when (equal arg '(64))
12558 (setq arg nil org-blocker-hook nil))
12559 (when (and org-blocker-hook
12560 (or org-inhibit-blocking
12561 (org-entry-get nil "NOBLOCKING")))
12562 (setq org-blocker-hook nil))
12563 (save-excursion
12564 (catch 'exit
12565 (org-back-to-heading t)
12566 (when (org-in-commented-heading-p t)
12567 (org-toggle-comment)
12568 (setq commentp t))
12569 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12570 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12571 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12572 (let* ((match-data (match-data))
12573 (startpos (point-at-bol))
12574 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12575 (org-log-done org-log-done)
12576 (org-log-repeat org-log-repeat)
12577 (org-todo-log-states org-todo-log-states)
12578 (org-inhibit-logging
12579 (if (equal arg 0)
12580 (progn (setq arg nil) 'note) org-inhibit-logging))
12581 (this (match-string 1))
12582 (hl-pos (match-beginning 0))
12583 (head (org-get-todo-sequence-head this))
12584 (ass (assoc head org-todo-kwd-alist))
12585 (interpret (nth 1 ass))
12586 (done-word (nth 3 ass))
12587 (final-done-word (nth 4 ass))
12588 (org-last-state (or this ""))
12589 (completion-ignore-case t)
12590 (member (member this org-todo-keywords-1))
12591 (tail (cdr member))
12592 (org-state (cond
12593 ((and org-todo-key-trigger
12594 (or (and (equal arg '(4))
12595 (eq org-use-fast-todo-selection 'prefix))
12596 (and (not arg) org-use-fast-todo-selection
12597 (not (eq org-use-fast-todo-selection
12598 'prefix)))))
12599 ;; Use fast selection
12600 (org-fast-todo-selection))
12601 ((and (equal arg '(4))
12602 (or (not org-use-fast-todo-selection)
12603 (not org-todo-key-trigger)))
12604 ;; Read a state with completion
12605 (completing-read
12606 "State: " (mapcar #'list org-todo-keywords-1)
12607 nil t))
12608 ((eq arg 'right)
12609 (if this
12610 (if tail (car tail) nil)
12611 (car org-todo-keywords-1)))
12612 ((eq arg 'left)
12613 (unless (equal member org-todo-keywords-1)
12614 (if this
12615 (nth (- (length org-todo-keywords-1)
12616 (length tail) 2)
12617 org-todo-keywords-1)
12618 (org-last org-todo-keywords-1))))
12619 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12620 (setq arg nil))) ; hack to fall back to cycling
12621 (arg
12622 ;; user or caller requests a specific state
12623 (cond
12624 ((equal arg "") nil)
12625 ((eq arg 'none) nil)
12626 ((eq arg 'done) (or done-word (car org-done-keywords)))
12627 ((eq arg 'nextset)
12628 (or (car (cdr (member head org-todo-heads)))
12629 (car org-todo-heads)))
12630 ((eq arg 'previousset)
12631 (let ((org-todo-heads (reverse org-todo-heads)))
12632 (or (car (cdr (member head org-todo-heads)))
12633 (car org-todo-heads))))
12634 ((car (member arg org-todo-keywords-1)))
12635 ((stringp arg)
12636 (user-error "State `%s' not valid in this file" arg))
12637 ((nth (1- (prefix-numeric-value arg))
12638 org-todo-keywords-1))))
12639 ((null member) (or head (car org-todo-keywords-1)))
12640 ((equal this final-done-word) nil) ;; -> make empty
12641 ((null tail) nil) ;; -> first entry
12642 ((memq interpret '(type priority))
12643 (if (eq this-command last-command)
12644 (car tail)
12645 (if (> (length tail) 0)
12646 (or done-word (car org-done-keywords))
12647 nil)))
12649 (car tail))))
12650 (org-state (or
12651 (run-hook-with-args-until-success
12652 'org-todo-get-default-hook org-state org-last-state)
12653 org-state))
12654 (next (if org-state (concat " " org-state " ") " "))
12655 (change-plist (list :type 'todo-state-change :from this :to org-state
12656 :position startpos))
12657 dolog now-done-p)
12658 (when org-blocker-hook
12659 (setq org-last-todo-state-is-todo
12660 (not (member this org-done-keywords)))
12661 (unless (save-excursion
12662 (save-match-data
12663 (org-with-wide-buffer
12664 (run-hook-with-args-until-failure
12665 'org-blocker-hook change-plist))))
12666 (if (called-interactively-p 'interactive)
12667 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12668 this org-state org-block-entry-blocking)
12669 ;; fail silently
12670 (message "TODO state change from %s to %s blocked (by \"%s\")"
12671 this org-state org-block-entry-blocking)
12672 (throw 'exit nil))))
12673 (store-match-data match-data)
12674 (replace-match next t t)
12675 (cond ((equal this org-state)
12676 (message "TODO state was already %s" (org-trim next)))
12677 ((pos-visible-in-window-p hl-pos)
12678 (message "TODO state changed to %s" (org-trim next))))
12679 (unless head
12680 (setq head (org-get-todo-sequence-head org-state)
12681 ass (assoc head org-todo-kwd-alist)
12682 interpret (nth 1 ass)
12683 done-word (nth 3 ass)
12684 final-done-word (nth 4 ass)))
12685 (when (memq arg '(nextset previousset))
12686 (message "Keyword-Set %d/%d: %s"
12687 (- (length org-todo-sets) -1
12688 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12689 (length org-todo-sets)
12690 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12691 (setq org-last-todo-state-is-todo
12692 (not (member org-state org-done-keywords)))
12693 (setq now-done-p (and (member org-state org-done-keywords)
12694 (not (member this org-done-keywords))))
12695 (and logging (org-local-logging logging))
12696 (when (and (or org-todo-log-states org-log-done)
12697 (not (eq org-inhibit-logging t))
12698 (not (memq arg '(nextset previousset))))
12699 ;; we need to look at recording a time and note
12700 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12701 (nth 2 (assoc this org-todo-log-states))))
12702 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12703 (setq dolog 'time))
12704 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12705 (and org-state
12706 (member org-state org-not-done-keywords)
12707 (not (member this org-not-done-keywords))))
12708 ;; This is now a todo state and was not one before
12709 ;; If there was a CLOSED time stamp, get rid of it.
12710 (org-add-planning-info nil nil 'closed))
12711 (when (and now-done-p org-log-done)
12712 ;; It is now done, and it was not done before
12713 (org-add-planning-info 'closed (org-current-effective-time))
12714 (when (and (not dolog) (eq 'note org-log-done))
12715 (org-add-log-setup 'done org-state this 'note)))
12716 (when (and org-state dolog)
12717 ;; This is a non-nil state, and we need to log it
12718 (org-add-log-setup 'state org-state this dolog)))
12719 ;; Fixup tag positioning
12720 (org-todo-trigger-tag-changes org-state)
12721 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12722 (when org-provide-todo-statistics
12723 (org-update-parent-todo-statistics))
12724 (run-hooks 'org-after-todo-state-change-hook)
12725 (when (and arg (not (member org-state org-done-keywords)))
12726 (setq head (org-get-todo-sequence-head org-state)))
12727 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12728 ;; Do we need to trigger a repeat?
12729 (when now-done-p
12730 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12731 ;; This is for the agenda, take a snapshot of the headline.
12732 (save-match-data
12733 (setq org-agenda-headline-snapshot-before-repeat
12734 (org-get-heading))))
12735 (org-auto-repeat-maybe org-state))
12736 ;; Fixup cursor location if close to the keyword
12737 (when (and (outline-on-heading-p)
12738 (not (bolp))
12739 (save-excursion (beginning-of-line 1)
12740 (looking-at org-todo-line-regexp))
12741 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12742 (goto-char (or (match-end 2) (match-end 1)))
12743 (and (looking-at " ") (just-one-space)))
12744 (when org-trigger-hook
12745 (save-excursion
12746 (run-hook-with-args 'org-trigger-hook change-plist)))
12747 (when commentp (org-toggle-comment))))))))
12749 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12750 "Block turning an entry into a TODO, using the hierarchy.
12751 This checks whether the current task should be blocked from state
12752 changes. Such blocking occurs when:
12754 1. The task has children which are not all in a completed state.
12756 2. A task has a parent with the property :ORDERED:, and there
12757 are siblings prior to the current task with incomplete
12758 status.
12760 3. The parent of the task is blocked because it has siblings that should
12761 be done first, or is child of a block grandparent TODO entry."
12763 (if (not org-enforce-todo-dependencies)
12764 t ; if locally turned off don't block
12765 (catch 'dont-block
12766 ;; If this is not a todo state change, or if this entry is already DONE,
12767 ;; do not block
12768 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12769 (member (plist-get change-plist :from)
12770 (cons 'done org-done-keywords))
12771 (member (plist-get change-plist :to)
12772 (cons 'todo org-not-done-keywords))
12773 (not (plist-get change-plist :to)))
12774 (throw 'dont-block t))
12775 ;; If this task has children, and any are undone, it's blocked
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (let ((this-level (funcall outline-level)))
12779 (outline-next-heading)
12780 (let ((child-level (funcall outline-level)))
12781 (while (and (not (eobp))
12782 (> child-level this-level))
12783 ;; this todo has children, check whether they are all
12784 ;; completed
12785 (when (and (not (org-entry-is-done-p))
12786 (org-entry-is-todo-p))
12787 (setq org-block-entry-blocking (org-get-heading))
12788 (throw 'dont-block nil))
12789 (outline-next-heading)
12790 (setq child-level (funcall outline-level))))))
12791 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12792 ;; any previous siblings are undone, it's blocked
12793 (save-excursion
12794 (org-back-to-heading t)
12795 (let* ((pos (point))
12796 (parent-pos (and (org-up-heading-safe) (point))))
12797 (unless parent-pos (throw 'dont-block t)) ; no parent
12798 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12799 (forward-line 1)
12800 (re-search-forward org-not-done-heading-regexp pos t))
12801 (setq org-block-entry-blocking (match-string 0))
12802 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12803 ;; Search further up the hierarchy, to see if an ancestor is blocked
12804 (while t
12805 (goto-char parent-pos)
12806 (unless (looking-at org-not-done-heading-regexp)
12807 (throw 'dont-block t)) ; do not block, parent is not a TODO
12808 (setq pos (point))
12809 (setq parent-pos (and (org-up-heading-safe) (point)))
12810 (unless parent-pos (throw 'dont-block t)) ; no parent
12811 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12812 (forward-line 1)
12813 (re-search-forward org-not-done-heading-regexp pos t)
12814 (setq org-block-entry-blocking (org-get-heading)))
12815 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12817 (defcustom org-track-ordered-property-with-tag nil
12818 "Should the ORDERED property also be shown as a tag?
12819 The ORDERED property decides if an entry should require subtasks to be
12820 completed in sequence. Since a property is not very visible, setting
12821 this option means that toggling the ORDERED property with the command
12822 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12823 not relevant for the behavior, but it makes things more visible.
12825 Note that toggling the tag with tags commands will not change the property
12826 and therefore not influence behavior!
12828 This can be t, meaning the tag ORDERED should be used, It can also be a
12829 string to select a different tag for this task."
12830 :group 'org-todo
12831 :type '(choice
12832 (const :tag "No tracking" nil)
12833 (const :tag "Track with ORDERED tag" t)
12834 (string :tag "Use other tag")))
12836 (defun org-toggle-ordered-property ()
12837 "Toggle the ORDERED property of the current entry.
12838 For better visibility, you can track the value of this property with a tag.
12839 See variable `org-track-ordered-property-with-tag'."
12840 (interactive)
12841 (let* ((t1 org-track-ordered-property-with-tag)
12842 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12843 (save-excursion
12844 (org-back-to-heading)
12845 (if (org-entry-get nil "ORDERED")
12846 (progn
12847 (org-delete-property "ORDERED")
12848 (and tag (org-toggle-tag tag 'off))
12849 (message "Subtasks can be completed in arbitrary order"))
12850 (org-entry-put nil "ORDERED" "t")
12851 (and tag (org-toggle-tag tag 'on))
12852 (message "Subtasks must be completed in sequence")))))
12854 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12855 (defun org-block-todo-from-checkboxes (change-plist)
12856 "Block turning an entry into a TODO, using checkboxes.
12857 This checks whether the current task should be blocked from state
12858 changes because there are unchecked boxes in this entry."
12859 (if (not org-enforce-todo-checkbox-dependencies)
12860 t ; if locally turned off don't block
12861 (catch 'dont-block
12862 ;; If this is not a todo state change, or if this entry is already DONE,
12863 ;; do not block
12864 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12865 (member (plist-get change-plist :from)
12866 (cons 'done org-done-keywords))
12867 (member (plist-get change-plist :to)
12868 (cons 'todo org-not-done-keywords))
12869 (not (plist-get change-plist :to)))
12870 (throw 'dont-block t))
12871 ;; If this task has checkboxes that are not checked, it's blocked
12872 (save-excursion
12873 (org-back-to-heading t)
12874 (let ((beg (point)) end)
12875 (outline-next-heading)
12876 (setq end (point))
12877 (goto-char beg)
12878 (when (org-list-search-forward
12879 (concat (org-item-beginning-re)
12880 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12881 "\\[[- ]\\]")
12882 end t)
12883 (when (boundp 'org-blocked-by-checkboxes)
12884 (setq org-blocked-by-checkboxes t))
12885 (throw 'dont-block nil))))
12886 t))) ; do not block
12888 (defun org-entry-blocked-p ()
12889 "Non-nil if entry at point is blocked."
12890 (and (not (org-entry-get nil "NOBLOCKING"))
12891 (member (org-entry-get nil "TODO") org-not-done-keywords)
12892 (not (run-hook-with-args-until-failure
12893 'org-blocker-hook
12894 (list :type 'todo-state-change
12895 :position (point)
12896 :from 'todo
12897 :to 'done)))))
12899 (defun org-update-statistics-cookies (all)
12900 "Update the statistics cookie, either from TODO or from checkboxes.
12901 This should be called with the cursor in a line with a statistics cookie."
12902 (interactive "P")
12903 (if all
12904 (progn
12905 (org-update-checkbox-count 'all)
12906 (org-map-entries 'org-update-parent-todo-statistics))
12907 (if (not (org-at-heading-p))
12908 (org-update-checkbox-count)
12909 (let ((pos (point-marker))
12910 end l1 l2)
12911 (ignore-errors (org-back-to-heading t))
12912 (if (not (org-at-heading-p))
12913 (org-update-checkbox-count)
12914 (setq l1 (org-outline-level))
12915 (setq end (save-excursion
12916 (outline-next-heading)
12917 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12918 (point)))
12919 (if (and (save-excursion
12920 (re-search-forward
12921 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12922 (not (save-excursion (re-search-forward
12923 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12924 (org-update-checkbox-count)
12925 (if (and l2 (> l2 l1))
12926 (progn
12927 (goto-char end)
12928 (org-update-parent-todo-statistics))
12929 (goto-char pos)
12930 (beginning-of-line 1)
12931 (while (re-search-forward
12932 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12933 (point-at-eol) t)
12934 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12935 (goto-char pos)
12936 (move-marker pos nil)))))
12938 (defvar org-entry-property-inherited-from) ;; defined below
12939 (defun org-update-parent-todo-statistics ()
12940 "Update any statistics cookie in the parent of the current headline.
12941 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12942 the entire subtree and this will travel up the hierarchy and update
12943 statistics everywhere."
12944 (let* ((prop (save-excursion (org-up-heading-safe)
12945 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12946 (recursive (or (not org-hierarchical-todo-statistics)
12947 (and prop (string-match "\\<recursive\\>" prop))))
12948 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12950 (first t)
12951 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12952 level ltoggle l1 new ndel
12953 (cnt-all 0) (cnt-done 0) is-percent kwd
12954 checkbox-beg cookie-present)
12955 (catch 'exit
12956 (save-excursion
12957 (beginning-of-line 1)
12958 (setq ltoggle (funcall outline-level))
12959 ;; Three situations are to consider:
12961 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12962 ;; to the top-level ancestor on the headline;
12964 ;; 2. If parent has "recursive" property, repeat up to the
12965 ;; headline setting that property, taking inheritance into
12966 ;; account;
12968 ;; 3. Else, move up to direct parent and proceed only once.
12969 (while (and (setq level (org-up-heading-safe))
12970 (or recursive first)
12971 (>= (point) lim))
12972 (setq first nil cookie-present nil)
12973 (unless (and level
12974 (not (string-match
12975 "\\<checkbox\\>"
12976 (downcase (or (org-entry-get nil "COOKIE_DATA")
12977 "")))))
12978 (throw 'exit nil))
12979 (while (re-search-forward box-re (point-at-eol) t)
12980 (setq cnt-all 0 cnt-done 0 cookie-present t)
12981 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12982 (save-match-data
12983 (unless (outline-next-heading) (throw 'exit nil))
12984 (while (and (looking-at org-complex-heading-regexp)
12985 (> (setq l1 (length (match-string 1))) level))
12986 (setq kwd (and (or recursive (= l1 ltoggle))
12987 (match-string 2)))
12988 (if (or (eq org-provide-todo-statistics 'all-headlines)
12989 (and (eq org-provide-todo-statistics t)
12990 (or (member kwd org-done-keywords)))
12991 (and (listp org-provide-todo-statistics)
12992 (stringp (car org-provide-todo-statistics))
12993 (or (member kwd org-provide-todo-statistics)
12994 (member kwd org-done-keywords)))
12995 (and (listp org-provide-todo-statistics)
12996 (listp (car org-provide-todo-statistics))
12997 (or (member kwd (car org-provide-todo-statistics))
12998 (and (member kwd org-done-keywords)
12999 (member kwd (cadr org-provide-todo-statistics))))))
13000 (setq cnt-all (1+ cnt-all))
13001 (and (eq org-provide-todo-statistics t)
13003 (setq cnt-all (1+ cnt-all))))
13004 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13005 (member kwd org-done-keywords))
13006 (and (listp org-provide-todo-statistics)
13007 (listp (car org-provide-todo-statistics))
13008 (member kwd org-done-keywords)
13009 (member kwd (cadr org-provide-todo-statistics)))
13010 (and (listp org-provide-todo-statistics)
13011 (stringp (car org-provide-todo-statistics))
13012 (member kwd org-done-keywords)))
13013 (setq cnt-done (1+ cnt-done)))
13014 (outline-next-heading)))
13015 (setq new
13016 (if is-percent
13017 (format "[%d%%]" (floor (* 100.0 cnt-done)
13018 (max 1 cnt-all)))
13019 (format "[%d/%d]" cnt-done cnt-all))
13020 ndel (- (match-end 0) checkbox-beg))
13021 (goto-char checkbox-beg)
13022 (insert new)
13023 (delete-region (point) (+ (point) ndel))
13024 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13025 (when cookie-present
13026 (run-hook-with-args 'org-after-todo-statistics-hook
13027 cnt-done (- cnt-all cnt-done))))))
13028 (run-hooks 'org-todo-statistics-hook)))
13030 (defvar org-after-todo-statistics-hook nil
13031 "Hook that is called after a TODO statistics cookie has been updated.
13032 Each function is called with two arguments: the number of not-done entries
13033 and the number of done entries.
13035 For example, the following function, when added to this hook, will switch
13036 an entry to DONE when all children are done, and back to TODO when new
13037 entries are set to a TODO status. Note that this hook is only called
13038 when there is a statistics cookie in the headline!
13040 \(defun org-summary-todo (n-done n-not-done)
13041 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13042 \(let (org-log-done org-log-states) ; turn off logging
13043 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13046 (defvar org-todo-statistics-hook nil
13047 "Hook that is run whenever Org thinks TODO statistics should be updated.
13048 This hook runs even if there is no statistics cookie present, in which case
13049 `org-after-todo-statistics-hook' would not run.")
13051 (defun org-todo-trigger-tag-changes (state)
13052 "Apply the changes defined in `org-todo-state-tags-triggers'."
13053 (let ((l org-todo-state-tags-triggers)
13054 changes)
13055 (when (or (not state) (equal state ""))
13056 (setq changes (append changes (cdr (assoc "" l)))))
13057 (when (and (stringp state) (> (length state) 0))
13058 (setq changes (append changes (cdr (assoc state l)))))
13059 (when (member state org-not-done-keywords)
13060 (setq changes (append changes (cdr (assoc 'todo l)))))
13061 (when (member state org-done-keywords)
13062 (setq changes (append changes (cdr (assoc 'done l)))))
13063 (dolist (c changes)
13064 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13066 (defun org-local-logging (value)
13067 "Get logging settings from a property VALUE."
13068 ;; Directly set the variables, they are already local.
13069 (setq org-log-done nil
13070 org-log-repeat nil
13071 org-todo-log-states nil)
13072 (dolist (w (org-split-string value))
13073 (let (a)
13074 (cond
13075 ((setq a (assoc w org-startup-options))
13076 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13077 (set (nth 1 a) (nth 2 a))))
13078 ((setq a (org-extract-log-state-settings w))
13079 (and (member (car a) org-todo-keywords-1)
13080 (push a org-todo-log-states)))))))
13082 (defun org-get-todo-sequence-head (kwd)
13083 "Return the head of the TODO sequence to which KWD belongs.
13084 If KWD is not set, check if there is a text property remembering the
13085 right sequence."
13086 (let (p)
13087 (cond
13088 ((not kwd)
13089 (or (get-text-property (point-at-bol) 'org-todo-head)
13090 (progn
13091 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13092 nil (point-at-eol)))
13093 (get-text-property p 'org-todo-head))))
13094 ((not (member kwd org-todo-keywords-1))
13095 (car org-todo-keywords-1))
13096 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13098 (defun org-fast-todo-selection ()
13099 "Fast TODO keyword selection with single keys.
13100 Returns the new TODO keyword, or nil if no state change should occur."
13101 (let* ((fulltable org-todo-key-alist)
13102 (done-keywords org-done-keywords) ;; needed for the faces.
13103 (maxlen (apply 'max (mapcar
13104 (lambda (x)
13105 (if (stringp (car x)) (string-width (car x)) 0))
13106 fulltable)))
13107 (expert nil)
13108 (fwidth (+ maxlen 3 1 3))
13109 (ncol (/ (- (window-width) 4) fwidth))
13110 tg cnt e c tbl
13111 groups ingroup)
13112 (save-excursion
13113 (save-window-excursion
13114 (if expert
13115 (set-buffer (get-buffer-create " *Org todo*"))
13116 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13117 (erase-buffer)
13118 (setq-local org-done-keywords done-keywords)
13119 (setq tbl fulltable cnt 0)
13120 (while (setq e (pop tbl))
13121 (cond
13122 ((equal e '(:startgroup))
13123 (push '() groups) (setq ingroup t)
13124 (unless (= cnt 0)
13125 (setq cnt 0)
13126 (insert "\n"))
13127 (insert "{ "))
13128 ((equal e '(:endgroup))
13129 (setq ingroup nil cnt 0)
13130 (insert "}\n"))
13131 ((equal e '(:newline))
13132 (unless (= cnt 0)
13133 (setq cnt 0)
13134 (insert "\n")
13135 (setq e (car tbl))
13136 (while (equal (car tbl) '(:newline))
13137 (insert "\n")
13138 (setq tbl (cdr tbl)))))
13140 (setq tg (car e) c (cdr e))
13141 (when ingroup (push tg (car groups)))
13142 (setq tg (org-add-props tg nil 'face
13143 (org-get-todo-face tg)))
13144 (when (and (= cnt 0) (not ingroup)) (insert " "))
13145 (insert "[" c "] " tg (make-string
13146 (- fwidth 4 (length tg)) ?\ ))
13147 (when (= (setq cnt (1+ cnt)) ncol)
13148 (insert "\n")
13149 (when ingroup (insert " "))
13150 (setq cnt 0)))))
13151 (insert "\n")
13152 (goto-char (point-min))
13153 (unless expert (org-fit-window-to-buffer))
13154 (message "[a-z..]:Set [SPC]:clear")
13155 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13156 (cond
13157 ((or (= c ?\C-g)
13158 (and (= c ?q) (not (rassoc c fulltable))))
13159 (setq quit-flag t))
13160 ((= c ?\ ) nil)
13161 ((setq e (rassoc c fulltable) tg (car e))
13163 (t (setq quit-flag t)))))))
13165 (defun org-entry-is-todo-p ()
13166 (member (org-get-todo-state) org-not-done-keywords))
13168 (defun org-entry-is-done-p ()
13169 (member (org-get-todo-state) org-done-keywords))
13171 (defun org-get-todo-state ()
13172 "Return the TODO keyword of the current subtree."
13173 (save-excursion
13174 (org-back-to-heading t)
13175 (and (looking-at org-todo-line-regexp)
13176 (match-end 2)
13177 (match-string 2))))
13179 (defun org-at-date-range-p (&optional inactive-ok)
13180 "Non-nil if point is inside a date range.
13182 When optional argument INACTIVE-OK is non-nil, also consider
13183 inactive time ranges.
13185 When this function returns a non-nil value, match data is set
13186 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13187 on INACTIVE-OK."
13188 (interactive)
13189 (save-excursion
13190 (catch 'exit
13191 (let ((pos (point)))
13192 (skip-chars-backward "^[<\r\n")
13193 (skip-chars-backward "<[")
13194 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13195 (>= (match-end 0) pos)
13196 (throw 'exit t))
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 nil)))
13204 (defun org-get-repeat (&optional tagline)
13205 "Check if there is a deadline/schedule with repeater in this entry."
13206 (save-match-data
13207 (save-excursion
13208 (org-back-to-heading t)
13209 (and (re-search-forward (if tagline
13210 (concat tagline "\\s-*" org-repeat-re)
13211 org-repeat-re)
13212 (org-entry-end-position) t)
13213 (match-string-no-properties 1)))))
13215 (defvar org-last-changed-timestamp)
13216 (defvar org-last-inserted-timestamp)
13217 (defvar org-log-post-message)
13218 (defvar org-log-note-purpose)
13219 (defvar org-log-note-how nil)
13220 (defvar org-log-note-extra)
13221 (defun org-auto-repeat-maybe (done-word)
13222 "Check if the current headline contains a repeated time-stamp.
13224 If yes, set TODO state back to what it was and change the base date
13225 of repeating deadline/scheduled time stamps to new date.
13227 This function is run automatically after each state change to a DONE state."
13228 (let* ((repeat (org-get-repeat))
13229 (aa (assoc org-last-state org-todo-kwd-alist))
13230 (interpret (nth 1 aa))
13231 (head (nth 2 aa))
13232 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13233 (msg "Entry repeats: ")
13234 (org-log-done nil)
13235 (org-todo-log-states nil))
13236 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13237 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13238 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13239 org-todo-repeat-to-state)))
13240 (unless (and to-state (member to-state org-todo-keywords-1))
13241 (setq to-state (if (eq interpret 'type) org-last-state head)))
13242 (org-todo to-state))
13243 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13244 (org-entry-put nil "LAST_REPEAT" (format-time-string
13245 (org-time-stamp-format t t))))
13246 (when org-log-repeat
13247 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13248 (memq 'org-add-log-note post-command-hook))
13249 ;; We are already setup for some record.
13250 (when (eq org-log-repeat 'note)
13251 ;; Make sure we take a note, not only a time stamp.
13252 (setq org-log-note-how 'note))
13253 ;; Set up for taking a record.
13254 (org-add-log-setup 'state
13255 (or done-word (car org-done-keywords))
13256 org-last-state
13257 org-log-repeat)))
13258 (org-back-to-heading t)
13259 (org-add-planning-info nil nil 'closed)
13260 (let ((end (save-excursion (outline-next-heading) (point))))
13261 (while (re-search-forward org-ts-regexp end t)
13262 (when (save-match-data
13263 (or (org-at-planning-p)
13264 (org-at-property-p)
13265 (eq (org-element-type (save-excursion
13266 (backward-char)
13267 (org-element-context)))
13268 'timestamp)))
13269 (let ((type (cond ((match-end 1) org-scheduled-string)
13270 ((match-end 3) org-deadline-string)
13271 (t "Plain:")))
13272 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13273 (cond
13274 ((not
13275 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13276 ;; Time-stamps without a repeater are usually skipped.
13277 ;; However, a SCHEDULED time-stamp without one is
13278 ;; removed, as it is considered as no longer relevant.
13279 (when (equal type org-scheduled-string)
13280 (org-remove-timestamp-with-keyword type)))
13282 (let ((n (string-to-number (match-string 2 ts)))
13283 (what (match-string 3 ts)))
13284 (when (equal what "w") (setq n (* n 7) what "d"))
13285 (when (and (equal what "h")
13286 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13287 ts)))
13288 (user-error
13289 "Cannot repeat in Repeat in %d hour(s) because no hour \
13290 has been set"
13292 ;; Preparation, see if we need to modify the start
13293 ;; date for the change.
13294 (when (match-end 1)
13295 (let ((time (save-match-data (org-time-string-to-time ts))))
13296 (cond
13297 ((equal (match-string 1 ts) ".")
13298 ;; Shift starting date to today
13299 (org-timestamp-change
13300 (- (org-today) (time-to-days time))
13301 'day))
13302 ((equal (match-string 1 ts) "+")
13303 (let ((nshiftmax 10)
13304 (nshift 0))
13305 (while (or (= nshift 0)
13306 (not (time-less-p (current-time) time)))
13307 (when (= (cl-incf nshift) nshiftmax)
13308 (or (y-or-n-p
13309 (format "%d repeater intervals were not \
13310 enough to shift date past today. Continue? "
13311 nshift))
13312 (user-error "Abort")))
13313 (org-timestamp-change n (cdr (assoc what whata)))
13314 (org-at-timestamp-p t)
13315 (setq ts (match-string 1))
13316 (setq time
13317 (save-match-data
13318 (org-time-string-to-time ts)))))
13319 (org-timestamp-change (- n) (cdr (assoc what whata)))
13320 ;; Rematch, so that we have everything in
13321 ;; place for the real shift.
13322 (org-at-timestamp-p t)
13323 (setq ts (match-string 1))
13324 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13325 ts)))))
13326 (save-excursion
13327 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13328 (setq msg
13329 (concat
13330 msg type " " org-last-changed-timestamp " ")))))))))
13331 (setq org-log-post-message msg)
13332 (message "%s" msg))))
13334 (defun org-show-todo-tree (arg)
13335 "Make a compact tree which shows all headlines marked with TODO.
13336 The tree will show the lines where the regexp matches, and all higher
13337 headlines above the match.
13338 With a \\[universal-argument] prefix, prompt for a regexp to match.
13339 With a numeric prefix N, construct a sparse tree for the Nth element
13340 of `org-todo-keywords-1'."
13341 (interactive "P")
13342 (let ((case-fold-search nil)
13343 (kwd-re
13344 (cond ((null arg) org-not-done-regexp)
13345 ((equal arg '(4))
13346 (let ((kwd
13347 (completing-read "Keyword (or KWD1|KWD2|...): "
13348 (mapcar #'list org-todo-keywords-1))))
13349 (concat "\\("
13350 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13351 "\\)\\>")))
13352 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13353 (regexp-quote (nth (1- (prefix-numeric-value arg))
13354 org-todo-keywords-1)))
13355 (t (user-error "Invalid prefix argument: %s" arg)))))
13356 (message "%d TODO entries found"
13357 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13359 (defun org-deadline (arg &optional time)
13360 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13361 With one universal prefix argument, remove any deadline from the item.
13362 With two universal prefix arguments, prompt for a warning delay.
13363 With argument TIME, set the deadline at the corresponding date. TIME
13364 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13365 (interactive "P")
13366 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13367 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13368 'region-start-level 'region))
13369 org-loop-over-headlines-in-active-region)
13370 (org-map-entries
13371 `(org-deadline ',arg ,time)
13372 org-loop-over-headlines-in-active-region
13373 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13374 (let* ((old-date (org-entry-get nil "DEADLINE"))
13375 (old-date-time (when old-date (org-time-string-to-time old-date)))
13376 (repeater (and old-date
13377 (string-match
13378 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13379 old-date)
13380 (match-string 1 old-date))))
13381 (cond
13382 ((equal arg '(4))
13383 (when (and old-date org-log-redeadline)
13384 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13385 (org-remove-timestamp-with-keyword org-deadline-string)
13386 (message "Item no longer has a deadline."))
13387 ((equal arg '(16))
13388 (save-excursion
13389 (org-back-to-heading t)
13390 (if (re-search-forward
13391 org-deadline-time-regexp
13392 (save-excursion (outline-next-heading) (point)) t)
13393 (let* ((rpl0 (match-string 1))
13394 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13395 (replace-match
13396 (concat org-deadline-string
13397 " <" rpl
13398 (format " -%dd"
13399 (abs
13400 (- (time-to-days
13401 (save-match-data
13402 (org-read-date nil t nil "Warn starting from" old-date-time)))
13403 (time-to-days old-date-time))))
13404 ">") t t))
13405 (user-error "No deadline information to update"))))
13407 (org-add-planning-info 'deadline time 'closed)
13408 (when (and old-date
13409 org-log-redeadline
13410 (not (equal old-date org-last-inserted-timestamp)))
13411 (org-add-log-setup
13412 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13413 (when repeater
13414 (save-excursion
13415 (org-back-to-heading t)
13416 (when (re-search-forward (concat org-deadline-string " "
13417 org-last-inserted-timestamp)
13418 (save-excursion
13419 (outline-next-heading) (point)) t)
13420 (goto-char (1- (match-end 0)))
13421 (insert " " repeater)
13422 (setq org-last-inserted-timestamp
13423 (concat (substring org-last-inserted-timestamp 0 -1)
13424 " " repeater
13425 (substring org-last-inserted-timestamp -1))))))
13426 (message "Deadline on %s" org-last-inserted-timestamp))))))
13428 (defun org-schedule (arg &optional time)
13429 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13430 With one universal prefix argument, remove any scheduling date from the item.
13431 With two universal prefix arguments, prompt for a delay cookie.
13432 With argument TIME, scheduled at the corresponding date. TIME can
13433 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13434 (interactive "P")
13435 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13436 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13437 'region-start-level 'region))
13438 org-loop-over-headlines-in-active-region)
13439 (org-map-entries
13440 `(org-schedule ',arg ,time)
13441 org-loop-over-headlines-in-active-region
13442 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13443 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13444 (old-date-time (when old-date (org-time-string-to-time old-date)))
13445 (repeater (and old-date
13446 (string-match
13447 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13448 old-date)
13449 (match-string 1 old-date))))
13450 (cond
13451 ((equal arg '(4))
13452 (progn
13453 (when (and old-date org-log-reschedule)
13454 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13455 (org-remove-timestamp-with-keyword org-scheduled-string)
13456 (message "Item is no longer scheduled.")))
13457 ((equal arg '(16))
13458 (save-excursion
13459 (org-back-to-heading t)
13460 (if (re-search-forward
13461 org-scheduled-time-regexp
13462 (save-excursion (outline-next-heading) (point)) t)
13463 (let* ((rpl0 (match-string 1))
13464 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13465 (replace-match
13466 (concat org-scheduled-string
13467 " <" rpl
13468 (format " -%dd"
13469 (abs
13470 (- (time-to-days
13471 (save-match-data
13472 (org-read-date nil t nil "Delay until" old-date-time)))
13473 (time-to-days old-date-time))))
13474 ">") t t))
13475 (user-error "No scheduled information to update"))))
13477 (org-add-planning-info 'scheduled time 'closed)
13478 (when (and old-date
13479 org-log-reschedule
13480 (not (equal old-date org-last-inserted-timestamp)))
13481 (org-add-log-setup
13482 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13483 (when repeater
13484 (save-excursion
13485 (org-back-to-heading t)
13486 (when (re-search-forward (concat org-scheduled-string " "
13487 org-last-inserted-timestamp)
13488 (save-excursion
13489 (outline-next-heading) (point)) t)
13490 (goto-char (1- (match-end 0)))
13491 (insert " " repeater)
13492 (setq org-last-inserted-timestamp
13493 (concat (substring org-last-inserted-timestamp 0 -1)
13494 " " repeater
13495 (substring org-last-inserted-timestamp -1))))))
13496 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13498 (defun org-get-scheduled-time (pom &optional inherit)
13499 "Get the scheduled time as a time tuple, of a format suitable
13500 for calling org-schedule with, or if there is no scheduling,
13501 returns nil."
13502 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13503 (when time
13504 (apply 'encode-time (org-parse-time-string time)))))
13506 (defun org-get-deadline-time (pom &optional inherit)
13507 "Get the deadline as a time tuple, of a format suitable for
13508 calling org-deadline with, or if there is no scheduling, returns
13509 nil."
13510 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13511 (when time
13512 (apply 'encode-time (org-parse-time-string time)))))
13514 (defun org-remove-timestamp-with-keyword (keyword)
13515 "Remove all time stamps with KEYWORD in the current entry."
13516 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13517 beg)
13518 (save-excursion
13519 (org-back-to-heading t)
13520 (setq beg (point))
13521 (outline-next-heading)
13522 (while (re-search-backward re beg t)
13523 (replace-match "")
13524 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13525 (equal (char-before) ?\ ))
13526 (backward-delete-char 1)
13527 (when (string-match "^[ \t]*$" (buffer-substring
13528 (point-at-bol) (point-at-eol)))
13529 (delete-region (point-at-bol)
13530 (min (point-max) (1+ (point-at-eol))))))))))
13532 (defvar org-time-was-given) ; dynamically scoped parameter
13533 (defvar org-end-time-was-given) ; dynamically scoped parameter
13535 (defun org-at-planning-p ()
13536 "Non-nil when point is on a planning info line."
13537 ;; This is as accurate and faster than `org-element-at-point' since
13538 ;; planning info location is fixed in the section.
13539 (org-with-wide-buffer
13540 (beginning-of-line)
13541 (and (looking-at-p org-planning-line-re)
13542 (eq (point)
13543 (ignore-errors
13544 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13545 (org-back-to-heading t)
13546 (org-with-limited-levels (org-back-to-heading t)))
13547 (line-beginning-position 2))))))
13549 (defun org-add-planning-info (what &optional time &rest remove)
13550 "Insert new timestamp with keyword in the planning line.
13551 WHAT indicates what kind of time stamp to add. It is a symbol
13552 among `closed', `deadline', `scheduled' and nil. TIME indicates
13553 the time to use. If none is given, the user is prompted for
13554 a date. REMOVE indicates what kind of entries to remove. An old
13555 WHAT entry will also be removed."
13556 (let (org-time-was-given org-end-time-was-given default-time default-input)
13557 (catch 'exit
13558 (when (and (memq what '(scheduled deadline))
13559 (or (not time)
13560 (and (stringp time)
13561 (string-match "^[-+]+[0-9]" time))))
13562 ;; Try to get a default date/time from existing timestamp
13563 (save-excursion
13564 (org-back-to-heading t)
13565 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13566 (when (re-search-forward (if (eq what 'scheduled)
13567 org-scheduled-time-regexp
13568 org-deadline-time-regexp)
13569 end t)
13570 (setq ts (match-string 1)
13571 default-time (apply 'encode-time (org-parse-time-string ts))
13572 default-input (and ts (org-get-compact-tod ts)))))))
13573 (when what
13574 (setq time
13575 (if (stringp time)
13576 ;; This is a string (relative or absolute), set
13577 ;; proper date.
13578 (apply #'encode-time
13579 (org-read-date-analyze
13580 time default-time (decode-time default-time)))
13581 ;; If necessary, get the time from the user
13582 (or time (org-read-date nil 'to-time nil nil
13583 default-time default-input)))))
13585 (org-with-wide-buffer
13586 (org-back-to-heading t)
13587 (forward-line)
13588 (unless (bolp) (insert "\n"))
13589 (cond ((looking-at-p org-planning-line-re)
13590 ;; Move to current indentation.
13591 (skip-chars-forward " \t")
13592 ;; Check if we have to remove something.
13593 (dolist (type (if what (cons what remove) remove))
13594 (save-excursion
13595 (when (re-search-forward
13596 (cl-case type
13597 (closed org-closed-time-regexp)
13598 (deadline org-deadline-time-regexp)
13599 (scheduled org-scheduled-time-regexp)
13600 (otherwise
13601 (error "Invalid planning type: %s" type)))
13602 (line-end-position) t)
13603 ;; Delete until next keyword or end of line.
13604 (delete-region
13605 (match-beginning 0)
13606 (if (re-search-forward org-keyword-time-not-clock-regexp
13607 (line-end-position)
13609 (match-beginning 0)
13610 (line-end-position))))))
13611 ;; If there is nothing more to add and no more keyword
13612 ;; is left, remove the line completely.
13613 (if (and (looking-at-p "[ \t]*$") (not what))
13614 (delete-region (line-beginning-position)
13615 (line-beginning-position 2))
13616 ;; If we removed last keyword, do not leave trailing
13617 ;; white space at the end of line.
13618 (let ((p (point)))
13619 (save-excursion
13620 (end-of-line)
13621 (unless (= (skip-chars-backward " \t" p) 0)
13622 (delete-region (point) (line-end-position)))))))
13623 ((not what) (throw 'exit nil)) ; Nothing to do.
13624 (t (insert-before-markers "\n")
13625 (backward-char 1)
13626 (when org-adapt-indentation
13627 (indent-to-column (1+ (org-outline-level))))))
13628 (when what
13629 ;; Insert planning keyword.
13630 (insert (cl-case what
13631 (closed org-closed-string)
13632 (deadline org-deadline-string)
13633 (scheduled org-scheduled-string)
13634 (otherwise (error "Invalid planning type: %s" what)))
13635 " ")
13636 ;; Insert associated timestamp.
13637 (let ((ts (org-insert-time-stamp
13638 time
13639 (or org-time-was-given
13640 (and (eq what 'closed) org-log-done-with-time))
13641 (eq what 'closed)
13642 nil nil (list org-end-time-was-given))))
13643 (unless (eolp) (insert " "))
13644 ts))))))
13646 (defvar org-log-note-marker (make-marker)
13647 "Marker pointing at the entry where the note is to be inserted.")
13648 (defvar org-log-note-purpose nil)
13649 (defvar org-log-note-state nil)
13650 (defvar org-log-note-previous-state nil)
13651 (defvar org-log-note-extra nil)
13652 (defvar org-log-note-window-configuration nil)
13653 (defvar org-log-note-return-to (make-marker))
13654 (defvar org-log-note-effective-time nil
13655 "Remembered current time so that dynamically scoped
13656 `org-extend-today-until' affects timestamps in state change log")
13658 (defvar org-log-post-message nil
13659 "Message to be displayed after a log note has been stored.
13660 The auto-repeater uses this.")
13662 (defun org-add-note ()
13663 "Add a note to the current entry.
13664 This is done in the same way as adding a state change note."
13665 (interactive)
13666 (org-add-log-setup 'note))
13668 (defun org-log-beginning (&optional create)
13669 "Return expected start of log notes in current entry.
13670 When optional argument CREATE is non-nil, the function creates
13671 a drawer to store notes, if necessary. Returned position ignores
13672 narrowing."
13673 (org-with-wide-buffer
13674 (let ((drawer (org-log-into-drawer)))
13675 (cond
13676 (drawer
13677 (org-end-of-meta-data)
13678 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13679 (end (if (org-at-heading-p) (point)
13680 (save-excursion (outline-next-heading) (point))))
13681 (case-fold-search t))
13682 (catch 'exit
13683 ;; Try to find existing drawer.
13684 (while (re-search-forward regexp end t)
13685 (let ((element (org-element-at-point)))
13686 (when (eq (org-element-type element) 'drawer)
13687 (let ((cend (org-element-property :contents-end element)))
13688 (when (and (not org-log-states-order-reversed) cend)
13689 (goto-char cend)))
13690 (throw 'exit nil))))
13691 ;; No drawer found. Create one, if permitted.
13692 (when create
13693 (unless (bolp) (insert "\n"))
13694 (let ((beg (point)))
13695 (insert ":" drawer ":\n:END:\n")
13696 (org-indent-region beg (point)))
13697 (end-of-line -1)))))
13699 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13700 (skip-chars-forward " \t\n")
13701 (beginning-of-line)
13702 (unless org-log-states-order-reversed
13703 (org-skip-over-state-notes)
13704 (skip-chars-backward " \t\n")
13705 (forward-line)))))
13706 (if (bolp) (point) (line-beginning-position 2))))
13708 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13709 "Set up the post command hook to take a note.
13710 If this is about to TODO state change, the new state is expected in STATE.
13711 HOW is an indicator what kind of note should be created.
13712 EXTRA is additional text that will be inserted into the notes buffer."
13713 (move-marker org-log-note-marker (point))
13714 (setq org-log-note-purpose purpose
13715 org-log-note-state state
13716 org-log-note-previous-state prev-state
13717 org-log-note-how how
13718 org-log-note-extra extra
13719 org-log-note-effective-time (org-current-effective-time))
13720 (add-hook 'post-command-hook 'org-add-log-note 'append))
13722 (defun org-skip-over-state-notes ()
13723 "Skip past the list of State notes in an entry."
13724 (when (ignore-errors (goto-char (org-in-item-p)))
13725 (let* ((struct (org-list-struct))
13726 (prevs (org-list-prevs-alist struct))
13727 (regexp
13728 (concat "[ \t]*- +"
13729 (replace-regexp-in-string
13730 " +" " +"
13731 (org-replace-escapes
13732 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13733 `(("%d" . ,org-ts-regexp-inactive)
13734 ("%D" . ,org-ts-regexp)
13735 ("%s" . "\"\\S-+\"")
13736 ("%S" . "\"\\S-+\"")
13737 ("%t" . ,org-ts-regexp-inactive)
13738 ("%T" . ,org-ts-regexp)
13739 ("%u" . ".*?")
13740 ("%U" . ".*?")))))))
13741 (while (looking-at-p regexp)
13742 (goto-char (or (org-list-get-next-item (point) struct prevs)
13743 (org-list-get-item-end (point) struct)))))))
13745 (defun org-add-log-note (&optional _purpose)
13746 "Pop up a window for taking a note, and add this note later."
13747 (remove-hook 'post-command-hook 'org-add-log-note)
13748 (setq org-log-note-window-configuration (current-window-configuration))
13749 (delete-other-windows)
13750 (move-marker org-log-note-return-to (point))
13751 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13752 (goto-char org-log-note-marker)
13753 (org-switch-to-buffer-other-window "*Org Note*")
13754 (erase-buffer)
13755 (if (memq org-log-note-how '(time state))
13756 (let (current-prefix-arg) (org-store-log-note))
13757 (let ((org-inhibit-startup t)) (org-mode))
13758 (insert (format "# Insert note for %s.
13759 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13760 (cond
13761 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13762 ((eq org-log-note-purpose 'done) "closed todo item")
13763 ((eq org-log-note-purpose 'state)
13764 (format "state change from \"%s\" to \"%s\""
13765 (or org-log-note-previous-state "")
13766 (or org-log-note-state "")))
13767 ((eq org-log-note-purpose 'reschedule)
13768 "rescheduling")
13769 ((eq org-log-note-purpose 'delschedule)
13770 "no longer scheduled")
13771 ((eq org-log-note-purpose 'redeadline)
13772 "changing deadline")
13773 ((eq org-log-note-purpose 'deldeadline)
13774 "removing deadline")
13775 ((eq org-log-note-purpose 'refile)
13776 "refiling")
13777 ((eq org-log-note-purpose 'note)
13778 "this entry")
13779 (t (error "This should not happen")))))
13780 (when org-log-note-extra (insert org-log-note-extra))
13781 (setq-local org-finish-function 'org-store-log-note)
13782 (run-hooks 'org-log-buffer-setup-hook)))
13784 (defvar org-note-abort nil) ; dynamically scoped
13785 (defun org-store-log-note ()
13786 "Finish taking a log note, and insert it to where it belongs."
13787 (let ((txt (prog1 (buffer-string)
13788 (kill-buffer)))
13789 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13790 lines)
13791 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13792 (setq txt (replace-match "" t t txt)))
13793 (when (string-match "\\s-+\\'" txt)
13794 (setq txt (replace-match "" t t txt)))
13795 (setq lines (org-split-string txt "\n"))
13796 (when (org-string-nw-p note)
13797 (setq note
13798 (org-replace-escapes
13799 note
13800 (list (cons "%u" (user-login-name))
13801 (cons "%U" user-full-name)
13802 (cons "%t" (format-time-string
13803 (org-time-stamp-format 'long 'inactive)
13804 org-log-note-effective-time))
13805 (cons "%T" (format-time-string
13806 (org-time-stamp-format 'long nil)
13807 org-log-note-effective-time))
13808 (cons "%d" (format-time-string
13809 (org-time-stamp-format nil 'inactive)
13810 org-log-note-effective-time))
13811 (cons "%D" (format-time-string
13812 (org-time-stamp-format nil nil)
13813 org-log-note-effective-time))
13814 (cons "%s" (cond
13815 ((not org-log-note-state) "")
13816 ((string-match-p org-ts-regexp
13817 org-log-note-state)
13818 (format "\"[%s]\""
13819 (substring org-log-note-state 1 -1)))
13820 (t (format "\"%s\"" org-log-note-state))))
13821 (cons "%S"
13822 (cond
13823 ((not org-log-note-previous-state) "")
13824 ((string-match-p org-ts-regexp
13825 org-log-note-previous-state)
13826 (format "\"[%s]\""
13827 (substring
13828 org-log-note-previous-state 1 -1)))
13829 (t (format "\"%s\""
13830 org-log-note-previous-state)))))))
13831 (when lines (setq note (concat note " \\\\")))
13832 (push note lines))
13833 (when (and lines (not (or current-prefix-arg org-note-abort)))
13834 (with-current-buffer (marker-buffer org-log-note-marker)
13835 (org-with-wide-buffer
13836 ;; Find location for the new note.
13837 (goto-char org-log-note-marker)
13838 (set-marker org-log-note-marker nil)
13839 (goto-char (org-log-beginning t))
13840 ;; Make sure point is at the beginning of an empty line.
13841 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13842 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13843 ;; In an existing list, add a new item at the top level.
13844 ;; Otherwise, indent line like a regular one.
13845 (let ((itemp (org-in-item-p)))
13846 (if itemp
13847 (indent-line-to
13848 (let ((struct (save-excursion
13849 (goto-char itemp) (org-list-struct))))
13850 (org-list-get-ind (org-list-get-top-point struct) struct)))
13851 (org-indent-line)))
13852 (insert (org-list-bullet-string "-") (pop lines))
13853 (let ((ind (org-list-item-body-column (line-beginning-position))))
13854 (dolist (line lines)
13855 (insert "\n")
13856 (indent-line-to ind)
13857 (insert line)))
13858 (message "Note stored")
13859 (org-back-to-heading t)
13860 (org-cycle-hide-drawers 'children))
13861 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13862 ;; from within `org-add-log-note' because `buffer-undo-list'
13863 ;; is then modified outside of `org-with-remote-undo'.
13864 (when (eq this-command 'org-agenda-todo)
13865 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13866 ;; Don't add undo information when called from `org-agenda-todo'.
13867 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13868 (set-window-configuration org-log-note-window-configuration)
13869 (with-current-buffer (marker-buffer org-log-note-return-to)
13870 (goto-char org-log-note-return-to))
13871 (move-marker org-log-note-return-to nil)
13872 (when org-log-post-message (message "%s" org-log-post-message))))
13874 (defun org-remove-empty-drawer-at (pos)
13875 "Remove an empty drawer at position POS.
13876 POS may also be a marker."
13877 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13878 (org-with-wide-buffer
13879 (goto-char pos)
13880 (let ((drawer (org-element-at-point)))
13881 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13882 (not (org-element-property :contents-begin drawer)))
13883 (delete-region (org-element-property :begin drawer)
13884 (progn (goto-char (org-element-property :end drawer))
13885 (skip-chars-backward " \r\t\n")
13886 (forward-line)
13887 (point))))))))
13889 (defvar org-ts-type nil)
13890 (defun org-sparse-tree (&optional arg type)
13891 "Create a sparse tree, prompt for the details.
13892 This command can create sparse trees. You first need to select the type
13893 of match used to create the tree:
13895 t Show all TODO entries.
13896 T Show entries with a specific TODO keyword.
13897 m Show entries selected by a tags/property match.
13898 p Enter a property name and its value (both with completion on existing
13899 names/values) and show entries with that property.
13900 r Show entries matching a regular expression (`/' can be used as well).
13901 b Show deadlines and scheduled items before a date.
13902 a Show deadlines and scheduled items after a date.
13903 d Show deadlines due within `org-deadline-warning-days'.
13904 D Show deadlines and scheduled items between a date range."
13905 (interactive "P")
13906 (setq type (or type org-sparse-tree-default-date-type))
13907 (setq org-ts-type type)
13908 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13909 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13910 \[c]ycle through date types: %s"
13911 (cl-case type
13912 (all "all timestamps")
13913 (scheduled "only scheduled")
13914 (deadline "only deadline")
13915 (active "only active timestamps")
13916 (inactive "only inactive timestamps")
13917 (closed "with a closed time-stamp")
13918 (otherwise "scheduled/deadline")))
13919 (let ((answer (read-char-exclusive)))
13920 (cl-case answer
13922 (org-sparse-tree
13924 (cadr
13925 (memq type '(nil all scheduled deadline active inactive closed)))))
13926 (?d (call-interactively 'org-check-deadlines))
13927 (?b (call-interactively 'org-check-before-date))
13928 (?a (call-interactively 'org-check-after-date))
13929 (?D (call-interactively 'org-check-dates-range))
13930 (?t (call-interactively 'org-show-todo-tree))
13931 (?T (org-show-todo-tree '(4)))
13932 (?m (call-interactively 'org-match-sparse-tree))
13933 ((?p ?P)
13934 (let* ((kwd (completing-read
13935 "Property: " (mapcar #'list (org-buffer-property-keys))))
13936 (value (completing-read
13937 "Value: " (mapcar #'list (org-property-values kwd)))))
13938 (unless (string-match "\\`{.*}\\'" value)
13939 (setq value (concat "\"" value "\"")))
13940 (org-match-sparse-tree arg (concat kwd "=" value))))
13941 ((?r ?R ?/) (call-interactively 'org-occur))
13942 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13944 (defvar-local org-occur-highlights nil
13945 "List of overlays used for occur matches.")
13946 (defvar-local org-occur-parameters nil
13947 "Parameters of the active org-occur calls.
13948 This is a list, each call to org-occur pushes as cons cell,
13949 containing the regular expression and the callback, onto the list.
13950 The list can contain several entries if `org-occur' has been called
13951 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13952 will only contain one set of parameters. When the highlights are
13953 removed (for example with `C-c C-c', or with the next edit (depending
13954 on `org-remove-highlights-with-change'), this variable is emptied
13955 as well.")
13957 (defun org-occur (regexp &optional keep-previous callback)
13958 "Make a compact tree which shows all matches of REGEXP.
13960 The tree will show the lines where the regexp matches, and any other context
13961 defined in `org-show-context-detail', which see.
13963 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13964 done by a previous call to `org-occur' will be kept, to allow stacking of
13965 calls to this command.
13967 Optional argument CALLBACK can be a function of no argument. In this case,
13968 it is called with point at the end of the match, match data being set
13969 accordingly. Current match is shown only if the return value is non-nil.
13970 The function must neither move point nor alter narrowing."
13971 (interactive "sRegexp: \nP")
13972 (when (equal regexp "")
13973 (user-error "Regexp cannot be empty"))
13974 (unless keep-previous
13975 (org-remove-occur-highlights nil nil t))
13976 (push (cons regexp callback) org-occur-parameters)
13977 (let ((cnt 0))
13978 (save-excursion
13979 (goto-char (point-min))
13980 (when (or (not keep-previous) ; do not want to keep
13981 (not org-occur-highlights)) ; no previous matches
13982 ;; hide everything
13983 (org-overview))
13984 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13985 (isearch-no-upper-case-p regexp t)
13986 org-occur-case-fold-search)))
13987 (while (re-search-forward regexp nil t)
13988 (when (or (not callback)
13989 (save-match-data (funcall callback)))
13990 (setq cnt (1+ cnt))
13991 (when org-highlight-sparse-tree-matches
13992 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13993 (org-show-context 'occur-tree)))))
13994 (when org-remove-highlights-with-change
13995 (add-hook 'before-change-functions 'org-remove-occur-highlights
13996 nil 'local))
13997 (unless org-sparse-tree-open-archived-trees
13998 (org-hide-archived-subtrees (point-min) (point-max)))
13999 (run-hooks 'org-occur-hook)
14000 (when (called-interactively-p 'interactive)
14001 (message "%d match(es) for regexp %s" cnt regexp))
14002 cnt))
14004 (defun org-occur-next-match (&optional n _reset)
14005 "Function for `next-error-function' to find sparse tree matches.
14006 N is the number of matches to move, when negative move backwards.
14007 This function always goes back to the starting point when no
14008 match is found."
14009 (let* ((limit (if (< n 0) (point-min) (point-max)))
14010 (search-func (if (< n 0)
14011 'previous-single-char-property-change
14012 'next-single-char-property-change))
14013 (n (abs n))
14014 (pos (point))
14016 (catch 'exit
14017 (while (setq p1 (funcall search-func (point) 'org-type))
14018 (when (equal p1 limit)
14019 (goto-char pos)
14020 (user-error "No more matches"))
14021 (when (equal (get-char-property p1 'org-type) 'org-occur)
14022 (setq n (1- n))
14023 (when (= n 0)
14024 (goto-char p1)
14025 (throw 'exit (point))))
14026 (goto-char p1))
14027 (goto-char p1)
14028 (user-error "No more matches"))))
14030 (defun org-show-context (&optional key)
14031 "Make sure point and context are visible.
14032 Optional argument KEY, when non-nil, is a symbol. See
14033 `org-show-context-detail' for allowed values and how much is to
14034 be shown."
14035 (org-show-set-visibility
14036 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14037 ((cdr (assq key org-show-context-detail)))
14038 (t (cdr (assq 'default org-show-context-detail))))))
14040 (defun org-show-set-visibility (detail)
14041 "Set visibility around point according to DETAIL.
14042 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14043 `tree', `canonical' or t. See `org-show-context-detail' for more
14044 information."
14045 ;; Show current heading and possibly its entry, following headline
14046 ;; or all children.
14047 (if (and (org-at-heading-p) (not (eq detail 'local)))
14048 (org-flag-heading nil)
14049 (org-show-entry)
14050 ;; If point is hidden within a drawer or a block, make sure to
14051 ;; expose it.
14052 (dolist (o (overlays-at (point)))
14053 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14054 (delete-overlay o)))
14055 (unless (org-before-first-heading-p)
14056 (org-with-limited-levels
14057 (cl-case detail
14058 ((tree canonical t) (org-show-children))
14059 ((nil minimal ancestors))
14060 (t (save-excursion
14061 (outline-next-heading)
14062 (org-flag-heading nil)))))))
14063 ;; Show all siblings.
14064 (when (eq detail 'lineage) (org-show-siblings))
14065 ;; Show ancestors, possibly with their children.
14066 (when (memq detail '(ancestors lineage tree canonical t))
14067 (save-excursion
14068 (while (org-up-heading-safe)
14069 (org-flag-heading nil)
14070 (when (memq detail '(canonical t)) (org-show-entry))
14071 (when (memq detail '(tree canonical t)) (org-show-children))))))
14073 (defvar org-reveal-start-hook nil
14074 "Hook run before revealing a location.")
14076 (defun org-reveal (&optional siblings)
14077 "Show current entry, hierarchy above it, and the following headline.
14079 This can be used to show a consistent set of context around
14080 locations exposed with `org-show-context'.
14082 With optional argument SIBLINGS, on each level of the hierarchy all
14083 siblings are shown. This repairs the tree structure to what it would
14084 look like when opened with hierarchical calls to `org-cycle'.
14086 With double optional argument \\[universal-argument] \\[universal-argument], \
14087 go to the parent and show the
14088 entire tree."
14089 (interactive "P")
14090 (run-hooks 'org-reveal-start-hook)
14091 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14092 ((equal siblings '(16))
14093 (save-excursion
14094 (when (org-up-heading-safe)
14095 (org-show-subtree)
14096 (run-hook-with-args 'org-cycle-hook 'subtree))))
14097 (t (org-show-set-visibility 'lineage))))
14099 (defun org-highlight-new-match (beg end)
14100 "Highlight from BEG to END and mark the highlight is an occur headline."
14101 (let ((ov (make-overlay beg end)))
14102 (overlay-put ov 'face 'secondary-selection)
14103 (overlay-put ov 'org-type 'org-occur)
14104 (push ov org-occur-highlights)))
14106 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14107 "Remove the occur highlights from the buffer.
14108 BEG and END are ignored. If NOREMOVE is nil, remove this function
14109 from the `before-change-functions' in the current buffer."
14110 (interactive)
14111 (unless org-inhibit-highlight-removal
14112 (mapc #'delete-overlay org-occur-highlights)
14113 (setq org-occur-highlights nil)
14114 (setq org-occur-parameters nil)
14115 (unless noremove
14116 (remove-hook 'before-change-functions
14117 'org-remove-occur-highlights 'local))))
14119 ;;;; Priorities
14121 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14122 "Regular expression matching the priority indicator.")
14124 (defvar org-remove-priority-next-time nil)
14126 (defun org-priority-up ()
14127 "Increase the priority of the current item."
14128 (interactive)
14129 (org-priority 'up))
14131 (defun org-priority-down ()
14132 "Decrease the priority of the current item."
14133 (interactive)
14134 (org-priority 'down))
14136 (defun org-priority (&optional action _show)
14137 "Change the priority of an item.
14138 ACTION can be `set', `up', `down', or a character."
14139 (interactive "P")
14140 (if (equal action '(4))
14141 (org-show-priority)
14142 (unless org-enable-priority-commands
14143 (user-error "Priority commands are disabled"))
14144 (setq action (or action 'set))
14145 (let (current new news have remove)
14146 (save-excursion
14147 (org-back-to-heading t)
14148 (when (looking-at org-priority-regexp)
14149 (setq current (string-to-char (match-string 2))
14150 have t))
14151 (cond
14152 ((eq action 'remove)
14153 (setq remove t new ?\ ))
14154 ((or (eq action 'set)
14155 (integerp action))
14156 (if (not (eq action 'set))
14157 (setq new action)
14158 (message "Priority %c-%c, SPC to remove: "
14159 org-highest-priority org-lowest-priority)
14160 (save-match-data
14161 (setq new (read-char-exclusive))))
14162 (when (and (= (upcase org-highest-priority) org-highest-priority)
14163 (= (upcase org-lowest-priority) org-lowest-priority))
14164 (setq new (upcase new)))
14165 (cond ((equal new ?\ ) (setq remove t))
14166 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14167 (user-error "Priority must be between `%c' and `%c'"
14168 org-highest-priority org-lowest-priority))))
14169 ((eq action 'up)
14170 (setq new (if have
14171 (1- current) ; normal cycling
14172 ;; last priority was empty
14173 (if (eq last-command this-command)
14174 org-lowest-priority ; wrap around empty to lowest
14175 ;; default
14176 (if org-priority-start-cycle-with-default
14177 org-default-priority
14178 (1- org-default-priority))))))
14179 ((eq action 'down)
14180 (setq new (if have
14181 (1+ current) ; normal cycling
14182 ;; last priority was empty
14183 (if (eq last-command this-command)
14184 org-highest-priority ; wrap around empty to highest
14185 ;; default
14186 (if org-priority-start-cycle-with-default
14187 org-default-priority
14188 (1+ org-default-priority))))))
14189 (t (user-error "Invalid action")))
14190 (when (or (< (upcase new) org-highest-priority)
14191 (> (upcase new) org-lowest-priority))
14192 (if (and (memq action '(up down))
14193 (not have) (not (eq last-command this-command)))
14194 ;; `new' is from default priority
14195 (error
14196 "The default can not be set, see `org-default-priority' why")
14197 ;; normal cycling: `new' is beyond highest/lowest priority
14198 ;; and is wrapped around to the empty priority
14199 (setq remove t)))
14200 (setq news (format "%c" new))
14201 (if have
14202 (if remove
14203 (replace-match "" t t nil 1)
14204 (replace-match news t t nil 2))
14205 (if remove
14206 (user-error "No priority cookie found in line")
14207 (let ((case-fold-search nil))
14208 (looking-at org-todo-line-regexp))
14209 (if (match-end 2)
14210 (progn
14211 (goto-char (match-end 2))
14212 (insert " [#" news "]"))
14213 (goto-char (match-beginning 3))
14214 (insert "[#" news "] "))))
14215 (org-set-tags nil 'align))
14216 (if remove
14217 (message "Priority removed")
14218 (message "Priority of current item set to %s" news)))))
14220 (defun org-show-priority ()
14221 "Show the priority of the current item.
14222 This priority is composed of the main priority given with the [#A] cookies,
14223 and by additional input from the age of a schedules or deadline entry."
14224 (interactive)
14225 (let ((pri (if (eq major-mode 'org-agenda-mode)
14226 (org-get-at-bol 'priority)
14227 (save-excursion
14228 (save-match-data
14229 (beginning-of-line)
14230 (and (looking-at org-heading-regexp)
14231 (org-get-priority (match-string 0))))))))
14232 (message "Priority is %d" (if pri pri -1000))))
14234 (defun org-get-priority (s)
14235 "Find priority cookie and return priority."
14236 (save-match-data
14237 (if (functionp org-get-priority-function)
14238 (funcall org-get-priority-function)
14239 (if (not (string-match org-priority-regexp s))
14240 (* 1000 (- org-lowest-priority org-default-priority))
14241 (* 1000 (- org-lowest-priority
14242 (string-to-char (match-string 2 s))))))))
14244 ;;;; Tags
14246 (defvar org-agenda-archives-mode)
14247 (defvar org-map-continue-from nil
14248 "Position from where mapping should continue.
14249 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14251 (defvar org-scanner-tags nil
14252 "The current tag list while the tags scanner is running.")
14254 (defvar org-trust-scanner-tags nil
14255 "Should `org-get-tags-at' use the tags for the scanner.
14256 This is for internal dynamical scoping only.
14257 When this is non-nil, the function `org-get-tags-at' will return the value
14258 of `org-scanner-tags' instead of building the list by itself. This
14259 can lead to large speed-ups when the tags scanner is used in a file with
14260 many entries, and when the list of tags is retrieved, for example to
14261 obtain a list of properties. Building the tags list for each entry in such
14262 a file becomes an N^2 operation - but with this variable set, it scales
14263 as N.")
14265 (defvar org--matcher-tags-todo-only nil)
14267 (defun org-scan-tags (action matcher todo-only &optional start-level)
14268 "Scan headline tags with inheritance and produce output ACTION.
14270 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14271 or `agenda' to produce an entry list for an agenda view. It can also be
14272 a Lisp form or a function that should be called at each matched headline, in
14273 this case the return value is a list of all return values from these calls.
14275 MATCHER is a function accepting three arguments, returning
14276 a non-nil value whenever a given set of tags qualifies a headline
14277 for inclusion. See `org-make-tags-matcher' for more information.
14278 As a special case, it can also be set to t (respectively nil) in
14279 order to match all (respectively none) headline.
14281 When TODO-ONLY is non-nil, only lines with a not-done TODO
14282 keyword are included in the output.
14284 START-LEVEL can be a string with asterisks, reducing the scope to
14285 headlines matching this string."
14286 (require 'org-agenda)
14287 (let* ((re (concat "^"
14288 (if start-level
14289 ;; Get the correct level to match
14290 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14291 org-outline-regexp)
14292 " *\\(\\<\\("
14293 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14294 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14295 (props (list 'face 'default
14296 'done-face 'org-agenda-done
14297 'undone-face 'default
14298 'mouse-face 'highlight
14299 'org-not-done-regexp org-not-done-regexp
14300 'org-todo-regexp org-todo-regexp
14301 'org-complex-heading-regexp org-complex-heading-regexp
14302 'help-echo
14303 (format "mouse-2 or RET jump to org file %s"
14304 (abbreviate-file-name
14305 (or (buffer-file-name (buffer-base-buffer))
14306 (buffer-name (buffer-base-buffer)))))))
14307 (org-map-continue-from nil)
14308 lspos tags tags-list
14309 (tags-alist (list (cons 0 org-file-tags)))
14310 (llast 0) rtn rtn1 level category i txt
14311 todo marker entry priority
14312 ts-date ts-date-type ts-date-pair)
14313 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14314 (setq action (list 'lambda nil action)))
14315 (save-excursion
14316 (goto-char (point-min))
14317 (when (eq action 'sparse-tree)
14318 (org-overview)
14319 (org-remove-occur-highlights))
14320 (while (let (case-fold-search)
14321 (re-search-forward re nil t))
14322 (setq org-map-continue-from nil)
14323 (catch :skip
14324 (setq todo
14325 ;; TODO: is the 1-2 difference a bug?
14326 (when (match-end 1) (match-string-no-properties 2))
14327 tags (when (match-end 4) (match-string-no-properties 4)))
14328 (goto-char (setq lspos (match-beginning 0)))
14329 (setq level (org-reduced-level (org-outline-level))
14330 category (org-get-category))
14331 (when (eq action 'agenda)
14332 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14333 ts-date (car ts-date-pair)
14334 ts-date-type (cdr ts-date-pair)))
14335 (setq i llast llast level)
14336 ;; remove tag lists from same and sublevels
14337 (while (>= i level)
14338 (when (setq entry (assoc i tags-alist))
14339 (setq tags-alist (delete entry tags-alist)))
14340 (setq i (1- i)))
14341 ;; add the next tags
14342 (when tags
14343 (setq tags (org-split-string tags ":")
14344 tags-alist
14345 (cons (cons level tags) tags-alist)))
14346 ;; compile tags for current headline
14347 (setq tags-list
14348 (if org-use-tag-inheritance
14349 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14350 tags)
14351 org-scanner-tags tags-list)
14352 (when org-use-tag-inheritance
14353 (setcdr (car tags-alist)
14354 (mapcar (lambda (x)
14355 (setq x (copy-sequence x))
14356 (org-add-prop-inherited x))
14357 (cdar tags-alist))))
14358 (when (and tags org-use-tag-inheritance
14359 (or (not (eq t org-use-tag-inheritance))
14360 org-tags-exclude-from-inheritance))
14361 ;; Selective inheritance, remove uninherited ones.
14362 (setcdr (car tags-alist)
14363 (org-remove-uninherited-tags (cdar tags-alist))))
14364 (when (and
14366 ;; eval matcher only when the todo condition is OK
14367 (and (or (not todo-only) (member todo org-not-done-keywords))
14368 (if (functionp matcher)
14369 (let ((case-fold-search t) (org-trust-scanner-tags t))
14370 (funcall matcher todo tags-list level))
14371 matcher))
14373 ;; Call the skipper, but return t if it does not
14374 ;; skip, so that the `and' form continues evaluating.
14375 (progn
14376 (unless (eq action 'sparse-tree) (org-agenda-skip))
14379 ;; Check if timestamps are deselecting this entry
14380 (or (not todo-only)
14381 (and (member todo org-not-done-keywords)
14382 (or (not org-agenda-tags-todo-honor-ignore-options)
14383 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14385 ;; select this headline
14386 (cond
14387 ((eq action 'sparse-tree)
14388 (and org-highlight-sparse-tree-matches
14389 (org-get-heading) (match-end 0)
14390 (org-highlight-new-match
14391 (match-beginning 1) (match-end 1)))
14392 (org-show-context 'tags-tree))
14393 ((eq action 'agenda)
14394 (setq txt (org-agenda-format-item
14396 (concat
14397 (if (eq org-tags-match-list-sublevels 'indented)
14398 (make-string (1- level) ?.) "")
14399 (org-get-heading))
14400 (make-string level ?\s)
14401 category
14402 tags-list)
14403 priority (org-get-priority txt))
14404 (goto-char lspos)
14405 (setq marker (org-agenda-new-marker))
14406 (org-add-props txt props
14407 'org-marker marker 'org-hd-marker marker 'org-category category
14408 'todo-state todo
14409 'ts-date ts-date
14410 'priority priority
14411 'type (concat "tagsmatch" ts-date-type))
14412 (push txt rtn))
14413 ((functionp action)
14414 (setq org-map-continue-from nil)
14415 (save-excursion
14416 (setq rtn1 (funcall action))
14417 (push rtn1 rtn)))
14418 (t (user-error "Invalid action")))
14420 ;; if we are to skip sublevels, jump to end of subtree
14421 (unless org-tags-match-list-sublevels
14422 (org-end-of-subtree t)
14423 (backward-char 1))))
14424 ;; Get the correct position from where to continue
14425 (if org-map-continue-from
14426 (goto-char org-map-continue-from)
14427 (and (= (point) lspos) (end-of-line 1)))))
14428 (when (and (eq action 'sparse-tree)
14429 (not org-sparse-tree-open-archived-trees))
14430 (org-hide-archived-subtrees (point-min) (point-max)))
14431 (nreverse rtn)))
14433 (defun org-remove-uninherited-tags (tags)
14434 "Remove all tags that are not inherited from the list TAGS."
14435 (cond
14436 ((eq org-use-tag-inheritance t)
14437 (if org-tags-exclude-from-inheritance
14438 (org-delete-all org-tags-exclude-from-inheritance tags)
14439 tags))
14440 ((not org-use-tag-inheritance) nil)
14441 ((stringp org-use-tag-inheritance)
14442 (delq nil (mapcar
14443 (lambda (x)
14444 (if (and (string-match org-use-tag-inheritance x)
14445 (not (member x org-tags-exclude-from-inheritance)))
14446 x nil))
14447 tags)))
14448 ((listp org-use-tag-inheritance)
14449 (delq nil (mapcar
14450 (lambda (x)
14451 (if (member x org-use-tag-inheritance) x nil))
14452 tags)))))
14454 (defun org-match-sparse-tree (&optional todo-only match)
14455 "Create a sparse tree according to tags string MATCH.
14456 MATCH can contain positive and negative selection of tags, like
14457 \"+WORK+URGENT-WITHBOSS\".
14458 If optional argument TODO-ONLY is non-nil, only select lines that are
14459 also TODO lines."
14460 (interactive "P")
14461 (org-agenda-prepare-buffers (list (current-buffer)))
14462 (let ((org--matcher-tags-todo-only todo-only))
14463 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14464 org--matcher-tags-todo-only)))
14466 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14468 (defvar org-cached-props nil)
14469 (defun org-cached-entry-get (pom property)
14470 (if (or (eq t org-use-property-inheritance)
14471 (and (stringp org-use-property-inheritance)
14472 (let ((case-fold-search t))
14473 (string-match-p org-use-property-inheritance property)))
14474 (and (listp org-use-property-inheritance)
14475 (member-ignore-case property org-use-property-inheritance)))
14476 ;; Caching is not possible, check it directly.
14477 (org-entry-get pom property 'inherit)
14478 ;; Get all properties, so we can do complicated checks easily.
14479 (cdr (assoc-string property
14480 (or org-cached-props
14481 (setq org-cached-props (org-entry-properties pom)))
14482 t))))
14484 (defun org-global-tags-completion-table (&optional files)
14485 "Return the list of all tags in all agenda buffer/files.
14486 Optional FILES argument is a list of files which can be used
14487 instead of the agenda files."
14488 (save-excursion
14489 (org-uniquify
14490 (delq nil
14491 (apply #'append
14492 (mapcar
14493 (lambda (file)
14494 (set-buffer (find-file-noselect file))
14495 (mapcar (lambda (x)
14496 (and (stringp (car-safe x))
14497 (list (car-safe x))))
14498 (or org-current-tag-alist (org-get-buffer-tags))))
14499 (if (car-safe files) files
14500 (org-agenda-files))))))))
14502 (defun org-make-tags-matcher (match)
14503 "Create the TAGS/TODO matcher form for the selection string MATCH.
14505 Returns a cons of the selection string MATCH and a function
14506 implementing the matcher.
14508 The matcher is to be called at an Org entry, with point on the
14509 headline, and returns non-nil if the entry matches the selection
14510 string MATCH. It must be called with three arguments: the TODO
14511 keyword at the entry (or nil if none), the list of all tags at
14512 the entry including inherited ones and the reduced level of the
14513 headline. Additionally, the category of the entry, if any, must
14514 be specified as the text property `org-category' on the headline.
14516 This function sets the variable `org--matcher-tags-todo-only' to
14517 a non-nil value if the matcher restricts matching to TODO
14518 entries, otherwise it is not touched.
14520 See also `org-scan-tags'."
14521 (unless match
14522 ;; Get a new match request, with completion against the global
14523 ;; tags table and the local tags in current buffer.
14524 (let ((org-last-tags-completion-table
14525 (org-uniquify
14526 (delq nil (append (org-get-buffer-tags)
14527 (org-global-tags-completion-table))))))
14528 (setq match
14529 (completing-read
14530 "Match: "
14531 'org-tags-completion-function nil nil nil 'org-tags-history))))
14533 (let ((match0 match)
14534 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14535 (start 0)
14536 tagsmatch todomatch tagsmatcher todomatcher)
14538 ;; Expand group tags.
14539 (setq match (org-tags-expand match))
14541 ;; Check if there is a TODO part of this match, which would be the
14542 ;; part after a "/". To make sure that this slash is not part of
14543 ;; a property value to be matched against, we also check that
14544 ;; there is no / after that slash. First, find the last slash.
14545 (let ((s 0))
14546 (while (string-match "/+" match s)
14547 (setq start (match-beginning 0))
14548 (setq s (match-end 0))))
14549 (if (and (string-match "/+" match start)
14550 (not (string-match-p "\"" match start)))
14551 ;; Match contains also a TODO-matching request.
14552 (progn
14553 (setq tagsmatch (substring match 0 (match-beginning 0)))
14554 (setq todomatch (substring match (match-end 0)))
14555 (when (string-prefix-p "!" todomatch)
14556 (setq org--matcher-tags-todo-only t)
14557 (setq todomatch (substring todomatch 1)))
14558 (when (string-match "\\`\\s-*\\'" todomatch)
14559 (setq todomatch nil)))
14560 ;; Only matching tags.
14561 (setq tagsmatch match)
14562 (setq todomatch nil))
14564 ;; Make the tags matcher.
14565 (when (org-string-nw-p tagsmatch)
14566 (let ((orlist nil)
14567 (orterms (org-split-string tagsmatch "|"))
14568 term)
14569 (while (setq term (pop orterms))
14570 (while (and (equal (substring term -1) "\\") orterms)
14571 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14572 (while (string-match re term)
14573 (let* ((rest (substring term (match-end 0)))
14574 (minus (and (match-end 1)
14575 (equal (match-string 1 term) "-")))
14576 (tag (save-match-data
14577 (replace-regexp-in-string
14578 "\\\\-" "-" (match-string 2 term))))
14579 (regexp (eq (string-to-char tag) ?{))
14580 (levelp (match-end 4))
14581 (propp (match-end 5))
14583 (cond
14584 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14585 (levelp
14586 `(,(org-op-to-function (match-string 3 term))
14587 level
14588 ,(string-to-number (match-string 4 term))))
14589 (propp
14590 (let* ((gv (pcase (upcase (match-string 5 term))
14591 ("CATEGORY"
14592 '(get-text-property (point) 'org-category))
14593 ("TODO" 'todo)
14594 (p `(org-cached-entry-get nil ,p))))
14595 (pv (match-string 7 term))
14596 (regexp (eq (string-to-char pv) ?{))
14597 (strp (eq (string-to-char pv) ?\"))
14598 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14599 (po (org-op-to-function (match-string 6 term)
14600 (if timep 'time strp))))
14601 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14602 (when timep (setq pv (org-matcher-time pv)))
14603 (cond ((and regexp (eq po 'org<>))
14604 `(not (string-match ,pv (or ,gv ""))))
14605 (regexp `(string-match ,pv (or ,gv "")))
14606 (strp `(,po (or ,gv "") ,pv))
14608 `(,po
14609 (string-to-number (or ,gv ""))
14610 ,(string-to-number pv))))))
14611 (t `(member ,tag tags-list)))))
14612 (push (if minus `(not ,mm) mm) tagsmatcher)
14613 (setq term rest)))
14614 (push `(and ,@tagsmatcher) orlist)
14615 (setq tagsmatcher nil))
14616 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14618 ;; Make the TODO matcher.
14619 (when (org-string-nw-p todomatch)
14620 (let ((orlist nil))
14621 (dolist (term (org-split-string todomatch "|"))
14622 (while (string-match re term)
14623 (let* ((minus (and (match-end 1)
14624 (equal (match-string 1 term) "-")))
14625 (kwd (match-string 2 term))
14626 (regexp (eq (string-to-char kwd) ?{))
14627 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14628 `(equal todo ,kwd))))
14629 (push (if minus `(not ,mm) mm) todomatcher))
14630 (setq term (substring term (match-end 0))))
14631 (push (if (> (length todomatcher) 1)
14632 (cons 'and todomatcher)
14633 (car todomatcher))
14634 orlist)
14635 (setq todomatcher nil))
14636 (setq todomatcher (cons 'or orlist))))
14638 ;; Return the string and function of the matcher. If no
14639 ;; tags-specific or todo-specific matcher exists, match
14640 ;; everything.
14641 (let ((matcher (if (and tagsmatcher todomatcher)
14642 `(and ,tagsmatcher ,todomatcher)
14643 (or tagsmatcher todomatcher t))))
14644 (when org--matcher-tags-todo-only
14645 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14646 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14648 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14649 "Expand group tags in MATCH.
14651 This replaces every group tag in MATCH with a regexp tag search.
14652 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14653 will be replaced like this:
14655 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14656 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14657 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14659 Replacing by a regexp preserves the structure of the match.
14660 E.g., this expansion
14662 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14664 will match anything tagged with \"Lab\" and \"Home\", or tagged
14665 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14667 A group tag in MATCH can contain regular expressions of its own.
14668 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14669 will be replaced like this:
14671 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14673 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14674 assumed to be a single group tag, and the function will return
14675 the list of tags in this group.
14677 When DOWNCASE is non-nil, expand downcased TAGS."
14678 (if org-group-tags
14679 (let* ((case-fold-search t)
14680 (stable org-mode-syntax-table)
14681 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14682 (taggroups (if downcased
14683 (mapcar (lambda (tg) (mapcar #'downcase tg))
14684 taggroups)
14685 taggroups))
14686 (taggroups-keys (mapcar #'car taggroups))
14687 (return-match (if downcased (downcase match) match))
14688 (count 0)
14689 (work-already-expanded tags-already-expanded)
14690 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14691 ;; @ and _ are allowed as word-components in tags.
14692 (modify-syntax-entry ?@ "w" stable)
14693 (modify-syntax-entry ?_ "w" stable)
14694 ;; Temporarily replace regexp-expressions in the match-expression.
14695 (while (string-match "{.+?}" return-match)
14696 (cl-incf count)
14697 (push (match-string 0 return-match) regexps-in-match)
14698 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14699 (while (and taggroups-keys
14700 (with-syntax-table stable
14701 (string-match
14702 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14703 (regexp-opt taggroups-keys) "\\>\\)")
14704 return-match)))
14705 (let* ((dir (match-string 1 return-match))
14706 (tag (match-string 2 return-match))
14707 (tag (if downcased (downcase tag) tag)))
14708 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14709 (member tag work-already-expanded))
14710 (setq tags-in-group (assoc tag taggroups))
14711 (push tag work-already-expanded)
14712 ;; Recursively expand each tag in the group, if the tag hasn't
14713 ;; already been expanded. Restore the match-data after all recursive calls.
14714 (save-match-data
14715 (let (tags-expanded)
14716 (dolist (x (cdr tags-in-group))
14717 (if (and (member x taggroups-keys)
14718 (not (member x work-already-expanded)))
14719 (setq tags-expanded
14720 (delete-dups
14721 (append
14722 (org-tags-expand x t downcased
14723 work-already-expanded)
14724 tags-expanded)))
14725 (setq tags-expanded
14726 (append (list x) tags-expanded)))
14727 (setq work-already-expanded
14728 (delete-dups
14729 (append tags-expanded
14730 work-already-expanded))))
14731 (setq tags-in-group
14732 (delete-dups (cons (car tags-in-group)
14733 tags-expanded)))))
14734 ;; Filter tag-regexps from tags.
14735 (setq regexp-in-group-escaped
14736 (delq nil (mapcar (lambda (x)
14737 (if (stringp x)
14738 (and (equal "{" (substring x 0 1))
14739 (equal "}" (substring x -1))
14742 tags-in-group))
14743 regexp-in-group
14744 (mapcar (lambda (x)
14745 (substring x 1 -1))
14746 regexp-in-group-escaped)
14747 tags-in-group
14748 (delq nil (mapcar (lambda (x)
14749 (if (stringp x)
14750 (and (not (equal "{" (substring x 0 1)))
14751 (not (equal "}" (substring x -1)))
14754 tags-in-group)))
14755 ;; If single-as-list, do no more in the while-loop.
14756 (if (not single-as-list)
14757 (progn
14758 (when regexp-in-group
14759 (setq regexp-in-group
14760 (concat "\\|"
14761 (mapconcat 'identity regexp-in-group
14762 "\\|"))))
14763 (setq tags-in-group
14764 (concat dir
14765 "{\\<"
14766 (regexp-opt tags-in-group)
14767 "\\>"
14768 regexp-in-group
14769 "}"))
14770 (when (stringp tags-in-group)
14771 (org-add-props tags-in-group '(grouptag t)))
14772 (setq return-match
14773 (replace-match tags-in-group t t return-match)))
14774 (setq tags-in-group
14775 (append regexp-in-group-escaped tags-in-group))))
14776 (setq taggroups-keys (delete tag taggroups-keys))))
14777 ;; Add the regular expressions back into the match-expression again.
14778 (while regexps-in-match
14779 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14780 (pop regexps-in-match)
14781 return-match t t))
14782 (cl-decf count))
14783 (if single-as-list
14784 (if tags-in-group tags-in-group (list return-match))
14785 return-match))
14786 (if single-as-list
14787 (list (if downcased (downcase match) match))
14788 match)))
14790 (defun org-op-to-function (op &optional stringp)
14791 "Turn an operator into the appropriate function."
14792 (setq op
14793 (cond
14794 ((equal op "<" ) '(< string< org-time<))
14795 ((equal op ">" ) '(> org-string> org-time>))
14796 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14797 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14798 ((member op '("=" "==")) '(= string= org-time=))
14799 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14800 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14802 (defun org<> (a b) (not (= a b)))
14803 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14804 (defun org-string>= (a b) (not (string< a b)))
14805 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14806 (defun org-string<> (a b) (not (string= a b)))
14807 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14808 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14809 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14810 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14811 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14812 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14813 (defun org-2ft (s)
14814 "Convert S to a floating point time.
14815 If S is already a number, just return it. If it is a string, parse
14816 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14817 (cond
14818 ((numberp s) s)
14819 ((stringp s)
14820 (condition-case nil
14821 (float-time (apply 'encode-time (org-parse-time-string s)))
14822 (error 0.)))
14823 (t 0.)))
14825 (defun org-time-today ()
14826 "Time in seconds today at 0:00.
14827 Returns the float number of seconds since the beginning of the
14828 epoch to the beginning of today (00:00)."
14829 (float-time (apply 'encode-time
14830 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14832 (defun org-matcher-time (s)
14833 "Interpret a time comparison value."
14834 (save-match-data
14835 (cond
14836 ((string= s "<now>") (float-time))
14837 ((string= s "<today>") (org-time-today))
14838 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14839 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14840 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14841 (+ (org-time-today)
14842 (* (string-to-number (match-string 1 s))
14843 (cdr (assoc (match-string 2 s)
14844 '(("d" . 86400.0) ("w" . 604800.0)
14845 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14846 (t (org-2ft s)))))
14848 (defun org-match-any-p (re list)
14849 "Does re match any element of list?"
14850 (setq list (mapcar (lambda (x) (string-match re x)) list))
14851 (delq nil list))
14853 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14854 (defvar org-tags-overlay (make-overlay 1 1))
14855 (delete-overlay org-tags-overlay)
14857 (defun org-get-local-tags-at (&optional pos)
14858 "Get a list of tags defined in the current headline."
14859 (org-get-tags-at pos 'local))
14861 (defun org-get-local-tags ()
14862 "Get a list of tags defined in the current headline."
14863 (org-get-tags-at nil 'local))
14865 (defun org-get-tags-at (&optional pos local)
14866 "Get a list of all headline tags applicable at POS.
14867 POS defaults to point. If tags are inherited, the list contains
14868 the targets in the same sequence as the headlines appear, i.e.
14869 the tags of the current headline come last.
14870 When LOCAL is non-nil, only return tags from the current headline,
14871 ignore inherited ones."
14872 (interactive)
14873 (if (and org-trust-scanner-tags
14874 (or (not pos) (equal pos (point)))
14875 (not local))
14876 org-scanner-tags
14877 (let (tags ltags lastpos parent)
14878 (save-excursion
14879 (save-restriction
14880 (widen)
14881 (goto-char (or pos (point)))
14882 (save-match-data
14883 (catch 'done
14884 (condition-case nil
14885 (progn
14886 (org-back-to-heading t)
14887 (while (not (equal lastpos (point)))
14888 (setq lastpos (point))
14889 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14890 (setq ltags (org-split-string
14891 (match-string-no-properties 1) ":"))
14892 (when parent
14893 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14894 (setq tags (append
14895 (if parent
14896 (org-remove-uninherited-tags ltags)
14897 ltags)
14898 tags)))
14899 (or org-use-tag-inheritance (throw 'done t))
14900 (when local (throw 'done t))
14901 (or (org-up-heading-safe) (error nil))
14902 (setq parent t)))
14903 (error nil)))))
14904 (if local
14905 tags
14906 (reverse (delete-dups
14907 (reverse (append
14908 (org-remove-uninherited-tags
14909 org-file-tags)
14910 tags)))))))))
14912 (defun org-add-prop-inherited (s)
14913 (add-text-properties 0 (length s) '(inherited t) s)
14916 (defun org-toggle-tag (tag &optional onoff)
14917 "Toggle the tag TAG for the current line.
14918 If ONOFF is `on' or `off', don't toggle but set to this state."
14919 (let (res current)
14920 (save-excursion
14921 (org-back-to-heading t)
14922 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14923 (point-at-eol) t)
14924 (progn
14925 (setq current (match-string 1))
14926 (replace-match ""))
14927 (setq current ""))
14928 (setq current (nreverse (org-split-string current ":")))
14929 (cond
14930 ((eq onoff 'on)
14931 (setq res t)
14932 (or (member tag current) (push tag current)))
14933 ((eq onoff 'off)
14934 (or (not (member tag current)) (setq current (delete tag current))))
14935 (t (if (member tag current)
14936 (setq current (delete tag current))
14937 (setq res t)
14938 (push tag current))))
14939 (end-of-line 1)
14940 (if current
14941 (progn
14942 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14943 (org-set-tags nil t))
14944 (delete-horizontal-space))
14945 (run-hooks 'org-after-tags-change-hook))
14946 res))
14948 (defun org-align-tags-here (to-col)
14949 ;; Assumes that this is a headline
14950 "Align tags on the current headline to TO-COL."
14951 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14952 (beginning-of-line 1)
14953 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14954 (< pos (match-beginning 2)))
14955 (progn
14956 (setq tags-l (string-width (match-string 2)))
14957 (goto-char (match-beginning 1))
14958 (insert " ")
14959 (delete-region (point) (1+ (match-beginning 2)))
14960 (setq ncol (max (current-column)
14961 (1+ col)
14962 (if (> to-col 0)
14963 to-col
14964 (- (abs to-col) tags-l))))
14965 (setq p (point))
14966 (insert (make-string (- ncol (current-column)) ?\ ))
14967 (setq ncol (current-column))
14968 (when indent-tabs-mode (tabify p (point-at-eol)))
14969 (org-move-to-column (min ncol col)))
14970 (goto-char pos))))
14972 (defun org-set-tags-command (&optional arg just-align)
14973 "Call the set-tags command for the current entry."
14974 (interactive "P")
14975 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14976 (org-set-tags arg just-align)
14977 (save-excursion
14978 (unless (and (org-region-active-p)
14979 org-loop-over-headlines-in-active-region)
14980 (org-back-to-heading t))
14981 (org-set-tags arg just-align))))
14983 (defun org-set-tags-to (data)
14984 "Set the tags of the current entry to DATA, replacing the current tags.
14985 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14986 If DATA is nil or the empty string, any tags will be removed."
14987 (interactive "sTags: ")
14988 (setq data
14989 (cond
14990 ((eq data nil) "")
14991 ((equal data "") "")
14992 ((stringp data)
14993 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14994 ":"))
14995 ((listp data)
14996 (concat ":" (mapconcat 'identity data ":") ":"))))
14997 (when data
14998 (save-excursion
14999 (org-back-to-heading t)
15000 (when (looking-at org-complex-heading-regexp)
15001 (if (match-end 5)
15002 (progn
15003 (goto-char (match-beginning 5))
15004 (insert data)
15005 (delete-region (point) (point-at-eol))
15006 (org-set-tags nil 'align))
15007 (goto-char (point-at-eol))
15008 (insert " " data)
15009 (org-set-tags nil 'align)))
15010 (beginning-of-line 1)
15011 (when (looking-at ".*?\\([ \t]+\\)$")
15012 (delete-region (match-beginning 1) (match-end 1))))))
15014 (defun org-align-all-tags ()
15015 "Align the tags in all headings."
15016 (interactive)
15017 (save-excursion
15018 (or (ignore-errors (org-back-to-heading t))
15019 (outline-next-heading))
15020 (if (org-at-heading-p)
15021 (org-set-tags t)
15022 (message "No headings"))))
15024 (defvar org-indent-indentation-per-level)
15025 (defun org-set-tags (&optional arg just-align)
15026 "Set the tags for the current headline.
15027 With prefix ARG, realign all tags in headings in the current buffer.
15028 When JUST-ALIGN is non-nil, only align tags."
15029 (interactive "P")
15030 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15031 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15032 'region-start-level
15033 'region))
15034 org-loop-over-headlines-in-active-region)
15035 (org-map-entries
15036 ;; We don't use ARG and JUST-ALIGN here because these args
15037 ;; are not useful when looping over headlines.
15038 #'org-set-tags
15039 org-loop-over-headlines-in-active-region
15041 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15042 (let ((org-setting-tags t))
15043 (if arg
15044 (save-excursion
15045 (goto-char (point-min))
15046 (while (re-search-forward org-outline-regexp-bol nil t)
15047 (org-set-tags nil t)
15048 (end-of-line))
15049 (message "All tags realigned to column %d" org-tags-column))
15050 (let* ((current (org-get-tags-string))
15051 (col (current-column))
15052 (tags
15053 (if just-align current
15054 ;; Get a new set of tags from the user.
15055 (save-excursion
15056 (let* ((seen)
15057 (table
15058 (setq
15059 org-last-tags-completion-table
15060 ;; Uniquify tags in alists, yet preserve
15061 ;; structure (i.e., keywords).
15062 (delq nil
15063 (mapcar
15064 (lambda (pair)
15065 (let ((head (car pair)))
15066 (cond ((symbolp head) pair)
15067 ((member head seen) nil)
15068 (t (push head seen)
15069 pair))))
15070 (append
15071 (or org-current-tag-alist
15072 (org-get-buffer-tags))
15073 (and
15074 org-complete-tags-always-offer-all-agenda-tags
15075 (org-global-tags-completion-table
15076 (org-agenda-files))))))))
15077 (current-tags (org-split-string current ":"))
15078 (inherited-tags
15079 (nreverse (nthcdr (length current-tags)
15080 (nreverse (org-get-tags-at))))))
15081 (replace-regexp-in-string
15082 "\\([-+&]+\\|,\\)"
15084 (if (or (eq t org-use-fast-tag-selection)
15085 (and org-use-fast-tag-selection
15086 (delq nil (mapcar #'cdr table))))
15087 (org-fast-tag-selection
15088 current-tags inherited-tags table
15089 (and org-fast-tag-selection-include-todo
15090 org-todo-key-alist))
15091 (let ((org-add-colon-after-tag-completion
15092 (< 1 (length table))))
15093 (org-trim
15094 (completing-read
15095 "Tags: "
15096 #'org-tags-completion-function
15097 nil nil current 'org-tags-history))))))))))
15099 (when org-tags-sort-function
15100 (setq tags
15101 (mapconcat
15102 #'identity
15103 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15104 org-tags-sort-function)
15105 ":")))
15107 (if (not (org-string-nw-p tags)) (setq tags "")
15108 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15109 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15111 ;; Insert new tags at the correct column
15112 (beginning-of-line)
15113 (let ((level (if (looking-at org-outline-regexp)
15114 (- (match-end 0) (point) 1)
15115 1)))
15116 (cond
15117 ((and (equal current "") (equal tags "")))
15118 ((re-search-forward
15119 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15120 (line-end-position)
15122 (if (equal tags "") (replace-match "" t t)
15123 (goto-char (match-beginning 0))
15124 (let* ((c0 (current-column))
15125 ;; Compute offset for the case of org-indent-mode
15126 ;; active.
15127 (di (if (bound-and-true-p org-indent-mode)
15128 (* (1- org-indent-indentation-per-level)
15129 (1- level))
15131 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15132 (tc (+ org-tags-column
15133 (if (> org-tags-column 0) (- di) di)))
15134 (c1 (max (1+ c0)
15135 (if (> tc 0) tc
15136 (- (- tc) (string-width tags)))))
15137 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15138 (replace-match rpl t t)
15139 (when indent-tabs-mode (tabify p0 (point))))))
15140 (t (error "Tags alignment failed"))))
15141 (org-move-to-column col))
15142 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15144 (defun org-change-tag-in-region (beg end tag off)
15145 "Add or remove TAG for each entry in the region.
15146 This works in the agenda, and also in an Org buffer."
15147 (interactive
15148 (list (region-beginning) (region-end)
15149 (let ((org-last-tags-completion-table
15150 (if (derived-mode-p 'org-mode)
15151 (org-uniquify
15152 (delq nil (append (org-get-buffer-tags)
15153 (org-global-tags-completion-table))))
15154 (org-global-tags-completion-table))))
15155 (completing-read
15156 "Tag: " 'org-tags-completion-function nil nil nil
15157 'org-tags-history))
15158 (progn
15159 (message "[s]et or [r]emove? ")
15160 (equal (read-char-exclusive) ?r))))
15161 (when (fboundp 'deactivate-mark) (deactivate-mark))
15162 (let ((agendap (equal major-mode 'org-agenda-mode))
15163 l1 l2 m buf pos newhead (cnt 0))
15164 (goto-char end)
15165 (setq l2 (1- (org-current-line)))
15166 (goto-char beg)
15167 (setq l1 (org-current-line))
15168 (cl-loop for l from l1 to l2 do
15169 (org-goto-line l)
15170 (setq m (get-text-property (point) 'org-hd-marker))
15171 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15172 (and agendap m))
15173 (setq buf (if agendap (marker-buffer m) (current-buffer))
15174 pos (if agendap m (point)))
15175 (with-current-buffer buf
15176 (save-excursion
15177 (save-restriction
15178 (goto-char pos)
15179 (setq cnt (1+ cnt))
15180 (org-toggle-tag tag (if off 'off 'on))
15181 (setq newhead (org-get-heading)))))
15182 (and agendap (org-agenda-change-all-lines newhead m))))
15183 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15185 (defun org-tags-completion-function (string _predicate &optional flag)
15186 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15187 (confirm (lambda (x) (stringp (car x)))))
15188 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15189 (setq s1 (match-string 1 string)
15190 s2 (match-string 2 string))
15191 (setq s1 "" s2 string))
15192 (cond
15193 ((eq flag nil)
15194 ;; try completion
15195 (setq rtn (try-completion s2 ctable confirm))
15196 (when (stringp rtn)
15197 (setq rtn
15198 (concat s1 s2 (substring rtn (length s2))
15199 (if (and org-add-colon-after-tag-completion
15200 (assoc rtn ctable))
15201 ":" ""))))
15202 rtn)
15203 ((eq flag t)
15204 ;; all-completions
15205 (all-completions s2 ctable confirm))
15206 ((eq flag 'lambda)
15207 ;; exact match?
15208 (assoc s2 ctable)))))
15210 (defun org-fast-tag-insert (kwd tags face &optional end)
15211 "Insert KDW, and the TAGS, the latter with face FACE.
15212 Also insert END."
15213 (insert (format "%-12s" (concat kwd ":"))
15214 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15215 (or end "")))
15217 (defun org-fast-tag-show-exit (flag)
15218 (save-excursion
15219 (org-goto-line 3)
15220 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15221 (replace-match ""))
15222 (when flag
15223 (end-of-line 1)
15224 (org-move-to-column (- (window-width) 19) t)
15225 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15227 (defun org-set-current-tags-overlay (current prefix)
15228 "Add an overlay to CURRENT tag with PREFIX."
15229 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15230 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15231 (org-overlay-display org-tags-overlay (concat prefix s))))
15233 (defvar org-last-tag-selection-key nil)
15234 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15235 "Fast tag selection with single keys.
15236 CURRENT is the current list of tags in the headline, INHERITED is the
15237 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15238 possibly with grouping information. TODO-TABLE is a similar table with
15239 TODO keywords, should these have keys assigned to them.
15240 If the keys are nil, a-z are automatically assigned.
15241 Returns the new tags string, or nil to not change the current settings."
15242 (let* ((fulltable (append table todo-table))
15243 (maxlen (apply 'max (mapcar
15244 (lambda (x)
15245 (if (stringp (car x)) (string-width (car x)) 0))
15246 fulltable)))
15247 (buf (current-buffer))
15248 (expert (eq org-fast-tag-selection-single-key 'expert))
15249 (buffer-tags nil)
15250 (fwidth (+ maxlen 3 1 3))
15251 (ncol (/ (- (window-width) 4) fwidth))
15252 (i-face 'org-done)
15253 (c-face 'org-todo)
15254 tg cnt e c char c1 c2 ntable tbl rtn
15255 ov-start ov-end ov-prefix
15256 (exit-after-next org-fast-tag-selection-single-key)
15257 (done-keywords org-done-keywords)
15258 groups ingroup intaggroup)
15259 (save-excursion
15260 (beginning-of-line 1)
15261 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15262 (setq ov-start (match-beginning 1)
15263 ov-end (match-end 1)
15264 ov-prefix "")
15265 (setq ov-start (1- (point-at-eol))
15266 ov-end (1+ ov-start))
15267 (skip-chars-forward "^\n\r")
15268 (setq ov-prefix
15269 (concat
15270 (buffer-substring (1- (point)) (point))
15271 (if (> (current-column) org-tags-column)
15273 (make-string (- org-tags-column (current-column)) ?\ ))))))
15274 (move-overlay org-tags-overlay ov-start ov-end)
15275 (save-window-excursion
15276 (if expert
15277 (set-buffer (get-buffer-create " *Org tags*"))
15278 (delete-other-windows)
15279 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15280 (org-switch-to-buffer-other-window " *Org tags*"))
15281 (erase-buffer)
15282 (setq-local org-done-keywords done-keywords)
15283 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15284 (org-fast-tag-insert "Current" current c-face "\n\n")
15285 (org-fast-tag-show-exit exit-after-next)
15286 (org-set-current-tags-overlay current ov-prefix)
15287 (setq tbl fulltable char ?a cnt 0)
15288 (while (setq e (pop tbl))
15289 (cond
15290 ((eq (car e) :startgroup)
15291 (push '() groups) (setq ingroup t)
15292 (unless (zerop cnt)
15293 (setq cnt 0)
15294 (insert "\n"))
15295 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15296 ((eq (car e) :endgroup)
15297 (setq ingroup nil cnt 0)
15298 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15299 ((eq (car e) :startgrouptag)
15300 (setq intaggroup t)
15301 (unless (zerop cnt)
15302 (setq cnt 0)
15303 (insert "\n"))
15304 (insert "[ "))
15305 ((eq (car e) :endgrouptag)
15306 (setq intaggroup nil cnt 0)
15307 (insert "]\n"))
15308 ((equal e '(:newline))
15309 (unless (zerop cnt)
15310 (setq cnt 0)
15311 (insert "\n")
15312 (setq e (car tbl))
15313 (while (equal (car tbl) '(:newline))
15314 (insert "\n")
15315 (setq tbl (cdr tbl)))))
15316 ((equal e '(:grouptags)) (insert " : "))
15318 (setq tg (copy-sequence (car e)) c2 nil)
15319 (if (cdr e)
15320 (setq c (cdr e))
15321 ;; automatically assign a character.
15322 (setq c1 (string-to-char
15323 (downcase (substring
15324 tg (if (= (string-to-char tg) ?@) 1 0)))))
15325 (if (or (rassoc c1 ntable) (rassoc c1 table))
15326 (while (or (rassoc char ntable) (rassoc char table))
15327 (setq char (1+ char)))
15328 (setq c2 c1))
15329 (setq c (or c2 char)))
15330 (when ingroup (push tg (car groups)))
15331 (setq tg (org-add-props tg nil 'face
15332 (cond
15333 ((not (assoc tg table))
15334 (org-get-todo-face tg))
15335 ((member tg current) c-face)
15336 ((member tg inherited) i-face))))
15337 (when (equal (caar tbl) :grouptags)
15338 (org-add-props tg nil 'face 'org-tag-group))
15339 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15340 (insert "[" c "] " tg (make-string
15341 (- fwidth 4 (length tg)) ?\ ))
15342 (push (cons tg c) ntable)
15343 (when (= (cl-incf cnt) ncol)
15344 (insert "\n")
15345 (when (or ingroup intaggroup) (insert " "))
15346 (setq cnt 0)))))
15347 (setq ntable (nreverse ntable))
15348 (insert "\n")
15349 (goto-char (point-min))
15350 (unless expert (org-fit-window-to-buffer))
15351 (setq rtn
15352 (catch 'exit
15353 (while t
15354 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15355 (if (not groups) "no " "")
15356 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15357 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15358 (setq org-last-tag-selection-key c)
15359 (cond
15360 ((= c ?\r) (throw 'exit t))
15361 ((= c ?!)
15362 (setq groups (not groups))
15363 (goto-char (point-min))
15364 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15365 ((= c ?\C-c)
15366 (if (not expert)
15367 (org-fast-tag-show-exit
15368 (setq exit-after-next (not exit-after-next)))
15369 (setq expert nil)
15370 (delete-other-windows)
15371 (set-window-buffer (split-window-vertically) " *Org tags*")
15372 (org-switch-to-buffer-other-window " *Org tags*")
15373 (org-fit-window-to-buffer)))
15374 ((or (= c ?\C-g)
15375 (and (= c ?q) (not (rassoc c ntable))))
15376 (delete-overlay org-tags-overlay)
15377 (setq quit-flag t))
15378 ((= c ?\ )
15379 (setq current nil)
15380 (when exit-after-next (setq exit-after-next 'now)))
15381 ((= c ?\t)
15382 (condition-case nil
15383 (setq tg (completing-read
15384 "Tag: "
15385 (or buffer-tags
15386 (with-current-buffer buf
15387 (setq buffer-tags
15388 (org-get-buffer-tags))))))
15389 (quit (setq tg "")))
15390 (when (string-match "\\S-" tg)
15391 (cl-pushnew (list tg) buffer-tags :test #'equal)
15392 (if (member tg current)
15393 (setq current (delete tg current))
15394 (push tg current)))
15395 (when exit-after-next (setq exit-after-next 'now)))
15396 ((setq e (rassoc c todo-table) tg (car e))
15397 (with-current-buffer buf
15398 (save-excursion (org-todo tg)))
15399 (when exit-after-next (setq exit-after-next 'now)))
15400 ((setq e (rassoc c ntable) tg (car e))
15401 (if (member tg current)
15402 (setq current (delete tg current))
15403 (cl-loop for g in groups do
15404 (when (member tg g)
15405 (dolist (x g) (setq current (delete x current)))))
15406 (push tg current))
15407 (when exit-after-next (setq exit-after-next 'now))))
15409 ;; Create a sorted list
15410 (setq current
15411 (sort current
15412 (lambda (a b)
15413 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15414 (when (eq exit-after-next 'now) (throw 'exit t))
15415 (goto-char (point-min))
15416 (beginning-of-line 2)
15417 (delete-region (point) (point-at-eol))
15418 (org-fast-tag-insert "Current" current c-face)
15419 (org-set-current-tags-overlay current ov-prefix)
15420 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15421 (setq tg (match-string 1))
15422 (add-text-properties
15423 (match-beginning 1) (match-end 1)
15424 (list 'face
15425 (cond
15426 ((member tg current) c-face)
15427 ((member tg inherited) i-face)
15428 (t (get-text-property (match-beginning 1) 'face))))))
15429 (goto-char (point-min)))))
15430 (delete-overlay org-tags-overlay)
15431 (if rtn
15432 (mapconcat 'identity current ":")
15433 nil))))
15435 (defun org-get-tags-string ()
15436 "Get the TAGS string in the current headline."
15437 (unless (org-at-heading-p t)
15438 (user-error "Not on a heading"))
15439 (save-excursion
15440 (beginning-of-line 1)
15441 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15442 (match-string-no-properties 1)
15443 "")))
15445 (defun org-get-tags ()
15446 "Get the list of tags specified in the current headline."
15447 (org-split-string (org-get-tags-string) ":"))
15449 (defun org-get-buffer-tags ()
15450 "Get a table of all tags used in the buffer, for completion."
15451 (org-with-wide-buffer
15452 (goto-char (point-min))
15453 (let ((tag-re (concat org-outline-regexp-bol
15454 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15455 tags)
15456 (while (re-search-forward tag-re nil t)
15457 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15458 (push tag tags)))
15459 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15461 ;;;; The mapping API
15463 (defvar org-agenda-skip-comment-trees)
15464 (defvar org-agenda-skip-function)
15465 (defun org-map-entries (func &optional match scope &rest skip)
15466 "Call FUNC at each headline selected by MATCH in SCOPE.
15468 FUNC is a function or a lisp form. The function will be called without
15469 arguments, with the cursor positioned at the beginning of the headline.
15470 The return values of all calls to the function will be collected and
15471 returned as a list.
15473 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15474 does not need to preserve point. After evaluation, the cursor will be
15475 moved to the end of the line (presumably of the headline of the
15476 processed entry) and search continues from there. Under some
15477 circumstances, this may not produce the wanted results. For example,
15478 if you have removed (e.g. archived) the current (sub)tree it could
15479 mean that the next entry will be skipped entirely. In such cases, you
15480 can specify the position from where search should continue by making
15481 FUNC set the variable `org-map-continue-from' to the desired buffer
15482 position.
15484 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15485 Only headlines that are matched by this query will be considered during
15486 the iteration. When MATCH is nil or t, all headlines will be
15487 visited by the iteration.
15489 SCOPE determines the scope of this command. It can be any of:
15491 nil The current buffer, respecting the restriction if any
15492 tree The subtree started with the entry at point
15493 region The entries within the active region, if any
15494 region-start-level
15495 The entries within the active region, but only those at
15496 the same level than the first one.
15497 file The current buffer, without restriction
15498 file-with-archives
15499 The current buffer, and any archives associated with it
15500 agenda All agenda files
15501 agenda-with-archives
15502 All agenda files with any archive files associated with them
15503 \(file1 file2 ...)
15504 If this is a list, all files in the list will be scanned
15506 The remaining args are treated as settings for the skipping facilities of
15507 the scanner. The following items can be given here:
15509 archive skip trees with the archive tag
15510 comment skip trees with the COMMENT keyword
15511 function or Emacs Lisp form:
15512 will be used as value for `org-agenda-skip-function', so
15513 whenever the function returns a position, FUNC will not be
15514 called for that entry and search will continue from the
15515 position returned
15517 If your function needs to retrieve the tags including inherited tags
15518 at the *current* entry, you can use the value of the variable
15519 `org-scanner-tags' which will be much faster than getting the value
15520 with `org-get-tags-at'. If your function gets properties with
15521 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15522 to t around the call to `org-entry-properties' to get the same speedup.
15523 Note that if your function moves around to retrieve tags and properties at
15524 a *different* entry, you cannot use these techniques."
15525 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15526 (not (org-region-active-p)))
15527 (let* ((org-agenda-archives-mode nil) ; just to make sure
15528 (org-agenda-skip-archived-trees (memq 'archive skip))
15529 (org-agenda-skip-comment-trees (memq 'comment skip))
15530 (org-agenda-skip-function
15531 (car (org-delete-all '(comment archive) skip)))
15532 (org-tags-match-list-sublevels t)
15533 (start-level (eq scope 'region-start-level))
15534 matcher res
15535 org-todo-keywords-for-agenda
15536 org-done-keywords-for-agenda
15537 org-todo-keyword-alist-for-agenda
15538 org-tag-alist-for-agenda
15539 org--matcher-tags-todo-only)
15541 (cond
15542 ((eq match t) (setq matcher t))
15543 ((eq match nil) (setq matcher t))
15544 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15546 (save-excursion
15547 (save-restriction
15548 (cond ((eq scope 'tree)
15549 (org-back-to-heading t)
15550 (org-narrow-to-subtree)
15551 (setq scope nil))
15552 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15553 (org-region-active-p))
15554 ;; If needed, set start-level to a string like "2"
15555 (when start-level
15556 (save-excursion
15557 (goto-char (region-beginning))
15558 (unless (org-at-heading-p) (outline-next-heading))
15559 (setq start-level (org-current-level))))
15560 (narrow-to-region (region-beginning)
15561 (save-excursion
15562 (goto-char (region-end))
15563 (unless (and (bolp) (org-at-heading-p))
15564 (outline-next-heading))
15565 (point)))
15566 (setq scope nil)))
15568 (if (not scope)
15569 (progn
15570 (org-agenda-prepare-buffers
15571 (and buffer-file-name (list buffer-file-name)))
15572 (setq res
15573 (org-scan-tags
15574 func matcher org--matcher-tags-todo-only start-level)))
15575 ;; Get the right scope
15576 (cond
15577 ((and scope (listp scope) (symbolp (car scope)))
15578 (setq scope (eval scope)))
15579 ((eq scope 'agenda)
15580 (setq scope (org-agenda-files t)))
15581 ((eq scope 'agenda-with-archives)
15582 (setq scope (org-agenda-files t))
15583 (setq scope (org-add-archive-files scope)))
15584 ((eq scope 'file)
15585 (setq scope (and buffer-file-name (list buffer-file-name))))
15586 ((eq scope 'file-with-archives)
15587 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15588 (org-agenda-prepare-buffers scope)
15589 (dolist (file scope)
15590 (with-current-buffer (org-find-base-buffer-visiting file)
15591 (org-with-wide-buffer
15592 (goto-char (point-min))
15593 (setq res
15594 (append
15596 (org-scan-tags
15597 func matcher org--matcher-tags-todo-only)))))))))
15598 res)))
15600 ;;; Properties API
15602 (defconst org-special-properties
15603 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15604 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15605 "The special properties valid in Org mode.
15606 These are properties that are not defined in the property drawer,
15607 but in some other way.")
15609 (defconst org-default-properties
15610 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15611 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15612 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15613 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15614 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15615 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15616 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15617 "Some properties that are used by Org mode for various purposes.
15618 Being in this list makes sure that they are offered for completion.")
15620 (defun org--valid-property-p (property)
15621 "Non nil when string PROPERTY is a valid property name."
15622 (not
15623 (or (equal property "")
15624 (string-match-p "\\s-" property))))
15626 (defun org--update-property-plist (key val props)
15627 "Associate KEY to VAL in alist PROPS.
15628 Modifications are made by side-effect. Return new alist."
15629 (let* ((appending (string= (substring key -1) "+"))
15630 (key (if appending (substring key 0 -1) key))
15631 (old (assoc-string key props t)))
15632 (if (not old) (cons (cons key val) props)
15633 (setcdr old (if appending (concat (cdr old) " " val) val))
15634 props)))
15636 (defun org-get-property-block (&optional beg force)
15637 "Return the (beg . end) range of the body of the property drawer.
15638 BEG is the beginning of the current subtree, or of the part
15639 before the first headline. If it is not given, it will be found.
15640 If the drawer does not exist, create it if FORCE is non-nil, or
15641 return nil."
15642 (org-with-wide-buffer
15643 (when beg (goto-char beg))
15644 (unless (org-before-first-heading-p)
15645 (let ((beg (cond (beg)
15646 ((or (not (featurep 'org-inlinetask))
15647 (org-inlinetask-in-task-p))
15648 (org-back-to-heading t))
15649 (t (org-with-limited-levels (org-back-to-heading t))))))
15650 (forward-line)
15651 (when (looking-at-p org-planning-line-re) (forward-line))
15652 (cond ((looking-at org-property-drawer-re)
15653 (forward-line)
15654 (cons (point) (progn (goto-char (match-end 0))
15655 (line-beginning-position))))
15656 (force
15657 (goto-char beg)
15658 (org-insert-property-drawer)
15659 (let ((pos (save-excursion (search-forward ":END:")
15660 (line-beginning-position))))
15661 (cons pos pos))))))))
15663 (defun org-at-property-p ()
15664 "Non-nil when point is inside a property drawer.
15665 See `org-property-re' for match data, if applicable."
15666 (save-excursion
15667 (beginning-of-line)
15668 (and (looking-at org-property-re)
15669 (let ((property-drawer (save-match-data (org-get-property-block))))
15670 (and property-drawer
15671 (>= (point) (car property-drawer))
15672 (< (point) (cdr property-drawer)))))))
15674 (defun org-property-action ()
15675 "Do an action on properties."
15676 (interactive)
15677 (unless (org-at-property-p) (user-error "Not at a property"))
15678 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15679 (let ((c (read-char-exclusive)))
15680 (cl-case c
15681 (?s (call-interactively #'org-set-property))
15682 (?d (call-interactively #'org-delete-property))
15683 (?D (call-interactively #'org-delete-property-globally))
15684 (?c (call-interactively #'org-compute-property-at-point))
15685 (otherwise (user-error "No such property action %c" c)))))
15687 (defun org-inc-effort ()
15688 "Increment the value of the effort property in the current entry."
15689 (interactive)
15690 (org-set-effort nil t))
15692 (defvar org-clock-effort) ; Defined in org-clock.el.
15693 (defvar org-clock-current-task) ; Defined in org-clock.el.
15694 (defun org-set-effort (&optional value increment)
15695 "Set the effort property of the current entry.
15696 With numerical prefix arg, use the nth allowed value, 0 stands for the
15697 10th allowed value.
15699 When INCREMENT is non-nil, set the property to the next allowed value."
15700 (interactive "P")
15701 (when (equal value 0) (setq value 10))
15702 (let* ((completion-ignore-case t)
15703 (prop org-effort-property)
15704 (cur (org-entry-get nil prop))
15705 (allowed (org-property-get-allowed-values nil prop 'table))
15706 (existing (mapcar 'list (org-property-values prop)))
15707 (heading (nth 4 (org-heading-components)))
15709 (val (cond
15710 ((stringp value) value)
15711 ((and allowed (integerp value))
15712 (or (car (nth (1- value) allowed))
15713 (car (org-last allowed))))
15714 ((and allowed increment)
15715 (or (cl-caadr (member (list cur) allowed))
15716 (user-error "Allowed effort values are not set")))
15717 (allowed
15718 (message "Select 1-9,0, [RET%s]: %s"
15719 (if cur (concat "=" cur) "")
15720 (mapconcat 'car allowed " "))
15721 (setq rpl (read-char-exclusive))
15722 (if (equal rpl ?\r)
15724 (setq rpl (- rpl ?0))
15725 (when (equal rpl 0) (setq rpl 10))
15726 (if (and (> rpl 0) (<= rpl (length allowed)))
15727 (car (nth (1- rpl) allowed))
15728 (org-completing-read "Effort: " allowed nil))))
15730 (org-completing-read
15731 (concat "Effort" (and cur (string-match "\\S-" cur)
15732 (concat " [" cur "]"))
15733 ": ")
15734 existing nil nil "" nil cur)))))
15735 (unless (equal (org-entry-get nil prop) val)
15736 (org-entry-put nil prop val))
15737 (org-refresh-property
15738 '((effort . identity)
15739 (effort-minutes . org-duration-string-to-minutes))
15740 val)
15741 (when (equal heading (bound-and-true-p org-clock-current-task))
15742 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15743 (org-clock-update-mode-line))
15744 (message "%s is now %s" prop val)))
15746 (defun org-entry-properties (&optional pom which)
15747 "Get all properties of the current entry.
15749 When POM is a buffer position, get all properties from the entry
15750 there instead.
15752 This includes the TODO keyword, the tags, time strings for
15753 deadline, scheduled, and clocking, and any additional properties
15754 defined in the entry.
15756 If WHICH is nil or `all', get all properties. If WHICH is
15757 `special' or `standard', only get that subclass. If WHICH is
15758 a string, only get that property.
15760 Return value is an alist. Keys are properties, as upcased
15761 strings."
15762 (org-with-point-at pom
15763 (when (and (derived-mode-p 'org-mode)
15764 (ignore-errors (org-back-to-heading t)))
15765 (catch 'exit
15766 (let* ((beg (point))
15767 (specific (and (stringp which) (upcase which)))
15768 (which (cond ((not specific) which)
15769 ((member specific org-special-properties) 'special)
15770 (t 'standard)))
15771 props)
15772 ;; Get the special properties, like TODO and TAGS.
15773 (when (memq which '(nil all special))
15774 (when (or (not specific) (string= specific "CLOCKSUM"))
15775 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15776 (when clocksum
15777 (push (cons "CLOCKSUM"
15778 (org-minutes-to-clocksum-string clocksum))
15779 props)))
15780 (when specific (throw 'exit props)))
15781 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15782 (let ((clocksumt (get-text-property (point)
15783 :org-clock-minutes-today)))
15784 (when clocksumt
15785 (push (cons "CLOCKSUM_T"
15786 (org-minutes-to-clocksum-string clocksumt))
15787 props)))
15788 (when specific (throw 'exit props)))
15789 (when (or (not specific) (string= specific "ITEM"))
15790 (when (looking-at org-complex-heading-regexp)
15791 (push (cons "ITEM"
15792 (let ((title (match-string-no-properties 4)))
15793 (if (org-string-nw-p title)
15794 (org-remove-tabs title)
15795 "")))
15796 props))
15797 (when specific (throw 'exit props)))
15798 (when (or (not specific) (string= specific "TODO"))
15799 (let ((case-fold-search nil))
15800 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15801 (push (cons "TODO" (match-string-no-properties 2)) props)))
15802 (when specific (throw 'exit props)))
15803 (when (or (not specific) (string= specific "PRIORITY"))
15804 (push (cons "PRIORITY"
15805 (if (looking-at org-priority-regexp)
15806 (match-string-no-properties 2)
15807 (char-to-string org-default-priority)))
15808 props)
15809 (when specific (throw 'exit props)))
15810 (when (or (not specific) (string= specific "FILE"))
15811 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15812 props)
15813 (when specific (throw 'exit props)))
15814 (when (or (not specific) (string= specific "TAGS"))
15815 (let ((value (org-string-nw-p (org-get-tags-string))))
15816 (when value (push (cons "TAGS" value) props)))
15817 (when specific (throw 'exit props)))
15818 (when (or (not specific) (string= specific "ALLTAGS"))
15819 (let ((value (org-get-tags-at)))
15820 (when value
15821 (push (cons "ALLTAGS"
15822 (format ":%s:" (mapconcat #'identity value ":")))
15823 props)))
15824 (when specific (throw 'exit props)))
15825 (when (or (not specific) (string= specific "BLOCKED"))
15826 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15827 (when specific (throw 'exit props)))
15828 (when (or (not specific)
15829 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15830 (forward-line)
15831 (when (looking-at-p org-planning-line-re)
15832 (end-of-line)
15833 (let ((bol (line-beginning-position))
15834 ;; Backward compatibility: time keywords used to
15835 ;; be configurable (before 8.3). Make sure we
15836 ;; get the correct keyword.
15837 (key-assoc `(("CLOSED" . ,org-closed-string)
15838 ("DEADLINE" . ,org-deadline-string)
15839 ("SCHEDULED" . ,org-scheduled-string))))
15840 (dolist (pair (if specific (list (assoc specific key-assoc))
15841 key-assoc))
15842 (save-excursion
15843 (when (search-backward (cdr pair) bol t)
15844 (goto-char (match-end 0))
15845 (skip-chars-forward " \t")
15846 (and (looking-at org-ts-regexp-both)
15847 (push (cons (car pair)
15848 (match-string-no-properties 0))
15849 props)))))))
15850 (when specific (throw 'exit props)))
15851 (when (or (not specific)
15852 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15853 (let ((find-ts
15854 (lambda (end ts)
15855 ;; Fix next time-stamp before END. TS is the
15856 ;; list of time-stamps found so far.
15857 (let ((ts ts)
15858 (regexp (cond
15859 ((string= specific "TIMESTAMP")
15860 org-ts-regexp)
15861 ((string= specific "TIMESTAMP_IA")
15862 org-ts-regexp-inactive)
15863 ((assoc "TIMESTAMP_IA" ts)
15864 org-ts-regexp)
15865 ((assoc "TIMESTAMP" ts)
15866 org-ts-regexp-inactive)
15867 (t org-ts-regexp-both))))
15868 (catch 'next
15869 (while (re-search-forward regexp end t)
15870 (backward-char)
15871 (let ((object (org-element-context)))
15872 ;; Accept to match timestamps in node
15873 ;; properties, too.
15874 (when (memq (org-element-type object)
15875 '(node-property timestamp))
15876 (let ((type
15877 (org-element-property :type object)))
15878 (cond
15879 ((and (memq type '(active active-range))
15880 (not (equal specific "TIMESTAMP_IA")))
15881 (unless (assoc "TIMESTAMP" ts)
15882 (push (cons "TIMESTAMP"
15883 (org-element-property
15884 :raw-value object))
15886 (when specific (throw 'exit ts))))
15887 ((and (memq type '(inactive inactive-range))
15888 (not (string= specific "TIMESTAMP")))
15889 (unless (assoc "TIMESTAMP_IA" ts)
15890 (push (cons "TIMESTAMP_IA"
15891 (org-element-property
15892 :raw-value object))
15894 (when specific (throw 'exit ts))))))
15895 ;; Both timestamp types are found,
15896 ;; move to next part.
15897 (when (= (length ts) 2) (throw 'next ts)))))
15898 ts)))))
15899 (goto-char beg)
15900 ;; First look for timestamps within headline.
15901 (let ((ts (funcall find-ts (line-end-position) nil)))
15902 (if (= (length ts) 2) (setq props (nconc ts props))
15903 (forward-line)
15904 ;; Then find timestamps in the section, skipping
15905 ;; planning line.
15906 (when (looking-at-p org-planning-line-re)
15907 (forward-line))
15908 (let ((end (save-excursion (outline-next-heading))))
15909 (setq props (nconc (funcall find-ts end ts) props))))))))
15910 ;; Get the standard properties, like :PROP:.
15911 (when (memq which '(nil all standard))
15912 ;; If we are looking after a specific property, delegate
15913 ;; to `org-entry-get', which is faster. However, make an
15914 ;; exception for "CATEGORY", since it can be also set
15915 ;; through keywords (i.e. #+CATEGORY).
15916 (if (and specific (not (equal specific "CATEGORY")))
15917 (let ((value (org-entry-get beg specific nil t)))
15918 (throw 'exit (and value (list (cons specific value)))))
15919 (let ((range (org-get-property-block beg)))
15920 (when range
15921 (let ((end (cdr range)) seen-base)
15922 (goto-char (car range))
15923 ;; Unlike to `org--update-property-plist', we
15924 ;; handle the case where base values is found
15925 ;; after its extension. We also forbid standard
15926 ;; properties to be named as special properties.
15927 (while (re-search-forward org-property-re end t)
15928 (let* ((key (upcase (match-string-no-properties 2)))
15929 (extendp (string-match-p "\\+\\'" key))
15930 (key-base (if extendp (substring key 0 -1) key))
15931 (value (match-string-no-properties 3)))
15932 (cond
15933 ((member-ignore-case key-base org-special-properties))
15934 (extendp
15935 (setq props
15936 (org--update-property-plist key value props)))
15937 ((member key seen-base))
15938 (t (push key seen-base)
15939 (let ((p (assoc-string key props t)))
15940 (if p (setcdr p (concat value " " (cdr p)))
15941 (push (cons key value) props))))))))))))
15942 (unless (assoc "CATEGORY" props)
15943 (push (cons "CATEGORY" (org-get-category beg)) props)
15944 (when (string= specific "CATEGORY") (throw 'exit props)))
15945 ;; Return value.
15946 props)))))
15948 (defun org-property--local-values (property literal-nil)
15949 "Return value for PROPERTY in current entry.
15950 Value is a list whose car is the base value for PROPERTY and cdr
15951 a list of accumulated values. Return nil if neither is found in
15952 the entry. Also return nil when PROPERTY is set to \"nil\",
15953 unless LITERAL-NIL is non-nil."
15954 (let ((range (org-get-property-block)))
15955 (when range
15956 (goto-char (car range))
15957 (let* ((case-fold-search t)
15958 (end (cdr range))
15959 (value
15960 ;; Base value.
15961 (save-excursion
15962 (let ((v (and (re-search-forward
15963 (org-re-property property nil t) end t)
15964 (match-string-no-properties 3))))
15965 (list (if literal-nil v (org-not-nil v)))))))
15966 ;; Find additional values.
15967 (let* ((property+ (org-re-property (concat property "+") nil t)))
15968 (while (re-search-forward property+ end t)
15969 (push (match-string-no-properties 3) value)))
15970 ;; Return final values.
15971 (and (not (equal value '(nil))) (nreverse value))))))
15973 (defun org-entry-get (pom property &optional inherit literal-nil)
15974 "Get value of PROPERTY for entry or content at point-or-marker POM.
15976 If INHERIT is non-nil and the entry does not have the property,
15977 then also check higher levels of the hierarchy. If INHERIT is
15978 the symbol `selective', use inheritance only if the setting in
15979 `org-use-property-inheritance' selects PROPERTY for inheritance.
15981 If the property is present but empty, the return value is the
15982 empty string. If the property is not present at all, nil is
15983 returned. In any other case, return the value as a string.
15984 Search is case-insensitive.
15986 If LITERAL-NIL is set, return the string value \"nil\" as
15987 a string, do not interpret it as the list atom nil. This is used
15988 for inheritance when a \"nil\" value can supersede a non-nil
15989 value higher up the hierarchy."
15990 (org-with-point-at pom
15991 (cond
15992 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15993 ;; We need a special property. Use `org-entry-properties' to
15994 ;; retrieve it, but specify the wanted property.
15995 (cdr (assoc-string property (org-entry-properties nil property))))
15996 ((and inherit
15997 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15998 (org-entry-get-with-inheritance property literal-nil))
16000 (let* ((local (org-property--local-values property literal-nil))
16001 (value (and local (mapconcat #'identity (delq nil local) " "))))
16002 (if literal-nil value (org-not-nil value)))))))
16004 (defun org-property-or-variable-value (var &optional inherit)
16005 "Check if there is a property fixing the value of VAR.
16006 If yes, return this value. If not, return the current value of the variable."
16007 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16008 (if (and prop (stringp prop) (string-match "\\S-" prop))
16009 (read prop)
16010 (symbol-value var))))
16012 (defun org-entry-delete (pom property)
16013 "Delete PROPERTY from entry at point-or-marker POM.
16014 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16015 non-nil when a property was removed."
16016 (unless (member property org-special-properties)
16017 (org-with-point-at pom
16018 (let ((range (org-get-property-block)))
16019 (when range
16020 (let* ((begin (car range))
16021 (origin (cdr range))
16022 (end (copy-marker origin))
16023 (re (org-re-property
16024 (concat (regexp-quote property) "\\+?") t t)))
16025 (goto-char begin)
16026 (while (re-search-forward re end t)
16027 (delete-region (match-beginning 0) (line-beginning-position 2)))
16028 ;; If drawer is empty, remove it altogether.
16029 (when (= begin end)
16030 (delete-region (line-beginning-position 0)
16031 (line-beginning-position 2)))
16032 ;; Return non-nil if some property was removed.
16033 (prog1 (/= end origin) (set-marker end nil))))))))
16035 ;; Multi-values properties are properties that contain multiple values
16036 ;; These values are assumed to be single words, separated by whitespace.
16037 (defun org-entry-add-to-multivalued-property (pom property value)
16038 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16039 (let* ((old (org-entry-get pom property))
16040 (values (and old (org-split-string old "[ \t]"))))
16041 (setq value (org-entry-protect-space value))
16042 (unless (member value values)
16043 (setq values (append values (list value)))
16044 (org-entry-put pom property
16045 (mapconcat 'identity values " ")))))
16047 (defun org-entry-remove-from-multivalued-property (pom property value)
16048 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16049 (let* ((old (org-entry-get pom property))
16050 (values (and old (org-split-string old "[ \t]"))))
16051 (setq value (org-entry-protect-space value))
16052 (when (member value values)
16053 (setq values (delete value values))
16054 (org-entry-put pom property
16055 (mapconcat 'identity values " ")))))
16057 (defun org-entry-member-in-multivalued-property (pom property value)
16058 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16059 (let* ((old (org-entry-get pom property))
16060 (values (and old (org-split-string old "[ \t]"))))
16061 (setq value (org-entry-protect-space value))
16062 (member value values)))
16064 (defun org-entry-get-multivalued-property (pom property)
16065 "Return a list of values in a multivalued property."
16066 (let* ((value (org-entry-get pom property))
16067 (values (and value (org-split-string value "[ \t]"))))
16068 (mapcar 'org-entry-restore-space values)))
16070 (defun org-entry-put-multivalued-property (pom property &rest values)
16071 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16072 VALUES should be a list of strings. Spaces will be protected."
16073 (org-entry-put pom property
16074 (mapconcat 'org-entry-protect-space values " "))
16075 (let* ((value (org-entry-get pom property))
16076 (values (and value (org-split-string value "[ \t]"))))
16077 (mapcar 'org-entry-restore-space values)))
16079 (defun org-entry-protect-space (s)
16080 "Protect spaces and newline in string S."
16081 (while (string-match " " s)
16082 (setq s (replace-match "%20" t t s)))
16083 (while (string-match "\n" s)
16084 (setq s (replace-match "%0A" t t s)))
16087 (defun org-entry-restore-space (s)
16088 "Restore spaces and newline in string S."
16089 (while (string-match "%20" s)
16090 (setq s (replace-match " " t t s)))
16091 (while (string-match "%0A" s)
16092 (setq s (replace-match "\n" t t s)))
16095 (defvar org-entry-property-inherited-from (make-marker)
16096 "Marker pointing to the entry from where a property was inherited.
16097 Each call to `org-entry-get-with-inheritance' will set this marker to the
16098 location of the entry where the inheritance search matched. If there was
16099 no match, the marker will point nowhere.
16100 Note that also `org-entry-get' calls this function, if the INHERIT flag
16101 is set.")
16103 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16104 "Get PROPERTY of entry or content at point, search higher levels if needed.
16105 The search will stop at the first ancestor which has the property defined.
16106 If the value found is \"nil\", return nil to show that the property
16107 should be considered as undefined (this is the meaning of nil here).
16108 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16109 (move-marker org-entry-property-inherited-from nil)
16110 (org-with-wide-buffer
16111 (let (value)
16112 (catch 'exit
16113 (while t
16114 (let ((v (org-property--local-values property literal-nil)))
16115 (when v
16116 (setq value
16117 (concat (mapconcat #'identity (delq nil v) " ")
16118 (and value " ")
16119 value)))
16120 (cond
16121 ((car v)
16122 (org-back-to-heading t)
16123 (move-marker org-entry-property-inherited-from (point))
16124 (throw 'exit nil))
16125 ((org-up-heading-safe))
16127 (let ((global
16128 (cdr (or (assoc-string property org-file-properties t)
16129 (assoc-string property org-global-properties t)
16130 (assoc-string property org-global-properties-fixed t)))))
16131 (cond ((not global))
16132 (value (setq value (concat global " " value)))
16133 (t (setq value global))))
16134 (throw 'exit nil))))))
16135 (if literal-nil value (org-not-nil value)))))
16137 (defvar org-property-changed-functions nil
16138 "Hook called when the value of a property has changed.
16139 Each hook function should accept two arguments, the name of the property
16140 and the new value.")
16142 (defun org-entry-put (pom property value)
16143 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16145 If the value is nil, it is converted to the empty string. If it
16146 is not a string, an error is raised. Also raise an error on
16147 invalid property names.
16149 PROPERTY can be any regular property (see
16150 `org-special-properties'). It can also be \"TODO\",
16151 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16153 For the last two properties, VALUE may have any of the special
16154 values \"earlier\" and \"later\". The function then increases or
16155 decreases scheduled or deadline date by one day."
16156 (cond ((null value) (setq value ""))
16157 ((not (stringp value)) (error "Properties values should be strings"))
16158 ((not (org--valid-property-p property))
16159 (user-error "Invalid property name: \"%s\"" property)))
16160 (org-with-point-at pom
16161 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16162 (org-back-to-heading t)
16163 (org-with-limited-levels (org-back-to-heading t)))
16164 (let ((beg (point)))
16165 (cond
16166 ((equal property "TODO")
16167 (cond ((not (org-string-nw-p value)) (setq value 'none))
16168 ((not (member value org-todo-keywords-1))
16169 (user-error "\"%s\" is not a valid TODO state" value)))
16170 (org-todo value)
16171 (org-set-tags nil 'align))
16172 ((equal property "PRIORITY")
16173 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16174 (org-set-tags nil 'align))
16175 ((equal property "SCHEDULED")
16176 (forward-line)
16177 (if (and (looking-at-p org-planning-line-re)
16178 (re-search-forward
16179 org-scheduled-time-regexp (line-end-position) t))
16180 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16181 ((string= value "later") (org-timestamp-change 1 'day))
16182 ((string= value "") (org-schedule '(4)))
16183 (t (org-schedule nil value)))
16184 (if (member value '("earlier" "later" ""))
16185 (call-interactively #'org-schedule)
16186 (org-schedule nil value))))
16187 ((equal property "DEADLINE")
16188 (forward-line)
16189 (if (and (looking-at-p org-planning-line-re)
16190 (re-search-forward
16191 org-deadline-time-regexp (line-end-position) t))
16192 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16193 ((string= value "later") (org-timestamp-change 1 'day))
16194 ((string= value "") (org-deadline '(4)))
16195 (t (org-deadline nil value)))
16196 (if (member value '("earlier" "later" ""))
16197 (call-interactively #'org-deadline)
16198 (org-deadline nil value))))
16199 ((member property org-special-properties)
16200 (error "The %s property cannot be set with `org-entry-put'" property))
16202 (let* ((range (org-get-property-block beg 'force))
16203 (end (cdr range))
16204 (case-fold-search t))
16205 (goto-char (car range))
16206 (if (re-search-forward (org-re-property property nil t) end t)
16207 (progn (delete-region (match-beginning 0) (match-end 0))
16208 (goto-char (match-beginning 0)))
16209 (goto-char end)
16210 (insert "\n")
16211 (backward-char))
16212 (insert ":" property ":")
16213 (when value (insert " " value))
16214 (org-indent-line)))))
16215 (run-hook-with-args 'org-property-changed-functions property value)))
16217 (defun org-buffer-property-keys
16218 (&optional specials defaults columns ignore-malformed)
16219 "Get all property keys in the current buffer.
16221 When SPECIALS is non-nil, also list the special properties that
16222 reflect things like tags and TODO state.
16224 When DEFAULTS is non-nil, also include properties that has
16225 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16226 DESCRIPTION, LOCATION, and LOGGING and others.
16228 When COLUMNS in non-nil, also include property names given in
16229 COLUMN formats in the current buffer.
16231 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16232 automatically performed, such drawers will be silently ignored."
16233 (let ((case-fold-search t)
16234 (props (append
16235 (and specials org-special-properties)
16236 (and defaults (cons org-effort-property org-default-properties))
16237 nil)))
16238 (org-with-wide-buffer
16239 (goto-char (point-min))
16240 (while (re-search-forward org-property-start-re nil t)
16241 (let ((range (org-get-property-block)))
16242 (catch 'skip
16243 (unless range
16244 (when (and (not ignore-malformed)
16245 (not (org-before-first-heading-p))
16246 (y-or-n-p (format "Malformed drawer at %d, repair?"
16247 (line-beginning-position))))
16248 (org-get-property-block nil t))
16249 (throw 'skip nil))
16250 (goto-char (car range))
16251 (let ((begin (car range))
16252 (end (cdr range)))
16253 ;; Make sure that found property block is not located
16254 ;; before current point, as it would generate an infloop.
16255 ;; It can happen, for example, in the following
16256 ;; situation:
16258 ;; * Headline
16259 ;; :PROPERTIES:
16260 ;; ...
16261 ;; :END:
16262 ;; *************** Inlinetask
16263 ;; #+BEGIN_EXAMPLE
16264 ;; :PROPERTIES:
16265 ;; #+END_EXAMPLE
16267 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16268 (while (< (point) end)
16269 (let ((p (progn (looking-at org-property-re)
16270 (match-string-no-properties 2))))
16271 ;; Only add true property name, not extension symbol.
16272 (push (if (not (string-match-p "\\+\\'" p)) p
16273 (substring p 0 -1))
16274 props))
16275 (forward-line))))
16276 (outline-next-heading)))
16277 (when columns
16278 (goto-char (point-min))
16279 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16280 (let ((element (org-element-at-point)))
16281 (when (memq (org-element-type element) '(keyword node-property))
16282 (let ((value (org-element-property :value element))
16283 (start 0))
16284 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16285 (setq start (match-end 0))
16286 (let ((p (match-string-no-properties 1 value)))
16287 (unless (member-ignore-case p org-special-properties)
16288 (push p props))))))))))
16289 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16291 (defun org-property-values (key)
16292 "List all non-nil values of property KEY in current buffer."
16293 (org-with-wide-buffer
16294 (goto-char (point-min))
16295 (let ((case-fold-search t)
16296 (re (org-re-property key))
16297 values)
16298 (while (re-search-forward re nil t)
16299 (push (org-entry-get (point) key) values))
16300 (delete-dups values))))
16302 (defun org-insert-property-drawer ()
16303 "Insert a property drawer into the current entry."
16304 (org-with-wide-buffer
16305 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16306 (org-back-to-heading t)
16307 (org-with-limited-levels (org-back-to-heading t)))
16308 (forward-line)
16309 (when (looking-at-p org-planning-line-re) (forward-line))
16310 (unless (looking-at-p org-property-drawer-re)
16311 ;; Make sure we start editing a line from current entry, not from
16312 ;; next one. It prevents extending text properties or overlays
16313 ;; belonging to the latter.
16314 (when (bolp) (backward-char))
16315 (let ((begin (1+ (point)))
16316 (inhibit-read-only t))
16317 (insert "\n:PROPERTIES:\n:END:")
16318 (when (eobp) (insert "\n"))
16319 (org-indent-region begin (point))))))
16321 (defun org-insert-drawer (&optional arg drawer)
16322 "Insert a drawer at point.
16324 When optional argument ARG is non-nil, insert a property drawer.
16326 Optional argument DRAWER, when non-nil, is a string representing
16327 drawer's name. Otherwise, the user is prompted for a name.
16329 If a region is active, insert the drawer around that region
16330 instead.
16332 Point is left between drawer's boundaries."
16333 (interactive "P")
16334 (let* ((drawer (if arg "PROPERTIES"
16335 (or drawer (read-from-minibuffer "Drawer: ")))))
16336 (cond
16337 ;; With C-u, fall back on `org-insert-property-drawer'
16338 (arg (org-insert-property-drawer))
16339 ;; Check validity of suggested drawer's name.
16340 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16341 (user-error "Invalid drawer name"))
16342 ;; With an active region, insert a drawer at point.
16343 ((not (org-region-active-p))
16344 (progn
16345 (unless (bolp) (insert "\n"))
16346 (insert (format ":%s:\n\n:END:\n" drawer))
16347 (forward-line -2)))
16348 ;; Otherwise, insert the drawer at point
16350 (let ((rbeg (region-beginning))
16351 (rend (copy-marker (region-end))))
16352 (unwind-protect
16353 (progn
16354 (goto-char rbeg)
16355 (beginning-of-line)
16356 (when (save-excursion
16357 (re-search-forward org-outline-regexp-bol rend t))
16358 (user-error "Drawers cannot contain headlines"))
16359 ;; Position point at the beginning of the first
16360 ;; non-blank line in region. Insert drawer's opening
16361 ;; there, then indent it.
16362 (org-skip-whitespace)
16363 (beginning-of-line)
16364 (insert ":" drawer ":\n")
16365 (forward-line -1)
16366 (indent-for-tab-command)
16367 ;; Move point to the beginning of the first blank line
16368 ;; after the last non-blank line in region. Insert
16369 ;; drawer's closing, then indent it.
16370 (goto-char rend)
16371 (skip-chars-backward " \r\t\n")
16372 (insert "\n:END:")
16373 (deactivate-mark t)
16374 (indent-for-tab-command)
16375 (unless (eolp) (insert "\n")))
16376 ;; Clear marker, whatever the outcome of insertion is.
16377 (set-marker rend nil)))))))
16379 (defvar org-property-set-functions-alist nil
16380 "Property set function alist.
16381 Each entry should have the following format:
16383 (PROPERTY . READ-FUNCTION)
16385 The read function will be called with the same argument as
16386 `org-completing-read'.")
16388 (defun org-set-property-function (property)
16389 "Get the function that should be used to set PROPERTY.
16390 This is computed according to `org-property-set-functions-alist'."
16391 (or (cdr (assoc property org-property-set-functions-alist))
16392 'org-completing-read))
16394 (defun org-read-property-value (property)
16395 "Read PROPERTY value from user."
16396 (let* ((completion-ignore-case t)
16397 (allowed (org-property-get-allowed-values nil property 'table))
16398 (cur (org-entry-get nil property))
16399 (prompt (concat property " value"
16400 (if (and cur (string-match "\\S-" cur))
16401 (concat " [" cur "]") "") ": "))
16402 (set-function (org-set-property-function property))
16403 (val (if allowed
16404 (funcall set-function prompt allowed nil
16405 (not (get-text-property 0 'org-unrestricted
16406 (caar allowed))))
16407 (funcall set-function prompt
16408 (mapcar 'list (org-property-values property))
16409 nil nil "" nil cur))))
16410 (org-trim val)))
16412 (defvar org-last-set-property nil)
16413 (defvar org-last-set-property-value nil)
16414 (defun org-read-property-name ()
16415 "Read a property name."
16416 (let ((completion-ignore-case t)
16417 (default-prop (or (and (org-at-property-p)
16418 (match-string-no-properties 2))
16419 org-last-set-property)))
16420 (org-completing-read
16421 (concat "Property"
16422 (if default-prop (concat " [" default-prop "]") "")
16423 ": ")
16424 (mapcar #'list (org-buffer-property-keys nil t t))
16425 nil nil nil nil default-prop)))
16427 (defun org-set-property-and-value (use-last)
16428 "Allow to set [PROPERTY]: [value] direction from prompt.
16429 When use-default, don't even ask, just use the last
16430 \"[PROPERTY]: [value]\" string from the history."
16431 (interactive "P")
16432 (let* ((completion-ignore-case t)
16433 (pv (or (and use-last org-last-set-property-value)
16434 (org-completing-read
16435 "Enter a \"[Property]: [value]\" pair: "
16436 nil nil nil nil nil
16437 org-last-set-property-value)))
16438 prop val)
16439 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16440 (setq prop (match-string 1 pv)
16441 val (match-string 2 pv))
16442 (org-set-property prop val))))
16444 (defun org-set-property (property value)
16445 "In the current entry, set PROPERTY to VALUE.
16447 When called interactively, this will prompt for a property name, offering
16448 completion on existing and default properties. And then it will prompt
16449 for a value, offering completion either on allowed values (via an inherited
16450 xxx_ALL property) or on existing values in other instances of this property
16451 in the current file.
16453 Throw an error when trying to set a property with an invalid name."
16454 (interactive (list nil nil))
16455 (let ((property (or property (org-read-property-name))))
16456 ;; `org-entry-put' also makes the following check, but this one
16457 ;; avoids polluting `org-last-set-property' and
16458 ;; `org-last-set-property-value' needlessly.
16459 (unless (org--valid-property-p property)
16460 (user-error "Invalid property name: \"%s\"" property))
16461 (let ((value (or value (org-read-property-value property)))
16462 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16463 (setq org-last-set-property property)
16464 (setq org-last-set-property-value (concat property ": " value))
16465 ;; Possibly postprocess the inserted value:
16466 (when fn (setq value (funcall fn value)))
16467 (unless (equal (org-entry-get nil property) value)
16468 (org-entry-put nil property value)))))
16470 (defun org-find-property (property &optional value)
16471 "Find first entry in buffer that sets PROPERTY.
16473 When optional argument VALUE is non-nil, only consider an entry
16474 if it contains PROPERTY set to this value. If PROPERTY should be
16475 explicitly set to nil, use string \"nil\" for VALUE.
16477 Return position where the entry begins, or nil if there is no
16478 such entry. If narrowing is in effect, only search the visible
16479 part of the buffer."
16480 (save-excursion
16481 (goto-char (point-min))
16482 (let ((case-fold-search t)
16483 (re (org-re-property property nil (not value) value)))
16484 (catch 'exit
16485 (while (re-search-forward re nil t)
16486 (when (if value (org-at-property-p)
16487 (org-entry-get (point) property nil t))
16488 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16490 (defun org-delete-property (property)
16491 "In the current entry, delete PROPERTY."
16492 (interactive
16493 (let* ((completion-ignore-case t)
16494 (cat (org-entry-get (point) "CATEGORY"))
16495 (props0 (org-entry-properties nil 'standard))
16496 (props (if cat props0
16497 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16498 (prop (if (< 1 (length props))
16499 (completing-read "Property: " props nil t)
16500 (caar props))))
16501 (list prop)))
16502 (if (not property)
16503 (message "No property to delete in this entry")
16504 (org-entry-delete nil property)
16505 (message "Property \"%s\" deleted" property)))
16507 (defun org-delete-property-globally (property)
16508 "Remove PROPERTY globally, from all entries.
16509 This function ignores narrowing, if any."
16510 (interactive
16511 (let* ((completion-ignore-case t)
16512 (prop (completing-read
16513 "Globally remove property: "
16514 (mapcar #'list (org-buffer-property-keys)))))
16515 (list prop)))
16516 (org-with-wide-buffer
16517 (goto-char (point-min))
16518 (let ((count 0)
16519 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16520 (while (re-search-forward re nil t)
16521 (when (org-entry-delete (point) property) (cl-incf count)))
16522 (message "Property \"%s\" removed from %d entries" property count))))
16524 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16526 (defun org-compute-property-at-point ()
16527 "Compute the property at point.
16528 This looks for an enclosing column format, extracts the operator and
16529 then applies it to the property in the column format's scope."
16530 (interactive)
16531 (unless (org-at-property-p)
16532 (user-error "Not at a property"))
16533 (let ((prop (match-string-no-properties 2)))
16534 (org-columns-get-format-and-top-level)
16535 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16536 (user-error "No operator defined for property %s" prop))
16537 (org-columns-compute prop)))
16539 (defvar org-property-allowed-value-functions nil
16540 "Hook for functions supplying allowed values for a specific property.
16541 The functions must take a single argument, the name of the property, and
16542 return a flat list of allowed values. If \":ETC\" is one of
16543 the values, this means that these values are intended as defaults for
16544 completion, but that other values should be allowed too.
16545 The functions must return nil if they are not responsible for this
16546 property.")
16548 (defun org-property-get-allowed-values (pom property &optional table)
16549 "Get allowed values for the property PROPERTY.
16550 When TABLE is non-nil, return an alist that can directly be used for
16551 completion."
16552 (let (vals)
16553 (cond
16554 ((equal property "TODO")
16555 (setq vals (org-with-point-at pom
16556 (append org-todo-keywords-1 '("")))))
16557 ((equal property "PRIORITY")
16558 (let ((n org-lowest-priority))
16559 (while (>= n org-highest-priority)
16560 (push (char-to-string n) vals)
16561 (setq n (1- n)))))
16562 ((equal property "CATEGORY"))
16563 ((member property org-special-properties))
16564 ((setq vals (run-hook-with-args-until-success
16565 'org-property-allowed-value-functions property)))
16567 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16568 (when (and vals (string-match "\\S-" vals))
16569 (setq vals (car (read-from-string (concat "(" vals ")"))))
16570 (setq vals (mapcar (lambda (x)
16571 (cond ((stringp x) x)
16572 ((numberp x) (number-to-string x))
16573 ((symbolp x) (symbol-name x))
16574 (t "???")))
16575 vals)))))
16576 (when (member ":ETC" vals)
16577 (setq vals (remove ":ETC" vals))
16578 (org-add-props (car vals) '(org-unrestricted t)))
16579 (if table (mapcar 'list vals) vals)))
16581 (defun org-property-previous-allowed-value (&optional _previous)
16582 "Switch to the next allowed value for this property."
16583 (interactive)
16584 (org-property-next-allowed-value t))
16586 (defun org-property-next-allowed-value (&optional previous)
16587 "Switch to the next allowed value for this property."
16588 (interactive)
16589 (unless (org-at-property-p)
16590 (user-error "Not at a property"))
16591 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16592 (key (match-string 2))
16593 (value (match-string 3))
16594 (allowed (or (org-property-get-allowed-values (point) key)
16595 (and (member value '("[ ]" "[-]" "[X]"))
16596 '("[ ]" "[X]"))))
16597 (heading (save-match-data (nth 4 (org-heading-components))))
16598 nval)
16599 (unless allowed
16600 (user-error "Allowed values for this property have not been defined"))
16601 (when previous (setq allowed (reverse allowed)))
16602 (when (member value allowed)
16603 (setq nval (car (cdr (member value allowed)))))
16604 (setq nval (or nval (car allowed)))
16605 (when (equal nval value)
16606 (user-error "Only one allowed value for this property"))
16607 (org-at-property-p)
16608 (replace-match (concat " :" key ": " nval) t t)
16609 (org-indent-line)
16610 (beginning-of-line 1)
16611 (skip-chars-forward " \t")
16612 (when (equal prop org-effort-property)
16613 (org-refresh-property
16614 '((effort . identity)
16615 (effort-minutes . org-duration-string-to-minutes))
16616 nval)
16617 (when (string= org-clock-current-task heading)
16618 (setq org-clock-effort nval)
16619 (org-clock-update-mode-line)))
16620 (run-hook-with-args 'org-property-changed-functions key nval)))
16622 (defun org-find-olp (path &optional this-buffer)
16623 "Return a marker pointing to the entry at outline path OLP.
16624 If anything goes wrong, throw an error.
16625 You can wrap this call to catch the error like this:
16627 \(condition-case msg
16628 \(org-mobile-locate-entry (match-string 4))
16629 \(error (nth 1 msg)))
16631 The return value will then be either a string with the error message,
16632 or a marker if everything is OK.
16634 If THIS-BUFFER is set, the outline path does not contain a file,
16635 only headings."
16636 (let* ((file (if this-buffer buffer-file-name (pop path)))
16637 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16638 (level 1)
16639 (lmin 1)
16640 (lmax 1)
16641 end found flevel)
16642 (unless buffer (error "File not found :%s" file))
16643 (with-current-buffer buffer
16644 (org-with-wide-buffer
16645 (goto-char (point-min))
16646 (dolist (heading path)
16647 (let ((re (format org-complex-heading-regexp-format
16648 (regexp-quote heading)))
16649 (cnt 0))
16650 (while (re-search-forward re end t)
16651 (setq level (- (match-end 1) (match-beginning 1)))
16652 (when (and (>= level lmin) (<= level lmax))
16653 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16654 (when (= cnt 0)
16655 (error "Heading not found on level %d: %s" lmax heading))
16656 (when (> cnt 1)
16657 (error "Heading not unique on level %d: %s" lmax heading))
16658 (goto-char found)
16659 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16660 (setq end (save-excursion (org-end-of-subtree t t)))))
16661 (when (org-at-heading-p)
16662 (point-marker))))))
16664 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16665 "Find node HEADING in BUFFER.
16666 Return a marker to the heading if it was found, or nil if not.
16667 If POS-ONLY is set, return just the position instead of a marker.
16669 The heading text must match exact, but it may have a TODO keyword,
16670 a priority cookie and tags in the standard locations."
16671 (with-current-buffer (or buffer (current-buffer))
16672 (org-with-wide-buffer
16673 (goto-char (point-min))
16674 (let (case-fold-search)
16675 (when (re-search-forward
16676 (format org-complex-heading-regexp-format
16677 (regexp-quote heading)) nil t)
16678 (if pos-only
16679 (match-beginning 0)
16680 (move-marker (make-marker) (match-beginning 0))))))))
16682 (defun org-find-exact-heading-in-directory (heading &optional dir)
16683 "Find Org node headline HEADING in all .org files in directory DIR.
16684 When the target headline is found, return a marker to this location."
16685 (let ((files (directory-files (or dir default-directory)
16686 t "\\`[^.#].*\\.org\\'"))
16687 visiting m buffer)
16688 (catch 'found
16689 (dolist (file files)
16690 (message "trying %s" file)
16691 (setq visiting (org-find-base-buffer-visiting file))
16692 (setq buffer (or visiting (find-file-noselect file)))
16693 (setq m (org-find-exact-headline-in-buffer
16694 heading buffer))
16695 (when (and (not m) (not visiting)) (kill-buffer buffer))
16696 (and m (throw 'found m))))))
16698 (defun org-find-entry-with-id (ident)
16699 "Locate the entry that contains the ID property with exact value IDENT.
16700 IDENT can be a string, a symbol or a number, this function will search for
16701 the string representation of it.
16702 Return the position where this entry starts, or nil if there is no such entry."
16703 (interactive "sID: ")
16704 (let ((id (cond
16705 ((stringp ident) ident)
16706 ((symbolp ident) (symbol-name ident))
16707 ((numberp ident) (number-to-string ident))
16708 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16709 (org-with-wide-buffer (org-find-property "ID" id))))
16711 ;;;; Timestamps
16713 (defvar org-last-changed-timestamp nil)
16714 (defvar org-last-inserted-timestamp nil
16715 "The last time stamp inserted with `org-insert-time-stamp'.")
16716 (defvar org-ts-what) ; dynamically scoped parameter
16718 (defun org-time-stamp (arg &optional inactive)
16719 "Prompt for a date/time and insert a time stamp.
16721 If the user specifies a time like HH:MM or if this command is
16722 called with at least one prefix argument, the time stamp contains
16723 the date and the time. Otherwise, only the date is included.
16725 All parts of a date not specified by the user are filled in from
16726 the timestamp at point, if any, or the current date/time
16727 otherwise.
16729 If there is already a timestamp at the cursor, it is replaced.
16731 With two universal prefix arguments, insert an active timestamp
16732 with the current time without prompting the user.
16734 When called from lisp, the timestamp is inactive if INACTIVE is
16735 non-nil."
16736 (interactive "P")
16737 (let* ((ts (cond
16738 ((org-at-date-range-p t)
16739 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16740 ((org-at-timestamp-p t) (match-string 0))))
16741 ;; Default time is either the timestamp at point or today.
16742 ;; When entering a range, only the range start is considered.
16743 (default-time (if (not ts) (current-time)
16744 (apply #'encode-time (org-parse-time-string ts))))
16745 (default-input (and ts (org-get-compact-tod ts)))
16746 (repeater (and ts
16747 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16748 (match-string 0 ts)))
16749 org-time-was-given
16750 org-end-time-was-given
16751 (time
16752 (and (if (equal arg '(16)) (current-time)
16753 ;; Preserve `this-command' and `last-command'.
16754 (let ((this-command this-command)
16755 (last-command last-command))
16756 (org-read-date
16757 arg 'totime nil nil default-time default-input
16758 inactive))))))
16759 (cond
16760 ((and ts
16761 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16762 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16763 (insert "--")
16764 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16766 ;; Make sure we're on a timestamp. When in the middle of a date
16767 ;; range, move arbitrarily to range end.
16768 (unless (org-at-timestamp-p t)
16769 (skip-chars-forward "-")
16770 (org-at-timestamp-p t))
16771 (replace-match "")
16772 (setq org-last-changed-timestamp
16773 (org-insert-time-stamp
16774 time (or org-time-was-given arg)
16775 inactive nil nil (list org-end-time-was-given)))
16776 (when repeater
16777 (backward-char)
16778 (insert " " repeater)
16779 (setq org-last-changed-timestamp
16780 (concat (substring org-last-inserted-timestamp 0 -1)
16781 " " repeater ">")))
16782 (message "Timestamp updated"))
16783 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16784 (t (org-insert-time-stamp
16785 time (or org-time-was-given arg) inactive nil nil
16786 (list org-end-time-was-given))))))
16788 ;; FIXME: can we use this for something else, like computing time differences?
16789 (defun org-get-compact-tod (s)
16790 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16791 (let* ((t1 (match-string 1 s))
16792 (h1 (string-to-number (match-string 2 s)))
16793 (m1 (string-to-number (match-string 3 s)))
16794 (t2 (and (match-end 4) (match-string 5 s)))
16795 (h2 (and t2 (string-to-number (match-string 6 s))))
16796 (m2 (and t2 (string-to-number (match-string 7 s))))
16797 dh dm)
16798 (if (not t2)
16800 (setq dh (- h2 h1) dm (- m2 m1))
16801 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16802 (concat t1 "+" (number-to-string dh)
16803 (and (/= 0 dm) (format ":%02d" dm)))))))
16805 (defun org-time-stamp-inactive (&optional arg)
16806 "Insert an inactive time stamp.
16807 An inactive time stamp is enclosed in square brackets instead of angle
16808 brackets. It is inactive in the sense that it does not trigger agenda entries,
16809 does not link to the calendar and cannot be changed with the S-cursor keys.
16810 So these are more for recording a certain time/date."
16811 (interactive "P")
16812 (org-time-stamp arg 'inactive))
16814 (defvar org-date-ovl (make-overlay 1 1))
16815 (overlay-put org-date-ovl 'face 'org-date-selected)
16816 (delete-overlay org-date-ovl)
16818 (defvar org-ans1) ; dynamically scoped parameter
16819 (defvar org-ans2) ; dynamically scoped parameter
16821 (defvar org-plain-time-of-day-regexp) ; defined below
16823 (defvar org-overriding-default-time nil) ; dynamically scoped
16824 (defvar org-read-date-overlay nil)
16825 (defvar org-dcst nil) ; dynamically scoped
16826 (defvar org-read-date-history nil)
16827 (defvar org-read-date-final-answer nil)
16828 (defvar org-read-date-analyze-futurep nil)
16829 (defvar org-read-date-analyze-forced-year nil)
16830 (defvar org-read-date-inactive)
16832 (defvar org-read-date-minibuffer-local-map
16833 (let* ((map (make-sparse-keymap)))
16834 (set-keymap-parent map minibuffer-local-map)
16835 (org-defkey map (kbd ".")
16836 (lambda () (interactive)
16837 ;; Are we at the beginning of the prompt?
16838 (if (looking-back "^[^:]+: "
16839 (let ((inhibit-field-text-motion t))
16840 (line-beginning-position)))
16841 (org-eval-in-calendar '(calendar-goto-today))
16842 (insert "."))))
16843 (org-defkey map (kbd "C-.")
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-goto-today))))
16846 (org-defkey map [(meta shift left)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-backward-month 1))))
16849 (org-defkey map [(meta shift right)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-forward-month 1))))
16852 (org-defkey map [(meta shift up)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-backward-year 1))))
16855 (org-defkey map [(meta shift down)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-forward-year 1))))
16858 (org-defkey map [?\e (shift left)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-backward-month 1))))
16861 (org-defkey map [?\e (shift right)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-forward-month 1))))
16864 (org-defkey map [?\e (shift up)]
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(calendar-backward-year 1))))
16867 (org-defkey map [?\e (shift down)]
16868 (lambda () (interactive)
16869 (org-eval-in-calendar '(calendar-forward-year 1))))
16870 (org-defkey map [(shift up)]
16871 (lambda () (interactive)
16872 (org-eval-in-calendar '(calendar-backward-week 1))))
16873 (org-defkey map [(shift down)]
16874 (lambda () (interactive)
16875 (org-eval-in-calendar '(calendar-forward-week 1))))
16876 (org-defkey map [(shift left)]
16877 (lambda () (interactive)
16878 (org-eval-in-calendar '(calendar-backward-day 1))))
16879 (org-defkey map [(shift right)]
16880 (lambda () (interactive)
16881 (org-eval-in-calendar '(calendar-forward-day 1))))
16882 (org-defkey map "!"
16883 (lambda () (interactive)
16884 (org-eval-in-calendar '(diary-view-entries))
16885 (message "")))
16886 (org-defkey map ">"
16887 (lambda () (interactive)
16888 (org-eval-in-calendar '(calendar-scroll-left 1))))
16889 (org-defkey map "<"
16890 (lambda () (interactive)
16891 (org-eval-in-calendar '(calendar-scroll-right 1))))
16892 (org-defkey map "\C-v"
16893 (lambda () (interactive)
16894 (org-eval-in-calendar
16895 '(calendar-scroll-left-three-months 1))))
16896 (org-defkey map "\M-v"
16897 (lambda () (interactive)
16898 (org-eval-in-calendar
16899 '(calendar-scroll-right-three-months 1))))
16900 map)
16901 "Keymap for minibuffer commands when using `org-read-date'.")
16903 (defvar org-def)
16904 (defvar org-defdecode)
16905 (defvar org-with-time)
16907 (defvar calendar-setup) ; Dynamically scoped.
16908 (defun org-read-date (&optional with-time to-time from-string prompt
16909 default-time default-input inactive)
16910 "Read a date, possibly a time, and make things smooth for the user.
16911 The prompt will suggest to enter an ISO date, but you can also enter anything
16912 which will at least partially be understood by `parse-time-string'.
16913 Unrecognized parts of the date will default to the current day, month, year,
16914 hour and minute. If this command is called to replace a timestamp at point,
16915 or to enter the second timestamp of a range, the default time is taken
16916 from the existing stamp. Furthermore, the command prefers the future,
16917 so if you are giving a date where the year is not given, and the day-month
16918 combination is already past in the current year, it will assume you
16919 mean next year. For details, see the manual. A few examples:
16921 3-2-5 --> 2003-02-05
16922 feb 15 --> currentyear-02-15
16923 2/15 --> currentyear-02-15
16924 sep 12 9 --> 2009-09-12
16925 12:45 --> today 12:45
16926 22 sept 0:34 --> currentyear-09-22 0:34
16927 12 --> currentyear-currentmonth-12
16928 Fri --> nearest Friday after today
16929 -Tue --> last Tuesday
16930 etc.
16932 Furthermore you can specify a relative date by giving, as the *first* thing
16933 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16934 change in days weeks, months, years.
16935 With a single plus or minus, the date is relative to today. With a double
16936 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16937 +4d --> four days from today
16938 +4 --> same as above
16939 +2w --> two weeks from today
16940 ++5 --> five days from default date
16942 The function understands only English month and weekday abbreviations.
16944 While prompting, a calendar is popped up - you can also select the
16945 date with the mouse (button 1). The calendar shows a period of three
16946 months. To scroll it to other months, use the keys `>' and `<'.
16947 If you don't like the calendar, turn it off with
16948 (setq org-read-date-popup-calendar nil)
16950 With optional argument TO-TIME, the date will immediately be converted
16951 to an internal time.
16952 With an optional argument WITH-TIME, the prompt will suggest to
16953 also insert a time. Note that when WITH-TIME is not set, you can
16954 still enter a time, and this function will inform the calling routine
16955 about this change. The calling routine may then choose to change the
16956 format used to insert the time stamp into the buffer to include the time.
16957 With optional argument FROM-STRING, read from this string instead from
16958 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16959 the time/date that is used for everything that is not specified by the
16960 user."
16961 (require 'parse-time)
16962 (let* ((org-with-time with-time)
16963 (org-time-stamp-rounding-minutes
16964 (if (equal org-with-time '(16))
16965 '(0 0)
16966 org-time-stamp-rounding-minutes))
16967 (org-dcst org-display-custom-times)
16968 (ct (org-current-time))
16969 (org-def (or org-overriding-default-time default-time ct))
16970 (org-defdecode (decode-time org-def))
16971 (cur-frame (selected-frame))
16972 (mouse-autoselect-window nil) ; Don't let the mouse jump
16973 (calendar-setup
16974 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16975 (calendar-move-hook nil)
16976 (calendar-view-diary-initially-flag nil)
16977 (calendar-view-holidays-initially-flag nil)
16978 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16979 ;; Rationalize `org-def' and `org-defdecode', if required.
16980 (when (< (nth 2 org-defdecode) org-extend-today-until)
16981 (setf (nth 2 org-defdecode) -1)
16982 (setf (nth 1 org-defdecode) 59)
16983 (setq org-def (apply #'encode-time org-defdecode))
16984 (setq org-defdecode (decode-time org-def)))
16985 (let* ((timestr (format-time-string
16986 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16987 org-def))
16988 (prompt (concat (if prompt (concat prompt " ") "")
16989 (format "Date+time [%s]: " timestr))))
16990 (cond
16991 (from-string (setq ans from-string))
16992 (org-read-date-popup-calendar
16993 (save-excursion
16994 (save-window-excursion
16995 (calendar)
16996 (when (eq calendar-setup 'calendar-only)
16997 (setq cal-frame
16998 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16999 (select-frame cal-frame))
17000 (org-eval-in-calendar '(setq cursor-type nil) t)
17001 (unwind-protect
17002 (progn
17003 (calendar-forward-day (- (time-to-days org-def)
17004 (calendar-absolute-from-gregorian
17005 (calendar-current-date))))
17006 (org-eval-in-calendar nil t)
17007 (let* ((old-map (current-local-map))
17008 (map (copy-keymap calendar-mode-map))
17009 (minibuffer-local-map
17010 (copy-keymap org-read-date-minibuffer-local-map)))
17011 (org-defkey map (kbd "RET") 'org-calendar-select)
17012 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17013 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17014 (unwind-protect
17015 (progn
17016 (use-local-map map)
17017 (setq org-read-date-inactive inactive)
17018 (add-hook 'post-command-hook 'org-read-date-display)
17019 (setq org-ans0
17020 (read-string prompt
17021 default-input
17022 'org-read-date-history
17023 nil))
17024 ;; org-ans0: from prompt
17025 ;; org-ans1: from mouse click
17026 ;; org-ans2: from calendar motion
17027 (setq ans
17028 (concat org-ans0 " " (or org-ans1 org-ans2))))
17029 (remove-hook 'post-command-hook 'org-read-date-display)
17030 (use-local-map old-map)
17031 (when org-read-date-overlay
17032 (delete-overlay org-read-date-overlay)
17033 (setq org-read-date-overlay nil)))))
17034 (bury-buffer "*Calendar*")
17035 (when cal-frame
17036 (delete-frame cal-frame)
17037 (select-frame-set-input-focus cur-frame))))))
17039 (t ; Naked prompt only
17040 (unwind-protect
17041 (setq ans (read-string prompt default-input
17042 'org-read-date-history timestr))
17043 (when org-read-date-overlay
17044 (delete-overlay org-read-date-overlay)
17045 (setq org-read-date-overlay nil))))))
17047 (setq final (org-read-date-analyze ans org-def org-defdecode))
17049 (when org-read-date-analyze-forced-year
17050 (message "Year was forced into %s"
17051 (if org-read-date-force-compatible-dates
17052 "compatible range (1970-2037)"
17053 "range representable on this machine"))
17054 (ding))
17056 ;; One round trip to get rid of 34th of August and stuff like that....
17057 (setq final (decode-time (apply 'encode-time final)))
17059 (setq org-read-date-final-answer ans)
17061 (if to-time
17062 (apply 'encode-time final)
17063 (if (and (boundp 'org-time-was-given) org-time-was-given)
17064 (format "%04d-%02d-%02d %02d:%02d"
17065 (nth 5 final) (nth 4 final) (nth 3 final)
17066 (nth 2 final) (nth 1 final))
17067 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17069 (defun org-read-date-display ()
17070 "Display the current date prompt interpretation in the minibuffer."
17071 (when org-read-date-display-live
17072 (when org-read-date-overlay
17073 (delete-overlay org-read-date-overlay))
17074 (when (minibufferp (current-buffer))
17075 (save-excursion
17076 (end-of-line 1)
17077 (while (not (equal (buffer-substring
17078 (max (point-min) (- (point) 4)) (point))
17079 " "))
17080 (insert " ")))
17081 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17082 " " (or org-ans1 org-ans2)))
17083 (org-end-time-was-given nil)
17084 (f (org-read-date-analyze ans org-def org-defdecode))
17085 (fmts (if org-dcst
17086 org-time-stamp-custom-formats
17087 org-time-stamp-formats))
17088 (fmt (if (or org-with-time
17089 (and (boundp 'org-time-was-given) org-time-was-given))
17090 (cdr fmts)
17091 (car fmts)))
17092 (txt (format-time-string fmt (apply 'encode-time f)))
17093 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17094 (txt (concat "=> " txt)))
17095 (when (and org-end-time-was-given
17096 (string-match org-plain-time-of-day-regexp txt))
17097 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17098 org-end-time-was-given
17099 (substring txt (match-end 0)))))
17100 (when org-read-date-analyze-futurep
17101 (setq txt (concat txt " (=>F)")))
17102 (setq org-read-date-overlay
17103 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17104 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17106 (defun org-read-date-analyze (ans def defdecode)
17107 "Analyze the combined answer of the date prompt."
17108 ;; FIXME: cleanup and comment
17109 ;; Pass `current-time' result to `decode-time' (instead of calling
17110 ;; without arguments) so that only `current-time' has to be
17111 ;; overriden in tests.
17112 (let ((org-def def)
17113 (org-defdecode defdecode)
17114 (nowdecode (decode-time (current-time)))
17115 delta deltan deltaw deltadef year month day
17116 hour minute second wday pm h2 m2 tl wday1
17117 iso-year iso-weekday iso-week iso-date futurep kill-year)
17118 (setq org-read-date-analyze-futurep nil
17119 org-read-date-analyze-forced-year nil)
17120 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17121 (setq ans "+0"))
17123 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17124 (setq ans (replace-match "" t t ans)
17125 deltan (car delta)
17126 deltaw (nth 1 delta)
17127 deltadef (nth 2 delta)))
17129 ;; Check if there is an iso week date in there. If yes, store the
17130 ;; info and postpone interpreting it until the rest of the parsing
17131 ;; is done.
17132 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17133 (setq iso-year (when (match-end 1)
17134 (org-small-year-to-year
17135 (string-to-number (match-string 1 ans))))
17136 iso-weekday (when (match-end 3)
17137 (string-to-number (match-string 3 ans)))
17138 iso-week (string-to-number (match-string 2 ans)))
17139 (setq ans (replace-match "" t t ans)))
17141 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17142 (when (string-match
17143 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17144 (setq year (if (match-end 2)
17145 (string-to-number (match-string 2 ans))
17146 (progn (setq kill-year t)
17147 (string-to-number (format-time-string "%Y"))))
17148 month (string-to-number (match-string 3 ans))
17149 day (string-to-number (match-string 4 ans)))
17150 (setq year (org-small-year-to-year year))
17151 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17152 t nil ans)))
17154 ;; Help matching dotted european dates
17155 (when (string-match
17156 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17157 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17158 (setq kill-year t)
17159 (string-to-number (format-time-string "%Y")))
17160 day (string-to-number (match-string 1 ans))
17161 month (string-to-number (match-string 2 ans))
17162 ans (replace-match (format "%04d-%02d-%02d" year month day)
17163 t nil ans)))
17165 ;; Help matching american dates, like 5/30 or 5/30/7
17166 (when (string-match
17167 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17168 (setq year (if (match-end 4)
17169 (string-to-number (match-string 4 ans))
17170 (progn (setq kill-year t)
17171 (string-to-number (format-time-string "%Y"))))
17172 month (string-to-number (match-string 1 ans))
17173 day (string-to-number (match-string 2 ans)))
17174 (setq year (org-small-year-to-year year))
17175 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17176 t nil ans)))
17177 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17178 ;; If there is a time with am/pm, and *no* time without it, we convert
17179 ;; so that matching will be successful.
17180 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17181 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17182 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17183 (setq hour (string-to-number (match-string 1 ans))
17184 minute (if (match-end 3)
17185 (string-to-number (match-string 3 ans))
17187 pm (equal ?p
17188 (string-to-char (downcase (match-string 4 ans)))))
17189 (if (and (= hour 12) (not pm))
17190 (setq hour 0)
17191 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17192 (setq ans (replace-match (format "%02d:%02d" hour minute)
17193 t t ans))))
17195 ;; Check if a time range is given as a duration
17196 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17197 (setq hour (string-to-number (match-string 1 ans))
17198 h2 (+ hour (string-to-number (match-string 3 ans)))
17199 minute (string-to-number (match-string 2 ans))
17200 m2 (+ minute (if (match-end 5) (string-to-number
17201 (match-string 5 ans))0)))
17202 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17203 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17204 t t ans)))
17206 ;; Check if there is a time range
17207 (when (boundp 'org-end-time-was-given)
17208 (setq org-time-was-given nil)
17209 (when (and (string-match org-plain-time-of-day-regexp ans)
17210 (match-end 8))
17211 (setq org-end-time-was-given (match-string 8 ans))
17212 (setq ans (concat (substring ans 0 (match-beginning 7))
17213 (substring ans (match-end 7))))))
17215 (setq tl (parse-time-string ans)
17216 day (or (nth 3 tl) (nth 3 org-defdecode))
17217 month
17218 (cond ((nth 4 tl))
17219 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17220 ;; Day was specified. Make sure DAY+MONTH
17221 ;; combination happens in the future.
17222 ((nth 3 tl)
17223 (setq futurep t)
17224 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17225 (nth 4 nowdecode)))
17226 (t (nth 4 org-defdecode)))
17227 year
17228 (cond ((and (not kill-year) (nth 5 tl)))
17229 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17230 ;; Month was guessed in the future and is at least
17231 ;; equal to NOWDECODE's. Fix year accordingly.
17232 (futurep
17233 (if (or (> month (nth 4 nowdecode))
17234 (>= day (nth 3 nowdecode)))
17235 (nth 5 nowdecode)
17236 (1+ (nth 5 nowdecode))))
17237 ;; Month was specified. Make sure MONTH+YEAR
17238 ;; combination happens in the future.
17239 ((nth 4 tl)
17240 (setq futurep t)
17241 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17242 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17243 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17244 (t (nth 5 nowdecode))))
17245 (t (nth 5 org-defdecode)))
17246 hour (or (nth 2 tl) (nth 2 org-defdecode))
17247 minute (or (nth 1 tl) (nth 1 org-defdecode))
17248 second (or (nth 0 tl) 0)
17249 wday (nth 6 tl))
17251 (when (and (eq org-read-date-prefer-future 'time)
17252 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17253 (equal day (nth 3 nowdecode))
17254 (equal month (nth 4 nowdecode))
17255 (equal year (nth 5 nowdecode))
17256 (nth 2 tl)
17257 (or (< (nth 2 tl) (nth 2 nowdecode))
17258 (and (= (nth 2 tl) (nth 2 nowdecode))
17259 (nth 1 tl)
17260 (< (nth 1 tl) (nth 1 nowdecode)))))
17261 (setq day (1+ day)
17262 futurep t))
17264 ;; Special date definitions below
17265 (cond
17266 (iso-week
17267 ;; There was an iso week
17268 (require 'cal-iso)
17269 (setq futurep nil)
17270 (setq year (or iso-year year)
17271 day (or iso-weekday wday 1)
17272 wday nil ; to make sure that the trigger below does not match
17273 iso-date (calendar-gregorian-from-absolute
17274 (calendar-iso-to-absolute
17275 (list iso-week day year))))
17276 ; FIXME: Should we also push ISO weeks into the future?
17277 ; (when (and org-read-date-prefer-future
17278 ; (not iso-year)
17279 ; (< (calendar-absolute-from-gregorian iso-date)
17280 ; (time-to-days (current-time))))
17281 ; (setq year (1+ year)
17282 ; iso-date (calendar-gregorian-from-absolute
17283 ; (calendar-iso-to-absolute
17284 ; (list iso-week day year)))))
17285 (setq month (car iso-date)
17286 year (nth 2 iso-date)
17287 day (nth 1 iso-date)))
17288 (deltan
17289 (setq futurep nil)
17290 (unless deltadef
17291 ;; Pass `current-time' result to `decode-time' (instead of
17292 ;; calling without arguments) so that only `current-time' has
17293 ;; to be overriden in tests.
17294 (let ((now (decode-time (current-time))))
17295 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17296 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17297 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17298 ((equal deltaw "m") (setq month (+ month deltan)))
17299 ((equal deltaw "y") (setq year (+ year deltan)))))
17300 ((and wday (not (nth 3 tl)))
17301 ;; Weekday was given, but no day, so pick that day in the week
17302 ;; on or after the derived date.
17303 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17304 (unless (equal wday wday1)
17305 (setq day (+ day (% (- wday wday1 -7) 7))))))
17306 (when (and (boundp 'org-time-was-given)
17307 (nth 2 tl))
17308 (setq org-time-was-given t))
17309 (when (< year 100) (setq year (+ 2000 year)))
17310 ;; Check of the date is representable
17311 (if org-read-date-force-compatible-dates
17312 (progn
17313 (when (< year 1970)
17314 (setq year 1970 org-read-date-analyze-forced-year t))
17315 (when (> year 2037)
17316 (setq year 2037 org-read-date-analyze-forced-year t)))
17317 (condition-case nil
17318 (ignore (encode-time second minute hour day month year))
17319 (error
17320 (setq year (nth 5 org-defdecode))
17321 (setq org-read-date-analyze-forced-year t))))
17322 (setq org-read-date-analyze-futurep futurep)
17323 (list second minute hour day month year)))
17325 (defvar parse-time-weekdays)
17326 (defun org-read-date-get-relative (s today default)
17327 "Check string S for special relative date string.
17328 TODAY and DEFAULT are internal times, for today and for a default.
17329 Return shift list (N what def-flag)
17330 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17331 N is the number of WHATs to shift.
17332 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17333 the DEFAULT date rather than TODAY."
17334 (require 'parse-time)
17335 (when (and
17336 (string-match
17337 (concat
17338 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17339 "\\([0-9]+\\)?"
17340 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17341 "\\([ \t]\\|$\\)") s)
17342 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17343 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17344 (string-to-char (substring (match-string 1 s) -1))
17345 ?+))
17346 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17347 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17348 (what (if (match-end 3) (match-string 3 s) "d"))
17349 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17350 (date (if rel default today))
17351 (wday (nth 6 (decode-time date)))
17352 delta)
17353 (if wday1
17354 (progn
17355 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17356 (when (= delta 0) (setq delta 7))
17357 (when (= dir ?-)
17358 (setq delta (- delta 7))
17359 (when (= delta 0) (setq delta -7)))
17360 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17361 (list delta "d" rel))
17362 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17364 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17365 "Turn a user-specified date into the internal representation.
17366 The internal representation needed by the calendar is (month day year).
17367 This is a wrapper to handle the brain-dead convention in calendar that
17368 user function argument order change dependent on argument order."
17369 (pcase calendar-date-style
17370 (`american (list arg1 arg2 arg3))
17371 (`european (list arg2 arg1 arg3))
17372 (`iso (list arg2 arg3 arg1))))
17374 (defun org-eval-in-calendar (form &optional keepdate)
17375 "Eval FORM in the calendar window and return to current window.
17376 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17377 (let ((sf (selected-frame))
17378 (sw (selected-window)))
17379 (select-window (get-buffer-window "*Calendar*" t))
17380 (eval form)
17381 (when (and (not keepdate) (calendar-cursor-to-date))
17382 (let* ((date (calendar-cursor-to-date))
17383 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17384 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17385 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17386 (select-window sw)
17387 (select-frame-set-input-focus sf)))
17389 (defun org-calendar-select ()
17390 "Return to `org-read-date' with the date currently selected.
17391 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17392 (interactive)
17393 (when (calendar-cursor-to-date)
17394 (let* ((date (calendar-cursor-to-date))
17395 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17396 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17397 (when (active-minibuffer-window) (exit-minibuffer))))
17399 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17400 "Insert a date stamp for the date given by the internal TIME.
17401 See `format-time-string' for the format of TIME.
17402 WITH-HM means use the stamp format that includes the time of the day.
17403 INACTIVE means use square brackets instead of angular ones, so that the
17404 stamp will not contribute to the agenda.
17405 PRE and POST are optional strings to be inserted before and after the
17406 stamp.
17407 The command returns the inserted time stamp."
17408 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17409 stamp)
17410 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17411 (insert-before-markers (or pre ""))
17412 (when (listp extra)
17413 (setq extra (car extra))
17414 (if (and (stringp extra)
17415 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17416 (setq extra (format "-%02d:%02d"
17417 (string-to-number (match-string 1 extra))
17418 (string-to-number (match-string 2 extra))))
17419 (setq extra nil)))
17420 (when extra
17421 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17422 (insert-before-markers (setq stamp (format-time-string fmt time)))
17423 (insert-before-markers (or post ""))
17424 (setq org-last-inserted-timestamp stamp)))
17426 (defun org-toggle-time-stamp-overlays ()
17427 "Toggle the use of custom time stamp formats."
17428 (interactive)
17429 (setq org-display-custom-times (not org-display-custom-times))
17430 (unless org-display-custom-times
17431 (let ((p (point-min)) (bmp (buffer-modified-p)))
17432 (while (setq p (next-single-property-change p 'display))
17433 (when (and (get-text-property p 'display)
17434 (eq (get-text-property p 'face) 'org-date))
17435 (remove-text-properties
17436 p (setq p (next-single-property-change p 'display))
17437 '(display t))))
17438 (set-buffer-modified-p bmp)))
17439 (org-restart-font-lock)
17440 (setq org-table-may-need-update t)
17441 (if org-display-custom-times
17442 (message "Time stamps are overlaid with custom format")
17443 (message "Time stamp overlays removed")))
17445 (defun org-display-custom-time (beg end)
17446 "Overlay modified time stamp format over timestamp between BEG and END."
17447 (let* ((ts (buffer-substring beg end))
17448 t1 w1 with-hm tf time str w2 (off 0))
17449 (save-match-data
17450 (setq t1 (org-parse-time-string ts t))
17451 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17452 (setq off (- (match-end 0) (match-beginning 0)))))
17453 (setq end (- end off))
17454 (setq w1 (- end beg)
17455 with-hm (and (nth 1 t1) (nth 2 t1))
17456 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17457 time (org-fix-decoded-time t1)
17458 str (org-add-props
17459 (format-time-string
17460 (substring tf 1 -1) (apply 'encode-time time))
17461 nil 'mouse-face 'highlight)
17462 w2 (length str))
17463 (unless (= w2 w1)
17464 (add-text-properties (1+ beg) (+ 2 beg)
17465 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17466 (put-text-property beg end 'display str)))
17468 (defun org-fix-decoded-time (time)
17469 "Set 0 instead of nil for the first 6 elements of time.
17470 Don't touch the rest."
17471 (let ((n 0))
17472 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17474 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17475 "Difference between TIMESTAMP-STRING and now in days.
17476 If SECONDS is non-nil, return the difference in seconds."
17477 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17478 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17479 (funcall fdiff (current-time)))))
17481 (defun org-deadline-close-p (timestamp-string &optional ndays)
17482 "Is the time in TIMESTAMP-STRING close to the current date?"
17483 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17484 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17485 (not (org-entry-is-done-p))))
17487 (defun org-get-wdays (ts &optional delay zero-delay)
17488 "Get the deadline lead time appropriate for timestring TS.
17489 When DELAY is non-nil, get the delay time for scheduled items
17490 instead of the deadline lead time. When ZERO-DELAY is non-nil
17491 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17492 don't try to find the delay cookie in the scheduled timestamp."
17493 (let ((tv (if delay org-scheduled-delay-days
17494 org-deadline-warning-days)))
17495 (cond
17496 ((or (and delay (< tv 0))
17497 (and delay zero-delay (<= tv 0))
17498 (and (not delay) (<= tv 0)))
17499 ;; Enforce this value no matter what
17500 (- tv))
17501 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17502 ;; lead time is specified.
17503 (floor (* (string-to-number (match-string 1 ts))
17504 (cdr (assoc (match-string 2 ts)
17505 '(("d" . 1) ("w" . 7)
17506 ("m" . 30.4) ("y" . 365.25)
17507 ("h" . 0.041667)))))))
17508 ;; go for the default.
17509 (t tv))))
17511 (defun org-calendar-select-mouse (ev)
17512 "Return to `org-read-date' with the date currently selected.
17513 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17514 (interactive "e")
17515 (mouse-set-point ev)
17516 (when (calendar-cursor-to-date)
17517 (let* ((date (calendar-cursor-to-date))
17518 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17519 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17520 (when (active-minibuffer-window) (exit-minibuffer))))
17522 (defun org-check-deadlines (ndays)
17523 "Check if there are any deadlines due or past due.
17524 A deadline is considered due if it happens within `org-deadline-warning-days'
17525 days from today's date. If the deadline appears in an entry marked DONE,
17526 it is not shown. The prefix arg NDAYS can be used to test that many
17527 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17528 (interactive "P")
17529 (let* ((org-warn-days
17530 (cond
17531 ((equal ndays '(4)) 100000)
17532 (ndays (prefix-numeric-value ndays))
17533 (t (abs org-deadline-warning-days))))
17534 (case-fold-search nil)
17535 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17536 (callback
17537 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17538 (message "%d deadlines past-due or due within %d days"
17539 (org-occur regexp nil callback)
17540 org-warn-days)))
17542 (defsubst org-re-timestamp (type)
17543 "Return a regexp for timestamp TYPE.
17544 Allowed values for TYPE are:
17546 all: all timestamps
17547 active: only active timestamps (<...>)
17548 inactive: only inactive timestamps ([...])
17549 scheduled: only scheduled timestamps
17550 deadline: only deadline timestamps
17551 closed: only closed time-stamps
17553 When TYPE is nil, fall back on returning a regexp that matches
17554 both scheduled and deadline timestamps."
17555 (cl-case type
17556 (all org-ts-regexp-both)
17557 (active org-ts-regexp)
17558 (inactive org-ts-regexp-inactive)
17559 (scheduled org-scheduled-time-regexp)
17560 (deadline org-deadline-time-regexp)
17561 (closed org-closed-time-regexp)
17562 (otherwise
17563 (concat "\\<"
17564 (regexp-opt (list org-deadline-string org-scheduled-string))
17565 " *<\\([^>]+\\)>"))))
17567 (defun org-check-before-date (d)
17568 "Check if there are deadlines or scheduled entries before date D."
17569 (interactive (list (org-read-date)))
17570 (let* ((case-fold-search nil)
17571 (regexp (org-re-timestamp org-ts-type))
17572 (ts-type org-ts-type)
17573 (callback
17574 (lambda ()
17575 (let ((match (match-string 1)))
17576 (and (if (memq ts-type '(active inactive all))
17577 (eq (org-element-type (save-excursion
17578 (backward-char)
17579 (org-element-context)))
17580 'timestamp)
17581 (org-at-planning-p))
17582 (time-less-p
17583 (org-time-string-to-time match)
17584 (org-time-string-to-time d)))))))
17585 (message "%d entries before %s"
17586 (org-occur regexp nil callback)
17587 d)))
17589 (defun org-check-after-date (d)
17590 "Check if there are deadlines or scheduled entries after date D."
17591 (interactive (list (org-read-date)))
17592 (let* ((case-fold-search nil)
17593 (regexp (org-re-timestamp org-ts-type))
17594 (ts-type org-ts-type)
17595 (callback
17596 (lambda ()
17597 (let ((match (match-string 1)))
17598 (and (if (memq ts-type '(active inactive all))
17599 (eq (org-element-type (save-excursion
17600 (backward-char)
17601 (org-element-context)))
17602 'timestamp)
17603 (org-at-planning-p))
17604 (not (time-less-p
17605 (org-time-string-to-time match)
17606 (org-time-string-to-time d))))))))
17607 (message "%d entries after %s"
17608 (org-occur regexp nil callback)
17609 d)))
17611 (defun org-check-dates-range (start-date end-date)
17612 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17613 (interactive (list (org-read-date nil nil nil "Range starts")
17614 (org-read-date nil nil nil "Range end")))
17615 (let ((case-fold-search nil)
17616 (regexp (org-re-timestamp org-ts-type))
17617 (callback
17618 (let ((type org-ts-type))
17619 (lambda ()
17620 (let ((match (match-string 1)))
17621 (and
17622 (if (memq type '(active inactive all))
17623 (eq (org-element-type (save-excursion
17624 (backward-char)
17625 (org-element-context)))
17626 'timestamp)
17627 (org-at-planning-p))
17628 (not (time-less-p
17629 (org-time-string-to-time match)
17630 (org-time-string-to-time start-date)))
17631 (time-less-p
17632 (org-time-string-to-time match)
17633 (org-time-string-to-time end-date))))))))
17634 (message "%d entries between %s and %s"
17635 (org-occur regexp nil callback) start-date end-date)))
17637 (defun org-evaluate-time-range (&optional to-buffer)
17638 "Evaluate a time range by computing the difference between start and end.
17639 Normally the result is just printed in the echo area, but with prefix arg
17640 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17641 If the time range is actually in a table, the result is inserted into the
17642 next column.
17643 For time difference computation, a year is assumed to be exactly 365
17644 days in order to avoid rounding problems."
17645 (interactive "P")
17647 (org-clock-update-time-maybe)
17648 (save-excursion
17649 (unless (org-at-date-range-p t)
17650 (goto-char (point-at-bol))
17651 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17652 (unless (org-at-date-range-p t)
17653 (user-error "Not at a time-stamp range, and none found in current line")))
17654 (let* ((ts1 (match-string 1))
17655 (ts2 (match-string 2))
17656 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17657 (match-end (match-end 0))
17658 (time1 (org-time-string-to-time ts1))
17659 (time2 (org-time-string-to-time ts2))
17660 (t1 (float-time time1))
17661 (t2 (float-time time2))
17662 (diff (abs (- t2 t1)))
17663 (negative (< (- t2 t1) 0))
17664 ;; (ys (floor (* 365 24 60 60)))
17665 (ds (* 24 60 60))
17666 (hs (* 60 60))
17667 (fy "%dy %dd %02d:%02d")
17668 (fy1 "%dy %dd")
17669 (fd "%dd %02d:%02d")
17670 (fd1 "%dd")
17671 (fh "%02d:%02d")
17672 y d h m align)
17673 (if havetime
17674 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17676 d (floor (/ diff ds)) diff (mod diff ds)
17677 h (floor (/ diff hs)) diff (mod diff hs)
17678 m (floor (/ diff 60)))
17679 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17681 d (floor (+ (/ diff ds) 0.5))
17682 h 0 m 0))
17683 (if (not to-buffer)
17684 (message "%s" (org-make-tdiff-string y d h m))
17685 (if (org-at-table-p)
17686 (progn
17687 (goto-char match-end)
17688 (setq align t)
17689 (and (looking-at " *|") (goto-char (match-end 0))))
17690 (goto-char match-end))
17691 (when (looking-at
17692 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17693 (replace-match ""))
17694 (when negative (insert " -"))
17695 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17696 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17697 (insert " " (format fh h m))))
17698 (when align (org-table-align))
17699 (message "Time difference inserted")))))
17701 (defun org-make-tdiff-string (y d h m)
17702 (let ((fmt "")
17703 (l nil))
17704 (when (> y 0)
17705 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17706 (push y l))
17707 (when (> d 0)
17708 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17709 (push d l))
17710 (when (> h 0)
17711 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17712 (push h l))
17713 (when (> m 0)
17714 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17715 (push m l))
17716 (apply 'format fmt (nreverse l))))
17718 (defun org-time-string-to-time (s &optional buffer pos)
17719 "Convert a timestamp string into internal time."
17720 (condition-case errdata
17721 (apply 'encode-time (org-parse-time-string s))
17722 (error (error "Bad timestamp `%s'%s\nError was: %s"
17723 s (if (not (and buffer pos))
17725 (format-message " at %d in buffer `%s'" pos buffer))
17726 (cdr errdata)))))
17728 (defun org-time-string-to-seconds (s)
17729 "Convert a timestamp string to a number of seconds."
17730 (float-time (org-time-string-to-time s)))
17732 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17734 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17735 "Convert time stamp S to an absolute day number.
17737 If DAYNR in non-nil, and there is a specifier for a cyclic time
17738 stamp, get the closest date to DAYNR. If PREFER is
17739 `past' (respectively `future') return a date past (respectively
17740 after) or equal to DAYNR.
17742 POS is the location of time stamp S, as a buffer position in
17743 BUFFER.
17745 Diary sexp timestamps are matched against DAYNR, when non-nil.
17746 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17747 signalled."
17748 (cond
17749 ((string-match "\\`%%\\((.*)\\)" s)
17750 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17751 ;; only able to match individual dates. If it fails, raise an
17752 ;; error.
17753 (if (and daynr
17754 (org-diary-sexp-entry
17755 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17756 daynr
17757 (signal 'org-diary-sexp-no-match (list s))))
17758 ((and daynr show-all) (org-closest-date s daynr prefer))
17759 (t (time-to-days
17760 (condition-case errdata
17761 (apply #'encode-time (org-parse-time-string s))
17762 (error (error "Bad timestamp `%s'%s\nError was: %s"
17764 (if (not (and buffer pos)) ""
17765 (format-message " at %d in buffer `%s'" pos buffer))
17766 (cdr errdata))))))))
17768 (defun org-days-to-iso-week (days)
17769 "Return the iso week number."
17770 (require 'cal-iso)
17771 (car (calendar-iso-from-absolute days)))
17773 (defun org-small-year-to-year (year)
17774 "Convert 2-digit years into 4-digit years.
17775 YEAR is expanded into one of the 30 next years, if possible, or
17776 into a past one. Any year larger than 99 is returned unchanged."
17777 (if (>= year 100) year
17778 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17779 (century (/ current 100))
17780 (offset (- year (% current 100))))
17781 (cond ((> offset 30) (+ (* (1- century) 100) year))
17782 ((> offset -70) (+ (* century 100) year))
17783 (t (+ (* (1+ century) 100) year))))))
17785 (defun org-time-from-absolute (d)
17786 "Return the time corresponding to date D.
17787 D may be an absolute day number, or a calendar-type list (month day year)."
17788 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17789 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17791 (defvar org-agenda-current-date)
17792 (defun org-calendar-holiday ()
17793 "List of holidays, for Diary display in Org mode."
17794 (require 'holidays)
17795 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17796 (and hl (mapconcat #'identity hl "; "))))
17798 (defun org-diary-sexp-entry (sexp entry d)
17799 "Process a SEXP diary ENTRY for date D."
17800 (require 'diary-lib)
17801 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17802 ;; dynamically.
17803 (let* ((sexp `(let ((entry ,entry)
17804 (date ',d))
17805 ,(car (read-from-string sexp))))
17806 (result (if calendar-debug-sexp (eval sexp)
17807 (condition-case nil
17808 (eval sexp)
17809 (error
17810 (beep)
17811 (message "Bad sexp at line %d in %s: %s"
17812 (org-current-line)
17813 (buffer-file-name) sexp)
17814 (sleep-for 2))))))
17815 (cond ((stringp result) (split-string result "; "))
17816 ((and (consp result)
17817 (not (consp (cdr result)))
17818 (stringp (cdr result))) (cdr result))
17819 ((and (consp result)
17820 (stringp (car result))) result)
17821 (result entry))))
17823 (defun org-diary-to-ical-string (frombuf)
17824 "Get iCalendar entries from diary entries in buffer FROMBUF.
17825 This uses the icalendar.el library."
17826 (let* ((tmpdir temporary-file-directory)
17827 (tmpfile (make-temp-name
17828 (expand-file-name "orgics" tmpdir)))
17829 buf rtn b e)
17830 (with-current-buffer frombuf
17831 (icalendar-export-region (point-min) (point-max) tmpfile)
17832 (setq buf (find-buffer-visiting tmpfile))
17833 (set-buffer buf)
17834 (goto-char (point-min))
17835 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17836 (setq b (match-beginning 0)))
17837 (goto-char (point-max))
17838 (when (re-search-backward "^END:VEVENT" nil t)
17839 (setq e (match-end 0)))
17840 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17841 (kill-buffer buf)
17842 (delete-file tmpfile)
17843 rtn))
17845 (defun org-closest-date (start current prefer)
17846 "Return closest date to CURRENT starting from START.
17848 CURRENT and START are both time stamps.
17850 When PREFER is `past', return a date that is either CURRENT or
17851 past. When PREFER is `future', return a date that is either
17852 CURRENT or future.
17854 Only time stamps with a repeater are modified. Any other time
17855 stamp stay unchanged. In any case, return value is an absolute
17856 day number."
17857 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17858 ;; No repeater. Do not shift time stamp.
17859 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17860 (let ((value (string-to-number (match-string 1 start)))
17861 (type (match-string 2 start)))
17862 (if (= 0 value)
17863 ;; Repeater with a 0-value is considered as void.
17864 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17865 (let* ((base (org-date-to-gregorian start))
17866 (target (org-date-to-gregorian current))
17867 (sday (calendar-absolute-from-gregorian base))
17868 (cday (calendar-absolute-from-gregorian target))
17869 n1 n2)
17870 ;; If START is already past CURRENT, just return START.
17871 (if (<= cday sday) sday
17872 ;; Compute closest date before (N1) and closest date past
17873 ;; (N2) CURRENT.
17874 (pcase type
17875 ("h"
17876 (let ((missing-hours
17877 (mod (+ (- (* 24 (- cday sday))
17878 (nth 2 (org-parse-time-string start)))
17879 org-extend-today-until)
17880 value)))
17881 (setf n1 (if (= missing-hours 0) cday
17882 (- cday (1+ (/ missing-hours 24)))))
17883 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17884 ((or "d" "w")
17885 (let ((value (if (equal type "w") (* 7 value) value)))
17886 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17887 (setf n2 (+ n1 value))))
17888 ("m"
17889 (let* ((add-months
17890 (lambda (d n)
17891 ;; Add N months to gregorian date D, i.e.,
17892 ;; a list (MONTH DAY YEAR). Return a valid
17893 ;; gregorian date.
17894 (let ((m (+ (nth 0 d) n)))
17895 (list (mod m 12)
17896 (nth 1 d)
17897 (+ (/ m 12) (nth 2 d))))))
17898 (months ; Complete months to TARGET.
17899 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17900 (- (nth 0 target) (nth 0 base))
17901 ;; If START's day is greater than
17902 ;; TARGET's, remove incomplete month.
17903 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17904 value)
17905 value))
17906 (before (funcall add-months base months)))
17907 (setf n1 (calendar-absolute-from-gregorian before))
17908 (setf n2
17909 (calendar-absolute-from-gregorian
17910 (funcall add-months before value)))))
17912 (let* ((d (nth 1 base))
17913 (m (nth 0 base))
17914 (y (nth 2 base))
17915 (years ; Complete years to TARGET.
17916 (* (/ (- (nth 2 target)
17918 ;; If START's month and day are
17919 ;; greater than TARGET's, remove
17920 ;; incomplete year.
17921 (if (or (> (nth 0 target) m)
17922 (and (= (nth 0 target) m)
17923 (> (nth 1 target) d)))
17926 value)
17927 value))
17928 (before (list m d (+ y years))))
17929 (setf n1 (calendar-absolute-from-gregorian before))
17930 (setf n2 (calendar-absolute-from-gregorian
17931 (list m d (+ (nth 2 before) value)))))))
17932 ;; Handle PREFER parameter, if any.
17933 (cond
17934 ((eq prefer 'past) (if (= cday n2) n2 n1))
17935 ((eq prefer 'future) (if (= cday n1) n1 n2))
17936 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17938 (defun org-date-to-gregorian (d)
17939 "Turn any specification of date D into a Gregorian date for the calendar."
17940 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17941 ((and (listp d) (= (length d) 3)) d)
17942 ((stringp d)
17943 (let ((d (org-parse-time-string d)))
17944 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17945 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17947 (defun org-parse-time-string (s &optional nodefault)
17948 "Parse the standard Org time string.
17949 This should be a lot faster than the normal `parse-time-string'.
17950 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17951 hour and minute fields will be nil if not given."
17952 (cond ((string-match org-ts-regexp0 s)
17953 (list 0
17954 (when (or (match-beginning 8) (not nodefault))
17955 (string-to-number (or (match-string 8 s) "0")))
17956 (when (or (match-beginning 7) (not nodefault))
17957 (string-to-number (or (match-string 7 s) "0")))
17958 (string-to-number (match-string 4 s))
17959 (string-to-number (match-string 3 s))
17960 (string-to-number (match-string 2 s))
17961 nil nil nil))
17962 ((string-match "^<[^>]+>$" s)
17963 (decode-time (seconds-to-time (org-matcher-time s))))
17964 (t (error "Not a standard Org time string: %s" s))))
17966 (defun org-timestamp-up (&optional arg)
17967 "Increase the date item at the cursor by one.
17968 If the cursor is on the year, change the year. If it is on the month,
17969 the day or the time, change that.
17970 With prefix ARG, change by that many units."
17971 (interactive "p")
17972 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17974 (defun org-timestamp-down (&optional arg)
17975 "Decrease the date item at the cursor by one.
17976 If the cursor is on the year, change the year. If it is on the month,
17977 the day or the time, change that.
17978 With prefix ARG, change by that many units."
17979 (interactive "p")
17980 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17982 (defun org-timestamp-up-day (&optional arg)
17983 "Increase the date in the time stamp by one day.
17984 With prefix ARG, change that many days."
17985 (interactive "p")
17986 (if (and (not (org-at-timestamp-p t))
17987 (org-at-heading-p))
17988 (org-todo 'up)
17989 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17991 (defun org-timestamp-down-day (&optional arg)
17992 "Decrease the date in the time stamp by one day.
17993 With prefix ARG, change that many days."
17994 (interactive "p")
17995 (if (and (not (org-at-timestamp-p t))
17996 (org-at-heading-p))
17997 (org-todo 'down)
17998 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18000 (defun org-at-timestamp-p (&optional inactive-ok)
18001 "Non-nil if point is inside a timestamp.
18003 When optional argument INACTIVE-OK is non-nil, also consider
18004 inactive timestamps.
18006 When this function returns a non-nil value, match data is set
18007 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18008 INACTIVE-OK."
18009 (interactive)
18010 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18011 (pos (point))
18012 (ans (or (looking-at tsr)
18013 (save-excursion
18014 (skip-chars-backward "^[<\n\r\t")
18015 (when (> (point) (point-min)) (backward-char 1))
18016 (and (looking-at tsr)
18017 (> (- (match-end 0) pos) -1))))))
18018 (and ans
18019 (boundp 'org-ts-what)
18020 (setq org-ts-what
18021 (cond
18022 ((= pos (match-beginning 0)) 'bracket)
18023 ;; Point is considered to be "on the bracket" whether
18024 ;; it's really on it or right after it.
18025 ((= pos (1- (match-end 0))) 'bracket)
18026 ((= pos (match-end 0)) 'after)
18027 ((org-pos-in-match-range pos 2) 'year)
18028 ((org-pos-in-match-range pos 3) 'month)
18029 ((org-pos-in-match-range pos 7) 'hour)
18030 ((org-pos-in-match-range pos 8) 'minute)
18031 ((or (org-pos-in-match-range pos 4)
18032 (org-pos-in-match-range pos 5)) 'day)
18033 ((and (> pos (or (match-end 8) (match-end 5)))
18034 (< pos (match-end 0)))
18035 (- pos (or (match-end 8) (match-end 5))))
18036 (t 'day))))
18037 ans))
18039 (defun org-toggle-timestamp-type ()
18040 "Toggle the type (<active> or [inactive]) of a time stamp."
18041 (interactive)
18042 (when (org-at-timestamp-p t)
18043 (let ((beg (match-beginning 0)) (end (match-end 0))
18044 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18045 (save-excursion
18046 (goto-char beg)
18047 (while (re-search-forward "[][<>]" end t)
18048 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18049 t t)))
18050 (message "Timestamp is now %sactive"
18051 (if (equal (char-after beg) ?<) "" "in")))))
18053 (defun org-at-clock-log-p nil
18054 "Is the cursor on the clock log line?"
18055 (save-excursion
18056 (move-beginning-of-line 1)
18057 (looking-at org-clock-line-re)))
18059 (defvar org-clock-history) ; defined in org-clock.el
18060 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18061 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18062 "Change the date in the time stamp at point.
18063 The date will be changed by N times WHAT. WHAT can be `day', `month',
18064 `year', `minute', `second'. If WHAT is not given, the cursor position
18065 in the timestamp determines what will be changed.
18066 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18067 (let ((origin (point)) origin-cat
18068 with-hm inactive
18069 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18070 org-ts-what
18071 extra rem
18072 ts time time0 fixnext clrgx)
18073 (unless (org-at-timestamp-p t)
18074 (user-error "Not at a timestamp"))
18075 (if (and (not what) (eq org-ts-what 'bracket))
18076 (org-toggle-timestamp-type)
18077 ;; Point isn't on brackets. Remember the part of the time-stamp
18078 ;; the point was in. Indeed, size of time-stamps may change,
18079 ;; but point must be kept in the same category nonetheless.
18080 (setq origin-cat org-ts-what)
18081 (when (and (not what) (not (eq org-ts-what 'day))
18082 org-display-custom-times
18083 (get-text-property (point) 'display)
18084 (not (get-text-property (1- (point)) 'display)))
18085 (setq org-ts-what 'day))
18086 (setq org-ts-what (or what org-ts-what)
18087 inactive (= (char-after (match-beginning 0)) ?\[)
18088 ts (match-string 0))
18089 (replace-match "")
18090 (when (string-match
18091 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18093 (setq extra (match-string 1 ts))
18094 (when suppress-tmp-delay
18095 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18096 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18097 (setq with-hm t))
18098 (setq time0 (org-parse-time-string ts))
18099 (when (and updown
18100 (eq org-ts-what 'minute)
18101 (not current-prefix-arg))
18102 ;; This looks like s-up and s-down. Change by one rounding step.
18103 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18104 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18105 (setcar (cdr time0) (+ (nth 1 time0)
18106 (if (> n 0) (- rem) (- dm rem))))))
18107 (setq time
18108 (apply #'encode-time
18109 (or (car time0) 0)
18110 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18111 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18112 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18113 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18114 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18115 (nthcdr 6 time0)))
18116 (when (and (member org-ts-what '(hour minute))
18117 extra
18118 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18119 (setq extra (org-modify-ts-extra
18120 extra
18121 (if (eq org-ts-what 'hour) 2 5)
18122 n dm)))
18123 (when (integerp org-ts-what)
18124 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18125 (when (eq what 'calendar)
18126 (let ((cal-date (org-get-date-from-calendar)))
18127 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18128 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18129 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18130 (setcar time0 (or (car time0) 0))
18131 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18132 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18133 (setq time (apply 'encode-time time0))))
18134 ;; Insert the new time-stamp, and ensure point stays in the same
18135 ;; category as before (i.e. not after the last position in that
18136 ;; category).
18137 (let ((pos (point)))
18138 ;; Stay before inserted string. `save-excursion' is of no use.
18139 (setq org-last-changed-timestamp
18140 (org-insert-time-stamp time with-hm inactive nil nil extra))
18141 (goto-char pos))
18142 (save-match-data
18143 (looking-at org-ts-regexp3)
18144 (goto-char (cond
18145 ;; `day' category ends before `hour' if any, or at
18146 ;; the end of the day name.
18147 ((eq origin-cat 'day)
18148 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18149 ((eq origin-cat 'hour) (min (match-end 7) origin))
18150 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18151 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18152 ;; `year' and `month' have both fixed size: point
18153 ;; couldn't have moved into another part.
18154 (t origin))))
18155 ;; Update clock if on a CLOCK line.
18156 (org-clock-update-time-maybe)
18157 ;; Maybe adjust the closest clock in `org-clock-history'
18158 (when org-clock-adjust-closest
18159 (if (not (and (org-at-clock-log-p)
18160 (< 1 (length (delq nil (mapcar 'marker-position
18161 org-clock-history))))))
18162 (message "No clock to adjust")
18163 (cond ((save-excursion ; fix previous clock?
18164 (re-search-backward org-ts-regexp0 nil t)
18165 (looking-back (concat org-clock-string " \\[")
18166 (line-beginning-position)))
18167 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18168 ((save-excursion ; fix next clock?
18169 (re-search-backward org-ts-regexp0 nil t)
18170 (looking-at (concat org-ts-regexp0 "\\] =>")))
18171 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18172 (save-window-excursion
18173 ;; Find closest clock to point, adjust the previous/next one in history
18174 (let* ((p (save-excursion (org-back-to-heading t)))
18175 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18176 (clfixnth
18177 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18178 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18179 (if (not clfixpos)
18180 (message "No clock to adjust")
18181 (save-excursion
18182 (org-goto-marker-or-bmk clfixpos)
18183 (org-show-subtree)
18184 (when (re-search-forward clrgx nil t)
18185 (goto-char (match-beginning 1))
18186 (let (org-clock-adjust-closest)
18187 (org-timestamp-change n org-ts-what updown))
18188 (message "Clock adjusted in %s for heading: %s"
18189 (file-name-nondirectory (buffer-file-name))
18190 (org-get-heading t t)))))))))
18191 ;; Try to recenter the calendar window, if any.
18192 (when (and org-calendar-follow-timestamp-change
18193 (get-buffer-window "*Calendar*" t)
18194 (memq org-ts-what '(day month year)))
18195 (org-recenter-calendar (time-to-days time))))))
18197 (defun org-modify-ts-extra (s pos n dm)
18198 "Change the different parts of the lead-time and repeat fields in timestamp."
18199 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18200 ng h m new rem)
18201 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18202 (cond
18203 ((or (org-pos-in-match-range pos 2)
18204 (org-pos-in-match-range pos 3))
18205 (setq m (string-to-number (match-string 3 s))
18206 h (string-to-number (match-string 2 s)))
18207 (if (org-pos-in-match-range pos 2)
18208 (setq h (+ h n))
18209 (setq n (* dm (with-no-warnings (signum n))))
18210 (unless (= 0 (setq rem (% m dm)))
18211 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18212 (setq m (+ m n)))
18213 (when (< m 0) (setq m (+ m 60) h (1- h)))
18214 (when (> m 59) (setq m (- m 60) h (1+ h)))
18215 (setq h (mod h 24))
18216 (setq ng 1 new (format "-%02d:%02d" h m)))
18217 ((org-pos-in-match-range pos 6)
18218 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18219 ((org-pos-in-match-range pos 5)
18220 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18222 ((org-pos-in-match-range pos 9)
18223 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18224 ((org-pos-in-match-range pos 8)
18225 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18227 (when ng
18228 (setq s (concat
18229 (substring s 0 (match-beginning ng))
18231 (substring s (match-end ng))))))
18234 (defun org-recenter-calendar (d)
18235 "If the calendar is visible, recenter it to date D."
18236 (let ((cwin (get-buffer-window "*Calendar*" t)))
18237 (when cwin
18238 (let ((calendar-move-hook nil))
18239 (with-selected-window cwin
18240 (calendar-goto-date
18241 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18243 (defun org-goto-calendar (&optional arg)
18244 "Go to the Emacs calendar at the current date.
18245 If there is a time stamp in the current line, go to that date.
18246 A prefix ARG can be used to force the current date."
18247 (interactive "P")
18248 (let ((tsr org-ts-regexp) diff
18249 (calendar-move-hook nil)
18250 (calendar-view-holidays-initially-flag nil)
18251 (calendar-view-diary-initially-flag nil))
18252 (when (or (org-at-timestamp-p)
18253 (save-excursion
18254 (beginning-of-line 1)
18255 (looking-at (concat ".*" tsr))))
18256 (let ((d1 (time-to-days (current-time)))
18257 (d2 (time-to-days
18258 (org-time-string-to-time (match-string 1)))))
18259 (setq diff (- d2 d1))))
18260 (calendar)
18261 (calendar-goto-today)
18262 (when (and diff (not arg)) (calendar-forward-day diff))))
18264 (defun org-get-date-from-calendar ()
18265 "Return a list (month day year) of date at point in calendar."
18266 (with-current-buffer "*Calendar*"
18267 (save-match-data
18268 (calendar-cursor-to-date))))
18270 (defun org-date-from-calendar ()
18271 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18272 If there is already a time stamp at the cursor position, update it."
18273 (interactive)
18274 (if (org-at-timestamp-p t)
18275 (org-timestamp-change 0 'calendar)
18276 (let ((cal-date (org-get-date-from-calendar)))
18277 (org-insert-time-stamp
18278 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18280 (defcustom org-effort-durations
18281 `(("min" . 1)
18282 ("h" . 60)
18283 ("d" . ,(* 60 8))
18284 ("w" . ,(* 60 8 5))
18285 ("m" . ,(* 60 8 5 4))
18286 ("y" . ,(* 60 8 5 40)))
18287 "Conversion factor to minutes for an effort modifier.
18289 Each entry has the form (MODIFIER . MINUTES).
18291 In an effort string, a number followed by MODIFIER is multiplied
18292 by the specified number of MINUTES to obtain an effort in
18293 minutes.
18295 For example, if the value of this variable is ((\"hours\" . 60)), then an
18296 effort string \"2hours\" is equivalent to 120 minutes."
18297 :group 'org-agenda
18298 :version "25.1"
18299 :package-version '(Org . "8.3")
18300 :type '(alist :key-type (string :tag "Modifier")
18301 :value-type (number :tag "Minutes")))
18303 (defun org-minutes-to-clocksum-string (m)
18304 "Format number of minutes as a clocksum string.
18305 The format is determined by `org-time-clocksum-format',
18306 `org-time-clocksum-use-fractional' and
18307 `org-time-clocksum-fractional-format' and
18308 `org-time-clocksum-use-effort-durations'."
18309 (let ((clocksum "")
18310 (m (round m)) ; Don't allow fractions of minutes
18311 h d w mo y fmt n)
18312 (setq h (if org-time-clocksum-use-effort-durations
18313 (cdr (assoc "h" org-effort-durations)) 60)
18314 d (if org-time-clocksum-use-effort-durations
18315 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18316 w (if org-time-clocksum-use-effort-durations
18317 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18318 mo (if org-time-clocksum-use-effort-durations
18319 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18320 y (if org-time-clocksum-use-effort-durations
18321 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18322 ;; fractional format
18323 (if org-time-clocksum-use-fractional
18324 (cond
18325 ;; single format string
18326 ((stringp org-time-clocksum-fractional-format)
18327 (format org-time-clocksum-fractional-format (/ m (float h))))
18328 ;; choice of fractional formats for different time units
18329 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18330 (> (/ (truncate m) (* y d h)) 0))
18331 (format fmt (/ m (* y d (float h)))))
18332 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18333 (> (/ (truncate m) (* mo d h)) 0))
18334 (format fmt (/ m (* mo d (float h)))))
18335 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18336 (> (/ (truncate m) (* w d h)) 0))
18337 (format fmt (/ m (* w d (float h)))))
18338 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18339 (> (/ (truncate m) (* d h)) 0))
18340 (format fmt (/ m (* d (float h)))))
18341 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18342 (> (/ (truncate m) h) 0))
18343 (format fmt (/ m (float h))))
18344 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18345 (format fmt m))
18346 ;; fall back to smallest time unit with a format
18347 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18348 (format fmt (/ m (float h))))
18349 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18350 (format fmt (/ m (* d (float h)))))
18351 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18352 (format fmt (/ m (* w d (float h)))))
18353 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18354 (format fmt (/ m (* mo d (float h)))))
18355 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18356 (format fmt (/ m (* y d (float h))))))
18357 ;; standard (non-fractional) format, with single format string
18358 (if (stringp org-time-clocksum-format)
18359 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18360 ;; separate formats components
18361 (and (setq fmt (plist-get org-time-clocksum-format :years))
18362 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18363 (plist-get org-time-clocksum-format :require-years))
18364 (setq clocksum (concat clocksum (format fmt n))
18365 m (- m (* n y d h))))
18366 (and (setq fmt (plist-get org-time-clocksum-format :months))
18367 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18368 (plist-get org-time-clocksum-format :require-months))
18369 (setq clocksum (concat clocksum (format fmt n))
18370 m (- m (* n mo d h))))
18371 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18372 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18373 (plist-get org-time-clocksum-format :require-weeks))
18374 (setq clocksum (concat clocksum (format fmt n))
18375 m (- m (* n w d h))))
18376 (and (setq fmt (plist-get org-time-clocksum-format :days))
18377 (or (> (setq n (/ (truncate m) (* d h))) 0)
18378 (plist-get org-time-clocksum-format :require-days))
18379 (setq clocksum (concat clocksum (format fmt n))
18380 m (- m (* n d h))))
18381 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18382 (or (> (setq n (/ (truncate m) h)) 0)
18383 (plist-get org-time-clocksum-format :require-hours))
18384 (setq clocksum (concat clocksum (format fmt n))
18385 m (- m (* n h))))
18386 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18387 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18388 (setq clocksum (concat clocksum (format fmt m))))
18389 ;; return formatted time duration
18390 clocksum))))
18392 (defun org-hours-to-clocksum-string (n)
18393 (org-minutes-to-clocksum-string (* n 60)))
18395 (defun org-hh:mm-string-to-minutes (s)
18396 "Convert a string H:MM to a number of minutes.
18397 If the string is just a number, interpret it as minutes.
18398 In fact, the first hh:mm or number in the string will be taken,
18399 there can be extra stuff in the string.
18400 If no number is found, the return value is 0."
18401 (cond
18402 ((integerp s) s)
18403 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18404 (+ (* (string-to-number (match-string 1 s)) 60)
18405 (string-to-number (match-string 2 s))))
18406 ((string-match "\\([0-9]+\\)" s)
18407 (string-to-number (match-string 1 s)))
18408 (t 0)))
18410 (defcustom org-image-actual-width t
18411 "Should we use the actual width of images when inlining them?
18413 When set to t, always use the image width.
18415 When set to a number, use imagemagick (when available) to set
18416 the image's width to this value.
18418 When set to a number in a list, try to get the width from any
18419 #+ATTR.* keyword if it matches a width specification like
18421 #+ATTR_HTML: :width 300px
18423 and fall back on that number if none is found.
18425 When set to nil, try to get the width from an #+ATTR.* keyword
18426 and fall back on the original width if none is found.
18428 This requires Emacs >= 24.1, build with imagemagick support."
18429 :group 'org-appearance
18430 :version "24.4"
18431 :package-version '(Org . "8.0")
18432 :type '(choice
18433 (const :tag "Use the image width" t)
18434 (integer :tag "Use a number of pixels")
18435 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18436 (const :tag "Use #+ATTR* or don't resize" nil)))
18438 (defcustom org-agenda-inhibit-startup nil
18439 "Inhibit startup when preparing agenda buffers.
18440 When this variable is t, the initialization of the Org agenda
18441 buffers is inhibited: e.g. the visibility state is not set, the
18442 tables are not re-aligned, etc."
18443 :type 'boolean
18444 :version "24.3"
18445 :group 'org-agenda)
18447 (defcustom org-agenda-ignore-properties nil
18448 "Avoid updating text properties when building the agenda.
18449 Properties are used to prepare buffers for effort estimates,
18450 appointments, statistics and subtree-local categories.
18451 If you don't use these in the agenda, you can add them to this
18452 list and agenda building will be a bit faster.
18453 The value is a list, with zero or more of the symbols `effort', `appt',
18454 `stats' or `category'."
18455 :type '(set :greedy t
18456 (const effort)
18457 (const appt)
18458 (const stats)
18459 (const category))
18460 :version "25.1"
18461 :package-version '(Org . "8.3")
18462 :group 'org-agenda)
18464 (defun org-duration-string-to-minutes (s &optional output-to-string)
18465 "Convert a duration string S to minutes.
18467 A bare number is interpreted as minutes, modifiers can be set by
18468 customizing `org-effort-durations' (which see).
18470 Entries containing a colon are interpreted as H:MM by
18471 `org-hh:mm-string-to-minutes'."
18472 (let ((result 0)
18473 (re (concat "\\([0-9.]+\\) *\\("
18474 (regexp-opt (mapcar 'car org-effort-durations))
18475 "\\)")))
18476 (while (string-match re s)
18477 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18478 (string-to-number (match-string 1 s))))
18479 (setq s (replace-match "" nil t s)))
18480 (setq result (floor result))
18481 (cl-incf result (org-hh:mm-string-to-minutes s))
18482 (if output-to-string (number-to-string result) result)))
18484 ;;;; Files
18486 (defun org-save-all-org-buffers ()
18487 "Save all Org buffers without user confirmation."
18488 (interactive)
18489 (message "Saving all Org buffers...")
18490 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18491 (when (featurep 'org-id) (org-id-locations-save))
18492 (message "Saving all Org buffers... done"))
18494 (defun org-revert-all-org-buffers ()
18495 "Revert all Org buffers.
18496 Prompt for confirmation when there are unsaved changes.
18497 Be sure you know what you are doing before letting this function
18498 overwrite your changes.
18500 This function is useful in a setup where one tracks org files
18501 with a version control system, to revert on one machine after pulling
18502 changes from another. I believe the procedure must be like this:
18504 1. M-x org-save-all-org-buffers
18505 2. Pull changes from the other machine, resolve conflicts
18506 3. M-x org-revert-all-org-buffers"
18507 (interactive)
18508 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18509 (user-error "Abort"))
18510 (save-excursion
18511 (save-window-excursion
18512 (dolist (b (buffer-list))
18513 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18514 (with-current-buffer b buffer-file-name))
18515 (pop-to-buffer-same-window b)
18516 (revert-buffer t 'no-confirm)))
18517 (when (and (featurep 'org-id) org-id-track-globally)
18518 (org-id-locations-load)))))
18520 ;;;; Agenda files
18522 ;;;###autoload
18523 (defun org-switchb (&optional arg)
18524 "Switch between Org buffers.
18526 With \\[universal-argument] prefix, restrict available buffers to files.
18528 With \\[universal-argument] \\[universal-argument] \
18529 prefix, restrict available buffers to agenda files."
18530 (interactive "P")
18531 (let ((blist (org-buffer-list
18532 (cond ((equal arg '(4)) 'files)
18533 ((equal arg '(16)) 'agenda)))))
18534 (pop-to-buffer-same-window
18535 (completing-read "Org buffer: "
18536 (mapcar #'list (mapcar #'buffer-name blist))
18537 nil t))))
18539 (defun org-buffer-list (&optional predicate exclude-tmp)
18540 "Return a list of Org buffers.
18541 PREDICATE can be `export', `files' or `agenda'.
18543 export restrict the list to Export buffers.
18544 files restrict the list to buffers visiting Org files.
18545 agenda restrict the list to buffers visiting agenda files.
18547 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18548 (let* ((bfn nil)
18549 (agenda-files (and (eq predicate 'agenda)
18550 (mapcar 'file-truename (org-agenda-files t))))
18551 (filter
18552 (cond
18553 ((eq predicate 'files)
18554 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18555 ((eq predicate 'export)
18556 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18557 ((eq predicate 'agenda)
18558 (lambda (b)
18559 (with-current-buffer b
18560 (and (derived-mode-p 'org-mode)
18561 (setq bfn (buffer-file-name b))
18562 (member (file-truename bfn) agenda-files)))))
18563 (t (lambda (b) (with-current-buffer b
18564 (or (derived-mode-p 'org-mode)
18565 (string-match "\\*Org .*Export"
18566 (buffer-name b)))))))))
18567 (delq nil
18568 (mapcar
18569 (lambda(b)
18570 (if (and (funcall filter b)
18571 (or (not exclude-tmp)
18572 (not (string-match "tmp" (buffer-name b)))))
18574 nil))
18575 (buffer-list)))))
18577 (defun org-agenda-files (&optional unrestricted archives)
18578 "Get the list of agenda files.
18579 Optional UNRESTRICTED means return the full list even if a restriction
18580 is currently in place.
18581 When ARCHIVES is t, include all archive files that are really being
18582 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18583 `org-agenda-archives-mode' is t."
18584 (let ((files
18585 (cond
18586 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18587 ((stringp org-agenda-files) (org-read-agenda-file-list))
18588 ((listp org-agenda-files) org-agenda-files)
18589 (t (error "Invalid value of `org-agenda-files'")))))
18590 (setq files (apply 'append
18591 (mapcar (lambda (f)
18592 (if (file-directory-p f)
18593 (directory-files
18594 f t org-agenda-file-regexp)
18595 (list f)))
18596 files)))
18597 (when org-agenda-skip-unavailable-files
18598 (setq files (delq nil
18599 (mapcar (function
18600 (lambda (file)
18601 (and (file-readable-p file) file)))
18602 files))))
18603 (when (or (eq archives t)
18604 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18605 (setq files (org-add-archive-files files)))
18606 files))
18608 (defun org-agenda-file-p (&optional file)
18609 "Return non-nil, if FILE is an agenda file.
18610 If FILE is omitted, use the file associated with the current
18611 buffer."
18612 (let ((fname (or file (buffer-file-name))))
18613 (and fname
18614 (member (file-truename fname)
18615 (mapcar #'file-truename (org-agenda-files t))))))
18617 (defun org-edit-agenda-file-list ()
18618 "Edit the list of agenda files.
18619 Depending on setup, this either uses customize to edit the variable
18620 `org-agenda-files', or it visits the file that is holding the list. In the
18621 latter case, the buffer is set up in a way that saving it automatically kills
18622 the buffer and restores the previous window configuration."
18623 (interactive)
18624 (if (stringp org-agenda-files)
18625 (let ((cw (current-window-configuration)))
18626 (find-file org-agenda-files)
18627 (setq-local org-window-configuration cw)
18628 (add-hook 'after-save-hook
18629 (lambda ()
18630 (set-window-configuration
18631 (prog1 org-window-configuration
18632 (kill-buffer (current-buffer))))
18633 (org-install-agenda-files-menu)
18634 (message "New agenda file list installed"))
18635 nil 'local)
18636 (message "%s" (substitute-command-keys
18637 "Edit list and finish with \\[save-buffer]")))
18638 (customize-variable 'org-agenda-files)))
18640 (defun org-store-new-agenda-file-list (list)
18641 "Set new value for the agenda file list and save it correctly."
18642 (if (stringp org-agenda-files)
18643 (let ((fe (org-read-agenda-file-list t)) b u)
18644 (while (setq b (find-buffer-visiting org-agenda-files))
18645 (kill-buffer b))
18646 (with-temp-file org-agenda-files
18647 (insert
18648 (mapconcat
18649 (lambda (f) ;; Keep un-expanded entries.
18650 (if (setq u (assoc f fe))
18651 (cdr u)
18653 list "\n")
18654 "\n")))
18655 (let ((org-mode-hook nil) (org-inhibit-startup t)
18656 (org-insert-mode-line-in-empty-file nil))
18657 (setq org-agenda-files list)
18658 (customize-save-variable 'org-agenda-files org-agenda-files))))
18660 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18661 "Read the list of agenda files from a file.
18662 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18663 filenames, used by `org-store-new-agenda-file-list' to write back
18664 un-expanded file names."
18665 (when (file-directory-p org-agenda-files)
18666 (error "`org-agenda-files' cannot be a single directory"))
18667 (when (stringp org-agenda-files)
18668 (with-temp-buffer
18669 (insert-file-contents org-agenda-files)
18670 (mapcar
18671 (lambda (f)
18672 (let ((e (expand-file-name (substitute-in-file-name f)
18673 org-directory)))
18674 (if pair-with-expansion
18675 (cons e f)
18676 e)))
18677 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18679 ;;;###autoload
18680 (defun org-cycle-agenda-files ()
18681 "Cycle through the files in `org-agenda-files'.
18682 If the current buffer visits an agenda file, find the next one in the list.
18683 If the current buffer does not, find the first agenda file."
18684 (interactive)
18685 (let* ((fs (or (org-agenda-files t)
18686 (user-error "No agenda files")))
18687 (files (copy-sequence fs))
18688 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18689 file)
18690 (when tcf
18691 (while (and (setq file (pop files))
18692 (not (equal (file-truename file) tcf)))))
18693 (find-file (car (or files fs)))
18694 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18696 (defun org-agenda-file-to-front (&optional to-end)
18697 "Move/add the current file to the top of the agenda file list.
18698 If the file is not present in the list, it is added to the front. If it is
18699 present, it is moved there. With optional argument TO-END, add/move to the
18700 end of the list."
18701 (interactive "P")
18702 (let ((org-agenda-skip-unavailable-files nil)
18703 (file-alist (mapcar (lambda (x)
18704 (cons (file-truename x) x))
18705 (org-agenda-files t)))
18706 (ctf (file-truename
18707 (or buffer-file-name
18708 (user-error "Please save the current buffer to a file"))))
18709 x had)
18710 (setq x (assoc ctf file-alist) had x)
18712 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18713 (if to-end
18714 (setq file-alist (append (delq x file-alist) (list x)))
18715 (setq file-alist (cons x (delq x file-alist))))
18716 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18717 (org-install-agenda-files-menu)
18718 (message "File %s to %s of agenda file list"
18719 (if had "moved" "added") (if to-end "end" "front"))))
18721 (defun org-remove-file (&optional file)
18722 "Remove current file from the list of files in variable `org-agenda-files'.
18723 These are the files which are being checked for agenda entries.
18724 Optional argument FILE means use this file instead of the current."
18725 (interactive)
18726 (let* ((org-agenda-skip-unavailable-files nil)
18727 (file (or file buffer-file-name
18728 (user-error "Current buffer does not visit a file")))
18729 (true-file (file-truename file))
18730 (afile (abbreviate-file-name file))
18731 (files (delq nil (mapcar
18732 (lambda (x)
18733 (unless (equal true-file
18734 (file-truename x))
18736 (org-agenda-files t)))))
18737 (if (not (= (length files) (length (org-agenda-files t))))
18738 (progn
18739 (org-store-new-agenda-file-list files)
18740 (org-install-agenda-files-menu)
18741 (message "Removed from Org Agenda list: %s" afile))
18742 (message "File was not in list: %s (not removed)" afile))))
18744 (defun org-file-menu-entry (file)
18745 (vector file (list 'find-file file) t))
18747 (defun org-check-agenda-file (file)
18748 "Make sure FILE exists. If not, ask user what to do."
18749 (unless (file-exists-p file)
18750 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18751 (abbreviate-file-name file))
18752 (let ((r (downcase (read-char-exclusive))))
18753 (cond
18754 ((equal r ?r)
18755 (org-remove-file file)
18756 (throw 'nextfile t))
18757 (t (user-error "Abort"))))))
18759 (defun org-get-agenda-file-buffer (file)
18760 "Get an agenda buffer visiting FILE.
18761 If the buffer needs to be created, add it to the list of buffers
18762 which might be released later."
18763 (let ((buf (org-find-base-buffer-visiting file)))
18764 (if buf
18765 buf ; just return it
18766 ;; Make a new buffer and remember it
18767 (setq buf (find-file-noselect file))
18768 (when buf (push buf org-agenda-new-buffers))
18769 buf)))
18771 (defun org-release-buffers (blist)
18772 "Release all buffers in list, asking the user for confirmation when needed.
18773 When a buffer is unmodified, it is just killed. When modified, it is saved
18774 \(if the user agrees) and then killed."
18775 (let (file)
18776 (dolist (buf blist)
18777 (setq file (buffer-file-name buf))
18778 (when (and (buffer-modified-p buf)
18779 file
18780 (y-or-n-p (format "Save file %s? " file)))
18781 (with-current-buffer buf (save-buffer)))
18782 (kill-buffer buf))))
18784 (defun org-agenda-prepare-buffers (files)
18785 "Create buffers for all agenda files, protect archived trees and comments."
18786 (interactive)
18787 (let ((pa '(:org-archived t))
18788 (pc '(:org-comment t))
18789 (pall '(:org-archived t :org-comment t))
18790 (inhibit-read-only t)
18791 (org-inhibit-startup org-agenda-inhibit-startup)
18792 (rea (concat ":" org-archive-tag ":"))
18793 re pos)
18794 (setq org-tag-alist-for-agenda nil
18795 org-tag-groups-alist-for-agenda nil)
18796 (save-excursion
18797 (save-restriction
18798 (dolist (file files)
18799 (catch 'nextfile
18800 (if (bufferp file)
18801 (set-buffer file)
18802 (org-check-agenda-file file)
18803 (set-buffer (org-get-agenda-file-buffer file)))
18804 (widen)
18805 (org-set-regexps-and-options 'tags-only)
18806 (setq pos (point))
18807 (or (memq 'category org-agenda-ignore-properties)
18808 (org-refresh-category-properties))
18809 (or (memq 'stats org-agenda-ignore-properties)
18810 (org-refresh-stats-properties))
18811 (or (memq 'effort org-agenda-ignore-properties)
18812 (org-refresh-effort-properties))
18813 (or (memq 'appt org-agenda-ignore-properties)
18814 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18815 (setq org-todo-keywords-for-agenda
18816 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18817 (setq org-done-keywords-for-agenda
18818 (append org-done-keywords-for-agenda org-done-keywords))
18819 (setq org-todo-keyword-alist-for-agenda
18820 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18821 (setq org-tag-alist-for-agenda
18822 (org-uniquify
18823 (append org-tag-alist-for-agenda
18824 org-current-tag-alist)))
18825 ;; Merge current file's tag groups into global
18826 ;; `org-tag-groups-alist-for-agenda'.
18827 (when org-group-tags
18828 (dolist (alist org-tag-groups-alist)
18829 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18830 (if old
18831 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18832 (push alist org-tag-groups-alist-for-agenda)))))
18833 (org-with-silent-modifications
18834 (save-excursion
18835 (remove-text-properties (point-min) (point-max) pall)
18836 (when org-agenda-skip-archived-trees
18837 (goto-char (point-min))
18838 (while (re-search-forward rea nil t)
18839 (when (org-at-heading-p t)
18840 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18841 (goto-char (point-min))
18842 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18843 (while (re-search-forward re nil t)
18844 (when (save-match-data (org-in-commented-heading-p t))
18845 (add-text-properties
18846 (match-beginning 0) (org-end-of-subtree t) pc)))))
18847 (goto-char pos)))))
18848 (setq org-todo-keywords-for-agenda
18849 (org-uniquify org-todo-keywords-for-agenda))
18850 (setq org-todo-keyword-alist-for-agenda
18851 (org-uniquify org-todo-keyword-alist-for-agenda))))
18854 ;;;; CDLaTeX minor mode
18856 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18857 "Keymap for the minor `org-cdlatex-mode'.")
18859 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18860 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18861 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18862 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18863 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18865 (defvar org-cdlatex-texmathp-advice-is-done nil
18866 "Flag remembering if we have applied the advice to texmathp already.")
18868 (define-minor-mode org-cdlatex-mode
18869 "Toggle the minor `org-cdlatex-mode'.
18870 This mode supports entering LaTeX environment and math in LaTeX fragments
18871 in Org-mode.
18872 \\{org-cdlatex-mode-map}"
18873 nil " OCDL" nil
18874 (when org-cdlatex-mode
18875 (require 'cdlatex)
18876 (run-hooks 'cdlatex-mode-hook)
18877 (cdlatex-compute-tables))
18878 (unless org-cdlatex-texmathp-advice-is-done
18879 (setq org-cdlatex-texmathp-advice-is-done t)
18880 (defadvice texmathp (around org-math-always-on activate)
18881 "Always return t in Org buffers.
18882 This is because we want to insert math symbols without dollars even outside
18883 the LaTeX math segments. If Orgmode thinks that point is actually inside
18884 an embedded LaTeX fragment, let texmathp do its job.
18885 \\[org-cdlatex-mode-map]"
18886 (interactive)
18887 (let (p)
18888 (cond
18889 ((not (derived-mode-p 'org-mode)) ad-do-it)
18890 ((eq this-command 'cdlatex-math-symbol)
18891 (setq ad-return-value t
18892 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18894 (let ((p (org-inside-LaTeX-fragment-p)))
18895 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18896 (setq ad-return-value t
18897 texmathp-why '("Org-mode embedded math" . 0))
18898 (when p ad-do-it)))))))))
18900 (defun turn-on-org-cdlatex ()
18901 "Unconditionally turn on `org-cdlatex-mode'."
18902 (org-cdlatex-mode 1))
18904 (defun org-try-cdlatex-tab ()
18905 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18906 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18907 - inside a LaTeX fragment, or
18908 - after the first word in a line, where an abbreviation expansion could
18909 insert a LaTeX environment."
18910 (when org-cdlatex-mode
18911 (cond
18912 ;; Before any word on the line: No expansion possible.
18913 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18914 ;; Just after first word on the line: Expand it. Make sure it
18915 ;; cannot happen on headlines, though.
18916 ((save-excursion
18917 (skip-chars-backward "a-zA-Z0-9*")
18918 (skip-chars-backward " \t")
18919 (and (bolp) (not (org-at-heading-p))))
18920 (cdlatex-tab) t)
18921 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18923 (defun org-cdlatex-underscore-caret (&optional _arg)
18924 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18925 Revert to the normal definition outside of these fragments."
18926 (interactive "P")
18927 (if (org-inside-LaTeX-fragment-p)
18928 (call-interactively 'cdlatex-sub-superscript)
18929 (let (org-cdlatex-mode)
18930 (call-interactively (key-binding (vector last-input-event))))))
18932 (defun org-cdlatex-math-modify (&optional _arg)
18933 "Execute `cdlatex-math-modify' in LaTeX fragments.
18934 Revert to the normal definition outside of these fragments."
18935 (interactive "P")
18936 (if (org-inside-LaTeX-fragment-p)
18937 (call-interactively 'cdlatex-math-modify)
18938 (let (org-cdlatex-mode)
18939 (call-interactively (key-binding (vector last-input-event))))))
18941 (defun org-cdlatex-environment-indent (&optional environment item)
18942 "Execute `cdlatex-environment' and indent the inserted environment.
18944 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18946 The inserted environment is indented to current indentation
18947 unless point is at the beginning of the line, in which the
18948 environment remains unintended."
18949 (interactive)
18950 ;; cdlatex-environment always return nil. Therefore, capture output
18951 ;; first and determine if an environment was selected.
18952 (let* ((beg (point-marker))
18953 (end (copy-marker (point) t))
18954 (inserted (progn
18955 (ignore-errors (cdlatex-environment environment item))
18956 (< beg end)))
18957 ;; Figure out how many lines to move forward after the
18958 ;; environment has been inserted.
18959 (lines (when inserted
18960 (save-excursion
18961 (- (cl-loop while (< beg (point))
18962 with x = 0
18963 do (forward-line -1)
18964 (cl-incf x)
18965 finally return x)
18966 (if (progn (goto-char beg)
18967 (and (progn (skip-chars-forward " \t") (eolp))
18968 (progn (skip-chars-backward " \t") (bolp))))
18969 1 0)))))
18970 (env (org-trim (delete-and-extract-region beg end))))
18971 (when inserted
18972 ;; Get indentation of next line unless at column 0.
18973 (let ((ind (if (bolp) 0
18974 (save-excursion
18975 (org-return-indent)
18976 (prog1 (org-get-indentation)
18977 (when (progn (skip-chars-forward " \t") (eolp))
18978 (delete-region beg (point)))))))
18979 (bol (progn (skip-chars-backward " \t") (bolp))))
18980 ;; Insert a newline before environment unless at column zero
18981 ;; to "escape" the current line. Insert a newline if
18982 ;; something is one the same line as \end{ENVIRONMENT}.
18983 (insert
18984 (concat (unless bol "\n") env
18985 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18986 (unless (zerop ind)
18987 (save-excursion
18988 (goto-char beg)
18989 (while (< (point) end)
18990 (unless (eolp) (indent-line-to ind))
18991 (forward-line))))
18992 (goto-char beg)
18993 (forward-line lines)
18994 (indent-line-to ind)))
18995 (set-marker beg nil)
18996 (set-marker end nil)))
18999 ;;;; LaTeX fragments
19001 (defun org-inside-LaTeX-fragment-p ()
19002 "Test if point is inside a LaTeX fragment.
19003 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19004 sequence appearing also before point.
19005 Even though the matchers for math are configurable, this function assumes
19006 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19007 delimiters are skipped when they have been removed by customization.
19008 The return value is nil, or a cons cell with the delimiter and the
19009 position of this delimiter.
19011 This function does a reasonably good job, but can locally be fooled by
19012 for example currency specifications. For example it will assume being in
19013 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19014 fragments that are properly closed, but during editing, we have to live
19015 with the uncertainty caused by missing closing delimiters. This function
19016 looks only before point, not after."
19017 (catch 'exit
19018 (let ((pos (point))
19019 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19020 (lim (progn
19021 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19022 (point)))
19023 dd-on str (start 0) m re)
19024 (goto-char pos)
19025 (when dodollar
19026 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19027 re (nth 1 (assoc "$" org-latex-regexps)))
19028 (while (string-match re str start)
19029 (cond
19030 ((= (match-end 0) (length str))
19031 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19032 ((= (match-end 0) (- (length str) 5))
19033 (throw 'exit nil))
19034 (t (setq start (match-end 0))))))
19035 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19036 (goto-char pos)
19037 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19038 (and (match-beginning 2) (throw 'exit nil))
19039 ;; count $$
19040 (while (re-search-backward "\\$\\$" lim t)
19041 (setq dd-on (not dd-on)))
19042 (goto-char pos)
19043 (when dd-on (cons "$$" m))))))
19045 (defun org-inside-latex-macro-p ()
19046 "Is point inside a LaTeX macro or its arguments?"
19047 (save-match-data
19048 (org-in-regexp
19049 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19051 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19052 "Build an overlay between BEG and END using IMAGE file.
19053 Argument IMAGETYPE is the extension of the displayed image,
19054 as a string. It defaults to \"png\"."
19055 (let ((ov (make-overlay beg end))
19056 (imagetype (or (intern imagetype) 'png)))
19057 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19058 (overlay-put ov 'evaporate t)
19059 (overlay-put ov
19060 'modification-hooks
19061 (list (lambda (o _flag _beg _end &optional _l)
19062 (delete-overlay o))))
19063 (overlay-put ov
19064 'display
19065 (list 'image :type imagetype :file image :ascent 'center))))
19067 (defun org--list-latex-overlays (&optional beg end)
19068 "List all Org LaTeX overlays in current buffer.
19069 Limit to overlays between BEG and END when those are provided."
19070 (cl-remove-if-not
19071 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19072 (overlays-in (or beg (point-min)) (or end (point-max)))))
19074 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19075 "Remove all overlays with LaTeX fragment images in current buffer.
19076 When optional arguments BEG and END are non-nil, remove all
19077 overlays between them instead. Return a non-nil value when some
19078 overlays were removed, nil otherwise."
19079 (let ((overlays (org--list-latex-overlays beg end)))
19080 (mapc #'delete-overlay overlays)
19081 overlays))
19083 (defun org-toggle-latex-fragment (&optional arg)
19084 "Preview the LaTeX fragment at point, or all locally or globally.
19086 If the cursor is on a LaTeX fragment, create the image and overlay
19087 it over the source code, if there is none. Remove it otherwise.
19088 If there is no fragment at point, display all fragments in the
19089 current section.
19091 With prefix ARG, preview or clear image for all fragments in the
19092 current subtree or in the whole buffer when used before the first
19093 headline. With a double prefix ARG \\[universal-argument] \
19094 \\[universal-argument] preview or clear images
19095 for all fragments in the buffer."
19096 (interactive "P")
19097 (when (display-graphic-p)
19098 (catch 'exit
19099 (save-excursion
19100 (let (beg end msg)
19101 (cond
19102 ((or (equal arg '(16))
19103 (and (equal arg '(4))
19104 (org-with-limited-levels (org-before-first-heading-p))))
19105 (if (org-remove-latex-fragment-image-overlays)
19106 (progn (message "LaTeX fragments images removed from buffer")
19107 (throw 'exit nil))
19108 (setq msg "Creating images for buffer...")))
19109 ((equal arg '(4))
19110 (org-with-limited-levels (org-back-to-heading t))
19111 (setq beg (point))
19112 (setq end (progn (org-end-of-subtree t) (point)))
19113 (if (org-remove-latex-fragment-image-overlays beg end)
19114 (progn
19115 (message "LaTeX fragment images removed from subtree")
19116 (throw 'exit nil))
19117 (setq msg "Creating images for subtree...")))
19118 ((let ((datum (org-element-context)))
19119 (when (memq (org-element-type datum)
19120 '(latex-environment latex-fragment))
19121 (setq beg (org-element-property :begin datum))
19122 (setq end (org-element-property :end datum))
19123 (if (org-remove-latex-fragment-image-overlays beg end)
19124 (progn (message "LaTeX fragment image removed")
19125 (throw 'exit nil))
19126 (setq msg "Creating image...")))))
19128 (org-with-limited-levels
19129 (setq beg (if (org-at-heading-p) (line-beginning-position)
19130 (outline-previous-heading)
19131 (point)))
19132 (setq end (progn (outline-next-heading) (point)))
19133 (if (org-remove-latex-fragment-image-overlays beg end)
19134 (progn
19135 (message "LaTeX fragment images removed from section")
19136 (throw 'exit nil))
19137 (setq msg "Creating images for section...")))))
19138 (let ((file (buffer-file-name (buffer-base-buffer))))
19139 (org-format-latex
19140 (concat org-preview-latex-image-directory "org-ltximg")
19141 beg end
19142 ;; Emacs cannot overlay images from remote hosts. Create
19143 ;; it in `temporary-file-directory' instead.
19144 (if (or (not file) (file-remote-p file))
19145 temporary-file-directory
19146 default-directory)
19147 'overlays msg 'forbuffer org-preview-latex-default-process))
19148 (message (concat msg "done")))))))
19150 (defun org-format-latex
19151 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19152 "Replace LaTeX fragments with links to an image.
19154 The function takes care of creating the replacement image.
19156 Only consider fragments between BEG and END when those are
19157 provided.
19159 When optional argument OVERLAYS is non-nil, display the image on
19160 top of the fragment instead of replacing it.
19162 PROCESSING-TYPE is the conversion method to use, as a symbol.
19164 Some of the options can be changed using the variable
19165 `org-format-latex-options', which see."
19166 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19167 (unless (eq processing-type 'verbatim)
19168 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19169 (cnt 0)
19170 checkdir-flag)
19171 (goto-char (or beg (point-min)))
19172 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19173 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19174 (overlay-recenter (or end (point-max))))
19175 (while (re-search-forward math-regexp end t)
19176 (unless (and overlays
19177 (eq (get-char-property (point) 'org-overlay-type)
19178 'org-latex-overlay))
19179 (let* ((context (org-element-context))
19180 (type (org-element-type context)))
19181 (when (memq type '(latex-environment latex-fragment))
19182 (let ((block-type (eq type 'latex-environment))
19183 (value (org-element-property :value context))
19184 (beg (org-element-property :begin context))
19185 (end (save-excursion
19186 (goto-char (org-element-property :end context))
19187 (skip-chars-backward " \r\t\n")
19188 (point))))
19189 (cond
19190 ((eq processing-type 'mathjax)
19191 ;; Prepare for MathJax processing.
19192 (if (not (string-match "\\`\\$\\$?" value))
19193 (goto-char end)
19194 (delete-region beg end)
19195 (if (string= (match-string 0 value) "$$")
19196 (insert "\\[" (substring value 2 -2) "\\]")
19197 (insert "\\(" (substring value 1 -1) "\\)"))))
19198 ((assq processing-type org-preview-latex-process-alist)
19199 ;; Process to an image.
19200 (cl-incf cnt)
19201 (goto-char beg)
19202 (let* ((processing-info
19203 (cdr (assq processing-type org-preview-latex-process-alist)))
19204 (face (face-at-point))
19205 ;; Get the colors from the face at point.
19207 (let ((color (plist-get org-format-latex-options
19208 :foreground)))
19209 (if (and forbuffer (eq color 'auto))
19210 (face-attribute face :foreground nil 'default)
19211 color)))
19213 (let ((color (plist-get org-format-latex-options
19214 :background)))
19215 (if (and forbuffer (eq color 'auto))
19216 (face-attribute face :background nil 'default)
19217 color)))
19218 (hash (sha1 (prin1-to-string
19219 (list org-format-latex-header
19220 org-latex-default-packages-alist
19221 org-latex-packages-alist
19222 org-format-latex-options
19223 forbuffer value fg bg))))
19224 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19225 (absprefix (expand-file-name prefix dir))
19226 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19227 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19228 (sep (and block-type "\n\n"))
19229 (link (concat sep "[[file:" linkfile "]]" sep))
19230 (options
19231 (org-combine-plists
19232 org-format-latex-options
19233 `(:foreground ,fg :background ,bg))))
19234 (when msg (message msg cnt))
19235 (unless checkdir-flag ; Ensure the directory exists.
19236 (setq checkdir-flag t)
19237 (let ((todir (file-name-directory absprefix)))
19238 (unless (file-directory-p todir)
19239 (make-directory todir t))))
19240 (unless (file-exists-p movefile)
19241 (org-create-formula-image
19242 value movefile options forbuffer processing-type))
19243 (if overlays
19244 (progn
19245 (dolist (o (overlays-in beg end))
19246 (when (eq (overlay-get o 'org-overlay-type)
19247 'org-latex-overlay)
19248 (delete-overlay o)))
19249 (org--format-latex-make-overlay beg end movefile imagetype)
19250 (goto-char end))
19251 (delete-region beg end)
19252 (insert
19253 (org-add-props link
19254 (list 'org-latex-src
19255 (replace-regexp-in-string "\"" "" value)
19256 'org-latex-src-embed-type
19257 (if block-type 'paragraph 'character)))))))
19258 ((eq processing-type 'mathml)
19259 ;; Process to MathML.
19260 (unless (org-format-latex-mathml-available-p)
19261 (user-error "LaTeX to MathML converter not configured"))
19262 (cl-incf cnt)
19263 (when msg (message msg cnt))
19264 (goto-char beg)
19265 (delete-region beg end)
19266 (insert (org-format-latex-as-mathml
19267 value block-type prefix dir)))
19269 (error "Unknown conversion process %s for LaTeX fragments"
19270 processing-type)))))))))))
19272 (defun org-create-math-formula (latex-frag &optional mathml-file)
19273 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19274 Use `org-latex-to-mathml-convert-command'. If the conversion is
19275 sucessful, return the portion between \"<math...> </math>\"
19276 elements otherwise return nil. When MATHML-FILE is specified,
19277 write the results in to that file. When invoked as an
19278 interactive command, prompt for LATEX-FRAG, with initial value
19279 set to the current active region and echo the results for user
19280 inspection."
19281 (interactive (list (let ((frag (when (org-region-active-p)
19282 (buffer-substring-no-properties
19283 (region-beginning) (region-end)))))
19284 (read-string "LaTeX Fragment: " frag nil frag))))
19285 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19286 (let* ((tmp-in-file
19287 (let ((file (file-relative-name
19288 (make-temp-name (expand-file-name "ltxmathml-in")))))
19289 (write-region latex-frag nil file)
19290 file))
19291 (tmp-out-file (file-relative-name
19292 (make-temp-name (expand-file-name "ltxmathml-out"))))
19293 (cmd (format-spec
19294 org-latex-to-mathml-convert-command
19295 `((?j . ,(and org-latex-to-mathml-jar-file
19296 (shell-quote-argument
19297 (expand-file-name
19298 org-latex-to-mathml-jar-file))))
19299 (?I . ,(shell-quote-argument tmp-in-file))
19300 (?i . ,latex-frag)
19301 (?o . ,(shell-quote-argument tmp-out-file)))))
19302 mathml shell-command-output)
19303 (when (called-interactively-p 'any)
19304 (unless (org-format-latex-mathml-available-p)
19305 (user-error "LaTeX to MathML converter not configured")))
19306 (message "Running %s" cmd)
19307 (setq shell-command-output (shell-command-to-string cmd))
19308 (setq mathml
19309 (when (file-readable-p tmp-out-file)
19310 (with-current-buffer (find-file-noselect tmp-out-file t)
19311 (goto-char (point-min))
19312 (when (re-search-forward
19313 (concat
19314 (regexp-quote
19315 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19316 "[^>]*?>"
19317 "\\(.\\|\n\\)*"
19318 "</math>")
19319 nil t)
19320 (prog1 (match-string 0) (kill-buffer))))))
19321 (cond
19322 (mathml
19323 (setq mathml
19324 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19325 (when mathml-file
19326 (write-region mathml nil mathml-file))
19327 (when (called-interactively-p 'any)
19328 (message mathml)))
19329 ((message "LaTeX to MathML conversion failed")
19330 (message shell-command-output)))
19331 (delete-file tmp-in-file)
19332 (when (file-exists-p tmp-out-file)
19333 (delete-file tmp-out-file))
19334 mathml))
19336 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19337 prefix &optional dir)
19338 "Use `org-create-math-formula' but check local cache first."
19339 (let* ((absprefix (expand-file-name prefix dir))
19340 (print-length nil) (print-level nil)
19341 (formula-id (concat
19342 "formula-"
19343 (sha1
19344 (prin1-to-string
19345 (list latex-frag
19346 org-latex-to-mathml-convert-command)))))
19347 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19348 (formula-cache-dir (file-name-directory formula-cache)))
19350 (unless (file-directory-p formula-cache-dir)
19351 (make-directory formula-cache-dir t))
19353 (unless (file-exists-p formula-cache)
19354 (org-create-math-formula latex-frag formula-cache))
19356 (if (file-exists-p formula-cache)
19357 ;; Successful conversion. Return the link to MathML file.
19358 (org-add-props
19359 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19360 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19361 'org-latex-src-embed-type (if latex-frag-type
19362 'paragraph 'character)))
19363 ;; Failed conversion. Return the LaTeX fragment verbatim
19364 latex-frag)))
19366 (declare-function org-export-get-backend "ox" (name))
19367 (declare-function org-export--get-global-options "ox" (&optional backend))
19368 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19369 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19370 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19371 (defun org-create-formula--latex-header ()
19372 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19373 (let ((info (org-combine-plists (org-export--get-global-options
19374 (org-export-get-backend 'latex))
19375 (org-export--get-inbuffer-options
19376 (org-export-get-backend 'latex)))))
19377 (org-latex-guess-babel-language
19378 (org-latex-guess-inputenc
19379 (org-splice-latex-header
19380 org-format-latex-header
19381 org-latex-default-packages-alist
19382 org-latex-packages-alist t
19383 (plist-get info :latex-header)))
19384 info)))
19386 (defun org--get-display-dpi ()
19387 "Get the DPI of the display.
19389 Assumes that the display has the same pixel width in the
19390 horizontal and vertical directions."
19391 (if (display-graphic-p)
19392 (round (/ (display-pixel-height)
19393 (/ (display-mm-height) 25.4)))
19394 (error "Attempt to calculate the dpi of a non-graphic display")))
19396 (defun org-create-formula-image
19397 (string tofile options buffer &optional processing-type)
19398 "Create an image from LaTeX source using external processes.
19400 The LaTeX STRING is saved to a temporary LaTeX file, then
19401 converted to an image file by process PROCESSING-TYPE defined in
19402 `org-preview-latex-process-alist'. A nil value defaults to
19403 `org-preview-latex-default-process'.
19405 The generated image file is eventually moved to TOFILE.
19407 The OPTIONS argument controls the size, foreground color and
19408 background color of the generated image.
19410 When BUFFER non-nil, this function is used for LaTeX previewing.
19411 Otherwise, it is used to deal with LaTeX snippets showed in
19412 a HTML file."
19413 (let* ((processing-type (or processing-type
19414 org-preview-latex-default-process))
19415 (processing-info
19416 (cdr (assq processing-type org-preview-latex-process-alist)))
19417 (programs (plist-get processing-info :programs))
19418 (error-message (or (plist-get processing-info :message) ""))
19419 (use-xcolor (plist-get processing-info :use-xcolor))
19420 (image-input-type (plist-get processing-info :image-input-type))
19421 (image-output-type (plist-get processing-info :image-output-type))
19422 (post-clean (or (plist-get processing-info :post-clean)
19423 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19424 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19425 (latex-header (or (plist-get processing-info :latex-header)
19426 (org-create-formula--latex-header)))
19427 (latex-compiler (plist-get processing-info :latex-compiler))
19428 (image-converter (plist-get processing-info :image-converter))
19429 (tmpdir temporary-file-directory)
19430 (texfilebase (make-temp-name
19431 (expand-file-name "orgtex" tmpdir)))
19432 (texfile (concat texfilebase ".tex"))
19433 (font-height (face-attribute 'default :height nil))
19434 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19435 '(1.0 . 1.0)))
19436 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19437 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19438 (dpi (* scale (floor (if buffer font-height 140.0))))
19439 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19440 "Black"))
19441 (bg (or (plist-get options (if buffer :background :html-background))
19442 "Transparent"))
19443 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19444 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19445 (dolist (program programs)
19446 (org-check-external-command program error-message))
19447 (if use-xcolor
19448 (progn (if (eq fg 'default)
19449 (setq fg (org-latex-color :foreground))
19450 (setq fg (org-latex-color-format fg)))
19451 (if (eq bg 'default)
19452 (setq bg (org-latex-color :background))
19453 (setq bg (org-latex-color-format
19454 (if (string= bg "Transparent") "white" bg))))
19455 (with-temp-file texfile
19456 (insert latex-header)
19457 (insert "\n\\begin{document}\n"
19458 "\\definecolor{fg}{rgb}{" fg "}\n"
19459 "\\definecolor{bg}{rgb}{" bg "}\n"
19460 "\n\\pagecolor{bg}\n"
19461 "\n{\\color{fg}\n"
19462 string
19463 "\n}\n"
19464 "\n\\end{document}\n")))
19465 (if (eq fg 'default)
19466 (setq fg (org-dvipng-color :foreground))
19467 (unless (string= fg "Transparent")
19468 (setq fg (org-dvipng-color-format fg))))
19469 (if (eq bg 'default)
19470 (setq bg (org-dvipng-color :background))
19471 (unless (string= bg "Transparent")
19472 (setq bg (org-dvipng-color-format bg))))
19473 (with-temp-file texfile
19474 (insert latex-header)
19475 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19477 (let* ((err-msg (format "Please adjust '%s' part of \
19478 `org-preview-latex-process-alist'."
19479 processing-type))
19480 (image-input-file
19481 (org-compile-file
19482 texfile latex-compiler image-input-type err-msg log-buf))
19483 (image-output-file
19484 (org-compile-file
19485 image-input-file image-converter image-output-type err-msg log-buf
19486 `((?F . ,(shell-quote-argument fg))
19487 (?B . ,(shell-quote-argument bg))
19488 (?D . ,(shell-quote-argument (format "%s" dpi)))
19489 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19490 (copy-file image-output-file tofile 'replace)
19491 (dolist (e post-clean)
19492 (when (file-exists-p (concat texfilebase e))
19493 (delete-file (concat texfilebase e))))
19494 image-output-file)))
19496 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19497 "Fill a LaTeX header template TPL.
19498 In the template, the following place holders will be recognized:
19500 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19501 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19502 [PACKAGES] \\usepackage statements for PKG
19503 [NO-PACKAGES] do not include PKG
19504 [EXTRA] the string EXTRA
19505 [NO-EXTRA] do not include EXTRA
19507 For backward compatibility, if both the positive and the negative place
19508 holder is missing, the positive one (without the \"NO-\") will be
19509 assumed to be present at the end of the template.
19510 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19511 EXTRA is a string.
19512 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19513 (let (rpl (end ""))
19514 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19515 (setq rpl (if (or (match-end 1) (not def-pkg))
19516 "" (org-latex-packages-to-string def-pkg snippets-p t))
19517 tpl (replace-match rpl t t tpl))
19518 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19520 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19521 (setq rpl (if (or (match-end 1) (not pkg))
19522 "" (org-latex-packages-to-string pkg snippets-p t))
19523 tpl (replace-match rpl t t tpl))
19524 (when pkg (setq end
19525 (concat end "\n"
19526 (org-latex-packages-to-string pkg snippets-p)))))
19528 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19529 (setq rpl (if (or (match-end 1) (not extra))
19530 "" (concat extra "\n"))
19531 tpl (replace-match rpl t t tpl))
19532 (when (and extra (string-match "\\S-" extra))
19533 (setq end (concat end "\n" extra))))
19535 (if (string-match "\\S-" end)
19536 (concat tpl "\n" end)
19537 tpl)))
19539 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19540 "Turn an alist of packages into a string with the \\usepackage macros."
19541 (setq pkg (mapconcat (lambda(p)
19542 (cond
19543 ((stringp p) p)
19544 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19545 (format "%% Package %s omitted" (cadr p)))
19546 ((equal "" (car p))
19547 (format "\\usepackage{%s}" (cadr p)))
19549 (format "\\usepackage[%s]{%s}"
19550 (car p) (cadr p)))))
19552 "\n"))
19553 (if newline (concat pkg "\n") pkg))
19555 (defun org-dvipng-color (attr)
19556 "Return a RGB color specification for dvipng."
19557 (apply #'format "rgb %s %s %s"
19558 (mapcar #'org-normalize-color
19559 (color-values (face-attribute 'default attr nil)))))
19561 (defun org-dvipng-color-format (color-name)
19562 "Convert COLOR-NAME to a RGB color value for dvipng."
19563 (apply 'format "rgb %s %s %s"
19564 (mapcar 'org-normalize-color
19565 (color-values color-name))))
19567 (defun org-latex-color (attr)
19568 "Return a RGB color for the LaTeX color package."
19569 (apply #'format "%s,%s,%s"
19570 (mapcar #'org-normalize-color
19571 (color-values (face-attribute 'default attr nil)))))
19573 (defun org-latex-color-format (color-name)
19574 "Convert COLOR-NAME to a RGB color value."
19575 (apply 'format "%s,%s,%s"
19576 (mapcar 'org-normalize-color
19577 (color-values color-name))))
19579 (defun org-normalize-color (value)
19580 "Return string to be used as color value for an RGB component."
19581 (format "%g" (/ value 65535.0)))
19585 ;; Image display
19587 (defvar-local org-inline-image-overlays nil)
19589 (defun org-toggle-inline-images (&optional include-linked)
19590 "Toggle the display of inline images.
19591 INCLUDE-LINKED is passed to `org-display-inline-images'."
19592 (interactive "P")
19593 (if org-inline-image-overlays
19594 (progn
19595 (org-remove-inline-images)
19596 (when (called-interactively-p 'interactive)
19597 (message "Inline image display turned off")))
19598 (org-display-inline-images include-linked)
19599 (when (called-interactively-p 'interactive)
19600 (message (if org-inline-image-overlays
19601 (format "%d images displayed inline"
19602 (length org-inline-image-overlays))
19603 "No images to display inline")))))
19605 (defun org-redisplay-inline-images ()
19606 "Refresh the display of inline images."
19607 (interactive)
19608 (if (not org-inline-image-overlays)
19609 (org-toggle-inline-images)
19610 (org-toggle-inline-images)
19611 (org-toggle-inline-images)))
19613 (defun org-display-inline-images (&optional include-linked refresh beg end)
19614 "Display inline images.
19616 An inline image is a link which follows either of these
19617 conventions:
19619 1. Its path is a file with an extension matching return value
19620 from `image-file-name-regexp' and it has no contents.
19622 2. Its description consists in a single link of the previous
19623 type.
19625 When optional argument INCLUDE-LINKED is non-nil, also links with
19626 a text description part will be inlined. This can be nice for
19627 a quick look at those images, but it does not reflect what
19628 exported files will look like.
19630 When optional argument REFRESH is non-nil, refresh existing
19631 images between BEG and END. This will create new image displays
19632 only if necessary. BEG and END default to the buffer
19633 boundaries."
19634 (interactive "P")
19635 (when (display-graphic-p)
19636 (unless refresh
19637 (org-remove-inline-images)
19638 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19639 (org-with-wide-buffer
19640 (goto-char (or beg (point-min)))
19641 (let ((case-fold-search t)
19642 (file-extension-re (image-file-name-regexp)))
19643 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19644 (let ((link (save-match-data (org-element-context))))
19645 ;; Check if we're at an inline image.
19646 (when (and (equal (org-element-property :type link) "file")
19647 (or include-linked
19648 (not (org-element-property :contents-begin link)))
19649 (let ((parent (org-element-property :parent link)))
19650 (or (not (eq (org-element-type parent) 'link))
19651 (not (cdr (org-element-contents parent)))))
19652 (string-match-p file-extension-re
19653 (org-element-property :path link)))
19654 (let ((file (expand-file-name
19655 (org-link-unescape
19656 (org-element-property :path link)))))
19657 (when (file-exists-p file)
19658 (let ((width
19659 ;; Apply `org-image-actual-width' specifications.
19660 (cond
19661 ((not (image-type-available-p 'imagemagick)) nil)
19662 ((eq org-image-actual-width t) nil)
19663 ((listp org-image-actual-width)
19665 ;; First try to find a width among
19666 ;; attributes associated to the paragraph
19667 ;; containing link.
19668 (let ((paragraph
19669 (let ((e link))
19670 (while (and (setq e (org-element-property
19671 :parent e))
19672 (not (eq (org-element-type e)
19673 'paragraph))))
19674 e)))
19675 (when paragraph
19676 (save-excursion
19677 (goto-char (org-element-property :begin paragraph))
19678 (when
19679 (re-search-forward
19680 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19681 (org-element-property
19682 :post-affiliated paragraph)
19684 (string-to-number (match-string 1))))))
19685 ;; Otherwise, fall-back to provided number.
19686 (car org-image-actual-width)))
19687 ((numberp org-image-actual-width)
19688 org-image-actual-width)))
19689 (old (get-char-property-and-overlay
19690 (org-element-property :begin link)
19691 'org-image-overlay)))
19692 (if (and (car-safe old) refresh)
19693 (image-refresh (overlay-get (cdr old) 'display))
19694 (let ((image (create-image file
19695 (and width 'imagemagick)
19697 :width width)))
19698 (when image
19699 (let* ((link
19700 ;; If inline image is the description
19701 ;; of another link, be sure to
19702 ;; consider the latter as the one to
19703 ;; apply the overlay on.
19704 (let ((parent
19705 (org-element-property :parent link)))
19706 (if (eq (org-element-type parent) 'link)
19707 parent
19708 link)))
19709 (ov (make-overlay
19710 (org-element-property :begin link)
19711 (progn
19712 (goto-char
19713 (org-element-property :end link))
19714 (skip-chars-backward " \t")
19715 (point)))))
19716 (overlay-put ov 'display image)
19717 (overlay-put ov 'face 'default)
19718 (overlay-put ov 'org-image-overlay t)
19719 (overlay-put
19720 ov 'modification-hooks
19721 (list 'org-display-inline-remove-overlay))
19722 (push ov org-inline-image-overlays)))))))))))))))
19724 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19725 "Remove inline-display overlay if a corresponding region is modified."
19726 (let ((inhibit-modification-hooks t))
19727 (when (and ov after)
19728 (delete ov org-inline-image-overlays)
19729 (delete-overlay ov))))
19731 (defun org-remove-inline-images ()
19732 "Remove inline display of images."
19733 (interactive)
19734 (mapc #'delete-overlay org-inline-image-overlays)
19735 (setq org-inline-image-overlays nil))
19737 ;;;; Key bindings
19739 ;; Outline functions from `outline-mode-prefix-map'
19740 ;; that can be remapped in Org:
19741 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19742 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19743 (define-key org-mode-map [remap outline-forward-same-level]
19744 'org-forward-heading-same-level)
19745 (define-key org-mode-map [remap outline-backward-same-level]
19746 'org-backward-heading-same-level)
19747 (define-key org-mode-map [remap outline-show-branches]
19748 'org-kill-note-or-show-branches)
19749 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19750 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19751 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19752 (define-key org-mode-map [remap outline-next-visible-heading]
19753 'org-next-visible-heading)
19754 (define-key org-mode-map [remap outline-previous-visible-heading]
19755 'org-previous-visible-heading)
19756 (define-key org-mode-map [remap show-children] 'org-show-children)
19758 ;; Outline functions from `outline-mode-prefix-map' that can not
19759 ;; be remapped in Org:
19761 ;; - the column "key binding" shows whether the Outline function is still
19762 ;; available in Org mode on the same key that it has been bound to in
19763 ;; Outline mode:
19764 ;; - "overridden": key used for a different functionality in Org mode
19765 ;; - else: key still bound to the same Outline function in Org mode
19767 ;; | Outline function | key binding | Org replacement |
19768 ;; |------------------------------------+-------------+--------------------------|
19769 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19770 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19771 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19772 ;; | `show-entry' | overridden | no replacement |
19773 ;; | `show-branches' | `C-c C-k' | still same function |
19774 ;; | `show-subtree' | overridden | visibility cycling |
19775 ;; | `show-all' | overridden | no replacement |
19776 ;; | `hide-subtree' | overridden | visibility cycling |
19777 ;; | `hide-body' | overridden | no replacement |
19778 ;; | `hide-entry' | overridden | visibility cycling |
19779 ;; | `hide-leaves' | overridden | no replacement |
19780 ;; | `hide-sublevels' | overridden | no replacement |
19781 ;; | `hide-other' | overridden | no replacement |
19783 ;; Make `C-c C-x' a prefix key
19784 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19786 ;; TAB key with modifiers
19787 (org-defkey org-mode-map "\C-i" 'org-cycle)
19788 (org-defkey org-mode-map [(tab)] 'org-cycle)
19789 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19790 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19791 ;; The following line is necessary under Suse GNU/Linux
19792 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19793 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19794 (define-key org-mode-map [backtab] 'org-shifttab)
19796 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19797 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19798 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19800 ;; Cursor keys with modifiers
19801 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19802 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19803 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19804 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19806 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19807 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19808 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19809 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19810 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19811 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19813 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19814 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19815 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19816 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19818 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19819 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19820 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19821 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19823 ;; Babel keys
19824 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19825 (dolist (pair org-babel-key-bindings)
19826 (define-key org-babel-map (car pair) (cdr pair)))
19828 ;;; Extra keys for tty access.
19829 ;; We only set them when really needed because otherwise the
19830 ;; menus don't show the simple keys
19832 (when (or org-use-extra-keys (not window-system))
19833 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19834 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19835 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19836 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19837 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19838 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19839 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19840 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19841 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19842 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19843 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19844 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19845 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19846 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19847 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19848 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19849 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19850 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19851 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19852 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19853 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19854 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19855 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19856 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19857 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19858 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19859 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19860 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19862 ;; All the other keys
19864 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19865 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19866 (if (boundp 'narrow-map)
19867 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19868 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19869 (if (boundp 'narrow-map)
19870 (org-defkey narrow-map "b" 'org-narrow-to-block)
19871 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19872 (if (boundp 'narrow-map)
19873 (org-defkey narrow-map "e" 'org-narrow-to-element)
19874 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19875 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19876 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19877 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19878 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19879 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19880 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19881 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19882 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19883 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19884 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19885 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19886 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19887 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19888 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19889 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19890 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19891 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19892 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19893 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19894 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19895 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19896 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19897 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19898 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19899 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19900 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19901 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19902 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19903 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19904 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19905 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19906 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19907 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19908 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19909 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19910 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19911 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19912 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19913 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19914 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19915 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19916 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19917 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19918 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19919 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19920 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19921 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19922 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19923 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19924 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19925 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19926 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19927 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19928 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19929 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19930 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19931 (org-defkey org-mode-map "\C-c^" 'org-sort)
19932 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19933 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19934 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19935 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19936 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19937 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19938 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19939 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19940 (org-defkey org-mode-map "\C-m" 'org-return)
19941 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19942 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19943 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19944 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19945 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19946 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19947 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19948 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19949 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19950 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19951 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19952 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19953 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19954 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19955 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19956 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19957 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19958 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19959 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19960 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19961 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19962 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19963 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19964 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19965 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19967 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19968 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19969 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19971 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19972 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19973 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19974 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19975 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19976 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19977 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19978 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19979 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19980 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19981 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19982 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19983 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19984 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19985 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19986 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19987 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19988 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19989 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19990 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19991 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19992 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19994 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19995 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19996 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19997 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19998 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20000 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20002 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20004 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20005 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20007 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20010 (defconst org-speed-commands-default
20012 ("Outline Navigation")
20013 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20014 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20015 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20016 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20017 ("F" . org-next-block)
20018 ("B" . org-previous-block)
20019 ("u" . (org-speed-move-safe 'outline-up-heading))
20020 ("j" . org-goto)
20021 ("g" . (org-refile t))
20022 ("Outline Visibility")
20023 ("c" . org-cycle)
20024 ("C" . org-shifttab)
20025 (" " . org-display-outline-path)
20026 ("s" . org-narrow-to-subtree)
20027 ("=" . org-columns)
20028 ("Outline Structure Editing")
20029 ("U" . org-metaup)
20030 ("D" . org-metadown)
20031 ("r" . org-metaright)
20032 ("l" . org-metaleft)
20033 ("R" . org-shiftmetaright)
20034 ("L" . org-shiftmetaleft)
20035 ("i" . (progn (forward-char 1) (call-interactively
20036 'org-insert-heading-respect-content)))
20037 ("^" . org-sort)
20038 ("w" . org-refile)
20039 ("a" . org-archive-subtree-default-with-confirmation)
20040 ("@" . org-mark-subtree)
20041 ("#" . org-toggle-comment)
20042 ("Clock Commands")
20043 ("I" . org-clock-in)
20044 ("O" . org-clock-out)
20045 ("Meta Data Editing")
20046 ("t" . org-todo)
20047 ("," . (org-priority))
20048 ("0" . (org-priority ?\ ))
20049 ("1" . (org-priority ?A))
20050 ("2" . (org-priority ?B))
20051 ("3" . (org-priority ?C))
20052 (":" . org-set-tags-command)
20053 ("e" . org-set-effort)
20054 ("E" . org-inc-effort)
20055 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20056 (org-entry-put (point) "APPT_WARNTIME" m)))
20057 ("Agenda Views etc")
20058 ("v" . org-agenda)
20059 ("/" . org-sparse-tree)
20060 ("Misc")
20061 ("o" . org-open-at-point)
20062 ("?" . org-speed-command-help)
20063 ("<" . (org-agenda-set-restriction-lock 'subtree))
20064 (">" . (org-agenda-remove-restriction-lock))
20066 "The default speed commands.")
20068 (defun org-print-speed-command (e)
20069 (if (> (length (car e)) 1)
20070 (progn
20071 (princ "\n")
20072 (princ (car e))
20073 (princ "\n")
20074 (princ (make-string (length (car e)) ?-))
20075 (princ "\n"))
20076 (princ (car e))
20077 (princ " ")
20078 (if (symbolp (cdr e))
20079 (princ (symbol-name (cdr e)))
20080 (prin1 (cdr e)))
20081 (princ "\n")))
20083 (defun org-speed-command-help ()
20084 "Show the available speed commands."
20085 (interactive)
20086 (if (not org-use-speed-commands)
20087 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20088 (with-output-to-temp-buffer "*Help*"
20089 (princ "User-defined Speed commands\n===========================\n")
20090 (mapc #'org-print-speed-command org-speed-commands-user)
20091 (princ "\n")
20092 (princ "Built-in Speed commands\n=======================\n")
20093 (mapc #'org-print-speed-command org-speed-commands-default))
20094 (with-current-buffer "*Help*"
20095 (setq truncate-lines t))))
20097 (defun org-speed-move-safe (cmd)
20098 "Execute CMD, but make sure that the cursor always ends up in a headline.
20099 If not, return to the original position and throw an error."
20100 (interactive)
20101 (let ((pos (point)))
20102 (call-interactively cmd)
20103 (unless (and (bolp) (org-at-heading-p))
20104 (goto-char pos)
20105 (error "Boundary reached while executing %s" cmd))))
20107 (defvar org-self-insert-command-undo-counter 0)
20109 (defvar org-table-auto-blank-field) ; defined in org-table.el
20110 (defvar org-speed-command nil)
20112 (defun org-speed-command-activate (keys)
20113 "Hook for activating single-letter speed commands.
20114 `org-speed-commands-default' specifies a minimal command set.
20115 Use `org-speed-commands-user' for further customization."
20116 (when (or (and (bolp) (looking-at org-outline-regexp))
20117 (and (functionp org-use-speed-commands)
20118 (funcall org-use-speed-commands)))
20119 (cdr (assoc keys (append org-speed-commands-user
20120 org-speed-commands-default)))))
20122 (defun org-babel-speed-command-activate (keys)
20123 "Hook for activating single-letter code block commands."
20124 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20125 (cdr (assoc keys org-babel-key-bindings))))
20127 (defcustom org-speed-command-hook
20128 '(org-speed-command-default-hook org-babel-speed-command-hook)
20129 "Hook for activating speed commands at strategic locations.
20130 Hook functions are called in sequence until a valid handler is
20131 found.
20133 Each hook takes a single argument, a user-pressed command key
20134 which is also a `self-insert-command' from the global map.
20136 Within the hook, examine the cursor position and the command key
20137 and return nil or a valid handler as appropriate. Handler could
20138 be one of an interactive command, a function, or a form.
20140 Set `org-use-speed-commands' to non-nil value to enable this
20141 hook. The default setting is `org-speed-command-activate'."
20142 :group 'org-structure
20143 :version "24.1"
20144 :type 'hook)
20146 (defun org-self-insert-command (N)
20147 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20148 If the cursor is in a table looking at whitespace, the whitespace is
20149 overwritten, and the table is not marked as requiring realignment."
20150 (interactive "p")
20151 (org-check-before-invisible-edit 'insert)
20152 (cond
20153 ((and org-use-speed-commands
20154 (let ((kv (this-command-keys-vector)))
20155 (setq org-speed-command
20156 (run-hook-with-args-until-success
20157 'org-speed-command-hook
20158 (make-string 1 (aref kv (1- (length kv))))))))
20159 (cond
20160 ((commandp org-speed-command)
20161 (setq this-command org-speed-command)
20162 (call-interactively org-speed-command))
20163 ((functionp org-speed-command)
20164 (funcall org-speed-command))
20165 ((and org-speed-command (listp org-speed-command))
20166 (eval org-speed-command))
20167 (t (let (org-use-speed-commands)
20168 (call-interactively 'org-self-insert-command)))))
20169 ((and
20170 (org-at-table-p)
20171 (progn
20172 ;; Check if we blank the field, and if that triggers align.
20173 (and (featurep 'org-table) org-table-auto-blank-field
20174 (memq last-command
20175 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20176 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20177 ;; Got extra space, this field does not determine
20178 ;; column width.
20179 (let (org-table-may-need-update) (org-table-blank-field))
20180 ;; No extra space, this field may determine column
20181 ;; width.
20182 (org-table-blank-field)))
20184 (eq N 1)
20185 (looking-at "[^|\n]* \\( \\)|"))
20186 ;; There is room for insertion without re-aligning the table.
20187 (delete-region (match-beginning 1) (match-end 1))
20188 (self-insert-command N))
20190 (setq org-table-may-need-update t)
20191 (self-insert-command N)
20192 (org-fix-tags-on-the-fly)
20193 (when org-self-insert-cluster-for-undo
20194 (if (not (eq last-command 'org-self-insert-command))
20195 (setq org-self-insert-command-undo-counter 1)
20196 (if (>= org-self-insert-command-undo-counter 20)
20197 (setq org-self-insert-command-undo-counter 1)
20198 (and (> org-self-insert-command-undo-counter 0)
20199 buffer-undo-list (listp buffer-undo-list)
20200 (not (cadr buffer-undo-list)) ; remove nil entry
20201 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20202 (setq org-self-insert-command-undo-counter
20203 (1+ org-self-insert-command-undo-counter))))))))
20205 (defun org-check-before-invisible-edit (kind)
20206 "Check is editing if kind KIND would be dangerous with invisible text around.
20207 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20208 ;; First, try to get out of here as quickly as possible, to reduce overhead
20209 (when (and org-catch-invisible-edits
20210 (or (not (boundp 'visible-mode)) (not visible-mode))
20211 (or (get-char-property (point) 'invisible)
20212 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20213 ;; OK, we need to take a closer look
20214 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20215 (invisible-before-point (unless (bobp) (get-char-property
20216 (1- (point)) 'invisible)))
20217 (border-and-ok-direction
20219 ;; Check if we are acting predictably before invisible text
20220 (and invisible-at-point (not invisible-before-point)
20221 (memq kind '(insert delete-backward)))
20222 ;; Check if we are acting predictably after invisible text
20223 ;; This works not well, and I have turned it off. It seems
20224 ;; better to always show and stop after invisible text.
20225 ;; (and (not invisible-at-point) invisible-before-point
20226 ;; (memq kind '(insert delete)))
20228 (when (or (memq invisible-at-point '(outline org-hide-block t))
20229 (memq invisible-before-point '(outline org-hide-block t)))
20230 (when (eq org-catch-invisible-edits 'error)
20231 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20232 (if (and org-custom-properties-overlays
20233 (y-or-n-p "Display invisible properties in this buffer? "))
20234 (org-toggle-custom-properties-visibility)
20235 ;; Make the area visible
20236 (save-excursion
20237 (when invisible-before-point
20238 (goto-char (previous-single-char-property-change
20239 (point) 'invisible)))
20240 (outline-show-subtree))
20241 (cond
20242 ((eq org-catch-invisible-edits 'show)
20243 ;; That's it, we do the edit after showing
20244 (message
20245 "Unfolding invisible region around point before editing")
20246 (sit-for 1))
20247 ((and (eq org-catch-invisible-edits 'smart)
20248 border-and-ok-direction)
20249 (message "Unfolding invisible region around point before editing"))
20251 ;; Don't do the edit, make the user repeat it in full visibility
20252 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20254 (defun org-fix-tags-on-the-fly ()
20255 (when (and (equal (char-after (point-at-bol)) ?*)
20256 (org-at-heading-p))
20257 (org-align-tags-here org-tags-column)))
20259 (defun org-delete-backward-char (N)
20260 "Like `delete-backward-char', insert whitespace at field end in tables.
20261 When deleting backwards, in tables this function will insert whitespace in
20262 front of the next \"|\" separator, to keep the table aligned. The table will
20263 still be marked for re-alignment if the field did fill the entire column,
20264 because, in this case the deletion might narrow the column."
20265 (interactive "p")
20266 (save-match-data
20267 (org-check-before-invisible-edit 'delete-backward)
20268 (if (and (org-at-table-p)
20269 (eq N 1)
20270 (string-match "|" (buffer-substring (point-at-bol) (point)))
20271 (looking-at ".*?|"))
20272 (let ((pos (point))
20273 (noalign (looking-at "[^|\n\r]* |"))
20274 (c org-table-may-need-update))
20275 (backward-delete-char N)
20276 (unless overwrite-mode
20277 (skip-chars-forward "^|")
20278 (insert " ")
20279 (goto-char (1- pos)))
20280 ;; noalign: if there were two spaces at the end, this field
20281 ;; does not determine the width of the column.
20282 (when noalign (setq org-table-may-need-update c)))
20283 (backward-delete-char N)
20284 (org-fix-tags-on-the-fly))))
20286 (defun org-delete-char (N)
20287 "Like `delete-char', but insert whitespace at field end in tables.
20288 When deleting characters, in tables this function will insert whitespace in
20289 front of the next \"|\" separator, to keep the table aligned. The table will
20290 still be marked for re-alignment if the field did fill the entire column,
20291 because, in this case the deletion might narrow the column."
20292 (interactive "p")
20293 (save-match-data
20294 (org-check-before-invisible-edit 'delete)
20295 (if (and (org-at-table-p)
20296 (not (bolp))
20297 (not (= (char-after) ?|))
20298 (eq N 1))
20299 (if (looking-at ".*?|")
20300 (let ((pos (point))
20301 (noalign (looking-at "[^|\n\r]* |"))
20302 (c org-table-may-need-update))
20303 (replace-match
20304 (concat (substring (match-string 0) 1 -1) " |") nil t)
20305 (goto-char pos)
20306 ;; noalign: if there were two spaces at the end, this field
20307 ;; does not determine the width of the column.
20308 (when noalign (setq org-table-may-need-update c)))
20309 (delete-char N))
20310 (delete-char N)
20311 (org-fix-tags-on-the-fly))))
20313 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20314 (put 'org-self-insert-command 'delete-selection
20315 (lambda ()
20316 (not (run-hook-with-args-until-success
20317 'self-insert-uses-region-functions))))
20318 (put 'orgtbl-self-insert-command 'delete-selection
20319 (lambda ()
20320 (not (run-hook-with-args-until-success
20321 'self-insert-uses-region-functions))))
20322 (put 'org-delete-char 'delete-selection 'supersede)
20323 (put 'org-delete-backward-char 'delete-selection 'supersede)
20324 (put 'org-yank 'delete-selection 'yank)
20326 ;; Make `flyspell-mode' delay after some commands
20327 (put 'org-self-insert-command 'flyspell-delayed t)
20328 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20329 (put 'org-delete-char 'flyspell-delayed t)
20330 (put 'org-delete-backward-char 'flyspell-delayed t)
20332 ;; Make pabbrev-mode expand after Org mode commands
20333 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20334 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20336 (defun org-remap (map &rest commands)
20337 "In MAP, remap the functions given in COMMANDS.
20338 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20339 (let (new old)
20340 (while commands
20341 (setq old (pop commands) new (pop commands))
20342 (if (fboundp 'command-remapping)
20343 (org-defkey map (vector 'remap old) new)
20344 (substitute-key-definition old new map global-map)))))
20346 (defun org-transpose-words ()
20347 "Transpose words for Org.
20348 This uses the `org-mode-transpose-word-syntax-table' syntax
20349 table, which interprets characters in `org-emphasis-alist' as
20350 word constituents."
20351 (interactive)
20352 (with-syntax-table org-mode-transpose-word-syntax-table
20353 (call-interactively 'transpose-words)))
20354 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20356 (when (eq org-enable-table-editor 'optimized)
20357 ;; If the user wants maximum table support, we need to hijack
20358 ;; some standard editing functions
20359 (org-remap org-mode-map
20360 'self-insert-command 'org-self-insert-command
20361 'delete-char 'org-delete-char
20362 'delete-backward-char 'org-delete-backward-char)
20363 (org-defkey org-mode-map "|" 'org-force-self-insert))
20365 (defvar org-ctrl-c-ctrl-c-hook nil
20366 "Hook for functions attaching themselves to `C-c C-c'.
20368 This can be used to add additional functionality to the C-c C-c
20369 key which executes context-dependent commands. This hook is run
20370 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20371 run after the last test.
20373 Each function will be called with no arguments. The function
20374 must check if the context is appropriate for it to act. If yes,
20375 it should do its thing and then return a non-nil value. If the
20376 context is wrong, just do nothing and return nil.")
20378 (defvar org-ctrl-c-ctrl-c-final-hook nil
20379 "Hook for functions attaching themselves to `C-c C-c'.
20381 This can be used to add additional functionality to the C-c C-c
20382 key which executes context-dependent commands. This hook is run
20383 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20384 before the first test.
20386 Each function will be called with no arguments. The function
20387 must check if the context is appropriate for it to act. If yes,
20388 it should do its thing and then return a non-nil value. If the
20389 context is wrong, just do nothing and return nil.")
20391 (defvar org-tab-first-hook nil
20392 "Hook for functions to attach themselves to TAB.
20393 See `org-ctrl-c-ctrl-c-hook' for more information.
20394 This hook runs as the first action when TAB is pressed, even before
20395 `org-cycle' messes around with the `outline-regexp' to cater for
20396 inline tasks and plain list item folding.
20397 If any function in this hook returns t, any other actions that
20398 would have been caused by TAB (such as table field motion or visibility
20399 cycling) will not occur.")
20401 (defvar org-tab-after-check-for-table-hook nil
20402 "Hook for functions to attach themselves to TAB.
20403 See `org-ctrl-c-ctrl-c-hook' for more information.
20404 This hook runs after it has been established that the cursor is not in a
20405 table, but before checking if the cursor is in a headline or if global cycling
20406 should be done.
20407 If any function in this hook returns t, not other actions like visibility
20408 cycling will be done.")
20410 (defvar org-tab-after-check-for-cycling-hook nil
20411 "Hook for functions to attach themselves to TAB.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.
20413 This hook runs after it has been established that not table field motion and
20414 not visibility should be done because of current context. This is probably
20415 the place where a package like yasnippets can hook in.")
20417 (defvar org-tab-before-tab-emulation-hook nil
20418 "Hook for functions to attach themselves to TAB.
20419 See `org-ctrl-c-ctrl-c-hook' for more information.
20420 This hook runs after every other options for TAB have been exhausted, but
20421 before indentation and \t insertion takes place.")
20423 (defvar org-metaleft-hook nil
20424 "Hook for functions attaching themselves to `M-left'.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20426 (defvar org-metaright-hook nil
20427 "Hook for functions attaching themselves to `M-right'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-metaup-hook nil
20430 "Hook for functions attaching themselves to `M-up'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-metadown-hook nil
20433 "Hook for functions attaching themselves to `M-down'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftmetaleft-hook nil
20436 "Hook for functions attaching themselves to `M-S-left'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftmetaright-hook nil
20439 "Hook for functions attaching themselves to `M-S-right'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftmetaup-hook nil
20442 "Hook for functions attaching themselves to `M-S-up'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftmetadown-hook nil
20445 "Hook for functions attaching themselves to `M-S-down'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-metareturn-hook nil
20448 "Hook for functions attaching themselves to `M-RET'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-shiftup-hook nil
20451 "Hook for functions attaching themselves to `S-up'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftup-final-hook nil
20454 "Hook for functions attaching themselves to `S-up'.
20455 This one runs after all other options except shift-select have been excluded.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-shiftdown-hook nil
20458 "Hook for functions attaching themselves to `S-down'.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-shiftdown-final-hook nil
20461 "Hook for functions attaching themselves to `S-down'.
20462 This one runs after all other options except shift-select have been excluded.
20463 See `org-ctrl-c-ctrl-c-hook' for more information.")
20464 (defvar org-shiftleft-hook nil
20465 "Hook for functions attaching themselves to `S-left'.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.")
20467 (defvar org-shiftleft-final-hook nil
20468 "Hook for functions attaching themselves to `S-left'.
20469 This one runs after all other options except shift-select have been excluded.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-shiftright-hook nil
20472 "Hook for functions attaching themselves to `S-right'.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.")
20474 (defvar org-shiftright-final-hook nil
20475 "Hook for functions attaching themselves to `S-right'.
20476 This one runs after all other options except shift-select have been excluded.
20477 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defun org-modifier-cursor-error ()
20480 "Throw an error, a modified cursor command was applied in wrong context."
20481 (user-error "This command is active in special context like tables, headlines or items"))
20483 (defun org-shiftselect-error ()
20484 "Throw an error because Shift-Cursor command was applied in wrong context."
20485 (if (and (boundp 'shift-select-mode) shift-select-mode)
20486 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20487 (user-error "This command works only in special context like headlines or timestamps")))
20489 (defun org-call-for-shift-select (cmd)
20490 (let ((this-command-keys-shift-translated t))
20491 (call-interactively cmd)))
20493 (defun org-shifttab (&optional arg)
20494 "Global visibility cycling or move to previous table field.
20495 Call `org-table-previous-field' within a table.
20496 When ARG is nil, cycle globally through visibility states.
20497 When ARG is a numeric prefix, show contents of this level."
20498 (interactive "P")
20499 (cond
20500 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20501 ((integerp arg)
20502 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20503 (message "Content view to level: %d" arg)
20504 (org-content (prefix-numeric-value arg2))
20505 (org-cycle-show-empty-lines t)
20506 (setq org-cycle-global-status 'overview)))
20507 (t (call-interactively 'org-global-cycle))))
20509 (defun org-shiftmetaleft ()
20510 "Promote subtree or delete table column.
20511 Calls `org-promote-subtree', `org-outdent-item-tree', or
20512 `org-table-delete-column', depending on context. See the
20513 individual commands for more information."
20514 (interactive)
20515 (cond
20516 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20517 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20518 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20519 ((if (not (org-region-active-p)) (org-at-item-p)
20520 (save-excursion (goto-char (region-beginning))
20521 (org-at-item-p)))
20522 (call-interactively 'org-outdent-item-tree))
20523 (t (org-modifier-cursor-error))))
20525 (defun org-shiftmetaright ()
20526 "Demote subtree or insert table column.
20527 Calls `org-demote-subtree', `org-indent-item-tree', or
20528 `org-table-insert-column', depending on context. See the
20529 individual commands for more information."
20530 (interactive)
20531 (cond
20532 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20533 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20534 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20535 ((if (not (org-region-active-p)) (org-at-item-p)
20536 (save-excursion (goto-char (region-beginning))
20537 (org-at-item-p)))
20538 (call-interactively 'org-indent-item-tree))
20539 (t (org-modifier-cursor-error))))
20541 (defun org-shiftmetaup (&optional _arg)
20542 "Drag the line at point up.
20543 In a table, kill the current row.
20544 On a clock timestamp, update the value of the timestamp like `S-<up>'
20545 but also adjust the previous clocked item in the clock history.
20546 Everywhere else, drag the line at point up."
20547 (interactive "P")
20548 (cond
20549 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20550 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20551 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20552 (call-interactively 'org-timestamp-up)))
20553 (t (call-interactively 'org-drag-line-backward))))
20555 (defun org-shiftmetadown (&optional _arg)
20556 "Drag the line at point down.
20557 In a table, insert an empty row at the current line.
20558 On a clock timestamp, update the value of the timestamp like `S-<down>'
20559 but also adjust the previous clocked item in the clock history.
20560 Everywhere else, drag the line at point down."
20561 (interactive "P")
20562 (cond
20563 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20564 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20565 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20566 (call-interactively 'org-timestamp-down)))
20567 (t (call-interactively 'org-drag-line-forward))))
20569 (defsubst org-hidden-tree-error ()
20570 (user-error
20571 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20573 (defun org-metaleft (&optional _arg)
20574 "Promote heading, list item at point or move table column left.
20576 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20577 depending on context. With no specific context, calls the Emacs
20578 default `backward-word'. See the individual commands for more
20579 information.
20581 This function runs the hook `org-metaleft-hook' as a first step,
20582 and returns at first non-nil value."
20583 (interactive "P")
20584 (cond
20585 ((run-hook-with-args-until-success 'org-metaleft-hook))
20586 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20587 ((org-with-limited-levels
20588 (or (org-at-heading-p)
20589 (and (org-region-active-p)
20590 (save-excursion
20591 (goto-char (region-beginning))
20592 (org-at-heading-p)))))
20593 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20594 (call-interactively 'org-do-promote))
20595 ;; At an inline task.
20596 ((org-at-heading-p)
20597 (call-interactively 'org-inlinetask-promote))
20598 ((or (org-at-item-p)
20599 (and (org-region-active-p)
20600 (save-excursion
20601 (goto-char (region-beginning))
20602 (org-at-item-p))))
20603 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20604 (call-interactively 'org-outdent-item))
20605 (t (call-interactively 'backward-word))))
20607 (defun org-metaright (&optional _arg)
20608 "Demote heading, list item at point or move table column right.
20610 In front of a drawer or a block keyword, indent it correctly.
20612 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20613 `org-indnet-drawer' or `org-indent-block' depending on context.
20614 With no specific context, calls the Emacs default `forward-word'.
20615 See the individual commands for more information.
20617 This function runs the hook `org-metaright-hook' as a first step,
20618 and returns at first non-nil value."
20619 (interactive "P")
20620 (cond
20621 ((run-hook-with-args-until-success 'org-metaright-hook))
20622 ((org-at-table-p) (call-interactively 'org-table-move-column))
20623 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20624 ((org-at-block-p) (call-interactively 'org-indent-block))
20625 ((org-with-limited-levels
20626 (or (org-at-heading-p)
20627 (and (org-region-active-p)
20628 (save-excursion
20629 (goto-char (region-beginning))
20630 (org-at-heading-p)))))
20631 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20632 (call-interactively 'org-do-demote))
20633 ;; At an inline task.
20634 ((org-at-heading-p)
20635 (call-interactively 'org-inlinetask-demote))
20636 ((or (org-at-item-p)
20637 (and (org-region-active-p)
20638 (save-excursion
20639 (goto-char (region-beginning))
20640 (org-at-item-p))))
20641 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20642 (call-interactively 'org-indent-item))
20643 (t (call-interactively 'forward-word))))
20645 (defun org-check-for-hidden (what)
20646 "Check if there are hidden headlines/items in the current visual line.
20647 WHAT can be either `headlines' or `items'. If the current line is
20648 an outline or item heading and it has a folded subtree below it,
20649 this function returns t, nil otherwise."
20650 (let ((re (cond
20651 ((eq what 'headlines) org-outline-regexp-bol)
20652 ((eq what 'items) (org-item-beginning-re))
20653 (t (error "This should not happen"))))
20654 beg end)
20655 (save-excursion
20656 (catch 'exit
20657 (unless (org-region-active-p)
20658 (setq beg (point-at-bol))
20659 (beginning-of-line 2)
20660 (while (and (not (eobp)) ;; this is like `next-line'
20661 (get-char-property (1- (point)) 'invisible))
20662 (beginning-of-line 2))
20663 (setq end (point))
20664 (goto-char beg)
20665 (goto-char (point-at-eol))
20666 (setq end (max end (point)))
20667 (while (re-search-forward re end t)
20668 (when (get-char-property (match-beginning 0) 'invisible)
20669 (throw 'exit t))))
20670 nil))))
20672 (defun org-metaup (&optional _arg)
20673 "Move subtree up or move table row up.
20674 Calls `org-move-subtree-up' or `org-table-move-row' or
20675 `org-move-item-up', depending on context. See the individual commands
20676 for more information."
20677 (interactive "P")
20678 (cond
20679 ((run-hook-with-args-until-success 'org-metaup-hook))
20680 ((org-region-active-p)
20681 (let* ((a (min (region-beginning) (region-end)))
20682 (b (1- (max (region-beginning) (region-end))))
20683 (c (save-excursion (goto-char a)
20684 (move-beginning-of-line 0)))
20685 (d (save-excursion (goto-char a)
20686 (move-end-of-line 0) (point))))
20687 (transpose-regions a b c d)
20688 (goto-char c)))
20689 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20690 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20691 ((org-at-item-p) (call-interactively 'org-move-item-up))
20692 (t (org-drag-element-backward))))
20694 (defun org-metadown (&optional _arg)
20695 "Move subtree down or move table row down.
20696 Calls `org-move-subtree-down' or `org-table-move-row' or
20697 `org-move-item-down', depending on context. See the individual
20698 commands for more information."
20699 (interactive "P")
20700 (cond
20701 ((run-hook-with-args-until-success 'org-metadown-hook))
20702 ((org-region-active-p)
20703 (let* ((a (min (region-beginning) (region-end)))
20704 (b (max (region-beginning) (region-end)))
20705 (c (save-excursion (goto-char b)
20706 (move-beginning-of-line 1)))
20707 (d (save-excursion (goto-char b)
20708 (move-end-of-line 1) (1+ (point)))))
20709 (transpose-regions a b c d)
20710 (goto-char d)))
20711 ((org-at-table-p) (call-interactively 'org-table-move-row))
20712 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20713 ((org-at-item-p) (call-interactively 'org-move-item-down))
20714 (t (org-drag-element-forward))))
20716 (defun org-shiftup (&optional arg)
20717 "Increase item in timestamp or increase priority of current headline.
20718 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20719 depending on context. See the individual commands for more information."
20720 (interactive "P")
20721 (cond
20722 ((run-hook-with-args-until-success 'org-shiftup-hook))
20723 ((and org-support-shift-select (org-region-active-p))
20724 (org-call-for-shift-select 'previous-line))
20725 ((org-at-timestamp-p t)
20726 (call-interactively (if org-edit-timestamp-down-means-later
20727 'org-timestamp-down 'org-timestamp-up)))
20728 ((and (not (eq org-support-shift-select 'always))
20729 org-enable-priority-commands
20730 (org-at-heading-p))
20731 (call-interactively 'org-priority-up))
20732 ((and (not org-support-shift-select) (org-at-item-p))
20733 (call-interactively 'org-previous-item))
20734 ((org-clocktable-try-shift 'up arg))
20735 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20736 (org-support-shift-select
20737 (org-call-for-shift-select 'previous-line))
20738 (t (org-shiftselect-error))))
20740 (defun org-shiftdown (&optional arg)
20741 "Decrease item in timestamp or decrease priority of current headline.
20742 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20743 depending on context. See the individual commands for more information."
20744 (interactive "P")
20745 (cond
20746 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20747 ((and org-support-shift-select (org-region-active-p))
20748 (org-call-for-shift-select 'next-line))
20749 ((org-at-timestamp-p t)
20750 (call-interactively (if org-edit-timestamp-down-means-later
20751 'org-timestamp-up 'org-timestamp-down)))
20752 ((and (not (eq org-support-shift-select 'always))
20753 org-enable-priority-commands
20754 (org-at-heading-p))
20755 (call-interactively 'org-priority-down))
20756 ((and (not org-support-shift-select) (org-at-item-p))
20757 (call-interactively 'org-next-item))
20758 ((org-clocktable-try-shift 'down arg))
20759 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20760 (org-support-shift-select
20761 (org-call-for-shift-select 'next-line))
20762 (t (org-shiftselect-error))))
20764 (defun org-shiftright (&optional arg)
20765 "Cycle the thing at point or in the current line, depending on context.
20766 Depending on context, this does one of the following:
20768 - switch a timestamp at point one day into the future
20769 - on a headline, switch to the next TODO keyword.
20770 - on an item, switch entire list to the next bullet type
20771 - on a property line, switch to the next allowed value
20772 - on a clocktable definition line, move time block into the future"
20773 (interactive "P")
20774 (cond
20775 ((run-hook-with-args-until-success 'org-shiftright-hook))
20776 ((and org-support-shift-select (org-region-active-p))
20777 (org-call-for-shift-select 'forward-char))
20778 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20779 ((and (not (eq org-support-shift-select 'always))
20780 (org-at-heading-p))
20781 (let ((org-inhibit-logging
20782 (not org-treat-S-cursor-todo-selection-as-state-change))
20783 (org-inhibit-blocking
20784 (not org-treat-S-cursor-todo-selection-as-state-change)))
20785 (org-call-with-arg 'org-todo 'right)))
20786 ((or (and org-support-shift-select
20787 (not (eq org-support-shift-select 'always))
20788 (org-at-item-bullet-p))
20789 (and (not org-support-shift-select) (org-at-item-p)))
20790 (org-call-with-arg 'org-cycle-list-bullet nil))
20791 ((and (not (eq org-support-shift-select 'always))
20792 (org-at-property-p))
20793 (call-interactively 'org-property-next-allowed-value))
20794 ((org-clocktable-try-shift 'right arg))
20795 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20796 (org-support-shift-select
20797 (org-call-for-shift-select 'forward-char))
20798 (t (org-shiftselect-error))))
20800 (defun org-shiftleft (&optional arg)
20801 "Cycle the thing at point or in the current line, depending on context.
20802 Depending on context, this does one of the following:
20804 - switch a timestamp at point one day into the past
20805 - on a headline, switch to the previous TODO keyword.
20806 - on an item, switch entire list to the previous bullet type
20807 - on a property line, switch to the previous allowed value
20808 - on a clocktable definition line, move time block into the past"
20809 (interactive "P")
20810 (cond
20811 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20812 ((and org-support-shift-select (org-region-active-p))
20813 (org-call-for-shift-select 'backward-char))
20814 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20815 ((and (not (eq org-support-shift-select 'always))
20816 (org-at-heading-p))
20817 (let ((org-inhibit-logging
20818 (not org-treat-S-cursor-todo-selection-as-state-change))
20819 (org-inhibit-blocking
20820 (not org-treat-S-cursor-todo-selection-as-state-change)))
20821 (org-call-with-arg 'org-todo 'left)))
20822 ((or (and org-support-shift-select
20823 (not (eq org-support-shift-select 'always))
20824 (org-at-item-bullet-p))
20825 (and (not org-support-shift-select) (org-at-item-p)))
20826 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20827 ((and (not (eq org-support-shift-select 'always))
20828 (org-at-property-p))
20829 (call-interactively 'org-property-previous-allowed-value))
20830 ((org-clocktable-try-shift 'left arg))
20831 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20832 (org-support-shift-select
20833 (org-call-for-shift-select 'backward-char))
20834 (t (org-shiftselect-error))))
20836 (defun org-shiftcontrolright ()
20837 "Switch to next TODO set."
20838 (interactive)
20839 (cond
20840 ((and org-support-shift-select (org-region-active-p))
20841 (org-call-for-shift-select 'forward-word))
20842 ((and (not (eq org-support-shift-select 'always))
20843 (org-at-heading-p))
20844 (org-call-with-arg 'org-todo 'nextset))
20845 (org-support-shift-select
20846 (org-call-for-shift-select 'forward-word))
20847 (t (org-shiftselect-error))))
20849 (defun org-shiftcontrolleft ()
20850 "Switch to previous TODO set."
20851 (interactive)
20852 (cond
20853 ((and org-support-shift-select (org-region-active-p))
20854 (org-call-for-shift-select 'backward-word))
20855 ((and (not (eq org-support-shift-select 'always))
20856 (org-at-heading-p))
20857 (org-call-with-arg 'org-todo 'previousset))
20858 (org-support-shift-select
20859 (org-call-for-shift-select 'backward-word))
20860 (t (org-shiftselect-error))))
20862 (defun org-shiftcontrolup (&optional n)
20863 "Change timestamps synchronously up in CLOCK log lines.
20864 Optional argument N tells to change by that many units."
20865 (interactive "P")
20866 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20867 (let (org-support-shift-select)
20868 (org-clock-timestamps-up n))
20869 (user-error "Not at a clock log")))
20871 (defun org-shiftcontroldown (&optional n)
20872 "Change timestamps synchronously down in CLOCK log lines.
20873 Optional argument N tells to change by that many units."
20874 (interactive "P")
20875 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20876 (let (org-support-shift-select)
20877 (org-clock-timestamps-down n))
20878 (user-error "Not at a clock log")))
20880 (defun org-increase-number-at-point (&optional inc)
20881 "Increment the number at point.
20882 With an optional prefix numeric argument INC, increment using
20883 this numeric value."
20884 (interactive "p")
20885 (if (not (number-at-point))
20886 (user-error "Not on a number")
20887 (unless inc (setq inc 1))
20888 (let ((pos (point))
20889 (beg (skip-chars-backward "-+^/*0-9eE."))
20890 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20891 (setq nap (buffer-substring-no-properties
20892 (+ pos beg) (+ pos beg end)))
20893 (delete-region (+ pos beg) (+ pos beg end))
20894 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20895 (when (org-at-table-p)
20896 (org-table-align)
20897 (org-table-end-of-field 1))))
20899 (defun org-decrease-number-at-point (&optional inc)
20900 "Decrement the number at point.
20901 With an optional prefix numeric argument INC, decrement using
20902 this numeric value."
20903 (interactive "p")
20904 (org-increase-number-at-point (- (or inc 1))))
20906 (defun org-ctrl-c-ret ()
20907 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20908 (interactive)
20909 (cond
20910 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20911 (t (call-interactively 'org-insert-heading))))
20913 (defun org-find-visible ()
20914 (let ((s (point)))
20915 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20916 (get-char-property s 'invisible)))
20918 (defun org-find-invisible ()
20919 (let ((s (point)))
20920 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20921 (not (get-char-property s 'invisible))))
20924 (defun org-copy-visible (beg end)
20925 "Copy the visible parts of the region."
20926 (interactive "r")
20927 (let (snippets s)
20928 (save-excursion
20929 (save-restriction
20930 (narrow-to-region beg end)
20931 (setq s (goto-char (point-min)))
20932 (while (not (= (point) (point-max)))
20933 (goto-char (org-find-invisible))
20934 (push (buffer-substring s (point)) snippets)
20935 (setq s (goto-char (org-find-visible))))))
20936 (kill-new (apply 'concat (nreverse snippets)))))
20938 (defun org-copy-special ()
20939 "Copy region in table or copy current subtree.
20940 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20941 See the individual commands for more information."
20942 (interactive)
20943 (call-interactively
20944 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20946 (defun org-cut-special ()
20947 "Cut region in table or cut current subtree.
20948 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20949 See the individual commands for more information."
20950 (interactive)
20951 (call-interactively
20952 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20954 (defun org-paste-special (arg)
20955 "Paste rectangular region into table, or past subtree relative to level.
20956 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20957 See the individual commands for more information."
20958 (interactive "P")
20959 (if (org-at-table-p)
20960 (org-table-paste-rectangle)
20961 (org-paste-subtree arg)))
20963 (defsubst org-in-fixed-width-region-p ()
20964 "Is point in a fixed-width region?"
20965 (save-match-data
20966 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20968 (defun org-edit-special (&optional arg)
20969 "Call a special editor for the element at point.
20970 When at a table, call the formula editor with `org-table-edit-formulas'.
20971 When in a source code block, call `org-edit-src-code'.
20972 When in a fixed-width region, call `org-edit-fixed-width-region'.
20973 When in an export block, call `org-edit-export-block'.
20974 When at an #+INCLUDE keyword, visit the included file.
20975 When at a footnote reference, call `org-edit-footnote-reference'
20976 On a link, call `ffap' to visit the link at point.
20977 Otherwise, return a user error."
20978 (interactive "P")
20979 (let ((element (org-element-at-point)))
20980 (cl-assert (not buffer-read-only) nil
20981 "Buffer is read-only: %s" (buffer-name))
20982 (pcase (org-element-type element)
20983 (`src-block
20984 (if (not arg) (org-edit-src-code)
20985 (let* ((info (org-babel-get-src-block-info))
20986 (lang (nth 0 info))
20987 (params (nth 2 info))
20988 (session (cdr (assq :session params))))
20989 (if (not session) (org-edit-src-code)
20990 ;; At a src-block with a session and function called with
20991 ;; an ARG: switch to the buffer related to the inferior
20992 ;; process.
20993 (switch-to-buffer
20994 (funcall (intern (concat "org-babel-prep-session:" lang))
20995 session params))))))
20996 (`keyword
20997 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20998 (org-open-link-from-string
20999 (format "[[%s]]"
21000 (expand-file-name
21001 (let ((value (org-element-property :value element)))
21002 (cond ((not (org-string-nw-p value))
21003 (user-error "No file to edit"))
21004 ((string-match "\\`\"\\(.*?\\)\"" value)
21005 (match-string 1 value))
21006 ((string-match "\\`[^ \t\"]\\S-*" value)
21007 (match-string 0 value))
21008 (t (user-error "No valid file specified")))))))
21009 (user-error "No special environment to edit here")))
21010 (`table
21011 (if (eq (org-element-property :type element) 'table.el)
21012 (org-edit-table.el)
21013 (call-interactively 'org-table-edit-formulas)))
21014 ;; Only Org tables contain `table-row' type elements.
21015 (`table-row (call-interactively 'org-table-edit-formulas))
21016 (`example-block (org-edit-src-code))
21017 (`export-block (org-edit-export-block))
21018 (`fixed-width (org-edit-fixed-width-region))
21020 ;; No notable element at point. Though, we may be at a link or
21021 ;; a footnote reference, which are objects. Thus, scan deeper.
21022 (let ((context (org-element-context element)))
21023 (pcase (org-element-type context)
21024 (`footnote-reference (org-edit-footnote-reference))
21025 (`inline-src-block (org-edit-inline-src-code))
21026 (`link (call-interactively #'ffap))
21027 (_ (user-error "No special environment to edit here"))))))))
21029 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21030 (defun org-ctrl-c-ctrl-c (&optional arg)
21031 "Set tags in headline, or update according to changed information at point.
21033 This command does many different things, depending on context:
21035 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21036 this is what we do.
21038 - If the cursor is on a statistics cookie, update it.
21040 - If the cursor is in a headline, prompt for tags and insert them
21041 into the current line, aligned to `org-tags-column'. When called
21042 with prefix arg, realign all tags in the current buffer.
21044 - If the cursor is in one of the special #+KEYWORD lines, this
21045 triggers scanning the buffer for these lines and updating the
21046 information.
21048 - If the cursor is inside a table, realign the table. This command
21049 works even if the automatic table editor has been turned off.
21051 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21052 the entire table.
21054 - If the cursor is at a footnote reference or definition, jump to
21055 the corresponding definition or references, respectively.
21057 - If the cursor is a the beginning of a dynamic block, update it.
21059 - If the current buffer is a capture buffer, close note and file it.
21061 - If the cursor is on a <<<target>>>, update radio targets and
21062 corresponding links in this buffer.
21064 - If the cursor is on a numbered item in a plain list, renumber the
21065 ordered list.
21067 - If the cursor is on a checkbox, toggle it.
21069 - If the cursor is on a code block, evaluate it. The variable
21070 `org-confirm-babel-evaluate' can be used to control prompting
21071 before code block evaluation, by default every code block
21072 evaluation requires confirmation. Code block evaluation can be
21073 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21074 (interactive "P")
21075 (cond
21076 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21077 org-occur-highlights)
21078 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21079 (org-remove-occur-highlights)
21080 (message "Temporary highlights/overlays removed from current buffer"))
21081 ((and (local-variable-p 'org-finish-function (current-buffer))
21082 (fboundp org-finish-function))
21083 (funcall org-finish-function))
21084 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21086 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21087 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21088 (user-error "C-c C-c can do nothing useful at this location"))
21089 (let* ((context (org-element-context))
21090 (type (org-element-type context)))
21091 (cl-case type
21092 ;; When at a link, act according to the parent instead.
21093 (link (setq context (org-element-property :parent context))
21094 (setq type (org-element-type context)))
21095 ;; Unsupported object types: refer to the first supported
21096 ;; element or object containing it.
21097 ((bold code entity export-snippet inline-babel-call inline-src-block
21098 italic latex-fragment line-break macro strike-through subscript
21099 superscript underline verbatim)
21100 (setq context
21101 (org-element-lineage
21102 context '(radio-target paragraph verse-block table-cell)))))
21103 ;; For convenience: at the first line of a paragraph on the
21104 ;; same line as an item, apply function on that item instead.
21105 (when (eq type 'paragraph)
21106 (let ((parent (org-element-property :parent context)))
21107 (when (and (eq (org-element-type parent) 'item)
21108 (= (line-beginning-position)
21109 (org-element-property :begin parent)))
21110 (setq context parent type 'item))))
21111 ;; Act according to type of element or object at point.
21112 (cl-case type
21113 (clock (org-clock-update-time-maybe))
21114 (dynamic-block
21115 (save-excursion
21116 (goto-char (org-element-property :post-affiliated context))
21117 (org-update-dblock)))
21118 (footnote-definition
21119 (goto-char (org-element-property :post-affiliated context))
21120 (call-interactively 'org-footnote-action))
21121 (footnote-reference (call-interactively 'org-footnote-action))
21122 ((headline inlinetask)
21123 (save-excursion (goto-char (org-element-property :begin context))
21124 (call-interactively 'org-set-tags)))
21125 (item
21126 ;; At an item: a double C-u set checkbox to "[-]"
21127 ;; unconditionally, whereas a single one will toggle its
21128 ;; presence. Without a universal argument, if the item
21129 ;; has a checkbox, toggle it. Otherwise repair the list.
21130 (let* ((box (org-element-property :checkbox context))
21131 (struct (org-element-property :structure context))
21132 (old-struct (copy-tree struct))
21133 (parents (org-list-parents-alist struct))
21134 (prevs (org-list-prevs-alist struct))
21135 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21136 (org-list-set-checkbox
21137 (org-element-property :begin context) struct
21138 (cond ((equal arg '(16)) "[-]")
21139 ((and (not box) (equal arg '(4))) "[ ]")
21140 ((or (not box) (equal arg '(4))) nil)
21141 ((eq box 'on) "[ ]")
21142 (t "[X]")))
21143 ;; Mimic `org-list-write-struct' but with grabbing
21144 ;; a return value from `org-list-struct-fix-box'.
21145 (org-list-struct-fix-ind struct parents 2)
21146 (org-list-struct-fix-item-end struct)
21147 (org-list-struct-fix-bul struct prevs)
21148 (org-list-struct-fix-ind struct parents)
21149 (let ((block-item
21150 (org-list-struct-fix-box struct parents prevs orderedp)))
21151 (if (and box (equal struct old-struct))
21152 (if (equal arg '(16))
21153 (message "Checkboxes already reset")
21154 (user-error "Cannot toggle this checkbox: %s"
21155 (if (eq box 'on)
21156 "all subitems checked"
21157 "unchecked subitems")))
21158 (org-list-struct-apply-struct struct old-struct)
21159 (org-update-checkbox-count-maybe))
21160 (when block-item
21161 (message "Checkboxes were removed due to empty box at line %d"
21162 (org-current-line block-item))))))
21163 (keyword
21164 (let ((org-inhibit-startup-visibility-stuff t)
21165 (org-startup-align-all-tables nil))
21166 (when (boundp 'org-table-coordinate-overlays)
21167 (mapc #'delete-overlay org-table-coordinate-overlays)
21168 (setq org-table-coordinate-overlays nil))
21169 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21170 (message "Local setup has been refreshed"))
21171 (plain-list
21172 ;; At a plain list, with a double C-u argument, set
21173 ;; checkboxes of each item to "[-]", whereas a single one
21174 ;; will toggle their presence according to the state of the
21175 ;; first item in the list. Without an argument, repair the
21176 ;; list.
21177 (let* ((begin (org-element-property :contents-begin context))
21178 (beginm (move-marker (make-marker) begin))
21179 (struct (org-element-property :structure context))
21180 (old-struct (copy-tree struct))
21181 (first-box (save-excursion
21182 (goto-char begin)
21183 (looking-at org-list-full-item-re)
21184 (match-string-no-properties 3)))
21185 (new-box (cond ((equal arg '(16)) "[-]")
21186 ((equal arg '(4)) (unless first-box "[ ]"))
21187 ((equal first-box "[X]") "[ ]")
21188 (t "[X]"))))
21189 (cond
21190 (arg
21191 (dolist (pos
21192 (org-list-get-all-items
21193 begin struct (org-list-prevs-alist struct)))
21194 (org-list-set-checkbox pos struct new-box)))
21195 ((and first-box (eq (point) begin))
21196 ;; For convenience, when point is at bol on the first
21197 ;; item of the list and no argument is provided, simply
21198 ;; toggle checkbox of that item, if any.
21199 (org-list-set-checkbox begin struct new-box)))
21200 (org-list-write-struct
21201 struct (org-list-parents-alist struct) old-struct)
21202 (org-update-checkbox-count-maybe)
21203 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21204 ((property-drawer node-property)
21205 (call-interactively 'org-property-action))
21206 ((radio-target target)
21207 (call-interactively 'org-update-radio-target-regexp))
21208 (statistics-cookie
21209 (call-interactively 'org-update-statistics-cookies))
21210 ((table table-cell table-row)
21211 ;; At a table, recalculate every field and align it. Also
21212 ;; send the table if necessary. If the table has
21213 ;; a `table.el' type, just give up. At a table row or
21214 ;; cell, maybe recalculate line but always align table.
21215 (if (eq (org-element-property :type context) 'table.el)
21216 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21217 Use \\[org-edit-special] to edit table.el tables"))
21218 (let ((org-enable-table-editor t))
21219 (if (or (eq type 'table)
21220 ;; Check if point is at a TBLFM line.
21221 (and (eq type 'table-row)
21222 (= (point) (org-element-property :end context))))
21223 (save-excursion
21224 (if (org-at-TBLFM-p)
21225 (progn (require 'org-table)
21226 (org-table-calc-current-TBLFM))
21227 (goto-char (org-element-property :contents-begin context))
21228 (org-call-with-arg 'org-table-recalculate (or arg t))
21229 (orgtbl-send-table 'maybe)))
21230 (org-table-maybe-eval-formula)
21231 (cond (arg (call-interactively 'org-table-recalculate))
21232 ((org-table-maybe-recalculate-line))
21233 (t (org-table-align)))))))
21234 (timestamp (org-timestamp-change 0 'day))
21235 (otherwise
21236 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21237 (user-error
21238 "C-c C-c can do nothing useful at this location")))))))))
21240 (defun org-mode-restart ()
21241 (interactive)
21242 (let ((indent-status (bound-and-true-p org-indent-mode)))
21243 (funcall major-mode)
21244 (hack-local-variables)
21245 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21246 (org-indent-mode -1)))
21247 (message "%s restarted" major-mode))
21249 (defun org-kill-note-or-show-branches ()
21250 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21251 (interactive)
21252 (if (not org-finish-function)
21253 (progn
21254 (outline-hide-subtree)
21255 (call-interactively 'outline-show-branches))
21256 (let ((org-note-abort t))
21257 (funcall org-finish-function))))
21259 (defun org-delete-indentation (&optional ARG)
21260 "Join current line to previous and fix whitespace at join.
21262 If previous line is a headline add to headline title. Otherwise
21263 the function calls `delete-indentation'.
21265 With argument, join this line to following line."
21266 (interactive "*P")
21267 (if (save-excursion
21268 (if ARG (beginning-of-line)
21269 (forward-line -1))
21270 (looking-at org-complex-heading-regexp))
21271 ;; At headline.
21272 (let ((tags-column (when (match-beginning 5)
21273 (save-excursion (goto-char (match-beginning 5))
21274 (current-column))))
21275 (string (concat " " (progn (when ARG (forward-line 1))
21276 (org-trim (delete-and-extract-region
21277 (line-beginning-position)
21278 (line-end-position)))))))
21279 (unless (bobp) (delete-region (point) (1- (point))))
21280 (goto-char (or (match-end 4)
21281 (match-beginning 5)
21282 (match-end 0)))
21283 (skip-chars-backward " \t")
21284 (save-excursion (insert string))
21285 ;; Adjust alignment of tags.
21286 (when tags-column
21287 (org-align-tags-here (if org-auto-align-tags
21288 org-tags-column
21289 tags-column))))
21290 (delete-indentation ARG)))
21292 (defun org-open-line (n)
21293 "Insert a new row in tables, call `open-line' elsewhere.
21294 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21295 (interactive "*p")
21296 (cond
21297 ((not org-special-ctrl-o)
21298 (open-line n))
21299 ((org-at-table-p)
21300 (org-table-insert-row))
21302 (open-line n))))
21304 (defun org-return (&optional indent)
21305 "Goto next table row or insert a newline.
21307 Calls `org-table-next-row' or `newline', depending on context.
21309 When optional INDENT argument is non-nil, call
21310 `newline-and-indent' instead of `newline'.
21312 When `org-return-follows-link' is non-nil and point is on
21313 a timestamp or a link, call `org-open-at-point'. However, it
21314 will not happen if point is in a table or on a \"dead\"
21315 object (e.g., within a comment). In these case, you need to use
21316 `org-open-at-point' directly."
21317 (interactive)
21318 (let ((context (if org-return-follows-link (org-element-context)
21319 (org-element-at-point))))
21320 (cond
21321 ;; In a table, call `org-table-next-row'.
21322 ((or (and (eq (org-element-type context) 'table)
21323 (>= (point) (org-element-property :contents-begin context))
21324 (< (point) (org-element-property :contents-end context)))
21325 (org-element-lineage context '(table-row table-cell) t))
21326 (org-table-justify-field-maybe)
21327 (call-interactively #'org-table-next-row))
21328 ;; On a link or a timestamp, call `org-open-at-point' if
21329 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21330 ;; locations, e.g., in a comment, as `org-open-at-point'.
21331 ((and org-return-follows-link
21332 (or (org-in-regexp org-ts-regexp-both nil t)
21333 (org-in-regexp org-tsr-regexp-both nil t)
21334 (org-in-regexp org-any-link-re nil t)))
21335 (call-interactively #'org-open-at-point))
21336 ;; Insert newline in heading, but preserve tags.
21337 ((and (not (bolp))
21338 (save-excursion (beginning-of-line)
21339 (looking-at org-complex-heading-regexp)))
21340 ;; At headline. Split line. However, if point is on keyword,
21341 ;; priority cookie or tags, do not break any of them: add
21342 ;; a newline after the headline instead.
21343 (let ((tags-column (and (match-beginning 5)
21344 (save-excursion (goto-char (match-beginning 5))
21345 (current-column))))
21346 (string
21347 (when (and (match-end 4)
21348 (>= (point)
21349 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21350 (<= (point) (match-end 4)))
21351 (delete-and-extract-region (point) (match-end 4)))))
21352 (when (and tags-column string) ; Adjust tag alignment.
21353 (org-align-tags-here
21354 (if org-auto-align-tags org-tags-column tags-column)))
21355 (end-of-line)
21356 (org-show-entry)
21357 (if indent (newline-and-indent) (newline))
21358 (when string (save-excursion (insert (org-trim string))))))
21359 ;; In a list, make sure indenting keeps trailing text within.
21360 ((and indent
21361 (not (eolp))
21362 (org-element-lineage context '(item)))
21363 (let ((trailing-data
21364 (delete-and-extract-region (point) (line-end-position))))
21365 (newline-and-indent)
21366 (save-excursion (insert trailing-data))))
21367 (t (if indent (newline-and-indent) (newline))))))
21369 (defun org-return-indent ()
21370 "Goto next table row or insert a newline and indent.
21371 Calls `org-table-next-row' or `newline-and-indent', depending on
21372 context. See the individual commands for more information."
21373 (interactive)
21374 (org-return t))
21376 (defun org-ctrl-c-star ()
21377 "Compute table, or change heading status of lines.
21378 Calls `org-table-recalculate' or `org-toggle-heading',
21379 depending on context."
21380 (interactive)
21381 (cond
21382 ((org-at-table-p)
21383 (call-interactively 'org-table-recalculate))
21385 ;; Convert all lines in region to list items
21386 (call-interactively 'org-toggle-heading))))
21388 (defun org-ctrl-c-minus ()
21389 "Insert separator line in table or modify bullet status of line.
21390 Also turns a plain line or a region of lines into list items.
21391 Calls `org-table-insert-hline', `org-toggle-item', or
21392 `org-cycle-list-bullet', depending on context."
21393 (interactive)
21394 (cond
21395 ((org-at-table-p)
21396 (call-interactively 'org-table-insert-hline))
21397 ((org-region-active-p)
21398 (call-interactively 'org-toggle-item))
21399 ((org-in-item-p)
21400 (call-interactively 'org-cycle-list-bullet))
21402 (call-interactively 'org-toggle-item))))
21404 (defun org-toggle-heading (&optional nstars)
21405 "Convert headings to normal text, or items or text to headings.
21406 If there is no active region, only convert the current line.
21408 With a \\[universal-argument] prefix, convert the whole list at
21409 point into heading.
21411 In a region:
21413 - If the first non blank line is a headline, remove the stars
21414 from all headlines in the region.
21416 - If it is a normal line, turn each and every normal line (i.e.,
21417 not an heading or an item) in the region into headings. If you
21418 want to convert only the first line of this region, use one
21419 universal prefix argument.
21421 - If it is a plain list item, turn all plain list items into headings.
21423 When converting a line into a heading, the number of stars is chosen
21424 such that the lines become children of the current entry. However,
21425 when a numeric prefix argument is given, its value determines the
21426 number of stars to add."
21427 (interactive "P")
21428 (let ((skip-blanks
21429 (function
21430 ;; Return beginning of first non-blank line, starting from
21431 ;; line at POS.
21432 (lambda (pos)
21433 (save-excursion
21434 (goto-char pos)
21435 (while (org-at-comment-p) (forward-line))
21436 (skip-chars-forward " \r\t\n")
21437 (point-at-bol)))))
21438 beg end toggled)
21439 ;; Determine boundaries of changes. If a universal prefix has
21440 ;; been given, put the list in a region. If region ends at a bol,
21441 ;; do not consider the last line to be in the region.
21443 (when (and current-prefix-arg (org-at-item-p))
21444 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21445 (org-mark-element))
21447 (if (org-region-active-p)
21448 (setq beg (funcall skip-blanks (region-beginning))
21449 end (copy-marker (save-excursion
21450 (goto-char (region-end))
21451 (if (bolp) (point) (point-at-eol)))))
21452 (setq beg (funcall skip-blanks (point-at-bol))
21453 end (copy-marker (point-at-eol))))
21454 ;; Ensure inline tasks don't count as headings.
21455 (org-with-limited-levels
21456 (save-excursion
21457 (goto-char beg)
21458 (cond
21459 ;; Case 1. Started at an heading: de-star headings.
21460 ((org-at-heading-p)
21461 (while (< (point) end)
21462 (when (org-at-heading-p t)
21463 (looking-at org-outline-regexp) (replace-match "")
21464 (setq toggled t))
21465 (forward-line)))
21466 ;; Case 2. Started at an item: change items into headlines.
21467 ;; One star will be added by `org-list-to-subtree'.
21468 ((org-at-item-p)
21469 (while (< (point) end)
21470 (when (org-at-item-p)
21471 ;; Pay attention to cases when region ends before list.
21472 (let* ((struct (org-list-struct))
21473 (list-end
21474 (min (org-list-get-bottom-point struct) (1+ end))))
21475 (save-restriction
21476 (narrow-to-region (point) list-end)
21477 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21478 (setq toggled t))
21479 (forward-line)))
21480 ;; Case 3. Started at normal text: make every line an heading,
21481 ;; skipping headlines and items.
21482 (t (let* ((stars
21483 (make-string
21484 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21485 (add-stars
21486 (cond (nstars "") ; stars from prefix only
21487 ((equal stars "") "*") ; before first heading
21488 (org-odd-levels-only "**") ; inside heading, odd
21489 (t "*"))) ; inside heading, oddeven
21490 (rpl (concat stars add-stars " "))
21491 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21492 (while (< (point) (if (equal nstars '(4)) lend end))
21493 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21494 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21495 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21496 (forward-line)))))))
21497 (unless toggled (message "Cannot toggle heading from here"))))
21499 (defun org-meta-return (&optional _arg)
21500 "Insert a new heading or wrap a region in a table.
21501 Calls `org-insert-heading' or `org-table-wrap-region', depending
21502 on context. See the individual commands for more information."
21503 (interactive)
21504 (org-check-before-invisible-edit 'insert)
21505 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21506 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21507 #'org-insert-heading))))
21509 ;;; Menu entries
21511 (defsubst org-in-subtree-not-table-p ()
21512 "Are we in a subtree and not in a table?"
21513 (and (not (org-before-first-heading-p))
21514 (not (org-at-table-p))))
21516 ;; Define the Org mode menus
21517 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21518 '("Tbl"
21519 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21520 ["Next Field" org-cycle (org-at-table-p)]
21521 ["Previous Field" org-shifttab (org-at-table-p)]
21522 ["Next Row" org-return (org-at-table-p)]
21523 "--"
21524 ["Blank Field" org-table-blank-field (org-at-table-p)]
21525 ["Edit Field" org-table-edit-field (org-at-table-p)]
21526 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21527 "--"
21528 ("Column"
21529 ["Move Column Left" org-metaleft (org-at-table-p)]
21530 ["Move Column Right" org-metaright (org-at-table-p)]
21531 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21532 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21533 ("Row"
21534 ["Move Row Up" org-metaup (org-at-table-p)]
21535 ["Move Row Down" org-metadown (org-at-table-p)]
21536 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21537 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21538 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21539 "--"
21540 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21541 ("Rectangle"
21542 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21543 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21544 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21545 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21546 "--"
21547 ("Calculate"
21548 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21549 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21550 ["Edit Formulas" org-edit-special (org-at-table-p)]
21551 "--"
21552 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21553 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21554 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21555 "--"
21556 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21557 "--"
21558 ["Sum Column/Rectangle" org-table-sum
21559 (or (org-at-table-p) (org-region-active-p))]
21560 ["Which Column?" org-table-current-column (org-at-table-p)])
21561 ["Debug Formulas"
21562 org-table-toggle-formula-debugger
21563 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21564 ["Show Col/Row Numbers"
21565 org-table-toggle-coordinate-overlays
21566 :style toggle
21567 :selected (bound-and-true-p org-table-overlay-coordinates)]
21568 "--"
21569 ["Create" org-table-create (and (not (org-at-table-p))
21570 org-enable-table-editor)]
21571 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21572 ["Import from File" org-table-import (not (org-at-table-p))]
21573 ["Export to File" org-table-export (org-at-table-p)]
21574 "--"
21575 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21576 "--"
21577 ("Plot"
21578 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21579 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21581 (easy-menu-define org-org-menu org-mode-map "Org menu"
21582 '("Org"
21583 ("Show/Hide"
21584 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21585 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21586 ["Sparse Tree..." org-sparse-tree t]
21587 ["Reveal Context" org-reveal t]
21588 ["Show All" outline-show-all t]
21589 "--"
21590 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21591 "--"
21592 ["New Heading" org-insert-heading t]
21593 ("Navigate Headings"
21594 ["Up" outline-up-heading t]
21595 ["Next" outline-next-visible-heading t]
21596 ["Previous" outline-previous-visible-heading t]
21597 ["Next Same Level" outline-forward-same-level t]
21598 ["Previous Same Level" outline-backward-same-level t]
21599 "--"
21600 ["Jump" org-goto t])
21601 ("Edit Structure"
21602 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21603 "--"
21604 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21605 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21606 "--"
21607 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21608 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21609 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21610 "--"
21611 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21612 "--"
21613 ["Copy visible text" org-copy-visible t]
21614 "--"
21615 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21616 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21617 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21618 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21619 "--"
21620 ["Sort Region/Children" org-sort t]
21621 "--"
21622 ["Convert to odd levels" org-convert-to-odd-levels t]
21623 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21624 ("Editing"
21625 ["Emphasis..." org-emphasize t]
21626 ["Edit Source Example" org-edit-special t]
21627 "--"
21628 ["Footnote new/jump" org-footnote-action t]
21629 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21630 ("Archive"
21631 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21632 "--"
21633 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21634 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21635 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21637 "--"
21638 ("Hyperlinks"
21639 ["Store Link (Global)" org-store-link t]
21640 ["Find existing link to here" org-occur-link-in-agenda-files t]
21641 ["Insert Link" org-insert-link t]
21642 ["Follow Link" org-open-at-point t]
21643 "--"
21644 ["Next link" org-next-link t]
21645 ["Previous link" org-previous-link t]
21646 "--"
21647 ["Descriptive Links"
21648 org-toggle-link-display
21649 :style radio
21650 :selected org-descriptive-links
21652 ["Literal Links"
21653 org-toggle-link-display
21654 :style radio
21655 :selected (not org-descriptive-links)])
21656 "--"
21657 ("TODO Lists"
21658 ["TODO/DONE/-" org-todo t]
21659 ("Select keyword"
21660 ["Next keyword" org-shiftright (org-at-heading-p)]
21661 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21662 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21663 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21664 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21665 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21666 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21667 "--"
21668 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21669 :selected org-enforce-todo-dependencies :style toggle :active t]
21670 "Settings for tree at point"
21671 ["Do Children sequentially" org-toggle-ordered-property :style radio
21672 :selected (org-entry-get nil "ORDERED")
21673 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21674 ["Do Children parallel" org-toggle-ordered-property :style radio
21675 :selected (not (org-entry-get nil "ORDERED"))
21676 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21677 "--"
21678 ["Set Priority" org-priority t]
21679 ["Priority Up" org-shiftup t]
21680 ["Priority Down" org-shiftdown t]
21681 "--"
21682 ["Get news from all feeds" org-feed-update-all t]
21683 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21684 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21685 ("TAGS and Properties"
21686 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21687 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21688 "--"
21689 ["Set property" org-set-property (not (org-before-first-heading-p))]
21690 ["Column view of properties" org-columns t]
21691 ["Insert Column View DBlock" org-columns-insert-dblock t])
21692 ("Dates and Scheduling"
21693 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21694 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21695 ("Change Date"
21696 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21697 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21698 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21699 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21700 ["Compute Time Range" org-evaluate-time-range t]
21701 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21702 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21703 "--"
21704 ["Custom time format" org-toggle-time-stamp-overlays
21705 :style radio :selected org-display-custom-times]
21706 "--"
21707 ["Goto Calendar" org-goto-calendar t]
21708 ["Date from Calendar" org-date-from-calendar t]
21709 "--"
21710 ["Start/Restart Timer" org-timer-start t]
21711 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21712 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21713 ["Insert Timer String" org-timer t]
21714 ["Insert Timer Item" org-timer-item t])
21715 ("Logging work"
21716 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21717 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21718 ["Clock out" org-clock-out t]
21719 ["Clock cancel" org-clock-cancel t]
21720 "--"
21721 ["Mark as default task" org-clock-mark-default-task t]
21722 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21723 ["Goto running clock" org-clock-goto t]
21724 "--"
21725 ["Display times" org-clock-display t]
21726 ["Create clock table" org-clock-report t]
21727 "--"
21728 ["Record DONE time"
21729 (progn (setq org-log-done (not org-log-done))
21730 (message "Switching to %s will %s record a timestamp"
21731 (car org-done-keywords)
21732 (if org-log-done "automatically" "not")))
21733 :style toggle :selected org-log-done])
21734 "--"
21735 ["Agenda Command..." org-agenda t]
21736 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21737 ("File List for Agenda")
21738 ("Special views current file"
21739 ["TODO Tree" org-show-todo-tree t]
21740 ["Check Deadlines" org-check-deadlines t]
21741 ["Timeline" org-timeline t]
21742 ["Tags/Property tree" org-match-sparse-tree t])
21743 "--"
21744 ["Export/Publish..." org-export-dispatch t]
21745 ("LaTeX"
21746 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21747 :selected org-cdlatex-mode]
21748 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21749 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21750 ["Modify math symbol" org-cdlatex-math-modify
21751 (org-inside-LaTeX-fragment-p)]
21752 ["Insert citation" org-reftex-citation t])
21753 "--"
21754 ("MobileOrg"
21755 ["Push Files and Views" org-mobile-push t]
21756 ["Get Captured and Flagged" org-mobile-pull t]
21757 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21758 "--"
21759 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21760 "--"
21761 ("Documentation"
21762 ["Show Version" org-version t]
21763 ["Info Documentation" org-info t])
21764 ("Customize"
21765 ["Browse Org Group" org-customize t]
21766 "--"
21767 ["Expand This Menu" org-create-customize-menu
21768 (fboundp 'customize-menu-create)])
21769 ["Send bug report" org-submit-bug-report t]
21770 "--"
21771 ("Refresh/Reload"
21772 ["Refresh setup current buffer" org-mode-restart t]
21773 ["Reload Org (after update)" org-reload t]
21774 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21777 (defun org-info (&optional node)
21778 "Read documentation for Org in the info system.
21779 With optional NODE, go directly to that node."
21780 (interactive)
21781 (info (format "(org)%s" (or node ""))))
21783 ;;;###autoload
21784 (defun org-submit-bug-report ()
21785 "Submit a bug report on Org via mail.
21787 Don't hesitate to report any problems or inaccurate documentation.
21789 If you don't have setup sending mail from (X)Emacs, please copy the
21790 output buffer into your mail program, as it gives us important
21791 information about your Org version and configuration."
21792 (interactive)
21793 (require 'reporter)
21794 (defvar reporter-prompt-for-summary-p)
21795 (org-load-modules-maybe)
21796 (org-require-autoloaded-modules)
21797 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21798 (reporter-submit-bug-report
21799 "emacs-orgmode@gnu.org"
21800 (org-version nil 'full)
21801 (let (list)
21802 (save-window-excursion
21803 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21804 (delete-other-windows)
21805 (erase-buffer)
21806 (insert "You are about to submit a bug report to the Org mailing list.
21808 We would like to add your full Org and Outline configuration to the
21809 bug report. This greatly simplifies the work of the maintainer and
21810 other experts on the mailing list.
21812 HOWEVER, some variables you have customized may contain private
21813 information. The names of customers, colleagues, or friends, might
21814 appear in the form of file names, tags, todo states, or search strings.
21815 If you answer yes to the prompt, you might want to check and remove
21816 such private information before sending the email.")
21817 (add-text-properties (point-min) (point-max) '(face org-warning))
21818 (when (yes-or-no-p "Include your Org configuration ")
21819 (mapatoms
21820 (lambda (v)
21821 (and (boundp v)
21822 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21823 (or (and (symbol-value v)
21824 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21825 (and
21826 (get v 'custom-type) (get v 'standard-value)
21827 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21828 (push v list)))))
21829 (kill-buffer (get-buffer "*Warn about privacy*"))
21830 list))
21831 nil nil
21832 "Remember to cover the basics, that is, what you expected to happen and
21833 what in fact did happen. You don't know how to make a good report? See
21835 http://orgmode.org/manual/Feedback.html#Feedback
21837 Your bug report will be posted to the Org mailing list.
21838 ------------------------------------------------------------------------")
21839 (save-excursion
21840 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21841 (replace-match "\\1Bug: \\3 [\\2]")))))
21844 (defun org-install-agenda-files-menu ()
21845 (let ((bl (buffer-list)))
21846 (save-excursion
21847 (while bl
21848 (set-buffer (pop bl))
21849 (when (derived-mode-p 'org-mode) (setq bl nil)))
21850 (when (derived-mode-p 'org-mode)
21851 (easy-menu-change
21852 '("Org") "File List for Agenda"
21853 (append
21854 (list
21855 ["Edit File List" (org-edit-agenda-file-list) t]
21856 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21857 ["Remove Current File from List" org-remove-file t]
21858 ["Cycle through agenda files" org-cycle-agenda-files t]
21859 ["Occur in all agenda files" org-occur-in-agenda-files t]
21860 "--")
21861 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21863 ;;;; Documentation
21865 (defun org-require-autoloaded-modules ()
21866 (interactive)
21867 (mapc #'require
21868 '(org-agenda org-archive org-attach org-clock org-colview org-id
21869 org-table org-timer)))
21871 ;;;###autoload
21872 (defun org-reload (&optional uncompiled)
21873 "Reload all org lisp files.
21874 With prefix arg UNCOMPILED, load the uncompiled versions."
21875 (interactive "P")
21876 (require 'loadhist)
21877 (let* ((org-dir (org-find-library-dir "org"))
21878 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21879 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21880 (remove-re (format "\\`%s\\'"
21881 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21882 (feats (delete-dups
21883 (mapcar 'file-name-sans-extension
21884 (mapcar 'file-name-nondirectory
21885 (delq nil
21886 (mapcar 'feature-file
21887 features))))))
21888 (lfeat (append
21889 (sort
21890 (setq feats
21891 (delq nil (mapcar
21892 (lambda (f)
21893 (if (and (string-match feature-re f)
21894 (not (string-match remove-re f)))
21895 f nil))
21896 feats)))
21897 'string-lessp)
21898 (list "org-version" "org")))
21899 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21900 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21901 load-uncore load-misses)
21902 (setq load-misses
21903 (delq 't
21904 (mapcar (lambda (f)
21905 (or (org-load-noerror-mustsuffix (concat org-dir f))
21906 (and (string= org-dir contrib-dir)
21907 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21908 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21909 (add-to-list 'load-uncore f 'append)
21912 lfeat)))
21913 (when load-uncore
21914 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21915 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21916 (if load-misses
21917 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21918 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21919 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21921 ;;;###autoload
21922 (defun org-customize ()
21923 "Call the customize function with org as argument."
21924 (interactive)
21925 (org-load-modules-maybe)
21926 (org-require-autoloaded-modules)
21927 (customize-browse 'org))
21929 (defun org-create-customize-menu ()
21930 "Create a full customization menu for Org-mode, insert it into the menu."
21931 (interactive)
21932 (org-load-modules-maybe)
21933 (org-require-autoloaded-modules)
21934 (if (fboundp 'customize-menu-create)
21935 (progn
21936 (easy-menu-change
21937 '("Org") "Customize"
21938 `(["Browse Org group" org-customize t]
21939 "--"
21940 ,(customize-menu-create 'org)
21941 ["Set" Custom-set t]
21942 ["Save" Custom-save t]
21943 ["Reset to Current" Custom-reset-current t]
21944 ["Reset to Saved" Custom-reset-saved t]
21945 ["Reset to Standard Settings" Custom-reset-standard t]))
21946 (message "\"Org\"-menu now contains full customization menu"))
21947 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21949 ;;;; Miscellaneous stuff
21951 ;;; Generally useful functions
21953 (defun org-get-at-eol (property n)
21954 "Get text property PROPERTY at the end of line less N characters."
21955 (get-text-property (- (point-at-eol) n) property))
21957 (defun org-find-text-property-in-string (prop s)
21958 "Return the first non-nil value of property PROP in string S."
21959 (or (get-text-property 0 prop s)
21960 (get-text-property (or (next-single-property-change 0 prop s) 0)
21961 prop s)))
21963 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21964 "Display the given MESSAGE as a warning."
21965 (if (fboundp 'display-warning)
21966 (display-warning 'org message :warning)
21967 (let ((buf (get-buffer-create "*Org warnings*")))
21968 (with-current-buffer buf
21969 (goto-char (point-max))
21970 (insert "Warning (Org): " message)
21971 (unless (bolp)
21972 (newline)))
21973 (display-buffer buf)
21974 (sit-for 0))))
21976 (defun org-eval (form)
21977 "Eval FORM and return result."
21978 (condition-case error
21979 (eval form)
21980 (error (format "%%![Error: %s]" error))))
21982 (defun org-in-clocktable-p ()
21983 "Check if the cursor is in a clocktable."
21984 (let ((pos (point)) start)
21985 (save-excursion
21986 (end-of-line 1)
21987 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21988 (setq start (match-beginning 0))
21989 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21990 (>= (match-end 0) pos)
21991 start))))
21993 (defun org-in-verbatim-emphasis ()
21994 (save-match-data
21995 (and (org-in-regexp org-emph-re 2)
21996 (>= (point) (match-beginning 3))
21997 (<= (point) (match-end 4))
21998 (member (match-string 3) '("=" "~")))))
22000 (defun org-overlay-display (ovl text &optional face evap)
22001 "Make overlay OVL display TEXT with face FACE."
22002 (overlay-put ovl 'display text)
22003 (if face (overlay-put ovl 'face face))
22004 (if evap (overlay-put ovl 'evaporate t)))
22006 (defun org-overlay-before-string (ovl text &optional face evap)
22007 "Make overlay OVL display TEXT with face FACE."
22008 (if face (org-add-props text nil 'face face))
22009 (overlay-put ovl 'before-string text)
22010 (if evap (overlay-put ovl 'evaporate t)))
22012 (defun org-find-overlays (prop &optional pos delete)
22013 "Find all overlays specifying PROP at POS or point.
22014 If DELETE is non-nil, delete all those overlays."
22015 (let (found)
22016 (dolist (ov (overlays-at (or pos (point))) found)
22017 (cond ((not (overlay-get ov prop)))
22018 (delete (delete-overlay ov))
22019 (t (push ov found))))))
22021 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22022 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22023 (if (and marker (marker-buffer marker)
22024 (buffer-live-p (marker-buffer marker)))
22025 (progn
22026 (pop-to-buffer-same-window (marker-buffer marker))
22027 (when (or (> marker (point-max)) (< marker (point-min)))
22028 (widen))
22029 (goto-char marker)
22030 (org-show-context 'org-goto))
22031 (if bookmark
22032 (bookmark-jump bookmark)
22033 (error "Cannot find location"))))
22035 (defun org-quote-csv-field (s)
22036 "Quote field for inclusion in CSV material."
22037 (if (string-match "[\",]" s)
22038 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22041 (defun org-force-self-insert (N)
22042 "Needed to enforce self-insert under remapping."
22043 (interactive "p")
22044 (self-insert-command N))
22046 (defun org-string-width (s)
22047 "Compute width of string, ignoring invisible characters.
22048 This ignores character with invisibility property `org-link', and also
22049 characters with property `org-cwidth', because these will become invisible
22050 upon the next fontification round."
22051 (let (b l)
22052 (when (or (eq t buffer-invisibility-spec)
22053 (assq 'org-link buffer-invisibility-spec))
22054 (while (setq b (text-property-any 0 (length s)
22055 'invisible 'org-link s))
22056 (setq s (concat (substring s 0 b)
22057 (substring s (or (next-single-property-change
22058 b 'invisible s)
22059 (length s)))))))
22060 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22061 (setq s (concat (substring s 0 b)
22062 (substring s (or (next-single-property-change
22063 b 'org-cwidth s)
22064 (length s))))))
22065 (setq l (string-width s) b -1)
22066 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22067 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22070 (defun org-shorten-string (s maxlength)
22071 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22072 If the string is shorter or has length MAXLENGTH, just return the
22073 original string. If it is longer, the functions finds a space in the
22074 string, breaks this string off at that locations and adds three dots
22075 as ellipsis. Including the ellipsis, the string will not be longer
22076 than MAXLENGTH. If finding a good breaking point in the string does
22077 not work, the string is just chopped off in the middle of a word
22078 if necessary."
22079 (if (<= (length s) maxlength)
22081 (let* ((n (max (- maxlength 4) 1))
22082 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22083 (if (string-match re s)
22084 (concat (match-string 1 s) "...")
22085 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22087 (defun org-get-indentation (&optional line)
22088 "Get the indentation of the current line, interpreting tabs.
22089 When LINE is given, assume it represents a line and compute its indentation."
22090 (if line
22091 (when (string-match "^ *" (org-remove-tabs line))
22092 (match-end 0))
22093 (save-excursion
22094 (beginning-of-line 1)
22095 (skip-chars-forward " \t")
22096 (current-column))))
22098 (defun org-get-string-indentation (s)
22099 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22100 (let ((n -1) (i 0) (w tab-width) c)
22101 (catch 'exit
22102 (while (< (setq n (1+ n)) (length s))
22103 (setq c (aref s n))
22104 (cond ((= c ?\ ) (setq i (1+ i)))
22105 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22106 (t (throw 'exit t)))))
22109 (defun org-remove-tabs (s &optional width)
22110 "Replace tabulators in S with spaces.
22111 Assumes that s is a single line, starting in column 0."
22112 (setq width (or width tab-width))
22113 (while (string-match "\t" s)
22114 (setq s (replace-match
22115 (make-string
22116 (- (* width (/ (+ (match-beginning 0) width) width))
22117 (match-beginning 0)) ?\ )
22118 t t s)))
22121 (defun org-fix-indentation (line ind)
22122 "Fix indentation in LINE.
22123 IND is a cons cell with target and minimum indentation.
22124 If the current indentation in LINE is smaller than the minimum,
22125 leave it alone. If it is larger than ind, set it to the target."
22126 (let* ((l (org-remove-tabs line))
22127 (i (org-get-indentation l))
22128 (i1 (car ind)) (i2 (cdr ind)))
22129 (when (>= i i2) (setq l (substring line i2)))
22130 (if (> i1 0)
22131 (concat (make-string i1 ?\ ) l)
22132 l)))
22134 (defun org-remove-indentation (code &optional n)
22135 "Remove maximum common indentation in string CODE and return it.
22136 N may optionally be the number of columns to remove. Return CODE
22137 as-is if removal failed."
22138 (with-temp-buffer
22139 (insert code)
22140 (if (org-do-remove-indentation n) (buffer-string) code)))
22142 (defun org-do-remove-indentation (&optional n)
22143 "Remove the maximum common indentation from the buffer.
22144 When optional argument N is a positive integer, remove exactly
22145 that much characters from indentation, if possible. Return nil
22146 if it fails."
22147 (catch :exit
22148 (goto-char (point-min))
22149 ;; Find maximum common indentation, if not specified.
22150 (let ((n (or n
22151 (let ((min-ind (point-max)))
22152 (save-excursion
22153 (while (re-search-forward "^[ \t]*\\S-" nil t)
22154 (let ((ind (1- (current-column))))
22155 (if (zerop ind) (throw :exit nil)
22156 (setq min-ind (min min-ind ind))))))
22157 min-ind))))
22158 (if (zerop n) (throw :exit nil)
22159 ;; Remove exactly N indentation, but give up if not possible.
22160 (while (not (eobp))
22161 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22162 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22163 ((< ind n) (throw :exit nil))
22164 (t (indent-line-to (- ind n))))
22165 (forward-line)))
22166 ;; Signal success.
22167 t))))
22169 (defun org-fill-template (template alist)
22170 "Find each %key of ALIST in TEMPLATE and replace it."
22171 (let ((case-fold-search nil))
22172 (dolist (entry (sort (copy-sequence alist)
22173 (lambda (a b) (< (length (car a)) (length (car b))))))
22174 (setq template
22175 (replace-regexp-in-string
22176 (concat "%" (regexp-quote (car entry)))
22177 (or (cdr entry) "") template t t)))
22178 template))
22180 (defun org-base-buffer (buffer)
22181 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22182 (if (not buffer)
22183 buffer
22184 (or (buffer-base-buffer buffer)
22185 buffer)))
22187 (defun org-wrap (string &optional width lines)
22188 "Wrap string to either a number of lines, or a width in characters.
22189 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22190 that costs. If there is a word longer than WIDTH, the text is actually
22191 wrapped to the length of that word.
22192 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22193 many lines, whatever width that takes.
22194 The return value is a list of lines, without newlines at the end."
22195 (let* ((words (org-split-string string "[ \t\n]+"))
22196 (maxword (apply 'max (mapcar 'org-string-width words)))
22197 w ll)
22198 (cond (width
22199 (org-do-wrap words (max maxword width)))
22200 (lines
22201 (setq w maxword)
22202 (setq ll (org-do-wrap words maxword))
22203 (if (<= (length ll) lines)
22205 (setq ll words)
22206 (while (> (length ll) lines)
22207 (setq w (1+ w))
22208 (setq ll (org-do-wrap words w)))
22209 ll))
22210 (t (error "Cannot wrap this")))))
22212 (defun org-do-wrap (words width)
22213 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22214 (let (lines line)
22215 (while words
22216 (setq line (pop words))
22217 (while (and words (< (+ (length line) (length (car words))) width))
22218 (setq line (concat line " " (pop words))))
22219 (setq lines (push line lines)))
22220 (nreverse lines)))
22222 (defun org-split-string (string &optional separators)
22223 "Splits STRING into substrings at SEPARATORS.
22224 SEPARATORS is a regular expression.
22225 No empty strings are returned if there are matches at the beginning
22226 and end of string."
22227 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22228 (let ((start 0) notfirst list)
22229 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22230 (if (and notfirst
22231 (= start (match-beginning 0))
22232 (< start (length string)))
22233 (1+ start) start))
22234 (< (match-beginning 0) (length string)))
22235 (setq notfirst t)
22236 (or (eq (match-beginning 0) 0)
22237 (and (eq (match-beginning 0) (match-end 0))
22238 (eq (match-beginning 0) start))
22239 (push (substring string start (match-beginning 0)) list))
22240 (setq start (match-end 0)))
22241 (or (eq start (length string))
22242 (push (substring string start) list))
22243 (nreverse list)))
22245 (defun org-quote-vert (s)
22246 "Replace \"|\" with \"\\vert\"."
22247 (while (string-match "|" s)
22248 (setq s (replace-match "\\vert" t t s)))
22251 (defun org-uuidgen-p (s)
22252 "Is S an ID created by UUIDGEN?"
22253 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22255 (defun org-in-src-block-p (&optional inside)
22256 "Whether point is in a code source block.
22257 When INSIDE is non-nil, don't consider we are within a src block
22258 when point is at #+BEGIN_SRC or #+END_SRC."
22259 (let ((case-fold-search t))
22260 (or (and (eq (get-char-property (point) 'src-block) t))
22261 (and (not inside)
22262 (save-match-data
22263 (save-excursion
22264 (beginning-of-line)
22265 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22267 (defun org-context ()
22268 "Return a list of contexts of the current cursor position.
22269 If several contexts apply, all are returned.
22270 Each context entry is a list with a symbol naming the context, and
22271 two positions indicating start and end of the context. Possible
22272 contexts are:
22274 :headline anywhere in a headline
22275 :headline-stars on the leading stars in a headline
22276 :todo-keyword on a TODO keyword (including DONE) in a headline
22277 :tags on the TAGS in a headline
22278 :priority on the priority cookie in a headline
22279 :item on the first line of a plain list item
22280 :item-bullet on the bullet/number of a plain list item
22281 :checkbox on the checkbox in a plain list item
22282 :table in an Org table
22283 :table-special on a special filed in a table
22284 :table-table in a table.el table
22285 :clocktable in a clocktable
22286 :src-block in a source block
22287 :link on a hyperlink
22288 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22289 :target on a <<target>>
22290 :radio-target on a <<<radio-target>>>
22291 :latex-fragment on a LaTeX fragment
22292 :latex-preview on a LaTeX fragment with overlaid preview image
22294 This function expects the position to be visible because it uses font-lock
22295 faces as a help to recognize the following contexts: :table-special, :link,
22296 and :keyword."
22297 (let* ((f (get-text-property (point) 'face))
22298 (faces (if (listp f) f (list f)))
22299 (case-fold-search t)
22300 (p (point)) clist o)
22301 ;; First the large context
22302 (cond
22303 ((org-at-heading-p t)
22304 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22305 (when (progn
22306 (beginning-of-line 1)
22307 (looking-at org-todo-line-tags-regexp))
22308 (push (org-point-in-group p 1 :headline-stars) clist)
22309 (push (org-point-in-group p 2 :todo-keyword) clist)
22310 (push (org-point-in-group p 4 :tags) clist))
22311 (goto-char p)
22312 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22313 (when (looking-at "\\[#[A-Z0-9]\\]")
22314 (push (org-point-in-group p 0 :priority) clist)))
22316 ((org-at-item-p)
22317 (push (org-point-in-group p 2 :item-bullet) clist)
22318 (push (list :item (point-at-bol)
22319 (save-excursion (org-end-of-item) (point)))
22320 clist)
22321 (and (org-at-item-checkbox-p)
22322 (push (org-point-in-group p 0 :checkbox) clist)))
22324 ((org-at-table-p)
22325 (push (list :table (org-table-begin) (org-table-end)) clist)
22326 (when (memq 'org-formula faces)
22327 (push (list :table-special
22328 (previous-single-property-change p 'face)
22329 (next-single-property-change p 'face)) clist)))
22330 ((org-at-table-p 'any)
22331 (push (list :table-table) clist)))
22332 (goto-char p)
22334 (let ((case-fold-search t))
22335 ;; New the "medium" contexts: clocktables, source blocks
22336 (cond ((org-in-clocktable-p)
22337 (push (list :clocktable
22338 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22339 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22340 (match-beginning 1))
22341 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22342 (match-end 0))) clist))
22343 ((org-in-src-block-p)
22344 (push (list :src-block
22345 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22346 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22347 (match-beginning 1))
22348 (and (search-forward "#+END_SRC" nil t)
22349 (match-beginning 0))) clist))))
22350 (goto-char p)
22352 ;; Now the small context
22353 (cond
22354 ((org-at-timestamp-p)
22355 (push (org-point-in-group p 0 :timestamp) clist))
22356 ((memq 'org-link faces)
22357 (push (list :link
22358 (previous-single-property-change p 'face)
22359 (next-single-property-change p 'face)) clist))
22360 ((memq 'org-special-keyword faces)
22361 (push (list :keyword
22362 (previous-single-property-change p 'face)
22363 (next-single-property-change p 'face)) clist))
22364 ((org-at-target-p)
22365 (push (org-point-in-group p 0 :target) clist)
22366 (goto-char (1- (match-beginning 0)))
22367 (when (looking-at org-radio-target-regexp)
22368 (push (org-point-in-group p 0 :radio-target) clist))
22369 (goto-char p))
22370 ((setq o (cl-some
22371 (lambda (o)
22372 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22374 (overlays-at (point))))
22375 (push (list :latex-fragment
22376 (overlay-start o) (overlay-end o)) clist)
22377 (push (list :latex-preview
22378 (overlay-start o) (overlay-end o)) clist))
22379 ((org-inside-LaTeX-fragment-p)
22380 ;; FIXME: positions wrong.
22381 (push (list :latex-fragment (point) (point)) clist)))
22383 (setq clist (nreverse (delq nil clist)))
22384 clist))
22386 (defun org-in-regexp (regexp &optional nlines visually)
22387 "Check if point is inside a match of REGEXP.
22389 Normally only the current line is checked, but you can include
22390 NLINES extra lines around point into the search. If VISUALLY is
22391 set, require that the cursor is not after the match but really
22392 on, so that the block visually is on the match.
22394 Return nil or a cons cell (BEG . END) where BEG and END are,
22395 respectively, the positions at the beginning and the end of the
22396 match."
22397 (catch :exit
22398 (let ((pos (point))
22399 (eol (line-end-position (if nlines (1+ nlines) 1))))
22400 (save-excursion
22401 (beginning-of-line (- 1 (or nlines 0)))
22402 (while (and (re-search-forward regexp eol t)
22403 (<= (match-beginning 0) pos))
22404 (let ((end (match-end 0)))
22405 (when (or (> end pos) (and (= end pos) (not visually)))
22406 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22408 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22409 "Non-nil when point is between matches of START-RE and END-RE.
22411 Also return a non-nil value when point is on one of the matches.
22413 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22414 buffer positions. Default values are the positions of headlines
22415 surrounding the point.
22417 The functions returns a cons cell whose car (resp. cdr) is the
22418 position before START-RE (resp. after END-RE)."
22419 (save-match-data
22420 (let ((pos (point))
22421 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22422 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22423 beg end)
22424 (save-excursion
22425 ;; Point is on a block when on START-RE or if START-RE can be
22426 ;; found before it...
22427 (and (or (org-in-regexp start-re)
22428 (re-search-backward start-re limit-up t))
22429 (setq beg (match-beginning 0))
22430 ;; ... and END-RE after it...
22431 (goto-char (match-end 0))
22432 (re-search-forward end-re limit-down t)
22433 (> (setq end (match-end 0)) pos)
22434 ;; ... without another START-RE in-between.
22435 (goto-char (match-beginning 0))
22436 (not (re-search-backward start-re (1+ beg) t))
22437 ;; Return value.
22438 (cons beg end))))))
22440 (defun org-in-block-p (names)
22441 "Non-nil when point belongs to a block whose name belongs to NAMES.
22443 NAMES is a list of strings containing names of blocks.
22445 Return first block name matched, or nil. Beware that in case of
22446 nested blocks, the returned name may not belong to the closest
22447 block from point."
22448 (save-match-data
22449 (catch 'exit
22450 (let ((case-fold-search t)
22451 (lim-up (save-excursion (outline-previous-heading)))
22452 (lim-down (save-excursion (outline-next-heading))))
22453 (dolist (name names)
22454 (let ((n (regexp-quote name)))
22455 (when (org-between-regexps-p
22456 (concat "^[ \t]*#\\+begin_" n)
22457 (concat "^[ \t]*#\\+end_" n)
22458 lim-up lim-down)
22459 (throw 'exit n)))))
22460 nil)))
22462 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22463 "Call `multi-occur' with buffers for all agenda files."
22464 (interactive "sOrg-files matching: ")
22465 (let* ((files (org-agenda-files))
22466 (tnames (mapcar #'file-truename files))
22467 (extra org-agenda-text-search-extra-files))
22468 (when (eq (car extra) 'agenda-archives)
22469 (setq extra (cdr extra))
22470 (setq files (org-add-archive-files files)))
22471 (dolist (f extra)
22472 (unless (member (file-truename f) tnames)
22473 (unless (member f files) (setq files (append files (list f))))
22474 (setq tnames (append tnames (list (file-truename f))))))
22475 (multi-occur
22476 (mapcar (lambda (x)
22477 (with-current-buffer
22478 ;; FIXME: Why not just (find-file-noselect x)?
22479 ;; Is it to avoid the "revert buffer" prompt?
22480 (or (get-file-buffer x) (find-file-noselect x))
22481 (widen)
22482 (current-buffer)))
22483 files)
22484 regexp)))
22486 (add-hook 'occur-mode-find-occurrence-hook
22487 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22489 (defun org-occur-link-in-agenda-files ()
22490 "Create a link and search for it in the agendas.
22491 The link is not stored in `org-stored-links', it is just created
22492 for the search purpose."
22493 (interactive)
22494 (let ((link (condition-case nil
22495 (org-store-link nil)
22496 (error "Unable to create a link to here"))))
22497 (org-occur-in-agenda-files (regexp-quote link))))
22499 (defun org-reverse-string (string)
22500 "Return the reverse of STRING."
22501 (apply 'string (reverse (string-to-list string))))
22503 ;; defsubst org-uniquify must be defined before first use
22505 (defun org-uniquify-alist (alist)
22506 "Merge elements of ALIST with the same key.
22508 For example, in this alist:
22510 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22511 => \\='((a 1 3) (b 2))
22513 merge (a 1) and (a 3) into (a 1 3).
22515 The function returns the new ALIST."
22516 (let (rtn)
22517 (dolist (e alist rtn)
22518 (let (n)
22519 (if (not (assoc (car e) rtn))
22520 (push e rtn)
22521 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22522 (setq rtn (assq-delete-all (car e) rtn))
22523 (push n rtn))))))
22525 (defun org-delete-all (elts list)
22526 "Remove all elements in ELTS from LIST.
22527 Comparison is done with `equal'. It is a destructive operation
22528 that may remove elements by altering the list structure."
22529 (while elts
22530 (setq list (delete (pop elts) list)))
22531 list)
22533 (defun org-back-over-empty-lines ()
22534 "Move backwards over whitespace, to the beginning of the first empty line.
22535 Returns the number of empty lines passed."
22536 (let ((pos (point)))
22537 (if (cdr (assoc 'heading org-blank-before-new-entry))
22538 (skip-chars-backward " \t\n\r")
22539 (unless (eobp)
22540 (forward-line -1)))
22541 (beginning-of-line 2)
22542 (goto-char (min (point) pos))
22543 (count-lines (point) pos)))
22545 (defun org-skip-whitespace ()
22546 (skip-chars-forward " \t\n\r"))
22548 (defun org-point-in-group (point group &optional context)
22549 "Check if POINT is in match-group GROUP.
22550 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22551 match. If the match group does not exist or point is not inside it,
22552 return nil."
22553 (and (match-beginning group)
22554 (>= point (match-beginning group))
22555 (<= point (match-end group))
22556 (if context
22557 (list context (match-beginning group) (match-end group))
22558 t)))
22560 (defun org-switch-to-buffer-other-window (&rest args)
22561 "Switch to buffer in a second window on the current frame.
22562 In particular, do not allow pop-up frames.
22563 Returns the newly created buffer."
22564 (org-no-popups
22565 (apply 'switch-to-buffer-other-window args)))
22567 (defun org-combine-plists (&rest plists)
22568 "Create a single property list from all plists in PLISTS.
22569 The process starts by copying the first list, and then setting properties
22570 from the other lists. Settings in the last list are the most significant
22571 ones and overrule settings in the other lists."
22572 (let ((rtn (copy-sequence (pop plists)))
22573 p v ls)
22574 (while plists
22575 (setq ls (pop plists))
22576 (while ls
22577 (setq p (pop ls) v (pop ls))
22578 (setq rtn (plist-put rtn p v))))
22579 rtn))
22581 (defun org-replace-escapes (string table)
22582 "Replace %-escapes in STRING with values in TABLE.
22583 TABLE is an association list with keys like \"%a\" and string values.
22584 The sequences in STRING may contain normal field width and padding information,
22585 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22586 so values can contain further %-escapes if they are define later in TABLE."
22587 (let ((tbl (copy-alist table))
22588 (case-fold-search nil)
22589 (pchg 0)
22590 re rpl)
22591 (dolist (e tbl)
22592 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22593 (when (and (cdr e) (string-match re (cdr e)))
22594 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22595 (safe "SREF"))
22596 (add-text-properties 0 3 (list 'sref sref) safe)
22597 (setcdr e (replace-match safe t t (cdr e)))))
22598 (while (string-match re string)
22599 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22600 (cdr e)))
22601 (setq string (replace-match rpl t t string))))
22602 (while (setq pchg (next-property-change pchg string))
22603 (let ((sref (get-text-property pchg 'sref string)))
22604 (when (and sref (string-match "SREF" string pchg))
22605 (setq string (replace-match sref t t string)))))
22606 string))
22608 (defun org-find-base-buffer-visiting (file)
22609 "Like `find-buffer-visiting' but always return the base buffer and
22610 not an indirect buffer."
22611 (let ((buf (or (get-file-buffer file)
22612 (find-buffer-visiting file))))
22613 (if buf
22614 (or (buffer-base-buffer buf) buf)
22615 nil)))
22617 ;;; TODO: Only called once, from ox-odt which should probably use
22618 ;;; org-export-inline-image-p or something.
22619 (defun org-file-image-p (file)
22620 "Return non-nil if FILE is an image."
22621 (save-match-data
22622 (string-match (image-file-name-regexp) file)))
22624 (defun org-get-cursor-date (&optional with-time)
22625 "Return the date at cursor in as a time.
22626 This works in the calendar and in the agenda, anywhere else it just
22627 returns the current time.
22628 If WITH-TIME is non-nil, returns the time of the event at point (in
22629 the agenda) or the current time of the day."
22630 (let (date day defd tp hod mod)
22631 (when with-time
22632 (setq tp (get-text-property (point) 'time))
22633 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22634 (setq hod (string-to-number (match-string 1 tp))
22635 mod (string-to-number (match-string 2 tp))))
22636 (or tp (let ((now (decode-time)))
22637 (setq hod (nth 2 now)
22638 mod (nth 1 now)))))
22639 (cond
22640 ((eq major-mode 'calendar-mode)
22641 (setq date (calendar-cursor-to-date)
22642 defd (encode-time 0 (or mod 0) (or hod 0)
22643 (nth 1 date) (nth 0 date) (nth 2 date))))
22644 ((eq major-mode 'org-agenda-mode)
22645 (setq day (get-text-property (point) 'day))
22646 (when day
22647 (setq date (calendar-gregorian-from-absolute day)
22648 defd (encode-time 0 (or mod 0) (or hod 0)
22649 (nth 1 date) (nth 0 date) (nth 2 date))))))
22650 (or defd (current-time))))
22652 (defun org-mark-subtree (&optional up)
22653 "Mark the current subtree.
22654 This puts point at the start of the current subtree, and mark at
22655 the end. If a numeric prefix UP is given, move up into the
22656 hierarchy of headlines by UP levels before marking the subtree."
22657 (interactive "P")
22658 (org-with-limited-levels
22659 (cond ((org-at-heading-p) (beginning-of-line))
22660 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22661 (t (outline-previous-visible-heading 1))))
22662 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22663 (if (called-interactively-p 'any)
22664 (call-interactively 'org-mark-element)
22665 (org-mark-element)))
22667 (defun org-file-newer-than-p (file time)
22668 "Non-nil if FILE is newer than TIME.
22669 FILE is a filename, as a string, TIME is a list of integers, as
22670 returned by, e.g., `current-time'."
22671 (and (file-exists-p file)
22672 ;; Only compare times up to whole seconds as some file-systems
22673 ;; (e.g. HFS+) do not retain any finer granularity. As
22674 ;; a consequence, make sure we return non-nil when the two
22675 ;; times are equal.
22676 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22677 (cl-subseq time 0 2)))))
22679 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22680 "Compile a SOURCE file using PROCESS.
22682 PROCESS is either a function or a list of shell commands, as
22683 strings. EXT is a file extension, without the leading dot, as
22684 a string. It is used to check if the process actually succeeded.
22686 PROCESS must create a file with the same base name and directory
22687 as SOURCE, but ending with EXT. The function then returns its
22688 filename. Otherwise, it raises an error. The error message can
22689 then be refined by providing string ERR-MSG, which is appended to
22690 the standard message.
22692 If PROCESS is a function, it is called with a single argument:
22693 the SOURCE file.
22695 If it is a list of commands, each of them is called using
22696 `shell-command'. By default, in each command, %b, %f, %F and %o
22697 are replaced with, respectively, SOURCE base name, name, full
22698 name and directory. It is possible, however, to use more
22699 place-holders by specifying them in optional argument SPEC, as an
22700 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22702 When PROCESS is a list of commands, optional argument LOG-BUF can
22703 be set to a buffer or a buffer name. `shell-command' then uses
22704 it for output.
22706 `default-directory' is set to SOURCE directory during the whole
22707 process."
22708 (let* ((source-name (file-name-nondirectory source))
22709 (base-name (file-name-sans-extension source-name))
22710 (full-name (file-truename source))
22711 (out-dir (file-name-directory source))
22712 (time (current-time))
22713 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22714 (save-window-excursion
22715 (let ((default-directory (file-name-directory full-name)))
22716 (pcase process
22717 ((pred functionp) (funcall process (shell-quote-argument source)))
22718 ((pred consp)
22719 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22720 (spec (append spec
22721 `((?b . ,(shell-quote-argument base-name))
22722 (?f . ,(shell-quote-argument source-name))
22723 (?F . ,(shell-quote-argument full-name))
22724 (?o . ,(shell-quote-argument out-dir))))))
22725 (dolist (command process)
22726 (shell-command (format-spec command spec) log-buf))))
22727 (_ (error "No valid command to process %S%s" source err-msg)))))
22728 ;; Check for process failure.
22729 (let ((output (concat out-dir base-name "." ext)))
22730 (unless (org-file-newer-than-p output time)
22731 (error (format "File %S wasn't produced%s" output err-msg)))
22732 output)))
22734 ;;; Indentation
22736 (defun org--get-expected-indentation (element contentsp)
22737 "Expected indentation column for current line, according to ELEMENT.
22738 ELEMENT is an element containing point. CONTENTSP is non-nil
22739 when indentation is to be computed according to contents of
22740 ELEMENT."
22741 (let ((type (org-element-type element))
22742 (start (org-element-property :begin element))
22743 (post-affiliated (org-element-property :post-affiliated element)))
22744 (org-with-wide-buffer
22745 (cond
22746 (contentsp
22747 (cl-case type
22748 ((diary-sexp footnote-definition) 0)
22749 ((headline inlinetask nil)
22750 (if (not org-adapt-indentation) 0
22751 (let ((level (org-current-level)))
22752 (if level (1+ level) 0))))
22753 ((item plain-list) (org-list-item-body-column post-affiliated))
22755 (goto-char start)
22756 (org-get-indentation))))
22757 ((memq type '(headline inlinetask nil))
22758 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22759 (org--get-expected-indentation element t)
22761 ((memq type '(diary-sexp footnote-definition)) 0)
22762 ;; First paragraph of a footnote definition or an item.
22763 ;; Indent like parent.
22764 ((< (line-beginning-position) start)
22765 (org--get-expected-indentation
22766 (org-element-property :parent element) t))
22767 ;; At first line: indent according to previous sibling, if any,
22768 ;; ignoring footnote definitions and inline tasks, or parent's
22769 ;; contents.
22770 ((= (line-beginning-position) start)
22771 (catch 'exit
22772 (while t
22773 (if (= (point-min) start) (throw 'exit 0)
22774 (goto-char (1- start))
22775 (let* ((previous (org-element-at-point))
22776 (parent previous))
22777 (while (and parent (<= (org-element-property :end parent) start))
22778 (setq previous parent
22779 parent (org-element-property :parent parent)))
22780 (cond
22781 ((not previous) (throw 'exit 0))
22782 ((> (org-element-property :end previous) start)
22783 (throw 'exit (org--get-expected-indentation previous t)))
22784 ((memq (org-element-type previous)
22785 '(footnote-definition inlinetask))
22786 (setq start (org-element-property :begin previous)))
22787 (t (goto-char (org-element-property :begin previous))
22788 (throw 'exit
22789 (if (bolp) (org-get-indentation)
22790 ;; At first paragraph in an item or
22791 ;; a footnote definition.
22792 (org--get-expected-indentation
22793 (org-element-property :parent previous) t))))))))))
22794 ;; Otherwise, move to the first non-blank line above.
22796 (beginning-of-line)
22797 (let ((pos (point)))
22798 (skip-chars-backward " \r\t\n")
22799 (cond
22800 ;; Two blank lines end a footnote definition or a plain
22801 ;; list. When we indent an empty line after them, the
22802 ;; containing list or footnote definition is over, so it
22803 ;; qualifies as a previous sibling. Therefore, we indent
22804 ;; like its first line.
22805 ((and (memq type '(footnote-definition plain-list))
22806 (> (count-lines (point) pos) 2))
22807 (goto-char start)
22808 (org-get-indentation))
22809 ;; Line above is the first one of a paragraph at the
22810 ;; beginning of an item or a footnote definition. Indent
22811 ;; like parent.
22812 ((< (line-beginning-position) start)
22813 (org--get-expected-indentation
22814 (org-element-property :parent element) t))
22815 ;; Line above is the beginning of an element, i.e., point
22816 ;; was originally on the blank lines between element's start
22817 ;; and contents.
22818 ((= (line-beginning-position) post-affiliated)
22819 (org--get-expected-indentation element t))
22820 ;; POS is after contents in a greater element. Indent like
22821 ;; the beginning of the element.
22823 ;; As a special case, if point is at the end of a footnote
22824 ;; definition or an item, indent like the very last element
22825 ;; within. If that last element is an item, indent like its
22826 ;; contents.
22827 ((and (not (eq type 'paragraph))
22828 (let ((cend (org-element-property :contents-end element)))
22829 (and cend (<= cend pos))))
22830 (if (memq type '(footnote-definition item plain-list))
22831 (let ((last (org-element-at-point)))
22832 (org--get-expected-indentation
22833 last (eq (org-element-type last) 'item)))
22834 (goto-char start)
22835 (org-get-indentation)))
22836 ;; In any other case, indent like the current line.
22837 (t (org-get-indentation)))))))))
22839 (defun org--align-node-property ()
22840 "Align node property at point.
22841 Alignment is done according to `org-property-format', which see."
22842 (when (save-excursion
22843 (beginning-of-line)
22844 (looking-at org-property-re))
22845 (replace-match
22846 (concat (match-string 4)
22847 (org-trim
22848 (format org-property-format (match-string 1) (match-string 3))))
22849 t t)))
22851 (defun org-indent-line ()
22852 "Indent line depending on context.
22854 Indentation is done according to the following rules:
22856 - Footnote definitions, diary sexps, headlines and inline tasks
22857 have to start at column 0.
22859 - On the very first line of an element, consider, in order, the
22860 next rules until one matches:
22862 1. If there's a sibling element before, ignoring footnote
22863 definitions and inline tasks, indent like its first line.
22865 2. If element has a parent, indent like its contents. More
22866 precisely, if parent is an item, indent after the
22867 description part, if any, or the bullet (see
22868 `org-list-description-max-indent'). Else, indent like
22869 parent's first line.
22871 3. Otherwise, indent relatively to current level, if
22872 `org-adapt-indentation' is non-nil, or to left margin.
22874 - On a blank line at the end of an element, indent according to
22875 the type of the element. More precisely
22877 1. If element is a plain list, an item, or a footnote
22878 definition, indent like the very last element within.
22880 2. If element is a paragraph, indent like its last non blank
22881 line.
22883 3. Otherwise, indent like its very first line.
22885 - In the code part of a source block, use language major mode
22886 to indent current line if `org-src-tab-acts-natively' is
22887 non-nil. If it is nil, do nothing.
22889 - Otherwise, indent like the first non-blank line above.
22891 The function doesn't indent an item as it could break the whole
22892 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22893 \\[org-shiftmetaright].
22895 Also align node properties according to `org-property-format'."
22896 (interactive)
22897 (cond
22898 (orgstruct-is-++
22899 (let ((indent-line-function
22900 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22901 (indent-according-to-mode)))
22902 ((org-at-heading-p) 'noindent)
22904 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22905 (type (org-element-type element)))
22906 (cond ((and (memq type '(plain-list item))
22907 (= (line-beginning-position)
22908 (org-element-property :post-affiliated element)))
22909 'noindent)
22910 ((and (eq type 'src-block)
22911 org-src-tab-acts-natively
22912 (> (line-beginning-position)
22913 (org-element-property :post-affiliated element))
22914 (< (line-beginning-position)
22915 (org-with-wide-buffer
22916 (goto-char (org-element-property :end element))
22917 (skip-chars-backward " \r\t\n")
22918 (line-beginning-position))))
22919 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22921 (let ((column (org--get-expected-indentation element nil)))
22922 ;; Preserve current column.
22923 (if (<= (current-column) (current-indentation))
22924 (indent-line-to column)
22925 (save-excursion (indent-line-to column))))
22926 ;; Align node property. Also preserve current column.
22927 (when (eq type 'node-property)
22928 (let ((column (current-column)))
22929 (org--align-node-property)
22930 (org-move-to-column column)))))))))
22932 (defun org-indent-region (start end)
22933 "Indent each non-blank line in the region.
22934 Called from a program, START and END specify the region to
22935 indent. The function will not indent contents of example blocks,
22936 verse blocks and export blocks as leading white spaces are
22937 assumed to be significant there."
22938 (interactive "r")
22939 (save-excursion
22940 (goto-char start)
22941 (skip-chars-forward " \r\t\n")
22942 (unless (eobp) (beginning-of-line))
22943 (let ((indent-to
22944 (lambda (ind pos)
22945 ;; Set IND as indentation for all lines between point and
22946 ;; POS. Blank lines are ignored. Leave point after POS
22947 ;; once done.
22948 (let ((limit (copy-marker pos)))
22949 (while (< (point) limit)
22950 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22951 (forward-line))
22952 (set-marker limit nil))))
22953 (end (copy-marker end)))
22954 (while (< (point) end)
22955 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22956 (let* ((element (org-element-at-point))
22957 (type (org-element-type element))
22958 (element-end (copy-marker (org-element-property :end element)))
22959 (ind (org--get-expected-indentation element nil)))
22960 (cond
22961 ((or (memq type '(paragraph table table-row))
22962 (not (or (org-element-property :contents-begin element)
22963 (memq type
22964 '(example-block export-block src-block)))))
22965 ;; Elements here are indented as a single block. Also
22966 ;; align node properties.
22967 (when (eq type 'node-property)
22968 (org--align-node-property)
22969 (beginning-of-line))
22970 (funcall indent-to ind (min element-end end)))
22972 ;; Elements in this category consist of three parts:
22973 ;; before the contents, the contents, and after the
22974 ;; contents. The contents are treated specially,
22975 ;; according to the element type, or not indented at
22976 ;; all. Other parts are indented as a single block.
22977 (let* ((post (copy-marker
22978 (org-element-property :post-affiliated element)))
22979 (cbeg
22980 (copy-marker
22981 (cond
22982 ((not (org-element-property :contents-begin element))
22983 ;; Fake contents for source blocks.
22984 (org-with-wide-buffer
22985 (goto-char post)
22986 (forward-line)
22987 (point)))
22988 ((memq type '(footnote-definition item plain-list))
22989 ;; Contents in these elements could start on
22990 ;; the same line as the beginning of the
22991 ;; element. Make sure we start indenting
22992 ;; from the second line.
22993 (org-with-wide-buffer
22994 (goto-char post)
22995 (end-of-line)
22996 (skip-chars-forward " \r\t\n")
22997 (if (eobp) (point) (line-beginning-position))))
22998 (t (org-element-property :contents-begin element)))))
22999 (cend (copy-marker
23000 (or (org-element-property :contents-end element)
23001 ;; Fake contents for source blocks.
23002 (org-with-wide-buffer
23003 (goto-char element-end)
23004 (skip-chars-backward " \r\t\n")
23005 (line-beginning-position)))
23006 t)))
23007 ;; Do not change items indentation individually as it
23008 ;; might break the list as a whole. On the other
23009 ;; hand, when at a plain list, indent it as a whole.
23010 (cond ((eq type 'plain-list)
23011 (let ((offset (- ind (org-get-indentation))))
23012 (unless (zerop offset)
23013 (indent-rigidly (org-element-property :begin element)
23014 (org-element-property :end element)
23015 offset))
23016 (goto-char cbeg)))
23017 ((eq type 'item) (goto-char cbeg))
23018 (t (funcall indent-to ind (min cbeg end))))
23019 (when (< (point) end)
23020 (cl-case type
23021 ((example-block export-block verse-block))
23022 (src-block
23023 ;; In a source block, indent source code
23024 ;; according to language major mode, but only if
23025 ;; `org-src-tab-acts-natively' is non-nil.
23026 (when (and (< (point) end) org-src-tab-acts-natively)
23027 (ignore-errors
23028 (org-babel-do-in-edit-buffer
23029 (indent-region (point-min) (point-max))))))
23030 (t (org-indent-region (point) (min cend end))))
23031 (goto-char (min cend end))
23032 (when (< (point) end)
23033 (funcall indent-to ind (min element-end end))))
23034 (set-marker post nil)
23035 (set-marker cbeg nil)
23036 (set-marker cend nil))))
23037 (set-marker element-end nil))))
23038 (set-marker end nil))))
23040 (defun org-indent-drawer ()
23041 "Indent the drawer at point."
23042 (interactive)
23043 (unless (save-excursion
23044 (beginning-of-line)
23045 (looking-at-p org-drawer-regexp))
23046 (user-error "Not at a drawer"))
23047 (let ((element (org-element-at-point)))
23048 (unless (memq (org-element-type element) '(drawer property-drawer))
23049 (user-error "Not at a drawer"))
23050 (org-with-wide-buffer
23051 (org-indent-region (org-element-property :begin element)
23052 (org-element-property :end element))))
23053 (message "Drawer at point indented"))
23055 (defun org-indent-block ()
23056 "Indent the block at point."
23057 (interactive)
23058 (unless (save-excursion
23059 (beginning-of-line)
23060 (let ((case-fold-search t))
23061 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23062 (user-error "Not at a block"))
23063 (let ((element (org-element-at-point)))
23064 (unless (memq (org-element-type element)
23065 '(comment-block center-block dynamic-block example-block
23066 export-block quote-block special-block
23067 src-block verse-block))
23068 (user-error "Not at a block"))
23069 (org-with-wide-buffer
23070 (org-indent-region (org-element-property :begin element)
23071 (org-element-property :end element))))
23072 (message "Block at point indented"))
23075 ;;; Filling
23077 ;; We use our own fill-paragraph and auto-fill functions.
23079 ;; `org-fill-paragraph' relies on adaptive filling and context
23080 ;; checking. Appropriate `fill-prefix' is computed with
23081 ;; `org-adaptive-fill-function'.
23083 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23084 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23085 ;; `org-adaptive-fill-function' value. Internally,
23086 ;; `org-comment-line-break-function' breaks the line.
23088 ;; `org-setup-filling' installs filling and auto-filling related
23089 ;; variables during `org-mode' initialization.
23091 (defvar org-element-paragraph-separate) ; org-element.el
23092 (defun org-setup-filling ()
23093 (require 'org-element)
23094 ;; Prevent auto-fill from inserting unwanted new items.
23095 (when (boundp 'fill-nobreak-predicate)
23096 (setq-local
23097 fill-nobreak-predicate
23098 (org-uniquify
23099 (append fill-nobreak-predicate
23100 '(org-fill-line-break-nobreak-p
23101 org-fill-paragraph-with-timestamp-nobreak-p)))))
23102 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23103 (setq-local paragraph-start paragraph-ending)
23104 (setq-local paragraph-separate paragraph-ending))
23105 (setq-local fill-paragraph-function 'org-fill-paragraph)
23106 (setq-local auto-fill-inhibit-regexp nil)
23107 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23108 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23109 (setq-local comment-line-break-function 'org-comment-line-break-function))
23111 (defun org-fill-line-break-nobreak-p ()
23112 "Non-nil when a new line at point would create an Org line break."
23113 (save-excursion
23114 (skip-chars-backward "[ \t]")
23115 (skip-chars-backward "\\\\")
23116 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23118 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23119 "Non-nil when a new line at point would split a timestamp."
23120 (and (org-at-timestamp-p t)
23121 (not (looking-at org-ts-regexp-both))))
23123 (declare-function message-in-body-p "message" ())
23124 (defvar orgtbl-line-start-regexp) ; From org-table.el
23125 (defun org-adaptive-fill-function ()
23126 "Compute a fill prefix for the current line.
23127 Return fill prefix, as a string, or nil if current line isn't
23128 meant to be filled. For convenience, if `adaptive-fill-regexp'
23129 matches in paragraphs or comments, use it."
23130 (catch 'exit
23131 (when (derived-mode-p 'message-mode)
23132 (save-excursion
23133 (beginning-of-line)
23134 (cond ((not (message-in-body-p)) (throw 'exit nil))
23135 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23136 ((looking-at message-cite-prefix-regexp)
23137 (throw 'exit (match-string-no-properties 0)))
23138 ((looking-at org-outline-regexp)
23139 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23140 (org-with-wide-buffer
23141 (unless (org-at-heading-p)
23142 (let* ((p (line-beginning-position))
23143 (element (save-excursion
23144 (beginning-of-line)
23145 (org-element-at-point)))
23146 (type (org-element-type element))
23147 (post-affiliated (org-element-property :post-affiliated element)))
23148 (unless (< p post-affiliated)
23149 (cl-case type
23150 (comment
23151 (save-excursion
23152 (beginning-of-line)
23153 (looking-at "[ \t]*")
23154 (concat (match-string 0) "# ")))
23155 (footnote-definition "")
23156 ((item plain-list)
23157 (make-string (org-list-item-body-column post-affiliated) ?\s))
23158 (paragraph
23159 ;; Fill prefix is usually the same as the current line,
23160 ;; unless the paragraph is at the beginning of an item.
23161 (let ((parent (org-element-property :parent element)))
23162 (save-excursion
23163 (beginning-of-line)
23164 (cond ((eq (org-element-type parent) 'item)
23165 (make-string (org-list-item-body-column
23166 (org-element-property :begin parent))
23167 ?\s))
23168 ((and adaptive-fill-regexp
23169 ;; Locally disable
23170 ;; `adaptive-fill-function' to let
23171 ;; `fill-context-prefix' handle
23172 ;; `adaptive-fill-regexp' variable.
23173 (let (adaptive-fill-function)
23174 (fill-context-prefix
23175 post-affiliated
23176 (org-element-property :end element)))))
23177 ((looking-at "[ \t]+") (match-string 0))
23178 (t "")))))
23179 (comment-block
23180 ;; Only fill contents if P is within block boundaries.
23181 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23182 (forward-line)
23183 (point)))
23184 (cend (save-excursion
23185 (goto-char (org-element-property :end element))
23186 (skip-chars-backward " \r\t\n")
23187 (line-beginning-position))))
23188 (when (and (>= p cbeg) (< p cend))
23189 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23190 (match-string 0)
23191 "")))))))))))
23193 (declare-function message-goto-body "message" ())
23194 (defvar message-cite-prefix-regexp) ; From message.el
23195 (defun org-fill-paragraph (&optional justify)
23196 "Fill element at point, when applicable.
23198 This function only applies to comment blocks, comments, example
23199 blocks and paragraphs. Also, as a special case, re-align table
23200 when point is at one.
23202 If JUSTIFY is non-nil (interactively, with prefix argument),
23203 justify as well. If `sentence-end-double-space' is non-nil, then
23204 period followed by one space does not end a sentence, so don't
23205 break a line there. The variable `fill-column' controls the
23206 width for filling.
23208 For convenience, when point is at a plain list, an item or
23209 a footnote definition, try to fill the first paragraph within."
23210 (interactive)
23211 (if (and (derived-mode-p 'message-mode)
23212 (or (not (message-in-body-p))
23213 (save-excursion (move-beginning-of-line 1)
23214 (looking-at message-cite-prefix-regexp))))
23215 ;; First ensure filling is correct in message-mode.
23216 (let ((fill-paragraph-function
23217 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23218 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23219 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23220 (paragraph-separate
23221 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23222 (fill-paragraph nil))
23223 (with-syntax-table org-mode-transpose-word-syntax-table
23224 ;; Move to end of line in order to get the first paragraph
23225 ;; within a plain list or a footnote definition.
23226 (let ((element (save-excursion
23227 (end-of-line)
23228 (or (ignore-errors (org-element-at-point))
23229 (user-error "An element cannot be parsed line %d"
23230 (line-number-at-pos (point)))))))
23231 ;; First check if point is in a blank line at the beginning of
23232 ;; the buffer. In that case, ignore filling.
23233 (cl-case (org-element-type element)
23234 ;; Use major mode filling function is src blocks.
23235 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23236 ;; Align Org tables, leave table.el tables as-is.
23237 (table-row (org-table-align) t)
23238 (table
23239 (when (eq (org-element-property :type element) 'org)
23240 (save-excursion
23241 (goto-char (org-element-property :post-affiliated element))
23242 (org-table-align)))
23244 (paragraph
23245 ;; Paragraphs may contain `line-break' type objects.
23246 (let ((beg (max (point-min)
23247 (org-element-property :contents-begin element)))
23248 (end (min (point-max)
23249 (org-element-property :contents-end element))))
23250 ;; Do nothing if point is at an affiliated keyword.
23251 (if (< (line-end-position) beg) t
23252 (when (derived-mode-p 'message-mode)
23253 ;; In `message-mode', do not fill following citation
23254 ;; in current paragraph nor text before message body.
23255 (let ((body-start (save-excursion (message-goto-body))))
23256 (when body-start (setq beg (max body-start beg))))
23257 (when (save-excursion
23258 (re-search-forward
23259 (concat "^" message-cite-prefix-regexp) end t))
23260 (setq end (match-beginning 0))))
23261 ;; Fill paragraph, taking line breaks into account.
23262 (save-excursion
23263 (goto-char beg)
23264 (let ((cuts (list beg)))
23265 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23266 (when (eq 'line-break
23267 (org-element-type
23268 (save-excursion (backward-char)
23269 (org-element-context))))
23270 (push (point) cuts)))
23271 (dolist (c (delq end cuts))
23272 (fill-region-as-paragraph c end justify)
23273 (setq end c))))
23274 t)))
23275 ;; Contents of `comment-block' type elements should be
23276 ;; filled as plain text, but only if point is within block
23277 ;; markers.
23278 (comment-block
23279 (let* ((case-fold-search t)
23280 (beg (save-excursion
23281 (goto-char (org-element-property :begin element))
23282 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23283 (forward-line)
23284 (point)))
23285 (end (save-excursion
23286 (goto-char (org-element-property :end element))
23287 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23288 (line-beginning-position))))
23289 (if (or (< (point) beg) (> (point) end)) t
23290 (fill-region-as-paragraph
23291 (save-excursion (end-of-line)
23292 (re-search-backward "^[ \t]*$" beg 'move)
23293 (line-beginning-position))
23294 (save-excursion (beginning-of-line)
23295 (re-search-forward "^[ \t]*$" end 'move)
23296 (line-beginning-position))
23297 justify))))
23298 ;; Fill comments.
23299 (comment
23300 (let ((begin (org-element-property :post-affiliated element))
23301 (end (org-element-property :end element)))
23302 (when (and (>= (point) begin) (<= (point) end))
23303 (let ((begin (save-excursion
23304 (end-of-line)
23305 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23306 (progn (forward-line) (point))
23307 begin)))
23308 (end (save-excursion
23309 (end-of-line)
23310 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23311 (1- (line-beginning-position))
23312 (skip-chars-backward " \r\t\n")
23313 (line-end-position)))))
23314 ;; Do not fill comments when at a blank line.
23315 (when (> end begin)
23316 (let ((fill-prefix
23317 (save-excursion
23318 (beginning-of-line)
23319 (looking-at "[ \t]*#")
23320 (let ((comment-prefix (match-string 0)))
23321 (goto-char (match-end 0))
23322 (if (looking-at adaptive-fill-regexp)
23323 (concat comment-prefix (match-string 0))
23324 (concat comment-prefix " "))))))
23325 (save-excursion
23326 (fill-region-as-paragraph begin end justify))))))
23328 ;; Ignore every other element.
23329 (otherwise t))))))
23331 (defun org-auto-fill-function ()
23332 "Auto-fill function."
23333 ;; Check if auto-filling is meaningful.
23334 (let ((fc (current-fill-column)))
23335 (when (and fc (> (current-column) fc))
23336 (let* ((fill-prefix (org-adaptive-fill-function))
23337 ;; Enforce empty fill prefix, if required. Otherwise, it
23338 ;; will be computed again.
23339 (adaptive-fill-mode (not (equal fill-prefix ""))))
23340 (when fill-prefix (do-auto-fill))))))
23342 (defun org-comment-line-break-function (&optional soft)
23343 "Break line at point and indent, continuing comment if within one.
23344 The inserted newline is marked hard if variable
23345 `use-hard-newlines' is true, unless optional argument SOFT is
23346 non-nil."
23347 (if soft (insert-and-inherit ?\n) (newline 1))
23348 (save-excursion (forward-char -1) (delete-horizontal-space))
23349 (delete-horizontal-space)
23350 (indent-to-left-margin)
23351 (insert-before-markers-and-inherit fill-prefix))
23354 ;;; Fixed Width Areas
23356 (defun org-toggle-fixed-width ()
23357 "Toggle fixed-width markup.
23359 Add or remove fixed-width markup on current line, whenever it
23360 makes sense. Return an error otherwise.
23362 If a region is active and if it contains only fixed-width areas
23363 or blank lines, remove all fixed-width markup in it. If the
23364 region contains anything else, convert all non-fixed-width lines
23365 to fixed-width ones.
23367 Blank lines at the end of the region are ignored unless the
23368 region only contains such lines."
23369 (interactive)
23370 (if (not (org-region-active-p))
23371 ;; No region:
23373 ;; Remove fixed width marker only in a fixed-with element.
23375 ;; Add fixed width maker in paragraphs, in blank lines after
23376 ;; elements or at the beginning of a headline or an inlinetask,
23377 ;; and before any one-line elements (e.g., a clock).
23378 (progn
23379 (beginning-of-line)
23380 (let* ((element (org-element-at-point))
23381 (type (org-element-type element)))
23382 (cond
23383 ((and (eq type 'fixed-width)
23384 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23385 (replace-match
23386 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23387 ((and (memq type '(babel-call clock comment diary-sexp headline
23388 horizontal-rule keyword paragraph
23389 planning))
23390 (<= (org-element-property :post-affiliated element) (point)))
23391 (skip-chars-forward " \t")
23392 (insert ": "))
23393 ((and (looking-at-p "[ \t]*$")
23394 (or (eq type 'inlinetask)
23395 (save-excursion
23396 (skip-chars-forward " \r\t\n")
23397 (<= (org-element-property :end element) (point)))))
23398 (delete-region (point) (line-end-position))
23399 (org-indent-line)
23400 (insert ": "))
23401 (t (user-error "Cannot insert a fixed-width line here")))))
23402 ;; Region active.
23403 (let* ((begin (save-excursion
23404 (goto-char (region-beginning))
23405 (line-beginning-position)))
23406 (end (copy-marker
23407 (save-excursion
23408 (goto-char (region-end))
23409 (unless (eolp) (beginning-of-line))
23410 (if (save-excursion (re-search-backward "\\S-" begin t))
23411 (progn (skip-chars-backward " \r\t\n") (point))
23412 (point)))))
23413 (all-fixed-width-p
23414 (catch 'not-all-p
23415 (save-excursion
23416 (goto-char begin)
23417 (skip-chars-forward " \r\t\n")
23418 (when (eobp) (throw 'not-all-p nil))
23419 (while (< (point) end)
23420 (let ((element (org-element-at-point)))
23421 (if (eq (org-element-type element) 'fixed-width)
23422 (goto-char (org-element-property :end element))
23423 (throw 'not-all-p nil))))
23424 t))))
23425 (if all-fixed-width-p
23426 (save-excursion
23427 (goto-char begin)
23428 (while (< (point) end)
23429 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23430 (replace-match
23431 "" nil nil nil
23432 (if (= (line-end-position) (match-end 0)) 0 1)))
23433 (forward-line)))
23434 (let ((min-ind (point-max)))
23435 ;; Find minimum indentation across all lines.
23436 (save-excursion
23437 (goto-char begin)
23438 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23439 (setq min-ind 0)
23440 (catch 'zerop
23441 (while (< (point) end)
23442 (unless (looking-at-p "[ \t]*$")
23443 (let ((ind (org-get-indentation)))
23444 (setq min-ind (min min-ind ind))
23445 (when (zerop ind) (throw 'zerop t))))
23446 (forward-line)))))
23447 ;; Loop over all lines and add fixed-width markup everywhere
23448 ;; but in fixed-width lines.
23449 (save-excursion
23450 (goto-char begin)
23451 (while (< (point) end)
23452 (cond
23453 ((org-at-heading-p)
23454 (insert ": ")
23455 (forward-line)
23456 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23457 (insert ":")
23458 (forward-line)))
23459 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23460 (let* ((element (org-element-at-point))
23461 (element-end (org-element-property :end element)))
23462 (if (eq (org-element-type element) 'fixed-width)
23463 (progn (goto-char element-end)
23464 (skip-chars-backward " \r\t\n")
23465 (forward-line))
23466 (let ((limit (min end element-end)))
23467 (while (< (point) limit)
23468 (org-move-to-column min-ind t)
23469 (insert ": ")
23470 (forward-line))))))
23472 (org-move-to-column min-ind t)
23473 (insert ": ")
23474 (forward-line)))))))
23475 (set-marker end nil))))
23478 ;;; Comments
23480 ;; Org comments syntax is quite complex. It requires the entire line
23481 ;; to be just a comment. Also, even with the right syntax at the
23482 ;; beginning of line, some some elements (i.e. verse-block or
23483 ;; example-block) don't accept comments. Usual Emacs comment commands
23484 ;; cannot cope with those requirements. Therefore, Org replaces them.
23486 ;; Org still relies on `comment-dwim', but cannot trust
23487 ;; `comment-only-p'. So, `comment-region-function' and
23488 ;; `uncomment-region-function' both point
23489 ;; to`org-comment-or-uncomment-region'. Eventually,
23490 ;; `org-insert-comment' takes care of insertion of comments at the
23491 ;; beginning of line.
23493 ;; `org-setup-comments-handling' install comments related variables
23494 ;; during `org-mode' initialization.
23496 (defun org-setup-comments-handling ()
23497 (interactive)
23498 (setq-local comment-use-syntax nil)
23499 (setq-local comment-start "# ")
23500 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23501 (setq-local comment-insert-comment-function 'org-insert-comment)
23502 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23503 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23505 (defun org-insert-comment ()
23506 "Insert an empty comment above current line.
23507 If the line is empty, insert comment at its beginning. When
23508 point is within a source block, comment according to the related
23509 major mode."
23510 (if (let ((element (org-element-at-point)))
23511 (and (eq (org-element-type element) 'src-block)
23512 (< (save-excursion
23513 (goto-char (org-element-property :post-affiliated element))
23514 (line-end-position))
23515 (point))
23516 (> (save-excursion
23517 (goto-char (org-element-property :end element))
23518 (skip-chars-backward " \r\t\n")
23519 (line-beginning-position))
23520 (point))))
23521 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23522 (beginning-of-line)
23523 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23524 (open-line 1))
23525 (org-indent-line)
23526 (insert "# ")))
23528 (defvar comment-empty-lines) ; From newcomment.el.
23529 (defun org-comment-or-uncomment-region (beg end &rest _)
23530 "Comment or uncomment each non-blank line in the region.
23531 Uncomment each non-blank line between BEG and END if it only
23532 contains commented lines. Otherwise, comment them. If region is
23533 strictly within a source block, use appropriate comment syntax."
23534 (if (let ((element (org-element-at-point)))
23535 (and (eq (org-element-type element) 'src-block)
23536 (< (save-excursion
23537 (goto-char (org-element-property :post-affiliated element))
23538 (line-end-position))
23539 beg)
23540 (>= (save-excursion
23541 (goto-char (org-element-property :end element))
23542 (skip-chars-backward " \r\t\n")
23543 (line-beginning-position))
23544 end)))
23545 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23546 (save-restriction
23547 ;; Restrict region
23548 (narrow-to-region (save-excursion (goto-char beg)
23549 (skip-chars-forward " \r\t\n" end)
23550 (line-beginning-position))
23551 (save-excursion (goto-char end)
23552 (skip-chars-backward " \r\t\n" beg)
23553 (line-end-position)))
23554 (let ((uncommentp
23555 ;; UNCOMMENTP is non-nil when every non blank line between
23556 ;; BEG and END is a comment.
23557 (save-excursion
23558 (goto-char (point-min))
23559 (while (and (not (eobp))
23560 (let ((element (org-element-at-point)))
23561 (and (eq (org-element-type element) 'comment)
23562 (goto-char (min (point-max)
23563 (org-element-property
23564 :end element)))))))
23565 (eobp))))
23566 (if uncommentp
23567 ;; Only blank lines and comments in region: uncomment it.
23568 (save-excursion
23569 (goto-char (point-min))
23570 (while (not (eobp))
23571 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23572 (replace-match "" nil nil nil 1))
23573 (forward-line)))
23574 ;; Comment each line in region.
23575 (let ((min-indent (point-max)))
23576 ;; First find the minimum indentation across all lines.
23577 (save-excursion
23578 (goto-char (point-min))
23579 (while (and (not (eobp)) (not (zerop min-indent)))
23580 (unless (looking-at "[ \t]*$")
23581 (setq min-indent (min min-indent (current-indentation))))
23582 (forward-line)))
23583 ;; Then loop over all lines.
23584 (save-excursion
23585 (goto-char (point-min))
23586 (while (not (eobp))
23587 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23588 ;; Don't get fooled by invisible text (e.g. link path)
23589 ;; when moving to column MIN-INDENT.
23590 (let ((buffer-invisibility-spec nil))
23591 (org-move-to-column min-indent t))
23592 (insert comment-start))
23593 (forward-line)))))))))
23595 (defun org-comment-dwim (_arg)
23596 "Call `comment-dwim' within a source edit buffer if needed."
23597 (interactive "*P")
23598 (if (org-in-src-block-p)
23599 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23600 (call-interactively 'comment-dwim)))
23603 ;;; Timestamps API
23605 ;; This section contains tools to operate on timestamp objects, as
23606 ;; returned by, e.g. `org-element-context'.
23608 (defun org-timestamp--to-internal-time (timestamp &optional end)
23609 "Encode TIMESTAMP object into Emacs internal time.
23610 Use end of date range or time range when END is non-nil."
23611 (apply #'encode-time
23612 (cons 0
23613 (mapcar
23614 (lambda (prop) (or (org-element-property prop timestamp) 0))
23615 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23616 '(:minute-start :hour-start :day-start :month-start
23617 :year-start))))))
23619 (defun org-timestamp-has-time-p (timestamp)
23620 "Non-nil when TIMESTAMP has a time specified."
23621 (org-element-property :hour-start timestamp))
23623 (defun org-timestamp-format (timestamp format &optional end utc)
23624 "Format a TIMESTAMP object into a string.
23626 FORMAT is a format specifier to be passed to
23627 `format-time-string'.
23629 When optional argument END is non-nil, use end of date-range or
23630 time-range, if possible.
23632 When optional argument UTC is non-nil, time will be expressed as
23633 Universal Time."
23634 (format-time-string
23635 format (org-timestamp--to-internal-time timestamp end)
23636 (and utc t)))
23638 (defun org-timestamp-split-range (timestamp &optional end)
23639 "Extract a TIMESTAMP object from a date or time range.
23641 END, when non-nil, means extract the end of the range.
23642 Otherwise, extract its start.
23644 Return a new timestamp object."
23645 (let ((type (org-element-property :type timestamp)))
23646 (if (memq type '(active inactive diary)) timestamp
23647 (let ((split-ts (org-element-copy timestamp)))
23648 ;; Set new type.
23649 (org-element-put-property
23650 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23651 ;; Copy start properties over end properties if END is
23652 ;; non-nil. Otherwise, copy end properties over `start' ones.
23653 (let ((p-alist '((:minute-start . :minute-end)
23654 (:hour-start . :hour-end)
23655 (:day-start . :day-end)
23656 (:month-start . :month-end)
23657 (:year-start . :year-end))))
23658 (dolist (p-cell p-alist)
23659 (org-element-put-property
23660 split-ts
23661 (funcall (if end #'car #'cdr) p-cell)
23662 (org-element-property
23663 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23664 ;; Eventually refresh `:raw-value'.
23665 (org-element-put-property split-ts :raw-value nil)
23666 (org-element-put-property
23667 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23669 (defun org-timestamp-translate (timestamp &optional boundary)
23670 "Translate TIMESTAMP object to custom format.
23672 Format string is defined in `org-time-stamp-custom-formats',
23673 which see.
23675 When optional argument BOUNDARY is non-nil, it is either the
23676 symbol `start' or `end'. In this case, only translate the
23677 starting or ending part of TIMESTAMP if it is a date or time
23678 range. Otherwise, translate both parts.
23680 Return timestamp as-is if `org-display-custom-times' is nil or if
23681 it has a `diary' type."
23682 (let ((type (org-element-property :type timestamp)))
23683 (if (or (not org-display-custom-times) (eq type 'diary))
23684 (org-element-interpret-data timestamp)
23685 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23686 org-time-stamp-custom-formats)))
23687 (if (and (not boundary) (memq type '(active-range inactive-range)))
23688 (concat (org-timestamp-format timestamp fmt)
23689 "--"
23690 (org-timestamp-format timestamp fmt t))
23691 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23695 ;;; Other stuff.
23697 (defvar reftex-docstruct-symbol)
23698 (defvar reftex-cite-format)
23699 (defvar org--rds)
23701 (defun org-reftex-citation ()
23702 "Use reftex-citation to insert a citation into the buffer.
23703 This looks for a line like
23705 #+BIBLIOGRAPHY: foo plain option:-d
23707 and derives from it that foo.bib is the bibliography file relevant
23708 for this document. It then installs the necessary environment for RefTeX
23709 to work in this buffer and calls `reftex-citation' to insert a citation
23710 into the buffer.
23712 Export of such citations to both LaTeX and HTML is handled by the contributed
23713 package ox-bibtex by Taru Karttunen."
23714 (interactive)
23715 (let ((reftex-docstruct-symbol 'org--rds)
23716 (reftex-cite-format "\\cite{%l}")
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