Fix `org-ctrl-c-ctrl-c'
[org-mode/org-tableheadings.git] / lisp / org.el
blob625622964d5744a15f9d43c116d57534751f343c
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (defsubst org-uniquify (list)
176 "Non-destructively remove duplicate elements from LIST."
177 (let ((res (copy-sequence list))) (delete-dups res)))
179 (defsubst org-get-at-bol (property)
180 "Get text property PROPERTY at the beginning of line."
181 (get-text-property (point-at-bol) property))
183 (defsubst org-trim (s &optional keep-lead)
184 "Remove whitespace at the beginning and the end of string S.
185 When optional argument KEEP-LEAD is non-nil, removing blank lines
186 at the beginning of the string does not affect leading indentation."
187 (replace-regexp-in-string
188 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
189 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
191 ;; load languages based on value of `org-babel-load-languages'
192 (defvar org-babel-load-languages)
194 ;;;###autoload
195 (defun org-babel-do-load-languages (sym value)
196 "Load the languages defined in `org-babel-load-languages'."
197 (set-default sym value)
198 (dolist (pair org-babel-load-languages)
199 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
200 (if active
201 (require (intern (concat "ob-" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-execute:" lang)))
204 (funcall 'fmakunbound
205 (intern (concat "org-babel-expand-body:" lang)))))))
207 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
208 ;;;###autoload
209 (defun org-babel-load-file (file &optional compile)
210 "Load Emacs Lisp source code blocks in the Org FILE.
211 This function exports the source code using `org-babel-tangle'
212 and then loads the resulting file using `load-file'. With prefix
213 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
214 file to byte-code before it is loaded."
215 (interactive "fFile to load: \nP")
216 (let* ((age (lambda (file)
217 (float-time
218 (time-subtract (current-time)
219 (nth 5 (or (file-attributes (file-truename file))
220 (file-attributes file)))))))
221 (base-name (file-name-sans-extension file))
222 (exported-file (concat base-name ".el")))
223 ;; tangle if the Org file is newer than the elisp file
224 (unless (and (file-exists-p exported-file)
225 (> (funcall age file) (funcall age exported-file)))
226 ;; Tangle-file traversal returns reversed list of tangled files
227 ;; and we want to evaluate the first target.
228 (setq exported-file
229 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
230 (message "%s %s"
231 (if compile
232 (progn (byte-compile-file exported-file 'load)
233 "Compiled and loaded")
234 (progn (load-file exported-file) "Loaded"))
235 exported-file)))
237 (defcustom org-babel-load-languages '((emacs-lisp . t))
238 "Languages which can be evaluated in Org buffers.
239 This list can be used to load support for any of the languages
240 below, note that each language will depend on a different set of
241 system executables and/or Emacs modes. When a language is
242 \"loaded\", then code blocks in that language can be evaluated
243 with `org-babel-execute-src-block' bound by default to C-c
244 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
245 be set to remove code block evaluation from the C-c C-c
246 keybinding. By default only Emacs Lisp (which has no
247 requirements) is loaded."
248 :group 'org-babel
249 :set 'org-babel-do-load-languages
250 :version "24.1"
251 :type '(alist :tag "Babel Languages"
252 :key-type
253 (choice
254 (const :tag "Awk" awk)
255 (const :tag "C" C)
256 (const :tag "R" R)
257 (const :tag "Asymptote" asymptote)
258 (const :tag "Calc" calc)
259 (const :tag "Clojure" clojure)
260 (const :tag "CSS" css)
261 (const :tag "Ditaa" ditaa)
262 (const :tag "Dot" dot)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "ebnf2ps" ebnf2ps))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org-mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 A deadline is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-deadline].")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 A schedule is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-schedule].")
385 (defconst org-ds-keyword-length
386 (+ 2
387 (apply #'max
388 (mapcar #'length
389 (list org-deadline-string org-scheduled-string
390 org-clock-string org-closed-string))))
391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
393 (defconst org-planning-line-re
394 (concat "^[ \t]*"
395 (regexp-opt
396 (list org-closed-string org-deadline-string org-scheduled-string)
398 "Matches a line with planning info.
399 Matched keyword is in group 1.")
401 (defconst org-clock-line-re
402 (concat "^[ \t]*" org-clock-string)
403 "Matches a line with clock info.")
405 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
406 "Matches the DEADLINE keyword.")
408 (defconst org-deadline-time-regexp
409 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
410 "Matches the DEADLINE keyword together with a time stamp.")
412 (defconst org-deadline-time-hour-regexp
413 (concat "\\<" org-deadline-string
414 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
415 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
417 (defconst org-deadline-line-regexp
418 (concat "\\<\\(" org-deadline-string "\\).*")
419 "Matches the DEADLINE keyword and the rest of the line.")
421 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
422 "Matches the SCHEDULED keyword.")
424 (defconst org-scheduled-time-regexp
425 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
426 "Matches the SCHEDULED keyword together with a time stamp.")
428 (defconst org-scheduled-time-hour-regexp
429 (concat "\\<" org-scheduled-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
433 (defconst org-closed-time-regexp
434 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
435 "Matches the CLOSED keyword together with a time stamp.")
437 (defconst org-keyword-time-regexp
438 (concat "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string
441 org-clock-string)
443 " *[[<]\\([^]>]+\\)[]>]")
444 "Matches any of the 4 keywords, together with the time stamp.")
446 (defconst org-keyword-time-not-clock-regexp
447 (concat
448 "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string) t)
451 " *[[<]\\([^]>]+\\)[]>]")
452 "Matches any of the 3 keywords, together with the time stamp.")
454 (defconst org-maybe-keyword-time-regexp
455 (concat "\\(\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string
458 org-clock-string)
460 "\\)?"
461 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
462 "\\|"
463 "<%%([^\r\n>]*>\\)")
464 "Matches a timestamp, possibly preceded by a keyword.")
466 (defconst org-all-time-keywords
467 (mapcar (lambda (w) (substring w 0 -1))
468 (list org-scheduled-string org-deadline-string
469 org-clock-string org-closed-string))
470 "List of time keywords.")
472 ;;;; Drawer
474 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
475 "Matches first or last line of a hidden block.
476 Group 1 contains drawer's name or \"END\".")
478 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
479 "Regular expression matching the first line of a property drawer.")
481 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a property drawer.")
484 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
485 "Regular expression matching the first line of a clock drawer.")
487 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a clock drawer.")
490 (defconst org-property-drawer-re
491 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
492 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
493 "[ \t]*:END:[ \t]*$")
494 "Matches an entire property drawer.")
496 (defconst org-clock-drawer-re
497 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
498 org-clock-drawer-end-re "\\)\n?")
499 "Matches an entire clock drawer.")
501 ;;;; Headline
503 (defconst org-heading-keyword-regexp-format
504 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
505 "Printf format for a regexp matching a headline with some keyword.
506 This regexp will match the headline of any node which has the
507 exact keyword that is put into the format. The keyword isn't in
508 any group by default, but the stars and the body are.")
510 (defconst org-heading-keyword-maybe-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline, possibly with some keyword.
513 This regexp can match any headline with the specified keyword, or
514 without a keyword. The keyword isn't in any group by default,
515 but the stars and the body are.")
517 (defconst org-archive-tag "ARCHIVE"
518 "The tag that marks a subtree as archived.
519 An archived subtree does not open during visibility cycling, and does
520 not contribute to the agenda listings.")
522 (defconst org-comment-string "COMMENT"
523 "Entries starting with this keyword will never be exported.
524 An entry can be toggled between COMMENT and normal with
525 \\[org-toggle-comment].")
528 ;;;; LaTeX Environments and Fragments
530 (defconst org-latex-regexps
531 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
532 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
533 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
534 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
535 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
536 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
537 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
538 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
539 "Regular expressions for matching embedded LaTeX.")
541 ;;;; Node Property
543 (defconst org-effort-property "Effort"
544 "The property that is being used to keep track of effort estimates.
545 Effort estimates given in this property need to have the format H:MM.")
547 ;;;; Table
549 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
550 "Detect an org-type or table-type table.")
552 (defconst org-table-line-regexp "^[ \t]*|"
553 "Detect an org-type table line.")
555 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
556 "Detect an org-type table line.")
558 (defconst org-table-hline-regexp "^[ \t]*|-"
559 "Detect an org-type table hline.")
561 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
562 "Detect a table-type table hline.")
564 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
565 "Detect the first line outside a table when searching from within it.
566 This works for both table types.")
568 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
569 "Detect a #+TBLFM line.")
571 ;;;; Timestamp
573 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
574 "Regular expression for fast time stamp matching.")
576 (defconst org-ts-regexp-inactive
577 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
578 "Regular expression for fast inactive time stamp matching.")
580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp0
584 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
585 "Regular expression matching time strings for analysis.
586 This one does not require the space after the date, so it can be used
587 on a string that terminates immediately after the date.")
589 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.")
592 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
593 "Regular expression matching time stamps, with groups.")
595 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
596 "Regular expression matching time stamps (also [..]), with groups.")
598 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tr-regexp-both
602 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
606 org-ts-regexp "\\)?")
607 "Regular expression matching a time stamp or time stamp range.")
609 (defconst org-tsr-regexp-both
610 (concat org-ts-regexp-both "\\(--?-?"
611 org-ts-regexp-both "\\)?")
612 "Regular expression matching a time stamp or time stamp range.
613 The time stamps may be either active or inactive.")
615 (defconst org-repeat-re
616 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
617 "Regular expression for specifying repeated events.
618 After a match, group 1 contains the repeat expression.")
620 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
621 "Formats for `format-time-string' which are used for time stamps.")
624 ;;; The custom variables
626 (defgroup org nil
627 "Outline-based notes management and organizer."
628 :tag "Org"
629 :group 'outlines
630 :group 'calendar)
632 (defcustom org-mode-hook nil
633 "Mode hook for Org-mode, run after the mode was turned on."
634 :group 'org
635 :type 'hook)
637 (defcustom org-load-hook nil
638 "Hook that is run after org.el has been loaded."
639 :group 'org
640 :type 'hook)
642 (defcustom org-log-buffer-setup-hook nil
643 "Hook that is run after an Org log buffer is created."
644 :group 'org
645 :version "24.1"
646 :type 'hook)
648 (defvar org-modules) ; defined below
649 (defvar org-modules-loaded nil
650 "Have the modules been loaded already?")
652 (defun org-load-modules-maybe (&optional force)
653 "Load all extensions listed in `org-modules'."
654 (when (or force (not org-modules-loaded))
655 (dolist (ext org-modules)
656 (condition-case nil (require ext)
657 (error (message "Problems while trying to load feature `%s'" ext))))
658 (setq org-modules-loaded t)))
660 (defun org-set-modules (var value)
661 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
662 (set var value)
663 (when (featurep 'org)
664 (org-load-modules-maybe 'force)
665 (org-element-cache-reset 'all)))
667 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
668 "Modules that should always be loaded together with org.el.
670 If a description starts with <C>, the file is not part of Emacs
671 and loading it will require that you have downloaded and properly
672 installed the Org mode distribution.
674 You can also use this system to load external packages (i.e. neither Org
675 core modules, nor modules from the CONTRIB directory). Just add symbols
676 to the end of the list. If the package is called org-xyz.el, then you need
677 to add the symbol `xyz', and the package must have a call to:
679 (provide \\='org-xyz)
681 For export specific modules, see also `org-export-backends'."
682 :group 'org
683 :set 'org-set-modules
684 :version "24.4"
685 :package-version '(Org . "8.0")
686 :type
687 '(set :greedy t
688 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
689 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
690 (const :tag " crypt: Encryption of subtrees" org-crypt)
691 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
692 (const :tag " docview: Links to doc-view buffers" org-docview)
693 (const :tag " eww: Store link to url of eww" org-eww)
694 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
695 (const :tag " habit: Track your consistency with habits" org-habit)
696 (const :tag " id: Global IDs for identifying entries" org-id)
697 (const :tag " info: Links to Info nodes" org-info)
698 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
699 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
700 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
701 (const :tag " mouse: Additional mouse support" org-mouse)
702 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
703 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
704 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
706 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
707 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
708 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
709 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
710 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
711 (const :tag "C collector: Collect properties into tables" org-collector)
712 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
713 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
714 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
715 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
716 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
717 (const :tag "C eval: Include command output as text" org-eval)
718 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
719 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
720 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
721 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
722 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
723 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
724 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
725 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
726 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
727 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
728 (const :tag "C mew: Links to Mew folders/messages" org-mew)
729 (const :tag "C mtags: Support for muse-like tags" org-mtags)
730 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
731 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
732 (const :tag "C registry: A registry for Org links" org-registry)
733 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
734 (const :tag "C secretary: Team management with org-mode" org-secretary)
735 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
736 (const :tag "C toc: Table of contents for Org buffer" org-toc)
737 (const :tag "C track: Keep up with Org mode development" org-track)
738 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
739 (const :tag "C vm: Links to VM folders/messages" org-vm)
740 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
741 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
742 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
744 (defvar org-export-registered-backends) ; From ox.el.
745 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
746 (declare-function org-export-backend-name "ox" (backend) t)
747 (defcustom org-export-backends '(ascii html icalendar latex odt)
748 "List of export back-ends that should be always available.
750 If a description starts with <C>, the file is not part of Emacs
751 and loading it will require that you have downloaded and properly
752 installed the Org mode distribution.
754 Unlike to `org-modules', libraries in this list will not be
755 loaded along with Org, but only once the export framework is
756 needed.
758 This variable needs to be set before org.el is loaded. If you
759 need to make a change while Emacs is running, use the customize
760 interface or run the following code, where VAL stands for the new
761 value of the variable, after updating it:
763 (progn
764 (setq org-export-registered-backends
765 (cl-remove-if-not
766 (lambda (backend)
767 (let ((name (org-export-backend-name backend)))
768 (or (memq name val)
769 (catch \\='parentp
770 (dolist (b val)
771 (and (org-export-derived-backend-p b name)
772 (throw \\='parentp t)))))))
773 org-export-registered-backends))
774 (let ((new-list (mapcar #\\='org-export-backend-name
775 org-export-registered-backends)))
776 (dolist (backend val)
777 (cond
778 ((not (load (format \"ox-%s\" backend) t t))
779 (message \"Problems while trying to load export back-end \\=`%s\\='\"
780 backend))
781 ((not (memq backend new-list)) (push backend new-list))))
782 (set-default \\='org-export-backends new-list)))
784 Adding a back-end to this list will also pull the back-end it
785 depends on, if any."
786 :group 'org
787 :group 'org-export
788 :version "25.1"
789 :package-version '(Org . "9.0")
790 :initialize 'custom-initialize-set
791 :set (lambda (var val)
792 (if (not (featurep 'ox)) (set-default var val)
793 ;; Any back-end not required anymore (not present in VAL and not
794 ;; a parent of any back-end in the new value) is removed from the
795 ;; list of registered back-ends.
796 (setq org-export-registered-backends
797 (cl-remove-if-not
798 (lambda (backend)
799 (let ((name (org-export-backend-name backend)))
800 (or (memq name val)
801 (catch 'parentp
802 (dolist (b val)
803 (and (org-export-derived-backend-p b name)
804 (throw 'parentp t)))))))
805 org-export-registered-backends))
806 ;; Now build NEW-LIST of both new back-ends and required
807 ;; parents.
808 (let ((new-list (mapcar #'org-export-backend-name
809 org-export-registered-backends)))
810 (dolist (backend val)
811 (cond
812 ((not (load (format "ox-%s" backend) t t))
813 (message "Problems while trying to load export back-end `%s'"
814 backend))
815 ((not (memq backend new-list)) (push backend new-list))))
816 ;; Set VAR to that list with fixed dependencies.
817 (set-default var new-list))))
818 :type '(set :greedy t
819 (const :tag " ascii Export buffer to ASCII format" ascii)
820 (const :tag " beamer Export buffer to Beamer presentation" beamer)
821 (const :tag " html Export buffer to HTML format" html)
822 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
823 (const :tag " latex Export buffer to LaTeX format" latex)
824 (const :tag " man Export buffer to MAN format" man)
825 (const :tag " md Export buffer to Markdown format" md)
826 (const :tag " odt Export buffer to ODT format" odt)
827 (const :tag " org Export buffer to Org format" org)
828 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
829 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
830 (const :tag "C deck Export buffer to deck.js presentations" deck)
831 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
832 (const :tag "C groff Export buffer to Groff format" groff)
833 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
834 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
835 (const :tag "C s5 Export buffer to s5 presentations" s5)
836 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
838 (eval-after-load 'ox
839 '(dolist (backend org-export-backends)
840 (condition-case nil (require (intern (format "ox-%s" backend)))
841 (error (message "Problems while trying to load export back-end `%s'"
842 backend)))))
844 (defcustom org-support-shift-select nil
845 "Non-nil means make shift-cursor commands select text when possible.
846 \\<org-mode-map>\
848 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
849 start selecting a region, or enlarge regions started in this way.
850 In Org-mode, in special contexts, these same keys are used for
851 other purposes, important enough to compete with shift selection.
852 Org tries to balance these needs by supporting `shift-select-mode'
853 outside these special contexts, under control of this variable.
855 The default of this variable is nil, to avoid confusing behavior. Shifted
856 cursor keys will then execute Org commands in the following contexts:
857 - on a headline, changing TODO state (left/right) and priority (up/down)
858 - on a time stamp, changing the time
859 - in a plain list item, changing the bullet type
860 - in a property definition line, switching between allowed values
861 - in the BEGIN line of a clock table (changing the time block).
862 Outside these contexts, the commands will throw an error.
864 When this variable is t and the cursor is not in a special
865 context, Org mode will support shift-selection for making and
866 enlarging regions. To make this more effective, the bullet
867 cycling will no longer happen anywhere in an item line, but only
868 if the cursor is exactly on the bullet.
870 If you set this variable to the symbol `always', then the keys
871 will not be special in headlines, property lines, and item lines,
872 to make shift selection work there as well. If this is what you
873 want, you can use the following alternative commands:
874 `\\[org-todo]' and `\\[org-priority]' \
875 to change TODO state and priority,
876 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
877 can be used to switch TODO sets,
878 `\\[org-ctrl-c-minus]' to cycle item bullet types,
879 and properties can be edited by hand or in column view.
881 However, when the cursor is on a timestamp, shift-cursor commands
882 will still edit the time stamp - this is just too good to give up."
883 :group 'org
884 :type '(choice
885 (const :tag "Never" nil)
886 (const :tag "When outside special context" t)
887 (const :tag "Everywhere except timestamps" always)))
889 (defcustom org-loop-over-headlines-in-active-region nil
890 "Shall some commands act upon headlines in the active region?
892 When set to t, some commands will be performed in all headlines
893 within the active region.
895 When set to `start-level', some commands will be performed in all
896 headlines within the active region, provided that these headlines
897 are of the same level than the first one.
899 When set to a string, those commands will be performed on the
900 matching headlines within the active region. Such string must be
901 a tags/property/todo match as it is used in the agenda tags view.
903 The list of commands is: `org-schedule', `org-deadline',
904 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
905 `org-archive-to-archive-sibling'. The archiving commands skip
906 already archived entries."
907 :type '(choice (const :tag "Don't loop" nil)
908 (const :tag "All headlines in active region" t)
909 (const :tag "In active region, headlines at the same level than the first one" start-level)
910 (string :tag "Tags/Property/Todo matcher"))
911 :version "24.1"
912 :group 'org-todo
913 :group 'org-archive)
915 (defgroup org-startup nil
916 "Options concerning startup of Org-mode."
917 :tag "Org Startup"
918 :group 'org)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
922 This can also be configured on a per-file basis by adding one of
923 the following lines anywhere in the buffer:
925 #+STARTUP: fold (or `overview', this is equivalent)
926 #+STARTUP: nofold (or `showall', this is equivalent)
927 #+STARTUP: content
928 #+STARTUP: showeverything
930 By default, this option is ignored when Org opens agenda files
931 for the first time. If you want the agenda to honor the startup
932 option, set `org-agenda-inhibit-startup' to nil."
933 :group 'org-startup
934 :type '(choice
935 (const :tag "nofold: show all" nil)
936 (const :tag "fold: overview" t)
937 (const :tag "content: all headlines" content)
938 (const :tag "show everything, even drawers" showeverything)))
940 (defcustom org-startup-truncated t
941 "Non-nil means entering Org mode will set `truncate-lines'.
942 This is useful since some lines containing links can be very long and
943 uninteresting. Also tables look terrible when wrapped.
945 The variable `org-startup-truncated' allows to configure
946 truncation for Org mode different to the other modes that use the
947 variable `truncate-lines' and as a shortcut instead of putting
948 the variable `truncate-lines' into the `org-mode-hook'. If one
949 wants to configure truncation for Org mode not statically but
950 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
951 the variable `truncate-lines' has to be used because in such a
952 case it is too late to set the variable `org-startup-truncated'."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org mode.
1048 To ensure that the file will always be in Org mode in the future, a
1049 line enforcing Org mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org mode together with one of these other modes,
1060 or more generally if you would like to move some Org mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org-mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if `window-system' is nil. This
1073 variable lets you do the same manually. You must set it before
1074 loading Org."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1080 (defcustom org-disputed-keys
1081 '(([(shift up)] . [(meta p)])
1082 ([(shift down)] . [(meta n)])
1083 ([(shift left)] . [(meta -)])
1084 ([(shift right)] . [(meta +)])
1085 ([(control shift right)] . [(meta shift +)])
1086 ([(control shift left)] . [(meta shift -)]))
1087 "Keys for which Org mode and other modes compete.
1088 This is an alist, cars are the default keys, second element specifies
1089 the alternative to use when `org-replace-disputed-keys' is t.
1091 Keys can be specified in any syntax supported by `define-key'.
1092 The value of this option takes effect only at Org-mode's startup,
1093 therefore you'll have to restart Emacs to apply it after changing."
1094 :group 'org-startup
1095 :type 'alist)
1097 (defun org-key (key)
1098 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1099 Or return the original if not disputed."
1100 (when org-replace-disputed-keys
1101 (let* ((nkey (key-description key))
1102 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1103 org-disputed-keys)))
1104 (setq key (if x (cdr x) key))))
1105 key)
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org-mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((agenda . local)
1151 (bookmark-jump . lineage)
1152 (isearch . lineage)
1153 (default . ancestors))
1154 "Alist between context and visibility span when revealing a location.
1156 \\<org-mode-map>Some actions may move point into invisible
1157 locations. As a consequence, Org always expose a neighborhood
1158 around point. How much is shown depends on the initial action,
1159 or context. Valid contexts are
1161 agenda when exposing an entry from the agenda
1162 org-goto when using the command `org-goto' (\\[org-goto])
1163 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1164 tags-tree when constructing a sparse tree based on tags matches
1165 link-search when exposing search matches associated with a link
1166 mark-goto when exposing the jump goal of a mark
1167 bookmark-jump when exposing a bookmark location
1168 isearch when exiting from an incremental search
1169 default default for all contexts not set explicitly
1171 Allowed visibility spans are
1173 minimal show current headline; if point is not on headline,
1174 also show entry
1176 local show current headline, entry and next headline
1178 ancestors show current headline and its direct ancestors; if
1179 point is not on headline, also show entry
1181 lineage show current headline, its direct ancestors and all
1182 their children; if point is not on headline, also show
1183 entry and first child
1185 tree show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and all children
1189 canonical show current headline, its direct ancestors along with
1190 their entries and children; if point is not located on
1191 the headline, also show current entry and all children
1193 As special cases, a nil or t value means show all contexts in
1194 `minimal' or `canonical' view, respectively.
1196 Some views can make displayed information very compact, but also
1197 make it harder to edit the location of the match. In such
1198 a case, use the command `org-reveal' (\\[org-reveal]) to show
1199 more context."
1200 :group 'org-reveal-location
1201 :version "25.2"
1202 :package-version '(Org . "9.0")
1203 :type '(choice
1204 (const :tag "Canonical" t)
1205 (const :tag "Minimal" nil)
1206 (repeat :greedy t :tag "Individual contexts"
1207 (cons
1208 (choice :tag "Context"
1209 (const agenda)
1210 (const org-goto)
1211 (const occur-tree)
1212 (const tags-tree)
1213 (const link-search)
1214 (const mark-goto)
1215 (const bookmark-jump)
1216 (const isearch)
1217 (const default))
1218 (choice :tag "Detail level"
1219 (const minimal)
1220 (const local)
1221 (const ancestors)
1222 (const lineage)
1223 (const tree)
1224 (const canonical))))))
1226 (defcustom org-indirect-buffer-display 'other-window
1227 "How should indirect tree buffers be displayed?
1228 This applies to indirect buffers created with the commands
1229 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1230 Valid values are:
1231 current-window Display in the current window
1232 other-window Just display in another window.
1233 dedicated-frame Create one new frame, and re-use it each time.
1234 new-frame Make a new frame each time. Note that in this case
1235 previously-made indirect buffers are kept, and you need to
1236 kill these buffers yourself."
1237 :group 'org-structure
1238 :group 'org-agenda-windows
1239 :type '(choice
1240 (const :tag "In current window" current-window)
1241 (const :tag "In current frame, other window" other-window)
1242 (const :tag "Each time a new frame" new-frame)
1243 (const :tag "One dedicated frame" dedicated-frame)))
1245 (defcustom org-use-speed-commands nil
1246 "Non-nil means activate single letter commands at beginning of a headline.
1247 This may also be a function to test for appropriate locations where speed
1248 commands should be active.
1250 For example, to activate speed commands when the point is on any
1251 star at the beginning of the headline, you can do this:
1253 (setq org-use-speed-commands
1254 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1255 :group 'org-structure
1256 :type '(choice
1257 (const :tag "Never" nil)
1258 (const :tag "At beginning of headline stars" t)
1259 (function)))
1261 (defcustom org-speed-commands-user nil
1262 "Alist of additional speed commands.
1263 This list will be checked before `org-speed-commands-default'
1264 when the variable `org-use-speed-commands' is non-nil
1265 and when the cursor is at the beginning of a headline.
1266 The car if each entry is a string with a single letter, which must
1267 be assigned to `self-insert-command' in the global map.
1268 The cdr is either a command to be called interactively, a function
1269 to be called, or a form to be evaluated.
1270 An entry that is just a list with a single string will be interpreted
1271 as a descriptive headline that will be added when listing the speed
1272 commands in the Help buffer using the `?' speed command."
1273 :group 'org-structure
1274 :type '(repeat :value ("k" . ignore)
1275 (choice :value ("k" . ignore)
1276 (list :tag "Descriptive Headline" (string :tag "Headline"))
1277 (cons :tag "Letter and Command"
1278 (string :tag "Command letter")
1279 (choice
1280 (function)
1281 (sexp))))))
1283 (defcustom org-bookmark-names-plist
1284 '(:last-capture "org-capture-last-stored"
1285 :last-refile "org-refile-last-stored"
1286 :last-capture-marker "org-capture-last-stored-marker")
1287 "Names for bookmarks automatically set by some Org commands.
1288 This can provide strings as names for a number of bookmarks Org sets
1289 automatically. The following keys are currently implemented:
1290 :last-capture
1291 :last-capture-marker
1292 :last-refile
1293 When a key does not show up in the property list, the corresponding bookmark
1294 is not set."
1295 :group 'org-structure
1296 :type 'plist)
1298 (defgroup org-cycle nil
1299 "Options concerning visibility cycling in Org-mode."
1300 :tag "Org Cycle"
1301 :group 'org-structure)
1303 (defcustom org-cycle-skip-children-state-if-no-children t
1304 "Non-nil means skip CHILDREN state in entries that don't have any."
1305 :group 'org-cycle
1306 :type 'boolean)
1308 (defcustom org-cycle-max-level nil
1309 "Maximum level which should still be subject to visibility cycling.
1310 Levels higher than this will, for cycling, be treated as text, not a headline.
1311 When `org-odd-levels-only' is set, a value of N in this variable actually
1312 means 2N-1 stars as the limiting headline.
1313 When nil, cycle all levels.
1314 Note that the limiting level of cycling is also influenced by
1315 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1316 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1317 than its value."
1318 :group 'org-cycle
1319 :type '(choice
1320 (const :tag "No limit" nil)
1321 (integer :tag "Maximum level")))
1323 (defcustom org-hide-block-startup nil
1324 "Non-nil means entering Org mode will fold all blocks.
1325 This can also be set in on a per-file basis with
1327 #+STARTUP: hideblocks
1328 #+STARTUP: showblocks"
1329 :group 'org-startup
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-global-at-bob nil
1334 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1335 This makes it possible to do global cycling without having to use S-TAB or
1336 \\[universal-argument] TAB. For this special case to work, the first line
1337 of the buffer must not be a headline -- it may be empty or some other text.
1338 When used in this way, `org-cycle-hook' is disabled temporarily to make
1339 sure the cursor stays at the beginning of the buffer. When this option is
1340 nil, don't do anything special at the beginning of the buffer."
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-level-after-item/entry-creation t
1345 "Non-nil means cycle entry level or item indentation in new empty entries.
1347 When the cursor is at the end of an empty headline, i.e., with only stars
1348 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1349 and then all possible ancestor states, before returning to the original state.
1350 This makes data entry extremely fast: M-RET to create a new headline,
1351 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1353 When the cursor is at the end of an empty plain list item, one TAB will
1354 make it a subitem, two or more tabs will back up to make this an item
1355 higher up in the item hierarchy."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-emulate-tab t
1360 "Where should `org-cycle' emulate TAB.
1361 nil Never
1362 white Only in completely white lines
1363 whitestart Only at the beginning of lines, before the first non-white char
1364 t Everywhere except in headlines
1365 exc-hl-bol Everywhere except at the start of a headline
1366 If TAB is used in a place where it does not emulate TAB, the current subtree
1367 visibility is cycled."
1368 :group 'org-cycle
1369 :type '(choice (const :tag "Never" nil)
1370 (const :tag "Only in completely white lines" white)
1371 (const :tag "Before first char in a line" whitestart)
1372 (const :tag "Everywhere except in headlines" t)
1373 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1375 (defcustom org-cycle-separator-lines 2
1376 "Number of empty lines needed to keep an empty line between collapsed trees.
1377 If you leave an empty line between the end of a subtree and the following
1378 headline, this empty line is hidden when the subtree is folded.
1379 Org mode will leave (exactly) one empty line visible if the number of
1380 empty lines is equal or larger to the number given in this variable.
1381 So the default 2 means at least 2 empty lines after the end of a subtree
1382 are needed to produce free space between a collapsed subtree and the
1383 following headline.
1385 If the number is negative, and the number of empty lines is at least -N,
1386 all empty lines are shown.
1388 Special case: when 0, never leave empty lines in collapsed view."
1389 :group 'org-cycle
1390 :type 'integer)
1391 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1393 (defcustom org-pre-cycle-hook nil
1394 "Hook that is run before visibility cycling is happening.
1395 The function(s) in this hook must accept a single argument which indicates
1396 the new state that will be set right after running this hook. The
1397 argument is a symbol. Before a global state change, it can have the values
1398 `overview', `content', or `all'. Before a local state change, it can have
1399 the values `folded', `children', or `subtree'."
1400 :group 'org-cycle
1401 :type 'hook)
1403 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1404 org-cycle-hide-drawers
1405 org-cycle-show-empty-lines
1406 org-optimize-window-after-visibility-change)
1407 "Hook that is run after `org-cycle' has changed the buffer visibility.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that was set by the most recent `org-cycle' command. The
1410 argument is a symbol. After a global state change, it can have the values
1411 `overview', `contents', or `all'. After a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook
1415 :version "25.1"
1416 :package-version '(Org . "8.3"))
1418 (defgroup org-edit-structure nil
1419 "Options concerning structure editing in Org-mode."
1420 :tag "Org Edit Structure"
1421 :group 'org-structure)
1423 (defcustom org-odd-levels-only nil
1424 "Non-nil means skip even levels and only use odd levels for the outline.
1425 This has the effect that two stars are being added/taken away in
1426 promotion/demotion commands. It also influences how levels are
1427 handled by the exporters.
1428 Changing it requires restart of `font-lock-mode' to become effective
1429 for fontification also in regions already fontified.
1430 You may also set this on a per-file basis by adding one of the following
1431 lines to the buffer:
1433 #+STARTUP: odd
1434 #+STARTUP: oddeven"
1435 :group 'org-edit-structure
1436 :group 'org-appearance
1437 :type 'boolean)
1439 (defcustom org-adapt-indentation t
1440 "Non-nil means adapt indentation to outline node level.
1442 When this variable is set, Org assumes that you write outlines by
1443 indenting text in each node to align with the headline (after the
1444 stars). The following issues are influenced by this variable:
1446 - The indentation is increased by one space in a demotion
1447 command, and decreased by one in a promotion command. However,
1448 in the latter case, if shifting some line in the entry body
1449 would alter document structure (e.g., insert a new headline),
1450 indentation is not changed at all.
1452 - Property drawers and planning information is inserted indented
1453 when this variable is set. When nil, they will not be indented.
1455 - TAB indents a line relative to current level. The lines below
1456 a headline will be indented when this variable is set.
1458 Note that this is all about true indentation, by adding and
1459 removing space characters. See also `org-indent.el' which does
1460 level-dependent indentation in a virtual way, i.e. at display
1461 time in Emacs."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-special-ctrl-a/e nil
1466 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1468 When t, `C-a' will bring back the cursor to the beginning of the
1469 headline text, i.e. after the stars and after a possible TODO
1470 keyword. In an item, this will be the position after bullet and
1471 check-box, if any. When the cursor is already at that position,
1472 another `C-a' will bring it to the beginning of the line.
1474 `C-e' will jump to the end of the headline, ignoring the presence
1475 of tags in the headline. A second `C-e' will then jump to the
1476 true end of the line, after any tags. This also means that, when
1477 this variable is non-nil, `C-e' also will never jump beyond the
1478 end of the heading of a folded section, i.e. not after the
1479 ellipses.
1481 When set to the symbol `reversed', the first `C-a' or `C-e' works
1482 normally, going to the true line boundary first. Only a directly
1483 following, identical keypress will bring the cursor to the
1484 special positions.
1486 This may also be a cons cell where the behavior for `C-a' and
1487 `C-e' is set separately."
1488 :group 'org-edit-structure
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on: after stars/bullet and before tags first" t)
1492 (const :tag "reversed: true line boundary first" reversed)
1493 (cons :tag "Set C-a and C-e separately"
1494 (choice :tag "Special C-a"
1495 (const :tag "off" nil)
1496 (const :tag "on: after stars/bullet first" t)
1497 (const :tag "reversed: before stars/bullet first" reversed))
1498 (choice :tag "Special C-e"
1499 (const :tag "off" nil)
1500 (const :tag "on: before tags first" t)
1501 (const :tag "reversed: after tags first" reversed)))))
1502 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1504 (defcustom org-special-ctrl-k nil
1505 "Non-nil means `C-k' will behave specially in headlines.
1506 When nil, `C-k' will call the default `kill-line' command.
1507 When t, the following will happen while the cursor is in the headline:
1509 - When the cursor is at the beginning of a headline, kill the entire
1510 line and possible the folded subtree below the line.
1511 - When in the middle of the headline text, kill the headline up to the tags.
1512 - When after the headline text, kill the tags."
1513 :group 'org-edit-structure
1514 :type 'boolean)
1516 (defcustom org-ctrl-k-protect-subtree nil
1517 "Non-nil means, do not delete a hidden subtree with C-k.
1518 When set to the symbol `error', simply throw an error when C-k is
1519 used to kill (part-of) a headline that has hidden text behind it.
1520 Any other non-nil value will result in a query to the user, if it is
1521 OK to kill that hidden subtree. When nil, kill without remorse."
1522 :group 'org-edit-structure
1523 :version "24.1"
1524 :type '(choice
1525 (const :tag "Do not protect hidden subtrees" nil)
1526 (const :tag "Protect hidden subtrees with a security query" t)
1527 (const :tag "Never kill a hidden subtree with C-k" error)))
1529 (defcustom org-special-ctrl-o t
1530 "Non-nil means, make `C-o' insert a row in tables."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-catch-invisible-edits nil
1535 "Check if in invisible region before inserting or deleting a character.
1536 Valid values are:
1538 nil Do not check, so just do invisible edits.
1539 error Throw an error and do nothing.
1540 show Make point visible, and do the requested edit.
1541 show-and-error Make point visible, then throw an error and abort the edit.
1542 smart Make point visible, and do insertion/deletion if it is
1543 adjacent to visible text and the change feels predictable.
1544 Never delete a previously invisible character or add in the
1545 middle or right after an invisible region. Basically, this
1546 allows insertion and backward-delete right before ellipses.
1547 FIXME: maybe in this case we should not even show?"
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not check" nil)
1552 (const :tag "Throw error when trying to edit" error)
1553 (const :tag "Unhide, but do not do the edit" show-and-error)
1554 (const :tag "Show invisible part and do the edit" show)
1555 (const :tag "Be smart and do the right thing" smart)))
1557 (defcustom org-yank-folded-subtrees t
1558 "Non-nil means when yanking subtrees, fold them.
1559 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1560 it starts with a heading and all other headings in it are either children
1561 or siblings, then fold all the subtrees. However, do this only if no
1562 text after the yank would be swallowed into a folded tree by this action."
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defcustom org-yank-adjusted-subtrees nil
1567 "Non-nil means when yanking subtrees, adjust the level.
1568 With this setting, `org-paste-subtree' is used to insert the subtree, see
1569 this function for details."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-M-RET-may-split-line '((default . t))
1574 "Non-nil means M-RET will split the line at the cursor position.
1575 When nil, it will go to the end of the line before making a
1576 new line.
1577 You may also set this option in a different way for different
1578 contexts. Valid contexts are:
1580 headline when creating a new headline
1581 item when creating a new item
1582 table in a table field
1583 default the value to be used for all contexts not explicitly
1584 customized"
1585 :group 'org-structure
1586 :group 'org-table
1587 :type '(choice
1588 (const :tag "Always" t)
1589 (const :tag "Never" nil)
1590 (repeat :greedy t :tag "Individual contexts"
1591 (cons
1592 (choice :tag "Context"
1593 (const headline)
1594 (const item)
1595 (const table)
1596 (const default))
1597 (boolean)))))
1600 (defcustom org-insert-heading-respect-content nil
1601 "Non-nil means insert new headings after the current subtree.
1602 When nil, the new heading is created directly after the current line.
1603 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1604 this variable on for the duration of the command."
1605 :group 'org-structure
1606 :type 'boolean)
1608 (defcustom org-blank-before-new-entry '((heading . auto)
1609 (plain-list-item . auto))
1610 "Should `org-insert-heading' leave a blank line before new heading/item?
1611 The value is an alist, with `heading' and `plain-list-item' as CAR,
1612 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1613 which case Org will look at the surrounding headings/items and try to
1614 make an intelligent decision whether to insert a blank line or not."
1615 :group 'org-edit-structure
1616 :type '(list
1617 (cons (const heading)
1618 (choice (const :tag "Never" nil)
1619 (const :tag "Always" t)
1620 (const :tag "Auto" auto)))
1621 (cons (const plain-list-item)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))))
1626 (defcustom org-insert-heading-hook nil
1627 "Hook being run after inserting a new heading."
1628 :group 'org-edit-structure
1629 :type 'hook)
1631 (defcustom org-enable-fixed-width-editor t
1632 "Non-nil means lines starting with \":\" are treated as fixed-width.
1633 This currently only means they are never auto-wrapped.
1634 When nil, such lines will be treated like ordinary lines."
1635 :group 'org-edit-structure
1636 :type 'boolean)
1638 (defcustom org-goto-auto-isearch t
1639 "Non-nil means typing characters in `org-goto' starts incremental search.
1640 When nil, you can use these keybindings to navigate the buffer:
1642 q Quit the org-goto interface
1643 n Go to the next visible heading
1644 p Go to the previous visible heading
1645 f Go one heading forward on same level
1646 b Go one heading backward on same level
1647 u Go one heading up"
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defgroup org-sparse-trees nil
1652 "Options concerning sparse trees in Org-mode."
1653 :tag "Org Sparse Trees"
1654 :group 'org-structure)
1656 (defcustom org-highlight-sparse-tree-matches t
1657 "Non-nil means highlight all matches that define a sparse tree.
1658 The highlights will automatically disappear the next time the buffer is
1659 changed by an edit command."
1660 :group 'org-sparse-trees
1661 :type 'boolean)
1663 (defcustom org-remove-highlights-with-change t
1664 "Non-nil means any change to the buffer will remove temporary highlights.
1665 \\<org-mode-map>\
1666 Such highlights are created by `org-occur' and `org-clock-display'.
1667 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1668 to get rid of the highlights.
1669 The highlights created by `org-toggle-latex-fragment' always need
1670 `\\[org-toggle-latex-fragment]' to be removed."
1671 :group 'org-sparse-trees
1672 :group 'org-time
1673 :type 'boolean)
1675 (defcustom org-occur-case-fold-search t
1676 "Non-nil means `org-occur' should be case-insensitive.
1677 If set to `smart' the search will be case-insensitive only if it
1678 doesn't specify any upper case character."
1679 :group 'org-sparse-trees
1680 :version "25.1"
1681 :type '(choice
1682 (const :tag "Case-sensitive" nil)
1683 (const :tag "Case-insensitive" t)
1684 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1686 (defcustom org-occur-hook '(org-first-headline-recenter)
1687 "Hook that is run after `org-occur' has constructed a sparse tree.
1688 This can be used to recenter the window to show as much of the structure
1689 as possible."
1690 :group 'org-sparse-trees
1691 :type 'hook)
1693 (defgroup org-imenu-and-speedbar nil
1694 "Options concerning imenu and speedbar in Org-mode."
1695 :tag "Org Imenu and Speedbar"
1696 :group 'org-structure)
1698 (defcustom org-imenu-depth 2
1699 "The maximum level for Imenu access to Org headlines.
1700 This also applied for speedbar access."
1701 :group 'org-imenu-and-speedbar
1702 :type 'integer)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org-mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-enable-table-editor 'optimized
1710 "Non-nil means lines starting with \"|\" are handled by the table editor.
1711 When nil, such lines will be treated like ordinary lines.
1713 When equal to the symbol `optimized', the table editor will be optimized to
1714 do the following:
1715 - Automatic overwrite mode in front of whitespace in table fields.
1716 This makes the structure of the table stay in tact as long as the edited
1717 field does not exceed the column width.
1718 - Minimize the number of realigns. Normally, the table is aligned each time
1719 TAB or RET are pressed to move to another field. With optimization this
1720 happens only if changes to a field might have changed the column width.
1721 Optimization requires replacing the functions `self-insert-command',
1722 `delete-char', and `backward-delete-char' in Org buffers, with a
1723 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1724 good at guessing when a re-align will be necessary, but you can always
1725 force one with \\[org-ctrl-c-ctrl-c].
1727 If you would like to use the optimized version in Org-mode, but the
1728 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1730 This variable can be used to turn on and off the table editor during a session,
1731 but in order to toggle optimization, a restart is required.
1733 See also the variable `org-table-auto-blank-field'."
1734 :group 'org-table
1735 :type '(choice
1736 (const :tag "off" nil)
1737 (const :tag "on" t)
1738 (const :tag "on, optimized" optimized)))
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org-mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-parameters
1765 '(("doi" :follow org--open-doi-link)
1766 ("elisp" :follow org--open-elisp-link)
1767 ("file" :complete org-file-complete-link)
1768 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1769 ("help" :follow org--open-help-link)
1770 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1771 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1772 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1773 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1774 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1775 ("shell" :follow org--open-shell-link))
1776 "An alist of properties that defines all the links in Org mode.
1777 The key in each association is a string of the link type.
1778 Subsequent optional elements make up a p-list of link properties.
1780 :follow - A function that takes the link path as an argument.
1782 :export - A function that takes the link path, description and
1783 export-backend as arguments.
1785 :store - A function responsible for storing the link. See the
1786 function `org-store-link-functions'.
1788 :complete - A function that inserts a link with completion. The
1789 function takes one optional prefix arg.
1791 :face - A face for the link, or a function that returns a face.
1792 The function takes one argument which is the link path. The
1793 default face is `org-link'.
1795 :mouse-face - The mouse-face. The default is `highlight'.
1797 :display - `full' will not fold the link in descriptive
1798 display. Default is `org-link'.
1800 :help-echo - A string or function that takes (window object position)
1801 as arguments and returns a string.
1803 :keymap - A keymap that is active on the link. The default is
1804 `org-mouse-map'.
1806 :htmlize-link - A function for the htmlize-link. Defaults
1807 to (list :uri \"type:path\")
1809 :activate-func - A function to run at the end of font-lock
1810 activation. The function must accept (link-start link-end path bracketp)
1811 as arguments."
1812 :group 'org-link
1813 :type '(alist :tag "Link display parameters"
1814 :value-type plist))
1816 (defun org-link-get-parameter (type key)
1817 "Get TYPE link property for KEY.
1818 TYPE is a string and KEY is a plist keyword."
1819 (plist-get
1820 (cdr (assoc type org-link-parameters))
1821 key))
1823 (defun org-link-set-parameters (type &rest parameters)
1824 "Set link TYPE properties to PARAMETERS.
1825 PARAMETERS should be :key val pairs."
1826 (let ((data (assoc type org-link-parameters)))
1827 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1828 (push (cons type parameters) org-link-parameters)
1829 (org-make-link-regexps)
1830 (org-element-update-syntax))))
1832 (defun org-link-types ()
1833 "Return a list of known link types."
1834 (mapcar #'car org-link-parameters))
1836 (defcustom org-link-abbrev-alist nil
1837 "Alist of link abbreviations.
1838 The car of each element is a string, to be replaced at the start of a link.
1839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1840 links in Org buffers can have an optional tag after a double colon, e.g.,
1842 [[linkkey:tag][description]]
1844 The `linkkey' must be a single word, starting with a letter, followed
1845 by letters, numbers, `-' or `_'.
1847 If REPLACE is a string, the tag will simply be appended to create the link.
1848 If the string contains \"%s\", the tag will be inserted there. If the string
1849 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1850 at that point (see the function `url-hexify-string'). If the string contains
1851 the specifier \"%(my-function)\", then the custom function `my-function' will
1852 be invoked: this function takes the tag as its only argument and must return
1853 a string.
1855 REPLACE may also be a function that will be called with the tag as the
1856 only argument to create the link, which should be returned as a string.
1858 See the manual for examples."
1859 :group 'org-link
1860 :type '(repeat
1861 (cons
1862 (string :tag "Protocol")
1863 (choice
1864 (string :tag "Format")
1865 (function)))))
1867 (defcustom org-descriptive-links t
1868 "Non-nil means Org will display descriptive links.
1869 E.g. [[http://orgmode.org][Org website]] will be displayed as
1870 \"Org Website\", hiding the link itself and just displaying its
1871 description. When set to nil, Org will display the full links
1872 literally.
1874 You can interactively set the value of this variable by calling
1875 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1876 :group 'org-link
1877 :type 'boolean)
1879 (defcustom org-link-file-path-type 'adaptive
1880 "How the path name in file links should be stored.
1881 Valid values are:
1883 relative Relative to the current directory, i.e. the directory of the file
1884 into which the link is being inserted.
1885 absolute Absolute path, if possible with ~ for home directory.
1886 noabbrev Absolute path, no abbreviation of home directory.
1887 adaptive Use relative path for files in the current directory and sub-
1888 directories of it. For other files, use an absolute path."
1889 :group 'org-link
1890 :type '(choice
1891 (const relative)
1892 (const absolute)
1893 (const noabbrev)
1894 (const adaptive)))
1896 (defvaralias 'org-activate-links 'org-highlight-links)
1897 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1898 "Types of links that should be highlighted in Org files.
1900 This is a list of symbols, each one of them leading to the
1901 highlighting of a certain link type.
1903 You can still open links that are not highlighted.
1905 In principle, it does not hurt to turn on highlighting for all
1906 link types. There may be a small gain when turning off unused
1907 link types. The types are:
1909 bracket The recommended [[link][description]] or [[link]] links with hiding.
1910 angle Links in angular brackets that may contain whitespace like
1911 <bbdb:Carsten Dominik>.
1912 plain Plain links in normal text, no whitespace, like http://google.com.
1913 radio Text that is matched by a radio target, see manual for details.
1914 tag Tag settings in a headline (link to tag search).
1915 date Time stamps (link to calendar).
1916 footnote Footnote labels.
1918 If you set this variable during an Emacs session, use `org-mode-restart'
1919 in the Org buffer so that the change takes effect."
1920 :group 'org-link
1921 :group 'org-appearance
1922 :type '(set :greedy t
1923 (const :tag "Double bracket links" bracket)
1924 (const :tag "Angular bracket links" angle)
1925 (const :tag "Plain text links" plain)
1926 (const :tag "Radio target matches" radio)
1927 (const :tag "Tags" tag)
1928 (const :tag "Timestamps" date)
1929 (const :tag "Footnotes" footnote)))
1931 (defcustom org-make-link-description-function nil
1932 "Function to use for generating link descriptions from links.
1933 When nil, the link location will be used. This function must take
1934 two parameters: the first one is the link, the second one is the
1935 description generated by `org-insert-link'. The function should
1936 return the description to use."
1937 :group 'org-link
1938 :type '(choice (const nil) (function)))
1940 (defgroup org-link-store nil
1941 "Options concerning storing links in Org-mode."
1942 :tag "Org Store Link"
1943 :group 'org-link)
1945 (defcustom org-url-hexify-p t
1946 "When non-nil, hexify URL when creating a link."
1947 :type 'boolean
1948 :version "24.3"
1949 :group 'org-link-store)
1951 (defcustom org-email-link-description-format "Email %c: %.30s"
1952 "Format of the description part of a link to an email or usenet message.
1953 The following %-escapes will be replaced by corresponding information:
1955 %F full \"From\" field
1956 %f name, taken from \"From\" field, address if no name
1957 %T full \"To\" field
1958 %t first name in \"To\" field, address if no name
1959 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1960 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1961 %s subject
1962 %d date
1963 %m message-id.
1965 You may use normal field width specification between the % and the letter.
1966 This is for example useful to limit the length of the subject.
1968 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1969 :group 'org-link-store
1970 :type 'string)
1972 (defcustom org-from-is-user-regexp
1973 (let (r1 r2)
1974 (when (and user-mail-address (not (string= user-mail-address "")))
1975 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1976 (when (and user-full-name (not (string= user-full-name "")))
1977 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1978 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1979 "Regexp matched against the \"From:\" header of an email or usenet message.
1980 It should match if the message is from the user him/herself."
1981 :group 'org-link-store
1982 :type 'regexp)
1984 (defcustom org-context-in-file-links t
1985 "Non-nil means file links from `org-store-link' contain context.
1986 A search string will be added to the file name with :: as separator and
1987 used to find the context when the link is activated by the command
1988 `org-open-at-point'. When this option is t, the entire active region
1989 will be placed in the search string of the file link. If set to a
1990 positive integer, only the first n lines of context will be stored.
1992 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1993 negates this setting for the duration of the command."
1994 :group 'org-link-store
1995 :type '(choice boolean integer))
1997 (defcustom org-keep-stored-link-after-insertion nil
1998 "Non-nil means keep link in list for entire session.
2000 The command `org-store-link' adds a link pointing to the current
2001 location to an internal list. These links accumulate during a session.
2002 The command `org-insert-link' can be used to insert links into any
2003 Org file (offering completion for all stored links). When this option
2004 is nil, every link which has been inserted once using \\[org-insert-link]
2005 will be removed from the list, to make completing the unused links
2006 more efficient."
2007 :group 'org-link-store
2008 :type 'boolean)
2010 (defgroup org-link-follow nil
2011 "Options concerning following links in Org-mode."
2012 :tag "Org Follow Link"
2013 :group 'org-link)
2015 (defcustom org-link-translation-function nil
2016 "Function to translate links with different syntax to Org syntax.
2017 This can be used to translate links created for example by the Planner
2018 or emacs-wiki packages to Org syntax.
2019 The function must accept two parameters, a TYPE containing the link
2020 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2021 which is everything after the link protocol. It should return a cons
2022 with possibly modified values of type and path.
2023 Org contains a function for this, so if you set this variable to
2024 `org-translate-link-from-planner', you should be able follow many
2025 links created by planner."
2026 :group 'org-link-follow
2027 :type '(choice (const nil) (function)))
2029 (defcustom org-follow-link-hook nil
2030 "Hook that is run after a link has been followed."
2031 :group 'org-link-follow
2032 :type 'hook)
2034 (defcustom org-tab-follows-link nil
2035 "Non-nil means on links TAB will follow the link.
2036 Needs to be set before org.el is loaded.
2037 This really should not be used, it does not make sense, and the
2038 implementation is bad."
2039 :group 'org-link-follow
2040 :type 'boolean)
2042 (defcustom org-return-follows-link nil
2043 "Non-nil means on links RET will follow the link.
2044 In tables, the special behavior of RET has precedence."
2045 :group 'org-link-follow
2046 :type 'boolean)
2048 (defcustom org-mouse-1-follows-link
2049 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2050 "Non-nil means mouse-1 on a link will follow the link.
2051 A longer mouse click will still set point. Needs to be set
2052 before org.el is loaded."
2053 :group 'org-link-follow
2054 :version "24.4"
2055 :package-version '(Org . "8.3")
2056 :type '(choice
2057 (const :tag "A double click follows the link" double)
2058 (const :tag "Unconditionally follow the link with mouse-1" t)
2059 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2061 (defcustom org-mark-ring-length 4
2062 "Number of different positions to be recorded in the ring.
2063 Changing this requires a restart of Emacs to work correctly."
2064 :group 'org-link-follow
2065 :type 'integer)
2067 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2068 "Non-nil means internal links in Org files must exactly match a headline.
2069 When nil, the link search tries to match a phrase with all words
2070 in the search text."
2071 :group 'org-link-follow
2072 :version "24.1"
2073 :type '(choice
2074 (const :tag "Use fuzzy text search" nil)
2075 (const :tag "Match only exact headline" t)
2076 (const :tag "Match exact headline or query to create it"
2077 query-to-create)))
2079 (defcustom org-link-frame-setup
2080 '((vm . vm-visit-folder-other-frame)
2081 (vm-imap . vm-visit-imap-folder-other-frame)
2082 (gnus . org-gnus-no-new-news)
2083 (file . find-file-other-window)
2084 (wl . wl-other-frame))
2085 "Setup the frame configuration for following links.
2086 When following a link with Emacs, it may often be useful to display
2087 this link in another window or frame. This variable can be used to
2088 set this up for the different types of links.
2089 For VM, use any of
2090 `vm-visit-folder'
2091 `vm-visit-folder-other-window'
2092 `vm-visit-folder-other-frame'
2093 For Gnus, use any of
2094 `gnus'
2095 `gnus-other-frame'
2096 `org-gnus-no-new-news'
2097 For FILE, use any of
2098 `find-file'
2099 `find-file-other-window'
2100 `find-file-other-frame'
2101 For Wanderlust use any of
2102 `wl'
2103 `wl-other-frame'
2104 For the calendar, use the variable `calendar-setup'.
2105 For BBDB, it is currently only possible to display the matches in
2106 another window."
2107 :group 'org-link-follow
2108 :type '(list
2109 (cons (const vm)
2110 (choice
2111 (const vm-visit-folder)
2112 (const vm-visit-folder-other-window)
2113 (const vm-visit-folder-other-frame)))
2114 (cons (const vm-imap)
2115 (choice
2116 (const vm-visit-imap-folder)
2117 (const vm-visit-imap-folder-other-window)
2118 (const vm-visit-imap-folder-other-frame)))
2119 (cons (const gnus)
2120 (choice
2121 (const gnus)
2122 (const gnus-other-frame)
2123 (const org-gnus-no-new-news)))
2124 (cons (const file)
2125 (choice
2126 (const find-file)
2127 (const find-file-other-window)
2128 (const find-file-other-frame)))
2129 (cons (const wl)
2130 (choice
2131 (const wl)
2132 (const wl-other-frame)))))
2134 (defcustom org-display-internal-link-with-indirect-buffer nil
2135 "Non-nil means use indirect buffer to display infile links.
2136 Activating internal links (from one location in a file to another location
2137 in the same file) normally just jumps to the location. When the link is
2138 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2139 is displayed in
2140 another window. When this option is set, the other window actually displays
2141 an indirect buffer clone of the current buffer, to avoid any visibility
2142 changes to the current buffer."
2143 :group 'org-link-follow
2144 :type 'boolean)
2146 (defcustom org-open-non-existing-files nil
2147 "Non-nil means `org-open-file' will open non-existing files.
2148 When nil, an error will be generated.
2149 This variable applies only to external applications because they
2150 might choke on non-existing files. If the link is to a file that
2151 will be opened in Emacs, the variable is ignored."
2152 :group 'org-link-follow
2153 :type 'boolean)
2155 (defcustom org-open-directory-means-index-dot-org nil
2156 "Non-nil means a link to a directory really means to index.org.
2157 When nil, following a directory link will run dired or open a finder/explorer
2158 window on that directory."
2159 :group 'org-link-follow
2160 :type 'boolean)
2162 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing shell links.
2164 Shell links can be dangerous: just think about a link
2166 [[shell:rm -rf ~/*][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-shell-link-not-regexp ""
2183 "A regexp to skip confirmation for shell links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2189 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2190 Elisp links can be dangerous: just think about a link
2192 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2194 This link would show up in your Org document as \"Google Search\",
2195 but really it would remove your entire home directory.
2196 Therefore we advise against setting this variable to nil.
2197 Just change it to `y-or-n-p' if you want to confirm with a
2198 single keystroke rather than having to type \"yes\"."
2199 :group 'org-link-follow
2200 :type '(choice
2201 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2202 (const :tag "with y-or-n (faster)" y-or-n-p)
2203 (const :tag "no confirmation (dangerous)" nil)))
2204 (put 'org-confirm-shell-link-function
2205 'safe-local-variable
2206 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2208 (defcustom org-confirm-elisp-link-not-regexp ""
2209 "A regexp to skip confirmation for Elisp links."
2210 :group 'org-link-follow
2211 :version "24.1"
2212 :type 'regexp)
2214 (defconst org-file-apps-defaults-gnu
2215 '((remote . emacs)
2216 (system . mailcap)
2217 (t . mailcap))
2218 "Default file applications on a UNIX or GNU/Linux system.
2219 See `org-file-apps'.")
2221 (defconst org-file-apps-defaults-macosx
2222 '((remote . emacs)
2223 (system . "open %s")
2224 ("ps.gz" . "gv %s")
2225 ("eps.gz" . "gv %s")
2226 ("dvi" . "xdvi %s")
2227 ("fig" . "xfig %s")
2228 (t . "open %s"))
2229 "Default file applications on a MacOS X system.
2230 The system \"open\" is known as a default, but we use X11 applications
2231 for some files for which the OS does not have a good default.
2232 See `org-file-apps'.")
2234 (defconst org-file-apps-defaults-windowsnt
2235 (list '(remote . emacs)
2236 (cons 'system (lambda (file _path)
2237 (with-no-warnings (w32-shell-execute "open" file))))
2238 (cons t (lambda (file _path)
2239 (with-no-warnings (w32-shell-execute "open" file)))))
2240 "Default file applications on a Windows NT system.
2241 The system \"open\" is used for most files.
2242 See `org-file-apps'.")
2244 (defcustom org-file-apps
2245 '((auto-mode . emacs)
2246 ("\\.mm\\'" . default)
2247 ("\\.x?html?\\'" . default)
2248 ("\\.pdf\\'" . default))
2249 "External applications for opening `file:path' items in a document.
2250 \\<org-mode-map>\
2252 Org mode uses system defaults for different file types, but
2253 you can use this variable to set the application for a given file
2254 extension. The entries in this list are cons cells where the car identifies
2255 files and the cdr the corresponding command.
2257 Possible values for the file identifier are:
2259 \"string\" A string as a file identifier can be interpreted in different
2260 ways, depending on its contents:
2262 - Alphanumeric characters only:
2263 Match links with this file extension.
2264 Example: (\"pdf\" . \"evince %s\")
2265 to open PDFs with evince.
2267 - Regular expression: Match links where the
2268 filename matches the regexp. If you want to
2269 use groups here, use shy groups.
2271 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2272 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2273 to open *.html and *.xhtml with firefox.
2275 - Regular expression which contains (non-shy) groups:
2276 Match links where the whole link, including \"::\", and
2277 anything after that, matches the regexp.
2278 In a custom command string, %1, %2, etc. are replaced with
2279 the parts of the link that were matched by the groups.
2280 For backwards compatibility, if a command string is given
2281 that does not use any of the group matches, this case is
2282 handled identically to the second one (i.e. match against
2283 file name only).
2284 In a custom function, you can access the group matches with
2285 \(match-string n link).
2287 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2288 \"evince -p %1 %s\")
2289 to open [[file:document.pdf::5]] with evince at page 5.
2291 `directory' Matches a directory
2292 `remote' Matches a remote file, accessible through tramp or efs.
2293 Remote files most likely should be visited through Emacs
2294 because external applications cannot handle such paths.
2295 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2296 so all files Emacs knows how to handle. Using this with
2297 command `emacs' will open most files in Emacs. Beware that this
2298 will also open html files inside Emacs, unless you add
2299 \(\"html\" . default) to the list as well.
2300 `system' The system command to open files, like `open' on Windows
2301 and Mac OS X, and mailcap under GNU/Linux. This is the command
2302 that will be selected if you call \\[org-open-at-point] with a double
2303 \\[universal-argument] \\[universal-argument] prefix.
2304 t Default for files not matched by any of the other options.
2306 Possible values for the command are:
2308 `emacs' The file will be visited by the current Emacs process.
2309 `default' Use the default application for this file type, which is the
2310 association for t in the list, most likely in the system-specific
2311 part. This can be used to overrule an unwanted setting in the
2312 system-specific variable.
2313 `system' Use the system command for opening files, like \"open\".
2314 This command is specified by the entry whose car is `system'.
2315 Most likely, the system-specific version of this variable
2316 does define this command, but you can overrule/replace it
2317 here.
2318 `mailcap' Use command specified in the mailcaps.
2319 string A command to be executed by a shell; %s will be replaced
2320 by the path to the file.
2321 function A Lisp function, which will be called with two arguments:
2322 the file path and the original link string, without the
2323 \"file:\" prefix.
2325 For more examples, see the system specific constants
2326 `org-file-apps-defaults-macosx'
2327 `org-file-apps-defaults-windowsnt'
2328 `org-file-apps-defaults-gnu'."
2329 :group 'org-link-follow
2330 :type '(repeat
2331 (cons (choice :value ""
2332 (string :tag "Extension")
2333 (const :tag "System command to open files" system)
2334 (const :tag "Default for unrecognized files" t)
2335 (const :tag "Remote file" remote)
2336 (const :tag "Links to a directory" directory)
2337 (const :tag "Any files that have Emacs modes"
2338 auto-mode))
2339 (choice :value ""
2340 (const :tag "Visit with Emacs" emacs)
2341 (const :tag "Use default" default)
2342 (const :tag "Use the system command" system)
2343 (string :tag "Command")
2344 (function :tag "Function")))))
2346 (defcustom org-doi-server-url "http://dx.doi.org/"
2347 "The URL of the DOI server."
2348 :type 'string
2349 :version "24.3"
2350 :group 'org-link-follow)
2352 (defgroup org-refile nil
2353 "Options concerning refiling entries in Org-mode."
2354 :tag "Org Refile"
2355 :group 'org)
2357 (defcustom org-directory "~/org"
2358 "Directory with Org files.
2359 This is just a default location to look for Org files. There is no need
2360 at all to put your files into this directory. It is used in the
2361 following situations:
2363 1. When a capture template specifies a target file that is not an
2364 absolute path. The path will then be interpreted relative to
2365 `org-directory'
2366 2. When the value of variable `org-agenda-files' is a single file, any
2367 relative paths in this file will be taken as relative to
2368 `org-directory'."
2369 :group 'org-refile
2370 :group 'org-capture
2371 :type 'directory)
2373 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2374 "Default target for storing notes.
2375 Used as a fall back file for org-capture.el, for templates that
2376 do not specify a target file."
2377 :group 'org-refile
2378 :group 'org-capture
2379 :type 'file)
2381 (defcustom org-goto-interface 'outline
2382 "The default interface to be used for `org-goto'.
2383 Allowed values are:
2384 outline The interface shows an outline of the relevant file
2385 and the correct heading is found by moving through
2386 the outline or by searching with incremental search.
2387 outline-path-completion Headlines in the current buffer are offered via
2388 completion. This is the interface also used by
2389 the refile command."
2390 :group 'org-refile
2391 :type '(choice
2392 (const :tag "Outline" outline)
2393 (const :tag "Outline-path-completion" outline-path-completion)))
2395 (defcustom org-goto-max-level 5
2396 "Maximum target level when running `org-goto' with refile interface."
2397 :group 'org-refile
2398 :type 'integer)
2400 (defcustom org-reverse-note-order nil
2401 "Non-nil means store new notes at the beginning of a file or entry.
2402 When nil, new notes will be filed to the end of a file or entry.
2403 This can also be a list with cons cells of regular expressions that
2404 are matched against file names, and values."
2405 :group 'org-capture
2406 :group 'org-refile
2407 :type '(choice
2408 (const :tag "Reverse always" t)
2409 (const :tag "Reverse never" nil)
2410 (repeat :tag "By file name regexp"
2411 (cons regexp boolean))))
2413 (defcustom org-log-refile nil
2414 "Information to record when a task is refiled.
2416 Possible values are:
2418 nil Don't add anything
2419 time Add a time stamp to the task
2420 note Prompt for a note and add it with template `org-log-note-headings'
2422 This option can also be set with on a per-file-basis with
2424 #+STARTUP: nologrefile
2425 #+STARTUP: logrefile
2426 #+STARTUP: lognoterefile
2428 You can have local logging settings for a subtree by setting the LOGGING
2429 property to one or more of these keywords.
2431 When bulk-refiling from the agenda, the value `note' is forbidden and
2432 will temporarily be changed to `time'."
2433 :group 'org-refile
2434 :group 'org-progress
2435 :version "24.1"
2436 :type '(choice
2437 (const :tag "No logging" nil)
2438 (const :tag "Record timestamp" time)
2439 (const :tag "Record timestamp with note." note)))
2441 (defcustom org-refile-targets nil
2442 "Targets for refiling entries with \\[org-refile].
2443 This is a list of cons cells. Each cell contains:
2444 - a specification of the files to be considered, either a list of files,
2445 or a symbol whose function or variable value will be used to retrieve
2446 a file name or a list of file names. If you use `org-agenda-files' for
2447 that, all agenda files will be scanned for targets. Nil means consider
2448 headings in the current buffer.
2449 - A specification of how to find candidate refile targets. This may be
2450 any of:
2451 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2452 This tag has to be present in all target headlines, inheritance will
2453 not be considered.
2454 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2455 todo keyword.
2456 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2457 headlines that are refiling targets.
2458 - a cons cell (:level . N). Any headline of level N is considered a target.
2459 Note that, when `org-odd-levels-only' is set, level corresponds to
2460 order in hierarchy, not to the number of stars.
2461 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2462 Note that, when `org-odd-levels-only' is set, level corresponds to
2463 order in hierarchy, not to the number of stars.
2465 Each element of this list generates a set of possible targets.
2466 The union of these sets is presented (with completion) to
2467 the user by `org-refile'.
2469 You can set the variable `org-refile-target-verify-function' to a function
2470 to verify each headline found by the simple criteria above.
2472 When this variable is nil, all top-level headlines in the current buffer
2473 are used, equivalent to the value `((nil . (:level . 1))'."
2474 :group 'org-refile
2475 :type '(repeat
2476 (cons
2477 (choice :value org-agenda-files
2478 (const :tag "All agenda files" org-agenda-files)
2479 (const :tag "Current buffer" nil)
2480 (function) (variable) (file))
2481 (choice :tag "Identify target headline by"
2482 (cons :tag "Specific tag" (const :value :tag) (string))
2483 (cons :tag "TODO keyword" (const :value :todo) (string))
2484 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2485 (cons :tag "Level number" (const :value :level) (integer))
2486 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2488 (defcustom org-refile-target-verify-function nil
2489 "Function to verify if the headline at point should be a refile target.
2490 The function will be called without arguments, with point at the
2491 beginning of the headline. It should return t and leave point
2492 where it is if the headline is a valid target for refiling.
2494 If the target should not be selected, the function must return nil.
2495 In addition to this, it may move point to a place from where the search
2496 should be continued. For example, the function may decide that the entire
2497 subtree of the current entry should be excluded and move point to the end
2498 of the subtree."
2499 :group 'org-refile
2500 :type '(choice
2501 (const nil)
2502 (function)))
2504 (defcustom org-refile-use-cache nil
2505 "Non-nil means cache refile targets to speed up the process.
2506 \\<org-mode-map>\
2507 The cache for a particular file will be updated automatically when
2508 the buffer has been killed, or when any of the marker used for flagging
2509 refile targets no longer points at a live buffer.
2510 If you have added new entries to a buffer that might themselves be targets,
2511 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2512 if you find that easier, \
2513 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2514 \\[org-refile]'."
2515 :group 'org-refile
2516 :version "24.1"
2517 :type 'boolean)
2519 (defcustom org-refile-use-outline-path nil
2520 "Non-nil means provide refile targets as paths.
2521 So a level 3 headline will be available as level1/level2/level3.
2523 When the value is `file', also include the file name (without directory)
2524 into the path. In this case, you can also stop the completion after
2525 the file name, to get entries inserted as top level in the file.
2527 When `full-file-path', include the full file path."
2528 :group 'org-refile
2529 :type '(choice
2530 (const :tag "Not" nil)
2531 (const :tag "Yes" t)
2532 (const :tag "Start with file name" file)
2533 (const :tag "Start with full file path" full-file-path)))
2535 (defcustom org-outline-path-complete-in-steps t
2536 "Non-nil means complete the outline path in hierarchical steps.
2537 When Org uses the refile interface to select an outline path (see
2538 `org-refile-use-outline-path'), the completion of the path can be
2539 done in a single go, or it can be done in steps down the headline
2540 hierarchy. Going in steps is probably the best if you do not use
2541 a special completion package like `ido' or `icicles'. However,
2542 when using these packages, going in one step can be very fast,
2543 while still showing the whole path to the entry."
2544 :group 'org-refile
2545 :type 'boolean)
2547 (defcustom org-refile-allow-creating-parent-nodes nil
2548 "Non-nil means allow the creation of new nodes as refile targets.
2549 New nodes are then created by adding \"/new node name\" to the completion
2550 of an existing node. When the value of this variable is `confirm',
2551 new node creation must be confirmed by the user (recommended).
2552 When nil, the completion must match an existing entry.
2554 Note that, if the new heading is not seen by the criteria
2555 listed in `org-refile-targets', multiple instances of the same
2556 heading would be created by trying again to file under the new
2557 heading."
2558 :group 'org-refile
2559 :type '(choice
2560 (const :tag "Never" nil)
2561 (const :tag "Always" t)
2562 (const :tag "Prompt for confirmation" confirm)))
2564 (defcustom org-refile-active-region-within-subtree nil
2565 "Non-nil means also refile active region within a subtree.
2567 By default `org-refile' doesn't allow refiling regions if they
2568 don't contain a set of subtrees, but it might be convenient to
2569 do so sometimes: in that case, the first line of the region is
2570 converted to a headline before refiling."
2571 :group 'org-refile
2572 :version "24.1"
2573 :type 'boolean)
2575 (defgroup org-todo nil
2576 "Options concerning TODO items in Org-mode."
2577 :tag "Org TODO"
2578 :group 'org)
2580 (defgroup org-progress nil
2581 "Options concerning Progress logging in Org-mode."
2582 :tag "Org Progress"
2583 :group 'org-time)
2585 (defvar org-todo-interpretation-widgets
2586 '((:tag "Sequence (cycling hits every state)" sequence)
2587 (:tag "Type (cycling directly to DONE)" type))
2588 "The available interpretation symbols for customizing `org-todo-keywords'.
2589 Interested libraries should add to this list.")
2591 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2592 "List of TODO entry keyword sequences and their interpretation.
2593 \\<org-mode-map>This is a list of sequences.
2595 Each sequence starts with a symbol, either `sequence' or `type',
2596 indicating if the keywords should be interpreted as a sequence of
2597 action steps, or as different types of TODO items. The first
2598 keywords are states requiring action - these states will select a headline
2599 for inclusion into the global TODO list Org produces. If one of the
2600 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2601 signify that no further action is necessary. If \"|\" is not found,
2602 the last keyword is treated as the only DONE state of the sequence.
2604 The command \\[org-todo] cycles an entry through these states, and one
2605 additional state where no keyword is present. For details about this
2606 cycling, see the manual.
2608 TODO keywords and interpretation can also be set on a per-file basis with
2609 the special #+SEQ_TODO and #+TYP_TODO lines.
2611 Each keyword can optionally specify a character for fast state selection
2612 \(in combination with the variable `org-use-fast-todo-selection')
2613 and specifiers for state change logging, using the same syntax that
2614 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2615 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2616 indicates to record a time stamp each time this state is selected.
2618 Each keyword may also specify if a timestamp or a note should be
2619 recorded when entering or leaving the state, by adding additional
2620 characters in the parenthesis after the keyword. This looks like this:
2621 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2622 record only the time of the state change. With X and Y being either
2623 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2624 Y when leaving the state if and only if the *target* state does not
2625 define X. You may omit any of the fast-selection key or X or /Y,
2626 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2628 For backward compatibility, this variable may also be just a list
2629 of keywords. In this case the interpretation (sequence or type) will be
2630 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2631 :group 'org-todo
2632 :group 'org-keywords
2633 :type '(choice
2634 (repeat :tag "Old syntax, just keywords"
2635 (string :tag "Keyword"))
2636 (repeat :tag "New syntax"
2637 (cons
2638 (choice
2639 :tag "Interpretation"
2640 ;;Quick and dirty way to see
2641 ;;`org-todo-interpretations'. This takes the
2642 ;;place of item arguments
2643 :convert-widget
2644 (lambda (widget)
2645 (widget-put widget
2646 :args (mapcar
2647 (lambda (x)
2648 (widget-convert
2649 (cons 'const x)))
2650 org-todo-interpretation-widgets))
2651 widget))
2652 (repeat
2653 (string :tag "Keyword"))))))
2655 (defvar-local org-todo-keywords-1 nil
2656 "All TODO and DONE keywords active in a buffer.")
2657 (defvar org-todo-keywords-for-agenda nil)
2658 (defvar org-done-keywords-for-agenda nil)
2659 (defvar org-todo-keyword-alist-for-agenda nil)
2660 (defvar org-tag-alist-for-agenda nil
2661 "Alist of all tags from all agenda files.")
2662 (defvar org-tag-groups-alist-for-agenda nil
2663 "Alist of all groups tags from all current agenda files.")
2664 (defvar-local org-tag-groups-alist nil)
2665 (defvar org-agenda-contributing-files nil)
2666 (defvar-local org-current-tag-alist nil
2667 "Alist of all tag groups in current buffer.
2668 This variable takes into consideration `org-tag-alist',
2669 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2670 (defvar-local org-not-done-keywords nil)
2671 (defvar-local org-done-keywords nil)
2672 (defvar-local org-todo-heads nil)
2673 (defvar-local org-todo-sets nil)
2674 (defvar-local org-todo-log-states nil)
2675 (defvar-local org-todo-kwd-alist nil)
2676 (defvar-local org-todo-key-alist nil)
2677 (defvar-local org-todo-key-trigger nil)
2679 (defcustom org-todo-interpretation 'sequence
2680 "Controls how TODO keywords are interpreted.
2681 This variable is in principle obsolete and is only used for
2682 backward compatibility, if the interpretation of todo keywords is
2683 not given already in `org-todo-keywords'. See that variable for
2684 more information."
2685 :group 'org-todo
2686 :group 'org-keywords
2687 :type '(choice (const sequence)
2688 (const type)))
2690 (defcustom org-use-fast-todo-selection t
2691 "\\<org-mode-map>\
2692 Non-nil means use the fast todo selection scheme with \\[org-todo].
2693 This variable describes if and under what circumstances the cycling
2694 mechanism for TODO keywords will be replaced by a single-key, direct
2695 selection scheme.
2697 When nil, fast selection is never used.
2699 When the symbol `prefix', it will be used when `org-todo' is called
2700 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2701 in an Org buffer, and
2702 `\\[universal-argument] t' in an agenda buffer.
2704 When t, fast selection is used by default. In this case, the prefix
2705 argument forces cycling instead.
2707 In all cases, the special interface is only used if access keys have
2708 actually been assigned by the user, i.e. if keywords in the configuration
2709 are followed by a letter in parenthesis, like TODO(t)."
2710 :group 'org-todo
2711 :type '(choice
2712 (const :tag "Never" nil)
2713 (const :tag "By default" t)
2714 (const :tag "Only with C-u C-c C-t" prefix)))
2716 (defcustom org-provide-todo-statistics t
2717 "Non-nil means update todo statistics after insert and toggle.
2718 ALL-HEADLINES means update todo statistics by including headlines
2719 with no TODO keyword as well, counting them as not done.
2720 A list of TODO keywords means the same, but skip keywords that are
2721 not in this list.
2722 When set to a list of two lists, the first list contains keywords
2723 to consider as TODO keywords, the second list contains keywords
2724 to consider as DONE keywords.
2726 When this is set, todo statistics is updated in the parent of the
2727 current entry each time a todo state is changed."
2728 :group 'org-todo
2729 :type '(choice
2730 (const :tag "Yes, only for TODO entries" t)
2731 (const :tag "Yes, including all entries" all-headlines)
2732 (repeat :tag "Yes, for TODOs in this list"
2733 (string :tag "TODO keyword"))
2734 (list :tag "Yes, for TODOs and DONEs in these lists"
2735 (repeat (string :tag "TODO keyword"))
2736 (repeat (string :tag "DONE keyword")))
2737 (other :tag "No TODO statistics" nil)))
2739 (defcustom org-hierarchical-todo-statistics t
2740 "Non-nil means TODO statistics covers just direct children.
2741 When nil, all entries in the subtree are considered.
2742 This has only an effect if `org-provide-todo-statistics' is set.
2743 To set this to nil for only a single subtree, use a COOKIE_DATA
2744 property and include the word \"recursive\" into the value."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-after-todo-state-change-hook nil
2749 "Hook which is run after the state of a TODO item was changed.
2750 The new state (a string with a TODO keyword, or nil) is available in the
2751 Lisp variable `org-state'."
2752 :group 'org-todo
2753 :type 'hook)
2755 (defvar org-blocker-hook nil
2756 "Hook for functions that are allowed to block a state change.
2758 Functions in this hook should not modify the buffer.
2759 Each function gets as its single argument a property list,
2760 see `org-trigger-hook' for more information about this list.
2762 If any of the functions in this hook returns nil, the state change
2763 is blocked.")
2765 (defvar org-trigger-hook nil
2766 "Hook for functions that are triggered by a state change.
2768 Each function gets as its single argument a property list with at
2769 least the following elements:
2771 (:type type-of-change :position pos-at-entry-start
2772 :from old-state :to new-state)
2774 Depending on the type, more properties may be present.
2776 This mechanism is currently implemented for:
2778 TODO state changes
2779 ------------------
2780 :type todo-state-change
2781 :from previous state (keyword as a string), or nil, or a symbol
2782 `todo' or `done', to indicate the general type of state.
2783 :to new state, like in :from")
2785 (defcustom org-enforce-todo-dependencies nil
2786 "Non-nil means undone TODO entries will block switching the parent to DONE.
2787 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2788 be blocked if any prior sibling is not yet done.
2789 Finally, if the parent is blocked because of ordered siblings of its own,
2790 the child will also be blocked."
2791 :set (lambda (var val)
2792 (set var val)
2793 (if val
2794 (add-hook 'org-blocker-hook
2795 'org-block-todo-from-children-or-siblings-or-parent)
2796 (remove-hook 'org-blocker-hook
2797 'org-block-todo-from-children-or-siblings-or-parent)))
2798 :group 'org-todo
2799 :type 'boolean)
2801 (defcustom org-enforce-todo-checkbox-dependencies nil
2802 "Non-nil means unchecked boxes will block switching the parent to DONE.
2803 When this is nil, checkboxes have no influence on switching TODO states.
2804 When non-nil, you first need to check off all check boxes before the TODO
2805 entry can be switched to DONE.
2806 This variable needs to be set before org.el is loaded, and you need to
2807 restart Emacs after a change to make the change effective. The only way
2808 to change is while Emacs is running is through the customize interface."
2809 :set (lambda (var val)
2810 (set var val)
2811 (if val
2812 (add-hook 'org-blocker-hook
2813 'org-block-todo-from-checkboxes)
2814 (remove-hook 'org-blocker-hook
2815 'org-block-todo-from-checkboxes)))
2816 :group 'org-todo
2817 :type 'boolean)
2819 (defcustom org-treat-insert-todo-heading-as-state-change nil
2820 "Non-nil means inserting a TODO heading is treated as state change.
2821 So when the command \\[org-insert-todo-heading] is used, state change
2822 logging will apply if appropriate. When nil, the new TODO item will
2823 be inserted directly, and no logging will take place."
2824 :group 'org-todo
2825 :type 'boolean)
2827 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2828 "Non-nil means switching TODO states with S-cursor counts as state change.
2829 This is the default behavior. However, setting this to nil allows a
2830 convenient way to select a TODO state and bypass any logging associated
2831 with that."
2832 :group 'org-todo
2833 :type 'boolean)
2835 (defcustom org-todo-state-tags-triggers nil
2836 "Tag changes that should be triggered by TODO state changes.
2837 This is a list. Each entry is
2839 (state-change (tag . flag) .......)
2841 State-change can be a string with a state, and empty string to indicate the
2842 state that has no TODO keyword, or it can be one of the symbols `todo'
2843 or `done', meaning any not-done or done state, respectively."
2844 :group 'org-todo
2845 :group 'org-tags
2846 :type '(repeat
2847 (cons (choice :tag "When changing to"
2848 (const :tag "Not-done state" todo)
2849 (const :tag "Done state" done)
2850 (string :tag "State"))
2851 (repeat
2852 (cons :tag "Tag action"
2853 (string :tag "Tag")
2854 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2856 (defcustom org-log-done nil
2857 "Information to record when a task moves to the DONE state.
2859 Possible values are:
2861 nil Don't add anything, just change the keyword
2862 time Add a time stamp to the task
2863 note Prompt for a note and add it with template `org-log-note-headings'
2865 This option can also be set with on a per-file-basis with
2867 #+STARTUP: nologdone
2868 #+STARTUP: logdone
2869 #+STARTUP: lognotedone
2871 You can have local logging settings for a subtree by setting the LOGGING
2872 property to one or more of these keywords."
2873 :group 'org-todo
2874 :group 'org-progress
2875 :type '(choice
2876 (const :tag "No logging" nil)
2877 (const :tag "Record CLOSED timestamp" time)
2878 (const :tag "Record CLOSED timestamp with note." note)))
2880 ;; Normalize old uses of org-log-done.
2881 (cond
2882 ((eq org-log-done t) (setq org-log-done 'time))
2883 ((and (listp org-log-done) (memq 'done org-log-done))
2884 (setq org-log-done 'note)))
2886 (defcustom org-log-reschedule nil
2887 "Information to record when the scheduling date of a tasks is modified.
2889 Possible values are:
2891 nil Don't add anything, just change the date
2892 time Add a time stamp to the task
2893 note Prompt for a note and add it with template `org-log-note-headings'
2895 This option can also be set with on a per-file-basis with
2897 #+STARTUP: nologreschedule
2898 #+STARTUP: logreschedule
2899 #+STARTUP: lognotereschedule"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type '(choice
2903 (const :tag "No logging" nil)
2904 (const :tag "Record timestamp" time)
2905 (const :tag "Record timestamp with note." note)))
2907 (defcustom org-log-redeadline nil
2908 "Information to record when the deadline date of a tasks is modified.
2910 Possible values are:
2912 nil Don't add anything, just change the date
2913 time Add a time stamp to the task
2914 note Prompt for a note and add it with template `org-log-note-headings'
2916 This option can also be set with on a per-file-basis with
2918 #+STARTUP: nologredeadline
2919 #+STARTUP: logredeadline
2920 #+STARTUP: lognoteredeadline
2922 You can have local logging settings for a subtree by setting the LOGGING
2923 property to one or more of these keywords."
2924 :group 'org-todo
2925 :group 'org-progress
2926 :type '(choice
2927 (const :tag "No logging" nil)
2928 (const :tag "Record timestamp" time)
2929 (const :tag "Record timestamp with note." note)))
2931 (defcustom org-log-note-clock-out nil
2932 "Non-nil means record a note when clocking out of an item.
2933 This can also be configured on a per-file basis by adding one of
2934 the following lines anywhere in the buffer:
2936 #+STARTUP: lognoteclock-out
2937 #+STARTUP: nolognoteclock-out"
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type 'boolean)
2942 (defcustom org-log-done-with-time t
2943 "Non-nil means the CLOSED time stamp will contain date and time.
2944 When nil, only the date will be recorded."
2945 :group 'org-progress
2946 :type 'boolean)
2948 (defcustom org-log-note-headings
2949 '((done . "CLOSING NOTE %t")
2950 (state . "State %-12s from %-12S %t")
2951 (note . "Note taken on %t")
2952 (reschedule . "Rescheduled from %S on %t")
2953 (delschedule . "Not scheduled, was %S on %t")
2954 (redeadline . "New deadline from %S on %t")
2955 (deldeadline . "Removed deadline, was %S on %t")
2956 (refile . "Refiled on %t")
2957 (clock-out . ""))
2958 "Headings for notes added to entries.
2960 The value is an alist, with the car being a symbol indicating the
2961 note context, and the cdr is the heading to be used. The heading
2962 may also be the empty string. The following placeholders can be
2963 used:
2965 %t a time stamp.
2966 %T an active time stamp instead the default inactive one
2967 %d a short-format time stamp.
2968 %D an active short-format time stamp.
2969 %s the new TODO state or time stamp (inactive), in double quotes.
2970 %S the old TODO state or time stamp (inactive), in double quotes.
2971 %u the user name.
2972 %U full user name.
2974 In fact, it is not a good idea to change the `state' entry,
2975 because Agenda Log mode depends on the format of these entries."
2976 :group 'org-todo
2977 :group 'org-progress
2978 :type '(list :greedy t
2979 (cons (const :tag "Heading when closing an item" done) string)
2980 (cons (const :tag
2981 "Heading when changing todo state (todo sequence only)"
2982 state) string)
2983 (cons (const :tag "Heading when just taking a note" note) string)
2984 (cons (const :tag "Heading when rescheduling" reschedule) string)
2985 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2986 (cons (const :tag "Heading when changing deadline" redeadline) string)
2987 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2988 (cons (const :tag "Heading when refiling" refile) string)
2989 (cons (const :tag "Heading when clocking out" clock-out) string)))
2991 (unless (assq 'note org-log-note-headings)
2992 (push '(note . "%t") org-log-note-headings))
2994 (defcustom org-log-into-drawer nil
2995 "Non-nil means insert state change notes and time stamps into a drawer.
2996 When nil, state changes notes will be inserted after the headline and
2997 any scheduling and clock lines, but not inside a drawer.
2999 The value of this variable should be the name of the drawer to use.
3000 LOGBOOK is proposed as the default drawer for this purpose, you can
3001 also set this to a string to define the drawer of your choice.
3003 A value of t is also allowed, representing \"LOGBOOK\".
3005 A value of t or nil can also be set with on a per-file-basis with
3007 #+STARTUP: logdrawer
3008 #+STARTUP: nologdrawer
3010 If this variable is set, `org-log-state-notes-insert-after-drawers'
3011 will be ignored.
3013 You can set the property LOG_INTO_DRAWER to overrule this setting for
3014 a subtree.
3016 Do not check directly this variable in a Lisp program. Call
3017 function `org-log-into-drawer' instead."
3018 :group 'org-todo
3019 :group 'org-progress
3020 :type '(choice
3021 (const :tag "Not into a drawer" nil)
3022 (const :tag "LOGBOOK" t)
3023 (string :tag "Other")))
3025 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3027 (defun org-log-into-drawer ()
3028 "Name of the log drawer, as a string, or nil.
3029 This is the value of `org-log-into-drawer'. However, if the
3030 current entry has or inherits a LOG_INTO_DRAWER property, it will
3031 be used instead of the default value."
3032 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3033 (cond ((equal p "nil") nil)
3034 ((equal p "t") "LOGBOOK")
3035 ((stringp p) p)
3036 (p "LOGBOOK")
3037 ((stringp org-log-into-drawer) org-log-into-drawer)
3038 (org-log-into-drawer "LOGBOOK"))))
3040 (defcustom org-log-state-notes-insert-after-drawers nil
3041 "Non-nil means insert state change notes after any drawers in entry.
3042 Only the drawers that *immediately* follow the headline and the
3043 deadline/scheduled line are skipped.
3044 When nil, insert notes right after the heading and perhaps the line
3045 with deadline/scheduling if present.
3047 This variable will have no effect if `org-log-into-drawer' is
3048 set."
3049 :group 'org-todo
3050 :group 'org-progress
3051 :type 'boolean)
3053 (defcustom org-log-states-order-reversed t
3054 "Non-nil means the latest state note will be directly after heading.
3055 When nil, the state change notes will be ordered according to time.
3057 This option can also be set with on a per-file-basis with
3059 #+STARTUP: logstatesreversed
3060 #+STARTUP: nologstatesreversed"
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type 'boolean)
3065 (defcustom org-todo-repeat-to-state nil
3066 "The TODO state to which a repeater should return the repeating task.
3067 By default this is the first task in a TODO sequence, or the previous state
3068 in a TODO_TYP set. But you can specify another task here.
3069 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3070 :group 'org-todo
3071 :version "24.1"
3072 :type '(choice (const :tag "Head of sequence" nil)
3073 (string :tag "Specific state")))
3075 (defcustom org-log-repeat 'time
3076 "Non-nil means record moving through the DONE state when triggering repeat.
3077 An auto-repeating task is immediately switched back to TODO when
3078 marked DONE. If you are not logging state changes (by adding \"@\"
3079 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3080 record a closing note, there will be no record of the task moving
3081 through DONE. This variable forces taking a note anyway.
3083 nil Don't force a record
3084 time Record a time stamp
3085 note Prompt for a note and add it with template `org-log-note-headings'
3087 This option can also be set with on a per-file-basis with
3089 #+STARTUP: nologrepeat
3090 #+STARTUP: logrepeat
3091 #+STARTUP: lognoterepeat
3093 You can have local logging settings for a subtree by setting the LOGGING
3094 property to one or more of these keywords."
3095 :group 'org-todo
3096 :group 'org-progress
3097 :type '(choice
3098 (const :tag "Don't force a record" nil)
3099 (const :tag "Force recording the DONE state" time)
3100 (const :tag "Force recording a note with the DONE state" note)))
3103 (defgroup org-priorities nil
3104 "Priorities in Org-mode."
3105 :tag "Org Priorities"
3106 :group 'org-todo)
3108 (defcustom org-enable-priority-commands t
3109 "Non-nil means priority commands are active.
3110 When nil, these commands will be disabled, so that you never accidentally
3111 set a priority."
3112 :group 'org-priorities
3113 :type 'boolean)
3115 (defcustom org-highest-priority ?A
3116 "The highest priority of TODO items. A character like ?A, ?B etc.
3117 Must have a smaller ASCII number than `org-lowest-priority'."
3118 :group 'org-priorities
3119 :type 'character)
3121 (defcustom org-lowest-priority ?C
3122 "The lowest priority of TODO items. A character like ?A, ?B etc.
3123 Must have a larger ASCII number than `org-highest-priority'."
3124 :group 'org-priorities
3125 :type 'character)
3127 (defcustom org-default-priority ?B
3128 "The default priority of TODO items.
3129 This is the priority an item gets if no explicit priority is given.
3130 When starting to cycle on an empty priority the first step in the cycle
3131 depends on `org-priority-start-cycle-with-default'. The resulting first
3132 step priority must not exceed the range from `org-highest-priority' to
3133 `org-lowest-priority' which means that `org-default-priority' has to be
3134 in this range exclusive or inclusive the range boundaries. Else the
3135 first step refuses to set the default and the second will fall back
3136 to (depending on the command used) the highest or lowest priority."
3137 :group 'org-priorities
3138 :type 'character)
3140 (defcustom org-priority-start-cycle-with-default t
3141 "Non-nil means start with default priority when starting to cycle.
3142 When this is nil, the first step in the cycle will be (depending on the
3143 command used) one higher or lower than the default priority.
3144 See also `org-default-priority'."
3145 :group 'org-priorities
3146 :type 'boolean)
3148 (defcustom org-get-priority-function nil
3149 "Function to extract the priority from a string.
3150 The string is normally the headline. If this is nil Org computes the
3151 priority from the priority cookie like [#A] in the headline. It returns
3152 an integer, increasing by 1000 for each priority level.
3153 The user can set a different function here, which should take a string
3154 as an argument and return the numeric priority."
3155 :group 'org-priorities
3156 :version "24.1"
3157 :type '(choice
3158 (const nil)
3159 (function)))
3161 (defgroup org-time nil
3162 "Options concerning time stamps and deadlines in Org-mode."
3163 :tag "Org Time"
3164 :group 'org)
3166 (defcustom org-time-stamp-rounding-minutes '(0 5)
3167 "Number of minutes to round time stamps to.
3168 \\<org-mode-map>\
3169 These are two values, the first applies when first creating a time stamp.
3170 The second applies when changing it with the commands `S-up' and `S-down'.
3171 When changing the time stamp, this means that it will change in steps
3172 of N minutes, as given by the second value.
3174 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3175 numbers should be factors of 60, so for example 5, 10, 15.
3177 When this is larger than 1, you can still force an exact time stamp by using
3178 a double prefix argument to a time stamp command like \
3179 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3180 and by using a prefix arg to `S-up/down' to specify the exact number
3181 of minutes to shift."
3182 :group 'org-time
3183 :get (lambda (var) ; Make sure both elements are there
3184 (if (integerp (default-value var))
3185 (list (default-value var) 5)
3186 (default-value var)))
3187 :type '(list
3188 (integer :tag "when inserting times")
3189 (integer :tag "when modifying times")))
3191 ;; Normalize old customizations of this variable.
3192 (when (integerp org-time-stamp-rounding-minutes)
3193 (setq org-time-stamp-rounding-minutes
3194 (list org-time-stamp-rounding-minutes
3195 org-time-stamp-rounding-minutes)))
3197 (defcustom org-display-custom-times nil
3198 "Non-nil means overlay custom formats over all time stamps.
3199 The formats are defined through the variable `org-time-stamp-custom-formats'.
3200 To turn this on on a per-file basis, insert anywhere in the file:
3201 #+STARTUP: customtime"
3202 :group 'org-time
3203 :set 'set-default
3204 :type 'sexp)
3205 (make-variable-buffer-local 'org-display-custom-times)
3207 (defcustom org-time-stamp-custom-formats
3208 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3209 "Custom formats for time stamps. See `format-time-string' for the syntax.
3210 These are overlaid over the default ISO format if the variable
3211 `org-display-custom-times' is set. Time like %H:%M should be at the
3212 end of the second format. The custom formats are also honored by export
3213 commands, if custom time display is turned on at the time of export."
3214 :group 'org-time
3215 :type 'sexp)
3217 (defun org-time-stamp-format (&optional long inactive)
3218 "Get the right format for a time string."
3219 (let ((f (if long (cdr org-time-stamp-formats)
3220 (car org-time-stamp-formats))))
3221 (if inactive
3222 (concat "[" (substring f 1 -1) "]")
3223 f)))
3225 (defcustom org-time-clocksum-format
3226 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3227 "The format string used when creating CLOCKSUM lines.
3228 This is also used when Org mode generates a time duration.
3230 The value can be a single format string containing two
3231 %-sequences, which will be filled with the number of hours and
3232 minutes in that order.
3234 Alternatively, the value can be a plist associating any of the
3235 keys :years, :months, :weeks, :days, :hours or :minutes with
3236 format strings. The time duration is formatted using only the
3237 time components that are needed and concatenating the results.
3238 If a time unit in absent, it falls back to the next smallest
3239 unit.
3241 The keys :require-years, :require-months, :require-days,
3242 :require-weeks, :require-hours, :require-minutes are also
3243 meaningful. A non-nil value for these keys indicates that the
3244 corresponding time component should always be included, even if
3245 its value is 0.
3248 For example,
3250 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3251 :require-minutes t)
3253 means durations longer than a day will be expressed in days,
3254 hours and minutes, and durations less than a day will always be
3255 expressed in hours and minutes (even for durations less than an
3256 hour).
3258 The value
3260 (:days \"%dd\" :minutes \"%dm\")
3262 means durations longer than a day will be expressed in days and
3263 minutes, and durations less than a day will be expressed entirely
3264 in minutes (even for durations longer than an hour)."
3265 :group 'org-time
3266 :group 'org-clock
3267 :version "24.4"
3268 :package-version '(Org . "8.0")
3269 :type '(choice (string :tag "Format string")
3270 (set :tag "Plist"
3271 (group :inline t (const :tag "Years" :years)
3272 (string :tag "Format string"))
3273 (group :inline t
3274 (const :tag "Always show years" :require-years)
3275 (const t))
3276 (group :inline t (const :tag "Months" :months)
3277 (string :tag "Format string"))
3278 (group :inline t
3279 (const :tag "Always show months" :require-months)
3280 (const t))
3281 (group :inline t (const :tag "Weeks" :weeks)
3282 (string :tag "Format string"))
3283 (group :inline t
3284 (const :tag "Always show weeks" :require-weeks)
3285 (const t))
3286 (group :inline t (const :tag "Days" :days)
3287 (string :tag "Format string"))
3288 (group :inline t
3289 (const :tag "Always show days" :require-days)
3290 (const t))
3291 (group :inline t (const :tag "Hours" :hours)
3292 (string :tag "Format string"))
3293 (group :inline t
3294 (const :tag "Always show hours" :require-hours)
3295 (const t))
3296 (group :inline t (const :tag "Minutes" :minutes)
3297 (string :tag "Format string"))
3298 (group :inline t
3299 (const :tag "Always show minutes" :require-minutes)
3300 (const t)))))
3302 (defcustom org-time-clocksum-use-fractional nil
3303 "When non-nil, \\[org-clock-display] uses fractional times.
3304 See `org-time-clocksum-format' for more on time clock formats."
3305 :group 'org-time
3306 :group 'org-clock
3307 :version "24.3"
3308 :type 'boolean)
3310 (defcustom org-time-clocksum-use-effort-durations nil
3311 "When non-nil, \\[org-clock-display] uses effort durations.
3312 E.g. by default, one day is considered to be a 8 hours effort,
3313 so a task that has been clocked for 16 hours will be displayed
3314 as during 2 days in the clock display or in the clocktable.
3316 See `org-effort-durations' on how to set effort durations
3317 and `org-time-clocksum-format' for more on time clock formats."
3318 :group 'org-time
3319 :group 'org-clock
3320 :version "24.4"
3321 :package-version '(Org . "8.0")
3322 :type 'boolean)
3324 (defcustom org-time-clocksum-fractional-format "%.2f"
3325 "The format string used when creating CLOCKSUM lines,
3326 or when Org mode generates a time duration, if
3327 `org-time-clocksum-use-fractional' is enabled.
3329 The value can be a single format string containing one
3330 %-sequence, which will be filled with the number of hours as
3331 a float.
3333 Alternatively, the value can be a plist associating any of the
3334 keys :years, :months, :weeks, :days, :hours or :minutes with
3335 a format string. The time duration is formatted using the
3336 largest time unit which gives a non-zero integer part. If all
3337 specified formats have zero integer part, the smallest time unit
3338 is used."
3339 :group 'org-time
3340 :type '(choice (string :tag "Format string")
3341 (set (group :inline t (const :tag "Years" :years)
3342 (string :tag "Format string"))
3343 (group :inline t (const :tag "Months" :months)
3344 (string :tag "Format string"))
3345 (group :inline t (const :tag "Weeks" :weeks)
3346 (string :tag "Format string"))
3347 (group :inline t (const :tag "Days" :days)
3348 (string :tag "Format string"))
3349 (group :inline t (const :tag "Hours" :hours)
3350 (string :tag "Format string"))
3351 (group :inline t (const :tag "Minutes" :minutes)
3352 (string :tag "Format string")))))
3354 (defcustom org-deadline-warning-days 14
3355 "Number of days before expiration during which a deadline becomes active.
3356 This variable governs the display in sparse trees and in the agenda.
3357 When 0 or negative, it means use this number (the absolute value of it)
3358 even if a deadline has a different individual lead time specified.
3360 Custom commands can set this variable in the options section."
3361 :group 'org-time
3362 :group 'org-agenda-daily/weekly
3363 :type 'integer)
3365 (defcustom org-scheduled-delay-days 0
3366 "Number of days before a scheduled item becomes active.
3367 This variable governs the display in sparse trees and in the agenda.
3368 The default value (i.e. 0) means: don't delay scheduled item.
3369 When negative, it means use this number (the absolute value of it)
3370 even if a scheduled item has a different individual delay time
3371 specified.
3373 Custom commands can set this variable in the options section."
3374 :group 'org-time
3375 :group 'org-agenda-daily/weekly
3376 :version "24.4"
3377 :package-version '(Org . "8.0")
3378 :type 'integer)
3380 (defcustom org-read-date-prefer-future t
3381 "Non-nil means assume future for incomplete date input from user.
3382 This affects the following situations:
3383 1. The user gives a month but not a year.
3384 For example, if it is April and you enter \"feb 2\", this will be read
3385 as Feb 2, *next* year. \"May 5\", however, will be this year.
3386 2. The user gives a day, but no month.
3387 For example, if today is the 15th, and you enter \"3\", Org will read
3388 this as the third of *next* month. However, if you enter \"17\",
3389 it will be considered as *this* month.
3391 If you set this variable to the symbol `time', then also the following
3392 will work:
3394 3. If the user gives a time.
3395 If the time is before now, it will be interpreted as tomorrow.
3397 Currently none of this works for ISO week specifications.
3399 When this option is nil, the current day, month and year will always be
3400 used as defaults.
3402 See also `org-agenda-jump-prefer-future'."
3403 :group 'org-time
3404 :type '(choice
3405 (const :tag "Never" nil)
3406 (const :tag "Check month and day" t)
3407 (const :tag "Check month, day, and time" time)))
3409 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3410 "Should the agenda jump command prefer the future for incomplete dates?
3411 The default is to do the same as configured in `org-read-date-prefer-future'.
3412 But you can also set a deviating value here.
3413 This may t or nil, or the symbol `org-read-date-prefer-future'."
3414 :group 'org-agenda
3415 :group 'org-time
3416 :version "24.1"
3417 :type '(choice
3418 (const :tag "Use org-read-date-prefer-future"
3419 org-read-date-prefer-future)
3420 (const :tag "Never" nil)
3421 (const :tag "Always" t)))
3423 (defcustom org-read-date-force-compatible-dates t
3424 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3426 Depending on the system Emacs is running on, certain dates cannot
3427 be represented with the type used internally to represent time.
3428 Dates between 1970-1-1 and 2038-1-1 can always be represented
3429 correctly. Some systems allow for earlier dates, some for later,
3430 some for both. One way to find out it to insert any date into an
3431 Org buffer, putting the cursor on the year and hitting S-up and
3432 S-down to test the range.
3434 When this variable is set to t, the date/time prompt will not let
3435 you specify dates outside the 1970-2037 range, so it is certain that
3436 these dates will work in whatever version of Emacs you are
3437 running, and also that you can move a file from one Emacs implementation
3438 to another. WHenever Org is forcing the year for you, it will display
3439 a message and beep.
3441 When this variable is nil, Org will check if the date is
3442 representable in the specific Emacs implementation you are using.
3443 If not, it will force a year, usually the current year, and beep
3444 to remind you. Currently this setting is not recommended because
3445 the likelihood that you will open your Org files in an Emacs that
3446 has limited date range is not negligible.
3448 A workaround for this problem is to use diary sexp dates for time
3449 stamps outside of this range."
3450 :group 'org-time
3451 :version "24.1"
3452 :type 'boolean)
3454 (defcustom org-read-date-display-live t
3455 "Non-nil means display current interpretation of date prompt live.
3456 This display will be in an overlay, in the minibuffer."
3457 :group 'org-time
3458 :type 'boolean)
3460 (defcustom org-read-date-popup-calendar t
3461 "Non-nil means pop up a calendar when prompting for a date.
3462 In the calendar, the date can be selected with mouse-1. However, the
3463 minibuffer will also be active, and you can simply enter the date as well.
3464 When nil, only the minibuffer will be available."
3465 :group 'org-time
3466 :type 'boolean)
3467 (defvaralias 'org-popup-calendar-for-date-prompt
3468 'org-read-date-popup-calendar)
3470 (defcustom org-extend-today-until 0
3471 "The hour when your day really ends. Must be an integer.
3472 This has influence for the following applications:
3473 - When switching the agenda to \"today\". It it is still earlier than
3474 the time given here, the day recognized as TODAY is actually yesterday.
3475 - When a date is read from the user and it is still before the time given
3476 here, the current date and time will be assumed to be yesterday, 23:59.
3477 Also, timestamps inserted in capture templates follow this rule.
3479 IMPORTANT: This is a feature whose implementation is and likely will
3480 remain incomplete. Really, it is only here because past midnight seems to
3481 be the favorite working time of John Wiegley :-)"
3482 :group 'org-time
3483 :type 'integer)
3485 (defcustom org-use-effective-time nil
3486 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3487 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3488 \"effective time\" of any timestamps between midnight and 8am will be
3489 23:59 of the previous day."
3490 :group 'org-time
3491 :version "24.1"
3492 :type 'boolean)
3494 (defcustom org-use-last-clock-out-time-as-effective-time nil
3495 "When non-nil, use the last clock out time for `org-todo'.
3496 Note that this option has precedence over the combined use of
3497 `org-use-effective-time' and `org-extend-today-until'."
3498 :group 'org-time
3499 :version "24.4"
3500 :package-version '(Org . "8.0")
3501 :type 'boolean)
3503 (defcustom org-edit-timestamp-down-means-later nil
3504 "Non-nil means S-down will increase the time in a time stamp.
3505 When nil, S-up will increase."
3506 :group 'org-time
3507 :type 'boolean)
3509 (defcustom org-calendar-follow-timestamp-change t
3510 "Non-nil means make the calendar window follow timestamp changes.
3511 When a timestamp is modified and the calendar window is visible, it will be
3512 moved to the new date."
3513 :group 'org-time
3514 :type 'boolean)
3516 (defgroup org-tags nil
3517 "Options concerning tags in Org-mode."
3518 :tag "Org Tags"
3519 :group 'org)
3521 (defcustom org-tag-alist nil
3522 "Default tags available in Org files.
3524 The value of this variable is an alist. Associations either:
3526 (TAG)
3527 (TAG . SELECT)
3528 (SPECIAL)
3530 where TAG is a tag as a string, SELECT is a character, used to
3531 select that tag through the fast tag selection interface, and
3532 SPECIAL is one of the following keywords: `:startgroup',
3533 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3534 `:newline'. These keywords are used to define a hierarchy of
3535 tags. See manual for details.
3537 When this variable is nil, Org mode bases tag input on what is
3538 already in the buffer. The value can be overridden locally by
3539 using a TAGS keyword, e.g.,
3541 #+TAGS: tag1 tag2
3543 See also `org-tag-persistent-alist' to sidestep this behavior."
3544 :group 'org-tags
3545 :type '(repeat
3546 (choice
3547 (cons (string :tag "Tag name")
3548 (character :tag "Access char"))
3549 (const :tag "Start radio group" (:startgroup))
3550 (const :tag "Start tag group, non distinct" (:startgrouptag))
3551 (const :tag "Group tags delimiter" (:grouptags))
3552 (const :tag "End radio group" (:endgroup))
3553 (const :tag "End tag group, non distinct" (:endgrouptag))
3554 (const :tag "New line" (:newline)))))
3556 (defcustom org-tag-persistent-alist nil
3557 "Tags always available in Org files.
3559 The value of this variable is an alist. Associations either:
3561 (TAG)
3562 (TAG . SELECT)
3563 (SPECIAL)
3565 where TAG is a tag as a string, SELECT is a character, used to
3566 select that tag through the fast tag selection interface, and
3567 SPECIAL is one of the following keywords: `:startgroup',
3568 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3569 `:newline'. These keywords are used to define a hierarchy of
3570 tags. See manual for details.
3572 Unlike to `org-tag-alist', tags defined in this variable do not
3573 depend on a local TAGS keyword. Instead, to disable these tags
3574 on a per-file basis, insert anywhere in the file:
3576 #+STARTUP: noptag"
3577 :group 'org-tags
3578 :type '(repeat
3579 (choice
3580 (cons (string :tag "Tag name")
3581 (character :tag "Access char"))
3582 (const :tag "Start radio group" (:startgroup))
3583 (const :tag "Start tag group, non distinct" (:startgrouptag))
3584 (const :tag "Group tags delimiter" (:grouptags))
3585 (const :tag "End radio group" (:endgroup))
3586 (const :tag "End tag group, non distinct" (:endgrouptag))
3587 (const :tag "New line" (:newline)))))
3589 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3590 "If non-nil, always offer completion for all tags of all agenda files.
3591 Instead of customizing this variable directly, you might want to
3592 set it locally for capture buffers, because there no list of
3593 tags in that file can be created dynamically (there are none).
3595 (add-hook \\='org-capture-mode-hook
3596 (lambda ()
3597 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3598 :group 'org-tags
3599 :version "24.1"
3600 :type 'boolean)
3602 (defvar org-file-tags nil
3603 "List of tags that can be inherited by all entries in the file.
3604 The tags will be inherited if the variable `org-use-tag-inheritance'
3605 says they should be.
3606 This variable is populated from #+FILETAGS lines.")
3608 (defcustom org-use-fast-tag-selection 'auto
3609 "Non-nil means use fast tag selection scheme.
3610 This is a special interface to select and deselect tags with single keys.
3611 When nil, fast selection is never used.
3612 When the symbol `auto', fast selection is used if and only if selection
3613 characters for tags have been configured, either through the variable
3614 `org-tag-alist' or through a #+TAGS line in the buffer.
3615 When t, fast selection is always used and selection keys are assigned
3616 automatically if necessary."
3617 :group 'org-tags
3618 :type '(choice
3619 (const :tag "Always" t)
3620 (const :tag "Never" nil)
3621 (const :tag "When selection characters are configured" auto)))
3623 (defcustom org-fast-tag-selection-single-key nil
3624 "Non-nil means fast tag selection exits after first change.
3625 When nil, you have to press RET to exit it.
3626 During fast tag selection, you can toggle this flag with `C-c'.
3627 This variable can also have the value `expert'. In this case, the window
3628 displaying the tags menu is not even shown, until you press C-c again."
3629 :group 'org-tags
3630 :type '(choice
3631 (const :tag "No" nil)
3632 (const :tag "Yes" t)
3633 (const :tag "Expert" expert)))
3635 (defvar org-fast-tag-selection-include-todo nil
3636 "Non-nil means fast tags selection interface will also offer TODO states.
3637 This is an undocumented feature, you should not rely on it.")
3639 (defcustom org-tags-column -77
3640 "The column to which tags should be indented in a headline.
3641 If this number is positive, it specifies the column. If it is negative,
3642 it means that the tags should be flushright to that column. For example,
3643 -80 works well for a normal 80 character screen.
3644 When 0, place tags directly after headline text, with only one space in
3645 between."
3646 :group 'org-tags
3647 :type 'integer)
3649 (defcustom org-auto-align-tags t
3650 "Non-nil keeps tags aligned when modifying headlines.
3651 Some operations (i.e. demoting) change the length of a headline and
3652 therefore shift the tags around. With this option turned on, after
3653 each such operation the tags are again aligned to `org-tags-column'."
3654 :group 'org-tags
3655 :type 'boolean)
3657 (defcustom org-use-tag-inheritance t
3658 "Non-nil means tags in levels apply also for sublevels.
3659 When nil, only the tags directly given in a specific line apply there.
3660 This may also be a list of tags that should be inherited, or a regexp that
3661 matches tags that should be inherited. Additional control is possible
3662 with the variable `org-tags-exclude-from-inheritance' which gives an
3663 explicit list of tags to be excluded from inheritance, even if the value of
3664 `org-use-tag-inheritance' would select it for inheritance.
3666 If this option is t, a match early-on in a tree can lead to a large
3667 number of matches in the subtree when constructing the agenda or creating
3668 a sparse tree. If you only want to see the first match in a tree during
3669 a search, check out the variable `org-tags-match-list-sublevels'."
3670 :group 'org-tags
3671 :type '(choice
3672 (const :tag "Not" nil)
3673 (const :tag "Always" t)
3674 (repeat :tag "Specific tags" (string :tag "Tag"))
3675 (regexp :tag "Tags matched by regexp")))
3677 (defcustom org-tags-exclude-from-inheritance nil
3678 "List of tags that should never be inherited.
3679 This is a way to exclude a few tags from inheritance. For way to do
3680 the opposite, to actively allow inheritance for selected tags,
3681 see the variable `org-use-tag-inheritance'."
3682 :group 'org-tags
3683 :type '(repeat (string :tag "Tag")))
3685 (defun org-tag-inherit-p (tag)
3686 "Check if TAG is one that should be inherited."
3687 (cond
3688 ((member tag org-tags-exclude-from-inheritance) nil)
3689 ((eq org-use-tag-inheritance t) t)
3690 ((not org-use-tag-inheritance) nil)
3691 ((stringp org-use-tag-inheritance)
3692 (string-match org-use-tag-inheritance tag))
3693 ((listp org-use-tag-inheritance)
3694 (member tag org-use-tag-inheritance))
3695 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3697 (defcustom org-tags-match-list-sublevels t
3698 "Non-nil means list also sublevels of headlines matching a search.
3699 This variable applies to tags/property searches, and also to stuck
3700 projects because this search is based on a tags match as well.
3702 When set to the symbol `indented', sublevels are indented with
3703 leading dots.
3705 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3706 the sublevels of a headline matching a tag search often also match
3707 the same search. Listing all of them can create very long lists.
3708 Setting this variable to nil causes subtrees of a match to be skipped.
3710 This variable is semi-obsolete and probably should always be true. It
3711 is better to limit inheritance to certain tags using the variables
3712 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3713 :group 'org-tags
3714 :type '(choice
3715 (const :tag "No, don't list them" nil)
3716 (const :tag "Yes, do list them" t)
3717 (const :tag "List them, indented with leading dots" indented)))
3719 (defcustom org-tags-sort-function nil
3720 "When set, tags are sorted using this function as a comparator."
3721 :group 'org-tags
3722 :type '(choice
3723 (const :tag "No sorting" nil)
3724 (const :tag "Alphabetical" string<)
3725 (const :tag "Reverse alphabetical" string>)
3726 (function :tag "Custom function" nil)))
3728 (defvar org-tags-history nil
3729 "History of minibuffer reads for tags.")
3730 (defvar org-last-tags-completion-table nil
3731 "The last used completion table for tags.")
3732 (defvar org-after-tags-change-hook nil
3733 "Hook that is run after the tags in a line have changed.")
3735 (defgroup org-properties nil
3736 "Options concerning properties in Org-mode."
3737 :tag "Org Properties"
3738 :group 'org)
3740 (defcustom org-property-format "%-10s %s"
3741 "How property key/value pairs should be formatted by `indent-line'.
3742 When `indent-line' hits a property definition, it will format the line
3743 according to this format, mainly to make sure that the values are
3744 lined-up with respect to each other."
3745 :group 'org-properties
3746 :type 'string)
3748 (defcustom org-properties-postprocess-alist nil
3749 "Alist of properties and functions to adjust inserted values.
3750 Elements of this alist must be of the form
3752 ([string] [function])
3754 where [string] must be a property name and [function] must be a
3755 lambda expression: this lambda expression must take one argument,
3756 the value to adjust, and return the new value as a string.
3758 For example, this element will allow the property \"Remaining\"
3759 to be updated wrt the relation between the \"Effort\" property
3760 and the clock summary:
3762 ((\"Remaining\" (lambda(value)
3763 (let ((clocksum (org-clock-sum-current-item))
3764 (effort (org-duration-string-to-minutes
3765 (org-entry-get (point) \"Effort\"))))
3766 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3767 :group 'org-properties
3768 :version "24.1"
3769 :type '(alist :key-type (string :tag "Property")
3770 :value-type (function :tag "Function")))
3772 (defcustom org-use-property-inheritance nil
3773 "Non-nil means properties apply also for sublevels.
3775 This setting is chiefly used during property searches. Turning it on can
3776 cause significant overhead when doing a search, which is why it is not
3777 on by default.
3779 When nil, only the properties directly given in the current entry count.
3780 When t, every property is inherited. The value may also be a list of
3781 properties that should have inheritance, or a regular expression matching
3782 properties that should be inherited.
3784 However, note that some special properties use inheritance under special
3785 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3786 and the properties ending in \"_ALL\" when they are used as descriptor
3787 for valid values of a property.
3789 Note for programmers:
3790 When querying an entry with `org-entry-get', you can control if inheritance
3791 should be used. By default, `org-entry-get' looks only at the local
3792 properties. You can request inheritance by setting the inherit argument
3793 to t (to force inheritance) or to `selective' (to respect the setting
3794 in this variable)."
3795 :group 'org-properties
3796 :type '(choice
3797 (const :tag "Not" nil)
3798 (const :tag "Always" t)
3799 (repeat :tag "Specific properties" (string :tag "Property"))
3800 (regexp :tag "Properties matched by regexp")))
3802 (defun org-property-inherit-p (property)
3803 "Check if PROPERTY is one that should be inherited."
3804 (cond
3805 ((eq org-use-property-inheritance t) t)
3806 ((not org-use-property-inheritance) nil)
3807 ((stringp org-use-property-inheritance)
3808 (string-match org-use-property-inheritance property))
3809 ((listp org-use-property-inheritance)
3810 (member property org-use-property-inheritance))
3811 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3813 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3814 "The default column format, if no other format has been defined.
3815 This variable can be set on the per-file basis by inserting a line
3817 #+COLUMNS: %25ITEM ....."
3818 :group 'org-properties
3819 :type 'string)
3821 (defcustom org-columns-ellipses ".."
3822 "The ellipses to be used when a field in column view is truncated.
3823 When this is the empty string, as many characters as possible are shown,
3824 but then there will be no visual indication that the field has been truncated.
3825 When this is a string of length N, the last N characters of a truncated
3826 field are replaced by this string. If the column is narrower than the
3827 ellipses string, only part of the ellipses string will be shown."
3828 :group 'org-properties
3829 :type 'string)
3831 (defconst org-global-properties-fixed
3832 '(("VISIBILITY_ALL" . "folded children content all")
3833 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3834 "List of property/value pairs that can be inherited by any entry.
3836 These are fixed values, for the preset properties. The user variable
3837 that can be used to add to this list is `org-global-properties'.
3839 The entries in this list are cons cells where the car is a property
3840 name and cdr is a string with the value. If the value represents
3841 multiple items like an \"_ALL\" property, separate the items by
3842 spaces.")
3844 (defcustom org-global-properties nil
3845 "List of property/value pairs that can be inherited by any entry.
3847 This list will be combined with the constant `org-global-properties-fixed'.
3849 The entries in this list are cons cells where the car is a property
3850 name and cdr is a string with the value.
3852 You can set buffer-local values for the same purpose in the variable
3853 `org-file-properties' this by adding lines like
3855 #+PROPERTY: NAME VALUE"
3856 :group 'org-properties
3857 :type '(repeat
3858 (cons (string :tag "Property")
3859 (string :tag "Value"))))
3861 (defvar-local org-file-properties nil
3862 "List of property/value pairs that can be inherited by any entry.
3863 Valid for the current buffer.
3864 This variable is populated from #+PROPERTY lines.")
3866 (defgroup org-agenda nil
3867 "Options concerning agenda views in Org-mode."
3868 :tag "Org Agenda"
3869 :group 'org)
3871 (defvar-local org-category nil
3872 "Variable used by org files to set a category for agenda display.
3873 Such files should use a file variable to set it, for example
3875 # -*- mode: org; org-category: \"ELisp\"
3877 or contain a special line
3879 #+CATEGORY: ELisp
3881 If the file does not specify a category, then file's base name
3882 is used instead.")
3883 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3885 (defcustom org-agenda-files nil
3886 "The files to be used for agenda display.
3887 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3888 \\[org-remove-file]. You can also use customize to edit the list.
3890 If an entry is a directory, all files in that directory that are matched by
3891 `org-agenda-file-regexp' will be part of the file list.
3893 If the value of the variable is not a list but a single file name, then
3894 the list of agenda files is actually stored and maintained in that file, one
3895 agenda file per line. In this file paths can be given relative to
3896 `org-directory'. Tilde expansion and environment variable substitution
3897 are also made."
3898 :group 'org-agenda
3899 :type '(choice
3900 (repeat :tag "List of files and directories" file)
3901 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3903 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3904 "Regular expression to match files for `org-agenda-files'.
3905 If any element in the list in that variable contains a directory instead
3906 of a normal file, all files in that directory that are matched by this
3907 regular expression will be included."
3908 :group 'org-agenda
3909 :type 'regexp)
3911 (defcustom org-agenda-text-search-extra-files nil
3912 "List of extra files to be searched by text search commands.
3913 These files will be searched in addition to the agenda files by the
3914 commands `org-search-view' (`\\[org-agenda] s') \
3915 and `org-occur-in-agenda-files'.
3916 Note that these files will only be searched for text search commands,
3917 not for the other agenda views like todo lists, tag searches or the weekly
3918 agenda. This variable is intended to list notes and possibly archive files
3919 that should also be searched by these two commands.
3920 In fact, if the first element in the list is the symbol `agenda-archives',
3921 then all archive files of all agenda files will be added to the search
3922 scope."
3923 :group 'org-agenda
3924 :type '(set :greedy t
3925 (const :tag "Agenda Archives" agenda-archives)
3926 (repeat :inline t (file))))
3928 (defvaralias 'org-agenda-multi-occur-extra-files
3929 'org-agenda-text-search-extra-files)
3931 (defcustom org-agenda-skip-unavailable-files nil
3932 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3933 A nil value means to remove them, after a query, from the list."
3934 :group 'org-agenda
3935 :type 'boolean)
3937 (defcustom org-calendar-to-agenda-key [?c]
3938 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3939 The command `org-calendar-goto-agenda' will be bound to this key. The
3940 default is the character `c' because then `c' can be used to switch back and
3941 forth between agenda and calendar."
3942 :group 'org-agenda
3943 :type 'sexp)
3945 (defcustom org-calendar-insert-diary-entry-key [?i]
3946 "The key to be installed in `calendar-mode-map' for adding diary entries.
3947 This option is irrelevant until `org-agenda-diary-file' has been configured
3948 to point to an Org file. When that is the case, the command
3949 `org-agenda-diary-entry' will be bound to the key given here, by default
3950 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3951 if you want to continue doing this, you need to change this to a different
3952 key."
3953 :group 'org-agenda
3954 :type 'sexp)
3956 (defcustom org-agenda-diary-file 'diary-file
3957 "File to which to add new entries with the `i' key in agenda and calendar.
3958 When this is the symbol `diary-file', the functionality in the Emacs
3959 calendar will be used to add entries to the `diary-file'. But when this
3960 points to a file, `org-agenda-diary-entry' will be used instead."
3961 :group 'org-agenda
3962 :type '(choice
3963 (const :tag "The standard Emacs diary file" diary-file)
3964 (file :tag "Special Org file diary entries")))
3966 (eval-after-load "calendar"
3967 '(progn
3968 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3969 'org-calendar-goto-agenda)
3970 (add-hook 'calendar-mode-hook
3971 (lambda ()
3972 (unless (eq org-agenda-diary-file 'diary-file)
3973 (define-key calendar-mode-map
3974 org-calendar-insert-diary-entry-key
3975 'org-agenda-diary-entry))))))
3977 (defgroup org-latex nil
3978 "Options for embedding LaTeX code into Org-mode."
3979 :tag "Org LaTeX"
3980 :group 'org)
3982 (defcustom org-format-latex-options
3983 '(:foreground default :background default :scale 1.0
3984 :html-foreground "Black" :html-background "Transparent"
3985 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3986 "Options for creating images from LaTeX fragments.
3987 This is a property list with the following properties:
3988 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3989 `default' means use the foreground of the default face.
3990 `auto' means use the foreground from the text face.
3991 :background the background color, or \"Transparent\".
3992 `default' means use the background of the default face.
3993 `auto' means use the background from the text face.
3994 :scale a scaling factor for the size of the images, to get more pixels
3995 :html-foreground, :html-background, :html-scale
3996 the same numbers for HTML export.
3997 :matchers a list indicating which matchers should be used to
3998 find LaTeX fragments. Valid members of this list are:
3999 \"begin\" find environments
4000 \"$1\" find single characters surrounded by $.$
4001 \"$\" find math expressions surrounded by $...$
4002 \"$$\" find math expressions surrounded by $$....$$
4003 \"\\(\" find math expressions surrounded by \\(...\\)
4004 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4005 :group 'org-latex
4006 :type 'plist)
4008 (defcustom org-format-latex-signal-error t
4009 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4010 When nil, just push out a message."
4011 :group 'org-latex
4012 :version "24.1"
4013 :type 'boolean)
4015 (defcustom org-latex-to-mathml-jar-file nil
4016 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4017 Use this to specify additional executable file say a jar file.
4019 When using MathToWeb as the converter, specify the full-path to
4020 your mathtoweb.jar file."
4021 :group 'org-latex
4022 :version "24.1"
4023 :type '(choice
4024 (const :tag "None" nil)
4025 (file :tag "JAR file" :must-match t)))
4027 (defcustom org-latex-to-mathml-convert-command nil
4028 "Command to convert LaTeX fragments to MathML.
4029 Replace format-specifiers in the command as noted below and use
4030 `shell-command' to convert LaTeX to MathML.
4031 %j: Executable file in fully expanded form as specified by
4032 `org-latex-to-mathml-jar-file'.
4033 %I: Input LaTeX file in fully expanded form.
4034 %i: The latex fragment to be converted.
4035 %o: Output MathML file.
4037 This command is used by `org-create-math-formula'.
4039 When using MathToWeb as the converter, set this option to
4040 \"java -jar %j -unicode -force -df %o %I\".
4042 When using LaTeXML set this option to
4043 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4044 :group 'org-latex
4045 :version "24.1"
4046 :type '(choice
4047 (const :tag "None" nil)
4048 (string :tag "\nShell command")))
4050 (defcustom org-preview-latex-default-process 'dvipng
4051 "The default process to convert LaTeX fragments to image files.
4052 All available processes and theirs documents can be found in
4053 `org-preview-latex-process-alist', which see."
4054 :group 'org-latex
4055 :version "25.2"
4056 :package-version '(Org . "9.0")
4057 :type 'symbol)
4059 (defcustom org-preview-latex-process-alist
4060 '((dvipng
4061 :programs ("latex" "dvipng" "gs")
4062 :description "dvi > png"
4063 :message "you need to install the programs: latex, dvipng and ghostscript."
4064 :image-input-type "dvi"
4065 :image-output-type "png"
4066 :image-size-adjust (1.0 . 1.0)
4067 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4068 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4069 (dvisvgm
4070 :programs ("latex" "dvisvgm" "gs")
4071 :description "dvi > svg"
4072 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4073 :use-xcolor t
4074 :image-input-type "dvi"
4075 :image-output-type "svg"
4076 :image-size-adjust (1.7 . 1.5)
4077 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4078 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4079 (imagemagick
4080 :programs ("latex" "convert" "gs")
4081 :description "pdf > png"
4082 :message
4083 "you need to install the programs: latex, imagemagick and ghostscript."
4084 :use-xcolor t
4085 :image-input-type "pdf"
4086 :image-output-type "png"
4087 :image-size-adjust (1.0 . 1.0)
4088 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4089 :image-converter
4090 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4091 "Definitions of external processes for LaTeX previewing.
4092 Org mode can use some external commands to generate TeX snippet's images for
4093 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4094 `org-create-formula-image' how to call them.
4096 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4097 PROPERTIES accepts the following attributes:
4099 :programs list of strings, required programs.
4100 :description string, describe the process.
4101 :message string, message it when required programs cannot be found.
4102 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4103 :image-output-type string, output file type of image converter (e.g., \"png\").
4104 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4105 deal with background and foreground color of image.
4106 Otherwise, dvipng style background and foregroud color
4107 format are generated. You may then refer to them in
4108 command options with \"%F\" and \"%B\".
4109 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4110 image size showed in buffer and the cdr element is for
4111 HTML file. This option is only useful for process
4112 developers, users should use variable
4113 `org-format-latex-options' instead.
4114 :post-clean list of strings, files matched are to be cleaned up once
4115 the image is generated. When nil, the files with \".dvi\",
4116 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4117 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4118 be cleaned up.
4119 :latex-header list of strings, the LaTeX header of the snippet file.
4120 When nil, the fallback value is used instead, which is
4121 controlled by `org-format-latex-header',
4122 `org-latex-default-packages-alist' and
4123 `org-latex-packages-alist', which see.
4124 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4125 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4126 replaced with values defined below.
4127 :image-converter list of image converter commands strings. Each of them is
4128 given to the shell and supports any of the following
4129 place-holders defined below.
4131 Place-holders used by `:image-converter' and `:latex-compiler':
4133 %f input file name.
4134 %b base name of input file.
4135 %o base directory of input file.
4137 Place-holders only used by `:image-converter':
4139 %F foreground of image
4140 %B background of image
4141 %D dpi, which is used to adjust image size by some processing commands.
4142 %S the image size scale ratio, which is used to adjust image size by some
4143 processing commands."
4144 :group 'org-latex
4145 :version "25.2"
4146 :package-version '(Org . "9.0")
4147 :type '(alist :tag "LaTeX to image backends"
4148 :value-type (plist)))
4150 (defcustom org-preview-latex-image-directory "ltximg/"
4151 "Path to store latex preview images.
4152 A relative path here creates many directories relative to the
4153 processed org files paths. An absolute path puts all preview
4154 images at the same place."
4155 :group 'org-latex
4156 :version "25.1"
4157 :package-version '(Org . "9.0")
4158 :type 'string)
4160 (defun org-format-latex-mathml-available-p ()
4161 "Return t if `org-latex-to-mathml-convert-command' is usable."
4162 (save-match-data
4163 (when (and (boundp 'org-latex-to-mathml-convert-command)
4164 org-latex-to-mathml-convert-command)
4165 (let ((executable (car (split-string
4166 org-latex-to-mathml-convert-command))))
4167 (when (executable-find executable)
4168 (if (string-match
4169 "%j" org-latex-to-mathml-convert-command)
4170 (file-readable-p org-latex-to-mathml-jar-file)
4171 t))))))
4173 (defcustom org-format-latex-header "\\documentclass{article}
4174 \\usepackage[usenames]{color}
4175 \[PACKAGES]
4176 \[DEFAULT-PACKAGES]
4177 \\pagestyle{empty} % do not remove
4178 % The settings below are copied from fullpage.sty
4179 \\setlength{\\textwidth}{\\paperwidth}
4180 \\addtolength{\\textwidth}{-3cm}
4181 \\setlength{\\oddsidemargin}{1.5cm}
4182 \\addtolength{\\oddsidemargin}{-2.54cm}
4183 \\setlength{\\evensidemargin}{\\oddsidemargin}
4184 \\setlength{\\textheight}{\\paperheight}
4185 \\addtolength{\\textheight}{-\\headheight}
4186 \\addtolength{\\textheight}{-\\headsep}
4187 \\addtolength{\\textheight}{-\\footskip}
4188 \\addtolength{\\textheight}{-3cm}
4189 \\setlength{\\topmargin}{1.5cm}
4190 \\addtolength{\\topmargin}{-2.54cm}"
4191 "The document header used for processing LaTeX fragments.
4192 It is imperative that this header make sure that no page number
4193 appears on the page. The package defined in the variables
4194 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4195 will either replace the placeholder \"[PACKAGES]\" in this
4196 header, or they will be appended."
4197 :group 'org-latex
4198 :type 'string)
4200 (defun org-set-packages-alist (var val)
4201 "Set the packages alist and make sure it has 3 elements per entry."
4202 (set var (mapcar (lambda (x)
4203 (if (and (consp x) (= (length x) 2))
4204 (list (car x) (nth 1 x) t)
4206 val)))
4208 (defun org-get-packages-alist (var)
4209 "Get the packages alist and make sure it has 3 elements per entry."
4210 (mapcar (lambda (x)
4211 (if (and (consp x) (= (length x) 2))
4212 (list (car x) (nth 1 x) t)
4214 (default-value var)))
4216 (defcustom org-latex-default-packages-alist
4217 '(("AUTO" "inputenc" t ("pdflatex"))
4218 ("T1" "fontenc" t ("pdflatex"))
4219 ("" "graphicx" t)
4220 ("" "grffile" t)
4221 ("" "longtable" nil)
4222 ("" "wrapfig" nil)
4223 ("" "rotating" nil)
4224 ("normalem" "ulem" t)
4225 ("" "amsmath" t)
4226 ("" "textcomp" t)
4227 ("" "amssymb" t)
4228 ("" "capt-of" nil)
4229 ("" "hyperref" nil))
4230 "Alist of default packages to be inserted in the header.
4232 Change this only if one of the packages here causes an
4233 incompatibility with another package you are using.
4235 The packages in this list are needed by one part or another of
4236 Org mode to function properly:
4238 - inputenc, fontenc: for basic font and character selection
4239 - graphicx: for including images
4240 - grffile: allow periods and spaces in graphics file names
4241 - longtable: For multipage tables
4242 - wrapfig: for figure placement
4243 - rotating: for sideways figures and tables
4244 - ulem: for underline and strike-through
4245 - amsmath: for subscript and superscript and math environments
4246 - textcomp, amssymb: for various symbols used
4247 for interpreting the entities in `org-entities'. You can skip
4248 some of these packages if you don't use any of their symbols.
4249 - capt-of: for captions outside of floats
4250 - hyperref: for cross references
4252 Therefore you should not modify this variable unless you know
4253 what you are doing. The one reason to change it anyway is that
4254 you might be loading some other package that conflicts with one
4255 of the default packages. Each element is either a cell or
4256 a string.
4258 A cell is of the format
4260 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4262 If SNIPPET-FLAG is non-nil, the package also needs to be included
4263 when compiling LaTeX snippets into images for inclusion into
4264 non-LaTeX output. COMPILERS is a list of compilers that should
4265 include the package, see `org-latex-compiler'. If the document
4266 compiler is not in the list, and the list is non-nil, the package
4267 will not be inserted in the final document.
4269 A string will be inserted as-is in the header of the document."
4270 :group 'org-latex
4271 :group 'org-export-latex
4272 :set 'org-set-packages-alist
4273 :get 'org-get-packages-alist
4274 :version "25.1"
4275 :package-version '(Org . "8.3")
4276 :type '(repeat
4277 (choice
4278 (list :tag "options/package pair"
4279 (string :tag "options")
4280 (string :tag "package")
4281 (boolean :tag "Snippet"))
4282 (string :tag "A line of LaTeX"))))
4284 (defcustom org-latex-packages-alist nil
4285 "Alist of packages to be inserted in every LaTeX header.
4287 These will be inserted after `org-latex-default-packages-alist'.
4288 Each element is either a cell or a string.
4290 A cell is of the format:
4292 (\"options\" \"package\" SNIPPET-FLAG)
4294 SNIPPET-FLAG, when non-nil, indicates that this package is also
4295 needed when turning LaTeX snippets into images for inclusion into
4296 non-LaTeX output.
4298 A string will be inserted as-is in the header of the document.
4300 Make sure that you only list packages here which:
4302 - you want in every file;
4303 - do not conflict with the setup in `org-format-latex-header';
4304 - do not conflict with the default packages in
4305 `org-latex-default-packages-alist'."
4306 :group 'org-latex
4307 :group 'org-export-latex
4308 :set 'org-set-packages-alist
4309 :get 'org-get-packages-alist
4310 :type '(repeat
4311 (choice
4312 (list :tag "options/package pair"
4313 (string :tag "options")
4314 (string :tag "package")
4315 (boolean :tag "Snippet"))
4316 (string :tag "A line of LaTeX"))))
4318 (defgroup org-appearance nil
4319 "Settings for Org mode appearance."
4320 :tag "Org Appearance"
4321 :group 'org)
4323 (defcustom org-level-color-stars-only nil
4324 "Non-nil means fontify only the stars in each headline.
4325 When nil, the entire headline is fontified.
4326 Changing it requires restart of `font-lock-mode' to become effective
4327 also in regions already fontified."
4328 :group 'org-appearance
4329 :type 'boolean)
4331 (defcustom org-hide-leading-stars nil
4332 "Non-nil means hide the first N-1 stars in a headline.
4333 This works by using the face `org-hide' for these stars. This
4334 face is white for a light background, and black for a dark
4335 background. You may have to customize the face `org-hide' to
4336 make this work.
4337 Changing it requires restart of `font-lock-mode' to become effective
4338 also in regions already fontified.
4339 You may also set this on a per-file basis by adding one of the following
4340 lines to the buffer:
4342 #+STARTUP: hidestars
4343 #+STARTUP: showstars"
4344 :group 'org-appearance
4345 :type 'boolean)
4347 (defcustom org-hidden-keywords nil
4348 "List of symbols corresponding to keywords to be hidden the org buffer.
4349 For example, a value \\='(title) for this list will make the document's title
4350 appear in the buffer without the initial #+TITLE: keyword."
4351 :group 'org-appearance
4352 :version "24.1"
4353 :type '(set (const :tag "#+AUTHOR" author)
4354 (const :tag "#+DATE" date)
4355 (const :tag "#+EMAIL" email)
4356 (const :tag "#+TITLE" title)))
4358 (defcustom org-custom-properties nil
4359 "List of properties (as strings) with a special meaning.
4360 The default use of these custom properties is to let the user
4361 hide them with `org-toggle-custom-properties-visibility'."
4362 :group 'org-properties
4363 :group 'org-appearance
4364 :version "24.3"
4365 :type '(repeat (string :tag "Property Name")))
4367 (defcustom org-fontify-done-headline nil
4368 "Non-nil means change the face of a headline if it is marked DONE.
4369 Normally, only the TODO/DONE keyword indicates the state of a headline.
4370 When this is non-nil, the headline after the keyword is set to the
4371 `org-headline-done' as an additional indication."
4372 :group 'org-appearance
4373 :type 'boolean)
4375 (defcustom org-fontify-emphasized-text t
4376 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4377 Changing this variable requires a restart of Emacs to take effect."
4378 :group 'org-appearance
4379 :type 'boolean)
4381 (defcustom org-fontify-whole-heading-line nil
4382 "Non-nil means fontify the whole line for headings.
4383 This is useful when setting a background color for the
4384 org-level-* faces."
4385 :group 'org-appearance
4386 :type 'boolean)
4388 (defcustom org-highlight-latex-and-related nil
4389 "Non-nil means highlight LaTeX related syntax in the buffer.
4390 When non nil, the value should be a list containing any of the
4391 following symbols:
4392 `latex' Highlight LaTeX snippets and environments.
4393 `script' Highlight subscript and superscript.
4394 `entities' Highlight entities."
4395 :group 'org-appearance
4396 :version "24.4"
4397 :package-version '(Org . "8.0")
4398 :type '(choice
4399 (const :tag "No highlighting" nil)
4400 (set :greedy t :tag "Highlight"
4401 (const :tag "LaTeX snippets and environments" latex)
4402 (const :tag "Subscript and superscript" script)
4403 (const :tag "Entities" entities))))
4405 (defcustom org-hide-emphasis-markers nil
4406 "Non-nil mean font-lock should hide the emphasis marker characters."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-hide-macro-markers nil
4411 "Non-nil mean font-lock should hide the brackets marking macro calls."
4412 :group 'org-appearance
4413 :type 'boolean)
4415 (defcustom org-pretty-entities nil
4416 "Non-nil means show entities as UTF8 characters.
4417 When nil, the \\name form remains in the buffer."
4418 :group 'org-appearance
4419 :version "24.1"
4420 :type 'boolean)
4422 (defcustom org-pretty-entities-include-sub-superscripts t
4423 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4424 :group 'org-appearance
4425 :version "24.1"
4426 :type 'boolean)
4428 (defvar org-emph-re nil
4429 "Regular expression for matching emphasis.
4430 After a match, the match groups contain these elements:
4431 0 The match of the full regular expression, including the characters
4432 before and after the proper match
4433 1 The character before the proper match, or empty at beginning of line
4434 2 The proper match, including the leading and trailing markers
4435 3 The leading marker like * or /, indicating the type of highlighting
4436 4 The text between the emphasis markers, not including the markers
4437 5 The character after the match, empty at the end of a line")
4438 (defvar org-verbatim-re nil
4439 "Regular expression for matching verbatim text.")
4440 (defvar org-emphasis-regexp-components) ; defined just below
4441 (defvar org-emphasis-alist) ; defined just below
4442 (defun org-set-emph-re (var val)
4443 "Set variable and compute the emphasis regular expression."
4444 (set var val)
4445 (when (and (boundp 'org-emphasis-alist)
4446 (boundp 'org-emphasis-regexp-components)
4447 org-emphasis-alist org-emphasis-regexp-components)
4448 (let* ((e org-emphasis-regexp-components)
4449 (pre (car e))
4450 (post (nth 1 e))
4451 (border (nth 2 e))
4452 (body (nth 3 e))
4453 (nl (nth 4 e))
4454 (body1 (concat body "*?"))
4455 (markers (mapconcat 'car org-emphasis-alist ""))
4456 (vmarkers (mapconcat
4457 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4458 org-emphasis-alist "")))
4459 ;; make sure special characters appear at the right position in the class
4460 (if (string-match "\\^" markers)
4461 (setq markers (concat (replace-match "" t t markers) "^")))
4462 (if (string-match "-" markers)
4463 (setq markers (concat (replace-match "" t t markers) "-")))
4464 (if (string-match "\\^" vmarkers)
4465 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4466 (if (string-match "-" vmarkers)
4467 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4468 (if (> nl 0)
4469 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4470 (int-to-string nl) "\\}")))
4471 ;; Make the regexp
4472 (setq org-emph-re
4473 (concat "\\([" pre "]\\|^\\)"
4474 "\\("
4475 "\\([" markers "]\\)"
4476 "\\("
4477 "[^" border "]\\|"
4478 "[^" border "]"
4479 body1
4480 "[^" border "]"
4481 "\\)"
4482 "\\3\\)"
4483 "\\([" post "]\\|$\\)"))
4484 (setq org-verbatim-re
4485 (concat "\\([" pre "]\\|^\\)"
4486 "\\("
4487 "\\([" vmarkers "]\\)"
4488 "\\("
4489 "[^" border "]\\|"
4490 "[^" border "]"
4491 body1
4492 "[^" border "]"
4493 "\\)"
4494 "\\3\\)"
4495 "\\([" post "]\\|$\\)")))))
4497 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4498 ;; set this option proved cumbersome. See this message/thread:
4499 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4500 (defvar org-emphasis-regexp-components
4501 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4502 "Components used to build the regular expression for emphasis.
4503 This is a list with five entries. Terminology: In an emphasis string
4504 like \" *strong word* \", we call the initial space PREMATCH, the final
4505 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4506 and \"trong wor\" is the body. The different components in this variable
4507 specify what is allowed/forbidden in each part:
4509 pre Chars allowed as prematch. Beginning of line will be allowed too.
4510 post Chars allowed as postmatch. End of line will be allowed too.
4511 border The chars *forbidden* as border characters.
4512 body-regexp A regexp like \".\" to match a body character. Don't use
4513 non-shy groups here, and don't allow newline here.
4514 newline The maximum number of newlines allowed in an emphasis exp.
4516 You need to reload Org or to restart Emacs after customizing this.")
4518 (defcustom org-emphasis-alist
4519 '(("*" bold)
4520 ("/" italic)
4521 ("_" underline)
4522 ("=" org-verbatim verbatim)
4523 ("~" org-code verbatim)
4524 ("+" (:strike-through t)))
4525 "Alist of characters and faces to emphasize text.
4526 Text starting and ending with a special character will be emphasized,
4527 for example *bold*, _underlined_ and /italic/. This variable sets the
4528 marker characters and the face to be used by font-lock for highlighting
4529 in Org buffers.
4531 You need to reload Org or to restart Emacs after customizing this."
4532 :group 'org-appearance
4533 :set 'org-set-emph-re
4534 :version "24.4"
4535 :package-version '(Org . "8.0")
4536 :type '(repeat
4537 (list
4538 (string :tag "Marker character")
4539 (choice
4540 (face :tag "Font-lock-face")
4541 (plist :tag "Face property list"))
4542 (option (const verbatim)))))
4544 (defvar org-protecting-blocks '("src" "example" "export")
4545 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4546 This is needed for font-lock setup.")
4548 ;;; Functions and variables from their packages
4549 ;; Declared here to avoid compiler warnings
4550 (defvar mark-active)
4552 ;; Various packages
4553 (declare-function calc-eval "calc" (str &optional separator &rest args))
4554 (declare-function calendar-forward-day "cal-move" (arg))
4555 (declare-function calendar-goto-date "cal-move" (date))
4556 (declare-function calendar-goto-today "cal-move" ())
4557 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4558 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4559 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4560 (declare-function cdlatex-tab "ext:cdlatex" ())
4561 (declare-function dired-get-filename
4562 "dired"
4563 (&optional localp no-error-if-not-filep))
4564 (declare-function iswitchb-read-buffer
4565 "iswitchb"
4566 (prompt &optional
4567 default require-match _predicate start matches-set))
4568 (declare-function org-agenda-change-all-lines
4569 "org-agenda"
4570 (newhead hdmarker &optional fixface just-this))
4571 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4572 "org-agenda"
4573 (&optional end))
4574 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4575 (declare-function org-agenda-format-item
4576 "org-agenda"
4577 (extra txt &optional level category tags dotime
4578 remove-re habitp))
4579 (declare-function org-agenda-maybe-redo "org-agenda" ())
4580 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4581 (declare-function org-agenda-save-markers-for-cut-and-paste
4582 "org-agenda"
4583 (beg end))
4584 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4585 (declare-function org-agenda-skip "org-agenda" ())
4586 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4587 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4588 (declare-function org-indent-mode "org-indent" (&optional arg))
4589 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4590 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4591 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4592 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4593 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4594 (declare-function parse-time-string "parse-time" (string))
4595 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4597 (defvar align-mode-rules-list)
4598 (defvar calc-embedded-close-formula)
4599 (defvar calc-embedded-open-formula)
4600 (defvar calc-embedded-open-mode)
4601 (defvar font-lock-unfontify-region-function)
4602 (defvar iswitchb-temp-buflist)
4603 (defvar org-agenda-tags-todo-honor-ignore-options)
4604 (defvar remember-data-file)
4605 (defvar texmathp-why)
4607 ;;;###autoload
4608 (defun turn-on-orgtbl ()
4609 "Unconditionally turn on `orgtbl-mode'."
4610 (require 'org-table)
4611 (orgtbl-mode 1))
4613 (defun org-at-table-p (&optional table-type)
4614 "Non-nil if the cursor is inside an Org table.
4615 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4616 If `org-enable-table-editor' is nil, return nil unconditionally."
4617 (and
4618 org-enable-table-editor
4619 (save-excursion
4620 (beginning-of-line)
4621 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4622 (or (not (derived-mode-p 'org-mode))
4623 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4624 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4626 (defun org-at-table.el-p ()
4627 "Non-nil when point is at a table.el table."
4628 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4629 (let ((element (org-element-at-point)))
4630 (and (eq (org-element-type element) 'table)
4631 (eq (org-element-property :type element) 'table.el)))))
4633 (defun org-at-table-hline-p ()
4634 "Non-nil when point is inside a hline in a table.
4635 Assume point is already in a table. If `org-enable-table-editor'
4636 is nil, return nil unconditionally."
4637 (and org-enable-table-editor
4638 (save-excursion
4639 (beginning-of-line)
4640 (looking-at org-table-hline-regexp))))
4642 (defun org-table-map-tables (function &optional quietly)
4643 "Apply FUNCTION to the start of all tables in the buffer."
4644 (org-with-wide-buffer
4645 (goto-char (point-min))
4646 (while (re-search-forward org-table-any-line-regexp nil t)
4647 (unless quietly
4648 (message "Mapping tables: %d%%"
4649 (floor (* 100.0 (point)) (buffer-size))))
4650 (beginning-of-line 1)
4651 (when (and (looking-at org-table-line-regexp)
4652 ;; Exclude tables in src/example/verbatim/clocktable blocks
4653 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4654 (save-excursion (funcall function))
4655 (or (looking-at org-table-line-regexp)
4656 (forward-char 1)))
4657 (re-search-forward org-table-any-border-regexp nil 1)))
4658 (unless quietly (message "Mapping tables: done")))
4660 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4661 (declare-function org-clock-update-mode-line "org-clock" ())
4662 (declare-function org-resolve-clocks "org-clock"
4663 (&optional also-non-dangling-p prompt last-valid))
4665 (defun org-at-TBLFM-p (&optional pos)
4666 "Non-nil when point (or POS) is in #+TBLFM line."
4667 (save-excursion
4668 (goto-char (or pos (point)))
4669 (beginning-of-line)
4670 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4671 (eq (org-element-type (org-element-at-point)) 'table))))
4673 (defvar org-clock-start-time)
4674 (defvar org-clock-marker (make-marker)
4675 "Marker recording the last clock-in.")
4676 (defvar org-clock-hd-marker (make-marker)
4677 "Marker recording the last clock-in, but the headline position.")
4678 (defvar org-clock-heading ""
4679 "The heading of the current clock entry.")
4680 (defun org-clock-is-active ()
4681 "Return the buffer where the clock is currently running.
4682 Return nil if no clock is running."
4683 (marker-buffer org-clock-marker))
4685 (defun org-check-running-clock ()
4686 "Check if the current buffer contains the running clock.
4687 If yes, offer to stop it and to save the buffer with the changes."
4688 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4689 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4690 (buffer-name))))
4691 (org-clock-out)
4692 (when (y-or-n-p "Save changed buffer?")
4693 (save-buffer))))
4695 (defun org-clocktable-try-shift (dir n)
4696 "Check if this line starts a clock table, if yes, shift the time block."
4697 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4698 (org-clocktable-shift dir n)))
4700 ;;;###autoload
4701 (defun org-clock-persistence-insinuate ()
4702 "Set up hooks for clock persistence."
4703 (require 'org-clock)
4704 (add-hook 'org-mode-hook 'org-clock-load)
4705 (add-hook 'kill-emacs-hook 'org-clock-save))
4707 (defgroup org-archive nil
4708 "Options concerning archiving in Org-mode."
4709 :tag "Org Archive"
4710 :group 'org-structure)
4712 (defcustom org-archive-location "%s_archive::"
4713 "The location where subtrees should be archived.
4715 The value of this variable is a string, consisting of two parts,
4716 separated by a double-colon. The first part is a filename and
4717 the second part is a headline.
4719 When the filename is omitted, archiving happens in the same file.
4720 %s in the filename will be replaced by the current file
4721 name (without the directory part). Archiving to a different file
4722 is useful to keep archived entries from contributing to the
4723 Org Agenda.
4725 The archived entries will be filed as subtrees of the specified
4726 headline. When the headline is omitted, the subtrees are simply
4727 filed away at the end of the file, as top-level entries. Also in
4728 the heading you can use %s to represent the file name, this can be
4729 useful when using the same archive for a number of different files.
4731 Here are a few examples:
4732 \"%s_archive::\"
4733 If the current file is Projects.org, archive in file
4734 Projects.org_archive, as top-level trees. This is the default.
4736 \"::* Archived Tasks\"
4737 Archive in the current file, under the top-level headline
4738 \"* Archived Tasks\".
4740 \"~/org/archive.org::\"
4741 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4743 \"~/org/archive.org::* From %s\"
4744 Archive in file ~/org/archive.org (absolute path), under headlines
4745 \"From FILENAME\" where file name is the current file name.
4747 \"~/org/datetree.org::datetree/* Finished Tasks\"
4748 The \"datetree/\" string is special, signifying to archive
4749 items to the datetree. Items are placed in either the CLOSED
4750 date of the item, or the current date if there is no CLOSED date.
4751 The heading will be a subentry to the current date. There doesn't
4752 need to be a heading, but there always needs to be a slash after
4753 datetree. For example, to store archived items directly in the
4754 datetree, use \"~/org/datetree.org::datetree/\".
4756 \"basement::** Finished Tasks\"
4757 Archive in file ./basement (relative path), as level 3 trees
4758 below the level 2 heading \"** Finished Tasks\".
4760 You may set this option on a per-file basis by adding to the buffer a
4761 line like
4763 #+ARCHIVE: basement::** Finished Tasks
4765 You may also define it locally for a subtree by setting an ARCHIVE property
4766 in the entry. If such a property is found in an entry, or anywhere up
4767 the hierarchy, it will be used."
4768 :group 'org-archive
4769 :type 'string)
4771 (defcustom org-agenda-skip-archived-trees t
4772 "Non-nil means the agenda will skip any items located in archived trees.
4773 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4774 variable is no longer recommended, you should leave it at the value t.
4775 Instead, use the key `v' to cycle the archives-mode in the agenda."
4776 :group 'org-archive
4777 :group 'org-agenda-skip
4778 :type 'boolean)
4780 (defcustom org-columns-skip-archived-trees t
4781 "Non-nil means ignore archived trees when creating column view."
4782 :group 'org-archive
4783 :group 'org-properties
4784 :type 'boolean)
4786 (defcustom org-cycle-open-archived-trees nil
4787 "Non-nil means `org-cycle' will open archived trees.
4788 An archived tree is a tree marked with the tag ARCHIVE.
4789 When nil, archived trees will stay folded. You can still open them with
4790 normal outline commands like `show-all', but not with the cycling commands."
4791 :group 'org-archive
4792 :group 'org-cycle
4793 :type 'boolean)
4795 (defcustom org-sparse-tree-open-archived-trees nil
4796 "Non-nil means sparse tree construction shows matches in archived trees.
4797 When nil, matches in these trees are highlighted, but the trees are kept in
4798 collapsed state."
4799 :group 'org-archive
4800 :group 'org-sparse-trees
4801 :type 'boolean)
4803 (defcustom org-sparse-tree-default-date-type nil
4804 "The default date type when building a sparse tree.
4805 When this is nil, a date is a scheduled or a deadline timestamp.
4806 Otherwise, these types are allowed:
4808 all: all timestamps
4809 active: only active timestamps (<...>)
4810 inactive: only inactive timestamps ([...])
4811 scheduled: only scheduled timestamps
4812 deadline: only deadline timestamps"
4813 :type '(choice (const :tag "Scheduled or deadline" nil)
4814 (const :tag "All timestamps" all)
4815 (const :tag "Only active timestamps" active)
4816 (const :tag "Only inactive timestamps" inactive)
4817 (const :tag "Only scheduled timestamps" scheduled)
4818 (const :tag "Only deadline timestamps" deadline)
4819 (const :tag "Only closed timestamps" closed))
4820 :version "25.1"
4821 :package-version '(Org . "8.3")
4822 :group 'org-sparse-trees)
4824 (defun org-cycle-hide-archived-subtrees (state)
4825 "Re-hide all archived subtrees after a visibility state change."
4826 (when (and (not org-cycle-open-archived-trees)
4827 (not (memq state '(overview folded))))
4828 (save-excursion
4829 (let* ((globalp (memq state '(contents all)))
4830 (beg (if globalp (point-min) (point)))
4831 (end (if globalp (point-max) (org-end-of-subtree t))))
4832 (org-hide-archived-subtrees beg end)
4833 (goto-char beg)
4834 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4835 (message "%s" (substitute-command-keys
4836 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4838 (defun org-force-cycle-archived ()
4839 "Cycle subtree even if it is archived."
4840 (interactive)
4841 (setq this-command 'org-cycle)
4842 (let ((org-cycle-open-archived-trees t))
4843 (call-interactively 'org-cycle)))
4845 (defun org-hide-archived-subtrees (beg end)
4846 "Re-hide all archived subtrees after a visibility state change."
4847 (org-with-wide-buffer
4848 (let ((case-fold-search nil)
4849 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4850 (goto-char beg)
4851 ;; Include headline point is currently on.
4852 (beginning-of-line)
4853 (while (and (< (point) end) (re-search-forward re end t))
4854 (when (member org-archive-tag (org-get-tags))
4855 (org-flag-subtree t)
4856 (org-end-of-subtree t))))))
4858 (declare-function outline-end-of-heading "outline" ())
4859 (declare-function outline-flag-region "outline" (from to flag))
4860 (defun org-flag-subtree (flag)
4861 (save-excursion
4862 (org-back-to-heading t)
4863 (outline-end-of-heading)
4864 (outline-flag-region (point)
4865 (progn (org-end-of-subtree t) (point))
4866 flag)))
4868 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4870 ;; Declare Column View Code
4872 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4873 (declare-function org-columns-compute "org-colview" (property))
4875 ;; Declare ID code
4877 (declare-function org-id-store-link "org-id")
4878 (declare-function org-id-locations-load "org-id")
4879 (declare-function org-id-locations-save "org-id")
4880 (defvar org-id-track-globally)
4882 ;;; Variables for pre-computed regular expressions, all buffer local
4884 (defvar-local org-todo-regexp nil
4885 "Matches any of the TODO state keywords.")
4886 (defvar-local org-not-done-regexp nil
4887 "Matches any of the TODO state keywords except the last one.")
4888 (defvar-local org-not-done-heading-regexp nil
4889 "Matches a TODO headline that is not done.")
4890 (defvar-local org-todo-line-regexp nil
4891 "Matches a headline and puts TODO state into group 2 if present.")
4892 (defvar-local org-complex-heading-regexp nil
4893 "Matches a headline and puts everything into groups:
4894 group 1: the stars
4895 group 2: The todo keyword, maybe
4896 group 3: Priority cookie
4897 group 4: True headline
4898 group 5: Tags")
4899 (defvar-local org-complex-heading-regexp-format nil
4900 "Printf format to make regexp to match an exact headline.
4901 This regexp will match the headline of any node which has the
4902 exact headline text that is put into the format, but may have any
4903 TODO state, priority and tags.")
4904 (defvar-local org-todo-line-tags-regexp nil
4905 "Matches a headline and puts TODO state into group 2 if present.
4906 Also put tags into group 4 if tags are present.")
4908 (defconst org-plain-time-of-day-regexp
4909 (concat
4910 "\\(\\<[012]?[0-9]"
4911 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4912 "\\(--?"
4913 "\\(\\<[012]?[0-9]"
4914 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4915 "\\)?")
4916 "Regular expression to match a plain time or time range.
4917 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4918 groups carry important information:
4919 0 the full match
4920 1 the first time, range or not
4921 8 the second time, if it is a range.")
4923 (defconst org-plain-time-extension-regexp
4924 (concat
4925 "\\(\\<[012]?[0-9]"
4926 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4927 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4928 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4929 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4930 groups carry important information:
4931 0 the full match
4932 7 hours of duration
4933 9 minutes of duration")
4935 (defconst org-stamp-time-of-day-regexp
4936 (concat
4937 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4938 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4939 "\\(--?"
4940 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4941 "Regular expression to match a timestamp time or time range.
4942 After a match, the following groups carry important information:
4943 0 the full match
4944 1 date plus weekday, for back referencing to make sure both times are on the same day
4945 2 the first time, range or not
4946 4 the second time, if it is a range.")
4948 (defconst org-startup-options
4949 '(("fold" org-startup-folded t)
4950 ("overview" org-startup-folded t)
4951 ("nofold" org-startup-folded nil)
4952 ("showall" org-startup-folded nil)
4953 ("showeverything" org-startup-folded showeverything)
4954 ("content" org-startup-folded content)
4955 ("indent" org-startup-indented t)
4956 ("noindent" org-startup-indented nil)
4957 ("hidestars" org-hide-leading-stars t)
4958 ("showstars" org-hide-leading-stars nil)
4959 ("odd" org-odd-levels-only t)
4960 ("oddeven" org-odd-levels-only nil)
4961 ("align" org-startup-align-all-tables t)
4962 ("noalign" org-startup-align-all-tables nil)
4963 ("inlineimages" org-startup-with-inline-images t)
4964 ("noinlineimages" org-startup-with-inline-images nil)
4965 ("latexpreview" org-startup-with-latex-preview t)
4966 ("nolatexpreview" org-startup-with-latex-preview nil)
4967 ("customtime" org-display-custom-times t)
4968 ("logdone" org-log-done time)
4969 ("lognotedone" org-log-done note)
4970 ("nologdone" org-log-done nil)
4971 ("lognoteclock-out" org-log-note-clock-out t)
4972 ("nolognoteclock-out" org-log-note-clock-out nil)
4973 ("logrepeat" org-log-repeat state)
4974 ("lognoterepeat" org-log-repeat note)
4975 ("logdrawer" org-log-into-drawer t)
4976 ("nologdrawer" org-log-into-drawer nil)
4977 ("logstatesreversed" org-log-states-order-reversed t)
4978 ("nologstatesreversed" org-log-states-order-reversed nil)
4979 ("nologrepeat" org-log-repeat nil)
4980 ("logreschedule" org-log-reschedule time)
4981 ("lognotereschedule" org-log-reschedule note)
4982 ("nologreschedule" org-log-reschedule nil)
4983 ("logredeadline" org-log-redeadline time)
4984 ("lognoteredeadline" org-log-redeadline note)
4985 ("nologredeadline" org-log-redeadline nil)
4986 ("logrefile" org-log-refile time)
4987 ("lognoterefile" org-log-refile note)
4988 ("nologrefile" org-log-refile nil)
4989 ("fninline" org-footnote-define-inline t)
4990 ("nofninline" org-footnote-define-inline nil)
4991 ("fnlocal" org-footnote-section nil)
4992 ("fnauto" org-footnote-auto-label t)
4993 ("fnprompt" org-footnote-auto-label nil)
4994 ("fnconfirm" org-footnote-auto-label confirm)
4995 ("fnplain" org-footnote-auto-label plain)
4996 ("fnadjust" org-footnote-auto-adjust t)
4997 ("nofnadjust" org-footnote-auto-adjust nil)
4998 ("constcgs" constants-unit-system cgs)
4999 ("constSI" constants-unit-system SI)
5000 ("noptag" org-tag-persistent-alist nil)
5001 ("hideblocks" org-hide-block-startup t)
5002 ("nohideblocks" org-hide-block-startup nil)
5003 ("beamer" org-startup-with-beamer-mode t)
5004 ("entitiespretty" org-pretty-entities t)
5005 ("entitiesplain" org-pretty-entities nil))
5006 "Variable associated with STARTUP options for org-mode.
5007 Each element is a list of three items: the startup options (as written
5008 in the #+STARTUP line), the corresponding variable, and the value to set
5009 this variable to if the option is found. An optional forth element PUSH
5010 means to push this value onto the list in the variable.")
5012 (defcustom org-group-tags t
5013 "When non-nil (the default), use group tags.
5014 This can be turned on/off through `org-toggle-tags-groups'."
5015 :group 'org-tags
5016 :group 'org-startup
5017 :type 'boolean)
5019 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5021 (defun org-toggle-tags-groups ()
5022 "Toggle support for group tags.
5023 Support for group tags is controlled by the option
5024 `org-group-tags', which is non-nil by default."
5025 (interactive)
5026 (setq org-group-tags (not org-group-tags))
5027 (cond ((and (derived-mode-p 'org-agenda-mode)
5028 org-group-tags)
5029 (org-agenda-redo))
5030 ((derived-mode-p 'org-mode)
5031 (let ((org-inhibit-startup t)) (org-mode))))
5032 (message "Groups tags support has been turned %s"
5033 (if org-group-tags "on" "off")))
5035 (defun org-set-regexps-and-options (&optional tags-only)
5036 "Precompute regular expressions used in the current buffer.
5037 When optional argument TAGS-ONLY is non-nil, only compute tags
5038 related expressions."
5039 (when (derived-mode-p 'org-mode)
5040 (let ((alist (org--setup-collect-keywords
5041 (org-make-options-regexp
5042 (append '("FILETAGS" "TAGS" "SETUPFILE")
5043 (and (not tags-only)
5044 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5045 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5046 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5047 ;; Startup options. Get this early since it does change
5048 ;; behavior for other options (e.g., tags).
5049 (let ((startup (cdr (assq 'startup alist))))
5050 (dolist (option startup)
5051 (let ((entry (assoc-string option org-startup-options t)))
5052 (when entry
5053 (let ((var (nth 1 entry))
5054 (val (nth 2 entry)))
5055 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5056 (unless (listp (symbol-value var))
5057 (set (make-local-variable var) nil))
5058 (add-to-list var val)))))))
5059 (setq-local org-file-tags
5060 (mapcar #'org-add-prop-inherited
5061 (cdr (assq 'filetags alist))))
5062 (setq org-current-tag-alist
5063 (append org-tag-persistent-alist
5064 (let ((tags (cdr (assq 'tags alist))))
5065 (if tags (org-tag-string-to-alist tags)
5066 org-tag-alist))))
5067 (setq org-tag-groups-alist
5068 (org-tag-alist-to-groups org-current-tag-alist))
5069 (unless tags-only
5070 ;; File properties.
5071 (setq-local org-file-properties (cdr (assq 'property alist)))
5072 ;; Archive location.
5073 (let ((archive (cdr (assq 'archive alist))))
5074 (when archive (setq-local org-archive-location archive)))
5075 ;; Category.
5076 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5077 (when cat
5078 (setq-local org-category (intern cat))
5079 (setq-local org-file-properties
5080 (org--update-property-plist
5081 "CATEGORY" cat org-file-properties))))
5082 ;; Columns.
5083 (let ((column (cdr (assq 'columns alist))))
5084 (when column (setq-local org-columns-default-format column)))
5085 ;; Constants.
5086 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5087 ;; Link abbreviations.
5088 (let ((links (cdr (assq 'link alist))))
5089 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5090 ;; Priorities.
5091 (let ((priorities (cdr (assq 'priorities alist))))
5092 (when priorities
5093 (setq-local org-highest-priority (nth 0 priorities))
5094 (setq-local org-lowest-priority (nth 1 priorities))
5095 (setq-local org-default-priority (nth 2 priorities))))
5096 ;; Scripts.
5097 (let ((scripts (assq 'scripts alist)))
5098 (when scripts
5099 (setq-local org-use-sub-superscripts (cdr scripts))))
5100 ;; TODO keywords.
5101 (setq-local org-todo-kwd-alist nil)
5102 (setq-local org-todo-key-alist nil)
5103 (setq-local org-todo-key-trigger nil)
5104 (setq-local org-todo-keywords-1 nil)
5105 (setq-local org-done-keywords nil)
5106 (setq-local org-todo-heads nil)
5107 (setq-local org-todo-sets nil)
5108 (setq-local org-todo-log-states nil)
5109 (let ((todo-sequences
5110 (or (nreverse (cdr (assq 'todo alist)))
5111 (let ((d (default-value 'org-todo-keywords)))
5112 (if (not (stringp (car d))) d
5113 ;; XXX: Backward compatibility code.
5114 (list (cons org-todo-interpretation d)))))))
5115 (dolist (sequence todo-sequences)
5116 (let* ((sequence (or (run-hook-with-args-until-success
5117 'org-todo-setup-filter-hook sequence)
5118 sequence))
5119 (sequence-type (car sequence))
5120 (keywords (cdr sequence))
5121 (sep (member "|" keywords))
5122 names alist)
5123 (dolist (k (remove "|" keywords))
5124 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5126 (error "Invalid TODO keyword %s" k))
5127 (let ((name (match-string 1 k))
5128 (key (match-string 2 k))
5129 (log (org-extract-log-state-settings k)))
5130 (push name names)
5131 (push (cons name (and key (string-to-char key))) alist)
5132 (when log (push log org-todo-log-states))))
5133 (let* ((names (nreverse names))
5134 (done (if sep (org-remove-keyword-keys (cdr sep))
5135 (last names)))
5136 (head (car names))
5137 (tail (list sequence-type head (car done) (org-last done))))
5138 (add-to-list 'org-todo-heads head 'append)
5139 (push names org-todo-sets)
5140 (setq org-done-keywords (append org-done-keywords done nil))
5141 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5142 (setq org-todo-key-alist
5143 (append org-todo-key-alist
5144 (and alist
5145 (append '((:startgroup))
5146 (nreverse alist)
5147 '((:endgroup))))))
5148 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5149 (setq org-todo-sets (nreverse org-todo-sets)
5150 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5151 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5152 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5153 ;; Compute the regular expressions and other local variables.
5154 ;; Using `org-outline-regexp-bol' would complicate them much,
5155 ;; because of the fixed white space at the end of that string.
5156 (unless org-done-keywords
5157 (setq org-done-keywords
5158 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5159 (setq org-not-done-keywords
5160 (org-delete-all org-done-keywords
5161 (copy-sequence org-todo-keywords-1))
5162 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5163 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5164 org-not-done-heading-regexp
5165 (format org-heading-keyword-regexp-format org-not-done-regexp)
5166 org-todo-line-regexp
5167 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5168 org-complex-heading-regexp
5169 (concat "^\\(\\*+\\)"
5170 "\\(?: +" org-todo-regexp "\\)?"
5171 "\\(?: +\\(\\[#.\\]\\)\\)?"
5172 "\\(?: +\\(.*?\\)\\)??"
5173 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5174 "[ \t]*$")
5175 org-complex-heading-regexp-format
5176 (concat "^\\(\\*+\\)"
5177 "\\(?: +" org-todo-regexp "\\)?"
5178 "\\(?: +\\(\\[#.\\]\\)\\)?"
5179 "\\(?: +"
5180 ;; Stats cookies can be stuck to body.
5181 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5182 "\\(%s\\)"
5183 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5184 "\\)"
5185 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5186 "[ \t]*$")
5187 org-todo-line-tags-regexp
5188 (concat "^\\(\\*+\\)"
5189 "\\(?: +" org-todo-regexp "\\)?"
5190 "\\(?: +\\(.*?\\)\\)??"
5191 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5192 "[ \t]*$"))
5193 (org-compute-latex-and-related-regexp)))))
5195 (defun org--setup-collect-keywords (regexp &optional files alist)
5196 "Return setup keywords values as an alist.
5198 REGEXP matches a subset of setup keywords. FILES is a list of
5199 file names already visited. It is used to avoid circular setup
5200 files. ALIST, when non-nil, is the alist computed so far.
5202 Return value contains the following keys: `archive', `category',
5203 `columns', `constants', `filetags', `link', `priorities',
5204 `property', `scripts', `startup', `tags' and `todo'."
5205 (org-with-wide-buffer
5206 (goto-char (point-min))
5207 (let ((case-fold-search t))
5208 (while (re-search-forward regexp nil t)
5209 (let ((element (org-element-at-point)))
5210 (when (eq (org-element-type element) 'keyword)
5211 (let ((key (org-element-property :key element))
5212 (value (org-element-property :value element)))
5213 (cond
5214 ((equal key "ARCHIVE")
5215 (when (org-string-nw-p value)
5216 (push (cons 'archive value) alist)))
5217 ((equal key "CATEGORY") (push (cons 'category value) alist))
5218 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5219 ((equal key "CONSTANTS")
5220 (let* ((constants (assq 'constants alist))
5221 (store (cdr constants)))
5222 (dolist (pair (org-split-string value))
5223 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5224 pair)
5225 (let* ((name (match-string 1 pair))
5226 (value (match-string 2 pair))
5227 (old (assoc name store)))
5228 (if old (setcdr old value)
5229 (push (cons name value) store)))))
5230 (if constants (setcdr constants store)
5231 (push (cons 'constants store) alist))))
5232 ((equal key "FILETAGS")
5233 (when (org-string-nw-p value)
5234 (let ((old (assq 'filetags alist))
5235 (new (apply #'nconc
5236 (mapcar (lambda (x) (org-split-string x ":"))
5237 (org-split-string value)))))
5238 (if old (setcdr old (append new (cdr old)))
5239 (push (cons 'filetags new) alist)))))
5240 ((equal key "LINK")
5241 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5242 (let ((links (assq 'link alist))
5243 (pair (cons (match-string-no-properties 1 value)
5244 (match-string-no-properties 2 value))))
5245 (if links (push pair (cdr links))
5246 (push (list 'link pair) alist)))))
5247 ((equal key "OPTIONS")
5248 (when (and (org-string-nw-p value)
5249 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5250 (push (cons 'scripts (read (match-string 1 value))) alist)))
5251 ((equal key "PRIORITIES")
5252 (push (cons 'priorities
5253 (let ((prio (org-split-string value)))
5254 (if (< (length prio) 3) '(?A ?C ?B)
5255 (mapcar #'string-to-char prio))))
5256 alist))
5257 ((equal key "PROPERTY")
5258 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5259 (let* ((property (assq 'property alist))
5260 (value (org--update-property-plist
5261 (match-string-no-properties 1 value)
5262 (match-string-no-properties 2 value)
5263 (cdr property))))
5264 (if property (setcdr property value)
5265 (push (cons 'property value) alist)))))
5266 ((equal key "STARTUP")
5267 (let ((startup (assq 'startup alist)))
5268 (if startup
5269 (setcdr startup
5270 (append (cdr startup) (org-split-string value)))
5271 (push (cons 'startup (org-split-string value)) alist))))
5272 ((equal key "TAGS")
5273 (let ((tag-cell (assq 'tags alist)))
5274 (if tag-cell
5275 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5276 (push (cons 'tags value) alist))))
5277 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5278 (let ((todo (assq 'todo alist))
5279 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5280 (org-split-string value))))
5281 (if todo (push value (cdr todo))
5282 (push (list 'todo value) alist))))
5283 ((equal key "SETUPFILE")
5284 (unless buffer-read-only ; Do not check in Gnus messages.
5285 (let ((f (and (org-string-nw-p value)
5286 (expand-file-name
5287 (org-unbracket-string "\"" "\"" value)))))
5288 (when (and f (file-readable-p f) (not (member f files)))
5289 (with-temp-buffer
5290 (setq default-directory (file-name-directory f))
5291 (insert-file-contents f)
5292 (setq alist
5293 ;; Fake Org mode to benefit from cache
5294 ;; without recurring needlessly.
5295 (let ((major-mode 'org-mode))
5296 (org--setup-collect-keywords
5297 regexp (cons f files) alist)))))))))))))))
5298 alist)
5300 (defun org-tag-string-to-alist (s)
5301 "Return tag alist associated to string S.
5302 S is a value for TAGS keyword or produced with
5303 `org-tag-alist-to-string'. Return value is an alist suitable for
5304 `org-tag-alist' or `org-tag-persistent-alist'."
5305 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5306 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5307 "\\|{.+?}\\)" ; regular expression
5308 "\\(?:(\\(.\\))\\)?\\'"))
5309 alist group-flag)
5310 (dolist (tokens lines (cdr (nreverse alist)))
5311 (push '(:newline) alist)
5312 (while tokens
5313 (let ((token (pop tokens)))
5314 (pcase token
5315 ("{"
5316 (push '(:startgroup) alist)
5317 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5318 ("}"
5319 (push '(:endgroup) alist)
5320 (setq group-flag nil))
5321 ("["
5322 (push '(:startgrouptag) alist)
5323 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5324 ("]"
5325 (push '(:endgrouptag) alist)
5326 (setq group-flag nil))
5327 (":"
5328 (push '(:grouptags) alist))
5329 ((guard (string-match tag-re token))
5330 (let ((tag (match-string 1 token))
5331 (key (and (match-beginning 2)
5332 (string-to-char (match-string 2 token)))))
5333 ;; Push all tags in groups, no matter if they already
5334 ;; appear somewhere else in the list.
5335 (when (or group-flag (not (assoc tag alist)))
5336 (push (cons tag key) alist))))))))))
5338 (defun org-tag-alist-to-string (alist &optional skip-key)
5339 "Return tag string associated to ALIST.
5341 ALIST is an alist, as defined in `org-tag-alist' or
5342 `org-tag-persistent-alist', or produced with
5343 `org-tag-string-to-alist'.
5345 Return value is a string suitable as a value for \"TAGS\"
5346 keyword.
5348 When optional argument SKIP-KEY is non-nil, skip selection keys
5349 next to tags."
5350 (mapconcat (lambda (token)
5351 (pcase token
5352 (`(:startgroup) "{")
5353 (`(:endgroup) "}")
5354 (`(:startgrouptag) "[")
5355 (`(:endgrouptag) "]")
5356 (`(:grouptags) ":")
5357 (`(:newline) "\\n")
5358 ((and
5359 (guard (not skip-key))
5360 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5361 (format "%s(%c)" tag key))
5362 (`(,(and tag (pred stringp)) . ,_) tag)
5363 (_ (user-error "Invalid tag token: %S" token))))
5364 alist
5365 " "))
5367 (defun org-tag-alist-to-groups (alist)
5368 "Return group alist from tag ALIST.
5369 ALIST is an alist, as defined in `org-tag-alist' or
5370 `org-tag-persistent-alist', or produced with
5371 `org-tag-string-to-alist'. Return value is an alist following
5372 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5373 a string, summarizing TAGS, as a list of strings."
5374 (let (groups group-status current-group)
5375 (dolist (token alist (nreverse groups))
5376 (pcase token
5377 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5378 (`(,(or :endgroup :endgrouptag))
5379 (when (eq group-status 'append)
5380 (push (nreverse current-group) groups))
5381 (setq group-status nil))
5382 (`(:grouptags) (setq group-status 'append))
5383 ((and `(,tag . ,_) (guard group-status))
5384 (if (eq group-status 'append) (push tag current-group)
5385 (setq current-group (list tag))))
5386 (_ nil)))))
5388 (defun org-file-contents (file &optional noerror)
5389 "Return the contents of FILE, as a string."
5390 (if (and file (file-readable-p file))
5391 (with-temp-buffer
5392 (insert-file-contents file)
5393 (buffer-string))
5394 (funcall (if noerror 'message 'error)
5395 "Cannot read file \"%s\"%s"
5396 file
5397 (let ((from (buffer-file-name (buffer-base-buffer))))
5398 (if from (concat " (referenced in file \"" from "\")") "")))))
5400 (defun org-extract-log-state-settings (x)
5401 "Extract the log state setting from a TODO keyword string.
5402 This will extract info from a string like \"WAIT(w@/!)\"."
5403 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5404 (let ((kw (match-string 1 x))
5405 (log1 (and (match-end 3) (match-string 3 x)))
5406 (log2 (and (match-end 4) (match-string 4 x))))
5407 (and (or log1 log2)
5408 (list kw
5409 (and log1 (if (equal log1 "!") 'time 'note))
5410 (and log2 (if (equal log2 "!") 'time 'note)))))))
5412 (defun org-remove-keyword-keys (list)
5413 "Remove a pair of parenthesis at the end of each string in LIST."
5414 (mapcar (lambda (x)
5415 (if (string-match "(.*)$" x)
5416 (substring x 0 (match-beginning 0))
5418 list))
5420 (defun org-assign-fast-keys (alist)
5421 "Assign fast keys to a keyword-key alist.
5422 Respect keys that are already there."
5423 (let (new e (alt ?0))
5424 (while (setq e (pop alist))
5425 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5426 (cdr e)) ;; Key already assigned.
5427 (push e new)
5428 (let ((clist (string-to-list (downcase (car e))))
5429 (used (append new alist)))
5430 (when (= (car clist) ?@)
5431 (pop clist))
5432 (while (and clist (rassoc (car clist) used))
5433 (pop clist))
5434 (unless clist
5435 (while (rassoc alt used)
5436 (cl-incf alt)))
5437 (push (cons (car e) (or (car clist) alt)) new))))
5438 (nreverse new)))
5440 ;;; Some variables used in various places
5442 (defvar org-window-configuration nil
5443 "Used in various places to store a window configuration.")
5444 (defvar org-selected-window nil
5445 "Used in various places to store a window configuration.")
5446 (defvar org-finish-function nil
5447 "Function to be called when `C-c C-c' is used.
5448 This is for getting out of special buffers like capture.")
5449 (defvar org-last-state)
5451 ;; Defined somewhere in this file, but used before definition.
5452 (defvar org-entities) ;; defined in org-entities.el
5453 (defvar org-struct-menu)
5454 (defvar org-org-menu)
5455 (defvar org-tbl-menu)
5457 ;;;; Define the Org mode
5459 ;; We use a before-change function to check if a table might need
5460 ;; an update.
5461 (defvar org-table-may-need-update t
5462 "Indicates that a table might need an update.
5463 This variable is set by `org-before-change-function'.
5464 `org-table-align' sets it back to nil.")
5465 (defun org-before-change-function (_beg _end)
5466 "Every change indicates that a table might need an update."
5467 (setq org-table-may-need-update t))
5468 (defvar org-mode-map)
5469 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5470 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5471 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5472 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5473 (defvar org-table-buffer-is-an nil)
5475 (defvar bidi-paragraph-direction)
5476 (defvar buffer-face-mode-face)
5478 (require 'outline)
5480 ;; Other stuff we need.
5481 (require 'time-date)
5482 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5483 (require 'easymenu)
5484 (autoload 'easy-menu-add "easymenu")
5485 (require 'overlay)
5487 ;; (require 'org-macs) moved higher up in the file before it is first used
5488 (require 'org-entities)
5489 ;; (require 'org-compat) moved higher up in the file before it is first used
5490 (require 'org-faces)
5491 (require 'org-list)
5492 (require 'org-pcomplete)
5493 (require 'org-src)
5494 (require 'org-footnote)
5495 (require 'org-macro)
5497 ;; babel
5498 (require 'ob)
5500 ;;;###autoload
5501 (define-derived-mode org-mode outline-mode "Org"
5502 "Outline-based notes management and organizer, alias
5503 \"Carsten's outline-mode for keeping track of everything.\"
5505 Org mode develops organizational tasks around a NOTES file which
5506 contains information about projects as plain text. Org mode is
5507 implemented on top of Outline mode, which is ideal to keep the content
5508 of large files well structured. It supports ToDo items, deadlines and
5509 time stamps, which magically appear in the diary listing of the Emacs
5510 calendar. Tables are easily created with a built-in table editor.
5511 Plain text URL-like links connect to websites, emails (VM), Usenet
5512 messages (Gnus), BBDB entries, and any files related to the project.
5513 For printing and sharing of notes, an Org file (or a part of it)
5514 can be exported as a structured ASCII or HTML file.
5516 The following commands are available:
5518 \\{org-mode-map}"
5520 ;; Get rid of Outline menus, they are not needed
5521 ;; Need to do this here because define-derived-mode sets up
5522 ;; the keymap so late. Still, it is a waste to call this each time
5523 ;; we switch another buffer into Org mode.
5524 (define-key org-mode-map [menu-bar headings] 'undefined)
5525 (define-key org-mode-map [menu-bar hide] 'undefined)
5526 (define-key org-mode-map [menu-bar show] 'undefined)
5528 (org-load-modules-maybe)
5529 (org-install-agenda-files-menu)
5530 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5531 (add-to-invisibility-spec '(org-cwidth))
5532 (add-to-invisibility-spec '(org-hide-block . t))
5533 (setq-local outline-regexp org-outline-regexp)
5534 (setq-local outline-level 'org-outline-level)
5535 (setq bidi-paragraph-direction 'left-to-right)
5536 (when (and org-ellipsis
5537 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5538 (fboundp 'make-glyph-code))
5539 (unless org-display-table
5540 (setq org-display-table (make-display-table)))
5541 (set-display-table-slot
5542 org-display-table 4
5543 (vconcat (mapcar
5544 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5545 org-ellipsis)))
5546 (if (stringp org-ellipsis) org-ellipsis "..."))))
5547 (setq buffer-display-table org-display-table))
5548 (org-set-regexps-and-options)
5549 (org-set-font-lock-defaults)
5550 (when (and org-tag-faces (not org-tags-special-faces-re))
5551 ;; tag faces set outside customize.... force initialization.
5552 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5553 ;; Calc embedded
5554 (setq-local calc-embedded-open-mode "# ")
5555 ;; Modify a few syntax entries
5556 (modify-syntax-entry ?@ "w")
5557 (modify-syntax-entry ?\" "\"")
5558 (modify-syntax-entry ?\\ "_")
5559 (modify-syntax-entry ?~ "_")
5560 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5561 ;; Activate before-change-function
5562 (setq-local org-table-may-need-update t)
5563 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5564 ;; Check for running clock before killing a buffer
5565 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5566 ;; Initialize macros templates.
5567 (org-macro-initialize-templates)
5568 ;; Initialize radio targets.
5569 (org-update-radio-target-regexp)
5570 ;; Indentation.
5571 (setq-local indent-line-function 'org-indent-line)
5572 (setq-local indent-region-function 'org-indent-region)
5573 ;; Filling and auto-filling.
5574 (org-setup-filling)
5575 ;; Comments.
5576 (org-setup-comments-handling)
5577 ;; Initialize cache.
5578 (org-element-cache-reset)
5579 ;; Beginning/end of defun
5580 (setq-local beginning-of-defun-function 'org-backward-element)
5581 (setq-local end-of-defun-function
5582 (lambda ()
5583 (if (not (org-at-heading-p))
5584 (org-forward-element)
5585 (org-forward-element)
5586 (forward-char -1))))
5587 ;; Next error for sparse trees
5588 (setq-local next-error-function 'org-occur-next-match)
5589 ;; Make sure dependence stuff works reliably, even for users who set it
5590 ;; too late :-(
5591 (if org-enforce-todo-dependencies
5592 (add-hook 'org-blocker-hook
5593 'org-block-todo-from-children-or-siblings-or-parent)
5594 (remove-hook 'org-blocker-hook
5595 'org-block-todo-from-children-or-siblings-or-parent))
5596 (if org-enforce-todo-checkbox-dependencies
5597 (add-hook 'org-blocker-hook
5598 'org-block-todo-from-checkboxes)
5599 (remove-hook 'org-blocker-hook
5600 'org-block-todo-from-checkboxes))
5602 ;; Align options lines
5603 (setq-local
5604 align-mode-rules-list
5605 '((org-in-buffer-settings
5606 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5607 (modes . '(org-mode)))))
5609 ;; Imenu
5610 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5612 ;; Make isearch reveal context
5613 (setq-local outline-isearch-open-invisible-function
5614 (lambda (&rest _) (org-show-context 'isearch)))
5616 ;; Setup the pcomplete hooks
5617 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5618 (setq-local pcomplete-command-name-function 'org-command-at-point)
5619 (setq-local pcomplete-default-completion-function 'ignore)
5620 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5621 (setq-local pcomplete-termination-string "")
5622 (setq-local buffer-face-mode-face 'org-default)
5624 ;; If empty file that did not turn on Org mode automatically, make
5625 ;; it to.
5626 (when (and org-insert-mode-line-in-empty-file
5627 (called-interactively-p 'any)
5628 (= (point-min) (point-max)))
5629 (insert "# -*- mode: org -*-\n\n"))
5630 (unless org-inhibit-startup
5631 (org-unmodified
5632 (when org-startup-with-beamer-mode (org-beamer-mode))
5633 (when org-startup-align-all-tables
5634 (org-table-map-tables #'org-table-align t))
5635 (when org-startup-with-inline-images (org-display-inline-images))
5636 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5637 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5638 (when org-startup-truncated (setq truncate-lines t))
5639 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5640 (org-refresh-effort-properties)))
5641 ;; Try to set `org-hide' face correctly.
5642 (let ((foreground (org-find-invisible-foreground)))
5643 (when foreground
5644 (set-face-foreground 'org-hide foreground))))
5646 ;; Update `customize-package-emacs-version-alist'
5647 (add-to-list 'customize-package-emacs-version-alist
5648 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5649 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5650 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5652 (defvar org-mode-transpose-word-syntax-table
5653 (let ((st (make-syntax-table text-mode-syntax-table)))
5654 (dolist (c org-emphasis-alist st)
5655 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5657 (when (fboundp 'abbrev-table-put)
5658 (abbrev-table-put org-mode-abbrev-table
5659 :parents (list text-mode-abbrev-table)))
5661 (defun org-find-invisible-foreground ()
5662 (let ((candidates (remove
5663 "unspecified-bg"
5664 (nconc
5665 (list (face-background 'default)
5666 (face-background 'org-default))
5667 (mapcar
5668 (lambda (alist)
5669 (when (boundp alist)
5670 (cdr (assq 'background-color (symbol-value alist)))))
5671 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5672 (list (face-foreground 'org-hide))))))
5673 (car (remove nil candidates))))
5675 (defun org-current-time (&optional rounding-minutes past)
5676 "Current time, possibly rounded to ROUNDING-MINUTES.
5677 When ROUNDING-MINUTES is not an integer, fall back on the car of
5678 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5679 the rounding returns a past time."
5680 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5681 (car org-time-stamp-rounding-minutes)))
5682 (time (decode-time)) res)
5683 (if (< r 1)
5684 (current-time)
5685 (setq res
5686 (apply 'encode-time
5687 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5688 (nthcdr 2 time))))
5689 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5690 (seconds-to-time (- (float-time res) (* r 60)))
5691 res))))
5693 (defun org-today ()
5694 "Return today date, considering `org-extend-today-until'."
5695 (time-to-days
5696 (time-subtract (current-time)
5697 (list 0 (* 3600 org-extend-today-until) 0))))
5699 ;;;; Font-Lock stuff, including the activators
5701 (defvar org-mouse-map (make-sparse-keymap))
5702 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5703 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5704 (when org-mouse-1-follows-link
5705 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5706 (when org-tab-follows-link
5707 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5708 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5710 (require 'font-lock)
5712 (defconst org-non-link-chars "]\t\n\r<>")
5713 (defvar org-link-types-re nil
5714 "Matches a link that has a url-like prefix like \"http:\"")
5715 (defvar org-link-re-with-space nil
5716 "Matches a link with spaces, optional angular brackets around it.")
5717 (defvar org-link-re-with-space2 nil
5718 "Matches a link with spaces, optional angular brackets around it.")
5719 (defvar org-link-re-with-space3 nil
5720 "Matches a link with spaces, only for internal part in bracket links.")
5721 (defvar org-angle-link-re nil
5722 "Matches link with angular brackets, spaces are allowed.")
5723 (defvar org-plain-link-re nil
5724 "Matches plain link, without spaces.")
5725 (defvar org-bracket-link-regexp nil
5726 "Matches a link in double brackets.")
5727 (defvar org-bracket-link-analytic-regexp nil
5728 "Regular expression used to analyze links.
5729 Here is what the match groups contain after a match:
5730 1: http:
5731 2: http
5732 3: path
5733 4: [desc]
5734 5: desc")
5735 (defvar org-bracket-link-analytic-regexp++ nil
5736 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5737 (defvar org-any-link-re nil
5738 "Regular expression matching any link.")
5740 (defconst org-match-sexp-depth 3
5741 "Number of stacked braces for sub/superscript matching.")
5743 (defun org-create-multibrace-regexp (left right n)
5744 "Create a regular expression which will match a balanced sexp.
5745 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5746 as single character strings.
5747 The regexp returned will match the entire expression including the
5748 delimiters. It will also define a single group which contains the
5749 match except for the outermost delimiters. The maximum depth of
5750 stacked delimiters is N. Escaping delimiters is not possible."
5751 (let* ((nothing (concat "[^" left right "]*?"))
5752 (or "\\|")
5753 (re nothing)
5754 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5755 (while (> n 1)
5756 (setq n (1- n)
5757 re (concat re or next)
5758 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5759 (concat left "\\(" re "\\)" right)))
5761 (defconst org-match-substring-regexp
5762 (concat
5763 "\\(\\S-\\)\\([_^]\\)\\("
5764 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5765 "\\|"
5766 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5767 "\\|"
5768 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5769 "The regular expression matching a sub- or superscript.")
5771 (defconst org-match-substring-with-braces-regexp
5772 (concat
5773 "\\(\\S-\\)\\([_^]\\)"
5774 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5775 "The regular expression matching a sub- or superscript, forcing braces.")
5777 (defun org-make-link-regexps ()
5778 "Update the link regular expressions.
5779 This should be called after the variable `org-link-parameters' has changed."
5780 (let ((types-re (regexp-opt (org-link-types) t)))
5781 (setq org-link-types-re
5782 (concat "\\`" types-re ":")
5783 org-link-re-with-space
5784 (concat "<?" types-re ":"
5785 "\\([^" org-non-link-chars " ]"
5786 "[^" org-non-link-chars "]*"
5787 "[^" org-non-link-chars " ]\\)>?")
5788 org-link-re-with-space2
5789 (concat "<?" types-re ":"
5790 "\\([^" org-non-link-chars " ]"
5791 "[^\t\n\r]*"
5792 "[^" org-non-link-chars " ]\\)>?")
5793 org-link-re-with-space3
5794 (concat "<?" types-re ":"
5795 "\\([^" org-non-link-chars " ]"
5796 "[^\t\n\r]*\\)")
5797 org-angle-link-re
5798 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5799 types-re)
5800 org-plain-link-re
5801 (concat
5802 "\\<" types-re ":"
5803 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5804 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5805 org-bracket-link-regexp
5806 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5807 org-bracket-link-analytic-regexp
5808 (concat
5809 "\\[\\["
5810 "\\(" types-re ":\\)?"
5811 "\\([^]]+\\)"
5812 "\\]"
5813 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5814 "\\]")
5815 org-bracket-link-analytic-regexp++
5816 (concat
5817 "\\[\\["
5818 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5819 "\\([^]]+\\)"
5820 "\\]"
5821 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5822 "\\]")
5823 org-any-link-re
5824 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5825 org-angle-link-re "\\)\\|\\("
5826 org-plain-link-re "\\)"))))
5828 (org-make-link-regexps)
5830 (defvar org-emph-face nil)
5832 (defun org-do-emphasis-faces (limit)
5833 "Run through the buffer and emphasize strings."
5834 (let (rtn a)
5835 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5836 (let* ((border (char-after (match-beginning 3)))
5837 (bre (regexp-quote (char-to-string border))))
5838 (when (and (not (= border (char-after (match-beginning 4))))
5839 (not (string-match-p (concat bre ".*" bre)
5840 (replace-regexp-in-string
5841 "\n" " "
5842 (substring (match-string 2) 1 -1)))))
5843 (setq rtn t)
5844 (setq a (assoc (match-string 3) org-emphasis-alist))
5845 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5846 'face
5847 (nth 1 a))
5848 (and (nth 2 a)
5849 (org-remove-flyspell-overlays-in
5850 (match-beginning 0) (match-end 0)))
5851 (add-text-properties (match-beginning 2) (match-end 2)
5852 '(font-lock-multiline t org-emphasis t))
5853 (when org-hide-emphasis-markers
5854 (add-text-properties (match-end 4) (match-beginning 5)
5855 '(invisible org-link))
5856 (add-text-properties (match-beginning 3) (match-end 3)
5857 '(invisible org-link)))))
5858 (goto-char (1+ (match-beginning 0))))
5859 rtn))
5861 (defun org-emphasize (&optional char)
5862 "Insert or change an emphasis, i.e. a font like bold or italic.
5863 If there is an active region, change that region to a new emphasis.
5864 If there is no region, just insert the marker characters and position
5865 the cursor between them.
5866 CHAR should be the marker character. If it is a space, it means to
5867 remove the emphasis of the selected region.
5868 If CHAR is not given (for example in an interactive call) it will be
5869 prompted for."
5870 (interactive)
5871 (let ((erc org-emphasis-regexp-components)
5872 (string "") beg end move s)
5873 (if (org-region-active-p)
5874 (setq beg (region-beginning)
5875 end (region-end)
5876 string (buffer-substring beg end))
5877 (setq move t))
5879 (unless char
5880 (message "Emphasis marker or tag: [%s]"
5881 (mapconcat #'car org-emphasis-alist ""))
5882 (setq char (read-char-exclusive)))
5883 (if (equal char ?\s)
5884 (setq s ""
5885 move nil)
5886 (unless (assoc (char-to-string char) org-emphasis-alist)
5887 (user-error "No such emphasis marker: \"%c\"" char))
5888 (setq s (char-to-string char)))
5889 (while (and (> (length string) 1)
5890 (equal (substring string 0 1) (substring string -1))
5891 (assoc (substring string 0 1) org-emphasis-alist))
5892 (setq string (substring string 1 -1)))
5893 (setq string (concat s string s))
5894 (when beg (delete-region beg end))
5895 (unless (or (bolp)
5896 (string-match (concat "[" (nth 0 erc) "\n]")
5897 (char-to-string (char-before (point)))))
5898 (insert " "))
5899 (unless (or (eobp)
5900 (string-match (concat "[" (nth 1 erc) "\n]")
5901 (char-to-string (char-after (point)))))
5902 (insert " ") (backward-char 1))
5903 (insert string)
5904 (and move (backward-char 1))))
5906 (defconst org-nonsticky-props
5907 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5909 (defsubst org-rear-nonsticky-at (pos)
5910 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5912 (defun org-activate-plain-links (limit)
5913 "Add link properties for plain links."
5914 (when (and (re-search-forward org-plain-link-re limit t)
5915 (not (org-in-src-block-p)))
5917 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5918 'face))
5919 (link (match-string-no-properties 0))
5920 (type (match-string-no-properties 1))
5921 (path (match-string-no-properties 2))
5922 (link-start (match-beginning 0))
5923 (link-end (match-end 0))
5924 (link-face (org-link-get-parameter type :face))
5925 (help-echo (org-link-get-parameter type :help-echo))
5926 (htmlize-link (org-link-get-parameter type :htmlize-link))
5927 (activate-func (org-link-get-parameter type :activate-func)))
5928 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5929 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5930 (add-text-properties (match-beginning 0) (match-end 0)
5931 (list
5932 'mouse-face (or (org-link-get-parameter type :mouse-face)
5933 'highlight)
5934 'face (cond
5935 ;; A function that returns a face
5936 ((functionp link-face)
5937 (funcall link-face path))
5938 ;; a face
5939 ((facep link-face)
5940 link-face)
5941 ;; An anonymous face
5942 ((consp link-face)
5943 link-face)
5944 ;; default
5946 'org-link))
5947 'help-echo (cond
5948 ((stringp help-echo)
5949 help-echo)
5950 ((functionp help-echo)
5951 help-echo)
5953 (concat "LINK: "
5954 (save-match-data
5955 (org-link-unescape link)))))
5956 'htmlize-link (cond
5957 ((functionp htmlize-link)
5958 (funcall htmlize-link path))
5960 `(:uri ,link)))
5961 'keymap (or (org-link-get-parameter type :keymap)
5962 org-mouse-map)
5963 'org-link-start (match-beginning 0)))
5964 (org-rear-nonsticky-at (match-end 0))
5965 (when activate-func
5966 (funcall activate-func link-start link-end path nil))
5967 t))))
5969 (defun org-activate-code (limit)
5970 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (remove-text-properties (match-beginning 0) (match-end 0)
5973 '(display t invisible t intangible t))
5976 (defcustom org-src-fontify-natively t
5977 "When non-nil, fontify code in code blocks.
5978 See also the `org-block' face."
5979 :type 'boolean
5980 :version "24.4"
5981 :package-version '(Org . "8.3")
5982 :group 'org-appearance
5983 :group 'org-babel)
5985 (defcustom org-allow-promoting-top-level-subtree nil
5986 "When non-nil, allow promoting a top level subtree.
5987 The leading star of the top level headline will be replaced
5988 by a #."
5989 :type 'boolean
5990 :version "24.1"
5991 :group 'org-appearance)
5993 (defun org-fontify-meta-lines-and-blocks (limit)
5994 (condition-case nil
5995 (org-fontify-meta-lines-and-blocks-1 limit)
5996 (error (message "org-mode fontification error in %S at %d"
5997 (current-buffer)
5998 (line-number-at-pos)))))
6000 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6001 "Fontify #+ lines and blocks."
6002 (let ((case-fold-search t))
6003 (when (re-search-forward
6004 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6005 limit t)
6006 (let ((beg (match-beginning 0))
6007 (block-start (match-end 0))
6008 (block-end nil)
6009 (lang (match-string 7))
6010 (beg1 (line-beginning-position 2))
6011 (dc1 (downcase (match-string 2)))
6012 (dc3 (downcase (match-string 3)))
6013 end end1 quoting block-type)
6014 (cond
6015 ((and (match-end 4) (equal dc3 "+begin"))
6016 ;; Truly a block
6017 (setq block-type (downcase (match-string 5))
6018 quoting (member block-type org-protecting-blocks))
6019 (when (re-search-forward
6020 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6021 nil t) ;; on purpose, we look further than LIMIT
6022 (setq end (min (point-max) (match-end 0))
6023 end1 (min (point-max) (1- (match-beginning 0))))
6024 (setq block-end (match-beginning 0))
6025 (when quoting
6026 (org-remove-flyspell-overlays-in beg1 end1)
6027 (remove-text-properties beg end
6028 '(display t invisible t intangible t)))
6029 (add-text-properties
6030 beg end '(font-lock-fontified t font-lock-multiline t))
6031 (add-text-properties beg beg1 '(face org-meta-line))
6032 (org-remove-flyspell-overlays-in beg beg1)
6033 (add-text-properties ; For end_src
6034 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6035 (org-remove-flyspell-overlays-in end1 end)
6036 (cond
6037 ((and lang (not (string= lang "")) org-src-fontify-natively)
6038 (org-src-font-lock-fontify-block lang block-start block-end)
6039 (add-text-properties beg1 block-end '(src-block t)))
6040 (quoting
6041 (add-text-properties beg1 (min (point-max) (1+ end1))
6042 (list 'face
6043 (list :inherit
6044 (let ((face-name
6045 (intern (format "org-block-%s" lang))))
6046 (append (and (facep face-name) (list face-name))
6047 '(org-block))))))) ; end of source block
6048 ((not org-fontify-quote-and-verse-blocks))
6049 ((string= block-type "quote")
6050 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6051 ((string= block-type "verse")
6052 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6053 (add-text-properties beg beg1 '(face org-block-begin-line))
6054 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6055 '(face org-block-end-line))
6057 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6058 (org-remove-flyspell-overlays-in
6059 (match-beginning 0)
6060 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6061 (add-text-properties
6062 beg (match-end 3)
6063 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6064 '(font-lock-fontified t invisible t)
6065 '(font-lock-fontified t face org-document-info-keyword)))
6066 (add-text-properties
6067 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6068 (if (string-equal dc1 "+title:")
6069 '(font-lock-fontified t face org-document-title)
6070 '(font-lock-fontified t face org-document-info))))
6071 ((equal dc1 "+caption:")
6072 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6073 (remove-text-properties (match-beginning 0) (match-end 0)
6074 '(display t invisible t intangible t))
6075 (add-text-properties (match-beginning 1) (match-end 3)
6076 '(font-lock-fontified t face org-meta-line))
6077 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6078 '(font-lock-fontified t face org-block))
6080 ((member dc3 '(" " ""))
6081 (org-remove-flyspell-overlays-in beg (match-end 0))
6082 (add-text-properties
6083 beg (match-end 0)
6084 '(font-lock-fontified t face font-lock-comment-face)))
6085 (t ;; just any other in-buffer setting, but not indented
6086 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6087 (remove-text-properties (match-beginning 0) (match-end 0)
6088 '(display t invisible t intangible t))
6089 (add-text-properties beg (match-end 0)
6090 '(font-lock-fontified t face org-meta-line))
6091 t))))))
6093 (defun org-fontify-drawers (limit)
6094 "Fontify drawers."
6095 (when (re-search-forward org-drawer-regexp limit t)
6096 (add-text-properties
6097 (match-beginning 0) (match-end 0)
6098 '(font-lock-fontified t face org-special-keyword))
6099 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6102 (defun org-fontify-macros (limit)
6103 "Fontify macros."
6104 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6105 (add-text-properties
6106 (match-beginning 0) (match-end 0)
6107 '(font-lock-fontified t face org-macro))
6108 (when org-hide-macro-markers
6109 (add-text-properties (match-end 2) (match-beginning 2)
6110 '(invisible t))
6111 (add-text-properties (match-beginning 1) (match-end 1)
6112 '(invisible t)))
6113 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6116 (defun org-activate-angle-links (limit)
6117 "Add text properties for angle links."
6118 (when (and (re-search-forward org-angle-link-re limit t)
6119 (not (org-in-src-block-p)))
6120 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6121 (add-text-properties (match-beginning 0) (match-end 0)
6122 (list 'mouse-face 'highlight
6123 'keymap org-mouse-map
6124 'font-lock-multiline t))
6125 (org-rear-nonsticky-at (match-end 0))
6128 (defun org-activate-footnote-links (limit)
6129 "Add text properties for footnotes."
6130 (let ((fn (org-footnote-next-reference-or-definition limit)))
6131 (when fn
6132 (let* ((beg (nth 1 fn))
6133 (end (nth 2 fn))
6134 (label (car fn))
6135 (referencep (/= (line-beginning-position) beg)))
6136 (when (and referencep (nth 3 fn))
6137 (save-excursion
6138 (goto-char beg)
6139 (search-forward (or label "fn:"))
6140 (org-remove-flyspell-overlays-in beg (match-end 0))))
6141 (add-text-properties beg end
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map
6144 'help-echo
6145 (if referencep "Footnote reference"
6146 "Footnote definition")
6147 'font-lock-fontified t
6148 'font-lock-multiline t
6149 'face 'org-footnote))))))
6151 (defun org-activate-bracket-links (limit)
6152 "Add text properties for bracketed links."
6153 (when (and (re-search-forward org-bracket-link-regexp limit t)
6154 (not (org-in-src-block-p)))
6155 (let* ((hl (save-match-data
6156 (org-link-expand-abbrev (match-string-no-properties 1))))
6157 (type (save-match-data
6158 (and (string-match org-plain-link-re hl)
6159 (match-string-no-properties 1 hl))))
6160 (path (save-match-data
6161 (and (string-match org-plain-link-re hl)
6162 (match-string-no-properties 2 hl))))
6163 (link-start (match-beginning 0))
6164 (link-end (match-end 0))
6165 (bracketp t)
6166 (help-echo (org-link-get-parameter type :help-echo))
6167 (help (cond
6168 ((stringp help-echo)
6169 help-echo)
6170 ((functionp help-echo)
6171 help-echo)
6173 (concat "LINK: "
6174 (save-match-data
6175 (org-link-unescape hl))))))
6176 (link-face (org-link-get-parameter type :face))
6177 (face (cond
6178 ;; A function that returns a face
6179 ((functionp link-face)
6180 (funcall link-face path))
6181 ;; a face
6182 ((facep link-face)
6183 link-face)
6184 ;; An anonymous face
6185 ((consp link-face)
6186 link-face)
6187 ;; default
6189 'org-link)))
6190 (keymap (or (org-link-get-parameter type :keymap)
6191 org-mouse-map))
6192 (mouse-face (or (org-link-get-parameter type :mouse-face)
6193 'highlight))
6194 (htmlize (org-link-get-parameter type :htmlize-link))
6195 (htmlize-link (cond
6196 ((functionp htmlize)
6197 (funcall htmlize))
6199 `(:uri ,(format "%s:%s" type path)))))
6200 (activate-func (org-link-get-parameter type :activate-func))
6201 ;; invisible part
6202 (ip (list 'invisible (or
6203 (org-link-get-parameter type :display)
6204 'org-link)
6205 'face face
6206 'keymap keymap
6207 'mouse-face mouse-face
6208 'font-lock-multiline t
6209 'help-echo help
6210 'htmlize-link htmlize-link))
6211 ;; visible part
6212 (vp (list 'keymap keymap
6213 'face face
6214 'mouse-face mouse-face
6215 'font-lock-multiline t
6216 'help-echo help
6217 'htmlize-link htmlize-link)))
6218 ;; We need to remove the invisible property here. Table narrowing
6219 ;; may have made some of this invisible.
6220 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6221 (remove-text-properties (match-beginning 0) (match-end 0)
6222 '(invisible nil))
6223 (if (match-end 3)
6224 (progn
6225 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6226 (org-rear-nonsticky-at (match-beginning 3))
6227 (add-text-properties (match-beginning 3) (match-end 3) vp)
6228 (org-rear-nonsticky-at (match-end 3))
6229 (add-text-properties (match-end 3) (match-end 0) ip)
6230 (org-rear-nonsticky-at (match-end 0)))
6231 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6232 (org-rear-nonsticky-at (match-beginning 1))
6233 (add-text-properties (match-beginning 1) (match-end 1) vp)
6234 (org-rear-nonsticky-at (match-end 1))
6235 (add-text-properties (match-end 1) (match-end 0) ip)
6236 (org-rear-nonsticky-at (match-end 0)))
6237 (when activate-func
6238 (funcall activate-func link-start link-end path bracketp))
6239 t)))
6241 (defun org-activate-dates (limit)
6242 "Add text properties for dates."
6243 (when (and (re-search-forward org-tsr-regexp-both limit t)
6244 (not (equal (char-before (match-beginning 0)) 91)))
6245 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6246 (add-text-properties (match-beginning 0) (match-end 0)
6247 (list 'mouse-face 'highlight
6248 'keymap org-mouse-map))
6249 (org-rear-nonsticky-at (match-end 0))
6250 (when org-display-custom-times
6251 (if (match-end 3)
6252 (org-display-custom-time (match-beginning 3) (match-end 3))
6253 (org-display-custom-time (match-beginning 1) (match-end 1))))
6256 (defvar-local org-target-link-regexp nil
6257 "Regular expression matching radio targets in plain text.")
6259 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6260 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6261 border border border))
6262 "Regular expression matching a link target.")
6264 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6265 "Regular expression matching a radio target.")
6267 (defconst org-any-target-regexp
6268 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6269 "Regular expression matching any target.")
6271 (defun org-activate-target-links (limit)
6272 "Add text properties for target matches."
6273 (when org-target-link-regexp
6274 (let ((case-fold-search t))
6275 (when (re-search-forward org-target-link-regexp limit t)
6276 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6277 (add-text-properties (match-beginning 1) (match-end 1)
6278 (list 'mouse-face 'highlight
6279 'keymap org-mouse-map
6280 'help-echo "Radio target link"
6281 'org-linked-text t))
6282 (org-rear-nonsticky-at (match-end 1))
6283 t))))
6285 (defun org-update-radio-target-regexp ()
6286 "Find all radio targets in this file and update the regular expression.
6287 Also refresh fontification if needed."
6288 (interactive)
6289 (let ((old-regexp org-target-link-regexp)
6290 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6291 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6292 (targets
6293 (org-with-wide-buffer
6294 (goto-char (point-min))
6295 (let (rtn)
6296 (while (re-search-forward org-radio-target-regexp nil t)
6297 ;; Make sure point is really within the object.
6298 (backward-char)
6299 (let ((obj (org-element-context)))
6300 (when (eq (org-element-type obj) 'radio-target)
6301 (cl-pushnew (org-element-property :value obj) rtn
6302 :test #'equal))))
6303 rtn))))
6304 (setq org-target-link-regexp
6305 (and targets
6306 (concat before-re
6307 (mapconcat
6308 (lambda (x)
6309 (replace-regexp-in-string
6310 " +" "\\s-+" (regexp-quote x) t t))
6311 targets
6312 "\\|")
6313 after-re)))
6314 (unless (equal old-regexp org-target-link-regexp)
6315 ;; Clean-up cache.
6316 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6317 ((not org-target-link-regexp) old-regexp)
6319 (concat before-re
6320 (mapconcat
6321 (lambda (re)
6322 (substring re (length before-re)
6323 (- (length after-re))))
6324 (list old-regexp org-target-link-regexp)
6325 "\\|")
6326 after-re)))))
6327 (org-with-wide-buffer
6328 (goto-char (point-min))
6329 (while (re-search-forward regexp nil t)
6330 (org-element-cache-refresh (match-beginning 1)))))
6331 ;; Re fontify buffer.
6332 (when (memq 'radio org-highlight-links)
6333 (org-restart-font-lock)))))
6335 (defun org-hide-wide-columns (limit)
6336 (let (s e)
6337 (setq s (text-property-any (point) (or limit (point-max))
6338 'org-cwidth t))
6339 (when s
6340 (setq e (next-single-property-change s 'org-cwidth))
6341 (add-text-properties s e '(invisible org-cwidth))
6342 (goto-char e)
6343 t)))
6345 (defvar org-latex-and-related-regexp nil
6346 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6348 (defun org-compute-latex-and-related-regexp ()
6349 "Compute regular expression for LaTeX, entities and sub/superscript.
6350 Result depends on variable `org-highlight-latex-and-related'."
6351 (setq-local
6352 org-latex-and-related-regexp
6353 (let* ((re-sub
6354 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6355 ((eq org-use-sub-superscripts '{})
6356 (list org-match-substring-with-braces-regexp))
6357 (org-use-sub-superscripts (list org-match-substring-regexp))))
6358 (re-latex
6359 (when (memq 'latex org-highlight-latex-and-related)
6360 (let ((matchers (plist-get org-format-latex-options :matchers)))
6361 (delq nil
6362 (mapcar (lambda (x)
6363 (and (member (car x) matchers) (nth 1 x)))
6364 org-latex-regexps)))))
6365 (re-entities
6366 (when (memq 'entities org-highlight-latex-and-related)
6367 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6368 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6370 (defun org-do-latex-and-related (limit)
6371 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6372 LIMIT bounds the search for syntax to highlight. Stop at first
6373 highlighted object, if any. Return t if some highlighting was
6374 done, nil otherwise."
6375 (when (org-string-nw-p org-latex-and-related-regexp)
6376 (catch 'found
6377 (while (re-search-forward org-latex-and-related-regexp limit t)
6378 (unless
6379 (cl-some
6380 (lambda (f)
6381 (memq f '(org-code org-verbatim underline org-special-keyword)))
6382 (save-excursion
6383 (goto-char (1+ (match-beginning 0)))
6384 (face-at-point nil t)))
6385 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6386 '(?_ ?^))
6388 0)))
6389 (font-lock-prepend-text-property
6390 (+ offset (match-beginning 0)) (match-end 0)
6391 'face 'org-latex-and-related)
6392 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6393 '(font-lock-multiline t)))
6394 (throw 'found t)))
6395 nil)))
6397 (defun org-restart-font-lock ()
6398 "Restart `font-lock-mode', to force refontification."
6399 (when (and (boundp 'font-lock-mode) font-lock-mode)
6400 (font-lock-mode -1)
6401 (font-lock-mode 1)))
6403 (defun org-activate-tags (limit)
6404 (when (re-search-forward
6405 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6406 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6407 (add-text-properties (match-beginning 1) (match-end 1)
6408 (list 'mouse-face 'highlight
6409 'keymap org-mouse-map))
6410 (org-rear-nonsticky-at (match-end 1))
6413 (defun org-outline-level ()
6414 "Compute the outline level of the heading at point.
6416 If this is called at a normal headline, the level is the number
6417 of stars. Use `org-reduced-level' to remove the effect of
6418 `org-odd-levels'. Unlike to `org-current-level', this function
6419 takes into consideration inlinetasks."
6420 (org-with-wide-buffer
6421 (end-of-line)
6422 (if (re-search-backward org-outline-regexp-bol nil t)
6423 (1- (- (match-end 0) (match-beginning 0)))
6424 0)))
6426 (defvar org-font-lock-keywords nil)
6428 (defsubst org-re-property (property &optional literal allow-null value)
6429 "Return a regexp matching a PROPERTY line.
6431 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6432 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6433 non-nil, match properties even without a value.
6435 Match group 3 is set to the value when it exists. If there is no
6436 value and ALLOW-NULL is non-nil, it is set to the empty string.
6438 With optional argument VALUE, match only property lines with
6439 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6440 unless LITERAL is non-nil."
6441 (concat
6442 "^\\(?4:[ \t]*\\)"
6443 (format "\\(?1::\\(?2:%s\\):\\)"
6444 (if literal property (regexp-quote property)))
6445 (cond (value
6446 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6447 (if literal value (regexp-quote value))))
6448 (allow-null
6449 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6451 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6453 (defconst org-property-re
6454 (org-re-property "\\S-+" 'literal t)
6455 "Regular expression matching a property line.
6456 There are four matching groups:
6457 1: :PROPKEY: including the leading and trailing colon,
6458 2: PROPKEY without the leading and trailing colon,
6459 3: PROPVAL without leading or trailing spaces,
6460 4: the indentation of the current line,
6461 5: trailing whitespace.")
6463 (defvar org-font-lock-hook nil
6464 "Functions to be called for special font lock stuff.")
6466 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6468 (defvar org-font-lock-set-keywords-hook nil
6469 "Functions that can manipulate `org-font-lock-extra-keywords'.
6470 This is called after `org-font-lock-extra-keywords' is defined, but before
6471 it is installed to be used by font lock. This can be useful if something
6472 needs to be inserted at a specific position in the font-lock sequence.")
6474 (defun org-font-lock-hook (limit)
6475 "Run `org-font-lock-hook' within LIMIT."
6476 (run-hook-with-args 'org-font-lock-hook limit))
6478 (defun org-set-font-lock-defaults ()
6479 "Set font lock defaults for the current buffer."
6480 (let* ((em org-fontify-emphasized-text)
6481 (lk org-highlight-links)
6482 (org-font-lock-extra-keywords
6483 (list
6484 ;; Call the hook
6485 '(org-font-lock-hook)
6486 ;; Headlines
6487 `(,(if org-fontify-whole-heading-line
6488 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6489 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6490 (1 (org-get-level-face 1))
6491 (2 (org-get-level-face 2))
6492 (3 (org-get-level-face 3)))
6493 ;; Table lines
6494 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6495 (1 'org-table t))
6496 ;; Table internals
6497 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6498 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6499 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6500 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6501 ;; Drawers
6502 '(org-fontify-drawers)
6503 ;; Properties
6504 (list org-property-re
6505 '(1 'org-special-keyword t)
6506 '(3 'org-property-value t))
6507 ;; Links
6508 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6509 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6510 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6511 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6512 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6513 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6514 (when (memq 'footnote lk) '(org-activate-footnote-links))
6515 ;; Targets.
6516 (list org-any-target-regexp '(0 'org-target t))
6517 ;; Diary sexps.
6518 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6519 ;; Macro
6520 '(org-fontify-macros)
6521 '(org-hide-wide-columns (0 nil append))
6522 ;; TODO keyword
6523 (list (format org-heading-keyword-regexp-format
6524 org-todo-regexp)
6525 '(2 (org-get-todo-face 2) t))
6526 ;; DONE
6527 (if org-fontify-done-headline
6528 (list (format org-heading-keyword-regexp-format
6529 (concat
6530 "\\(?:"
6531 (mapconcat 'regexp-quote org-done-keywords "\\|")
6532 "\\)"))
6533 '(2 'org-headline-done t))
6534 nil)
6535 ;; Priorities
6536 '(org-font-lock-add-priority-faces)
6537 ;; Tags
6538 '(org-font-lock-add-tag-faces)
6539 ;; Tags groups
6540 (when (and org-group-tags org-tag-groups-alist)
6541 (list (concat org-outline-regexp-bol ".+\\(:"
6542 (regexp-opt (mapcar 'car org-tag-groups-alist))
6543 ":\\).*$")
6544 '(1 'org-tag-group prepend)))
6545 ;; Special keywords
6546 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6547 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6548 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6549 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6550 ;; Emphasis
6551 (when em '(org-do-emphasis-faces))
6552 ;; Checkboxes
6553 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6554 1 'org-checkbox prepend)
6555 (when (cdr (assq 'checkbox org-list-automatic-rules))
6556 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6557 (0 (org-get-checkbox-statistics-face) t)))
6558 ;; Description list items
6559 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6560 1 'org-list-dt prepend)
6561 ;; ARCHIVEd headings
6562 (list (concat
6563 org-outline-regexp-bol
6564 "\\(.*:" org-archive-tag ":.*\\)")
6565 '(1 'org-archived prepend))
6566 ;; Specials
6567 '(org-do-latex-and-related)
6568 '(org-fontify-entities)
6569 '(org-raise-scripts)
6570 ;; Code
6571 '(org-activate-code (1 'org-code t))
6572 ;; COMMENT
6573 (list (format
6574 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6575 org-todo-regexp
6576 org-comment-string)
6577 '(9 'org-special-keyword t))
6578 ;; Blocks and meta lines
6579 '(org-fontify-meta-lines-and-blocks))))
6580 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6581 (run-hooks 'org-font-lock-set-keywords-hook)
6582 ;; Now set the full font-lock-keywords
6583 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6584 (setq-local font-lock-defaults
6585 '(org-font-lock-keywords t nil nil backward-paragraph))
6586 (kill-local-variable 'font-lock-keywords)
6587 nil))
6589 (defun org-toggle-pretty-entities ()
6590 "Toggle the composition display of entities as UTF8 characters."
6591 (interactive)
6592 (setq-local org-pretty-entities (not org-pretty-entities))
6593 (org-restart-font-lock)
6594 (if org-pretty-entities
6595 (message "Entities are now displayed as UTF8 characters")
6596 (save-restriction
6597 (widen)
6598 (decompose-region (point-min) (point-max))
6599 (message "Entities are now displayed as plain text"))))
6601 (defvar-local org-custom-properties-overlays nil
6602 "List of overlays used for custom properties.")
6604 (defun org-toggle-custom-properties-visibility ()
6605 "Display or hide properties in `org-custom-properties'."
6606 (interactive)
6607 (if org-custom-properties-overlays
6608 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6609 (setq org-custom-properties-overlays nil))
6610 (when org-custom-properties
6611 (org-with-wide-buffer
6612 (goto-char (point-min))
6613 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6614 (while (re-search-forward regexp nil t)
6615 (let ((end (cdr (save-match-data (org-get-property-block)))))
6616 (when (and end (< (point) end))
6617 ;; Hide first custom property in current drawer.
6618 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6619 (overlay-put o 'invisible t)
6620 (overlay-put o 'org-custom-property t)
6621 (push o org-custom-properties-overlays))
6622 ;; Hide additional custom properties in the same drawer.
6623 (while (re-search-forward regexp end t)
6624 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6625 (overlay-put o 'invisible t)
6626 (overlay-put o 'org-custom-property t)
6627 (push o org-custom-properties-overlays)))))
6628 ;; Each entry is limited to a single property drawer.
6629 (outline-next-heading)))))))
6631 (defun org-fontify-entities (limit)
6632 "Find an entity to fontify."
6633 (let (ee)
6634 (when org-pretty-entities
6635 (catch 'match
6636 ;; "\_ "-family is left out on purpose. Only the first one,
6637 ;; i.e., "\_ ", could be fontified anyway, and it would be
6638 ;; confusing when adding a second white space character.
6639 (while (re-search-forward
6640 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6641 limit t)
6642 (when (and (not (org-at-comment-p))
6643 (setq ee (org-entity-get (match-string 1)))
6644 (= (length (nth 6 ee)) 1))
6645 (let* ((end (if (equal (match-string 2) "{}")
6646 (match-end 2)
6647 (match-end 1))))
6648 (add-text-properties
6649 (match-beginning 0) end
6650 (list 'font-lock-fontified t))
6651 (compose-region (match-beginning 0) end
6652 (nth 6 ee) nil)
6653 (backward-char 1)
6654 (throw 'match t))))
6655 nil))))
6657 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6658 "Fontify string S like in Org-mode."
6659 (with-temp-buffer
6660 (insert s)
6661 (let ((org-odd-levels-only odd-levels))
6662 (org-mode)
6663 (org-font-lock-ensure)
6664 (buffer-string))))
6666 (defvar org-m nil)
6667 (defvar org-l nil)
6668 (defvar org-f nil)
6669 (defun org-get-level-face (n)
6670 "Get the right face for match N in font-lock matching of headlines."
6671 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6672 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6673 (if org-cycle-level-faces
6674 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6675 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6676 (cond
6677 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6678 ((eq n 2) org-f)
6679 (t (unless org-level-color-stars-only org-f))))
6681 (defun org-face-from-face-or-color (context inherit face-or-color)
6682 "Create a face list that inherits INHERIT, but sets the foreground color.
6683 When FACE-OR-COLOR is not a string, just return it."
6684 (if (stringp face-or-color)
6685 (list :inherit inherit
6686 (cdr (assoc context org-faces-easy-properties))
6687 face-or-color)
6688 face-or-color))
6690 (defun org-get-todo-face (kwd)
6691 "Get the right face for a TODO keyword KWD.
6692 If KWD is a number, get the corresponding match group."
6693 (when (numberp kwd) (setq kwd (match-string kwd)))
6694 (or (org-face-from-face-or-color
6695 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6696 (and (member kwd org-done-keywords) 'org-done)
6697 'org-todo))
6699 (defun org-get-priority-face (priority)
6700 "Get the right face for PRIORITY.
6701 PRIORITY is a character."
6702 (or (org-face-from-face-or-color
6703 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6704 'org-priority))
6706 (defun org-get-tag-face (tag)
6707 "Get the right face for TAG.
6708 If TAG is a number, get the corresponding match group."
6709 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6710 (or (org-face-from-face-or-color
6711 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6712 'org-tag)))
6714 (defun org-font-lock-add-priority-faces (limit)
6715 "Add the special priority faces."
6716 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6717 (add-text-properties
6718 (match-beginning 1) (match-end 1)
6719 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6720 'font-lock-fontified t))))
6722 (defun org-font-lock-add-tag-faces (limit)
6723 "Add the special tag faces."
6724 (when (and org-tag-faces org-tags-special-faces-re)
6725 (while (re-search-forward org-tags-special-faces-re limit t)
6726 (add-text-properties (match-beginning 1) (match-end 1)
6727 (list 'face (org-get-tag-face 1)
6728 'font-lock-fontified t))
6729 (backward-char 1))))
6731 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6732 "Remove fontification and activation overlays from links."
6733 (font-lock-default-unfontify-region beg end)
6734 (let* ((buffer-undo-list t)
6735 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6736 (inhibit-modification-hooks t)
6737 deactivate-mark buffer-file-name buffer-file-truename)
6738 (decompose-region beg end)
6739 (remove-text-properties beg end
6740 '(mouse-face t keymap t org-linked-text t
6741 invisible t intangible t
6742 org-emphasis t))
6743 (org-remove-font-lock-display-properties beg end)))
6745 (defconst org-script-display '(((raise -0.3) (height 0.7))
6746 ((raise 0.3) (height 0.7))
6747 ((raise -0.5))
6748 ((raise 0.5)))
6749 "Display properties for showing superscripts and subscripts.")
6751 (defun org-remove-font-lock-display-properties (beg end)
6752 "Remove specific display properties that have been added by font lock.
6753 The will remove the raise properties that are used to show superscripts
6754 and subscripts."
6755 (let (next prop)
6756 (while (< beg end)
6757 (setq next (next-single-property-change beg 'display nil end)
6758 prop (get-text-property beg 'display))
6759 (when (member prop org-script-display)
6760 (put-text-property beg next 'display nil))
6761 (setq beg next))))
6763 (defun org-raise-scripts (limit)
6764 "Add raise properties to sub/superscripts."
6765 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6766 (re-search-forward
6767 (if (eq org-use-sub-superscripts t)
6768 org-match-substring-regexp
6769 org-match-substring-with-braces-regexp)
6770 limit t))
6771 (let* ((pos (point)) table-p comment-p
6772 (mpos (match-beginning 3))
6773 (emph-p (get-text-property mpos 'org-emphasis))
6774 (link-p (get-text-property mpos 'mouse-face))
6775 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6776 (goto-char (point-at-bol))
6777 (setq table-p (looking-at-p org-table-dataline-regexp)
6778 comment-p (looking-at-p "^[ \t]*#[ +]"))
6779 (goto-char pos)
6780 ;; Handle a_b^c
6781 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6782 (unless (or comment-p emph-p link-p keyw-p)
6783 (put-text-property (match-beginning 3) (match-end 0)
6784 'display
6785 (if (equal (char-after (match-beginning 2)) ?^)
6786 (nth (if table-p 3 1) org-script-display)
6787 (nth (if table-p 2 0) org-script-display)))
6788 (add-text-properties (match-beginning 2) (match-end 2)
6789 (list 'invisible t
6790 'org-dwidth t 'org-dwidth-n 1))
6791 (if (and (eq (char-after (match-beginning 3)) ?{)
6792 (eq (char-before (match-end 3)) ?}))
6793 (progn
6794 (add-text-properties
6795 (match-beginning 3) (1+ (match-beginning 3))
6796 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6797 (add-text-properties
6798 (1- (match-end 3)) (match-end 3)
6799 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6800 t)))
6802 ;;;; Visibility cycling, including org-goto and indirect buffer
6804 ;;; Cycling
6806 (defvar-local org-cycle-global-status nil)
6807 (put 'org-cycle-global-status 'org-state t)
6808 (defvar-local org-cycle-subtree-status nil)
6809 (put 'org-cycle-subtree-status 'org-state t)
6811 (defvar org-inlinetask-min-level)
6813 (defun org-unlogged-message (&rest args)
6814 "Display a message, but avoid logging it in the *Messages* buffer."
6815 (let ((message-log-max nil))
6816 (apply 'message args)))
6818 ;;;###autoload
6819 (defun org-cycle (&optional arg)
6820 "TAB-action and visibility cycling for Org-mode.
6822 This is the command invoked in Org mode by the TAB key. Its main purpose
6823 is outline visibility cycling, but it also invokes other actions
6824 in special contexts.
6826 - When this function is called with a prefix argument, rotate the entire
6827 buffer through 3 states (global cycling)
6828 1. OVERVIEW: Show only top-level headlines.
6829 2. CONTENTS: Show all headlines of all levels, but no body text.
6830 3. SHOW ALL: Show everything.
6831 With a double \\[universal-argument] prefix argument, \
6832 switch to the startup visibility,
6833 determined by the variable `org-startup-folded', and by any VISIBILITY
6834 properties in the buffer.
6835 With a triple \\[universal-argument] prefix argument, \
6836 show the entire buffer, including any drawers.
6838 - When inside a table, re-align the table and move to the next field.
6840 - When point is at the beginning of a headline, rotate the subtree started
6841 by this line through 3 different states (local cycling)
6842 1. FOLDED: Only the main headline is shown.
6843 2. CHILDREN: The main headline and the direct children are shown.
6844 From this state, you can move to one of the children
6845 and zoom in further.
6846 3. SUBTREE: Show the entire subtree, including body text.
6847 If there is no subtree, switch directly from CHILDREN to FOLDED.
6849 - When point is at the beginning of an empty headline and the variable
6850 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6851 of the headline by demoting and promoting it to likely levels. This
6852 speeds up creation document structure by pressing TAB once or several
6853 times right after creating a new headline.
6855 - When there is a numeric prefix, go up to a heading with level ARG, do
6856 a `show-subtree' and return to the previous cursor position. If ARG
6857 is negative, go up that many levels.
6859 - When point is not at the beginning of a headline, execute the global
6860 binding for TAB, which is re-indenting the line. See the option
6861 `org-cycle-emulate-tab' for details.
6863 - Special case: if point is at the beginning of the buffer and there is
6864 no headline in line 1, this function will act as if called with prefix arg
6865 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6866 But only if also the variable `org-cycle-global-at-bob' is t."
6867 (interactive "P")
6868 (org-load-modules-maybe)
6869 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6870 (and org-cycle-level-after-item/entry-creation
6871 (or (org-cycle-level)
6872 (org-cycle-item-indentation))))
6873 (let* ((limit-level
6874 (or org-cycle-max-level
6875 (and (boundp 'org-inlinetask-min-level)
6876 org-inlinetask-min-level
6877 (1- org-inlinetask-min-level))))
6878 (nstars (and limit-level
6879 (if org-odd-levels-only
6880 (and limit-level (1- (* limit-level 2)))
6881 limit-level)))
6882 (org-outline-regexp
6883 (if (not (derived-mode-p 'org-mode))
6884 outline-regexp
6885 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6886 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6887 (not (looking-at org-outline-regexp))))
6888 (org-cycle-hook
6889 (if bob-special
6890 (delq 'org-optimize-window-after-visibility-change
6891 (copy-sequence org-cycle-hook))
6892 org-cycle-hook))
6893 (pos (point)))
6895 (when (or bob-special (equal arg '(4)))
6896 ;; special case: use global cycling
6897 (setq arg t))
6899 (cond
6901 ((equal arg '(16))
6902 (setq last-command 'dummy)
6903 (org-set-startup-visibility)
6904 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6906 ((equal arg '(64))
6907 (outline-show-all)
6908 (org-unlogged-message "Entire buffer visible, including drawers"))
6910 ;; Try cdlatex TAB completion
6911 ((org-try-cdlatex-tab))
6913 ;; Table: enter it or move to the next field.
6914 ((org-at-table-p 'any)
6915 (if (org-at-table.el-p)
6916 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6917 Use \\[org-edit-special] to edit table.el tables"))
6918 (if arg (org-table-edit-field t)
6919 (org-table-justify-field-maybe)
6920 (call-interactively 'org-table-next-field))))
6922 ((run-hook-with-args-until-success
6923 'org-tab-after-check-for-table-hook))
6925 ;; Global cycling: delegate to `org-cycle-internal-global'.
6926 ((eq arg t) (org-cycle-internal-global))
6928 ;; Drawers: delegate to `org-flag-drawer'.
6929 ((save-excursion
6930 (beginning-of-line 1)
6931 (looking-at org-drawer-regexp))
6932 (org-flag-drawer ; toggle block visibility
6933 (not (get-char-property (match-end 0) 'invisible))))
6935 ;; Show-subtree, ARG levels up from here.
6936 ((integerp arg)
6937 (save-excursion
6938 (org-back-to-heading)
6939 (outline-up-heading (if (< arg 0) (- arg)
6940 (- (funcall outline-level) arg)))
6941 (org-show-subtree)))
6943 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6944 ((and (featurep 'org-inlinetask)
6945 (org-inlinetask-at-task-p)
6946 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6947 (org-inlinetask-toggle-visibility))
6949 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6950 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6951 (save-excursion (move-beginning-of-line 1)
6952 (looking-at org-outline-regexp)))
6953 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6954 (org-cycle-internal-local))
6956 ;; From there: TAB emulation and template completion.
6957 (buffer-read-only (org-back-to-heading))
6959 ((run-hook-with-args-until-success
6960 'org-tab-after-check-for-cycling-hook))
6962 ((org-try-structure-completion))
6964 ((run-hook-with-args-until-success
6965 'org-tab-before-tab-emulation-hook))
6967 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6968 (or (not (bolp))
6969 (not (looking-at org-outline-regexp))))
6970 (call-interactively (global-key-binding "\t")))
6972 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6973 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6974 (or (and (eq org-cycle-emulate-tab 'white)
6975 (= (match-end 0) (point-at-eol)))
6976 (and (eq org-cycle-emulate-tab 'whitestart)
6977 (>= (match-end 0) pos))))
6979 (eq org-cycle-emulate-tab t))
6980 (call-interactively (global-key-binding "\t")))
6982 (t (save-excursion
6983 (org-back-to-heading)
6984 (org-cycle)))))))
6986 (defun org-cycle-internal-global ()
6987 "Do the global cycling action."
6988 ;; Hack to avoid display of messages for .org attachments in Gnus
6989 (let ((ga (string-match "\\*fontification" (buffer-name))))
6990 (cond
6991 ((and (eq last-command this-command)
6992 (eq org-cycle-global-status 'overview))
6993 ;; We just created the overview - now do table of contents
6994 ;; This can be slow in very large buffers, so indicate action
6995 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6996 (unless ga (org-unlogged-message "CONTENTS..."))
6997 (org-content)
6998 (unless ga (org-unlogged-message "CONTENTS...done"))
6999 (setq org-cycle-global-status 'contents)
7000 (run-hook-with-args 'org-cycle-hook 'contents))
7002 ((and (eq last-command this-command)
7003 (eq org-cycle-global-status 'contents))
7004 ;; We just showed the table of contents - now show everything
7005 (run-hook-with-args 'org-pre-cycle-hook 'all)
7006 (outline-show-all)
7007 (unless ga (org-unlogged-message "SHOW ALL"))
7008 (setq org-cycle-global-status 'all)
7009 (run-hook-with-args 'org-cycle-hook 'all))
7012 ;; Default action: go to overview
7013 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7014 (org-overview)
7015 (unless ga (org-unlogged-message "OVERVIEW"))
7016 (setq org-cycle-global-status 'overview)
7017 (run-hook-with-args 'org-cycle-hook 'overview)))))
7019 (defvar org-called-with-limited-levels nil
7020 "Non-nil when `org-with-limited-levels' is currently active.")
7022 (defun org-cycle-internal-local ()
7023 "Do the local cycling action."
7024 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7025 ;; First, determine end of headline (EOH), end of subtree or item
7026 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7027 (save-excursion
7028 (if (org-at-item-p)
7029 (progn
7030 (beginning-of-line)
7031 (setq struct (org-list-struct))
7032 (setq eoh (point-at-eol))
7033 (setq eos (org-list-get-item-end-before-blank (point) struct))
7034 (setq has-children (org-list-has-child-p (point) struct)))
7035 (org-back-to-heading)
7036 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7037 (setq eos (save-excursion (org-end-of-subtree t t)
7038 (when (bolp) (backward-char)) (point)))
7039 (setq has-children
7040 (or (save-excursion
7041 (let ((level (funcall outline-level)))
7042 (outline-next-heading)
7043 (and (org-at-heading-p t)
7044 (> (funcall outline-level) level))))
7045 (save-excursion
7046 (org-list-search-forward (org-item-beginning-re) eos t)))))
7047 ;; Determine end invisible part of buffer (EOL)
7048 (beginning-of-line 2)
7049 (while (and (not (eobp)) ;This is like `next-line'.
7050 (get-char-property (1- (point)) 'invisible))
7051 (goto-char (next-single-char-property-change (point) 'invisible))
7052 (and (eolp) (beginning-of-line 2)))
7053 (setq eol (point)))
7054 ;; Find out what to do next and set `this-command'
7055 (cond
7056 ((= eos eoh)
7057 ;; Nothing is hidden behind this heading
7058 (unless (org-before-first-heading-p)
7059 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7060 (org-unlogged-message "EMPTY ENTRY")
7061 (setq org-cycle-subtree-status nil)
7062 (save-excursion
7063 (goto-char eos)
7064 (outline-next-heading)
7065 (when (outline-invisible-p) (org-flag-heading nil))))
7066 ((and (or (>= eol eos)
7067 (not (string-match "\\S-" (buffer-substring eol eos))))
7068 (or has-children
7069 (not (setq children-skipped
7070 org-cycle-skip-children-state-if-no-children))))
7071 ;; Entire subtree is hidden in one line: children view
7072 (unless (org-before-first-heading-p)
7073 (run-hook-with-args 'org-pre-cycle-hook 'children))
7074 (if (org-at-item-p)
7075 (org-list-set-item-visibility (point-at-bol) struct 'children)
7076 (org-show-entry)
7077 (org-with-limited-levels (org-show-children))
7078 ;; FIXME: This slows down the func way too much.
7079 ;; How keep drawers hidden in subtree anyway?
7080 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7081 ;; (org-cycle-hide-drawers 'subtree))
7083 ;; Fold every list in subtree to top-level items.
7084 (when (eq org-cycle-include-plain-lists 'integrate)
7085 (save-excursion
7086 (org-back-to-heading)
7087 (while (org-list-search-forward (org-item-beginning-re) eos t)
7088 (beginning-of-line 1)
7089 (let* ((struct (org-list-struct))
7090 (prevs (org-list-prevs-alist struct))
7091 (end (org-list-get-bottom-point struct)))
7092 (dolist (e (org-list-get-all-items (point) struct prevs))
7093 (org-list-set-item-visibility e struct 'folded))
7094 (goto-char (if (< end eos) end eos)))))))
7095 (org-unlogged-message "CHILDREN")
7096 (save-excursion
7097 (goto-char eos)
7098 (outline-next-heading)
7099 (when (outline-invisible-p) (org-flag-heading nil)))
7100 (setq org-cycle-subtree-status 'children)
7101 (unless (org-before-first-heading-p)
7102 (run-hook-with-args 'org-cycle-hook 'children)))
7103 ((or children-skipped
7104 (and (eq last-command this-command)
7105 (eq org-cycle-subtree-status 'children)))
7106 ;; We just showed the children, or no children are there,
7107 ;; now show everything.
7108 (unless (org-before-first-heading-p)
7109 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7110 (outline-flag-region eoh eos nil)
7111 (org-unlogged-message
7112 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7113 (setq org-cycle-subtree-status 'subtree)
7114 (unless (org-before-first-heading-p)
7115 (run-hook-with-args 'org-cycle-hook 'subtree)))
7117 ;; Default action: hide the subtree.
7118 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7119 (outline-flag-region eoh eos t)
7120 (org-unlogged-message "FOLDED")
7121 (setq org-cycle-subtree-status 'folded)
7122 (unless (org-before-first-heading-p)
7123 (run-hook-with-args 'org-cycle-hook 'folded))))))
7125 ;;;###autoload
7126 (defun org-global-cycle (&optional arg)
7127 "Cycle the global visibility. For details see `org-cycle'.
7128 With \\[universal-argument] prefix arg, switch to startup visibility.
7129 With a numeric prefix, show all headlines up to that level."
7130 (interactive "P")
7131 (let ((org-cycle-include-plain-lists
7132 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7133 (cond
7134 ((integerp arg)
7135 (outline-show-all)
7136 (outline-hide-sublevels arg)
7137 (setq org-cycle-global-status 'contents))
7138 ((equal arg '(4))
7139 (org-set-startup-visibility)
7140 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7142 (org-cycle '(4))))))
7144 (defun org-set-startup-visibility ()
7145 "Set the visibility required by startup options and properties."
7146 (cond
7147 ((eq org-startup-folded t)
7148 (org-overview))
7149 ((eq org-startup-folded 'content)
7150 (org-content))
7151 ((or (eq org-startup-folded 'showeverything)
7152 (eq org-startup-folded nil))
7153 (outline-show-all)))
7154 (unless (eq org-startup-folded 'showeverything)
7155 (when org-hide-block-startup (org-hide-block-all))
7156 (org-set-visibility-according-to-property 'no-cleanup)
7157 (org-cycle-hide-archived-subtrees 'all)
7158 (org-cycle-hide-drawers 'all)
7159 (org-cycle-show-empty-lines t)))
7161 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7162 "Switch subtree visibilities according to :VISIBILITY: property."
7163 (interactive)
7164 (org-with-wide-buffer
7165 (goto-char (point-min))
7166 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7167 (if (not (org-at-property-p)) (outline-next-heading)
7168 (let ((state (match-string 3)))
7169 (save-excursion
7170 (org-back-to-heading t)
7171 (outline-hide-subtree)
7172 (org-reveal)
7173 (cond
7174 ((equal state "folded")
7175 (outline-hide-subtree))
7176 ((equal state "children")
7177 (org-show-hidden-entry)
7178 (org-show-children))
7179 ((equal state "content")
7180 (save-excursion
7181 (save-restriction
7182 (org-narrow-to-subtree)
7183 (org-content))))
7184 ((member state '("all" "showall"))
7185 (outline-show-subtree)))))))
7186 (unless no-cleanup
7187 (org-cycle-hide-archived-subtrees 'all)
7188 (org-cycle-hide-drawers 'all)
7189 (org-cycle-show-empty-lines 'all))))
7191 ;; This function uses outline-regexp instead of the more fundamental
7192 ;; org-outline-regexp so that org-cycle-global works outside of Org
7193 ;; buffers, where outline-regexp is needed.
7194 (defun org-overview ()
7195 "Switch to overview mode, showing only top-level headlines.
7196 This shows all headlines with a level equal or greater than the level
7197 of the first headline in the buffer. This is important, because if the
7198 first headline is not level one, then (hide-sublevels 1) gives confusing
7199 results."
7200 (interactive)
7201 (save-excursion
7202 (let ((level
7203 (save-excursion
7204 (goto-char (point-min))
7205 (when (re-search-forward (concat "^" outline-regexp) nil t)
7206 (goto-char (match-beginning 0))
7207 (funcall outline-level)))))
7208 (and level (outline-hide-sublevels level)))))
7210 (defun org-content (&optional arg)
7211 "Show all headlines in the buffer, like a table of contents.
7212 With numerical argument N, show content up to level N."
7213 (interactive "P")
7214 (org-overview)
7215 (save-excursion
7216 ;; Visit all headings and show their offspring
7217 (and (integerp arg) (org-overview))
7218 (goto-char (point-max))
7219 (catch 'exit
7220 (while (and (progn (condition-case nil
7221 (outline-previous-visible-heading 1)
7222 (error (goto-char (point-min))))
7224 (looking-at org-outline-regexp))
7225 (if (integerp arg)
7226 (org-show-children (1- arg))
7227 (outline-show-branches))
7228 (when (bobp) (throw 'exit nil))))))
7230 (defun org-optimize-window-after-visibility-change (state)
7231 "Adjust the window after a change in outline visibility.
7232 This function is the default value of the hook `org-cycle-hook'."
7233 (when (get-buffer-window (current-buffer))
7234 (cond
7235 ((eq state 'content) nil)
7236 ((eq state 'all) nil)
7237 ((eq state 'folded) nil)
7238 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7239 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7241 (defun org-remove-empty-overlays-at (pos)
7242 "Remove outline overlays that do not contain non-white stuff."
7243 (dolist (o (overlays-at pos))
7244 (and (eq 'outline (overlay-get o 'invisible))
7245 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7246 (overlay-end o))))
7247 (delete-overlay o))))
7249 (defun org-clean-visibility-after-subtree-move ()
7250 "Fix visibility issues after moving a subtree."
7251 ;; First, find a reasonable region to look at:
7252 ;; Start two siblings above, end three below
7253 (let* ((beg (save-excursion
7254 (and (org-get-last-sibling)
7255 (org-get-last-sibling))
7256 (point)))
7257 (end (save-excursion
7258 (and (org-get-next-sibling)
7259 (org-get-next-sibling)
7260 (org-get-next-sibling))
7261 (if (org-at-heading-p)
7262 (point-at-eol)
7263 (point))))
7264 (level (looking-at "\\*+"))
7265 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7266 (save-excursion
7267 (save-restriction
7268 (narrow-to-region beg end)
7269 (when re
7270 ;; Properly fold already folded siblings
7271 (goto-char (point-min))
7272 (while (re-search-forward re nil t)
7273 (when (and (not (outline-invisible-p))
7274 (save-excursion
7275 (goto-char (point-at-eol)) (outline-invisible-p)))
7276 (outline-hide-entry))))
7277 (org-cycle-show-empty-lines 'overview)
7278 (org-cycle-hide-drawers 'overview)))))
7280 (defun org-cycle-show-empty-lines (state)
7281 "Show empty lines above all visible headlines.
7282 The region to be covered depends on STATE when called through
7283 `org-cycle-hook'. Lisp program can use t for STATE to get the
7284 entire buffer covered. Note that an empty line is only shown if there
7285 are at least `org-cycle-separator-lines' empty lines before the headline."
7286 (when (/= org-cycle-separator-lines 0)
7287 (save-excursion
7288 (let* ((n (abs org-cycle-separator-lines))
7289 (re (cond
7290 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7291 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7292 (t (let ((ns (number-to-string (- n 2))))
7293 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7294 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7295 beg end)
7296 (cond
7297 ((memq state '(overview contents t))
7298 (setq beg (point-min) end (point-max)))
7299 ((memq state '(children folded))
7300 (setq beg (point)
7301 end (progn (org-end-of-subtree t t)
7302 (line-beginning-position 2)))))
7303 (when beg
7304 (goto-char beg)
7305 (while (re-search-forward re end t)
7306 (unless (get-char-property (match-end 1) 'invisible)
7307 (let ((e (match-end 1))
7308 (b (if (>= org-cycle-separator-lines 0)
7309 (match-beginning 1)
7310 (save-excursion
7311 (goto-char (match-beginning 0))
7312 (skip-chars-backward " \t\n")
7313 (line-end-position)))))
7314 (outline-flag-region b e nil))))))))
7315 ;; Never hide empty lines at the end of the file.
7316 (save-excursion
7317 (goto-char (point-max))
7318 (outline-previous-heading)
7319 (outline-end-of-heading)
7320 (when (and (looking-at "[ \t\n]+")
7321 (= (match-end 0) (point-max)))
7322 (outline-flag-region (point) (match-end 0) nil))))
7324 (defun org-show-empty-lines-in-parent ()
7325 "Move to the parent and re-show empty lines before visible headlines."
7326 (save-excursion
7327 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7328 (org-cycle-show-empty-lines context))))
7330 (defun org-files-list ()
7331 "Return `org-agenda-files' list, plus all open Org files.
7332 This is useful for operations that need to scan all of a user's
7333 open and agenda-wise Org files."
7334 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7335 (dolist (buf (buffer-list))
7336 (with-current-buffer buf
7337 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7338 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7339 files))
7341 (defsubst org-entry-beginning-position ()
7342 "Return the beginning position of the current entry."
7343 (save-excursion (org-back-to-heading t) (point)))
7345 (defsubst org-entry-end-position ()
7346 "Return the end position of the current entry."
7347 (save-excursion (outline-next-heading) (point)))
7349 (defun org-cycle-hide-drawers (state &optional exceptions)
7350 "Re-hide all drawers after a visibility state change.
7351 When non-nil, optional argument EXCEPTIONS is a list of strings
7352 specifying which drawers should not be hidden."
7353 (when (and (derived-mode-p 'org-mode)
7354 (not (memq state '(overview folded contents))))
7355 (save-excursion
7356 (let* ((globalp (memq state '(contents all)))
7357 (beg (if globalp (point-min) (point)))
7358 (end (if globalp (point-max)
7359 (if (eq state 'children)
7360 (save-excursion (outline-next-heading) (point))
7361 (org-end-of-subtree t)))))
7362 (goto-char beg)
7363 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7364 (unless (member-ignore-case (match-string 1) exceptions)
7365 (let ((drawer (org-element-at-point)))
7366 (when (memq (org-element-type drawer) '(drawer property-drawer))
7367 (org-flag-drawer t drawer)
7368 ;; Make sure to skip drawer entirely or we might flag
7369 ;; it another time when matching its ending line with
7370 ;; `org-drawer-regexp'.
7371 (goto-char (org-element-property :end drawer))))))))))
7373 (defun org-flag-drawer (flag &optional element)
7374 "When FLAG is non-nil, hide the drawer we are at.
7375 Otherwise make it visible. When optional argument ELEMENT is
7376 a parsed drawer, as returned by `org-element-at-point', hide or
7377 show that drawer instead."
7378 (let ((drawer (or element
7379 (and (save-excursion
7380 (beginning-of-line)
7381 (looking-at-p org-drawer-regexp))
7382 (org-element-at-point)))))
7383 (when (memq (org-element-type drawer) '(drawer property-drawer))
7384 (let ((post (org-element-property :post-affiliated drawer)))
7385 (save-excursion
7386 (outline-flag-region
7387 (progn (goto-char post) (line-end-position))
7388 (progn (goto-char (org-element-property :end drawer))
7389 (skip-chars-backward " \r\t\n")
7390 (line-end-position))
7391 flag))
7392 ;; When the drawer is hidden away, make sure point lies in
7393 ;; a visible part of the buffer.
7394 (when (and flag (> (line-beginning-position) post))
7395 (goto-char post))))))
7397 (defun org-subtree-end-visible-p ()
7398 "Is the end of the current subtree visible?"
7399 (pos-visible-in-window-p
7400 (save-excursion (org-end-of-subtree t) (point))))
7402 (defun org-first-headline-recenter ()
7403 "Move cursor to the first headline and recenter the headline."
7404 (let ((window (get-buffer-window)))
7405 (when window
7406 (goto-char (point-min))
7407 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7408 (set-window-start window (line-beginning-position))))))
7410 ;;; Saving and restoring visibility
7412 (defun org-outline-overlay-data (&optional use-markers)
7413 "Return a list of the locations of all outline overlays.
7414 These are overlays with the `invisible' property value `outline'.
7415 The return value is a list of cons cells, with start and stop
7416 positions for each overlay.
7417 If USE-MARKERS is set, return the positions as markers."
7418 (let (beg end)
7419 (org-with-wide-buffer
7420 (delq nil
7421 (mapcar (lambda (o)
7422 (when (eq (overlay-get o 'invisible) 'outline)
7423 (setq beg (overlay-start o)
7424 end (overlay-end o))
7425 (and beg end (> end beg)
7426 (if use-markers
7427 (cons (copy-marker beg)
7428 (copy-marker end t))
7429 (cons beg end)))))
7430 (overlays-in (point-min) (point-max)))))))
7432 (defun org-set-outline-overlay-data (data)
7433 "Create visibility overlays for all positions in DATA.
7434 DATA should have been made by `org-outline-overlay-data'."
7435 (org-with-wide-buffer
7436 (outline-show-all)
7437 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7439 ;;; Folding of blocks
7441 (defvar-local org-hide-block-overlays nil
7442 "Overlays hiding blocks.")
7444 (defun org-block-map (function &optional start end)
7445 "Call FUNCTION at the head of all source blocks in the current buffer.
7446 Optional arguments START and END can be used to limit the range."
7447 (let ((start (or start (point-min)))
7448 (end (or end (point-max))))
7449 (save-excursion
7450 (goto-char start)
7451 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7452 (save-excursion
7453 (save-match-data
7454 (goto-char (match-beginning 0))
7455 (funcall function)))))))
7457 (defun org-hide-block-toggle-all ()
7458 "Toggle the visibility of all blocks in the current buffer."
7459 (org-block-map 'org-hide-block-toggle))
7461 (defun org-hide-block-all ()
7462 "Fold all blocks in the current buffer."
7463 (interactive)
7464 (org-show-block-all)
7465 (org-block-map 'org-hide-block-toggle-maybe))
7467 (defun org-show-block-all ()
7468 "Unfold all blocks in the current buffer."
7469 (interactive)
7470 (mapc #'delete-overlay org-hide-block-overlays)
7471 (setq org-hide-block-overlays nil))
7473 (defun org-hide-block-toggle-maybe ()
7474 "Toggle visibility of block at point.
7475 Unlike to `org-hide-block-toggle', this function does not throw
7476 an error. Return a non-nil value when toggling is successful."
7477 (interactive)
7478 (ignore-errors (org-hide-block-toggle)))
7480 (defun org-hide-block-toggle (&optional force)
7481 "Toggle the visibility of the current block.
7482 When optional argument FORCE is `off', make block visible. If it
7483 is non-nil, hide it unconditionally. Throw an error when not at
7484 a block. Return a non-nil value when toggling is successful."
7485 (interactive)
7486 (let ((element (org-element-at-point)))
7487 (unless (memq (org-element-type element)
7488 '(center-block comment-block dynamic-block example-block
7489 export-block quote-block special-block
7490 src-block verse-block))
7491 (user-error "Not at a block"))
7492 (let* ((start (save-excursion
7493 (goto-char (org-element-property :post-affiliated element))
7494 (line-end-position)))
7495 (end (save-excursion
7496 (goto-char (org-element-property :end element))
7497 (skip-chars-backward " \r\t\n")
7498 (line-end-position)))
7499 (overlays (overlays-at start)))
7500 (cond
7501 ;; Do nothing when not before or at the block opening line or
7502 ;; at the block closing line.
7503 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7504 ((and (not (eq force 'off))
7505 (not (memq t (mapcar
7506 (lambda (o)
7507 (eq (overlay-get o 'invisible) 'org-hide-block))
7508 overlays))))
7509 (let ((ov (make-overlay start end)))
7510 (overlay-put ov 'invisible 'org-hide-block)
7511 ;; Make the block accessible to `isearch'.
7512 (overlay-put
7513 ov 'isearch-open-invisible
7514 (lambda (ov)
7515 (when (memq ov org-hide-block-overlays)
7516 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7517 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7518 (delete-overlay ov))))
7519 (push ov org-hide-block-overlays)
7520 ;; When the block is hidden away, make sure point is left in
7521 ;; a visible part of the buffer.
7522 (when (> (line-beginning-position) start)
7523 (goto-char start)
7524 (beginning-of-line))
7525 ;; Signal successful toggling.
7527 ((or (not force) (eq force 'off))
7528 (dolist (ov overlays t)
7529 (when (memq ov org-hide-block-overlays)
7530 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7531 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7532 (delete-overlay ov))))))))
7534 ;; org-tab-after-check-for-cycling-hook
7535 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7536 ;; Remove overlays when changing major mode
7537 (add-hook 'org-mode-hook
7538 (lambda () (add-hook 'change-major-mode-hook
7539 'org-show-block-all 'append 'local)))
7541 ;;; Org-goto
7543 (defvar org-goto-window-configuration nil)
7544 (defvar org-goto-marker nil)
7545 (defvar org-goto-map)
7546 (defun org-goto-map ()
7547 "Set the keymap `org-goto'."
7548 (setq org-goto-map
7549 (let ((map (make-sparse-keymap)))
7550 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7551 mouse-drag-region universal-argument org-occur)))
7552 (dolist (cmd cmds)
7553 (substitute-key-definition cmd cmd map global-map)))
7554 (suppress-keymap map)
7555 (org-defkey map "\C-m" 'org-goto-ret)
7556 (org-defkey map [(return)] 'org-goto-ret)
7557 (org-defkey map [(left)] 'org-goto-left)
7558 (org-defkey map [(right)] 'org-goto-right)
7559 (org-defkey map [(control ?g)] 'org-goto-quit)
7560 (org-defkey map "\C-i" 'org-cycle)
7561 (org-defkey map [(tab)] 'org-cycle)
7562 (org-defkey map [(down)] 'outline-next-visible-heading)
7563 (org-defkey map [(up)] 'outline-previous-visible-heading)
7564 (if org-goto-auto-isearch
7565 (if (fboundp 'define-key-after)
7566 (define-key-after map [t] 'org-goto-local-auto-isearch)
7567 nil)
7568 (org-defkey map "q" 'org-goto-quit)
7569 (org-defkey map "n" 'outline-next-visible-heading)
7570 (org-defkey map "p" 'outline-previous-visible-heading)
7571 (org-defkey map "f" 'outline-forward-same-level)
7572 (org-defkey map "b" 'outline-backward-same-level)
7573 (org-defkey map "u" 'outline-up-heading))
7574 (org-defkey map "/" 'org-occur)
7575 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7576 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7577 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7578 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7579 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7580 map)))
7582 (defconst org-goto-help
7583 "Browse buffer copy, to find location or copy text.%s
7584 RET=jump to location C-g=quit and return to previous location
7585 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7587 (defvar org-goto-start-pos) ; dynamically scoped parameter
7589 (defun org-goto (&optional alternative-interface)
7590 "Look up a different location in the current file, keeping current visibility.
7592 When you want look-up or go to a different location in a
7593 document, the fastest way is often to fold the entire buffer and
7594 then dive into the tree. This method has the disadvantage, that
7595 the previous location will be folded, which may not be what you
7596 want.
7598 This command works around this by showing a copy of the current
7599 buffer in an indirect buffer, in overview mode. You can dive
7600 into the tree in that copy, use org-occur and incremental search
7601 to find a location. When pressing RET or `Q', the command
7602 returns to the original buffer in which the visibility is still
7603 unchanged. After RET it will also jump to the location selected
7604 in the indirect buffer and expose the headline hierarchy above.
7606 With a prefix argument, use the alternative interface: e.g., if
7607 `org-goto-interface' is `outline' use `outline-path-completion'."
7608 (interactive "P")
7609 (org-goto-map)
7610 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7611 (org-refile-use-outline-path t)
7612 (org-refile-target-verify-function nil)
7613 (interface
7614 (if (not alternative-interface)
7615 org-goto-interface
7616 (if (eq org-goto-interface 'outline)
7617 'outline-path-completion
7618 'outline)))
7619 (org-goto-start-pos (point))
7620 (selected-point
7621 (if (eq interface 'outline)
7622 (car (org-get-location (current-buffer) org-goto-help))
7623 (let ((pa (org-refile-get-location "Goto")))
7624 (org-refile-check-position pa)
7625 (nth 3 pa)))))
7626 (if selected-point
7627 (progn
7628 (org-mark-ring-push org-goto-start-pos)
7629 (goto-char selected-point)
7630 (when (or (outline-invisible-p) (org-invisible-p2))
7631 (org-show-context 'org-goto)))
7632 (message "Quit"))))
7634 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7635 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7636 (defvar org-goto-local-auto-isearch-map) ; defined below
7638 (defun org-get-location (_buf help)
7639 "Let the user select a location in current buffer.
7640 This function uses a recursive edit. It returns the selected position
7641 or nil."
7642 (org-no-popups
7643 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7644 (isearch-hide-immediately nil)
7645 (isearch-search-fun-function
7646 (lambda () 'org-goto-local-search-headings))
7647 (org-goto-selected-point org-goto-exit-command))
7648 (save-excursion
7649 (save-window-excursion
7650 (delete-other-windows)
7651 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7652 (pop-to-buffer-same-window
7653 (condition-case nil
7654 (make-indirect-buffer (current-buffer) "*org-goto*")
7655 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7656 (with-output-to-temp-buffer "*Org Help*"
7657 (princ (format help (if org-goto-auto-isearch
7658 " Just type for auto-isearch."
7659 " n/p/f/b/u to navigate, q to quit."))))
7660 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7661 (setq buffer-read-only nil)
7662 (let ((org-startup-truncated t)
7663 (org-startup-folded nil)
7664 (org-startup-align-all-tables nil))
7665 (org-mode)
7666 (org-overview))
7667 (setq buffer-read-only t)
7668 (if (and (boundp 'org-goto-start-pos)
7669 (integer-or-marker-p org-goto-start-pos))
7670 (progn (goto-char org-goto-start-pos)
7671 (when (outline-invisible-p)
7672 (org-show-set-visibility 'lineage)))
7673 (goto-char (point-min)))
7674 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7675 (message "Select location and press RET")
7676 (use-local-map org-goto-map)
7677 (recursive-edit)))
7678 (kill-buffer "*org-goto*")
7679 (cons org-goto-selected-point org-goto-exit-command))))
7681 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7682 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7683 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7684 (if (fboundp 'isearch-other-control-char)
7685 (progn
7686 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7687 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7688 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7689 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7690 (define-key org-goto-local-auto-isearch-map [return] nil))
7692 (defun org-goto-local-search-headings (string bound noerror)
7693 "Search and make sure that any matches are in headlines."
7694 (catch 'return
7695 (while (if isearch-forward
7696 (search-forward string bound noerror)
7697 (search-backward string bound noerror))
7698 (when (save-match-data
7699 (and (save-excursion
7700 (beginning-of-line)
7701 (looking-at org-complex-heading-regexp))
7702 (or (not (match-beginning 5))
7703 (< (point) (match-beginning 5)))))
7704 (throw 'return (point))))))
7706 (defun org-goto-local-auto-isearch ()
7707 "Start isearch."
7708 (interactive)
7709 (goto-char (point-min))
7710 (let ((keys (this-command-keys)))
7711 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7712 (isearch-mode t)
7713 (isearch-process-search-char (string-to-char keys)))))
7715 (defun org-goto-ret (&optional _arg)
7716 "Finish `org-goto' by going to the new location."
7717 (interactive "P")
7718 (setq org-goto-selected-point (point))
7719 (setq org-goto-exit-command 'return)
7720 (throw 'exit nil))
7722 (defun org-goto-left ()
7723 "Finish `org-goto' by going to the new location."
7724 (interactive)
7725 (if (org-at-heading-p)
7726 (progn
7727 (beginning-of-line 1)
7728 (setq org-goto-selected-point (point)
7729 org-goto-exit-command 'left)
7730 (throw 'exit nil))
7731 (user-error "Not on a heading")))
7733 (defun org-goto-right ()
7734 "Finish `org-goto' by going to the new location."
7735 (interactive)
7736 (if (org-at-heading-p)
7737 (progn
7738 (setq org-goto-selected-point (point)
7739 org-goto-exit-command 'right)
7740 (throw 'exit nil))
7741 (user-error "Not on a heading")))
7743 (defun org-goto-quit ()
7744 "Finish `org-goto' without cursor motion."
7745 (interactive)
7746 (setq org-goto-selected-point nil)
7747 (setq org-goto-exit-command 'quit)
7748 (throw 'exit nil))
7750 ;;; Indirect buffer display of subtrees
7752 (defvar org-indirect-dedicated-frame nil
7753 "This is the frame being used for indirect tree display.")
7754 (defvar org-last-indirect-buffer nil)
7756 (defun org-tree-to-indirect-buffer (&optional arg)
7757 "Create indirect buffer and narrow it to current subtree.
7758 With a numerical prefix ARG, go up to this level and then take that tree.
7759 If ARG is negative, go up that many levels.
7761 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7762 indirect buffer previously made with this command, to avoid proliferation of
7763 indirect buffers. However, when you call the command with a \
7764 \\[universal-argument] prefix, or
7765 when `org-indirect-buffer-display' is `new-frame', the last buffer
7766 is kept so that you can work with several indirect buffers at the same time.
7767 If `org-indirect-buffer-display' is `dedicated-frame', the \
7768 \\[universal-argument] prefix also
7769 requests that a new frame be made for the new buffer, so that the dedicated
7770 frame is not changed."
7771 (interactive "P")
7772 (let ((cbuf (current-buffer))
7773 (cwin (selected-window))
7774 (pos (point))
7775 beg end level heading ibuf)
7776 (save-excursion
7777 (org-back-to-heading t)
7778 (when (numberp arg)
7779 (setq level (org-outline-level))
7780 (when (< arg 0) (setq arg (+ level arg)))
7781 (while (> (setq level (org-outline-level)) arg)
7782 (org-up-heading-safe)))
7783 (setq beg (point)
7784 heading (org-get-heading 'no-tags))
7785 (org-end-of-subtree t t)
7786 (when (org-at-heading-p) (backward-char 1))
7787 (setq end (point)))
7788 (when (and (buffer-live-p org-last-indirect-buffer)
7789 (not (eq org-indirect-buffer-display 'new-frame))
7790 (not arg))
7791 (kill-buffer org-last-indirect-buffer))
7792 (setq ibuf (org-get-indirect-buffer cbuf heading)
7793 org-last-indirect-buffer ibuf)
7794 (cond
7795 ((or (eq org-indirect-buffer-display 'new-frame)
7796 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7797 (select-frame (make-frame))
7798 (delete-other-windows)
7799 (pop-to-buffer-same-window ibuf)
7800 (org-set-frame-title heading))
7801 ((eq org-indirect-buffer-display 'dedicated-frame)
7802 (raise-frame
7803 (select-frame (or (and org-indirect-dedicated-frame
7804 (frame-live-p org-indirect-dedicated-frame)
7805 org-indirect-dedicated-frame)
7806 (setq org-indirect-dedicated-frame (make-frame)))))
7807 (delete-other-windows)
7808 (pop-to-buffer-same-window ibuf)
7809 (org-set-frame-title (concat "Indirect: " heading)))
7810 ((eq org-indirect-buffer-display 'current-window)
7811 (pop-to-buffer-same-window ibuf))
7812 ((eq org-indirect-buffer-display 'other-window)
7813 (pop-to-buffer ibuf))
7814 (t (error "Invalid value")))
7815 (narrow-to-region beg end)
7816 (outline-show-all)
7817 (goto-char pos)
7818 (run-hook-with-args 'org-cycle-hook 'all)
7819 (and (window-live-p cwin) (select-window cwin))))
7821 (defun org-get-indirect-buffer (&optional buffer heading)
7822 (setq buffer (or buffer (current-buffer)))
7823 (let ((n 1) (base (buffer-name buffer)) bname)
7824 (while (buffer-live-p
7825 (get-buffer
7826 (setq bname
7827 (concat base "-"
7828 (if heading (concat heading "-" (number-to-string n))
7829 (number-to-string n))))))
7830 (setq n (1+ n)))
7831 (condition-case nil
7832 (make-indirect-buffer buffer bname 'clone)
7833 (error (make-indirect-buffer buffer bname)))))
7835 (defun org-set-frame-title (title)
7836 "Set the title of the current frame to the string TITLE."
7837 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7839 ;;;; Structure editing
7841 ;;; Inserting headlines
7843 (defun org--line-empty-p (n)
7844 "Is the Nth next line empty?
7846 Counts the current line as N = 1 and the previous line as N = 0;
7847 see `beginning-of-line'."
7848 (save-excursion
7849 (and (not (bobp))
7850 (or (beginning-of-line n) t)
7851 (save-match-data
7852 (looking-at "[ \t]*$")))))
7854 (defun org-previous-line-empty-p ()
7855 "Is the previous line a blank line?
7856 When NEXT is non-nil, check the next line instead."
7857 (org--line-empty-p 0))
7859 (defun org-next-line-empty-p ()
7860 "Is the previous line a blank line?
7861 When NEXT is non-nil, check the next line instead."
7862 (org--line-empty-p 2))
7864 (defun org-insert-heading (&optional arg invisible-ok top)
7865 "Insert a new heading or an item with the same depth at point.
7867 If point is at the beginning of a heading or a list item, insert
7868 a new heading or a new item above the current one. When at the
7869 beginning of a regular line of text, turn it into a heading.
7871 If point is in the middle of a line, split it and create a new
7872 headline/item with the text in the current line after point (see
7873 `org-M-RET-may-split-line' on how to modify this behavior). As
7874 a special case, on a headline, splitting can only happen on the
7875 title itself. E.g., this excludes breaking stars or tags.
7877 With a \\[universal-argument] prefix, set \
7878 `org-insert-heading-respect-content' to
7879 a non-nil value for the duration of the command. This forces the
7880 insertion of a heading after the current subtree, independently
7881 on the location of point.
7883 With a \\[universal-argument] \\[universal-argument] prefix, \
7884 insert the heading at the end of the tree
7885 above the current heading. For example, if point is within a
7886 2nd-level heading, then it will insert a 2nd-level heading at
7887 the end of the 1st-level parent subtree.
7889 When INVISIBLE-OK is set, stop at invisible headlines when going
7890 back. This is important for non-interactive uses of the
7891 command.
7893 When optional argument TOP is non-nil, insert a level 1 heading,
7894 unconditionally."
7895 (interactive "P")
7896 (let ((itemp (and (not top) (org-in-item-p)))
7897 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7898 (respect-content (or org-insert-heading-respect-content
7899 (equal arg '(4))))
7900 (initial-content ""))
7902 (cond
7904 ((or (= (buffer-size) 0)
7905 (and (not (save-excursion
7906 (and (ignore-errors (org-back-to-heading invisible-ok))
7907 (org-at-heading-p))))
7908 (or arg (not itemp))))
7909 ;; At beginning of buffer or so high up that only a heading
7910 ;; makes sense.
7911 (cond ((and (bolp) (not respect-content)) (insert "* "))
7912 ((not respect-content)
7913 (unless may-split (end-of-line))
7914 (insert "\n* "))
7915 ((re-search-forward org-outline-regexp-bol nil t)
7916 (beginning-of-line)
7917 (insert "* \n")
7918 (backward-char))
7919 (t (goto-char (point-max))
7920 (insert "\n* ")))
7921 (run-hooks 'org-insert-heading-hook))
7923 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7926 ;; Maybe move at the end of the subtree
7927 (when (equal arg '(16))
7928 (org-up-heading-safe)
7929 (org-end-of-subtree t))
7930 ;; Insert a heading
7931 (save-restriction
7932 (widen)
7933 (let* ((level nil)
7934 (on-heading (org-at-heading-p))
7935 (empty-line-p (if on-heading
7936 (org-previous-line-empty-p)
7937 ;; We will decide later
7938 nil))
7939 ;; Get a level string to fall back on.
7940 (fix-level
7941 (if (org-before-first-heading-p) "*"
7942 (save-excursion
7943 (org-back-to-heading t)
7944 (when (org-previous-line-empty-p) (setq empty-line-p t))
7945 (looking-at org-outline-regexp)
7946 (make-string (1- (length (match-string 0))) ?*))))
7947 (stars
7948 (save-excursion
7949 (condition-case nil
7950 (if top "* "
7951 (org-back-to-heading invisible-ok)
7952 (when (and (not on-heading)
7953 (featurep 'org-inlinetask)
7954 (integerp org-inlinetask-min-level)
7955 (>= (length (match-string 0))
7956 org-inlinetask-min-level))
7957 ;; Find a heading level before the inline
7958 ;; task.
7959 (while (and (setq level (org-up-heading-safe))
7960 (>= level org-inlinetask-min-level)))
7961 (if (org-at-heading-p)
7962 (org-back-to-heading invisible-ok)
7963 (error "This should not happen")))
7964 (unless (and (save-excursion
7965 (save-match-data
7966 (org-backward-heading-same-level
7967 1 invisible-ok))
7968 (= (point) (match-beginning 0)))
7969 (not (org-next-line-empty-p)))
7970 (setq empty-line-p (or empty-line-p
7971 (org-previous-line-empty-p))))
7972 (match-string 0))
7973 (error (or fix-level "* ")))))
7974 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7975 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7977 ;; If we insert after content, move there and clean up
7978 ;; whitespace.
7979 (when respect-content
7980 (if (not (org-before-first-heading-p))
7981 (org-end-of-subtree nil t)
7982 (re-search-forward org-outline-regexp-bol)
7983 (beginning-of-line 0))
7984 (skip-chars-backward " \r\t\n")
7985 (and (not (looking-back "^\\*+" (line-beginning-position)))
7986 (looking-at "[ \t]+") (replace-match ""))
7987 (unless (eobp) (forward-char 1))
7988 (when (looking-at "^\\*")
7989 (unless (bobp) (backward-char 1))
7990 (insert "\n")))
7992 ;; If we are splitting, grab the text that should be moved
7993 ;; to the new headline.
7994 (when may-split
7995 (if (org-at-heading-p)
7996 ;; This is a heading: split intelligently (keeping
7997 ;; tags).
7998 (let ((pos (point)))
7999 (beginning-of-line)
8000 (unless (looking-at org-complex-heading-regexp)
8001 (error "This should not happen"))
8002 (when (and (match-beginning 4)
8003 (> pos (match-beginning 4))
8004 (< pos (match-end 4)))
8005 (setq initial-content (buffer-substring pos (match-end 4)))
8006 (goto-char pos)
8007 (delete-region (point) (match-end 4))
8008 (if (looking-at "[ \t]*$")
8009 (replace-match "")
8010 (insert (make-string (length initial-content) ?\s)))
8011 (setq initial-content (org-trim initial-content)))
8012 (goto-char pos))
8013 ;; A normal line.
8014 (setq initial-content
8015 (org-trim
8016 (delete-and-extract-region (point) (line-end-position))))))
8018 ;; If we are at the beginning of the line, insert before it.
8019 ;; Otherwise, after it.
8020 (cond
8021 ((and (bolp) (looking-at "[ \t]*$")))
8022 ((bolp) (save-excursion (insert "\n")))
8023 (t (end-of-line)
8024 (insert "\n")))
8026 ;; Insert the new heading
8027 (insert stars)
8028 (just-one-space)
8029 (insert initial-content)
8030 (unless (and blank (org-previous-line-empty-p))
8031 (org-N-empty-lines-before-current (if blank 1 0)))
8032 ;; Adjust visibility, which may be messed up if we removed
8033 ;; blank lines while previous entry was hidden.
8034 (let ((bol (line-beginning-position)))
8035 (dolist (o (overlays-at (1- bol)))
8036 (when (and (eq (overlay-get o 'invisible) 'outline)
8037 (eq (overlay-end o) bol))
8038 (move-overlay o (overlay-start o) (1- bol)))))
8039 (run-hooks 'org-insert-heading-hook)))))))
8041 (defun org-N-empty-lines-before-current (N)
8042 "Make the number of empty lines before current exactly N.
8043 So this will delete or add empty lines."
8044 (save-excursion
8045 (beginning-of-line)
8046 (let ((p (point)))
8047 (skip-chars-backward " \r\t\n")
8048 (unless (bolp) (forward-line))
8049 (delete-region (point) p))
8050 (when (> N 0) (insert (make-string N ?\n)))))
8052 (defun org-get-heading (&optional no-tags no-todo)
8053 "Return the heading of the current entry, without the stars.
8054 When NO-TAGS is non-nil, don't include tags.
8055 When NO-TODO is non-nil, don't include TODO keywords."
8056 (save-excursion
8057 (org-back-to-heading t)
8058 (let ((case-fold-search nil))
8059 (cond
8060 ((and no-tags no-todo)
8061 (looking-at org-complex-heading-regexp)
8062 ;; Return value has to be a string, but match group 4 is
8063 ;; optional.
8064 (or (match-string 4) ""))
8065 (no-tags
8066 (looking-at (concat org-outline-regexp
8067 "\\(.*?\\)"
8068 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8069 (match-string 1))
8070 (no-todo
8071 (looking-at org-todo-line-regexp)
8072 (match-string 3))
8073 (t (looking-at org-heading-regexp)
8074 (match-string 2))))))
8076 (defvar orgstruct-mode) ; defined below
8078 (defun org-heading-components ()
8079 "Return the components of the current heading.
8080 This is a list with the following elements:
8081 - the level as an integer
8082 - the reduced level, different if `org-odd-levels-only' is set.
8083 - the TODO keyword, or nil
8084 - the priority character, like ?A, or nil if no priority is given
8085 - the headline text itself, or the tags string if no headline text
8086 - the tags string, or nil."
8087 (save-excursion
8088 (org-back-to-heading t)
8089 (when (let (case-fold-search)
8090 (looking-at
8091 (if orgstruct-mode
8092 org-heading-regexp
8093 org-complex-heading-regexp)))
8094 (if orgstruct-mode
8095 (list (length (match-string 1))
8096 (org-reduced-level (length (match-string 1)))
8099 (match-string 2)
8100 nil)
8101 (list (length (match-string 1))
8102 (org-reduced-level (length (match-string 1)))
8103 (match-string-no-properties 2)
8104 (and (match-end 3) (aref (match-string 3) 2))
8105 (match-string-no-properties 4)
8106 (match-string-no-properties 5))))))
8108 (defun org-get-entry ()
8109 "Get the entry text, after heading, entire subtree."
8110 (save-excursion
8111 (org-back-to-heading t)
8112 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8114 (defun org-edit-headline (&optional heading)
8115 "Edit the current headline.
8116 Set it to HEADING when provided."
8117 (interactive)
8118 (org-with-wide-buffer
8119 (org-back-to-heading t)
8120 (when (looking-at org-complex-heading-regexp)
8121 (let* ((old (match-string-no-properties 4))
8122 (new (save-match-data
8123 (org-trim (or heading (read-string "Edit: " old))))))
8124 (unless (equal old new)
8125 (if old (replace-match new t t nil 4)
8126 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8127 (insert " " new))
8128 (org-set-tags nil t)
8129 (when (looking-at "[ \t]*$") (replace-match "")))))))
8131 (defun org-insert-heading-after-current ()
8132 "Insert a new heading with same level as current, after current subtree."
8133 (interactive)
8134 (org-back-to-heading)
8135 (org-insert-heading)
8136 (org-move-subtree-down)
8137 (end-of-line 1))
8139 (defun org-insert-heading-respect-content (&optional invisible-ok)
8140 "Insert heading with `org-insert-heading-respect-content' set to t."
8141 (interactive)
8142 (org-insert-heading '(4) invisible-ok))
8144 (defun org-insert-todo-heading-respect-content (&optional force-state)
8145 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8146 (interactive)
8147 (org-insert-todo-heading force-state '(4)))
8149 (defun org-insert-todo-heading (arg &optional force-heading)
8150 "Insert a new heading with the same level and TODO state as current heading.
8152 If the heading has no TODO state, or if the state is DONE, use
8153 the first state (TODO by default). Also with one prefix arg,
8154 force first state. With two prefix args, force inserting at the
8155 end of the parent subtree.
8157 When called at a plain list item, insert a new item with an
8158 unchecked check box."
8159 (interactive "P")
8160 (when (or force-heading (not (org-insert-item 'checkbox)))
8161 (org-insert-heading (or (and (equal arg '(16)) '(16))
8162 force-heading))
8163 (save-excursion
8164 (org-back-to-heading)
8165 (outline-previous-heading)
8166 (looking-at org-todo-line-regexp))
8167 (let* ((new-mark-x
8168 (if (or (equal arg '(4))
8169 (not (match-beginning 2))
8170 (member (match-string 2) org-done-keywords))
8171 (car org-todo-keywords-1)
8172 (match-string 2)))
8173 (new-mark
8175 (run-hook-with-args-until-success
8176 'org-todo-get-default-hook new-mark-x nil)
8177 new-mark-x)))
8178 (beginning-of-line 1)
8179 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8180 (if org-treat-insert-todo-heading-as-state-change
8181 (org-todo new-mark)
8182 (insert new-mark " "))))
8183 (when org-provide-todo-statistics
8184 (org-update-parent-todo-statistics))))
8186 (defun org-insert-subheading (arg)
8187 "Insert a new subheading and demote it.
8188 Works for outline headings and for plain lists alike."
8189 (interactive "P")
8190 (org-insert-heading arg)
8191 (cond
8192 ((org-at-heading-p) (org-do-demote))
8193 ((org-at-item-p) (org-indent-item))))
8195 (defun org-insert-todo-subheading (arg)
8196 "Insert a new subheading with TODO keyword or checkbox and demote it.
8197 Works for outline headings and for plain lists alike."
8198 (interactive "P")
8199 (org-insert-todo-heading arg)
8200 (cond
8201 ((org-at-heading-p) (org-do-demote))
8202 ((org-at-item-p) (org-indent-item))))
8204 ;;; Promotion and Demotion
8206 (defvar org-after-demote-entry-hook nil
8207 "Hook run after an entry has been demoted.
8208 The cursor will be at the beginning of the entry.
8209 When a subtree is being demoted, the hook will be called for each node.")
8211 (defvar org-after-promote-entry-hook nil
8212 "Hook run after an entry has been promoted.
8213 The cursor will be at the beginning of the entry.
8214 When a subtree is being promoted, the hook will be called for each node.")
8216 (defun org-promote-subtree ()
8217 "Promote the entire subtree.
8218 See also `org-promote'."
8219 (interactive)
8220 (save-excursion
8221 (org-with-limited-levels (org-map-tree 'org-promote)))
8222 (org-fix-position-after-promote))
8224 (defun org-demote-subtree ()
8225 "Demote the entire subtree.
8226 See `org-demote' and `org-promote'."
8227 (interactive)
8228 (save-excursion
8229 (org-with-limited-levels (org-map-tree 'org-demote)))
8230 (org-fix-position-after-promote))
8232 (defun org-do-promote ()
8233 "Promote the current heading higher up the tree.
8234 If the region is active in `transient-mark-mode', promote all
8235 headings in the region."
8236 (interactive)
8237 (save-excursion
8238 (if (org-region-active-p)
8239 (org-map-region 'org-promote (region-beginning) (region-end))
8240 (org-promote)))
8241 (org-fix-position-after-promote))
8243 (defun org-do-demote ()
8244 "Demote the current heading lower down the tree.
8245 If the region is active in `transient-mark-mode', demote all
8246 headings in the region."
8247 (interactive)
8248 (save-excursion
8249 (if (org-region-active-p)
8250 (org-map-region 'org-demote (region-beginning) (region-end))
8251 (org-demote)))
8252 (org-fix-position-after-promote))
8254 (defun org-fix-position-after-promote ()
8255 "Fix cursor position and indentation after demoting/promoting."
8256 (let ((pos (point)))
8257 (when (save-excursion
8258 (beginning-of-line 1)
8259 (looking-at org-todo-line-regexp)
8260 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8261 (cond ((eobp) (insert " "))
8262 ((eolp) (insert " "))
8263 ((equal (char-after) ?\ ) (forward-char 1))))))
8265 (defun org-current-level ()
8266 "Return the level of the current entry, or nil if before the first headline.
8267 The level is the number of stars at the beginning of the
8268 headline. Use `org-reduced-level' to remove the effect of
8269 `org-odd-levels'. Unlike to `org-outline-level', this function
8270 ignores inlinetasks."
8271 (let ((level (org-with-limited-levels (org-outline-level))))
8272 (and (> level 0) level)))
8274 (defun org-get-previous-line-level ()
8275 "Return the outline depth of the last headline before the current line.
8276 Returns 0 for the first headline in the buffer, and nil if before the
8277 first headline."
8278 (and (org-current-level)
8279 (or (and (/= (line-beginning-position) (point-min))
8280 (save-excursion (beginning-of-line 0) (org-current-level)))
8281 0)))
8283 (defun org-reduced-level (l)
8284 "Compute the effective level of a heading.
8285 This takes into account the setting of `org-odd-levels-only'."
8286 (cond
8287 ((zerop l) 0)
8288 (org-odd-levels-only (1+ (floor (/ l 2))))
8289 (t l)))
8291 (defun org-level-increment ()
8292 "Return the number of stars that will be added or removed at a
8293 time to headlines when structure editing, based on the value of
8294 `org-odd-levels-only'."
8295 (if org-odd-levels-only 2 1))
8297 (defun org-get-valid-level (level &optional change)
8298 "Rectify a level change under the influence of `org-odd-levels-only'
8299 LEVEL is a current level, CHANGE is by how much the level should be
8300 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8301 even level numbers will become the next higher odd number."
8302 (if org-odd-levels-only
8303 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8304 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8305 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8306 (max 1 (+ level (or change 0)))))
8308 (defun org-promote ()
8309 "Promote the current heading higher up the tree."
8310 (org-with-wide-buffer
8311 (org-back-to-heading t)
8312 (let* ((after-change-functions (remq 'flyspell-after-change-function
8313 after-change-functions))
8314 (level (save-match-data (funcall outline-level)))
8315 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8316 (diff (abs (- level (length up-head) -1))))
8317 (cond
8318 ((and (= level 1) org-allow-promoting-top-level-subtree)
8319 (replace-match "# " nil t))
8320 ((= level 1)
8321 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8322 (t (replace-match up-head nil t)))
8323 (unless (= level 1)
8324 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8325 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8326 (run-hooks 'org-after-promote-entry-hook))))
8328 (defun org-demote ()
8329 "Demote the current heading lower down the tree."
8330 (org-with-wide-buffer
8331 (org-back-to-heading t)
8332 (let* ((after-change-functions (remq 'flyspell-after-change-function
8333 after-change-functions))
8334 (level (save-match-data (funcall outline-level)))
8335 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8336 (diff (abs (- level (length down-head) -1))))
8337 (replace-match down-head nil t)
8338 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8339 (when org-adapt-indentation (org-fixup-indentation diff))
8340 (run-hooks 'org-after-demote-entry-hook))))
8342 (defun org-cycle-level ()
8343 "Cycle the level of an empty headline through possible states.
8344 This goes first to child, then to parent, level, then up the hierarchy.
8345 After top level, it switches back to sibling level."
8346 (interactive)
8347 (let ((org-adapt-indentation nil))
8348 (when (org-point-at-end-of-empty-headline)
8349 (setq this-command 'org-cycle-level) ; Only needed for caching
8350 (let ((cur-level (org-current-level))
8351 (prev-level (org-get-previous-line-level)))
8352 (cond
8353 ;; If first headline in file, promote to top-level.
8354 ((= prev-level 0)
8355 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8356 do (org-do-promote)))
8357 ;; If same level as prev, demote one.
8358 ((= prev-level cur-level)
8359 (org-do-demote))
8360 ;; If parent is top-level, promote to top level if not already.
8361 ((= prev-level 1)
8362 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8363 do (org-do-promote)))
8364 ;; If top-level, return to prev-level.
8365 ((= cur-level 1)
8366 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8367 do (org-do-demote)))
8368 ;; If less than prev-level, promote one.
8369 ((< cur-level prev-level)
8370 (org-do-promote))
8371 ;; If deeper than prev-level, promote until higher than
8372 ;; prev-level.
8373 ((> cur-level prev-level)
8374 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8375 do (org-do-promote))))
8376 t))))
8378 (defun org-map-tree (fun)
8379 "Call FUN for every heading underneath the current one."
8380 (org-back-to-heading t)
8381 (let ((level (funcall outline-level)))
8382 (save-excursion
8383 (funcall fun)
8384 (while (and (progn
8385 (outline-next-heading)
8386 (> (funcall outline-level) level))
8387 (not (eobp)))
8388 (funcall fun)))))
8390 (defun org-map-region (fun beg end)
8391 "Call FUN for every heading between BEG and END."
8392 (let ((org-ignore-region t))
8393 (save-excursion
8394 (setq end (copy-marker end))
8395 (goto-char beg)
8396 (when (and (re-search-forward org-outline-regexp-bol nil t)
8397 (< (point) end))
8398 (funcall fun))
8399 (while (and (progn
8400 (outline-next-heading)
8401 (< (point) end))
8402 (not (eobp)))
8403 (funcall fun)))))
8405 (defun org-fixup-indentation (diff)
8406 "Change the indentation in the current entry by DIFF.
8408 DIFF is an integer. Indentation is done according to the
8409 following rules:
8411 - Planning information and property drawers are always indented
8412 according to the new level of the headline;
8414 - Footnote definitions and their contents are ignored;
8416 - Inlinetasks' boundaries are not shifted;
8418 - Empty lines are ignored;
8420 - Other lines' indentation are shifted by DIFF columns, unless
8421 it would introduce a structural change in the document, in
8422 which case no shifting is done at all.
8424 Assume point is at a heading or an inlinetask beginning."
8425 (org-with-wide-buffer
8426 (narrow-to-region (line-beginning-position)
8427 (save-excursion
8428 (if (org-with-limited-levels (org-at-heading-p))
8429 (org-with-limited-levels (outline-next-heading))
8430 (org-inlinetask-goto-end))
8431 (point)))
8432 (forward-line)
8433 ;; Indent properly planning info and property drawer.
8434 (when (looking-at-p org-planning-line-re)
8435 (org-indent-line)
8436 (forward-line))
8437 (when (looking-at org-property-drawer-re)
8438 (goto-char (match-end 0))
8439 (forward-line)
8440 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8441 (catch 'no-shift
8442 (when (zerop diff) (throw 'no-shift nil))
8443 ;; If DIFF is negative, first check if a shift is possible at all
8444 ;; (e.g., it doesn't break structure). This can only happen if
8445 ;; some contents are not properly indented.
8446 (let ((case-fold-search t))
8447 (when (< diff 0)
8448 (let ((diff (- diff))
8449 (forbidden-re (concat org-outline-regexp
8450 "\\|"
8451 (substring org-footnote-definition-re 1))))
8452 (save-excursion
8453 (while (not (eobp))
8454 (cond
8455 ((looking-at-p "[ \t]*$") (forward-line))
8456 ((and (looking-at-p org-footnote-definition-re)
8457 (let ((e (org-element-at-point)))
8458 (and (eq (org-element-type e) 'footnote-definition)
8459 (goto-char (org-element-property :end e))))))
8460 ((looking-at-p org-outline-regexp) (forward-line))
8461 ;; Give up if shifting would move before column 0 or
8462 ;; if it would introduce a headline or a footnote
8463 ;; definition.
8465 (skip-chars-forward " \t")
8466 (let ((ind (current-column)))
8467 (when (or (< ind diff)
8468 (and (= ind diff) (looking-at-p forbidden-re)))
8469 (throw 'no-shift nil)))
8470 ;; Ignore contents of example blocks and source
8471 ;; blocks if their indentation is meant to be
8472 ;; preserved. Jump to block's closing line.
8473 (beginning-of-line)
8474 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8475 (let ((e (org-element-at-point)))
8476 (and (memq (org-element-type e)
8477 '(example-block src-block))
8478 (or org-src-preserve-indentation
8479 (org-element-property :preserve-indent e))
8480 (goto-char (org-element-property :end e))
8481 (progn (skip-chars-backward " \r\t\n")
8482 (beginning-of-line)
8483 t))))
8484 (forward-line))))))))
8485 ;; Shift lines but footnote definitions, inlinetasks boundaries
8486 ;; by DIFF. Also skip contents of source or example blocks
8487 ;; when indentation is meant to be preserved.
8488 (while (not (eobp))
8489 (cond
8490 ((and (looking-at-p org-footnote-definition-re)
8491 (let ((e (org-element-at-point)))
8492 (and (eq (org-element-type e) 'footnote-definition)
8493 (goto-char (org-element-property :end e))))))
8494 ((looking-at-p org-outline-regexp) (forward-line))
8495 ((looking-at-p "[ \t]*$") (forward-line))
8497 (indent-line-to (+ (org-get-indentation) diff))
8498 (beginning-of-line)
8499 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8500 (let ((e (org-element-at-point)))
8501 (and (memq (org-element-type e)
8502 '(example-block src-block))
8503 (or org-src-preserve-indentation
8504 (org-element-property :preserve-indent e))
8505 (goto-char (org-element-property :end e))
8506 (progn (skip-chars-backward " \r\t\n")
8507 (beginning-of-line)
8508 t))))
8509 (forward-line)))))))))
8511 (defun org-convert-to-odd-levels ()
8512 "Convert an Org file with all levels allowed to one with odd levels.
8513 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8514 level 5 etc."
8515 (interactive)
8516 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8517 (let ((outline-level 'org-outline-level)
8518 (org-odd-levels-only nil) n)
8519 (save-excursion
8520 (goto-char (point-min))
8521 (while (re-search-forward "^\\*\\*+ " nil t)
8522 (setq n (- (length (match-string 0)) 2))
8523 (while (>= (setq n (1- n)) 0)
8524 (org-demote))
8525 (end-of-line 1))))))
8527 (defun org-convert-to-oddeven-levels ()
8528 "Convert an Org file with only odd levels to one with odd/even levels.
8529 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8530 file contains a section with an even level, conversion would
8531 destroy the structure of the file. An error is signaled in this
8532 case."
8533 (interactive)
8534 (goto-char (point-min))
8535 ;; First check if there are no even levels
8536 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8537 (org-show-set-visibility 'canonical)
8538 (error "Not all levels are odd in this file. Conversion not possible"))
8539 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8540 (let ((outline-regexp org-outline-regexp)
8541 (outline-level 'org-outline-level)
8542 (org-odd-levels-only nil) n)
8543 (save-excursion
8544 (goto-char (point-min))
8545 (while (re-search-forward "^\\*\\*+ " nil t)
8546 (setq n (/ (1- (length (match-string 0))) 2))
8547 (while (>= (setq n (1- n)) 0)
8548 (org-promote))
8549 (end-of-line 1))))))
8551 (defun org-tr-level (n)
8552 "Make N odd if required."
8553 (if org-odd-levels-only (1+ (/ n 2)) n))
8555 ;;; Vertical tree motion, cutting and pasting of subtrees
8557 (defun org-move-subtree-up (&optional arg)
8558 "Move the current subtree up past ARG headlines of the same level."
8559 (interactive "p")
8560 (org-move-subtree-down (- (prefix-numeric-value arg))))
8562 (defun org-move-subtree-down (&optional arg)
8563 "Move the current subtree down past ARG headlines of the same level."
8564 (interactive "p")
8565 (setq arg (prefix-numeric-value arg))
8566 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8567 'org-get-last-sibling))
8568 (ins-point (make-marker))
8569 (cnt (abs arg))
8570 (col (current-column))
8571 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8572 ;; Select the tree
8573 (org-back-to-heading)
8574 (setq beg0 (point))
8575 (save-excursion
8576 (setq ne-beg (org-back-over-empty-lines))
8577 (setq beg (point)))
8578 (save-match-data
8579 (save-excursion (outline-end-of-heading)
8580 (setq folded (outline-invisible-p)))
8581 (progn (org-end-of-subtree nil t)
8582 (unless (eobp) (backward-char))))
8583 (outline-next-heading)
8584 (setq ne-end (org-back-over-empty-lines))
8585 (setq end (point))
8586 (goto-char beg0)
8587 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8588 ;; include less whitespace
8589 (save-excursion
8590 (goto-char beg)
8591 (forward-line (- ne-beg ne-end))
8592 (setq beg (point))))
8593 ;; Find insertion point, with error handling
8594 (while (> cnt 0)
8595 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8596 (progn (goto-char beg0)
8597 (user-error "Cannot move past superior level or buffer limit")))
8598 (setq cnt (1- cnt)))
8599 (when (> arg 0)
8600 ;; Moving forward - still need to move over subtree
8601 (org-end-of-subtree t t)
8602 (save-excursion
8603 (org-back-over-empty-lines)
8604 (or (bolp) (newline))))
8605 (setq ne-ins (org-back-over-empty-lines))
8606 (move-marker ins-point (point))
8607 (setq txt (buffer-substring beg end))
8608 (org-save-markers-in-region beg end)
8609 (delete-region beg end)
8610 (org-remove-empty-overlays-at beg)
8611 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8612 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8613 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8614 (let ((bbb (point)))
8615 (insert-before-markers txt)
8616 (org-reinstall-markers-in-region bbb)
8617 (move-marker ins-point bbb))
8618 (or (bolp) (insert "\n"))
8619 (setq ins-end (point))
8620 (goto-char ins-point)
8621 (org-skip-whitespace)
8622 (when (and (< arg 0)
8623 (org-first-sibling-p)
8624 (> ne-ins ne-beg))
8625 ;; Move whitespace back to beginning
8626 (save-excursion
8627 (goto-char ins-end)
8628 (let ((kill-whole-line t))
8629 (kill-line (- ne-ins ne-beg)) (point)))
8630 (insert (make-string (- ne-ins ne-beg) ?\n)))
8631 (move-marker ins-point nil)
8632 (if folded
8633 (outline-hide-subtree)
8634 (org-show-entry)
8635 (org-show-children)
8636 (org-cycle-hide-drawers 'children))
8637 (org-clean-visibility-after-subtree-move)
8638 ;; move back to the initial column we were at
8639 (move-to-column col)))
8641 (defvar org-subtree-clip ""
8642 "Clipboard for cut and paste of subtrees.
8643 This is actually only a copy of the kill, because we use the normal kill
8644 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8646 (defvar org-subtree-clip-folded nil
8647 "Was the last copied subtree folded?
8648 This is used to fold the tree back after pasting.")
8650 (defun org-cut-subtree (&optional n)
8651 "Cut the current subtree into the clipboard.
8652 With prefix arg N, cut this many sequential subtrees.
8653 This is a short-hand for marking the subtree and then cutting it."
8654 (interactive "p")
8655 (org-copy-subtree n 'cut))
8657 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8658 "Copy the current subtree it in the clipboard.
8659 With prefix arg N, copy this many sequential subtrees.
8660 This is a short-hand for marking the subtree and then copying it.
8661 If CUT is non-nil, actually cut the subtree.
8662 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8663 of some markers in the region, even if CUT is non-nil. This is
8664 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8665 (interactive "p")
8666 (let (beg end folded (beg0 (point)))
8667 (if (called-interactively-p 'any)
8668 (org-back-to-heading nil) ; take what looks like a subtree
8669 (org-back-to-heading t)) ; take what is really there
8670 (setq beg (point))
8671 (skip-chars-forward " \t\r\n")
8672 (save-match-data
8673 (if nosubtrees
8674 (outline-next-heading)
8675 (save-excursion (outline-end-of-heading)
8676 (setq folded (outline-invisible-p)))
8677 (ignore-errors (org-forward-heading-same-level (1- n) t))
8678 (org-end-of-subtree t t)))
8679 ;; Include the end of an inlinetask
8680 (when (and (featurep 'org-inlinetask)
8681 (looking-at-p (concat (org-inlinetask-outline-regexp)
8682 "END[ \t]*$")))
8683 (end-of-line))
8684 (setq end (point))
8685 (goto-char beg0)
8686 (when (> end beg)
8687 (setq org-subtree-clip-folded folded)
8688 (when (or cut force-store-markers)
8689 (org-save-markers-in-region beg end))
8690 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8691 (setq org-subtree-clip (current-kill 0))
8692 (message "%s: Subtree(s) with %d characters"
8693 (if cut "Cut" "Copied")
8694 (length org-subtree-clip)))))
8696 (defun org-paste-subtree (&optional level tree for-yank remove)
8697 "Paste the clipboard as a subtree, with modification of headline level.
8698 The entire subtree is promoted or demoted in order to match a new headline
8699 level.
8701 If the cursor is at the beginning of a headline, the same level as
8702 that headline is used to paste the tree.
8704 If not, the new level is derived from the *visible* headings
8705 before and after the insertion point, and taken to be the inferior headline
8706 level of the two. So if the previous visible heading is level 3 and the
8707 next is level 4 (or vice versa), level 4 will be used for insertion.
8708 This makes sure that the subtree remains an independent subtree and does
8709 not swallow low level entries.
8711 You can also force a different level, either by using a numeric prefix
8712 argument, or by inserting the heading marker by hand. For example, if the
8713 cursor is after \"*****\", then the tree will be shifted to level 5.
8715 If optional TREE is given, use this text instead of the kill ring.
8717 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8718 move back over whitespace before inserting, and move point to the end of
8719 the inserted text when done.
8721 When REMOVE is non-nil, remove the subtree from the clipboard."
8722 (interactive "P")
8723 (setq tree (or tree (and kill-ring (current-kill 0))))
8724 (unless (org-kill-is-subtree-p tree)
8725 (user-error "%s"
8726 (substitute-command-keys
8727 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8728 (org-with-limited-levels
8729 (let* ((visp (not (outline-invisible-p)))
8730 (txt tree)
8731 (^re_ "\\(\\*+\\)[ \t]*")
8732 (old-level (if (string-match org-outline-regexp-bol txt)
8733 (- (match-end 0) (match-beginning 0) 1)
8734 -1))
8735 (force-level (cond (level (prefix-numeric-value level))
8736 ((and (looking-at "[ \t]*$")
8737 (string-match
8738 "^\\*+$" (buffer-substring
8739 (point-at-bol) (point))))
8740 (- (match-end 0) (match-beginning 0)))
8741 ((and (bolp)
8742 (looking-at org-outline-regexp))
8743 (- (match-end 0) (point) 1))))
8744 (previous-level (save-excursion
8745 (condition-case nil
8746 (progn
8747 (outline-previous-visible-heading 1)
8748 (if (looking-at ^re_)
8749 (- (match-end 0) (match-beginning 0) 1)
8751 (error 1))))
8752 (next-level (save-excursion
8753 (condition-case nil
8754 (progn
8755 (or (looking-at org-outline-regexp)
8756 (outline-next-visible-heading 1))
8757 (if (looking-at ^re_)
8758 (- (match-end 0) (match-beginning 0) 1)
8760 (error 1))))
8761 (new-level (or force-level (max previous-level next-level)))
8762 (shift (if (or (= old-level -1)
8763 (= new-level -1)
8764 (= old-level new-level))
8766 (- new-level old-level)))
8767 (delta (if (> shift 0) -1 1))
8768 (func (if (> shift 0) 'org-demote 'org-promote))
8769 (org-odd-levels-only nil)
8770 beg end newend)
8771 ;; Remove the forced level indicator
8772 (when force-level
8773 (delete-region (point-at-bol) (point)))
8774 ;; Paste
8775 (beginning-of-line (if (bolp) 1 2))
8776 (setq beg (point))
8777 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8778 (insert-before-markers txt)
8779 (unless (string-suffix-p "\n" txt) (insert "\n"))
8780 (setq newend (point))
8781 (org-reinstall-markers-in-region beg)
8782 (setq end (point))
8783 (goto-char beg)
8784 (skip-chars-forward " \t\n\r")
8785 (setq beg (point))
8786 (when (and (outline-invisible-p) visp)
8787 (save-excursion (outline-show-heading)))
8788 ;; Shift if necessary
8789 (unless (= shift 0)
8790 (save-restriction
8791 (narrow-to-region beg end)
8792 (while (not (= shift 0))
8793 (org-map-region func (point-min) (point-max))
8794 (setq shift (+ delta shift)))
8795 (goto-char (point-min))
8796 (setq newend (point-max))))
8797 (when (or (called-interactively-p 'interactive) for-yank)
8798 (message "Clipboard pasted as level %d subtree" new-level))
8799 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8800 kill-ring
8801 (eq org-subtree-clip (current-kill 0))
8802 org-subtree-clip-folded)
8803 ;; The tree was folded before it was killed/copied
8804 (outline-hide-subtree))
8805 (and for-yank (goto-char newend))
8806 (and remove (setq kill-ring (cdr kill-ring))))))
8808 (defun org-kill-is-subtree-p (&optional txt)
8809 "Check if the current kill is an outline subtree, or a set of trees.
8810 Returns nil if kill does not start with a headline, or if the first
8811 headline level is not the largest headline level in the tree.
8812 So this will actually accept several entries of equal levels as well,
8813 which is OK for `org-paste-subtree'.
8814 If optional TXT is given, check this string instead of the current kill."
8815 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8816 (re (org-get-limited-outline-regexp))
8817 (^re (concat "^" re))
8818 (start-level (and kill
8819 (string-match
8820 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8821 kill)
8822 (- (match-end 2) (match-beginning 2) 1)))
8823 (start (1+ (or (match-beginning 2) -1))))
8824 (if (not start-level)
8825 (progn
8826 nil) ;; does not even start with a heading
8827 (catch 'exit
8828 (while (setq start (string-match ^re kill (1+ start)))
8829 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8830 (throw 'exit nil)))
8831 t))))
8833 (defvar org-markers-to-move nil
8834 "Markers that should be moved with a cut-and-paste operation.
8835 Those markers are stored together with their positions relative to
8836 the start of the region.")
8838 (defun org-save-markers-in-region (beg end)
8839 "Check markers in region.
8840 If these markers are between BEG and END, record their position relative
8841 to BEG, so that after moving the block of text, we can put the markers back
8842 into place.
8843 This function gets called just before an entry or tree gets cut from the
8844 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8845 called immediately, to move the markers with the entries."
8846 (setq org-markers-to-move nil)
8847 (when (featurep 'org-clock)
8848 (org-clock-save-markers-for-cut-and-paste beg end))
8849 (when (featurep 'org-agenda)
8850 (org-agenda-save-markers-for-cut-and-paste beg end)))
8852 (defun org-check-and-save-marker (marker beg end)
8853 "Check if MARKER is between BEG and END.
8854 If yes, remember the marker and the distance to BEG."
8855 (when (and (marker-buffer marker)
8856 (equal (marker-buffer marker) (current-buffer))
8857 (>= marker beg) (< marker end))
8858 (push (cons marker (- marker beg)) org-markers-to-move)))
8860 (defun org-reinstall-markers-in-region (beg)
8861 "Move all remembered markers to their position relative to BEG."
8862 (dolist (x org-markers-to-move)
8863 (move-marker (car x) (+ beg (cdr x))))
8864 (setq org-markers-to-move nil))
8866 (defun org-narrow-to-subtree ()
8867 "Narrow buffer to the current subtree."
8868 (interactive)
8869 (save-excursion
8870 (save-match-data
8871 (org-with-limited-levels
8872 (narrow-to-region
8873 (progn (org-back-to-heading t) (point))
8874 (progn (org-end-of-subtree t t)
8875 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8876 (point)))))))
8878 (defun org-narrow-to-block ()
8879 "Narrow buffer to the current block."
8880 (interactive)
8881 (let* ((case-fold-search t)
8882 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8883 "^[ \t]*#\\+end_.*")))
8884 (if blockp
8885 (narrow-to-region (car blockp) (cdr blockp))
8886 (user-error "Not in a block"))))
8888 (defun org-clone-subtree-with-time-shift (n &optional shift)
8889 "Clone the task (subtree) at point N times.
8890 The clones will be inserted as siblings.
8892 In interactive use, the user will be prompted for the number of
8893 clones to be produced. If the entry has a timestamp, the user
8894 will also be prompted for a time shift, which may be a repeater
8895 as used in time stamps, for example `+3d'. To disable this,
8896 you can call the function with a universal prefix argument.
8898 When a valid repeater is given and the entry contains any time
8899 stamps, the clones will become a sequence in time, with time
8900 stamps in the subtree shifted for each clone produced. If SHIFT
8901 is nil or the empty string, time stamps will be left alone. The
8902 ID property of the original subtree is removed.
8904 In each clone, all the CLOCK entries will be removed. This
8905 prevents Org from considering that the clocked times overlap.
8907 If the original subtree did contain time stamps with a repeater,
8908 the following will happen:
8909 - the repeater will be removed in each clone
8910 - an additional clone will be produced, with the current, unshifted
8911 date(s) in the entry.
8912 - the original entry will be placed *after* all the clones, with
8913 repeater intact.
8914 - the start days in the repeater in the original entry will be shifted
8915 to past the last clone.
8916 In this way you can spell out a number of instances of a repeating task,
8917 and still retain the repeater to cover future instances of the task.
8919 As described above, N+1 clones are produced when the original
8920 subtree has a repeater. Setting N to 0, then, can be used to
8921 remove the repeater from a subtree and create a shifted clone
8922 with the original repeater."
8923 (interactive "nNumber of clones to produce: ")
8924 (let ((shift
8925 (or shift
8926 (if (and (not (equal current-prefix-arg '(4)))
8927 (save-excursion
8928 (re-search-forward org-ts-regexp-both
8929 (save-excursion
8930 (org-end-of-subtree t)
8931 (point)) t)))
8932 (read-from-minibuffer
8933 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8934 ""))) ;; No time shift
8935 (n-no-remove -1)
8936 (drawer-re org-drawer-regexp)
8937 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8938 beg end template task idprop
8939 shift-n shift-what doshift nmin nmax)
8940 (unless (wholenump n)
8941 (user-error "Invalid number of replications %s" n))
8942 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8943 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8944 shift)))
8945 (user-error "Invalid shift specification %s" shift))
8946 (when doshift
8947 (setq shift-n (string-to-number (match-string 1 shift))
8948 shift-what (cdr (assoc (match-string 2 shift)
8949 '(("d" . day) ("w" . week)
8950 ("m" . month) ("y" . year))))))
8951 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8952 (setq nmin 1 nmax n)
8953 (org-back-to-heading t)
8954 (setq beg (point))
8955 (setq idprop (org-entry-get nil "ID"))
8956 (org-end-of-subtree t t)
8957 (or (bolp) (insert "\n"))
8958 (setq end (point))
8959 (setq template (buffer-substring beg end))
8960 (when (and doshift
8961 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8962 (delete-region beg end)
8963 (setq end beg)
8964 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8965 (goto-char end)
8966 (cl-loop for n from nmin to nmax do
8967 ;; prepare clone
8968 (with-temp-buffer
8969 (insert template)
8970 (org-mode)
8971 (goto-char (point-min))
8972 (org-show-subtree)
8973 (and idprop (if org-clone-delete-id
8974 (org-entry-delete nil "ID")
8975 (org-id-get-create t)))
8976 (unless (= n 0)
8977 (while (re-search-forward org-clock-re nil t)
8978 (kill-whole-line))
8979 (goto-char (point-min))
8980 (while (re-search-forward drawer-re nil t)
8981 (org-remove-empty-drawer-at (point))))
8982 (goto-char (point-min))
8983 (when doshift
8984 (while (re-search-forward org-ts-regexp-both nil t)
8985 (org-timestamp-change (* n shift-n) shift-what))
8986 (unless (= n n-no-remove)
8987 (goto-char (point-min))
8988 (while (re-search-forward org-ts-regexp nil t)
8989 (save-excursion
8990 (goto-char (match-beginning 0))
8991 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8992 (delete-region (match-beginning 1) (match-end 1)))))))
8993 (setq task (buffer-string)))
8994 (insert task))
8995 (goto-char beg)))
8997 ;;; Outline Sorting
8999 (defun org-sort (with-case)
9000 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9001 Optional argument WITH-CASE means sort case-sensitively."
9002 (interactive "P")
9003 (cond
9004 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9005 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9007 (org-call-with-arg 'org-sort-entries with-case))))
9009 (defun org-sort-remove-invisible (s)
9010 "Remove invisible links from string S."
9011 (remove-text-properties 0 (length s) org-rm-props s)
9012 (while (string-match org-bracket-link-regexp s)
9013 (setq s (replace-match (if (match-end 2)
9014 (match-string 3 s)
9015 (match-string 1 s))
9016 t t s)))
9017 (let ((st (format " %s " s)))
9018 (while (string-match org-emph-re st)
9019 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9020 (setq s (substring st 1 -1)))
9023 (defvar org-priority-regexp) ; defined later in the file
9025 (defvar org-after-sorting-entries-or-items-hook nil
9026 "Hook that is run after a bunch of entries or items have been sorted.
9027 When children are sorted, the cursor is in the parent line when this
9028 hook gets called. When a region or a plain list is sorted, the cursor
9029 will be in the first entry of the sorted region/list.")
9031 (defun org-sort-entries
9032 (&optional with-case sorting-type getkey-func compare-func property)
9033 "Sort entries on a certain level of an outline tree.
9034 If there is an active region, the entries in the region are sorted.
9035 Else, if the cursor is before the first entry, sort the top-level items.
9036 Else, the children of the entry at point are sorted.
9038 Sorting can be alphabetically, numerically, by date/time as given by
9039 a time stamp, by a property, by priority order, or by a custom function.
9041 The command prompts for the sorting type unless it has been given to the
9042 function through the SORTING-TYPE argument, which needs to be a character,
9043 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9044 the precise meaning of each character:
9046 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9047 c By creation time, which is assumed to be the first inactive time stamp
9048 at the beginning of a line.
9049 d By deadline date/time.
9050 k By clocking time.
9051 n Numerically, by converting the beginning of the entry/item to a number.
9052 o By order of TODO keywords.
9053 p By priority according to the cookie.
9054 r By the value of a property.
9055 s By scheduled date/time.
9056 t By date/time, either the first active time stamp in the entry, or, if
9057 none exist, by the first inactive one.
9059 Capital letters will reverse the sort order.
9061 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9062 called with point at the beginning of the record. It must return either
9063 a string or a number that should serve as the sorting key for that record.
9065 Comparing entries ignores case by default. However, with an optional argument
9066 WITH-CASE, the sorting considers case as well.
9068 Sorting is done against the visible part of the headlines, it ignores hidden
9069 links.
9071 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9072 (interactive "P")
9073 (let ((case-func (if with-case 'identity 'downcase))
9074 (cmstr
9075 ;; The clock marker is lost when using `sort-subr', let's
9076 ;; store the clocking string.
9077 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9078 (save-excursion
9079 (goto-char org-clock-marker)
9080 (buffer-substring-no-properties (line-beginning-position)
9081 (point)))))
9082 start beg end stars re re2
9083 txt what tmp)
9084 ;; Find beginning and end of region to sort
9085 (cond
9086 ((org-region-active-p)
9087 ;; we will sort the region
9088 (setq end (region-end)
9089 what "region")
9090 (goto-char (region-beginning))
9091 (unless (org-at-heading-p) (outline-next-heading))
9092 (setq start (point)))
9093 ((or (org-at-heading-p)
9094 (ignore-errors (progn (org-back-to-heading) t)))
9095 ;; we will sort the children of the current headline
9096 (org-back-to-heading)
9097 (setq start (point)
9098 end (progn (org-end-of-subtree t t)
9099 (or (bolp) (insert "\n"))
9100 (when (>= (org-back-over-empty-lines) 1)
9101 (forward-line 1))
9102 (point))
9103 what "children")
9104 (goto-char start)
9105 (outline-show-subtree)
9106 (outline-next-heading))
9108 ;; we will sort the top-level entries in this file
9109 (goto-char (point-min))
9110 (or (org-at-heading-p) (outline-next-heading))
9111 (setq start (point))
9112 (goto-char (point-max))
9113 (beginning-of-line 1)
9114 (when (looking-at ".*?\\S-")
9115 ;; File ends in a non-white line
9116 (end-of-line 1)
9117 (insert "\n"))
9118 (setq end (point-max))
9119 (setq what "top-level")
9120 (goto-char start)
9121 (outline-show-all)))
9123 (setq beg (point))
9124 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9126 (looking-at "\\(\\*+\\)")
9127 (setq stars (match-string 1)
9128 re (concat "^" (regexp-quote stars) " +")
9129 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9130 txt (buffer-substring beg end))
9131 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9132 (when (and (not (equal stars "*")) (string-match re2 txt))
9133 (user-error "Region to sort contains a level above the first entry"))
9135 (unless sorting-type
9136 (message
9137 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9138 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9139 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9140 what)
9141 (setq sorting-type (read-char-exclusive))
9143 (unless getkey-func
9144 (and (= (downcase sorting-type) ?f)
9145 (setq getkey-func
9146 (completing-read "Sort using function: "
9147 obarray 'fboundp t nil nil))
9148 (setq getkey-func (intern getkey-func))))
9150 (and (= (downcase sorting-type) ?r)
9151 (not property)
9152 (setq property
9153 (completing-read "Property: "
9154 (mapcar #'list (org-buffer-property-keys t))
9155 nil t))))
9157 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9158 (message "Sorting entries...")
9160 (save-restriction
9161 (narrow-to-region start end)
9162 (let ((dcst (downcase sorting-type))
9163 (case-fold-search nil)
9164 (now (current-time)))
9165 (sort-subr
9166 (/= dcst sorting-type)
9167 ;; This function moves to the beginning character of the "record" to
9168 ;; be sorted.
9169 (lambda nil
9170 (if (re-search-forward re nil t)
9171 (goto-char (match-beginning 0))
9172 (goto-char (point-max))))
9173 ;; This function moves to the last character of the "record" being
9174 ;; sorted.
9175 (lambda nil
9176 (save-match-data
9177 (condition-case nil
9178 (outline-forward-same-level 1)
9179 (error
9180 (goto-char (point-max))))))
9181 ;; This function returns the value that gets sorted against.
9182 (lambda nil
9183 (cond
9184 ((= dcst ?n)
9185 (if (looking-at org-complex-heading-regexp)
9186 (string-to-number (org-sort-remove-invisible (match-string 4)))
9187 nil))
9188 ((= dcst ?a)
9189 (if (looking-at org-complex-heading-regexp)
9190 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9191 nil))
9192 ((= dcst ?k)
9193 (or (get-text-property (point) :org-clock-minutes) 0))
9194 ((= dcst ?t)
9195 (let ((end (save-excursion (outline-next-heading) (point))))
9196 (if (or (re-search-forward org-ts-regexp end t)
9197 (re-search-forward org-ts-regexp-both end t))
9198 (org-time-string-to-seconds (match-string 0))
9199 (float-time now))))
9200 ((= dcst ?c)
9201 (let ((end (save-excursion (outline-next-heading) (point))))
9202 (if (re-search-forward
9203 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9204 end t)
9205 (org-time-string-to-seconds (match-string 0))
9206 (float-time now))))
9207 ((= dcst ?s)
9208 (let ((end (save-excursion (outline-next-heading) (point))))
9209 (if (re-search-forward org-scheduled-time-regexp end t)
9210 (org-time-string-to-seconds (match-string 1))
9211 (float-time now))))
9212 ((= dcst ?d)
9213 (let ((end (save-excursion (outline-next-heading) (point))))
9214 (if (re-search-forward org-deadline-time-regexp end t)
9215 (org-time-string-to-seconds (match-string 1))
9216 (float-time now))))
9217 ((= dcst ?p)
9218 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9219 (string-to-char (match-string 2))
9220 org-default-priority))
9221 ((= dcst ?r)
9222 (or (org-entry-get nil property) ""))
9223 ((= dcst ?o)
9224 (when (looking-at org-complex-heading-regexp)
9225 (let* ((m (match-string 2))
9226 (s (if (member m org-done-keywords) '- '+)))
9227 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9228 ((= dcst ?f)
9229 (if getkey-func
9230 (progn
9231 (setq tmp (funcall getkey-func))
9232 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9233 tmp)
9234 (error "Invalid key function `%s'" getkey-func)))
9235 (t (error "Invalid sorting type `%c'" sorting-type))))
9237 (cond
9238 ((= dcst ?a) 'string<)
9239 ((= dcst ?f) compare-func)
9240 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9241 (run-hooks 'org-after-sorting-entries-or-items-hook)
9242 ;; Reset the clock marker if needed
9243 (when cmstr
9244 (save-excursion
9245 (goto-char start)
9246 (search-forward cmstr nil t)
9247 (move-marker org-clock-marker (point))))
9248 (message "Sorting entries...done")))
9250 ;;; The orgstruct minor mode
9252 ;; Define a minor mode which can be used in other modes in order to
9253 ;; integrate the Org mode structure editing commands.
9255 ;; This is really a hack, because the Org mode structure commands use
9256 ;; keys which normally belong to the major mode. Here is how it
9257 ;; works: The minor mode defines all the keys necessary to operate the
9258 ;; structure commands, but wraps the commands into a function which
9259 ;; tests if the cursor is currently at a headline or a plain list
9260 ;; item. If that is the case, the structure command is used,
9261 ;; temporarily setting many Org mode variables like regular
9262 ;; expressions for filling etc. However, when any of those keys is
9263 ;; used at a different location, function uses `key-binding' to look
9264 ;; up if the key has an associated command in another currently active
9265 ;; keymap (minor modes, major mode, global), and executes that
9266 ;; command. There might be problems if any of the keys is otherwise
9267 ;; used as a prefix key.
9269 (defcustom orgstruct-heading-prefix-regexp ""
9270 "Regexp that matches the custom prefix of Org headlines in
9271 orgstruct(++)-mode."
9272 :group 'org
9273 :version "24.4"
9274 :package-version '(Org . "8.3")
9275 :type 'regexp)
9276 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9278 (defcustom orgstruct-setup-hook nil
9279 "Hook run after orgstruct-mode-map is filled."
9280 :group 'org
9281 :version "24.4"
9282 :package-version '(Org . "8.0")
9283 :type 'hook)
9285 (defvar orgstruct-initialized nil)
9287 (defvar org-local-vars nil
9288 "List of local variables, for use by `orgstruct-mode'.")
9290 ;;;###autoload
9291 (define-minor-mode orgstruct-mode
9292 "Toggle the minor mode `orgstruct-mode'.
9293 This mode is for using Org mode structure commands in other
9294 modes. The following keys behave as if Org mode were active, if
9295 the cursor is on a headline, or on a plain list item (both as
9296 defined by Org-mode)."
9297 nil " OrgStruct" (make-sparse-keymap)
9298 (funcall (if orgstruct-mode
9299 'add-to-invisibility-spec
9300 'remove-from-invisibility-spec)
9301 '(outline . t))
9302 (when orgstruct-mode
9303 (org-load-modules-maybe)
9304 (unless orgstruct-initialized
9305 (orgstruct-setup)
9306 (setq orgstruct-initialized t))))
9308 ;;;###autoload
9309 (defun turn-on-orgstruct ()
9310 "Unconditionally turn on `orgstruct-mode'."
9311 (orgstruct-mode 1))
9313 (defvar-local orgstruct-is-++ nil
9314 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9315 (defvar-local org-fb-vars nil)
9316 (defun orgstruct++-mode (&optional arg)
9317 "Toggle `orgstruct-mode', the enhanced version of it.
9318 In addition to setting orgstruct-mode, this also exports all
9319 indentation and autofilling variables from Org mode into the
9320 buffer. It will also recognize item context in multiline items."
9321 (interactive "P")
9322 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9323 (if (< arg 1)
9324 (progn (orgstruct-mode -1)
9325 (dolist (v org-fb-vars)
9326 (set (make-local-variable (car v))
9327 (if (eq (car-safe (cadr v)) 'quote)
9328 (cl-cadadr v)
9329 (nth 1 v)))))
9330 (orgstruct-mode 1)
9331 (setq org-fb-vars nil)
9332 (unless org-local-vars
9333 (setq org-local-vars (org-get-local-variables)))
9334 (let (var val)
9335 (dolist (x org-local-vars)
9336 (when (string-match
9337 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9338 \\|fill-prefix\\|indent-\\)"
9339 (symbol-name (car x)))
9340 (setq var (car x) val (nth 1 x))
9341 (push (list var `(quote ,(eval var))) org-fb-vars)
9342 (set (make-local-variable var)
9343 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9344 (setq-local orgstruct-is-++ t))))
9346 ;;;###autoload
9347 (defun turn-on-orgstruct++ ()
9348 "Unconditionally turn on `orgstruct++-mode'."
9349 (orgstruct++-mode 1))
9351 (defun orgstruct-error ()
9352 "Error when there is no default binding for a structure key."
9353 (interactive)
9354 (funcall (if (fboundp 'user-error)
9355 'user-error
9356 'error)
9357 "This key has no function outside structure elements"))
9359 (defun orgstruct-setup ()
9360 "Setup orgstruct keymap."
9361 (dolist (cell '((org-demote . t)
9362 (org-metaleft . t)
9363 (org-metaright . t)
9364 (org-promote . t)
9365 (org-shiftmetaleft . t)
9366 (org-shiftmetaright . t)
9367 org-backward-element
9368 org-backward-heading-same-level
9369 org-ctrl-c-ret
9370 org-ctrl-c-minus
9371 org-ctrl-c-star
9372 org-cycle
9373 org-force-cycle-archived
9374 org-forward-heading-same-level
9375 org-insert-heading
9376 org-insert-heading-respect-content
9377 org-kill-note-or-show-branches
9378 org-mark-subtree
9379 org-meta-return
9380 org-metadown
9381 org-metaup
9382 org-narrow-to-subtree
9383 org-promote-subtree
9384 org-reveal
9385 org-shiftdown
9386 org-shiftleft
9387 org-shiftmetadown
9388 org-shiftmetaup
9389 org-shiftright
9390 org-shifttab
9391 org-shifttab
9392 org-shiftup
9393 org-show-children
9394 org-show-subtree
9395 org-sort
9396 org-up-element
9397 outline-demote
9398 outline-next-visible-heading
9399 outline-previous-visible-heading
9400 outline-promote
9401 outline-up-heading))
9402 (let ((f (or (car-safe cell) cell))
9403 (disable-when-heading-prefix (cdr-safe cell)))
9404 (when (fboundp f)
9405 (let ((new-bindings))
9406 (dolist (binding (nconc (where-is-internal f org-mode-map)
9407 (where-is-internal f outline-mode-map)))
9408 (push binding new-bindings)
9409 ;; TODO use local-function-key-map
9410 (dolist (rep '(("<tab>" . "TAB")
9411 ("<return>" . "RET")
9412 ("<escape>" . "ESC")
9413 ("<delete>" . "DEL")))
9414 (setq binding (read-kbd-macro
9415 (let ((case-fold-search))
9416 (replace-regexp-in-string
9417 (regexp-quote (cdr rep))
9418 (car rep)
9419 (key-description binding)))))
9420 (cl-pushnew binding new-bindings :test 'equal)))
9421 (dolist (binding new-bindings)
9422 (let ((key (lookup-key orgstruct-mode-map binding)))
9423 (when (or (not key) (numberp key))
9424 (ignore-errors
9425 (org-defkey orgstruct-mode-map
9426 binding
9427 (orgstruct-make-binding
9428 f binding disable-when-heading-prefix))))))))))
9429 (run-hooks 'orgstruct-setup-hook))
9431 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9432 "Create a function for binding in the structure minor mode.
9433 FUN is the command to call inside a table. KEY is the key that
9434 should be checked in for a command to execute outside of tables.
9435 Non-nil `disable-when-heading-prefix' means to disable the command
9436 if `orgstruct-heading-prefix-regexp' is not empty."
9437 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9438 (let ((nname name)
9439 (i 0))
9440 (while (fboundp (intern nname))
9441 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9442 (setq name (intern nname)))
9443 (eval
9444 (let ((bindings '((org-heading-regexp
9445 (concat "^"
9446 orgstruct-heading-prefix-regexp
9447 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9448 (org-outline-regexp
9449 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9450 (org-outline-regexp-bol
9451 (concat "^" org-outline-regexp))
9452 (outline-regexp org-outline-regexp)
9453 (outline-heading-end-regexp "\n")
9454 (outline-level 'org-outline-level)
9455 (outline-heading-alist))))
9456 `(defun ,name (arg)
9457 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9458 "Outside of structure, run the binding of `"
9459 (key-description key) "'."
9460 (when disable-when-heading-prefix
9461 (concat
9462 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9463 "back to the default binding due to limitations of Org's implementation of\n"
9464 "`" (symbol-name fun) "'.")))
9465 (interactive "p")
9466 (let* ((disable
9467 ,(and disable-when-heading-prefix
9468 '(not (string= orgstruct-heading-prefix-regexp ""))))
9469 (fallback
9470 (or disable
9471 (not
9472 (let* ,bindings
9473 (org-context-p 'headline 'item
9474 ,(when (memq fun
9475 '(org-insert-heading
9476 org-insert-heading-respect-content
9477 org-meta-return))
9478 '(when orgstruct-is-++
9479 'item-body))))))))
9480 (if fallback
9481 (let* ((orgstruct-mode)
9482 (binding
9483 (let ((key ,key))
9484 (catch 'exit
9485 (dolist
9486 (rep
9487 '(nil
9488 ("<\\([^>]*\\)tab>" . "\\1TAB")
9489 ("<\\([^>]*\\)return>" . "\\1RET")
9490 ("<\\([^>]*\\)escape>" . "\\1ESC")
9491 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9492 nil)
9493 (when rep
9494 (setq key (read-kbd-macro
9495 (let ((case-fold-search))
9496 (replace-regexp-in-string
9497 (car rep)
9498 (cdr rep)
9499 (key-description key))))))
9500 (when (key-binding key)
9501 (throw 'exit (key-binding key))))))))
9502 (if (keymapp binding)
9503 (org-set-transient-map binding)
9504 (let ((func (or binding
9505 (unless disable
9506 'orgstruct-error))))
9507 (when func
9508 (call-interactively func)))))
9509 (org-run-like-in-org-mode
9510 (lambda ()
9511 (interactive)
9512 (let* ,bindings
9513 (call-interactively ',fun)))))))))
9514 name))
9516 (defun org-contextualize-keys (alist contexts)
9517 "Return valid elements in ALIST depending on CONTEXTS.
9519 `org-agenda-custom-commands' or `org-capture-templates' are the
9520 values used for ALIST, and `org-agenda-custom-commands-contexts'
9521 or `org-capture-templates-contexts' are the associated contexts
9522 definitions."
9523 (let ((contexts
9524 ;; normalize contexts
9525 (mapcar
9526 (lambda(c) (cond ((listp (cadr c))
9527 (list (car c) (car c) (nth 1 c)))
9528 ((string= "" (cadr c))
9529 (list (car c) (car c) (nth 2 c)))
9530 (t c)))
9531 contexts))
9532 (a alist) r s)
9533 ;; loop over all commands or templates
9534 (dolist (c a)
9535 (let (vrules repl)
9536 (cond
9537 ((not (assoc (car c) contexts))
9538 (push c r))
9539 ((and (assoc (car c) contexts)
9540 (setq vrules (org-contextualize-validate-key
9541 (car c) contexts)))
9542 (mapc (lambda (vr)
9543 (unless (equal (car vr) (cadr vr))
9544 (setq repl vr)))
9545 vrules)
9546 (if (not repl) (push c r)
9547 (push (cadr repl) s)
9548 (push
9549 (cons (car c)
9550 (cdr (or (assoc (cadr repl) alist)
9551 (error "Undefined key `%s' as contextual replacement for `%s'"
9552 (cadr repl) (car c)))))
9553 r))))))
9554 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9555 (delq
9557 (delete-dups
9558 (mapcar (lambda (x)
9559 (let ((tpl (car x)))
9560 (unless (delq
9562 (mapcar (lambda (y)
9563 (equal y tpl))
9565 x)))
9566 (reverse r))))))
9568 (defun org-contextualize-validate-key (key contexts)
9569 "Check CONTEXTS for agenda or capture KEY."
9570 (let (res)
9571 (dolist (r contexts)
9572 (dolist (rr (car (last r)))
9573 (when
9574 (and (equal key (car r))
9575 (if (functionp rr) (funcall rr)
9576 (or (and (eq (car rr) 'in-file)
9577 (buffer-file-name)
9578 (string-match (cdr rr) (buffer-file-name)))
9579 (and (eq (car rr) 'in-mode)
9580 (string-match (cdr rr) (symbol-name major-mode)))
9581 (and (eq (car rr) 'in-buffer)
9582 (string-match (cdr rr) (buffer-name)))
9583 (when (and (eq (car rr) 'not-in-file)
9584 (buffer-file-name))
9585 (not (string-match (cdr rr) (buffer-file-name))))
9586 (when (eq (car rr) 'not-in-mode)
9587 (not (string-match (cdr rr) (symbol-name major-mode))))
9588 (when (eq (car rr) 'not-in-buffer)
9589 (not (string-match (cdr rr) (buffer-name)))))))
9590 (push r res))))
9591 (delete-dups (delq nil res))))
9593 (defun org-context-p (&rest contexts)
9594 "Check if local context is any of CONTEXTS.
9595 Possible values in the list of contexts are `table', `headline', and `item'."
9596 (let ((pos (point)))
9597 (goto-char (point-at-bol))
9598 (prog1 (or (and (memq 'table contexts)
9599 (looking-at "[ \t]*|"))
9600 (and (memq 'headline contexts)
9601 (looking-at org-outline-regexp))
9602 (and (memq 'item contexts)
9603 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9604 (and (memq 'item-body contexts)
9605 (org-in-item-p)))
9606 (goto-char pos))))
9608 (defconst org-unique-local-variables
9609 '(org-element--cache
9610 org-element--cache-objects
9611 org-element--cache-sync-keys
9612 org-element--cache-sync-requests
9613 org-element--cache-sync-timer)
9614 "List of local variables that cannot be transferred to another buffer.")
9616 (defun org-get-local-variables ()
9617 "Return a list of all local variables in an Org mode buffer."
9618 (delq nil
9619 (mapcar
9620 (lambda (x)
9621 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9622 (name (car binding)))
9623 (and (not (get name 'org-state))
9624 (not (memq name org-unique-local-variables))
9625 (string-match-p
9626 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9627 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9628 (symbol-name name))
9629 binding)))
9630 (with-temp-buffer
9631 (org-mode)
9632 (buffer-local-variables)))))
9634 (defun org-clone-local-variables (from-buffer &optional regexp)
9635 "Clone local variables from FROM-BUFFER.
9636 Optional argument REGEXP selects variables to clone."
9637 (dolist (pair (buffer-local-variables from-buffer))
9638 (let ((name (car pair)))
9639 (when (and (symbolp name)
9640 (not (memq name org-unique-local-variables))
9641 (or (null regexp) (string-match regexp (symbol-name name))))
9642 (set (make-local-variable name) (cdr pair))))))
9644 ;;;###autoload
9645 (defun org-run-like-in-org-mode (cmd)
9646 "Run a command, pretending that the current buffer is in Org-mode.
9647 This will temporarily bind local variables that are typically bound in
9648 Org mode to the values they have in Org-mode, and then interactively
9649 call CMD."
9650 (org-load-modules-maybe)
9651 (unless org-local-vars
9652 (setq org-local-vars (org-get-local-variables)))
9653 (let (binds)
9654 (dolist (var org-local-vars)
9655 (when (or (not (boundp (car var)))
9656 (eq (symbol-value (car var))
9657 (default-value (car var))))
9658 (push (list (car var) `(quote ,(cadr var))) binds)))
9659 (eval `(let ,binds
9660 (call-interactively (quote ,cmd))))))
9662 (defun org-get-category (&optional pos force-refresh)
9663 "Get the category applying to position POS."
9664 (save-match-data
9665 (when force-refresh (org-refresh-category-properties))
9666 (let ((pos (or pos (point))))
9667 (or (get-text-property pos 'org-category)
9668 (progn (org-refresh-category-properties)
9669 (get-text-property pos 'org-category))))))
9671 ;;; Refresh properties
9673 (defun org-refresh-properties (dprop tprop)
9674 "Refresh buffer text properties.
9675 DPROP is the drawer property and TPROP is either the
9676 corresponding text property to set, or an alist with each element
9677 being a text property (as a symbol) and a function to apply to
9678 the value of the drawer property."
9679 (let ((case-fold-search t)
9680 (inhibit-read-only t))
9681 (org-with-silent-modifications
9682 (org-with-wide-buffer
9683 (goto-char (point-min))
9684 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9685 (org-refresh-property tprop (match-string-no-properties 1)))))))
9687 (defun org-refresh-property (tprop p)
9688 "Refresh the buffer text property TPROP from the drawer property P.
9689 The refresh happens only for the current tree (not subtree)."
9690 (unless (org-before-first-heading-p)
9691 (save-excursion
9692 (org-back-to-heading t)
9693 (if (symbolp tprop)
9694 ;; TPROP is a text property symbol
9695 (put-text-property
9696 (point) (or (outline-next-heading) (point-max)) tprop p)
9697 ;; TPROP is an alist with (properties . function) elements
9698 (dolist (al tprop)
9699 (save-excursion
9700 (put-text-property
9701 (line-beginning-position) (or (outline-next-heading) (point-max))
9702 (car al)
9703 (funcall (cdr al) p))))))))
9705 (defun org-refresh-category-properties ()
9706 "Refresh category text properties in the buffer."
9707 (let ((case-fold-search t)
9708 (inhibit-read-only t)
9709 (default-category
9710 (cond ((null org-category)
9711 (if buffer-file-name
9712 (file-name-sans-extension
9713 (file-name-nondirectory buffer-file-name))
9714 "???"))
9715 ((symbolp org-category) (symbol-name org-category))
9716 (t org-category))))
9717 (org-with-silent-modifications
9718 (org-with-wide-buffer
9719 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9720 ;; This is the default category for the buffer. If none is
9721 ;; found, fall-back to `org-category' or buffer file name.
9722 (put-text-property
9723 (point-min) (point-max)
9724 'org-category
9725 (catch 'buffer-category
9726 (goto-char (point-max))
9727 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9728 (let ((element (org-element-at-point)))
9729 (when (eq (org-element-type element) 'keyword)
9730 (throw 'buffer-category
9731 (org-element-property :value element)))))
9732 default-category))
9733 ;; Set sub-tree specific categories.
9734 (goto-char (point-min))
9735 (let ((regexp (org-re-property "CATEGORY")))
9736 (while (re-search-forward regexp nil t)
9737 (let ((value (match-string-no-properties 3)))
9738 (when (org-at-property-p)
9739 (put-text-property
9740 (save-excursion (org-back-to-heading t) (point))
9741 (save-excursion (org-end-of-subtree t t) (point))
9742 'org-category
9743 value)))))))))
9745 (defun org-refresh-stats-properties ()
9746 "Refresh stats text properties in the buffer."
9747 (let (stats)
9748 (org-with-silent-modifications
9749 (org-with-wide-buffer
9750 (goto-char (point-min))
9751 (while (re-search-forward
9752 (concat org-outline-regexp-bol ".*"
9753 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9754 nil t)
9755 (setq stats (cond ((equal (match-string 3) "0") 0)
9756 ((match-string 2)
9757 (/ (* (string-to-number (match-string 2)) 100)
9758 (string-to-number (match-string 3))))
9759 (t (string-to-number (match-string 1)))))
9760 (org-back-to-heading t)
9761 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9762 'org-stats stats))))))
9764 (defun org-refresh-effort-properties ()
9765 "Refresh effort properties"
9766 (org-refresh-properties
9767 org-effort-property
9768 '((effort . identity)
9769 (effort-minutes . org-duration-string-to-minutes))))
9771 ;;;; Link Stuff
9773 ;;; Link abbreviations
9775 (defun org-link-expand-abbrev (link)
9776 "Apply replacements as defined in `org-link-abbrev-alist'."
9777 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9778 (let* ((key (match-string 1 link))
9779 (as (or (assoc key org-link-abbrev-alist-local)
9780 (assoc key org-link-abbrev-alist)))
9781 (tag (and (match-end 2) (match-string 3 link)))
9782 rpl)
9783 (if (not as)
9784 link
9785 (setq rpl (cdr as))
9786 (cond
9787 ((symbolp rpl) (funcall rpl tag))
9788 ((string-match "%(\\([^)]+\\))" rpl)
9789 (replace-match
9790 (save-match-data
9791 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9792 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9793 ((string-match "%h" rpl)
9794 (replace-match (url-hexify-string (or tag "")) t t rpl))
9795 (t (concat rpl tag)))))
9796 link))
9798 ;;; Storing and inserting links
9800 (defvar org-insert-link-history nil
9801 "Minibuffer history for links inserted with `org-insert-link'.")
9803 (defvar org-stored-links nil
9804 "Contains the links stored with `org-store-link'.")
9806 (defvar org-store-link-plist nil
9807 "Plist with info about the most recently link created with `org-store-link'.")
9809 (defun org-store-link-functions ()
9810 "Return a list of functions that are called to create and store a link.
9811 The functions defined in the :store property of
9812 `org-link-parameters'.
9814 Each function will be called in turn until one returns a non-nil
9815 value. Each function should check if it is responsible for
9816 creating this link (for example by looking at the major mode).
9817 If not, it must exit and return nil. If yes, it should return
9818 a non-nil value after calling `org-store-link-props' with a list
9819 of properties and values. Special properties are:
9821 :type The link prefix, like \"http\". This must be given.
9822 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9823 This is obligatory as well.
9824 :description Optional default description for the second pair
9825 of brackets in an Org mode link. The user can still change
9826 this when inserting this link into an Org mode buffer.
9828 In addition to these, any additional properties can be specified
9829 and then used in capture templates."
9830 (cl-loop for link in org-link-parameters
9831 with store-func
9832 do (setq store-func (org-link-get-parameter (car link) :store))
9833 if store-func
9834 collect store-func))
9836 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9837 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9839 ;;;###autoload
9840 (defun org-store-link (arg)
9841 "\\<org-mode-map>Store an org-link to the current location.
9842 This link is added to `org-stored-links' and can later be inserted
9843 into an Org buffer with \\[org-insert-link].
9845 For some link types, a prefix ARG is interpreted.
9846 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9847 For file links, ARG negates `org-context-in-file-links'.
9849 A double prefix ARG force skipping storing functions that are not
9850 part of Org's core.
9852 A triple prefix ARG force storing a link for each line in the
9853 active region."
9854 (interactive "P")
9855 (org-load-modules-maybe)
9856 (if (and (equal arg '(64)) (org-region-active-p))
9857 (save-excursion
9858 (let ((end (region-end)))
9859 (goto-char (region-beginning))
9860 (set-mark (point))
9861 (while (< (point-at-eol) end)
9862 (move-end-of-line 1) (activate-mark)
9863 (let (current-prefix-arg)
9864 (call-interactively 'org-store-link))
9865 (move-beginning-of-line 2)
9866 (set-mark (point)))))
9867 (setq org-store-link-plist nil)
9868 (let (link cpltxt desc description search
9869 txt custom-id agenda-link sfuns sfunsn)
9870 (cond
9872 ;; Store a link using an external link type
9873 ((and (not (equal arg '(16)))
9874 (setq sfuns
9875 (delq
9876 nil (mapcar (lambda (f)
9877 (let (fs) (if (funcall f) (push f fs))))
9878 (org-store-link-functions)))
9879 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9880 (or (and (cdr sfuns)
9881 (funcall (intern
9882 (completing-read
9883 "Which function for creating the link? "
9884 sfunsn nil t (car sfunsn)))))
9885 (funcall (caar sfuns)))
9886 (setq link (plist-get org-store-link-plist :link)
9887 desc (or (plist-get org-store-link-plist
9888 :description)
9889 link))))
9891 ;; Store a link from a source code buffer.
9892 ((org-src-edit-buffer-p)
9893 (let ((coderef-format (org-src-coderef-format)))
9894 (cond ((save-excursion
9895 (beginning-of-line)
9896 (looking-at (org-src-coderef-regexp coderef-format)))
9897 (setq link (format "(%s)" (match-string-no-properties 3))))
9898 ((called-interactively-p 'any)
9899 (let ((label (read-string "Code line label: ")))
9900 (end-of-line)
9901 (setq link (format coderef-format label))
9902 (let ((gc (- 79 (length link))))
9903 (if (< (current-column) gc)
9904 (org-move-to-column gc t)
9905 (insert " ")))
9906 (insert link)
9907 (setq link (concat "(" label ")"))
9908 (setq desc nil)))
9909 (t (setq link nil)))))
9911 ;; We are in the agenda, link to referenced location
9912 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9913 (let ((m (or (get-text-property (point) 'org-hd-marker)
9914 (get-text-property (point) 'org-marker))))
9915 (when m
9916 (org-with-point-at m
9917 (setq agenda-link
9918 (if (called-interactively-p 'any)
9919 (call-interactively 'org-store-link)
9920 (org-store-link nil)))))))
9922 ((eq major-mode 'calendar-mode)
9923 (let ((cd (calendar-cursor-to-date)))
9924 (setq link
9925 (format-time-string
9926 (car org-time-stamp-formats)
9927 (apply 'encode-time
9928 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9929 nil nil nil))))
9930 (org-store-link-props :type "calendar" :date cd)))
9932 ((eq major-mode 'help-mode)
9933 (setq link (concat "help:" (save-excursion
9934 (goto-char (point-min))
9935 (looking-at "^[^ ]+")
9936 (match-string 0))))
9937 (org-store-link-props :type "help"))
9939 ((eq major-mode 'w3-mode)
9940 (setq cpltxt (if (and (buffer-name)
9941 (not (string-match "Untitled" (buffer-name))))
9942 (buffer-name)
9943 (url-view-url t))
9944 link (url-view-url t))
9945 (org-store-link-props :type "w3" :url (url-view-url t)))
9947 ((eq major-mode 'image-mode)
9948 (setq cpltxt (concat "file:"
9949 (abbreviate-file-name buffer-file-name))
9950 link cpltxt)
9951 (org-store-link-props :type "image" :file buffer-file-name))
9953 ;; In dired, store a link to the file of the current line
9954 ((derived-mode-p 'dired-mode)
9955 (let ((file (dired-get-filename nil t)))
9956 (setq file (if file
9957 (abbreviate-file-name
9958 (expand-file-name (dired-get-filename nil t)))
9959 ;; otherwise, no file so use current directory.
9960 default-directory))
9961 (setq cpltxt (concat "file:" file)
9962 link cpltxt)))
9964 ((setq search (run-hook-with-args-until-success
9965 'org-create-file-search-functions))
9966 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9967 "::" search))
9968 (setq cpltxt (or description link)))
9970 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9971 (org-with-limited-levels
9972 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9973 (cond
9974 ;; Store a link using the target at point
9975 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9976 (setq cpltxt
9977 (concat "file:"
9978 (abbreviate-file-name
9979 (buffer-file-name (buffer-base-buffer)))
9980 "::" (match-string 1))
9981 link cpltxt))
9982 ((and (featurep 'org-id)
9983 (or (eq org-id-link-to-org-use-id t)
9984 (and (called-interactively-p 'any)
9985 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9986 (and (eq org-id-link-to-org-use-id
9987 'create-if-interactive-and-no-custom-id)
9988 (not custom-id))))
9989 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9990 ;; Store a link using the ID at point
9991 (setq link (condition-case nil
9992 (prog1 (org-id-store-link)
9993 (setq desc (or (plist-get org-store-link-plist
9994 :description)
9995 "")))
9996 (error
9997 ;; Probably before first headline, link only to file
9998 (concat "file:"
9999 (abbreviate-file-name
10000 (buffer-file-name (buffer-base-buffer))))))))
10002 ;; Just link to current headline
10003 (setq cpltxt (concat "file:"
10004 (abbreviate-file-name
10005 (buffer-file-name (buffer-base-buffer)))))
10006 ;; Add a context search string
10007 (when (org-xor org-context-in-file-links arg)
10008 (let* ((element (org-element-at-point))
10009 (name (org-element-property :name element)))
10010 (setq txt (cond
10011 ((org-at-heading-p) nil)
10012 (name)
10013 ((org-region-active-p)
10014 (buffer-substring (region-beginning) (region-end)))))
10015 (when (or (null txt) (string-match "\\S-" txt))
10016 (setq cpltxt
10017 (concat cpltxt "::"
10018 (condition-case nil
10019 (org-make-org-heading-search-string txt)
10020 (error "")))
10021 desc (or name
10022 (nth 4 (ignore-errors (org-heading-components)))
10023 "NONE")))))
10024 (when (string-match "::\\'" cpltxt)
10025 (setq cpltxt (substring cpltxt 0 -2)))
10026 (setq link cpltxt)))))
10028 ((buffer-file-name (buffer-base-buffer))
10029 ;; Just link to this file here.
10030 (setq cpltxt (concat "file:"
10031 (abbreviate-file-name
10032 (buffer-file-name (buffer-base-buffer)))))
10033 ;; Add a context string.
10034 (when (org-xor org-context-in-file-links arg)
10035 (setq txt (if (org-region-active-p)
10036 (buffer-substring (region-beginning) (region-end))
10037 (buffer-substring (point-at-bol) (point-at-eol))))
10038 ;; Only use search option if there is some text.
10039 (when (string-match "\\S-" txt)
10040 (setq cpltxt
10041 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10042 desc "NONE")))
10043 (setq link cpltxt))
10045 ((called-interactively-p 'interactive)
10046 (user-error "No method for storing a link from this buffer"))
10048 (t (setq link nil)))
10050 ;; We're done setting link and desc, clean up
10051 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10052 (setq link (or link cpltxt)
10053 desc (or desc cpltxt))
10054 (cond ((not desc))
10055 ((equal desc "NONE") (setq desc nil))
10056 (t (setq desc
10057 (replace-regexp-in-string
10058 org-bracket-link-analytic-regexp
10059 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10060 desc))))
10061 ;; Return the link
10062 (if (not (and (or (called-interactively-p 'any)
10063 executing-kbd-macro)
10064 link))
10065 (or agenda-link (and link (org-make-link-string link desc)))
10066 (push (list link desc) org-stored-links)
10067 (message "Stored: %s" (or desc link))
10068 (when custom-id
10069 (setq link (concat "file:" (abbreviate-file-name
10070 (buffer-file-name)) "::#" custom-id))
10071 (push (list link desc) org-stored-links))
10072 (car org-stored-links)))))
10074 (defun org-store-link-props (&rest plist)
10075 "Store link properties, extract names, addresses and dates."
10076 (let ((x (plist-get plist :from)))
10077 (when x
10078 (let ((adr (mail-extract-address-components x)))
10079 (setq plist (plist-put plist :fromname (car adr)))
10080 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10081 (let ((x (plist-get plist :to)))
10082 (when x
10083 (let ((adr (mail-extract-address-components x)))
10084 (setq plist (plist-put plist :toname (car adr)))
10085 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10086 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10087 (when x
10088 (setq plist (plist-put plist :date-timestamp
10089 (format-time-string
10090 (org-time-stamp-format t) x)))
10091 (setq plist (plist-put plist :date-timestamp-inactive
10092 (format-time-string
10093 (org-time-stamp-format t t) x)))))
10094 (let ((from (plist-get plist :from))
10095 (to (plist-get plist :to)))
10096 (when (and from to org-from-is-user-regexp)
10097 (setq plist
10098 (plist-put plist :fromto
10099 (if (string-match org-from-is-user-regexp from)
10100 (concat "to %t")
10101 (concat "from %f"))))))
10102 (setq org-store-link-plist plist))
10104 (defun org-add-link-props (&rest plist)
10105 "Add these properties to the link property list."
10106 (let (key value)
10107 (while plist
10108 (setq key (pop plist) value (pop plist))
10109 (setq org-store-link-plist
10110 (plist-put org-store-link-plist key value)))))
10112 (defun org-email-link-description (&optional fmt)
10113 "Return the description part of an email link.
10114 This takes information from `org-store-link-plist' and formats it
10115 according to FMT (default from `org-email-link-description-format')."
10116 (setq fmt (or fmt org-email-link-description-format))
10117 (let* ((p org-store-link-plist)
10118 (to (plist-get p :toaddress))
10119 (from (plist-get p :fromaddress))
10120 (table
10121 (list
10122 (cons "%c" (plist-get p :fromto))
10123 (cons "%F" (plist-get p :from))
10124 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10125 (cons "%T" (plist-get p :to))
10126 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10127 (cons "%s" (plist-get p :subject))
10128 (cons "%d" (plist-get p :date))
10129 (cons "%m" (plist-get p :message-id)))))
10130 (when (string-match "%c" fmt)
10131 ;; Check if the user wrote this message
10132 (if (and org-from-is-user-regexp from to
10133 (save-match-data (string-match org-from-is-user-regexp from)))
10134 (setq fmt (replace-match "to %t" t t fmt))
10135 (setq fmt (replace-match "from %f" t t fmt))))
10136 (org-replace-escapes fmt table)))
10138 (defun org-make-org-heading-search-string (&optional string)
10139 "Make search string for the current headline or STRING."
10140 (let ((s (or string
10141 (and (derived-mode-p 'org-mode)
10142 (save-excursion
10143 (org-back-to-heading t)
10144 (org-element-property :raw-value (org-element-at-point))))))
10145 (lines org-context-in-file-links))
10146 (or string (setq s (concat "*" s))) ; Add * for headlines
10147 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10148 (when (and string (integerp lines) (> lines 0))
10149 (let ((slines (org-split-string s "\n")))
10150 (when (< lines (length slines))
10151 (setq s (mapconcat
10152 'identity
10153 (reverse (nthcdr (- (length slines) lines)
10154 (reverse slines))) "\n")))))
10155 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10157 (defun org-make-link-string (link &optional description)
10158 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10159 (unless (org-string-nw-p link) (error "Empty link"))
10160 (let ((uri (cond ((string-match org-link-types-re link)
10161 (concat (match-string 1 link)
10162 (org-link-escape (substring link (match-end 1)))))
10163 ;; For readability, url-encode internal links only
10164 ;; when absolutely needed (i.e, when they contain
10165 ;; square brackets). File links however, are
10166 ;; encoded since, e.g., spaces are significant.
10167 ((or (file-name-absolute-p link)
10168 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10169 (org-link-escape link))
10170 (t link)))
10171 (description
10172 (and (org-string-nw-p description)
10173 ;; Remove brackets from description, as they are fatal.
10174 (replace-regexp-in-string
10175 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10176 (org-trim description)))))
10177 (format "[[%s]%s]"
10179 (if description (format "[%s]" description) ""))))
10181 (defconst org-link-escape-chars
10182 ;;%20 %5B %5D %25
10183 '(?\s ?\[ ?\] ?%)
10184 "List of characters that should be escaped in a link when stored to Org.
10185 This is the list that is used for internal purposes.")
10187 (defun org-link-escape (text &optional table merge)
10188 "Return percent escaped representation of TEXT.
10189 TEXT is a string with the text to escape.
10190 Optional argument TABLE is a list with characters that should be
10191 escaped. When nil, `org-link-escape-chars' is used.
10192 If optional argument MERGE is set, merge TABLE into
10193 `org-link-escape-chars'."
10194 (let ((characters-to-encode
10195 (cond ((null table) org-link-escape-chars)
10196 (merge (append org-link-escape-chars table))
10197 (t table))))
10198 (mapconcat
10199 (lambda (c)
10200 (if (or (memq c characters-to-encode)
10201 (and org-url-hexify-p (or (< c 32) (> c 126))))
10202 (mapconcat (lambda (e) (format "%%%.2X" e))
10203 (or (encode-coding-char c 'utf-8)
10204 (error "Unable to percent escape character: %c" c))
10206 (char-to-string c)))
10207 text "")))
10209 (defun org-link-unescape (str)
10210 "Unhex hexified Unicode parts in string STR.
10211 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10212 reciprocal of `org-link-escape', which see."
10213 (if (org-string-nw-p str)
10214 (replace-regexp-in-string
10215 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10216 str))
10218 (defun org-link-unescape-compound (hex)
10219 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10220 Note: this function also decodes single byte encodings like
10221 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10222 (save-match-data
10223 (let* ((bytes (cdr (split-string hex "%")))
10224 (ret "")
10225 (eat 0)
10226 (sum 0))
10227 (while bytes
10228 (let* ((val (string-to-number (pop bytes) 16))
10229 (shift-xor
10230 (if (= 0 eat)
10231 (cond
10232 ((>= val 252) (cons 6 252))
10233 ((>= val 248) (cons 5 248))
10234 ((>= val 240) (cons 4 240))
10235 ((>= val 224) (cons 3 224))
10236 ((>= val 192) (cons 2 192))
10237 (t (cons 0 0)))
10238 (cons 6 128))))
10239 (when (>= val 192) (setq eat (car shift-xor)))
10240 (setq val (logxor val (cdr shift-xor)))
10241 (setq sum (+ (lsh sum (car shift-xor)) val))
10242 (when (> eat 0) (setq eat (- eat 1)))
10243 (cond
10244 ((= 0 eat) ;multi byte
10245 (setq ret (concat ret (char-to-string sum)))
10246 (setq sum 0))
10247 ((not bytes) ; single byte(s)
10248 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10249 ret)))
10251 (defun org-link-unescape-single-byte-sequence (hex)
10252 "Unhexify hex-encoded single byte character sequences."
10253 (mapconcat (lambda (byte)
10254 (char-to-string (string-to-number byte 16)))
10255 (cdr (split-string hex "%")) ""))
10257 (defun org-xor (a b)
10258 "Exclusive or."
10259 (if a (not b) b))
10261 (defun org-fixup-message-id-for-http (s)
10262 "Replace special characters in a message id, so it can be used in an http query."
10263 (when (string-match "%" s)
10264 (setq s (mapconcat (lambda (c)
10265 (if (eq c ?%)
10266 "%25"
10267 (char-to-string c)))
10268 s "")))
10269 (while (string-match "<" s)
10270 (setq s (replace-match "%3C" t t s)))
10271 (while (string-match ">" s)
10272 (setq s (replace-match "%3E" t t s)))
10273 (while (string-match "@" s)
10274 (setq s (replace-match "%40" t t s)))
10277 (defun org-link-prettify (link)
10278 "Return a human-readable representation of LINK.
10279 The car of LINK must be a raw link.
10280 The cdr of LINK must be either a link description or nil."
10281 (let ((desc (or (cadr link) "<no description>")))
10282 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10283 "<" (car link) ">")))
10285 ;;;###autoload
10286 (defun org-insert-link-global ()
10287 "Insert a link like Org mode does.
10288 This command can be called in any mode to insert a link in Org syntax."
10289 (interactive)
10290 (org-load-modules-maybe)
10291 (org-run-like-in-org-mode 'org-insert-link))
10293 (defun org-insert-all-links (arg &optional pre post)
10294 "Insert all links in `org-stored-links'.
10295 When a universal prefix, do not delete the links from `org-stored-links'.
10296 When `ARG' is a number, insert the last N link(s).
10297 `PRE' and `POST' are optional arguments to define a string to
10298 prepend or to append."
10299 (interactive "P")
10300 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10301 (links (copy-sequence org-stored-links))
10302 (pr (or pre "- "))
10303 (po (or post "\n"))
10304 (cnt 1) l)
10305 (if (null org-stored-links)
10306 (message "No link to insert")
10307 (while (and (or (listp arg) (>= arg cnt))
10308 (setq l (if (listp arg)
10309 (pop links)
10310 (pop org-stored-links))))
10311 (setq cnt (1+ cnt))
10312 (insert pr)
10313 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10314 (insert po)))))
10316 (defun org-insert-last-stored-link (arg)
10317 "Insert the last link stored in `org-stored-links'."
10318 (interactive "p")
10319 (org-insert-all-links arg "" "\n"))
10321 (defun org-link-fontify-links-to-this-file ()
10322 "Fontify links to the current file in `org-stored-links'."
10323 (let ((f (buffer-file-name)) a b)
10324 (setq a (mapcar (lambda(l)
10325 (let ((ll (car l)))
10326 (when (and (string-match "^file:\\(.+\\)::" ll)
10327 (equal f (expand-file-name (match-string 1 ll))))
10328 ll)))
10329 org-stored-links))
10330 (when (featurep 'org-id)
10331 (setq b (mapcar (lambda(l)
10332 (let ((ll (car l)))
10333 (when (and (string-match "^id:\\(.+\\)$" ll)
10334 (equal f (expand-file-name
10335 (or (org-id-find-id-file
10336 (match-string 1 ll)) ""))))
10337 ll)))
10338 org-stored-links)))
10339 (mapcar (lambda(l)
10340 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10341 (delq nil (append a b)))))
10343 (defvar org--links-history nil)
10344 (defun org-insert-link (&optional complete-file link-location default-description)
10345 "Insert a link. At the prompt, enter the link.
10347 Completion can be used to insert any of the link protocol prefixes like
10348 http or ftp in use.
10350 The history can be used to select a link previously stored with
10351 `org-store-link'. When the empty string is entered (i.e. if you just
10352 press RET at the prompt), the link defaults to the most recently
10353 stored link. As SPC triggers completion in the minibuffer, you need to
10354 use M-SPC or C-q SPC to force the insertion of a space character.
10356 You will also be prompted for a description, and if one is given, it will
10357 be displayed in the buffer instead of the link.
10359 If there is already a link at point, this command will allow you to edit link
10360 and description parts.
10362 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10363 be selected using completion. The path to the file will be relative to the
10364 current directory if the file is in the current directory or a subdirectory.
10365 Otherwise, the link will be the absolute path as completed in the minibuffer
10366 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10367 option `org-link-file-path-type'.
10369 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10370 the current directory or below.
10372 With three \\[universal-argument] prefixes, negate the meaning of
10373 `org-keep-stored-link-after-insertion'.
10375 If `org-make-link-description-function' is non-nil, this function will be
10376 called with the link target, and the result will be the default
10377 link description.
10379 If the LINK-LOCATION parameter is non-nil, this value will be
10380 used as the link location instead of reading one interactively.
10382 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10383 be used as the default description."
10384 (interactive "P")
10385 (let* ((wcf (current-window-configuration))
10386 (origbuf (current-buffer))
10387 (region (when (org-region-active-p)
10388 (buffer-substring (region-beginning) (region-end))))
10389 (remove (and region (list (region-beginning) (region-end))))
10390 (desc region)
10391 (link link-location)
10392 (abbrevs org-link-abbrev-alist-local)
10393 entry all-prefixes auto-desc)
10394 (cond
10395 (link-location) ; specified by arg, just use it.
10396 ((org-in-regexp org-bracket-link-regexp 1)
10397 ;; We do have a link at point, and we are going to edit it.
10398 (setq remove (list (match-beginning 0) (match-end 0)))
10399 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10400 (setq link (read-string "Link: "
10401 (org-link-unescape
10402 (match-string-no-properties 1)))))
10403 ((or (org-in-regexp org-angle-link-re)
10404 (org-in-regexp org-plain-link-re))
10405 ;; Convert to bracket link
10406 (setq remove (list (match-beginning 0) (match-end 0))
10407 link (read-string "Link: "
10408 (org-unbracket-string "<" ">" (match-string 0)))))
10409 ((member complete-file '((4) (16)))
10410 ;; Completing read for file names.
10411 (setq link (org-file-complete-link complete-file)))
10413 ;; Read link, with completion for stored links.
10414 (org-link-fontify-links-to-this-file)
10415 (org-switch-to-buffer-other-window "*Org Links*")
10416 (with-current-buffer "*Org Links*"
10417 (erase-buffer)
10418 (insert "Insert a link.
10419 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10420 (when org-stored-links
10421 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10422 (insert (mapconcat 'org-link-prettify
10423 (reverse org-stored-links) "\n")))
10424 (goto-char (point-min)))
10425 (let ((cw (selected-window)))
10426 (select-window (get-buffer-window "*Org Links*" 'visible))
10427 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10428 (unless (pos-visible-in-window-p (point-max))
10429 (org-fit-window-to-buffer))
10430 (and (window-live-p cw) (select-window cw)))
10431 (setq all-prefixes (append (mapcar 'car abbrevs)
10432 (mapcar 'car org-link-abbrev-alist)
10433 (org-link-types)))
10434 (unwind-protect
10435 ;; Fake a link history, containing the stored links.
10436 (let ((org--links-history
10437 (append (mapcar #'car org-stored-links)
10438 org-insert-link-history)))
10439 (setq link
10440 (org-completing-read
10441 "Link: "
10442 (append
10443 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10444 (mapcar #'car org-stored-links))
10445 nil nil nil
10446 'org--links-history
10447 (caar org-stored-links)))
10448 (unless (org-string-nw-p link) (user-error "No link selected"))
10449 (dolist (l org-stored-links)
10450 (when (equal link (cadr l))
10451 (setq link (car l))
10452 (setq auto-desc t)))
10453 (when (or (member link all-prefixes)
10454 (and (equal ":" (substring link -1))
10455 (member (substring link 0 -1) all-prefixes)
10456 (setq link (substring link 0 -1))))
10457 (setq link (with-current-buffer origbuf
10458 (org-link-try-special-completion link)))))
10459 (set-window-configuration wcf)
10460 (kill-buffer "*Org Links*"))
10461 (setq entry (assoc link org-stored-links))
10462 (or entry (push link org-insert-link-history))
10463 (setq desc (or desc (nth 1 entry)))))
10465 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10466 (not org-keep-stored-link-after-insertion))
10467 (setq org-stored-links (delq (assoc link org-stored-links)
10468 org-stored-links)))
10470 (when (and (string-match org-plain-link-re link)
10471 (not (string-match org-ts-regexp link)))
10472 ;; URL-like link, normalize the use of angular brackets.
10473 (setq link (org-unbracket-string "<" ">" link)))
10475 ;; Check if we are linking to the current file with a search
10476 ;; option If yes, simplify the link by using only the search
10477 ;; option.
10478 (when (and buffer-file-name
10479 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10480 (let* ((path (match-string 1 link))
10481 (case-fold-search nil)
10482 (search (match-string 2 link)))
10483 (save-match-data
10484 (when (equal (file-truename buffer-file-name) (file-truename path))
10485 ;; We are linking to this same file, with a search option
10486 (setq link search)))))
10488 ;; Check if we can/should use a relative path. If yes, simplify the link
10489 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10490 (let* ((type (match-string 1 link))
10491 (path (match-string 2 link))
10492 (origpath path)
10493 (case-fold-search nil))
10494 (cond
10495 ((or (eq org-link-file-path-type 'absolute)
10496 (equal complete-file '(16)))
10497 (setq path (abbreviate-file-name (expand-file-name path))))
10498 ((eq org-link-file-path-type 'noabbrev)
10499 (setq path (expand-file-name path)))
10500 ((eq org-link-file-path-type 'relative)
10501 (setq path (file-relative-name path)))
10503 (save-match-data
10504 (if (string-match (concat "^" (regexp-quote
10505 (expand-file-name
10506 (file-name-as-directory
10507 default-directory))))
10508 (expand-file-name path))
10509 ;; We are linking a file with relative path name.
10510 (setq path (substring (expand-file-name path)
10511 (match-end 0)))
10512 (setq path (abbreviate-file-name (expand-file-name path)))))))
10513 (setq link (concat type path))
10514 (when (equal desc origpath)
10515 (setq desc path))))
10517 (if org-make-link-description-function
10518 (setq desc
10519 (or (condition-case nil
10520 (funcall org-make-link-description-function link desc)
10521 (error (progn (message "Can't get link description from `%s'"
10522 (symbol-name org-make-link-description-function))
10523 (sit-for 2) nil)))
10524 (read-string "Description: " default-description)))
10525 (if default-description (setq desc default-description)
10526 (setq desc (or (and auto-desc desc)
10527 (read-string "Description: " desc)))))
10529 (unless (string-match "\\S-" desc) (setq desc nil))
10530 (when remove (apply 'delete-region remove))
10531 (insert (org-make-link-string link desc))
10532 ;; Redisplay so as the new link has proper invisible characters.
10533 (sit-for 0)))
10535 (defun org-link-try-special-completion (type)
10536 "If there is completion support for link type TYPE, offer it."
10537 (let ((fun (org-link-get-parameter type :complete)))
10538 (if (functionp fun)
10539 (funcall fun)
10540 (read-string "Link (no completion support): " (concat type ":")))))
10542 (defun org-file-complete-link (&optional arg)
10543 "Create a file link using completion."
10544 (let ((file (read-file-name "File: "))
10545 (pwd (file-name-as-directory (expand-file-name ".")))
10546 (pwd1 (file-name-as-directory (abbreviate-file-name
10547 (expand-file-name ".")))))
10548 (cond ((equal arg '(16))
10549 (concat "file:"
10550 (abbreviate-file-name (expand-file-name file))))
10551 ((string-match
10552 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10553 (concat "file:" (match-string 1 file)))
10554 ((string-match
10555 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10556 (expand-file-name file))
10557 (concat "file:"
10558 (match-string 1 (expand-file-name file))))
10559 (t (concat "file:" file)))))
10561 (defun org-completing-read (&rest args)
10562 "Completing-read with SPACE being a normal character."
10563 (let ((enable-recursive-minibuffers t)
10564 (minibuffer-local-completion-map
10565 (copy-keymap minibuffer-local-completion-map)))
10566 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10567 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10568 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10569 'org-time-stamp-inactive)
10570 (apply #'completing-read args)))
10572 ;;; Opening/following a link
10574 (defvar org-link-search-failed nil)
10576 (defvar org-open-link-functions nil
10577 "Hook for functions finding a plain text link.
10578 These functions must take a single argument, the link content.
10579 They will be called for links that look like [[link text][description]]
10580 when LINK TEXT does not have a protocol like \"http:\" and does not look
10581 like a filename (e.g. \"./blue.png\").
10583 These functions will be called *before* Org attempts to resolve the
10584 link by doing text searches in the current buffer - so if you want a
10585 link \"[[target]]\" to still find \"<<target>>\", your function should
10586 handle this as a special case.
10588 When the function does handle the link, it must return a non-nil value.
10589 If it decides that it is not responsible for this link, it must return
10590 nil to indicate that that Org can continue with other options like
10591 exact and fuzzy text search.")
10593 (defun org-next-link (&optional search-backward)
10594 "Move forward to the next link.
10595 If the link is in hidden text, expose it."
10596 (interactive "P")
10597 (when (and org-link-search-failed (eq this-command last-command))
10598 (goto-char (point-min))
10599 (message "Link search wrapped back to beginning of buffer"))
10600 (setq org-link-search-failed nil)
10601 (let* ((pos (point))
10602 (ct (org-context))
10603 (a (assq :link ct))
10604 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10605 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10606 ((looking-at org-any-link-re)
10607 ;; Don't stay stuck at link without an org-link face
10608 (forward-char (if search-backward -1 1))))
10609 (if (funcall srch-fun org-any-link-re nil t)
10610 (progn
10611 (goto-char (match-beginning 0))
10612 (when (outline-invisible-p) (org-show-context)))
10613 (goto-char pos)
10614 (setq org-link-search-failed t)
10615 (message "No further link found"))))
10617 (defun org-previous-link ()
10618 "Move backward to the previous link.
10619 If the link is in hidden text, expose it."
10620 (interactive)
10621 (funcall 'org-next-link t))
10623 (defun org-translate-link (s)
10624 "Translate a link string if a translation function has been defined."
10625 (with-temp-buffer
10626 (insert (org-trim s))
10627 (org-trim (org-element-interpret-data (org-element-context)))))
10629 (defun org-translate-link-from-planner (type path)
10630 "Translate a link from Emacs Planner syntax so that Org can follow it.
10631 This is still an experimental function, your mileage may vary."
10632 (cond
10633 ((member type '("http" "https" "news" "ftp"))
10634 ;; standard Internet links are the same.
10635 nil)
10636 ((and (equal type "irc") (string-match "^//" path))
10637 ;; Planner has two / at the beginning of an irc link, we have 1.
10638 ;; We should have zero, actually....
10639 (setq path (substring path 1)))
10640 ((and (equal type "lisp") (string-match "^/" path))
10641 ;; Planner has a slash, we do not.
10642 (setq type "elisp" path (substring path 1)))
10643 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10644 ;; A typical message link. Planner has the id after the final slash,
10645 ;; we separate it with a hash mark
10646 (setq path (concat (match-string 1 path) "#"
10647 (org-unbracket-string "<" ">" (match-string 2 path))))))
10648 (cons type path))
10650 (defun org-find-file-at-mouse (ev)
10651 "Open file link or URL at mouse."
10652 (interactive "e")
10653 (mouse-set-point ev)
10654 (org-open-at-point 'in-emacs))
10656 (defun org-open-at-mouse (ev)
10657 "Open file link or URL at mouse.
10658 See the docstring of `org-open-file' for details."
10659 (interactive "e")
10660 (mouse-set-point ev)
10661 (when (eq major-mode 'org-agenda-mode)
10662 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10663 (org-open-at-point))
10665 (defvar org-window-config-before-follow-link nil
10666 "The window configuration before following a link.
10667 This is saved in case the need arises to restore it.")
10669 ;;;###autoload
10670 (defun org-open-at-point-global ()
10671 "Follow a link or time-stamp like Org mode does.
10672 This command can be called in any mode to follow an external link
10673 or a time-stamp that has Org mode syntax. Its behavior is
10674 undefined when called on internal links (e.g., fuzzy links).
10675 Raise an error when there is nothing to follow. "
10676 (interactive)
10677 (cond ((org-in-regexp org-any-link-re)
10678 (org-open-link-from-string (match-string-no-properties 0)))
10679 ((or (org-in-regexp org-ts-regexp-both nil t)
10680 (org-in-regexp org-tsr-regexp-both nil t))
10681 (org-follow-timestamp-link))
10682 (t (user-error "No link found"))))
10684 ;;;###autoload
10685 (defun org-open-link-from-string (s &optional arg reference-buffer)
10686 "Open a link in the string S, as if it was in Org-mode."
10687 (interactive "sLink: \nP")
10688 (let ((reference-buffer (or reference-buffer (current-buffer))))
10689 (with-temp-buffer
10690 (let ((org-inhibit-startup (not reference-buffer)))
10691 (org-mode)
10692 (insert s)
10693 (goto-char (point-min))
10694 (when reference-buffer
10695 (setq org-link-abbrev-alist-local
10696 (with-current-buffer reference-buffer
10697 org-link-abbrev-alist-local)))
10698 (org-open-at-point arg reference-buffer)))))
10700 (defvar org-open-at-point-functions nil
10701 "Hook that is run when following a link at point.
10703 Functions in this hook must return t if they identify and follow
10704 a link at point. If they don't find anything interesting at point,
10705 they must return nil.")
10707 (defvar org-link-search-inhibit-query nil)
10708 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10709 (defun org--open-doi-link (path)
10710 "Open a \"doi\" type link.
10711 PATH is a the path to search for, as a string."
10712 (browse-url (url-encode-url (concat org-doi-server-url path))))
10714 (defun org--open-elisp-link (path)
10715 "Open a \"elisp\" type link.
10716 PATH is the sexp to evaluate, as a string."
10717 (let ((cmd path))
10718 (if (or (and (org-string-nw-p
10719 org-confirm-elisp-link-not-regexp)
10720 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10721 (not org-confirm-elisp-link-function)
10722 (funcall org-confirm-elisp-link-function
10723 (format "Execute \"%s\" as elisp? "
10724 (org-add-props cmd nil 'face 'org-warning))))
10725 (message "%s => %s" cmd
10726 (if (eq (string-to-char cmd) ?\()
10727 (eval (read cmd))
10728 (call-interactively (read cmd))))
10729 (user-error "Abort"))))
10731 (defun org--open-help-link (path)
10732 "Open a \"help\" type link.
10733 PATH is a symbol name, as a string."
10734 (pcase (intern path)
10735 ((and (pred fboundp) variable) (describe-function variable))
10736 ((and (pred boundp) function) (describe-variable function))
10737 (name (user-error "Unknown function or variable: %s" name))))
10739 (defun org--open-shell-link (path)
10740 "Open a \"shell\" type link.
10741 PATH is the command to execute, as a string."
10742 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10743 (cmd path))
10744 (if (or (and (org-string-nw-p
10745 org-confirm-shell-link-not-regexp)
10746 (string-match
10747 org-confirm-shell-link-not-regexp cmd))
10748 (not org-confirm-shell-link-function)
10749 (funcall org-confirm-shell-link-function
10750 (format "Execute \"%s\" in shell? "
10751 (org-add-props cmd nil
10752 'face 'org-warning))))
10753 (progn
10754 (message "Executing %s" cmd)
10755 (shell-command cmd buf)
10756 (when (featurep 'midnight)
10757 (setq clean-buffer-list-kill-buffer-names
10758 (cons (buffer-name buf)
10759 clean-buffer-list-kill-buffer-names))))
10760 (user-error "Abort"))))
10762 (defun org-open-at-point (&optional arg reference-buffer)
10763 "Open link, timestamp, footnote or tags at point.
10765 When point is on a link, follow it. Normally, files will be
10766 opened by an appropriate application. If the optional prefix
10767 argument ARG is non-nil, Emacs will visit the file. With
10768 a double prefix argument, try to open outside of Emacs, in the
10769 application the system uses for this file type.
10771 When point is on a timestamp, open the agenda at the day
10772 specified.
10774 When point is a footnote definition, move to the first reference
10775 found. If it is on a reference, move to the associated
10776 definition.
10778 When point is on a headline, display a list of every link in the
10779 entry, so it is possible to pick one, or all, of them. If point
10780 is on a tag, call `org-tags-view' instead.
10782 When optional argument REFERENCE-BUFFER is non-nil, it should
10783 specify a buffer from where the link search should happen. This
10784 is used internally by `org-open-link-from-string'.
10786 On top of syntactically correct links, this function will open
10787 the link at point in comments or comment blocks and the first
10788 link in a property drawer line."
10789 (interactive "P")
10790 ;; On a code block, open block's results.
10791 (unless (call-interactively 'org-babel-open-src-block-result)
10792 (org-load-modules-maybe)
10793 (setq org-window-config-before-follow-link (current-window-configuration))
10794 (org-remove-occur-highlights nil nil t)
10795 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10796 (let* ((context
10797 ;; Only consider supported types, even if they are not
10798 ;; the closest one.
10799 (org-element-lineage
10800 (org-element-context)
10801 '(clock comment comment-block footnote-definition
10802 footnote-reference headline inlinetask keyword link
10803 node-property timestamp)
10805 (type (org-element-type context))
10806 (value (org-element-property :value context)))
10807 (cond
10808 ((not context) (user-error "No link found"))
10809 ;; Exception: open timestamps and links in properties
10810 ;; drawers, keywords and comments.
10811 ((memq type '(comment comment-block keyword node-property))
10812 (call-interactively #'org-open-at-point-global))
10813 ;; On a headline or an inlinetask, but not on a timestamp,
10814 ;; a link, a footnote reference or on tags.
10815 ((and (memq type '(headline inlinetask))
10816 ;; Not on tags.
10817 (progn (save-excursion (beginning-of-line)
10818 (looking-at org-complex-heading-regexp))
10819 (or (not (match-beginning 5))
10820 (< (point) (match-beginning 5)))))
10821 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10822 (links (car data))
10823 (links-end (cdr data)))
10824 (if links
10825 (dolist (link (if (stringp links) (list links) links))
10826 (search-forward link nil links-end)
10827 (goto-char (match-beginning 0))
10828 (org-open-at-point))
10829 (require 'org-attach)
10830 (org-attach-reveal 'if-exists))))
10831 ;; On a clock line, make sure point is on the timestamp
10832 ;; before opening it.
10833 ((and (eq type 'clock)
10834 value
10835 (>= (point) (org-element-property :begin value))
10836 (<= (point) (org-element-property :end value)))
10837 (org-follow-timestamp-link))
10838 ;; Do nothing on white spaces after an object.
10839 ((>= (point)
10840 (save-excursion
10841 (goto-char (org-element-property :end context))
10842 (skip-chars-backward " \t")
10843 (point)))
10844 (user-error "No link found"))
10845 ((eq type 'timestamp) (org-follow-timestamp-link))
10846 ;; On tags within a headline or an inlinetask.
10847 ((and (memq type '(headline inlinetask))
10848 (progn (save-excursion (beginning-of-line)
10849 (looking-at org-complex-heading-regexp))
10850 (and (match-beginning 5)
10851 (>= (point) (match-beginning 5)))))
10852 (org-tags-view arg (substring (match-string 5) 0 -1)))
10853 ((eq type 'link)
10854 ;; When link is located within the description of another
10855 ;; link (e.g., an inline image), always open the parent
10856 ;; link.
10857 (let* ((link (let ((up (org-element-property :parent context)))
10858 (if (eq (org-element-type up) 'link) up context)))
10859 (type (org-element-property :type link))
10860 (path (org-link-unescape (org-element-property :path link))))
10861 ;; Switch back to REFERENCE-BUFFER needed when called in
10862 ;; a temporary buffer through `org-open-link-from-string'.
10863 (with-current-buffer (or reference-buffer (current-buffer))
10864 (cond
10865 ((equal type "file")
10866 (if (string-match "[*?{]" (file-name-nondirectory path))
10867 (dired path)
10868 ;; Look into `org-link-parameters' in order to find
10869 ;; a DEDICATED-FUNCTION to open file. The function
10870 ;; will be applied on raw link instead of parsed
10871 ;; link due to the limitation in `org-add-link-type'
10872 ;; ("open" function called with a single argument).
10873 ;; If no such function is found, fallback to
10874 ;; `org-open-file'.
10875 (let* ((option (org-element-property :search-option link))
10876 (app (org-element-property :application link))
10877 (dedicated-function
10878 (org-link-get-parameter
10879 (if app (concat type "+" app) type)
10880 :follow)))
10881 (if dedicated-function
10882 (funcall dedicated-function
10883 (concat path
10884 (and option (concat "::" option))))
10885 (apply #'org-open-file
10886 path
10887 (cond (arg)
10888 ((equal app "emacs") 'emacs)
10889 ((equal app "sys") 'system))
10890 (cond ((not option) nil)
10891 ((string-match-p "\\`[0-9]+\\'" option)
10892 (list (string-to-number option)))
10893 (t (list nil
10894 (org-link-unescape option)))))))))
10895 ((functionp (org-link-get-parameter type :follow))
10896 (funcall (org-link-get-parameter type :follow) path))
10897 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10898 (unless (run-hook-with-args-until-success
10899 'org-open-link-functions path)
10900 (if (not arg) (org-mark-ring-push)
10901 (switch-to-buffer-other-window
10902 (org-get-buffer-for-internal-link (current-buffer))))
10903 (let ((destination
10904 (org-with-wide-buffer
10905 (if (equal type "radio")
10906 (org-search-radio-target
10907 (org-element-property :path link))
10908 (org-link-search
10909 (if (member type '("custom-id" "coderef"))
10910 (org-element-property :raw-link link)
10911 path)
10912 ;; Prevent fuzzy links from matching
10913 ;; themselves.
10914 (and (equal type "fuzzy")
10915 (+ 2 (org-element-property :begin link)))))
10916 (point))))
10917 (unless (and (<= (point-min) destination)
10918 (>= (point-max) destination))
10919 (widen))
10920 (goto-char destination))))
10921 (t (browse-url-at-point))))))
10922 ;; On a footnote reference or at a footnote definition's label.
10923 ((or (eq type 'footnote-reference)
10924 (and (eq type 'footnote-definition)
10925 (save-excursion
10926 ;; Do not validate action when point is on the
10927 ;; spaces right after the footnote label, in
10928 ;; order to be on par with behaviour on links.
10929 (skip-chars-forward " \t")
10930 (let ((begin
10931 (org-element-property :contents-begin context)))
10932 (if begin (< (point) begin)
10933 (= (org-element-property :post-affiliated context)
10934 (line-beginning-position)))))))
10935 (org-footnote-action))
10936 (t (user-error "No link found")))))
10937 (run-hook-with-args 'org-follow-link-hook)))
10939 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10940 "Offer links in the current entry and return the selected link.
10941 If there is only one link, return it.
10942 If NTH is an integer, return the NTH link found.
10943 If ZERO is a string, check also this string for a link, and if
10944 there is one, return it."
10945 (with-current-buffer buffer
10946 (org-with-wide-buffer
10947 (goto-char marker)
10948 (let ((cnt ?0)
10949 have-zero end links link c)
10950 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10951 (push (match-string 0 zero) links)
10952 (setq cnt (1- cnt) have-zero t))
10953 (save-excursion
10954 (org-back-to-heading t)
10955 (setq end (save-excursion (outline-next-heading) (point)))
10956 (while (re-search-forward org-any-link-re end t)
10957 (push (match-string 0) links))
10958 (setq links (org-uniquify (reverse links))))
10959 (cond
10960 ((null links)
10961 (message "No links"))
10962 ((equal (length links) 1)
10963 (setq link (car links)))
10964 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10965 (setq link (nth (if have-zero nth (1- nth)) links)))
10966 (t ; we have to select a link
10967 (save-excursion
10968 (save-window-excursion
10969 (delete-other-windows)
10970 (with-output-to-temp-buffer "*Select Link*"
10971 (dolist (l links)
10972 (cond
10973 ((not (string-match org-bracket-link-regexp l))
10974 (princ (format "[%c] %s\n" (cl-incf cnt)
10975 (org-unbracket-string "<" ">" l))))
10976 ((match-end 3)
10977 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10978 (match-string 3 l) (match-string 1 l))))
10979 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10980 (match-string 1 l)))))))
10981 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10982 (message "Select link to open, RET to open all:")
10983 (setq c (read-char-exclusive))
10984 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10985 (when (equal c ?q) (user-error "Abort"))
10986 (if (equal c ?\C-m)
10987 (setq link links)
10988 (setq nth (- c ?0))
10989 (when have-zero (setq nth (1+ nth)))
10990 (unless (and (integerp nth) (>= (length links) nth))
10991 (user-error "Invalid link selection"))
10992 (setq link (nth (1- nth) links)))))
10993 (cons link end)))))
10995 ;; TODO: These functions are deprecated since `org-open-at-point'
10996 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10997 (defun org-open-file-with-system (path)
10998 "Open file at PATH using the system way of opening it."
10999 (org-open-file path 'system))
11000 (defun org-open-file-with-emacs (path)
11001 "Open file at PATH in Emacs."
11002 (org-open-file path 'emacs))
11005 ;;; File search
11007 (defvar org-create-file-search-functions nil
11008 "List of functions to construct the right search string for a file link.
11009 These functions are called in turn with point at the location to
11010 which the link should point.
11012 A function in the hook should first test if it would like to
11013 handle this file type, for example by checking the `major-mode'
11014 or the file extension. If it decides not to handle this file, it
11015 should just return nil to give other functions a chance. If it
11016 does handle the file, it must return the search string to be used
11017 when following the link. The search string will be part of the
11018 file link, given after a double colon, and `org-open-at-point'
11019 will automatically search for it. If special measures must be
11020 taken to make the search successful, another function should be
11021 added to the companion hook `org-execute-file-search-functions',
11022 which see.
11024 A function in this hook may also use `setq' to set the variable
11025 `description' to provide a suggestion for the descriptive text to
11026 be used for this link when it gets inserted into an Org buffer
11027 with \\[org-insert-link].")
11029 (defvar org-execute-file-search-functions nil
11030 "List of functions to execute a file search triggered by a link.
11032 Functions added to this hook must accept a single argument, the
11033 search string that was part of the file link, the part after the
11034 double colon. The function must first check if it would like to
11035 handle this search, for example by checking the `major-mode' or
11036 the file extension. If it decides not to handle this search, it
11037 should just return nil to give other functions a chance. If it
11038 does handle the search, it must return a non-nil value to keep
11039 other functions from trying.
11041 Each function can access the current prefix argument through the
11042 variable `current-prefix-arg'. Note that a single prefix is used
11043 to force opening a link in Emacs, so it may be good to only use a
11044 numeric or double prefix to guide the search function.
11046 In case this is needed, a function in this hook can also restore
11047 the window configuration before `org-open-at-point' was called using:
11049 \(set-window-configuration org-window-config-before-follow-link)")
11051 (defun org-search-radio-target (target)
11052 "Search a radio target matching TARGET in current buffer.
11053 White spaces are not significant."
11054 (let ((re (format "<<<%s>>>"
11055 (mapconcat #'regexp-quote
11056 (org-split-string target "[ \t\n]+")
11057 "[ \t]+\\(?:\n[ \t]*\\)?")))
11058 (origin (point)))
11059 (goto-char (point-min))
11060 (catch :radio-match
11061 (while (re-search-forward re nil t)
11062 (backward-char)
11063 (let ((object (org-element-context)))
11064 (when (eq (org-element-type object) 'radio-target)
11065 (goto-char (org-element-property :begin object))
11066 (org-show-context 'link-search)
11067 (throw :radio-match nil))))
11068 (goto-char origin)
11069 (user-error "No match for radio target: %s" target))))
11071 (defun org-link-search (s &optional avoid-pos stealth)
11072 "Search for a search string S.
11074 If S starts with \"#\", it triggers a custom ID search.
11076 If S is enclosed within parenthesis, it initiates a coderef
11077 search.
11079 If S is surrounded by forward slashes, it is interpreted as
11080 a regular expression. In Org mode files, this will create an
11081 `org-occur' sparse tree. In ordinary files, `occur' will be used
11082 to list matches. If the current buffer is in `dired-mode', grep
11083 will be used to search in all files.
11085 When AVOID-POS is given, ignore matches near that position.
11087 When optional argument STEALTH is non-nil, do not modify
11088 visibility around point, thus ignoring `org-show-context-detail'
11089 variable.
11091 Search is case-insensitive and ignores white spaces. Return type
11092 of matched result, with is either `dedicated' or `fuzzy'."
11093 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11094 (let* ((case-fold-search t)
11095 (origin (point))
11096 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11097 (words (org-split-string s "[ \t\n]+"))
11098 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11099 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11100 type)
11101 (cond
11102 ;; Check if there are any special search functions.
11103 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11104 ((eq (string-to-char s) ?#)
11105 ;; Look for a custom ID S if S starts with "#".
11106 (let* ((id (substring normalized 1))
11107 (match (org-find-property "CUSTOM_ID" id)))
11108 (if match (progn (goto-char match) (setf type 'dedicated))
11109 (error "No match for custom ID: %s" id))))
11110 ((string-match "\\`(\\(.*\\))\\'" normalized)
11111 ;; Look for coderef targets if S is enclosed within parenthesis.
11112 (let ((coderef (match-string-no-properties 1 normalized))
11113 (re (substring s-single-re 1 -1)))
11114 (goto-char (point-min))
11115 (catch :coderef-match
11116 (while (re-search-forward re nil t)
11117 (let ((element (org-element-at-point)))
11118 (when (and (memq (org-element-type element)
11119 '(example-block src-block))
11120 ;; Build proper regexp according to current
11121 ;; block's label format.
11122 (let ((label-fmt
11123 (regexp-quote
11124 (or (org-element-property :label-fmt element)
11125 org-coderef-label-format))))
11126 (save-excursion
11127 (beginning-of-line)
11128 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11129 (format label-fmt coderef))))))
11130 (setq type 'dedicated)
11131 (goto-char (match-beginning 1))
11132 (throw :coderef-match nil))))
11133 (goto-char origin)
11134 (error "No match for coderef: %s" coderef))))
11135 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11136 ;; Look for a regular expression.
11137 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11138 (match-string 1 s)))
11139 ;; Fuzzy links.
11141 (let ((starred (eq (string-to-char normalized) ?*)))
11142 (cond
11143 ;; Look for targets, only if not in a headline search.
11144 ((and (not starred)
11145 (let ((target (format "<<%s>>" s-multi-re)))
11146 (catch :target-match
11147 (goto-char (point-min))
11148 (while (re-search-forward target nil t)
11149 (backward-char)
11150 (let ((context (org-element-context)))
11151 (when (eq (org-element-type context) 'target)
11152 (setq type 'dedicated)
11153 (goto-char (org-element-property :begin context))
11154 (throw :target-match t))))
11155 nil))))
11156 ;; Look for elements named after S, only if not in a headline
11157 ;; search.
11158 ((and (not starred)
11159 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11160 (catch :name-match
11161 (goto-char (point-min))
11162 (while (re-search-forward name nil t)
11163 (let ((element (org-element-at-point)))
11164 (when (equal (org-split-string
11165 (org-element-property :name element)
11166 "[ \t]+")
11167 words)
11168 (setq type 'dedicated)
11169 (beginning-of-line)
11170 (throw :name-match t))))
11171 nil))))
11172 ;; Regular text search. Prefer headlines in Org mode
11173 ;; buffers.
11174 ((and (derived-mode-p 'org-mode)
11175 (let* ((wspace "[ \t]")
11176 (wspaceopt (concat wspace "*"))
11177 (cookie (concat "\\(?:"
11178 wspaceopt
11179 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11180 wspaceopt
11181 "\\)"))
11182 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11183 (re (concat
11184 org-outline-regexp-bol
11185 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11186 "\\(?:\\[#.\\][ \t]+\\)?"
11187 "\\(?:" org-comment-string "[ \t]+\\)?"
11188 sep "?"
11189 (let ((title (mapconcat #'regexp-quote
11190 words
11191 sep)))
11192 (if starred (substring title 1) title))
11193 sep "?"
11194 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11195 "[ \t]*$")))
11196 (goto-char (point-min))
11197 (re-search-forward re nil t)))
11198 (goto-char (match-beginning 0))
11199 (setq type 'dedicated))
11200 ;; Offer to create non-existent headline depending on
11201 ;; `org-link-search-must-match-exact-headline'.
11202 ((and (derived-mode-p 'org-mode)
11203 (not org-link-search-inhibit-query)
11204 (eq org-link-search-must-match-exact-headline 'query-to-create)
11205 (yes-or-no-p "No match - create this as a new heading? "))
11206 (goto-char (point-max))
11207 (unless (bolp) (newline))
11208 (org-insert-heading nil t t)
11209 (insert s "\n")
11210 (beginning-of-line 0))
11211 ;; Only headlines are looked after. No need to process
11212 ;; further: throw an error.
11213 ((and (derived-mode-p 'org-mode)
11214 (or starred org-link-search-must-match-exact-headline))
11215 (goto-char origin)
11216 (error "No match for fuzzy expression: %s" normalized))
11217 ;; Regular text search.
11218 ((catch :fuzzy-match
11219 (goto-char (point-min))
11220 (while (re-search-forward s-multi-re nil t)
11221 ;; Skip match if it contains AVOID-POS or it is included
11222 ;; in a link with a description but outside the
11223 ;; description.
11224 (unless (or (and avoid-pos
11225 (<= (match-beginning 0) avoid-pos)
11226 (> (match-end 0) avoid-pos))
11227 (and (save-match-data
11228 (org-in-regexp org-bracket-link-regexp))
11229 (match-beginning 3)
11230 (or (> (match-beginning 3) (point))
11231 (<= (match-end 3) (point)))
11232 (org-element-lineage
11233 (save-match-data (org-element-context))
11234 '(link) t)))
11235 (goto-char (match-beginning 0))
11236 (setq type 'fuzzy)
11237 (throw :fuzzy-match t)))
11238 nil))
11239 ;; All failed. Throw an error.
11240 (t (goto-char origin)
11241 (error "No match for fuzzy expression: %s" normalized))))))
11242 ;; Disclose surroundings of match, if appropriate.
11243 (when (and (derived-mode-p 'org-mode) (not stealth))
11244 (org-show-context 'link-search))
11245 type))
11247 (defun org-get-buffer-for-internal-link (buffer)
11248 "Return a buffer to be used for displaying the link target of internal links."
11249 (cond
11250 ((not org-display-internal-link-with-indirect-buffer)
11251 buffer)
11252 ((string-suffix-p "(Clone)" (buffer-name buffer))
11253 (message "Buffer is already a clone, not making another one")
11254 ;; we also do not modify visibility in this case
11255 buffer)
11256 (t ; make a new indirect buffer for displaying the link
11257 (let* ((bn (buffer-name buffer))
11258 (ibn (concat bn "(Clone)"))
11259 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11260 (with-current-buffer ib (org-overview))
11261 ib))))
11263 (defun org-do-occur (regexp &optional cleanup)
11264 "Call the Emacs command `occur'.
11265 If CLEANUP is non-nil, remove the printout of the regular expression
11266 in the *Occur* buffer. This is useful if the regex is long and not useful
11267 to read."
11268 (occur regexp)
11269 (when cleanup
11270 (let ((cwin (selected-window)) win beg end)
11271 (when (setq win (get-buffer-window "*Occur*"))
11272 (select-window win))
11273 (goto-char (point-min))
11274 (when (re-search-forward "match[a-z]+" nil t)
11275 (setq beg (match-end 0))
11276 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11277 (setq end (1- (match-beginning 0)))))
11278 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11279 (goto-char (point-min))
11280 (select-window cwin))))
11282 ;;; The mark ring for links jumps
11284 (defvar org-mark-ring nil
11285 "Mark ring for positions before jumps in Org-mode.")
11286 (defvar org-mark-ring-last-goto nil
11287 "Last position in the mark ring used to go back.")
11288 ;; Fill and close the ring
11289 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11290 (dotimes (_ org-mark-ring-length)
11291 (push (make-marker) org-mark-ring))
11292 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11293 org-mark-ring)
11295 (defun org-mark-ring-push (&optional pos buffer)
11296 "Put the current position or POS into the mark ring and rotate it."
11297 (interactive)
11298 (setq pos (or pos (point)))
11299 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11300 (move-marker (car org-mark-ring)
11301 (or pos (point))
11302 (or buffer (current-buffer)))
11303 (message "%s"
11304 (substitute-command-keys
11305 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11307 (defun org-mark-ring-goto (&optional n)
11308 "Jump to the previous position in the mark ring.
11309 With prefix arg N, jump back that many stored positions. When
11310 called several times in succession, walk through the entire ring.
11311 Org mode commands jumping to a different position in the current file,
11312 or to another Org file, automatically push the old position onto the ring."
11313 (interactive "p")
11314 (let (p m)
11315 (if (eq last-command this-command)
11316 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11317 (setq p org-mark-ring))
11318 (setq org-mark-ring-last-goto p)
11319 (setq m (car p))
11320 (pop-to-buffer-same-window (marker-buffer m))
11321 (goto-char m)
11322 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11324 (defun org-add-angle-brackets (s)
11325 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11326 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11329 ;;; Following specific links
11331 (defvar org-agenda-buffer-tmp-name)
11332 (defvar org-agenda-start-on-weekday)
11333 (defun org-follow-timestamp-link ()
11334 "Open an agenda view for the time-stamp date/range at point."
11335 (cond
11336 ((org-at-date-range-p t)
11337 (let ((org-agenda-start-on-weekday)
11338 (t1 (match-string 1))
11339 (t2 (match-string 2)) tt1 tt2)
11340 (setq tt1 (time-to-days (org-time-string-to-time t1))
11341 tt2 (time-to-days (org-time-string-to-time t2)))
11342 (let ((org-agenda-buffer-tmp-name
11343 (format "*Org Agenda(a:%s)"
11344 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11345 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11346 ((org-at-timestamp-p t)
11347 (let ((org-agenda-buffer-tmp-name
11348 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11349 (org-agenda-list nil (time-to-days (org-time-string-to-time
11350 (substring (match-string 1) 0 10)))
11351 1)))
11352 (t (error "This should not happen"))))
11355 ;;; Following file links
11356 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11357 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11358 (declare-function mailcap-mime-info
11359 "mailcap" (string &optional request no-decode))
11360 (defvar org-wait nil)
11361 (defun org-open-file (path &optional in-emacs line search)
11362 "Open the file at PATH.
11363 First, this expands any special file name abbreviations. Then the
11364 configuration variable `org-file-apps' is checked if it contains an
11365 entry for this file type, and if yes, the corresponding command is launched.
11367 If no application is found, Emacs simply visits the file.
11369 With optional prefix argument IN-EMACS, Emacs will visit the file.
11370 With a double \\[universal-argument] \\[universal-argument] \
11371 prefix arg, Org tries to avoid opening in Emacs
11372 and to use an external application to visit the file.
11374 Optional LINE specifies a line to go to, optional SEARCH a string
11375 to search for. If LINE or SEARCH is given, the file will be
11376 opened in Emacs, unless an entry from org-file-apps that makes
11377 use of groups in a regexp matches.
11379 If you want to change the way frames are used when following a
11380 link, please customize `org-link-frame-setup'.
11382 If the file does not exist, an error is thrown."
11383 (let* ((file (if (equal path "")
11384 buffer-file-name
11385 (substitute-in-file-name (expand-file-name path))))
11386 (file-apps (append org-file-apps (org-default-apps)))
11387 (apps (cl-remove-if
11388 'org-file-apps-entry-match-against-dlink-p file-apps))
11389 (apps-dlink (cl-remove-if-not
11390 'org-file-apps-entry-match-against-dlink-p file-apps))
11391 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11392 (dirp (unless remp (file-directory-p file)))
11393 (file (if (and dirp org-open-directory-means-index-dot-org)
11394 (concat (file-name-as-directory file) "index.org")
11395 file))
11396 (a-m-a-p (assq 'auto-mode apps))
11397 (dfile (downcase file))
11398 ;; Reconstruct the original link from the PATH, LINE and
11399 ;; SEARCH args.
11400 (link (cond (line (concat file "::" (number-to-string line)))
11401 (search (concat file "::" search))
11402 (t file)))
11403 (dlink (downcase link))
11404 (old-buffer (current-buffer))
11405 (old-pos (point))
11406 (old-mode major-mode)
11407 (ext
11408 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11409 (match-string 1 dfile)))
11410 cmd link-match-data)
11411 (cond
11412 ((member in-emacs '((16) system))
11413 (setq cmd (cdr (assq 'system apps))))
11414 (in-emacs (setq cmd 'emacs))
11416 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11417 (and dirp (cdr (assq 'directory apps)))
11418 ;; First, try matching against apps-dlink if we
11419 ;; get a match here, store the match data for
11420 ;; later.
11421 (let ((match (assoc-default dlink apps-dlink
11422 'string-match)))
11423 (if match
11424 (progn (setq link-match-data (match-data))
11425 match)
11426 (progn (setq in-emacs (or in-emacs line search))
11427 nil))) ; if we have no match in apps-dlink,
11428 ; always open the file in emacs if line or search
11429 ; is given (for backwards compatibility)
11430 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11431 'string-match)
11432 (cdr (assoc ext apps))
11433 (cdr (assq t apps))))))
11434 (when (eq cmd 'system)
11435 (setq cmd (cdr (assq 'system apps))))
11436 (when (eq cmd 'default)
11437 (setq cmd (cdr (assoc t apps))))
11438 (when (eq cmd 'mailcap)
11439 (require 'mailcap)
11440 (mailcap-parse-mailcaps)
11441 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11442 (command (mailcap-mime-info mime-type)))
11443 (if (stringp command)
11444 (setq cmd command)
11445 (setq cmd 'emacs))))
11446 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11447 (not (file-exists-p file))
11448 (not org-open-non-existing-files))
11449 (user-error "No such file: %s" file))
11450 (cond
11451 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11452 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11453 (while (string-match "['\"]%s['\"]" cmd)
11454 (setq cmd (replace-match "%s" t t cmd)))
11455 (setq cmd (replace-regexp-in-string
11456 "%s"
11457 (shell-quote-argument (convert-standard-filename file))
11459 nil t))
11461 ;; Replace "%1", "%2" etc. in command with group matches from regex
11462 (save-match-data
11463 (let ((match-index 1)
11464 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11465 (set-match-data link-match-data)
11466 (while (<= match-index number-of-groups)
11467 (let ((regex (concat "%" (number-to-string match-index)))
11468 (replace-with (match-string match-index dlink)))
11469 (while (string-match regex cmd)
11470 (setq cmd (replace-match replace-with t t cmd))))
11471 (setq match-index (+ match-index 1)))))
11473 (save-window-excursion
11474 (message "Running %s...done" cmd)
11475 (start-process-shell-command cmd nil cmd)
11476 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11477 ((or (stringp cmd)
11478 (eq cmd 'emacs))
11479 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11480 (widen)
11481 (cond (line (org-goto-line line)
11482 (when (derived-mode-p 'org-mode) (org-reveal)))
11483 (search (org-link-search search))))
11484 ((functionp cmd)
11485 (save-match-data
11486 (set-match-data link-match-data)
11487 (condition-case nil
11488 (funcall cmd file link)
11489 ;; FIXME: Remove this check when most default installations
11490 ;; of Emacs have at least Org 9.0.
11491 ((debug wrong-number-of-arguments wrong-type-argument
11492 invalid-function)
11493 (user-error "Please see Org News for version 9.0 about \
11494 `org-file-apps'--Lisp error: %S" cmd)))))
11495 ((consp cmd)
11496 ;; FIXME: Remove this check when most default installations of
11497 ;; Emacs have at least Org 9.0.
11498 ;; Heads-up instead of silently fall back to
11499 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11500 ;; with sexp instead of a function for `cmd'.
11501 (user-error "Please see Org News for version 9.0 about \
11502 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11503 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11504 (and (derived-mode-p 'org-mode)
11505 (eq old-mode 'org-mode)
11506 (or (not (eq old-buffer (current-buffer)))
11507 (not (eq old-pos (point))))
11508 (org-mark-ring-push old-pos old-buffer))))
11510 (defun org-file-apps-entry-match-against-dlink-p (entry)
11511 "This function returns non-nil if `entry' uses a regular
11512 expression which should be matched against the whole link by
11513 org-open-file.
11515 It assumes that is the case when the entry uses a regular
11516 expression which has at least one grouping construct and the
11517 action is either a lisp form or a command string containing
11518 `%1', i.e. using at least one subexpression match as a
11519 parameter."
11520 (let ((selector (car entry))
11521 (action (cdr entry)))
11522 (if (stringp selector)
11523 (and (> (regexp-opt-depth selector) 0)
11524 (or (and (stringp action)
11525 (string-match "%[0-9]" action))
11526 (consp action)))
11527 nil)))
11529 (defun org-default-apps ()
11530 "Return the default applications for this operating system."
11531 (cond
11532 ((eq system-type 'darwin)
11533 org-file-apps-defaults-macosx)
11534 ((eq system-type 'windows-nt)
11535 org-file-apps-defaults-windowsnt)
11536 (t org-file-apps-defaults-gnu)))
11538 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11539 "Convert extensions to regular expressions in the cars of LIST.
11540 Also, weed out any non-string entries, because the return value is used
11541 only for regexp matching.
11542 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11543 point to the symbol `emacs', indicating that the file should
11544 be opened in Emacs."
11545 (append
11546 (delq nil
11547 (mapcar (lambda (x)
11548 (unless (not (stringp (car x)))
11549 (if (string-match "\\W" (car x))
11551 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11552 list))
11553 (when add-auto-mode
11554 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11556 (defvar ange-ftp-name-format)
11557 (defun org-file-remote-p (file)
11558 "Test whether FILE specifies a location on a remote system.
11559 Return non-nil if the location is indeed remote.
11561 For example, the filename \"/user@host:/foo\" specifies a location
11562 on the system \"/user@host:\"."
11563 (cond ((fboundp 'file-remote-p)
11564 (file-remote-p file))
11565 ((fboundp 'tramp-handle-file-remote-p)
11566 (tramp-handle-file-remote-p file))
11567 ((and (boundp 'ange-ftp-name-format)
11568 (string-match (car ange-ftp-name-format) file))
11569 t)))
11572 ;;;; Refiling
11574 (defun org-get-org-file ()
11575 "Read a filename, with default directory `org-directory'."
11576 (let ((default (or org-default-notes-file remember-data-file)))
11577 (read-file-name (format "File name [%s]: " default)
11578 (file-name-as-directory org-directory)
11579 default)))
11581 (defun org-notes-order-reversed-p ()
11582 "Check if the current file should receive notes in reversed order."
11583 (cond
11584 ((not org-reverse-note-order) nil)
11585 ((eq t org-reverse-note-order) t)
11586 ((not (listp org-reverse-note-order)) nil)
11587 (t (catch 'exit
11588 (dolist (entry org-reverse-note-order)
11589 (when (string-match (car entry) buffer-file-name)
11590 (throw 'exit (cdr entry))))))))
11592 (defvar org-refile-target-table nil
11593 "The list of refile targets, created by `org-refile'.")
11595 (defvar org-agenda-new-buffers nil
11596 "Buffers created to visit agenda files.")
11598 (defvar org-refile-cache nil
11599 "Cache for refile targets.")
11601 (defvar org-refile-markers nil
11602 "All the markers used for caching refile locations.")
11604 (defun org-refile-marker (pos)
11605 "Get a new refile marker, but only if caching is in use."
11606 (if (not org-refile-use-cache)
11608 (let ((m (make-marker)))
11609 (move-marker m pos)
11610 (push m org-refile-markers)
11611 m)))
11613 (defun org-refile-cache-clear ()
11614 "Clear the refile cache and disable all the markers."
11615 (dolist (m org-refile-markers) (move-marker m nil))
11616 (setq org-refile-markers nil)
11617 (setq org-refile-cache nil)
11618 (message "Refile cache has been cleared"))
11620 (defun org-refile-cache-check-set (set)
11621 "Check if all the markers in the cache still have live buffers."
11622 (let (marker)
11623 (catch 'exit
11624 (while (and set (setq marker (nth 3 (pop set))))
11625 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11626 (when (and marker (null (marker-buffer marker)))
11627 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11628 (sit-for 3)
11629 (throw 'exit nil)))
11630 t)))
11632 (defun org-refile-cache-put (set &rest identifiers)
11633 "Push the refile targets SET into the cache, under IDENTIFIERS."
11634 (let* ((key (sha1 (prin1-to-string identifiers)))
11635 (entry (assoc key org-refile-cache)))
11636 (if entry
11637 (setcdr entry set)
11638 (push (cons key set) org-refile-cache))))
11640 (defun org-refile-cache-get (&rest identifiers)
11641 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11642 (cond
11643 ((not org-refile-cache) nil)
11644 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11646 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11647 org-refile-cache))))
11648 (and set (org-refile-cache-check-set set) set)))))
11650 (defvar org-outline-path-cache nil
11651 "Alist between buffer positions and outline paths.
11652 It value is an alist (POSITION . PATH) where POSITION is the
11653 buffer position at the beginning of an entry and PATH is a list
11654 of strings describing the outline path for that entry, in reverse
11655 order.")
11657 (defun org-refile-get-targets (&optional default-buffer)
11658 "Produce a table with refile targets."
11659 (let ((case-fold-search nil)
11660 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11661 (entries (or org-refile-targets '((nil . (:level . 1)))))
11662 targets tgs files desc descre)
11663 (message "Getting targets...")
11664 (with-current-buffer (or default-buffer (current-buffer))
11665 (dolist (entry entries)
11666 (setq files (car entry) desc (cdr entry))
11667 (cond
11668 ((null files) (setq files (list (current-buffer))))
11669 ((eq files 'org-agenda-files)
11670 (setq files (org-agenda-files 'unrestricted)))
11671 ((and (symbolp files) (fboundp files))
11672 (setq files (funcall files)))
11673 ((and (symbolp files) (boundp files))
11674 (setq files (symbol-value files))))
11675 (when (stringp files) (setq files (list files)))
11676 (cond
11677 ((eq (car desc) :tag)
11678 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11679 ((eq (car desc) :todo)
11680 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11681 ((eq (car desc) :regexp)
11682 (setq descre (cdr desc)))
11683 ((eq (car desc) :level)
11684 (setq descre (concat "^\\*\\{" (number-to-string
11685 (if org-odd-levels-only
11686 (1- (* 2 (cdr desc)))
11687 (cdr desc)))
11688 "\\}[ \t]")))
11689 ((eq (car desc) :maxlevel)
11690 (setq descre (concat "^\\*\\{1," (number-to-string
11691 (if org-odd-levels-only
11692 (1- (* 2 (cdr desc)))
11693 (cdr desc)))
11694 "\\}[ \t]")))
11695 (t (error "Bad refiling target description %s" desc)))
11696 (dolist (f files)
11697 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11699 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11700 (progn
11701 (when (bufferp f)
11702 (setq f (buffer-file-name (buffer-base-buffer f))))
11703 (setq f (and f (expand-file-name f)))
11704 (when (eq org-refile-use-outline-path 'file)
11705 (push (list (file-name-nondirectory f) f nil nil) tgs))
11706 (org-with-wide-buffer
11707 (goto-char (point-min))
11708 (setq org-outline-path-cache nil)
11709 (while (re-search-forward descre nil t)
11710 (beginning-of-line)
11711 (looking-at org-complex-heading-regexp)
11712 (let ((begin (point))
11713 (heading (match-string-no-properties 4)))
11714 (unless (or (and
11715 org-refile-target-verify-function
11716 (not
11717 (funcall org-refile-target-verify-function)))
11718 (not heading))
11719 (let ((re (format org-complex-heading-regexp-format
11720 (regexp-quote heading)))
11721 (target
11722 (if (not org-refile-use-outline-path) heading
11723 (mapconcat
11724 #'org-protect-slash
11725 (append
11726 (pcase org-refile-use-outline-path
11727 (`file (list (file-name-nondirectory
11728 (buffer-file-name
11729 (buffer-base-buffer)))))
11730 (`full-file-path
11731 (list (buffer-file-name
11732 (buffer-base-buffer))))
11733 (_ nil))
11734 (org-get-outline-path t t))
11735 "/"))))
11736 (push (list target f re (org-refile-marker (point)))
11737 tgs)))
11738 (when (= (point) begin)
11739 ;; Verification function has not moved point.
11740 (end-of-line)))))))
11741 (when org-refile-use-cache
11742 (org-refile-cache-put tgs (buffer-file-name) descre))
11743 (setq targets (append tgs targets))))))
11744 (message "Getting targets...done")
11745 (nreverse targets)))
11747 (defun org-protect-slash (s)
11748 (replace-regexp-in-string "/" "\\/" s nil t))
11750 (defun org--get-outline-path-1 (&optional use-cache)
11751 "Return outline path to current headline.
11753 Outline path is a list of strings, in reverse order. When
11754 optional argument USE-CACHE is non-nil, make use of a cache. See
11755 `org-get-outline-path' for details.
11757 Assume buffer is widened and point is on a headline."
11758 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11759 (let ((p (point))
11760 (heading (progn
11761 (looking-at org-complex-heading-regexp)
11762 (if (not (match-end 4)) ""
11763 ;; Remove statistics cookies.
11764 (org-trim
11765 (org-link-display-format
11766 (replace-regexp-in-string
11767 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11768 (match-string-no-properties 4))))))))
11769 (if (org-up-heading-safe)
11770 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11771 (when use-cache
11772 (push (cons p path) org-outline-path-cache))
11773 path)
11774 ;; This is a new root node. Since we assume we are moving
11775 ;; forward, we can drop previous cache so as to limit number
11776 ;; of associations there.
11777 (let ((path (list heading)))
11778 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11779 path)))))
11781 (defun org-get-outline-path (&optional with-self use-cache)
11782 "Return the outline path to the current entry.
11784 An outline path is a list of ancestors for current headline, as
11785 a list of strings. Statistics cookies are removed and links are
11786 replaced with their description, if any, or their path otherwise.
11788 When optional argument WITH-SELF is non-nil, the path also
11789 includes the current headline.
11791 When optional argument USE-CACHE is non-nil, cache outline paths
11792 between calls to this function so as to avoid backtracking. This
11793 argument is useful when planning to find more than one outline
11794 path in the same document. In that case, there are two
11795 conditions to satisfy:
11796 - `org-outline-path-cache' is set to nil before starting the
11797 process;
11798 - outline paths are computed by increasing buffer positions."
11799 (org-with-wide-buffer
11800 (and (or (and with-self (org-back-to-heading t))
11801 (org-up-heading-safe))
11802 (reverse (org--get-outline-path-1 use-cache)))))
11804 (defun org-format-outline-path (path &optional width prefix separator)
11805 "Format the outline path PATH for display.
11806 WIDTH is the maximum number of characters that is available.
11807 PREFIX is a prefix to be included in the returned string,
11808 such as the file name.
11809 SEPARATOR is inserted between the different parts of the path,
11810 the default is \"/\"."
11811 (setq width (or width 79))
11812 (setq path (delq nil path))
11813 (unless (> width 0)
11814 (user-error "Argument `width' must be positive"))
11815 (setq separator (or separator "/"))
11816 (let* ((org-odd-levels-only nil)
11817 (fpath (concat
11818 prefix (and prefix path separator)
11819 (mapconcat
11820 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11821 (cl-loop for head in path
11822 for n from 0
11823 collect (org-add-props
11824 head nil 'face
11825 (nth (% n org-n-level-faces) org-level-faces)))
11826 separator))))
11827 (when (> (length fpath) width)
11828 (if (< width 7)
11829 ;; It's unlikely that `width' will be this small, but don't
11830 ;; waste characters by adding ".." if it is.
11831 (setq fpath (substring fpath 0 width))
11832 (setf (substring fpath (- width 2)) "..")))
11833 fpath))
11835 (defun org-display-outline-path (&optional file current separator just-return-string)
11836 "Display the current outline path in the echo area.
11838 If FILE is non-nil, prepend the output with the file name.
11839 If CURRENT is non-nil, append the current heading to the output.
11840 SEPARATOR is passed through to `org-format-outline-path'. It separates
11841 the different parts of the path and defaults to \"/\".
11842 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11843 (interactive "P")
11844 (let* (case-fold-search
11845 (bfn (buffer-file-name (buffer-base-buffer)))
11846 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11847 res)
11848 (when current (setq path (append path
11849 (save-excursion
11850 (org-back-to-heading t)
11851 (when (looking-at org-complex-heading-regexp)
11852 (list (match-string 4)))))))
11853 (setq res
11854 (org-format-outline-path
11855 path
11856 (1- (frame-width))
11857 (and file bfn (concat (file-name-nondirectory bfn) separator))
11858 separator))
11859 (if just-return-string
11860 (org-no-properties res)
11861 (org-unlogged-message "%s" res))))
11863 (defvar org-refile-history nil
11864 "History for refiling operations.")
11866 (defvar org-after-refile-insert-hook nil
11867 "Hook run after `org-refile' has inserted its stuff at the new location.
11868 Note that this is still *before* the stuff will be removed from
11869 the *old* location.")
11871 (defvar org-capture-last-stored-marker)
11872 (defvar org-refile-keep nil
11873 "Non-nil means `org-refile' will copy instead of refile.")
11875 (defun org-copy ()
11876 "Like `org-refile', but copy."
11877 (interactive)
11878 (let ((org-refile-keep t))
11879 (funcall 'org-refile nil nil nil "Copy")))
11881 (defun org-refile (&optional arg default-buffer rfloc msg)
11882 "Move the entry or entries at point to another heading.
11883 The list of target headings is compiled using the information in
11884 `org-refile-targets', which see.
11886 At the target location, the entry is filed as a subitem of the
11887 target heading. Depending on `org-reverse-note-order', the new
11888 subitem will either be the first or the last subitem.
11890 If there is an active region, all entries in that region will be
11891 refiled. However, the region must fulfill the requirement that
11892 the first heading sets the top-level of the moved text.
11894 With prefix arg ARG, the command will only visit the target
11895 location and not actually move anything.
11897 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11898 refiling operation has put the subtree.
11900 With a numeric prefix argument of `2', refile to the running clock.
11902 With a numeric prefix argument of `3', emulate `org-refile-keep'
11903 being set to t and copy to the target location, don't move it.
11904 Beware that keeping refiled entries may result in duplicated ID
11905 properties.
11907 RFLOC can be a refile location obtained in a different way.
11909 MSG is a string to replace \"Refile\" in the default prompt with
11910 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11912 See also `org-refile-use-outline-path'.
11914 If you are using target caching (see `org-refile-use-cache'), you
11915 have to clear the target cache in order to find new targets.
11916 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11917 prefix argument (`C-u C-u C-u C-c C-w')."
11918 (interactive "P")
11919 (if (member arg '(0 (64)))
11920 (org-refile-cache-clear)
11921 (let* ((actionmsg (cond (msg msg)
11922 ((equal arg 3) "Refile (and keep)")
11923 (t "Refile")))
11924 (regionp (org-region-active-p))
11925 (region-start (and regionp (region-beginning)))
11926 (region-end (and regionp (region-end)))
11927 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11928 pos it nbuf file level reversed)
11929 (setq last-command nil)
11930 (when regionp
11931 (goto-char region-start)
11932 (or (bolp) (goto-char (point-at-bol)))
11933 (setq region-start (point))
11934 (unless (or (org-kill-is-subtree-p
11935 (buffer-substring region-start region-end))
11936 (prog1 org-refile-active-region-within-subtree
11937 (let ((s (point-at-eol)))
11938 (org-toggle-heading)
11939 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11940 (user-error "The region is not a (sequence of) subtree(s)")))
11941 (if (equal arg '(16))
11942 (org-refile-goto-last-stored)
11943 (when (or
11944 (and (equal arg 2)
11945 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11946 (prog1
11947 (setq it (list (or org-clock-heading "running clock")
11948 (buffer-file-name
11949 (marker-buffer org-clock-hd-marker))
11951 (marker-position org-clock-hd-marker)))
11952 (setq arg nil)))
11953 (setq it
11954 (or rfloc
11955 (let (heading-text)
11956 (save-excursion
11957 (unless (and arg (listp arg))
11958 (org-back-to-heading t)
11959 (setq heading-text
11960 (replace-regexp-in-string
11961 org-bracket-link-regexp
11962 "\\3"
11963 (or (nth 4 (org-heading-components))
11964 ""))))
11965 (org-refile-get-location
11966 (cond ((and arg (listp arg)) "Goto")
11967 (regionp (concat actionmsg " region to"))
11968 (t (concat actionmsg " subtree \""
11969 heading-text "\" to")))
11970 default-buffer
11971 (and (not (equal '(4) arg))
11972 org-refile-allow-creating-parent-nodes)))))))
11973 (setq file (nth 1 it)
11974 pos (nth 3 it))
11975 (when (and (not arg)
11977 (equal (buffer-file-name) file)
11978 (if regionp
11979 (and (>= pos region-start)
11980 (<= pos region-end))
11981 (and (>= pos (point))
11982 (< pos (save-excursion
11983 (org-end-of-subtree t t))))))
11984 (error "Cannot refile to position inside the tree or region"))
11985 (setq nbuf (or (find-buffer-visiting file)
11986 (find-file-noselect file)))
11987 (if (and arg (not (equal arg 3)))
11988 (progn
11989 (pop-to-buffer-same-window nbuf)
11990 (goto-char pos)
11991 (org-show-context 'org-goto))
11992 (if regionp
11993 (progn
11994 (org-kill-new (buffer-substring region-start region-end))
11995 (org-save-markers-in-region region-start region-end))
11996 (org-copy-subtree 1 nil t))
11997 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11998 (find-file-noselect file)))
11999 (setq reversed (org-notes-order-reversed-p))
12000 (org-with-wide-buffer
12001 (if pos
12002 (progn
12003 (goto-char pos)
12004 (looking-at org-outline-regexp)
12005 (setq level (org-get-valid-level (funcall outline-level) 1))
12006 (goto-char
12007 (if reversed
12008 (or (outline-next-heading) (point-max))
12009 (or (save-excursion (org-get-next-sibling))
12010 (org-end-of-subtree t t)
12011 (point-max)))))
12012 (setq level 1)
12013 (if (not reversed)
12014 (goto-char (point-max))
12015 (goto-char (point-min))
12016 (or (outline-next-heading) (goto-char (point-max)))))
12017 (unless (bolp) (newline))
12018 (org-paste-subtree level nil nil t)
12019 (when org-log-refile
12020 (org-add-log-setup 'refile nil nil org-log-refile)
12021 (unless (eq org-log-refile 'note)
12022 (save-excursion (org-add-log-note))))
12023 (and org-auto-align-tags
12024 (let ((org-loop-over-headlines-in-active-region nil))
12025 (org-set-tags nil t)))
12026 (let ((bookmark-name (plist-get org-bookmark-names-plist
12027 :last-refile)))
12028 (when bookmark-name
12029 (with-demoted-errors
12030 (bookmark-set bookmark-name))))
12031 ;; If we are refiling for capture, make sure that the
12032 ;; last-capture pointers point here
12033 (when (bound-and-true-p org-capture-is-refiling)
12034 (let ((bookmark-name (plist-get org-bookmark-names-plist
12035 :last-capture-marker)))
12036 (when bookmark-name
12037 (with-demoted-errors
12038 (bookmark-set bookmark-name))))
12039 (move-marker org-capture-last-stored-marker (point)))
12040 (when (fboundp 'deactivate-mark) (deactivate-mark))
12041 (run-hooks 'org-after-refile-insert-hook)))
12042 (unless org-refile-keep
12043 (if regionp
12044 (delete-region (point) (+ (point) (- region-end region-start)))
12045 (delete-region
12046 (and (org-back-to-heading t) (point))
12047 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12048 (when (featurep 'org-inlinetask)
12049 (org-inlinetask-remove-END-maybe))
12050 (setq org-markers-to-move nil)
12051 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12053 (defun org-refile-goto-last-stored ()
12054 "Go to the location where the last refile was stored."
12055 (interactive)
12056 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12057 (message "This is the location of the last refile"))
12059 (defun org-refile--get-location (refloc tbl)
12060 "When user refile to REFLOC, find the associated target in TBL.
12061 Also check `org-refile-target-table'."
12062 (car (delq
12064 (mapcar
12065 (lambda (r) (or (assoc r tbl)
12066 (assoc r org-refile-target-table)))
12067 (list (replace-regexp-in-string "/$" "" refloc)
12068 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12070 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12071 "Prompt the user for a refile location, using PROMPT.
12072 PROMPT should not be suffixed with a colon and a space, because
12073 this function appends the default value from
12074 `org-refile-history' automatically, if that is not empty."
12075 (let ((org-refile-targets org-refile-targets)
12076 (org-refile-use-outline-path org-refile-use-outline-path))
12077 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12078 (unless org-refile-target-table
12079 (user-error "No refile targets"))
12080 (let* ((cbuf (current-buffer))
12081 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12082 (cfunc (if (and org-refile-use-outline-path
12083 org-outline-path-complete-in-steps)
12084 #'org-olpath-completing-read
12085 #'completing-read))
12086 (extra (if org-refile-use-outline-path "/" ""))
12087 (cbnex (concat (buffer-name) extra))
12088 (filename (and cfn (expand-file-name cfn)))
12089 (tbl (mapcar
12090 (lambda (x)
12091 (if (and (not (member org-refile-use-outline-path
12092 '(file full-file-path)))
12093 (not (equal filename (nth 1 x))))
12094 (cons (concat (car x) extra " ("
12095 (file-name-nondirectory (nth 1 x)) ")")
12096 (cdr x))
12097 (cons (concat (car x) extra) (cdr x))))
12098 org-refile-target-table))
12099 (completion-ignore-case t)
12100 cdef
12101 (prompt (concat prompt
12102 (or (and (car org-refile-history)
12103 (concat " (default " (car org-refile-history) ")"))
12104 (and (assoc cbnex tbl) (setq cdef cbnex)
12105 (concat " (default " cbnex ")"))) ": "))
12106 pa answ parent-target child parent old-hist)
12107 (setq old-hist org-refile-history)
12108 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12109 nil 'org-refile-history (or cdef (car org-refile-history))))
12110 (if (setq pa (org-refile--get-location answ tbl))
12111 (progn
12112 (org-refile-check-position pa)
12113 (when (or (not org-refile-history)
12114 (not (eq old-hist org-refile-history))
12115 (not (equal (car pa) (car org-refile-history))))
12116 (setq org-refile-history
12117 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12118 org-refile-history
12119 (cdr org-refile-history))))
12120 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12121 (pop org-refile-history)))
12123 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12124 (progn
12125 (setq parent (match-string 1 answ)
12126 child (match-string 2 answ))
12127 (setq parent-target (org-refile--get-location parent tbl))
12128 (when (and parent-target
12129 (or (eq new-nodes t)
12130 (and (eq new-nodes 'confirm)
12131 (y-or-n-p (format "Create new node \"%s\"? "
12132 child)))))
12133 (org-refile-new-child parent-target child)))
12134 (user-error "Invalid target location")))))
12136 (declare-function org-string-nw-p "org-macs" (s))
12137 (defun org-refile-check-position (refile-pointer)
12138 "Check if the refile pointer matches the headline to which it points."
12139 (let* ((file (nth 1 refile-pointer))
12140 (re (nth 2 refile-pointer))
12141 (pos (nth 3 refile-pointer))
12142 buffer)
12143 (if (and (not (markerp pos)) (not file))
12144 (user-error "Please indicate a target file in the refile path")
12145 (when (org-string-nw-p re)
12146 (setq buffer (if (markerp pos)
12147 (marker-buffer pos)
12148 (or (find-buffer-visiting file)
12149 (find-file-noselect file))))
12150 (with-current-buffer buffer
12151 (org-with-wide-buffer
12152 (goto-char pos)
12153 (beginning-of-line 1)
12154 (unless (looking-at-p re)
12155 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12157 (defun org-refile-new-child (parent-target child)
12158 "Use refile target PARENT-TARGET to add new CHILD below it."
12159 (unless parent-target
12160 (error "Cannot find parent for new node"))
12161 (let ((file (nth 1 parent-target))
12162 (pos (nth 3 parent-target))
12163 level)
12164 (with-current-buffer (or (find-buffer-visiting file)
12165 (find-file-noselect file))
12166 (org-with-wide-buffer
12167 (if pos
12168 (goto-char pos)
12169 (goto-char (point-max))
12170 (unless (bolp) (newline)))
12171 (when (looking-at org-outline-regexp)
12172 (setq level (funcall outline-level))
12173 (org-end-of-subtree t t))
12174 (org-back-over-empty-lines)
12175 (insert "\n" (make-string
12176 (if pos (org-get-valid-level level 1) 1) ?*)
12177 " " child "\n")
12178 (beginning-of-line 0)
12179 (list (concat (car parent-target) "/" child) file "" (point))))))
12181 (defun org-olpath-completing-read (prompt collection &rest args)
12182 "Read an outline path like a file name."
12183 (let ((thetable collection))
12184 (apply #'completing-read
12185 prompt
12186 (lambda (string predicate &optional flag)
12187 (cond
12188 ((eq flag nil) (try-completion string thetable))
12189 ((eq flag t)
12190 (let ((l (length string)))
12191 (mapcar (lambda (x)
12192 (let ((r (substring x l))
12193 (f (if (string-match " ([^)]*)$" x)
12194 (match-string 0 x)
12195 "")))
12196 (if (string-match "/" r)
12197 (concat string (substring r 0 (match-end 0)) f)
12198 x)))
12199 (all-completions string thetable predicate))))
12200 ;; Exact match?
12201 ((eq flag 'lambda) (assoc string thetable))))
12202 args)))
12204 ;;;; Dynamic blocks
12206 (defun org-find-dblock (name)
12207 "Find the first dynamic block with name NAME in the buffer.
12208 If not found, stay at current position and return nil."
12209 (let ((case-fold-search t) pos)
12210 (save-excursion
12211 (goto-char (point-min))
12212 (setq pos (and (re-search-forward
12213 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12214 (match-beginning 0))))
12215 (when pos (goto-char pos))
12216 pos))
12218 (defun org-create-dblock (plist)
12219 "Create a dynamic block section, with parameters taken from PLIST.
12220 PLIST must contain a :name entry which is used as the name of the block."
12221 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12222 (end-of-line 1)
12223 (newline))
12224 (let ((col (current-column))
12225 (name (plist-get plist :name)))
12226 (insert "#+BEGIN: " name)
12227 (while plist
12228 (if (eq (car plist) :name)
12229 (setq plist (cddr plist))
12230 (insert " " (prin1-to-string (pop plist)))))
12231 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12232 (beginning-of-line -2)))
12234 (defun org-prepare-dblock ()
12235 "Prepare dynamic block for refresh.
12236 This empties the block, puts the cursor at the insert position and returns
12237 the property list including an extra property :name with the block name."
12238 (unless (looking-at org-dblock-start-re)
12239 (user-error "Not at a dynamic block"))
12240 (let* ((begdel (1+ (match-end 0)))
12241 (name (org-no-properties (match-string 1)))
12242 (params (append (list :name name)
12243 (read (concat "(" (match-string 3) ")")))))
12244 (save-excursion
12245 (beginning-of-line 1)
12246 (skip-chars-forward " \t")
12247 (setq params (plist-put params :indentation-column (current-column))))
12248 (unless (re-search-forward org-dblock-end-re nil t)
12249 (error "Dynamic block not terminated"))
12250 (setq params
12251 (append params
12252 (list :content (buffer-substring
12253 begdel (match-beginning 0)))))
12254 (delete-region begdel (match-beginning 0))
12255 (goto-char begdel)
12256 (open-line 1)
12257 params))
12259 (defun org-map-dblocks (&optional command)
12260 "Apply COMMAND to all dynamic blocks in the current buffer.
12261 If COMMAND is not given, use `org-update-dblock'."
12262 (let ((cmd (or command 'org-update-dblock)))
12263 (save-excursion
12264 (goto-char (point-min))
12265 (while (re-search-forward org-dblock-start-re nil t)
12266 (goto-char (match-beginning 0))
12267 (save-excursion
12268 (condition-case nil
12269 (funcall cmd)
12270 (error (message "Error during update of dynamic block"))))
12271 (unless (re-search-forward org-dblock-end-re nil t)
12272 (error "Dynamic block not terminated"))))))
12274 (defun org-dblock-update (&optional arg)
12275 "User command for updating dynamic blocks.
12276 Update the dynamic block at point. With prefix ARG, update all dynamic
12277 blocks in the buffer."
12278 (interactive "P")
12279 (if arg
12280 (org-update-all-dblocks)
12281 (or (looking-at org-dblock-start-re)
12282 (org-beginning-of-dblock))
12283 (org-update-dblock)))
12285 (defun org-update-dblock ()
12286 "Update the dynamic block at point.
12287 This means to empty the block, parse for parameters and then call
12288 the correct writing function."
12289 (interactive)
12290 (save-excursion
12291 (let* ((win (selected-window))
12292 (pos (point))
12293 (line (org-current-line))
12294 (params (org-prepare-dblock))
12295 (name (plist-get params :name))
12296 (indent (plist-get params :indentation-column))
12297 (cmd (intern (concat "org-dblock-write:" name))))
12298 (message "Updating dynamic block `%s' at line %d..." name line)
12299 (funcall cmd params)
12300 (message "Updating dynamic block `%s' at line %d...done" name line)
12301 (goto-char pos)
12302 (when (and indent (> indent 0))
12303 (setq indent (make-string indent ?\ ))
12304 (save-excursion
12305 (select-window win)
12306 (org-beginning-of-dblock)
12307 (forward-line 1)
12308 (while (not (looking-at org-dblock-end-re))
12309 (insert indent)
12310 (beginning-of-line 2))
12311 (when (looking-at org-dblock-end-re)
12312 (and (looking-at "[ \t]+")
12313 (replace-match ""))
12314 (insert indent)))))))
12316 (defun org-beginning-of-dblock ()
12317 "Find the beginning of the dynamic block at point.
12318 Error if there is no such block at point."
12319 (let ((pos (point))
12320 beg)
12321 (end-of-line 1)
12322 (if (and (re-search-backward org-dblock-start-re nil t)
12323 (setq beg (match-beginning 0))
12324 (re-search-forward org-dblock-end-re nil t)
12325 (> (match-end 0) pos))
12326 (goto-char beg)
12327 (goto-char pos)
12328 (error "Not in a dynamic block"))))
12330 (defun org-update-all-dblocks ()
12331 "Update all dynamic blocks in the buffer.
12332 This function can be used in a hook."
12333 (interactive)
12334 (when (derived-mode-p 'org-mode)
12335 (org-map-dblocks 'org-update-dblock)))
12338 ;;;; Completion
12340 (declare-function org-export-backend-options "ox" (cl-x) t)
12341 (defun org-get-export-keywords ()
12342 "Return a list of all currently understood export keywords.
12343 Export keywords include options, block names, attributes and
12344 keywords relative to each registered export back-end."
12345 (let (keywords)
12346 (dolist (backend
12347 (bound-and-true-p org-export-registered-backends)
12348 (delq nil keywords))
12349 ;; Back-end name (for keywords, like #+LATEX:)
12350 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12351 (dolist (option-entry (org-export-backend-options backend))
12352 ;; Back-end options.
12353 (push (nth 1 option-entry) keywords)))))
12355 (defconst org-options-keywords
12356 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12357 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12358 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12359 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12360 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12362 (defcustom org-structure-template-alist
12363 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12364 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12365 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12366 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12367 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12368 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12369 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12370 ("L" "#+LaTeX: ")
12371 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12372 ("H" "#+HTML: ")
12373 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12374 ("A" "#+ASCII: ")
12375 ("i" "#+INDEX: ?")
12376 ("I" "#+INCLUDE: %file ?"))
12377 "Structure completion elements.
12378 This is a list of abbreviation keys and values. The value gets inserted
12379 if you type `<' followed by the key and then press the completion key,
12380 usually `TAB'. %file will be replaced by a file name after prompting
12381 for the file using completion. The cursor will be placed at the position
12382 of the `?' in the template.
12383 There are two templates for each key, the first uses the original Org syntax,
12384 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12385 the default when the /org-mtags.el/ module has been loaded. See also the
12386 variable `org-mtags-prefer-muse-templates'."
12387 :group 'org-completion
12388 :type '(repeat
12389 (list
12390 (string :tag "Key")
12391 (string :tag "Template")))
12392 :version "25.1"
12393 :package-version '(Org . "8.3"))
12395 (defun org-try-structure-completion ()
12396 "Try to complete a structure template before point.
12397 This looks for strings like \"<e\" on an otherwise empty line and
12398 expands them."
12399 (let ((l (buffer-substring (point-at-bol) (point)))
12401 (when (and (looking-at "[ \t]*$")
12402 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12403 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12404 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12405 (match-beginning 1)) a)
12406 t)))
12408 (defun org-complete-expand-structure-template (start cell)
12409 "Expand a structure template."
12410 (let ((rpl (nth 1 cell))
12411 (ind ""))
12412 (delete-region start (point))
12413 (when (string-match "\\`[ \t]*#\\+" rpl)
12414 (cond
12415 ((bolp))
12416 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12417 (setq ind (buffer-substring (point-at-bol) (point))))
12418 (t (newline))))
12419 (setq start (point))
12420 (when (string-match "%file" rpl)
12421 (setq rpl (replace-match
12422 (concat
12423 "\""
12424 (save-match-data
12425 (abbreviate-file-name (read-file-name "Include file: ")))
12426 "\"")
12427 t t rpl)))
12428 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12429 (concat "\n" ind)))
12430 (insert rpl)
12431 (when (re-search-backward "\\?" start t) (delete-char 1))))
12433 ;;;; TODO, DEADLINE, Comments
12435 (defun org-toggle-comment ()
12436 "Change the COMMENT state of an entry."
12437 (interactive)
12438 (save-excursion
12439 (org-back-to-heading)
12440 (looking-at org-complex-heading-regexp)
12441 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12442 (skip-chars-forward " \t")
12443 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12444 (if (org-in-commented-heading-p t)
12445 (delete-region (point)
12446 (progn (search-forward " " (line-end-position) 'move)
12447 (skip-chars-forward " \t")
12448 (point)))
12449 (insert org-comment-string)
12450 (unless (eolp) (insert " ")))))
12452 (defvar org-last-todo-state-is-todo nil
12453 "This is non-nil when the last TODO state change led to a TODO state.
12454 If the last change removed the TODO tag or switched to DONE, then
12455 this is nil.")
12457 (defvar org-setting-tags nil) ; dynamically skipped
12459 (defvar org-todo-setup-filter-hook nil
12460 "Hook for functions that pre-filter todo specs.
12461 Each function takes a todo spec and returns either nil or the spec
12462 transformed into canonical form." )
12464 (defvar org-todo-get-default-hook nil
12465 "Hook for functions that get a default item for todo.
12466 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12467 nil or a string to be used for the todo mark." )
12469 (defvar org-agenda-headline-snapshot-before-repeat)
12471 (defun org-current-effective-time ()
12472 "Return current time adjusted for `org-extend-today-until' variable."
12473 (let* ((ct (org-current-time))
12474 (dct (decode-time ct))
12475 (ct1
12476 (cond
12477 (org-use-last-clock-out-time-as-effective-time
12478 (or (org-clock-get-last-clock-out-time) ct))
12479 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12480 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12481 (t ct))))
12482 ct1))
12484 (defun org-todo-yesterday (&optional arg)
12485 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12486 (interactive "P")
12487 (if (eq major-mode 'org-agenda-mode)
12488 (apply 'org-agenda-todo-yesterday arg)
12489 (let* ((org-use-effective-time t)
12490 (hour (nth 2 (decode-time (org-current-time))))
12491 (org-extend-today-until (1+ hour)))
12492 (org-todo arg))))
12494 (defvar org-block-entry-blocking ""
12495 "First entry preventing the TODO state change.")
12497 (defun org-cancel-repeater ()
12498 "Cancel a repeater by setting its numeric value to zero."
12499 (interactive)
12500 (save-excursion
12501 (org-back-to-heading t)
12502 (let ((bound1 (point))
12503 (bound0 (save-excursion (outline-next-heading) (point))))
12504 (when (and (re-search-forward
12505 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12506 org-deadline-time-regexp "\\)\\|\\("
12507 org-ts-regexp "\\)")
12508 bound0 t)
12509 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12510 bound1 t))
12511 (replace-match "0" t nil nil 1)))))
12513 (defvar org-state) ;; dynamically scoped into this function
12514 (defun org-todo (&optional arg)
12515 "Change the TODO state of an item.
12516 The state of an item is given by a keyword at the start of the heading,
12517 like
12518 *** TODO Write paper
12519 *** DONE Call mom
12521 The different keywords are specified in the variable `org-todo-keywords'.
12522 By default the available states are \"TODO\" and \"DONE\".
12523 So for this example: when the item starts with TODO, it is changed to DONE.
12524 When it starts with DONE, the DONE is removed. And when neither TODO nor
12525 DONE are present, add TODO at the beginning of the heading.
12527 With \\[universal-argument] prefix arg, use completion to determine the new \
12528 state.
12529 With numeric prefix arg, switch to that state.
12530 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12531 keywords (nextset).
12532 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12533 With a numeric prefix arg of 0, inhibit note taking for the change.
12534 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12536 When called through ELisp, arg is also interpreted in the following way:
12537 `none' -> empty state
12538 \"\"(empty string) -> switch to empty state
12539 `done' -> switch to DONE
12540 `nextset' -> switch to the next set of keywords
12541 `previousset' -> switch to the previous set of keywords
12542 \"WAITING\" -> switch to the specified keyword, but only if it
12543 really is a member of `org-todo-keywords'."
12544 (interactive "P")
12545 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12546 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12547 'region-start-level 'region))
12548 org-loop-over-headlines-in-active-region)
12549 (org-map-entries
12550 `(org-todo ,arg)
12551 org-loop-over-headlines-in-active-region
12552 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12553 (when (equal arg '(16)) (setq arg 'nextset))
12554 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12555 (let ((org-blocker-hook org-blocker-hook)
12556 commentp
12557 case-fold-search)
12558 (when (equal arg '(64))
12559 (setq arg nil org-blocker-hook nil))
12560 (when (and org-blocker-hook
12561 (or org-inhibit-blocking
12562 (org-entry-get nil "NOBLOCKING")))
12563 (setq org-blocker-hook nil))
12564 (save-excursion
12565 (catch 'exit
12566 (org-back-to-heading t)
12567 (when (org-in-commented-heading-p t)
12568 (org-toggle-comment)
12569 (setq commentp t))
12570 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12571 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12572 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12573 (let* ((match-data (match-data))
12574 (startpos (point-at-bol))
12575 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12576 (org-log-done org-log-done)
12577 (org-log-repeat org-log-repeat)
12578 (org-todo-log-states org-todo-log-states)
12579 (org-inhibit-logging
12580 (if (equal arg 0)
12581 (progn (setq arg nil) 'note) org-inhibit-logging))
12582 (this (match-string 1))
12583 (hl-pos (match-beginning 0))
12584 (head (org-get-todo-sequence-head this))
12585 (ass (assoc head org-todo-kwd-alist))
12586 (interpret (nth 1 ass))
12587 (done-word (nth 3 ass))
12588 (final-done-word (nth 4 ass))
12589 (org-last-state (or this ""))
12590 (completion-ignore-case t)
12591 (member (member this org-todo-keywords-1))
12592 (tail (cdr member))
12593 (org-state (cond
12594 ((and org-todo-key-trigger
12595 (or (and (equal arg '(4))
12596 (eq org-use-fast-todo-selection 'prefix))
12597 (and (not arg) org-use-fast-todo-selection
12598 (not (eq org-use-fast-todo-selection
12599 'prefix)))))
12600 ;; Use fast selection
12601 (org-fast-todo-selection))
12602 ((and (equal arg '(4))
12603 (or (not org-use-fast-todo-selection)
12604 (not org-todo-key-trigger)))
12605 ;; Read a state with completion
12606 (completing-read
12607 "State: " (mapcar #'list org-todo-keywords-1)
12608 nil t))
12609 ((eq arg 'right)
12610 (if this
12611 (if tail (car tail) nil)
12612 (car org-todo-keywords-1)))
12613 ((eq arg 'left)
12614 (unless (equal member org-todo-keywords-1)
12615 (if this
12616 (nth (- (length org-todo-keywords-1)
12617 (length tail) 2)
12618 org-todo-keywords-1)
12619 (org-last org-todo-keywords-1))))
12620 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12621 (setq arg nil))) ; hack to fall back to cycling
12622 (arg
12623 ;; user or caller requests a specific state
12624 (cond
12625 ((equal arg "") nil)
12626 ((eq arg 'none) nil)
12627 ((eq arg 'done) (or done-word (car org-done-keywords)))
12628 ((eq arg 'nextset)
12629 (or (car (cdr (member head org-todo-heads)))
12630 (car org-todo-heads)))
12631 ((eq arg 'previousset)
12632 (let ((org-todo-heads (reverse org-todo-heads)))
12633 (or (car (cdr (member head org-todo-heads)))
12634 (car org-todo-heads))))
12635 ((car (member arg org-todo-keywords-1)))
12636 ((stringp arg)
12637 (user-error "State `%s' not valid in this file" arg))
12638 ((nth (1- (prefix-numeric-value arg))
12639 org-todo-keywords-1))))
12640 ((null member) (or head (car org-todo-keywords-1)))
12641 ((equal this final-done-word) nil) ;; -> make empty
12642 ((null tail) nil) ;; -> first entry
12643 ((memq interpret '(type priority))
12644 (if (eq this-command last-command)
12645 (car tail)
12646 (if (> (length tail) 0)
12647 (or done-word (car org-done-keywords))
12648 nil)))
12650 (car tail))))
12651 (org-state (or
12652 (run-hook-with-args-until-success
12653 'org-todo-get-default-hook org-state org-last-state)
12654 org-state))
12655 (next (if org-state (concat " " org-state " ") " "))
12656 (change-plist (list :type 'todo-state-change :from this :to org-state
12657 :position startpos))
12658 dolog now-done-p)
12659 (when org-blocker-hook
12660 (setq org-last-todo-state-is-todo
12661 (not (member this org-done-keywords)))
12662 (unless (save-excursion
12663 (save-match-data
12664 (org-with-wide-buffer
12665 (run-hook-with-args-until-failure
12666 'org-blocker-hook change-plist))))
12667 (if (called-interactively-p 'interactive)
12668 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12669 this org-state org-block-entry-blocking)
12670 ;; fail silently
12671 (message "TODO state change from %s to %s blocked (by \"%s\")"
12672 this org-state org-block-entry-blocking)
12673 (throw 'exit nil))))
12674 (store-match-data match-data)
12675 (replace-match next t t)
12676 (cond ((equal this org-state)
12677 (message "TODO state was already %s" (org-trim next)))
12678 ((pos-visible-in-window-p hl-pos)
12679 (message "TODO state changed to %s" (org-trim next))))
12680 (unless head
12681 (setq head (org-get-todo-sequence-head org-state)
12682 ass (assoc head org-todo-kwd-alist)
12683 interpret (nth 1 ass)
12684 done-word (nth 3 ass)
12685 final-done-word (nth 4 ass)))
12686 (when (memq arg '(nextset previousset))
12687 (message "Keyword-Set %d/%d: %s"
12688 (- (length org-todo-sets) -1
12689 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12690 (length org-todo-sets)
12691 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12692 (setq org-last-todo-state-is-todo
12693 (not (member org-state org-done-keywords)))
12694 (setq now-done-p (and (member org-state org-done-keywords)
12695 (not (member this org-done-keywords))))
12696 (and logging (org-local-logging logging))
12697 (when (and (or org-todo-log-states org-log-done)
12698 (not (eq org-inhibit-logging t))
12699 (not (memq arg '(nextset previousset))))
12700 ;; we need to look at recording a time and note
12701 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12702 (nth 2 (assoc this org-todo-log-states))))
12703 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12704 (setq dolog 'time))
12705 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12706 (and org-state
12707 (member org-state org-not-done-keywords)
12708 (not (member this org-not-done-keywords))))
12709 ;; This is now a todo state and was not one before
12710 ;; If there was a CLOSED time stamp, get rid of it.
12711 (org-add-planning-info nil nil 'closed))
12712 (when (and now-done-p org-log-done)
12713 ;; It is now done, and it was not done before
12714 (org-add-planning-info 'closed (org-current-effective-time))
12715 (when (and (not dolog) (eq 'note org-log-done))
12716 (org-add-log-setup 'done org-state this 'note)))
12717 (when (and org-state dolog)
12718 ;; This is a non-nil state, and we need to log it
12719 (org-add-log-setup 'state org-state this dolog)))
12720 ;; Fixup tag positioning
12721 (org-todo-trigger-tag-changes org-state)
12722 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12723 (when org-provide-todo-statistics
12724 (org-update-parent-todo-statistics))
12725 (run-hooks 'org-after-todo-state-change-hook)
12726 (when (and arg (not (member org-state org-done-keywords)))
12727 (setq head (org-get-todo-sequence-head org-state)))
12728 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12729 ;; Do we need to trigger a repeat?
12730 (when now-done-p
12731 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12732 ;; This is for the agenda, take a snapshot of the headline.
12733 (save-match-data
12734 (setq org-agenda-headline-snapshot-before-repeat
12735 (org-get-heading))))
12736 (org-auto-repeat-maybe org-state))
12737 ;; Fixup cursor location if close to the keyword
12738 (when (and (outline-on-heading-p)
12739 (not (bolp))
12740 (save-excursion (beginning-of-line 1)
12741 (looking-at org-todo-line-regexp))
12742 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12743 (goto-char (or (match-end 2) (match-end 1)))
12744 (and (looking-at " ") (just-one-space)))
12745 (when org-trigger-hook
12746 (save-excursion
12747 (run-hook-with-args 'org-trigger-hook change-plist)))
12748 (when commentp (org-toggle-comment))))))))
12750 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12751 "Block turning an entry into a TODO, using the hierarchy.
12752 This checks whether the current task should be blocked from state
12753 changes. Such blocking occurs when:
12755 1. The task has children which are not all in a completed state.
12757 2. A task has a parent with the property :ORDERED:, and there
12758 are siblings prior to the current task with incomplete
12759 status.
12761 3. The parent of the task is blocked because it has siblings that should
12762 be done first, or is child of a block grandparent TODO entry."
12764 (if (not org-enforce-todo-dependencies)
12765 t ; if locally turned off don't block
12766 (catch 'dont-block
12767 ;; If this is not a todo state change, or if this entry is already DONE,
12768 ;; do not block
12769 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12770 (member (plist-get change-plist :from)
12771 (cons 'done org-done-keywords))
12772 (member (plist-get change-plist :to)
12773 (cons 'todo org-not-done-keywords))
12774 (not (plist-get change-plist :to)))
12775 (throw 'dont-block t))
12776 ;; If this task has children, and any are undone, it's blocked
12777 (save-excursion
12778 (org-back-to-heading t)
12779 (let ((this-level (funcall outline-level)))
12780 (outline-next-heading)
12781 (let ((child-level (funcall outline-level)))
12782 (while (and (not (eobp))
12783 (> child-level this-level))
12784 ;; this todo has children, check whether they are all
12785 ;; completed
12786 (when (and (not (org-entry-is-done-p))
12787 (org-entry-is-todo-p))
12788 (setq org-block-entry-blocking (org-get-heading))
12789 (throw 'dont-block nil))
12790 (outline-next-heading)
12791 (setq child-level (funcall outline-level))))))
12792 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12793 ;; any previous siblings are undone, it's blocked
12794 (save-excursion
12795 (org-back-to-heading t)
12796 (let* ((pos (point))
12797 (parent-pos (and (org-up-heading-safe) (point))))
12798 (unless parent-pos (throw 'dont-block t)) ; no parent
12799 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12800 (forward-line 1)
12801 (re-search-forward org-not-done-heading-regexp pos t))
12802 (setq org-block-entry-blocking (match-string 0))
12803 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12804 ;; Search further up the hierarchy, to see if an ancestor is blocked
12805 (while t
12806 (goto-char parent-pos)
12807 (unless (looking-at org-not-done-heading-regexp)
12808 (throw 'dont-block t)) ; do not block, parent is not a TODO
12809 (setq pos (point))
12810 (setq parent-pos (and (org-up-heading-safe) (point)))
12811 (unless parent-pos (throw 'dont-block t)) ; no parent
12812 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12813 (forward-line 1)
12814 (re-search-forward org-not-done-heading-regexp pos t)
12815 (setq org-block-entry-blocking (org-get-heading)))
12816 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12818 (defcustom org-track-ordered-property-with-tag nil
12819 "Should the ORDERED property also be shown as a tag?
12820 The ORDERED property decides if an entry should require subtasks to be
12821 completed in sequence. Since a property is not very visible, setting
12822 this option means that toggling the ORDERED property with the command
12823 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12824 not relevant for the behavior, but it makes things more visible.
12826 Note that toggling the tag with tags commands will not change the property
12827 and therefore not influence behavior!
12829 This can be t, meaning the tag ORDERED should be used, It can also be a
12830 string to select a different tag for this task."
12831 :group 'org-todo
12832 :type '(choice
12833 (const :tag "No tracking" nil)
12834 (const :tag "Track with ORDERED tag" t)
12835 (string :tag "Use other tag")))
12837 (defun org-toggle-ordered-property ()
12838 "Toggle the ORDERED property of the current entry.
12839 For better visibility, you can track the value of this property with a tag.
12840 See variable `org-track-ordered-property-with-tag'."
12841 (interactive)
12842 (let* ((t1 org-track-ordered-property-with-tag)
12843 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12844 (save-excursion
12845 (org-back-to-heading)
12846 (if (org-entry-get nil "ORDERED")
12847 (progn
12848 (org-delete-property "ORDERED")
12849 (and tag (org-toggle-tag tag 'off))
12850 (message "Subtasks can be completed in arbitrary order"))
12851 (org-entry-put nil "ORDERED" "t")
12852 (and tag (org-toggle-tag tag 'on))
12853 (message "Subtasks must be completed in sequence")))))
12855 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12856 (defun org-block-todo-from-checkboxes (change-plist)
12857 "Block turning an entry into a TODO, using checkboxes.
12858 This checks whether the current task should be blocked from state
12859 changes because there are unchecked boxes in this entry."
12860 (if (not org-enforce-todo-checkbox-dependencies)
12861 t ; if locally turned off don't block
12862 (catch 'dont-block
12863 ;; If this is not a todo state change, or if this entry is already DONE,
12864 ;; do not block
12865 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12866 (member (plist-get change-plist :from)
12867 (cons 'done org-done-keywords))
12868 (member (plist-get change-plist :to)
12869 (cons 'todo org-not-done-keywords))
12870 (not (plist-get change-plist :to)))
12871 (throw 'dont-block t))
12872 ;; If this task has checkboxes that are not checked, it's blocked
12873 (save-excursion
12874 (org-back-to-heading t)
12875 (let ((beg (point)) end)
12876 (outline-next-heading)
12877 (setq end (point))
12878 (goto-char beg)
12879 (when (org-list-search-forward
12880 (concat (org-item-beginning-re)
12881 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12882 "\\[[- ]\\]")
12883 end t)
12884 (when (boundp 'org-blocked-by-checkboxes)
12885 (setq org-blocked-by-checkboxes t))
12886 (throw 'dont-block nil))))
12887 t))) ; do not block
12889 (defun org-entry-blocked-p ()
12890 "Non-nil if entry at point is blocked."
12891 (and (not (org-entry-get nil "NOBLOCKING"))
12892 (member (org-entry-get nil "TODO") org-not-done-keywords)
12893 (not (run-hook-with-args-until-failure
12894 'org-blocker-hook
12895 (list :type 'todo-state-change
12896 :position (point)
12897 :from 'todo
12898 :to 'done)))))
12900 (defun org-update-statistics-cookies (all)
12901 "Update the statistics cookie, either from TODO or from checkboxes.
12902 This should be called with the cursor in a line with a statistics
12903 cookie. When called with a \\[universal-argument] prefix, update
12904 all statistics cookies in the buffer."
12905 (interactive "P")
12906 (if all
12907 (progn
12908 (org-update-checkbox-count 'all)
12909 (org-map-entries 'org-update-parent-todo-statistics))
12910 (if (not (org-at-heading-p))
12911 (org-update-checkbox-count)
12912 (let ((pos (point-marker))
12913 end l1 l2)
12914 (ignore-errors (org-back-to-heading t))
12915 (if (not (org-at-heading-p))
12916 (org-update-checkbox-count)
12917 (setq l1 (org-outline-level))
12918 (setq end (save-excursion
12919 (outline-next-heading)
12920 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12921 (point)))
12922 (if (and (save-excursion
12923 (re-search-forward
12924 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12925 (not (save-excursion (re-search-forward
12926 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12927 (org-update-checkbox-count)
12928 (if (and l2 (> l2 l1))
12929 (progn
12930 (goto-char end)
12931 (org-update-parent-todo-statistics))
12932 (goto-char pos)
12933 (beginning-of-line 1)
12934 (while (re-search-forward
12935 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12936 (point-at-eol) t)
12937 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12938 (goto-char pos)
12939 (move-marker pos nil)))))
12941 (defvar org-entry-property-inherited-from) ;; defined below
12942 (defun org-update-parent-todo-statistics ()
12943 "Update any statistics cookie in the parent of the current headline.
12944 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12945 the entire subtree and this will travel up the hierarchy and update
12946 statistics everywhere."
12947 (let* ((prop (save-excursion (org-up-heading-safe)
12948 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12949 (recursive (or (not org-hierarchical-todo-statistics)
12950 (and prop (string-match "\\<recursive\\>" prop))))
12951 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12953 (first t)
12954 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12955 level ltoggle l1 new ndel
12956 (cnt-all 0) (cnt-done 0) is-percent kwd
12957 checkbox-beg cookie-present)
12958 (catch 'exit
12959 (save-excursion
12960 (beginning-of-line 1)
12961 (setq ltoggle (funcall outline-level))
12962 ;; Three situations are to consider:
12964 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12965 ;; to the top-level ancestor on the headline;
12967 ;; 2. If parent has "recursive" property, repeat up to the
12968 ;; headline setting that property, taking inheritance into
12969 ;; account;
12971 ;; 3. Else, move up to direct parent and proceed only once.
12972 (while (and (setq level (org-up-heading-safe))
12973 (or recursive first)
12974 (>= (point) lim))
12975 (setq first nil cookie-present nil)
12976 (unless (and level
12977 (not (string-match
12978 "\\<checkbox\\>"
12979 (downcase (or (org-entry-get nil "COOKIE_DATA")
12980 "")))))
12981 (throw 'exit nil))
12982 (while (re-search-forward box-re (point-at-eol) t)
12983 (setq cnt-all 0 cnt-done 0 cookie-present t)
12984 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12985 (save-match-data
12986 (unless (outline-next-heading) (throw 'exit nil))
12987 (while (and (looking-at org-complex-heading-regexp)
12988 (> (setq l1 (length (match-string 1))) level))
12989 (setq kwd (and (or recursive (= l1 ltoggle))
12990 (match-string 2)))
12991 (if (or (eq org-provide-todo-statistics 'all-headlines)
12992 (and (eq org-provide-todo-statistics t)
12993 (or (member kwd org-done-keywords)))
12994 (and (listp org-provide-todo-statistics)
12995 (stringp (car org-provide-todo-statistics))
12996 (or (member kwd org-provide-todo-statistics)
12997 (member kwd org-done-keywords)))
12998 (and (listp org-provide-todo-statistics)
12999 (listp (car org-provide-todo-statistics))
13000 (or (member kwd (car org-provide-todo-statistics))
13001 (and (member kwd org-done-keywords)
13002 (member kwd (cadr org-provide-todo-statistics))))))
13003 (setq cnt-all (1+ cnt-all))
13004 (and (eq org-provide-todo-statistics t)
13006 (setq cnt-all (1+ cnt-all))))
13007 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13008 (member kwd org-done-keywords))
13009 (and (listp org-provide-todo-statistics)
13010 (listp (car org-provide-todo-statistics))
13011 (member kwd org-done-keywords)
13012 (member kwd (cadr org-provide-todo-statistics)))
13013 (and (listp org-provide-todo-statistics)
13014 (stringp (car org-provide-todo-statistics))
13015 (member kwd org-done-keywords)))
13016 (setq cnt-done (1+ cnt-done)))
13017 (outline-next-heading)))
13018 (setq new
13019 (if is-percent
13020 (format "[%d%%]" (floor (* 100.0 cnt-done)
13021 (max 1 cnt-all)))
13022 (format "[%d/%d]" cnt-done cnt-all))
13023 ndel (- (match-end 0) checkbox-beg))
13024 (goto-char checkbox-beg)
13025 (insert new)
13026 (delete-region (point) (+ (point) ndel))
13027 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13028 (when cookie-present
13029 (run-hook-with-args 'org-after-todo-statistics-hook
13030 cnt-done (- cnt-all cnt-done))))))
13031 (run-hooks 'org-todo-statistics-hook)))
13033 (defvar org-after-todo-statistics-hook nil
13034 "Hook that is called after a TODO statistics cookie has been updated.
13035 Each function is called with two arguments: the number of not-done entries
13036 and the number of done entries.
13038 For example, the following function, when added to this hook, will switch
13039 an entry to DONE when all children are done, and back to TODO when new
13040 entries are set to a TODO status. Note that this hook is only called
13041 when there is a statistics cookie in the headline!
13043 \(defun org-summary-todo (n-done n-not-done)
13044 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13045 \(let (org-log-done org-log-states) ; turn off logging
13046 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13049 (defvar org-todo-statistics-hook nil
13050 "Hook that is run whenever Org thinks TODO statistics should be updated.
13051 This hook runs even if there is no statistics cookie present, in which case
13052 `org-after-todo-statistics-hook' would not run.")
13054 (defun org-todo-trigger-tag-changes (state)
13055 "Apply the changes defined in `org-todo-state-tags-triggers'."
13056 (let ((l org-todo-state-tags-triggers)
13057 changes)
13058 (when (or (not state) (equal state ""))
13059 (setq changes (append changes (cdr (assoc "" l)))))
13060 (when (and (stringp state) (> (length state) 0))
13061 (setq changes (append changes (cdr (assoc state l)))))
13062 (when (member state org-not-done-keywords)
13063 (setq changes (append changes (cdr (assq 'todo l)))))
13064 (when (member state org-done-keywords)
13065 (setq changes (append changes (cdr (assq 'done l)))))
13066 (dolist (c changes)
13067 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13069 (defun org-local-logging (value)
13070 "Get logging settings from a property VALUE."
13071 ;; Directly set the variables, they are already local.
13072 (setq org-log-done nil
13073 org-log-repeat nil
13074 org-todo-log-states nil)
13075 (dolist (w (org-split-string value))
13076 (let (a)
13077 (cond
13078 ((setq a (assoc w org-startup-options))
13079 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13080 (set (nth 1 a) (nth 2 a))))
13081 ((setq a (org-extract-log-state-settings w))
13082 (and (member (car a) org-todo-keywords-1)
13083 (push a org-todo-log-states)))))))
13085 (defun org-get-todo-sequence-head (kwd)
13086 "Return the head of the TODO sequence to which KWD belongs.
13087 If KWD is not set, check if there is a text property remembering the
13088 right sequence."
13089 (let (p)
13090 (cond
13091 ((not kwd)
13092 (or (get-text-property (point-at-bol) 'org-todo-head)
13093 (progn
13094 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13095 nil (point-at-eol)))
13096 (get-text-property p 'org-todo-head))))
13097 ((not (member kwd org-todo-keywords-1))
13098 (car org-todo-keywords-1))
13099 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13101 (defun org-fast-todo-selection ()
13102 "Fast TODO keyword selection with single keys.
13103 Returns the new TODO keyword, or nil if no state change should occur."
13104 (let* ((fulltable org-todo-key-alist)
13105 (done-keywords org-done-keywords) ;; needed for the faces.
13106 (maxlen (apply 'max (mapcar
13107 (lambda (x)
13108 (if (stringp (car x)) (string-width (car x)) 0))
13109 fulltable)))
13110 (expert nil)
13111 (fwidth (+ maxlen 3 1 3))
13112 (ncol (/ (- (window-width) 4) fwidth))
13113 tg cnt e c tbl
13114 groups ingroup)
13115 (save-excursion
13116 (save-window-excursion
13117 (if expert
13118 (set-buffer (get-buffer-create " *Org todo*"))
13119 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13120 (erase-buffer)
13121 (setq-local org-done-keywords done-keywords)
13122 (setq tbl fulltable cnt 0)
13123 (while (setq e (pop tbl))
13124 (cond
13125 ((equal e '(:startgroup))
13126 (push '() groups) (setq ingroup t)
13127 (unless (= cnt 0)
13128 (setq cnt 0)
13129 (insert "\n"))
13130 (insert "{ "))
13131 ((equal e '(:endgroup))
13132 (setq ingroup nil cnt 0)
13133 (insert "}\n"))
13134 ((equal e '(:newline))
13135 (unless (= cnt 0)
13136 (setq cnt 0)
13137 (insert "\n")
13138 (setq e (car tbl))
13139 (while (equal (car tbl) '(:newline))
13140 (insert "\n")
13141 (setq tbl (cdr tbl)))))
13143 (setq tg (car e) c (cdr e))
13144 (when ingroup (push tg (car groups)))
13145 (setq tg (org-add-props tg nil 'face
13146 (org-get-todo-face tg)))
13147 (when (and (= cnt 0) (not ingroup)) (insert " "))
13148 (insert "[" c "] " tg (make-string
13149 (- fwidth 4 (length tg)) ?\ ))
13150 (when (= (setq cnt (1+ cnt)) ncol)
13151 (insert "\n")
13152 (when ingroup (insert " "))
13153 (setq cnt 0)))))
13154 (insert "\n")
13155 (goto-char (point-min))
13156 (unless expert (org-fit-window-to-buffer))
13157 (message "[a-z..]:Set [SPC]:clear")
13158 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13159 (cond
13160 ((or (= c ?\C-g)
13161 (and (= c ?q) (not (rassoc c fulltable))))
13162 (setq quit-flag t))
13163 ((= c ?\ ) nil)
13164 ((setq e (rassoc c fulltable) tg (car e))
13166 (t (setq quit-flag t)))))))
13168 (defun org-entry-is-todo-p ()
13169 (member (org-get-todo-state) org-not-done-keywords))
13171 (defun org-entry-is-done-p ()
13172 (member (org-get-todo-state) org-done-keywords))
13174 (defun org-get-todo-state ()
13175 "Return the TODO keyword of the current subtree."
13176 (save-excursion
13177 (org-back-to-heading t)
13178 (and (looking-at org-todo-line-regexp)
13179 (match-end 2)
13180 (match-string 2))))
13182 (defun org-at-date-range-p (&optional inactive-ok)
13183 "Non-nil if point is inside a date range.
13185 When optional argument INACTIVE-OK is non-nil, also consider
13186 inactive time ranges.
13188 When this function returns a non-nil value, match data is set
13189 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13190 on INACTIVE-OK."
13191 (interactive)
13192 (save-excursion
13193 (catch 'exit
13194 (let ((pos (point)))
13195 (skip-chars-backward "^[<\r\n")
13196 (skip-chars-backward "<[")
13197 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13198 (>= (match-end 0) pos)
13199 (throw 'exit t))
13200 (skip-chars-backward "^<[\r\n")
13201 (skip-chars-backward "<[")
13202 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13203 (>= (match-end 0) pos)
13204 (throw 'exit t)))
13205 nil)))
13207 (defun org-get-repeat (&optional tagline)
13208 "Check if there is a deadline/schedule with repeater in this entry."
13209 (save-match-data
13210 (save-excursion
13211 (org-back-to-heading t)
13212 (and (re-search-forward (if tagline
13213 (concat tagline "\\s-*" org-repeat-re)
13214 org-repeat-re)
13215 (org-entry-end-position) t)
13216 (match-string-no-properties 1)))))
13218 (defvar org-last-changed-timestamp)
13219 (defvar org-last-inserted-timestamp)
13220 (defvar org-log-post-message)
13221 (defvar org-log-note-purpose)
13222 (defvar org-log-note-how nil)
13223 (defvar org-log-note-extra)
13224 (defun org-auto-repeat-maybe (done-word)
13225 "Check if the current headline contains a repeated time-stamp.
13227 If yes, set TODO state back to what it was and change the base date
13228 of repeating deadline/scheduled time stamps to new date.
13230 This function is run automatically after each state change to a DONE state."
13231 (let* ((repeat (org-get-repeat))
13232 (aa (assoc org-last-state org-todo-kwd-alist))
13233 (interpret (nth 1 aa))
13234 (head (nth 2 aa))
13235 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13236 (msg "Entry repeats: ")
13237 (org-log-done nil)
13238 (org-todo-log-states nil))
13239 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13240 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13241 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13242 org-todo-repeat-to-state)))
13243 (unless (and to-state (member to-state org-todo-keywords-1))
13244 (setq to-state (if (eq interpret 'type) org-last-state head)))
13245 (org-todo to-state))
13246 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13247 (org-entry-put nil "LAST_REPEAT" (format-time-string
13248 (org-time-stamp-format t t))))
13249 (when org-log-repeat
13250 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13251 (memq 'org-add-log-note post-command-hook))
13252 ;; We are already setup for some record.
13253 (when (eq org-log-repeat 'note)
13254 ;; Make sure we take a note, not only a time stamp.
13255 (setq org-log-note-how 'note))
13256 ;; Set up for taking a record.
13257 (org-add-log-setup 'state
13258 (or done-word (car org-done-keywords))
13259 org-last-state
13260 org-log-repeat)))
13261 (org-back-to-heading t)
13262 (org-add-planning-info nil nil 'closed)
13263 (let ((end (save-excursion (outline-next-heading) (point))))
13264 (while (re-search-forward org-ts-regexp end t)
13265 (when (save-match-data
13266 (or (org-at-planning-p)
13267 (org-at-property-p)
13268 (eq (org-element-type (save-excursion
13269 (backward-char)
13270 (org-element-context)))
13271 'timestamp)))
13272 (let ((type (cond ((match-end 1) org-scheduled-string)
13273 ((match-end 3) org-deadline-string)
13274 (t "Plain:")))
13275 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13276 (cond
13277 ((not
13278 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13279 ;; Time-stamps without a repeater are usually skipped.
13280 ;; However, a SCHEDULED time-stamp without one is
13281 ;; removed, as it is considered as no longer relevant.
13282 (when (equal type org-scheduled-string)
13283 (org-remove-timestamp-with-keyword type)))
13285 (let ((n (string-to-number (match-string 2 ts)))
13286 (what (match-string 3 ts)))
13287 (when (equal what "w") (setq n (* n 7) what "d"))
13288 (when (and (equal what "h")
13289 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13290 ts)))
13291 (user-error
13292 "Cannot repeat in Repeat in %d hour(s) because no hour \
13293 has been set"
13295 ;; Preparation, see if we need to modify the start
13296 ;; date for the change.
13297 (when (match-end 1)
13298 (let ((time (save-match-data (org-time-string-to-time ts))))
13299 (cond
13300 ((equal (match-string 1 ts) ".")
13301 ;; Shift starting date to today
13302 (org-timestamp-change
13303 (- (org-today) (time-to-days time))
13304 'day))
13305 ((equal (match-string 1 ts) "+")
13306 (let ((nshiftmax 10)
13307 (nshift 0))
13308 (while (or (= nshift 0)
13309 (not (time-less-p (current-time) time)))
13310 (when (= (cl-incf nshift) nshiftmax)
13311 (or (y-or-n-p
13312 (format "%d repeater intervals were not \
13313 enough to shift date past today. Continue? "
13314 nshift))
13315 (user-error "Abort")))
13316 (org-timestamp-change n (cdr (assoc what whata)))
13317 (org-at-timestamp-p t)
13318 (setq ts (match-string 1))
13319 (setq time
13320 (save-match-data
13321 (org-time-string-to-time ts)))))
13322 (org-timestamp-change (- n) (cdr (assoc what whata)))
13323 ;; Rematch, so that we have everything in
13324 ;; place for the real shift.
13325 (org-at-timestamp-p t)
13326 (setq ts (match-string 1))
13327 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13328 ts)))))
13329 (save-excursion
13330 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13331 (setq msg
13332 (concat
13333 msg type " " org-last-changed-timestamp " ")))))))))
13334 (setq org-log-post-message msg)
13335 (message "%s" msg))))
13337 (defun org-show-todo-tree (arg)
13338 "Make a compact tree which shows all headlines marked with TODO.
13339 The tree will show the lines where the regexp matches, and all higher
13340 headlines above the match.
13341 With a \\[universal-argument] prefix, prompt for a regexp to match.
13342 With a numeric prefix N, construct a sparse tree for the Nth element
13343 of `org-todo-keywords-1'."
13344 (interactive "P")
13345 (let ((case-fold-search nil)
13346 (kwd-re
13347 (cond ((null arg) org-not-done-regexp)
13348 ((equal arg '(4))
13349 (let ((kwd
13350 (completing-read "Keyword (or KWD1|KWD2|...): "
13351 (mapcar #'list org-todo-keywords-1))))
13352 (concat "\\("
13353 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13354 "\\)\\>")))
13355 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13356 (regexp-quote (nth (1- (prefix-numeric-value arg))
13357 org-todo-keywords-1)))
13358 (t (user-error "Invalid prefix argument: %s" arg)))))
13359 (message "%d TODO entries found"
13360 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13362 (defun org-deadline (arg &optional time)
13363 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13364 With one universal prefix argument, remove any deadline from the item.
13365 With two universal prefix arguments, prompt for a warning delay.
13366 With argument TIME, set the deadline at the corresponding date. TIME
13367 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13368 (interactive "P")
13369 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13370 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13371 'region-start-level 'region))
13372 org-loop-over-headlines-in-active-region)
13373 (org-map-entries
13374 `(org-deadline ',arg ,time)
13375 org-loop-over-headlines-in-active-region
13376 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13377 (let* ((old-date (org-entry-get nil "DEADLINE"))
13378 (old-date-time (when old-date (org-time-string-to-time old-date)))
13379 (repeater (and old-date
13380 (string-match
13381 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13382 old-date)
13383 (match-string 1 old-date))))
13384 (cond
13385 ((equal arg '(4))
13386 (when (and old-date org-log-redeadline)
13387 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13388 (org-remove-timestamp-with-keyword org-deadline-string)
13389 (message "Item no longer has a deadline."))
13390 ((equal arg '(16))
13391 (save-excursion
13392 (org-back-to-heading t)
13393 (if (re-search-forward
13394 org-deadline-time-regexp
13395 (save-excursion (outline-next-heading) (point)) t)
13396 (let* ((rpl0 (match-string 1))
13397 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13398 (replace-match
13399 (concat org-deadline-string
13400 " <" rpl
13401 (format " -%dd"
13402 (abs
13403 (- (time-to-days
13404 (save-match-data
13405 (org-read-date nil t nil "Warn starting from" old-date-time)))
13406 (time-to-days old-date-time))))
13407 ">") t t))
13408 (user-error "No deadline information to update"))))
13410 (org-add-planning-info 'deadline time 'closed)
13411 (when (and old-date
13412 org-log-redeadline
13413 (not (equal old-date org-last-inserted-timestamp)))
13414 (org-add-log-setup
13415 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13416 (when repeater
13417 (save-excursion
13418 (org-back-to-heading t)
13419 (when (re-search-forward (concat org-deadline-string " "
13420 org-last-inserted-timestamp)
13421 (save-excursion
13422 (outline-next-heading) (point)) t)
13423 (goto-char (1- (match-end 0)))
13424 (insert " " repeater)
13425 (setq org-last-inserted-timestamp
13426 (concat (substring org-last-inserted-timestamp 0 -1)
13427 " " repeater
13428 (substring org-last-inserted-timestamp -1))))))
13429 (message "Deadline on %s" org-last-inserted-timestamp))))))
13431 (defun org-schedule (arg &optional time)
13432 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13433 With one universal prefix argument, remove any scheduling date from the item.
13434 With two universal prefix arguments, prompt for a delay cookie.
13435 With argument TIME, scheduled at the corresponding date. TIME can
13436 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13437 (interactive "P")
13438 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13439 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13440 'region-start-level 'region))
13441 org-loop-over-headlines-in-active-region)
13442 (org-map-entries
13443 `(org-schedule ',arg ,time)
13444 org-loop-over-headlines-in-active-region
13445 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13446 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13447 (old-date-time (when old-date (org-time-string-to-time old-date)))
13448 (repeater (and old-date
13449 (string-match
13450 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13451 old-date)
13452 (match-string 1 old-date))))
13453 (cond
13454 ((equal arg '(4))
13455 (progn
13456 (when (and old-date org-log-reschedule)
13457 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13458 (org-remove-timestamp-with-keyword org-scheduled-string)
13459 (message "Item is no longer scheduled.")))
13460 ((equal arg '(16))
13461 (save-excursion
13462 (org-back-to-heading t)
13463 (if (re-search-forward
13464 org-scheduled-time-regexp
13465 (save-excursion (outline-next-heading) (point)) t)
13466 (let* ((rpl0 (match-string 1))
13467 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13468 (replace-match
13469 (concat org-scheduled-string
13470 " <" rpl
13471 (format " -%dd"
13472 (abs
13473 (- (time-to-days
13474 (save-match-data
13475 (org-read-date nil t nil "Delay until" old-date-time)))
13476 (time-to-days old-date-time))))
13477 ">") t t))
13478 (user-error "No scheduled information to update"))))
13480 (org-add-planning-info 'scheduled time 'closed)
13481 (when (and old-date
13482 org-log-reschedule
13483 (not (equal old-date org-last-inserted-timestamp)))
13484 (org-add-log-setup
13485 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13486 (when repeater
13487 (save-excursion
13488 (org-back-to-heading t)
13489 (when (re-search-forward (concat org-scheduled-string " "
13490 org-last-inserted-timestamp)
13491 (save-excursion
13492 (outline-next-heading) (point)) t)
13493 (goto-char (1- (match-end 0)))
13494 (insert " " repeater)
13495 (setq org-last-inserted-timestamp
13496 (concat (substring org-last-inserted-timestamp 0 -1)
13497 " " repeater
13498 (substring org-last-inserted-timestamp -1))))))
13499 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13501 (defun org-get-scheduled-time (pom &optional inherit)
13502 "Get the scheduled time as a time tuple, of a format suitable
13503 for calling org-schedule with, or if there is no scheduling,
13504 returns nil."
13505 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13506 (when time
13507 (apply 'encode-time (org-parse-time-string time)))))
13509 (defun org-get-deadline-time (pom &optional inherit)
13510 "Get the deadline as a time tuple, of a format suitable for
13511 calling org-deadline with, or if there is no scheduling, returns
13512 nil."
13513 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13514 (when time
13515 (apply 'encode-time (org-parse-time-string time)))))
13517 (defun org-remove-timestamp-with-keyword (keyword)
13518 "Remove all time stamps with KEYWORD in the current entry."
13519 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13520 beg)
13521 (save-excursion
13522 (org-back-to-heading t)
13523 (setq beg (point))
13524 (outline-next-heading)
13525 (while (re-search-backward re beg t)
13526 (replace-match "")
13527 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13528 (equal (char-before) ?\ ))
13529 (backward-delete-char 1)
13530 (when (string-match "^[ \t]*$" (buffer-substring
13531 (point-at-bol) (point-at-eol)))
13532 (delete-region (point-at-bol)
13533 (min (point-max) (1+ (point-at-eol))))))))))
13535 (defvar org-time-was-given) ; dynamically scoped parameter
13536 (defvar org-end-time-was-given) ; dynamically scoped parameter
13538 (defun org-at-planning-p ()
13539 "Non-nil when point is on a planning info line."
13540 ;; This is as accurate and faster than `org-element-at-point' since
13541 ;; planning info location is fixed in the section.
13542 (org-with-wide-buffer
13543 (beginning-of-line)
13544 (and (looking-at-p org-planning-line-re)
13545 (eq (point)
13546 (ignore-errors
13547 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13548 (org-back-to-heading t)
13549 (org-with-limited-levels (org-back-to-heading t)))
13550 (line-beginning-position 2))))))
13552 (defun org-add-planning-info (what &optional time &rest remove)
13553 "Insert new timestamp with keyword in the planning line.
13554 WHAT indicates what kind of time stamp to add. It is a symbol
13555 among `closed', `deadline', `scheduled' and nil. TIME indicates
13556 the time to use. If none is given, the user is prompted for
13557 a date. REMOVE indicates what kind of entries to remove. An old
13558 WHAT entry will also be removed."
13559 (let (org-time-was-given org-end-time-was-given default-time default-input)
13560 (catch 'exit
13561 (when (and (memq what '(scheduled deadline))
13562 (or (not time)
13563 (and (stringp time)
13564 (string-match "^[-+]+[0-9]" time))))
13565 ;; Try to get a default date/time from existing timestamp
13566 (save-excursion
13567 (org-back-to-heading t)
13568 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13569 (when (re-search-forward (if (eq what 'scheduled)
13570 org-scheduled-time-regexp
13571 org-deadline-time-regexp)
13572 end t)
13573 (setq ts (match-string 1)
13574 default-time (apply 'encode-time (org-parse-time-string ts))
13575 default-input (and ts (org-get-compact-tod ts)))))))
13576 (when what
13577 (setq time
13578 (if (stringp time)
13579 ;; This is a string (relative or absolute), set
13580 ;; proper date.
13581 (apply #'encode-time
13582 (org-read-date-analyze
13583 time default-time (decode-time default-time)))
13584 ;; If necessary, get the time from the user
13585 (or time (org-read-date nil 'to-time nil nil
13586 default-time default-input)))))
13588 (org-with-wide-buffer
13589 (org-back-to-heading t)
13590 (forward-line)
13591 (unless (bolp) (insert "\n"))
13592 (cond ((looking-at-p org-planning-line-re)
13593 ;; Move to current indentation.
13594 (skip-chars-forward " \t")
13595 ;; Check if we have to remove something.
13596 (dolist (type (if what (cons what remove) remove))
13597 (save-excursion
13598 (when (re-search-forward
13599 (cl-case type
13600 (closed org-closed-time-regexp)
13601 (deadline org-deadline-time-regexp)
13602 (scheduled org-scheduled-time-regexp)
13603 (otherwise
13604 (error "Invalid planning type: %s" type)))
13605 (line-end-position) t)
13606 ;; Delete until next keyword or end of line.
13607 (delete-region
13608 (match-beginning 0)
13609 (if (re-search-forward org-keyword-time-not-clock-regexp
13610 (line-end-position)
13612 (match-beginning 0)
13613 (line-end-position))))))
13614 ;; If there is nothing more to add and no more keyword
13615 ;; is left, remove the line completely.
13616 (if (and (looking-at-p "[ \t]*$") (not what))
13617 (delete-region (line-beginning-position)
13618 (line-beginning-position 2))
13619 ;; If we removed last keyword, do not leave trailing
13620 ;; white space at the end of line.
13621 (let ((p (point)))
13622 (save-excursion
13623 (end-of-line)
13624 (unless (= (skip-chars-backward " \t" p) 0)
13625 (delete-region (point) (line-end-position)))))))
13626 ((not what) (throw 'exit nil)) ; Nothing to do.
13627 (t (insert-before-markers "\n")
13628 (backward-char 1)
13629 (when org-adapt-indentation
13630 (indent-to-column (1+ (org-outline-level))))))
13631 (when what
13632 ;; Insert planning keyword.
13633 (insert (cl-case what
13634 (closed org-closed-string)
13635 (deadline org-deadline-string)
13636 (scheduled org-scheduled-string)
13637 (otherwise (error "Invalid planning type: %s" what)))
13638 " ")
13639 ;; Insert associated timestamp.
13640 (let ((ts (org-insert-time-stamp
13641 time
13642 (or org-time-was-given
13643 (and (eq what 'closed) org-log-done-with-time))
13644 (eq what 'closed)
13645 nil nil (list org-end-time-was-given))))
13646 (unless (eolp) (insert " "))
13647 ts))))))
13649 (defvar org-log-note-marker (make-marker)
13650 "Marker pointing at the entry where the note is to be inserted.")
13651 (defvar org-log-note-purpose nil)
13652 (defvar org-log-note-state nil)
13653 (defvar org-log-note-previous-state nil)
13654 (defvar org-log-note-extra nil)
13655 (defvar org-log-note-window-configuration nil)
13656 (defvar org-log-note-return-to (make-marker))
13657 (defvar org-log-note-effective-time nil
13658 "Remembered current time so that dynamically scoped
13659 `org-extend-today-until' affects timestamps in state change log")
13661 (defvar org-log-post-message nil
13662 "Message to be displayed after a log note has been stored.
13663 The auto-repeater uses this.")
13665 (defun org-add-note ()
13666 "Add a note to the current entry.
13667 This is done in the same way as adding a state change note."
13668 (interactive)
13669 (org-add-log-setup 'note))
13671 (defun org-log-beginning (&optional create)
13672 "Return expected start of log notes in current entry.
13673 When optional argument CREATE is non-nil, the function creates
13674 a drawer to store notes, if necessary. Returned position ignores
13675 narrowing."
13676 (org-with-wide-buffer
13677 (let ((drawer (org-log-into-drawer)))
13678 (cond
13679 (drawer
13680 (org-end-of-meta-data)
13681 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13682 (end (if (org-at-heading-p) (point)
13683 (save-excursion (outline-next-heading) (point))))
13684 (case-fold-search t))
13685 (catch 'exit
13686 ;; Try to find existing drawer.
13687 (while (re-search-forward regexp end t)
13688 (let ((element (org-element-at-point)))
13689 (when (eq (org-element-type element) 'drawer)
13690 (let ((cend (org-element-property :contents-end element)))
13691 (when (and (not org-log-states-order-reversed) cend)
13692 (goto-char cend)))
13693 (throw 'exit nil))))
13694 ;; No drawer found. Create one, if permitted.
13695 (when create
13696 (unless (bolp) (insert "\n"))
13697 (let ((beg (point)))
13698 (insert ":" drawer ":\n:END:\n")
13699 (org-indent-region beg (point)))
13700 (end-of-line -1)))))
13702 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13703 (skip-chars-forward " \t\n")
13704 (beginning-of-line)
13705 (unless org-log-states-order-reversed
13706 (org-skip-over-state-notes)
13707 (skip-chars-backward " \t\n")
13708 (forward-line)))))
13709 (if (bolp) (point) (line-beginning-position 2))))
13711 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13712 "Set up the post command hook to take a note.
13713 If this is about to TODO state change, the new state is expected in STATE.
13714 HOW is an indicator what kind of note should be created.
13715 EXTRA is additional text that will be inserted into the notes buffer."
13716 (move-marker org-log-note-marker (point))
13717 (setq org-log-note-purpose purpose
13718 org-log-note-state state
13719 org-log-note-previous-state prev-state
13720 org-log-note-how how
13721 org-log-note-extra extra
13722 org-log-note-effective-time (org-current-effective-time))
13723 (add-hook 'post-command-hook 'org-add-log-note 'append))
13725 (defun org-skip-over-state-notes ()
13726 "Skip past the list of State notes in an entry."
13727 (when (ignore-errors (goto-char (org-in-item-p)))
13728 (let* ((struct (org-list-struct))
13729 (prevs (org-list-prevs-alist struct))
13730 (regexp
13731 (concat "[ \t]*- +"
13732 (replace-regexp-in-string
13733 " +" " +"
13734 (org-replace-escapes
13735 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13736 `(("%d" . ,org-ts-regexp-inactive)
13737 ("%D" . ,org-ts-regexp)
13738 ("%s" . "\"\\S-+\"")
13739 ("%S" . "\"\\S-+\"")
13740 ("%t" . ,org-ts-regexp-inactive)
13741 ("%T" . ,org-ts-regexp)
13742 ("%u" . ".*?")
13743 ("%U" . ".*?")))))))
13744 (while (looking-at-p regexp)
13745 (goto-char (or (org-list-get-next-item (point) struct prevs)
13746 (org-list-get-item-end (point) struct)))))))
13748 (defun org-add-log-note (&optional _purpose)
13749 "Pop up a window for taking a note, and add this note later."
13750 (remove-hook 'post-command-hook 'org-add-log-note)
13751 (setq org-log-note-window-configuration (current-window-configuration))
13752 (delete-other-windows)
13753 (move-marker org-log-note-return-to (point))
13754 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13755 (goto-char org-log-note-marker)
13756 (org-switch-to-buffer-other-window "*Org Note*")
13757 (erase-buffer)
13758 (if (memq org-log-note-how '(time state))
13759 (let (current-prefix-arg) (org-store-log-note))
13760 (let ((org-inhibit-startup t)) (org-mode))
13761 (insert (format "# Insert note for %s.
13762 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13763 (cond
13764 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13765 ((eq org-log-note-purpose 'done) "closed todo item")
13766 ((eq org-log-note-purpose 'state)
13767 (format "state change from \"%s\" to \"%s\""
13768 (or org-log-note-previous-state "")
13769 (or org-log-note-state "")))
13770 ((eq org-log-note-purpose 'reschedule)
13771 "rescheduling")
13772 ((eq org-log-note-purpose 'delschedule)
13773 "no longer scheduled")
13774 ((eq org-log-note-purpose 'redeadline)
13775 "changing deadline")
13776 ((eq org-log-note-purpose 'deldeadline)
13777 "removing deadline")
13778 ((eq org-log-note-purpose 'refile)
13779 "refiling")
13780 ((eq org-log-note-purpose 'note)
13781 "this entry")
13782 (t (error "This should not happen")))))
13783 (when org-log-note-extra (insert org-log-note-extra))
13784 (setq-local org-finish-function 'org-store-log-note)
13785 (run-hooks 'org-log-buffer-setup-hook)))
13787 (defvar org-note-abort nil) ; dynamically scoped
13788 (defun org-store-log-note ()
13789 "Finish taking a log note, and insert it to where it belongs."
13790 (let ((txt (prog1 (buffer-string)
13791 (kill-buffer)))
13792 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13793 lines)
13794 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13795 (setq txt (replace-match "" t t txt)))
13796 (when (string-match "\\s-+\\'" txt)
13797 (setq txt (replace-match "" t t txt)))
13798 (setq lines (org-split-string txt "\n"))
13799 (when (org-string-nw-p note)
13800 (setq note
13801 (org-replace-escapes
13802 note
13803 (list (cons "%u" (user-login-name))
13804 (cons "%U" user-full-name)
13805 (cons "%t" (format-time-string
13806 (org-time-stamp-format 'long 'inactive)
13807 org-log-note-effective-time))
13808 (cons "%T" (format-time-string
13809 (org-time-stamp-format 'long nil)
13810 org-log-note-effective-time))
13811 (cons "%d" (format-time-string
13812 (org-time-stamp-format nil 'inactive)
13813 org-log-note-effective-time))
13814 (cons "%D" (format-time-string
13815 (org-time-stamp-format nil nil)
13816 org-log-note-effective-time))
13817 (cons "%s" (cond
13818 ((not org-log-note-state) "")
13819 ((string-match-p org-ts-regexp
13820 org-log-note-state)
13821 (format "\"[%s]\""
13822 (substring org-log-note-state 1 -1)))
13823 (t (format "\"%s\"" org-log-note-state))))
13824 (cons "%S"
13825 (cond
13826 ((not org-log-note-previous-state) "")
13827 ((string-match-p org-ts-regexp
13828 org-log-note-previous-state)
13829 (format "\"[%s]\""
13830 (substring
13831 org-log-note-previous-state 1 -1)))
13832 (t (format "\"%s\""
13833 org-log-note-previous-state)))))))
13834 (when lines (setq note (concat note " \\\\")))
13835 (push note lines))
13836 (when (and lines (not (or current-prefix-arg org-note-abort)))
13837 (with-current-buffer (marker-buffer org-log-note-marker)
13838 (org-with-wide-buffer
13839 ;; Find location for the new note.
13840 (goto-char org-log-note-marker)
13841 (set-marker org-log-note-marker nil)
13842 (goto-char (org-log-beginning t))
13843 ;; Make sure point is at the beginning of an empty line.
13844 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13845 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13846 ;; In an existing list, add a new item at the top level.
13847 ;; Otherwise, indent line like a regular one.
13848 (let ((itemp (org-in-item-p)))
13849 (if itemp
13850 (indent-line-to
13851 (let ((struct (save-excursion
13852 (goto-char itemp) (org-list-struct))))
13853 (org-list-get-ind (org-list-get-top-point struct) struct)))
13854 (org-indent-line)))
13855 (insert (org-list-bullet-string "-") (pop lines))
13856 (let ((ind (org-list-item-body-column (line-beginning-position))))
13857 (dolist (line lines)
13858 (insert "\n")
13859 (indent-line-to ind)
13860 (insert line)))
13861 (message "Note stored")
13862 (org-back-to-heading t)
13863 (org-cycle-hide-drawers 'children))
13864 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13865 ;; from within `org-add-log-note' because `buffer-undo-list'
13866 ;; is then modified outside of `org-with-remote-undo'.
13867 (when (eq this-command 'org-agenda-todo)
13868 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13869 ;; Don't add undo information when called from `org-agenda-todo'.
13870 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13871 (set-window-configuration org-log-note-window-configuration)
13872 (with-current-buffer (marker-buffer org-log-note-return-to)
13873 (goto-char org-log-note-return-to))
13874 (move-marker org-log-note-return-to nil)
13875 (when org-log-post-message (message "%s" org-log-post-message))))
13877 (defun org-remove-empty-drawer-at (pos)
13878 "Remove an empty drawer at position POS.
13879 POS may also be a marker."
13880 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13881 (org-with-wide-buffer
13882 (goto-char pos)
13883 (let ((drawer (org-element-at-point)))
13884 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13885 (not (org-element-property :contents-begin drawer)))
13886 (delete-region (org-element-property :begin drawer)
13887 (progn (goto-char (org-element-property :end drawer))
13888 (skip-chars-backward " \r\t\n")
13889 (forward-line)
13890 (point))))))))
13892 (defvar org-ts-type nil)
13893 (defun org-sparse-tree (&optional arg type)
13894 "Create a sparse tree, prompt for the details.
13895 This command can create sparse trees. You first need to select the type
13896 of match used to create the tree:
13898 t Show all TODO entries.
13899 T Show entries with a specific TODO keyword.
13900 m Show entries selected by a tags/property match.
13901 p Enter a property name and its value (both with completion on existing
13902 names/values) and show entries with that property.
13903 r Show entries matching a regular expression (`/' can be used as well).
13904 b Show deadlines and scheduled items before a date.
13905 a Show deadlines and scheduled items after a date.
13906 d Show deadlines due within `org-deadline-warning-days'.
13907 D Show deadlines and scheduled items between a date range."
13908 (interactive "P")
13909 (setq type (or type org-sparse-tree-default-date-type))
13910 (setq org-ts-type type)
13911 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13912 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13913 \[c]ycle through date types: %s"
13914 (cl-case type
13915 (all "all timestamps")
13916 (scheduled "only scheduled")
13917 (deadline "only deadline")
13918 (active "only active timestamps")
13919 (inactive "only inactive timestamps")
13920 (closed "with a closed time-stamp")
13921 (otherwise "scheduled/deadline")))
13922 (let ((answer (read-char-exclusive)))
13923 (cl-case answer
13925 (org-sparse-tree
13927 (cadr
13928 (memq type '(nil all scheduled deadline active inactive closed)))))
13929 (?d (call-interactively 'org-check-deadlines))
13930 (?b (call-interactively 'org-check-before-date))
13931 (?a (call-interactively 'org-check-after-date))
13932 (?D (call-interactively 'org-check-dates-range))
13933 (?t (call-interactively 'org-show-todo-tree))
13934 (?T (org-show-todo-tree '(4)))
13935 (?m (call-interactively 'org-match-sparse-tree))
13936 ((?p ?P)
13937 (let* ((kwd (completing-read
13938 "Property: " (mapcar #'list (org-buffer-property-keys))))
13939 (value (completing-read
13940 "Value: " (mapcar #'list (org-property-values kwd)))))
13941 (unless (string-match "\\`{.*}\\'" value)
13942 (setq value (concat "\"" value "\"")))
13943 (org-match-sparse-tree arg (concat kwd "=" value))))
13944 ((?r ?R ?/) (call-interactively 'org-occur))
13945 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13947 (defvar-local org-occur-highlights nil
13948 "List of overlays used for occur matches.")
13949 (defvar-local org-occur-parameters nil
13950 "Parameters of the active org-occur calls.
13951 This is a list, each call to org-occur pushes as cons cell,
13952 containing the regular expression and the callback, onto the list.
13953 The list can contain several entries if `org-occur' has been called
13954 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13955 will only contain one set of parameters. When the highlights are
13956 removed (for example with `C-c C-c', or with the next edit (depending
13957 on `org-remove-highlights-with-change'), this variable is emptied
13958 as well.")
13960 (defun org-occur (regexp &optional keep-previous callback)
13961 "Make a compact tree which shows all matches of REGEXP.
13963 The tree will show the lines where the regexp matches, and any other context
13964 defined in `org-show-context-detail', which see.
13966 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13967 done by a previous call to `org-occur' will be kept, to allow stacking of
13968 calls to this command.
13970 Optional argument CALLBACK can be a function of no argument. In this case,
13971 it is called with point at the end of the match, match data being set
13972 accordingly. Current match is shown only if the return value is non-nil.
13973 The function must neither move point nor alter narrowing."
13974 (interactive "sRegexp: \nP")
13975 (when (equal regexp "")
13976 (user-error "Regexp cannot be empty"))
13977 (unless keep-previous
13978 (org-remove-occur-highlights nil nil t))
13979 (push (cons regexp callback) org-occur-parameters)
13980 (let ((cnt 0))
13981 (save-excursion
13982 (goto-char (point-min))
13983 (when (or (not keep-previous) ; do not want to keep
13984 (not org-occur-highlights)) ; no previous matches
13985 ;; hide everything
13986 (org-overview))
13987 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13988 (isearch-no-upper-case-p regexp t)
13989 org-occur-case-fold-search)))
13990 (while (re-search-forward regexp nil t)
13991 (when (or (not callback)
13992 (save-match-data (funcall callback)))
13993 (setq cnt (1+ cnt))
13994 (when org-highlight-sparse-tree-matches
13995 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13996 (org-show-context 'occur-tree)))))
13997 (when org-remove-highlights-with-change
13998 (add-hook 'before-change-functions 'org-remove-occur-highlights
13999 nil 'local))
14000 (unless org-sparse-tree-open-archived-trees
14001 (org-hide-archived-subtrees (point-min) (point-max)))
14002 (run-hooks 'org-occur-hook)
14003 (when (called-interactively-p 'interactive)
14004 (message "%d match(es) for regexp %s" cnt regexp))
14005 cnt))
14007 (defun org-occur-next-match (&optional n _reset)
14008 "Function for `next-error-function' to find sparse tree matches.
14009 N is the number of matches to move, when negative move backwards.
14010 This function always goes back to the starting point when no
14011 match is found."
14012 (let* ((limit (if (< n 0) (point-min) (point-max)))
14013 (search-func (if (< n 0)
14014 'previous-single-char-property-change
14015 'next-single-char-property-change))
14016 (n (abs n))
14017 (pos (point))
14019 (catch 'exit
14020 (while (setq p1 (funcall search-func (point) 'org-type))
14021 (when (equal p1 limit)
14022 (goto-char pos)
14023 (user-error "No more matches"))
14024 (when (equal (get-char-property p1 'org-type) 'org-occur)
14025 (setq n (1- n))
14026 (when (= n 0)
14027 (goto-char p1)
14028 (throw 'exit (point))))
14029 (goto-char p1))
14030 (goto-char p1)
14031 (user-error "No more matches"))))
14033 (defun org-show-context (&optional key)
14034 "Make sure point and context are visible.
14035 Optional argument KEY, when non-nil, is a symbol. See
14036 `org-show-context-detail' for allowed values and how much is to
14037 be shown."
14038 (org-show-set-visibility
14039 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14040 ((cdr (assq key org-show-context-detail)))
14041 (t (cdr (assq 'default org-show-context-detail))))))
14043 (defun org-show-set-visibility (detail)
14044 "Set visibility around point according to DETAIL.
14045 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14046 `tree', `canonical' or t. See `org-show-context-detail' for more
14047 information."
14048 ;; Show current heading and possibly its entry, following headline
14049 ;; or all children.
14050 (if (and (org-at-heading-p) (not (eq detail 'local)))
14051 (org-flag-heading nil)
14052 (org-show-entry)
14053 ;; If point is hidden within a drawer or a block, make sure to
14054 ;; expose it.
14055 (dolist (o (overlays-at (point)))
14056 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14057 (delete-overlay o)))
14058 (unless (org-before-first-heading-p)
14059 (org-with-limited-levels
14060 (cl-case detail
14061 ((tree canonical t) (org-show-children))
14062 ((nil minimal ancestors))
14063 (t (save-excursion
14064 (outline-next-heading)
14065 (org-flag-heading nil)))))))
14066 ;; Show all siblings.
14067 (when (eq detail 'lineage) (org-show-siblings))
14068 ;; Show ancestors, possibly with their children.
14069 (when (memq detail '(ancestors lineage tree canonical t))
14070 (save-excursion
14071 (while (org-up-heading-safe)
14072 (org-flag-heading nil)
14073 (when (memq detail '(canonical t)) (org-show-entry))
14074 (when (memq detail '(tree canonical t)) (org-show-children))))))
14076 (defvar org-reveal-start-hook nil
14077 "Hook run before revealing a location.")
14079 (defun org-reveal (&optional siblings)
14080 "Show current entry, hierarchy above it, and the following headline.
14082 This can be used to show a consistent set of context around
14083 locations exposed with `org-show-context'.
14085 With optional argument SIBLINGS, on each level of the hierarchy all
14086 siblings are shown. This repairs the tree structure to what it would
14087 look like when opened with hierarchical calls to `org-cycle'.
14089 With double optional argument \\[universal-argument] \\[universal-argument], \
14090 go to the parent and show the
14091 entire tree."
14092 (interactive "P")
14093 (run-hooks 'org-reveal-start-hook)
14094 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14095 ((equal siblings '(16))
14096 (save-excursion
14097 (when (org-up-heading-safe)
14098 (org-show-subtree)
14099 (run-hook-with-args 'org-cycle-hook 'subtree))))
14100 (t (org-show-set-visibility 'lineage))))
14102 (defun org-highlight-new-match (beg end)
14103 "Highlight from BEG to END and mark the highlight is an occur headline."
14104 (let ((ov (make-overlay beg end)))
14105 (overlay-put ov 'face 'secondary-selection)
14106 (overlay-put ov 'org-type 'org-occur)
14107 (push ov org-occur-highlights)))
14109 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14110 "Remove the occur highlights from the buffer.
14111 BEG and END are ignored. If NOREMOVE is nil, remove this function
14112 from the `before-change-functions' in the current buffer."
14113 (interactive)
14114 (unless org-inhibit-highlight-removal
14115 (mapc #'delete-overlay org-occur-highlights)
14116 (setq org-occur-highlights nil)
14117 (setq org-occur-parameters nil)
14118 (unless noremove
14119 (remove-hook 'before-change-functions
14120 'org-remove-occur-highlights 'local))))
14122 ;;;; Priorities
14124 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14125 "Regular expression matching the priority indicator.")
14127 (defvar org-remove-priority-next-time nil)
14129 (defun org-priority-up ()
14130 "Increase the priority of the current item."
14131 (interactive)
14132 (org-priority 'up))
14134 (defun org-priority-down ()
14135 "Decrease the priority of the current item."
14136 (interactive)
14137 (org-priority 'down))
14139 (defun org-priority (&optional action _show)
14140 "Change the priority of an item.
14141 ACTION can be `set', `up', `down', or a character."
14142 (interactive "P")
14143 (if (equal action '(4))
14144 (org-show-priority)
14145 (unless org-enable-priority-commands
14146 (user-error "Priority commands are disabled"))
14147 (setq action (or action 'set))
14148 (let (current new news have remove)
14149 (save-excursion
14150 (org-back-to-heading t)
14151 (when (looking-at org-priority-regexp)
14152 (setq current (string-to-char (match-string 2))
14153 have t))
14154 (cond
14155 ((eq action 'remove)
14156 (setq remove t new ?\ ))
14157 ((or (eq action 'set)
14158 (integerp action))
14159 (if (not (eq action 'set))
14160 (setq new action)
14161 (message "Priority %c-%c, SPC to remove: "
14162 org-highest-priority org-lowest-priority)
14163 (save-match-data
14164 (setq new (read-char-exclusive))))
14165 (when (and (= (upcase org-highest-priority) org-highest-priority)
14166 (= (upcase org-lowest-priority) org-lowest-priority))
14167 (setq new (upcase new)))
14168 (cond ((equal new ?\ ) (setq remove t))
14169 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14170 (user-error "Priority must be between `%c' and `%c'"
14171 org-highest-priority org-lowest-priority))))
14172 ((eq action 'up)
14173 (setq new (if have
14174 (1- current) ; normal cycling
14175 ;; last priority was empty
14176 (if (eq last-command this-command)
14177 org-lowest-priority ; wrap around empty to lowest
14178 ;; default
14179 (if org-priority-start-cycle-with-default
14180 org-default-priority
14181 (1- org-default-priority))))))
14182 ((eq action 'down)
14183 (setq new (if have
14184 (1+ current) ; normal cycling
14185 ;; last priority was empty
14186 (if (eq last-command this-command)
14187 org-highest-priority ; wrap around empty to highest
14188 ;; default
14189 (if org-priority-start-cycle-with-default
14190 org-default-priority
14191 (1+ org-default-priority))))))
14192 (t (user-error "Invalid action")))
14193 (when (or (< (upcase new) org-highest-priority)
14194 (> (upcase new) org-lowest-priority))
14195 (if (and (memq action '(up down))
14196 (not have) (not (eq last-command this-command)))
14197 ;; `new' is from default priority
14198 (error
14199 "The default can not be set, see `org-default-priority' why")
14200 ;; normal cycling: `new' is beyond highest/lowest priority
14201 ;; and is wrapped around to the empty priority
14202 (setq remove t)))
14203 (setq news (format "%c" new))
14204 (if have
14205 (if remove
14206 (replace-match "" t t nil 1)
14207 (replace-match news t t nil 2))
14208 (if remove
14209 (user-error "No priority cookie found in line")
14210 (let ((case-fold-search nil))
14211 (looking-at org-todo-line-regexp))
14212 (if (match-end 2)
14213 (progn
14214 (goto-char (match-end 2))
14215 (insert " [#" news "]"))
14216 (goto-char (match-beginning 3))
14217 (insert "[#" news "] "))))
14218 (org-set-tags nil 'align))
14219 (if remove
14220 (message "Priority removed")
14221 (message "Priority of current item set to %s" news)))))
14223 (defun org-show-priority ()
14224 "Show the priority of the current item.
14225 This priority is composed of the main priority given with the [#A] cookies,
14226 and by additional input from the age of a schedules or deadline entry."
14227 (interactive)
14228 (let ((pri (if (eq major-mode 'org-agenda-mode)
14229 (org-get-at-bol 'priority)
14230 (save-excursion
14231 (save-match-data
14232 (beginning-of-line)
14233 (and (looking-at org-heading-regexp)
14234 (org-get-priority (match-string 0))))))))
14235 (message "Priority is %d" (if pri pri -1000))))
14237 (defun org-get-priority (s)
14238 "Find priority cookie and return priority."
14239 (save-match-data
14240 (if (functionp org-get-priority-function)
14241 (funcall org-get-priority-function)
14242 (if (not (string-match org-priority-regexp s))
14243 (* 1000 (- org-lowest-priority org-default-priority))
14244 (* 1000 (- org-lowest-priority
14245 (string-to-char (match-string 2 s))))))))
14247 ;;;; Tags
14249 (defvar org-agenda-archives-mode)
14250 (defvar org-map-continue-from nil
14251 "Position from where mapping should continue.
14252 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14254 (defvar org-scanner-tags nil
14255 "The current tag list while the tags scanner is running.")
14257 (defvar org-trust-scanner-tags nil
14258 "Should `org-get-tags-at' use the tags for the scanner.
14259 This is for internal dynamical scoping only.
14260 When this is non-nil, the function `org-get-tags-at' will return the value
14261 of `org-scanner-tags' instead of building the list by itself. This
14262 can lead to large speed-ups when the tags scanner is used in a file with
14263 many entries, and when the list of tags is retrieved, for example to
14264 obtain a list of properties. Building the tags list for each entry in such
14265 a file becomes an N^2 operation - but with this variable set, it scales
14266 as N.")
14268 (defvar org--matcher-tags-todo-only nil)
14270 (defun org-scan-tags (action matcher todo-only &optional start-level)
14271 "Scan headline tags with inheritance and produce output ACTION.
14273 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14274 or `agenda' to produce an entry list for an agenda view. It can also be
14275 a Lisp form or a function that should be called at each matched headline, in
14276 this case the return value is a list of all return values from these calls.
14278 MATCHER is a function accepting three arguments, returning
14279 a non-nil value whenever a given set of tags qualifies a headline
14280 for inclusion. See `org-make-tags-matcher' for more information.
14281 As a special case, it can also be set to t (respectively nil) in
14282 order to match all (respectively none) headline.
14284 When TODO-ONLY is non-nil, only lines with a not-done TODO
14285 keyword are included in the output.
14287 START-LEVEL can be a string with asterisks, reducing the scope to
14288 headlines matching this string."
14289 (require 'org-agenda)
14290 (let* ((re (concat "^"
14291 (if start-level
14292 ;; Get the correct level to match
14293 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14294 org-outline-regexp)
14295 " *\\(\\<\\("
14296 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14297 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14298 (props (list 'face 'default
14299 'done-face 'org-agenda-done
14300 'undone-face 'default
14301 'mouse-face 'highlight
14302 'org-not-done-regexp org-not-done-regexp
14303 'org-todo-regexp org-todo-regexp
14304 'org-complex-heading-regexp org-complex-heading-regexp
14305 'help-echo
14306 (format "mouse-2 or RET jump to org file %s"
14307 (abbreviate-file-name
14308 (or (buffer-file-name (buffer-base-buffer))
14309 (buffer-name (buffer-base-buffer)))))))
14310 (org-map-continue-from nil)
14311 lspos tags tags-list
14312 (tags-alist (list (cons 0 org-file-tags)))
14313 (llast 0) rtn rtn1 level category i txt
14314 todo marker entry priority
14315 ts-date ts-date-type ts-date-pair)
14316 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14317 (setq action (list 'lambda nil action)))
14318 (save-excursion
14319 (goto-char (point-min))
14320 (when (eq action 'sparse-tree)
14321 (org-overview)
14322 (org-remove-occur-highlights))
14323 (while (let (case-fold-search)
14324 (re-search-forward re nil t))
14325 (setq org-map-continue-from nil)
14326 (catch :skip
14327 (setq todo
14328 ;; TODO: is the 1-2 difference a bug?
14329 (when (match-end 1) (match-string-no-properties 2))
14330 tags (when (match-end 4) (match-string-no-properties 4)))
14331 (goto-char (setq lspos (match-beginning 0)))
14332 (setq level (org-reduced-level (org-outline-level))
14333 category (org-get-category))
14334 (when (eq action 'agenda)
14335 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14336 ts-date (car ts-date-pair)
14337 ts-date-type (cdr ts-date-pair)))
14338 (setq i llast llast level)
14339 ;; remove tag lists from same and sublevels
14340 (while (>= i level)
14341 (when (setq entry (assoc i tags-alist))
14342 (setq tags-alist (delete entry tags-alist)))
14343 (setq i (1- i)))
14344 ;; add the next tags
14345 (when tags
14346 (setq tags (org-split-string tags ":")
14347 tags-alist
14348 (cons (cons level tags) tags-alist)))
14349 ;; compile tags for current headline
14350 (setq tags-list
14351 (if org-use-tag-inheritance
14352 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14353 tags)
14354 org-scanner-tags tags-list)
14355 (when org-use-tag-inheritance
14356 (setcdr (car tags-alist)
14357 (mapcar (lambda (x)
14358 (setq x (copy-sequence x))
14359 (org-add-prop-inherited x))
14360 (cdar tags-alist))))
14361 (when (and tags org-use-tag-inheritance
14362 (or (not (eq t org-use-tag-inheritance))
14363 org-tags-exclude-from-inheritance))
14364 ;; Selective inheritance, remove uninherited ones.
14365 (setcdr (car tags-alist)
14366 (org-remove-uninherited-tags (cdar tags-alist))))
14367 (when (and
14369 ;; eval matcher only when the todo condition is OK
14370 (and (or (not todo-only) (member todo org-not-done-keywords))
14371 (if (functionp matcher)
14372 (let ((case-fold-search t) (org-trust-scanner-tags t))
14373 (funcall matcher todo tags-list level))
14374 matcher))
14376 ;; Call the skipper, but return t if it does not
14377 ;; skip, so that the `and' form continues evaluating.
14378 (progn
14379 (unless (eq action 'sparse-tree) (org-agenda-skip))
14382 ;; Check if timestamps are deselecting this entry
14383 (or (not todo-only)
14384 (and (member todo org-not-done-keywords)
14385 (or (not org-agenda-tags-todo-honor-ignore-options)
14386 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14388 ;; select this headline
14389 (cond
14390 ((eq action 'sparse-tree)
14391 (and org-highlight-sparse-tree-matches
14392 (org-get-heading) (match-end 0)
14393 (org-highlight-new-match
14394 (match-beginning 1) (match-end 1)))
14395 (org-show-context 'tags-tree))
14396 ((eq action 'agenda)
14397 (setq txt (org-agenda-format-item
14399 (concat
14400 (if (eq org-tags-match-list-sublevels 'indented)
14401 (make-string (1- level) ?.) "")
14402 (org-get-heading))
14403 (make-string level ?\s)
14404 category
14405 tags-list)
14406 priority (org-get-priority txt))
14407 (goto-char lspos)
14408 (setq marker (org-agenda-new-marker))
14409 (org-add-props txt props
14410 'org-marker marker 'org-hd-marker marker 'org-category category
14411 'todo-state todo
14412 'ts-date ts-date
14413 'priority priority
14414 'type (concat "tagsmatch" ts-date-type))
14415 (push txt rtn))
14416 ((functionp action)
14417 (setq org-map-continue-from nil)
14418 (save-excursion
14419 (setq rtn1 (funcall action))
14420 (push rtn1 rtn)))
14421 (t (user-error "Invalid action")))
14423 ;; if we are to skip sublevels, jump to end of subtree
14424 (unless org-tags-match-list-sublevels
14425 (org-end-of-subtree t)
14426 (backward-char 1))))
14427 ;; Get the correct position from where to continue
14428 (if org-map-continue-from
14429 (goto-char org-map-continue-from)
14430 (and (= (point) lspos) (end-of-line 1)))))
14431 (when (and (eq action 'sparse-tree)
14432 (not org-sparse-tree-open-archived-trees))
14433 (org-hide-archived-subtrees (point-min) (point-max)))
14434 (nreverse rtn)))
14436 (defun org-remove-uninherited-tags (tags)
14437 "Remove all tags that are not inherited from the list TAGS."
14438 (cond
14439 ((eq org-use-tag-inheritance t)
14440 (if org-tags-exclude-from-inheritance
14441 (org-delete-all org-tags-exclude-from-inheritance tags)
14442 tags))
14443 ((not org-use-tag-inheritance) nil)
14444 ((stringp org-use-tag-inheritance)
14445 (delq nil (mapcar
14446 (lambda (x)
14447 (if (and (string-match org-use-tag-inheritance x)
14448 (not (member x org-tags-exclude-from-inheritance)))
14449 x nil))
14450 tags)))
14451 ((listp org-use-tag-inheritance)
14452 (delq nil (mapcar
14453 (lambda (x)
14454 (if (member x org-use-tag-inheritance) x nil))
14455 tags)))))
14457 (defun org-match-sparse-tree (&optional todo-only match)
14458 "Create a sparse tree according to tags string MATCH.
14459 MATCH can contain positive and negative selection of tags, like
14460 \"+WORK+URGENT-WITHBOSS\".
14461 If optional argument TODO-ONLY is non-nil, only select lines that are
14462 also TODO lines."
14463 (interactive "P")
14464 (org-agenda-prepare-buffers (list (current-buffer)))
14465 (let ((org--matcher-tags-todo-only todo-only))
14466 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14467 org--matcher-tags-todo-only)))
14469 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14471 (defvar org-cached-props nil)
14472 (defun org-cached-entry-get (pom property)
14473 (if (or (eq t org-use-property-inheritance)
14474 (and (stringp org-use-property-inheritance)
14475 (let ((case-fold-search t))
14476 (string-match-p org-use-property-inheritance property)))
14477 (and (listp org-use-property-inheritance)
14478 (member-ignore-case property org-use-property-inheritance)))
14479 ;; Caching is not possible, check it directly.
14480 (org-entry-get pom property 'inherit)
14481 ;; Get all properties, so we can do complicated checks easily.
14482 (cdr (assoc-string property
14483 (or org-cached-props
14484 (setq org-cached-props (org-entry-properties pom)))
14485 t))))
14487 (defun org-global-tags-completion-table (&optional files)
14488 "Return the list of all tags in all agenda buffer/files.
14489 Optional FILES argument is a list of files which can be used
14490 instead of the agenda files."
14491 (save-excursion
14492 (org-uniquify
14493 (delq nil
14494 (apply #'append
14495 (mapcar
14496 (lambda (file)
14497 (set-buffer (find-file-noselect file))
14498 (mapcar (lambda (x)
14499 (and (stringp (car-safe x))
14500 (list (car-safe x))))
14501 (or org-current-tag-alist (org-get-buffer-tags))))
14502 (if (car-safe files) files
14503 (org-agenda-files))))))))
14505 (defun org-make-tags-matcher (match)
14506 "Create the TAGS/TODO matcher form for the selection string MATCH.
14508 Returns a cons of the selection string MATCH and a function
14509 implementing the matcher.
14511 The matcher is to be called at an Org entry, with point on the
14512 headline, and returns non-nil if the entry matches the selection
14513 string MATCH. It must be called with three arguments: the TODO
14514 keyword at the entry (or nil if none), the list of all tags at
14515 the entry including inherited ones and the reduced level of the
14516 headline. Additionally, the category of the entry, if any, must
14517 be specified as the text property `org-category' on the headline.
14519 This function sets the variable `org--matcher-tags-todo-only' to
14520 a non-nil value if the matcher restricts matching to TODO
14521 entries, otherwise it is not touched.
14523 See also `org-scan-tags'."
14524 (unless match
14525 ;; Get a new match request, with completion against the global
14526 ;; tags table and the local tags in current buffer.
14527 (let ((org-last-tags-completion-table
14528 (org-uniquify
14529 (delq nil (append (org-get-buffer-tags)
14530 (org-global-tags-completion-table))))))
14531 (setq match
14532 (completing-read
14533 "Match: "
14534 'org-tags-completion-function nil nil nil 'org-tags-history))))
14536 (let ((match0 match)
14537 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14538 (start 0)
14539 tagsmatch todomatch tagsmatcher todomatcher)
14541 ;; Expand group tags.
14542 (setq match (org-tags-expand match))
14544 ;; Check if there is a TODO part of this match, which would be the
14545 ;; part after a "/". To make sure that this slash is not part of
14546 ;; a property value to be matched against, we also check that
14547 ;; there is no / after that slash. First, find the last slash.
14548 (let ((s 0))
14549 (while (string-match "/+" match s)
14550 (setq start (match-beginning 0))
14551 (setq s (match-end 0))))
14552 (if (and (string-match "/+" match start)
14553 (not (string-match-p "\"" match start)))
14554 ;; Match contains also a TODO-matching request.
14555 (progn
14556 (setq tagsmatch (substring match 0 (match-beginning 0)))
14557 (setq todomatch (substring match (match-end 0)))
14558 (when (string-prefix-p "!" todomatch)
14559 (setq org--matcher-tags-todo-only t)
14560 (setq todomatch (substring todomatch 1)))
14561 (when (string-match "\\`\\s-*\\'" todomatch)
14562 (setq todomatch nil)))
14563 ;; Only matching tags.
14564 (setq tagsmatch match)
14565 (setq todomatch nil))
14567 ;; Make the tags matcher.
14568 (when (org-string-nw-p tagsmatch)
14569 (let ((orlist nil)
14570 (orterms (org-split-string tagsmatch "|"))
14571 term)
14572 (while (setq term (pop orterms))
14573 (while (and (equal (substring term -1) "\\") orterms)
14574 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14575 (while (string-match re term)
14576 (let* ((rest (substring term (match-end 0)))
14577 (minus (and (match-end 1)
14578 (equal (match-string 1 term) "-")))
14579 (tag (save-match-data
14580 (replace-regexp-in-string
14581 "\\\\-" "-" (match-string 2 term))))
14582 (regexp (eq (string-to-char tag) ?{))
14583 (levelp (match-end 4))
14584 (propp (match-end 5))
14586 (cond
14587 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14588 (levelp
14589 `(,(org-op-to-function (match-string 3 term))
14590 level
14591 ,(string-to-number (match-string 4 term))))
14592 (propp
14593 (let* ((gv (pcase (upcase (match-string 5 term))
14594 ("CATEGORY"
14595 '(get-text-property (point) 'org-category))
14596 ("TODO" 'todo)
14597 (p `(org-cached-entry-get nil ,p))))
14598 (pv (match-string 7 term))
14599 (regexp (eq (string-to-char pv) ?{))
14600 (strp (eq (string-to-char pv) ?\"))
14601 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14602 (po (org-op-to-function (match-string 6 term)
14603 (if timep 'time strp))))
14604 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14605 (when timep (setq pv (org-matcher-time pv)))
14606 (cond ((and regexp (eq po 'org<>))
14607 `(not (string-match ,pv (or ,gv ""))))
14608 (regexp `(string-match ,pv (or ,gv "")))
14609 (strp `(,po (or ,gv "") ,pv))
14611 `(,po
14612 (string-to-number (or ,gv ""))
14613 ,(string-to-number pv))))))
14614 (t `(member ,tag tags-list)))))
14615 (push (if minus `(not ,mm) mm) tagsmatcher)
14616 (setq term rest)))
14617 (push `(and ,@tagsmatcher) orlist)
14618 (setq tagsmatcher nil))
14619 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14621 ;; Make the TODO matcher.
14622 (when (org-string-nw-p todomatch)
14623 (let ((orlist nil))
14624 (dolist (term (org-split-string todomatch "|"))
14625 (while (string-match re term)
14626 (let* ((minus (and (match-end 1)
14627 (equal (match-string 1 term) "-")))
14628 (kwd (match-string 2 term))
14629 (regexp (eq (string-to-char kwd) ?{))
14630 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14631 `(equal todo ,kwd))))
14632 (push (if minus `(not ,mm) mm) todomatcher))
14633 (setq term (substring term (match-end 0))))
14634 (push (if (> (length todomatcher) 1)
14635 (cons 'and todomatcher)
14636 (car todomatcher))
14637 orlist)
14638 (setq todomatcher nil))
14639 (setq todomatcher (cons 'or orlist))))
14641 ;; Return the string and function of the matcher. If no
14642 ;; tags-specific or todo-specific matcher exists, match
14643 ;; everything.
14644 (let ((matcher (if (and tagsmatcher todomatcher)
14645 `(and ,tagsmatcher ,todomatcher)
14646 (or tagsmatcher todomatcher t))))
14647 (when org--matcher-tags-todo-only
14648 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14649 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14651 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14652 "Expand group tags in MATCH.
14654 This replaces every group tag in MATCH with a regexp tag search.
14655 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14656 will be replaced like this:
14658 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14659 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14660 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14662 Replacing by a regexp preserves the structure of the match.
14663 E.g., this expansion
14665 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14667 will match anything tagged with \"Lab\" and \"Home\", or tagged
14668 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14670 A group tag in MATCH can contain regular expressions of its own.
14671 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14672 will be replaced like this:
14674 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14676 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14677 assumed to be a single group tag, and the function will return
14678 the list of tags in this group.
14680 When DOWNCASE is non-nil, expand downcased TAGS."
14681 (if org-group-tags
14682 (let* ((case-fold-search t)
14683 (stable org-mode-syntax-table)
14684 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14685 (taggroups (if downcased
14686 (mapcar (lambda (tg) (mapcar #'downcase tg))
14687 taggroups)
14688 taggroups))
14689 (taggroups-keys (mapcar #'car taggroups))
14690 (return-match (if downcased (downcase match) match))
14691 (count 0)
14692 (work-already-expanded tags-already-expanded)
14693 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14694 ;; @ and _ are allowed as word-components in tags.
14695 (modify-syntax-entry ?@ "w" stable)
14696 (modify-syntax-entry ?_ "w" stable)
14697 ;; Temporarily replace regexp-expressions in the match-expression.
14698 (while (string-match "{.+?}" return-match)
14699 (cl-incf count)
14700 (push (match-string 0 return-match) regexps-in-match)
14701 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14702 (while (and taggroups-keys
14703 (with-syntax-table stable
14704 (string-match
14705 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14706 (regexp-opt taggroups-keys) "\\>\\)")
14707 return-match)))
14708 (let* ((dir (match-string 1 return-match))
14709 (tag (match-string 2 return-match))
14710 (tag (if downcased (downcase tag) tag)))
14711 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14712 (member tag work-already-expanded))
14713 (setq tags-in-group (assoc tag taggroups))
14714 (push tag work-already-expanded)
14715 ;; Recursively expand each tag in the group, if the tag hasn't
14716 ;; already been expanded. Restore the match-data after all recursive calls.
14717 (save-match-data
14718 (let (tags-expanded)
14719 (dolist (x (cdr tags-in-group))
14720 (if (and (member x taggroups-keys)
14721 (not (member x work-already-expanded)))
14722 (setq tags-expanded
14723 (delete-dups
14724 (append
14725 (org-tags-expand x t downcased
14726 work-already-expanded)
14727 tags-expanded)))
14728 (setq tags-expanded
14729 (append (list x) tags-expanded)))
14730 (setq work-already-expanded
14731 (delete-dups
14732 (append tags-expanded
14733 work-already-expanded))))
14734 (setq tags-in-group
14735 (delete-dups (cons (car tags-in-group)
14736 tags-expanded)))))
14737 ;; Filter tag-regexps from tags.
14738 (setq regexp-in-group-escaped
14739 (delq nil (mapcar (lambda (x)
14740 (if (stringp x)
14741 (and (equal "{" (substring x 0 1))
14742 (equal "}" (substring x -1))
14745 tags-in-group))
14746 regexp-in-group
14747 (mapcar (lambda (x)
14748 (substring x 1 -1))
14749 regexp-in-group-escaped)
14750 tags-in-group
14751 (delq nil (mapcar (lambda (x)
14752 (if (stringp x)
14753 (and (not (equal "{" (substring x 0 1)))
14754 (not (equal "}" (substring x -1)))
14757 tags-in-group)))
14758 ;; If single-as-list, do no more in the while-loop.
14759 (if (not single-as-list)
14760 (progn
14761 (when regexp-in-group
14762 (setq regexp-in-group
14763 (concat "\\|"
14764 (mapconcat 'identity regexp-in-group
14765 "\\|"))))
14766 (setq tags-in-group
14767 (concat dir
14768 "{\\<"
14769 (regexp-opt tags-in-group)
14770 "\\>"
14771 regexp-in-group
14772 "}"))
14773 (when (stringp tags-in-group)
14774 (org-add-props tags-in-group '(grouptag t)))
14775 (setq return-match
14776 (replace-match tags-in-group t t return-match)))
14777 (setq tags-in-group
14778 (append regexp-in-group-escaped tags-in-group))))
14779 (setq taggroups-keys (delete tag taggroups-keys))))
14780 ;; Add the regular expressions back into the match-expression again.
14781 (while regexps-in-match
14782 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14783 (pop regexps-in-match)
14784 return-match t t))
14785 (cl-decf count))
14786 (if single-as-list
14787 (if tags-in-group tags-in-group (list return-match))
14788 return-match))
14789 (if single-as-list
14790 (list (if downcased (downcase match) match))
14791 match)))
14793 (defun org-op-to-function (op &optional stringp)
14794 "Turn an operator into the appropriate function."
14795 (setq op
14796 (cond
14797 ((equal op "<" ) '(< string< org-time<))
14798 ((equal op ">" ) '(> org-string> org-time>))
14799 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14800 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14801 ((member op '("=" "==")) '(= string= org-time=))
14802 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14803 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14805 (defun org<> (a b) (not (= a b)))
14806 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14807 (defun org-string>= (a b) (not (string< a b)))
14808 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14809 (defun org-string<> (a b) (not (string= 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) (<= a b)))
14813 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14814 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14815 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14816 (defun org-2ft (s)
14817 "Convert S to a floating point time.
14818 If S is already a number, just return it. If it is a string, parse
14819 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14820 (cond
14821 ((numberp s) s)
14822 ((stringp s)
14823 (condition-case nil
14824 (float-time (apply 'encode-time (org-parse-time-string s)))
14825 (error 0.)))
14826 (t 0.)))
14828 (defun org-time-today ()
14829 "Time in seconds today at 0:00.
14830 Returns the float number of seconds since the beginning of the
14831 epoch to the beginning of today (00:00)."
14832 (float-time (apply 'encode-time
14833 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14835 (defun org-matcher-time (s)
14836 "Interpret a time comparison value."
14837 (save-match-data
14838 (cond
14839 ((string= s "<now>") (float-time))
14840 ((string= s "<today>") (org-time-today))
14841 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14842 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14843 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14844 (+ (org-time-today)
14845 (* (string-to-number (match-string 1 s))
14846 (cdr (assoc (match-string 2 s)
14847 '(("d" . 86400.0) ("w" . 604800.0)
14848 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14849 (t (org-2ft s)))))
14851 (defun org-match-any-p (re list)
14852 "Does re match any element of list?"
14853 (setq list (mapcar (lambda (x) (string-match re x)) list))
14854 (delq nil list))
14856 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14857 (defvar org-tags-overlay (make-overlay 1 1))
14858 (delete-overlay org-tags-overlay)
14860 (defun org-get-local-tags-at (&optional pos)
14861 "Get a list of tags defined in the current headline."
14862 (org-get-tags-at pos 'local))
14864 (defun org-get-local-tags ()
14865 "Get a list of tags defined in the current headline."
14866 (org-get-tags-at nil 'local))
14868 (defun org-get-tags-at (&optional pos local)
14869 "Get a list of all headline tags applicable at POS.
14870 POS defaults to point. If tags are inherited, the list contains
14871 the targets in the same sequence as the headlines appear, i.e.
14872 the tags of the current headline come last.
14873 When LOCAL is non-nil, only return tags from the current headline,
14874 ignore inherited ones."
14875 (interactive)
14876 (if (and org-trust-scanner-tags
14877 (or (not pos) (equal pos (point)))
14878 (not local))
14879 org-scanner-tags
14880 (let (tags ltags lastpos parent)
14881 (save-excursion
14882 (save-restriction
14883 (widen)
14884 (goto-char (or pos (point)))
14885 (save-match-data
14886 (catch 'done
14887 (condition-case nil
14888 (progn
14889 (org-back-to-heading t)
14890 (while (not (equal lastpos (point)))
14891 (setq lastpos (point))
14892 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14893 (setq ltags (org-split-string
14894 (match-string-no-properties 1) ":"))
14895 (when parent
14896 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14897 (setq tags (append
14898 (if parent
14899 (org-remove-uninherited-tags ltags)
14900 ltags)
14901 tags)))
14902 (or org-use-tag-inheritance (throw 'done t))
14903 (when local (throw 'done t))
14904 (or (org-up-heading-safe) (error nil))
14905 (setq parent t)))
14906 (error nil)))))
14907 (if local
14908 tags
14909 (reverse (delete-dups
14910 (reverse (append
14911 (org-remove-uninherited-tags
14912 org-file-tags)
14913 tags)))))))))
14915 (defun org-add-prop-inherited (s)
14916 (add-text-properties 0 (length s) '(inherited t) s)
14919 (defun org-toggle-tag (tag &optional onoff)
14920 "Toggle the tag TAG for the current line.
14921 If ONOFF is `on' or `off', don't toggle but set to this state."
14922 (let (res current)
14923 (save-excursion
14924 (org-back-to-heading t)
14925 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14926 (point-at-eol) t)
14927 (progn
14928 (setq current (match-string 1))
14929 (replace-match ""))
14930 (setq current ""))
14931 (setq current (nreverse (org-split-string current ":")))
14932 (cond
14933 ((eq onoff 'on)
14934 (setq res t)
14935 (or (member tag current) (push tag current)))
14936 ((eq onoff 'off)
14937 (or (not (member tag current)) (setq current (delete tag current))))
14938 (t (if (member tag current)
14939 (setq current (delete tag current))
14940 (setq res t)
14941 (push tag current))))
14942 (end-of-line 1)
14943 (if current
14944 (progn
14945 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14946 (org-set-tags nil t))
14947 (delete-horizontal-space))
14948 (run-hooks 'org-after-tags-change-hook))
14949 res))
14951 (defun org-align-tags-here (to-col)
14952 "Align tags on the current headline to TO-COL.
14953 Assume point is on a headline."
14954 (let ((pos (point)))
14955 (beginning-of-line)
14956 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14957 (>= pos (match-beginning 2)))
14958 ;; No tags or point within tags: do not align.
14959 (goto-char pos)
14960 (goto-char (match-beginning 1))
14961 (let ((shift (max (- (if (>= to-col 0) to-col
14962 (- (abs to-col) (string-width (match-string 2))))
14963 (current-column))
14964 1)))
14965 (replace-match (make-string shift ?\s) nil nil nil 1)
14966 ;; Preserve initial position, if possible. In any case, stop
14967 ;; before tags.
14968 (when (< pos (point)) (goto-char pos))))))
14970 (defun org-set-tags-command (&optional arg just-align)
14971 "Call the set-tags command for the current entry."
14972 (interactive "P")
14973 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14974 (org-set-tags arg just-align)
14975 (save-excursion
14976 (unless (and (org-region-active-p)
14977 org-loop-over-headlines-in-active-region)
14978 (org-back-to-heading t))
14979 (org-set-tags arg just-align))))
14981 (defun org-set-tags-to (data)
14982 "Set the tags of the current entry to DATA, replacing the current tags.
14983 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14984 If DATA is nil or the empty string, any tags will be removed."
14985 (interactive "sTags: ")
14986 (setq data
14987 (cond
14988 ((eq data nil) "")
14989 ((equal data "") "")
14990 ((stringp data)
14991 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14992 ":"))
14993 ((listp data)
14994 (concat ":" (mapconcat 'identity data ":") ":"))))
14995 (when data
14996 (save-excursion
14997 (org-back-to-heading t)
14998 (when (looking-at org-complex-heading-regexp)
14999 (if (match-end 5)
15000 (progn
15001 (goto-char (match-beginning 5))
15002 (insert data)
15003 (delete-region (point) (point-at-eol))
15004 (org-set-tags nil 'align))
15005 (goto-char (point-at-eol))
15006 (insert " " data)
15007 (org-set-tags nil 'align)))
15008 (beginning-of-line 1)
15009 (when (looking-at ".*?\\([ \t]+\\)$")
15010 (delete-region (match-beginning 1) (match-end 1))))))
15012 (defun org-align-all-tags ()
15013 "Align the tags in all headings."
15014 (interactive)
15015 (save-excursion
15016 (or (ignore-errors (org-back-to-heading t))
15017 (outline-next-heading))
15018 (if (org-at-heading-p)
15019 (org-set-tags t)
15020 (message "No headings"))))
15022 (defvar org-indent-indentation-per-level)
15023 (defun org-set-tags (&optional arg just-align)
15024 "Set the tags for the current headline.
15025 With prefix ARG, realign all tags in headings in the current buffer.
15026 When JUST-ALIGN is non-nil, only align tags."
15027 (interactive "P")
15028 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15029 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15030 'region-start-level
15031 'region))
15032 org-loop-over-headlines-in-active-region)
15033 (org-map-entries
15034 ;; We don't use ARG and JUST-ALIGN here because these args
15035 ;; are not useful when looping over headlines.
15036 #'org-set-tags
15037 org-loop-over-headlines-in-active-region
15039 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15040 (let ((org-setting-tags t))
15041 (if arg
15042 (save-excursion
15043 (goto-char (point-min))
15044 (while (re-search-forward org-outline-regexp-bol nil t)
15045 (org-set-tags nil t)
15046 (end-of-line))
15047 (message "All tags realigned to column %d" org-tags-column))
15048 (let* ((current (org-get-tags-string))
15049 (col (current-column))
15050 (tags
15051 (if just-align current
15052 ;; Get a new set of tags from the user.
15053 (save-excursion
15054 (let* ((seen)
15055 (table
15056 (setq
15057 org-last-tags-completion-table
15058 ;; Uniquify tags in alists, yet preserve
15059 ;; structure (i.e., keywords).
15060 (delq nil
15061 (mapcar
15062 (lambda (pair)
15063 (let ((head (car pair)))
15064 (cond ((symbolp head) pair)
15065 ((member head seen) nil)
15066 (t (push head seen)
15067 pair))))
15068 (append
15069 (or org-current-tag-alist
15070 (org-get-buffer-tags))
15071 (and
15072 org-complete-tags-always-offer-all-agenda-tags
15073 (org-global-tags-completion-table
15074 (org-agenda-files))))))))
15075 (current-tags (org-split-string current ":"))
15076 (inherited-tags
15077 (nreverse (nthcdr (length current-tags)
15078 (nreverse (org-get-tags-at))))))
15079 (replace-regexp-in-string
15080 "\\([-+&]+\\|,\\)"
15082 (if (or (eq t org-use-fast-tag-selection)
15083 (and org-use-fast-tag-selection
15084 (delq nil (mapcar #'cdr table))))
15085 (org-fast-tag-selection
15086 current-tags inherited-tags table
15087 (and org-fast-tag-selection-include-todo
15088 org-todo-key-alist))
15089 (let ((org-add-colon-after-tag-completion
15090 (< 1 (length table))))
15091 (org-trim
15092 (completing-read
15093 "Tags: "
15094 #'org-tags-completion-function
15095 nil nil current 'org-tags-history))))))))))
15097 (when org-tags-sort-function
15098 (setq tags
15099 (mapconcat
15100 #'identity
15101 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15102 org-tags-sort-function)
15103 ":")))
15105 (if (not (org-string-nw-p tags)) (setq tags "")
15106 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15107 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15109 ;; Insert new tags at the correct column
15110 (beginning-of-line)
15111 (let ((level (if (looking-at org-outline-regexp)
15112 (- (match-end 0) (point) 1)
15113 1)))
15114 (cond
15115 ((and (equal current "") (equal tags "")))
15116 ((re-search-forward
15117 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15118 (line-end-position)
15120 (if (equal tags "") (replace-match "" t t)
15121 (goto-char (match-beginning 0))
15122 (let* ((c0 (current-column))
15123 ;; Compute offset for the case of org-indent-mode
15124 ;; active.
15125 (di (if (bound-and-true-p org-indent-mode)
15126 (* (1- org-indent-indentation-per-level)
15127 (1- level))
15129 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15130 (tc (+ org-tags-column
15131 (if (> org-tags-column 0) (- di) di)))
15132 (c1 (max (1+ c0)
15133 (if (> tc 0) tc
15134 (- (- tc) (string-width tags)))))
15135 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15136 (replace-match rpl t t)
15137 (when indent-tabs-mode (tabify p0 (point))))))
15138 (t (error "Tags alignment failed"))))
15139 (org-move-to-column col))
15140 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15142 (defun org-change-tag-in-region (beg end tag off)
15143 "Add or remove TAG for each entry in the region.
15144 This works in the agenda, and also in an Org buffer."
15145 (interactive
15146 (list (region-beginning) (region-end)
15147 (let ((org-last-tags-completion-table
15148 (if (derived-mode-p 'org-mode)
15149 (org-uniquify
15150 (delq nil (append (org-get-buffer-tags)
15151 (org-global-tags-completion-table))))
15152 (org-global-tags-completion-table))))
15153 (completing-read
15154 "Tag: " 'org-tags-completion-function nil nil nil
15155 'org-tags-history))
15156 (progn
15157 (message "[s]et or [r]emove? ")
15158 (equal (read-char-exclusive) ?r))))
15159 (when (fboundp 'deactivate-mark) (deactivate-mark))
15160 (let ((agendap (equal major-mode 'org-agenda-mode))
15161 l1 l2 m buf pos newhead (cnt 0))
15162 (goto-char end)
15163 (setq l2 (1- (org-current-line)))
15164 (goto-char beg)
15165 (setq l1 (org-current-line))
15166 (cl-loop for l from l1 to l2 do
15167 (org-goto-line l)
15168 (setq m (get-text-property (point) 'org-hd-marker))
15169 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15170 (and agendap m))
15171 (setq buf (if agendap (marker-buffer m) (current-buffer))
15172 pos (if agendap m (point)))
15173 (with-current-buffer buf
15174 (save-excursion
15175 (save-restriction
15176 (goto-char pos)
15177 (setq cnt (1+ cnt))
15178 (org-toggle-tag tag (if off 'off 'on))
15179 (setq newhead (org-get-heading)))))
15180 (and agendap (org-agenda-change-all-lines newhead m))))
15181 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15183 (defun org-tags-completion-function (string _predicate &optional flag)
15184 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15185 (confirm (lambda (x) (stringp (car x)))))
15186 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15187 (setq s1 (match-string 1 string)
15188 s2 (match-string 2 string))
15189 (setq s1 "" s2 string))
15190 (cond
15191 ((eq flag nil)
15192 ;; try completion
15193 (setq rtn (try-completion s2 ctable confirm))
15194 (when (stringp rtn)
15195 (setq rtn
15196 (concat s1 s2 (substring rtn (length s2))
15197 (if (and org-add-colon-after-tag-completion
15198 (assoc rtn ctable))
15199 ":" ""))))
15200 rtn)
15201 ((eq flag t)
15202 ;; all-completions
15203 (all-completions s2 ctable confirm))
15204 ((eq flag 'lambda)
15205 ;; exact match?
15206 (assoc s2 ctable)))))
15208 (defun org-fast-tag-insert (kwd tags face &optional end)
15209 "Insert KDW, and the TAGS, the latter with face FACE.
15210 Also insert END."
15211 (insert (format "%-12s" (concat kwd ":"))
15212 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15213 (or end "")))
15215 (defun org-fast-tag-show-exit (flag)
15216 (save-excursion
15217 (org-goto-line 3)
15218 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15219 (replace-match ""))
15220 (when flag
15221 (end-of-line 1)
15222 (org-move-to-column (- (window-width) 19) t)
15223 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15225 (defun org-set-current-tags-overlay (current prefix)
15226 "Add an overlay to CURRENT tag with PREFIX."
15227 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15228 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15229 (org-overlay-display org-tags-overlay (concat prefix s))))
15231 (defvar org-last-tag-selection-key nil)
15232 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15233 "Fast tag selection with single keys.
15234 CURRENT is the current list of tags in the headline, INHERITED is the
15235 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15236 possibly with grouping information. TODO-TABLE is a similar table with
15237 TODO keywords, should these have keys assigned to them.
15238 If the keys are nil, a-z are automatically assigned.
15239 Returns the new tags string, or nil to not change the current settings."
15240 (let* ((fulltable (append table todo-table))
15241 (maxlen (apply 'max (mapcar
15242 (lambda (x)
15243 (if (stringp (car x)) (string-width (car x)) 0))
15244 fulltable)))
15245 (buf (current-buffer))
15246 (expert (eq org-fast-tag-selection-single-key 'expert))
15247 (buffer-tags nil)
15248 (fwidth (+ maxlen 3 1 3))
15249 (ncol (/ (- (window-width) 4) fwidth))
15250 (i-face 'org-done)
15251 (c-face 'org-todo)
15252 tg cnt e c char c1 c2 ntable tbl rtn
15253 ov-start ov-end ov-prefix
15254 (exit-after-next org-fast-tag-selection-single-key)
15255 (done-keywords org-done-keywords)
15256 groups ingroup intaggroup)
15257 (save-excursion
15258 (beginning-of-line 1)
15259 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15260 (setq ov-start (match-beginning 1)
15261 ov-end (match-end 1)
15262 ov-prefix "")
15263 (setq ov-start (1- (point-at-eol))
15264 ov-end (1+ ov-start))
15265 (skip-chars-forward "^\n\r")
15266 (setq ov-prefix
15267 (concat
15268 (buffer-substring (1- (point)) (point))
15269 (if (> (current-column) org-tags-column)
15271 (make-string (- org-tags-column (current-column)) ?\ ))))))
15272 (move-overlay org-tags-overlay ov-start ov-end)
15273 (save-window-excursion
15274 (if expert
15275 (set-buffer (get-buffer-create " *Org tags*"))
15276 (delete-other-windows)
15277 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15278 (org-switch-to-buffer-other-window " *Org tags*"))
15279 (erase-buffer)
15280 (setq-local org-done-keywords done-keywords)
15281 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15282 (org-fast-tag-insert "Current" current c-face "\n\n")
15283 (org-fast-tag-show-exit exit-after-next)
15284 (org-set-current-tags-overlay current ov-prefix)
15285 (setq tbl fulltable char ?a cnt 0)
15286 (while (setq e (pop tbl))
15287 (cond
15288 ((eq (car e) :startgroup)
15289 (push '() groups) (setq ingroup t)
15290 (unless (zerop cnt)
15291 (setq cnt 0)
15292 (insert "\n"))
15293 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15294 ((eq (car e) :endgroup)
15295 (setq ingroup nil cnt 0)
15296 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15297 ((eq (car e) :startgrouptag)
15298 (setq intaggroup t)
15299 (unless (zerop cnt)
15300 (setq cnt 0)
15301 (insert "\n"))
15302 (insert "[ "))
15303 ((eq (car e) :endgrouptag)
15304 (setq intaggroup nil cnt 0)
15305 (insert "]\n"))
15306 ((equal e '(:newline))
15307 (unless (zerop cnt)
15308 (setq cnt 0)
15309 (insert "\n")
15310 (setq e (car tbl))
15311 (while (equal (car tbl) '(:newline))
15312 (insert "\n")
15313 (setq tbl (cdr tbl)))))
15314 ((equal e '(:grouptags)) (insert " : "))
15316 (setq tg (copy-sequence (car e)) c2 nil)
15317 (if (cdr e)
15318 (setq c (cdr e))
15319 ;; automatically assign a character.
15320 (setq c1 (string-to-char
15321 (downcase (substring
15322 tg (if (= (string-to-char tg) ?@) 1 0)))))
15323 (if (or (rassoc c1 ntable) (rassoc c1 table))
15324 (while (or (rassoc char ntable) (rassoc char table))
15325 (setq char (1+ char)))
15326 (setq c2 c1))
15327 (setq c (or c2 char)))
15328 (when ingroup (push tg (car groups)))
15329 (setq tg (org-add-props tg nil 'face
15330 (cond
15331 ((not (assoc tg table))
15332 (org-get-todo-face tg))
15333 ((member tg current) c-face)
15334 ((member tg inherited) i-face))))
15335 (when (equal (caar tbl) :grouptags)
15336 (org-add-props tg nil 'face 'org-tag-group))
15337 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15338 (insert "[" c "] " tg (make-string
15339 (- fwidth 4 (length tg)) ?\ ))
15340 (push (cons tg c) ntable)
15341 (when (= (cl-incf cnt) ncol)
15342 (insert "\n")
15343 (when (or ingroup intaggroup) (insert " "))
15344 (setq cnt 0)))))
15345 (setq ntable (nreverse ntable))
15346 (insert "\n")
15347 (goto-char (point-min))
15348 (unless expert (org-fit-window-to-buffer))
15349 (setq rtn
15350 (catch 'exit
15351 (while t
15352 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15353 (if (not groups) "no " "")
15354 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15355 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15356 (setq org-last-tag-selection-key c)
15357 (cond
15358 ((= c ?\r) (throw 'exit t))
15359 ((= c ?!)
15360 (setq groups (not groups))
15361 (goto-char (point-min))
15362 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15363 ((= c ?\C-c)
15364 (if (not expert)
15365 (org-fast-tag-show-exit
15366 (setq exit-after-next (not exit-after-next)))
15367 (setq expert nil)
15368 (delete-other-windows)
15369 (set-window-buffer (split-window-vertically) " *Org tags*")
15370 (org-switch-to-buffer-other-window " *Org tags*")
15371 (org-fit-window-to-buffer)))
15372 ((or (= c ?\C-g)
15373 (and (= c ?q) (not (rassoc c ntable))))
15374 (delete-overlay org-tags-overlay)
15375 (setq quit-flag t))
15376 ((= c ?\ )
15377 (setq current nil)
15378 (when exit-after-next (setq exit-after-next 'now)))
15379 ((= c ?\t)
15380 (condition-case nil
15381 (setq tg (completing-read
15382 "Tag: "
15383 (or buffer-tags
15384 (with-current-buffer buf
15385 (setq buffer-tags
15386 (org-get-buffer-tags))))))
15387 (quit (setq tg "")))
15388 (when (string-match "\\S-" tg)
15389 (cl-pushnew (list tg) buffer-tags :test #'equal)
15390 (if (member tg current)
15391 (setq current (delete tg current))
15392 (push tg current)))
15393 (when exit-after-next (setq exit-after-next 'now)))
15394 ((setq e (rassoc c todo-table) tg (car e))
15395 (with-current-buffer buf
15396 (save-excursion (org-todo tg)))
15397 (when exit-after-next (setq exit-after-next 'now)))
15398 ((setq e (rassoc c ntable) tg (car e))
15399 (if (member tg current)
15400 (setq current (delete tg current))
15401 (cl-loop for g in groups do
15402 (when (member tg g)
15403 (dolist (x g) (setq current (delete x current)))))
15404 (push tg current))
15405 (when exit-after-next (setq exit-after-next 'now))))
15407 ;; Create a sorted list
15408 (setq current
15409 (sort current
15410 (lambda (a b)
15411 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15412 (when (eq exit-after-next 'now) (throw 'exit t))
15413 (goto-char (point-min))
15414 (beginning-of-line 2)
15415 (delete-region (point) (point-at-eol))
15416 (org-fast-tag-insert "Current" current c-face)
15417 (org-set-current-tags-overlay current ov-prefix)
15418 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15419 (setq tg (match-string 1))
15420 (add-text-properties
15421 (match-beginning 1) (match-end 1)
15422 (list 'face
15423 (cond
15424 ((member tg current) c-face)
15425 ((member tg inherited) i-face)
15426 (t (get-text-property (match-beginning 1) 'face))))))
15427 (goto-char (point-min)))))
15428 (delete-overlay org-tags-overlay)
15429 (if rtn
15430 (mapconcat 'identity current ":")
15431 nil))))
15433 (defun org-get-tags-string ()
15434 "Get the TAGS string in the current headline."
15435 (unless (org-at-heading-p t)
15436 (user-error "Not on a heading"))
15437 (save-excursion
15438 (beginning-of-line 1)
15439 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15440 (match-string-no-properties 1)
15441 "")))
15443 (defun org-get-tags ()
15444 "Get the list of tags specified in the current headline."
15445 (org-split-string (org-get-tags-string) ":"))
15447 (defun org-get-buffer-tags ()
15448 "Get a table of all tags used in the buffer, for completion."
15449 (org-with-wide-buffer
15450 (goto-char (point-min))
15451 (let ((tag-re (concat org-outline-regexp-bol
15452 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15453 tags)
15454 (while (re-search-forward tag-re nil t)
15455 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15456 (push tag tags)))
15457 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15459 ;;;; The mapping API
15461 (defvar org-agenda-skip-comment-trees)
15462 (defvar org-agenda-skip-function)
15463 (defun org-map-entries (func &optional match scope &rest skip)
15464 "Call FUNC at each headline selected by MATCH in SCOPE.
15466 FUNC is a function or a lisp form. The function will be called without
15467 arguments, with the cursor positioned at the beginning of the headline.
15468 The return values of all calls to the function will be collected and
15469 returned as a list.
15471 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15472 does not need to preserve point. After evaluation, the cursor will be
15473 moved to the end of the line (presumably of the headline of the
15474 processed entry) and search continues from there. Under some
15475 circumstances, this may not produce the wanted results. For example,
15476 if you have removed (e.g. archived) the current (sub)tree it could
15477 mean that the next entry will be skipped entirely. In such cases, you
15478 can specify the position from where search should continue by making
15479 FUNC set the variable `org-map-continue-from' to the desired buffer
15480 position.
15482 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15483 Only headlines that are matched by this query will be considered during
15484 the iteration. When MATCH is nil or t, all headlines will be
15485 visited by the iteration.
15487 SCOPE determines the scope of this command. It can be any of:
15489 nil The current buffer, respecting the restriction if any
15490 tree The subtree started with the entry at point
15491 region The entries within the active region, if any
15492 region-start-level
15493 The entries within the active region, but only those at
15494 the same level than the first one.
15495 file The current buffer, without restriction
15496 file-with-archives
15497 The current buffer, and any archives associated with it
15498 agenda All agenda files
15499 agenda-with-archives
15500 All agenda files with any archive files associated with them
15501 \(file1 file2 ...)
15502 If this is a list, all files in the list will be scanned
15504 The remaining args are treated as settings for the skipping facilities of
15505 the scanner. The following items can be given here:
15507 archive skip trees with the archive tag
15508 comment skip trees with the COMMENT keyword
15509 function or Emacs Lisp form:
15510 will be used as value for `org-agenda-skip-function', so
15511 whenever the function returns a position, FUNC will not be
15512 called for that entry and search will continue from the
15513 position returned
15515 If your function needs to retrieve the tags including inherited tags
15516 at the *current* entry, you can use the value of the variable
15517 `org-scanner-tags' which will be much faster than getting the value
15518 with `org-get-tags-at'. If your function gets properties with
15519 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15520 to t around the call to `org-entry-properties' to get the same speedup.
15521 Note that if your function moves around to retrieve tags and properties at
15522 a *different* entry, you cannot use these techniques."
15523 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15524 (not (org-region-active-p)))
15525 (let* ((org-agenda-archives-mode nil) ; just to make sure
15526 (org-agenda-skip-archived-trees (memq 'archive skip))
15527 (org-agenda-skip-comment-trees (memq 'comment skip))
15528 (org-agenda-skip-function
15529 (car (org-delete-all '(comment archive) skip)))
15530 (org-tags-match-list-sublevels t)
15531 (start-level (eq scope 'region-start-level))
15532 matcher res
15533 org-todo-keywords-for-agenda
15534 org-done-keywords-for-agenda
15535 org-todo-keyword-alist-for-agenda
15536 org-tag-alist-for-agenda
15537 org--matcher-tags-todo-only)
15539 (cond
15540 ((eq match t) (setq matcher t))
15541 ((eq match nil) (setq matcher t))
15542 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15544 (save-excursion
15545 (save-restriction
15546 (cond ((eq scope 'tree)
15547 (org-back-to-heading t)
15548 (org-narrow-to-subtree)
15549 (setq scope nil))
15550 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15551 (org-region-active-p))
15552 ;; If needed, set start-level to a string like "2"
15553 (when start-level
15554 (save-excursion
15555 (goto-char (region-beginning))
15556 (unless (org-at-heading-p) (outline-next-heading))
15557 (setq start-level (org-current-level))))
15558 (narrow-to-region (region-beginning)
15559 (save-excursion
15560 (goto-char (region-end))
15561 (unless (and (bolp) (org-at-heading-p))
15562 (outline-next-heading))
15563 (point)))
15564 (setq scope nil)))
15566 (if (not scope)
15567 (progn
15568 (org-agenda-prepare-buffers
15569 (and buffer-file-name (list buffer-file-name)))
15570 (setq res
15571 (org-scan-tags
15572 func matcher org--matcher-tags-todo-only start-level)))
15573 ;; Get the right scope
15574 (cond
15575 ((and scope (listp scope) (symbolp (car scope)))
15576 (setq scope (eval scope)))
15577 ((eq scope 'agenda)
15578 (setq scope (org-agenda-files t)))
15579 ((eq scope 'agenda-with-archives)
15580 (setq scope (org-agenda-files t))
15581 (setq scope (org-add-archive-files scope)))
15582 ((eq scope 'file)
15583 (setq scope (and buffer-file-name (list buffer-file-name))))
15584 ((eq scope 'file-with-archives)
15585 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15586 (org-agenda-prepare-buffers scope)
15587 (dolist (file scope)
15588 (with-current-buffer (org-find-base-buffer-visiting file)
15589 (org-with-wide-buffer
15590 (goto-char (point-min))
15591 (setq res
15592 (append
15594 (org-scan-tags
15595 func matcher org--matcher-tags-todo-only)))))))))
15596 res)))
15598 ;;; Properties API
15600 (defconst org-special-properties
15601 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15602 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15603 "The special properties valid in Org mode.
15604 These are properties that are not defined in the property drawer,
15605 but in some other way.")
15607 (defconst org-default-properties
15608 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15609 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15610 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15611 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15612 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15613 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15614 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15615 "Some properties that are used by Org mode for various purposes.
15616 Being in this list makes sure that they are offered for completion.")
15618 (defun org--valid-property-p (property)
15619 "Non nil when string PROPERTY is a valid property name."
15620 (not
15621 (or (equal property "")
15622 (string-match-p "\\s-" property))))
15624 (defun org--update-property-plist (key val props)
15625 "Associate KEY to VAL in alist PROPS.
15626 Modifications are made by side-effect. Return new alist."
15627 (let* ((appending (string= (substring key -1) "+"))
15628 (key (if appending (substring key 0 -1) key))
15629 (old (assoc-string key props t)))
15630 (if (not old) (cons (cons key val) props)
15631 (setcdr old (if appending (concat (cdr old) " " val) val))
15632 props)))
15634 (defun org-get-property-block (&optional beg force)
15635 "Return the (beg . end) range of the body of the property drawer.
15636 BEG is the beginning of the current subtree, or of the part
15637 before the first headline. If it is not given, it will be found.
15638 If the drawer does not exist, create it if FORCE is non-nil, or
15639 return nil."
15640 (org-with-wide-buffer
15641 (when beg (goto-char beg))
15642 (unless (org-before-first-heading-p)
15643 (let ((beg (cond (beg)
15644 ((or (not (featurep 'org-inlinetask))
15645 (org-inlinetask-in-task-p))
15646 (org-back-to-heading t))
15647 (t (org-with-limited-levels (org-back-to-heading t))))))
15648 (forward-line)
15649 (when (looking-at-p org-planning-line-re) (forward-line))
15650 (cond ((looking-at org-property-drawer-re)
15651 (forward-line)
15652 (cons (point) (progn (goto-char (match-end 0))
15653 (line-beginning-position))))
15654 (force
15655 (goto-char beg)
15656 (org-insert-property-drawer)
15657 (let ((pos (save-excursion (search-forward ":END:")
15658 (line-beginning-position))))
15659 (cons pos pos))))))))
15661 (defun org-at-property-p ()
15662 "Non-nil when point is inside a property drawer.
15663 See `org-property-re' for match data, if applicable."
15664 (save-excursion
15665 (beginning-of-line)
15666 (and (looking-at org-property-re)
15667 (let ((property-drawer (save-match-data (org-get-property-block))))
15668 (and property-drawer
15669 (>= (point) (car property-drawer))
15670 (< (point) (cdr property-drawer)))))))
15672 (defun org-property-action ()
15673 "Do an action on properties."
15674 (interactive)
15675 (unless (org-at-property-p) (user-error "Not at a property"))
15676 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15677 (let ((c (read-char-exclusive)))
15678 (cl-case c
15679 (?s (call-interactively #'org-set-property))
15680 (?d (call-interactively #'org-delete-property))
15681 (?D (call-interactively #'org-delete-property-globally))
15682 (?c (call-interactively #'org-compute-property-at-point))
15683 (otherwise (user-error "No such property action %c" c)))))
15685 (defun org-inc-effort ()
15686 "Increment the value of the effort property in the current entry."
15687 (interactive)
15688 (org-set-effort nil t))
15690 (defvar org-clock-effort) ; Defined in org-clock.el.
15691 (defvar org-clock-current-task) ; Defined in org-clock.el.
15692 (defun org-set-effort (&optional value increment)
15693 "Set the effort property of the current entry.
15694 With numerical prefix arg, use the nth allowed value, 0 stands for the
15695 10th allowed value.
15697 When INCREMENT is non-nil, set the property to the next allowed value."
15698 (interactive "P")
15699 (when (equal value 0) (setq value 10))
15700 (let* ((completion-ignore-case t)
15701 (prop org-effort-property)
15702 (cur (org-entry-get nil prop))
15703 (allowed (org-property-get-allowed-values nil prop 'table))
15704 (existing (mapcar 'list (org-property-values prop)))
15705 (heading (nth 4 (org-heading-components)))
15707 (val (cond
15708 ((stringp value) value)
15709 ((and allowed (integerp value))
15710 (or (car (nth (1- value) allowed))
15711 (car (org-last allowed))))
15712 ((and allowed increment)
15713 (or (cl-caadr (member (list cur) allowed))
15714 (user-error "Allowed effort values are not set")))
15715 (allowed
15716 (message "Select 1-9,0, [RET%s]: %s"
15717 (if cur (concat "=" cur) "")
15718 (mapconcat 'car allowed " "))
15719 (setq rpl (read-char-exclusive))
15720 (if (equal rpl ?\r)
15722 (setq rpl (- rpl ?0))
15723 (when (equal rpl 0) (setq rpl 10))
15724 (if (and (> rpl 0) (<= rpl (length allowed)))
15725 (car (nth (1- rpl) allowed))
15726 (org-completing-read "Effort: " allowed nil))))
15728 (org-completing-read
15729 (concat "Effort" (and cur (string-match "\\S-" cur)
15730 (concat " [" cur "]"))
15731 ": ")
15732 existing nil nil "" nil cur)))))
15733 (unless (equal (org-entry-get nil prop) val)
15734 (org-entry-put nil prop val))
15735 (org-refresh-property
15736 '((effort . identity)
15737 (effort-minutes . org-duration-string-to-minutes))
15738 val)
15739 (when (equal heading (bound-and-true-p org-clock-current-task))
15740 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15741 (org-clock-update-mode-line))
15742 (message "%s is now %s" prop val)))
15744 (defun org-entry-properties (&optional pom which)
15745 "Get all properties of the current entry.
15747 When POM is a buffer position, get all properties from the entry
15748 there instead.
15750 This includes the TODO keyword, the tags, time strings for
15751 deadline, scheduled, and clocking, and any additional properties
15752 defined in the entry.
15754 If WHICH is nil or `all', get all properties. If WHICH is
15755 `special' or `standard', only get that subclass. If WHICH is
15756 a string, only get that property.
15758 Return value is an alist. Keys are properties, as upcased
15759 strings."
15760 (org-with-point-at pom
15761 (when (and (derived-mode-p 'org-mode)
15762 (ignore-errors (org-back-to-heading t)))
15763 (catch 'exit
15764 (let* ((beg (point))
15765 (specific (and (stringp which) (upcase which)))
15766 (which (cond ((not specific) which)
15767 ((member specific org-special-properties) 'special)
15768 (t 'standard)))
15769 props)
15770 ;; Get the special properties, like TODO and TAGS.
15771 (when (memq which '(nil all special))
15772 (when (or (not specific) (string= specific "CLOCKSUM"))
15773 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15774 (when clocksum
15775 (push (cons "CLOCKSUM"
15776 (org-minutes-to-clocksum-string clocksum))
15777 props)))
15778 (when specific (throw 'exit props)))
15779 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15780 (let ((clocksumt (get-text-property (point)
15781 :org-clock-minutes-today)))
15782 (when clocksumt
15783 (push (cons "CLOCKSUM_T"
15784 (org-minutes-to-clocksum-string clocksumt))
15785 props)))
15786 (when specific (throw 'exit props)))
15787 (when (or (not specific) (string= specific "ITEM"))
15788 (when (looking-at org-complex-heading-regexp)
15789 (push (cons "ITEM"
15790 (let ((title (match-string-no-properties 4)))
15791 (if (org-string-nw-p title)
15792 (org-remove-tabs title)
15793 "")))
15794 props))
15795 (when specific (throw 'exit props)))
15796 (when (or (not specific) (string= specific "TODO"))
15797 (let ((case-fold-search nil))
15798 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15799 (push (cons "TODO" (match-string-no-properties 2)) props)))
15800 (when specific (throw 'exit props)))
15801 (when (or (not specific) (string= specific "PRIORITY"))
15802 (push (cons "PRIORITY"
15803 (if (looking-at org-priority-regexp)
15804 (match-string-no-properties 2)
15805 (char-to-string org-default-priority)))
15806 props)
15807 (when specific (throw 'exit props)))
15808 (when (or (not specific) (string= specific "FILE"))
15809 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15810 props)
15811 (when specific (throw 'exit props)))
15812 (when (or (not specific) (string= specific "TAGS"))
15813 (let ((value (org-string-nw-p (org-get-tags-string))))
15814 (when value (push (cons "TAGS" value) props)))
15815 (when specific (throw 'exit props)))
15816 (when (or (not specific) (string= specific "ALLTAGS"))
15817 (let ((value (org-get-tags-at)))
15818 (when value
15819 (push (cons "ALLTAGS"
15820 (format ":%s:" (mapconcat #'identity value ":")))
15821 props)))
15822 (when specific (throw 'exit props)))
15823 (when (or (not specific) (string= specific "BLOCKED"))
15824 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15825 (when specific (throw 'exit props)))
15826 (when (or (not specific)
15827 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15828 (forward-line)
15829 (when (looking-at-p org-planning-line-re)
15830 (end-of-line)
15831 (let ((bol (line-beginning-position))
15832 ;; Backward compatibility: time keywords used to
15833 ;; be configurable (before 8.3). Make sure we
15834 ;; get the correct keyword.
15835 (key-assoc `(("CLOSED" . ,org-closed-string)
15836 ("DEADLINE" . ,org-deadline-string)
15837 ("SCHEDULED" . ,org-scheduled-string))))
15838 (dolist (pair (if specific (list (assoc specific key-assoc))
15839 key-assoc))
15840 (save-excursion
15841 (when (search-backward (cdr pair) bol t)
15842 (goto-char (match-end 0))
15843 (skip-chars-forward " \t")
15844 (and (looking-at org-ts-regexp-both)
15845 (push (cons (car pair)
15846 (match-string-no-properties 0))
15847 props)))))))
15848 (when specific (throw 'exit props)))
15849 (when (or (not specific)
15850 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15851 (let ((find-ts
15852 (lambda (end ts)
15853 ;; Fix next time-stamp before END. TS is the
15854 ;; list of time-stamps found so far.
15855 (let ((ts ts)
15856 (regexp (cond
15857 ((string= specific "TIMESTAMP")
15858 org-ts-regexp)
15859 ((string= specific "TIMESTAMP_IA")
15860 org-ts-regexp-inactive)
15861 ((assoc "TIMESTAMP_IA" ts)
15862 org-ts-regexp)
15863 ((assoc "TIMESTAMP" ts)
15864 org-ts-regexp-inactive)
15865 (t org-ts-regexp-both))))
15866 (catch 'next
15867 (while (re-search-forward regexp end t)
15868 (backward-char)
15869 (let ((object (org-element-context)))
15870 ;; Accept to match timestamps in node
15871 ;; properties, too.
15872 (when (memq (org-element-type object)
15873 '(node-property timestamp))
15874 (let ((type
15875 (org-element-property :type object)))
15876 (cond
15877 ((and (memq type '(active active-range))
15878 (not (equal specific "TIMESTAMP_IA")))
15879 (unless (assoc "TIMESTAMP" ts)
15880 (push (cons "TIMESTAMP"
15881 (org-element-property
15882 :raw-value object))
15884 (when specific (throw 'exit ts))))
15885 ((and (memq type '(inactive inactive-range))
15886 (not (string= specific "TIMESTAMP")))
15887 (unless (assoc "TIMESTAMP_IA" ts)
15888 (push (cons "TIMESTAMP_IA"
15889 (org-element-property
15890 :raw-value object))
15892 (when specific (throw 'exit ts))))))
15893 ;; Both timestamp types are found,
15894 ;; move to next part.
15895 (when (= (length ts) 2) (throw 'next ts)))))
15896 ts)))))
15897 (goto-char beg)
15898 ;; First look for timestamps within headline.
15899 (let ((ts (funcall find-ts (line-end-position) nil)))
15900 (if (= (length ts) 2) (setq props (nconc ts props))
15901 (forward-line)
15902 ;; Then find timestamps in the section, skipping
15903 ;; planning line.
15904 (when (looking-at-p org-planning-line-re)
15905 (forward-line))
15906 (let ((end (save-excursion (outline-next-heading))))
15907 (setq props (nconc (funcall find-ts end ts) props))))))))
15908 ;; Get the standard properties, like :PROP:.
15909 (when (memq which '(nil all standard))
15910 ;; If we are looking after a specific property, delegate
15911 ;; to `org-entry-get', which is faster. However, make an
15912 ;; exception for "CATEGORY", since it can be also set
15913 ;; through keywords (i.e. #+CATEGORY).
15914 (if (and specific (not (equal specific "CATEGORY")))
15915 (let ((value (org-entry-get beg specific nil t)))
15916 (throw 'exit (and value (list (cons specific value)))))
15917 (let ((range (org-get-property-block beg)))
15918 (when range
15919 (let ((end (cdr range)) seen-base)
15920 (goto-char (car range))
15921 ;; Unlike to `org--update-property-plist', we
15922 ;; handle the case where base values is found
15923 ;; after its extension. We also forbid standard
15924 ;; properties to be named as special properties.
15925 (while (re-search-forward org-property-re end t)
15926 (let* ((key (upcase (match-string-no-properties 2)))
15927 (extendp (string-match-p "\\+\\'" key))
15928 (key-base (if extendp (substring key 0 -1) key))
15929 (value (match-string-no-properties 3)))
15930 (cond
15931 ((member-ignore-case key-base org-special-properties))
15932 (extendp
15933 (setq props
15934 (org--update-property-plist key value props)))
15935 ((member key seen-base))
15936 (t (push key seen-base)
15937 (let ((p (assoc-string key props t)))
15938 (if p (setcdr p (concat value " " (cdr p)))
15939 (push (cons key value) props))))))))))))
15940 (unless (assoc "CATEGORY" props)
15941 (push (cons "CATEGORY" (org-get-category beg)) props)
15942 (when (string= specific "CATEGORY") (throw 'exit props)))
15943 ;; Return value.
15944 props)))))
15946 (defun org-property--local-values (property literal-nil)
15947 "Return value for PROPERTY in current entry.
15948 Value is a list whose car is the base value for PROPERTY and cdr
15949 a list of accumulated values. Return nil if neither is found in
15950 the entry. Also return nil when PROPERTY is set to \"nil\",
15951 unless LITERAL-NIL is non-nil."
15952 (let ((range (org-get-property-block)))
15953 (when range
15954 (goto-char (car range))
15955 (let* ((case-fold-search t)
15956 (end (cdr range))
15957 (value
15958 ;; Base value.
15959 (save-excursion
15960 (let ((v (and (re-search-forward
15961 (org-re-property property nil t) end t)
15962 (match-string-no-properties 3))))
15963 (list (if literal-nil v (org-not-nil v)))))))
15964 ;; Find additional values.
15965 (let* ((property+ (org-re-property (concat property "+") nil t)))
15966 (while (re-search-forward property+ end t)
15967 (push (match-string-no-properties 3) value)))
15968 ;; Return final values.
15969 (and (not (equal value '(nil))) (nreverse value))))))
15971 (defun org-entry-get (pom property &optional inherit literal-nil)
15972 "Get value of PROPERTY for entry or content at point-or-marker POM.
15974 If INHERIT is non-nil and the entry does not have the property,
15975 then also check higher levels of the hierarchy. If INHERIT is
15976 the symbol `selective', use inheritance only if the setting in
15977 `org-use-property-inheritance' selects PROPERTY for inheritance.
15979 If the property is present but empty, the return value is the
15980 empty string. If the property is not present at all, nil is
15981 returned. In any other case, return the value as a string.
15982 Search is case-insensitive.
15984 If LITERAL-NIL is set, return the string value \"nil\" as
15985 a string, do not interpret it as the list atom nil. This is used
15986 for inheritance when a \"nil\" value can supersede a non-nil
15987 value higher up the hierarchy."
15988 (org-with-point-at pom
15989 (cond
15990 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15991 ;; We need a special property. Use `org-entry-properties' to
15992 ;; retrieve it, but specify the wanted property.
15993 (cdr (assoc-string property (org-entry-properties nil property))))
15994 ((and inherit
15995 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15996 (org-entry-get-with-inheritance property literal-nil))
15998 (let* ((local (org-property--local-values property literal-nil))
15999 (value (and local (mapconcat #'identity (delq nil local) " "))))
16000 (if literal-nil value (org-not-nil value)))))))
16002 (defun org-property-or-variable-value (var &optional inherit)
16003 "Check if there is a property fixing the value of VAR.
16004 If yes, return this value. If not, return the current value of the variable."
16005 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16006 (if (and prop (stringp prop) (string-match "\\S-" prop))
16007 (read prop)
16008 (symbol-value var))))
16010 (defun org-entry-delete (pom property)
16011 "Delete PROPERTY from entry at point-or-marker POM.
16012 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16013 non-nil when a property was removed."
16014 (unless (member property org-special-properties)
16015 (org-with-point-at pom
16016 (let ((range (org-get-property-block)))
16017 (when range
16018 (let* ((begin (car range))
16019 (origin (cdr range))
16020 (end (copy-marker origin))
16021 (re (org-re-property
16022 (concat (regexp-quote property) "\\+?") t t)))
16023 (goto-char begin)
16024 (while (re-search-forward re end t)
16025 (delete-region (match-beginning 0) (line-beginning-position 2)))
16026 ;; If drawer is empty, remove it altogether.
16027 (when (= begin end)
16028 (delete-region (line-beginning-position 0)
16029 (line-beginning-position 2)))
16030 ;; Return non-nil if some property was removed.
16031 (prog1 (/= end origin) (set-marker end nil))))))))
16033 ;; Multi-values properties are properties that contain multiple values
16034 ;; These values are assumed to be single words, separated by whitespace.
16035 (defun org-entry-add-to-multivalued-property (pom property value)
16036 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16037 (let* ((old (org-entry-get pom property))
16038 (values (and old (org-split-string old "[ \t]"))))
16039 (setq value (org-entry-protect-space value))
16040 (unless (member value values)
16041 (setq values (append values (list value)))
16042 (org-entry-put pom property
16043 (mapconcat 'identity values " ")))))
16045 (defun org-entry-remove-from-multivalued-property (pom property value)
16046 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16047 (let* ((old (org-entry-get pom property))
16048 (values (and old (org-split-string old "[ \t]"))))
16049 (setq value (org-entry-protect-space value))
16050 (when (member value values)
16051 (setq values (delete value values))
16052 (org-entry-put pom property
16053 (mapconcat 'identity values " ")))))
16055 (defun org-entry-member-in-multivalued-property (pom property value)
16056 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16057 (let* ((old (org-entry-get pom property))
16058 (values (and old (org-split-string old "[ \t]"))))
16059 (setq value (org-entry-protect-space value))
16060 (member value values)))
16062 (defun org-entry-get-multivalued-property (pom property)
16063 "Return a list of values in a multivalued property."
16064 (let* ((value (org-entry-get pom property))
16065 (values (and value (org-split-string value "[ \t]"))))
16066 (mapcar 'org-entry-restore-space values)))
16068 (defun org-entry-put-multivalued-property (pom property &rest values)
16069 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16070 VALUES should be a list of strings. Spaces will be protected."
16071 (org-entry-put pom property
16072 (mapconcat 'org-entry-protect-space values " "))
16073 (let* ((value (org-entry-get pom property))
16074 (values (and value (org-split-string value "[ \t]"))))
16075 (mapcar 'org-entry-restore-space values)))
16077 (defun org-entry-protect-space (s)
16078 "Protect spaces and newline in string S."
16079 (while (string-match " " s)
16080 (setq s (replace-match "%20" t t s)))
16081 (while (string-match "\n" s)
16082 (setq s (replace-match "%0A" t t s)))
16085 (defun org-entry-restore-space (s)
16086 "Restore spaces and newline in string S."
16087 (while (string-match "%20" s)
16088 (setq s (replace-match " " t t s)))
16089 (while (string-match "%0A" s)
16090 (setq s (replace-match "\n" t t s)))
16093 (defvar org-entry-property-inherited-from (make-marker)
16094 "Marker pointing to the entry from where a property was inherited.
16095 Each call to `org-entry-get-with-inheritance' will set this marker to the
16096 location of the entry where the inheritance search matched. If there was
16097 no match, the marker will point nowhere.
16098 Note that also `org-entry-get' calls this function, if the INHERIT flag
16099 is set.")
16101 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16102 "Get PROPERTY of entry or content at point, search higher levels if needed.
16103 The search will stop at the first ancestor which has the property defined.
16104 If the value found is \"nil\", return nil to show that the property
16105 should be considered as undefined (this is the meaning of nil here).
16106 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16107 (move-marker org-entry-property-inherited-from nil)
16108 (org-with-wide-buffer
16109 (let (value)
16110 (catch 'exit
16111 (while t
16112 (let ((v (org-property--local-values property literal-nil)))
16113 (when v
16114 (setq value
16115 (concat (mapconcat #'identity (delq nil v) " ")
16116 (and value " ")
16117 value)))
16118 (cond
16119 ((car v)
16120 (org-back-to-heading t)
16121 (move-marker org-entry-property-inherited-from (point))
16122 (throw 'exit nil))
16123 ((org-up-heading-safe))
16125 (let ((global
16126 (cdr (or (assoc-string property org-file-properties t)
16127 (assoc-string property org-global-properties t)
16128 (assoc-string property org-global-properties-fixed t)))))
16129 (cond ((not global))
16130 (value (setq value (concat global " " value)))
16131 (t (setq value global))))
16132 (throw 'exit nil))))))
16133 (if literal-nil value (org-not-nil value)))))
16135 (defvar org-property-changed-functions nil
16136 "Hook called when the value of a property has changed.
16137 Each hook function should accept two arguments, the name of the property
16138 and the new value.")
16140 (defun org-entry-put (pom property value)
16141 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16143 If the value is nil, it is converted to the empty string. If it
16144 is not a string, an error is raised. Also raise an error on
16145 invalid property names.
16147 PROPERTY can be any regular property (see
16148 `org-special-properties'). It can also be \"TODO\",
16149 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16151 For the last two properties, VALUE may have any of the special
16152 values \"earlier\" and \"later\". The function then increases or
16153 decreases scheduled or deadline date by one day."
16154 (cond ((null value) (setq value ""))
16155 ((not (stringp value)) (error "Properties values should be strings"))
16156 ((not (org--valid-property-p property))
16157 (user-error "Invalid property name: \"%s\"" property)))
16158 (org-with-point-at pom
16159 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16160 (org-back-to-heading t)
16161 (org-with-limited-levels (org-back-to-heading t)))
16162 (let ((beg (point)))
16163 (cond
16164 ((equal property "TODO")
16165 (cond ((not (org-string-nw-p value)) (setq value 'none))
16166 ((not (member value org-todo-keywords-1))
16167 (user-error "\"%s\" is not a valid TODO state" value)))
16168 (org-todo value)
16169 (org-set-tags nil 'align))
16170 ((equal property "PRIORITY")
16171 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16172 (org-set-tags nil 'align))
16173 ((equal property "SCHEDULED")
16174 (forward-line)
16175 (if (and (looking-at-p org-planning-line-re)
16176 (re-search-forward
16177 org-scheduled-time-regexp (line-end-position) t))
16178 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16179 ((string= value "later") (org-timestamp-change 1 'day))
16180 ((string= value "") (org-schedule '(4)))
16181 (t (org-schedule nil value)))
16182 (if (member value '("earlier" "later" ""))
16183 (call-interactively #'org-schedule)
16184 (org-schedule nil value))))
16185 ((equal property "DEADLINE")
16186 (forward-line)
16187 (if (and (looking-at-p org-planning-line-re)
16188 (re-search-forward
16189 org-deadline-time-regexp (line-end-position) t))
16190 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16191 ((string= value "later") (org-timestamp-change 1 'day))
16192 ((string= value "") (org-deadline '(4)))
16193 (t (org-deadline nil value)))
16194 (if (member value '("earlier" "later" ""))
16195 (call-interactively #'org-deadline)
16196 (org-deadline nil value))))
16197 ((member property org-special-properties)
16198 (error "The %s property cannot be set with `org-entry-put'" property))
16200 (let* ((range (org-get-property-block beg 'force))
16201 (end (cdr range))
16202 (case-fold-search t))
16203 (goto-char (car range))
16204 (if (re-search-forward (org-re-property property nil t) end t)
16205 (progn (delete-region (match-beginning 0) (match-end 0))
16206 (goto-char (match-beginning 0)))
16207 (goto-char end)
16208 (insert "\n")
16209 (backward-char))
16210 (insert ":" property ":")
16211 (when value (insert " " value))
16212 (org-indent-line)))))
16213 (run-hook-with-args 'org-property-changed-functions property value)))
16215 (defun org-buffer-property-keys
16216 (&optional specials defaults columns ignore-malformed)
16217 "Get all property keys in the current buffer.
16219 When SPECIALS is non-nil, also list the special properties that
16220 reflect things like tags and TODO state.
16222 When DEFAULTS is non-nil, also include properties that has
16223 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16224 DESCRIPTION, LOCATION, and LOGGING and others.
16226 When COLUMNS in non-nil, also include property names given in
16227 COLUMN formats in the current buffer.
16229 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16230 automatically performed, such drawers will be silently ignored."
16231 (let ((case-fold-search t)
16232 (props (append
16233 (and specials org-special-properties)
16234 (and defaults (cons org-effort-property org-default-properties))
16235 nil)))
16236 (org-with-wide-buffer
16237 (goto-char (point-min))
16238 (while (re-search-forward org-property-start-re nil t)
16239 (let ((range (org-get-property-block)))
16240 (catch 'skip
16241 (unless range
16242 (when (and (not ignore-malformed)
16243 (not (org-before-first-heading-p))
16244 (y-or-n-p (format "Malformed drawer at %d, repair?"
16245 (line-beginning-position))))
16246 (org-get-property-block nil t))
16247 (throw 'skip nil))
16248 (goto-char (car range))
16249 (let ((begin (car range))
16250 (end (cdr range)))
16251 ;; Make sure that found property block is not located
16252 ;; before current point, as it would generate an infloop.
16253 ;; It can happen, for example, in the following
16254 ;; situation:
16256 ;; * Headline
16257 ;; :PROPERTIES:
16258 ;; ...
16259 ;; :END:
16260 ;; *************** Inlinetask
16261 ;; #+BEGIN_EXAMPLE
16262 ;; :PROPERTIES:
16263 ;; #+END_EXAMPLE
16265 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16266 (while (< (point) end)
16267 (let ((p (progn (looking-at org-property-re)
16268 (match-string-no-properties 2))))
16269 ;; Only add true property name, not extension symbol.
16270 (push (if (not (string-match-p "\\+\\'" p)) p
16271 (substring p 0 -1))
16272 props))
16273 (forward-line))))
16274 (outline-next-heading)))
16275 (when columns
16276 (goto-char (point-min))
16277 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16278 (let ((element (org-element-at-point)))
16279 (when (memq (org-element-type element) '(keyword node-property))
16280 (let ((value (org-element-property :value element))
16281 (start 0))
16282 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16283 (setq start (match-end 0))
16284 (let ((p (match-string-no-properties 1 value)))
16285 (unless (member-ignore-case p org-special-properties)
16286 (push p props))))))))))
16287 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16289 (defun org-property-values (key)
16290 "List all non-nil values of property KEY in current buffer."
16291 (org-with-wide-buffer
16292 (goto-char (point-min))
16293 (let ((case-fold-search t)
16294 (re (org-re-property key))
16295 values)
16296 (while (re-search-forward re nil t)
16297 (push (org-entry-get (point) key) values))
16298 (delete-dups values))))
16300 (defun org-insert-property-drawer ()
16301 "Insert a property drawer into the current entry."
16302 (org-with-wide-buffer
16303 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16304 (org-back-to-heading t)
16305 (org-with-limited-levels (org-back-to-heading t)))
16306 (forward-line)
16307 (when (looking-at-p org-planning-line-re) (forward-line))
16308 (unless (looking-at-p org-property-drawer-re)
16309 ;; Make sure we start editing a line from current entry, not from
16310 ;; next one. It prevents extending text properties or overlays
16311 ;; belonging to the latter.
16312 (when (bolp) (backward-char))
16313 (let ((begin (1+ (point)))
16314 (inhibit-read-only t))
16315 (insert "\n:PROPERTIES:\n:END:")
16316 (when (eobp) (insert "\n"))
16317 (org-indent-region begin (point))))))
16319 (defun org-insert-drawer (&optional arg drawer)
16320 "Insert a drawer at point.
16322 When optional argument ARG is non-nil, insert a property drawer.
16324 Optional argument DRAWER, when non-nil, is a string representing
16325 drawer's name. Otherwise, the user is prompted for a name.
16327 If a region is active, insert the drawer around that region
16328 instead.
16330 Point is left between drawer's boundaries."
16331 (interactive "P")
16332 (let* ((drawer (if arg "PROPERTIES"
16333 (or drawer (read-from-minibuffer "Drawer: ")))))
16334 (cond
16335 ;; With C-u, fall back on `org-insert-property-drawer'
16336 (arg (org-insert-property-drawer))
16337 ;; Check validity of suggested drawer's name.
16338 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16339 (user-error "Invalid drawer name"))
16340 ;; With an active region, insert a drawer at point.
16341 ((not (org-region-active-p))
16342 (progn
16343 (unless (bolp) (insert "\n"))
16344 (insert (format ":%s:\n\n:END:\n" drawer))
16345 (forward-line -2)))
16346 ;; Otherwise, insert the drawer at point
16348 (let ((rbeg (region-beginning))
16349 (rend (copy-marker (region-end))))
16350 (unwind-protect
16351 (progn
16352 (goto-char rbeg)
16353 (beginning-of-line)
16354 (when (save-excursion
16355 (re-search-forward org-outline-regexp-bol rend t))
16356 (user-error "Drawers cannot contain headlines"))
16357 ;; Position point at the beginning of the first
16358 ;; non-blank line in region. Insert drawer's opening
16359 ;; there, then indent it.
16360 (org-skip-whitespace)
16361 (beginning-of-line)
16362 (insert ":" drawer ":\n")
16363 (forward-line -1)
16364 (indent-for-tab-command)
16365 ;; Move point to the beginning of the first blank line
16366 ;; after the last non-blank line in region. Insert
16367 ;; drawer's closing, then indent it.
16368 (goto-char rend)
16369 (skip-chars-backward " \r\t\n")
16370 (insert "\n:END:")
16371 (deactivate-mark t)
16372 (indent-for-tab-command)
16373 (unless (eolp) (insert "\n")))
16374 ;; Clear marker, whatever the outcome of insertion is.
16375 (set-marker rend nil)))))))
16377 (defvar org-property-set-functions-alist nil
16378 "Property set function alist.
16379 Each entry should have the following format:
16381 (PROPERTY . READ-FUNCTION)
16383 The read function will be called with the same argument as
16384 `org-completing-read'.")
16386 (defun org-set-property-function (property)
16387 "Get the function that should be used to set PROPERTY.
16388 This is computed according to `org-property-set-functions-alist'."
16389 (or (cdr (assoc property org-property-set-functions-alist))
16390 'org-completing-read))
16392 (defun org-read-property-value (property)
16393 "Read PROPERTY value from user."
16394 (let* ((completion-ignore-case t)
16395 (allowed (org-property-get-allowed-values nil property 'table))
16396 (cur (org-entry-get nil property))
16397 (prompt (concat property " value"
16398 (if (and cur (string-match "\\S-" cur))
16399 (concat " [" cur "]") "") ": "))
16400 (set-function (org-set-property-function property))
16401 (val (if allowed
16402 (funcall set-function prompt allowed nil
16403 (not (get-text-property 0 'org-unrestricted
16404 (caar allowed))))
16405 (funcall set-function prompt
16406 (mapcar 'list (org-property-values property))
16407 nil nil "" nil cur))))
16408 (org-trim val)))
16410 (defvar org-last-set-property nil)
16411 (defvar org-last-set-property-value nil)
16412 (defun org-read-property-name ()
16413 "Read a property name."
16414 (let ((completion-ignore-case t)
16415 (default-prop (or (and (org-at-property-p)
16416 (match-string-no-properties 2))
16417 org-last-set-property)))
16418 (org-completing-read
16419 (concat "Property"
16420 (if default-prop (concat " [" default-prop "]") "")
16421 ": ")
16422 (mapcar #'list (org-buffer-property-keys nil t t))
16423 nil nil nil nil default-prop)))
16425 (defun org-set-property-and-value (use-last)
16426 "Allow to set [PROPERTY]: [value] direction from prompt.
16427 When use-default, don't even ask, just use the last
16428 \"[PROPERTY]: [value]\" string from the history."
16429 (interactive "P")
16430 (let* ((completion-ignore-case t)
16431 (pv (or (and use-last org-last-set-property-value)
16432 (org-completing-read
16433 "Enter a \"[Property]: [value]\" pair: "
16434 nil nil nil nil nil
16435 org-last-set-property-value)))
16436 prop val)
16437 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16438 (setq prop (match-string 1 pv)
16439 val (match-string 2 pv))
16440 (org-set-property prop val))))
16442 (defun org-set-property (property value)
16443 "In the current entry, set PROPERTY to VALUE.
16445 When called interactively, this will prompt for a property name, offering
16446 completion on existing and default properties. And then it will prompt
16447 for a value, offering completion either on allowed values (via an inherited
16448 xxx_ALL property) or on existing values in other instances of this property
16449 in the current file.
16451 Throw an error when trying to set a property with an invalid name."
16452 (interactive (list nil nil))
16453 (let ((property (or property (org-read-property-name))))
16454 ;; `org-entry-put' also makes the following check, but this one
16455 ;; avoids polluting `org-last-set-property' and
16456 ;; `org-last-set-property-value' needlessly.
16457 (unless (org--valid-property-p property)
16458 (user-error "Invalid property name: \"%s\"" property))
16459 (let ((value (or value (org-read-property-value property)))
16460 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16461 (setq org-last-set-property property)
16462 (setq org-last-set-property-value (concat property ": " value))
16463 ;; Possibly postprocess the inserted value:
16464 (when fn (setq value (funcall fn value)))
16465 (unless (equal (org-entry-get nil property) value)
16466 (org-entry-put nil property value)))))
16468 (defun org-find-property (property &optional value)
16469 "Find first entry in buffer that sets PROPERTY.
16471 When optional argument VALUE is non-nil, only consider an entry
16472 if it contains PROPERTY set to this value. If PROPERTY should be
16473 explicitly set to nil, use string \"nil\" for VALUE.
16475 Return position where the entry begins, or nil if there is no
16476 such entry. If narrowing is in effect, only search the visible
16477 part of the buffer."
16478 (save-excursion
16479 (goto-char (point-min))
16480 (let ((case-fold-search t)
16481 (re (org-re-property property nil (not value) value)))
16482 (catch 'exit
16483 (while (re-search-forward re nil t)
16484 (when (if value (org-at-property-p)
16485 (org-entry-get (point) property nil t))
16486 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16488 (defun org-delete-property (property)
16489 "In the current entry, delete PROPERTY."
16490 (interactive
16491 (let* ((completion-ignore-case t)
16492 (cat (org-entry-get (point) "CATEGORY"))
16493 (props0 (org-entry-properties nil 'standard))
16494 (props (if cat props0
16495 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16496 (prop (if (< 1 (length props))
16497 (completing-read "Property: " props nil t)
16498 (caar props))))
16499 (list prop)))
16500 (if (not property)
16501 (message "No property to delete in this entry")
16502 (org-entry-delete nil property)
16503 (message "Property \"%s\" deleted" property)))
16505 (defun org-delete-property-globally (property)
16506 "Remove PROPERTY globally, from all entries.
16507 This function ignores narrowing, if any."
16508 (interactive
16509 (let* ((completion-ignore-case t)
16510 (prop (completing-read
16511 "Globally remove property: "
16512 (mapcar #'list (org-buffer-property-keys)))))
16513 (list prop)))
16514 (org-with-wide-buffer
16515 (goto-char (point-min))
16516 (let ((count 0)
16517 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16518 (while (re-search-forward re nil t)
16519 (when (org-entry-delete (point) property) (cl-incf count)))
16520 (message "Property \"%s\" removed from %d entries" property count))))
16522 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16524 (defun org-compute-property-at-point ()
16525 "Compute the property at point.
16526 This looks for an enclosing column format, extracts the operator and
16527 then applies it to the property in the column format's scope."
16528 (interactive)
16529 (unless (org-at-property-p)
16530 (user-error "Not at a property"))
16531 (let ((prop (match-string-no-properties 2)))
16532 (org-columns-get-format-and-top-level)
16533 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16534 (user-error "No operator defined for property %s" prop))
16535 (org-columns-compute prop)))
16537 (defvar org-property-allowed-value-functions nil
16538 "Hook for functions supplying allowed values for a specific property.
16539 The functions must take a single argument, the name of the property, and
16540 return a flat list of allowed values. If \":ETC\" is one of
16541 the values, this means that these values are intended as defaults for
16542 completion, but that other values should be allowed too.
16543 The functions must return nil if they are not responsible for this
16544 property.")
16546 (defun org-property-get-allowed-values (pom property &optional table)
16547 "Get allowed values for the property PROPERTY.
16548 When TABLE is non-nil, return an alist that can directly be used for
16549 completion."
16550 (let (vals)
16551 (cond
16552 ((equal property "TODO")
16553 (setq vals (org-with-point-at pom
16554 (append org-todo-keywords-1 '("")))))
16555 ((equal property "PRIORITY")
16556 (let ((n org-lowest-priority))
16557 (while (>= n org-highest-priority)
16558 (push (char-to-string n) vals)
16559 (setq n (1- n)))))
16560 ((equal property "CATEGORY"))
16561 ((member property org-special-properties))
16562 ((setq vals (run-hook-with-args-until-success
16563 'org-property-allowed-value-functions property)))
16565 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16566 (when (and vals (string-match "\\S-" vals))
16567 (setq vals (car (read-from-string (concat "(" vals ")"))))
16568 (setq vals (mapcar (lambda (x)
16569 (cond ((stringp x) x)
16570 ((numberp x) (number-to-string x))
16571 ((symbolp x) (symbol-name x))
16572 (t "???")))
16573 vals)))))
16574 (when (member ":ETC" vals)
16575 (setq vals (remove ":ETC" vals))
16576 (org-add-props (car vals) '(org-unrestricted t)))
16577 (if table (mapcar 'list vals) vals)))
16579 (defun org-property-previous-allowed-value (&optional _previous)
16580 "Switch to the next allowed value for this property."
16581 (interactive)
16582 (org-property-next-allowed-value t))
16584 (defun org-property-next-allowed-value (&optional previous)
16585 "Switch to the next allowed value for this property."
16586 (interactive)
16587 (unless (org-at-property-p)
16588 (user-error "Not at a property"))
16589 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16590 (key (match-string 2))
16591 (value (match-string 3))
16592 (allowed (or (org-property-get-allowed-values (point) key)
16593 (and (member value '("[ ]" "[-]" "[X]"))
16594 '("[ ]" "[X]"))))
16595 (heading (save-match-data (nth 4 (org-heading-components))))
16596 nval)
16597 (unless allowed
16598 (user-error "Allowed values for this property have not been defined"))
16599 (when previous (setq allowed (reverse allowed)))
16600 (when (member value allowed)
16601 (setq nval (car (cdr (member value allowed)))))
16602 (setq nval (or nval (car allowed)))
16603 (when (equal nval value)
16604 (user-error "Only one allowed value for this property"))
16605 (org-at-property-p)
16606 (replace-match (concat " :" key ": " nval) t t)
16607 (org-indent-line)
16608 (beginning-of-line 1)
16609 (skip-chars-forward " \t")
16610 (when (equal prop org-effort-property)
16611 (org-refresh-property
16612 '((effort . identity)
16613 (effort-minutes . org-duration-string-to-minutes))
16614 nval)
16615 (when (string= org-clock-current-task heading)
16616 (setq org-clock-effort nval)
16617 (org-clock-update-mode-line)))
16618 (run-hook-with-args 'org-property-changed-functions key nval)))
16620 (defun org-find-olp (path &optional this-buffer)
16621 "Return a marker pointing to the entry at outline path OLP.
16622 If anything goes wrong, throw an error.
16623 You can wrap this call to catch the error like this:
16625 \(condition-case msg
16626 \(org-mobile-locate-entry (match-string 4))
16627 \(error (nth 1 msg)))
16629 The return value will then be either a string with the error message,
16630 or a marker if everything is OK.
16632 If THIS-BUFFER is set, the outline path does not contain a file,
16633 only headings."
16634 (let* ((file (if this-buffer buffer-file-name (pop path)))
16635 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16636 (level 1)
16637 (lmin 1)
16638 (lmax 1)
16639 end found flevel)
16640 (unless buffer (error "File not found :%s" file))
16641 (with-current-buffer buffer
16642 (org-with-wide-buffer
16643 (goto-char (point-min))
16644 (dolist (heading path)
16645 (let ((re (format org-complex-heading-regexp-format
16646 (regexp-quote heading)))
16647 (cnt 0))
16648 (while (re-search-forward re end t)
16649 (setq level (- (match-end 1) (match-beginning 1)))
16650 (when (and (>= level lmin) (<= level lmax))
16651 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16652 (when (= cnt 0)
16653 (error "Heading not found on level %d: %s" lmax heading))
16654 (when (> cnt 1)
16655 (error "Heading not unique on level %d: %s" lmax heading))
16656 (goto-char found)
16657 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16658 (setq end (save-excursion (org-end-of-subtree t t)))))
16659 (when (org-at-heading-p)
16660 (point-marker))))))
16662 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16663 "Find node HEADING in BUFFER.
16664 Return a marker to the heading if it was found, or nil if not.
16665 If POS-ONLY is set, return just the position instead of a marker.
16667 The heading text must match exact, but it may have a TODO keyword,
16668 a priority cookie and tags in the standard locations."
16669 (with-current-buffer (or buffer (current-buffer))
16670 (org-with-wide-buffer
16671 (goto-char (point-min))
16672 (let (case-fold-search)
16673 (when (re-search-forward
16674 (format org-complex-heading-regexp-format
16675 (regexp-quote heading)) nil t)
16676 (if pos-only
16677 (match-beginning 0)
16678 (move-marker (make-marker) (match-beginning 0))))))))
16680 (defun org-find-exact-heading-in-directory (heading &optional dir)
16681 "Find Org node headline HEADING in all .org files in directory DIR.
16682 When the target headline is found, return a marker to this location."
16683 (let ((files (directory-files (or dir default-directory)
16684 t "\\`[^.#].*\\.org\\'"))
16685 visiting m buffer)
16686 (catch 'found
16687 (dolist (file files)
16688 (message "trying %s" file)
16689 (setq visiting (org-find-base-buffer-visiting file))
16690 (setq buffer (or visiting (find-file-noselect file)))
16691 (setq m (org-find-exact-headline-in-buffer
16692 heading buffer))
16693 (when (and (not m) (not visiting)) (kill-buffer buffer))
16694 (and m (throw 'found m))))))
16696 (defun org-find-entry-with-id (ident)
16697 "Locate the entry that contains the ID property with exact value IDENT.
16698 IDENT can be a string, a symbol or a number, this function will search for
16699 the string representation of it.
16700 Return the position where this entry starts, or nil if there is no such entry."
16701 (interactive "sID: ")
16702 (let ((id (cond
16703 ((stringp ident) ident)
16704 ((symbolp ident) (symbol-name ident))
16705 ((numberp ident) (number-to-string ident))
16706 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16707 (org-with-wide-buffer (org-find-property "ID" id))))
16709 ;;;; Timestamps
16711 (defvar org-last-changed-timestamp nil)
16712 (defvar org-last-inserted-timestamp nil
16713 "The last time stamp inserted with `org-insert-time-stamp'.")
16714 (defvar org-ts-what) ; dynamically scoped parameter
16716 (defun org-time-stamp (arg &optional inactive)
16717 "Prompt for a date/time and insert a time stamp.
16719 If the user specifies a time like HH:MM or if this command is
16720 called with at least one prefix argument, the time stamp contains
16721 the date and the time. Otherwise, only the date is included.
16723 All parts of a date not specified by the user are filled in from
16724 the timestamp at point, if any, or the current date/time
16725 otherwise.
16727 If there is already a timestamp at the cursor, it is replaced.
16729 With two universal prefix arguments, insert an active timestamp
16730 with the current time without prompting the user.
16732 When called from lisp, the timestamp is inactive if INACTIVE is
16733 non-nil."
16734 (interactive "P")
16735 (let* ((ts (cond
16736 ((org-at-date-range-p t)
16737 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16738 ((org-at-timestamp-p t) (match-string 0))))
16739 ;; Default time is either the timestamp at point or today.
16740 ;; When entering a range, only the range start is considered.
16741 (default-time (if (not ts) (current-time)
16742 (apply #'encode-time (org-parse-time-string ts))))
16743 (default-input (and ts (org-get-compact-tod ts)))
16744 (repeater (and ts
16745 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16746 (match-string 0 ts)))
16747 org-time-was-given
16748 org-end-time-was-given
16749 (time
16750 (and (if (equal arg '(16)) (current-time)
16751 ;; Preserve `this-command' and `last-command'.
16752 (let ((this-command this-command)
16753 (last-command last-command))
16754 (org-read-date
16755 arg 'totime nil nil default-time default-input
16756 inactive))))))
16757 (cond
16758 ((and ts
16759 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16760 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16761 (insert "--")
16762 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16764 ;; Make sure we're on a timestamp. When in the middle of a date
16765 ;; range, move arbitrarily to range end.
16766 (unless (org-at-timestamp-p t)
16767 (skip-chars-forward "-")
16768 (org-at-timestamp-p t))
16769 (replace-match "")
16770 (setq org-last-changed-timestamp
16771 (org-insert-time-stamp
16772 time (or org-time-was-given arg)
16773 inactive nil nil (list org-end-time-was-given)))
16774 (when repeater
16775 (backward-char)
16776 (insert " " repeater)
16777 (setq org-last-changed-timestamp
16778 (concat (substring org-last-inserted-timestamp 0 -1)
16779 " " repeater ">")))
16780 (message "Timestamp updated"))
16781 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16782 (t (org-insert-time-stamp
16783 time (or org-time-was-given arg) inactive nil nil
16784 (list org-end-time-was-given))))))
16786 ;; FIXME: can we use this for something else, like computing time differences?
16787 (defun org-get-compact-tod (s)
16788 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16789 (let* ((t1 (match-string 1 s))
16790 (h1 (string-to-number (match-string 2 s)))
16791 (m1 (string-to-number (match-string 3 s)))
16792 (t2 (and (match-end 4) (match-string 5 s)))
16793 (h2 (and t2 (string-to-number (match-string 6 s))))
16794 (m2 (and t2 (string-to-number (match-string 7 s))))
16795 dh dm)
16796 (if (not t2)
16798 (setq dh (- h2 h1) dm (- m2 m1))
16799 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16800 (concat t1 "+" (number-to-string dh)
16801 (and (/= 0 dm) (format ":%02d" dm)))))))
16803 (defun org-time-stamp-inactive (&optional arg)
16804 "Insert an inactive time stamp.
16805 An inactive time stamp is enclosed in square brackets instead of angle
16806 brackets. It is inactive in the sense that it does not trigger agenda entries,
16807 does not link to the calendar and cannot be changed with the S-cursor keys.
16808 So these are more for recording a certain time/date."
16809 (interactive "P")
16810 (org-time-stamp arg 'inactive))
16812 (defvar org-date-ovl (make-overlay 1 1))
16813 (overlay-put org-date-ovl 'face 'org-date-selected)
16814 (delete-overlay org-date-ovl)
16816 (defvar org-ans1) ; dynamically scoped parameter
16817 (defvar org-ans2) ; dynamically scoped parameter
16819 (defvar org-plain-time-of-day-regexp) ; defined below
16821 (defvar org-overriding-default-time nil) ; dynamically scoped
16822 (defvar org-read-date-overlay nil)
16823 (defvar org-dcst nil) ; dynamically scoped
16824 (defvar org-read-date-history nil)
16825 (defvar org-read-date-final-answer nil)
16826 (defvar org-read-date-analyze-futurep nil)
16827 (defvar org-read-date-analyze-forced-year nil)
16828 (defvar org-read-date-inactive)
16830 (defvar org-read-date-minibuffer-local-map
16831 (let* ((map (make-sparse-keymap)))
16832 (set-keymap-parent map minibuffer-local-map)
16833 (org-defkey map (kbd ".")
16834 (lambda () (interactive)
16835 ;; Are we at the beginning of the prompt?
16836 (if (looking-back "^[^:]+: "
16837 (let ((inhibit-field-text-motion t))
16838 (line-beginning-position)))
16839 (org-eval-in-calendar '(calendar-goto-today))
16840 (insert "."))))
16841 (org-defkey map (kbd "C-.")
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-goto-today))))
16844 (org-defkey map [(meta shift left)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-backward-month 1))))
16847 (org-defkey map [(meta shift right)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-forward-month 1))))
16850 (org-defkey map [(meta shift up)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-backward-year 1))))
16853 (org-defkey map [(meta shift down)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-forward-year 1))))
16856 (org-defkey map [?\e (shift left)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-backward-month 1))))
16859 (org-defkey map [?\e (shift right)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-forward-month 1))))
16862 (org-defkey map [?\e (shift up)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-backward-year 1))))
16865 (org-defkey map [?\e (shift down)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-forward-year 1))))
16868 (org-defkey map [(shift up)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-backward-week 1))))
16871 (org-defkey map [(shift down)]
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-forward-week 1))))
16874 (org-defkey map [(shift left)]
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(calendar-backward-day 1))))
16877 (org-defkey map [(shift right)]
16878 (lambda () (interactive)
16879 (org-eval-in-calendar '(calendar-forward-day 1))))
16880 (org-defkey map "!"
16881 (lambda () (interactive)
16882 (org-eval-in-calendar '(diary-view-entries))
16883 (message "")))
16884 (org-defkey map ">"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-scroll-left 1))))
16887 (org-defkey map "<"
16888 (lambda () (interactive)
16889 (org-eval-in-calendar '(calendar-scroll-right 1))))
16890 (org-defkey map "\C-v"
16891 (lambda () (interactive)
16892 (org-eval-in-calendar
16893 '(calendar-scroll-left-three-months 1))))
16894 (org-defkey map "\M-v"
16895 (lambda () (interactive)
16896 (org-eval-in-calendar
16897 '(calendar-scroll-right-three-months 1))))
16898 map)
16899 "Keymap for minibuffer commands when using `org-read-date'.")
16901 (defvar org-def)
16902 (defvar org-defdecode)
16903 (defvar org-with-time)
16905 (defvar calendar-setup) ; Dynamically scoped.
16906 (defun org-read-date (&optional with-time to-time from-string prompt
16907 default-time default-input inactive)
16908 "Read a date, possibly a time, and make things smooth for the user.
16909 The prompt will suggest to enter an ISO date, but you can also enter anything
16910 which will at least partially be understood by `parse-time-string'.
16911 Unrecognized parts of the date will default to the current day, month, year,
16912 hour and minute. If this command is called to replace a timestamp at point,
16913 or to enter the second timestamp of a range, the default time is taken
16914 from the existing stamp. Furthermore, the command prefers the future,
16915 so if you are giving a date where the year is not given, and the day-month
16916 combination is already past in the current year, it will assume you
16917 mean next year. For details, see the manual. A few examples:
16919 3-2-5 --> 2003-02-05
16920 feb 15 --> currentyear-02-15
16921 2/15 --> currentyear-02-15
16922 sep 12 9 --> 2009-09-12
16923 12:45 --> today 12:45
16924 22 sept 0:34 --> currentyear-09-22 0:34
16925 12 --> currentyear-currentmonth-12
16926 Fri --> nearest Friday after today
16927 -Tue --> last Tuesday
16928 etc.
16930 Furthermore you can specify a relative date by giving, as the *first* thing
16931 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16932 change in days weeks, months, years.
16933 With a single plus or minus, the date is relative to today. With a double
16934 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16935 +4d --> four days from today
16936 +4 --> same as above
16937 +2w --> two weeks from today
16938 ++5 --> five days from default date
16940 The function understands only English month and weekday abbreviations.
16942 While prompting, a calendar is popped up - you can also select the
16943 date with the mouse (button 1). The calendar shows a period of three
16944 months. To scroll it to other months, use the keys `>' and `<'.
16945 If you don't like the calendar, turn it off with
16946 (setq org-read-date-popup-calendar nil)
16948 With optional argument TO-TIME, the date will immediately be converted
16949 to an internal time.
16950 With an optional argument WITH-TIME, the prompt will suggest to
16951 also insert a time. Note that when WITH-TIME is not set, you can
16952 still enter a time, and this function will inform the calling routine
16953 about this change. The calling routine may then choose to change the
16954 format used to insert the time stamp into the buffer to include the time.
16955 With optional argument FROM-STRING, read from this string instead from
16956 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16957 the time/date that is used for everything that is not specified by the
16958 user."
16959 (require 'parse-time)
16960 (let* ((org-with-time with-time)
16961 (org-time-stamp-rounding-minutes
16962 (if (equal org-with-time '(16))
16963 '(0 0)
16964 org-time-stamp-rounding-minutes))
16965 (org-dcst org-display-custom-times)
16966 (ct (org-current-time))
16967 (org-def (or org-overriding-default-time default-time ct))
16968 (org-defdecode (decode-time org-def))
16969 (cur-frame (selected-frame))
16970 (mouse-autoselect-window nil) ; Don't let the mouse jump
16971 (calendar-setup
16972 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16973 (calendar-move-hook nil)
16974 (calendar-view-diary-initially-flag nil)
16975 (calendar-view-holidays-initially-flag nil)
16976 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16977 ;; Rationalize `org-def' and `org-defdecode', if required.
16978 (when (< (nth 2 org-defdecode) org-extend-today-until)
16979 (setf (nth 2 org-defdecode) -1)
16980 (setf (nth 1 org-defdecode) 59)
16981 (setq org-def (apply #'encode-time org-defdecode))
16982 (setq org-defdecode (decode-time org-def)))
16983 (let* ((timestr (format-time-string
16984 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16985 org-def))
16986 (prompt (concat (if prompt (concat prompt " ") "")
16987 (format "Date+time [%s]: " timestr))))
16988 (cond
16989 (from-string (setq ans from-string))
16990 (org-read-date-popup-calendar
16991 (save-excursion
16992 (save-window-excursion
16993 (calendar)
16994 (when (eq calendar-setup 'calendar-only)
16995 (setq cal-frame
16996 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16997 (select-frame cal-frame))
16998 (org-eval-in-calendar '(setq cursor-type nil) t)
16999 (unwind-protect
17000 (progn
17001 (calendar-forward-day (- (time-to-days org-def)
17002 (calendar-absolute-from-gregorian
17003 (calendar-current-date))))
17004 (org-eval-in-calendar nil t)
17005 (let* ((old-map (current-local-map))
17006 (map (copy-keymap calendar-mode-map))
17007 (minibuffer-local-map
17008 (copy-keymap org-read-date-minibuffer-local-map)))
17009 (org-defkey map (kbd "RET") 'org-calendar-select)
17010 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17011 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17012 (unwind-protect
17013 (progn
17014 (use-local-map map)
17015 (setq org-read-date-inactive inactive)
17016 (add-hook 'post-command-hook 'org-read-date-display)
17017 (setq org-ans0
17018 (read-string prompt
17019 default-input
17020 'org-read-date-history
17021 nil))
17022 ;; org-ans0: from prompt
17023 ;; org-ans1: from mouse click
17024 ;; org-ans2: from calendar motion
17025 (setq ans
17026 (concat org-ans0 " " (or org-ans1 org-ans2))))
17027 (remove-hook 'post-command-hook 'org-read-date-display)
17028 (use-local-map old-map)
17029 (when org-read-date-overlay
17030 (delete-overlay org-read-date-overlay)
17031 (setq org-read-date-overlay nil)))))
17032 (bury-buffer "*Calendar*")
17033 (when cal-frame
17034 (delete-frame cal-frame)
17035 (select-frame-set-input-focus cur-frame))))))
17037 (t ; Naked prompt only
17038 (unwind-protect
17039 (setq ans (read-string prompt default-input
17040 'org-read-date-history timestr))
17041 (when org-read-date-overlay
17042 (delete-overlay org-read-date-overlay)
17043 (setq org-read-date-overlay nil))))))
17045 (setq final (org-read-date-analyze ans org-def org-defdecode))
17047 (when org-read-date-analyze-forced-year
17048 (message "Year was forced into %s"
17049 (if org-read-date-force-compatible-dates
17050 "compatible range (1970-2037)"
17051 "range representable on this machine"))
17052 (ding))
17054 ;; One round trip to get rid of 34th of August and stuff like that....
17055 (setq final (decode-time (apply 'encode-time final)))
17057 (setq org-read-date-final-answer ans)
17059 (if to-time
17060 (apply 'encode-time final)
17061 (if (and (boundp 'org-time-was-given) org-time-was-given)
17062 (format "%04d-%02d-%02d %02d:%02d"
17063 (nth 5 final) (nth 4 final) (nth 3 final)
17064 (nth 2 final) (nth 1 final))
17065 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17067 (defun org-read-date-display ()
17068 "Display the current date prompt interpretation in the minibuffer."
17069 (when org-read-date-display-live
17070 (when org-read-date-overlay
17071 (delete-overlay org-read-date-overlay))
17072 (when (minibufferp (current-buffer))
17073 (save-excursion
17074 (end-of-line 1)
17075 (while (not (equal (buffer-substring
17076 (max (point-min) (- (point) 4)) (point))
17077 " "))
17078 (insert " ")))
17079 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17080 " " (or org-ans1 org-ans2)))
17081 (org-end-time-was-given nil)
17082 (f (org-read-date-analyze ans org-def org-defdecode))
17083 (fmts (if org-dcst
17084 org-time-stamp-custom-formats
17085 org-time-stamp-formats))
17086 (fmt (if (or org-with-time
17087 (and (boundp 'org-time-was-given) org-time-was-given))
17088 (cdr fmts)
17089 (car fmts)))
17090 (txt (format-time-string fmt (apply 'encode-time f)))
17091 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17092 (txt (concat "=> " txt)))
17093 (when (and org-end-time-was-given
17094 (string-match org-plain-time-of-day-regexp txt))
17095 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17096 org-end-time-was-given
17097 (substring txt (match-end 0)))))
17098 (when org-read-date-analyze-futurep
17099 (setq txt (concat txt " (=>F)")))
17100 (setq org-read-date-overlay
17101 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17102 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17104 (defun org-read-date-analyze (ans def defdecode)
17105 "Analyze the combined answer of the date prompt."
17106 ;; FIXME: cleanup and comment
17107 ;; Pass `current-time' result to `decode-time' (instead of calling
17108 ;; without arguments) so that only `current-time' has to be
17109 ;; overriden in tests.
17110 (let ((org-def def)
17111 (org-defdecode defdecode)
17112 (nowdecode (decode-time (current-time)))
17113 delta deltan deltaw deltadef year month day
17114 hour minute second wday pm h2 m2 tl wday1
17115 iso-year iso-weekday iso-week iso-date futurep kill-year)
17116 (setq org-read-date-analyze-futurep nil
17117 org-read-date-analyze-forced-year nil)
17118 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17119 (setq ans "+0"))
17121 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17122 (setq ans (replace-match "" t t ans)
17123 deltan (car delta)
17124 deltaw (nth 1 delta)
17125 deltadef (nth 2 delta)))
17127 ;; Check if there is an iso week date in there. If yes, store the
17128 ;; info and postpone interpreting it until the rest of the parsing
17129 ;; is done.
17130 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17131 (setq iso-year (when (match-end 1)
17132 (org-small-year-to-year
17133 (string-to-number (match-string 1 ans))))
17134 iso-weekday (when (match-end 3)
17135 (string-to-number (match-string 3 ans)))
17136 iso-week (string-to-number (match-string 2 ans)))
17137 (setq ans (replace-match "" t t ans)))
17139 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17140 (when (string-match
17141 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17142 (setq year (if (match-end 2)
17143 (string-to-number (match-string 2 ans))
17144 (progn (setq kill-year t)
17145 (string-to-number (format-time-string "%Y"))))
17146 month (string-to-number (match-string 3 ans))
17147 day (string-to-number (match-string 4 ans)))
17148 (setq year (org-small-year-to-year year))
17149 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17150 t nil ans)))
17152 ;; Help matching dotted european dates
17153 (when (string-match
17154 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17155 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17156 (setq kill-year t)
17157 (string-to-number (format-time-string "%Y")))
17158 day (string-to-number (match-string 1 ans))
17159 month (string-to-number (match-string 2 ans))
17160 ans (replace-match (format "%04d-%02d-%02d" year month day)
17161 t nil ans)))
17163 ;; Help matching american dates, like 5/30 or 5/30/7
17164 (when (string-match
17165 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17166 (setq year (if (match-end 4)
17167 (string-to-number (match-string 4 ans))
17168 (progn (setq kill-year t)
17169 (string-to-number (format-time-string "%Y"))))
17170 month (string-to-number (match-string 1 ans))
17171 day (string-to-number (match-string 2 ans)))
17172 (setq year (org-small-year-to-year year))
17173 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17174 t nil ans)))
17175 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17176 ;; If there is a time with am/pm, and *no* time without it, we convert
17177 ;; so that matching will be successful.
17178 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17179 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17180 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17181 (setq hour (string-to-number (match-string 1 ans))
17182 minute (if (match-end 3)
17183 (string-to-number (match-string 3 ans))
17185 pm (equal ?p
17186 (string-to-char (downcase (match-string 4 ans)))))
17187 (if (and (= hour 12) (not pm))
17188 (setq hour 0)
17189 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17190 (setq ans (replace-match (format "%02d:%02d" hour minute)
17191 t t ans))))
17193 ;; Check if a time range is given as a duration
17194 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17195 (setq hour (string-to-number (match-string 1 ans))
17196 h2 (+ hour (string-to-number (match-string 3 ans)))
17197 minute (string-to-number (match-string 2 ans))
17198 m2 (+ minute (if (match-end 5) (string-to-number
17199 (match-string 5 ans))0)))
17200 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17201 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17202 t t ans)))
17204 ;; Check if there is a time range
17205 (when (boundp 'org-end-time-was-given)
17206 (setq org-time-was-given nil)
17207 (when (and (string-match org-plain-time-of-day-regexp ans)
17208 (match-end 8))
17209 (setq org-end-time-was-given (match-string 8 ans))
17210 (setq ans (concat (substring ans 0 (match-beginning 7))
17211 (substring ans (match-end 7))))))
17213 (setq tl (parse-time-string ans)
17214 day (or (nth 3 tl) (nth 3 org-defdecode))
17215 month
17216 (cond ((nth 4 tl))
17217 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17218 ;; Day was specified. Make sure DAY+MONTH
17219 ;; combination happens in the future.
17220 ((nth 3 tl)
17221 (setq futurep t)
17222 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17223 (nth 4 nowdecode)))
17224 (t (nth 4 org-defdecode)))
17225 year
17226 (cond ((and (not kill-year) (nth 5 tl)))
17227 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17228 ;; Month was guessed in the future and is at least
17229 ;; equal to NOWDECODE's. Fix year accordingly.
17230 (futurep
17231 (if (or (> month (nth 4 nowdecode))
17232 (>= day (nth 3 nowdecode)))
17233 (nth 5 nowdecode)
17234 (1+ (nth 5 nowdecode))))
17235 ;; Month was specified. Make sure MONTH+YEAR
17236 ;; combination happens in the future.
17237 ((nth 4 tl)
17238 (setq futurep t)
17239 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17240 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17241 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17242 (t (nth 5 nowdecode))))
17243 (t (nth 5 org-defdecode)))
17244 hour (or (nth 2 tl) (nth 2 org-defdecode))
17245 minute (or (nth 1 tl) (nth 1 org-defdecode))
17246 second (or (nth 0 tl) 0)
17247 wday (nth 6 tl))
17249 (when (and (eq org-read-date-prefer-future 'time)
17250 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17251 (equal day (nth 3 nowdecode))
17252 (equal month (nth 4 nowdecode))
17253 (equal year (nth 5 nowdecode))
17254 (nth 2 tl)
17255 (or (< (nth 2 tl) (nth 2 nowdecode))
17256 (and (= (nth 2 tl) (nth 2 nowdecode))
17257 (nth 1 tl)
17258 (< (nth 1 tl) (nth 1 nowdecode)))))
17259 (setq day (1+ day)
17260 futurep t))
17262 ;; Special date definitions below
17263 (cond
17264 (iso-week
17265 ;; There was an iso week
17266 (require 'cal-iso)
17267 (setq futurep nil)
17268 (setq year (or iso-year year)
17269 day (or iso-weekday wday 1)
17270 wday nil ; to make sure that the trigger below does not match
17271 iso-date (calendar-gregorian-from-absolute
17272 (calendar-iso-to-absolute
17273 (list iso-week day year))))
17274 ; FIXME: Should we also push ISO weeks into the future?
17275 ; (when (and org-read-date-prefer-future
17276 ; (not iso-year)
17277 ; (< (calendar-absolute-from-gregorian iso-date)
17278 ; (time-to-days (current-time))))
17279 ; (setq year (1+ year)
17280 ; iso-date (calendar-gregorian-from-absolute
17281 ; (calendar-iso-to-absolute
17282 ; (list iso-week day year)))))
17283 (setq month (car iso-date)
17284 year (nth 2 iso-date)
17285 day (nth 1 iso-date)))
17286 (deltan
17287 (setq futurep nil)
17288 (unless deltadef
17289 ;; Pass `current-time' result to `decode-time' (instead of
17290 ;; calling without arguments) so that only `current-time' has
17291 ;; to be overriden in tests.
17292 (let ((now (decode-time (current-time))))
17293 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17294 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17295 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17296 ((equal deltaw "m") (setq month (+ month deltan)))
17297 ((equal deltaw "y") (setq year (+ year deltan)))))
17298 ((and wday (not (nth 3 tl)))
17299 ;; Weekday was given, but no day, so pick that day in the week
17300 ;; on or after the derived date.
17301 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17302 (unless (equal wday wday1)
17303 (setq day (+ day (% (- wday wday1 -7) 7))))))
17304 (when (and (boundp 'org-time-was-given)
17305 (nth 2 tl))
17306 (setq org-time-was-given t))
17307 (when (< year 100) (setq year (+ 2000 year)))
17308 ;; Check of the date is representable
17309 (if org-read-date-force-compatible-dates
17310 (progn
17311 (when (< year 1970)
17312 (setq year 1970 org-read-date-analyze-forced-year t))
17313 (when (> year 2037)
17314 (setq year 2037 org-read-date-analyze-forced-year t)))
17315 (condition-case nil
17316 (ignore (encode-time second minute hour day month year))
17317 (error
17318 (setq year (nth 5 org-defdecode))
17319 (setq org-read-date-analyze-forced-year t))))
17320 (setq org-read-date-analyze-futurep futurep)
17321 (list second minute hour day month year)))
17323 (defvar parse-time-weekdays)
17324 (defun org-read-date-get-relative (s today default)
17325 "Check string S for special relative date string.
17326 TODAY and DEFAULT are internal times, for today and for a default.
17327 Return shift list (N what def-flag)
17328 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17329 N is the number of WHATs to shift.
17330 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17331 the DEFAULT date rather than TODAY."
17332 (require 'parse-time)
17333 (when (and
17334 (string-match
17335 (concat
17336 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17337 "\\([0-9]+\\)?"
17338 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17339 "\\([ \t]\\|$\\)") s)
17340 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17341 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17342 (string-to-char (substring (match-string 1 s) -1))
17343 ?+))
17344 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17345 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17346 (what (if (match-end 3) (match-string 3 s) "d"))
17347 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17348 (date (if rel default today))
17349 (wday (nth 6 (decode-time date)))
17350 delta)
17351 (if wday1
17352 (progn
17353 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17354 (when (= delta 0) (setq delta 7))
17355 (when (= dir ?-)
17356 (setq delta (- delta 7))
17357 (when (= delta 0) (setq delta -7)))
17358 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17359 (list delta "d" rel))
17360 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17362 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17363 "Turn a user-specified date into the internal representation.
17364 The internal representation needed by the calendar is (month day year).
17365 This is a wrapper to handle the brain-dead convention in calendar that
17366 user function argument order change dependent on argument order."
17367 (pcase calendar-date-style
17368 (`american (list arg1 arg2 arg3))
17369 (`european (list arg2 arg1 arg3))
17370 (`iso (list arg2 arg3 arg1))))
17372 (defun org-eval-in-calendar (form &optional keepdate)
17373 "Eval FORM in the calendar window and return to current window.
17374 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17375 (let ((sf (selected-frame))
17376 (sw (selected-window)))
17377 (select-window (get-buffer-window "*Calendar*" t))
17378 (eval form)
17379 (when (and (not keepdate) (calendar-cursor-to-date))
17380 (let* ((date (calendar-cursor-to-date))
17381 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17382 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17383 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17384 (select-window sw)
17385 (select-frame-set-input-focus sf)))
17387 (defun org-calendar-select ()
17388 "Return to `org-read-date' with the date currently selected.
17389 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17390 (interactive)
17391 (when (calendar-cursor-to-date)
17392 (let* ((date (calendar-cursor-to-date))
17393 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17394 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17395 (when (active-minibuffer-window) (exit-minibuffer))))
17397 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17398 "Insert a date stamp for the date given by the internal TIME.
17399 See `format-time-string' for the format of TIME.
17400 WITH-HM means use the stamp format that includes the time of the day.
17401 INACTIVE means use square brackets instead of angular ones, so that the
17402 stamp will not contribute to the agenda.
17403 PRE and POST are optional strings to be inserted before and after the
17404 stamp.
17405 The command returns the inserted time stamp."
17406 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17407 stamp)
17408 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17409 (insert-before-markers (or pre ""))
17410 (when (listp extra)
17411 (setq extra (car extra))
17412 (if (and (stringp extra)
17413 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17414 (setq extra (format "-%02d:%02d"
17415 (string-to-number (match-string 1 extra))
17416 (string-to-number (match-string 2 extra))))
17417 (setq extra nil)))
17418 (when extra
17419 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17420 (insert-before-markers (setq stamp (format-time-string fmt time)))
17421 (insert-before-markers (or post ""))
17422 (setq org-last-inserted-timestamp stamp)))
17424 (defun org-toggle-time-stamp-overlays ()
17425 "Toggle the use of custom time stamp formats."
17426 (interactive)
17427 (setq org-display-custom-times (not org-display-custom-times))
17428 (unless org-display-custom-times
17429 (let ((p (point-min)) (bmp (buffer-modified-p)))
17430 (while (setq p (next-single-property-change p 'display))
17431 (when (and (get-text-property p 'display)
17432 (eq (get-text-property p 'face) 'org-date))
17433 (remove-text-properties
17434 p (setq p (next-single-property-change p 'display))
17435 '(display t))))
17436 (set-buffer-modified-p bmp)))
17437 (org-restart-font-lock)
17438 (setq org-table-may-need-update t)
17439 (if org-display-custom-times
17440 (message "Time stamps are overlaid with custom format")
17441 (message "Time stamp overlays removed")))
17443 (defun org-display-custom-time (beg end)
17444 "Overlay modified time stamp format over timestamp between BEG and END."
17445 (let* ((ts (buffer-substring beg end))
17446 t1 w1 with-hm tf time str w2 (off 0))
17447 (save-match-data
17448 (setq t1 (org-parse-time-string ts t))
17449 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17450 (setq off (- (match-end 0) (match-beginning 0)))))
17451 (setq end (- end off))
17452 (setq w1 (- end beg)
17453 with-hm (and (nth 1 t1) (nth 2 t1))
17454 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17455 time (org-fix-decoded-time t1)
17456 str (org-add-props
17457 (format-time-string
17458 (substring tf 1 -1) (apply 'encode-time time))
17459 nil 'mouse-face 'highlight)
17460 w2 (length str))
17461 (unless (= w2 w1)
17462 (add-text-properties (1+ beg) (+ 2 beg)
17463 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17464 (put-text-property beg end 'display str)))
17466 (defun org-fix-decoded-time (time)
17467 "Set 0 instead of nil for the first 6 elements of time.
17468 Don't touch the rest."
17469 (let ((n 0))
17470 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17472 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17473 "Difference between TIMESTAMP-STRING and now in days.
17474 If SECONDS is non-nil, return the difference in seconds."
17475 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17476 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17477 (funcall fdiff (current-time)))))
17479 (defun org-deadline-close-p (timestamp-string &optional ndays)
17480 "Is the time in TIMESTAMP-STRING close to the current date?"
17481 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17482 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17483 (not (org-entry-is-done-p))))
17485 (defun org-get-wdays (ts &optional delay zero-delay)
17486 "Get the deadline lead time appropriate for timestring TS.
17487 When DELAY is non-nil, get the delay time for scheduled items
17488 instead of the deadline lead time. When ZERO-DELAY is non-nil
17489 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17490 don't try to find the delay cookie in the scheduled timestamp."
17491 (let ((tv (if delay org-scheduled-delay-days
17492 org-deadline-warning-days)))
17493 (cond
17494 ((or (and delay (< tv 0))
17495 (and delay zero-delay (<= tv 0))
17496 (and (not delay) (<= tv 0)))
17497 ;; Enforce this value no matter what
17498 (- tv))
17499 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17500 ;; lead time is specified.
17501 (floor (* (string-to-number (match-string 1 ts))
17502 (cdr (assoc (match-string 2 ts)
17503 '(("d" . 1) ("w" . 7)
17504 ("m" . 30.4) ("y" . 365.25)
17505 ("h" . 0.041667)))))))
17506 ;; go for the default.
17507 (t tv))))
17509 (defun org-calendar-select-mouse (ev)
17510 "Return to `org-read-date' with the date currently selected.
17511 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17512 (interactive "e")
17513 (mouse-set-point ev)
17514 (when (calendar-cursor-to-date)
17515 (let* ((date (calendar-cursor-to-date))
17516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17517 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17518 (when (active-minibuffer-window) (exit-minibuffer))))
17520 (defun org-check-deadlines (ndays)
17521 "Check if there are any deadlines due or past due.
17522 A deadline is considered due if it happens within `org-deadline-warning-days'
17523 days from today's date. If the deadline appears in an entry marked DONE,
17524 it is not shown. The prefix arg NDAYS can be used to test that many
17525 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17526 (interactive "P")
17527 (let* ((org-warn-days
17528 (cond
17529 ((equal ndays '(4)) 100000)
17530 (ndays (prefix-numeric-value ndays))
17531 (t (abs org-deadline-warning-days))))
17532 (case-fold-search nil)
17533 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17534 (callback
17535 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17536 (message "%d deadlines past-due or due within %d days"
17537 (org-occur regexp nil callback)
17538 org-warn-days)))
17540 (defsubst org-re-timestamp (type)
17541 "Return a regexp for timestamp TYPE.
17542 Allowed values for TYPE are:
17544 all: all timestamps
17545 active: only active timestamps (<...>)
17546 inactive: only inactive timestamps ([...])
17547 scheduled: only scheduled timestamps
17548 deadline: only deadline timestamps
17549 closed: only closed time-stamps
17551 When TYPE is nil, fall back on returning a regexp that matches
17552 both scheduled and deadline timestamps."
17553 (cl-case type
17554 (all org-ts-regexp-both)
17555 (active org-ts-regexp)
17556 (inactive org-ts-regexp-inactive)
17557 (scheduled org-scheduled-time-regexp)
17558 (deadline org-deadline-time-regexp)
17559 (closed org-closed-time-regexp)
17560 (otherwise
17561 (concat "\\<"
17562 (regexp-opt (list org-deadline-string org-scheduled-string))
17563 " *<\\([^>]+\\)>"))))
17565 (defun org-check-before-date (d)
17566 "Check if there are deadlines or scheduled entries before date D."
17567 (interactive (list (org-read-date)))
17568 (let* ((case-fold-search nil)
17569 (regexp (org-re-timestamp org-ts-type))
17570 (ts-type org-ts-type)
17571 (callback
17572 (lambda ()
17573 (let ((match (match-string 1)))
17574 (and (if (memq ts-type '(active inactive all))
17575 (eq (org-element-type (save-excursion
17576 (backward-char)
17577 (org-element-context)))
17578 'timestamp)
17579 (org-at-planning-p))
17580 (time-less-p
17581 (org-time-string-to-time match)
17582 (org-time-string-to-time d)))))))
17583 (message "%d entries before %s"
17584 (org-occur regexp nil callback)
17585 d)))
17587 (defun org-check-after-date (d)
17588 "Check if there are deadlines or scheduled entries after date D."
17589 (interactive (list (org-read-date)))
17590 (let* ((case-fold-search nil)
17591 (regexp (org-re-timestamp org-ts-type))
17592 (ts-type org-ts-type)
17593 (callback
17594 (lambda ()
17595 (let ((match (match-string 1)))
17596 (and (if (memq ts-type '(active inactive all))
17597 (eq (org-element-type (save-excursion
17598 (backward-char)
17599 (org-element-context)))
17600 'timestamp)
17601 (org-at-planning-p))
17602 (not (time-less-p
17603 (org-time-string-to-time match)
17604 (org-time-string-to-time d))))))))
17605 (message "%d entries after %s"
17606 (org-occur regexp nil callback)
17607 d)))
17609 (defun org-check-dates-range (start-date end-date)
17610 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17611 (interactive (list (org-read-date nil nil nil "Range starts")
17612 (org-read-date nil nil nil "Range end")))
17613 (let ((case-fold-search nil)
17614 (regexp (org-re-timestamp org-ts-type))
17615 (callback
17616 (let ((type org-ts-type))
17617 (lambda ()
17618 (let ((match (match-string 1)))
17619 (and
17620 (if (memq type '(active inactive all))
17621 (eq (org-element-type (save-excursion
17622 (backward-char)
17623 (org-element-context)))
17624 'timestamp)
17625 (org-at-planning-p))
17626 (not (time-less-p
17627 (org-time-string-to-time match)
17628 (org-time-string-to-time start-date)))
17629 (time-less-p
17630 (org-time-string-to-time match)
17631 (org-time-string-to-time end-date))))))))
17632 (message "%d entries between %s and %s"
17633 (org-occur regexp nil callback) start-date end-date)))
17635 (defun org-evaluate-time-range (&optional to-buffer)
17636 "Evaluate a time range by computing the difference between start and end.
17637 Normally the result is just printed in the echo area, but with prefix arg
17638 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17639 If the time range is actually in a table, the result is inserted into the
17640 next column.
17641 For time difference computation, a year is assumed to be exactly 365
17642 days in order to avoid rounding problems."
17643 (interactive "P")
17645 (org-clock-update-time-maybe)
17646 (save-excursion
17647 (unless (org-at-date-range-p t)
17648 (goto-char (point-at-bol))
17649 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17650 (unless (org-at-date-range-p t)
17651 (user-error "Not at a time-stamp range, and none found in current line")))
17652 (let* ((ts1 (match-string 1))
17653 (ts2 (match-string 2))
17654 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17655 (match-end (match-end 0))
17656 (time1 (org-time-string-to-time ts1))
17657 (time2 (org-time-string-to-time ts2))
17658 (t1 (float-time time1))
17659 (t2 (float-time time2))
17660 (diff (abs (- t2 t1)))
17661 (negative (< (- t2 t1) 0))
17662 ;; (ys (floor (* 365 24 60 60)))
17663 (ds (* 24 60 60))
17664 (hs (* 60 60))
17665 (fy "%dy %dd %02d:%02d")
17666 (fy1 "%dy %dd")
17667 (fd "%dd %02d:%02d")
17668 (fd1 "%dd")
17669 (fh "%02d:%02d")
17670 y d h m align)
17671 (if havetime
17672 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17674 d (floor (/ diff ds)) diff (mod diff ds)
17675 h (floor (/ diff hs)) diff (mod diff hs)
17676 m (floor (/ diff 60)))
17677 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17679 d (floor (+ (/ diff ds) 0.5))
17680 h 0 m 0))
17681 (if (not to-buffer)
17682 (message "%s" (org-make-tdiff-string y d h m))
17683 (if (org-at-table-p)
17684 (progn
17685 (goto-char match-end)
17686 (setq align t)
17687 (and (looking-at " *|") (goto-char (match-end 0))))
17688 (goto-char match-end))
17689 (when (looking-at
17690 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17691 (replace-match ""))
17692 (when negative (insert " -"))
17693 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17694 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17695 (insert " " (format fh h m))))
17696 (when align (org-table-align))
17697 (message "Time difference inserted")))))
17699 (defun org-make-tdiff-string (y d h m)
17700 (let ((fmt "")
17701 (l nil))
17702 (when (> y 0)
17703 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17704 (push y l))
17705 (when (> d 0)
17706 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17707 (push d l))
17708 (when (> h 0)
17709 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17710 (push h l))
17711 (when (> m 0)
17712 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17713 (push m l))
17714 (apply 'format fmt (nreverse l))))
17716 (defun org-time-string-to-time (s &optional buffer pos)
17717 "Convert a timestamp string into internal time."
17718 (condition-case errdata
17719 (apply 'encode-time (org-parse-time-string s))
17720 (error (error "Bad timestamp `%s'%s\nError was: %s"
17721 s (if (not (and buffer pos))
17723 (format-message " at %d in buffer `%s'" pos buffer))
17724 (cdr errdata)))))
17726 (defun org-time-string-to-seconds (s)
17727 "Convert a timestamp string to a number of seconds."
17728 (float-time (org-time-string-to-time s)))
17730 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17732 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17733 "Convert time stamp S to an absolute day number.
17735 If DAYNR in non-nil, and there is a specifier for a cyclic time
17736 stamp, get the closest date to DAYNR. If PREFER is
17737 `past' (respectively `future') return a date past (respectively
17738 after) or equal to DAYNR.
17740 POS is the location of time stamp S, as a buffer position in
17741 BUFFER.
17743 Diary sexp timestamps are matched against DAYNR, when non-nil.
17744 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17745 signalled."
17746 (cond
17747 ((string-match "\\`%%\\((.*)\\)" s)
17748 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17749 ;; only able to match individual dates. If it fails, raise an
17750 ;; error.
17751 (if (and daynr
17752 (org-diary-sexp-entry
17753 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17754 daynr
17755 (signal 'org-diary-sexp-no-match (list s))))
17756 ((and daynr show-all) (org-closest-date s daynr prefer))
17757 (t (time-to-days
17758 (condition-case errdata
17759 (apply #'encode-time (org-parse-time-string s))
17760 (error (error "Bad timestamp `%s'%s\nError was: %s"
17762 (if (not (and buffer pos)) ""
17763 (format-message " at %d in buffer `%s'" pos buffer))
17764 (cdr errdata))))))))
17766 (defun org-days-to-iso-week (days)
17767 "Return the iso week number."
17768 (require 'cal-iso)
17769 (car (calendar-iso-from-absolute days)))
17771 (defun org-small-year-to-year (year)
17772 "Convert 2-digit years into 4-digit years.
17773 YEAR is expanded into one of the 30 next years, if possible, or
17774 into a past one. Any year larger than 99 is returned unchanged."
17775 (if (>= year 100) year
17776 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17777 (century (/ current 100))
17778 (offset (- year (% current 100))))
17779 (cond ((> offset 30) (+ (* (1- century) 100) year))
17780 ((> offset -70) (+ (* century 100) year))
17781 (t (+ (* (1+ century) 100) year))))))
17783 (defun org-time-from-absolute (d)
17784 "Return the time corresponding to date D.
17785 D may be an absolute day number, or a calendar-type list (month day year)."
17786 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17787 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17789 (defvar org-agenda-current-date)
17790 (defun org-calendar-holiday ()
17791 "List of holidays, for Diary display in Org mode."
17792 (require 'holidays)
17793 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17794 (and hl (mapconcat #'identity hl "; "))))
17796 (defun org-diary-sexp-entry (sexp entry d)
17797 "Process a SEXP diary ENTRY for date D."
17798 (require 'diary-lib)
17799 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17800 ;; dynamically.
17801 (let* ((sexp `(let ((entry ,entry)
17802 (date ',d))
17803 ,(car (read-from-string sexp))))
17804 (result (if calendar-debug-sexp (eval sexp)
17805 (condition-case nil
17806 (eval sexp)
17807 (error
17808 (beep)
17809 (message "Bad sexp at line %d in %s: %s"
17810 (org-current-line)
17811 (buffer-file-name) sexp)
17812 (sleep-for 2))))))
17813 (cond ((stringp result) (split-string result "; "))
17814 ((and (consp result)
17815 (not (consp (cdr result)))
17816 (stringp (cdr result))) (cdr result))
17817 ((and (consp result)
17818 (stringp (car result))) result)
17819 (result entry))))
17821 (defun org-diary-to-ical-string (frombuf)
17822 "Get iCalendar entries from diary entries in buffer FROMBUF.
17823 This uses the icalendar.el library."
17824 (let* ((tmpdir temporary-file-directory)
17825 (tmpfile (make-temp-name
17826 (expand-file-name "orgics" tmpdir)))
17827 buf rtn b e)
17828 (with-current-buffer frombuf
17829 (icalendar-export-region (point-min) (point-max) tmpfile)
17830 (setq buf (find-buffer-visiting tmpfile))
17831 (set-buffer buf)
17832 (goto-char (point-min))
17833 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17834 (setq b (match-beginning 0)))
17835 (goto-char (point-max))
17836 (when (re-search-backward "^END:VEVENT" nil t)
17837 (setq e (match-end 0)))
17838 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17839 (kill-buffer buf)
17840 (delete-file tmpfile)
17841 rtn))
17843 (defun org-closest-date (start current prefer)
17844 "Return closest date to CURRENT starting from START.
17846 CURRENT and START are both time stamps.
17848 When PREFER is `past', return a date that is either CURRENT or
17849 past. When PREFER is `future', return a date that is either
17850 CURRENT or future.
17852 Only time stamps with a repeater are modified. Any other time
17853 stamp stay unchanged. In any case, return value is an absolute
17854 day number."
17855 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17856 ;; No repeater. Do not shift time stamp.
17857 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17858 (let ((value (string-to-number (match-string 1 start)))
17859 (type (match-string 2 start)))
17860 (if (= 0 value)
17861 ;; Repeater with a 0-value is considered as void.
17862 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17863 (let* ((base (org-date-to-gregorian start))
17864 (target (org-date-to-gregorian current))
17865 (sday (calendar-absolute-from-gregorian base))
17866 (cday (calendar-absolute-from-gregorian target))
17867 n1 n2)
17868 ;; If START is already past CURRENT, just return START.
17869 (if (<= cday sday) sday
17870 ;; Compute closest date before (N1) and closest date past
17871 ;; (N2) CURRENT.
17872 (pcase type
17873 ("h"
17874 (let ((missing-hours
17875 (mod (+ (- (* 24 (- cday sday))
17876 (nth 2 (org-parse-time-string start)))
17877 org-extend-today-until)
17878 value)))
17879 (setf n1 (if (= missing-hours 0) cday
17880 (- cday (1+ (/ missing-hours 24)))))
17881 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17882 ((or "d" "w")
17883 (let ((value (if (equal type "w") (* 7 value) value)))
17884 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17885 (setf n2 (+ n1 value))))
17886 ("m"
17887 (let* ((add-months
17888 (lambda (d n)
17889 ;; Add N months to gregorian date D, i.e.,
17890 ;; a list (MONTH DAY YEAR). Return a valid
17891 ;; gregorian date.
17892 (let ((m (+ (nth 0 d) n)))
17893 (list (mod m 12)
17894 (nth 1 d)
17895 (+ (/ m 12) (nth 2 d))))))
17896 (months ; Complete months to TARGET.
17897 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17898 (- (nth 0 target) (nth 0 base))
17899 ;; If START's day is greater than
17900 ;; TARGET's, remove incomplete month.
17901 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17902 value)
17903 value))
17904 (before (funcall add-months base months)))
17905 (setf n1 (calendar-absolute-from-gregorian before))
17906 (setf n2
17907 (calendar-absolute-from-gregorian
17908 (funcall add-months before value)))))
17910 (let* ((d (nth 1 base))
17911 (m (nth 0 base))
17912 (y (nth 2 base))
17913 (years ; Complete years to TARGET.
17914 (* (/ (- (nth 2 target)
17916 ;; If START's month and day are
17917 ;; greater than TARGET's, remove
17918 ;; incomplete year.
17919 (if (or (> (nth 0 target) m)
17920 (and (= (nth 0 target) m)
17921 (> (nth 1 target) d)))
17924 value)
17925 value))
17926 (before (list m d (+ y years))))
17927 (setf n1 (calendar-absolute-from-gregorian before))
17928 (setf n2 (calendar-absolute-from-gregorian
17929 (list m d (+ (nth 2 before) value)))))))
17930 ;; Handle PREFER parameter, if any.
17931 (cond
17932 ((eq prefer 'past) (if (= cday n2) n2 n1))
17933 ((eq prefer 'future) (if (= cday n1) n1 n2))
17934 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17936 (defun org-date-to-gregorian (d)
17937 "Turn any specification of date D into a Gregorian date for the calendar."
17938 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17939 ((and (listp d) (= (length d) 3)) d)
17940 ((stringp d)
17941 (let ((d (org-parse-time-string d)))
17942 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17943 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17945 (defun org-parse-time-string (s &optional nodefault)
17946 "Parse the standard Org time string.
17947 This should be a lot faster than the normal `parse-time-string'.
17948 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17949 hour and minute fields will be nil if not given."
17950 (cond ((string-match org-ts-regexp0 s)
17951 (list 0
17952 (when (or (match-beginning 8) (not nodefault))
17953 (string-to-number (or (match-string 8 s) "0")))
17954 (when (or (match-beginning 7) (not nodefault))
17955 (string-to-number (or (match-string 7 s) "0")))
17956 (string-to-number (match-string 4 s))
17957 (string-to-number (match-string 3 s))
17958 (string-to-number (match-string 2 s))
17959 nil nil nil))
17960 ((string-match "^<[^>]+>$" s)
17961 (decode-time (seconds-to-time (org-matcher-time s))))
17962 (t (error "Not a standard Org time string: %s" s))))
17964 (defun org-timestamp-up (&optional arg)
17965 "Increase the date item at the cursor by one.
17966 If the cursor is on the year, change the year. If it is on the month,
17967 the day or the time, change that.
17968 With prefix ARG, change by that many units."
17969 (interactive "p")
17970 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17972 (defun org-timestamp-down (&optional arg)
17973 "Decrease the date item at the cursor by one.
17974 If the cursor is on the year, change the year. If it is on the month,
17975 the day or the time, change that.
17976 With prefix ARG, change by that many units."
17977 (interactive "p")
17978 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17980 (defun org-timestamp-up-day (&optional arg)
17981 "Increase the date in the time stamp by one day.
17982 With prefix ARG, change that many days."
17983 (interactive "p")
17984 (if (and (not (org-at-timestamp-p t))
17985 (org-at-heading-p))
17986 (org-todo 'up)
17987 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17989 (defun org-timestamp-down-day (&optional arg)
17990 "Decrease the date in the time stamp by one day.
17991 With prefix ARG, change that many days."
17992 (interactive "p")
17993 (if (and (not (org-at-timestamp-p t))
17994 (org-at-heading-p))
17995 (org-todo 'down)
17996 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17998 (defun org-at-timestamp-p (&optional inactive-ok)
17999 "Non-nil if point is inside a timestamp.
18001 When optional argument INACTIVE-OK is non-nil, also consider
18002 inactive timestamps.
18004 When this function returns a non-nil value, match data is set
18005 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18006 INACTIVE-OK."
18007 (interactive)
18008 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18009 (pos (point))
18010 (ans (or (looking-at tsr)
18011 (save-excursion
18012 (skip-chars-backward "^[<\n\r\t")
18013 (when (> (point) (point-min)) (backward-char 1))
18014 (and (looking-at tsr)
18015 (> (- (match-end 0) pos) -1))))))
18016 (and ans
18017 (boundp 'org-ts-what)
18018 (setq org-ts-what
18019 (cond
18020 ((= pos (match-beginning 0)) 'bracket)
18021 ;; Point is considered to be "on the bracket" whether
18022 ;; it's really on it or right after it.
18023 ((= pos (1- (match-end 0))) 'bracket)
18024 ((= pos (match-end 0)) 'after)
18025 ((org-pos-in-match-range pos 2) 'year)
18026 ((org-pos-in-match-range pos 3) 'month)
18027 ((org-pos-in-match-range pos 7) 'hour)
18028 ((org-pos-in-match-range pos 8) 'minute)
18029 ((or (org-pos-in-match-range pos 4)
18030 (org-pos-in-match-range pos 5)) 'day)
18031 ((and (> pos (or (match-end 8) (match-end 5)))
18032 (< pos (match-end 0)))
18033 (- pos (or (match-end 8) (match-end 5))))
18034 (t 'day))))
18035 ans))
18037 (defun org-toggle-timestamp-type ()
18038 "Toggle the type (<active> or [inactive]) of a time stamp."
18039 (interactive)
18040 (when (org-at-timestamp-p t)
18041 (let ((beg (match-beginning 0)) (end (match-end 0))
18042 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18043 (save-excursion
18044 (goto-char beg)
18045 (while (re-search-forward "[][<>]" end t)
18046 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18047 t t)))
18048 (message "Timestamp is now %sactive"
18049 (if (equal (char-after beg) ?<) "" "in")))))
18051 (defun org-at-clock-log-p nil
18052 "Is the cursor on the clock log line?"
18053 (save-excursion
18054 (move-beginning-of-line 1)
18055 (looking-at org-clock-line-re)))
18057 (defvar org-clock-history) ; defined in org-clock.el
18058 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18059 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18060 "Change the date in the time stamp at point.
18061 The date will be changed by N times WHAT. WHAT can be `day', `month',
18062 `year', `minute', `second'. If WHAT is not given, the cursor position
18063 in the timestamp determines what will be changed.
18064 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18065 (let ((origin (point)) origin-cat
18066 with-hm inactive
18067 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18068 org-ts-what
18069 extra rem
18070 ts time time0 fixnext clrgx)
18071 (unless (org-at-timestamp-p t)
18072 (user-error "Not at a timestamp"))
18073 (if (and (not what) (eq org-ts-what 'bracket))
18074 (org-toggle-timestamp-type)
18075 ;; Point isn't on brackets. Remember the part of the time-stamp
18076 ;; the point was in. Indeed, size of time-stamps may change,
18077 ;; but point must be kept in the same category nonetheless.
18078 (setq origin-cat org-ts-what)
18079 (when (and (not what) (not (eq org-ts-what 'day))
18080 org-display-custom-times
18081 (get-text-property (point) 'display)
18082 (not (get-text-property (1- (point)) 'display)))
18083 (setq org-ts-what 'day))
18084 (setq org-ts-what (or what org-ts-what)
18085 inactive (= (char-after (match-beginning 0)) ?\[)
18086 ts (match-string 0))
18087 (replace-match "")
18088 (when (string-match
18089 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18091 (setq extra (match-string 1 ts))
18092 (when suppress-tmp-delay
18093 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18094 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18095 (setq with-hm t))
18096 (setq time0 (org-parse-time-string ts))
18097 (when (and updown
18098 (eq org-ts-what 'minute)
18099 (not current-prefix-arg))
18100 ;; This looks like s-up and s-down. Change by one rounding step.
18101 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18102 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18103 (setcar (cdr time0) (+ (nth 1 time0)
18104 (if (> n 0) (- rem) (- dm rem))))))
18105 (setq time
18106 (apply #'encode-time
18107 (or (car time0) 0)
18108 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18109 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18110 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18111 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18112 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18113 (nthcdr 6 time0)))
18114 (when (and (member org-ts-what '(hour minute))
18115 extra
18116 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18117 (setq extra (org-modify-ts-extra
18118 extra
18119 (if (eq org-ts-what 'hour) 2 5)
18120 n dm)))
18121 (when (integerp org-ts-what)
18122 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18123 (when (eq what 'calendar)
18124 (let ((cal-date (org-get-date-from-calendar)))
18125 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18126 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18127 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18128 (setcar time0 (or (car time0) 0))
18129 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18130 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18131 (setq time (apply 'encode-time time0))))
18132 ;; Insert the new time-stamp, and ensure point stays in the same
18133 ;; category as before (i.e. not after the last position in that
18134 ;; category).
18135 (let ((pos (point)))
18136 ;; Stay before inserted string. `save-excursion' is of no use.
18137 (setq org-last-changed-timestamp
18138 (org-insert-time-stamp time with-hm inactive nil nil extra))
18139 (goto-char pos))
18140 (save-match-data
18141 (looking-at org-ts-regexp3)
18142 (goto-char (cond
18143 ;; `day' category ends before `hour' if any, or at
18144 ;; the end of the day name.
18145 ((eq origin-cat 'day)
18146 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18147 ((eq origin-cat 'hour) (min (match-end 7) origin))
18148 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18149 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18150 ;; `year' and `month' have both fixed size: point
18151 ;; couldn't have moved into another part.
18152 (t origin))))
18153 ;; Update clock if on a CLOCK line.
18154 (org-clock-update-time-maybe)
18155 ;; Maybe adjust the closest clock in `org-clock-history'
18156 (when org-clock-adjust-closest
18157 (if (not (and (org-at-clock-log-p)
18158 (< 1 (length (delq nil (mapcar 'marker-position
18159 org-clock-history))))))
18160 (message "No clock to adjust")
18161 (cond ((save-excursion ; fix previous clock?
18162 (re-search-backward org-ts-regexp0 nil t)
18163 (looking-back (concat org-clock-string " \\[")
18164 (line-beginning-position)))
18165 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18166 ((save-excursion ; fix next clock?
18167 (re-search-backward org-ts-regexp0 nil t)
18168 (looking-at (concat org-ts-regexp0 "\\] =>")))
18169 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18170 (save-window-excursion
18171 ;; Find closest clock to point, adjust the previous/next one in history
18172 (let* ((p (save-excursion (org-back-to-heading t)))
18173 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18174 (clfixnth
18175 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18176 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18177 (if (not clfixpos)
18178 (message "No clock to adjust")
18179 (save-excursion
18180 (org-goto-marker-or-bmk clfixpos)
18181 (org-show-subtree)
18182 (when (re-search-forward clrgx nil t)
18183 (goto-char (match-beginning 1))
18184 (let (org-clock-adjust-closest)
18185 (org-timestamp-change n org-ts-what updown))
18186 (message "Clock adjusted in %s for heading: %s"
18187 (file-name-nondirectory (buffer-file-name))
18188 (org-get-heading t t)))))))))
18189 ;; Try to recenter the calendar window, if any.
18190 (when (and org-calendar-follow-timestamp-change
18191 (get-buffer-window "*Calendar*" t)
18192 (memq org-ts-what '(day month year)))
18193 (org-recenter-calendar (time-to-days time))))))
18195 (defun org-modify-ts-extra (s pos n dm)
18196 "Change the different parts of the lead-time and repeat fields in timestamp."
18197 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18198 ng h m new rem)
18199 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18200 (cond
18201 ((or (org-pos-in-match-range pos 2)
18202 (org-pos-in-match-range pos 3))
18203 (setq m (string-to-number (match-string 3 s))
18204 h (string-to-number (match-string 2 s)))
18205 (if (org-pos-in-match-range pos 2)
18206 (setq h (+ h n))
18207 (setq n (* dm (with-no-warnings (signum n))))
18208 (unless (= 0 (setq rem (% m dm)))
18209 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18210 (setq m (+ m n)))
18211 (when (< m 0) (setq m (+ m 60) h (1- h)))
18212 (when (> m 59) (setq m (- m 60) h (1+ h)))
18213 (setq h (mod h 24))
18214 (setq ng 1 new (format "-%02d:%02d" h m)))
18215 ((org-pos-in-match-range pos 6)
18216 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18217 ((org-pos-in-match-range pos 5)
18218 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18220 ((org-pos-in-match-range pos 9)
18221 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18222 ((org-pos-in-match-range pos 8)
18223 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18225 (when ng
18226 (setq s (concat
18227 (substring s 0 (match-beginning ng))
18229 (substring s (match-end ng))))))
18232 (defun org-recenter-calendar (d)
18233 "If the calendar is visible, recenter it to date D."
18234 (let ((cwin (get-buffer-window "*Calendar*" t)))
18235 (when cwin
18236 (let ((calendar-move-hook nil))
18237 (with-selected-window cwin
18238 (calendar-goto-date
18239 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18241 (defun org-goto-calendar (&optional arg)
18242 "Go to the Emacs calendar at the current date.
18243 If there is a time stamp in the current line, go to that date.
18244 A prefix ARG can be used to force the current date."
18245 (interactive "P")
18246 (let ((tsr org-ts-regexp) diff
18247 (calendar-move-hook nil)
18248 (calendar-view-holidays-initially-flag nil)
18249 (calendar-view-diary-initially-flag nil))
18250 (when (or (org-at-timestamp-p)
18251 (save-excursion
18252 (beginning-of-line 1)
18253 (looking-at (concat ".*" tsr))))
18254 (let ((d1 (time-to-days (current-time)))
18255 (d2 (time-to-days
18256 (org-time-string-to-time (match-string 1)))))
18257 (setq diff (- d2 d1))))
18258 (calendar)
18259 (calendar-goto-today)
18260 (when (and diff (not arg)) (calendar-forward-day diff))))
18262 (defun org-get-date-from-calendar ()
18263 "Return a list (month day year) of date at point in calendar."
18264 (with-current-buffer "*Calendar*"
18265 (save-match-data
18266 (calendar-cursor-to-date))))
18268 (defun org-date-from-calendar ()
18269 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18270 If there is already a time stamp at the cursor position, update it."
18271 (interactive)
18272 (if (org-at-timestamp-p t)
18273 (org-timestamp-change 0 'calendar)
18274 (let ((cal-date (org-get-date-from-calendar)))
18275 (org-insert-time-stamp
18276 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18278 (defcustom org-effort-durations
18279 `(("min" . 1)
18280 ("h" . 60)
18281 ("d" . ,(* 60 8))
18282 ("w" . ,(* 60 8 5))
18283 ("m" . ,(* 60 8 5 4))
18284 ("y" . ,(* 60 8 5 40)))
18285 "Conversion factor to minutes for an effort modifier.
18287 Each entry has the form (MODIFIER . MINUTES).
18289 In an effort string, a number followed by MODIFIER is multiplied
18290 by the specified number of MINUTES to obtain an effort in
18291 minutes.
18293 For example, if the value of this variable is ((\"hours\" . 60)), then an
18294 effort string \"2hours\" is equivalent to 120 minutes."
18295 :group 'org-agenda
18296 :version "25.1"
18297 :package-version '(Org . "8.3")
18298 :type '(alist :key-type (string :tag "Modifier")
18299 :value-type (number :tag "Minutes")))
18301 (defun org-minutes-to-clocksum-string (m)
18302 "Format number of minutes as a clocksum string.
18303 The format is determined by `org-time-clocksum-format',
18304 `org-time-clocksum-use-fractional' and
18305 `org-time-clocksum-fractional-format' and
18306 `org-time-clocksum-use-effort-durations'."
18307 (let ((clocksum "")
18308 (m (round m)) ; Don't allow fractions of minutes
18309 h d w mo y fmt n)
18310 (setq h (if org-time-clocksum-use-effort-durations
18311 (cdr (assoc "h" org-effort-durations)) 60)
18312 d (if org-time-clocksum-use-effort-durations
18313 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18314 w (if org-time-clocksum-use-effort-durations
18315 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18316 mo (if org-time-clocksum-use-effort-durations
18317 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18318 y (if org-time-clocksum-use-effort-durations
18319 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18320 ;; fractional format
18321 (if org-time-clocksum-use-fractional
18322 (cond
18323 ;; single format string
18324 ((stringp org-time-clocksum-fractional-format)
18325 (format org-time-clocksum-fractional-format (/ m (float h))))
18326 ;; choice of fractional formats for different time units
18327 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18328 (> (/ (truncate m) (* y d h)) 0))
18329 (format fmt (/ m (* y d (float h)))))
18330 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18331 (> (/ (truncate m) (* mo d h)) 0))
18332 (format fmt (/ m (* mo d (float h)))))
18333 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18334 (> (/ (truncate m) (* w d h)) 0))
18335 (format fmt (/ m (* w d (float h)))))
18336 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18337 (> (/ (truncate m) (* d h)) 0))
18338 (format fmt (/ m (* d (float h)))))
18339 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18340 (> (/ (truncate m) h) 0))
18341 (format fmt (/ m (float h))))
18342 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18343 (format fmt m))
18344 ;; fall back to smallest time unit with a format
18345 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18346 (format fmt (/ m (float h))))
18347 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18348 (format fmt (/ m (* d (float h)))))
18349 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18350 (format fmt (/ m (* w d (float h)))))
18351 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18352 (format fmt (/ m (* mo d (float h)))))
18353 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18354 (format fmt (/ m (* y d (float h))))))
18355 ;; standard (non-fractional) format, with single format string
18356 (if (stringp org-time-clocksum-format)
18357 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18358 ;; separate formats components
18359 (and (setq fmt (plist-get org-time-clocksum-format :years))
18360 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18361 (plist-get org-time-clocksum-format :require-years))
18362 (setq clocksum (concat clocksum (format fmt n))
18363 m (- m (* n y d h))))
18364 (and (setq fmt (plist-get org-time-clocksum-format :months))
18365 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18366 (plist-get org-time-clocksum-format :require-months))
18367 (setq clocksum (concat clocksum (format fmt n))
18368 m (- m (* n mo d h))))
18369 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18370 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18371 (plist-get org-time-clocksum-format :require-weeks))
18372 (setq clocksum (concat clocksum (format fmt n))
18373 m (- m (* n w d h))))
18374 (and (setq fmt (plist-get org-time-clocksum-format :days))
18375 (or (> (setq n (/ (truncate m) (* d h))) 0)
18376 (plist-get org-time-clocksum-format :require-days))
18377 (setq clocksum (concat clocksum (format fmt n))
18378 m (- m (* n d h))))
18379 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18380 (or (> (setq n (/ (truncate m) h)) 0)
18381 (plist-get org-time-clocksum-format :require-hours))
18382 (setq clocksum (concat clocksum (format fmt n))
18383 m (- m (* n h))))
18384 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18385 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18386 (setq clocksum (concat clocksum (format fmt m))))
18387 ;; return formatted time duration
18388 clocksum))))
18390 (defun org-hours-to-clocksum-string (n)
18391 (org-minutes-to-clocksum-string (* n 60)))
18393 (defun org-hh:mm-string-to-minutes (s)
18394 "Convert a string H:MM to a number of minutes.
18395 If the string is just a number, interpret it as minutes.
18396 In fact, the first hh:mm or number in the string will be taken,
18397 there can be extra stuff in the string.
18398 If no number is found, the return value is 0."
18399 (cond
18400 ((integerp s) s)
18401 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18402 (+ (* (string-to-number (match-string 1 s)) 60)
18403 (string-to-number (match-string 2 s))))
18404 ((string-match "\\([0-9]+\\)" s)
18405 (string-to-number (match-string 1 s)))
18406 (t 0)))
18408 (defcustom org-image-actual-width t
18409 "Should we use the actual width of images when inlining them?
18411 When set to t, always use the image width.
18413 When set to a number, use imagemagick (when available) to set
18414 the image's width to this value.
18416 When set to a number in a list, try to get the width from any
18417 #+ATTR.* keyword if it matches a width specification like
18419 #+ATTR_HTML: :width 300px
18421 and fall back on that number if none is found.
18423 When set to nil, try to get the width from an #+ATTR.* keyword
18424 and fall back on the original width if none is found.
18426 This requires Emacs >= 24.1, build with imagemagick support."
18427 :group 'org-appearance
18428 :version "24.4"
18429 :package-version '(Org . "8.0")
18430 :type '(choice
18431 (const :tag "Use the image width" t)
18432 (integer :tag "Use a number of pixels")
18433 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18434 (const :tag "Use #+ATTR* or don't resize" nil)))
18436 (defcustom org-agenda-inhibit-startup nil
18437 "Inhibit startup when preparing agenda buffers.
18438 When this variable is t, the initialization of the Org agenda
18439 buffers is inhibited: e.g. the visibility state is not set, the
18440 tables are not re-aligned, etc."
18441 :type 'boolean
18442 :version "24.3"
18443 :group 'org-agenda)
18445 (defcustom org-agenda-ignore-properties nil
18446 "Avoid updating text properties when building the agenda.
18447 Properties are used to prepare buffers for effort estimates,
18448 appointments, statistics and subtree-local categories.
18449 If you don't use these in the agenda, you can add them to this
18450 list and agenda building will be a bit faster.
18451 The value is a list, with zero or more of the symbols `effort', `appt',
18452 `stats' or `category'."
18453 :type '(set :greedy t
18454 (const effort)
18455 (const appt)
18456 (const stats)
18457 (const category))
18458 :version "25.1"
18459 :package-version '(Org . "8.3")
18460 :group 'org-agenda)
18462 (defun org-duration-string-to-minutes (s &optional output-to-string)
18463 "Convert a duration string S to minutes.
18465 A bare number is interpreted as minutes, modifiers can be set by
18466 customizing `org-effort-durations' (which see).
18468 Entries containing a colon are interpreted as H:MM by
18469 `org-hh:mm-string-to-minutes'."
18470 (let ((result 0)
18471 (re (concat "\\([0-9.]+\\) *\\("
18472 (regexp-opt (mapcar 'car org-effort-durations))
18473 "\\)")))
18474 (while (string-match re s)
18475 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18476 (string-to-number (match-string 1 s))))
18477 (setq s (replace-match "" nil t s)))
18478 (setq result (floor result))
18479 (cl-incf result (org-hh:mm-string-to-minutes s))
18480 (if output-to-string (number-to-string result) result)))
18482 ;;;; Files
18484 (defun org-save-all-org-buffers ()
18485 "Save all Org buffers without user confirmation."
18486 (interactive)
18487 (message "Saving all Org buffers...")
18488 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18489 (when (featurep 'org-id) (org-id-locations-save))
18490 (message "Saving all Org buffers... done"))
18492 (defun org-revert-all-org-buffers ()
18493 "Revert all Org buffers.
18494 Prompt for confirmation when there are unsaved changes.
18495 Be sure you know what you are doing before letting this function
18496 overwrite your changes.
18498 This function is useful in a setup where one tracks org files
18499 with a version control system, to revert on one machine after pulling
18500 changes from another. I believe the procedure must be like this:
18502 1. M-x org-save-all-org-buffers
18503 2. Pull changes from the other machine, resolve conflicts
18504 3. M-x org-revert-all-org-buffers"
18505 (interactive)
18506 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18507 (user-error "Abort"))
18508 (save-excursion
18509 (save-window-excursion
18510 (dolist (b (buffer-list))
18511 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18512 (with-current-buffer b buffer-file-name))
18513 (pop-to-buffer-same-window b)
18514 (revert-buffer t 'no-confirm)))
18515 (when (and (featurep 'org-id) org-id-track-globally)
18516 (org-id-locations-load)))))
18518 ;;;; Agenda files
18520 ;;;###autoload
18521 (defun org-switchb (&optional arg)
18522 "Switch between Org buffers.
18524 With \\[universal-argument] prefix, restrict available buffers to files.
18526 With \\[universal-argument] \\[universal-argument] \
18527 prefix, restrict available buffers to agenda files."
18528 (interactive "P")
18529 (let ((blist (org-buffer-list
18530 (cond ((equal arg '(4)) 'files)
18531 ((equal arg '(16)) 'agenda)))))
18532 (pop-to-buffer-same-window
18533 (completing-read "Org buffer: "
18534 (mapcar #'list (mapcar #'buffer-name blist))
18535 nil t))))
18537 (defun org-buffer-list (&optional predicate exclude-tmp)
18538 "Return a list of Org buffers.
18539 PREDICATE can be `export', `files' or `agenda'.
18541 export restrict the list to Export buffers.
18542 files restrict the list to buffers visiting Org files.
18543 agenda restrict the list to buffers visiting agenda files.
18545 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18546 (let* ((bfn nil)
18547 (agenda-files (and (eq predicate 'agenda)
18548 (mapcar 'file-truename (org-agenda-files t))))
18549 (filter
18550 (cond
18551 ((eq predicate 'files)
18552 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18553 ((eq predicate 'export)
18554 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18555 ((eq predicate 'agenda)
18556 (lambda (b)
18557 (with-current-buffer b
18558 (and (derived-mode-p 'org-mode)
18559 (setq bfn (buffer-file-name b))
18560 (member (file-truename bfn) agenda-files)))))
18561 (t (lambda (b) (with-current-buffer b
18562 (or (derived-mode-p 'org-mode)
18563 (string-match "\\*Org .*Export"
18564 (buffer-name b)))))))))
18565 (delq nil
18566 (mapcar
18567 (lambda(b)
18568 (if (and (funcall filter b)
18569 (or (not exclude-tmp)
18570 (not (string-match "tmp" (buffer-name b)))))
18572 nil))
18573 (buffer-list)))))
18575 (defun org-agenda-files (&optional unrestricted archives)
18576 "Get the list of agenda files.
18577 Optional UNRESTRICTED means return the full list even if a restriction
18578 is currently in place.
18579 When ARCHIVES is t, include all archive files that are really being
18580 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18581 `org-agenda-archives-mode' is t."
18582 (let ((files
18583 (cond
18584 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18585 ((stringp org-agenda-files) (org-read-agenda-file-list))
18586 ((listp org-agenda-files) org-agenda-files)
18587 (t (error "Invalid value of `org-agenda-files'")))))
18588 (setq files (apply 'append
18589 (mapcar (lambda (f)
18590 (if (file-directory-p f)
18591 (directory-files
18592 f t org-agenda-file-regexp)
18593 (list f)))
18594 files)))
18595 (when org-agenda-skip-unavailable-files
18596 (setq files (delq nil
18597 (mapcar (function
18598 (lambda (file)
18599 (and (file-readable-p file) file)))
18600 files))))
18601 (when (or (eq archives t)
18602 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18603 (setq files (org-add-archive-files files)))
18604 files))
18606 (defun org-agenda-file-p (&optional file)
18607 "Return non-nil, if FILE is an agenda file.
18608 If FILE is omitted, use the file associated with the current
18609 buffer."
18610 (let ((fname (or file (buffer-file-name))))
18611 (and fname
18612 (member (file-truename fname)
18613 (mapcar #'file-truename (org-agenda-files t))))))
18615 (defun org-edit-agenda-file-list ()
18616 "Edit the list of agenda files.
18617 Depending on setup, this either uses customize to edit the variable
18618 `org-agenda-files', or it visits the file that is holding the list. In the
18619 latter case, the buffer is set up in a way that saving it automatically kills
18620 the buffer and restores the previous window configuration."
18621 (interactive)
18622 (if (stringp org-agenda-files)
18623 (let ((cw (current-window-configuration)))
18624 (find-file org-agenda-files)
18625 (setq-local org-window-configuration cw)
18626 (add-hook 'after-save-hook
18627 (lambda ()
18628 (set-window-configuration
18629 (prog1 org-window-configuration
18630 (kill-buffer (current-buffer))))
18631 (org-install-agenda-files-menu)
18632 (message "New agenda file list installed"))
18633 nil 'local)
18634 (message "%s" (substitute-command-keys
18635 "Edit list and finish with \\[save-buffer]")))
18636 (customize-variable 'org-agenda-files)))
18638 (defun org-store-new-agenda-file-list (list)
18639 "Set new value for the agenda file list and save it correctly."
18640 (if (stringp org-agenda-files)
18641 (let ((fe (org-read-agenda-file-list t)) b u)
18642 (while (setq b (find-buffer-visiting org-agenda-files))
18643 (kill-buffer b))
18644 (with-temp-file org-agenda-files
18645 (insert
18646 (mapconcat
18647 (lambda (f) ;; Keep un-expanded entries.
18648 (if (setq u (assoc f fe))
18649 (cdr u)
18651 list "\n")
18652 "\n")))
18653 (let ((org-mode-hook nil) (org-inhibit-startup t)
18654 (org-insert-mode-line-in-empty-file nil))
18655 (setq org-agenda-files list)
18656 (customize-save-variable 'org-agenda-files org-agenda-files))))
18658 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18659 "Read the list of agenda files from a file.
18660 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18661 filenames, used by `org-store-new-agenda-file-list' to write back
18662 un-expanded file names."
18663 (when (file-directory-p org-agenda-files)
18664 (error "`org-agenda-files' cannot be a single directory"))
18665 (when (stringp org-agenda-files)
18666 (with-temp-buffer
18667 (insert-file-contents org-agenda-files)
18668 (mapcar
18669 (lambda (f)
18670 (let ((e (expand-file-name (substitute-in-file-name f)
18671 org-directory)))
18672 (if pair-with-expansion
18673 (cons e f)
18674 e)))
18675 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18677 ;;;###autoload
18678 (defun org-cycle-agenda-files ()
18679 "Cycle through the files in `org-agenda-files'.
18680 If the current buffer visits an agenda file, find the next one in the list.
18681 If the current buffer does not, find the first agenda file."
18682 (interactive)
18683 (let* ((fs (or (org-agenda-files t)
18684 (user-error "No agenda files")))
18685 (files (copy-sequence fs))
18686 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18687 file)
18688 (when tcf
18689 (while (and (setq file (pop files))
18690 (not (equal (file-truename file) tcf)))))
18691 (find-file (car (or files fs)))
18692 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18694 (defun org-agenda-file-to-front (&optional to-end)
18695 "Move/add the current file to the top of the agenda file list.
18696 If the file is not present in the list, it is added to the front. If it is
18697 present, it is moved there. With optional argument TO-END, add/move to the
18698 end of the list."
18699 (interactive "P")
18700 (let ((org-agenda-skip-unavailable-files nil)
18701 (file-alist (mapcar (lambda (x)
18702 (cons (file-truename x) x))
18703 (org-agenda-files t)))
18704 (ctf (file-truename
18705 (or buffer-file-name
18706 (user-error "Please save the current buffer to a file"))))
18707 x had)
18708 (setq x (assoc ctf file-alist) had x)
18710 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18711 (if to-end
18712 (setq file-alist (append (delq x file-alist) (list x)))
18713 (setq file-alist (cons x (delq x file-alist))))
18714 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18715 (org-install-agenda-files-menu)
18716 (message "File %s to %s of agenda file list"
18717 (if had "moved" "added") (if to-end "end" "front"))))
18719 (defun org-remove-file (&optional file)
18720 "Remove current file from the list of files in variable `org-agenda-files'.
18721 These are the files which are being checked for agenda entries.
18722 Optional argument FILE means use this file instead of the current."
18723 (interactive)
18724 (let* ((org-agenda-skip-unavailable-files nil)
18725 (file (or file buffer-file-name
18726 (user-error "Current buffer does not visit a file")))
18727 (true-file (file-truename file))
18728 (afile (abbreviate-file-name file))
18729 (files (delq nil (mapcar
18730 (lambda (x)
18731 (unless (equal true-file
18732 (file-truename x))
18734 (org-agenda-files t)))))
18735 (if (not (= (length files) (length (org-agenda-files t))))
18736 (progn
18737 (org-store-new-agenda-file-list files)
18738 (org-install-agenda-files-menu)
18739 (message "Removed from Org Agenda list: %s" afile))
18740 (message "File was not in list: %s (not removed)" afile))))
18742 (defun org-file-menu-entry (file)
18743 (vector file (list 'find-file file) t))
18745 (defun org-check-agenda-file (file)
18746 "Make sure FILE exists. If not, ask user what to do."
18747 (unless (file-exists-p file)
18748 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18749 (abbreviate-file-name file))
18750 (let ((r (downcase (read-char-exclusive))))
18751 (cond
18752 ((equal r ?r)
18753 (org-remove-file file)
18754 (throw 'nextfile t))
18755 (t (user-error "Abort"))))))
18757 (defun org-get-agenda-file-buffer (file)
18758 "Get an agenda buffer visiting FILE.
18759 If the buffer needs to be created, add it to the list of buffers
18760 which might be released later."
18761 (let ((buf (org-find-base-buffer-visiting file)))
18762 (if buf
18763 buf ; just return it
18764 ;; Make a new buffer and remember it
18765 (setq buf (find-file-noselect file))
18766 (when buf (push buf org-agenda-new-buffers))
18767 buf)))
18769 (defun org-release-buffers (blist)
18770 "Release all buffers in list, asking the user for confirmation when needed.
18771 When a buffer is unmodified, it is just killed. When modified, it is saved
18772 \(if the user agrees) and then killed."
18773 (let (file)
18774 (dolist (buf blist)
18775 (setq file (buffer-file-name buf))
18776 (when (and (buffer-modified-p buf)
18777 file
18778 (y-or-n-p (format "Save file %s? " file)))
18779 (with-current-buffer buf (save-buffer)))
18780 (kill-buffer buf))))
18782 (defun org-agenda-prepare-buffers (files)
18783 "Create buffers for all agenda files, protect archived trees and comments."
18784 (interactive)
18785 (let ((pa '(:org-archived t))
18786 (pc '(:org-comment t))
18787 (pall '(:org-archived t :org-comment t))
18788 (inhibit-read-only t)
18789 (org-inhibit-startup org-agenda-inhibit-startup)
18790 (rea (concat ":" org-archive-tag ":"))
18791 re pos)
18792 (setq org-tag-alist-for-agenda nil
18793 org-tag-groups-alist-for-agenda nil)
18794 (save-excursion
18795 (save-restriction
18796 (dolist (file files)
18797 (catch 'nextfile
18798 (if (bufferp file)
18799 (set-buffer file)
18800 (org-check-agenda-file file)
18801 (set-buffer (org-get-agenda-file-buffer file)))
18802 (widen)
18803 (org-set-regexps-and-options 'tags-only)
18804 (setq pos (point))
18805 (or (memq 'category org-agenda-ignore-properties)
18806 (org-refresh-category-properties))
18807 (or (memq 'stats org-agenda-ignore-properties)
18808 (org-refresh-stats-properties))
18809 (or (memq 'effort org-agenda-ignore-properties)
18810 (org-refresh-effort-properties))
18811 (or (memq 'appt org-agenda-ignore-properties)
18812 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18813 (setq org-todo-keywords-for-agenda
18814 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18815 (setq org-done-keywords-for-agenda
18816 (append org-done-keywords-for-agenda org-done-keywords))
18817 (setq org-todo-keyword-alist-for-agenda
18818 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18819 (setq org-tag-alist-for-agenda
18820 (org-uniquify
18821 (append org-tag-alist-for-agenda
18822 org-current-tag-alist)))
18823 ;; Merge current file's tag groups into global
18824 ;; `org-tag-groups-alist-for-agenda'.
18825 (when org-group-tags
18826 (dolist (alist org-tag-groups-alist)
18827 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18828 (if old
18829 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18830 (push alist org-tag-groups-alist-for-agenda)))))
18831 (org-with-silent-modifications
18832 (save-excursion
18833 (remove-text-properties (point-min) (point-max) pall)
18834 (when org-agenda-skip-archived-trees
18835 (goto-char (point-min))
18836 (while (re-search-forward rea nil t)
18837 (when (org-at-heading-p t)
18838 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18839 (goto-char (point-min))
18840 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18841 (while (re-search-forward re nil t)
18842 (when (save-match-data (org-in-commented-heading-p t))
18843 (add-text-properties
18844 (match-beginning 0) (org-end-of-subtree t) pc)))))
18845 (goto-char pos)))))
18846 (setq org-todo-keywords-for-agenda
18847 (org-uniquify org-todo-keywords-for-agenda))
18848 (setq org-todo-keyword-alist-for-agenda
18849 (org-uniquify org-todo-keyword-alist-for-agenda))))
18852 ;;;; CDLaTeX minor mode
18854 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18855 "Keymap for the minor `org-cdlatex-mode'.")
18857 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18858 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18859 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18860 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18861 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18863 (defvar org-cdlatex-texmathp-advice-is-done nil
18864 "Flag remembering if we have applied the advice to texmathp already.")
18866 (define-minor-mode org-cdlatex-mode
18867 "Toggle the minor `org-cdlatex-mode'.
18868 This mode supports entering LaTeX environment and math in LaTeX fragments
18869 in Org-mode.
18870 \\{org-cdlatex-mode-map}"
18871 nil " OCDL" nil
18872 (when org-cdlatex-mode
18873 (require 'cdlatex)
18874 (run-hooks 'cdlatex-mode-hook)
18875 (cdlatex-compute-tables))
18876 (unless org-cdlatex-texmathp-advice-is-done
18877 (setq org-cdlatex-texmathp-advice-is-done t)
18878 (defadvice texmathp (around org-math-always-on activate)
18879 "Always return t in Org buffers.
18880 This is because we want to insert math symbols without dollars even outside
18881 the LaTeX math segments. If Orgmode thinks that point is actually inside
18882 an embedded LaTeX fragment, let texmathp do its job.
18883 \\[org-cdlatex-mode-map]"
18884 (interactive)
18885 (let (p)
18886 (cond
18887 ((not (derived-mode-p 'org-mode)) ad-do-it)
18888 ((eq this-command 'cdlatex-math-symbol)
18889 (setq ad-return-value t
18890 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18892 (let ((p (org-inside-LaTeX-fragment-p)))
18893 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18894 (setq ad-return-value t
18895 texmathp-why '("Org-mode embedded math" . 0))
18896 (when p ad-do-it)))))))))
18898 (defun turn-on-org-cdlatex ()
18899 "Unconditionally turn on `org-cdlatex-mode'."
18900 (org-cdlatex-mode 1))
18902 (defun org-try-cdlatex-tab ()
18903 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18904 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18905 - inside a LaTeX fragment, or
18906 - after the first word in a line, where an abbreviation expansion could
18907 insert a LaTeX environment."
18908 (when org-cdlatex-mode
18909 (cond
18910 ;; Before any word on the line: No expansion possible.
18911 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18912 ;; Just after first word on the line: Expand it. Make sure it
18913 ;; cannot happen on headlines, though.
18914 ((save-excursion
18915 (skip-chars-backward "a-zA-Z0-9*")
18916 (skip-chars-backward " \t")
18917 (and (bolp) (not (org-at-heading-p))))
18918 (cdlatex-tab) t)
18919 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18921 (defun org-cdlatex-underscore-caret (&optional _arg)
18922 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18923 Revert to the normal definition outside of these fragments."
18924 (interactive "P")
18925 (if (org-inside-LaTeX-fragment-p)
18926 (call-interactively 'cdlatex-sub-superscript)
18927 (let (org-cdlatex-mode)
18928 (call-interactively (key-binding (vector last-input-event))))))
18930 (defun org-cdlatex-math-modify (&optional _arg)
18931 "Execute `cdlatex-math-modify' in LaTeX fragments.
18932 Revert to the normal definition outside of these fragments."
18933 (interactive "P")
18934 (if (org-inside-LaTeX-fragment-p)
18935 (call-interactively 'cdlatex-math-modify)
18936 (let (org-cdlatex-mode)
18937 (call-interactively (key-binding (vector last-input-event))))))
18939 (defun org-cdlatex-environment-indent (&optional environment item)
18940 "Execute `cdlatex-environment' and indent the inserted environment.
18942 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18944 The inserted environment is indented to current indentation
18945 unless point is at the beginning of the line, in which the
18946 environment remains unintended."
18947 (interactive)
18948 ;; cdlatex-environment always return nil. Therefore, capture output
18949 ;; first and determine if an environment was selected.
18950 (let* ((beg (point-marker))
18951 (end (copy-marker (point) t))
18952 (inserted (progn
18953 (ignore-errors (cdlatex-environment environment item))
18954 (< beg end)))
18955 ;; Figure out how many lines to move forward after the
18956 ;; environment has been inserted.
18957 (lines (when inserted
18958 (save-excursion
18959 (- (cl-loop while (< beg (point))
18960 with x = 0
18961 do (forward-line -1)
18962 (cl-incf x)
18963 finally return x)
18964 (if (progn (goto-char beg)
18965 (and (progn (skip-chars-forward " \t") (eolp))
18966 (progn (skip-chars-backward " \t") (bolp))))
18967 1 0)))))
18968 (env (org-trim (delete-and-extract-region beg end))))
18969 (when inserted
18970 ;; Get indentation of next line unless at column 0.
18971 (let ((ind (if (bolp) 0
18972 (save-excursion
18973 (org-return-indent)
18974 (prog1 (org-get-indentation)
18975 (when (progn (skip-chars-forward " \t") (eolp))
18976 (delete-region beg (point)))))))
18977 (bol (progn (skip-chars-backward " \t") (bolp))))
18978 ;; Insert a newline before environment unless at column zero
18979 ;; to "escape" the current line. Insert a newline if
18980 ;; something is one the same line as \end{ENVIRONMENT}.
18981 (insert
18982 (concat (unless bol "\n") env
18983 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18984 (unless (zerop ind)
18985 (save-excursion
18986 (goto-char beg)
18987 (while (< (point) end)
18988 (unless (eolp) (indent-line-to ind))
18989 (forward-line))))
18990 (goto-char beg)
18991 (forward-line lines)
18992 (indent-line-to ind)))
18993 (set-marker beg nil)
18994 (set-marker end nil)))
18997 ;;;; LaTeX fragments
18999 (defun org-inside-LaTeX-fragment-p ()
19000 "Test if point is inside a LaTeX fragment.
19001 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19002 sequence appearing also before point.
19003 Even though the matchers for math are configurable, this function assumes
19004 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19005 delimiters are skipped when they have been removed by customization.
19006 The return value is nil, or a cons cell with the delimiter and the
19007 position of this delimiter.
19009 This function does a reasonably good job, but can locally be fooled by
19010 for example currency specifications. For example it will assume being in
19011 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19012 fragments that are properly closed, but during editing, we have to live
19013 with the uncertainty caused by missing closing delimiters. This function
19014 looks only before point, not after."
19015 (catch 'exit
19016 (let ((pos (point))
19017 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19018 (lim (progn
19019 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19020 (point)))
19021 dd-on str (start 0) m re)
19022 (goto-char pos)
19023 (when dodollar
19024 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19025 re (nth 1 (assoc "$" org-latex-regexps)))
19026 (while (string-match re str start)
19027 (cond
19028 ((= (match-end 0) (length str))
19029 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19030 ((= (match-end 0) (- (length str) 5))
19031 (throw 'exit nil))
19032 (t (setq start (match-end 0))))))
19033 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19034 (goto-char pos)
19035 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19036 (and (match-beginning 2) (throw 'exit nil))
19037 ;; count $$
19038 (while (re-search-backward "\\$\\$" lim t)
19039 (setq dd-on (not dd-on)))
19040 (goto-char pos)
19041 (when dd-on (cons "$$" m))))))
19043 (defun org-inside-latex-macro-p ()
19044 "Is point inside a LaTeX macro or its arguments?"
19045 (save-match-data
19046 (org-in-regexp
19047 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19049 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19050 "Build an overlay between BEG and END using IMAGE file.
19051 Argument IMAGETYPE is the extension of the displayed image,
19052 as a string. It defaults to \"png\"."
19053 (let ((ov (make-overlay beg end))
19054 (imagetype (or (intern imagetype) 'png)))
19055 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19056 (overlay-put ov 'evaporate t)
19057 (overlay-put ov
19058 'modification-hooks
19059 (list (lambda (o _flag _beg _end &optional _l)
19060 (delete-overlay o))))
19061 (overlay-put ov
19062 'display
19063 (list 'image :type imagetype :file image :ascent 'center))))
19065 (defun org--list-latex-overlays (&optional beg end)
19066 "List all Org LaTeX overlays in current buffer.
19067 Limit to overlays between BEG and END when those are provided."
19068 (cl-remove-if-not
19069 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19070 (overlays-in (or beg (point-min)) (or end (point-max)))))
19072 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19073 "Remove all overlays with LaTeX fragment images in current buffer.
19074 When optional arguments BEG and END are non-nil, remove all
19075 overlays between them instead. Return a non-nil value when some
19076 overlays were removed, nil otherwise."
19077 (let ((overlays (org--list-latex-overlays beg end)))
19078 (mapc #'delete-overlay overlays)
19079 overlays))
19081 (defun org-toggle-latex-fragment (&optional arg)
19082 "Preview the LaTeX fragment at point, or all locally or globally.
19084 If the cursor is on a LaTeX fragment, create the image and overlay
19085 it over the source code, if there is none. Remove it otherwise.
19086 If there is no fragment at point, display all fragments in the
19087 current section.
19089 With prefix ARG, preview or clear image for all fragments in the
19090 current subtree or in the whole buffer when used before the first
19091 headline. With a double prefix ARG \\[universal-argument] \
19092 \\[universal-argument] preview or clear images
19093 for all fragments in the buffer."
19094 (interactive "P")
19095 (when (display-graphic-p)
19096 (catch 'exit
19097 (save-excursion
19098 (let (beg end msg)
19099 (cond
19100 ((or (equal arg '(16))
19101 (and (equal arg '(4))
19102 (org-with-limited-levels (org-before-first-heading-p))))
19103 (if (org-remove-latex-fragment-image-overlays)
19104 (progn (message "LaTeX fragments images removed from buffer")
19105 (throw 'exit nil))
19106 (setq msg "Creating images for buffer...")))
19107 ((equal arg '(4))
19108 (org-with-limited-levels (org-back-to-heading t))
19109 (setq beg (point))
19110 (setq end (progn (org-end-of-subtree t) (point)))
19111 (if (org-remove-latex-fragment-image-overlays beg end)
19112 (progn
19113 (message "LaTeX fragment images removed from subtree")
19114 (throw 'exit nil))
19115 (setq msg "Creating images for subtree...")))
19116 ((let ((datum (org-element-context)))
19117 (when (memq (org-element-type datum)
19118 '(latex-environment latex-fragment))
19119 (setq beg (org-element-property :begin datum))
19120 (setq end (org-element-property :end datum))
19121 (if (org-remove-latex-fragment-image-overlays beg end)
19122 (progn (message "LaTeX fragment image removed")
19123 (throw 'exit nil))
19124 (setq msg "Creating image...")))))
19126 (org-with-limited-levels
19127 (setq beg (if (org-at-heading-p) (line-beginning-position)
19128 (outline-previous-heading)
19129 (point)))
19130 (setq end (progn (outline-next-heading) (point)))
19131 (if (org-remove-latex-fragment-image-overlays beg end)
19132 (progn
19133 (message "LaTeX fragment images removed from section")
19134 (throw 'exit nil))
19135 (setq msg "Creating images for section...")))))
19136 (let ((file (buffer-file-name (buffer-base-buffer))))
19137 (org-format-latex
19138 (concat org-preview-latex-image-directory "org-ltximg")
19139 beg end
19140 ;; Emacs cannot overlay images from remote hosts. Create
19141 ;; it in `temporary-file-directory' instead.
19142 (if (or (not file) (file-remote-p file))
19143 temporary-file-directory
19144 default-directory)
19145 'overlays msg 'forbuffer org-preview-latex-default-process))
19146 (message (concat msg "done")))))))
19148 (defun org-format-latex
19149 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19150 "Replace LaTeX fragments with links to an image.
19152 The function takes care of creating the replacement image.
19154 Only consider fragments between BEG and END when those are
19155 provided.
19157 When optional argument OVERLAYS is non-nil, display the image on
19158 top of the fragment instead of replacing it.
19160 PROCESSING-TYPE is the conversion method to use, as a symbol.
19162 Some of the options can be changed using the variable
19163 `org-format-latex-options', which see."
19164 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19165 (unless (eq processing-type 'verbatim)
19166 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19167 (cnt 0)
19168 checkdir-flag)
19169 (goto-char (or beg (point-min)))
19170 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19171 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19172 (overlay-recenter (or end (point-max))))
19173 (while (re-search-forward math-regexp end t)
19174 (unless (and overlays
19175 (eq (get-char-property (point) 'org-overlay-type)
19176 'org-latex-overlay))
19177 (let* ((context (org-element-context))
19178 (type (org-element-type context)))
19179 (when (memq type '(latex-environment latex-fragment))
19180 (let ((block-type (eq type 'latex-environment))
19181 (value (org-element-property :value context))
19182 (beg (org-element-property :begin context))
19183 (end (save-excursion
19184 (goto-char (org-element-property :end context))
19185 (skip-chars-backward " \r\t\n")
19186 (point))))
19187 (cond
19188 ((eq processing-type 'mathjax)
19189 ;; Prepare for MathJax processing.
19190 (if (not (string-match "\\`\\$\\$?" value))
19191 (goto-char end)
19192 (delete-region beg end)
19193 (if (string= (match-string 0 value) "$$")
19194 (insert "\\[" (substring value 2 -2) "\\]")
19195 (insert "\\(" (substring value 1 -1) "\\)"))))
19196 ((assq processing-type org-preview-latex-process-alist)
19197 ;; Process to an image.
19198 (cl-incf cnt)
19199 (goto-char beg)
19200 (let* ((processing-info
19201 (cdr (assq processing-type org-preview-latex-process-alist)))
19202 (face (face-at-point))
19203 ;; Get the colors from the face at point.
19205 (let ((color (plist-get org-format-latex-options
19206 :foreground)))
19207 (if (and forbuffer (eq color 'auto))
19208 (face-attribute face :foreground nil 'default)
19209 color)))
19211 (let ((color (plist-get org-format-latex-options
19212 :background)))
19213 (if (and forbuffer (eq color 'auto))
19214 (face-attribute face :background nil 'default)
19215 color)))
19216 (hash (sha1 (prin1-to-string
19217 (list org-format-latex-header
19218 org-latex-default-packages-alist
19219 org-latex-packages-alist
19220 org-format-latex-options
19221 forbuffer value fg bg))))
19222 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19223 (absprefix (expand-file-name prefix dir))
19224 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19225 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19226 (sep (and block-type "\n\n"))
19227 (link (concat sep "[[file:" linkfile "]]" sep))
19228 (options
19229 (org-combine-plists
19230 org-format-latex-options
19231 `(:foreground ,fg :background ,bg))))
19232 (when msg (message msg cnt))
19233 (unless checkdir-flag ; Ensure the directory exists.
19234 (setq checkdir-flag t)
19235 (let ((todir (file-name-directory absprefix)))
19236 (unless (file-directory-p todir)
19237 (make-directory todir t))))
19238 (unless (file-exists-p movefile)
19239 (org-create-formula-image
19240 value movefile options forbuffer processing-type))
19241 (if overlays
19242 (progn
19243 (dolist (o (overlays-in beg end))
19244 (when (eq (overlay-get o 'org-overlay-type)
19245 'org-latex-overlay)
19246 (delete-overlay o)))
19247 (org--format-latex-make-overlay beg end movefile imagetype)
19248 (goto-char end))
19249 (delete-region beg end)
19250 (insert
19251 (org-add-props link
19252 (list 'org-latex-src
19253 (replace-regexp-in-string "\"" "" value)
19254 'org-latex-src-embed-type
19255 (if block-type 'paragraph 'character)))))))
19256 ((eq processing-type 'mathml)
19257 ;; Process to MathML.
19258 (unless (org-format-latex-mathml-available-p)
19259 (user-error "LaTeX to MathML converter not configured"))
19260 (cl-incf cnt)
19261 (when msg (message msg cnt))
19262 (goto-char beg)
19263 (delete-region beg end)
19264 (insert (org-format-latex-as-mathml
19265 value block-type prefix dir)))
19267 (error "Unknown conversion process %s for LaTeX fragments"
19268 processing-type)))))))))))
19270 (defun org-create-math-formula (latex-frag &optional mathml-file)
19271 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19272 Use `org-latex-to-mathml-convert-command'. If the conversion is
19273 sucessful, return the portion between \"<math...> </math>\"
19274 elements otherwise return nil. When MATHML-FILE is specified,
19275 write the results in to that file. When invoked as an
19276 interactive command, prompt for LATEX-FRAG, with initial value
19277 set to the current active region and echo the results for user
19278 inspection."
19279 (interactive (list (let ((frag (when (org-region-active-p)
19280 (buffer-substring-no-properties
19281 (region-beginning) (region-end)))))
19282 (read-string "LaTeX Fragment: " frag nil frag))))
19283 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19284 (let* ((tmp-in-file
19285 (let ((file (file-relative-name
19286 (make-temp-name (expand-file-name "ltxmathml-in")))))
19287 (write-region latex-frag nil file)
19288 file))
19289 (tmp-out-file (file-relative-name
19290 (make-temp-name (expand-file-name "ltxmathml-out"))))
19291 (cmd (format-spec
19292 org-latex-to-mathml-convert-command
19293 `((?j . ,(and org-latex-to-mathml-jar-file
19294 (shell-quote-argument
19295 (expand-file-name
19296 org-latex-to-mathml-jar-file))))
19297 (?I . ,(shell-quote-argument tmp-in-file))
19298 (?i . ,latex-frag)
19299 (?o . ,(shell-quote-argument tmp-out-file)))))
19300 mathml shell-command-output)
19301 (when (called-interactively-p 'any)
19302 (unless (org-format-latex-mathml-available-p)
19303 (user-error "LaTeX to MathML converter not configured")))
19304 (message "Running %s" cmd)
19305 (setq shell-command-output (shell-command-to-string cmd))
19306 (setq mathml
19307 (when (file-readable-p tmp-out-file)
19308 (with-current-buffer (find-file-noselect tmp-out-file t)
19309 (goto-char (point-min))
19310 (when (re-search-forward
19311 (concat
19312 (regexp-quote
19313 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19314 "[^>]*?>"
19315 "\\(.\\|\n\\)*"
19316 "</math>")
19317 nil t)
19318 (prog1 (match-string 0) (kill-buffer))))))
19319 (cond
19320 (mathml
19321 (setq mathml
19322 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19323 (when mathml-file
19324 (write-region mathml nil mathml-file))
19325 (when (called-interactively-p 'any)
19326 (message mathml)))
19327 ((message "LaTeX to MathML conversion failed")
19328 (message shell-command-output)))
19329 (delete-file tmp-in-file)
19330 (when (file-exists-p tmp-out-file)
19331 (delete-file tmp-out-file))
19332 mathml))
19334 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19335 prefix &optional dir)
19336 "Use `org-create-math-formula' but check local cache first."
19337 (let* ((absprefix (expand-file-name prefix dir))
19338 (print-length nil) (print-level nil)
19339 (formula-id (concat
19340 "formula-"
19341 (sha1
19342 (prin1-to-string
19343 (list latex-frag
19344 org-latex-to-mathml-convert-command)))))
19345 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19346 (formula-cache-dir (file-name-directory formula-cache)))
19348 (unless (file-directory-p formula-cache-dir)
19349 (make-directory formula-cache-dir t))
19351 (unless (file-exists-p formula-cache)
19352 (org-create-math-formula latex-frag formula-cache))
19354 (if (file-exists-p formula-cache)
19355 ;; Successful conversion. Return the link to MathML file.
19356 (org-add-props
19357 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19358 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19359 'org-latex-src-embed-type (if latex-frag-type
19360 'paragraph 'character)))
19361 ;; Failed conversion. Return the LaTeX fragment verbatim
19362 latex-frag)))
19364 (declare-function org-export-get-backend "ox" (name))
19365 (declare-function org-export--get-global-options "ox" (&optional backend))
19366 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19367 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19368 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19369 (defun org-create-formula--latex-header ()
19370 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19371 (let ((info (org-combine-plists (org-export--get-global-options
19372 (org-export-get-backend 'latex))
19373 (org-export--get-inbuffer-options
19374 (org-export-get-backend 'latex)))))
19375 (org-latex-guess-babel-language
19376 (org-latex-guess-inputenc
19377 (org-splice-latex-header
19378 org-format-latex-header
19379 org-latex-default-packages-alist
19380 org-latex-packages-alist t
19381 (plist-get info :latex-header)))
19382 info)))
19384 (defun org--get-display-dpi ()
19385 "Get the DPI of the display.
19387 Assumes that the display has the same pixel width in the
19388 horizontal and vertical directions."
19389 (if (display-graphic-p)
19390 (round (/ (display-pixel-height)
19391 (/ (display-mm-height) 25.4)))
19392 (error "Attempt to calculate the dpi of a non-graphic display")))
19394 (defun org-create-formula-image
19395 (string tofile options buffer &optional processing-type)
19396 "Create an image from LaTeX source using external processes.
19398 The LaTeX STRING is saved to a temporary LaTeX file, then
19399 converted to an image file by process PROCESSING-TYPE defined in
19400 `org-preview-latex-process-alist'. A nil value defaults to
19401 `org-preview-latex-default-process'.
19403 The generated image file is eventually moved to TOFILE.
19405 The OPTIONS argument controls the size, foreground color and
19406 background color of the generated image.
19408 When BUFFER non-nil, this function is used for LaTeX previewing.
19409 Otherwise, it is used to deal with LaTeX snippets showed in
19410 a HTML file."
19411 (let* ((processing-type (or processing-type
19412 org-preview-latex-default-process))
19413 (processing-info
19414 (cdr (assq processing-type org-preview-latex-process-alist)))
19415 (programs (plist-get processing-info :programs))
19416 (error-message (or (plist-get processing-info :message) ""))
19417 (use-xcolor (plist-get processing-info :use-xcolor))
19418 (image-input-type (plist-get processing-info :image-input-type))
19419 (image-output-type (plist-get processing-info :image-output-type))
19420 (post-clean (or (plist-get processing-info :post-clean)
19421 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19422 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19423 (latex-header (or (plist-get processing-info :latex-header)
19424 (org-create-formula--latex-header)))
19425 (latex-compiler (plist-get processing-info :latex-compiler))
19426 (image-converter (plist-get processing-info :image-converter))
19427 (tmpdir temporary-file-directory)
19428 (texfilebase (make-temp-name
19429 (expand-file-name "orgtex" tmpdir)))
19430 (texfile (concat texfilebase ".tex"))
19431 (font-height (face-attribute 'default :height nil))
19432 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19433 '(1.0 . 1.0)))
19434 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19435 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19436 (dpi (* scale (floor (if buffer font-height 140.0))))
19437 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19438 "Black"))
19439 (bg (or (plist-get options (if buffer :background :html-background))
19440 "Transparent"))
19441 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19442 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19443 (dolist (program programs)
19444 (org-check-external-command program error-message))
19445 (if use-xcolor
19446 (progn (if (eq fg 'default)
19447 (setq fg (org-latex-color :foreground))
19448 (setq fg (org-latex-color-format fg)))
19449 (if (eq bg 'default)
19450 (setq bg (org-latex-color :background))
19451 (setq bg (org-latex-color-format
19452 (if (string= bg "Transparent") "white" bg))))
19453 (with-temp-file texfile
19454 (insert latex-header)
19455 (insert "\n\\begin{document}\n"
19456 "\\definecolor{fg}{rgb}{" fg "}\n"
19457 "\\definecolor{bg}{rgb}{" bg "}\n"
19458 "\n\\pagecolor{bg}\n"
19459 "\n{\\color{fg}\n"
19460 string
19461 "\n}\n"
19462 "\n\\end{document}\n")))
19463 (if (eq fg 'default)
19464 (setq fg (org-dvipng-color :foreground))
19465 (unless (string= fg "Transparent")
19466 (setq fg (org-dvipng-color-format fg))))
19467 (if (eq bg 'default)
19468 (setq bg (org-dvipng-color :background))
19469 (unless (string= bg "Transparent")
19470 (setq bg (org-dvipng-color-format bg))))
19471 (with-temp-file texfile
19472 (insert latex-header)
19473 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19475 (let* ((err-msg (format "Please adjust '%s' part of \
19476 `org-preview-latex-process-alist'."
19477 processing-type))
19478 (image-input-file
19479 (org-compile-file
19480 texfile latex-compiler image-input-type err-msg log-buf))
19481 (image-output-file
19482 (org-compile-file
19483 image-input-file image-converter image-output-type err-msg log-buf
19484 `((?F . ,(shell-quote-argument fg))
19485 (?B . ,(shell-quote-argument bg))
19486 (?D . ,(shell-quote-argument (format "%s" dpi)))
19487 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19488 (copy-file image-output-file tofile 'replace)
19489 (dolist (e post-clean)
19490 (when (file-exists-p (concat texfilebase e))
19491 (delete-file (concat texfilebase e))))
19492 image-output-file)))
19494 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19495 "Fill a LaTeX header template TPL.
19496 In the template, the following place holders will be recognized:
19498 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19499 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19500 [PACKAGES] \\usepackage statements for PKG
19501 [NO-PACKAGES] do not include PKG
19502 [EXTRA] the string EXTRA
19503 [NO-EXTRA] do not include EXTRA
19505 For backward compatibility, if both the positive and the negative place
19506 holder is missing, the positive one (without the \"NO-\") will be
19507 assumed to be present at the end of the template.
19508 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19509 EXTRA is a string.
19510 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19511 (let (rpl (end ""))
19512 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19513 (setq rpl (if (or (match-end 1) (not def-pkg))
19514 "" (org-latex-packages-to-string def-pkg snippets-p t))
19515 tpl (replace-match rpl t t tpl))
19516 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19518 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19519 (setq rpl (if (or (match-end 1) (not pkg))
19520 "" (org-latex-packages-to-string pkg snippets-p t))
19521 tpl (replace-match rpl t t tpl))
19522 (when pkg (setq end
19523 (concat end "\n"
19524 (org-latex-packages-to-string pkg snippets-p)))))
19526 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19527 (setq rpl (if (or (match-end 1) (not extra))
19528 "" (concat extra "\n"))
19529 tpl (replace-match rpl t t tpl))
19530 (when (and extra (string-match "\\S-" extra))
19531 (setq end (concat end "\n" extra))))
19533 (if (string-match "\\S-" end)
19534 (concat tpl "\n" end)
19535 tpl)))
19537 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19538 "Turn an alist of packages into a string with the \\usepackage macros."
19539 (setq pkg (mapconcat (lambda(p)
19540 (cond
19541 ((stringp p) p)
19542 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19543 (format "%% Package %s omitted" (cadr p)))
19544 ((equal "" (car p))
19545 (format "\\usepackage{%s}" (cadr p)))
19547 (format "\\usepackage[%s]{%s}"
19548 (car p) (cadr p)))))
19550 "\n"))
19551 (if newline (concat pkg "\n") pkg))
19553 (defun org-dvipng-color (attr)
19554 "Return a RGB color specification for dvipng."
19555 (org-dvipng-color-format (face-attribute 'default attr nil)))
19557 (defun org-dvipng-color-format (color-name)
19558 "Convert COLOR-NAME to a RGB color value for dvipng."
19559 (apply #'format "rgb %s %s %s"
19560 (mapcar 'org-normalize-color
19561 (color-values color-name))))
19563 (defun org-latex-color (attr)
19564 "Return a RGB color for the LaTeX color package."
19565 (org-latex-color-format (face-attribute 'default attr nil)))
19567 (defun org-latex-color-format (color-name)
19568 "Convert COLOR-NAME to a RGB color value."
19569 (apply #'format "%s,%s,%s"
19570 (mapcar 'org-normalize-color
19571 (color-values color-name))))
19573 (defun org-normalize-color (value)
19574 "Return string to be used as color value for an RGB component."
19575 (format "%g" (/ value 65535.0)))
19579 ;; Image display
19581 (defvar-local org-inline-image-overlays nil)
19583 (defun org-toggle-inline-images (&optional include-linked)
19584 "Toggle the display of inline images.
19585 INCLUDE-LINKED is passed to `org-display-inline-images'."
19586 (interactive "P")
19587 (if org-inline-image-overlays
19588 (progn
19589 (org-remove-inline-images)
19590 (when (called-interactively-p 'interactive)
19591 (message "Inline image display turned off")))
19592 (org-display-inline-images include-linked)
19593 (when (called-interactively-p 'interactive)
19594 (message (if org-inline-image-overlays
19595 (format "%d images displayed inline"
19596 (length org-inline-image-overlays))
19597 "No images to display inline")))))
19599 (defun org-redisplay-inline-images ()
19600 "Refresh the display of inline images."
19601 (interactive)
19602 (if (not org-inline-image-overlays)
19603 (org-toggle-inline-images)
19604 (org-toggle-inline-images)
19605 (org-toggle-inline-images)))
19607 (defun org-display-inline-images (&optional include-linked refresh beg end)
19608 "Display inline images.
19610 An inline image is a link which follows either of these
19611 conventions:
19613 1. Its path is a file with an extension matching return value
19614 from `image-file-name-regexp' and it has no contents.
19616 2. Its description consists in a single link of the previous
19617 type.
19619 When optional argument INCLUDE-LINKED is non-nil, also links with
19620 a text description part will be inlined. This can be nice for
19621 a quick look at those images, but it does not reflect what
19622 exported files will look like.
19624 When optional argument REFRESH is non-nil, refresh existing
19625 images between BEG and END. This will create new image displays
19626 only if necessary. BEG and END default to the buffer
19627 boundaries."
19628 (interactive "P")
19629 (when (display-graphic-p)
19630 (unless refresh
19631 (org-remove-inline-images)
19632 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19633 (org-with-wide-buffer
19634 (goto-char (or beg (point-min)))
19635 (let ((case-fold-search t)
19636 (file-extension-re (image-file-name-regexp)))
19637 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19638 (let ((link (save-match-data (org-element-context))))
19639 ;; Check if we're at an inline image.
19640 (when (and (equal (org-element-property :type link) "file")
19641 (or include-linked
19642 (not (org-element-property :contents-begin link)))
19643 (let ((parent (org-element-property :parent link)))
19644 (or (not (eq (org-element-type parent) 'link))
19645 (not (cdr (org-element-contents parent)))))
19646 (string-match-p file-extension-re
19647 (org-element-property :path link)))
19648 (let ((file (expand-file-name
19649 (org-link-unescape
19650 (org-element-property :path link)))))
19651 (when (file-exists-p file)
19652 (let ((width
19653 ;; Apply `org-image-actual-width' specifications.
19654 (cond
19655 ((not (image-type-available-p 'imagemagick)) nil)
19656 ((eq org-image-actual-width t) nil)
19657 ((listp org-image-actual-width)
19659 ;; First try to find a width among
19660 ;; attributes associated to the paragraph
19661 ;; containing link.
19662 (let ((paragraph
19663 (let ((e link))
19664 (while (and (setq e (org-element-property
19665 :parent e))
19666 (not (eq (org-element-type e)
19667 'paragraph))))
19668 e)))
19669 (when paragraph
19670 (save-excursion
19671 (goto-char (org-element-property :begin paragraph))
19672 (when
19673 (re-search-forward
19674 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19675 (org-element-property
19676 :post-affiliated paragraph)
19678 (string-to-number (match-string 1))))))
19679 ;; Otherwise, fall-back to provided number.
19680 (car org-image-actual-width)))
19681 ((numberp org-image-actual-width)
19682 org-image-actual-width)))
19683 (old (get-char-property-and-overlay
19684 (org-element-property :begin link)
19685 'org-image-overlay)))
19686 (if (and (car-safe old) refresh)
19687 (image-refresh (overlay-get (cdr old) 'display))
19688 (let ((image (create-image file
19689 (and width 'imagemagick)
19691 :width width)))
19692 (when image
19693 (let* ((link
19694 ;; If inline image is the description
19695 ;; of another link, be sure to
19696 ;; consider the latter as the one to
19697 ;; apply the overlay on.
19698 (let ((parent
19699 (org-element-property :parent link)))
19700 (if (eq (org-element-type parent) 'link)
19701 parent
19702 link)))
19703 (ov (make-overlay
19704 (org-element-property :begin link)
19705 (progn
19706 (goto-char
19707 (org-element-property :end link))
19708 (skip-chars-backward " \t")
19709 (point)))))
19710 (overlay-put ov 'display image)
19711 (overlay-put ov 'face 'default)
19712 (overlay-put ov 'org-image-overlay t)
19713 (overlay-put
19714 ov 'modification-hooks
19715 (list 'org-display-inline-remove-overlay))
19716 (push ov org-inline-image-overlays)))))))))))))))
19718 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19719 "Remove inline-display overlay if a corresponding region is modified."
19720 (let ((inhibit-modification-hooks t))
19721 (when (and ov after)
19722 (delete ov org-inline-image-overlays)
19723 (delete-overlay ov))))
19725 (defun org-remove-inline-images ()
19726 "Remove inline display of images."
19727 (interactive)
19728 (mapc #'delete-overlay org-inline-image-overlays)
19729 (setq org-inline-image-overlays nil))
19731 ;;;; Key bindings
19733 ;; Outline functions from `outline-mode-prefix-map'
19734 ;; that can be remapped in Org:
19735 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19736 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19737 (define-key org-mode-map [remap outline-forward-same-level]
19738 'org-forward-heading-same-level)
19739 (define-key org-mode-map [remap outline-backward-same-level]
19740 'org-backward-heading-same-level)
19741 (define-key org-mode-map [remap outline-show-branches]
19742 'org-kill-note-or-show-branches)
19743 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19744 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19745 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19746 (define-key org-mode-map [remap outline-next-visible-heading]
19747 'org-next-visible-heading)
19748 (define-key org-mode-map [remap outline-previous-visible-heading]
19749 'org-previous-visible-heading)
19750 (define-key org-mode-map [remap show-children] 'org-show-children)
19752 ;; Outline functions from `outline-mode-prefix-map' that can not
19753 ;; be remapped in Org:
19755 ;; - the column "key binding" shows whether the Outline function is still
19756 ;; available in Org mode on the same key that it has been bound to in
19757 ;; Outline mode:
19758 ;; - "overridden": key used for a different functionality in Org mode
19759 ;; - else: key still bound to the same Outline function in Org mode
19761 ;; | Outline function | key binding | Org replacement |
19762 ;; |------------------------------------+-------------+--------------------------|
19763 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19764 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19765 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19766 ;; | `show-entry' | overridden | no replacement |
19767 ;; | `show-branches' | `C-c C-k' | still same function |
19768 ;; | `show-subtree' | overridden | visibility cycling |
19769 ;; | `show-all' | overridden | no replacement |
19770 ;; | `hide-subtree' | overridden | visibility cycling |
19771 ;; | `hide-body' | overridden | no replacement |
19772 ;; | `hide-entry' | overridden | visibility cycling |
19773 ;; | `hide-leaves' | overridden | no replacement |
19774 ;; | `hide-sublevels' | overridden | no replacement |
19775 ;; | `hide-other' | overridden | no replacement |
19777 ;; Make `C-c C-x' a prefix key
19778 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19780 ;; TAB key with modifiers
19781 (org-defkey org-mode-map "\C-i" 'org-cycle)
19782 (org-defkey org-mode-map [(tab)] 'org-cycle)
19783 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19784 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19785 ;; The following line is necessary under Suse GNU/Linux
19786 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19787 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19788 (define-key org-mode-map [backtab] 'org-shifttab)
19790 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19791 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19792 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19794 ;; Cursor keys with modifiers
19795 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19796 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19797 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19798 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19800 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19801 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19802 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19803 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19804 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19805 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19807 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19808 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19809 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19810 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19812 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19813 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19814 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19815 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19817 ;; Babel keys
19818 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19819 (dolist (pair org-babel-key-bindings)
19820 (define-key org-babel-map (car pair) (cdr pair)))
19822 ;;; Extra keys for tty access.
19823 ;; We only set them when really needed because otherwise the
19824 ;; menus don't show the simple keys
19826 (when (or org-use-extra-keys (not window-system))
19827 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19828 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19829 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19830 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19831 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19832 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19833 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19834 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19835 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19836 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19837 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19838 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19839 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19840 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19841 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19842 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19843 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19844 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19845 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19846 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19847 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19848 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19849 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19850 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19851 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19852 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19853 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19854 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19856 ;; All the other keys
19858 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19859 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19860 (if (boundp 'narrow-map)
19861 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19862 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19863 (if (boundp 'narrow-map)
19864 (org-defkey narrow-map "b" 'org-narrow-to-block)
19865 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19866 (if (boundp 'narrow-map)
19867 (org-defkey narrow-map "e" 'org-narrow-to-element)
19868 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19869 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19870 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19871 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19872 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19873 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19874 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19875 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19876 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19877 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19878 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19879 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19880 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19881 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19882 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19883 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19884 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19885 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19886 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19887 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19888 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19889 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19890 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19891 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19892 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19893 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19894 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19895 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19896 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19897 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19898 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19899 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19900 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19901 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19902 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19903 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19904 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19905 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19906 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19907 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19908 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19909 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19910 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19911 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19912 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19913 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19914 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19915 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19916 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19917 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19918 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19919 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19920 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19921 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19922 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19923 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19924 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19925 (org-defkey org-mode-map "\C-c^" 'org-sort)
19926 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19927 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19928 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19929 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19930 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19931 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19932 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19933 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19934 (org-defkey org-mode-map "\C-m" 'org-return)
19935 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19936 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19937 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19938 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19939 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19940 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19941 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19942 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19943 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19944 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19945 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19946 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19947 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19948 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19949 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19950 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19951 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19952 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19953 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19954 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19955 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19956 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19957 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19958 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19959 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19961 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19962 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19963 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19965 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19966 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19967 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19968 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19969 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19970 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19971 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19972 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19973 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19974 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19975 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19976 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19977 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19978 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19979 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19980 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19981 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19982 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19983 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19984 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19985 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19986 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19988 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19989 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19990 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19991 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19992 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19994 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19996 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19998 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19999 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20001 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20004 (defconst org-speed-commands-default
20006 ("Outline Navigation")
20007 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20008 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20009 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20010 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20011 ("F" . org-next-block)
20012 ("B" . org-previous-block)
20013 ("u" . (org-speed-move-safe 'outline-up-heading))
20014 ("j" . org-goto)
20015 ("g" . (org-refile t))
20016 ("Outline Visibility")
20017 ("c" . org-cycle)
20018 ("C" . org-shifttab)
20019 (" " . org-display-outline-path)
20020 ("s" . org-narrow-to-subtree)
20021 ("=" . org-columns)
20022 ("Outline Structure Editing")
20023 ("U" . org-metaup)
20024 ("D" . org-metadown)
20025 ("r" . org-metaright)
20026 ("l" . org-metaleft)
20027 ("R" . org-shiftmetaright)
20028 ("L" . org-shiftmetaleft)
20029 ("i" . (progn (forward-char 1) (call-interactively
20030 'org-insert-heading-respect-content)))
20031 ("^" . org-sort)
20032 ("w" . org-refile)
20033 ("a" . org-archive-subtree-default-with-confirmation)
20034 ("@" . org-mark-subtree)
20035 ("#" . org-toggle-comment)
20036 ("Clock Commands")
20037 ("I" . org-clock-in)
20038 ("O" . org-clock-out)
20039 ("Meta Data Editing")
20040 ("t" . org-todo)
20041 ("," . (org-priority))
20042 ("0" . (org-priority ?\ ))
20043 ("1" . (org-priority ?A))
20044 ("2" . (org-priority ?B))
20045 ("3" . (org-priority ?C))
20046 (":" . org-set-tags-command)
20047 ("e" . org-set-effort)
20048 ("E" . org-inc-effort)
20049 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20050 (org-entry-put (point) "APPT_WARNTIME" m)))
20051 ("Agenda Views etc")
20052 ("v" . org-agenda)
20053 ("/" . org-sparse-tree)
20054 ("Misc")
20055 ("o" . org-open-at-point)
20056 ("?" . org-speed-command-help)
20057 ("<" . (org-agenda-set-restriction-lock 'subtree))
20058 (">" . (org-agenda-remove-restriction-lock))
20060 "The default speed commands.")
20062 (defun org-print-speed-command (e)
20063 (if (> (length (car e)) 1)
20064 (progn
20065 (princ "\n")
20066 (princ (car e))
20067 (princ "\n")
20068 (princ (make-string (length (car e)) ?-))
20069 (princ "\n"))
20070 (princ (car e))
20071 (princ " ")
20072 (if (symbolp (cdr e))
20073 (princ (symbol-name (cdr e)))
20074 (prin1 (cdr e)))
20075 (princ "\n")))
20077 (defun org-speed-command-help ()
20078 "Show the available speed commands."
20079 (interactive)
20080 (if (not org-use-speed-commands)
20081 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20082 (with-output-to-temp-buffer "*Help*"
20083 (princ "User-defined Speed commands\n===========================\n")
20084 (mapc #'org-print-speed-command org-speed-commands-user)
20085 (princ "\n")
20086 (princ "Built-in Speed commands\n=======================\n")
20087 (mapc #'org-print-speed-command org-speed-commands-default))
20088 (with-current-buffer "*Help*"
20089 (setq truncate-lines t))))
20091 (defun org-speed-move-safe (cmd)
20092 "Execute CMD, but make sure that the cursor always ends up in a headline.
20093 If not, return to the original position and throw an error."
20094 (interactive)
20095 (let ((pos (point)))
20096 (call-interactively cmd)
20097 (unless (and (bolp) (org-at-heading-p))
20098 (goto-char pos)
20099 (error "Boundary reached while executing %s" cmd))))
20101 (defvar org-self-insert-command-undo-counter 0)
20103 (defvar org-table-auto-blank-field) ; defined in org-table.el
20104 (defvar org-speed-command nil)
20106 (defun org-speed-command-activate (keys)
20107 "Hook for activating single-letter speed commands.
20108 `org-speed-commands-default' specifies a minimal command set.
20109 Use `org-speed-commands-user' for further customization."
20110 (when (or (and (bolp) (looking-at org-outline-regexp))
20111 (and (functionp org-use-speed-commands)
20112 (funcall org-use-speed-commands)))
20113 (cdr (assoc keys (append org-speed-commands-user
20114 org-speed-commands-default)))))
20116 (defun org-babel-speed-command-activate (keys)
20117 "Hook for activating single-letter code block commands."
20118 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20119 (cdr (assoc keys org-babel-key-bindings))))
20121 (defcustom org-speed-command-hook
20122 '(org-speed-command-default-hook org-babel-speed-command-hook)
20123 "Hook for activating speed commands at strategic locations.
20124 Hook functions are called in sequence until a valid handler is
20125 found.
20127 Each hook takes a single argument, a user-pressed command key
20128 which is also a `self-insert-command' from the global map.
20130 Within the hook, examine the cursor position and the command key
20131 and return nil or a valid handler as appropriate. Handler could
20132 be one of an interactive command, a function, or a form.
20134 Set `org-use-speed-commands' to non-nil value to enable this
20135 hook. The default setting is `org-speed-command-activate'."
20136 :group 'org-structure
20137 :version "24.1"
20138 :type 'hook)
20140 (defun org-self-insert-command (N)
20141 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20142 If the cursor is in a table looking at whitespace, the whitespace is
20143 overwritten, and the table is not marked as requiring realignment."
20144 (interactive "p")
20145 (org-check-before-invisible-edit 'insert)
20146 (cond
20147 ((and org-use-speed-commands
20148 (let ((kv (this-command-keys-vector)))
20149 (setq org-speed-command
20150 (run-hook-with-args-until-success
20151 'org-speed-command-hook
20152 (make-string 1 (aref kv (1- (length kv))))))))
20153 (cond
20154 ((commandp org-speed-command)
20155 (setq this-command org-speed-command)
20156 (call-interactively org-speed-command))
20157 ((functionp org-speed-command)
20158 (funcall org-speed-command))
20159 ((and org-speed-command (listp org-speed-command))
20160 (eval org-speed-command))
20161 (t (let (org-use-speed-commands)
20162 (call-interactively 'org-self-insert-command)))))
20163 ((and
20164 (org-at-table-p)
20165 (progn
20166 ;; Check if we blank the field, and if that triggers align.
20167 (and (featurep 'org-table) org-table-auto-blank-field
20168 (memq last-command
20169 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20170 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20171 ;; Got extra space, this field does not determine
20172 ;; column width.
20173 (let (org-table-may-need-update) (org-table-blank-field))
20174 ;; No extra space, this field may determine column
20175 ;; width.
20176 (org-table-blank-field)))
20178 (eq N 1)
20179 (looking-at "[^|\n]* \\( \\)|"))
20180 ;; There is room for insertion without re-aligning the table.
20181 (delete-region (match-beginning 1) (match-end 1))
20182 (self-insert-command N))
20184 (setq org-table-may-need-update t)
20185 (self-insert-command N)
20186 (org-fix-tags-on-the-fly)
20187 (when org-self-insert-cluster-for-undo
20188 (if (not (eq last-command 'org-self-insert-command))
20189 (setq org-self-insert-command-undo-counter 1)
20190 (if (>= org-self-insert-command-undo-counter 20)
20191 (setq org-self-insert-command-undo-counter 1)
20192 (and (> org-self-insert-command-undo-counter 0)
20193 buffer-undo-list (listp buffer-undo-list)
20194 (not (cadr buffer-undo-list)) ; remove nil entry
20195 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20196 (setq org-self-insert-command-undo-counter
20197 (1+ org-self-insert-command-undo-counter))))))))
20199 (defun org-check-before-invisible-edit (kind)
20200 "Check is editing if kind KIND would be dangerous with invisible text around.
20201 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20202 ;; First, try to get out of here as quickly as possible, to reduce overhead
20203 (when (and org-catch-invisible-edits
20204 (or (not (boundp 'visible-mode)) (not visible-mode))
20205 (or (get-char-property (point) 'invisible)
20206 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20207 ;; OK, we need to take a closer look
20208 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20209 (invisible-before-point (unless (bobp) (get-char-property
20210 (1- (point)) 'invisible)))
20211 (border-and-ok-direction
20213 ;; Check if we are acting predictably before invisible text
20214 (and invisible-at-point (not invisible-before-point)
20215 (memq kind '(insert delete-backward)))
20216 ;; Check if we are acting predictably after invisible text
20217 ;; This works not well, and I have turned it off. It seems
20218 ;; better to always show and stop after invisible text.
20219 ;; (and (not invisible-at-point) invisible-before-point
20220 ;; (memq kind '(insert delete)))
20222 (when (or (memq invisible-at-point '(outline org-hide-block t))
20223 (memq invisible-before-point '(outline org-hide-block t)))
20224 (when (eq org-catch-invisible-edits 'error)
20225 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20226 (if (and org-custom-properties-overlays
20227 (y-or-n-p "Display invisible properties in this buffer? "))
20228 (org-toggle-custom-properties-visibility)
20229 ;; Make the area visible
20230 (save-excursion
20231 (when invisible-before-point
20232 (goto-char (previous-single-char-property-change
20233 (point) 'invisible)))
20234 (outline-show-subtree))
20235 (cond
20236 ((eq org-catch-invisible-edits 'show)
20237 ;; That's it, we do the edit after showing
20238 (message
20239 "Unfolding invisible region around point before editing")
20240 (sit-for 1))
20241 ((and (eq org-catch-invisible-edits 'smart)
20242 border-and-ok-direction)
20243 (message "Unfolding invisible region around point before editing"))
20245 ;; Don't do the edit, make the user repeat it in full visibility
20246 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20248 (defun org-fix-tags-on-the-fly ()
20249 (when (and (equal (char-after (point-at-bol)) ?*)
20250 (org-at-heading-p))
20251 (org-align-tags-here org-tags-column)))
20253 (defun org-delete-backward-char (N)
20254 "Like `delete-backward-char', insert whitespace at field end in tables.
20255 When deleting backwards, in tables this function will insert whitespace in
20256 front of the next \"|\" separator, to keep the table aligned. The table will
20257 still be marked for re-alignment if the field did fill the entire column,
20258 because, in this case the deletion might narrow the column."
20259 (interactive "p")
20260 (save-match-data
20261 (org-check-before-invisible-edit 'delete-backward)
20262 (if (and (org-at-table-p)
20263 (eq N 1)
20264 (string-match "|" (buffer-substring (point-at-bol) (point)))
20265 (looking-at ".*?|"))
20266 (let ((pos (point))
20267 (noalign (looking-at "[^|\n\r]* |"))
20268 (c org-table-may-need-update))
20269 (backward-delete-char N)
20270 (unless overwrite-mode
20271 (skip-chars-forward "^|")
20272 (insert " ")
20273 (goto-char (1- pos)))
20274 ;; noalign: if there were two spaces at the end, this field
20275 ;; does not determine the width of the column.
20276 (when noalign (setq org-table-may-need-update c)))
20277 (backward-delete-char N)
20278 (org-fix-tags-on-the-fly))))
20280 (defun org-delete-char (N)
20281 "Like `delete-char', but insert whitespace at field end in tables.
20282 When deleting characters, in tables this function will insert whitespace in
20283 front of the next \"|\" separator, to keep the table aligned. The table will
20284 still be marked for re-alignment if the field did fill the entire column,
20285 because, in this case the deletion might narrow the column."
20286 (interactive "p")
20287 (save-match-data
20288 (org-check-before-invisible-edit 'delete)
20289 (if (and (org-at-table-p)
20290 (not (bolp))
20291 (not (= (char-after) ?|))
20292 (eq N 1))
20293 (if (looking-at ".*?|")
20294 (let ((pos (point))
20295 (noalign (looking-at "[^|\n\r]* |"))
20296 (c org-table-may-need-update))
20297 (replace-match
20298 (concat (substring (match-string 0) 1 -1) " |") nil t)
20299 (goto-char pos)
20300 ;; noalign: if there were two spaces at the end, this field
20301 ;; does not determine the width of the column.
20302 (when noalign (setq org-table-may-need-update c)))
20303 (delete-char N))
20304 (delete-char N)
20305 (org-fix-tags-on-the-fly))))
20307 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20308 (put 'org-self-insert-command 'delete-selection
20309 (lambda ()
20310 (not (run-hook-with-args-until-success
20311 'self-insert-uses-region-functions))))
20312 (put 'orgtbl-self-insert-command 'delete-selection
20313 (lambda ()
20314 (not (run-hook-with-args-until-success
20315 'self-insert-uses-region-functions))))
20316 (put 'org-delete-char 'delete-selection 'supersede)
20317 (put 'org-delete-backward-char 'delete-selection 'supersede)
20318 (put 'org-yank 'delete-selection 'yank)
20320 ;; Make `flyspell-mode' delay after some commands
20321 (put 'org-self-insert-command 'flyspell-delayed t)
20322 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20323 (put 'org-delete-char 'flyspell-delayed t)
20324 (put 'org-delete-backward-char 'flyspell-delayed t)
20326 ;; Make pabbrev-mode expand after Org mode commands
20327 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20328 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20330 (defun org-remap (map &rest commands)
20331 "In MAP, remap the functions given in COMMANDS.
20332 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20333 (let (new old)
20334 (while commands
20335 (setq old (pop commands) new (pop commands))
20336 (org-defkey map (vector 'remap old) new))))
20338 (defun org-transpose-words ()
20339 "Transpose words for Org.
20340 This uses the `org-mode-transpose-word-syntax-table' syntax
20341 table, which interprets characters in `org-emphasis-alist' as
20342 word constituents."
20343 (interactive)
20344 (with-syntax-table org-mode-transpose-word-syntax-table
20345 (call-interactively 'transpose-words)))
20346 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20348 (when (eq org-enable-table-editor 'optimized)
20349 ;; If the user wants maximum table support, we need to hijack
20350 ;; some standard editing functions
20351 (org-remap org-mode-map
20352 'self-insert-command 'org-self-insert-command
20353 'delete-char 'org-delete-char
20354 'delete-backward-char 'org-delete-backward-char)
20355 (org-defkey org-mode-map "|" 'org-force-self-insert))
20357 (defvar org-ctrl-c-ctrl-c-hook nil
20358 "Hook for functions attaching themselves to `C-c C-c'.
20360 This can be used to add additional functionality to the C-c C-c
20361 key which executes context-dependent commands. This hook is run
20362 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20363 run after the last test.
20365 Each function will be called with no arguments. The function
20366 must check if the context is appropriate for it to act. If yes,
20367 it should do its thing and then return a non-nil value. If the
20368 context is wrong, just do nothing and return nil.")
20370 (defvar org-ctrl-c-ctrl-c-final-hook nil
20371 "Hook for functions attaching themselves to `C-c C-c'.
20373 This can be used to add additional functionality to the C-c C-c
20374 key which executes context-dependent commands. This hook is run
20375 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20376 before the first test.
20378 Each function will be called with no arguments. The function
20379 must check if the context is appropriate for it to act. If yes,
20380 it should do its thing and then return a non-nil value. If the
20381 context is wrong, just do nothing and return nil.")
20383 (defvar org-tab-first-hook nil
20384 "Hook for functions to attach themselves to TAB.
20385 See `org-ctrl-c-ctrl-c-hook' for more information.
20386 This hook runs as the first action when TAB is pressed, even before
20387 `org-cycle' messes around with the `outline-regexp' to cater for
20388 inline tasks and plain list item folding.
20389 If any function in this hook returns t, any other actions that
20390 would have been caused by TAB (such as table field motion or visibility
20391 cycling) will not occur.")
20393 (defvar org-tab-after-check-for-table-hook nil
20394 "Hook for functions to attach themselves to TAB.
20395 See `org-ctrl-c-ctrl-c-hook' for more information.
20396 This hook runs after it has been established that the cursor is not in a
20397 table, but before checking if the cursor is in a headline or if global cycling
20398 should be done.
20399 If any function in this hook returns t, not other actions like visibility
20400 cycling will be done.")
20402 (defvar org-tab-after-check-for-cycling-hook nil
20403 "Hook for functions to attach themselves to TAB.
20404 See `org-ctrl-c-ctrl-c-hook' for more information.
20405 This hook runs after it has been established that not table field motion and
20406 not visibility should be done because of current context. This is probably
20407 the place where a package like yasnippets can hook in.")
20409 (defvar org-tab-before-tab-emulation-hook nil
20410 "Hook for functions to attach themselves to TAB.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.
20412 This hook runs after every other options for TAB have been exhausted, but
20413 before indentation and \t insertion takes place.")
20415 (defvar org-metaleft-hook nil
20416 "Hook for functions attaching themselves to `M-left'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-metaright-hook nil
20419 "Hook for functions attaching themselves to `M-right'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-metaup-hook nil
20422 "Hook for functions attaching themselves to `M-up'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-metadown-hook nil
20425 "Hook for functions attaching themselves to `M-down'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-shiftmetaleft-hook nil
20428 "Hook for functions attaching themselves to `M-S-left'.
20429 See `org-ctrl-c-ctrl-c-hook' for more information.")
20430 (defvar org-shiftmetaright-hook nil
20431 "Hook for functions attaching themselves to `M-S-right'.
20432 See `org-ctrl-c-ctrl-c-hook' for more information.")
20433 (defvar org-shiftmetaup-hook nil
20434 "Hook for functions attaching themselves to `M-S-up'.
20435 See `org-ctrl-c-ctrl-c-hook' for more information.")
20436 (defvar org-shiftmetadown-hook nil
20437 "Hook for functions attaching themselves to `M-S-down'.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.")
20439 (defvar org-metareturn-hook nil
20440 "Hook for functions attaching themselves to `M-RET'.
20441 See `org-ctrl-c-ctrl-c-hook' for more information.")
20442 (defvar org-shiftup-hook nil
20443 "Hook for functions attaching themselves to `S-up'.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-shiftup-final-hook nil
20446 "Hook for functions attaching themselves to `S-up'.
20447 This one runs after all other options except shift-select have been excluded.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-shiftdown-hook nil
20450 "Hook for functions attaching themselves to `S-down'.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-shiftdown-final-hook nil
20453 "Hook for functions attaching themselves to `S-down'.
20454 This one runs after all other options except shift-select have been excluded.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftleft-hook nil
20457 "Hook for functions attaching themselves to `S-left'.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftleft-final-hook nil
20460 "Hook for functions attaching themselves to `S-left'.
20461 This one runs after all other options except shift-select have been excluded.
20462 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defvar org-shiftright-hook nil
20464 "Hook for functions attaching themselves to `S-right'.
20465 See `org-ctrl-c-ctrl-c-hook' for more information.")
20466 (defvar org-shiftright-final-hook nil
20467 "Hook for functions attaching themselves to `S-right'.
20468 This one runs after all other options except shift-select have been excluded.
20469 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defun org-modifier-cursor-error ()
20472 "Throw an error, a modified cursor command was applied in wrong context."
20473 (user-error "This command is active in special context like tables, headlines or items"))
20475 (defun org-shiftselect-error ()
20476 "Throw an error because Shift-Cursor command was applied in wrong context."
20477 (if (and (boundp 'shift-select-mode) shift-select-mode)
20478 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20479 (user-error "This command works only in special context like headlines or timestamps")))
20481 (defun org-call-for-shift-select (cmd)
20482 (let ((this-command-keys-shift-translated t))
20483 (call-interactively cmd)))
20485 (defun org-shifttab (&optional arg)
20486 "Global visibility cycling or move to previous table field.
20487 Call `org-table-previous-field' within a table.
20488 When ARG is nil, cycle globally through visibility states.
20489 When ARG is a numeric prefix, show contents of this level."
20490 (interactive "P")
20491 (cond
20492 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20493 ((integerp arg)
20494 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20495 (message "Content view to level: %d" arg)
20496 (org-content (prefix-numeric-value arg2))
20497 (org-cycle-show-empty-lines t)
20498 (setq org-cycle-global-status 'overview)))
20499 (t (call-interactively 'org-global-cycle))))
20501 (defun org-shiftmetaleft ()
20502 "Promote subtree or delete table column.
20503 Calls `org-promote-subtree', `org-outdent-item-tree', or
20504 `org-table-delete-column', depending on context. See the
20505 individual commands for more information."
20506 (interactive)
20507 (cond
20508 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20509 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20510 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20511 ((if (not (org-region-active-p)) (org-at-item-p)
20512 (save-excursion (goto-char (region-beginning))
20513 (org-at-item-p)))
20514 (call-interactively 'org-outdent-item-tree))
20515 (t (org-modifier-cursor-error))))
20517 (defun org-shiftmetaright ()
20518 "Demote subtree or insert table column.
20519 Calls `org-demote-subtree', `org-indent-item-tree', or
20520 `org-table-insert-column', depending on context. See the
20521 individual commands for more information."
20522 (interactive)
20523 (cond
20524 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20525 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20526 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20527 ((if (not (org-region-active-p)) (org-at-item-p)
20528 (save-excursion (goto-char (region-beginning))
20529 (org-at-item-p)))
20530 (call-interactively 'org-indent-item-tree))
20531 (t (org-modifier-cursor-error))))
20533 (defun org-shiftmetaup (&optional _arg)
20534 "Drag the line at point up.
20535 In a table, kill the current row.
20536 On a clock timestamp, update the value of the timestamp like `S-<up>'
20537 but also adjust the previous clocked item in the clock history.
20538 Everywhere else, drag the line at point up."
20539 (interactive "P")
20540 (cond
20541 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20542 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20543 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20544 (call-interactively 'org-timestamp-up)))
20545 (t (call-interactively 'org-drag-line-backward))))
20547 (defun org-shiftmetadown (&optional _arg)
20548 "Drag the line at point down.
20549 In a table, insert an empty row at the current line.
20550 On a clock timestamp, update the value of the timestamp like `S-<down>'
20551 but also adjust the previous clocked item in the clock history.
20552 Everywhere else, drag the line at point down."
20553 (interactive "P")
20554 (cond
20555 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20556 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20557 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20558 (call-interactively 'org-timestamp-down)))
20559 (t (call-interactively 'org-drag-line-forward))))
20561 (defsubst org-hidden-tree-error ()
20562 (user-error
20563 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20565 (defun org-metaleft (&optional _arg)
20566 "Promote heading, list item at point or move table column left.
20568 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20569 depending on context. With no specific context, calls the Emacs
20570 default `backward-word'. See the individual commands for more
20571 information.
20573 This function runs the hook `org-metaleft-hook' as a first step,
20574 and returns at first non-nil value."
20575 (interactive "P")
20576 (cond
20577 ((run-hook-with-args-until-success 'org-metaleft-hook))
20578 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20579 ((org-with-limited-levels
20580 (or (org-at-heading-p)
20581 (and (org-region-active-p)
20582 (save-excursion
20583 (goto-char (region-beginning))
20584 (org-at-heading-p)))))
20585 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20586 (call-interactively 'org-do-promote))
20587 ;; At an inline task.
20588 ((org-at-heading-p)
20589 (call-interactively 'org-inlinetask-promote))
20590 ((or (org-at-item-p)
20591 (and (org-region-active-p)
20592 (save-excursion
20593 (goto-char (region-beginning))
20594 (org-at-item-p))))
20595 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20596 (call-interactively 'org-outdent-item))
20597 (t (call-interactively 'backward-word))))
20599 (defun org-metaright (&optional _arg)
20600 "Demote heading, list item at point or move table column right.
20602 In front of a drawer or a block keyword, indent it correctly.
20604 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20605 `org-indent-drawer' or `org-indent-block' depending on context.
20606 With no specific context, calls the Emacs default `forward-word'.
20607 See the individual commands for more information.
20609 This function runs the hook `org-metaright-hook' as a first step,
20610 and returns at first non-nil value."
20611 (interactive "P")
20612 (cond
20613 ((run-hook-with-args-until-success 'org-metaright-hook))
20614 ((org-at-table-p) (call-interactively 'org-table-move-column))
20615 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20616 ((org-at-block-p) (call-interactively 'org-indent-block))
20617 ((org-with-limited-levels
20618 (or (org-at-heading-p)
20619 (and (org-region-active-p)
20620 (save-excursion
20621 (goto-char (region-beginning))
20622 (org-at-heading-p)))))
20623 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20624 (call-interactively 'org-do-demote))
20625 ;; At an inline task.
20626 ((org-at-heading-p)
20627 (call-interactively 'org-inlinetask-demote))
20628 ((or (org-at-item-p)
20629 (and (org-region-active-p)
20630 (save-excursion
20631 (goto-char (region-beginning))
20632 (org-at-item-p))))
20633 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20634 (call-interactively 'org-indent-item))
20635 (t (call-interactively 'forward-word))))
20637 (defun org-check-for-hidden (what)
20638 "Check if there are hidden headlines/items in the current visual line.
20639 WHAT can be either `headlines' or `items'. If the current line is
20640 an outline or item heading and it has a folded subtree below it,
20641 this function returns t, nil otherwise."
20642 (let ((re (cond
20643 ((eq what 'headlines) org-outline-regexp-bol)
20644 ((eq what 'items) (org-item-beginning-re))
20645 (t (error "This should not happen"))))
20646 beg end)
20647 (save-excursion
20648 (catch 'exit
20649 (unless (org-region-active-p)
20650 (setq beg (point-at-bol))
20651 (beginning-of-line 2)
20652 (while (and (not (eobp)) ;; this is like `next-line'
20653 (get-char-property (1- (point)) 'invisible))
20654 (beginning-of-line 2))
20655 (setq end (point))
20656 (goto-char beg)
20657 (goto-char (point-at-eol))
20658 (setq end (max end (point)))
20659 (while (re-search-forward re end t)
20660 (when (get-char-property (match-beginning 0) 'invisible)
20661 (throw 'exit t))))
20662 nil))))
20664 (defun org-metaup (&optional _arg)
20665 "Move subtree up or move table row up.
20666 Calls `org-move-subtree-up' or `org-table-move-row' or
20667 `org-move-item-up', depending on context. See the individual commands
20668 for more information."
20669 (interactive "P")
20670 (cond
20671 ((run-hook-with-args-until-success 'org-metaup-hook))
20672 ((org-region-active-p)
20673 (let* ((a (min (region-beginning) (region-end)))
20674 (b (1- (max (region-beginning) (region-end))))
20675 (c (save-excursion (goto-char a)
20676 (move-beginning-of-line 0)))
20677 (d (save-excursion (goto-char a)
20678 (move-end-of-line 0) (point))))
20679 (transpose-regions a b c d)
20680 (goto-char c)))
20681 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20682 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20683 ((org-at-item-p) (call-interactively 'org-move-item-up))
20684 (t (org-drag-element-backward))))
20686 (defun org-metadown (&optional _arg)
20687 "Move subtree down or move table row down.
20688 Calls `org-move-subtree-down' or `org-table-move-row' or
20689 `org-move-item-down', depending on context. See the individual
20690 commands for more information."
20691 (interactive "P")
20692 (cond
20693 ((run-hook-with-args-until-success 'org-metadown-hook))
20694 ((org-region-active-p)
20695 (let* ((a (min (region-beginning) (region-end)))
20696 (b (max (region-beginning) (region-end)))
20697 (c (save-excursion (goto-char b)
20698 (move-beginning-of-line 1)))
20699 (d (save-excursion (goto-char b)
20700 (move-end-of-line 1) (1+ (point)))))
20701 (transpose-regions a b c d)
20702 (goto-char d)))
20703 ((org-at-table-p) (call-interactively 'org-table-move-row))
20704 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20705 ((org-at-item-p) (call-interactively 'org-move-item-down))
20706 (t (org-drag-element-forward))))
20708 (defun org-shiftup (&optional arg)
20709 "Increase item in timestamp or increase priority of current headline.
20710 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20711 depending on context. See the individual commands for more information."
20712 (interactive "P")
20713 (cond
20714 ((run-hook-with-args-until-success 'org-shiftup-hook))
20715 ((and org-support-shift-select (org-region-active-p))
20716 (org-call-for-shift-select 'previous-line))
20717 ((org-at-timestamp-p t)
20718 (call-interactively (if org-edit-timestamp-down-means-later
20719 'org-timestamp-down 'org-timestamp-up)))
20720 ((and (not (eq org-support-shift-select 'always))
20721 org-enable-priority-commands
20722 (org-at-heading-p))
20723 (call-interactively 'org-priority-up))
20724 ((and (not org-support-shift-select) (org-at-item-p))
20725 (call-interactively 'org-previous-item))
20726 ((org-clocktable-try-shift 'up arg))
20727 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20728 (org-support-shift-select
20729 (org-call-for-shift-select 'previous-line))
20730 (t (org-shiftselect-error))))
20732 (defun org-shiftdown (&optional arg)
20733 "Decrease item in timestamp or decrease priority of current headline.
20734 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20735 depending on context. See the individual commands for more information."
20736 (interactive "P")
20737 (cond
20738 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20739 ((and org-support-shift-select (org-region-active-p))
20740 (org-call-for-shift-select 'next-line))
20741 ((org-at-timestamp-p t)
20742 (call-interactively (if org-edit-timestamp-down-means-later
20743 'org-timestamp-up 'org-timestamp-down)))
20744 ((and (not (eq org-support-shift-select 'always))
20745 org-enable-priority-commands
20746 (org-at-heading-p))
20747 (call-interactively 'org-priority-down))
20748 ((and (not org-support-shift-select) (org-at-item-p))
20749 (call-interactively 'org-next-item))
20750 ((org-clocktable-try-shift 'down arg))
20751 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20752 (org-support-shift-select
20753 (org-call-for-shift-select 'next-line))
20754 (t (org-shiftselect-error))))
20756 (defun org-shiftright (&optional arg)
20757 "Cycle the thing at point or in the current line, depending on context.
20758 Depending on context, this does one of the following:
20760 - switch a timestamp at point one day into the future
20761 - on a headline, switch to the next TODO keyword.
20762 - on an item, switch entire list to the next bullet type
20763 - on a property line, switch to the next allowed value
20764 - on a clocktable definition line, move time block into the future"
20765 (interactive "P")
20766 (cond
20767 ((run-hook-with-args-until-success 'org-shiftright-hook))
20768 ((and org-support-shift-select (org-region-active-p))
20769 (org-call-for-shift-select 'forward-char))
20770 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20771 ((and (not (eq org-support-shift-select 'always))
20772 (org-at-heading-p))
20773 (let ((org-inhibit-logging
20774 (not org-treat-S-cursor-todo-selection-as-state-change))
20775 (org-inhibit-blocking
20776 (not org-treat-S-cursor-todo-selection-as-state-change)))
20777 (org-call-with-arg 'org-todo 'right)))
20778 ((or (and org-support-shift-select
20779 (not (eq org-support-shift-select 'always))
20780 (org-at-item-bullet-p))
20781 (and (not org-support-shift-select) (org-at-item-p)))
20782 (org-call-with-arg 'org-cycle-list-bullet nil))
20783 ((and (not (eq org-support-shift-select 'always))
20784 (org-at-property-p))
20785 (call-interactively 'org-property-next-allowed-value))
20786 ((org-clocktable-try-shift 'right arg))
20787 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20788 (org-support-shift-select
20789 (org-call-for-shift-select 'forward-char))
20790 (t (org-shiftselect-error))))
20792 (defun org-shiftleft (&optional arg)
20793 "Cycle the thing at point or in the current line, depending on context.
20794 Depending on context, this does one of the following:
20796 - switch a timestamp at point one day into the past
20797 - on a headline, switch to the previous TODO keyword.
20798 - on an item, switch entire list to the previous bullet type
20799 - on a property line, switch to the previous allowed value
20800 - on a clocktable definition line, move time block into the past"
20801 (interactive "P")
20802 (cond
20803 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20804 ((and org-support-shift-select (org-region-active-p))
20805 (org-call-for-shift-select 'backward-char))
20806 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20807 ((and (not (eq org-support-shift-select 'always))
20808 (org-at-heading-p))
20809 (let ((org-inhibit-logging
20810 (not org-treat-S-cursor-todo-selection-as-state-change))
20811 (org-inhibit-blocking
20812 (not org-treat-S-cursor-todo-selection-as-state-change)))
20813 (org-call-with-arg 'org-todo 'left)))
20814 ((or (and org-support-shift-select
20815 (not (eq org-support-shift-select 'always))
20816 (org-at-item-bullet-p))
20817 (and (not org-support-shift-select) (org-at-item-p)))
20818 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20819 ((and (not (eq org-support-shift-select 'always))
20820 (org-at-property-p))
20821 (call-interactively 'org-property-previous-allowed-value))
20822 ((org-clocktable-try-shift 'left arg))
20823 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20824 (org-support-shift-select
20825 (org-call-for-shift-select 'backward-char))
20826 (t (org-shiftselect-error))))
20828 (defun org-shiftcontrolright ()
20829 "Switch to next TODO set."
20830 (interactive)
20831 (cond
20832 ((and org-support-shift-select (org-region-active-p))
20833 (org-call-for-shift-select 'forward-word))
20834 ((and (not (eq org-support-shift-select 'always))
20835 (org-at-heading-p))
20836 (org-call-with-arg 'org-todo 'nextset))
20837 (org-support-shift-select
20838 (org-call-for-shift-select 'forward-word))
20839 (t (org-shiftselect-error))))
20841 (defun org-shiftcontrolleft ()
20842 "Switch to previous TODO set."
20843 (interactive)
20844 (cond
20845 ((and org-support-shift-select (org-region-active-p))
20846 (org-call-for-shift-select 'backward-word))
20847 ((and (not (eq org-support-shift-select 'always))
20848 (org-at-heading-p))
20849 (org-call-with-arg 'org-todo 'previousset))
20850 (org-support-shift-select
20851 (org-call-for-shift-select 'backward-word))
20852 (t (org-shiftselect-error))))
20854 (defun org-shiftcontrolup (&optional n)
20855 "Change timestamps synchronously up in CLOCK log lines.
20856 Optional argument N tells to change by that many units."
20857 (interactive "P")
20858 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20859 (let (org-support-shift-select)
20860 (org-clock-timestamps-up n))
20861 (user-error "Not at a clock log")))
20863 (defun org-shiftcontroldown (&optional n)
20864 "Change timestamps synchronously down in CLOCK log lines.
20865 Optional argument N tells to change by that many units."
20866 (interactive "P")
20867 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20868 (let (org-support-shift-select)
20869 (org-clock-timestamps-down n))
20870 (user-error "Not at a clock log")))
20872 (defun org-increase-number-at-point (&optional inc)
20873 "Increment the number at point.
20874 With an optional prefix numeric argument INC, increment using
20875 this numeric value."
20876 (interactive "p")
20877 (if (not (number-at-point))
20878 (user-error "Not on a number")
20879 (unless inc (setq inc 1))
20880 (let ((pos (point))
20881 (beg (skip-chars-backward "-+^/*0-9eE."))
20882 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20883 (setq nap (buffer-substring-no-properties
20884 (+ pos beg) (+ pos beg end)))
20885 (delete-region (+ pos beg) (+ pos beg end))
20886 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20887 (when (org-at-table-p)
20888 (org-table-align)
20889 (org-table-end-of-field 1))))
20891 (defun org-decrease-number-at-point (&optional inc)
20892 "Decrement the number at point.
20893 With an optional prefix numeric argument INC, decrement using
20894 this numeric value."
20895 (interactive "p")
20896 (org-increase-number-at-point (- (or inc 1))))
20898 (defun org-ctrl-c-ret ()
20899 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20900 (interactive)
20901 (cond
20902 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20903 (t (call-interactively 'org-insert-heading))))
20905 (defun org-find-visible ()
20906 (let ((s (point)))
20907 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20908 (get-char-property s 'invisible)))
20910 (defun org-find-invisible ()
20911 (let ((s (point)))
20912 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20913 (not (get-char-property s 'invisible))))
20916 (defun org-copy-visible (beg end)
20917 "Copy the visible parts of the region."
20918 (interactive "r")
20919 (let (snippets s)
20920 (save-excursion
20921 (save-restriction
20922 (narrow-to-region beg end)
20923 (setq s (goto-char (point-min)))
20924 (while (not (= (point) (point-max)))
20925 (goto-char (org-find-invisible))
20926 (push (buffer-substring s (point)) snippets)
20927 (setq s (goto-char (org-find-visible))))))
20928 (kill-new (apply 'concat (nreverse snippets)))))
20930 (defun org-copy-special ()
20931 "Copy region in table or copy current subtree.
20932 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20933 context. See the individual commands for more information."
20934 (interactive)
20935 (call-interactively
20936 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20938 (defun org-cut-special ()
20939 "Cut region in table or cut current subtree.
20940 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20941 context. See the individual commands for more information."
20942 (interactive)
20943 (call-interactively
20944 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20946 (defun org-paste-special (arg)
20947 "Paste rectangular region into table, or past subtree relative to level.
20948 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20949 See the individual commands for more information."
20950 (interactive "P")
20951 (if (org-at-table-p)
20952 (org-table-paste-rectangle)
20953 (org-paste-subtree arg)))
20955 (defun org-edit-special (&optional arg)
20956 "Call a special editor for the element at point.
20957 When at a table, call the formula editor with `org-table-edit-formulas'.
20958 When in a source code block, call `org-edit-src-code'.
20959 When in a fixed-width region, call `org-edit-fixed-width-region'.
20960 When in an export block, call `org-edit-export-block'.
20961 When at an #+INCLUDE keyword, visit the included file.
20962 When at a footnote reference, call `org-edit-footnote-reference'
20963 On a link, call `ffap' to visit the link at point.
20964 Otherwise, return a user error."
20965 (interactive "P")
20966 (let ((element (org-element-at-point)))
20967 (barf-if-buffer-read-only)
20968 (pcase (org-element-type element)
20969 (`src-block
20970 (if (not arg) (org-edit-src-code)
20971 (let* ((info (org-babel-get-src-block-info))
20972 (lang (nth 0 info))
20973 (params (nth 2 info))
20974 (session (cdr (assq :session params))))
20975 (if (not session) (org-edit-src-code)
20976 ;; At a src-block with a session and function called with
20977 ;; an ARG: switch to the buffer related to the inferior
20978 ;; process.
20979 (switch-to-buffer
20980 (funcall (intern (concat "org-babel-prep-session:" lang))
20981 session params))))))
20982 (`keyword
20983 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20984 (org-open-link-from-string
20985 (format "[[%s]]"
20986 (expand-file-name
20987 (let ((value (org-element-property :value element)))
20988 (cond ((not (org-string-nw-p value))
20989 (user-error "No file to edit"))
20990 ((string-match "\\`\"\\(.*?\\)\"" value)
20991 (match-string 1 value))
20992 ((string-match "\\`[^ \t\"]\\S-*" value)
20993 (match-string 0 value))
20994 (t (user-error "No valid file specified")))))))
20995 (user-error "No special environment to edit here")))
20996 (`table
20997 (if (eq (org-element-property :type element) 'table.el)
20998 (org-edit-table.el)
20999 (call-interactively 'org-table-edit-formulas)))
21000 ;; Only Org tables contain `table-row' type elements.
21001 (`table-row (call-interactively 'org-table-edit-formulas))
21002 (`example-block (org-edit-src-code))
21003 (`export-block (org-edit-export-block))
21004 (`fixed-width (org-edit-fixed-width-region))
21006 ;; No notable element at point. Though, we may be at a link or
21007 ;; a footnote reference, which are objects. Thus, scan deeper.
21008 (let ((context (org-element-context element)))
21009 (pcase (org-element-type context)
21010 (`footnote-reference (org-edit-footnote-reference))
21011 (`inline-src-block (org-edit-inline-src-code))
21012 (`link (call-interactively #'ffap))
21013 (_ (user-error "No special environment to edit here"))))))))
21015 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21016 (defun org-ctrl-c-ctrl-c (&optional arg)
21017 "Set tags in headline, or update according to changed information at point.
21019 This command does many different things, depending on context:
21021 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21022 this is what we do.
21024 - If the cursor is on a statistics cookie, update it.
21026 - If the cursor is in a headline, prompt for tags and insert them
21027 into the current line, aligned to `org-tags-column'. When called
21028 with prefix arg, realign all tags in the current buffer.
21030 - If the cursor is in one of the special #+KEYWORD lines, this
21031 triggers scanning the buffer for these lines and updating the
21032 information.
21034 - If the cursor is inside a table, realign the table. This command
21035 works even if the automatic table editor has been turned off.
21037 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21038 the entire table.
21040 - If the cursor is at a footnote reference or definition, jump to
21041 the corresponding definition or references, respectively.
21043 - If the cursor is a the beginning of a dynamic block, update it.
21045 - If the current buffer is a capture buffer, close note and file it.
21047 - If the cursor is on a <<<target>>>, update radio targets and
21048 corresponding links in this buffer.
21050 - If the cursor is on a numbered item in a plain list, renumber the
21051 ordered list.
21053 - If the cursor is on a checkbox, toggle it.
21055 - If the cursor is on a code block, evaluate it. The variable
21056 `org-confirm-babel-evaluate' can be used to control prompting
21057 before code block evaluation, by default every code block
21058 evaluation requires confirmation. Code block evaluation can be
21059 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21060 (interactive "P")
21061 (cond
21062 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21063 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21064 (org-remove-occur-highlights)
21065 (message "Temporary highlights/overlays removed from current buffer"))
21066 ((and (local-variable-p 'org-finish-function)
21067 (fboundp org-finish-function))
21068 (funcall org-finish-function))
21069 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21071 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21072 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21073 (user-error
21074 (substitute-command-keys
21075 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))
21076 (let* ((context (org-element-context))
21077 (type (org-element-type context)))
21078 (cl-case type
21079 ;; When at a link, act according to the parent instead.
21080 (link (setq context (org-element-property :parent context))
21081 (setq type (org-element-type context)))
21082 ;; Unsupported object types: refer to the first supported
21083 ;; element or object containing it.
21084 ((bold code entity export-snippet inline-babel-call inline-src-block
21085 italic latex-fragment line-break macro strike-through subscript
21086 superscript underline verbatim)
21087 (setq context
21088 (org-element-lineage
21089 context '(paragraph radio-target table-cell verse-block)))
21090 (setq type (org-element-type context))))
21091 ;; For convenience: at the first line of a paragraph on the
21092 ;; same line as an item, apply function on that item instead.
21093 (when (eq type 'paragraph)
21094 (let ((parent (org-element-property :parent context)))
21095 (when (and (eq (org-element-type parent) 'item)
21096 (= (line-beginning-position)
21097 (org-element-property :begin parent)))
21098 (setq context parent)
21099 (setq type 'item))))
21100 ;; Act according to type of element or object at point.
21101 (pcase type
21102 (`clock (org-clock-update-time-maybe))
21103 (`dynamic-block
21104 (save-excursion
21105 (goto-char (org-element-property :post-affiliated context))
21106 (org-update-dblock)))
21107 (`footnote-definition
21108 (goto-char (org-element-property :post-affiliated context))
21109 (call-interactively 'org-footnote-action))
21110 (`footnote-reference (call-interactively 'org-footnote-action))
21111 ((or `headline `inlinetask)
21112 (save-excursion (goto-char (org-element-property :begin context))
21113 (call-interactively #'org-set-tags)))
21114 (`item
21115 ;; At an item: a double C-u set checkbox to "[-]"
21116 ;; unconditionally, whereas a single one will toggle its
21117 ;; presence. Without a universal argument, if the item
21118 ;; has a checkbox, toggle it. Otherwise repair the list.
21119 (let* ((box (org-element-property :checkbox context))
21120 (struct (org-element-property :structure context))
21121 (old-struct (copy-tree struct))
21122 (parents (org-list-parents-alist struct))
21123 (prevs (org-list-prevs-alist struct))
21124 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21125 (org-list-set-checkbox
21126 (org-element-property :begin context) struct
21127 (cond ((equal arg '(16)) "[-]")
21128 ((and (not box) (equal arg '(4))) "[ ]")
21129 ((or (not box) (equal arg '(4))) nil)
21130 ((eq box 'on) "[ ]")
21131 (t "[X]")))
21132 ;; Mimic `org-list-write-struct' but with grabbing
21133 ;; a return value from `org-list-struct-fix-box'.
21134 (org-list-struct-fix-ind struct parents 2)
21135 (org-list-struct-fix-item-end struct)
21136 (org-list-struct-fix-bul struct prevs)
21137 (org-list-struct-fix-ind struct parents)
21138 (let ((block-item
21139 (org-list-struct-fix-box struct parents prevs orderedp)))
21140 (if (and box (equal struct old-struct))
21141 (if (equal arg '(16))
21142 (message "Checkboxes already reset")
21143 (user-error "Cannot toggle this checkbox: %s"
21144 (if (eq box 'on)
21145 "all subitems checked"
21146 "unchecked subitems")))
21147 (org-list-struct-apply-struct struct old-struct)
21148 (org-update-checkbox-count-maybe))
21149 (when block-item
21150 (message "Checkboxes were removed due to empty box at line %d"
21151 (org-current-line block-item))))))
21152 (`keyword
21153 (let ((org-inhibit-startup-visibility-stuff t)
21154 (org-startup-align-all-tables nil))
21155 (when (boundp 'org-table-coordinate-overlays)
21156 (mapc #'delete-overlay org-table-coordinate-overlays)
21157 (setq org-table-coordinate-overlays nil))
21158 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21159 (message "Local setup has been refreshed"))
21160 (`plain-list
21161 ;; At a plain list, with a double C-u argument, set
21162 ;; checkboxes of each item to "[-]", whereas a single one
21163 ;; will toggle their presence according to the state of the
21164 ;; first item in the list. Without an argument, repair the
21165 ;; list.
21166 (let* ((begin (org-element-property :contents-begin context))
21167 (beginm (move-marker (make-marker) begin))
21168 (struct (org-element-property :structure context))
21169 (old-struct (copy-tree struct))
21170 (first-box (save-excursion
21171 (goto-char begin)
21172 (looking-at org-list-full-item-re)
21173 (match-string-no-properties 3)))
21174 (new-box (cond ((equal arg '(16)) "[-]")
21175 ((equal arg '(4)) (unless first-box "[ ]"))
21176 ((equal first-box "[X]") "[ ]")
21177 (t "[X]"))))
21178 (cond
21179 (arg
21180 (dolist (pos
21181 (org-list-get-all-items
21182 begin struct (org-list-prevs-alist struct)))
21183 (org-list-set-checkbox pos struct new-box)))
21184 ((and first-box (eq (point) begin))
21185 ;; For convenience, when point is at bol on the first
21186 ;; item of the list and no argument is provided, simply
21187 ;; toggle checkbox of that item, if any.
21188 (org-list-set-checkbox begin struct new-box)))
21189 (org-list-write-struct
21190 struct (org-list-parents-alist struct) old-struct)
21191 (org-update-checkbox-count-maybe)
21192 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21193 ((or `property-drawer `node-property)
21194 (call-interactively #'org-property-action))
21195 ((or `radio-target `target)
21196 (call-interactively #'org-update-radio-target-regexp))
21197 (`statistics-cookie
21198 (call-interactively #'org-update-statistics-cookies))
21199 ((or `table `table-cell `table-row)
21200 ;; At a table, recalculate every field and align it. Also
21201 ;; send the table if necessary. If the table has
21202 ;; a `table.el' type, just give up. At a table row or
21203 ;; cell, maybe recalculate line but always align table.
21204 (if (eq (org-element-property :type context) 'table.el)
21205 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21206 Use \\[org-edit-special] to edit table.el tables"))
21207 (let ((org-enable-table-editor t))
21208 (if (or (eq type 'table)
21209 ;; Check if point is at a TBLFM line.
21210 (and (eq type 'table-row)
21211 (= (point) (org-element-property :end context))))
21212 (save-excursion
21213 (if (org-at-TBLFM-p)
21214 (progn (require 'org-table)
21215 (org-table-calc-current-TBLFM))
21216 (goto-char (org-element-property :contents-begin context))
21217 (org-call-with-arg 'org-table-recalculate (or arg t))
21218 (orgtbl-send-table 'maybe)))
21219 (org-table-maybe-eval-formula)
21220 (cond (arg (call-interactively 'org-table-recalculate))
21221 ((org-table-maybe-recalculate-line))
21222 (t (org-table-align)))))))
21223 (`timestamp (org-timestamp-change 0 'day))
21224 ((and `nil (guard (org-at-heading-p)))
21225 ;; When point is on an unsupported object type, we can miss
21226 ;; the fact that it also is at a heading. Handle it here.
21227 (call-interactively #'org-set-tags))
21229 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21230 (user-error
21231 (substitute-command-keys
21232 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))))
21234 (defun org-mode-restart ()
21235 (interactive)
21236 (let ((indent-status (bound-and-true-p org-indent-mode)))
21237 (funcall major-mode)
21238 (hack-local-variables)
21239 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21240 (org-indent-mode -1)))
21241 (message "%s restarted" major-mode))
21243 (defun org-kill-note-or-show-branches ()
21244 "Abort storing current note, or call `outline-show-branches'."
21245 (interactive)
21246 (if (not org-finish-function)
21247 (progn
21248 (outline-hide-subtree)
21249 (call-interactively 'outline-show-branches))
21250 (let ((org-note-abort t))
21251 (funcall org-finish-function))))
21253 (defun org-delete-indentation (&optional ARG)
21254 "Join current line to previous and fix whitespace at join.
21256 If previous line is a headline add to headline title. Otherwise
21257 the function calls `delete-indentation'.
21259 With argument, join this line to following line."
21260 (interactive "*P")
21261 (if (save-excursion
21262 (if ARG (beginning-of-line)
21263 (forward-line -1))
21264 (looking-at org-complex-heading-regexp))
21265 ;; At headline.
21266 (let ((tags-column (when (match-beginning 5)
21267 (save-excursion (goto-char (match-beginning 5))
21268 (current-column))))
21269 (string (concat " " (progn (when ARG (forward-line 1))
21270 (org-trim (delete-and-extract-region
21271 (line-beginning-position)
21272 (line-end-position)))))))
21273 (unless (bobp) (delete-region (point) (1- (point))))
21274 (goto-char (or (match-end 4)
21275 (match-beginning 5)
21276 (match-end 0)))
21277 (skip-chars-backward " \t")
21278 (save-excursion (insert string))
21279 ;; Adjust alignment of tags.
21280 (when tags-column
21281 (org-align-tags-here (if org-auto-align-tags
21282 org-tags-column
21283 tags-column))))
21284 (delete-indentation ARG)))
21286 (defun org-open-line (n)
21287 "Insert a new row in tables, call `open-line' elsewhere.
21288 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21289 As a special case, when a document starts with a table, allow to
21290 call `open-line' on the very first character."
21291 (interactive "*p")
21292 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21293 (org-table-insert-row)
21294 (open-line n)))
21296 (defun org-return (&optional indent)
21297 "Goto next table row or insert a newline.
21299 Calls `org-table-next-row' or `newline', depending on context.
21301 When optional INDENT argument is non-nil, call
21302 `newline-and-indent' instead of `newline'.
21304 When `org-return-follows-link' is non-nil and point is on
21305 a timestamp or a link, call `org-open-at-point'. However, it
21306 will not happen if point is in a table or on a \"dead\"
21307 object (e.g., within a comment). In these case, you need to use
21308 `org-open-at-point' directly."
21309 (interactive)
21310 (let ((context (if org-return-follows-link (org-element-context)
21311 (org-element-at-point))))
21312 (cond
21313 ;; In a table, call `org-table-next-row'.
21314 ((or (and (eq (org-element-type context) 'table)
21315 (>= (point) (org-element-property :contents-begin context))
21316 (< (point) (org-element-property :contents-end context)))
21317 (org-element-lineage context '(table-row table-cell) t))
21318 (org-table-justify-field-maybe)
21319 (call-interactively #'org-table-next-row))
21320 ;; On a link or a timestamp, call `org-open-at-point' if
21321 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21322 ;; locations, e.g., in a comment, as `org-open-at-point'.
21323 ((and org-return-follows-link
21324 (or (org-in-regexp org-ts-regexp-both nil t)
21325 (org-in-regexp org-tsr-regexp-both nil t)
21326 (org-in-regexp org-any-link-re nil t)))
21327 (call-interactively #'org-open-at-point))
21328 ;; Insert newline in heading, but preserve tags.
21329 ((and (not (bolp))
21330 (save-excursion (beginning-of-line)
21331 (looking-at org-complex-heading-regexp)))
21332 ;; At headline. Split line. However, if point is on keyword,
21333 ;; priority cookie or tags, do not break any of them: add
21334 ;; a newline after the headline instead.
21335 (let ((tags-column (and (match-beginning 5)
21336 (save-excursion (goto-char (match-beginning 5))
21337 (current-column))))
21338 (string
21339 (when (and (match-end 4)
21340 (>= (point)
21341 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21342 (<= (point) (match-end 4)))
21343 (delete-and-extract-region (point) (match-end 4)))))
21344 (when (and tags-column string) ; Adjust tag alignment.
21345 (org-align-tags-here
21346 (if org-auto-align-tags org-tags-column tags-column)))
21347 (end-of-line)
21348 (org-show-entry)
21349 (if indent (newline-and-indent) (newline))
21350 (when string (save-excursion (insert (org-trim string))))))
21351 ;; In a list, make sure indenting keeps trailing text within.
21352 ((and indent
21353 (not (eolp))
21354 (org-element-lineage context '(item)))
21355 (let ((trailing-data
21356 (delete-and-extract-region (point) (line-end-position))))
21357 (newline-and-indent)
21358 (save-excursion (insert trailing-data))))
21359 (t (if indent (newline-and-indent) (newline))))))
21361 (defun org-return-indent ()
21362 "Goto next table row or insert a newline and indent.
21363 Calls `org-table-next-row' or `newline-and-indent', depending on
21364 context. See the individual commands for more information."
21365 (interactive)
21366 (org-return t))
21368 (defun org-ctrl-c-star ()
21369 "Compute table, or change heading status of lines.
21370 Calls `org-table-recalculate' or `org-toggle-heading',
21371 depending on context."
21372 (interactive)
21373 (cond
21374 ((org-at-table-p)
21375 (call-interactively 'org-table-recalculate))
21377 ;; Convert all lines in region to list items
21378 (call-interactively 'org-toggle-heading))))
21380 (defun org-ctrl-c-minus ()
21381 "Insert separator line in table or modify bullet status of line.
21382 Also turns a plain line or a region of lines into list items.
21383 Calls `org-table-insert-hline', `org-toggle-item', or
21384 `org-cycle-list-bullet', depending on context."
21385 (interactive)
21386 (cond
21387 ((org-at-table-p)
21388 (call-interactively 'org-table-insert-hline))
21389 ((org-region-active-p)
21390 (call-interactively 'org-toggle-item))
21391 ((org-in-item-p)
21392 (call-interactively 'org-cycle-list-bullet))
21394 (call-interactively 'org-toggle-item))))
21396 (defun org-toggle-heading (&optional nstars)
21397 "Convert headings to normal text, or items or text to headings.
21398 If there is no active region, only convert the current line.
21400 With a \\[universal-argument] prefix, convert the whole list at
21401 point into heading.
21403 In a region:
21405 - If the first non blank line is a headline, remove the stars
21406 from all headlines in the region.
21408 - If it is a normal line, turn each and every normal line (i.e.,
21409 not an heading or an item) in the region into headings. If you
21410 want to convert only the first line of this region, use one
21411 universal prefix argument.
21413 - If it is a plain list item, turn all plain list items into headings.
21415 When converting a line into a heading, the number of stars is chosen
21416 such that the lines become children of the current entry. However,
21417 when a numeric prefix argument is given, its value determines the
21418 number of stars to add."
21419 (interactive "P")
21420 (let ((skip-blanks
21421 (function
21422 ;; Return beginning of first non-blank line, starting from
21423 ;; line at POS.
21424 (lambda (pos)
21425 (save-excursion
21426 (goto-char pos)
21427 (while (org-at-comment-p) (forward-line))
21428 (skip-chars-forward " \r\t\n")
21429 (point-at-bol)))))
21430 beg end toggled)
21431 ;; Determine boundaries of changes. If a universal prefix has
21432 ;; been given, put the list in a region. If region ends at a bol,
21433 ;; do not consider the last line to be in the region.
21435 (when (and current-prefix-arg (org-at-item-p))
21436 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21437 (org-mark-element))
21439 (if (org-region-active-p)
21440 (setq beg (funcall skip-blanks (region-beginning))
21441 end (copy-marker (save-excursion
21442 (goto-char (region-end))
21443 (if (bolp) (point) (point-at-eol)))))
21444 (setq beg (funcall skip-blanks (point-at-bol))
21445 end (copy-marker (point-at-eol))))
21446 ;; Ensure inline tasks don't count as headings.
21447 (org-with-limited-levels
21448 (save-excursion
21449 (goto-char beg)
21450 (cond
21451 ;; Case 1. Started at an heading: de-star headings.
21452 ((org-at-heading-p)
21453 (while (< (point) end)
21454 (when (org-at-heading-p t)
21455 (looking-at org-outline-regexp) (replace-match "")
21456 (setq toggled t))
21457 (forward-line)))
21458 ;; Case 2. Started at an item: change items into headlines.
21459 ;; One star will be added by `org-list-to-subtree'.
21460 ((org-at-item-p)
21461 (while (< (point) end)
21462 (when (org-at-item-p)
21463 ;; Pay attention to cases when region ends before list.
21464 (let* ((struct (org-list-struct))
21465 (list-end
21466 (min (org-list-get-bottom-point struct) (1+ end))))
21467 (save-restriction
21468 (narrow-to-region (point) list-end)
21469 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21470 (setq toggled t))
21471 (forward-line)))
21472 ;; Case 3. Started at normal text: make every line an heading,
21473 ;; skipping headlines and items.
21474 (t (let* ((stars
21475 (make-string
21476 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21477 (add-stars
21478 (cond (nstars "") ; stars from prefix only
21479 ((equal stars "") "*") ; before first heading
21480 (org-odd-levels-only "**") ; inside heading, odd
21481 (t "*"))) ; inside heading, oddeven
21482 (rpl (concat stars add-stars " "))
21483 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21484 (while (< (point) (if (equal nstars '(4)) lend end))
21485 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21486 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21487 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21488 (forward-line)))))))
21489 (unless toggled (message "Cannot toggle heading from here"))))
21491 (defun org-meta-return (&optional _arg)
21492 "Insert a new heading or wrap a region in a table.
21493 Calls `org-insert-heading' or `org-table-wrap-region', depending
21494 on context. See the individual commands for more information."
21495 (interactive)
21496 (org-check-before-invisible-edit 'insert)
21497 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21498 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21499 #'org-insert-heading))))
21501 ;;; Menu entries
21503 (defsubst org-in-subtree-not-table-p ()
21504 "Are we in a subtree and not in a table?"
21505 (and (not (org-before-first-heading-p))
21506 (not (org-at-table-p))))
21508 ;; Define the Org mode menus
21509 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21510 '("Tbl"
21511 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21512 ["Next Field" org-cycle (org-at-table-p)]
21513 ["Previous Field" org-shifttab (org-at-table-p)]
21514 ["Next Row" org-return (org-at-table-p)]
21515 "--"
21516 ["Blank Field" org-table-blank-field (org-at-table-p)]
21517 ["Edit Field" org-table-edit-field (org-at-table-p)]
21518 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21519 "--"
21520 ("Column"
21521 ["Move Column Left" org-metaleft (org-at-table-p)]
21522 ["Move Column Right" org-metaright (org-at-table-p)]
21523 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21524 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21525 ("Row"
21526 ["Move Row Up" org-metaup (org-at-table-p)]
21527 ["Move Row Down" org-metadown (org-at-table-p)]
21528 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21529 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21530 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21531 "--"
21532 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21533 ("Rectangle"
21534 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21535 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21536 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21537 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21538 "--"
21539 ("Calculate"
21540 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21541 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21542 ["Edit Formulas" org-edit-special (org-at-table-p)]
21543 "--"
21544 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21545 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21546 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21547 "--"
21548 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21549 "--"
21550 ["Sum Column/Rectangle" org-table-sum
21551 (or (org-at-table-p) (org-region-active-p))]
21552 ["Which Column?" org-table-current-column (org-at-table-p)])
21553 ["Debug Formulas"
21554 org-table-toggle-formula-debugger
21555 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21556 ["Show Col/Row Numbers"
21557 org-table-toggle-coordinate-overlays
21558 :style toggle
21559 :selected (bound-and-true-p org-table-overlay-coordinates)]
21560 "--"
21561 ["Create" org-table-create (and (not (org-at-table-p))
21562 org-enable-table-editor)]
21563 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21564 ["Import from File" org-table-import (not (org-at-table-p))]
21565 ["Export to File" org-table-export (org-at-table-p)]
21566 "--"
21567 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21568 "--"
21569 ("Plot"
21570 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21571 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21573 (easy-menu-define org-org-menu org-mode-map "Org menu"
21574 '("Org"
21575 ("Show/Hide"
21576 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21577 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21578 ["Sparse Tree..." org-sparse-tree t]
21579 ["Reveal Context" org-reveal t]
21580 ["Show All" outline-show-all t]
21581 "--"
21582 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21583 "--"
21584 ["New Heading" org-insert-heading t]
21585 ("Navigate Headings"
21586 ["Up" outline-up-heading t]
21587 ["Next" outline-next-visible-heading t]
21588 ["Previous" outline-previous-visible-heading t]
21589 ["Next Same Level" outline-forward-same-level t]
21590 ["Previous Same Level" outline-backward-same-level t]
21591 "--"
21592 ["Jump" org-goto t])
21593 ("Edit Structure"
21594 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21595 "--"
21596 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21597 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21598 "--"
21599 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21600 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21601 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21602 "--"
21603 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21604 "--"
21605 ["Copy visible text" org-copy-visible t]
21606 "--"
21607 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21608 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21609 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21610 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21611 "--"
21612 ["Sort Region/Children" org-sort t]
21613 "--"
21614 ["Convert to odd levels" org-convert-to-odd-levels t]
21615 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21616 ("Editing"
21617 ["Emphasis..." org-emphasize t]
21618 ["Edit Source Example" org-edit-special t]
21619 "--"
21620 ["Footnote new/jump" org-footnote-action t]
21621 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21622 ("Archive"
21623 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21624 "--"
21625 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21626 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21627 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21629 "--"
21630 ("Hyperlinks"
21631 ["Store Link (Global)" org-store-link t]
21632 ["Find existing link to here" org-occur-link-in-agenda-files t]
21633 ["Insert Link" org-insert-link t]
21634 ["Follow Link" org-open-at-point t]
21635 "--"
21636 ["Next link" org-next-link t]
21637 ["Previous link" org-previous-link t]
21638 "--"
21639 ["Descriptive Links"
21640 org-toggle-link-display
21641 :style radio
21642 :selected org-descriptive-links
21644 ["Literal Links"
21645 org-toggle-link-display
21646 :style radio
21647 :selected (not org-descriptive-links)])
21648 "--"
21649 ("TODO Lists"
21650 ["TODO/DONE/-" org-todo t]
21651 ("Select keyword"
21652 ["Next keyword" org-shiftright (org-at-heading-p)]
21653 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21654 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21655 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21656 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21657 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21658 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21659 "--"
21660 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21661 :selected org-enforce-todo-dependencies :style toggle :active t]
21662 "Settings for tree at point"
21663 ["Do Children sequentially" org-toggle-ordered-property :style radio
21664 :selected (org-entry-get nil "ORDERED")
21665 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21666 ["Do Children parallel" org-toggle-ordered-property :style radio
21667 :selected (not (org-entry-get nil "ORDERED"))
21668 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21669 "--"
21670 ["Set Priority" org-priority t]
21671 ["Priority Up" org-shiftup t]
21672 ["Priority Down" org-shiftdown t]
21673 "--"
21674 ["Get news from all feeds" org-feed-update-all t]
21675 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21676 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21677 ("TAGS and Properties"
21678 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21679 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21680 "--"
21681 ["Set property" org-set-property (not (org-before-first-heading-p))]
21682 ["Column view of properties" org-columns t]
21683 ["Insert Column View DBlock" org-columns-insert-dblock t])
21684 ("Dates and Scheduling"
21685 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21686 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21687 ("Change Date"
21688 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21689 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21690 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21691 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21692 ["Compute Time Range" org-evaluate-time-range t]
21693 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21694 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21695 "--"
21696 ["Custom time format" org-toggle-time-stamp-overlays
21697 :style radio :selected org-display-custom-times]
21698 "--"
21699 ["Goto Calendar" org-goto-calendar t]
21700 ["Date from Calendar" org-date-from-calendar t]
21701 "--"
21702 ["Start/Restart Timer" org-timer-start t]
21703 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21704 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21705 ["Insert Timer String" org-timer t]
21706 ["Insert Timer Item" org-timer-item t])
21707 ("Logging work"
21708 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21709 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21710 ["Clock out" org-clock-out t]
21711 ["Clock cancel" org-clock-cancel t]
21712 "--"
21713 ["Mark as default task" org-clock-mark-default-task t]
21714 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21715 ["Goto running clock" org-clock-goto t]
21716 "--"
21717 ["Display times" org-clock-display t]
21718 ["Create clock table" org-clock-report t]
21719 "--"
21720 ["Record DONE time"
21721 (progn (setq org-log-done (not org-log-done))
21722 (message "Switching to %s will %s record a timestamp"
21723 (car org-done-keywords)
21724 (if org-log-done "automatically" "not")))
21725 :style toggle :selected org-log-done])
21726 "--"
21727 ["Agenda Command..." org-agenda t]
21728 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21729 ("File List for Agenda")
21730 ("Special views current file"
21731 ["TODO Tree" org-show-todo-tree t]
21732 ["Check Deadlines" org-check-deadlines t]
21733 ["Timeline" org-timeline t]
21734 ["Tags/Property tree" org-match-sparse-tree t])
21735 "--"
21736 ["Export/Publish..." org-export-dispatch t]
21737 ("LaTeX"
21738 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21739 :selected org-cdlatex-mode]
21740 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21741 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21742 ["Modify math symbol" org-cdlatex-math-modify
21743 (org-inside-LaTeX-fragment-p)]
21744 ["Insert citation" org-reftex-citation t])
21745 "--"
21746 ("MobileOrg"
21747 ["Push Files and Views" org-mobile-push t]
21748 ["Get Captured and Flagged" org-mobile-pull t]
21749 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21750 "--"
21751 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21752 "--"
21753 ("Documentation"
21754 ["Show Version" org-version t]
21755 ["Info Documentation" org-info t])
21756 ("Customize"
21757 ["Browse Org Group" org-customize t]
21758 "--"
21759 ["Expand This Menu" org-create-customize-menu
21760 (fboundp 'customize-menu-create)])
21761 ["Send bug report" org-submit-bug-report t]
21762 "--"
21763 ("Refresh/Reload"
21764 ["Refresh setup current buffer" org-mode-restart t]
21765 ["Reload Org (after update)" org-reload t]
21766 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21769 (defun org-info (&optional node)
21770 "Read documentation for Org in the info system.
21771 With optional NODE, go directly to that node."
21772 (interactive)
21773 (info (format "(org)%s" (or node ""))))
21775 ;;;###autoload
21776 (defun org-submit-bug-report ()
21777 "Submit a bug report on Org via mail.
21779 Don't hesitate to report any problems or inaccurate documentation.
21781 If you don't have setup sending mail from (X)Emacs, please copy the
21782 output buffer into your mail program, as it gives us important
21783 information about your Org version and configuration."
21784 (interactive)
21785 (require 'reporter)
21786 (defvar reporter-prompt-for-summary-p)
21787 (org-load-modules-maybe)
21788 (org-require-autoloaded-modules)
21789 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21790 (reporter-submit-bug-report
21791 "emacs-orgmode@gnu.org"
21792 (org-version nil 'full)
21793 (let (list)
21794 (save-window-excursion
21795 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21796 (delete-other-windows)
21797 (erase-buffer)
21798 (insert "You are about to submit a bug report to the Org mailing list.
21800 We would like to add your full Org and Outline configuration to the
21801 bug report. This greatly simplifies the work of the maintainer and
21802 other experts on the mailing list.
21804 HOWEVER, some variables you have customized may contain private
21805 information. The names of customers, colleagues, or friends, might
21806 appear in the form of file names, tags, todo states, or search strings.
21807 If you answer yes to the prompt, you might want to check and remove
21808 such private information before sending the email.")
21809 (add-text-properties (point-min) (point-max) '(face org-warning))
21810 (when (yes-or-no-p "Include your Org configuration ")
21811 (mapatoms
21812 (lambda (v)
21813 (and (boundp v)
21814 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21815 (or (and (symbol-value v)
21816 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21817 (and
21818 (get v 'custom-type) (get v 'standard-value)
21819 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21820 (push v list)))))
21821 (kill-buffer (get-buffer "*Warn about privacy*"))
21822 list))
21823 nil nil
21824 "Remember to cover the basics, that is, what you expected to happen and
21825 what in fact did happen. You don't know how to make a good report? See
21827 http://orgmode.org/manual/Feedback.html#Feedback
21829 Your bug report will be posted to the Org mailing list.
21830 ------------------------------------------------------------------------")
21831 (save-excursion
21832 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21833 (replace-match "\\1Bug: \\3 [\\2]")))))
21836 (defun org-install-agenda-files-menu ()
21837 (let ((bl (buffer-list)))
21838 (save-excursion
21839 (while bl
21840 (set-buffer (pop bl))
21841 (when (derived-mode-p 'org-mode) (setq bl nil)))
21842 (when (derived-mode-p 'org-mode)
21843 (easy-menu-change
21844 '("Org") "File List for Agenda"
21845 (append
21846 (list
21847 ["Edit File List" (org-edit-agenda-file-list) t]
21848 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21849 ["Remove Current File from List" org-remove-file t]
21850 ["Cycle through agenda files" org-cycle-agenda-files t]
21851 ["Occur in all agenda files" org-occur-in-agenda-files t]
21852 "--")
21853 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21855 ;;;; Documentation
21857 (defun org-require-autoloaded-modules ()
21858 (interactive)
21859 (mapc #'require
21860 '(org-agenda org-archive org-attach org-clock org-colview org-id
21861 org-table org-timer)))
21863 ;;;###autoload
21864 (defun org-reload (&optional uncompiled)
21865 "Reload all org lisp files.
21866 With prefix arg UNCOMPILED, load the uncompiled versions."
21867 (interactive "P")
21868 (require 'loadhist)
21869 (let* ((org-dir (org-find-library-dir "org"))
21870 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21871 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21872 (remove-re (format "\\`%s\\'"
21873 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21874 (feats (delete-dups
21875 (mapcar 'file-name-sans-extension
21876 (mapcar 'file-name-nondirectory
21877 (delq nil
21878 (mapcar 'feature-file
21879 features))))))
21880 (lfeat (append
21881 (sort
21882 (setq feats
21883 (delq nil (mapcar
21884 (lambda (f)
21885 (if (and (string-match feature-re f)
21886 (not (string-match remove-re f)))
21887 f nil))
21888 feats)))
21889 'string-lessp)
21890 (list "org-version" "org")))
21891 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21892 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21893 load-uncore load-misses)
21894 (setq load-misses
21895 (delq 't
21896 (mapcar (lambda (f)
21897 (or (org-load-noerror-mustsuffix (concat org-dir f))
21898 (and (string= org-dir contrib-dir)
21899 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21900 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21901 (add-to-list 'load-uncore f 'append)
21904 lfeat)))
21905 (when load-uncore
21906 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21907 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21908 (if load-misses
21909 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21910 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21911 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21913 ;;;###autoload
21914 (defun org-customize ()
21915 "Call the customize function with org as argument."
21916 (interactive)
21917 (org-load-modules-maybe)
21918 (org-require-autoloaded-modules)
21919 (customize-browse 'org))
21921 (defun org-create-customize-menu ()
21922 "Create a full customization menu for Org-mode, insert it into the menu."
21923 (interactive)
21924 (org-load-modules-maybe)
21925 (org-require-autoloaded-modules)
21926 (if (fboundp 'customize-menu-create)
21927 (progn
21928 (easy-menu-change
21929 '("Org") "Customize"
21930 `(["Browse Org group" org-customize t]
21931 "--"
21932 ,(customize-menu-create 'org)
21933 ["Set" Custom-set t]
21934 ["Save" Custom-save t]
21935 ["Reset to Current" Custom-reset-current t]
21936 ["Reset to Saved" Custom-reset-saved t]
21937 ["Reset to Standard Settings" Custom-reset-standard t]))
21938 (message "\"Org\"-menu now contains full customization menu"))
21939 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21941 ;;;; Miscellaneous stuff
21943 ;;; Generally useful functions
21945 (defun org-get-at-eol (property n)
21946 "Get text property PROPERTY at the end of line less N characters."
21947 (get-text-property (- (point-at-eol) n) property))
21949 (defun org-find-text-property-in-string (prop s)
21950 "Return the first non-nil value of property PROP in string S."
21951 (or (get-text-property 0 prop s)
21952 (get-text-property (or (next-single-property-change 0 prop s) 0)
21953 prop s)))
21955 (defun org-display-warning (message)
21956 "Display the given MESSAGE as a warning."
21957 (display-warning 'org message :warning))
21959 (defun org-eval (form)
21960 "Eval FORM and return result."
21961 (condition-case error
21962 (eval form)
21963 (error (format "%%![Error: %s]" error))))
21965 (defun org-in-clocktable-p ()
21966 "Check if the cursor is in a clocktable."
21967 (let ((pos (point)) start)
21968 (save-excursion
21969 (end-of-line 1)
21970 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21971 (setq start (match-beginning 0))
21972 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21973 (>= (match-end 0) pos)
21974 start))))
21976 (defun org-in-verbatim-emphasis ()
21977 (save-match-data
21978 (and (org-in-regexp org-emph-re 2)
21979 (>= (point) (match-beginning 3))
21980 (<= (point) (match-end 4))
21981 (member (match-string 3) '("=" "~")))))
21983 (defun org-overlay-display (ovl text &optional face evap)
21984 "Make overlay OVL display TEXT with face FACE."
21985 (overlay-put ovl 'display text)
21986 (if face (overlay-put ovl 'face face))
21987 (if evap (overlay-put ovl 'evaporate t)))
21989 (defun org-overlay-before-string (ovl text &optional face evap)
21990 "Make overlay OVL display TEXT with face FACE."
21991 (if face (org-add-props text nil 'face face))
21992 (overlay-put ovl 'before-string text)
21993 (if evap (overlay-put ovl 'evaporate t)))
21995 (defun org-find-overlays (prop &optional pos delete)
21996 "Find all overlays specifying PROP at POS or point.
21997 If DELETE is non-nil, delete all those overlays."
21998 (let (found)
21999 (dolist (ov (overlays-at (or pos (point))) found)
22000 (cond ((not (overlay-get ov prop)))
22001 (delete (delete-overlay ov))
22002 (t (push ov found))))))
22004 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22005 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22006 (if (and marker (marker-buffer marker)
22007 (buffer-live-p (marker-buffer marker)))
22008 (progn
22009 (pop-to-buffer-same-window (marker-buffer marker))
22010 (when (or (> marker (point-max)) (< marker (point-min)))
22011 (widen))
22012 (goto-char marker)
22013 (org-show-context 'org-goto))
22014 (if bookmark
22015 (bookmark-jump bookmark)
22016 (error "Cannot find location"))))
22018 (defun org-quote-csv-field (s)
22019 "Quote field for inclusion in CSV material."
22020 (if (string-match "[\",]" s)
22021 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22024 (defun org-force-self-insert (N)
22025 "Needed to enforce self-insert under remapping."
22026 (interactive "p")
22027 (self-insert-command N))
22029 (defun org-string-width (s)
22030 "Compute width of string, ignoring invisible characters.
22031 This ignores character with invisibility property `org-link', and also
22032 characters with property `org-cwidth', because these will become invisible
22033 upon the next fontification round."
22034 (let (b l)
22035 (when (or (eq t buffer-invisibility-spec)
22036 (assq 'org-link buffer-invisibility-spec))
22037 (while (setq b (text-property-any 0 (length s)
22038 'invisible 'org-link s))
22039 (setq s (concat (substring s 0 b)
22040 (substring s (or (next-single-property-change
22041 b 'invisible s)
22042 (length s)))))))
22043 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22044 (setq s (concat (substring s 0 b)
22045 (substring s (or (next-single-property-change
22046 b 'org-cwidth s)
22047 (length s))))))
22048 (setq l (string-width s) b -1)
22049 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22050 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22053 (defun org-shorten-string (s maxlength)
22054 "Shorten string S so that it is no longer than MAXLENGTH characters.
22055 If the string is shorter or has length MAXLENGTH, just return the
22056 original string. If it is longer, the functions finds a space in the
22057 string, breaks this string off at that locations and adds three dots
22058 as ellipsis. Including the ellipsis, the string will not be longer
22059 than MAXLENGTH. If finding a good breaking point in the string does
22060 not work, the string is just chopped off in the middle of a word
22061 if necessary."
22062 (if (<= (length s) maxlength)
22064 (let* ((n (max (- maxlength 4) 1))
22065 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22066 (if (string-match re s)
22067 (concat (match-string 1 s) "...")
22068 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22070 (defun org-get-indentation (&optional line)
22071 "Get the indentation of the current line, interpreting tabs.
22072 When LINE is given, assume it represents a line and compute its indentation."
22073 (if line
22074 (when (string-match "^ *" (org-remove-tabs line))
22075 (match-end 0))
22076 (save-excursion
22077 (beginning-of-line 1)
22078 (skip-chars-forward " \t")
22079 (current-column))))
22081 (defun org-get-string-indentation (s)
22082 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22083 (let ((n -1) (i 0) (w tab-width) c)
22084 (catch 'exit
22085 (while (< (setq n (1+ n)) (length s))
22086 (setq c (aref s n))
22087 (cond ((= c ?\ ) (setq i (1+ i)))
22088 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22089 (t (throw 'exit t)))))
22092 (defun org-remove-tabs (s &optional width)
22093 "Replace tabulators in S with spaces.
22094 Assumes that s is a single line, starting in column 0."
22095 (setq width (or width tab-width))
22096 (while (string-match "\t" s)
22097 (setq s (replace-match
22098 (make-string
22099 (- (* width (/ (+ (match-beginning 0) width) width))
22100 (match-beginning 0)) ?\ )
22101 t t s)))
22104 (defun org-fix-indentation (line ind)
22105 "Fix indentation in LINE.
22106 IND is a cons cell with target and minimum indentation.
22107 If the current indentation in LINE is smaller than the minimum,
22108 leave it alone. If it is larger than ind, set it to the target."
22109 (let* ((l (org-remove-tabs line))
22110 (i (org-get-indentation l))
22111 (i1 (car ind)) (i2 (cdr ind)))
22112 (when (>= i i2) (setq l (substring line i2)))
22113 (if (> i1 0)
22114 (concat (make-string i1 ?\ ) l)
22115 l)))
22117 (defun org-remove-indentation (code &optional n)
22118 "Remove maximum common indentation in string CODE and return it.
22119 N may optionally be the number of columns to remove. Return CODE
22120 as-is if removal failed."
22121 (with-temp-buffer
22122 (insert code)
22123 (if (org-do-remove-indentation n) (buffer-string) code)))
22125 (defun org-do-remove-indentation (&optional n)
22126 "Remove the maximum common indentation from the buffer.
22127 When optional argument N is a positive integer, remove exactly
22128 that much characters from indentation, if possible. Return nil
22129 if it fails."
22130 (catch :exit
22131 (goto-char (point-min))
22132 ;; Find maximum common indentation, if not specified.
22133 (let ((n (or n
22134 (let ((min-ind (point-max)))
22135 (save-excursion
22136 (while (re-search-forward "^[ \t]*\\S-" nil t)
22137 (let ((ind (1- (current-column))))
22138 (if (zerop ind) (throw :exit nil)
22139 (setq min-ind (min min-ind ind))))))
22140 min-ind))))
22141 (if (zerop n) (throw :exit nil)
22142 ;; Remove exactly N indentation, but give up if not possible.
22143 (while (not (eobp))
22144 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22145 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22146 ((< ind n) (throw :exit nil))
22147 (t (indent-line-to (- ind n))))
22148 (forward-line)))
22149 ;; Signal success.
22150 t))))
22152 (defun org-fill-template (template alist)
22153 "Find each %key of ALIST in TEMPLATE and replace it."
22154 (let ((case-fold-search nil))
22155 (dolist (entry (sort (copy-sequence alist)
22156 (lambda (a b) (< (length (car a)) (length (car b))))))
22157 (setq template
22158 (replace-regexp-in-string
22159 (concat "%" (regexp-quote (car entry)))
22160 (or (cdr entry) "") template t t)))
22161 template))
22163 (defun org-base-buffer (buffer)
22164 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22165 (if (not buffer)
22166 buffer
22167 (or (buffer-base-buffer buffer)
22168 buffer)))
22170 (defun org-wrap (string &optional width lines)
22171 "Wrap string to either a number of lines, or a width in characters.
22172 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22173 that costs. If there is a word longer than WIDTH, the text is actually
22174 wrapped to the length of that word.
22175 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22176 many lines, whatever width that takes.
22177 The return value is a list of lines, without newlines at the end."
22178 (let* ((words (org-split-string string "[ \t\n]+"))
22179 (maxword (apply 'max (mapcar 'org-string-width words)))
22180 w ll)
22181 (cond (width
22182 (org-do-wrap words (max maxword width)))
22183 (lines
22184 (setq w maxword)
22185 (setq ll (org-do-wrap words maxword))
22186 (if (<= (length ll) lines)
22188 (setq ll words)
22189 (while (> (length ll) lines)
22190 (setq w (1+ w))
22191 (setq ll (org-do-wrap words w)))
22192 ll))
22193 (t (error "Cannot wrap this")))))
22195 (defun org-do-wrap (words width)
22196 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22197 (let (lines line)
22198 (while words
22199 (setq line (pop words))
22200 (while (and words (< (+ (length line) (length (car words))) width))
22201 (setq line (concat line " " (pop words))))
22202 (setq lines (push line lines)))
22203 (nreverse lines)))
22205 (defun org-split-string (string &optional separators)
22206 "Splits STRING into substrings at SEPARATORS.
22207 SEPARATORS is a regular expression.
22208 No empty strings are returned if there are matches at the beginning
22209 and end of string."
22210 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22211 (let ((start 0) notfirst list)
22212 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22213 (if (and notfirst
22214 (= start (match-beginning 0))
22215 (< start (length string)))
22216 (1+ start) start))
22217 (< (match-beginning 0) (length string)))
22218 (setq notfirst t)
22219 (or (eq (match-beginning 0) 0)
22220 (and (eq (match-beginning 0) (match-end 0))
22221 (eq (match-beginning 0) start))
22222 (push (substring string start (match-beginning 0)) list))
22223 (setq start (match-end 0)))
22224 (or (eq start (length string))
22225 (push (substring string start) list))
22226 (nreverse list)))
22228 (defun org-quote-vert (s)
22229 "Replace \"|\" with \"\\vert\"."
22230 (while (string-match "|" s)
22231 (setq s (replace-match "\\vert" t t s)))
22234 (defun org-uuidgen-p (s)
22235 "Is S an ID created by UUIDGEN?"
22236 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22238 (defun org-in-src-block-p (&optional inside)
22239 "Whether point is in a code source block.
22240 When INSIDE is non-nil, don't consider we are within a src block
22241 when point is at #+BEGIN_SRC or #+END_SRC."
22242 (let ((case-fold-search t))
22243 (or (and (eq (get-char-property (point) 'src-block) t))
22244 (and (not inside)
22245 (save-match-data
22246 (save-excursion
22247 (beginning-of-line)
22248 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22250 (defun org-context ()
22251 "Return a list of contexts of the current cursor position.
22252 If several contexts apply, all are returned.
22253 Each context entry is a list with a symbol naming the context, and
22254 two positions indicating start and end of the context. Possible
22255 contexts are:
22257 :headline anywhere in a headline
22258 :headline-stars on the leading stars in a headline
22259 :todo-keyword on a TODO keyword (including DONE) in a headline
22260 :tags on the TAGS in a headline
22261 :priority on the priority cookie in a headline
22262 :item on the first line of a plain list item
22263 :item-bullet on the bullet/number of a plain list item
22264 :checkbox on the checkbox in a plain list item
22265 :table in an Org table
22266 :table-special on a special filed in a table
22267 :table-table in a table.el table
22268 :clocktable in a clocktable
22269 :src-block in a source block
22270 :link on a hyperlink
22271 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22272 :target on a <<target>>
22273 :radio-target on a <<<radio-target>>>
22274 :latex-fragment on a LaTeX fragment
22275 :latex-preview on a LaTeX fragment with overlaid preview image
22277 This function expects the position to be visible because it uses font-lock
22278 faces as a help to recognize the following contexts: :table-special, :link,
22279 and :keyword."
22280 (let* ((f (get-text-property (point) 'face))
22281 (faces (if (listp f) f (list f)))
22282 (case-fold-search t)
22283 (p (point)) clist o)
22284 ;; First the large context
22285 (cond
22286 ((org-at-heading-p t)
22287 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22288 (when (progn
22289 (beginning-of-line 1)
22290 (looking-at org-todo-line-tags-regexp))
22291 (push (org-point-in-group p 1 :headline-stars) clist)
22292 (push (org-point-in-group p 2 :todo-keyword) clist)
22293 (push (org-point-in-group p 4 :tags) clist))
22294 (goto-char p)
22295 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22296 (when (looking-at "\\[#[A-Z0-9]\\]")
22297 (push (org-point-in-group p 0 :priority) clist)))
22299 ((org-at-item-p)
22300 (push (org-point-in-group p 2 :item-bullet) clist)
22301 (push (list :item (point-at-bol)
22302 (save-excursion (org-end-of-item) (point)))
22303 clist)
22304 (and (org-at-item-checkbox-p)
22305 (push (org-point-in-group p 0 :checkbox) clist)))
22307 ((org-at-table-p)
22308 (push (list :table (org-table-begin) (org-table-end)) clist)
22309 (when (memq 'org-formula faces)
22310 (push (list :table-special
22311 (previous-single-property-change p 'face)
22312 (next-single-property-change p 'face)) clist)))
22313 ((org-at-table-p 'any)
22314 (push (list :table-table) clist)))
22315 (goto-char p)
22317 (let ((case-fold-search t))
22318 ;; New the "medium" contexts: clocktables, source blocks
22319 (cond ((org-in-clocktable-p)
22320 (push (list :clocktable
22321 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22322 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22323 (match-beginning 1))
22324 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22325 (match-end 0))) clist))
22326 ((org-in-src-block-p)
22327 (push (list :src-block
22328 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22329 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22330 (match-beginning 1))
22331 (and (search-forward "#+END_SRC" nil t)
22332 (match-beginning 0))) clist))))
22333 (goto-char p)
22335 ;; Now the small context
22336 (cond
22337 ((org-at-timestamp-p)
22338 (push (org-point-in-group p 0 :timestamp) clist))
22339 ((memq 'org-link faces)
22340 (push (list :link
22341 (previous-single-property-change p 'face)
22342 (next-single-property-change p 'face)) clist))
22343 ((memq 'org-special-keyword faces)
22344 (push (list :keyword
22345 (previous-single-property-change p 'face)
22346 (next-single-property-change p 'face)) clist))
22347 ((org-at-target-p)
22348 (push (org-point-in-group p 0 :target) clist)
22349 (goto-char (1- (match-beginning 0)))
22350 (when (looking-at org-radio-target-regexp)
22351 (push (org-point-in-group p 0 :radio-target) clist))
22352 (goto-char p))
22353 ((setq o (cl-some
22354 (lambda (o)
22355 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22357 (overlays-at (point))))
22358 (push (list :latex-fragment
22359 (overlay-start o) (overlay-end o)) clist)
22360 (push (list :latex-preview
22361 (overlay-start o) (overlay-end o)) clist))
22362 ((org-inside-LaTeX-fragment-p)
22363 ;; FIXME: positions wrong.
22364 (push (list :latex-fragment (point) (point)) clist)))
22366 (setq clist (nreverse (delq nil clist)))
22367 clist))
22369 (defun org-in-regexp (regexp &optional nlines visually)
22370 "Check if point is inside a match of REGEXP.
22372 Normally only the current line is checked, but you can include
22373 NLINES extra lines around point into the search. If VISUALLY is
22374 set, require that the cursor is not after the match but really
22375 on, so that the block visually is on the match.
22377 Return nil or a cons cell (BEG . END) where BEG and END are,
22378 respectively, the positions at the beginning and the end of the
22379 match."
22380 (catch :exit
22381 (let ((pos (point))
22382 (eol (line-end-position (if nlines (1+ nlines) 1))))
22383 (save-excursion
22384 (beginning-of-line (- 1 (or nlines 0)))
22385 (while (and (re-search-forward regexp eol t)
22386 (<= (match-beginning 0) pos))
22387 (let ((end (match-end 0)))
22388 (when (or (> end pos) (and (= end pos) (not visually)))
22389 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22391 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22392 "Non-nil when point is between matches of START-RE and END-RE.
22394 Also return a non-nil value when point is on one of the matches.
22396 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22397 buffer positions. Default values are the positions of headlines
22398 surrounding the point.
22400 The functions returns a cons cell whose car (resp. cdr) is the
22401 position before START-RE (resp. after END-RE)."
22402 (save-match-data
22403 (let ((pos (point))
22404 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22405 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22406 beg end)
22407 (save-excursion
22408 ;; Point is on a block when on START-RE or if START-RE can be
22409 ;; found before it...
22410 (and (or (org-in-regexp start-re)
22411 (re-search-backward start-re limit-up t))
22412 (setq beg (match-beginning 0))
22413 ;; ... and END-RE after it...
22414 (goto-char (match-end 0))
22415 (re-search-forward end-re limit-down t)
22416 (> (setq end (match-end 0)) pos)
22417 ;; ... without another START-RE in-between.
22418 (goto-char (match-beginning 0))
22419 (not (re-search-backward start-re (1+ beg) t))
22420 ;; Return value.
22421 (cons beg end))))))
22423 (defun org-in-block-p (names)
22424 "Non-nil when point belongs to a block whose name belongs to NAMES.
22426 NAMES is a list of strings containing names of blocks.
22428 Return first block name matched, or nil. Beware that in case of
22429 nested blocks, the returned name may not belong to the closest
22430 block from point."
22431 (save-match-data
22432 (catch 'exit
22433 (let ((case-fold-search t)
22434 (lim-up (save-excursion (outline-previous-heading)))
22435 (lim-down (save-excursion (outline-next-heading))))
22436 (dolist (name names)
22437 (let ((n (regexp-quote name)))
22438 (when (org-between-regexps-p
22439 (concat "^[ \t]*#\\+begin_" n)
22440 (concat "^[ \t]*#\\+end_" n)
22441 lim-up lim-down)
22442 (throw 'exit n)))))
22443 nil)))
22445 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22446 "Call `multi-occur' with buffers for all agenda files."
22447 (interactive "sOrg-files matching: ")
22448 (let* ((files (org-agenda-files))
22449 (tnames (mapcar #'file-truename files))
22450 (extra org-agenda-text-search-extra-files))
22451 (when (eq (car extra) 'agenda-archives)
22452 (setq extra (cdr extra))
22453 (setq files (org-add-archive-files files)))
22454 (dolist (f extra)
22455 (unless (member (file-truename f) tnames)
22456 (unless (member f files) (setq files (append files (list f))))
22457 (setq tnames (append tnames (list (file-truename f))))))
22458 (multi-occur
22459 (mapcar (lambda (x)
22460 (with-current-buffer
22461 ;; FIXME: Why not just (find-file-noselect x)?
22462 ;; Is it to avoid the "revert buffer" prompt?
22463 (or (get-file-buffer x) (find-file-noselect x))
22464 (widen)
22465 (current-buffer)))
22466 files)
22467 regexp)))
22469 (add-hook 'occur-mode-find-occurrence-hook
22470 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22472 (defun org-occur-link-in-agenda-files ()
22473 "Create a link and search for it in the agendas.
22474 The link is not stored in `org-stored-links', it is just created
22475 for the search purpose."
22476 (interactive)
22477 (let ((link (condition-case nil
22478 (org-store-link nil)
22479 (error "Unable to create a link to here"))))
22480 (org-occur-in-agenda-files (regexp-quote link))))
22482 (defun org-reverse-string (string)
22483 "Return the reverse of STRING."
22484 (apply 'string (reverse (string-to-list string))))
22486 ;; defsubst org-uniquify must be defined before first use
22488 (defun org-uniquify-alist (alist)
22489 "Merge elements of ALIST with the same key.
22491 For example, in this alist:
22493 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22494 => \\='((a 1 3) (b 2))
22496 merge (a 1) and (a 3) into (a 1 3).
22498 The function returns the new ALIST."
22499 (let (rtn)
22500 (dolist (e alist rtn)
22501 (let (n)
22502 (if (not (assoc (car e) rtn))
22503 (push e rtn)
22504 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22505 (setq rtn (assq-delete-all (car e) rtn))
22506 (push n rtn))))))
22508 (defun org-delete-all (elts list)
22509 "Remove all elements in ELTS from LIST.
22510 Comparison is done with `equal'. It is a destructive operation
22511 that may remove elements by altering the list structure."
22512 (while elts
22513 (setq list (delete (pop elts) list)))
22514 list)
22516 (defun org-back-over-empty-lines ()
22517 "Move backwards over whitespace, to the beginning of the first empty line.
22518 Returns the number of empty lines passed."
22519 (let ((pos (point)))
22520 (if (cdr (assq 'heading org-blank-before-new-entry))
22521 (skip-chars-backward " \t\n\r")
22522 (unless (eobp)
22523 (forward-line -1)))
22524 (beginning-of-line 2)
22525 (goto-char (min (point) pos))
22526 (count-lines (point) pos)))
22528 (defun org-skip-whitespace ()
22529 (skip-chars-forward " \t\n\r"))
22531 (defun org-point-in-group (point group &optional context)
22532 "Check if POINT is in match-group GROUP.
22533 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22534 match. If the match group does not exist or point is not inside it,
22535 return nil."
22536 (and (match-beginning group)
22537 (>= point (match-beginning group))
22538 (<= point (match-end group))
22539 (if context
22540 (list context (match-beginning group) (match-end group))
22541 t)))
22543 (defun org-switch-to-buffer-other-window (&rest args)
22544 "Switch to buffer in a second window on the current frame.
22545 In particular, do not allow pop-up frames.
22546 Returns the newly created buffer."
22547 (org-no-popups
22548 (apply 'switch-to-buffer-other-window args)))
22550 (defun org-combine-plists (&rest plists)
22551 "Create a single property list from all plists in PLISTS.
22552 The process starts by copying the first list, and then setting properties
22553 from the other lists. Settings in the last list are the most significant
22554 ones and overrule settings in the other lists."
22555 (let ((rtn (copy-sequence (pop plists)))
22556 p v ls)
22557 (while plists
22558 (setq ls (pop plists))
22559 (while ls
22560 (setq p (pop ls) v (pop ls))
22561 (setq rtn (plist-put rtn p v))))
22562 rtn))
22564 (defun org-replace-escapes (string table)
22565 "Replace %-escapes in STRING with values in TABLE.
22566 TABLE is an association list with keys like \"%a\" and string values.
22567 The sequences in STRING may contain normal field width and padding information,
22568 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22569 so values can contain further %-escapes if they are define later in TABLE."
22570 (let ((tbl (copy-alist table))
22571 (case-fold-search nil)
22572 (pchg 0)
22573 re rpl)
22574 (dolist (e tbl)
22575 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22576 (when (and (cdr e) (string-match re (cdr e)))
22577 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22578 (safe "SREF"))
22579 (add-text-properties 0 3 (list 'sref sref) safe)
22580 (setcdr e (replace-match safe t t (cdr e)))))
22581 (while (string-match re string)
22582 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22583 (cdr e)))
22584 (setq string (replace-match rpl t t string))))
22585 (while (setq pchg (next-property-change pchg string))
22586 (let ((sref (get-text-property pchg 'sref string)))
22587 (when (and sref (string-match "SREF" string pchg))
22588 (setq string (replace-match sref t t string)))))
22589 string))
22591 (defun org-find-base-buffer-visiting (file)
22592 "Like `find-buffer-visiting' but always return the base buffer and
22593 not an indirect buffer."
22594 (let ((buf (or (get-file-buffer file)
22595 (find-buffer-visiting file))))
22596 (if buf
22597 (or (buffer-base-buffer buf) buf)
22598 nil)))
22600 ;;; TODO: Only called once, from ox-odt which should probably use
22601 ;;; org-export-inline-image-p or something.
22602 (defun org-file-image-p (file)
22603 "Return non-nil if FILE is an image."
22604 (save-match-data
22605 (string-match (image-file-name-regexp) file)))
22607 (defun org-get-cursor-date (&optional with-time)
22608 "Return the date at cursor in as a time.
22609 This works in the calendar and in the agenda, anywhere else it just
22610 returns the current time.
22611 If WITH-TIME is non-nil, returns the time of the event at point (in
22612 the agenda) or the current time of the day."
22613 (let (date day defd tp hod mod)
22614 (when with-time
22615 (setq tp (get-text-property (point) 'time))
22616 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22617 (setq hod (string-to-number (match-string 1 tp))
22618 mod (string-to-number (match-string 2 tp))))
22619 (or tp (let ((now (decode-time)))
22620 (setq hod (nth 2 now)
22621 mod (nth 1 now)))))
22622 (cond
22623 ((eq major-mode 'calendar-mode)
22624 (setq date (calendar-cursor-to-date)
22625 defd (encode-time 0 (or mod 0) (or hod 0)
22626 (nth 1 date) (nth 0 date) (nth 2 date))))
22627 ((eq major-mode 'org-agenda-mode)
22628 (setq day (get-text-property (point) 'day))
22629 (when day
22630 (setq date (calendar-gregorian-from-absolute day)
22631 defd (encode-time 0 (or mod 0) (or hod 0)
22632 (nth 1 date) (nth 0 date) (nth 2 date))))))
22633 (or defd (current-time))))
22635 (defun org-mark-subtree (&optional up)
22636 "Mark the current subtree.
22637 This puts point at the start of the current subtree, and mark at
22638 the end. If a numeric prefix UP is given, move up into the
22639 hierarchy of headlines by UP levels before marking the subtree."
22640 (interactive "P")
22641 (org-with-limited-levels
22642 (cond ((org-at-heading-p) (beginning-of-line))
22643 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22644 (t (outline-previous-visible-heading 1))))
22645 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22646 (if (called-interactively-p 'any)
22647 (call-interactively 'org-mark-element)
22648 (org-mark-element)))
22650 (defun org-file-newer-than-p (file time)
22651 "Non-nil if FILE is newer than TIME.
22652 FILE is a filename, as a string, TIME is a list of integers, as
22653 returned by, e.g., `current-time'."
22654 (and (file-exists-p file)
22655 ;; Only compare times up to whole seconds as some file-systems
22656 ;; (e.g. HFS+) do not retain any finer granularity. As
22657 ;; a consequence, make sure we return non-nil when the two
22658 ;; times are equal.
22659 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22660 (cl-subseq time 0 2)))))
22662 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22663 "Compile a SOURCE file using PROCESS.
22665 PROCESS is either a function or a list of shell commands, as
22666 strings. EXT is a file extension, without the leading dot, as
22667 a string. It is used to check if the process actually succeeded.
22669 PROCESS must create a file with the same base name and directory
22670 as SOURCE, but ending with EXT. The function then returns its
22671 filename. Otherwise, it raises an error. The error message can
22672 then be refined by providing string ERR-MSG, which is appended to
22673 the standard message.
22675 If PROCESS is a function, it is called with a single argument:
22676 the SOURCE file.
22678 If it is a list of commands, each of them is called using
22679 `shell-command'. By default, in each command, %b, %f, %F and %o
22680 are replaced with, respectively, SOURCE base name, name, full
22681 name and directory. It is possible, however, to use more
22682 place-holders by specifying them in optional argument SPEC, as an
22683 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22685 When PROCESS is a list of commands, optional argument LOG-BUF can
22686 be set to a buffer or a buffer name. `shell-command' then uses
22687 it for output.
22689 `default-directory' is set to SOURCE directory during the whole
22690 process."
22691 (let* ((source-name (file-name-nondirectory source))
22692 (base-name (file-name-sans-extension source-name))
22693 (full-name (file-truename source))
22694 (out-dir (file-name-directory source))
22695 (time (current-time))
22696 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22697 (save-window-excursion
22698 (let ((default-directory (file-name-directory full-name)))
22699 (pcase process
22700 ((pred functionp) (funcall process (shell-quote-argument source)))
22701 ((pred consp)
22702 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22703 (spec (append spec
22704 `((?b . ,(shell-quote-argument base-name))
22705 (?f . ,(shell-quote-argument source-name))
22706 (?F . ,(shell-quote-argument full-name))
22707 (?o . ,(shell-quote-argument out-dir))))))
22708 (dolist (command process)
22709 (shell-command (format-spec command spec) log-buf))))
22710 (_ (error "No valid command to process %S%s" source err-msg)))))
22711 ;; Check for process failure.
22712 (let ((output (concat out-dir base-name "." ext)))
22713 (unless (org-file-newer-than-p output time)
22714 (error (format "File %S wasn't produced%s" output err-msg)))
22715 output)))
22717 ;;; Indentation
22719 (defun org--get-expected-indentation (element contentsp)
22720 "Expected indentation column for current line, according to ELEMENT.
22721 ELEMENT is an element containing point. CONTENTSP is non-nil
22722 when indentation is to be computed according to contents of
22723 ELEMENT."
22724 (let ((type (org-element-type element))
22725 (start (org-element-property :begin element))
22726 (post-affiliated (org-element-property :post-affiliated element)))
22727 (org-with-wide-buffer
22728 (cond
22729 (contentsp
22730 (cl-case type
22731 ((diary-sexp footnote-definition) 0)
22732 ((headline inlinetask nil)
22733 (if (not org-adapt-indentation) 0
22734 (let ((level (org-current-level)))
22735 (if level (1+ level) 0))))
22736 ((item plain-list) (org-list-item-body-column post-affiliated))
22738 (goto-char start)
22739 (org-get-indentation))))
22740 ((memq type '(headline inlinetask nil))
22741 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22742 (org--get-expected-indentation element t)
22744 ((memq type '(diary-sexp footnote-definition)) 0)
22745 ;; First paragraph of a footnote definition or an item.
22746 ;; Indent like parent.
22747 ((< (line-beginning-position) start)
22748 (org--get-expected-indentation
22749 (org-element-property :parent element) t))
22750 ;; At first line: indent according to previous sibling, if any,
22751 ;; ignoring footnote definitions and inline tasks, or parent's
22752 ;; contents.
22753 ((= (line-beginning-position) start)
22754 (catch 'exit
22755 (while t
22756 (if (= (point-min) start) (throw 'exit 0)
22757 (goto-char (1- start))
22758 (let* ((previous (org-element-at-point))
22759 (parent previous))
22760 (while (and parent (<= (org-element-property :end parent) start))
22761 (setq previous parent
22762 parent (org-element-property :parent parent)))
22763 (cond
22764 ((not previous) (throw 'exit 0))
22765 ((> (org-element-property :end previous) start)
22766 (throw 'exit (org--get-expected-indentation previous t)))
22767 ((memq (org-element-type previous)
22768 '(footnote-definition inlinetask))
22769 (setq start (org-element-property :begin previous)))
22770 (t (goto-char (org-element-property :begin previous))
22771 (throw 'exit
22772 (if (bolp) (org-get-indentation)
22773 ;; At first paragraph in an item or
22774 ;; a footnote definition.
22775 (org--get-expected-indentation
22776 (org-element-property :parent previous) t))))))))))
22777 ;; Otherwise, move to the first non-blank line above.
22779 (beginning-of-line)
22780 (let ((pos (point)))
22781 (skip-chars-backward " \r\t\n")
22782 (cond
22783 ;; Two blank lines end a footnote definition or a plain
22784 ;; list. When we indent an empty line after them, the
22785 ;; containing list or footnote definition is over, so it
22786 ;; qualifies as a previous sibling. Therefore, we indent
22787 ;; like its first line.
22788 ((and (memq type '(footnote-definition plain-list))
22789 (> (count-lines (point) pos) 2))
22790 (goto-char start)
22791 (org-get-indentation))
22792 ;; Line above is the first one of a paragraph at the
22793 ;; beginning of an item or a footnote definition. Indent
22794 ;; like parent.
22795 ((< (line-beginning-position) start)
22796 (org--get-expected-indentation
22797 (org-element-property :parent element) t))
22798 ;; Line above is the beginning of an element, i.e., point
22799 ;; was originally on the blank lines between element's start
22800 ;; and contents.
22801 ((= (line-beginning-position) post-affiliated)
22802 (org--get-expected-indentation element t))
22803 ;; POS is after contents in a greater element. Indent like
22804 ;; the beginning of the element.
22806 ;; As a special case, if point is at the end of a footnote
22807 ;; definition or an item, indent like the very last element
22808 ;; within. If that last element is an item, indent like its
22809 ;; contents.
22810 ((and (not (eq type 'paragraph))
22811 (let ((cend (org-element-property :contents-end element)))
22812 (and cend (<= cend pos))))
22813 (if (memq type '(footnote-definition item plain-list))
22814 (let ((last (org-element-at-point)))
22815 (org--get-expected-indentation
22816 last (eq (org-element-type last) 'item)))
22817 (goto-char start)
22818 (org-get-indentation)))
22819 ;; In any other case, indent like the current line.
22820 (t (org-get-indentation)))))))))
22822 (defun org--align-node-property ()
22823 "Align node property at point.
22824 Alignment is done according to `org-property-format', which see."
22825 (when (save-excursion
22826 (beginning-of-line)
22827 (looking-at org-property-re))
22828 (replace-match
22829 (concat (match-string 4)
22830 (org-trim
22831 (format org-property-format (match-string 1) (match-string 3))))
22832 t t)))
22834 (defun org-indent-line ()
22835 "Indent line depending on context.
22837 Indentation is done according to the following rules:
22839 - Footnote definitions, diary sexps, headlines and inline tasks
22840 have to start at column 0.
22842 - On the very first line of an element, consider, in order, the
22843 next rules until one matches:
22845 1. If there's a sibling element before, ignoring footnote
22846 definitions and inline tasks, indent like its first line.
22848 2. If element has a parent, indent like its contents. More
22849 precisely, if parent is an item, indent after the
22850 description part, if any, or the bullet (see
22851 `org-list-description-max-indent'). Else, indent like
22852 parent's first line.
22854 3. Otherwise, indent relatively to current level, if
22855 `org-adapt-indentation' is non-nil, or to left margin.
22857 - On a blank line at the end of an element, indent according to
22858 the type of the element. More precisely
22860 1. If element is a plain list, an item, or a footnote
22861 definition, indent like the very last element within.
22863 2. If element is a paragraph, indent like its last non blank
22864 line.
22866 3. Otherwise, indent like its very first line.
22868 - In the code part of a source block, use language major mode
22869 to indent current line if `org-src-tab-acts-natively' is
22870 non-nil. If it is nil, do nothing.
22872 - Otherwise, indent like the first non-blank line above.
22874 The function doesn't indent an item as it could break the whole
22875 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22876 \\[org-shiftmetaright].
22878 Also align node properties according to `org-property-format'."
22879 (interactive)
22880 (cond
22881 (orgstruct-is-++
22882 (let ((indent-line-function
22883 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22884 (indent-according-to-mode)))
22885 ((org-at-heading-p) 'noindent)
22887 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22888 (type (org-element-type element)))
22889 (cond ((and (memq type '(plain-list item))
22890 (= (line-beginning-position)
22891 (org-element-property :post-affiliated element)))
22892 'noindent)
22893 ((and (eq type 'src-block)
22894 org-src-tab-acts-natively
22895 (> (line-beginning-position)
22896 (org-element-property :post-affiliated element))
22897 (< (line-beginning-position)
22898 (org-with-wide-buffer
22899 (goto-char (org-element-property :end element))
22900 (skip-chars-backward " \r\t\n")
22901 (line-beginning-position))))
22902 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22904 (let ((column (org--get-expected-indentation element nil)))
22905 ;; Preserve current column.
22906 (if (<= (current-column) (current-indentation))
22907 (indent-line-to column)
22908 (save-excursion (indent-line-to column))))
22909 ;; Align node property. Also preserve current column.
22910 (when (eq type 'node-property)
22911 (let ((column (current-column)))
22912 (org--align-node-property)
22913 (org-move-to-column column)))))))))
22915 (defun org-indent-region (start end)
22916 "Indent each non-blank line in the region.
22917 Called from a program, START and END specify the region to
22918 indent. The function will not indent contents of example blocks,
22919 verse blocks and export blocks as leading white spaces are
22920 assumed to be significant there."
22921 (interactive "r")
22922 (save-excursion
22923 (goto-char start)
22924 (skip-chars-forward " \r\t\n")
22925 (unless (eobp) (beginning-of-line))
22926 (let ((indent-to
22927 (lambda (ind pos)
22928 ;; Set IND as indentation for all lines between point and
22929 ;; POS. Blank lines are ignored. Leave point after POS
22930 ;; once done.
22931 (let ((limit (copy-marker pos)))
22932 (while (< (point) limit)
22933 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22934 (forward-line))
22935 (set-marker limit nil))))
22936 (end (copy-marker end)))
22937 (while (< (point) end)
22938 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22939 (let* ((element (org-element-at-point))
22940 (type (org-element-type element))
22941 (element-end (copy-marker (org-element-property :end element)))
22942 (ind (org--get-expected-indentation element nil)))
22943 (cond
22944 ((or (memq type '(paragraph table table-row))
22945 (not (or (org-element-property :contents-begin element)
22946 (memq type
22947 '(example-block export-block src-block)))))
22948 ;; Elements here are indented as a single block. Also
22949 ;; align node properties.
22950 (when (eq type 'node-property)
22951 (org--align-node-property)
22952 (beginning-of-line))
22953 (funcall indent-to ind (min element-end end)))
22955 ;; Elements in this category consist of three parts:
22956 ;; before the contents, the contents, and after the
22957 ;; contents. The contents are treated specially,
22958 ;; according to the element type, or not indented at
22959 ;; all. Other parts are indented as a single block.
22960 (let* ((post (copy-marker
22961 (org-element-property :post-affiliated element)))
22962 (cbeg
22963 (copy-marker
22964 (cond
22965 ((not (org-element-property :contents-begin element))
22966 ;; Fake contents for source blocks.
22967 (org-with-wide-buffer
22968 (goto-char post)
22969 (forward-line)
22970 (point)))
22971 ((memq type '(footnote-definition item plain-list))
22972 ;; Contents in these elements could start on
22973 ;; the same line as the beginning of the
22974 ;; element. Make sure we start indenting
22975 ;; from the second line.
22976 (org-with-wide-buffer
22977 (goto-char post)
22978 (end-of-line)
22979 (skip-chars-forward " \r\t\n")
22980 (if (eobp) (point) (line-beginning-position))))
22981 (t (org-element-property :contents-begin element)))))
22982 (cend (copy-marker
22983 (or (org-element-property :contents-end element)
22984 ;; Fake contents for source blocks.
22985 (org-with-wide-buffer
22986 (goto-char element-end)
22987 (skip-chars-backward " \r\t\n")
22988 (line-beginning-position)))
22989 t)))
22990 ;; Do not change items indentation individually as it
22991 ;; might break the list as a whole. On the other
22992 ;; hand, when at a plain list, indent it as a whole.
22993 (cond ((eq type 'plain-list)
22994 (let ((offset (- ind (org-get-indentation))))
22995 (unless (zerop offset)
22996 (indent-rigidly (org-element-property :begin element)
22997 (org-element-property :end element)
22998 offset))
22999 (goto-char cbeg)))
23000 ((eq type 'item) (goto-char cbeg))
23001 (t (funcall indent-to ind (min cbeg end))))
23002 (when (< (point) end)
23003 (cl-case type
23004 ((example-block export-block verse-block))
23005 (src-block
23006 ;; In a source block, indent source code
23007 ;; according to language major mode, but only if
23008 ;; `org-src-tab-acts-natively' is non-nil.
23009 (when (and (< (point) end) org-src-tab-acts-natively)
23010 (ignore-errors
23011 (org-babel-do-in-edit-buffer
23012 (indent-region (point-min) (point-max))))))
23013 (t (org-indent-region (point) (min cend end))))
23014 (goto-char (min cend end))
23015 (when (< (point) end)
23016 (funcall indent-to ind (min element-end end))))
23017 (set-marker post nil)
23018 (set-marker cbeg nil)
23019 (set-marker cend nil))))
23020 (set-marker element-end nil))))
23021 (set-marker end nil))))
23023 (defun org-indent-drawer ()
23024 "Indent the drawer at point."
23025 (interactive)
23026 (unless (save-excursion
23027 (beginning-of-line)
23028 (looking-at-p org-drawer-regexp))
23029 (user-error "Not at a drawer"))
23030 (let ((element (org-element-at-point)))
23031 (unless (memq (org-element-type element) '(drawer property-drawer))
23032 (user-error "Not at a drawer"))
23033 (org-with-wide-buffer
23034 (org-indent-region (org-element-property :begin element)
23035 (org-element-property :end element))))
23036 (message "Drawer at point indented"))
23038 (defun org-indent-block ()
23039 "Indent the block at point."
23040 (interactive)
23041 (unless (save-excursion
23042 (beginning-of-line)
23043 (let ((case-fold-search t))
23044 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23045 (user-error "Not at a block"))
23046 (let ((element (org-element-at-point)))
23047 (unless (memq (org-element-type element)
23048 '(comment-block center-block dynamic-block example-block
23049 export-block quote-block special-block
23050 src-block verse-block))
23051 (user-error "Not at a block"))
23052 (org-with-wide-buffer
23053 (org-indent-region (org-element-property :begin element)
23054 (org-element-property :end element))))
23055 (message "Block at point indented"))
23058 ;;; Filling
23060 ;; We use our own fill-paragraph and auto-fill functions.
23062 ;; `org-fill-paragraph' relies on adaptive filling and context
23063 ;; checking. Appropriate `fill-prefix' is computed with
23064 ;; `org-adaptive-fill-function'.
23066 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23067 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23068 ;; `org-adaptive-fill-function' value. Internally,
23069 ;; `org-comment-line-break-function' breaks the line.
23071 ;; `org-setup-filling' installs filling and auto-filling related
23072 ;; variables during `org-mode' initialization.
23074 (defvar org-element-paragraph-separate) ; org-element.el
23075 (defun org-setup-filling ()
23076 (require 'org-element)
23077 ;; Prevent auto-fill from inserting unwanted new items.
23078 (when (boundp 'fill-nobreak-predicate)
23079 (setq-local
23080 fill-nobreak-predicate
23081 (org-uniquify
23082 (append fill-nobreak-predicate
23083 '(org-fill-line-break-nobreak-p
23084 org-fill-paragraph-with-timestamp-nobreak-p)))))
23085 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23086 (setq-local paragraph-start paragraph-ending)
23087 (setq-local paragraph-separate paragraph-ending))
23088 (setq-local fill-paragraph-function 'org-fill-paragraph)
23089 (setq-local auto-fill-inhibit-regexp nil)
23090 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23091 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23092 (setq-local comment-line-break-function 'org-comment-line-break-function))
23094 (defun org-fill-line-break-nobreak-p ()
23095 "Non-nil when a new line at point would create an Org line break."
23096 (save-excursion
23097 (skip-chars-backward "[ \t]")
23098 (skip-chars-backward "\\\\")
23099 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23101 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23102 "Non-nil when a new line at point would split a timestamp."
23103 (and (org-at-timestamp-p t)
23104 (not (looking-at org-ts-regexp-both))))
23106 (declare-function message-in-body-p "message" ())
23107 (defvar orgtbl-line-start-regexp) ; From org-table.el
23108 (defun org-adaptive-fill-function ()
23109 "Compute a fill prefix for the current line.
23110 Return fill prefix, as a string, or nil if current line isn't
23111 meant to be filled. For convenience, if `adaptive-fill-regexp'
23112 matches in paragraphs or comments, use it."
23113 (catch 'exit
23114 (when (derived-mode-p 'message-mode)
23115 (save-excursion
23116 (beginning-of-line)
23117 (cond ((not (message-in-body-p)) (throw 'exit nil))
23118 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23119 ((looking-at message-cite-prefix-regexp)
23120 (throw 'exit (match-string-no-properties 0)))
23121 ((looking-at org-outline-regexp)
23122 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23123 (org-with-wide-buffer
23124 (unless (org-at-heading-p)
23125 (let* ((p (line-beginning-position))
23126 (element (save-excursion
23127 (beginning-of-line)
23128 (org-element-at-point)))
23129 (type (org-element-type element))
23130 (post-affiliated (org-element-property :post-affiliated element)))
23131 (unless (< p post-affiliated)
23132 (cl-case type
23133 (comment
23134 (save-excursion
23135 (beginning-of-line)
23136 (looking-at "[ \t]*")
23137 (concat (match-string 0) "# ")))
23138 (footnote-definition "")
23139 ((item plain-list)
23140 (make-string (org-list-item-body-column post-affiliated) ?\s))
23141 (paragraph
23142 ;; Fill prefix is usually the same as the current line,
23143 ;; unless the paragraph is at the beginning of an item.
23144 (let ((parent (org-element-property :parent element)))
23145 (save-excursion
23146 (beginning-of-line)
23147 (cond ((eq (org-element-type parent) 'item)
23148 (make-string (org-list-item-body-column
23149 (org-element-property :begin parent))
23150 ?\s))
23151 ((and adaptive-fill-regexp
23152 ;; Locally disable
23153 ;; `adaptive-fill-function' to let
23154 ;; `fill-context-prefix' handle
23155 ;; `adaptive-fill-regexp' variable.
23156 (let (adaptive-fill-function)
23157 (fill-context-prefix
23158 post-affiliated
23159 (org-element-property :end element)))))
23160 ((looking-at "[ \t]+") (match-string 0))
23161 (t "")))))
23162 (comment-block
23163 ;; Only fill contents if P is within block boundaries.
23164 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23165 (forward-line)
23166 (point)))
23167 (cend (save-excursion
23168 (goto-char (org-element-property :end element))
23169 (skip-chars-backward " \r\t\n")
23170 (line-beginning-position))))
23171 (when (and (>= p cbeg) (< p cend))
23172 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23173 (match-string 0)
23174 "")))))))))))
23176 (declare-function message-goto-body "message" ())
23177 (defvar message-cite-prefix-regexp) ; From message.el
23178 (defun org-fill-paragraph (&optional justify)
23179 "Fill element at point, when applicable.
23181 This function only applies to comment blocks, comments, example
23182 blocks and paragraphs. Also, as a special case, re-align table
23183 when point is at one.
23185 If JUSTIFY is non-nil (interactively, with prefix argument),
23186 justify as well. If `sentence-end-double-space' is non-nil, then
23187 period followed by one space does not end a sentence, so don't
23188 break a line there. The variable `fill-column' controls the
23189 width for filling.
23191 For convenience, when point is at a plain list, an item or
23192 a footnote definition, try to fill the first paragraph within."
23193 (interactive)
23194 (if (and (derived-mode-p 'message-mode)
23195 (or (not (message-in-body-p))
23196 (save-excursion (move-beginning-of-line 1)
23197 (looking-at message-cite-prefix-regexp))))
23198 ;; First ensure filling is correct in message-mode.
23199 (let ((fill-paragraph-function
23200 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23201 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23202 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23203 (paragraph-separate
23204 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23205 (fill-paragraph nil))
23206 (with-syntax-table org-mode-transpose-word-syntax-table
23207 ;; Move to end of line in order to get the first paragraph
23208 ;; within a plain list or a footnote definition.
23209 (let ((element (save-excursion
23210 (end-of-line)
23211 (or (ignore-errors (org-element-at-point))
23212 (user-error "An element cannot be parsed line %d"
23213 (line-number-at-pos (point)))))))
23214 ;; First check if point is in a blank line at the beginning of
23215 ;; the buffer. In that case, ignore filling.
23216 (cl-case (org-element-type element)
23217 ;; Use major mode filling function is src blocks.
23218 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23219 ;; Align Org tables, leave table.el tables as-is.
23220 (table-row (org-table-align) t)
23221 (table
23222 (when (eq (org-element-property :type element) 'org)
23223 (save-excursion
23224 (goto-char (org-element-property :post-affiliated element))
23225 (org-table-align)))
23227 (paragraph
23228 ;; Paragraphs may contain `line-break' type objects.
23229 (let ((beg (max (point-min)
23230 (org-element-property :contents-begin element)))
23231 (end (min (point-max)
23232 (org-element-property :contents-end element))))
23233 ;; Do nothing if point is at an affiliated keyword.
23234 (if (< (line-end-position) beg) t
23235 (when (derived-mode-p 'message-mode)
23236 ;; In `message-mode', do not fill following citation
23237 ;; in current paragraph nor text before message body.
23238 (let ((body-start (save-excursion (message-goto-body))))
23239 (when body-start (setq beg (max body-start beg))))
23240 (when (save-excursion
23241 (re-search-forward
23242 (concat "^" message-cite-prefix-regexp) end t))
23243 (setq end (match-beginning 0))))
23244 ;; Fill paragraph, taking line breaks into account.
23245 (save-excursion
23246 (goto-char beg)
23247 (let ((cuts (list beg)))
23248 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23249 (when (eq 'line-break
23250 (org-element-type
23251 (save-excursion (backward-char)
23252 (org-element-context))))
23253 (push (point) cuts)))
23254 (dolist (c (delq end cuts))
23255 (fill-region-as-paragraph c end justify)
23256 (setq end c))))
23257 t)))
23258 ;; Contents of `comment-block' type elements should be
23259 ;; filled as plain text, but only if point is within block
23260 ;; markers.
23261 (comment-block
23262 (let* ((case-fold-search t)
23263 (beg (save-excursion
23264 (goto-char (org-element-property :begin element))
23265 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23266 (forward-line)
23267 (point)))
23268 (end (save-excursion
23269 (goto-char (org-element-property :end element))
23270 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23271 (line-beginning-position))))
23272 (if (or (< (point) beg) (> (point) end)) t
23273 (fill-region-as-paragraph
23274 (save-excursion (end-of-line)
23275 (re-search-backward "^[ \t]*$" beg 'move)
23276 (line-beginning-position))
23277 (save-excursion (beginning-of-line)
23278 (re-search-forward "^[ \t]*$" end 'move)
23279 (line-beginning-position))
23280 justify))))
23281 ;; Fill comments.
23282 (comment
23283 (let ((begin (org-element-property :post-affiliated element))
23284 (end (org-element-property :end element)))
23285 (when (and (>= (point) begin) (<= (point) end))
23286 (let ((begin (save-excursion
23287 (end-of-line)
23288 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23289 (progn (forward-line) (point))
23290 begin)))
23291 (end (save-excursion
23292 (end-of-line)
23293 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23294 (1- (line-beginning-position))
23295 (skip-chars-backward " \r\t\n")
23296 (line-end-position)))))
23297 ;; Do not fill comments when at a blank line.
23298 (when (> end begin)
23299 (let ((fill-prefix
23300 (save-excursion
23301 (beginning-of-line)
23302 (looking-at "[ \t]*#")
23303 (let ((comment-prefix (match-string 0)))
23304 (goto-char (match-end 0))
23305 (if (looking-at adaptive-fill-regexp)
23306 (concat comment-prefix (match-string 0))
23307 (concat comment-prefix " "))))))
23308 (save-excursion
23309 (fill-region-as-paragraph begin end justify))))))
23311 ;; Ignore every other element.
23312 (otherwise t))))))
23314 (defun org-auto-fill-function ()
23315 "Auto-fill function."
23316 ;; Check if auto-filling is meaningful.
23317 (let ((fc (current-fill-column)))
23318 (when (and fc (> (current-column) fc))
23319 (let* ((fill-prefix (org-adaptive-fill-function))
23320 ;; Enforce empty fill prefix, if required. Otherwise, it
23321 ;; will be computed again.
23322 (adaptive-fill-mode (not (equal fill-prefix ""))))
23323 (when fill-prefix (do-auto-fill))))))
23325 (defun org-comment-line-break-function (&optional soft)
23326 "Break line at point and indent, continuing comment if within one.
23327 The inserted newline is marked hard if variable
23328 `use-hard-newlines' is true, unless optional argument SOFT is
23329 non-nil."
23330 (if soft (insert-and-inherit ?\n) (newline 1))
23331 (save-excursion (forward-char -1) (delete-horizontal-space))
23332 (delete-horizontal-space)
23333 (indent-to-left-margin)
23334 (insert-before-markers-and-inherit fill-prefix))
23337 ;;; Fixed Width Areas
23339 (defun org-toggle-fixed-width ()
23340 "Toggle fixed-width markup.
23342 Add or remove fixed-width markup on current line, whenever it
23343 makes sense. Return an error otherwise.
23345 If a region is active and if it contains only fixed-width areas
23346 or blank lines, remove all fixed-width markup in it. If the
23347 region contains anything else, convert all non-fixed-width lines
23348 to fixed-width ones.
23350 Blank lines at the end of the region are ignored unless the
23351 region only contains such lines."
23352 (interactive)
23353 (if (not (org-region-active-p))
23354 ;; No region:
23356 ;; Remove fixed width marker only in a fixed-with element.
23358 ;; Add fixed width maker in paragraphs, in blank lines after
23359 ;; elements or at the beginning of a headline or an inlinetask,
23360 ;; and before any one-line elements (e.g., a clock).
23361 (progn
23362 (beginning-of-line)
23363 (let* ((element (org-element-at-point))
23364 (type (org-element-type element)))
23365 (cond
23366 ((and (eq type 'fixed-width)
23367 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23368 (replace-match
23369 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23370 ((and (memq type '(babel-call clock comment diary-sexp headline
23371 horizontal-rule keyword paragraph
23372 planning))
23373 (<= (org-element-property :post-affiliated element) (point)))
23374 (skip-chars-forward " \t")
23375 (insert ": "))
23376 ((and (looking-at-p "[ \t]*$")
23377 (or (eq type 'inlinetask)
23378 (save-excursion
23379 (skip-chars-forward " \r\t\n")
23380 (<= (org-element-property :end element) (point)))))
23381 (delete-region (point) (line-end-position))
23382 (org-indent-line)
23383 (insert ": "))
23384 (t (user-error "Cannot insert a fixed-width line here")))))
23385 ;; Region active.
23386 (let* ((begin (save-excursion
23387 (goto-char (region-beginning))
23388 (line-beginning-position)))
23389 (end (copy-marker
23390 (save-excursion
23391 (goto-char (region-end))
23392 (unless (eolp) (beginning-of-line))
23393 (if (save-excursion (re-search-backward "\\S-" begin t))
23394 (progn (skip-chars-backward " \r\t\n") (point))
23395 (point)))))
23396 (all-fixed-width-p
23397 (catch 'not-all-p
23398 (save-excursion
23399 (goto-char begin)
23400 (skip-chars-forward " \r\t\n")
23401 (when (eobp) (throw 'not-all-p nil))
23402 (while (< (point) end)
23403 (let ((element (org-element-at-point)))
23404 (if (eq (org-element-type element) 'fixed-width)
23405 (goto-char (org-element-property :end element))
23406 (throw 'not-all-p nil))))
23407 t))))
23408 (if all-fixed-width-p
23409 (save-excursion
23410 (goto-char begin)
23411 (while (< (point) end)
23412 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23413 (replace-match
23414 "" nil nil nil
23415 (if (= (line-end-position) (match-end 0)) 0 1)))
23416 (forward-line)))
23417 (let ((min-ind (point-max)))
23418 ;; Find minimum indentation across all lines.
23419 (save-excursion
23420 (goto-char begin)
23421 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23422 (setq min-ind 0)
23423 (catch 'zerop
23424 (while (< (point) end)
23425 (unless (looking-at-p "[ \t]*$")
23426 (let ((ind (org-get-indentation)))
23427 (setq min-ind (min min-ind ind))
23428 (when (zerop ind) (throw 'zerop t))))
23429 (forward-line)))))
23430 ;; Loop over all lines and add fixed-width markup everywhere
23431 ;; but in fixed-width lines.
23432 (save-excursion
23433 (goto-char begin)
23434 (while (< (point) end)
23435 (cond
23436 ((org-at-heading-p)
23437 (insert ": ")
23438 (forward-line)
23439 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23440 (insert ":")
23441 (forward-line)))
23442 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23443 (let* ((element (org-element-at-point))
23444 (element-end (org-element-property :end element)))
23445 (if (eq (org-element-type element) 'fixed-width)
23446 (progn (goto-char element-end)
23447 (skip-chars-backward " \r\t\n")
23448 (forward-line))
23449 (let ((limit (min end element-end)))
23450 (while (< (point) limit)
23451 (org-move-to-column min-ind t)
23452 (insert ": ")
23453 (forward-line))))))
23455 (org-move-to-column min-ind t)
23456 (insert ": ")
23457 (forward-line)))))))
23458 (set-marker end nil))))
23461 ;;; Comments
23463 ;; Org comments syntax is quite complex. It requires the entire line
23464 ;; to be just a comment. Also, even with the right syntax at the
23465 ;; beginning of line, some some elements (i.e. verse-block or
23466 ;; example-block) don't accept comments. Usual Emacs comment commands
23467 ;; cannot cope with those requirements. Therefore, Org replaces them.
23469 ;; Org still relies on `comment-dwim', but cannot trust
23470 ;; `comment-only-p'. So, `comment-region-function' and
23471 ;; `uncomment-region-function' both point
23472 ;; to`org-comment-or-uncomment-region'. Eventually,
23473 ;; `org-insert-comment' takes care of insertion of comments at the
23474 ;; beginning of line.
23476 ;; `org-setup-comments-handling' install comments related variables
23477 ;; during `org-mode' initialization.
23479 (defun org-setup-comments-handling ()
23480 (interactive)
23481 (setq-local comment-use-syntax nil)
23482 (setq-local comment-start "# ")
23483 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23484 (setq-local comment-insert-comment-function 'org-insert-comment)
23485 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23486 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23488 (defun org-insert-comment ()
23489 "Insert an empty comment above current line.
23490 If the line is empty, insert comment at its beginning. When
23491 point is within a source block, comment according to the related
23492 major mode."
23493 (if (let ((element (org-element-at-point)))
23494 (and (eq (org-element-type element) 'src-block)
23495 (< (save-excursion
23496 (goto-char (org-element-property :post-affiliated element))
23497 (line-end-position))
23498 (point))
23499 (> (save-excursion
23500 (goto-char (org-element-property :end element))
23501 (skip-chars-backward " \r\t\n")
23502 (line-beginning-position))
23503 (point))))
23504 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23505 (beginning-of-line)
23506 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23507 (open-line 1))
23508 (org-indent-line)
23509 (insert "# ")))
23511 (defvar comment-empty-lines) ; From newcomment.el.
23512 (defun org-comment-or-uncomment-region (beg end &rest _)
23513 "Comment or uncomment each non-blank line in the region.
23514 Uncomment each non-blank line between BEG and END if it only
23515 contains commented lines. Otherwise, comment them. If region is
23516 strictly within a source block, use appropriate comment syntax."
23517 (if (let ((element (org-element-at-point)))
23518 (and (eq (org-element-type element) 'src-block)
23519 (< (save-excursion
23520 (goto-char (org-element-property :post-affiliated element))
23521 (line-end-position))
23522 beg)
23523 (>= (save-excursion
23524 (goto-char (org-element-property :end element))
23525 (skip-chars-backward " \r\t\n")
23526 (line-beginning-position))
23527 end)))
23528 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23529 (save-restriction
23530 ;; Restrict region
23531 (narrow-to-region (save-excursion (goto-char beg)
23532 (skip-chars-forward " \r\t\n" end)
23533 (line-beginning-position))
23534 (save-excursion (goto-char end)
23535 (skip-chars-backward " \r\t\n" beg)
23536 (line-end-position)))
23537 (let ((uncommentp
23538 ;; UNCOMMENTP is non-nil when every non blank line between
23539 ;; BEG and END is a comment.
23540 (save-excursion
23541 (goto-char (point-min))
23542 (while (and (not (eobp))
23543 (let ((element (org-element-at-point)))
23544 (and (eq (org-element-type element) 'comment)
23545 (goto-char (min (point-max)
23546 (org-element-property
23547 :end element)))))))
23548 (eobp))))
23549 (if uncommentp
23550 ;; Only blank lines and comments in region: uncomment it.
23551 (save-excursion
23552 (goto-char (point-min))
23553 (while (not (eobp))
23554 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23555 (replace-match "" nil nil nil 1))
23556 (forward-line)))
23557 ;; Comment each line in region.
23558 (let ((min-indent (point-max)))
23559 ;; First find the minimum indentation across all lines.
23560 (save-excursion
23561 (goto-char (point-min))
23562 (while (and (not (eobp)) (not (zerop min-indent)))
23563 (unless (looking-at "[ \t]*$")
23564 (setq min-indent (min min-indent (current-indentation))))
23565 (forward-line)))
23566 ;; Then loop over all lines.
23567 (save-excursion
23568 (goto-char (point-min))
23569 (while (not (eobp))
23570 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23571 ;; Don't get fooled by invisible text (e.g. link path)
23572 ;; when moving to column MIN-INDENT.
23573 (let ((buffer-invisibility-spec nil))
23574 (org-move-to-column min-indent t))
23575 (insert comment-start))
23576 (forward-line)))))))))
23578 (defun org-comment-dwim (_arg)
23579 "Call `comment-dwim' within a source edit buffer if needed."
23580 (interactive "*P")
23581 (if (org-in-src-block-p)
23582 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23583 (call-interactively 'comment-dwim)))
23586 ;;; Timestamps API
23588 ;; This section contains tools to operate on timestamp objects, as
23589 ;; returned by, e.g. `org-element-context'.
23591 (defun org-timestamp--to-internal-time (timestamp &optional end)
23592 "Encode TIMESTAMP object into Emacs internal time.
23593 Use end of date range or time range when END is non-nil."
23594 (apply #'encode-time
23595 (cons 0
23596 (mapcar
23597 (lambda (prop) (or (org-element-property prop timestamp) 0))
23598 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23599 '(:minute-start :hour-start :day-start :month-start
23600 :year-start))))))
23602 (defun org-timestamp-has-time-p (timestamp)
23603 "Non-nil when TIMESTAMP has a time specified."
23604 (org-element-property :hour-start timestamp))
23606 (defun org-timestamp-format (timestamp format &optional end utc)
23607 "Format a TIMESTAMP object into a string.
23609 FORMAT is a format specifier to be passed to
23610 `format-time-string'.
23612 When optional argument END is non-nil, use end of date-range or
23613 time-range, if possible.
23615 When optional argument UTC is non-nil, time will be expressed as
23616 Universal Time."
23617 (format-time-string
23618 format (org-timestamp--to-internal-time timestamp end)
23619 (and utc t)))
23621 (defun org-timestamp-split-range (timestamp &optional end)
23622 "Extract a TIMESTAMP object from a date or time range.
23624 END, when non-nil, means extract the end of the range.
23625 Otherwise, extract its start.
23627 Return a new timestamp object."
23628 (let ((type (org-element-property :type timestamp)))
23629 (if (memq type '(active inactive diary)) timestamp
23630 (let ((split-ts (org-element-copy timestamp)))
23631 ;; Set new type.
23632 (org-element-put-property
23633 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23634 ;; Copy start properties over end properties if END is
23635 ;; non-nil. Otherwise, copy end properties over `start' ones.
23636 (let ((p-alist '((:minute-start . :minute-end)
23637 (:hour-start . :hour-end)
23638 (:day-start . :day-end)
23639 (:month-start . :month-end)
23640 (:year-start . :year-end))))
23641 (dolist (p-cell p-alist)
23642 (org-element-put-property
23643 split-ts
23644 (funcall (if end #'car #'cdr) p-cell)
23645 (org-element-property
23646 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23647 ;; Eventually refresh `:raw-value'.
23648 (org-element-put-property split-ts :raw-value nil)
23649 (org-element-put-property
23650 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23652 (defun org-timestamp-translate (timestamp &optional boundary)
23653 "Translate TIMESTAMP object to custom format.
23655 Format string is defined in `org-time-stamp-custom-formats',
23656 which see.
23658 When optional argument BOUNDARY is non-nil, it is either the
23659 symbol `start' or `end'. In this case, only translate the
23660 starting or ending part of TIMESTAMP if it is a date or time
23661 range. Otherwise, translate both parts.
23663 Return timestamp as-is if `org-display-custom-times' is nil or if
23664 it has a `diary' type."
23665 (let ((type (org-element-property :type timestamp)))
23666 (if (or (not org-display-custom-times) (eq type 'diary))
23667 (org-element-interpret-data timestamp)
23668 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23669 org-time-stamp-custom-formats)))
23670 (if (and (not boundary) (memq type '(active-range inactive-range)))
23671 (concat (org-timestamp-format timestamp fmt)
23672 "--"
23673 (org-timestamp-format timestamp fmt t))
23674 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23678 ;;; Other stuff.
23680 (defvar reftex-docstruct-symbol)
23681 (defvar org--rds)
23683 (defun org-reftex-citation ()
23684 "Use reftex-citation to insert a citation into the buffer.
23685 This looks for a line like
23687 #+BIBLIOGRAPHY: foo plain option:-d
23689 and derives from it that foo.bib is the bibliography file relevant
23690 for this document. It then installs the necessary environment for RefTeX
23691 to work in this buffer and calls `reftex-citation' to insert a citation
23692 into the buffer.
23694 Export of such citations to both LaTeX and HTML is handled by the contributed
23695 package ox-bibtex by Taru Karttunen."
23696 (interactive)
23697 (let ((reftex-docstruct-symbol 'org--rds)
23698 org--rds bib)
23699 (org-with-wide-buffer
23700 (let ((case-fold-search t)
23701 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23702 (if (not (save-excursion
23703 (or (re-search-forward re nil t)
23704 (re-search-backward re nil t))))
23705 (user-error "No bibliography defined in file")
23706 (setq bib (concat (match-string 1) ".bib")
23707 org--rds (list (list 'bib bib))))))
23708 (call-interactively 'reftex-citation)))
23710 ;;;; Functions extending outline functionality
23712 (defun org-beginning-of-line (&optional arg)
23713 "Go to the beginning of the current line. If that is invisible, continue
23714 to a visible line beginning. This makes the function of C-a more intuitive.
23715 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23716 first attempt, and only move to after the tags when the cursor is already
23717 beyond the end of the headline."
23718 (interactive "P")
23719 (let ((pos (point))
23720 (special (if (consp org-special-ctrl-a/e)
23721 (car org-special-ctrl-a/e)
23722 org-special-ctrl-a/e))
23723 deactivate-mark refpos)
23724 (call-interactively (if (bound-and-true-p visual-line-mode)
23725 #'beginning-of-visual-line
23726 #'move-beginning-of-line))
23727 (cond
23728 ((or arg (not special)))
23729 ((and (looking-at org-complex-heading-regexp)
23730 (eq (char-after (match-end 1)) ?\s))
23731 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23732 (point-at-eol)))
23733 (goto-char
23734 (if (eq special t)
23735 (cond ((> pos refpos) refpos)
23736 ((= pos (point)) refpos)
23737 (t (point)))
23738 (cond ((> pos (point)) (point))
23739 ((not (eq last-command this-command)) (point))
23740 (t refpos)))))
23741 ((org-at-item-p)
23742 ;; Being at an item and not looking at an the item means point
23743 ;; was previously moved to beginning of a visual line, which
23744 ;; doesn't contain the item. Therefore, do nothing special,
23745 ;; just stay here.
23746 (when (looking-at org-list-full-item-re)
23747 ;; Set special position at first white space character after
23748 ;; bullet, and check-box, if any.
23749 (let ((after-bullet
23750 (let ((box (match-end 3)))
23751 (if (not box) (match-end 1)
23752 (let ((after (char-after box)))
23753 (if (and after (= after ? )) (1+ box) box))))))
23754 ;; Special case: Move point to special position when
23755 ;; currently after it or at beginning of line.
23756 (if (eq special t)
23757 (when (or (> pos after-bullet) (= (point) pos))
23758 (goto-char after-bullet))
23759 ;; Reversed case: Move point to special position when
23760 ;; point was already at beginning of line and command is
23761 ;; repeated.
23762 (when (and (= (point) pos) (eq last-command this-command))
23763 (goto-char after-bullet))))))))
23764 (setq disable-point-adjustment
23765 (or (not (invisible-p (point)))
23766 (not (invisible-p (max (point-min) (1- (point))))))))
23768 (defun org-end-of-line (&optional arg)
23769 "Go to the end of the line.
23770 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23771 tags on the first attempt, and only move to after the tags when
23772 the cursor is already beyond the end of the headline."
23773 (interactive "P")
23774 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23775 org-special-ctrl-a/e))
23776 (move-fun (cond ((bound-and-true-p visual-line-mode)
23777 'end-of-visual-line)
23778 ((fboundp 'move-end-of-line) 'move-end-of-line)
23779 (t 'end-of-line)))
23780 deactivate-mark)
23781 (if (or (not special) arg) (call-interactively move-fun)
23782 (let* ((element (save-excursion (beginning-of-line)
23783 (org-element-at-point)))
23784 (type (org-element-type element)))
23785 (cond
23786 ((memq type '(headline inlinetask))
23787 (let ((pos (point)))
23788 (beginning-of-line 1)
23789 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23790 (if (eq special t)
23791 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23792 (goto-char (match-beginning 1))
23793 (goto-char (match-end 0)))
23794 (if (or (< pos (match-end 0))
23795 (not (eq this-command last-command)))
23796 (goto-char (match-end 0))
23797 (goto-char (match-beginning 1))))
23798 (call-interactively move-fun))))
23799 ((outline-invisible-p (line-end-position))
23800 ;; If element is hidden, `move-end-of-line' would put point
23801 ;; after it. Use `end-of-line' to stay on current line.
23802 (call-interactively 'end-of-line))
23803 (t (call-interactively move-fun))))))
23804 (setq disable-point-adjustment
23805 (or (not (invisible-p (point)))
23806 (not (invisible-p (max (point-min) (1- (point))))))))
23808 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23809 (define-key org-mode-map "\C-e" 'org-end-of-line)
23811 (defun org-backward-sentence (&optional _arg)
23812 "Go to beginning of sentence, or beginning of table field.
23813 This will call `backward-sentence' or `org-table-beginning-of-field',
23814 depending on context."
23815 (interactive)
23816 (let* ((element (org-element-at-point))
23817 (contents-begin (org-element-property :contents-begin element))
23818 (table (org-element-lineage element '(table) t)))
23819 (if (and table
23820 (> (point) contents-begin)
23821 (<= (point) (org-element-property :contents-end table)))
23822 (call-interactively #'org-table-beginning-of-field)
23823 (save-restriction
23824 (when (and contents-begin
23825 (< (point-min) contents-begin)
23826 (> (point) contents-begin))
23827 (narrow-to-region contents-begin
23828 (org-element-property :contents-end element)))
23829 (call-interactively #'backward-sentence)))))
23831 (defun org-forward-sentence (&optional _arg)
23832 "Go to end of sentence, or end of table field.
23833 This will call `forward-sentence' or `org-table-end-of-field',
23834 depending on context."
23835 (interactive)
23836 (let* ((element (org-element-at-point))
23837 (contents-end (org-element-property :contents-end element))
23838 (table (org-element-lineage element '(table) t)))
23839 (if (and table
23840 (>= (point) (org-element-property :contents-begin table))
23841 (< (point) contents-end))
23842 (call-interactively #'org-table-end-of-field)
23843 (save-restriction
23844 (when (and contents-end
23845 (> (point-max) contents-end)
23846 ;; Skip blank lines between elements.
23847 (< (org-element-property :end element)
23848 (save-excursion (goto-char contents-end)
23849 (skip-chars-forward " \r\t\n"))))
23850 (narrow-to-region (org-element-property :contents-begin element)
23851 contents-end))
23852 (call-interactively #'forward-sentence)))))
23854 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23855 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23857 (defun org-kill-line (&optional _arg)
23858 "Kill line, to tags or end of line."
23859 (interactive)
23860 (cond
23861 ((or (not org-special-ctrl-k)
23862 (bolp)
23863 (not (org-at-heading-p)))
23864 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23865 org-ctrl-k-protect-subtree
23866 (or (eq org-ctrl-k-protect-subtree 'error)
23867 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23868 (user-error "C-k aborted as it would kill a hidden subtree"))
23869 (call-interactively
23870 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23871 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23872 (kill-region (point) (match-beginning 1))
23873 (org-set-tags nil t))
23874 (t (kill-region (point) (point-at-eol)))))
23876 (define-key org-mode-map "\C-k" 'org-kill-line)
23878 (defun org-yank (&optional arg)
23879 "Yank. If the kill is a subtree, treat it specially.
23880 This command will look at the current kill and check if is a single
23881 subtree, or a series of subtrees[1]. If it passes the test, and if the
23882 cursor is at the beginning of a line or after the stars of a currently
23883 empty headline, then the yank is handled specially. How exactly depends
23884 on the value of the following variables.
23886 `org-yank-folded-subtrees'
23887 By default, this variable is non-nil, which results in
23888 subtree(s) being folded after insertion, except if doing so
23889 would swallow text after the yanked text.
23891 `org-yank-adjusted-subtrees'
23892 When non-nil (the default value is nil), the subtree will be
23893 promoted or demoted in order to fit into the local outline tree
23894 structure, which means that the level will be adjusted so that it
23895 becomes the smaller one of the two *visible* surrounding headings.
23897 Any prefix to this command will cause `yank' to be called directly with
23898 no special treatment. In particular, a simple \\[universal-argument] prefix \
23899 will just
23900 plainly yank the text as it is.
23902 \[1] The test checks if the first non-white line is a heading
23903 and if there are no other headings with fewer stars."
23904 (interactive "P")
23905 (org-yank-generic 'yank arg))
23907 (defun org-yank-generic (command arg)
23908 "Perform some yank-like command.
23910 This function implements the behavior described in the `org-yank'
23911 documentation. However, it has been generalized to work for any
23912 interactive command with similar behavior."
23914 ;; pretend to be command COMMAND
23915 (setq this-command command)
23917 (if arg
23918 (call-interactively command)
23920 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23921 (and (org-kill-is-subtree-p)
23922 (or (bolp)
23923 (and (looking-at "[ \t]*$")
23924 (string-match
23925 "\\`\\*+\\'"
23926 (buffer-substring (point-at-bol) (point)))))))
23927 swallowp)
23928 (cond
23929 ((and subtreep org-yank-folded-subtrees)
23930 (let ((beg (point))
23931 end)
23932 (if (and subtreep org-yank-adjusted-subtrees)
23933 (org-paste-subtree nil nil 'for-yank)
23934 (call-interactively command))
23936 (setq end (point))
23937 (goto-char beg)
23938 (when (and (bolp) subtreep
23939 (not (setq swallowp
23940 (org-yank-folding-would-swallow-text beg end))))
23941 (org-with-limited-levels
23942 (or (looking-at org-outline-regexp)
23943 (re-search-forward org-outline-regexp-bol end t))
23944 (while (and (< (point) end) (looking-at org-outline-regexp))
23945 (outline-hide-subtree)
23946 (org-cycle-show-empty-lines 'folded)
23947 (condition-case nil
23948 (outline-forward-same-level 1)
23949 (error (goto-char end))))))
23950 (when swallowp
23951 (message
23952 "Inserted text not folded because that would swallow text"))
23954 (goto-char end)
23955 (skip-chars-forward " \t\n\r")
23956 (beginning-of-line 1)
23957 (push-mark beg 'nomsg)))
23958 ((and subtreep org-yank-adjusted-subtrees)
23959 (let ((beg (point-at-bol)))
23960 (org-paste-subtree nil nil 'for-yank)
23961 (push-mark beg 'nomsg)))
23963 (call-interactively command))))))
23965 (defun org-yank-folding-would-swallow-text (beg end)
23966 "Would hide-subtree at BEG swallow any text after END?"
23967 (let (level)
23968 (org-with-limited-levels
23969 (save-excursion
23970 (goto-char beg)
23971 (when (or (looking-at org-outline-regexp)
23972 (re-search-forward org-outline-regexp-bol end t))
23973 (setq level (org-outline-level)))
23974 (goto-char end)
23975 (skip-chars-forward " \t\r\n\v\f")
23976 (not (or (eobp)
23977 (and (bolp) (looking-at-p org-outline-regexp)
23978 (<= (org-outline-level) level))))))))
23980 (define-key org-mode-map "\C-y" 'org-yank)
23982 (defun org-truely-invisible-p ()
23983 "Check if point is at a character currently not visible.
23984 This version does not only check the character property, but also
23985 `visible-mode'."
23986 ;; Early versions of noutline don't have `outline-invisible-p'.
23987 (unless (bound-and-true-p visible-mode)
23988 (outline-invisible-p)))
23990 (defun org-invisible-p2 ()
23991 "Check if point is at a character currently not visible."
23992 (save-excursion
23993 (when (and (eolp) (not (bobp))) (backward-char 1))
23994 ;; Early versions of noutline don't have `outline-invisible-p'.
23995 (outline-invisible-p)))
23997 (defun org-back-to-heading (&optional invisible-ok)
23998 "Call `outline-back-to-heading', but provide a better error message."
23999 (condition-case nil
24000 (outline-back-to-heading invisible-ok)
24001 (error (error "Before first headline at position %d in buffer %s"
24002 (point) (current-buffer)))))
24004 (defun org-before-first-heading-p ()
24005 "Before first heading?"
24006 (save-excursion
24007 (end-of-line)
24008 (null (re-search-backward org-outline-regexp-bol nil t))))
24010 (defun org-at-heading-p (&optional ignored)
24011 (outline-on-heading-p t))
24013 (defun org-in-commented-heading-p (&optional no-inheritance)
24014 "Non-nil if point is under a commented heading.
24015 This function also checks ancestors of the current headline,
24016 unless optional argument NO-INHERITANCE is non-nil."
24017 (cond
24018 ((org-before-first-heading-p) nil)
24019 ((let ((headline (nth 4 (org-heading-components))))
24020 (and headline
24021 (let ((case-fold-search nil))
24022 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24023 headline)))))
24024 (no-inheritance nil)
24026 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24028 (defun org-at-comment-p nil
24029 "Is cursor in a commented line?"
24030 (save-excursion
24031 (save-match-data
24032 (beginning-of-line)
24033 (looking-at "^[ \t]*# "))))
24035 (defun org-at-drawer-p nil
24036 "Is cursor at a drawer keyword?"
24037 (save-excursion
24038 (move-beginning-of-line 1)
24039 (looking-at org-drawer-regexp)))
24041 (defun org-at-block-p nil
24042 "Is cursor at a block keyword?"
24043 (save-excursion
24044 (move-beginning-of-line 1)
24045 (looking-at org-block-regexp)))
24047 (defun org-point-at-end-of-empty-headline ()
24048 "If point is at the end of an empty headline, return t, else nil.
24049 If the heading only contains a TODO keyword, it is still still considered
24050 empty."
24051 (and (looking-at "[ \t]*$")
24052 (when org-todo-line-regexp
24053 (save-excursion
24054 (beginning-of-line 1)
24055 (let ((case-fold-search nil))
24056 (looking-at org-todo-line-regexp)
24057 (string= (match-string 3) ""))))))
24059 (defun org-at-heading-or-item-p ()
24060 (or (org-at-heading-p) (org-at-item-p)))
24062 (defun org-at-target-p ()
24063 (or (org-in-regexp org-radio-target-regexp)
24064 (org-in-regexp org-target-regexp)))
24065 ;; Compatibility alias with Org versions < 7.8.03
24066 (defalias 'org-on-target-p 'org-at-target-p)
24068 (defun org-up-heading-all (arg)
24069 "Move to the heading line of which the present line is a subheading.
24070 This function considers both visible and invisible heading lines.
24071 With argument, move up ARG levels."
24072 (outline-up-heading arg t))
24074 (defun org-up-heading-safe ()
24075 "Move to the heading line of which the present line is a subheading.
24076 This version will not throw an error. It will return the level of the
24077 headline found, or nil if no higher level is found.
24079 Also, this function will be a lot faster than `outline-up-heading',
24080 because it relies on stars being the outline starters. This can really
24081 make a significant difference in outlines with very many siblings."
24082 (when (ignore-errors (org-back-to-heading t))
24083 (let ((level-up (1- (funcall outline-level))))
24084 (and (> level-up 0)
24085 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24086 (funcall outline-level)))))
24088 (defun org-first-sibling-p ()
24089 "Is this heading the first child of its parents?"
24090 (interactive)
24091 (let ((re org-outline-regexp-bol)
24092 level l)
24093 (unless (org-at-heading-p t)
24094 (user-error "Not at a heading"))
24095 (setq level (funcall outline-level))
24096 (save-excursion
24097 (if (not (re-search-backward re nil t))
24099 (setq l (funcall outline-level))
24100 (< l level)))))
24102 (defun org-goto-sibling (&optional previous)
24103 "Goto the next sibling, even if it is invisible.
24104 When PREVIOUS is set, go to the previous sibling instead. Returns t
24105 when a sibling was found. When none is found, return nil and don't
24106 move point."
24107 (let ((fun (if previous 're-search-backward 're-search-forward))
24108 (pos (point))
24109 (re org-outline-regexp-bol)
24110 level l)
24111 (when (ignore-errors (org-back-to-heading t))
24112 (setq level (funcall outline-level))
24113 (catch 'exit
24114 (or previous (forward-char 1))
24115 (while (funcall fun re nil t)
24116 (setq l (funcall outline-level))
24117 (when (< l level) (goto-char pos) (throw 'exit nil))
24118 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24119 (goto-char pos)
24120 nil))))
24122 (defun org-show-siblings ()
24123 "Show all siblings of the current headline."
24124 (save-excursion
24125 (while (org-goto-sibling) (org-flag-heading nil)))
24126 (save-excursion
24127 (while (org-goto-sibling 'previous)
24128 (org-flag-heading nil))))
24130 (defun org-goto-first-child ()
24131 "Goto the first child, even if it is invisible.
24132 Return t when a child was found. Otherwise don't move point and
24133 return nil."
24134 (let (level (pos (point)) (re org-outline-regexp-bol))
24135 (when (ignore-errors (org-back-to-heading t))
24136 (setq level (outline-level))
24137 (forward-char 1)
24138 (if (and (re-search-forward re nil t) (> (outline-level) level))
24139 (progn (goto-char (match-beginning 0)) t)
24140 (goto-char pos) nil))))
24142 (defun org-show-hidden-entry ()
24143 "Show an entry where even the heading is hidden."
24144 (save-excursion
24145 (org-show-entry)))
24147 (defun org-flag-heading (flag &optional entry)
24148 "Flag the current heading. FLAG non-nil means make invisible.
24149 When ENTRY is non-nil, show the entire entry."
24150 (save-excursion
24151 (org-back-to-heading t)
24152 ;; Check if we should show the entire entry
24153 (if entry
24154 (progn
24155 (org-show-entry)
24156 (save-excursion
24157 (and (outline-next-heading)
24158 (org-flag-heading nil))))
24159 (outline-flag-region (max (point-min) (1- (point)))
24160 (save-excursion (outline-end-of-heading) (point))
24161 flag))))
24163 (defun org-get-next-sibling ()
24164 "Move to next heading of the same level, and return point.
24165 If there is no such heading, return nil.
24166 This is like outline-next-sibling, but invisible headings are ok."
24167 (let ((level (funcall outline-level)))
24168 (outline-next-heading)
24169 (while (and (not (eobp)) (> (funcall outline-level) level))
24170 (outline-next-heading))
24171 (unless (or (eobp) (< (funcall outline-level) level))
24172 (point))))
24174 (defun org-get-last-sibling ()
24175 "Move to previous heading of the same level, and return point.
24176 If there is no such heading, return nil."
24177 (let ((opoint (point))
24178 (level (funcall outline-level)))
24179 (outline-previous-heading)
24180 (when (and (/= (point) opoint) (outline-on-heading-p t))
24181 (while (and (> (funcall outline-level) level)
24182 (not (bobp)))
24183 (outline-previous-heading))
24184 (unless (< (funcall outline-level) level)
24185 (point)))))
24187 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24188 "Goto to the end of a subtree."
24189 ;; This contains an exact copy of the original function, but it uses
24190 ;; `org-back-to-heading', to make it work also in invisible
24191 ;; trees. And is uses an invisible-ok argument.
24192 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24193 ;; Furthermore, when used inside Org, finding the end of a large subtree
24194 ;; with many children and grandchildren etc, this can be much faster
24195 ;; than the outline version.
24196 (org-back-to-heading invisible-ok)
24197 (let ((first t)
24198 (level (funcall outline-level)))
24199 (if (and (derived-mode-p 'org-mode) (< level 1000))
24200 ;; A true heading (not a plain list item), in Org
24201 ;; This means we can easily find the end by looking
24202 ;; only for the right number of stars. Using a regexp to do
24203 ;; this is so much faster than using a Lisp loop.
24204 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24205 (forward-char 1)
24206 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24207 ;; something else, do it the slow way
24208 (while (and (not (eobp))
24209 (or first (> (funcall outline-level) level)))
24210 (setq first nil)
24211 (outline-next-heading)))
24212 (unless to-heading
24213 (when (memq (preceding-char) '(?\n ?\^M))
24214 ;; Go to end of line before heading
24215 (forward-char -1)
24216 (when (memq (preceding-char) '(?\n ?\^M))
24217 ;; leave blank line before heading
24218 (forward-char -1)))))
24219 (point))
24221 (defun org-end-of-meta-data (&optional full)
24222 "Skip planning line and properties drawer in current entry.
24223 When optional argument FULL is non-nil, also skip empty lines,
24224 clocking lines and regular drawers at the beginning of the
24225 entry."
24226 (org-back-to-heading t)
24227 (forward-line)
24228 (when (looking-at-p org-planning-line-re) (forward-line))
24229 (when (looking-at org-property-drawer-re)
24230 (goto-char (match-end 0))
24231 (forward-line))
24232 (when (and full (not (org-at-heading-p)))
24233 (catch 'exit
24234 (let ((end (save-excursion (outline-next-heading) (point)))
24235 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24236 (while (not (eobp))
24237 (cond ((looking-at-p org-drawer-regexp)
24238 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24239 (forward-line)
24240 (throw 'exit t)))
24241 ((looking-at-p re) (forward-line))
24242 (t (throw 'exit t))))))))
24244 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24245 "Move forward to the ARG'th subheading at same level as this one.
24246 Stop at the first and last subheadings of a superior heading.
24247 Normally this only looks at visible headings, but when INVISIBLE-OK is
24248 non-nil it will also look at invisible ones."
24249 (interactive "p")
24250 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24251 (if (and arg (< arg 0))
24252 (goto-char (point-min))
24253 (outline-next-heading))
24254 (org-at-heading-p)
24255 (let ((level (- (match-end 0) (match-beginning 0) 1))
24256 (f (if (and arg (< arg 0))
24257 're-search-backward
24258 're-search-forward))
24259 (count (if arg (abs arg) 1))
24260 (result (point)))
24261 (while (and (prog1 (> count 0)
24262 (forward-char (if (and arg (< arg 0)) -1 1)))
24263 (funcall f org-outline-regexp-bol nil 'move))
24264 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24265 (cond ((< l level) (setq count 0))
24266 ((and (= l level)
24267 (or invisible-ok
24268 (progn
24269 (goto-char (line-beginning-position))
24270 (not (outline-invisible-p)))))
24271 (setq count (1- count))
24272 (when (eq l level)
24273 (setq result (point)))))))
24274 (goto-char result))
24275 (beginning-of-line 1)))
24277 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24278 "Move backward to the ARG'th subheading at same level as this one.
24279 Stop at the first and last subheadings of a superior heading."
24280 (interactive "p")
24281 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24283 (defun org-next-visible-heading (arg)
24284 "Move to the next visible heading.
24286 This function wraps `outline-next-visible-heading' with
24287 `org-with-limited-levels' in order to skip over inline tasks and
24288 respect customization of `org-odd-levels-only'."
24289 (interactive "p")
24290 (org-with-limited-levels
24291 (outline-next-visible-heading arg)))
24293 (defun org-previous-visible-heading (arg)
24294 "Move to the previous visible heading.
24296 This function wraps `outline-previous-visible-heading' with
24297 `org-with-limited-levels' in order to skip over inline tasks and
24298 respect customization of `org-odd-levels-only'."
24299 (interactive "p")
24300 (org-with-limited-levels
24301 (outline-previous-visible-heading arg)))
24303 (defun org-next-block (arg &optional backward block-regexp)
24304 "Jump to the next block.
24306 With a prefix argument ARG, jump forward ARG many blocks.
24308 When BACKWARD is non-nil, jump to the previous block.
24310 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24311 Match data is set according to this regexp when the function
24312 returns.
24314 Return point at beginning of the opening line of found block.
24315 Throw an error if no block is found."
24316 (interactive "p")
24317 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24318 (case-fold-search t)
24319 (search-fn (if backward #'re-search-backward #'re-search-forward))
24320 (count (or arg 1))
24321 (origin (point))
24322 last-element)
24323 (if backward (beginning-of-line) (end-of-line))
24324 (while (and (> count 0) (funcall search-fn re nil t))
24325 (let ((element (save-excursion
24326 (goto-char (match-beginning 0))
24327 (save-match-data (org-element-at-point)))))
24328 (when (and (memq (org-element-type element)
24329 '(center-block comment-block dynamic-block
24330 example-block export-block quote-block
24331 special-block src-block verse-block))
24332 (<= (match-beginning 0)
24333 (org-element-property :post-affiliated element)))
24334 (setq last-element element)
24335 (cl-decf count))))
24336 (if (= count 0)
24337 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24338 (save-match-data (org-show-context)))
24339 (goto-char origin)
24340 (user-error "No %s code blocks" (if backward "previous" "further")))))
24342 (defun org-previous-block (arg &optional block-regexp)
24343 "Jump to the previous block.
24344 With a prefix argument ARG, jump backward ARG many source blocks.
24345 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24346 (interactive "p")
24347 (org-next-block arg t block-regexp))
24349 (defun org-forward-paragraph ()
24350 "Move forward to beginning of next paragraph or equivalent.
24352 The function moves point to the beginning of the next visible
24353 structural element, which can be a paragraph, a table, a list
24354 item, etc. It also provides some special moves for convenience:
24356 - On an affiliated keyword, jump to the beginning of the
24357 relative element.
24358 - On an item or a footnote definition, move to the second
24359 element inside, if any.
24360 - On a table or a property drawer, jump after it.
24361 - On a verse or source block, stop after blank lines."
24362 (interactive)
24363 (when (eobp) (user-error "Cannot move further down"))
24364 (let* ((deactivate-mark nil)
24365 (element (org-element-at-point))
24366 (type (org-element-type element))
24367 (post-affiliated (org-element-property :post-affiliated element))
24368 (contents-begin (org-element-property :contents-begin element))
24369 (contents-end (org-element-property :contents-end element))
24370 (end (let ((end (org-element-property :end element)) (parent element))
24371 (while (and (setq parent (org-element-property :parent parent))
24372 (= (org-element-property :contents-end parent) end))
24373 (setq end (org-element-property :end parent)))
24374 end)))
24375 (cond ((not element)
24376 (skip-chars-forward " \r\t\n")
24377 (or (eobp) (beginning-of-line)))
24378 ;; On affiliated keywords, move to element's beginning.
24379 ((< (point) post-affiliated)
24380 (goto-char post-affiliated))
24381 ;; At a table row, move to the end of the table. Similarly,
24382 ;; at a node property, move to the end of the property
24383 ;; drawer.
24384 ((memq type '(node-property table-row))
24385 (goto-char (org-element-property
24386 :end (org-element-property :parent element))))
24387 ((memq type '(property-drawer table)) (goto-char end))
24388 ;; Consider blank lines as separators in verse and source
24389 ;; blocks to ease editing.
24390 ((memq type '(src-block verse-block))
24391 (when (eq type 'src-block)
24392 (setq contents-end
24393 (save-excursion (goto-char end)
24394 (skip-chars-backward " \r\t\n")
24395 (line-beginning-position))))
24396 (beginning-of-line)
24397 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24398 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24399 (goto-char end)
24400 (skip-chars-forward " \r\t\n")
24401 (if (= (point) contents-end) (goto-char end)
24402 (beginning-of-line))))
24403 ;; With no contents, just skip element.
24404 ((not contents-begin) (goto-char end))
24405 ;; If contents are invisible, skip the element altogether.
24406 ((outline-invisible-p (line-end-position))
24407 (cl-case type
24408 (headline
24409 (org-with-limited-levels (outline-next-visible-heading 1)))
24410 ;; At a plain list, make sure we move to the next item
24411 ;; instead of skipping the whole list.
24412 (plain-list (forward-char)
24413 (org-forward-paragraph))
24414 (otherwise (goto-char end))))
24415 ((>= (point) contents-end) (goto-char end))
24416 ((>= (point) contents-begin)
24417 ;; This can only happen on paragraphs and plain lists.
24418 (cl-case type
24419 (paragraph (goto-char end))
24420 ;; At a plain list, try to move to second element in
24421 ;; first item, if possible.
24422 (plain-list (end-of-line)
24423 (org-forward-paragraph))))
24424 ;; When contents start on the middle of a line (e.g. in
24425 ;; items and footnote definitions), try to reach first
24426 ;; element starting after current line.
24427 ((> (line-end-position) contents-begin)
24428 (end-of-line)
24429 (org-forward-paragraph))
24430 (t (goto-char contents-begin)))))
24432 (defun org-backward-paragraph ()
24433 "Move backward to start of previous paragraph or equivalent.
24435 The function moves point to the beginning of the current
24436 structural element, which can be a paragraph, a table, a list
24437 item, etc., or to the beginning of the previous visible one if
24438 point is already there. It also provides some special moves for
24439 convenience:
24441 - On an affiliated keyword, jump to the first one.
24442 - On a table or a property drawer, move to its beginning.
24443 - On a verse or source block, stop before blank lines."
24444 (interactive)
24445 (when (bobp) (user-error "Cannot move further up"))
24446 (let* ((deactivate-mark nil)
24447 (element (org-element-at-point))
24448 (type (org-element-type element))
24449 (contents-begin (org-element-property :contents-begin element))
24450 (contents-end (org-element-property :contents-end element))
24451 (post-affiliated (org-element-property :post-affiliated element))
24452 (begin (org-element-property :begin element)))
24453 (cond
24454 ((not element) (goto-char (point-min)))
24455 ((= (point) begin)
24456 (backward-char)
24457 (org-backward-paragraph))
24458 ((<= (point) post-affiliated) (goto-char begin))
24459 ((memq type '(node-property table-row))
24460 (goto-char (org-element-property
24461 :post-affiliated (org-element-property :parent element))))
24462 ((memq type '(property-drawer table)) (goto-char begin))
24463 ((memq type '(src-block verse-block))
24464 (when (eq type 'src-block)
24465 (setq contents-begin
24466 (save-excursion (goto-char begin) (forward-line) (point))))
24467 (if (= (point) contents-begin) (goto-char post-affiliated)
24468 ;; Inside a verse block, see blank lines as paragraph
24469 ;; separators.
24470 (let ((origin (point)))
24471 (skip-chars-backward " \r\t\n" contents-begin)
24472 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24473 (skip-chars-forward " \r\t\n" origin)
24474 (if (= (point) origin) (goto-char contents-begin)
24475 (beginning-of-line))))))
24476 ((not contents-begin) (goto-char (or post-affiliated begin)))
24477 ((eq type 'paragraph)
24478 (goto-char contents-begin)
24479 ;; When at first paragraph in an item or a footnote definition,
24480 ;; move directly to beginning of line.
24481 (let ((parent-contents
24482 (org-element-property
24483 :contents-begin (org-element-property :parent element))))
24484 (when (and parent-contents (= parent-contents contents-begin))
24485 (beginning-of-line))))
24486 ;; At the end of a greater element, move to the beginning of the
24487 ;; last element within.
24488 ((>= (point) contents-end)
24489 (goto-char (1- contents-end))
24490 (org-backward-paragraph))
24491 (t (goto-char (or post-affiliated begin))))
24492 ;; Ensure we never leave point invisible.
24493 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24495 (defun org-forward-element ()
24496 "Move forward by one element.
24497 Move to the next element at the same level, when possible."
24498 (interactive)
24499 (cond ((eobp) (user-error "Cannot move further down"))
24500 ((org-with-limited-levels (org-at-heading-p))
24501 (let ((origin (point)))
24502 (goto-char (org-end-of-subtree nil t))
24503 (unless (org-with-limited-levels (org-at-heading-p))
24504 (goto-char origin)
24505 (user-error "Cannot move further down"))))
24507 (let* ((elem (org-element-at-point))
24508 (end (org-element-property :end elem))
24509 (parent (org-element-property :parent elem)))
24510 (cond ((and parent (= (org-element-property :contents-end parent) end))
24511 (goto-char (org-element-property :end parent)))
24512 ((integer-or-marker-p end) (goto-char end))
24513 (t (message "No element at point")))))))
24515 (defun org-backward-element ()
24516 "Move backward by one element.
24517 Move to the previous element at the same level, when possible."
24518 (interactive)
24519 (cond ((bobp) (user-error "Cannot move further up"))
24520 ((org-with-limited-levels (org-at-heading-p))
24521 ;; At a headline, move to the previous one, if any, or stay
24522 ;; here.
24523 (let ((origin (point)))
24524 (org-with-limited-levels (org-backward-heading-same-level 1))
24525 ;; When current headline has no sibling above, move to its
24526 ;; parent.
24527 (when (= (point) origin)
24528 (or (org-with-limited-levels (org-up-heading-safe))
24529 (progn (goto-char origin)
24530 (user-error "Cannot move further up"))))))
24532 (let* ((elem (org-element-at-point))
24533 (beg (org-element-property :begin elem)))
24534 (cond
24535 ;; Move to beginning of current element if point isn't
24536 ;; there already.
24537 ((null beg) (message "No element at point"))
24538 ((/= (point) beg) (goto-char beg))
24539 (t (goto-char beg)
24540 (skip-chars-backward " \r\t\n")
24541 (unless (bobp)
24542 (let ((prev (org-element-at-point)))
24543 (goto-char (org-element-property :begin prev))
24544 (while (and (setq prev (org-element-property :parent prev))
24545 (<= (org-element-property :end prev) beg))
24546 (goto-char (org-element-property :begin prev)))))))))))
24548 (defun org-up-element ()
24549 "Move to upper element."
24550 (interactive)
24551 (if (org-with-limited-levels (org-at-heading-p))
24552 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24553 (let* ((elem (org-element-at-point))
24554 (parent (org-element-property :parent elem)))
24555 (if parent (goto-char (org-element-property :begin parent))
24556 (if (org-with-limited-levels (org-before-first-heading-p))
24557 (user-error "No surrounding element")
24558 (org-with-limited-levels (org-back-to-heading)))))))
24560 (defvar org-element-greater-elements)
24561 (defun org-down-element ()
24562 "Move to inner element."
24563 (interactive)
24564 (let ((element (org-element-at-point)))
24565 (cond
24566 ((memq (org-element-type element) '(plain-list table))
24567 (goto-char (org-element-property :contents-begin element))
24568 (forward-char))
24569 ((memq (org-element-type element) org-element-greater-elements)
24570 ;; If contents are hidden, first disclose them.
24571 (when (outline-invisible-p (line-end-position)) (org-cycle))
24572 (goto-char (or (org-element-property :contents-begin element)
24573 (user-error "No content for this element"))))
24574 (t (user-error "No inner element")))))
24576 (defun org-drag-element-backward ()
24577 "Move backward element at point."
24578 (interactive)
24579 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24580 (let* ((elem (org-element-at-point))
24581 (prev-elem
24582 (save-excursion
24583 (goto-char (org-element-property :begin elem))
24584 (skip-chars-backward " \r\t\n")
24585 (unless (bobp)
24586 (let* ((beg (org-element-property :begin elem))
24587 (prev (org-element-at-point))
24588 (up prev))
24589 (while (and (setq up (org-element-property :parent up))
24590 (<= (org-element-property :end up) beg))
24591 (setq prev up))
24592 prev)))))
24593 ;; Error out if no previous element or previous element is
24594 ;; a parent of the current one.
24595 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24596 (user-error "Cannot drag element backward")
24597 (let ((pos (point)))
24598 (org-element-swap-A-B prev-elem elem)
24599 (goto-char (+ (org-element-property :begin prev-elem)
24600 (- pos (org-element-property :begin elem)))))))))
24602 (defun org-drag-element-forward ()
24603 "Move forward element at point."
24604 (interactive)
24605 (let* ((pos (point))
24606 (elem (org-element-at-point)))
24607 (when (= (point-max) (org-element-property :end elem))
24608 (user-error "Cannot drag element forward"))
24609 (goto-char (org-element-property :end elem))
24610 (let ((next-elem (org-element-at-point)))
24611 (when (or (org-element-nested-p elem next-elem)
24612 (and (eq (org-element-type next-elem) 'headline)
24613 (not (eq (org-element-type elem) 'headline))))
24614 (goto-char pos)
24615 (user-error "Cannot drag element forward"))
24616 ;; Compute new position of point: it's shifted by NEXT-ELEM
24617 ;; body's length (without final blanks) and by the length of
24618 ;; blanks between ELEM and NEXT-ELEM.
24619 (let ((size-next (- (save-excursion
24620 (goto-char (org-element-property :end next-elem))
24621 (skip-chars-backward " \r\t\n")
24622 (forward-line)
24623 ;; Small correction if buffer doesn't end
24624 ;; with a newline character.
24625 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24626 (org-element-property :begin next-elem)))
24627 (size-blank (- (org-element-property :end elem)
24628 (save-excursion
24629 (goto-char (org-element-property :end elem))
24630 (skip-chars-backward " \r\t\n")
24631 (forward-line)
24632 (point)))))
24633 (org-element-swap-A-B elem next-elem)
24634 (goto-char (+ pos size-next size-blank))))))
24636 (defun org-drag-line-forward (arg)
24637 "Drag the line at point ARG lines forward."
24638 (interactive "p")
24639 (dotimes (_ (abs arg))
24640 (let ((c (current-column)))
24641 (if (< 0 arg)
24642 (progn
24643 (beginning-of-line 2)
24644 (transpose-lines 1)
24645 (beginning-of-line 0))
24646 (transpose-lines 1)
24647 (beginning-of-line -1))
24648 (org-move-to-column c))))
24650 (defun org-drag-line-backward (arg)
24651 "Drag the line at point ARG lines backward."
24652 (interactive "p")
24653 (org-drag-line-forward (- arg)))
24655 (defun org-mark-element ()
24656 "Put point at beginning of this element, mark at end.
24658 Interactively, if this command is repeated or (in Transient Mark
24659 mode) if the mark is active, it marks the next element after the
24660 ones already marked."
24661 (interactive)
24662 (let (deactivate-mark)
24663 (if (and (called-interactively-p 'any)
24664 (or (and (eq last-command this-command) (mark t))
24665 (and transient-mark-mode mark-active)))
24666 (set-mark
24667 (save-excursion
24668 (goto-char (mark))
24669 (goto-char (org-element-property :end (org-element-at-point)))))
24670 (let ((element (org-element-at-point)))
24671 (end-of-line)
24672 (push-mark (org-element-property :end element) t t)
24673 (goto-char (org-element-property :begin element))))))
24675 (defun org-narrow-to-element ()
24676 "Narrow buffer to current element."
24677 (interactive)
24678 (let ((elem (org-element-at-point)))
24679 (cond
24680 ((eq (car elem) 'headline)
24681 (narrow-to-region
24682 (org-element-property :begin elem)
24683 (org-element-property :end elem)))
24684 ((memq (car elem) org-element-greater-elements)
24685 (narrow-to-region
24686 (org-element-property :contents-begin elem)
24687 (org-element-property :contents-end elem)))
24689 (narrow-to-region
24690 (org-element-property :begin elem)
24691 (org-element-property :end elem))))))
24693 (defun org-transpose-element ()
24694 "Transpose current and previous elements, keeping blank lines between.
24695 Point is moved after both elements."
24696 (interactive)
24697 (org-skip-whitespace)
24698 (let ((end (org-element-property :end (org-element-at-point))))
24699 (org-drag-element-backward)
24700 (goto-char end)))
24702 (defun org-unindent-buffer ()
24703 "Un-indent the visible part of the buffer.
24704 Relative indentation (between items, inside blocks, etc.) isn't
24705 modified."
24706 (interactive)
24707 (unless (eq major-mode 'org-mode)
24708 (user-error "Cannot un-indent a buffer not in Org mode"))
24709 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24710 (unindent-tree
24711 (lambda (contents)
24712 (dolist (element (reverse contents))
24713 (if (memq (org-element-type element) '(headline section))
24714 (funcall unindent-tree (org-element-contents element))
24715 (save-excursion
24716 (save-restriction
24717 (narrow-to-region
24718 (org-element-property :begin element)
24719 (org-element-property :end element))
24720 (org-do-remove-indentation))))))))
24721 (funcall unindent-tree (org-element-contents parse-tree))))
24723 (defun org-show-children (&optional level)
24724 "Show all direct subheadings of this heading.
24725 Prefix arg LEVEL is how many levels below the current level
24726 should be shown. Default is enough to cause the following
24727 heading to appear."
24728 (interactive "p")
24729 ;; If `orgstruct-mode' is active, use the slower version.
24730 (if orgstruct-mode (call-interactively #'outline-show-children)
24731 (save-excursion
24732 (org-back-to-heading t)
24733 (let* ((current-level (funcall outline-level))
24734 (max-level (org-get-valid-level
24735 current-level
24736 (if level (prefix-numeric-value level) 1)))
24737 (end (save-excursion (org-end-of-subtree t t)))
24738 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24739 (past-first-child nil)
24740 ;; Make sure to skip inlinetasks.
24741 (re (format regexp-fmt
24742 current-level
24743 (cond
24744 ((not (featurep 'org-inlinetask)) "")
24745 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24747 (t (1- org-inlinetask-min-level))))))
24748 ;; Display parent heading.
24749 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24750 (forward-line)
24751 ;; Display children. First child may be deeper than expected
24752 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24753 ;; MAX-LEVEL accordingly.
24754 (while (re-search-forward re end t)
24755 (unless past-first-child
24756 (setq re (format regexp-fmt
24757 current-level
24758 (max (funcall outline-level) max-level)))
24759 (setq past-first-child t))
24760 (outline-flag-region
24761 (line-end-position 0) (line-end-position) nil))))))
24763 (defun org-show-subtree ()
24764 "Show everything after this heading at deeper levels."
24765 (interactive)
24766 (outline-flag-region
24767 (point)
24768 (save-excursion
24769 (org-end-of-subtree t t))
24770 nil))
24772 (defun org-show-entry ()
24773 "Show the body directly following this heading.
24774 Show the heading too, if it is currently invisible."
24775 (interactive)
24776 (save-excursion
24777 (ignore-errors
24778 (org-back-to-heading t)
24779 (outline-flag-region
24780 (max (point-min) (1- (point)))
24781 (save-excursion
24782 (if (re-search-forward
24783 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24784 (match-beginning 1)
24785 (point-max)))
24786 nil)
24787 (org-cycle-hide-drawers 'children))))
24789 (defun org-make-options-regexp (kwds &optional extra)
24790 "Make a regular expression for keyword lines.
24791 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24792 when non-nil, is a regexp matching keywords names."
24793 (concat "^[ \t]*#\\+\\("
24794 (regexp-opt kwds)
24795 (and extra (concat (and kwds "\\|") extra))
24796 "\\):[ \t]*\\(.*\\)"))
24798 ;;;; Integration with and fixes for other packages
24800 ;;; Imenu support
24802 (defvar-local org-imenu-markers nil
24803 "All markers currently used by Imenu.")
24805 (defun org-imenu-new-marker (&optional pos)
24806 "Return a new marker for use by Imenu, and remember the marker."
24807 (let ((m (make-marker)))
24808 (move-marker m (or pos (point)))
24809 (push m org-imenu-markers)
24812 (defun org-imenu-get-tree ()
24813 "Produce the index for Imenu."
24814 (dolist (x org-imenu-markers) (move-marker x nil))
24815 (setq org-imenu-markers nil)
24816 (let* ((case-fold-search nil)
24817 (n org-imenu-depth)
24818 (re (concat "^" (org-get-limited-outline-regexp)))
24819 (subs (make-vector (1+ n) nil))
24820 (last-level 0)
24821 m level head0 head)
24822 (org-with-wide-buffer
24823 (goto-char (point-max))
24824 (while (re-search-backward re nil t)
24825 (setq level (org-reduced-level (funcall outline-level)))
24826 (when (and (<= level n)
24827 (looking-at org-complex-heading-regexp)
24828 (setq head0 (match-string-no-properties 4)))
24829 (setq head (org-link-display-format head0)
24830 m (org-imenu-new-marker))
24831 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24832 (if (>= level last-level)
24833 (push (cons head m) (aref subs level))
24834 (push (cons head (aref subs (1+ level))) (aref subs level))
24835 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24836 (setq last-level level))))
24837 (aref subs 1)))
24839 (eval-after-load "imenu"
24840 '(progn
24841 (add-hook 'imenu-after-jump-hook
24842 (lambda ()
24843 (when (derived-mode-p 'org-mode)
24844 (org-show-context 'org-goto))))))
24846 (defun org-link-display-format (s)
24847 "Replace links in string S with their description.
24848 If there is no description, use the link target."
24849 (save-match-data
24850 (replace-regexp-in-string
24851 org-bracket-link-analytic-regexp
24852 (lambda (m)
24853 (if (match-end 5) (match-string 5 m)
24854 (concat (match-string 1 m) (match-string 3 m))))
24855 s nil t)))
24857 (defun org-toggle-link-display ()
24858 "Toggle the literal or descriptive display of links."
24859 (interactive)
24860 (if org-descriptive-links
24861 (progn (org-remove-from-invisibility-spec '(org-link))
24862 (org-restart-font-lock)
24863 (setq org-descriptive-links nil))
24864 (progn (add-to-invisibility-spec '(org-link))
24865 (org-restart-font-lock)
24866 (setq org-descriptive-links t))))
24868 ;; Speedbar support
24870 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24871 "Overlay marking the agenda restriction line in speedbar.")
24872 (overlay-put org-speedbar-restriction-lock-overlay
24873 'face 'org-agenda-restriction-lock)
24874 (overlay-put org-speedbar-restriction-lock-overlay
24875 'help-echo "Agendas are currently limited to this item.")
24876 (delete-overlay org-speedbar-restriction-lock-overlay)
24878 (defun org-speedbar-set-agenda-restriction ()
24879 "Restrict future agenda commands to the location at point in speedbar.
24880 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24881 (interactive)
24882 (require 'org-agenda)
24883 (let (p m tp np dir txt)
24884 (cond
24885 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24886 'org-imenu t))
24887 (setq m (get-text-property p 'org-imenu-marker))
24888 (with-current-buffer (marker-buffer m)
24889 (goto-char m)
24890 (org-agenda-set-restriction-lock 'subtree)))
24891 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24892 'speedbar-function 'speedbar-find-file))
24893 (setq tp (previous-single-property-change
24894 (1+ p) 'speedbar-function)
24895 np (next-single-property-change
24896 tp 'speedbar-function)
24897 dir (speedbar-line-directory)
24898 txt (buffer-substring-no-properties (or tp (point-min))
24899 (or np (point-max))))
24900 (with-current-buffer (find-file-noselect
24901 (let ((default-directory dir))
24902 (expand-file-name txt)))
24903 (unless (derived-mode-p 'org-mode)
24904 (user-error "Cannot restrict to non-Org-mode file"))
24905 (org-agenda-set-restriction-lock 'file)))
24906 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24907 (move-overlay org-speedbar-restriction-lock-overlay
24908 (point-at-bol) (point-at-eol))
24909 (setq current-prefix-arg nil)
24910 (org-agenda-maybe-redo)))
24912 (defvar speedbar-file-key-map)
24913 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24914 (eval-after-load "speedbar"
24915 '(progn
24916 (speedbar-add-supported-extension ".org")
24917 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24918 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24919 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24920 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24921 (add-hook 'speedbar-visiting-tag-hook
24922 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24924 ;;; Fixes and Hacks for problems with other packages
24926 (defun org--flyspell-object-check-p (element)
24927 "Non-nil when Flyspell can check object at point.
24928 ELEMENT is the element at point."
24929 (let ((object (save-excursion
24930 (when (looking-at-p "\\>") (backward-char))
24931 (org-element-context element))))
24932 (cl-case (org-element-type object)
24933 ;; Prevent checks in links due to keybinding conflict with
24934 ;; Flyspell.
24935 ((code entity export-snippet inline-babel-call
24936 inline-src-block line-break latex-fragment link macro
24937 statistics-cookie target timestamp verbatim)
24938 nil)
24939 (footnote-reference
24940 ;; Only in inline footnotes, within the definition.
24941 (and (eq (org-element-property :type object) 'inline)
24942 (< (save-excursion
24943 (goto-char (org-element-property :begin object))
24944 (search-forward ":" nil t 2))
24945 (point))))
24946 (otherwise t))))
24948 (defun org-mode-flyspell-verify ()
24949 "Function used for `flyspell-generic-check-word-predicate'."
24950 (if (org-at-heading-p)
24951 ;; At a headline or an inlinetask, check title only. This is
24952 ;; faster than relying on `org-element-at-point'.
24953 (and (save-excursion (beginning-of-line)
24954 (and (let ((case-fold-search t))
24955 (not (looking-at "\\*+ END[ \t]*$")))
24956 (looking-at org-complex-heading-regexp)))
24957 (match-beginning 4)
24958 (>= (point) (match-beginning 4))
24959 (or (not (match-beginning 5))
24960 (< (point) (match-beginning 5))))
24961 (let* ((element (org-element-at-point))
24962 (post-affiliated (org-element-property :post-affiliated element)))
24963 (cond
24964 ;; Ignore checks in all affiliated keywords but captions.
24965 ((< (point) post-affiliated)
24966 (and (save-excursion
24967 (beginning-of-line)
24968 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24969 (> (point) (match-end 0))
24970 (org--flyspell-object-check-p element)))
24971 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24972 ((let ((log (org-log-into-drawer)))
24973 (and log
24974 (let ((drawer (org-element-lineage element '(drawer))))
24975 (and drawer
24976 (eq (compare-strings
24977 log nil nil
24978 (org-element-property :drawer-name drawer) nil nil t)
24979 t)))))
24980 nil)
24982 (cl-case (org-element-type element)
24983 ((comment quote-section) t)
24984 (comment-block
24985 ;; Allow checks between block markers, not on them.
24986 (and (> (line-beginning-position) post-affiliated)
24987 (save-excursion
24988 (end-of-line)
24989 (skip-chars-forward " \r\t\n")
24990 (< (point) (org-element-property :end element)))))
24991 ;; Arbitrary list of keywords where checks are meaningful.
24992 ;; Make sure point is on the value part of the element.
24993 (keyword
24994 (and (member (org-element-property :key element)
24995 '("DESCRIPTION" "TITLE"))
24996 (save-excursion
24997 (search-backward ":" (line-beginning-position) t))))
24998 ;; Check is globally allowed in paragraphs verse blocks and
24999 ;; table rows (after affiliated keywords) but some objects
25000 ;; must not be affected.
25001 ((paragraph table-row verse-block)
25002 (let ((cbeg (org-element-property :contents-begin element))
25003 (cend (org-element-property :contents-end element)))
25004 (and cbeg (>= (point) cbeg) (< (point) cend)
25005 (org--flyspell-object-check-p element))))))))))
25006 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25008 (defun org-remove-flyspell-overlays-in (beg end)
25009 "Remove flyspell overlays in region."
25010 (and (bound-and-true-p flyspell-mode)
25011 (fboundp 'flyspell-delete-region-overlays)
25012 (flyspell-delete-region-overlays beg end)))
25014 (defvar flyspell-delayed-commands)
25015 (eval-after-load "flyspell"
25016 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25018 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25019 (eval-after-load "bookmark"
25020 '(if (boundp 'bookmark-after-jump-hook)
25021 ;; We can use the hook
25022 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25023 ;; Hook not available, use advice
25024 (defadvice bookmark-jump (after org-make-visible activate)
25025 "Make the position visible."
25026 (org-bookmark-jump-unhide))))
25028 ;; Make sure saveplace shows the location if it was hidden
25029 (eval-after-load "saveplace"
25030 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25031 "Make the position visible."
25032 (org-bookmark-jump-unhide)))
25034 ;; Make sure ecb shows the location if it was hidden
25035 (eval-after-load "ecb"
25036 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25037 "Make hierarchy visible when jumping into location from ECB tree buffer."
25038 (when (derived-mode-p 'org-mode)
25039 (org-show-context))))
25041 (defun org-bookmark-jump-unhide ()
25042 "Unhide the current position, to show the bookmark location."
25043 (and (derived-mode-p 'org-mode)
25044 (or (outline-invisible-p)
25045 (save-excursion (goto-char (max (point-min) (1- (point))))
25046 (outline-invisible-p)))
25047 (org-show-context 'bookmark-jump)))
25049 (defun org-mark-jump-unhide ()
25050 "Make the point visible with `org-show-context' after jumping to the mark."
25051 (when (and (derived-mode-p 'org-mode)
25052 (outline-invisible-p))
25053 (org-show-context 'mark-goto)))
25055 (eval-after-load "simple"
25056 '(defadvice pop-to-mark-command (after org-make-visible activate)
25057 "Make the point visible with `org-show-context'."
25058 (org-mark-jump-unhide)))
25060 (eval-after-load "simple"
25061 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25062 "Make the point visible with `org-show-context'."
25063 (org-mark-jump-unhide)))
25065 (eval-after-load "simple"
25066 '(defadvice pop-global-mark (after org-make-visible activate)
25067 "Make the point visible with `org-show-context'."
25068 (org-mark-jump-unhide)))
25070 ;; Make session.el ignore our circular variable
25071 (defvar session-globals-exclude)
25072 (eval-after-load "session"
25073 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25075 ;;;; Finish up
25077 (provide 'org)
25079 (run-hooks 'org-load-hook)
25081 ;;; org.el ends here