Fix a docstring
[org-mode/org-tableheadings.git] / lisp / org.el
blob772fe10b4cacbfec117abc391546dcd3c89757b0
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).
7875 With a \\[universal-argument] prefix, set \
7876 `org-insert-heading-respect-content' to
7877 a non-nil value for the duration of the command. This forces the
7878 insertion of a heading after the current subtree, independently
7879 on the location of point.
7881 With double \\[universal-argument] \\[universal-argument] prefix, \
7882 insert the heading at the end of the
7883 tree above the current heading. For example, if point is within
7884 a 2nd-level heading, then it will insert a 2nd-level heading at
7885 the end of the 1st-level parent subtree.
7887 When INVISIBLE-OK is set, stop at invisible headlines when going
7888 back. This is important for non-interactive uses of the
7889 command.
7891 When optional argument TOP is non-nil, insert a level 1 heading,
7892 unconditionally."
7893 (interactive "P")
7894 (let ((itemp (and (not top) (org-in-item-p)))
7895 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7896 (respect-content (or org-insert-heading-respect-content
7897 (equal arg '(4))))
7898 (initial-content ""))
7900 (cond
7902 ((or (= (buffer-size) 0)
7903 (and (not (save-excursion
7904 (and (ignore-errors (org-back-to-heading invisible-ok))
7905 (org-at-heading-p))))
7906 (or arg (not itemp))))
7907 ;; At beginning of buffer or so high up that only a heading
7908 ;; makes sense.
7909 (cond ((and (bolp) (not respect-content)) (insert "* "))
7910 ((not respect-content)
7911 (unless may-split (end-of-line))
7912 (insert "\n* "))
7913 ((re-search-forward org-outline-regexp-bol nil t)
7914 (beginning-of-line)
7915 (insert "* \n")
7916 (backward-char))
7917 (t (goto-char (point-max))
7918 (insert "\n* ")))
7919 (run-hooks 'org-insert-heading-hook))
7921 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7924 ;; Maybe move at the end of the subtree
7925 (when (equal arg '(16))
7926 (org-up-heading-safe)
7927 (org-end-of-subtree t))
7928 ;; Insert a heading
7929 (save-restriction
7930 (widen)
7931 (let* ((level nil)
7932 (on-heading (org-at-heading-p))
7933 (empty-line-p (if on-heading
7934 (org-previous-line-empty-p)
7935 ;; We will decide later
7936 nil))
7937 ;; Get a level string to fall back on.
7938 (fix-level
7939 (if (org-before-first-heading-p) "*"
7940 (save-excursion
7941 (org-back-to-heading t)
7942 (when (org-previous-line-empty-p) (setq empty-line-p t))
7943 (looking-at org-outline-regexp)
7944 (make-string (1- (length (match-string 0))) ?*))))
7945 (stars
7946 (save-excursion
7947 (condition-case nil
7948 (if top "* "
7949 (org-back-to-heading invisible-ok)
7950 (when (and (not on-heading)
7951 (featurep 'org-inlinetask)
7952 (integerp org-inlinetask-min-level)
7953 (>= (length (match-string 0))
7954 org-inlinetask-min-level))
7955 ;; Find a heading level before the inline
7956 ;; task.
7957 (while (and (setq level (org-up-heading-safe))
7958 (>= level org-inlinetask-min-level)))
7959 (if (org-at-heading-p)
7960 (org-back-to-heading invisible-ok)
7961 (error "This should not happen")))
7962 (unless (and (save-excursion
7963 (save-match-data
7964 (org-backward-heading-same-level
7965 1 invisible-ok))
7966 (= (point) (match-beginning 0)))
7967 (not (org-next-line-empty-p)))
7968 (setq empty-line-p (or empty-line-p
7969 (org-previous-line-empty-p))))
7970 (match-string 0))
7971 (error (or fix-level "* ")))))
7972 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7973 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7975 ;; If we insert after content, move there and clean up
7976 ;; whitespace.
7977 (when (and respect-content
7978 (not (looking-at-p org-outline-regexp-bol)))
7979 (if (not (org-before-first-heading-p))
7980 (org-end-of-subtree nil t)
7981 (re-search-forward org-outline-regexp-bol)
7982 (beginning-of-line 0))
7983 (skip-chars-backward " \r\t\n")
7984 (and (not (looking-back "^\\*+" (line-beginning-position)))
7985 (looking-at "[ \t]+") (replace-match ""))
7986 (unless (eobp) (forward-char 1))
7987 (when (looking-at "^\\*")
7988 (unless (bobp) (backward-char 1))
7989 (insert "\n")))
7991 ;; If we are splitting, grab the text that should be moved
7992 ;; to the new headline.
7993 (when may-split
7994 (if (org-at-heading-p)
7995 ;; This is a heading: split intelligently (keeping
7996 ;; tags).
7997 (let ((pos (point)))
7998 (beginning-of-line)
7999 (unless (looking-at org-complex-heading-regexp)
8000 (error "This should not happen"))
8001 (when (and (match-beginning 4)
8002 (> pos (match-beginning 4))
8003 (< pos (match-end 4)))
8004 (setq initial-content (buffer-substring pos (match-end 4)))
8005 (goto-char pos)
8006 (delete-region (point) (match-end 4))
8007 (if (looking-at "[ \t]*$")
8008 (replace-match "")
8009 (insert (make-string (length initial-content) ?\s)))
8010 (setq initial-content (org-trim initial-content)))
8011 (goto-char pos))
8012 ;; A normal line.
8013 (setq initial-content
8014 (org-trim
8015 (delete-and-extract-region (point) (line-end-position))))))
8017 ;; If we are at the beginning of the line, insert before it.
8018 ;; Otherwise, after it.
8019 (cond
8020 ((and (bolp) (looking-at "[ \t]*$")))
8021 ((bolp) (save-excursion (insert "\n")))
8022 (t (end-of-line)
8023 (insert "\n")))
8025 ;; Insert the new heading
8026 (insert stars)
8027 (just-one-space)
8028 (insert initial-content)
8029 (unless (and blank (org-previous-line-empty-p))
8030 (org-N-empty-lines-before-current (if blank 1 0)))
8031 ;; Adjust visibility, which may be messed up if we removed
8032 ;; blank lines while previous entry was hidden.
8033 (let ((bol (line-beginning-position)))
8034 (dolist (o (overlays-at (1- bol)))
8035 (when (and (eq (overlay-get o 'invisible) 'outline)
8036 (eq (overlay-end o) bol))
8037 (move-overlay o (overlay-start o) (1- bol)))))
8038 (run-hooks 'org-insert-heading-hook)))))))
8040 (defun org-N-empty-lines-before-current (N)
8041 "Make the number of empty lines before current exactly N.
8042 So this will delete or add empty lines."
8043 (save-excursion
8044 (beginning-of-line)
8045 (let ((p (point)))
8046 (skip-chars-backward " \r\t\n")
8047 (unless (bolp) (forward-line))
8048 (delete-region (point) p))
8049 (when (> N 0) (insert (make-string N ?\n)))))
8051 (defun org-get-heading (&optional no-tags no-todo)
8052 "Return the heading of the current entry, without the stars.
8053 When NO-TAGS is non-nil, don't include tags.
8054 When NO-TODO is non-nil, don't include TODO keywords."
8055 (save-excursion
8056 (org-back-to-heading t)
8057 (let ((case-fold-search nil))
8058 (cond
8059 ((and no-tags no-todo)
8060 (looking-at org-complex-heading-regexp)
8061 ;; Return value has to be a string, but match group 4 is
8062 ;; optional.
8063 (or (match-string 4) ""))
8064 (no-tags
8065 (looking-at (concat org-outline-regexp
8066 "\\(.*?\\)"
8067 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8068 (match-string 1))
8069 (no-todo
8070 (looking-at org-todo-line-regexp)
8071 (match-string 3))
8072 (t (looking-at org-heading-regexp)
8073 (match-string 2))))))
8075 (defvar orgstruct-mode) ; defined below
8077 (defun org-heading-components ()
8078 "Return the components of the current heading.
8079 This is a list with the following elements:
8080 - the level as an integer
8081 - the reduced level, different if `org-odd-levels-only' is set.
8082 - the TODO keyword, or nil
8083 - the priority character, like ?A, or nil if no priority is given
8084 - the headline text itself, or the tags string if no headline text
8085 - the tags string, or nil."
8086 (save-excursion
8087 (org-back-to-heading t)
8088 (when (let (case-fold-search)
8089 (looking-at
8090 (if orgstruct-mode
8091 org-heading-regexp
8092 org-complex-heading-regexp)))
8093 (if orgstruct-mode
8094 (list (length (match-string 1))
8095 (org-reduced-level (length (match-string 1)))
8098 (match-string 2)
8099 nil)
8100 (list (length (match-string 1))
8101 (org-reduced-level (length (match-string 1)))
8102 (match-string-no-properties 2)
8103 (and (match-end 3) (aref (match-string 3) 2))
8104 (match-string-no-properties 4)
8105 (match-string-no-properties 5))))))
8107 (defun org-get-entry ()
8108 "Get the entry text, after heading, entire subtree."
8109 (save-excursion
8110 (org-back-to-heading t)
8111 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8113 (defun org-edit-headline (&optional heading)
8114 "Edit the current headline.
8115 Set it to HEADING when provided."
8116 (interactive)
8117 (org-with-wide-buffer
8118 (org-back-to-heading t)
8119 (when (looking-at org-complex-heading-regexp)
8120 (let* ((old (match-string-no-properties 4))
8121 (new (save-match-data
8122 (org-trim (or heading (read-string "Edit: " old))))))
8123 (unless (equal old new)
8124 (if old (replace-match new t t nil 4)
8125 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8126 (insert " " new))
8127 (org-set-tags nil t)
8128 (when (looking-at "[ \t]*$") (replace-match "")))))))
8130 (defun org-insert-heading-after-current ()
8131 "Insert a new heading with same level as current, after current subtree."
8132 (interactive)
8133 (org-back-to-heading)
8134 (org-insert-heading)
8135 (org-move-subtree-down)
8136 (end-of-line 1))
8138 (defun org-insert-heading-respect-content (&optional invisible-ok)
8139 "Insert heading with `org-insert-heading-respect-content' set to t."
8140 (interactive)
8141 (org-insert-heading '(4) invisible-ok))
8143 (defun org-insert-todo-heading-respect-content (&optional force-state)
8144 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8145 (interactive)
8146 (org-insert-todo-heading force-state '(4)))
8148 (defun org-insert-todo-heading (arg &optional force-heading)
8149 "Insert a new heading with the same level and TODO state as current heading.
8151 If the heading has no TODO state, or if the state is DONE, use
8152 the first state (TODO by default). Also with one prefix arg,
8153 force first state. With two prefix args, force inserting at the
8154 end of the parent subtree.
8156 When called at a plain list item, insert a new item with an
8157 unchecked check box."
8158 (interactive "P")
8159 (when (or force-heading (not (org-insert-item 'checkbox)))
8160 (org-insert-heading (or (and (equal arg '(16)) '(16))
8161 force-heading))
8162 (save-excursion
8163 (org-back-to-heading)
8164 (outline-previous-heading)
8165 (looking-at org-todo-line-regexp))
8166 (let* ((new-mark-x
8167 (if (or (equal arg '(4))
8168 (not (match-beginning 2))
8169 (member (match-string 2) org-done-keywords))
8170 (car org-todo-keywords-1)
8171 (match-string 2)))
8172 (new-mark
8174 (run-hook-with-args-until-success
8175 'org-todo-get-default-hook new-mark-x nil)
8176 new-mark-x)))
8177 (beginning-of-line 1)
8178 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8179 (if org-treat-insert-todo-heading-as-state-change
8180 (org-todo new-mark)
8181 (insert new-mark " "))))
8182 (when org-provide-todo-statistics
8183 (org-update-parent-todo-statistics))))
8185 (defun org-insert-subheading (arg)
8186 "Insert a new subheading and demote it.
8187 Works for outline headings and for plain lists alike."
8188 (interactive "P")
8189 (org-insert-heading arg)
8190 (cond
8191 ((org-at-heading-p) (org-do-demote))
8192 ((org-at-item-p) (org-indent-item))))
8194 (defun org-insert-todo-subheading (arg)
8195 "Insert a new subheading with TODO keyword or checkbox and demote it.
8196 Works for outline headings and for plain lists alike."
8197 (interactive "P")
8198 (org-insert-todo-heading arg)
8199 (cond
8200 ((org-at-heading-p) (org-do-demote))
8201 ((org-at-item-p) (org-indent-item))))
8203 ;;; Promotion and Demotion
8205 (defvar org-after-demote-entry-hook nil
8206 "Hook run after an entry has been demoted.
8207 The cursor will be at the beginning of the entry.
8208 When a subtree is being demoted, the hook will be called for each node.")
8210 (defvar org-after-promote-entry-hook nil
8211 "Hook run after an entry has been promoted.
8212 The cursor will be at the beginning of the entry.
8213 When a subtree is being promoted, the hook will be called for each node.")
8215 (defun org-promote-subtree ()
8216 "Promote the entire subtree.
8217 See also `org-promote'."
8218 (interactive)
8219 (save-excursion
8220 (org-with-limited-levels (org-map-tree 'org-promote)))
8221 (org-fix-position-after-promote))
8223 (defun org-demote-subtree ()
8224 "Demote the entire subtree.
8225 See `org-demote' and `org-promote'."
8226 (interactive)
8227 (save-excursion
8228 (org-with-limited-levels (org-map-tree 'org-demote)))
8229 (org-fix-position-after-promote))
8231 (defun org-do-promote ()
8232 "Promote the current heading higher up the tree.
8233 If the region is active in `transient-mark-mode', promote all
8234 headings in the region."
8235 (interactive)
8236 (save-excursion
8237 (if (org-region-active-p)
8238 (org-map-region 'org-promote (region-beginning) (region-end))
8239 (org-promote)))
8240 (org-fix-position-after-promote))
8242 (defun org-do-demote ()
8243 "Demote the current heading lower down the tree.
8244 If the region is active in `transient-mark-mode', demote all
8245 headings in the region."
8246 (interactive)
8247 (save-excursion
8248 (if (org-region-active-p)
8249 (org-map-region 'org-demote (region-beginning) (region-end))
8250 (org-demote)))
8251 (org-fix-position-after-promote))
8253 (defun org-fix-position-after-promote ()
8254 "Fix cursor position and indentation after demoting/promoting."
8255 (let ((pos (point)))
8256 (when (save-excursion
8257 (beginning-of-line 1)
8258 (looking-at org-todo-line-regexp)
8259 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8260 (cond ((eobp) (insert " "))
8261 ((eolp) (insert " "))
8262 ((equal (char-after) ?\ ) (forward-char 1))))))
8264 (defun org-current-level ()
8265 "Return the level of the current entry, or nil if before the first headline.
8266 The level is the number of stars at the beginning of the
8267 headline. Use `org-reduced-level' to remove the effect of
8268 `org-odd-levels'. Unlike to `org-outline-level', this function
8269 ignores inlinetasks."
8270 (let ((level (org-with-limited-levels (org-outline-level))))
8271 (and (> level 0) level)))
8273 (defun org-get-previous-line-level ()
8274 "Return the outline depth of the last headline before the current line.
8275 Returns 0 for the first headline in the buffer, and nil if before the
8276 first headline."
8277 (and (org-current-level)
8278 (or (and (/= (line-beginning-position) (point-min))
8279 (save-excursion (beginning-of-line 0) (org-current-level)))
8280 0)))
8282 (defun org-reduced-level (l)
8283 "Compute the effective level of a heading.
8284 This takes into account the setting of `org-odd-levels-only'."
8285 (cond
8286 ((zerop l) 0)
8287 (org-odd-levels-only (1+ (floor (/ l 2))))
8288 (t l)))
8290 (defun org-level-increment ()
8291 "Return the number of stars that will be added or removed at a
8292 time to headlines when structure editing, based on the value of
8293 `org-odd-levels-only'."
8294 (if org-odd-levels-only 2 1))
8296 (defun org-get-valid-level (level &optional change)
8297 "Rectify a level change under the influence of `org-odd-levels-only'
8298 LEVEL is a current level, CHANGE is by how much the level should be
8299 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8300 even level numbers will become the next higher odd number."
8301 (if org-odd-levels-only
8302 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8303 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8304 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8305 (max 1 (+ level (or change 0)))))
8307 (defun org-promote ()
8308 "Promote the current heading higher up the tree."
8309 (org-with-wide-buffer
8310 (org-back-to-heading t)
8311 (let* ((after-change-functions (remq 'flyspell-after-change-function
8312 after-change-functions))
8313 (level (save-match-data (funcall outline-level)))
8314 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8315 (diff (abs (- level (length up-head) -1))))
8316 (cond
8317 ((and (= level 1) org-allow-promoting-top-level-subtree)
8318 (replace-match "# " nil t))
8319 ((= level 1)
8320 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8321 (t (replace-match up-head nil t)))
8322 (unless (= level 1)
8323 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8324 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8325 (run-hooks 'org-after-promote-entry-hook))))
8327 (defun org-demote ()
8328 "Demote the current heading lower down the tree."
8329 (org-with-wide-buffer
8330 (org-back-to-heading t)
8331 (let* ((after-change-functions (remq 'flyspell-after-change-function
8332 after-change-functions))
8333 (level (save-match-data (funcall outline-level)))
8334 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8335 (diff (abs (- level (length down-head) -1))))
8336 (replace-match down-head nil t)
8337 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8338 (when org-adapt-indentation (org-fixup-indentation diff))
8339 (run-hooks 'org-after-demote-entry-hook))))
8341 (defun org-cycle-level ()
8342 "Cycle the level of an empty headline through possible states.
8343 This goes first to child, then to parent, level, then up the hierarchy.
8344 After top level, it switches back to sibling level."
8345 (interactive)
8346 (let ((org-adapt-indentation nil))
8347 (when (org-point-at-end-of-empty-headline)
8348 (setq this-command 'org-cycle-level) ; Only needed for caching
8349 (let ((cur-level (org-current-level))
8350 (prev-level (org-get-previous-line-level)))
8351 (cond
8352 ;; If first headline in file, promote to top-level.
8353 ((= prev-level 0)
8354 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8355 do (org-do-promote)))
8356 ;; If same level as prev, demote one.
8357 ((= prev-level cur-level)
8358 (org-do-demote))
8359 ;; If parent is top-level, promote to top level if not already.
8360 ((= prev-level 1)
8361 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8362 do (org-do-promote)))
8363 ;; If top-level, return to prev-level.
8364 ((= cur-level 1)
8365 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8366 do (org-do-demote)))
8367 ;; If less than prev-level, promote one.
8368 ((< cur-level prev-level)
8369 (org-do-promote))
8370 ;; If deeper than prev-level, promote until higher than
8371 ;; prev-level.
8372 ((> cur-level prev-level)
8373 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8374 do (org-do-promote))))
8375 t))))
8377 (defun org-map-tree (fun)
8378 "Call FUN for every heading underneath the current one."
8379 (org-back-to-heading t)
8380 (let ((level (funcall outline-level)))
8381 (save-excursion
8382 (funcall fun)
8383 (while (and (progn
8384 (outline-next-heading)
8385 (> (funcall outline-level) level))
8386 (not (eobp)))
8387 (funcall fun)))))
8389 (defun org-map-region (fun beg end)
8390 "Call FUN for every heading between BEG and END."
8391 (let ((org-ignore-region t))
8392 (save-excursion
8393 (setq end (copy-marker end))
8394 (goto-char beg)
8395 (when (and (re-search-forward org-outline-regexp-bol nil t)
8396 (< (point) end))
8397 (funcall fun))
8398 (while (and (progn
8399 (outline-next-heading)
8400 (< (point) end))
8401 (not (eobp)))
8402 (funcall fun)))))
8404 (defun org-fixup-indentation (diff)
8405 "Change the indentation in the current entry by DIFF.
8407 DIFF is an integer. Indentation is done according to the
8408 following rules:
8410 - Planning information and property drawers are always indented
8411 according to the new level of the headline;
8413 - Footnote definitions and their contents are ignored;
8415 - Inlinetasks' boundaries are not shifted;
8417 - Empty lines are ignored;
8419 - Other lines' indentation are shifted by DIFF columns, unless
8420 it would introduce a structural change in the document, in
8421 which case no shifting is done at all.
8423 Assume point is at a heading or an inlinetask beginning."
8424 (org-with-wide-buffer
8425 (narrow-to-region (line-beginning-position)
8426 (save-excursion
8427 (if (org-with-limited-levels (org-at-heading-p))
8428 (org-with-limited-levels (outline-next-heading))
8429 (org-inlinetask-goto-end))
8430 (point)))
8431 (forward-line)
8432 ;; Indent properly planning info and property drawer.
8433 (when (looking-at-p org-planning-line-re)
8434 (org-indent-line)
8435 (forward-line))
8436 (when (looking-at org-property-drawer-re)
8437 (goto-char (match-end 0))
8438 (forward-line)
8439 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8440 (catch 'no-shift
8441 (when (zerop diff) (throw 'no-shift nil))
8442 ;; If DIFF is negative, first check if a shift is possible at all
8443 ;; (e.g., it doesn't break structure). This can only happen if
8444 ;; some contents are not properly indented.
8445 (let ((case-fold-search t))
8446 (when (< diff 0)
8447 (let ((diff (- diff))
8448 (forbidden-re (concat org-outline-regexp
8449 "\\|"
8450 (substring org-footnote-definition-re 1))))
8451 (save-excursion
8452 (while (not (eobp))
8453 (cond
8454 ((looking-at-p "[ \t]*$") (forward-line))
8455 ((and (looking-at-p org-footnote-definition-re)
8456 (let ((e (org-element-at-point)))
8457 (and (eq (org-element-type e) 'footnote-definition)
8458 (goto-char (org-element-property :end e))))))
8459 ((looking-at-p org-outline-regexp) (forward-line))
8460 ;; Give up if shifting would move before column 0 or
8461 ;; if it would introduce a headline or a footnote
8462 ;; definition.
8464 (skip-chars-forward " \t")
8465 (let ((ind (current-column)))
8466 (when (or (< ind diff)
8467 (and (= ind diff) (looking-at-p forbidden-re)))
8468 (throw 'no-shift nil)))
8469 ;; Ignore contents of example blocks and source
8470 ;; blocks if their indentation is meant to be
8471 ;; preserved. Jump to block's closing line.
8472 (beginning-of-line)
8473 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8474 (let ((e (org-element-at-point)))
8475 (and (memq (org-element-type e)
8476 '(example-block src-block))
8477 (or org-src-preserve-indentation
8478 (org-element-property :preserve-indent e))
8479 (goto-char (org-element-property :end e))
8480 (progn (skip-chars-backward " \r\t\n")
8481 (beginning-of-line)
8482 t))))
8483 (forward-line))))))))
8484 ;; Shift lines but footnote definitions, inlinetasks boundaries
8485 ;; by DIFF. Also skip contents of source or example blocks
8486 ;; when indentation is meant to be preserved.
8487 (while (not (eobp))
8488 (cond
8489 ((and (looking-at-p org-footnote-definition-re)
8490 (let ((e (org-element-at-point)))
8491 (and (eq (org-element-type e) 'footnote-definition)
8492 (goto-char (org-element-property :end e))))))
8493 ((looking-at-p org-outline-regexp) (forward-line))
8494 ((looking-at-p "[ \t]*$") (forward-line))
8496 (indent-line-to (+ (org-get-indentation) diff))
8497 (beginning-of-line)
8498 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8499 (let ((e (org-element-at-point)))
8500 (and (memq (org-element-type e)
8501 '(example-block src-block))
8502 (or org-src-preserve-indentation
8503 (org-element-property :preserve-indent e))
8504 (goto-char (org-element-property :end e))
8505 (progn (skip-chars-backward " \r\t\n")
8506 (beginning-of-line)
8507 t))))
8508 (forward-line)))))))))
8510 (defun org-convert-to-odd-levels ()
8511 "Convert an Org file with all levels allowed to one with odd levels.
8512 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8513 level 5 etc."
8514 (interactive)
8515 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8516 (let ((outline-level 'org-outline-level)
8517 (org-odd-levels-only nil) n)
8518 (save-excursion
8519 (goto-char (point-min))
8520 (while (re-search-forward "^\\*\\*+ " nil t)
8521 (setq n (- (length (match-string 0)) 2))
8522 (while (>= (setq n (1- n)) 0)
8523 (org-demote))
8524 (end-of-line 1))))))
8526 (defun org-convert-to-oddeven-levels ()
8527 "Convert an Org file with only odd levels to one with odd/even levels.
8528 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8529 file contains a section with an even level, conversion would
8530 destroy the structure of the file. An error is signaled in this
8531 case."
8532 (interactive)
8533 (goto-char (point-min))
8534 ;; First check if there are no even levels
8535 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8536 (org-show-set-visibility 'canonical)
8537 (error "Not all levels are odd in this file. Conversion not possible"))
8538 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8539 (let ((outline-regexp org-outline-regexp)
8540 (outline-level 'org-outline-level)
8541 (org-odd-levels-only nil) n)
8542 (save-excursion
8543 (goto-char (point-min))
8544 (while (re-search-forward "^\\*\\*+ " nil t)
8545 (setq n (/ (1- (length (match-string 0))) 2))
8546 (while (>= (setq n (1- n)) 0)
8547 (org-promote))
8548 (end-of-line 1))))))
8550 (defun org-tr-level (n)
8551 "Make N odd if required."
8552 (if org-odd-levels-only (1+ (/ n 2)) n))
8554 ;;; Vertical tree motion, cutting and pasting of subtrees
8556 (defun org-move-subtree-up (&optional arg)
8557 "Move the current subtree up past ARG headlines of the same level."
8558 (interactive "p")
8559 (org-move-subtree-down (- (prefix-numeric-value arg))))
8561 (defun org-move-subtree-down (&optional arg)
8562 "Move the current subtree down past ARG headlines of the same level."
8563 (interactive "p")
8564 (setq arg (prefix-numeric-value arg))
8565 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8566 'org-get-last-sibling))
8567 (ins-point (make-marker))
8568 (cnt (abs arg))
8569 (col (current-column))
8570 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8571 ;; Select the tree
8572 (org-back-to-heading)
8573 (setq beg0 (point))
8574 (save-excursion
8575 (setq ne-beg (org-back-over-empty-lines))
8576 (setq beg (point)))
8577 (save-match-data
8578 (save-excursion (outline-end-of-heading)
8579 (setq folded (outline-invisible-p)))
8580 (progn (org-end-of-subtree nil t)
8581 (unless (eobp) (backward-char))))
8582 (outline-next-heading)
8583 (setq ne-end (org-back-over-empty-lines))
8584 (setq end (point))
8585 (goto-char beg0)
8586 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8587 ;; include less whitespace
8588 (save-excursion
8589 (goto-char beg)
8590 (forward-line (- ne-beg ne-end))
8591 (setq beg (point))))
8592 ;; Find insertion point, with error handling
8593 (while (> cnt 0)
8594 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8595 (progn (goto-char beg0)
8596 (user-error "Cannot move past superior level or buffer limit")))
8597 (setq cnt (1- cnt)))
8598 (when (> arg 0)
8599 ;; Moving forward - still need to move over subtree
8600 (org-end-of-subtree t t)
8601 (save-excursion
8602 (org-back-over-empty-lines)
8603 (or (bolp) (newline))))
8604 (setq ne-ins (org-back-over-empty-lines))
8605 (move-marker ins-point (point))
8606 (setq txt (buffer-substring beg end))
8607 (org-save-markers-in-region beg end)
8608 (delete-region beg end)
8609 (org-remove-empty-overlays-at beg)
8610 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8611 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8612 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8613 (let ((bbb (point)))
8614 (insert-before-markers txt)
8615 (org-reinstall-markers-in-region bbb)
8616 (move-marker ins-point bbb))
8617 (or (bolp) (insert "\n"))
8618 (setq ins-end (point))
8619 (goto-char ins-point)
8620 (org-skip-whitespace)
8621 (when (and (< arg 0)
8622 (org-first-sibling-p)
8623 (> ne-ins ne-beg))
8624 ;; Move whitespace back to beginning
8625 (save-excursion
8626 (goto-char ins-end)
8627 (let ((kill-whole-line t))
8628 (kill-line (- ne-ins ne-beg)) (point)))
8629 (insert (make-string (- ne-ins ne-beg) ?\n)))
8630 (move-marker ins-point nil)
8631 (if folded
8632 (outline-hide-subtree)
8633 (org-show-entry)
8634 (org-show-children)
8635 (org-cycle-hide-drawers 'children))
8636 (org-clean-visibility-after-subtree-move)
8637 ;; move back to the initial column we were at
8638 (move-to-column col)))
8640 (defvar org-subtree-clip ""
8641 "Clipboard for cut and paste of subtrees.
8642 This is actually only a copy of the kill, because we use the normal kill
8643 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8645 (defvar org-subtree-clip-folded nil
8646 "Was the last copied subtree folded?
8647 This is used to fold the tree back after pasting.")
8649 (defun org-cut-subtree (&optional n)
8650 "Cut the current subtree into the clipboard.
8651 With prefix arg N, cut this many sequential subtrees.
8652 This is a short-hand for marking the subtree and then cutting it."
8653 (interactive "p")
8654 (org-copy-subtree n 'cut))
8656 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8657 "Copy the current subtree it in the clipboard.
8658 With prefix arg N, copy this many sequential subtrees.
8659 This is a short-hand for marking the subtree and then copying it.
8660 If CUT is non-nil, actually cut the subtree.
8661 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8662 of some markers in the region, even if CUT is non-nil. This is
8663 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8664 (interactive "p")
8665 (let (beg end folded (beg0 (point)))
8666 (if (called-interactively-p 'any)
8667 (org-back-to-heading nil) ; take what looks like a subtree
8668 (org-back-to-heading t)) ; take what is really there
8669 (setq beg (point))
8670 (skip-chars-forward " \t\r\n")
8671 (save-match-data
8672 (if nosubtrees
8673 (outline-next-heading)
8674 (save-excursion (outline-end-of-heading)
8675 (setq folded (outline-invisible-p)))
8676 (ignore-errors (org-forward-heading-same-level (1- n) t))
8677 (org-end-of-subtree t t)))
8678 ;; Include the end of an inlinetask
8679 (when (and (featurep 'org-inlinetask)
8680 (looking-at-p (concat (org-inlinetask-outline-regexp)
8681 "END[ \t]*$")))
8682 (end-of-line))
8683 (setq end (point))
8684 (goto-char beg0)
8685 (when (> end beg)
8686 (setq org-subtree-clip-folded folded)
8687 (when (or cut force-store-markers)
8688 (org-save-markers-in-region beg end))
8689 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8690 (setq org-subtree-clip (current-kill 0))
8691 (message "%s: Subtree(s) with %d characters"
8692 (if cut "Cut" "Copied")
8693 (length org-subtree-clip)))))
8695 (defun org-paste-subtree (&optional level tree for-yank remove)
8696 "Paste the clipboard as a subtree, with modification of headline level.
8697 The entire subtree is promoted or demoted in order to match a new headline
8698 level.
8700 If the cursor is at the beginning of a headline, the same level as
8701 that headline is used to paste the tree.
8703 If not, the new level is derived from the *visible* headings
8704 before and after the insertion point, and taken to be the inferior headline
8705 level of the two. So if the previous visible heading is level 3 and the
8706 next is level 4 (or vice versa), level 4 will be used for insertion.
8707 This makes sure that the subtree remains an independent subtree and does
8708 not swallow low level entries.
8710 You can also force a different level, either by using a numeric prefix
8711 argument, or by inserting the heading marker by hand. For example, if the
8712 cursor is after \"*****\", then the tree will be shifted to level 5.
8714 If optional TREE is given, use this text instead of the kill ring.
8716 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8717 move back over whitespace before inserting, and move point to the end of
8718 the inserted text when done.
8720 When REMOVE is non-nil, remove the subtree from the clipboard."
8721 (interactive "P")
8722 (setq tree (or tree (and kill-ring (current-kill 0))))
8723 (unless (org-kill-is-subtree-p tree)
8724 (user-error "%s"
8725 (substitute-command-keys
8726 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8727 (org-with-limited-levels
8728 (let* ((visp (not (outline-invisible-p)))
8729 (txt tree)
8730 (^re_ "\\(\\*+\\)[ \t]*")
8731 (old-level (if (string-match org-outline-regexp-bol txt)
8732 (- (match-end 0) (match-beginning 0) 1)
8733 -1))
8734 (force-level (cond (level (prefix-numeric-value level))
8735 ((and (looking-at "[ \t]*$")
8736 (string-match
8737 "^\\*+$" (buffer-substring
8738 (point-at-bol) (point))))
8739 (- (match-end 0) (match-beginning 0)))
8740 ((and (bolp)
8741 (looking-at org-outline-regexp))
8742 (- (match-end 0) (point) 1))))
8743 (previous-level (save-excursion
8744 (condition-case nil
8745 (progn
8746 (outline-previous-visible-heading 1)
8747 (if (looking-at ^re_)
8748 (- (match-end 0) (match-beginning 0) 1)
8750 (error 1))))
8751 (next-level (save-excursion
8752 (condition-case nil
8753 (progn
8754 (or (looking-at org-outline-regexp)
8755 (outline-next-visible-heading 1))
8756 (if (looking-at ^re_)
8757 (- (match-end 0) (match-beginning 0) 1)
8759 (error 1))))
8760 (new-level (or force-level (max previous-level next-level)))
8761 (shift (if (or (= old-level -1)
8762 (= new-level -1)
8763 (= old-level new-level))
8765 (- new-level old-level)))
8766 (delta (if (> shift 0) -1 1))
8767 (func (if (> shift 0) 'org-demote 'org-promote))
8768 (org-odd-levels-only nil)
8769 beg end newend)
8770 ;; Remove the forced level indicator
8771 (when force-level
8772 (delete-region (point-at-bol) (point)))
8773 ;; Paste
8774 (beginning-of-line (if (bolp) 1 2))
8775 (setq beg (point))
8776 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8777 (insert-before-markers txt)
8778 (unless (string-suffix-p "\n" txt) (insert "\n"))
8779 (setq newend (point))
8780 (org-reinstall-markers-in-region beg)
8781 (setq end (point))
8782 (goto-char beg)
8783 (skip-chars-forward " \t\n\r")
8784 (setq beg (point))
8785 (when (and (outline-invisible-p) visp)
8786 (save-excursion (outline-show-heading)))
8787 ;; Shift if necessary
8788 (unless (= shift 0)
8789 (save-restriction
8790 (narrow-to-region beg end)
8791 (while (not (= shift 0))
8792 (org-map-region func (point-min) (point-max))
8793 (setq shift (+ delta shift)))
8794 (goto-char (point-min))
8795 (setq newend (point-max))))
8796 (when (or (called-interactively-p 'interactive) for-yank)
8797 (message "Clipboard pasted as level %d subtree" new-level))
8798 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8799 kill-ring
8800 (eq org-subtree-clip (current-kill 0))
8801 org-subtree-clip-folded)
8802 ;; The tree was folded before it was killed/copied
8803 (outline-hide-subtree))
8804 (and for-yank (goto-char newend))
8805 (and remove (setq kill-ring (cdr kill-ring))))))
8807 (defun org-kill-is-subtree-p (&optional txt)
8808 "Check if the current kill is an outline subtree, or a set of trees.
8809 Returns nil if kill does not start with a headline, or if the first
8810 headline level is not the largest headline level in the tree.
8811 So this will actually accept several entries of equal levels as well,
8812 which is OK for `org-paste-subtree'.
8813 If optional TXT is given, check this string instead of the current kill."
8814 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8815 (re (org-get-limited-outline-regexp))
8816 (^re (concat "^" re))
8817 (start-level (and kill
8818 (string-match
8819 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8820 kill)
8821 (- (match-end 2) (match-beginning 2) 1)))
8822 (start (1+ (or (match-beginning 2) -1))))
8823 (if (not start-level)
8824 (progn
8825 nil) ;; does not even start with a heading
8826 (catch 'exit
8827 (while (setq start (string-match ^re kill (1+ start)))
8828 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8829 (throw 'exit nil)))
8830 t))))
8832 (defvar org-markers-to-move nil
8833 "Markers that should be moved with a cut-and-paste operation.
8834 Those markers are stored together with their positions relative to
8835 the start of the region.")
8837 (defun org-save-markers-in-region (beg end)
8838 "Check markers in region.
8839 If these markers are between BEG and END, record their position relative
8840 to BEG, so that after moving the block of text, we can put the markers back
8841 into place.
8842 This function gets called just before an entry or tree gets cut from the
8843 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8844 called immediately, to move the markers with the entries."
8845 (setq org-markers-to-move nil)
8846 (when (featurep 'org-clock)
8847 (org-clock-save-markers-for-cut-and-paste beg end))
8848 (when (featurep 'org-agenda)
8849 (org-agenda-save-markers-for-cut-and-paste beg end)))
8851 (defun org-check-and-save-marker (marker beg end)
8852 "Check if MARKER is between BEG and END.
8853 If yes, remember the marker and the distance to BEG."
8854 (when (and (marker-buffer marker)
8855 (equal (marker-buffer marker) (current-buffer))
8856 (>= marker beg) (< marker end))
8857 (push (cons marker (- marker beg)) org-markers-to-move)))
8859 (defun org-reinstall-markers-in-region (beg)
8860 "Move all remembered markers to their position relative to BEG."
8861 (dolist (x org-markers-to-move)
8862 (move-marker (car x) (+ beg (cdr x))))
8863 (setq org-markers-to-move nil))
8865 (defun org-narrow-to-subtree ()
8866 "Narrow buffer to the current subtree."
8867 (interactive)
8868 (save-excursion
8869 (save-match-data
8870 (org-with-limited-levels
8871 (narrow-to-region
8872 (progn (org-back-to-heading t) (point))
8873 (progn (org-end-of-subtree t t)
8874 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8875 (point)))))))
8877 (defun org-narrow-to-block ()
8878 "Narrow buffer to the current block."
8879 (interactive)
8880 (let* ((case-fold-search t)
8881 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8882 "^[ \t]*#\\+end_.*")))
8883 (if blockp
8884 (narrow-to-region (car blockp) (cdr blockp))
8885 (user-error "Not in a block"))))
8887 (defun org-clone-subtree-with-time-shift (n &optional shift)
8888 "Clone the task (subtree) at point N times.
8889 The clones will be inserted as siblings.
8891 In interactive use, the user will be prompted for the number of
8892 clones to be produced. If the entry has a timestamp, the user
8893 will also be prompted for a time shift, which may be a repeater
8894 as used in time stamps, for example `+3d'. To disable this,
8895 you can call the function with a universal prefix argument.
8897 When a valid repeater is given and the entry contains any time
8898 stamps, the clones will become a sequence in time, with time
8899 stamps in the subtree shifted for each clone produced. If SHIFT
8900 is nil or the empty string, time stamps will be left alone. The
8901 ID property of the original subtree is removed.
8903 In each clone, all the CLOCK entries will be removed. This
8904 prevents Org from considering that the clocked times overlap.
8906 If the original subtree did contain time stamps with a repeater,
8907 the following will happen:
8908 - the repeater will be removed in each clone
8909 - an additional clone will be produced, with the current, unshifted
8910 date(s) in the entry.
8911 - the original entry will be placed *after* all the clones, with
8912 repeater intact.
8913 - the start days in the repeater in the original entry will be shifted
8914 to past the last clone.
8915 In this way you can spell out a number of instances of a repeating task,
8916 and still retain the repeater to cover future instances of the task.
8918 As described above, N+1 clones are produced when the original
8919 subtree has a repeater. Setting N to 0, then, can be used to
8920 remove the repeater from a subtree and create a shifted clone
8921 with the original repeater."
8922 (interactive "nNumber of clones to produce: ")
8923 (let ((shift
8924 (or shift
8925 (if (and (not (equal current-prefix-arg '(4)))
8926 (save-excursion
8927 (re-search-forward org-ts-regexp-both
8928 (save-excursion
8929 (org-end-of-subtree t)
8930 (point)) t)))
8931 (read-from-minibuffer
8932 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8933 ""))) ;; No time shift
8934 (n-no-remove -1)
8935 (drawer-re org-drawer-regexp)
8936 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8937 beg end template task idprop
8938 shift-n shift-what doshift nmin nmax)
8939 (unless (wholenump n)
8940 (user-error "Invalid number of replications %s" n))
8941 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8942 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8943 shift)))
8944 (user-error "Invalid shift specification %s" shift))
8945 (when doshift
8946 (setq shift-n (string-to-number (match-string 1 shift))
8947 shift-what (cdr (assoc (match-string 2 shift)
8948 '(("d" . day) ("w" . week)
8949 ("m" . month) ("y" . year))))))
8950 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8951 (setq nmin 1 nmax n)
8952 (org-back-to-heading t)
8953 (setq beg (point))
8954 (setq idprop (org-entry-get nil "ID"))
8955 (org-end-of-subtree t t)
8956 (or (bolp) (insert "\n"))
8957 (setq end (point))
8958 (setq template (buffer-substring beg end))
8959 (when (and doshift
8960 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8961 (delete-region beg end)
8962 (setq end beg)
8963 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8964 (goto-char end)
8965 (cl-loop for n from nmin to nmax do
8966 ;; prepare clone
8967 (with-temp-buffer
8968 (insert template)
8969 (org-mode)
8970 (goto-char (point-min))
8971 (org-show-subtree)
8972 (and idprop (if org-clone-delete-id
8973 (org-entry-delete nil "ID")
8974 (org-id-get-create t)))
8975 (unless (= n 0)
8976 (while (re-search-forward org-clock-re nil t)
8977 (kill-whole-line))
8978 (goto-char (point-min))
8979 (while (re-search-forward drawer-re nil t)
8980 (org-remove-empty-drawer-at (point))))
8981 (goto-char (point-min))
8982 (when doshift
8983 (while (re-search-forward org-ts-regexp-both nil t)
8984 (org-timestamp-change (* n shift-n) shift-what))
8985 (unless (= n n-no-remove)
8986 (goto-char (point-min))
8987 (while (re-search-forward org-ts-regexp nil t)
8988 (save-excursion
8989 (goto-char (match-beginning 0))
8990 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8991 (delete-region (match-beginning 1) (match-end 1)))))))
8992 (setq task (buffer-string)))
8993 (insert task))
8994 (goto-char beg)))
8996 ;;; Outline Sorting
8998 (defun org-sort (with-case)
8999 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9000 Optional argument WITH-CASE means sort case-sensitively."
9001 (interactive "P")
9002 (cond
9003 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9004 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9006 (org-call-with-arg 'org-sort-entries with-case))))
9008 (defun org-sort-remove-invisible (s)
9009 "Remove invisible links from string S."
9010 (remove-text-properties 0 (length s) org-rm-props s)
9011 (while (string-match org-bracket-link-regexp s)
9012 (setq s (replace-match (if (match-end 2)
9013 (match-string 3 s)
9014 (match-string 1 s))
9015 t t s)))
9016 (let ((st (format " %s " s)))
9017 (while (string-match org-emph-re st)
9018 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9019 (setq s (substring st 1 -1)))
9022 (defvar org-priority-regexp) ; defined later in the file
9024 (defvar org-after-sorting-entries-or-items-hook nil
9025 "Hook that is run after a bunch of entries or items have been sorted.
9026 When children are sorted, the cursor is in the parent line when this
9027 hook gets called. When a region or a plain list is sorted, the cursor
9028 will be in the first entry of the sorted region/list.")
9030 (defun org-sort-entries
9031 (&optional with-case sorting-type getkey-func compare-func property)
9032 "Sort entries on a certain level of an outline tree.
9033 If there is an active region, the entries in the region are sorted.
9034 Else, if the cursor is before the first entry, sort the top-level items.
9035 Else, the children of the entry at point are sorted.
9037 Sorting can be alphabetically, numerically, by date/time as given by
9038 a time stamp, by a property, by priority order, or by a custom function.
9040 The command prompts for the sorting type unless it has been given to the
9041 function through the SORTING-TYPE argument, which needs to be a character,
9042 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9043 the precise meaning of each character:
9045 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9046 c By creation time, which is assumed to be the first inactive time stamp
9047 at the beginning of a line.
9048 d By deadline date/time.
9049 k By clocking time.
9050 n Numerically, by converting the beginning of the entry/item to a number.
9051 o By order of TODO keywords.
9052 p By priority according to the cookie.
9053 r By the value of a property.
9054 s By scheduled date/time.
9055 t By date/time, either the first active time stamp in the entry, or, if
9056 none exist, by the first inactive one.
9058 Capital letters will reverse the sort order.
9060 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9061 called with point at the beginning of the record. It must return either
9062 a string or a number that should serve as the sorting key for that record.
9064 Comparing entries ignores case by default. However, with an optional argument
9065 WITH-CASE, the sorting considers case as well.
9067 Sorting is done against the visible part of the headlines, it ignores hidden
9068 links.
9070 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9071 (interactive "P")
9072 (let ((case-func (if with-case 'identity 'downcase))
9073 (cmstr
9074 ;; The clock marker is lost when using `sort-subr', let's
9075 ;; store the clocking string.
9076 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9077 (save-excursion
9078 (goto-char org-clock-marker)
9079 (buffer-substring-no-properties (line-beginning-position)
9080 (point)))))
9081 start beg end stars re re2
9082 txt what tmp)
9083 ;; Find beginning and end of region to sort
9084 (cond
9085 ((org-region-active-p)
9086 ;; we will sort the region
9087 (setq end (region-end)
9088 what "region")
9089 (goto-char (region-beginning))
9090 (unless (org-at-heading-p) (outline-next-heading))
9091 (setq start (point)))
9092 ((or (org-at-heading-p)
9093 (ignore-errors (progn (org-back-to-heading) t)))
9094 ;; we will sort the children of the current headline
9095 (org-back-to-heading)
9096 (setq start (point)
9097 end (progn (org-end-of-subtree t t)
9098 (or (bolp) (insert "\n"))
9099 (when (>= (org-back-over-empty-lines) 1)
9100 (forward-line 1))
9101 (point))
9102 what "children")
9103 (goto-char start)
9104 (outline-show-subtree)
9105 (outline-next-heading))
9107 ;; we will sort the top-level entries in this file
9108 (goto-char (point-min))
9109 (or (org-at-heading-p) (outline-next-heading))
9110 (setq start (point))
9111 (goto-char (point-max))
9112 (beginning-of-line 1)
9113 (when (looking-at ".*?\\S-")
9114 ;; File ends in a non-white line
9115 (end-of-line 1)
9116 (insert "\n"))
9117 (setq end (point-max))
9118 (setq what "top-level")
9119 (goto-char start)
9120 (outline-show-all)))
9122 (setq beg (point))
9123 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9125 (looking-at "\\(\\*+\\)")
9126 (setq stars (match-string 1)
9127 re (concat "^" (regexp-quote stars) " +")
9128 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9129 txt (buffer-substring beg end))
9130 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9131 (when (and (not (equal stars "*")) (string-match re2 txt))
9132 (user-error "Region to sort contains a level above the first entry"))
9134 (unless sorting-type
9135 (message
9136 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9137 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9138 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9139 what)
9140 (setq sorting-type (read-char-exclusive))
9142 (unless getkey-func
9143 (and (= (downcase sorting-type) ?f)
9144 (setq getkey-func
9145 (completing-read "Sort using function: "
9146 obarray 'fboundp t nil nil))
9147 (setq getkey-func (intern getkey-func))))
9149 (and (= (downcase sorting-type) ?r)
9150 (not property)
9151 (setq property
9152 (completing-read "Property: "
9153 (mapcar #'list (org-buffer-property-keys t))
9154 nil t))))
9156 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9157 (message "Sorting entries...")
9159 (save-restriction
9160 (narrow-to-region start end)
9161 (let ((dcst (downcase sorting-type))
9162 (case-fold-search nil)
9163 (now (current-time)))
9164 (sort-subr
9165 (/= dcst sorting-type)
9166 ;; This function moves to the beginning character of the "record" to
9167 ;; be sorted.
9168 (lambda nil
9169 (if (re-search-forward re nil t)
9170 (goto-char (match-beginning 0))
9171 (goto-char (point-max))))
9172 ;; This function moves to the last character of the "record" being
9173 ;; sorted.
9174 (lambda nil
9175 (save-match-data
9176 (condition-case nil
9177 (outline-forward-same-level 1)
9178 (error
9179 (goto-char (point-max))))))
9180 ;; This function returns the value that gets sorted against.
9181 (lambda nil
9182 (cond
9183 ((= dcst ?n)
9184 (if (looking-at org-complex-heading-regexp)
9185 (string-to-number (org-sort-remove-invisible (match-string 4)))
9186 nil))
9187 ((= dcst ?a)
9188 (if (looking-at org-complex-heading-regexp)
9189 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9190 nil))
9191 ((= dcst ?k)
9192 (or (get-text-property (point) :org-clock-minutes) 0))
9193 ((= dcst ?t)
9194 (let ((end (save-excursion (outline-next-heading) (point))))
9195 (if (or (re-search-forward org-ts-regexp end t)
9196 (re-search-forward org-ts-regexp-both end t))
9197 (org-time-string-to-seconds (match-string 0))
9198 (float-time now))))
9199 ((= dcst ?c)
9200 (let ((end (save-excursion (outline-next-heading) (point))))
9201 (if (re-search-forward
9202 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9203 end t)
9204 (org-time-string-to-seconds (match-string 0))
9205 (float-time now))))
9206 ((= dcst ?s)
9207 (let ((end (save-excursion (outline-next-heading) (point))))
9208 (if (re-search-forward org-scheduled-time-regexp end t)
9209 (org-time-string-to-seconds (match-string 1))
9210 (float-time now))))
9211 ((= dcst ?d)
9212 (let ((end (save-excursion (outline-next-heading) (point))))
9213 (if (re-search-forward org-deadline-time-regexp end t)
9214 (org-time-string-to-seconds (match-string 1))
9215 (float-time now))))
9216 ((= dcst ?p)
9217 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9218 (string-to-char (match-string 2))
9219 org-default-priority))
9220 ((= dcst ?r)
9221 (or (org-entry-get nil property) ""))
9222 ((= dcst ?o)
9223 (when (looking-at org-complex-heading-regexp)
9224 (let* ((m (match-string 2))
9225 (s (if (member m org-done-keywords) '- '+)))
9226 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9227 ((= dcst ?f)
9228 (if getkey-func
9229 (progn
9230 (setq tmp (funcall getkey-func))
9231 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9232 tmp)
9233 (error "Invalid key function `%s'" getkey-func)))
9234 (t (error "Invalid sorting type `%c'" sorting-type))))
9236 (cond
9237 ((= dcst ?a) 'string<)
9238 ((= dcst ?f) compare-func)
9239 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9240 (run-hooks 'org-after-sorting-entries-or-items-hook)
9241 ;; Reset the clock marker if needed
9242 (when cmstr
9243 (save-excursion
9244 (goto-char start)
9245 (search-forward cmstr nil t)
9246 (move-marker org-clock-marker (point))))
9247 (message "Sorting entries...done")))
9249 ;;; The orgstruct minor mode
9251 ;; Define a minor mode which can be used in other modes in order to
9252 ;; integrate the Org mode structure editing commands.
9254 ;; This is really a hack, because the Org mode structure commands use
9255 ;; keys which normally belong to the major mode. Here is how it
9256 ;; works: The minor mode defines all the keys necessary to operate the
9257 ;; structure commands, but wraps the commands into a function which
9258 ;; tests if the cursor is currently at a headline or a plain list
9259 ;; item. If that is the case, the structure command is used,
9260 ;; temporarily setting many Org mode variables like regular
9261 ;; expressions for filling etc. However, when any of those keys is
9262 ;; used at a different location, function uses `key-binding' to look
9263 ;; up if the key has an associated command in another currently active
9264 ;; keymap (minor modes, major mode, global), and executes that
9265 ;; command. There might be problems if any of the keys is otherwise
9266 ;; used as a prefix key.
9268 (defcustom orgstruct-heading-prefix-regexp ""
9269 "Regexp that matches the custom prefix of Org headlines in
9270 orgstruct(++)-mode."
9271 :group 'org
9272 :version "24.4"
9273 :package-version '(Org . "8.3")
9274 :type 'regexp)
9275 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9277 (defcustom orgstruct-setup-hook nil
9278 "Hook run after orgstruct-mode-map is filled."
9279 :group 'org
9280 :version "24.4"
9281 :package-version '(Org . "8.0")
9282 :type 'hook)
9284 (defvar orgstruct-initialized nil)
9286 (defvar org-local-vars nil
9287 "List of local variables, for use by `orgstruct-mode'.")
9289 ;;;###autoload
9290 (define-minor-mode orgstruct-mode
9291 "Toggle the minor mode `orgstruct-mode'.
9292 This mode is for using Org mode structure commands in other
9293 modes. The following keys behave as if Org mode were active, if
9294 the cursor is on a headline, or on a plain list item (both as
9295 defined by Org-mode)."
9296 nil " OrgStruct" (make-sparse-keymap)
9297 (funcall (if orgstruct-mode
9298 'add-to-invisibility-spec
9299 'remove-from-invisibility-spec)
9300 '(outline . t))
9301 (when orgstruct-mode
9302 (org-load-modules-maybe)
9303 (unless orgstruct-initialized
9304 (orgstruct-setup)
9305 (setq orgstruct-initialized t))))
9307 ;;;###autoload
9308 (defun turn-on-orgstruct ()
9309 "Unconditionally turn on `orgstruct-mode'."
9310 (orgstruct-mode 1))
9312 (defvar-local orgstruct-is-++ nil
9313 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9314 (defvar-local org-fb-vars nil)
9315 (defun orgstruct++-mode (&optional arg)
9316 "Toggle `orgstruct-mode', the enhanced version of it.
9317 In addition to setting orgstruct-mode, this also exports all
9318 indentation and autofilling variables from Org mode into the
9319 buffer. It will also recognize item context in multiline items."
9320 (interactive "P")
9321 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9322 (if (< arg 1)
9323 (progn (orgstruct-mode -1)
9324 (dolist (v org-fb-vars)
9325 (set (make-local-variable (car v))
9326 (if (eq (car-safe (cadr v)) 'quote)
9327 (cl-cadadr v)
9328 (nth 1 v)))))
9329 (orgstruct-mode 1)
9330 (setq org-fb-vars nil)
9331 (unless org-local-vars
9332 (setq org-local-vars (org-get-local-variables)))
9333 (let (var val)
9334 (dolist (x org-local-vars)
9335 (when (string-match
9336 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9337 \\|fill-prefix\\|indent-\\)"
9338 (symbol-name (car x)))
9339 (setq var (car x) val (nth 1 x))
9340 (push (list var `(quote ,(eval var))) org-fb-vars)
9341 (set (make-local-variable var)
9342 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9343 (setq-local orgstruct-is-++ t))))
9345 ;;;###autoload
9346 (defun turn-on-orgstruct++ ()
9347 "Unconditionally turn on `orgstruct++-mode'."
9348 (orgstruct++-mode 1))
9350 (defun orgstruct-error ()
9351 "Error when there is no default binding for a structure key."
9352 (interactive)
9353 (funcall (if (fboundp 'user-error)
9354 'user-error
9355 'error)
9356 "This key has no function outside structure elements"))
9358 (defun orgstruct-setup ()
9359 "Setup orgstruct keymap."
9360 (dolist (cell '((org-demote . t)
9361 (org-metaleft . t)
9362 (org-metaright . t)
9363 (org-promote . t)
9364 (org-shiftmetaleft . t)
9365 (org-shiftmetaright . t)
9366 org-backward-element
9367 org-backward-heading-same-level
9368 org-ctrl-c-ret
9369 org-ctrl-c-minus
9370 org-ctrl-c-star
9371 org-cycle
9372 org-force-cycle-archived
9373 org-forward-heading-same-level
9374 org-insert-heading
9375 org-insert-heading-respect-content
9376 org-kill-note-or-show-branches
9377 org-mark-subtree
9378 org-meta-return
9379 org-metadown
9380 org-metaup
9381 org-narrow-to-subtree
9382 org-promote-subtree
9383 org-reveal
9384 org-shiftdown
9385 org-shiftleft
9386 org-shiftmetadown
9387 org-shiftmetaup
9388 org-shiftright
9389 org-shifttab
9390 org-shifttab
9391 org-shiftup
9392 org-show-children
9393 org-show-subtree
9394 org-sort
9395 org-up-element
9396 outline-demote
9397 outline-next-visible-heading
9398 outline-previous-visible-heading
9399 outline-promote
9400 outline-up-heading))
9401 (let ((f (or (car-safe cell) cell))
9402 (disable-when-heading-prefix (cdr-safe cell)))
9403 (when (fboundp f)
9404 (let ((new-bindings))
9405 (dolist (binding (nconc (where-is-internal f org-mode-map)
9406 (where-is-internal f outline-mode-map)))
9407 (push binding new-bindings)
9408 ;; TODO use local-function-key-map
9409 (dolist (rep '(("<tab>" . "TAB")
9410 ("<return>" . "RET")
9411 ("<escape>" . "ESC")
9412 ("<delete>" . "DEL")))
9413 (setq binding (read-kbd-macro
9414 (let ((case-fold-search))
9415 (replace-regexp-in-string
9416 (regexp-quote (cdr rep))
9417 (car rep)
9418 (key-description binding)))))
9419 (cl-pushnew binding new-bindings :test 'equal)))
9420 (dolist (binding new-bindings)
9421 (let ((key (lookup-key orgstruct-mode-map binding)))
9422 (when (or (not key) (numberp key))
9423 (ignore-errors
9424 (org-defkey orgstruct-mode-map
9425 binding
9426 (orgstruct-make-binding
9427 f binding disable-when-heading-prefix))))))))))
9428 (run-hooks 'orgstruct-setup-hook))
9430 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9431 "Create a function for binding in the structure minor mode.
9432 FUN is the command to call inside a table. KEY is the key that
9433 should be checked in for a command to execute outside of tables.
9434 Non-nil `disable-when-heading-prefix' means to disable the command
9435 if `orgstruct-heading-prefix-regexp' is not empty."
9436 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9437 (let ((nname name)
9438 (i 0))
9439 (while (fboundp (intern nname))
9440 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9441 (setq name (intern nname)))
9442 (eval
9443 (let ((bindings '((org-heading-regexp
9444 (concat "^"
9445 orgstruct-heading-prefix-regexp
9446 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9447 (org-outline-regexp
9448 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9449 (org-outline-regexp-bol
9450 (concat "^" org-outline-regexp))
9451 (outline-regexp org-outline-regexp)
9452 (outline-heading-end-regexp "\n")
9453 (outline-level 'org-outline-level)
9454 (outline-heading-alist))))
9455 `(defun ,name (arg)
9456 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9457 "Outside of structure, run the binding of `"
9458 (key-description key) "'."
9459 (when disable-when-heading-prefix
9460 (concat
9461 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9462 "back to the default binding due to limitations of Org's implementation of\n"
9463 "`" (symbol-name fun) "'.")))
9464 (interactive "p")
9465 (let* ((disable
9466 ,(and disable-when-heading-prefix
9467 '(not (string= orgstruct-heading-prefix-regexp ""))))
9468 (fallback
9469 (or disable
9470 (not
9471 (let* ,bindings
9472 (org-context-p 'headline 'item
9473 ,(when (memq fun
9474 '(org-insert-heading
9475 org-insert-heading-respect-content
9476 org-meta-return))
9477 '(when orgstruct-is-++
9478 'item-body))))))))
9479 (if fallback
9480 (let* ((orgstruct-mode)
9481 (binding
9482 (let ((key ,key))
9483 (catch 'exit
9484 (dolist
9485 (rep
9486 '(nil
9487 ("<\\([^>]*\\)tab>" . "\\1TAB")
9488 ("<\\([^>]*\\)return>" . "\\1RET")
9489 ("<\\([^>]*\\)escape>" . "\\1ESC")
9490 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9491 nil)
9492 (when rep
9493 (setq key (read-kbd-macro
9494 (let ((case-fold-search))
9495 (replace-regexp-in-string
9496 (car rep)
9497 (cdr rep)
9498 (key-description key))))))
9499 (when (key-binding key)
9500 (throw 'exit (key-binding key))))))))
9501 (if (keymapp binding)
9502 (org-set-transient-map binding)
9503 (let ((func (or binding
9504 (unless disable
9505 'orgstruct-error))))
9506 (when func
9507 (call-interactively func)))))
9508 (org-run-like-in-org-mode
9509 (lambda ()
9510 (interactive)
9511 (let* ,bindings
9512 (call-interactively ',fun)))))))))
9513 name))
9515 (defun org-contextualize-keys (alist contexts)
9516 "Return valid elements in ALIST depending on CONTEXTS.
9518 `org-agenda-custom-commands' or `org-capture-templates' are the
9519 values used for ALIST, and `org-agenda-custom-commands-contexts'
9520 or `org-capture-templates-contexts' are the associated contexts
9521 definitions."
9522 (let ((contexts
9523 ;; normalize contexts
9524 (mapcar
9525 (lambda(c) (cond ((listp (cadr c))
9526 (list (car c) (car c) (nth 1 c)))
9527 ((string= "" (cadr c))
9528 (list (car c) (car c) (nth 2 c)))
9529 (t c)))
9530 contexts))
9531 (a alist) r s)
9532 ;; loop over all commands or templates
9533 (dolist (c a)
9534 (let (vrules repl)
9535 (cond
9536 ((not (assoc (car c) contexts))
9537 (push c r))
9538 ((and (assoc (car c) contexts)
9539 (setq vrules (org-contextualize-validate-key
9540 (car c) contexts)))
9541 (mapc (lambda (vr)
9542 (unless (equal (car vr) (cadr vr))
9543 (setq repl vr)))
9544 vrules)
9545 (if (not repl) (push c r)
9546 (push (cadr repl) s)
9547 (push
9548 (cons (car c)
9549 (cdr (or (assoc (cadr repl) alist)
9550 (error "Undefined key `%s' as contextual replacement for `%s'"
9551 (cadr repl) (car c)))))
9552 r))))))
9553 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9554 (delq
9556 (delete-dups
9557 (mapcar (lambda (x)
9558 (let ((tpl (car x)))
9559 (unless (delq
9561 (mapcar (lambda (y)
9562 (equal y tpl))
9564 x)))
9565 (reverse r))))))
9567 (defun org-contextualize-validate-key (key contexts)
9568 "Check CONTEXTS for agenda or capture KEY."
9569 (let (res)
9570 (dolist (r contexts)
9571 (dolist (rr (car (last r)))
9572 (when
9573 (and (equal key (car r))
9574 (if (functionp rr) (funcall rr)
9575 (or (and (eq (car rr) 'in-file)
9576 (buffer-file-name)
9577 (string-match (cdr rr) (buffer-file-name)))
9578 (and (eq (car rr) 'in-mode)
9579 (string-match (cdr rr) (symbol-name major-mode)))
9580 (and (eq (car rr) 'in-buffer)
9581 (string-match (cdr rr) (buffer-name)))
9582 (when (and (eq (car rr) 'not-in-file)
9583 (buffer-file-name))
9584 (not (string-match (cdr rr) (buffer-file-name))))
9585 (when (eq (car rr) 'not-in-mode)
9586 (not (string-match (cdr rr) (symbol-name major-mode))))
9587 (when (eq (car rr) 'not-in-buffer)
9588 (not (string-match (cdr rr) (buffer-name)))))))
9589 (push r res))))
9590 (delete-dups (delq nil res))))
9592 (defun org-context-p (&rest contexts)
9593 "Check if local context is any of CONTEXTS.
9594 Possible values in the list of contexts are `table', `headline', and `item'."
9595 (let ((pos (point)))
9596 (goto-char (point-at-bol))
9597 (prog1 (or (and (memq 'table contexts)
9598 (looking-at "[ \t]*|"))
9599 (and (memq 'headline contexts)
9600 (looking-at org-outline-regexp))
9601 (and (memq 'item contexts)
9602 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9603 (and (memq 'item-body contexts)
9604 (org-in-item-p)))
9605 (goto-char pos))))
9607 (defconst org-unique-local-variables
9608 '(org-element--cache
9609 org-element--cache-objects
9610 org-element--cache-sync-keys
9611 org-element--cache-sync-requests
9612 org-element--cache-sync-timer)
9613 "List of local variables that cannot be transferred to another buffer.")
9615 (defun org-get-local-variables ()
9616 "Return a list of all local variables in an Org mode buffer."
9617 (delq nil
9618 (mapcar
9619 (lambda (x)
9620 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9621 (name (car binding)))
9622 (and (not (get name 'org-state))
9623 (not (memq name org-unique-local-variables))
9624 (string-match-p
9625 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9626 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9627 (symbol-name name))
9628 binding)))
9629 (with-temp-buffer
9630 (org-mode)
9631 (buffer-local-variables)))))
9633 (defun org-clone-local-variables (from-buffer &optional regexp)
9634 "Clone local variables from FROM-BUFFER.
9635 Optional argument REGEXP selects variables to clone."
9636 (dolist (pair (buffer-local-variables from-buffer))
9637 (let ((name (car pair)))
9638 (when (and (symbolp name)
9639 (not (memq name org-unique-local-variables))
9640 (or (null regexp) (string-match regexp (symbol-name name))))
9641 (set (make-local-variable name) (cdr pair))))))
9643 ;;;###autoload
9644 (defun org-run-like-in-org-mode (cmd)
9645 "Run a command, pretending that the current buffer is in Org-mode.
9646 This will temporarily bind local variables that are typically bound in
9647 Org mode to the values they have in Org-mode, and then interactively
9648 call CMD."
9649 (org-load-modules-maybe)
9650 (unless org-local-vars
9651 (setq org-local-vars (org-get-local-variables)))
9652 (let (binds)
9653 (dolist (var org-local-vars)
9654 (when (or (not (boundp (car var)))
9655 (eq (symbol-value (car var))
9656 (default-value (car var))))
9657 (push (list (car var) `(quote ,(cadr var))) binds)))
9658 (eval `(let ,binds
9659 (call-interactively (quote ,cmd))))))
9661 (defun org-get-category (&optional pos force-refresh)
9662 "Get the category applying to position POS."
9663 (save-match-data
9664 (when force-refresh (org-refresh-category-properties))
9665 (let ((pos (or pos (point))))
9666 (or (get-text-property pos 'org-category)
9667 (progn (org-refresh-category-properties)
9668 (get-text-property pos 'org-category))))))
9670 ;;; Refresh properties
9672 (defun org-refresh-properties (dprop tprop)
9673 "Refresh buffer text properties.
9674 DPROP is the drawer property and TPROP is either the
9675 corresponding text property to set, or an alist with each element
9676 being a text property (as a symbol) and a function to apply to
9677 the value of the drawer property."
9678 (let ((case-fold-search t)
9679 (inhibit-read-only t))
9680 (org-with-silent-modifications
9681 (org-with-wide-buffer
9682 (goto-char (point-min))
9683 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9684 (org-refresh-property tprop (match-string-no-properties 1)))))))
9686 (defun org-refresh-property (tprop p)
9687 "Refresh the buffer text property TPROP from the drawer property P.
9688 The refresh happens only for the current tree (not subtree)."
9689 (unless (org-before-first-heading-p)
9690 (save-excursion
9691 (org-back-to-heading t)
9692 (if (symbolp tprop)
9693 ;; TPROP is a text property symbol
9694 (put-text-property
9695 (point) (or (outline-next-heading) (point-max)) tprop p)
9696 ;; TPROP is an alist with (properties . function) elements
9697 (dolist (al tprop)
9698 (save-excursion
9699 (put-text-property
9700 (line-beginning-position) (or (outline-next-heading) (point-max))
9701 (car al)
9702 (funcall (cdr al) p))))))))
9704 (defun org-refresh-category-properties ()
9705 "Refresh category text properties in the buffer."
9706 (let ((case-fold-search t)
9707 (inhibit-read-only t)
9708 (default-category
9709 (cond ((null org-category)
9710 (if buffer-file-name
9711 (file-name-sans-extension
9712 (file-name-nondirectory buffer-file-name))
9713 "???"))
9714 ((symbolp org-category) (symbol-name org-category))
9715 (t org-category))))
9716 (org-with-silent-modifications
9717 (org-with-wide-buffer
9718 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9719 ;; This is the default category for the buffer. If none is
9720 ;; found, fall-back to `org-category' or buffer file name.
9721 (put-text-property
9722 (point-min) (point-max)
9723 'org-category
9724 (catch 'buffer-category
9725 (goto-char (point-max))
9726 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9727 (let ((element (org-element-at-point)))
9728 (when (eq (org-element-type element) 'keyword)
9729 (throw 'buffer-category
9730 (org-element-property :value element)))))
9731 default-category))
9732 ;; Set sub-tree specific categories.
9733 (goto-char (point-min))
9734 (let ((regexp (org-re-property "CATEGORY")))
9735 (while (re-search-forward regexp nil t)
9736 (let ((value (match-string-no-properties 3)))
9737 (when (org-at-property-p)
9738 (put-text-property
9739 (save-excursion (org-back-to-heading t) (point))
9740 (save-excursion (org-end-of-subtree t t) (point))
9741 'org-category
9742 value)))))))))
9744 (defun org-refresh-stats-properties ()
9745 "Refresh stats text properties in the buffer."
9746 (let (stats)
9747 (org-with-silent-modifications
9748 (org-with-wide-buffer
9749 (goto-char (point-min))
9750 (while (re-search-forward
9751 (concat org-outline-regexp-bol ".*"
9752 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9753 nil t)
9754 (setq stats (cond ((equal (match-string 3) "0") 0)
9755 ((match-string 2)
9756 (/ (* (string-to-number (match-string 2)) 100)
9757 (string-to-number (match-string 3))))
9758 (t (string-to-number (match-string 1)))))
9759 (org-back-to-heading t)
9760 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9761 'org-stats stats))))))
9763 (defun org-refresh-effort-properties ()
9764 "Refresh effort properties"
9765 (org-refresh-properties
9766 org-effort-property
9767 '((effort . identity)
9768 (effort-minutes . org-duration-string-to-minutes))))
9770 ;;;; Link Stuff
9772 ;;; Link abbreviations
9774 (defun org-link-expand-abbrev (link)
9775 "Apply replacements as defined in `org-link-abbrev-alist'."
9776 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9777 (let* ((key (match-string 1 link))
9778 (as (or (assoc key org-link-abbrev-alist-local)
9779 (assoc key org-link-abbrev-alist)))
9780 (tag (and (match-end 2) (match-string 3 link)))
9781 rpl)
9782 (if (not as)
9783 link
9784 (setq rpl (cdr as))
9785 (cond
9786 ((symbolp rpl) (funcall rpl tag))
9787 ((string-match "%(\\([^)]+\\))" rpl)
9788 (replace-match
9789 (save-match-data
9790 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9791 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9792 ((string-match "%h" rpl)
9793 (replace-match (url-hexify-string (or tag "")) t t rpl))
9794 (t (concat rpl tag)))))
9795 link))
9797 ;;; Storing and inserting links
9799 (defvar org-insert-link-history nil
9800 "Minibuffer history for links inserted with `org-insert-link'.")
9802 (defvar org-stored-links nil
9803 "Contains the links stored with `org-store-link'.")
9805 (defvar org-store-link-plist nil
9806 "Plist with info about the most recently link created with `org-store-link'.")
9808 (defun org-store-link-functions ()
9809 "Return a list of functions that are called to create and store a link.
9810 The functions defined in the :store property of
9811 `org-link-parameters'.
9813 Each function will be called in turn until one returns a non-nil
9814 value. Each function should check if it is responsible for
9815 creating this link (for example by looking at the major mode).
9816 If not, it must exit and return nil. If yes, it should return
9817 a non-nil value after calling `org-store-link-props' with a list
9818 of properties and values. Special properties are:
9820 :type The link prefix, like \"http\". This must be given.
9821 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9822 This is obligatory as well.
9823 :description Optional default description for the second pair
9824 of brackets in an Org mode link. The user can still change
9825 this when inserting this link into an Org mode buffer.
9827 In addition to these, any additional properties can be specified
9828 and then used in capture templates."
9829 (cl-loop for link in org-link-parameters
9830 with store-func
9831 do (setq store-func (org-link-get-parameter (car link) :store))
9832 if store-func
9833 collect store-func))
9835 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9836 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9838 ;;;###autoload
9839 (defun org-store-link (arg)
9840 "\\<org-mode-map>Store an org-link to the current location.
9841 This link is added to `org-stored-links' and can later be inserted
9842 into an Org buffer with \\[org-insert-link].
9844 For some link types, a prefix ARG is interpreted.
9845 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9846 For file links, ARG negates `org-context-in-file-links'.
9848 A double prefix ARG force skipping storing functions that are not
9849 part of Org's core.
9851 A triple prefix ARG force storing a link for each line in the
9852 active region."
9853 (interactive "P")
9854 (org-load-modules-maybe)
9855 (if (and (equal arg '(64)) (org-region-active-p))
9856 (save-excursion
9857 (let ((end (region-end)))
9858 (goto-char (region-beginning))
9859 (set-mark (point))
9860 (while (< (point-at-eol) end)
9861 (move-end-of-line 1) (activate-mark)
9862 (let (current-prefix-arg)
9863 (call-interactively 'org-store-link))
9864 (move-beginning-of-line 2)
9865 (set-mark (point)))))
9866 (setq org-store-link-plist nil)
9867 (let (link cpltxt desc description search
9868 txt custom-id agenda-link sfuns sfunsn)
9869 (cond
9871 ;; Store a link using an external link type
9872 ((and (not (equal arg '(16)))
9873 (setq sfuns
9874 (delq
9875 nil (mapcar (lambda (f)
9876 (let (fs) (if (funcall f) (push f fs))))
9877 (org-store-link-functions)))
9878 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9879 (or (and (cdr sfuns)
9880 (funcall (intern
9881 (completing-read
9882 "Which function for creating the link? "
9883 sfunsn nil t (car sfunsn)))))
9884 (funcall (caar sfuns)))
9885 (setq link (plist-get org-store-link-plist :link)
9886 desc (or (plist-get org-store-link-plist
9887 :description)
9888 link))))
9890 ;; Store a link from a source code buffer.
9891 ((org-src-edit-buffer-p)
9892 (let ((coderef-format (org-src-coderef-format)))
9893 (cond ((save-excursion
9894 (beginning-of-line)
9895 (looking-at (org-src-coderef-regexp coderef-format)))
9896 (setq link (format "(%s)" (match-string-no-properties 3))))
9897 ((called-interactively-p 'any)
9898 (let ((label (read-string "Code line label: ")))
9899 (end-of-line)
9900 (setq link (format coderef-format label))
9901 (let ((gc (- 79 (length link))))
9902 (if (< (current-column) gc)
9903 (org-move-to-column gc t)
9904 (insert " ")))
9905 (insert link)
9906 (setq link (concat "(" label ")"))
9907 (setq desc nil)))
9908 (t (setq link nil)))))
9910 ;; We are in the agenda, link to referenced location
9911 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9912 (let ((m (or (get-text-property (point) 'org-hd-marker)
9913 (get-text-property (point) 'org-marker))))
9914 (when m
9915 (org-with-point-at m
9916 (setq agenda-link
9917 (if (called-interactively-p 'any)
9918 (call-interactively 'org-store-link)
9919 (org-store-link nil)))))))
9921 ((eq major-mode 'calendar-mode)
9922 (let ((cd (calendar-cursor-to-date)))
9923 (setq link
9924 (format-time-string
9925 (car org-time-stamp-formats)
9926 (apply 'encode-time
9927 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9928 nil nil nil))))
9929 (org-store-link-props :type "calendar" :date cd)))
9931 ((eq major-mode 'help-mode)
9932 (setq link (concat "help:" (save-excursion
9933 (goto-char (point-min))
9934 (looking-at "^[^ ]+")
9935 (match-string 0))))
9936 (org-store-link-props :type "help"))
9938 ((eq major-mode 'w3-mode)
9939 (setq cpltxt (if (and (buffer-name)
9940 (not (string-match "Untitled" (buffer-name))))
9941 (buffer-name)
9942 (url-view-url t))
9943 link (url-view-url t))
9944 (org-store-link-props :type "w3" :url (url-view-url t)))
9946 ((eq major-mode 'image-mode)
9947 (setq cpltxt (concat "file:"
9948 (abbreviate-file-name buffer-file-name))
9949 link cpltxt)
9950 (org-store-link-props :type "image" :file buffer-file-name))
9952 ;; In dired, store a link to the file of the current line
9953 ((derived-mode-p 'dired-mode)
9954 (let ((file (dired-get-filename nil t)))
9955 (setq file (if file
9956 (abbreviate-file-name
9957 (expand-file-name (dired-get-filename nil t)))
9958 ;; otherwise, no file so use current directory.
9959 default-directory))
9960 (setq cpltxt (concat "file:" file)
9961 link cpltxt)))
9963 ((setq search (run-hook-with-args-until-success
9964 'org-create-file-search-functions))
9965 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9966 "::" search))
9967 (setq cpltxt (or description link)))
9969 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9970 (org-with-limited-levels
9971 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9972 (cond
9973 ;; Store a link using the target at point
9974 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9975 (setq cpltxt
9976 (concat "file:"
9977 (abbreviate-file-name
9978 (buffer-file-name (buffer-base-buffer)))
9979 "::" (match-string 1))
9980 link cpltxt))
9981 ((and (featurep 'org-id)
9982 (or (eq org-id-link-to-org-use-id t)
9983 (and (called-interactively-p 'any)
9984 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9985 (and (eq org-id-link-to-org-use-id
9986 'create-if-interactive-and-no-custom-id)
9987 (not custom-id))))
9988 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9989 ;; Store a link using the ID at point
9990 (setq link (condition-case nil
9991 (prog1 (org-id-store-link)
9992 (setq desc (or (plist-get org-store-link-plist
9993 :description)
9994 "")))
9995 (error
9996 ;; Probably before first headline, link only to file
9997 (concat "file:"
9998 (abbreviate-file-name
9999 (buffer-file-name (buffer-base-buffer))))))))
10001 ;; Just link to current headline
10002 (setq cpltxt (concat "file:"
10003 (abbreviate-file-name
10004 (buffer-file-name (buffer-base-buffer)))))
10005 ;; Add a context search string
10006 (when (org-xor org-context-in-file-links arg)
10007 (let* ((element (org-element-at-point))
10008 (name (org-element-property :name element)))
10009 (setq txt (cond
10010 ((org-at-heading-p) nil)
10011 (name)
10012 ((org-region-active-p)
10013 (buffer-substring (region-beginning) (region-end)))))
10014 (when (or (null txt) (string-match "\\S-" txt))
10015 (setq cpltxt
10016 (concat cpltxt "::"
10017 (condition-case nil
10018 (org-make-org-heading-search-string txt)
10019 (error "")))
10020 desc (or name
10021 (nth 4 (ignore-errors (org-heading-components)))
10022 "NONE")))))
10023 (when (string-match "::\\'" cpltxt)
10024 (setq cpltxt (substring cpltxt 0 -2)))
10025 (setq link cpltxt)))))
10027 ((buffer-file-name (buffer-base-buffer))
10028 ;; Just link to this file here.
10029 (setq cpltxt (concat "file:"
10030 (abbreviate-file-name
10031 (buffer-file-name (buffer-base-buffer)))))
10032 ;; Add a context string.
10033 (when (org-xor org-context-in-file-links arg)
10034 (setq txt (if (org-region-active-p)
10035 (buffer-substring (region-beginning) (region-end))
10036 (buffer-substring (point-at-bol) (point-at-eol))))
10037 ;; Only use search option if there is some text.
10038 (when (string-match "\\S-" txt)
10039 (setq cpltxt
10040 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10041 desc "NONE")))
10042 (setq link cpltxt))
10044 ((called-interactively-p 'interactive)
10045 (user-error "No method for storing a link from this buffer"))
10047 (t (setq link nil)))
10049 ;; We're done setting link and desc, clean up
10050 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10051 (setq link (or link cpltxt)
10052 desc (or desc cpltxt))
10053 (cond ((not desc))
10054 ((equal desc "NONE") (setq desc nil))
10055 (t (setq desc
10056 (replace-regexp-in-string
10057 org-bracket-link-analytic-regexp
10058 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10059 desc))))
10060 ;; Return the link
10061 (if (not (and (or (called-interactively-p 'any)
10062 executing-kbd-macro)
10063 link))
10064 (or agenda-link (and link (org-make-link-string link desc)))
10065 (push (list link desc) org-stored-links)
10066 (message "Stored: %s" (or desc link))
10067 (when custom-id
10068 (setq link (concat "file:" (abbreviate-file-name
10069 (buffer-file-name)) "::#" custom-id))
10070 (push (list link desc) org-stored-links))
10071 (car org-stored-links)))))
10073 (defun org-store-link-props (&rest plist)
10074 "Store link properties, extract names, addresses and dates."
10075 (let ((x (plist-get plist :from)))
10076 (when x
10077 (let ((adr (mail-extract-address-components x)))
10078 (setq plist (plist-put plist :fromname (car adr)))
10079 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10080 (let ((x (plist-get plist :to)))
10081 (when x
10082 (let ((adr (mail-extract-address-components x)))
10083 (setq plist (plist-put plist :toname (car adr)))
10084 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10085 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10086 (when x
10087 (setq plist (plist-put plist :date-timestamp
10088 (format-time-string
10089 (org-time-stamp-format t) x)))
10090 (setq plist (plist-put plist :date-timestamp-inactive
10091 (format-time-string
10092 (org-time-stamp-format t t) x)))))
10093 (let ((from (plist-get plist :from))
10094 (to (plist-get plist :to)))
10095 (when (and from to org-from-is-user-regexp)
10096 (setq plist
10097 (plist-put plist :fromto
10098 (if (string-match org-from-is-user-regexp from)
10099 (concat "to %t")
10100 (concat "from %f"))))))
10101 (setq org-store-link-plist plist))
10103 (defun org-add-link-props (&rest plist)
10104 "Add these properties to the link property list."
10105 (let (key value)
10106 (while plist
10107 (setq key (pop plist) value (pop plist))
10108 (setq org-store-link-plist
10109 (plist-put org-store-link-plist key value)))))
10111 (defun org-email-link-description (&optional fmt)
10112 "Return the description part of an email link.
10113 This takes information from `org-store-link-plist' and formats it
10114 according to FMT (default from `org-email-link-description-format')."
10115 (setq fmt (or fmt org-email-link-description-format))
10116 (let* ((p org-store-link-plist)
10117 (to (plist-get p :toaddress))
10118 (from (plist-get p :fromaddress))
10119 (table
10120 (list
10121 (cons "%c" (plist-get p :fromto))
10122 (cons "%F" (plist-get p :from))
10123 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10124 (cons "%T" (plist-get p :to))
10125 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10126 (cons "%s" (plist-get p :subject))
10127 (cons "%d" (plist-get p :date))
10128 (cons "%m" (plist-get p :message-id)))))
10129 (when (string-match "%c" fmt)
10130 ;; Check if the user wrote this message
10131 (if (and org-from-is-user-regexp from to
10132 (save-match-data (string-match org-from-is-user-regexp from)))
10133 (setq fmt (replace-match "to %t" t t fmt))
10134 (setq fmt (replace-match "from %f" t t fmt))))
10135 (org-replace-escapes fmt table)))
10137 (defun org-make-org-heading-search-string (&optional string)
10138 "Make search string for the current headline or STRING."
10139 (let ((s (or string
10140 (and (derived-mode-p 'org-mode)
10141 (save-excursion
10142 (org-back-to-heading t)
10143 (org-element-property :raw-value (org-element-at-point))))))
10144 (lines org-context-in-file-links))
10145 (or string (setq s (concat "*" s))) ; Add * for headlines
10146 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10147 (when (and string (integerp lines) (> lines 0))
10148 (let ((slines (org-split-string s "\n")))
10149 (when (< lines (length slines))
10150 (setq s (mapconcat
10151 'identity
10152 (reverse (nthcdr (- (length slines) lines)
10153 (reverse slines))) "\n")))))
10154 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10156 (defun org-make-link-string (link &optional description)
10157 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10158 (unless (org-string-nw-p link) (error "Empty link"))
10159 (let ((uri (cond ((string-match org-link-types-re link)
10160 (concat (match-string 1 link)
10161 (org-link-escape (substring link (match-end 1)))))
10162 ;; For readability, url-encode internal links only
10163 ;; when absolutely needed (i.e, when they contain
10164 ;; square brackets). File links however, are
10165 ;; encoded since, e.g., spaces are significant.
10166 ((or (file-name-absolute-p link)
10167 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10168 (org-link-escape link))
10169 (t link)))
10170 (description
10171 (and (org-string-nw-p description)
10172 ;; Remove brackets from description, as they are fatal.
10173 (replace-regexp-in-string
10174 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10175 (org-trim description)))))
10176 (format "[[%s]%s]"
10178 (if description (format "[%s]" description) ""))))
10180 (defconst org-link-escape-chars
10181 ;;%20 %5B %5D %25
10182 '(?\s ?\[ ?\] ?%)
10183 "List of characters that should be escaped in a link when stored to Org.
10184 This is the list that is used for internal purposes.")
10186 (defun org-link-escape (text &optional table merge)
10187 "Return percent escaped representation of TEXT.
10188 TEXT is a string with the text to escape.
10189 Optional argument TABLE is a list with characters that should be
10190 escaped. When nil, `org-link-escape-chars' is used.
10191 If optional argument MERGE is set, merge TABLE into
10192 `org-link-escape-chars'."
10193 (let ((characters-to-encode
10194 (cond ((null table) org-link-escape-chars)
10195 (merge (append org-link-escape-chars table))
10196 (t table))))
10197 (mapconcat
10198 (lambda (c)
10199 (if (or (memq c characters-to-encode)
10200 (and org-url-hexify-p (or (< c 32) (> c 126))))
10201 (mapconcat (lambda (e) (format "%%%.2X" e))
10202 (or (encode-coding-char c 'utf-8)
10203 (error "Unable to percent escape character: %c" c))
10205 (char-to-string c)))
10206 text "")))
10208 (defun org-link-unescape (str)
10209 "Unhex hexified Unicode parts in string STR.
10210 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10211 reciprocal of `org-link-escape', which see."
10212 (if (org-string-nw-p str)
10213 (replace-regexp-in-string
10214 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10215 str))
10217 (defun org-link-unescape-compound (hex)
10218 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10219 Note: this function also decodes single byte encodings like
10220 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10221 (save-match-data
10222 (let* ((bytes (cdr (split-string hex "%")))
10223 (ret "")
10224 (eat 0)
10225 (sum 0))
10226 (while bytes
10227 (let* ((val (string-to-number (pop bytes) 16))
10228 (shift-xor
10229 (if (= 0 eat)
10230 (cond
10231 ((>= val 252) (cons 6 252))
10232 ((>= val 248) (cons 5 248))
10233 ((>= val 240) (cons 4 240))
10234 ((>= val 224) (cons 3 224))
10235 ((>= val 192) (cons 2 192))
10236 (t (cons 0 0)))
10237 (cons 6 128))))
10238 (when (>= val 192) (setq eat (car shift-xor)))
10239 (setq val (logxor val (cdr shift-xor)))
10240 (setq sum (+ (lsh sum (car shift-xor)) val))
10241 (when (> eat 0) (setq eat (- eat 1)))
10242 (cond
10243 ((= 0 eat) ;multi byte
10244 (setq ret (concat ret (char-to-string sum)))
10245 (setq sum 0))
10246 ((not bytes) ; single byte(s)
10247 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10248 ret)))
10250 (defun org-link-unescape-single-byte-sequence (hex)
10251 "Unhexify hex-encoded single byte character sequences."
10252 (mapconcat (lambda (byte)
10253 (char-to-string (string-to-number byte 16)))
10254 (cdr (split-string hex "%")) ""))
10256 (defun org-xor (a b)
10257 "Exclusive or."
10258 (if a (not b) b))
10260 (defun org-fixup-message-id-for-http (s)
10261 "Replace special characters in a message id, so it can be used in an http query."
10262 (when (string-match "%" s)
10263 (setq s (mapconcat (lambda (c)
10264 (if (eq c ?%)
10265 "%25"
10266 (char-to-string c)))
10267 s "")))
10268 (while (string-match "<" s)
10269 (setq s (replace-match "%3C" t t s)))
10270 (while (string-match ">" s)
10271 (setq s (replace-match "%3E" t t s)))
10272 (while (string-match "@" s)
10273 (setq s (replace-match "%40" t t s)))
10276 (defun org-link-prettify (link)
10277 "Return a human-readable representation of LINK.
10278 The car of LINK must be a raw link.
10279 The cdr of LINK must be either a link description or nil."
10280 (let ((desc (or (cadr link) "<no description>")))
10281 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10282 "<" (car link) ">")))
10284 ;;;###autoload
10285 (defun org-insert-link-global ()
10286 "Insert a link like Org mode does.
10287 This command can be called in any mode to insert a link in Org syntax."
10288 (interactive)
10289 (org-load-modules-maybe)
10290 (org-run-like-in-org-mode 'org-insert-link))
10292 (defun org-insert-all-links (arg &optional pre post)
10293 "Insert all links in `org-stored-links'.
10294 When a universal prefix, do not delete the links from `org-stored-links'.
10295 When `ARG' is a number, insert the last N link(s).
10296 `PRE' and `POST' are optional arguments to define a string to
10297 prepend or to append."
10298 (interactive "P")
10299 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10300 (links (copy-sequence org-stored-links))
10301 (pr (or pre "- "))
10302 (po (or post "\n"))
10303 (cnt 1) l)
10304 (if (null org-stored-links)
10305 (message "No link to insert")
10306 (while (and (or (listp arg) (>= arg cnt))
10307 (setq l (if (listp arg)
10308 (pop links)
10309 (pop org-stored-links))))
10310 (setq cnt (1+ cnt))
10311 (insert pr)
10312 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10313 (insert po)))))
10315 (defun org-insert-last-stored-link (arg)
10316 "Insert the last link stored in `org-stored-links'."
10317 (interactive "p")
10318 (org-insert-all-links arg "" "\n"))
10320 (defun org-link-fontify-links-to-this-file ()
10321 "Fontify links to the current file in `org-stored-links'."
10322 (let ((f (buffer-file-name)) a b)
10323 (setq a (mapcar (lambda(l)
10324 (let ((ll (car l)))
10325 (when (and (string-match "^file:\\(.+\\)::" ll)
10326 (equal f (expand-file-name (match-string 1 ll))))
10327 ll)))
10328 org-stored-links))
10329 (when (featurep 'org-id)
10330 (setq b (mapcar (lambda(l)
10331 (let ((ll (car l)))
10332 (when (and (string-match "^id:\\(.+\\)$" ll)
10333 (equal f (expand-file-name
10334 (or (org-id-find-id-file
10335 (match-string 1 ll)) ""))))
10336 ll)))
10337 org-stored-links)))
10338 (mapcar (lambda(l)
10339 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10340 (delq nil (append a b)))))
10342 (defvar org--links-history nil)
10343 (defun org-insert-link (&optional complete-file link-location default-description)
10344 "Insert a link. At the prompt, enter the link.
10346 Completion can be used to insert any of the link protocol prefixes like
10347 http or ftp in use.
10349 The history can be used to select a link previously stored with
10350 `org-store-link'. When the empty string is entered (i.e. if you just
10351 press RET at the prompt), the link defaults to the most recently
10352 stored link. As SPC triggers completion in the minibuffer, you need to
10353 use M-SPC or C-q SPC to force the insertion of a space character.
10355 You will also be prompted for a description, and if one is given, it will
10356 be displayed in the buffer instead of the link.
10358 If there is already a link at point, this command will allow you to edit link
10359 and description parts.
10361 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10362 be selected using completion. The path to the file will be relative to the
10363 current directory if the file is in the current directory or a subdirectory.
10364 Otherwise, the link will be the absolute path as completed in the minibuffer
10365 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10366 option `org-link-file-path-type'.
10368 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10369 the current directory or below.
10371 With three \\[universal-argument] prefixes, negate the meaning of
10372 `org-keep-stored-link-after-insertion'.
10374 If `org-make-link-description-function' is non-nil, this function will be
10375 called with the link target, and the result will be the default
10376 link description.
10378 If the LINK-LOCATION parameter is non-nil, this value will be
10379 used as the link location instead of reading one interactively.
10381 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10382 be used as the default description."
10383 (interactive "P")
10384 (let* ((wcf (current-window-configuration))
10385 (origbuf (current-buffer))
10386 (region (when (org-region-active-p)
10387 (buffer-substring (region-beginning) (region-end))))
10388 (remove (and region (list (region-beginning) (region-end))))
10389 (desc region)
10390 (link link-location)
10391 (abbrevs org-link-abbrev-alist-local)
10392 entry all-prefixes auto-desc)
10393 (cond
10394 (link-location) ; specified by arg, just use it.
10395 ((org-in-regexp org-bracket-link-regexp 1)
10396 ;; We do have a link at point, and we are going to edit it.
10397 (setq remove (list (match-beginning 0) (match-end 0)))
10398 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10399 (setq link (read-string "Link: "
10400 (org-link-unescape
10401 (match-string-no-properties 1)))))
10402 ((or (org-in-regexp org-angle-link-re)
10403 (org-in-regexp org-plain-link-re))
10404 ;; Convert to bracket link
10405 (setq remove (list (match-beginning 0) (match-end 0))
10406 link (read-string "Link: "
10407 (org-unbracket-string "<" ">" (match-string 0)))))
10408 ((member complete-file '((4) (16)))
10409 ;; Completing read for file names.
10410 (setq link (org-file-complete-link complete-file)))
10412 ;; Read link, with completion for stored links.
10413 (org-link-fontify-links-to-this-file)
10414 (org-switch-to-buffer-other-window "*Org Links*")
10415 (with-current-buffer "*Org Links*"
10416 (erase-buffer)
10417 (insert "Insert a link.
10418 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10419 (when org-stored-links
10420 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10421 (insert (mapconcat 'org-link-prettify
10422 (reverse org-stored-links) "\n")))
10423 (goto-char (point-min)))
10424 (let ((cw (selected-window)))
10425 (select-window (get-buffer-window "*Org Links*" 'visible))
10426 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10427 (unless (pos-visible-in-window-p (point-max))
10428 (org-fit-window-to-buffer))
10429 (and (window-live-p cw) (select-window cw)))
10430 (setq all-prefixes (append (mapcar 'car abbrevs)
10431 (mapcar 'car org-link-abbrev-alist)
10432 (org-link-types)))
10433 (unwind-protect
10434 ;; Fake a link history, containing the stored links.
10435 (let ((org--links-history
10436 (append (mapcar #'car org-stored-links)
10437 org-insert-link-history)))
10438 (setq link
10439 (org-completing-read
10440 "Link: "
10441 (append
10442 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10443 (mapcar #'car org-stored-links))
10444 nil nil nil
10445 'org--links-history
10446 (caar org-stored-links)))
10447 (unless (org-string-nw-p link) (user-error "No link selected"))
10448 (dolist (l org-stored-links)
10449 (when (equal link (cadr l))
10450 (setq link (car l))
10451 (setq auto-desc t)))
10452 (when (or (member link all-prefixes)
10453 (and (equal ":" (substring link -1))
10454 (member (substring link 0 -1) all-prefixes)
10455 (setq link (substring link 0 -1))))
10456 (setq link (with-current-buffer origbuf
10457 (org-link-try-special-completion link)))))
10458 (set-window-configuration wcf)
10459 (kill-buffer "*Org Links*"))
10460 (setq entry (assoc link org-stored-links))
10461 (or entry (push link org-insert-link-history))
10462 (setq desc (or desc (nth 1 entry)))))
10464 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10465 (not org-keep-stored-link-after-insertion))
10466 (setq org-stored-links (delq (assoc link org-stored-links)
10467 org-stored-links)))
10469 (when (and (string-match org-plain-link-re link)
10470 (not (string-match org-ts-regexp link)))
10471 ;; URL-like link, normalize the use of angular brackets.
10472 (setq link (org-unbracket-string "<" ">" link)))
10474 ;; Check if we are linking to the current file with a search
10475 ;; option If yes, simplify the link by using only the search
10476 ;; option.
10477 (when (and buffer-file-name
10478 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10479 (let* ((path (match-string 1 link))
10480 (case-fold-search nil)
10481 (search (match-string 2 link)))
10482 (save-match-data
10483 (when (equal (file-truename buffer-file-name) (file-truename path))
10484 ;; We are linking to this same file, with a search option
10485 (setq link search)))))
10487 ;; Check if we can/should use a relative path. If yes, simplify the link
10488 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10489 (let* ((type (match-string 1 link))
10490 (path (match-string 2 link))
10491 (origpath path)
10492 (case-fold-search nil))
10493 (cond
10494 ((or (eq org-link-file-path-type 'absolute)
10495 (equal complete-file '(16)))
10496 (setq path (abbreviate-file-name (expand-file-name path))))
10497 ((eq org-link-file-path-type 'noabbrev)
10498 (setq path (expand-file-name path)))
10499 ((eq org-link-file-path-type 'relative)
10500 (setq path (file-relative-name path)))
10502 (save-match-data
10503 (if (string-match (concat "^" (regexp-quote
10504 (expand-file-name
10505 (file-name-as-directory
10506 default-directory))))
10507 (expand-file-name path))
10508 ;; We are linking a file with relative path name.
10509 (setq path (substring (expand-file-name path)
10510 (match-end 0)))
10511 (setq path (abbreviate-file-name (expand-file-name path)))))))
10512 (setq link (concat type path))
10513 (when (equal desc origpath)
10514 (setq desc path))))
10516 (if org-make-link-description-function
10517 (setq desc
10518 (or (condition-case nil
10519 (funcall org-make-link-description-function link desc)
10520 (error (progn (message "Can't get link description from `%s'"
10521 (symbol-name org-make-link-description-function))
10522 (sit-for 2) nil)))
10523 (read-string "Description: " default-description)))
10524 (if default-description (setq desc default-description)
10525 (setq desc (or (and auto-desc desc)
10526 (read-string "Description: " desc)))))
10528 (unless (string-match "\\S-" desc) (setq desc nil))
10529 (when remove (apply 'delete-region remove))
10530 (insert (org-make-link-string link desc))
10531 ;; Redisplay so as the new link has proper invisible characters.
10532 (sit-for 0)))
10534 (defun org-link-try-special-completion (type)
10535 "If there is completion support for link type TYPE, offer it."
10536 (let ((fun (org-link-get-parameter type :complete)))
10537 (if (functionp fun)
10538 (funcall fun)
10539 (read-string "Link (no completion support): " (concat type ":")))))
10541 (defun org-file-complete-link (&optional arg)
10542 "Create a file link using completion."
10543 (let ((file (read-file-name "File: "))
10544 (pwd (file-name-as-directory (expand-file-name ".")))
10545 (pwd1 (file-name-as-directory (abbreviate-file-name
10546 (expand-file-name ".")))))
10547 (cond ((equal arg '(16))
10548 (concat "file:"
10549 (abbreviate-file-name (expand-file-name file))))
10550 ((string-match
10551 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10552 (concat "file:" (match-string 1 file)))
10553 ((string-match
10554 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10555 (expand-file-name file))
10556 (concat "file:"
10557 (match-string 1 (expand-file-name file))))
10558 (t (concat "file:" file)))))
10560 (defun org-completing-read (&rest args)
10561 "Completing-read with SPACE being a normal character."
10562 (let ((enable-recursive-minibuffers t)
10563 (minibuffer-local-completion-map
10564 (copy-keymap minibuffer-local-completion-map)))
10565 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10566 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10567 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10568 'org-time-stamp-inactive)
10569 (apply #'completing-read args)))
10571 ;;; Opening/following a link
10573 (defvar org-link-search-failed nil)
10575 (defvar org-open-link-functions nil
10576 "Hook for functions finding a plain text link.
10577 These functions must take a single argument, the link content.
10578 They will be called for links that look like [[link text][description]]
10579 when LINK TEXT does not have a protocol like \"http:\" and does not look
10580 like a filename (e.g. \"./blue.png\").
10582 These functions will be called *before* Org attempts to resolve the
10583 link by doing text searches in the current buffer - so if you want a
10584 link \"[[target]]\" to still find \"<<target>>\", your function should
10585 handle this as a special case.
10587 When the function does handle the link, it must return a non-nil value.
10588 If it decides that it is not responsible for this link, it must return
10589 nil to indicate that that Org can continue with other options like
10590 exact and fuzzy text search.")
10592 (defun org-next-link (&optional search-backward)
10593 "Move forward to the next link.
10594 If the link is in hidden text, expose it."
10595 (interactive "P")
10596 (when (and org-link-search-failed (eq this-command last-command))
10597 (goto-char (point-min))
10598 (message "Link search wrapped back to beginning of buffer"))
10599 (setq org-link-search-failed nil)
10600 (let* ((pos (point))
10601 (ct (org-context))
10602 (a (assq :link ct))
10603 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10604 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10605 ((looking-at org-any-link-re)
10606 ;; Don't stay stuck at link without an org-link face
10607 (forward-char (if search-backward -1 1))))
10608 (if (funcall srch-fun org-any-link-re nil t)
10609 (progn
10610 (goto-char (match-beginning 0))
10611 (when (outline-invisible-p) (org-show-context)))
10612 (goto-char pos)
10613 (setq org-link-search-failed t)
10614 (message "No further link found"))))
10616 (defun org-previous-link ()
10617 "Move backward to the previous link.
10618 If the link is in hidden text, expose it."
10619 (interactive)
10620 (funcall 'org-next-link t))
10622 (defun org-translate-link (s)
10623 "Translate a link string if a translation function has been defined."
10624 (with-temp-buffer
10625 (insert (org-trim s))
10626 (org-trim (org-element-interpret-data (org-element-context)))))
10628 (defun org-translate-link-from-planner (type path)
10629 "Translate a link from Emacs Planner syntax so that Org can follow it.
10630 This is still an experimental function, your mileage may vary."
10631 (cond
10632 ((member type '("http" "https" "news" "ftp"))
10633 ;; standard Internet links are the same.
10634 nil)
10635 ((and (equal type "irc") (string-match "^//" path))
10636 ;; Planner has two / at the beginning of an irc link, we have 1.
10637 ;; We should have zero, actually....
10638 (setq path (substring path 1)))
10639 ((and (equal type "lisp") (string-match "^/" path))
10640 ;; Planner has a slash, we do not.
10641 (setq type "elisp" path (substring path 1)))
10642 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10643 ;; A typical message link. Planner has the id after the final slash,
10644 ;; we separate it with a hash mark
10645 (setq path (concat (match-string 1 path) "#"
10646 (org-unbracket-string "<" ">" (match-string 2 path))))))
10647 (cons type path))
10649 (defun org-find-file-at-mouse (ev)
10650 "Open file link or URL at mouse."
10651 (interactive "e")
10652 (mouse-set-point ev)
10653 (org-open-at-point 'in-emacs))
10655 (defun org-open-at-mouse (ev)
10656 "Open file link or URL at mouse.
10657 See the docstring of `org-open-file' for details."
10658 (interactive "e")
10659 (mouse-set-point ev)
10660 (when (eq major-mode 'org-agenda-mode)
10661 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10662 (org-open-at-point))
10664 (defvar org-window-config-before-follow-link nil
10665 "The window configuration before following a link.
10666 This is saved in case the need arises to restore it.")
10668 ;;;###autoload
10669 (defun org-open-at-point-global ()
10670 "Follow a link or time-stamp like Org mode does.
10671 This command can be called in any mode to follow an external link
10672 or a time-stamp that has Org mode syntax. Its behavior is
10673 undefined when called on internal links (e.g., fuzzy links).
10674 Raise an error when there is nothing to follow. "
10675 (interactive)
10676 (cond ((org-in-regexp org-any-link-re)
10677 (org-open-link-from-string (match-string-no-properties 0)))
10678 ((or (org-in-regexp org-ts-regexp-both nil t)
10679 (org-in-regexp org-tsr-regexp-both nil t))
10680 (org-follow-timestamp-link))
10681 (t (user-error "No link found"))))
10683 ;;;###autoload
10684 (defun org-open-link-from-string (s &optional arg reference-buffer)
10685 "Open a link in the string S, as if it was in Org-mode."
10686 (interactive "sLink: \nP")
10687 (let ((reference-buffer (or reference-buffer (current-buffer))))
10688 (with-temp-buffer
10689 (let ((org-inhibit-startup (not reference-buffer)))
10690 (org-mode)
10691 (insert s)
10692 (goto-char (point-min))
10693 (when reference-buffer
10694 (setq org-link-abbrev-alist-local
10695 (with-current-buffer reference-buffer
10696 org-link-abbrev-alist-local)))
10697 (org-open-at-point arg reference-buffer)))))
10699 (defvar org-open-at-point-functions nil
10700 "Hook that is run when following a link at point.
10702 Functions in this hook must return t if they identify and follow
10703 a link at point. If they don't find anything interesting at point,
10704 they must return nil.")
10706 (defvar org-link-search-inhibit-query nil)
10707 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10708 (defun org--open-doi-link (path)
10709 "Open a \"doi\" type link.
10710 PATH is a the path to search for, as a string."
10711 (browse-url (url-encode-url (concat org-doi-server-url path))))
10713 (defun org--open-elisp-link (path)
10714 "Open a \"elisp\" type link.
10715 PATH is the sexp to evaluate, as a string."
10716 (let ((cmd path))
10717 (if (or (and (org-string-nw-p
10718 org-confirm-elisp-link-not-regexp)
10719 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10720 (not org-confirm-elisp-link-function)
10721 (funcall org-confirm-elisp-link-function
10722 (format "Execute \"%s\" as elisp? "
10723 (org-add-props cmd nil 'face 'org-warning))))
10724 (message "%s => %s" cmd
10725 (if (eq (string-to-char cmd) ?\()
10726 (eval (read cmd))
10727 (call-interactively (read cmd))))
10728 (user-error "Abort"))))
10730 (defun org--open-help-link (path)
10731 "Open a \"help\" type link.
10732 PATH is a symbol name, as a string."
10733 (pcase (intern path)
10734 ((and (pred fboundp) variable) (describe-function variable))
10735 ((and (pred boundp) function) (describe-variable function))
10736 (name (user-error "Unknown function or variable: %s" name))))
10738 (defun org--open-shell-link (path)
10739 "Open a \"shell\" type link.
10740 PATH is the command to execute, as a string."
10741 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10742 (cmd path))
10743 (if (or (and (org-string-nw-p
10744 org-confirm-shell-link-not-regexp)
10745 (string-match
10746 org-confirm-shell-link-not-regexp cmd))
10747 (not org-confirm-shell-link-function)
10748 (funcall org-confirm-shell-link-function
10749 (format "Execute \"%s\" in shell? "
10750 (org-add-props cmd nil
10751 'face 'org-warning))))
10752 (progn
10753 (message "Executing %s" cmd)
10754 (shell-command cmd buf)
10755 (when (featurep 'midnight)
10756 (setq clean-buffer-list-kill-buffer-names
10757 (cons (buffer-name buf)
10758 clean-buffer-list-kill-buffer-names))))
10759 (user-error "Abort"))))
10761 (defun org-open-at-point (&optional arg reference-buffer)
10762 "Open link, timestamp, footnote or tags at point.
10764 When point is on a link, follow it. Normally, files will be
10765 opened by an appropriate application. If the optional prefix
10766 argument ARG is non-nil, Emacs will visit the file. With
10767 a double prefix argument, try to open outside of Emacs, in the
10768 application the system uses for this file type.
10770 When point is on a timestamp, open the agenda at the day
10771 specified.
10773 When point is a footnote definition, move to the first reference
10774 found. If it is on a reference, move to the associated
10775 definition.
10777 When point is on a headline, display a list of every link in the
10778 entry, so it is possible to pick one, or all, of them. If point
10779 is on a tag, call `org-tags-view' instead.
10781 When optional argument REFERENCE-BUFFER is non-nil, it should
10782 specify a buffer from where the link search should happen. This
10783 is used internally by `org-open-link-from-string'.
10785 On top of syntactically correct links, this function will open
10786 the link at point in comments or comment blocks and the first
10787 link in a property drawer line."
10788 (interactive "P")
10789 ;; On a code block, open block's results.
10790 (unless (call-interactively 'org-babel-open-src-block-result)
10791 (org-load-modules-maybe)
10792 (setq org-window-config-before-follow-link (current-window-configuration))
10793 (org-remove-occur-highlights nil nil t)
10794 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10795 (let* ((context
10796 ;; Only consider supported types, even if they are not
10797 ;; the closest one.
10798 (org-element-lineage
10799 (org-element-context)
10800 '(clock comment comment-block footnote-definition
10801 footnote-reference headline inlinetask keyword link
10802 node-property timestamp)
10804 (type (org-element-type context))
10805 (value (org-element-property :value context)))
10806 (cond
10807 ((not context) (user-error "No link found"))
10808 ;; Exception: open timestamps and links in properties
10809 ;; drawers, keywords and comments.
10810 ((memq type '(comment comment-block keyword node-property))
10811 (call-interactively #'org-open-at-point-global))
10812 ;; On a headline or an inlinetask, but not on a timestamp,
10813 ;; a link, a footnote reference or on tags.
10814 ((and (memq type '(headline inlinetask))
10815 ;; Not on tags.
10816 (progn (save-excursion (beginning-of-line)
10817 (looking-at org-complex-heading-regexp))
10818 (or (not (match-beginning 5))
10819 (< (point) (match-beginning 5)))))
10820 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10821 (links (car data))
10822 (links-end (cdr data)))
10823 (if links
10824 (dolist (link (if (stringp links) (list links) links))
10825 (search-forward link nil links-end)
10826 (goto-char (match-beginning 0))
10827 (org-open-at-point))
10828 (require 'org-attach)
10829 (org-attach-reveal 'if-exists))))
10830 ;; On a clock line, make sure point is on the timestamp
10831 ;; before opening it.
10832 ((and (eq type 'clock)
10833 value
10834 (>= (point) (org-element-property :begin value))
10835 (<= (point) (org-element-property :end value)))
10836 (org-follow-timestamp-link))
10837 ;; Do nothing on white spaces after an object.
10838 ((>= (point)
10839 (save-excursion
10840 (goto-char (org-element-property :end context))
10841 (skip-chars-backward " \t")
10842 (point)))
10843 (user-error "No link found"))
10844 ((eq type 'timestamp) (org-follow-timestamp-link))
10845 ;; On tags within a headline or an inlinetask.
10846 ((and (memq type '(headline inlinetask))
10847 (progn (save-excursion (beginning-of-line)
10848 (looking-at org-complex-heading-regexp))
10849 (and (match-beginning 5)
10850 (>= (point) (match-beginning 5)))))
10851 (org-tags-view arg (substring (match-string 5) 0 -1)))
10852 ((eq type 'link)
10853 ;; When link is located within the description of another
10854 ;; link (e.g., an inline image), always open the parent
10855 ;; link.
10856 (let* ((link (let ((up (org-element-property :parent context)))
10857 (if (eq (org-element-type up) 'link) up context)))
10858 (type (org-element-property :type link))
10859 (path (org-link-unescape (org-element-property :path link))))
10860 ;; Switch back to REFERENCE-BUFFER needed when called in
10861 ;; a temporary buffer through `org-open-link-from-string'.
10862 (with-current-buffer (or reference-buffer (current-buffer))
10863 (cond
10864 ((equal type "file")
10865 (if (string-match "[*?{]" (file-name-nondirectory path))
10866 (dired path)
10867 ;; Look into `org-link-parameters' in order to find
10868 ;; a DEDICATED-FUNCTION to open file. The function
10869 ;; will be applied on raw link instead of parsed
10870 ;; link due to the limitation in `org-add-link-type'
10871 ;; ("open" function called with a single argument).
10872 ;; If no such function is found, fallback to
10873 ;; `org-open-file'.
10874 (let* ((option (org-element-property :search-option link))
10875 (app (org-element-property :application link))
10876 (dedicated-function
10877 (org-link-get-parameter
10878 (if app (concat type "+" app) type)
10879 :follow)))
10880 (if dedicated-function
10881 (funcall dedicated-function
10882 (concat path
10883 (and option (concat "::" option))))
10884 (apply #'org-open-file
10885 path
10886 (cond (arg)
10887 ((equal app "emacs") 'emacs)
10888 ((equal app "sys") 'system))
10889 (cond ((not option) nil)
10890 ((string-match-p "\\`[0-9]+\\'" option)
10891 (list (string-to-number option)))
10892 (t (list nil
10893 (org-link-unescape option)))))))))
10894 ((functionp (org-link-get-parameter type :follow))
10895 (funcall (org-link-get-parameter type :follow) path))
10896 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10897 (unless (run-hook-with-args-until-success
10898 'org-open-link-functions path)
10899 (if (not arg) (org-mark-ring-push)
10900 (switch-to-buffer-other-window
10901 (org-get-buffer-for-internal-link (current-buffer))))
10902 (let ((destination
10903 (org-with-wide-buffer
10904 (if (equal type "radio")
10905 (org-search-radio-target
10906 (org-element-property :path link))
10907 (org-link-search
10908 (if (member type '("custom-id" "coderef"))
10909 (org-element-property :raw-link link)
10910 path)
10911 ;; Prevent fuzzy links from matching
10912 ;; themselves.
10913 (and (equal type "fuzzy")
10914 (+ 2 (org-element-property :begin link)))))
10915 (point))))
10916 (unless (and (<= (point-min) destination)
10917 (>= (point-max) destination))
10918 (widen))
10919 (goto-char destination))))
10920 (t (browse-url-at-point))))))
10921 ;; On a footnote reference or at a footnote definition's label.
10922 ((or (eq type 'footnote-reference)
10923 (and (eq type 'footnote-definition)
10924 (save-excursion
10925 ;; Do not validate action when point is on the
10926 ;; spaces right after the footnote label, in
10927 ;; order to be on par with behaviour on links.
10928 (skip-chars-forward " \t")
10929 (let ((begin
10930 (org-element-property :contents-begin context)))
10931 (if begin (< (point) begin)
10932 (= (org-element-property :post-affiliated context)
10933 (line-beginning-position)))))))
10934 (org-footnote-action))
10935 (t (user-error "No link found")))))
10936 (run-hook-with-args 'org-follow-link-hook)))
10938 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10939 "Offer links in the current entry and return the selected link.
10940 If there is only one link, return it.
10941 If NTH is an integer, return the NTH link found.
10942 If ZERO is a string, check also this string for a link, and if
10943 there is one, return it."
10944 (with-current-buffer buffer
10945 (org-with-wide-buffer
10946 (goto-char marker)
10947 (let ((cnt ?0)
10948 have-zero end links link c)
10949 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10950 (push (match-string 0 zero) links)
10951 (setq cnt (1- cnt) have-zero t))
10952 (save-excursion
10953 (org-back-to-heading t)
10954 (setq end (save-excursion (outline-next-heading) (point)))
10955 (while (re-search-forward org-any-link-re end t)
10956 (push (match-string 0) links))
10957 (setq links (org-uniquify (reverse links))))
10958 (cond
10959 ((null links)
10960 (message "No links"))
10961 ((equal (length links) 1)
10962 (setq link (car links)))
10963 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10964 (setq link (nth (if have-zero nth (1- nth)) links)))
10965 (t ; we have to select a link
10966 (save-excursion
10967 (save-window-excursion
10968 (delete-other-windows)
10969 (with-output-to-temp-buffer "*Select Link*"
10970 (dolist (l links)
10971 (cond
10972 ((not (string-match org-bracket-link-regexp l))
10973 (princ (format "[%c] %s\n" (cl-incf cnt)
10974 (org-unbracket-string "<" ">" l))))
10975 ((match-end 3)
10976 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10977 (match-string 3 l) (match-string 1 l))))
10978 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10979 (match-string 1 l)))))))
10980 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10981 (message "Select link to open, RET to open all:")
10982 (setq c (read-char-exclusive))
10983 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10984 (when (equal c ?q) (user-error "Abort"))
10985 (if (equal c ?\C-m)
10986 (setq link links)
10987 (setq nth (- c ?0))
10988 (when have-zero (setq nth (1+ nth)))
10989 (unless (and (integerp nth) (>= (length links) nth))
10990 (user-error "Invalid link selection"))
10991 (setq link (nth (1- nth) links)))))
10992 (cons link end)))))
10994 ;; TODO: These functions are deprecated since `org-open-at-point'
10995 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10996 (defun org-open-file-with-system (path)
10997 "Open file at PATH using the system way of opening it."
10998 (org-open-file path 'system))
10999 (defun org-open-file-with-emacs (path)
11000 "Open file at PATH in Emacs."
11001 (org-open-file path 'emacs))
11004 ;;; File search
11006 (defvar org-create-file-search-functions nil
11007 "List of functions to construct the right search string for a file link.
11008 These functions are called in turn with point at the location to
11009 which the link should point.
11011 A function in the hook should first test if it would like to
11012 handle this file type, for example by checking the `major-mode'
11013 or the file extension. If it decides not to handle this file, it
11014 should just return nil to give other functions a chance. If it
11015 does handle the file, it must return the search string to be used
11016 when following the link. The search string will be part of the
11017 file link, given after a double colon, and `org-open-at-point'
11018 will automatically search for it. If special measures must be
11019 taken to make the search successful, another function should be
11020 added to the companion hook `org-execute-file-search-functions',
11021 which see.
11023 A function in this hook may also use `setq' to set the variable
11024 `description' to provide a suggestion for the descriptive text to
11025 be used for this link when it gets inserted into an Org buffer
11026 with \\[org-insert-link].")
11028 (defvar org-execute-file-search-functions nil
11029 "List of functions to execute a file search triggered by a link.
11031 Functions added to this hook must accept a single argument, the
11032 search string that was part of the file link, the part after the
11033 double colon. The function must first check if it would like to
11034 handle this search, for example by checking the `major-mode' or
11035 the file extension. If it decides not to handle this search, it
11036 should just return nil to give other functions a chance. If it
11037 does handle the search, it must return a non-nil value to keep
11038 other functions from trying.
11040 Each function can access the current prefix argument through the
11041 variable `current-prefix-arg'. Note that a single prefix is used
11042 to force opening a link in Emacs, so it may be good to only use a
11043 numeric or double prefix to guide the search function.
11045 In case this is needed, a function in this hook can also restore
11046 the window configuration before `org-open-at-point' was called using:
11048 \(set-window-configuration org-window-config-before-follow-link)")
11050 (defun org-search-radio-target (target)
11051 "Search a radio target matching TARGET in current buffer.
11052 White spaces are not significant."
11053 (let ((re (format "<<<%s>>>"
11054 (mapconcat #'regexp-quote
11055 (org-split-string target "[ \t\n]+")
11056 "[ \t]+\\(?:\n[ \t]*\\)?")))
11057 (origin (point)))
11058 (goto-char (point-min))
11059 (catch :radio-match
11060 (while (re-search-forward re nil t)
11061 (backward-char)
11062 (let ((object (org-element-context)))
11063 (when (eq (org-element-type object) 'radio-target)
11064 (goto-char (org-element-property :begin object))
11065 (org-show-context 'link-search)
11066 (throw :radio-match nil))))
11067 (goto-char origin)
11068 (user-error "No match for radio target: %s" target))))
11070 (defun org-link-search (s &optional avoid-pos stealth)
11071 "Search for a search string S.
11073 If S starts with \"#\", it triggers a custom ID search.
11075 If S is enclosed within parenthesis, it initiates a coderef
11076 search.
11078 If S is surrounded by forward slashes, it is interpreted as
11079 a regular expression. In Org mode files, this will create an
11080 `org-occur' sparse tree. In ordinary files, `occur' will be used
11081 to list matches. If the current buffer is in `dired-mode', grep
11082 will be used to search in all files.
11084 When AVOID-POS is given, ignore matches near that position.
11086 When optional argument STEALTH is non-nil, do not modify
11087 visibility around point, thus ignoring `org-show-context-detail'
11088 variable.
11090 Search is case-insensitive and ignores white spaces. Return type
11091 of matched result, with is either `dedicated' or `fuzzy'."
11092 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11093 (let* ((case-fold-search t)
11094 (origin (point))
11095 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11096 (words (org-split-string s "[ \t\n]+"))
11097 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11098 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11099 type)
11100 (cond
11101 ;; Check if there are any special search functions.
11102 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11103 ((eq (string-to-char s) ?#)
11104 ;; Look for a custom ID S if S starts with "#".
11105 (let* ((id (substring normalized 1))
11106 (match (org-find-property "CUSTOM_ID" id)))
11107 (if match (progn (goto-char match) (setf type 'dedicated))
11108 (error "No match for custom ID: %s" id))))
11109 ((string-match "\\`(\\(.*\\))\\'" normalized)
11110 ;; Look for coderef targets if S is enclosed within parenthesis.
11111 (let ((coderef (match-string-no-properties 1 normalized))
11112 (re (substring s-single-re 1 -1)))
11113 (goto-char (point-min))
11114 (catch :coderef-match
11115 (while (re-search-forward re nil t)
11116 (let ((element (org-element-at-point)))
11117 (when (and (memq (org-element-type element)
11118 '(example-block src-block))
11119 ;; Build proper regexp according to current
11120 ;; block's label format.
11121 (let ((label-fmt
11122 (regexp-quote
11123 (or (org-element-property :label-fmt element)
11124 org-coderef-label-format))))
11125 (save-excursion
11126 (beginning-of-line)
11127 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11128 (format label-fmt coderef))))))
11129 (setq type 'dedicated)
11130 (goto-char (match-beginning 1))
11131 (throw :coderef-match nil))))
11132 (goto-char origin)
11133 (error "No match for coderef: %s" coderef))))
11134 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11135 ;; Look for a regular expression.
11136 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11137 (match-string 1 s)))
11138 ;; Fuzzy links.
11140 (let ((starred (eq (string-to-char normalized) ?*)))
11141 (cond
11142 ;; Look for targets, only if not in a headline search.
11143 ((and (not starred)
11144 (let ((target (format "<<%s>>" s-multi-re)))
11145 (catch :target-match
11146 (goto-char (point-min))
11147 (while (re-search-forward target nil t)
11148 (backward-char)
11149 (let ((context (org-element-context)))
11150 (when (eq (org-element-type context) 'target)
11151 (setq type 'dedicated)
11152 (goto-char (org-element-property :begin context))
11153 (throw :target-match t))))
11154 nil))))
11155 ;; Look for elements named after S, only if not in a headline
11156 ;; search.
11157 ((and (not starred)
11158 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11159 (catch :name-match
11160 (goto-char (point-min))
11161 (while (re-search-forward name nil t)
11162 (let ((element (org-element-at-point)))
11163 (when (equal (org-split-string
11164 (org-element-property :name element)
11165 "[ \t]+")
11166 words)
11167 (setq type 'dedicated)
11168 (beginning-of-line)
11169 (throw :name-match t))))
11170 nil))))
11171 ;; Regular text search. Prefer headlines in Org mode
11172 ;; buffers.
11173 ((and (derived-mode-p 'org-mode)
11174 (let* ((wspace "[ \t]")
11175 (wspaceopt (concat wspace "*"))
11176 (cookie (concat "\\(?:"
11177 wspaceopt
11178 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11179 wspaceopt
11180 "\\)"))
11181 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11182 (re (concat
11183 org-outline-regexp-bol
11184 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11185 "\\(?:\\[#.\\][ \t]+\\)?"
11186 "\\(?:" org-comment-string "[ \t]+\\)?"
11187 sep "?"
11188 (let ((title (mapconcat #'regexp-quote
11189 words
11190 sep)))
11191 (if starred (substring title 1) title))
11192 sep "?"
11193 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11194 "[ \t]*$")))
11195 (goto-char (point-min))
11196 (re-search-forward re nil t)))
11197 (goto-char (match-beginning 0))
11198 (setq type 'dedicated))
11199 ;; Offer to create non-existent headline depending on
11200 ;; `org-link-search-must-match-exact-headline'.
11201 ((and (derived-mode-p 'org-mode)
11202 (not org-link-search-inhibit-query)
11203 (eq org-link-search-must-match-exact-headline 'query-to-create)
11204 (yes-or-no-p "No match - create this as a new heading? "))
11205 (goto-char (point-max))
11206 (unless (bolp) (newline))
11207 (org-insert-heading nil t t)
11208 (insert s "\n")
11209 (beginning-of-line 0))
11210 ;; Only headlines are looked after. No need to process
11211 ;; further: throw an error.
11212 ((and (derived-mode-p 'org-mode)
11213 (or starred org-link-search-must-match-exact-headline))
11214 (goto-char origin)
11215 (error "No match for fuzzy expression: %s" normalized))
11216 ;; Regular text search.
11217 ((catch :fuzzy-match
11218 (goto-char (point-min))
11219 (while (re-search-forward s-multi-re nil t)
11220 ;; Skip match if it contains AVOID-POS or it is included
11221 ;; in a link with a description but outside the
11222 ;; description.
11223 (unless (or (and avoid-pos
11224 (<= (match-beginning 0) avoid-pos)
11225 (> (match-end 0) avoid-pos))
11226 (and (save-match-data
11227 (org-in-regexp org-bracket-link-regexp))
11228 (match-beginning 3)
11229 (or (> (match-beginning 3) (point))
11230 (<= (match-end 3) (point)))
11231 (org-element-lineage
11232 (save-match-data (org-element-context))
11233 '(link) t)))
11234 (goto-char (match-beginning 0))
11235 (setq type 'fuzzy)
11236 (throw :fuzzy-match t)))
11237 nil))
11238 ;; All failed. Throw an error.
11239 (t (goto-char origin)
11240 (error "No match for fuzzy expression: %s" normalized))))))
11241 ;; Disclose surroundings of match, if appropriate.
11242 (when (and (derived-mode-p 'org-mode) (not stealth))
11243 (org-show-context 'link-search))
11244 type))
11246 (defun org-get-buffer-for-internal-link (buffer)
11247 "Return a buffer to be used for displaying the link target of internal links."
11248 (cond
11249 ((not org-display-internal-link-with-indirect-buffer)
11250 buffer)
11251 ((string-suffix-p "(Clone)" (buffer-name buffer))
11252 (message "Buffer is already a clone, not making another one")
11253 ;; we also do not modify visibility in this case
11254 buffer)
11255 (t ; make a new indirect buffer for displaying the link
11256 (let* ((bn (buffer-name buffer))
11257 (ibn (concat bn "(Clone)"))
11258 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11259 (with-current-buffer ib (org-overview))
11260 ib))))
11262 (defun org-do-occur (regexp &optional cleanup)
11263 "Call the Emacs command `occur'.
11264 If CLEANUP is non-nil, remove the printout of the regular expression
11265 in the *Occur* buffer. This is useful if the regex is long and not useful
11266 to read."
11267 (occur regexp)
11268 (when cleanup
11269 (let ((cwin (selected-window)) win beg end)
11270 (when (setq win (get-buffer-window "*Occur*"))
11271 (select-window win))
11272 (goto-char (point-min))
11273 (when (re-search-forward "match[a-z]+" nil t)
11274 (setq beg (match-end 0))
11275 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11276 (setq end (1- (match-beginning 0)))))
11277 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11278 (goto-char (point-min))
11279 (select-window cwin))))
11281 ;;; The mark ring for links jumps
11283 (defvar org-mark-ring nil
11284 "Mark ring for positions before jumps in Org-mode.")
11285 (defvar org-mark-ring-last-goto nil
11286 "Last position in the mark ring used to go back.")
11287 ;; Fill and close the ring
11288 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11289 (dotimes (_ org-mark-ring-length)
11290 (push (make-marker) org-mark-ring))
11291 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11292 org-mark-ring)
11294 (defun org-mark-ring-push (&optional pos buffer)
11295 "Put the current position or POS into the mark ring and rotate it."
11296 (interactive)
11297 (setq pos (or pos (point)))
11298 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11299 (move-marker (car org-mark-ring)
11300 (or pos (point))
11301 (or buffer (current-buffer)))
11302 (message "%s"
11303 (substitute-command-keys
11304 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11306 (defun org-mark-ring-goto (&optional n)
11307 "Jump to the previous position in the mark ring.
11308 With prefix arg N, jump back that many stored positions. When
11309 called several times in succession, walk through the entire ring.
11310 Org mode commands jumping to a different position in the current file,
11311 or to another Org file, automatically push the old position onto the ring."
11312 (interactive "p")
11313 (let (p m)
11314 (if (eq last-command this-command)
11315 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11316 (setq p org-mark-ring))
11317 (setq org-mark-ring-last-goto p)
11318 (setq m (car p))
11319 (pop-to-buffer-same-window (marker-buffer m))
11320 (goto-char m)
11321 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11323 (defun org-add-angle-brackets (s)
11324 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11325 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11328 ;;; Following specific links
11330 (defvar org-agenda-buffer-tmp-name)
11331 (defvar org-agenda-start-on-weekday)
11332 (defun org-follow-timestamp-link ()
11333 "Open an agenda view for the time-stamp date/range at point."
11334 (cond
11335 ((org-at-date-range-p t)
11336 (let ((org-agenda-start-on-weekday)
11337 (t1 (match-string 1))
11338 (t2 (match-string 2)) tt1 tt2)
11339 (setq tt1 (time-to-days (org-time-string-to-time t1))
11340 tt2 (time-to-days (org-time-string-to-time t2)))
11341 (let ((org-agenda-buffer-tmp-name
11342 (format "*Org Agenda(a:%s)"
11343 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11344 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11345 ((org-at-timestamp-p t)
11346 (let ((org-agenda-buffer-tmp-name
11347 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11348 (org-agenda-list nil (time-to-days (org-time-string-to-time
11349 (substring (match-string 1) 0 10)))
11350 1)))
11351 (t (error "This should not happen"))))
11354 ;;; Following file links
11355 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11356 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11357 (declare-function mailcap-mime-info
11358 "mailcap" (string &optional request no-decode))
11359 (defvar org-wait nil)
11360 (defun org-open-file (path &optional in-emacs line search)
11361 "Open the file at PATH.
11362 First, this expands any special file name abbreviations. Then the
11363 configuration variable `org-file-apps' is checked if it contains an
11364 entry for this file type, and if yes, the corresponding command is launched.
11366 If no application is found, Emacs simply visits the file.
11368 With optional prefix argument IN-EMACS, Emacs will visit the file.
11369 With a double \\[universal-argument] \\[universal-argument] \
11370 prefix arg, Org tries to avoid opening in Emacs
11371 and to use an external application to visit the file.
11373 Optional LINE specifies a line to go to, optional SEARCH a string
11374 to search for. If LINE or SEARCH is given, the file will be
11375 opened in Emacs, unless an entry from org-file-apps that makes
11376 use of groups in a regexp matches.
11378 If you want to change the way frames are used when following a
11379 link, please customize `org-link-frame-setup'.
11381 If the file does not exist, an error is thrown."
11382 (let* ((file (if (equal path "")
11383 buffer-file-name
11384 (substitute-in-file-name (expand-file-name path))))
11385 (file-apps (append org-file-apps (org-default-apps)))
11386 (apps (cl-remove-if
11387 'org-file-apps-entry-match-against-dlink-p file-apps))
11388 (apps-dlink (cl-remove-if-not
11389 'org-file-apps-entry-match-against-dlink-p file-apps))
11390 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11391 (dirp (unless remp (file-directory-p file)))
11392 (file (if (and dirp org-open-directory-means-index-dot-org)
11393 (concat (file-name-as-directory file) "index.org")
11394 file))
11395 (a-m-a-p (assq 'auto-mode apps))
11396 (dfile (downcase file))
11397 ;; Reconstruct the original link from the PATH, LINE and
11398 ;; SEARCH args.
11399 (link (cond (line (concat file "::" (number-to-string line)))
11400 (search (concat file "::" search))
11401 (t file)))
11402 (dlink (downcase link))
11403 (old-buffer (current-buffer))
11404 (old-pos (point))
11405 (old-mode major-mode)
11406 (ext
11407 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11408 (match-string 1 dfile)))
11409 cmd link-match-data)
11410 (cond
11411 ((member in-emacs '((16) system))
11412 (setq cmd (cdr (assq 'system apps))))
11413 (in-emacs (setq cmd 'emacs))
11415 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11416 (and dirp (cdr (assq 'directory apps)))
11417 ;; First, try matching against apps-dlink if we
11418 ;; get a match here, store the match data for
11419 ;; later.
11420 (let ((match (assoc-default dlink apps-dlink
11421 'string-match)))
11422 (if match
11423 (progn (setq link-match-data (match-data))
11424 match)
11425 (progn (setq in-emacs (or in-emacs line search))
11426 nil))) ; if we have no match in apps-dlink,
11427 ; always open the file in emacs if line or search
11428 ; is given (for backwards compatibility)
11429 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11430 'string-match)
11431 (cdr (assoc ext apps))
11432 (cdr (assq t apps))))))
11433 (when (eq cmd 'system)
11434 (setq cmd (cdr (assq 'system apps))))
11435 (when (eq cmd 'default)
11436 (setq cmd (cdr (assoc t apps))))
11437 (when (eq cmd 'mailcap)
11438 (require 'mailcap)
11439 (mailcap-parse-mailcaps)
11440 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11441 (command (mailcap-mime-info mime-type)))
11442 (if (stringp command)
11443 (setq cmd command)
11444 (setq cmd 'emacs))))
11445 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11446 (not (file-exists-p file))
11447 (not org-open-non-existing-files))
11448 (user-error "No such file: %s" file))
11449 (cond
11450 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11451 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11452 (while (string-match "['\"]%s['\"]" cmd)
11453 (setq cmd (replace-match "%s" t t cmd)))
11454 (setq cmd (replace-regexp-in-string
11455 "%s"
11456 (shell-quote-argument (convert-standard-filename file))
11458 nil t))
11460 ;; Replace "%1", "%2" etc. in command with group matches from regex
11461 (save-match-data
11462 (let ((match-index 1)
11463 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11464 (set-match-data link-match-data)
11465 (while (<= match-index number-of-groups)
11466 (let ((regex (concat "%" (number-to-string match-index)))
11467 (replace-with (match-string match-index dlink)))
11468 (while (string-match regex cmd)
11469 (setq cmd (replace-match replace-with t t cmd))))
11470 (setq match-index (+ match-index 1)))))
11472 (save-window-excursion
11473 (message "Running %s...done" cmd)
11474 (start-process-shell-command cmd nil cmd)
11475 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11476 ((or (stringp cmd)
11477 (eq cmd 'emacs))
11478 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11479 (widen)
11480 (cond (line (org-goto-line line)
11481 (when (derived-mode-p 'org-mode) (org-reveal)))
11482 (search (org-link-search search))))
11483 ((functionp cmd)
11484 (save-match-data
11485 (set-match-data link-match-data)
11486 (condition-case nil
11487 (funcall cmd file link)
11488 ;; FIXME: Remove this check when most default installations
11489 ;; of Emacs have at least Org 9.0.
11490 ((debug wrong-number-of-arguments wrong-type-argument
11491 invalid-function)
11492 (user-error "Please see Org News for version 9.0 about \
11493 `org-file-apps'--Lisp error: %S" cmd)))))
11494 ((consp cmd)
11495 ;; FIXME: Remove this check when most default installations of
11496 ;; Emacs have at least Org 9.0.
11497 ;; Heads-up instead of silently fall back to
11498 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11499 ;; with sexp instead of a function for `cmd'.
11500 (user-error "Please see Org News for version 9.0 about \
11501 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11502 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11503 (and (derived-mode-p 'org-mode)
11504 (eq old-mode 'org-mode)
11505 (or (not (eq old-buffer (current-buffer)))
11506 (not (eq old-pos (point))))
11507 (org-mark-ring-push old-pos old-buffer))))
11509 (defun org-file-apps-entry-match-against-dlink-p (entry)
11510 "This function returns non-nil if `entry' uses a regular
11511 expression which should be matched against the whole link by
11512 org-open-file.
11514 It assumes that is the case when the entry uses a regular
11515 expression which has at least one grouping construct and the
11516 action is either a lisp form or a command string containing
11517 `%1', i.e. using at least one subexpression match as a
11518 parameter."
11519 (let ((selector (car entry))
11520 (action (cdr entry)))
11521 (if (stringp selector)
11522 (and (> (regexp-opt-depth selector) 0)
11523 (or (and (stringp action)
11524 (string-match "%[0-9]" action))
11525 (consp action)))
11526 nil)))
11528 (defun org-default-apps ()
11529 "Return the default applications for this operating system."
11530 (cond
11531 ((eq system-type 'darwin)
11532 org-file-apps-defaults-macosx)
11533 ((eq system-type 'windows-nt)
11534 org-file-apps-defaults-windowsnt)
11535 (t org-file-apps-defaults-gnu)))
11537 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11538 "Convert extensions to regular expressions in the cars of LIST.
11539 Also, weed out any non-string entries, because the return value is used
11540 only for regexp matching.
11541 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11542 point to the symbol `emacs', indicating that the file should
11543 be opened in Emacs."
11544 (append
11545 (delq nil
11546 (mapcar (lambda (x)
11547 (unless (not (stringp (car x)))
11548 (if (string-match "\\W" (car x))
11550 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11551 list))
11552 (when add-auto-mode
11553 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11555 (defvar ange-ftp-name-format)
11556 (defun org-file-remote-p (file)
11557 "Test whether FILE specifies a location on a remote system.
11558 Return non-nil if the location is indeed remote.
11560 For example, the filename \"/user@host:/foo\" specifies a location
11561 on the system \"/user@host:\"."
11562 (cond ((fboundp 'file-remote-p)
11563 (file-remote-p file))
11564 ((fboundp 'tramp-handle-file-remote-p)
11565 (tramp-handle-file-remote-p file))
11566 ((and (boundp 'ange-ftp-name-format)
11567 (string-match (car ange-ftp-name-format) file))
11568 t)))
11571 ;;;; Refiling
11573 (defun org-get-org-file ()
11574 "Read a filename, with default directory `org-directory'."
11575 (let ((default (or org-default-notes-file remember-data-file)))
11576 (read-file-name (format "File name [%s]: " default)
11577 (file-name-as-directory org-directory)
11578 default)))
11580 (defun org-notes-order-reversed-p ()
11581 "Check if the current file should receive notes in reversed order."
11582 (cond
11583 ((not org-reverse-note-order) nil)
11584 ((eq t org-reverse-note-order) t)
11585 ((not (listp org-reverse-note-order)) nil)
11586 (t (catch 'exit
11587 (dolist (entry org-reverse-note-order)
11588 (when (string-match (car entry) buffer-file-name)
11589 (throw 'exit (cdr entry))))))))
11591 (defvar org-refile-target-table nil
11592 "The list of refile targets, created by `org-refile'.")
11594 (defvar org-agenda-new-buffers nil
11595 "Buffers created to visit agenda files.")
11597 (defvar org-refile-cache nil
11598 "Cache for refile targets.")
11600 (defvar org-refile-markers nil
11601 "All the markers used for caching refile locations.")
11603 (defun org-refile-marker (pos)
11604 "Get a new refile marker, but only if caching is in use."
11605 (if (not org-refile-use-cache)
11607 (let ((m (make-marker)))
11608 (move-marker m pos)
11609 (push m org-refile-markers)
11610 m)))
11612 (defun org-refile-cache-clear ()
11613 "Clear the refile cache and disable all the markers."
11614 (dolist (m org-refile-markers) (move-marker m nil))
11615 (setq org-refile-markers nil)
11616 (setq org-refile-cache nil)
11617 (message "Refile cache has been cleared"))
11619 (defun org-refile-cache-check-set (set)
11620 "Check if all the markers in the cache still have live buffers."
11621 (let (marker)
11622 (catch 'exit
11623 (while (and set (setq marker (nth 3 (pop set))))
11624 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11625 (when (and marker (null (marker-buffer marker)))
11626 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11627 (sit-for 3)
11628 (throw 'exit nil)))
11629 t)))
11631 (defun org-refile-cache-put (set &rest identifiers)
11632 "Push the refile targets SET into the cache, under IDENTIFIERS."
11633 (let* ((key (sha1 (prin1-to-string identifiers)))
11634 (entry (assoc key org-refile-cache)))
11635 (if entry
11636 (setcdr entry set)
11637 (push (cons key set) org-refile-cache))))
11639 (defun org-refile-cache-get (&rest identifiers)
11640 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11641 (cond
11642 ((not org-refile-cache) nil)
11643 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11645 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11646 org-refile-cache))))
11647 (and set (org-refile-cache-check-set set) set)))))
11649 (defvar org-outline-path-cache nil
11650 "Alist between buffer positions and outline paths.
11651 It value is an alist (POSITION . PATH) where POSITION is the
11652 buffer position at the beginning of an entry and PATH is a list
11653 of strings describing the outline path for that entry, in reverse
11654 order.")
11656 (defun org-refile-get-targets (&optional default-buffer)
11657 "Produce a table with refile targets."
11658 (let ((case-fold-search nil)
11659 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11660 (entries (or org-refile-targets '((nil . (:level . 1)))))
11661 targets tgs files desc descre)
11662 (message "Getting targets...")
11663 (with-current-buffer (or default-buffer (current-buffer))
11664 (dolist (entry entries)
11665 (setq files (car entry) desc (cdr entry))
11666 (cond
11667 ((null files) (setq files (list (current-buffer))))
11668 ((eq files 'org-agenda-files)
11669 (setq files (org-agenda-files 'unrestricted)))
11670 ((and (symbolp files) (fboundp files))
11671 (setq files (funcall files)))
11672 ((and (symbolp files) (boundp files))
11673 (setq files (symbol-value files))))
11674 (when (stringp files) (setq files (list files)))
11675 (cond
11676 ((eq (car desc) :tag)
11677 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11678 ((eq (car desc) :todo)
11679 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11680 ((eq (car desc) :regexp)
11681 (setq descre (cdr desc)))
11682 ((eq (car desc) :level)
11683 (setq descre (concat "^\\*\\{" (number-to-string
11684 (if org-odd-levels-only
11685 (1- (* 2 (cdr desc)))
11686 (cdr desc)))
11687 "\\}[ \t]")))
11688 ((eq (car desc) :maxlevel)
11689 (setq descre (concat "^\\*\\{1," (number-to-string
11690 (if org-odd-levels-only
11691 (1- (* 2 (cdr desc)))
11692 (cdr desc)))
11693 "\\}[ \t]")))
11694 (t (error "Bad refiling target description %s" desc)))
11695 (dolist (f files)
11696 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11698 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11699 (progn
11700 (when (bufferp f)
11701 (setq f (buffer-file-name (buffer-base-buffer f))))
11702 (setq f (and f (expand-file-name f)))
11703 (when (eq org-refile-use-outline-path 'file)
11704 (push (list (file-name-nondirectory f) f nil nil) tgs))
11705 (org-with-wide-buffer
11706 (goto-char (point-min))
11707 (setq org-outline-path-cache nil)
11708 (while (re-search-forward descre nil t)
11709 (beginning-of-line)
11710 (looking-at org-complex-heading-regexp)
11711 (let ((begin (point))
11712 (heading (match-string-no-properties 4)))
11713 (unless (or (and
11714 org-refile-target-verify-function
11715 (not
11716 (funcall org-refile-target-verify-function)))
11717 (not heading))
11718 (let ((re (format org-complex-heading-regexp-format
11719 (regexp-quote heading)))
11720 (target
11721 (if (not org-refile-use-outline-path) heading
11722 (mapconcat
11723 #'org-protect-slash
11724 (append
11725 (pcase org-refile-use-outline-path
11726 (`file (list (file-name-nondirectory
11727 (buffer-file-name
11728 (buffer-base-buffer)))))
11729 (`full-file-path
11730 (list (buffer-file-name
11731 (buffer-base-buffer))))
11732 (_ nil))
11733 (org-get-outline-path t t))
11734 "/"))))
11735 (push (list target f re (org-refile-marker (point)))
11736 tgs)))
11737 (when (= (point) begin)
11738 ;; Verification function has not moved point.
11739 (end-of-line)))))))
11740 (when org-refile-use-cache
11741 (org-refile-cache-put tgs (buffer-file-name) descre))
11742 (setq targets (append tgs targets))))))
11743 (message "Getting targets...done")
11744 (nreverse targets)))
11746 (defun org-protect-slash (s)
11747 (replace-regexp-in-string "/" "\\/" s nil t))
11749 (defun org--get-outline-path-1 (&optional use-cache)
11750 "Return outline path to current headline.
11752 Outline path is a list of strings, in reverse order. When
11753 optional argument USE-CACHE is non-nil, make use of a cache. See
11754 `org-get-outline-path' for details.
11756 Assume buffer is widened and point is on a headline."
11757 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11758 (let ((p (point))
11759 (heading (progn
11760 (looking-at org-complex-heading-regexp)
11761 (if (not (match-end 4)) ""
11762 ;; Remove statistics cookies.
11763 (org-trim
11764 (org-link-display-format
11765 (replace-regexp-in-string
11766 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11767 (match-string-no-properties 4))))))))
11768 (if (org-up-heading-safe)
11769 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11770 (when use-cache
11771 (push (cons p path) org-outline-path-cache))
11772 path)
11773 ;; This is a new root node. Since we assume we are moving
11774 ;; forward, we can drop previous cache so as to limit number
11775 ;; of associations there.
11776 (let ((path (list heading)))
11777 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11778 path)))))
11780 (defun org-get-outline-path (&optional with-self use-cache)
11781 "Return the outline path to the current entry.
11783 An outline path is a list of ancestors for current headline, as
11784 a list of strings. Statistics cookies are removed and links are
11785 replaced with their description, if any, or their path otherwise.
11787 When optional argument WITH-SELF is non-nil, the path also
11788 includes the current headline.
11790 When optional argument USE-CACHE is non-nil, cache outline paths
11791 between calls to this function so as to avoid backtracking. This
11792 argument is useful when planning to find more than one outline
11793 path in the same document. In that case, there are two
11794 conditions to satisfy:
11795 - `org-outline-path-cache' is set to nil before starting the
11796 process;
11797 - outline paths are computed by increasing buffer positions."
11798 (org-with-wide-buffer
11799 (and (or (and with-self (org-back-to-heading t))
11800 (org-up-heading-safe))
11801 (reverse (org--get-outline-path-1 use-cache)))))
11803 (defun org-format-outline-path (path &optional width prefix separator)
11804 "Format the outline path PATH for display.
11805 WIDTH is the maximum number of characters that is available.
11806 PREFIX is a prefix to be included in the returned string,
11807 such as the file name.
11808 SEPARATOR is inserted between the different parts of the path,
11809 the default is \"/\"."
11810 (setq width (or width 79))
11811 (setq path (delq nil path))
11812 (unless (> width 0)
11813 (user-error "Argument `width' must be positive"))
11814 (setq separator (or separator "/"))
11815 (let* ((org-odd-levels-only nil)
11816 (fpath (concat
11817 prefix (and prefix path separator)
11818 (mapconcat
11819 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11820 (cl-loop for head in path
11821 for n from 0
11822 collect (org-add-props
11823 head nil 'face
11824 (nth (% n org-n-level-faces) org-level-faces)))
11825 separator))))
11826 (when (> (length fpath) width)
11827 (if (< width 7)
11828 ;; It's unlikely that `width' will be this small, but don't
11829 ;; waste characters by adding ".." if it is.
11830 (setq fpath (substring fpath 0 width))
11831 (setf (substring fpath (- width 2)) "..")))
11832 fpath))
11834 (defun org-display-outline-path (&optional file current separator just-return-string)
11835 "Display the current outline path in the echo area.
11837 If FILE is non-nil, prepend the output with the file name.
11838 If CURRENT is non-nil, append the current heading to the output.
11839 SEPARATOR is passed through to `org-format-outline-path'. It separates
11840 the different parts of the path and defaults to \"/\".
11841 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11842 (interactive "P")
11843 (let* (case-fold-search
11844 (bfn (buffer-file-name (buffer-base-buffer)))
11845 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11846 res)
11847 (when current (setq path (append path
11848 (save-excursion
11849 (org-back-to-heading t)
11850 (when (looking-at org-complex-heading-regexp)
11851 (list (match-string 4)))))))
11852 (setq res
11853 (org-format-outline-path
11854 path
11855 (1- (frame-width))
11856 (and file bfn (concat (file-name-nondirectory bfn) separator))
11857 separator))
11858 (if just-return-string
11859 (org-no-properties res)
11860 (org-unlogged-message "%s" res))))
11862 (defvar org-refile-history nil
11863 "History for refiling operations.")
11865 (defvar org-after-refile-insert-hook nil
11866 "Hook run after `org-refile' has inserted its stuff at the new location.
11867 Note that this is still *before* the stuff will be removed from
11868 the *old* location.")
11870 (defvar org-capture-last-stored-marker)
11871 (defvar org-refile-keep nil
11872 "Non-nil means `org-refile' will copy instead of refile.")
11874 (defun org-copy ()
11875 "Like `org-refile', but copy."
11876 (interactive)
11877 (let ((org-refile-keep t))
11878 (funcall 'org-refile nil nil nil "Copy")))
11880 (defun org-refile (&optional arg default-buffer rfloc msg)
11881 "Move the entry or entries at point to another heading.
11882 The list of target headings is compiled using the information in
11883 `org-refile-targets', which see.
11885 At the target location, the entry is filed as a subitem of the
11886 target heading. Depending on `org-reverse-note-order', the new
11887 subitem will either be the first or the last subitem.
11889 If there is an active region, all entries in that region will be
11890 refiled. However, the region must fulfill the requirement that
11891 the first heading sets the top-level of the moved text.
11893 With prefix arg ARG, the command will only visit the target
11894 location and not actually move anything.
11896 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11897 refiling operation has put the subtree.
11899 With a numeric prefix argument of `2', refile to the running clock.
11901 With a numeric prefix argument of `3', emulate `org-refile-keep'
11902 being set to t and copy to the target location, don't move it.
11903 Beware that keeping refiled entries may result in duplicated ID
11904 properties.
11906 RFLOC can be a refile location obtained in a different way.
11908 MSG is a string to replace \"Refile\" in the default prompt with
11909 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11911 See also `org-refile-use-outline-path'.
11913 If you are using target caching (see `org-refile-use-cache'), you
11914 have to clear the target cache in order to find new targets.
11915 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11916 prefix argument (`C-u C-u C-u C-c C-w')."
11917 (interactive "P")
11918 (if (member arg '(0 (64)))
11919 (org-refile-cache-clear)
11920 (let* ((actionmsg (cond (msg msg)
11921 ((equal arg 3) "Refile (and keep)")
11922 (t "Refile")))
11923 (regionp (org-region-active-p))
11924 (region-start (and regionp (region-beginning)))
11925 (region-end (and regionp (region-end)))
11926 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11927 pos it nbuf file level reversed)
11928 (setq last-command nil)
11929 (when regionp
11930 (goto-char region-start)
11931 (or (bolp) (goto-char (point-at-bol)))
11932 (setq region-start (point))
11933 (unless (or (org-kill-is-subtree-p
11934 (buffer-substring region-start region-end))
11935 (prog1 org-refile-active-region-within-subtree
11936 (let ((s (point-at-eol)))
11937 (org-toggle-heading)
11938 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11939 (user-error "The region is not a (sequence of) subtree(s)")))
11940 (if (equal arg '(16))
11941 (org-refile-goto-last-stored)
11942 (when (or
11943 (and (equal arg 2)
11944 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11945 (prog1
11946 (setq it (list (or org-clock-heading "running clock")
11947 (buffer-file-name
11948 (marker-buffer org-clock-hd-marker))
11950 (marker-position org-clock-hd-marker)))
11951 (setq arg nil)))
11952 (setq it
11953 (or rfloc
11954 (let (heading-text)
11955 (save-excursion
11956 (unless (and arg (listp arg))
11957 (org-back-to-heading t)
11958 (setq heading-text
11959 (replace-regexp-in-string
11960 org-bracket-link-regexp
11961 "\\3"
11962 (or (nth 4 (org-heading-components))
11963 ""))))
11964 (org-refile-get-location
11965 (cond ((and arg (listp arg)) "Goto")
11966 (regionp (concat actionmsg " region to"))
11967 (t (concat actionmsg " subtree \""
11968 heading-text "\" to")))
11969 default-buffer
11970 (and (not (equal '(4) arg))
11971 org-refile-allow-creating-parent-nodes)))))))
11972 (setq file (nth 1 it)
11973 pos (nth 3 it))
11974 (when (and (not arg)
11976 (equal (buffer-file-name) file)
11977 (if regionp
11978 (and (>= pos region-start)
11979 (<= pos region-end))
11980 (and (>= pos (point))
11981 (< pos (save-excursion
11982 (org-end-of-subtree t t))))))
11983 (error "Cannot refile to position inside the tree or region"))
11984 (setq nbuf (or (find-buffer-visiting file)
11985 (find-file-noselect file)))
11986 (if (and arg (not (equal arg 3)))
11987 (progn
11988 (pop-to-buffer-same-window nbuf)
11989 (goto-char pos)
11990 (org-show-context 'org-goto))
11991 (if regionp
11992 (progn
11993 (org-kill-new (buffer-substring region-start region-end))
11994 (org-save-markers-in-region region-start region-end))
11995 (org-copy-subtree 1 nil t))
11996 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11997 (find-file-noselect file)))
11998 (setq reversed (org-notes-order-reversed-p))
11999 (org-with-wide-buffer
12000 (if pos
12001 (progn
12002 (goto-char pos)
12003 (looking-at org-outline-regexp)
12004 (setq level (org-get-valid-level (funcall outline-level) 1))
12005 (goto-char
12006 (if reversed
12007 (or (outline-next-heading) (point-max))
12008 (or (save-excursion (org-get-next-sibling))
12009 (org-end-of-subtree t t)
12010 (point-max)))))
12011 (setq level 1)
12012 (if (not reversed)
12013 (goto-char (point-max))
12014 (goto-char (point-min))
12015 (or (outline-next-heading) (goto-char (point-max)))))
12016 (unless (bolp) (newline))
12017 (org-paste-subtree level nil nil t)
12018 (when org-log-refile
12019 (org-add-log-setup 'refile nil nil org-log-refile)
12020 (unless (eq org-log-refile 'note)
12021 (save-excursion (org-add-log-note))))
12022 (and org-auto-align-tags
12023 (let ((org-loop-over-headlines-in-active-region nil))
12024 (org-set-tags nil t)))
12025 (let ((bookmark-name (plist-get org-bookmark-names-plist
12026 :last-refile)))
12027 (when bookmark-name
12028 (with-demoted-errors
12029 (bookmark-set bookmark-name))))
12030 ;; If we are refiling for capture, make sure that the
12031 ;; last-capture pointers point here
12032 (when (bound-and-true-p org-capture-is-refiling)
12033 (let ((bookmark-name (plist-get org-bookmark-names-plist
12034 :last-capture-marker)))
12035 (when bookmark-name
12036 (with-demoted-errors
12037 (bookmark-set bookmark-name))))
12038 (move-marker org-capture-last-stored-marker (point)))
12039 (when (fboundp 'deactivate-mark) (deactivate-mark))
12040 (run-hooks 'org-after-refile-insert-hook)))
12041 (unless org-refile-keep
12042 (if regionp
12043 (delete-region (point) (+ (point) (- region-end region-start)))
12044 (delete-region
12045 (and (org-back-to-heading t) (point))
12046 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12047 (when (featurep 'org-inlinetask)
12048 (org-inlinetask-remove-END-maybe))
12049 (setq org-markers-to-move nil)
12050 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12052 (defun org-refile-goto-last-stored ()
12053 "Go to the location where the last refile was stored."
12054 (interactive)
12055 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12056 (message "This is the location of the last refile"))
12058 (defun org-refile--get-location (refloc tbl)
12059 "When user refile to REFLOC, find the associated target in TBL.
12060 Also check `org-refile-target-table'."
12061 (car (delq
12063 (mapcar
12064 (lambda (r) (or (assoc r tbl)
12065 (assoc r org-refile-target-table)))
12066 (list (replace-regexp-in-string "/$" "" refloc)
12067 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12069 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12070 "Prompt the user for a refile location, using PROMPT.
12071 PROMPT should not be suffixed with a colon and a space, because
12072 this function appends the default value from
12073 `org-refile-history' automatically, if that is not empty."
12074 (let ((org-refile-targets org-refile-targets)
12075 (org-refile-use-outline-path org-refile-use-outline-path))
12076 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12077 (unless org-refile-target-table
12078 (user-error "No refile targets"))
12079 (let* ((cbuf (current-buffer))
12080 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12081 (cfunc (if (and org-refile-use-outline-path
12082 org-outline-path-complete-in-steps)
12083 #'org-olpath-completing-read
12084 #'completing-read))
12085 (extra (if org-refile-use-outline-path "/" ""))
12086 (cbnex (concat (buffer-name) extra))
12087 (filename (and cfn (expand-file-name cfn)))
12088 (tbl (mapcar
12089 (lambda (x)
12090 (if (and (not (member org-refile-use-outline-path
12091 '(file full-file-path)))
12092 (not (equal filename (nth 1 x))))
12093 (cons (concat (car x) extra " ("
12094 (file-name-nondirectory (nth 1 x)) ")")
12095 (cdr x))
12096 (cons (concat (car x) extra) (cdr x))))
12097 org-refile-target-table))
12098 (completion-ignore-case t)
12099 cdef
12100 (prompt (concat prompt
12101 (or (and (car org-refile-history)
12102 (concat " (default " (car org-refile-history) ")"))
12103 (and (assoc cbnex tbl) (setq cdef cbnex)
12104 (concat " (default " cbnex ")"))) ": "))
12105 pa answ parent-target child parent old-hist)
12106 (setq old-hist org-refile-history)
12107 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12108 nil 'org-refile-history (or cdef (car org-refile-history))))
12109 (if (setq pa (org-refile--get-location answ tbl))
12110 (progn
12111 (org-refile-check-position pa)
12112 (when (or (not org-refile-history)
12113 (not (eq old-hist org-refile-history))
12114 (not (equal (car pa) (car org-refile-history))))
12115 (setq org-refile-history
12116 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12117 org-refile-history
12118 (cdr org-refile-history))))
12119 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12120 (pop org-refile-history)))
12122 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12123 (progn
12124 (setq parent (match-string 1 answ)
12125 child (match-string 2 answ))
12126 (setq parent-target (org-refile--get-location parent tbl))
12127 (when (and parent-target
12128 (or (eq new-nodes t)
12129 (and (eq new-nodes 'confirm)
12130 (y-or-n-p (format "Create new node \"%s\"? "
12131 child)))))
12132 (org-refile-new-child parent-target child)))
12133 (user-error "Invalid target location")))))
12135 (declare-function org-string-nw-p "org-macs" (s))
12136 (defun org-refile-check-position (refile-pointer)
12137 "Check if the refile pointer matches the headline to which it points."
12138 (let* ((file (nth 1 refile-pointer))
12139 (re (nth 2 refile-pointer))
12140 (pos (nth 3 refile-pointer))
12141 buffer)
12142 (if (and (not (markerp pos)) (not file))
12143 (user-error "Please indicate a target file in the refile path")
12144 (when (org-string-nw-p re)
12145 (setq buffer (if (markerp pos)
12146 (marker-buffer pos)
12147 (or (find-buffer-visiting file)
12148 (find-file-noselect file))))
12149 (with-current-buffer buffer
12150 (org-with-wide-buffer
12151 (goto-char pos)
12152 (beginning-of-line 1)
12153 (unless (looking-at-p re)
12154 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12156 (defun org-refile-new-child (parent-target child)
12157 "Use refile target PARENT-TARGET to add new CHILD below it."
12158 (unless parent-target
12159 (error "Cannot find parent for new node"))
12160 (let ((file (nth 1 parent-target))
12161 (pos (nth 3 parent-target))
12162 level)
12163 (with-current-buffer (or (find-buffer-visiting file)
12164 (find-file-noselect file))
12165 (org-with-wide-buffer
12166 (if pos
12167 (goto-char pos)
12168 (goto-char (point-max))
12169 (unless (bolp) (newline)))
12170 (when (looking-at org-outline-regexp)
12171 (setq level (funcall outline-level))
12172 (org-end-of-subtree t t))
12173 (org-back-over-empty-lines)
12174 (insert "\n" (make-string
12175 (if pos (org-get-valid-level level 1) 1) ?*)
12176 " " child "\n")
12177 (beginning-of-line 0)
12178 (list (concat (car parent-target) "/" child) file "" (point))))))
12180 (defun org-olpath-completing-read (prompt collection &rest args)
12181 "Read an outline path like a file name."
12182 (let ((thetable collection))
12183 (apply #'completing-read
12184 prompt
12185 (lambda (string predicate &optional flag)
12186 (cond
12187 ((eq flag nil) (try-completion string thetable))
12188 ((eq flag t)
12189 (let ((l (length string)))
12190 (mapcar (lambda (x)
12191 (let ((r (substring x l))
12192 (f (if (string-match " ([^)]*)$" x)
12193 (match-string 0 x)
12194 "")))
12195 (if (string-match "/" r)
12196 (concat string (substring r 0 (match-end 0)) f)
12197 x)))
12198 (all-completions string thetable predicate))))
12199 ;; Exact match?
12200 ((eq flag 'lambda) (assoc string thetable))))
12201 args)))
12203 ;;;; Dynamic blocks
12205 (defun org-find-dblock (name)
12206 "Find the first dynamic block with name NAME in the buffer.
12207 If not found, stay at current position and return nil."
12208 (let ((case-fold-search t) pos)
12209 (save-excursion
12210 (goto-char (point-min))
12211 (setq pos (and (re-search-forward
12212 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12213 (match-beginning 0))))
12214 (when pos (goto-char pos))
12215 pos))
12217 (defun org-create-dblock (plist)
12218 "Create a dynamic block section, with parameters taken from PLIST.
12219 PLIST must contain a :name entry which is used as the name of the block."
12220 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12221 (end-of-line 1)
12222 (newline))
12223 (let ((col (current-column))
12224 (name (plist-get plist :name)))
12225 (insert "#+BEGIN: " name)
12226 (while plist
12227 (if (eq (car plist) :name)
12228 (setq plist (cddr plist))
12229 (insert " " (prin1-to-string (pop plist)))))
12230 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12231 (beginning-of-line -2)))
12233 (defun org-prepare-dblock ()
12234 "Prepare dynamic block for refresh.
12235 This empties the block, puts the cursor at the insert position and returns
12236 the property list including an extra property :name with the block name."
12237 (unless (looking-at org-dblock-start-re)
12238 (user-error "Not at a dynamic block"))
12239 (let* ((begdel (1+ (match-end 0)))
12240 (name (org-no-properties (match-string 1)))
12241 (params (append (list :name name)
12242 (read (concat "(" (match-string 3) ")")))))
12243 (save-excursion
12244 (beginning-of-line 1)
12245 (skip-chars-forward " \t")
12246 (setq params (plist-put params :indentation-column (current-column))))
12247 (unless (re-search-forward org-dblock-end-re nil t)
12248 (error "Dynamic block not terminated"))
12249 (setq params
12250 (append params
12251 (list :content (buffer-substring
12252 begdel (match-beginning 0)))))
12253 (delete-region begdel (match-beginning 0))
12254 (goto-char begdel)
12255 (open-line 1)
12256 params))
12258 (defun org-map-dblocks (&optional command)
12259 "Apply COMMAND to all dynamic blocks in the current buffer.
12260 If COMMAND is not given, use `org-update-dblock'."
12261 (let ((cmd (or command 'org-update-dblock)))
12262 (save-excursion
12263 (goto-char (point-min))
12264 (while (re-search-forward org-dblock-start-re nil t)
12265 (goto-char (match-beginning 0))
12266 (save-excursion
12267 (condition-case nil
12268 (funcall cmd)
12269 (error (message "Error during update of dynamic block"))))
12270 (unless (re-search-forward org-dblock-end-re nil t)
12271 (error "Dynamic block not terminated"))))))
12273 (defun org-dblock-update (&optional arg)
12274 "User command for updating dynamic blocks.
12275 Update the dynamic block at point. With prefix ARG, update all dynamic
12276 blocks in the buffer."
12277 (interactive "P")
12278 (if arg
12279 (org-update-all-dblocks)
12280 (or (looking-at org-dblock-start-re)
12281 (org-beginning-of-dblock))
12282 (org-update-dblock)))
12284 (defun org-update-dblock ()
12285 "Update the dynamic block at point.
12286 This means to empty the block, parse for parameters and then call
12287 the correct writing function."
12288 (interactive)
12289 (save-excursion
12290 (let* ((win (selected-window))
12291 (pos (point))
12292 (line (org-current-line))
12293 (params (org-prepare-dblock))
12294 (name (plist-get params :name))
12295 (indent (plist-get params :indentation-column))
12296 (cmd (intern (concat "org-dblock-write:" name))))
12297 (message "Updating dynamic block `%s' at line %d..." name line)
12298 (funcall cmd params)
12299 (message "Updating dynamic block `%s' at line %d...done" name line)
12300 (goto-char pos)
12301 (when (and indent (> indent 0))
12302 (setq indent (make-string indent ?\ ))
12303 (save-excursion
12304 (select-window win)
12305 (org-beginning-of-dblock)
12306 (forward-line 1)
12307 (while (not (looking-at org-dblock-end-re))
12308 (insert indent)
12309 (beginning-of-line 2))
12310 (when (looking-at org-dblock-end-re)
12311 (and (looking-at "[ \t]+")
12312 (replace-match ""))
12313 (insert indent)))))))
12315 (defun org-beginning-of-dblock ()
12316 "Find the beginning of the dynamic block at point.
12317 Error if there is no such block at point."
12318 (let ((pos (point))
12319 beg)
12320 (end-of-line 1)
12321 (if (and (re-search-backward org-dblock-start-re nil t)
12322 (setq beg (match-beginning 0))
12323 (re-search-forward org-dblock-end-re nil t)
12324 (> (match-end 0) pos))
12325 (goto-char beg)
12326 (goto-char pos)
12327 (error "Not in a dynamic block"))))
12329 (defun org-update-all-dblocks ()
12330 "Update all dynamic blocks in the buffer.
12331 This function can be used in a hook."
12332 (interactive)
12333 (when (derived-mode-p 'org-mode)
12334 (org-map-dblocks 'org-update-dblock)))
12337 ;;;; Completion
12339 (declare-function org-export-backend-options "ox" (cl-x) t)
12340 (defun org-get-export-keywords ()
12341 "Return a list of all currently understood export keywords.
12342 Export keywords include options, block names, attributes and
12343 keywords relative to each registered export back-end."
12344 (let (keywords)
12345 (dolist (backend
12346 (bound-and-true-p org-export-registered-backends)
12347 (delq nil keywords))
12348 ;; Back-end name (for keywords, like #+LATEX:)
12349 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12350 (dolist (option-entry (org-export-backend-options backend))
12351 ;; Back-end options.
12352 (push (nth 1 option-entry) keywords)))))
12354 (defconst org-options-keywords
12355 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12356 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12357 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12358 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12359 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12361 (defcustom org-structure-template-alist
12362 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12363 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12364 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12365 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12366 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12367 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12368 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12369 ("L" "#+LaTeX: ")
12370 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12371 ("H" "#+HTML: ")
12372 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12373 ("A" "#+ASCII: ")
12374 ("i" "#+INDEX: ?")
12375 ("I" "#+INCLUDE: %file ?"))
12376 "Structure completion elements.
12377 This is a list of abbreviation keys and values. The value gets inserted
12378 if you type `<' followed by the key and then press the completion key,
12379 usually `TAB'. %file will be replaced by a file name after prompting
12380 for the file using completion. The cursor will be placed at the position
12381 of the `?' in the template.
12382 There are two templates for each key, the first uses the original Org syntax,
12383 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12384 the default when the /org-mtags.el/ module has been loaded. See also the
12385 variable `org-mtags-prefer-muse-templates'."
12386 :group 'org-completion
12387 :type '(repeat
12388 (list
12389 (string :tag "Key")
12390 (string :tag "Template")))
12391 :version "25.1"
12392 :package-version '(Org . "8.3"))
12394 (defun org-try-structure-completion ()
12395 "Try to complete a structure template before point.
12396 This looks for strings like \"<e\" on an otherwise empty line and
12397 expands them."
12398 (let ((l (buffer-substring (point-at-bol) (point)))
12400 (when (and (looking-at "[ \t]*$")
12401 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12402 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12403 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12404 (match-beginning 1)) a)
12405 t)))
12407 (defun org-complete-expand-structure-template (start cell)
12408 "Expand a structure template."
12409 (let ((rpl (nth 1 cell))
12410 (ind ""))
12411 (delete-region start (point))
12412 (when (string-match "\\`[ \t]*#\\+" rpl)
12413 (cond
12414 ((bolp))
12415 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12416 (setq ind (buffer-substring (point-at-bol) (point))))
12417 (t (newline))))
12418 (setq start (point))
12419 (when (string-match "%file" rpl)
12420 (setq rpl (replace-match
12421 (concat
12422 "\""
12423 (save-match-data
12424 (abbreviate-file-name (read-file-name "Include file: ")))
12425 "\"")
12426 t t rpl)))
12427 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12428 (concat "\n" ind)))
12429 (insert rpl)
12430 (when (re-search-backward "\\?" start t) (delete-char 1))))
12432 ;;;; TODO, DEADLINE, Comments
12434 (defun org-toggle-comment ()
12435 "Change the COMMENT state of an entry."
12436 (interactive)
12437 (save-excursion
12438 (org-back-to-heading)
12439 (looking-at org-complex-heading-regexp)
12440 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12441 (skip-chars-forward " \t")
12442 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12443 (if (org-in-commented-heading-p t)
12444 (delete-region (point)
12445 (progn (search-forward " " (line-end-position) 'move)
12446 (skip-chars-forward " \t")
12447 (point)))
12448 (insert org-comment-string)
12449 (unless (eolp) (insert " ")))))
12451 (defvar org-last-todo-state-is-todo nil
12452 "This is non-nil when the last TODO state change led to a TODO state.
12453 If the last change removed the TODO tag or switched to DONE, then
12454 this is nil.")
12456 (defvar org-setting-tags nil) ; dynamically skipped
12458 (defvar org-todo-setup-filter-hook nil
12459 "Hook for functions that pre-filter todo specs.
12460 Each function takes a todo spec and returns either nil or the spec
12461 transformed into canonical form." )
12463 (defvar org-todo-get-default-hook nil
12464 "Hook for functions that get a default item for todo.
12465 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12466 nil or a string to be used for the todo mark." )
12468 (defvar org-agenda-headline-snapshot-before-repeat)
12470 (defun org-current-effective-time ()
12471 "Return current time adjusted for `org-extend-today-until' variable."
12472 (let* ((ct (org-current-time))
12473 (dct (decode-time ct))
12474 (ct1
12475 (cond
12476 (org-use-last-clock-out-time-as-effective-time
12477 (or (org-clock-get-last-clock-out-time) ct))
12478 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12479 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12480 (t ct))))
12481 ct1))
12483 (defun org-todo-yesterday (&optional arg)
12484 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12485 (interactive "P")
12486 (if (eq major-mode 'org-agenda-mode)
12487 (apply 'org-agenda-todo-yesterday arg)
12488 (let* ((org-use-effective-time t)
12489 (hour (nth 2 (decode-time (org-current-time))))
12490 (org-extend-today-until (1+ hour)))
12491 (org-todo arg))))
12493 (defvar org-block-entry-blocking ""
12494 "First entry preventing the TODO state change.")
12496 (defun org-cancel-repeater ()
12497 "Cancel a repeater by setting its numeric value to zero."
12498 (interactive)
12499 (save-excursion
12500 (org-back-to-heading t)
12501 (let ((bound1 (point))
12502 (bound0 (save-excursion (outline-next-heading) (point))))
12503 (when (and (re-search-forward
12504 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12505 org-deadline-time-regexp "\\)\\|\\("
12506 org-ts-regexp "\\)")
12507 bound0 t)
12508 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12509 bound1 t))
12510 (replace-match "0" t nil nil 1)))))
12512 (defvar org-state) ;; dynamically scoped into this function
12513 (defun org-todo (&optional arg)
12514 "Change the TODO state of an item.
12515 The state of an item is given by a keyword at the start of the heading,
12516 like
12517 *** TODO Write paper
12518 *** DONE Call mom
12520 The different keywords are specified in the variable `org-todo-keywords'.
12521 By default the available states are \"TODO\" and \"DONE\".
12522 So for this example: when the item starts with TODO, it is changed to DONE.
12523 When it starts with DONE, the DONE is removed. And when neither TODO nor
12524 DONE are present, add TODO at the beginning of the heading.
12526 With \\[universal-argument] prefix arg, use completion to determine the new \
12527 state.
12528 With numeric prefix arg, switch to that state.
12529 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12530 keywords (nextset).
12531 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12532 With a numeric prefix arg of 0, inhibit note taking for the change.
12533 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12535 When called through ELisp, arg is also interpreted in the following way:
12536 `none' -> empty state
12537 \"\"(empty string) -> switch to empty state
12538 `done' -> switch to DONE
12539 `nextset' -> switch to the next set of keywords
12540 `previousset' -> switch to the previous set of keywords
12541 \"WAITING\" -> switch to the specified keyword, but only if it
12542 really is a member of `org-todo-keywords'."
12543 (interactive "P")
12544 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12545 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12546 'region-start-level 'region))
12547 org-loop-over-headlines-in-active-region)
12548 (org-map-entries
12549 `(org-todo ,arg)
12550 org-loop-over-headlines-in-active-region
12551 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12552 (when (equal arg '(16)) (setq arg 'nextset))
12553 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12554 (let ((org-blocker-hook org-blocker-hook)
12555 commentp
12556 case-fold-search)
12557 (when (equal arg '(64))
12558 (setq arg nil org-blocker-hook nil))
12559 (when (and org-blocker-hook
12560 (or org-inhibit-blocking
12561 (org-entry-get nil "NOBLOCKING")))
12562 (setq org-blocker-hook nil))
12563 (save-excursion
12564 (catch 'exit
12565 (org-back-to-heading t)
12566 (when (org-in-commented-heading-p t)
12567 (org-toggle-comment)
12568 (setq commentp t))
12569 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12570 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12571 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12572 (let* ((match-data (match-data))
12573 (startpos (point-at-bol))
12574 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12575 (org-log-done org-log-done)
12576 (org-log-repeat org-log-repeat)
12577 (org-todo-log-states org-todo-log-states)
12578 (org-inhibit-logging
12579 (if (equal arg 0)
12580 (progn (setq arg nil) 'note) org-inhibit-logging))
12581 (this (match-string 1))
12582 (hl-pos (match-beginning 0))
12583 (head (org-get-todo-sequence-head this))
12584 (ass (assoc head org-todo-kwd-alist))
12585 (interpret (nth 1 ass))
12586 (done-word (nth 3 ass))
12587 (final-done-word (nth 4 ass))
12588 (org-last-state (or this ""))
12589 (completion-ignore-case t)
12590 (member (member this org-todo-keywords-1))
12591 (tail (cdr member))
12592 (org-state (cond
12593 ((and org-todo-key-trigger
12594 (or (and (equal arg '(4))
12595 (eq org-use-fast-todo-selection 'prefix))
12596 (and (not arg) org-use-fast-todo-selection
12597 (not (eq org-use-fast-todo-selection
12598 'prefix)))))
12599 ;; Use fast selection
12600 (org-fast-todo-selection))
12601 ((and (equal arg '(4))
12602 (or (not org-use-fast-todo-selection)
12603 (not org-todo-key-trigger)))
12604 ;; Read a state with completion
12605 (completing-read
12606 "State: " (mapcar #'list org-todo-keywords-1)
12607 nil t))
12608 ((eq arg 'right)
12609 (if this
12610 (if tail (car tail) nil)
12611 (car org-todo-keywords-1)))
12612 ((eq arg 'left)
12613 (unless (equal member org-todo-keywords-1)
12614 (if this
12615 (nth (- (length org-todo-keywords-1)
12616 (length tail) 2)
12617 org-todo-keywords-1)
12618 (org-last org-todo-keywords-1))))
12619 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12620 (setq arg nil))) ; hack to fall back to cycling
12621 (arg
12622 ;; user or caller requests a specific state
12623 (cond
12624 ((equal arg "") nil)
12625 ((eq arg 'none) nil)
12626 ((eq arg 'done) (or done-word (car org-done-keywords)))
12627 ((eq arg 'nextset)
12628 (or (car (cdr (member head org-todo-heads)))
12629 (car org-todo-heads)))
12630 ((eq arg 'previousset)
12631 (let ((org-todo-heads (reverse org-todo-heads)))
12632 (or (car (cdr (member head org-todo-heads)))
12633 (car org-todo-heads))))
12634 ((car (member arg org-todo-keywords-1)))
12635 ((stringp arg)
12636 (user-error "State `%s' not valid in this file" arg))
12637 ((nth (1- (prefix-numeric-value arg))
12638 org-todo-keywords-1))))
12639 ((null member) (or head (car org-todo-keywords-1)))
12640 ((equal this final-done-word) nil) ;; -> make empty
12641 ((null tail) nil) ;; -> first entry
12642 ((memq interpret '(type priority))
12643 (if (eq this-command last-command)
12644 (car tail)
12645 (if (> (length tail) 0)
12646 (or done-word (car org-done-keywords))
12647 nil)))
12649 (car tail))))
12650 (org-state (or
12651 (run-hook-with-args-until-success
12652 'org-todo-get-default-hook org-state org-last-state)
12653 org-state))
12654 (next (if org-state (concat " " org-state " ") " "))
12655 (change-plist (list :type 'todo-state-change :from this :to org-state
12656 :position startpos))
12657 dolog now-done-p)
12658 (when org-blocker-hook
12659 (setq org-last-todo-state-is-todo
12660 (not (member this org-done-keywords)))
12661 (unless (save-excursion
12662 (save-match-data
12663 (org-with-wide-buffer
12664 (run-hook-with-args-until-failure
12665 'org-blocker-hook change-plist))))
12666 (if (called-interactively-p 'interactive)
12667 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12668 this org-state org-block-entry-blocking)
12669 ;; fail silently
12670 (message "TODO state change from %s to %s blocked (by \"%s\")"
12671 this org-state org-block-entry-blocking)
12672 (throw 'exit nil))))
12673 (store-match-data match-data)
12674 (replace-match next t t)
12675 (cond ((equal this org-state)
12676 (message "TODO state was already %s" (org-trim next)))
12677 ((pos-visible-in-window-p hl-pos)
12678 (message "TODO state changed to %s" (org-trim next))))
12679 (unless head
12680 (setq head (org-get-todo-sequence-head org-state)
12681 ass (assoc head org-todo-kwd-alist)
12682 interpret (nth 1 ass)
12683 done-word (nth 3 ass)
12684 final-done-word (nth 4 ass)))
12685 (when (memq arg '(nextset previousset))
12686 (message "Keyword-Set %d/%d: %s"
12687 (- (length org-todo-sets) -1
12688 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12689 (length org-todo-sets)
12690 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12691 (setq org-last-todo-state-is-todo
12692 (not (member org-state org-done-keywords)))
12693 (setq now-done-p (and (member org-state org-done-keywords)
12694 (not (member this org-done-keywords))))
12695 (and logging (org-local-logging logging))
12696 (when (and (or org-todo-log-states org-log-done)
12697 (not (eq org-inhibit-logging t))
12698 (not (memq arg '(nextset previousset))))
12699 ;; we need to look at recording a time and note
12700 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12701 (nth 2 (assoc this org-todo-log-states))))
12702 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12703 (setq dolog 'time))
12704 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12705 (and org-state
12706 (member org-state org-not-done-keywords)
12707 (not (member this org-not-done-keywords))))
12708 ;; This is now a todo state and was not one before
12709 ;; If there was a CLOSED time stamp, get rid of it.
12710 (org-add-planning-info nil nil 'closed))
12711 (when (and now-done-p org-log-done)
12712 ;; It is now done, and it was not done before
12713 (org-add-planning-info 'closed (org-current-effective-time))
12714 (when (and (not dolog) (eq 'note org-log-done))
12715 (org-add-log-setup 'done org-state this 'note)))
12716 (when (and org-state dolog)
12717 ;; This is a non-nil state, and we need to log it
12718 (org-add-log-setup 'state org-state this dolog)))
12719 ;; Fixup tag positioning
12720 (org-todo-trigger-tag-changes org-state)
12721 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12722 (when org-provide-todo-statistics
12723 (org-update-parent-todo-statistics))
12724 (run-hooks 'org-after-todo-state-change-hook)
12725 (when (and arg (not (member org-state org-done-keywords)))
12726 (setq head (org-get-todo-sequence-head org-state)))
12727 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12728 ;; Do we need to trigger a repeat?
12729 (when now-done-p
12730 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12731 ;; This is for the agenda, take a snapshot of the headline.
12732 (save-match-data
12733 (setq org-agenda-headline-snapshot-before-repeat
12734 (org-get-heading))))
12735 (org-auto-repeat-maybe org-state))
12736 ;; Fixup cursor location if close to the keyword
12737 (when (and (outline-on-heading-p)
12738 (not (bolp))
12739 (save-excursion (beginning-of-line 1)
12740 (looking-at org-todo-line-regexp))
12741 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12742 (goto-char (or (match-end 2) (match-end 1)))
12743 (and (looking-at " ") (just-one-space)))
12744 (when org-trigger-hook
12745 (save-excursion
12746 (run-hook-with-args 'org-trigger-hook change-plist)))
12747 (when commentp (org-toggle-comment))))))))
12749 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12750 "Block turning an entry into a TODO, using the hierarchy.
12751 This checks whether the current task should be blocked from state
12752 changes. Such blocking occurs when:
12754 1. The task has children which are not all in a completed state.
12756 2. A task has a parent with the property :ORDERED:, and there
12757 are siblings prior to the current task with incomplete
12758 status.
12760 3. The parent of the task is blocked because it has siblings that should
12761 be done first, or is child of a block grandparent TODO entry."
12763 (if (not org-enforce-todo-dependencies)
12764 t ; if locally turned off don't block
12765 (catch 'dont-block
12766 ;; If this is not a todo state change, or if this entry is already DONE,
12767 ;; do not block
12768 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12769 (member (plist-get change-plist :from)
12770 (cons 'done org-done-keywords))
12771 (member (plist-get change-plist :to)
12772 (cons 'todo org-not-done-keywords))
12773 (not (plist-get change-plist :to)))
12774 (throw 'dont-block t))
12775 ;; If this task has children, and any are undone, it's blocked
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (let ((this-level (funcall outline-level)))
12779 (outline-next-heading)
12780 (let ((child-level (funcall outline-level)))
12781 (while (and (not (eobp))
12782 (> child-level this-level))
12783 ;; this todo has children, check whether they are all
12784 ;; completed
12785 (when (and (not (org-entry-is-done-p))
12786 (org-entry-is-todo-p))
12787 (setq org-block-entry-blocking (org-get-heading))
12788 (throw 'dont-block nil))
12789 (outline-next-heading)
12790 (setq child-level (funcall outline-level))))))
12791 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12792 ;; any previous siblings are undone, it's blocked
12793 (save-excursion
12794 (org-back-to-heading t)
12795 (let* ((pos (point))
12796 (parent-pos (and (org-up-heading-safe) (point))))
12797 (unless parent-pos (throw 'dont-block t)) ; no parent
12798 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12799 (forward-line 1)
12800 (re-search-forward org-not-done-heading-regexp pos t))
12801 (setq org-block-entry-blocking (match-string 0))
12802 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12803 ;; Search further up the hierarchy, to see if an ancestor is blocked
12804 (while t
12805 (goto-char parent-pos)
12806 (unless (looking-at org-not-done-heading-regexp)
12807 (throw 'dont-block t)) ; do not block, parent is not a TODO
12808 (setq pos (point))
12809 (setq parent-pos (and (org-up-heading-safe) (point)))
12810 (unless parent-pos (throw 'dont-block t)) ; no parent
12811 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12812 (forward-line 1)
12813 (re-search-forward org-not-done-heading-regexp pos t)
12814 (setq org-block-entry-blocking (org-get-heading)))
12815 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12817 (defcustom org-track-ordered-property-with-tag nil
12818 "Should the ORDERED property also be shown as a tag?
12819 The ORDERED property decides if an entry should require subtasks to be
12820 completed in sequence. Since a property is not very visible, setting
12821 this option means that toggling the ORDERED property with the command
12822 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12823 not relevant for the behavior, but it makes things more visible.
12825 Note that toggling the tag with tags commands will not change the property
12826 and therefore not influence behavior!
12828 This can be t, meaning the tag ORDERED should be used, It can also be a
12829 string to select a different tag for this task."
12830 :group 'org-todo
12831 :type '(choice
12832 (const :tag "No tracking" nil)
12833 (const :tag "Track with ORDERED tag" t)
12834 (string :tag "Use other tag")))
12836 (defun org-toggle-ordered-property ()
12837 "Toggle the ORDERED property of the current entry.
12838 For better visibility, you can track the value of this property with a tag.
12839 See variable `org-track-ordered-property-with-tag'."
12840 (interactive)
12841 (let* ((t1 org-track-ordered-property-with-tag)
12842 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12843 (save-excursion
12844 (org-back-to-heading)
12845 (if (org-entry-get nil "ORDERED")
12846 (progn
12847 (org-delete-property "ORDERED")
12848 (and tag (org-toggle-tag tag 'off))
12849 (message "Subtasks can be completed in arbitrary order"))
12850 (org-entry-put nil "ORDERED" "t")
12851 (and tag (org-toggle-tag tag 'on))
12852 (message "Subtasks must be completed in sequence")))))
12854 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12855 (defun org-block-todo-from-checkboxes (change-plist)
12856 "Block turning an entry into a TODO, using checkboxes.
12857 This checks whether the current task should be blocked from state
12858 changes because there are unchecked boxes in this entry."
12859 (if (not org-enforce-todo-checkbox-dependencies)
12860 t ; if locally turned off don't block
12861 (catch 'dont-block
12862 ;; If this is not a todo state change, or if this entry is already DONE,
12863 ;; do not block
12864 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12865 (member (plist-get change-plist :from)
12866 (cons 'done org-done-keywords))
12867 (member (plist-get change-plist :to)
12868 (cons 'todo org-not-done-keywords))
12869 (not (plist-get change-plist :to)))
12870 (throw 'dont-block t))
12871 ;; If this task has checkboxes that are not checked, it's blocked
12872 (save-excursion
12873 (org-back-to-heading t)
12874 (let ((beg (point)) end)
12875 (outline-next-heading)
12876 (setq end (point))
12877 (goto-char beg)
12878 (when (org-list-search-forward
12879 (concat (org-item-beginning-re)
12880 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12881 "\\[[- ]\\]")
12882 end t)
12883 (when (boundp 'org-blocked-by-checkboxes)
12884 (setq org-blocked-by-checkboxes t))
12885 (throw 'dont-block nil))))
12886 t))) ; do not block
12888 (defun org-entry-blocked-p ()
12889 "Non-nil if entry at point is blocked."
12890 (and (not (org-entry-get nil "NOBLOCKING"))
12891 (member (org-entry-get nil "TODO") org-not-done-keywords)
12892 (not (run-hook-with-args-until-failure
12893 'org-blocker-hook
12894 (list :type 'todo-state-change
12895 :position (point)
12896 :from 'todo
12897 :to 'done)))))
12899 (defun org-update-statistics-cookies (all)
12900 "Update the statistics cookie, either from TODO or from checkboxes.
12901 This should be called with the cursor in a line with a statistics
12902 cookie. When called with a \\[universal-argument] prefix, update
12903 all statistics cookies in the buffer."
12904 (interactive "P")
12905 (if all
12906 (progn
12907 (org-update-checkbox-count 'all)
12908 (org-map-entries 'org-update-parent-todo-statistics))
12909 (if (not (org-at-heading-p))
12910 (org-update-checkbox-count)
12911 (let ((pos (point-marker))
12912 end l1 l2)
12913 (ignore-errors (org-back-to-heading t))
12914 (if (not (org-at-heading-p))
12915 (org-update-checkbox-count)
12916 (setq l1 (org-outline-level))
12917 (setq end (save-excursion
12918 (outline-next-heading)
12919 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12920 (point)))
12921 (if (and (save-excursion
12922 (re-search-forward
12923 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12924 (not (save-excursion (re-search-forward
12925 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12926 (org-update-checkbox-count)
12927 (if (and l2 (> l2 l1))
12928 (progn
12929 (goto-char end)
12930 (org-update-parent-todo-statistics))
12931 (goto-char pos)
12932 (beginning-of-line 1)
12933 (while (re-search-forward
12934 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12935 (point-at-eol) t)
12936 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12937 (goto-char pos)
12938 (move-marker pos nil)))))
12940 (defvar org-entry-property-inherited-from) ;; defined below
12941 (defun org-update-parent-todo-statistics ()
12942 "Update any statistics cookie in the parent of the current headline.
12943 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12944 the entire subtree and this will travel up the hierarchy and update
12945 statistics everywhere."
12946 (let* ((prop (save-excursion (org-up-heading-safe)
12947 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12948 (recursive (or (not org-hierarchical-todo-statistics)
12949 (and prop (string-match "\\<recursive\\>" prop))))
12950 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12952 (first t)
12953 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12954 level ltoggle l1 new ndel
12955 (cnt-all 0) (cnt-done 0) is-percent kwd
12956 checkbox-beg cookie-present)
12957 (catch 'exit
12958 (save-excursion
12959 (beginning-of-line 1)
12960 (setq ltoggle (funcall outline-level))
12961 ;; Three situations are to consider:
12963 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12964 ;; to the top-level ancestor on the headline;
12966 ;; 2. If parent has "recursive" property, repeat up to the
12967 ;; headline setting that property, taking inheritance into
12968 ;; account;
12970 ;; 3. Else, move up to direct parent and proceed only once.
12971 (while (and (setq level (org-up-heading-safe))
12972 (or recursive first)
12973 (>= (point) lim))
12974 (setq first nil cookie-present nil)
12975 (unless (and level
12976 (not (string-match
12977 "\\<checkbox\\>"
12978 (downcase (or (org-entry-get nil "COOKIE_DATA")
12979 "")))))
12980 (throw 'exit nil))
12981 (while (re-search-forward box-re (point-at-eol) t)
12982 (setq cnt-all 0 cnt-done 0 cookie-present t)
12983 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12984 (save-match-data
12985 (unless (outline-next-heading) (throw 'exit nil))
12986 (while (and (looking-at org-complex-heading-regexp)
12987 (> (setq l1 (length (match-string 1))) level))
12988 (setq kwd (and (or recursive (= l1 ltoggle))
12989 (match-string 2)))
12990 (if (or (eq org-provide-todo-statistics 'all-headlines)
12991 (and (eq org-provide-todo-statistics t)
12992 (or (member kwd org-done-keywords)))
12993 (and (listp org-provide-todo-statistics)
12994 (stringp (car org-provide-todo-statistics))
12995 (or (member kwd org-provide-todo-statistics)
12996 (member kwd org-done-keywords)))
12997 (and (listp org-provide-todo-statistics)
12998 (listp (car org-provide-todo-statistics))
12999 (or (member kwd (car org-provide-todo-statistics))
13000 (and (member kwd org-done-keywords)
13001 (member kwd (cadr org-provide-todo-statistics))))))
13002 (setq cnt-all (1+ cnt-all))
13003 (and (eq org-provide-todo-statistics t)
13005 (setq cnt-all (1+ cnt-all))))
13006 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13007 (member kwd org-done-keywords))
13008 (and (listp org-provide-todo-statistics)
13009 (listp (car org-provide-todo-statistics))
13010 (member kwd org-done-keywords)
13011 (member kwd (cadr org-provide-todo-statistics)))
13012 (and (listp org-provide-todo-statistics)
13013 (stringp (car org-provide-todo-statistics))
13014 (member kwd org-done-keywords)))
13015 (setq cnt-done (1+ cnt-done)))
13016 (outline-next-heading)))
13017 (setq new
13018 (if is-percent
13019 (format "[%d%%]" (floor (* 100.0 cnt-done)
13020 (max 1 cnt-all)))
13021 (format "[%d/%d]" cnt-done cnt-all))
13022 ndel (- (match-end 0) checkbox-beg))
13023 (goto-char checkbox-beg)
13024 (insert new)
13025 (delete-region (point) (+ (point) ndel))
13026 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13027 (when cookie-present
13028 (run-hook-with-args 'org-after-todo-statistics-hook
13029 cnt-done (- cnt-all cnt-done))))))
13030 (run-hooks 'org-todo-statistics-hook)))
13032 (defvar org-after-todo-statistics-hook nil
13033 "Hook that is called after a TODO statistics cookie has been updated.
13034 Each function is called with two arguments: the number of not-done entries
13035 and the number of done entries.
13037 For example, the following function, when added to this hook, will switch
13038 an entry to DONE when all children are done, and back to TODO when new
13039 entries are set to a TODO status. Note that this hook is only called
13040 when there is a statistics cookie in the headline!
13042 \(defun org-summary-todo (n-done n-not-done)
13043 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13044 \(let (org-log-done org-log-states) ; turn off logging
13045 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13048 (defvar org-todo-statistics-hook nil
13049 "Hook that is run whenever Org thinks TODO statistics should be updated.
13050 This hook runs even if there is no statistics cookie present, in which case
13051 `org-after-todo-statistics-hook' would not run.")
13053 (defun org-todo-trigger-tag-changes (state)
13054 "Apply the changes defined in `org-todo-state-tags-triggers'."
13055 (let ((l org-todo-state-tags-triggers)
13056 changes)
13057 (when (or (not state) (equal state ""))
13058 (setq changes (append changes (cdr (assoc "" l)))))
13059 (when (and (stringp state) (> (length state) 0))
13060 (setq changes (append changes (cdr (assoc state l)))))
13061 (when (member state org-not-done-keywords)
13062 (setq changes (append changes (cdr (assq 'todo l)))))
13063 (when (member state org-done-keywords)
13064 (setq changes (append changes (cdr (assq 'done l)))))
13065 (dolist (c changes)
13066 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13068 (defun org-local-logging (value)
13069 "Get logging settings from a property VALUE."
13070 ;; Directly set the variables, they are already local.
13071 (setq org-log-done nil
13072 org-log-repeat nil
13073 org-todo-log-states nil)
13074 (dolist (w (org-split-string value))
13075 (let (a)
13076 (cond
13077 ((setq a (assoc w org-startup-options))
13078 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13079 (set (nth 1 a) (nth 2 a))))
13080 ((setq a (org-extract-log-state-settings w))
13081 (and (member (car a) org-todo-keywords-1)
13082 (push a org-todo-log-states)))))))
13084 (defun org-get-todo-sequence-head (kwd)
13085 "Return the head of the TODO sequence to which KWD belongs.
13086 If KWD is not set, check if there is a text property remembering the
13087 right sequence."
13088 (let (p)
13089 (cond
13090 ((not kwd)
13091 (or (get-text-property (point-at-bol) 'org-todo-head)
13092 (progn
13093 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13094 nil (point-at-eol)))
13095 (get-text-property p 'org-todo-head))))
13096 ((not (member kwd org-todo-keywords-1))
13097 (car org-todo-keywords-1))
13098 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13100 (defun org-fast-todo-selection ()
13101 "Fast TODO keyword selection with single keys.
13102 Returns the new TODO keyword, or nil if no state change should occur."
13103 (let* ((fulltable org-todo-key-alist)
13104 (done-keywords org-done-keywords) ;; needed for the faces.
13105 (maxlen (apply 'max (mapcar
13106 (lambda (x)
13107 (if (stringp (car x)) (string-width (car x)) 0))
13108 fulltable)))
13109 (expert nil)
13110 (fwidth (+ maxlen 3 1 3))
13111 (ncol (/ (- (window-width) 4) fwidth))
13112 tg cnt e c tbl
13113 groups ingroup)
13114 (save-excursion
13115 (save-window-excursion
13116 (if expert
13117 (set-buffer (get-buffer-create " *Org todo*"))
13118 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13119 (erase-buffer)
13120 (setq-local org-done-keywords done-keywords)
13121 (setq tbl fulltable cnt 0)
13122 (while (setq e (pop tbl))
13123 (cond
13124 ((equal e '(:startgroup))
13125 (push '() groups) (setq ingroup t)
13126 (unless (= cnt 0)
13127 (setq cnt 0)
13128 (insert "\n"))
13129 (insert "{ "))
13130 ((equal e '(:endgroup))
13131 (setq ingroup nil cnt 0)
13132 (insert "}\n"))
13133 ((equal e '(:newline))
13134 (unless (= cnt 0)
13135 (setq cnt 0)
13136 (insert "\n")
13137 (setq e (car tbl))
13138 (while (equal (car tbl) '(:newline))
13139 (insert "\n")
13140 (setq tbl (cdr tbl)))))
13142 (setq tg (car e) c (cdr e))
13143 (when ingroup (push tg (car groups)))
13144 (setq tg (org-add-props tg nil 'face
13145 (org-get-todo-face tg)))
13146 (when (and (= cnt 0) (not ingroup)) (insert " "))
13147 (insert "[" c "] " tg (make-string
13148 (- fwidth 4 (length tg)) ?\ ))
13149 (when (= (setq cnt (1+ cnt)) ncol)
13150 (insert "\n")
13151 (when ingroup (insert " "))
13152 (setq cnt 0)))))
13153 (insert "\n")
13154 (goto-char (point-min))
13155 (unless expert (org-fit-window-to-buffer))
13156 (message "[a-z..]:Set [SPC]:clear")
13157 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13158 (cond
13159 ((or (= c ?\C-g)
13160 (and (= c ?q) (not (rassoc c fulltable))))
13161 (setq quit-flag t))
13162 ((= c ?\ ) nil)
13163 ((setq e (rassoc c fulltable) tg (car e))
13165 (t (setq quit-flag t)))))))
13167 (defun org-entry-is-todo-p ()
13168 (member (org-get-todo-state) org-not-done-keywords))
13170 (defun org-entry-is-done-p ()
13171 (member (org-get-todo-state) org-done-keywords))
13173 (defun org-get-todo-state ()
13174 "Return the TODO keyword of the current subtree."
13175 (save-excursion
13176 (org-back-to-heading t)
13177 (and (looking-at org-todo-line-regexp)
13178 (match-end 2)
13179 (match-string 2))))
13181 (defun org-at-date-range-p (&optional inactive-ok)
13182 "Non-nil if point is inside a date range.
13184 When optional argument INACTIVE-OK is non-nil, also consider
13185 inactive time ranges.
13187 When this function returns a non-nil value, match data is set
13188 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13189 on INACTIVE-OK."
13190 (interactive)
13191 (save-excursion
13192 (catch 'exit
13193 (let ((pos (point)))
13194 (skip-chars-backward "^[<\r\n")
13195 (skip-chars-backward "<[")
13196 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13197 (>= (match-end 0) pos)
13198 (throw 'exit t))
13199 (skip-chars-backward "^<[\r\n")
13200 (skip-chars-backward "<[")
13201 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13202 (>= (match-end 0) pos)
13203 (throw 'exit t)))
13204 nil)))
13206 (defun org-get-repeat (&optional tagline)
13207 "Check if there is a deadline/schedule with repeater in this entry."
13208 (save-match-data
13209 (save-excursion
13210 (org-back-to-heading t)
13211 (and (re-search-forward (if tagline
13212 (concat tagline "\\s-*" org-repeat-re)
13213 org-repeat-re)
13214 (org-entry-end-position) t)
13215 (match-string-no-properties 1)))))
13217 (defvar org-last-changed-timestamp)
13218 (defvar org-last-inserted-timestamp)
13219 (defvar org-log-post-message)
13220 (defvar org-log-note-purpose)
13221 (defvar org-log-note-how nil)
13222 (defvar org-log-note-extra)
13223 (defun org-auto-repeat-maybe (done-word)
13224 "Check if the current headline contains a repeated time-stamp.
13226 If yes, set TODO state back to what it was and change the base date
13227 of repeating deadline/scheduled time stamps to new date.
13229 This function is run automatically after each state change to a DONE state."
13230 (let* ((repeat (org-get-repeat))
13231 (aa (assoc org-last-state org-todo-kwd-alist))
13232 (interpret (nth 1 aa))
13233 (head (nth 2 aa))
13234 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13235 (msg "Entry repeats: ")
13236 (org-log-done nil)
13237 (org-todo-log-states nil))
13238 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13239 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13240 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13241 org-todo-repeat-to-state)))
13242 (unless (and to-state (member to-state org-todo-keywords-1))
13243 (setq to-state (if (eq interpret 'type) org-last-state head)))
13244 (org-todo to-state))
13245 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13246 (org-entry-put nil "LAST_REPEAT" (format-time-string
13247 (org-time-stamp-format t t))))
13248 (when org-log-repeat
13249 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13250 (memq 'org-add-log-note post-command-hook))
13251 ;; We are already setup for some record.
13252 (when (eq org-log-repeat 'note)
13253 ;; Make sure we take a note, not only a time stamp.
13254 (setq org-log-note-how 'note))
13255 ;; Set up for taking a record.
13256 (org-add-log-setup 'state
13257 (or done-word (car org-done-keywords))
13258 org-last-state
13259 org-log-repeat)))
13260 (org-back-to-heading t)
13261 (org-add-planning-info nil nil 'closed)
13262 (let ((end (save-excursion (outline-next-heading) (point))))
13263 (while (re-search-forward org-ts-regexp end t)
13264 (when (save-match-data
13265 (or (org-at-planning-p)
13266 (org-at-property-p)
13267 (eq (org-element-type (save-excursion
13268 (backward-char)
13269 (org-element-context)))
13270 'timestamp)))
13271 (let ((type (cond ((match-end 1) org-scheduled-string)
13272 ((match-end 3) org-deadline-string)
13273 (t "Plain:")))
13274 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13275 (cond
13276 ((not
13277 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13278 ;; Time-stamps without a repeater are usually skipped.
13279 ;; However, a SCHEDULED time-stamp without one is
13280 ;; removed, as it is considered as no longer relevant.
13281 (when (equal type org-scheduled-string)
13282 (org-remove-timestamp-with-keyword type)))
13284 (let ((n (string-to-number (match-string 2 ts)))
13285 (what (match-string 3 ts)))
13286 (when (equal what "w") (setq n (* n 7) what "d"))
13287 (when (and (equal what "h")
13288 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13289 ts)))
13290 (user-error
13291 "Cannot repeat in Repeat in %d hour(s) because no hour \
13292 has been set"
13294 ;; Preparation, see if we need to modify the start
13295 ;; date for the change.
13296 (when (match-end 1)
13297 (let ((time (save-match-data (org-time-string-to-time ts))))
13298 (cond
13299 ((equal (match-string 1 ts) ".")
13300 ;; Shift starting date to today
13301 (org-timestamp-change
13302 (- (org-today) (time-to-days time))
13303 'day))
13304 ((equal (match-string 1 ts) "+")
13305 (let ((nshiftmax 10)
13306 (nshift 0))
13307 (while (or (= nshift 0)
13308 (not (time-less-p (current-time) time)))
13309 (when (= (cl-incf nshift) nshiftmax)
13310 (or (y-or-n-p
13311 (format "%d repeater intervals were not \
13312 enough to shift date past today. Continue? "
13313 nshift))
13314 (user-error "Abort")))
13315 (org-timestamp-change n (cdr (assoc what whata)))
13316 (org-at-timestamp-p t)
13317 (setq ts (match-string 1))
13318 (setq time
13319 (save-match-data
13320 (org-time-string-to-time ts)))))
13321 (org-timestamp-change (- n) (cdr (assoc what whata)))
13322 ;; Rematch, so that we have everything in
13323 ;; place for the real shift.
13324 (org-at-timestamp-p t)
13325 (setq ts (match-string 1))
13326 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13327 ts)))))
13328 (save-excursion
13329 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13330 (setq msg
13331 (concat
13332 msg type " " org-last-changed-timestamp " ")))))))))
13333 (setq org-log-post-message msg)
13334 (message "%s" msg))))
13336 (defun org-show-todo-tree (arg)
13337 "Make a compact tree which shows all headlines marked with TODO.
13338 The tree will show the lines where the regexp matches, and all higher
13339 headlines above the match.
13340 With a \\[universal-argument] prefix, prompt for a regexp to match.
13341 With a numeric prefix N, construct a sparse tree for the Nth element
13342 of `org-todo-keywords-1'."
13343 (interactive "P")
13344 (let ((case-fold-search nil)
13345 (kwd-re
13346 (cond ((null arg) org-not-done-regexp)
13347 ((equal arg '(4))
13348 (let ((kwd
13349 (completing-read "Keyword (or KWD1|KWD2|...): "
13350 (mapcar #'list org-todo-keywords-1))))
13351 (concat "\\("
13352 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13353 "\\)\\>")))
13354 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13355 (regexp-quote (nth (1- (prefix-numeric-value arg))
13356 org-todo-keywords-1)))
13357 (t (user-error "Invalid prefix argument: %s" arg)))))
13358 (message "%d TODO entries found"
13359 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13361 (defun org-deadline (arg &optional time)
13362 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13363 With one universal prefix argument, remove any deadline from the item.
13364 With two universal prefix arguments, prompt for a warning delay.
13365 With argument TIME, set the deadline at the corresponding date. TIME
13366 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13367 (interactive "P")
13368 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13369 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13370 'region-start-level 'region))
13371 org-loop-over-headlines-in-active-region)
13372 (org-map-entries
13373 `(org-deadline ',arg ,time)
13374 org-loop-over-headlines-in-active-region
13375 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13376 (let* ((old-date (org-entry-get nil "DEADLINE"))
13377 (old-date-time (when old-date (org-time-string-to-time old-date)))
13378 (repeater (and old-date
13379 (string-match
13380 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13381 old-date)
13382 (match-string 1 old-date))))
13383 (cond
13384 ((equal arg '(4))
13385 (when (and old-date org-log-redeadline)
13386 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13387 (org-remove-timestamp-with-keyword org-deadline-string)
13388 (message "Item no longer has a deadline."))
13389 ((equal arg '(16))
13390 (save-excursion
13391 (org-back-to-heading t)
13392 (if (re-search-forward
13393 org-deadline-time-regexp
13394 (save-excursion (outline-next-heading) (point)) t)
13395 (let* ((rpl0 (match-string 1))
13396 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13397 (replace-match
13398 (concat org-deadline-string
13399 " <" rpl
13400 (format " -%dd"
13401 (abs
13402 (- (time-to-days
13403 (save-match-data
13404 (org-read-date nil t nil "Warn starting from" old-date-time)))
13405 (time-to-days old-date-time))))
13406 ">") t t))
13407 (user-error "No deadline information to update"))))
13409 (org-add-planning-info 'deadline time 'closed)
13410 (when (and old-date
13411 org-log-redeadline
13412 (not (equal old-date org-last-inserted-timestamp)))
13413 (org-add-log-setup
13414 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13415 (when repeater
13416 (save-excursion
13417 (org-back-to-heading t)
13418 (when (re-search-forward (concat org-deadline-string " "
13419 org-last-inserted-timestamp)
13420 (save-excursion
13421 (outline-next-heading) (point)) t)
13422 (goto-char (1- (match-end 0)))
13423 (insert " " repeater)
13424 (setq org-last-inserted-timestamp
13425 (concat (substring org-last-inserted-timestamp 0 -1)
13426 " " repeater
13427 (substring org-last-inserted-timestamp -1))))))
13428 (message "Deadline on %s" org-last-inserted-timestamp))))))
13430 (defun org-schedule (arg &optional time)
13431 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13432 With one universal prefix argument, remove any scheduling date from the item.
13433 With two universal prefix arguments, prompt for a delay cookie.
13434 With argument TIME, scheduled at the corresponding date. TIME can
13435 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13436 (interactive "P")
13437 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13438 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13439 'region-start-level 'region))
13440 org-loop-over-headlines-in-active-region)
13441 (org-map-entries
13442 `(org-schedule ',arg ,time)
13443 org-loop-over-headlines-in-active-region
13444 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13445 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13446 (old-date-time (when old-date (org-time-string-to-time old-date)))
13447 (repeater (and old-date
13448 (string-match
13449 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13450 old-date)
13451 (match-string 1 old-date))))
13452 (cond
13453 ((equal arg '(4))
13454 (progn
13455 (when (and old-date org-log-reschedule)
13456 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13457 (org-remove-timestamp-with-keyword org-scheduled-string)
13458 (message "Item is no longer scheduled.")))
13459 ((equal arg '(16))
13460 (save-excursion
13461 (org-back-to-heading t)
13462 (if (re-search-forward
13463 org-scheduled-time-regexp
13464 (save-excursion (outline-next-heading) (point)) t)
13465 (let* ((rpl0 (match-string 1))
13466 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13467 (replace-match
13468 (concat org-scheduled-string
13469 " <" rpl
13470 (format " -%dd"
13471 (abs
13472 (- (time-to-days
13473 (save-match-data
13474 (org-read-date nil t nil "Delay until" old-date-time)))
13475 (time-to-days old-date-time))))
13476 ">") t t))
13477 (user-error "No scheduled information to update"))))
13479 (org-add-planning-info 'scheduled time 'closed)
13480 (when (and old-date
13481 org-log-reschedule
13482 (not (equal old-date org-last-inserted-timestamp)))
13483 (org-add-log-setup
13484 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13485 (when repeater
13486 (save-excursion
13487 (org-back-to-heading t)
13488 (when (re-search-forward (concat org-scheduled-string " "
13489 org-last-inserted-timestamp)
13490 (save-excursion
13491 (outline-next-heading) (point)) t)
13492 (goto-char (1- (match-end 0)))
13493 (insert " " repeater)
13494 (setq org-last-inserted-timestamp
13495 (concat (substring org-last-inserted-timestamp 0 -1)
13496 " " repeater
13497 (substring org-last-inserted-timestamp -1))))))
13498 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13500 (defun org-get-scheduled-time (pom &optional inherit)
13501 "Get the scheduled time as a time tuple, of a format suitable
13502 for calling org-schedule with, or if there is no scheduling,
13503 returns nil."
13504 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13505 (when time
13506 (apply 'encode-time (org-parse-time-string time)))))
13508 (defun org-get-deadline-time (pom &optional inherit)
13509 "Get the deadline as a time tuple, of a format suitable for
13510 calling org-deadline with, or if there is no scheduling, returns
13511 nil."
13512 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13513 (when time
13514 (apply 'encode-time (org-parse-time-string time)))))
13516 (defun org-remove-timestamp-with-keyword (keyword)
13517 "Remove all time stamps with KEYWORD in the current entry."
13518 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13519 beg)
13520 (save-excursion
13521 (org-back-to-heading t)
13522 (setq beg (point))
13523 (outline-next-heading)
13524 (while (re-search-backward re beg t)
13525 (replace-match "")
13526 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13527 (equal (char-before) ?\ ))
13528 (backward-delete-char 1)
13529 (when (string-match "^[ \t]*$" (buffer-substring
13530 (point-at-bol) (point-at-eol)))
13531 (delete-region (point-at-bol)
13532 (min (point-max) (1+ (point-at-eol))))))))))
13534 (defvar org-time-was-given) ; dynamically scoped parameter
13535 (defvar org-end-time-was-given) ; dynamically scoped parameter
13537 (defun org-at-planning-p ()
13538 "Non-nil when point is on a planning info line."
13539 ;; This is as accurate and faster than `org-element-at-point' since
13540 ;; planning info location is fixed in the section.
13541 (org-with-wide-buffer
13542 (beginning-of-line)
13543 (and (looking-at-p org-planning-line-re)
13544 (eq (point)
13545 (ignore-errors
13546 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13547 (org-back-to-heading t)
13548 (org-with-limited-levels (org-back-to-heading t)))
13549 (line-beginning-position 2))))))
13551 (defun org-add-planning-info (what &optional time &rest remove)
13552 "Insert new timestamp with keyword in the planning line.
13553 WHAT indicates what kind of time stamp to add. It is a symbol
13554 among `closed', `deadline', `scheduled' and nil. TIME indicates
13555 the time to use. If none is given, the user is prompted for
13556 a date. REMOVE indicates what kind of entries to remove. An old
13557 WHAT entry will also be removed."
13558 (let (org-time-was-given org-end-time-was-given default-time default-input)
13559 (catch 'exit
13560 (when (and (memq what '(scheduled deadline))
13561 (or (not time)
13562 (and (stringp time)
13563 (string-match "^[-+]+[0-9]" time))))
13564 ;; Try to get a default date/time from existing timestamp
13565 (save-excursion
13566 (org-back-to-heading t)
13567 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13568 (when (re-search-forward (if (eq what 'scheduled)
13569 org-scheduled-time-regexp
13570 org-deadline-time-regexp)
13571 end t)
13572 (setq ts (match-string 1)
13573 default-time (apply 'encode-time (org-parse-time-string ts))
13574 default-input (and ts (org-get-compact-tod ts)))))))
13575 (when what
13576 (setq time
13577 (if (stringp time)
13578 ;; This is a string (relative or absolute), set
13579 ;; proper date.
13580 (apply #'encode-time
13581 (org-read-date-analyze
13582 time default-time (decode-time default-time)))
13583 ;; If necessary, get the time from the user
13584 (or time (org-read-date nil 'to-time nil nil
13585 default-time default-input)))))
13587 (org-with-wide-buffer
13588 (org-back-to-heading t)
13589 (forward-line)
13590 (unless (bolp) (insert "\n"))
13591 (cond ((looking-at-p org-planning-line-re)
13592 ;; Move to current indentation.
13593 (skip-chars-forward " \t")
13594 ;; Check if we have to remove something.
13595 (dolist (type (if what (cons what remove) remove))
13596 (save-excursion
13597 (when (re-search-forward
13598 (cl-case type
13599 (closed org-closed-time-regexp)
13600 (deadline org-deadline-time-regexp)
13601 (scheduled org-scheduled-time-regexp)
13602 (otherwise
13603 (error "Invalid planning type: %s" type)))
13604 (line-end-position) t)
13605 ;; Delete until next keyword or end of line.
13606 (delete-region
13607 (match-beginning 0)
13608 (if (re-search-forward org-keyword-time-not-clock-regexp
13609 (line-end-position)
13611 (match-beginning 0)
13612 (line-end-position))))))
13613 ;; If there is nothing more to add and no more keyword
13614 ;; is left, remove the line completely.
13615 (if (and (looking-at-p "[ \t]*$") (not what))
13616 (delete-region (line-beginning-position)
13617 (line-beginning-position 2))
13618 ;; If we removed last keyword, do not leave trailing
13619 ;; white space at the end of line.
13620 (let ((p (point)))
13621 (save-excursion
13622 (end-of-line)
13623 (unless (= (skip-chars-backward " \t" p) 0)
13624 (delete-region (point) (line-end-position)))))))
13625 ((not what) (throw 'exit nil)) ; Nothing to do.
13626 (t (insert-before-markers "\n")
13627 (backward-char 1)
13628 (when org-adapt-indentation
13629 (indent-to-column (1+ (org-outline-level))))))
13630 (when what
13631 ;; Insert planning keyword.
13632 (insert (cl-case what
13633 (closed org-closed-string)
13634 (deadline org-deadline-string)
13635 (scheduled org-scheduled-string)
13636 (otherwise (error "Invalid planning type: %s" what)))
13637 " ")
13638 ;; Insert associated timestamp.
13639 (let ((ts (org-insert-time-stamp
13640 time
13641 (or org-time-was-given
13642 (and (eq what 'closed) org-log-done-with-time))
13643 (eq what 'closed)
13644 nil nil (list org-end-time-was-given))))
13645 (unless (eolp) (insert " "))
13646 ts))))))
13648 (defvar org-log-note-marker (make-marker)
13649 "Marker pointing at the entry where the note is to be inserted.")
13650 (defvar org-log-note-purpose nil)
13651 (defvar org-log-note-state nil)
13652 (defvar org-log-note-previous-state nil)
13653 (defvar org-log-note-extra nil)
13654 (defvar org-log-note-window-configuration nil)
13655 (defvar org-log-note-return-to (make-marker))
13656 (defvar org-log-note-effective-time nil
13657 "Remembered current time so that dynamically scoped
13658 `org-extend-today-until' affects timestamps in state change log")
13660 (defvar org-log-post-message nil
13661 "Message to be displayed after a log note has been stored.
13662 The auto-repeater uses this.")
13664 (defun org-add-note ()
13665 "Add a note to the current entry.
13666 This is done in the same way as adding a state change note."
13667 (interactive)
13668 (org-add-log-setup 'note))
13670 (defun org-log-beginning (&optional create)
13671 "Return expected start of log notes in current entry.
13672 When optional argument CREATE is non-nil, the function creates
13673 a drawer to store notes, if necessary. Returned position ignores
13674 narrowing."
13675 (org-with-wide-buffer
13676 (let ((drawer (org-log-into-drawer)))
13677 (cond
13678 (drawer
13679 (org-end-of-meta-data)
13680 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13681 (end (if (org-at-heading-p) (point)
13682 (save-excursion (outline-next-heading) (point))))
13683 (case-fold-search t))
13684 (catch 'exit
13685 ;; Try to find existing drawer.
13686 (while (re-search-forward regexp end t)
13687 (let ((element (org-element-at-point)))
13688 (when (eq (org-element-type element) 'drawer)
13689 (let ((cend (org-element-property :contents-end element)))
13690 (when (and (not org-log-states-order-reversed) cend)
13691 (goto-char cend)))
13692 (throw 'exit nil))))
13693 ;; No drawer found. Create one, if permitted.
13694 (when create
13695 (unless (bolp) (insert "\n"))
13696 (let ((beg (point)))
13697 (insert ":" drawer ":\n:END:\n")
13698 (org-indent-region beg (point)))
13699 (end-of-line -1)))))
13701 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13702 (skip-chars-forward " \t\n")
13703 (beginning-of-line)
13704 (unless org-log-states-order-reversed
13705 (org-skip-over-state-notes)
13706 (skip-chars-backward " \t\n")
13707 (forward-line)))))
13708 (if (bolp) (point) (line-beginning-position 2))))
13710 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13711 "Set up the post command hook to take a note.
13712 If this is about to TODO state change, the new state is expected in STATE.
13713 HOW is an indicator what kind of note should be created.
13714 EXTRA is additional text that will be inserted into the notes buffer."
13715 (move-marker org-log-note-marker (point))
13716 (setq org-log-note-purpose purpose
13717 org-log-note-state state
13718 org-log-note-previous-state prev-state
13719 org-log-note-how how
13720 org-log-note-extra extra
13721 org-log-note-effective-time (org-current-effective-time))
13722 (add-hook 'post-command-hook 'org-add-log-note 'append))
13724 (defun org-skip-over-state-notes ()
13725 "Skip past the list of State notes in an entry."
13726 (when (ignore-errors (goto-char (org-in-item-p)))
13727 (let* ((struct (org-list-struct))
13728 (prevs (org-list-prevs-alist struct))
13729 (regexp
13730 (concat "[ \t]*- +"
13731 (replace-regexp-in-string
13732 " +" " +"
13733 (org-replace-escapes
13734 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13735 `(("%d" . ,org-ts-regexp-inactive)
13736 ("%D" . ,org-ts-regexp)
13737 ("%s" . "\"\\S-+\"")
13738 ("%S" . "\"\\S-+\"")
13739 ("%t" . ,org-ts-regexp-inactive)
13740 ("%T" . ,org-ts-regexp)
13741 ("%u" . ".*?")
13742 ("%U" . ".*?")))))))
13743 (while (looking-at-p regexp)
13744 (goto-char (or (org-list-get-next-item (point) struct prevs)
13745 (org-list-get-item-end (point) struct)))))))
13747 (defun org-add-log-note (&optional _purpose)
13748 "Pop up a window for taking a note, and add this note later."
13749 (remove-hook 'post-command-hook 'org-add-log-note)
13750 (setq org-log-note-window-configuration (current-window-configuration))
13751 (delete-other-windows)
13752 (move-marker org-log-note-return-to (point))
13753 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13754 (goto-char org-log-note-marker)
13755 (org-switch-to-buffer-other-window "*Org Note*")
13756 (erase-buffer)
13757 (if (memq org-log-note-how '(time state))
13758 (let (current-prefix-arg) (org-store-log-note))
13759 (let ((org-inhibit-startup t)) (org-mode))
13760 (insert (format "# Insert note for %s.
13761 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13762 (cond
13763 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13764 ((eq org-log-note-purpose 'done) "closed todo item")
13765 ((eq org-log-note-purpose 'state)
13766 (format "state change from \"%s\" to \"%s\""
13767 (or org-log-note-previous-state "")
13768 (or org-log-note-state "")))
13769 ((eq org-log-note-purpose 'reschedule)
13770 "rescheduling")
13771 ((eq org-log-note-purpose 'delschedule)
13772 "no longer scheduled")
13773 ((eq org-log-note-purpose 'redeadline)
13774 "changing deadline")
13775 ((eq org-log-note-purpose 'deldeadline)
13776 "removing deadline")
13777 ((eq org-log-note-purpose 'refile)
13778 "refiling")
13779 ((eq org-log-note-purpose 'note)
13780 "this entry")
13781 (t (error "This should not happen")))))
13782 (when org-log-note-extra (insert org-log-note-extra))
13783 (setq-local org-finish-function 'org-store-log-note)
13784 (run-hooks 'org-log-buffer-setup-hook)))
13786 (defvar org-note-abort nil) ; dynamically scoped
13787 (defun org-store-log-note ()
13788 "Finish taking a log note, and insert it to where it belongs."
13789 (let ((txt (prog1 (buffer-string)
13790 (kill-buffer)))
13791 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13792 lines)
13793 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13794 (setq txt (replace-match "" t t txt)))
13795 (when (string-match "\\s-+\\'" txt)
13796 (setq txt (replace-match "" t t txt)))
13797 (setq lines (org-split-string txt "\n"))
13798 (when (org-string-nw-p note)
13799 (setq note
13800 (org-replace-escapes
13801 note
13802 (list (cons "%u" (user-login-name))
13803 (cons "%U" user-full-name)
13804 (cons "%t" (format-time-string
13805 (org-time-stamp-format 'long 'inactive)
13806 org-log-note-effective-time))
13807 (cons "%T" (format-time-string
13808 (org-time-stamp-format 'long nil)
13809 org-log-note-effective-time))
13810 (cons "%d" (format-time-string
13811 (org-time-stamp-format nil 'inactive)
13812 org-log-note-effective-time))
13813 (cons "%D" (format-time-string
13814 (org-time-stamp-format nil nil)
13815 org-log-note-effective-time))
13816 (cons "%s" (cond
13817 ((not org-log-note-state) "")
13818 ((string-match-p org-ts-regexp
13819 org-log-note-state)
13820 (format "\"[%s]\""
13821 (substring org-log-note-state 1 -1)))
13822 (t (format "\"%s\"" org-log-note-state))))
13823 (cons "%S"
13824 (cond
13825 ((not org-log-note-previous-state) "")
13826 ((string-match-p org-ts-regexp
13827 org-log-note-previous-state)
13828 (format "\"[%s]\""
13829 (substring
13830 org-log-note-previous-state 1 -1)))
13831 (t (format "\"%s\""
13832 org-log-note-previous-state)))))))
13833 (when lines (setq note (concat note " \\\\")))
13834 (push note lines))
13835 (when (and lines (not (or current-prefix-arg org-note-abort)))
13836 (with-current-buffer (marker-buffer org-log-note-marker)
13837 (org-with-wide-buffer
13838 ;; Find location for the new note.
13839 (goto-char org-log-note-marker)
13840 (set-marker org-log-note-marker nil)
13841 (goto-char (org-log-beginning t))
13842 ;; Make sure point is at the beginning of an empty line.
13843 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13844 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13845 ;; In an existing list, add a new item at the top level.
13846 ;; Otherwise, indent line like a regular one.
13847 (let ((itemp (org-in-item-p)))
13848 (if itemp
13849 (indent-line-to
13850 (let ((struct (save-excursion
13851 (goto-char itemp) (org-list-struct))))
13852 (org-list-get-ind (org-list-get-top-point struct) struct)))
13853 (org-indent-line)))
13854 (insert (org-list-bullet-string "-") (pop lines))
13855 (let ((ind (org-list-item-body-column (line-beginning-position))))
13856 (dolist (line lines)
13857 (insert "\n")
13858 (indent-line-to ind)
13859 (insert line)))
13860 (message "Note stored")
13861 (org-back-to-heading t)
13862 (org-cycle-hide-drawers 'children))
13863 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13864 ;; from within `org-add-log-note' because `buffer-undo-list'
13865 ;; is then modified outside of `org-with-remote-undo'.
13866 (when (eq this-command 'org-agenda-todo)
13867 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13868 ;; Don't add undo information when called from `org-agenda-todo'.
13869 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13870 (set-window-configuration org-log-note-window-configuration)
13871 (with-current-buffer (marker-buffer org-log-note-return-to)
13872 (goto-char org-log-note-return-to))
13873 (move-marker org-log-note-return-to nil)
13874 (when org-log-post-message (message "%s" org-log-post-message))))
13876 (defun org-remove-empty-drawer-at (pos)
13877 "Remove an empty drawer at position POS.
13878 POS may also be a marker."
13879 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13880 (org-with-wide-buffer
13881 (goto-char pos)
13882 (let ((drawer (org-element-at-point)))
13883 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13884 (not (org-element-property :contents-begin drawer)))
13885 (delete-region (org-element-property :begin drawer)
13886 (progn (goto-char (org-element-property :end drawer))
13887 (skip-chars-backward " \r\t\n")
13888 (forward-line)
13889 (point))))))))
13891 (defvar org-ts-type nil)
13892 (defun org-sparse-tree (&optional arg type)
13893 "Create a sparse tree, prompt for the details.
13894 This command can create sparse trees. You first need to select the type
13895 of match used to create the tree:
13897 t Show all TODO entries.
13898 T Show entries with a specific TODO keyword.
13899 m Show entries selected by a tags/property match.
13900 p Enter a property name and its value (both with completion on existing
13901 names/values) and show entries with that property.
13902 r Show entries matching a regular expression (`/' can be used as well).
13903 b Show deadlines and scheduled items before a date.
13904 a Show deadlines and scheduled items after a date.
13905 d Show deadlines due within `org-deadline-warning-days'.
13906 D Show deadlines and scheduled items between a date range."
13907 (interactive "P")
13908 (setq type (or type org-sparse-tree-default-date-type))
13909 (setq org-ts-type type)
13910 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13911 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13912 \[c]ycle through date types: %s"
13913 (cl-case type
13914 (all "all timestamps")
13915 (scheduled "only scheduled")
13916 (deadline "only deadline")
13917 (active "only active timestamps")
13918 (inactive "only inactive timestamps")
13919 (closed "with a closed time-stamp")
13920 (otherwise "scheduled/deadline")))
13921 (let ((answer (read-char-exclusive)))
13922 (cl-case answer
13924 (org-sparse-tree
13926 (cadr
13927 (memq type '(nil all scheduled deadline active inactive closed)))))
13928 (?d (call-interactively 'org-check-deadlines))
13929 (?b (call-interactively 'org-check-before-date))
13930 (?a (call-interactively 'org-check-after-date))
13931 (?D (call-interactively 'org-check-dates-range))
13932 (?t (call-interactively 'org-show-todo-tree))
13933 (?T (org-show-todo-tree '(4)))
13934 (?m (call-interactively 'org-match-sparse-tree))
13935 ((?p ?P)
13936 (let* ((kwd (completing-read
13937 "Property: " (mapcar #'list (org-buffer-property-keys))))
13938 (value (completing-read
13939 "Value: " (mapcar #'list (org-property-values kwd)))))
13940 (unless (string-match "\\`{.*}\\'" value)
13941 (setq value (concat "\"" value "\"")))
13942 (org-match-sparse-tree arg (concat kwd "=" value))))
13943 ((?r ?R ?/) (call-interactively 'org-occur))
13944 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13946 (defvar-local org-occur-highlights nil
13947 "List of overlays used for occur matches.")
13948 (defvar-local org-occur-parameters nil
13949 "Parameters of the active org-occur calls.
13950 This is a list, each call to org-occur pushes as cons cell,
13951 containing the regular expression and the callback, onto the list.
13952 The list can contain several entries if `org-occur' has been called
13953 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13954 will only contain one set of parameters. When the highlights are
13955 removed (for example with `C-c C-c', or with the next edit (depending
13956 on `org-remove-highlights-with-change'), this variable is emptied
13957 as well.")
13959 (defun org-occur (regexp &optional keep-previous callback)
13960 "Make a compact tree which shows all matches of REGEXP.
13962 The tree will show the lines where the regexp matches, and any other context
13963 defined in `org-show-context-detail', which see.
13965 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13966 done by a previous call to `org-occur' will be kept, to allow stacking of
13967 calls to this command.
13969 Optional argument CALLBACK can be a function of no argument. In this case,
13970 it is called with point at the end of the match, match data being set
13971 accordingly. Current match is shown only if the return value is non-nil.
13972 The function must neither move point nor alter narrowing."
13973 (interactive "sRegexp: \nP")
13974 (when (equal regexp "")
13975 (user-error "Regexp cannot be empty"))
13976 (unless keep-previous
13977 (org-remove-occur-highlights nil nil t))
13978 (push (cons regexp callback) org-occur-parameters)
13979 (let ((cnt 0))
13980 (save-excursion
13981 (goto-char (point-min))
13982 (when (or (not keep-previous) ; do not want to keep
13983 (not org-occur-highlights)) ; no previous matches
13984 ;; hide everything
13985 (org-overview))
13986 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13987 (isearch-no-upper-case-p regexp t)
13988 org-occur-case-fold-search)))
13989 (while (re-search-forward regexp nil t)
13990 (when (or (not callback)
13991 (save-match-data (funcall callback)))
13992 (setq cnt (1+ cnt))
13993 (when org-highlight-sparse-tree-matches
13994 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13995 (org-show-context 'occur-tree)))))
13996 (when org-remove-highlights-with-change
13997 (add-hook 'before-change-functions 'org-remove-occur-highlights
13998 nil 'local))
13999 (unless org-sparse-tree-open-archived-trees
14000 (org-hide-archived-subtrees (point-min) (point-max)))
14001 (run-hooks 'org-occur-hook)
14002 (when (called-interactively-p 'interactive)
14003 (message "%d match(es) for regexp %s" cnt regexp))
14004 cnt))
14006 (defun org-occur-next-match (&optional n _reset)
14007 "Function for `next-error-function' to find sparse tree matches.
14008 N is the number of matches to move, when negative move backwards.
14009 This function always goes back to the starting point when no
14010 match is found."
14011 (let* ((limit (if (< n 0) (point-min) (point-max)))
14012 (search-func (if (< n 0)
14013 'previous-single-char-property-change
14014 'next-single-char-property-change))
14015 (n (abs n))
14016 (pos (point))
14018 (catch 'exit
14019 (while (setq p1 (funcall search-func (point) 'org-type))
14020 (when (equal p1 limit)
14021 (goto-char pos)
14022 (user-error "No more matches"))
14023 (when (equal (get-char-property p1 'org-type) 'org-occur)
14024 (setq n (1- n))
14025 (when (= n 0)
14026 (goto-char p1)
14027 (throw 'exit (point))))
14028 (goto-char p1))
14029 (goto-char p1)
14030 (user-error "No more matches"))))
14032 (defun org-show-context (&optional key)
14033 "Make sure point and context are visible.
14034 Optional argument KEY, when non-nil, is a symbol. See
14035 `org-show-context-detail' for allowed values and how much is to
14036 be shown."
14037 (org-show-set-visibility
14038 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14039 ((cdr (assq key org-show-context-detail)))
14040 (t (cdr (assq 'default org-show-context-detail))))))
14042 (defun org-show-set-visibility (detail)
14043 "Set visibility around point according to DETAIL.
14044 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14045 `tree', `canonical' or t. See `org-show-context-detail' for more
14046 information."
14047 ;; Show current heading and possibly its entry, following headline
14048 ;; or all children.
14049 (if (and (org-at-heading-p) (not (eq detail 'local)))
14050 (org-flag-heading nil)
14051 (org-show-entry)
14052 ;; If point is hidden within a drawer or a block, make sure to
14053 ;; expose it.
14054 (dolist (o (overlays-at (point)))
14055 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14056 (delete-overlay o)))
14057 (unless (org-before-first-heading-p)
14058 (org-with-limited-levels
14059 (cl-case detail
14060 ((tree canonical t) (org-show-children))
14061 ((nil minimal ancestors))
14062 (t (save-excursion
14063 (outline-next-heading)
14064 (org-flag-heading nil)))))))
14065 ;; Show all siblings.
14066 (when (eq detail 'lineage) (org-show-siblings))
14067 ;; Show ancestors, possibly with their children.
14068 (when (memq detail '(ancestors lineage tree canonical t))
14069 (save-excursion
14070 (while (org-up-heading-safe)
14071 (org-flag-heading nil)
14072 (when (memq detail '(canonical t)) (org-show-entry))
14073 (when (memq detail '(tree canonical t)) (org-show-children))))))
14075 (defvar org-reveal-start-hook nil
14076 "Hook run before revealing a location.")
14078 (defun org-reveal (&optional siblings)
14079 "Show current entry, hierarchy above it, and the following headline.
14081 This can be used to show a consistent set of context around
14082 locations exposed with `org-show-context'.
14084 With optional argument SIBLINGS, on each level of the hierarchy all
14085 siblings are shown. This repairs the tree structure to what it would
14086 look like when opened with hierarchical calls to `org-cycle'.
14088 With double optional argument \\[universal-argument] \\[universal-argument], \
14089 go to the parent and show the
14090 entire tree."
14091 (interactive "P")
14092 (run-hooks 'org-reveal-start-hook)
14093 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14094 ((equal siblings '(16))
14095 (save-excursion
14096 (when (org-up-heading-safe)
14097 (org-show-subtree)
14098 (run-hook-with-args 'org-cycle-hook 'subtree))))
14099 (t (org-show-set-visibility 'lineage))))
14101 (defun org-highlight-new-match (beg end)
14102 "Highlight from BEG to END and mark the highlight is an occur headline."
14103 (let ((ov (make-overlay beg end)))
14104 (overlay-put ov 'face 'secondary-selection)
14105 (overlay-put ov 'org-type 'org-occur)
14106 (push ov org-occur-highlights)))
14108 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14109 "Remove the occur highlights from the buffer.
14110 BEG and END are ignored. If NOREMOVE is nil, remove this function
14111 from the `before-change-functions' in the current buffer."
14112 (interactive)
14113 (unless org-inhibit-highlight-removal
14114 (mapc #'delete-overlay org-occur-highlights)
14115 (setq org-occur-highlights nil)
14116 (setq org-occur-parameters nil)
14117 (unless noremove
14118 (remove-hook 'before-change-functions
14119 'org-remove-occur-highlights 'local))))
14121 ;;;; Priorities
14123 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14124 "Regular expression matching the priority indicator.")
14126 (defvar org-remove-priority-next-time nil)
14128 (defun org-priority-up ()
14129 "Increase the priority of the current item."
14130 (interactive)
14131 (org-priority 'up))
14133 (defun org-priority-down ()
14134 "Decrease the priority of the current item."
14135 (interactive)
14136 (org-priority 'down))
14138 (defun org-priority (&optional action _show)
14139 "Change the priority of an item.
14140 ACTION can be `set', `up', `down', or a character."
14141 (interactive "P")
14142 (if (equal action '(4))
14143 (org-show-priority)
14144 (unless org-enable-priority-commands
14145 (user-error "Priority commands are disabled"))
14146 (setq action (or action 'set))
14147 (let (current new news have remove)
14148 (save-excursion
14149 (org-back-to-heading t)
14150 (when (looking-at org-priority-regexp)
14151 (setq current (string-to-char (match-string 2))
14152 have t))
14153 (cond
14154 ((eq action 'remove)
14155 (setq remove t new ?\ ))
14156 ((or (eq action 'set)
14157 (integerp action))
14158 (if (not (eq action 'set))
14159 (setq new action)
14160 (message "Priority %c-%c, SPC to remove: "
14161 org-highest-priority org-lowest-priority)
14162 (save-match-data
14163 (setq new (read-char-exclusive))))
14164 (when (and (= (upcase org-highest-priority) org-highest-priority)
14165 (= (upcase org-lowest-priority) org-lowest-priority))
14166 (setq new (upcase new)))
14167 (cond ((equal new ?\ ) (setq remove t))
14168 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14169 (user-error "Priority must be between `%c' and `%c'"
14170 org-highest-priority org-lowest-priority))))
14171 ((eq action 'up)
14172 (setq new (if have
14173 (1- current) ; normal cycling
14174 ;; last priority was empty
14175 (if (eq last-command this-command)
14176 org-lowest-priority ; wrap around empty to lowest
14177 ;; default
14178 (if org-priority-start-cycle-with-default
14179 org-default-priority
14180 (1- org-default-priority))))))
14181 ((eq action 'down)
14182 (setq new (if have
14183 (1+ current) ; normal cycling
14184 ;; last priority was empty
14185 (if (eq last-command this-command)
14186 org-highest-priority ; wrap around empty to highest
14187 ;; default
14188 (if org-priority-start-cycle-with-default
14189 org-default-priority
14190 (1+ org-default-priority))))))
14191 (t (user-error "Invalid action")))
14192 (when (or (< (upcase new) org-highest-priority)
14193 (> (upcase new) org-lowest-priority))
14194 (if (and (memq action '(up down))
14195 (not have) (not (eq last-command this-command)))
14196 ;; `new' is from default priority
14197 (error
14198 "The default can not be set, see `org-default-priority' why")
14199 ;; normal cycling: `new' is beyond highest/lowest priority
14200 ;; and is wrapped around to the empty priority
14201 (setq remove t)))
14202 (setq news (format "%c" new))
14203 (if have
14204 (if remove
14205 (replace-match "" t t nil 1)
14206 (replace-match news t t nil 2))
14207 (if remove
14208 (user-error "No priority cookie found in line")
14209 (let ((case-fold-search nil))
14210 (looking-at org-todo-line-regexp))
14211 (if (match-end 2)
14212 (progn
14213 (goto-char (match-end 2))
14214 (insert " [#" news "]"))
14215 (goto-char (match-beginning 3))
14216 (insert "[#" news "] "))))
14217 (org-set-tags nil 'align))
14218 (if remove
14219 (message "Priority removed")
14220 (message "Priority of current item set to %s" news)))))
14222 (defun org-show-priority ()
14223 "Show the priority of the current item.
14224 This priority is composed of the main priority given with the [#A] cookies,
14225 and by additional input from the age of a schedules or deadline entry."
14226 (interactive)
14227 (let ((pri (if (eq major-mode 'org-agenda-mode)
14228 (org-get-at-bol 'priority)
14229 (save-excursion
14230 (save-match-data
14231 (beginning-of-line)
14232 (and (looking-at org-heading-regexp)
14233 (org-get-priority (match-string 0))))))))
14234 (message "Priority is %d" (if pri pri -1000))))
14236 (defun org-get-priority (s)
14237 "Find priority cookie and return priority."
14238 (save-match-data
14239 (if (functionp org-get-priority-function)
14240 (funcall org-get-priority-function)
14241 (if (not (string-match org-priority-regexp s))
14242 (* 1000 (- org-lowest-priority org-default-priority))
14243 (* 1000 (- org-lowest-priority
14244 (string-to-char (match-string 2 s))))))))
14246 ;;;; Tags
14248 (defvar org-agenda-archives-mode)
14249 (defvar org-map-continue-from nil
14250 "Position from where mapping should continue.
14251 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14253 (defvar org-scanner-tags nil
14254 "The current tag list while the tags scanner is running.")
14256 (defvar org-trust-scanner-tags nil
14257 "Should `org-get-tags-at' use the tags for the scanner.
14258 This is for internal dynamical scoping only.
14259 When this is non-nil, the function `org-get-tags-at' will return the value
14260 of `org-scanner-tags' instead of building the list by itself. This
14261 can lead to large speed-ups when the tags scanner is used in a file with
14262 many entries, and when the list of tags is retrieved, for example to
14263 obtain a list of properties. Building the tags list for each entry in such
14264 a file becomes an N^2 operation - but with this variable set, it scales
14265 as N.")
14267 (defvar org--matcher-tags-todo-only nil)
14269 (defun org-scan-tags (action matcher todo-only &optional start-level)
14270 "Scan headline tags with inheritance and produce output ACTION.
14272 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14273 or `agenda' to produce an entry list for an agenda view. It can also be
14274 a Lisp form or a function that should be called at each matched headline, in
14275 this case the return value is a list of all return values from these calls.
14277 MATCHER is a function accepting three arguments, returning
14278 a non-nil value whenever a given set of tags qualifies a headline
14279 for inclusion. See `org-make-tags-matcher' for more information.
14280 As a special case, it can also be set to t (respectively nil) in
14281 order to match all (respectively none) headline.
14283 When TODO-ONLY is non-nil, only lines with a not-done TODO
14284 keyword are included in the output.
14286 START-LEVEL can be a string with asterisks, reducing the scope to
14287 headlines matching this string."
14288 (require 'org-agenda)
14289 (let* ((re (concat "^"
14290 (if start-level
14291 ;; Get the correct level to match
14292 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14293 org-outline-regexp)
14294 " *\\(\\<\\("
14295 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14296 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14297 (props (list 'face 'default
14298 'done-face 'org-agenda-done
14299 'undone-face 'default
14300 'mouse-face 'highlight
14301 'org-not-done-regexp org-not-done-regexp
14302 'org-todo-regexp org-todo-regexp
14303 'org-complex-heading-regexp org-complex-heading-regexp
14304 'help-echo
14305 (format "mouse-2 or RET jump to org file %s"
14306 (abbreviate-file-name
14307 (or (buffer-file-name (buffer-base-buffer))
14308 (buffer-name (buffer-base-buffer)))))))
14309 (org-map-continue-from nil)
14310 lspos tags tags-list
14311 (tags-alist (list (cons 0 org-file-tags)))
14312 (llast 0) rtn rtn1 level category i txt
14313 todo marker entry priority
14314 ts-date ts-date-type ts-date-pair)
14315 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14316 (setq action (list 'lambda nil action)))
14317 (save-excursion
14318 (goto-char (point-min))
14319 (when (eq action 'sparse-tree)
14320 (org-overview)
14321 (org-remove-occur-highlights))
14322 (while (let (case-fold-search)
14323 (re-search-forward re nil t))
14324 (setq org-map-continue-from nil)
14325 (catch :skip
14326 (setq todo
14327 ;; TODO: is the 1-2 difference a bug?
14328 (when (match-end 1) (match-string-no-properties 2))
14329 tags (when (match-end 4) (match-string-no-properties 4)))
14330 (goto-char (setq lspos (match-beginning 0)))
14331 (setq level (org-reduced-level (org-outline-level))
14332 category (org-get-category))
14333 (when (eq action 'agenda)
14334 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14335 ts-date (car ts-date-pair)
14336 ts-date-type (cdr ts-date-pair)))
14337 (setq i llast llast level)
14338 ;; remove tag lists from same and sublevels
14339 (while (>= i level)
14340 (when (setq entry (assoc i tags-alist))
14341 (setq tags-alist (delete entry tags-alist)))
14342 (setq i (1- i)))
14343 ;; add the next tags
14344 (when tags
14345 (setq tags (org-split-string tags ":")
14346 tags-alist
14347 (cons (cons level tags) tags-alist)))
14348 ;; compile tags for current headline
14349 (setq tags-list
14350 (if org-use-tag-inheritance
14351 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14352 tags)
14353 org-scanner-tags tags-list)
14354 (when org-use-tag-inheritance
14355 (setcdr (car tags-alist)
14356 (mapcar (lambda (x)
14357 (setq x (copy-sequence x))
14358 (org-add-prop-inherited x))
14359 (cdar tags-alist))))
14360 (when (and tags org-use-tag-inheritance
14361 (or (not (eq t org-use-tag-inheritance))
14362 org-tags-exclude-from-inheritance))
14363 ;; Selective inheritance, remove uninherited ones.
14364 (setcdr (car tags-alist)
14365 (org-remove-uninherited-tags (cdar tags-alist))))
14366 (when (and
14368 ;; eval matcher only when the todo condition is OK
14369 (and (or (not todo-only) (member todo org-not-done-keywords))
14370 (if (functionp matcher)
14371 (let ((case-fold-search t) (org-trust-scanner-tags t))
14372 (funcall matcher todo tags-list level))
14373 matcher))
14375 ;; Call the skipper, but return t if it does not
14376 ;; skip, so that the `and' form continues evaluating.
14377 (progn
14378 (unless (eq action 'sparse-tree) (org-agenda-skip))
14381 ;; Check if timestamps are deselecting this entry
14382 (or (not todo-only)
14383 (and (member todo org-not-done-keywords)
14384 (or (not org-agenda-tags-todo-honor-ignore-options)
14385 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14387 ;; select this headline
14388 (cond
14389 ((eq action 'sparse-tree)
14390 (and org-highlight-sparse-tree-matches
14391 (org-get-heading) (match-end 0)
14392 (org-highlight-new-match
14393 (match-beginning 1) (match-end 1)))
14394 (org-show-context 'tags-tree))
14395 ((eq action 'agenda)
14396 (setq txt (org-agenda-format-item
14398 (concat
14399 (if (eq org-tags-match-list-sublevels 'indented)
14400 (make-string (1- level) ?.) "")
14401 (org-get-heading))
14402 (make-string level ?\s)
14403 category
14404 tags-list)
14405 priority (org-get-priority txt))
14406 (goto-char lspos)
14407 (setq marker (org-agenda-new-marker))
14408 (org-add-props txt props
14409 'org-marker marker 'org-hd-marker marker 'org-category category
14410 'todo-state todo
14411 'ts-date ts-date
14412 'priority priority
14413 'type (concat "tagsmatch" ts-date-type))
14414 (push txt rtn))
14415 ((functionp action)
14416 (setq org-map-continue-from nil)
14417 (save-excursion
14418 (setq rtn1 (funcall action))
14419 (push rtn1 rtn)))
14420 (t (user-error "Invalid action")))
14422 ;; if we are to skip sublevels, jump to end of subtree
14423 (unless org-tags-match-list-sublevels
14424 (org-end-of-subtree t)
14425 (backward-char 1))))
14426 ;; Get the correct position from where to continue
14427 (if org-map-continue-from
14428 (goto-char org-map-continue-from)
14429 (and (= (point) lspos) (end-of-line 1)))))
14430 (when (and (eq action 'sparse-tree)
14431 (not org-sparse-tree-open-archived-trees))
14432 (org-hide-archived-subtrees (point-min) (point-max)))
14433 (nreverse rtn)))
14435 (defun org-remove-uninherited-tags (tags)
14436 "Remove all tags that are not inherited from the list TAGS."
14437 (cond
14438 ((eq org-use-tag-inheritance t)
14439 (if org-tags-exclude-from-inheritance
14440 (org-delete-all org-tags-exclude-from-inheritance tags)
14441 tags))
14442 ((not org-use-tag-inheritance) nil)
14443 ((stringp org-use-tag-inheritance)
14444 (delq nil (mapcar
14445 (lambda (x)
14446 (if (and (string-match org-use-tag-inheritance x)
14447 (not (member x org-tags-exclude-from-inheritance)))
14448 x nil))
14449 tags)))
14450 ((listp org-use-tag-inheritance)
14451 (delq nil (mapcar
14452 (lambda (x)
14453 (if (member x org-use-tag-inheritance) x nil))
14454 tags)))))
14456 (defun org-match-sparse-tree (&optional todo-only match)
14457 "Create a sparse tree according to tags string MATCH.
14458 MATCH can contain positive and negative selection of tags, like
14459 \"+WORK+URGENT-WITHBOSS\".
14460 If optional argument TODO-ONLY is non-nil, only select lines that are
14461 also TODO lines."
14462 (interactive "P")
14463 (org-agenda-prepare-buffers (list (current-buffer)))
14464 (let ((org--matcher-tags-todo-only todo-only))
14465 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14466 org--matcher-tags-todo-only)))
14468 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14470 (defvar org-cached-props nil)
14471 (defun org-cached-entry-get (pom property)
14472 (if (or (eq t org-use-property-inheritance)
14473 (and (stringp org-use-property-inheritance)
14474 (let ((case-fold-search t))
14475 (string-match-p org-use-property-inheritance property)))
14476 (and (listp org-use-property-inheritance)
14477 (member-ignore-case property org-use-property-inheritance)))
14478 ;; Caching is not possible, check it directly.
14479 (org-entry-get pom property 'inherit)
14480 ;; Get all properties, so we can do complicated checks easily.
14481 (cdr (assoc-string property
14482 (or org-cached-props
14483 (setq org-cached-props (org-entry-properties pom)))
14484 t))))
14486 (defun org-global-tags-completion-table (&optional files)
14487 "Return the list of all tags in all agenda buffer/files.
14488 Optional FILES argument is a list of files which can be used
14489 instead of the agenda files."
14490 (save-excursion
14491 (org-uniquify
14492 (delq nil
14493 (apply #'append
14494 (mapcar
14495 (lambda (file)
14496 (set-buffer (find-file-noselect file))
14497 (mapcar (lambda (x)
14498 (and (stringp (car-safe x))
14499 (list (car-safe x))))
14500 (or org-current-tag-alist (org-get-buffer-tags))))
14501 (if (car-safe files) files
14502 (org-agenda-files))))))))
14504 (defun org-make-tags-matcher (match)
14505 "Create the TAGS/TODO matcher form for the selection string MATCH.
14507 Returns a cons of the selection string MATCH and a function
14508 implementing the matcher.
14510 The matcher is to be called at an Org entry, with point on the
14511 headline, and returns non-nil if the entry matches the selection
14512 string MATCH. It must be called with three arguments: the TODO
14513 keyword at the entry (or nil if none), the list of all tags at
14514 the entry including inherited ones and the reduced level of the
14515 headline. Additionally, the category of the entry, if any, must
14516 be specified as the text property `org-category' on the headline.
14518 This function sets the variable `org--matcher-tags-todo-only' to
14519 a non-nil value if the matcher restricts matching to TODO
14520 entries, otherwise it is not touched.
14522 See also `org-scan-tags'."
14523 (unless match
14524 ;; Get a new match request, with completion against the global
14525 ;; tags table and the local tags in current buffer.
14526 (let ((org-last-tags-completion-table
14527 (org-uniquify
14528 (delq nil (append (org-get-buffer-tags)
14529 (org-global-tags-completion-table))))))
14530 (setq match
14531 (completing-read
14532 "Match: "
14533 'org-tags-completion-function nil nil nil 'org-tags-history))))
14535 (let ((match0 match)
14536 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14537 (start 0)
14538 tagsmatch todomatch tagsmatcher todomatcher)
14540 ;; Expand group tags.
14541 (setq match (org-tags-expand match))
14543 ;; Check if there is a TODO part of this match, which would be the
14544 ;; part after a "/". To make sure that this slash is not part of
14545 ;; a property value to be matched against, we also check that
14546 ;; there is no / after that slash. First, find the last slash.
14547 (let ((s 0))
14548 (while (string-match "/+" match s)
14549 (setq start (match-beginning 0))
14550 (setq s (match-end 0))))
14551 (if (and (string-match "/+" match start)
14552 (not (string-match-p "\"" match start)))
14553 ;; Match contains also a TODO-matching request.
14554 (progn
14555 (setq tagsmatch (substring match 0 (match-beginning 0)))
14556 (setq todomatch (substring match (match-end 0)))
14557 (when (string-prefix-p "!" todomatch)
14558 (setq org--matcher-tags-todo-only t)
14559 (setq todomatch (substring todomatch 1)))
14560 (when (string-match "\\`\\s-*\\'" todomatch)
14561 (setq todomatch nil)))
14562 ;; Only matching tags.
14563 (setq tagsmatch match)
14564 (setq todomatch nil))
14566 ;; Make the tags matcher.
14567 (when (org-string-nw-p tagsmatch)
14568 (let ((orlist nil)
14569 (orterms (org-split-string tagsmatch "|"))
14570 term)
14571 (while (setq term (pop orterms))
14572 (while (and (equal (substring term -1) "\\") orterms)
14573 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14574 (while (string-match re term)
14575 (let* ((rest (substring term (match-end 0)))
14576 (minus (and (match-end 1)
14577 (equal (match-string 1 term) "-")))
14578 (tag (save-match-data
14579 (replace-regexp-in-string
14580 "\\\\-" "-" (match-string 2 term))))
14581 (regexp (eq (string-to-char tag) ?{))
14582 (levelp (match-end 4))
14583 (propp (match-end 5))
14585 (cond
14586 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14587 (levelp
14588 `(,(org-op-to-function (match-string 3 term))
14589 level
14590 ,(string-to-number (match-string 4 term))))
14591 (propp
14592 (let* ((gv (pcase (upcase (match-string 5 term))
14593 ("CATEGORY"
14594 '(get-text-property (point) 'org-category))
14595 ("TODO" 'todo)
14596 (p `(org-cached-entry-get nil ,p))))
14597 (pv (match-string 7 term))
14598 (regexp (eq (string-to-char pv) ?{))
14599 (strp (eq (string-to-char pv) ?\"))
14600 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14601 (po (org-op-to-function (match-string 6 term)
14602 (if timep 'time strp))))
14603 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14604 (when timep (setq pv (org-matcher-time pv)))
14605 (cond ((and regexp (eq po 'org<>))
14606 `(not (string-match ,pv (or ,gv ""))))
14607 (regexp `(string-match ,pv (or ,gv "")))
14608 (strp `(,po (or ,gv "") ,pv))
14610 `(,po
14611 (string-to-number (or ,gv ""))
14612 ,(string-to-number pv))))))
14613 (t `(member ,tag tags-list)))))
14614 (push (if minus `(not ,mm) mm) tagsmatcher)
14615 (setq term rest)))
14616 (push `(and ,@tagsmatcher) orlist)
14617 (setq tagsmatcher nil))
14618 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14620 ;; Make the TODO matcher.
14621 (when (org-string-nw-p todomatch)
14622 (let ((orlist nil))
14623 (dolist (term (org-split-string todomatch "|"))
14624 (while (string-match re term)
14625 (let* ((minus (and (match-end 1)
14626 (equal (match-string 1 term) "-")))
14627 (kwd (match-string 2 term))
14628 (regexp (eq (string-to-char kwd) ?{))
14629 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14630 `(equal todo ,kwd))))
14631 (push (if minus `(not ,mm) mm) todomatcher))
14632 (setq term (substring term (match-end 0))))
14633 (push (if (> (length todomatcher) 1)
14634 (cons 'and todomatcher)
14635 (car todomatcher))
14636 orlist)
14637 (setq todomatcher nil))
14638 (setq todomatcher (cons 'or orlist))))
14640 ;; Return the string and function of the matcher. If no
14641 ;; tags-specific or todo-specific matcher exists, match
14642 ;; everything.
14643 (let ((matcher (if (and tagsmatcher todomatcher)
14644 `(and ,tagsmatcher ,todomatcher)
14645 (or tagsmatcher todomatcher t))))
14646 (when org--matcher-tags-todo-only
14647 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14648 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14650 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14651 "Expand group tags in MATCH.
14653 This replaces every group tag in MATCH with a regexp tag search.
14654 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14655 will be replaced like this:
14657 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14658 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14659 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14661 Replacing by a regexp preserves the structure of the match.
14662 E.g., this expansion
14664 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14666 will match anything tagged with \"Lab\" and \"Home\", or tagged
14667 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14669 A group tag in MATCH can contain regular expressions of its own.
14670 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14671 will be replaced like this:
14673 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14675 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14676 assumed to be a single group tag, and the function will return
14677 the list of tags in this group.
14679 When DOWNCASE is non-nil, expand downcased TAGS."
14680 (if org-group-tags
14681 (let* ((case-fold-search t)
14682 (stable org-mode-syntax-table)
14683 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14684 (taggroups (if downcased
14685 (mapcar (lambda (tg) (mapcar #'downcase tg))
14686 taggroups)
14687 taggroups))
14688 (taggroups-keys (mapcar #'car taggroups))
14689 (return-match (if downcased (downcase match) match))
14690 (count 0)
14691 (work-already-expanded tags-already-expanded)
14692 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14693 ;; @ and _ are allowed as word-components in tags.
14694 (modify-syntax-entry ?@ "w" stable)
14695 (modify-syntax-entry ?_ "w" stable)
14696 ;; Temporarily replace regexp-expressions in the match-expression.
14697 (while (string-match "{.+?}" return-match)
14698 (cl-incf count)
14699 (push (match-string 0 return-match) regexps-in-match)
14700 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14701 (while (and taggroups-keys
14702 (with-syntax-table stable
14703 (string-match
14704 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14705 (regexp-opt taggroups-keys) "\\>\\)")
14706 return-match)))
14707 (let* ((dir (match-string 1 return-match))
14708 (tag (match-string 2 return-match))
14709 (tag (if downcased (downcase tag) tag)))
14710 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14711 (member tag work-already-expanded))
14712 (setq tags-in-group (assoc tag taggroups))
14713 (push tag work-already-expanded)
14714 ;; Recursively expand each tag in the group, if the tag hasn't
14715 ;; already been expanded. Restore the match-data after all recursive calls.
14716 (save-match-data
14717 (let (tags-expanded)
14718 (dolist (x (cdr tags-in-group))
14719 (if (and (member x taggroups-keys)
14720 (not (member x work-already-expanded)))
14721 (setq tags-expanded
14722 (delete-dups
14723 (append
14724 (org-tags-expand x t downcased
14725 work-already-expanded)
14726 tags-expanded)))
14727 (setq tags-expanded
14728 (append (list x) tags-expanded)))
14729 (setq work-already-expanded
14730 (delete-dups
14731 (append tags-expanded
14732 work-already-expanded))))
14733 (setq tags-in-group
14734 (delete-dups (cons (car tags-in-group)
14735 tags-expanded)))))
14736 ;; Filter tag-regexps from tags.
14737 (setq regexp-in-group-escaped
14738 (delq nil (mapcar (lambda (x)
14739 (if (stringp x)
14740 (and (equal "{" (substring x 0 1))
14741 (equal "}" (substring x -1))
14744 tags-in-group))
14745 regexp-in-group
14746 (mapcar (lambda (x)
14747 (substring x 1 -1))
14748 regexp-in-group-escaped)
14749 tags-in-group
14750 (delq nil (mapcar (lambda (x)
14751 (if (stringp x)
14752 (and (not (equal "{" (substring x 0 1)))
14753 (not (equal "}" (substring x -1)))
14756 tags-in-group)))
14757 ;; If single-as-list, do no more in the while-loop.
14758 (if (not single-as-list)
14759 (progn
14760 (when regexp-in-group
14761 (setq regexp-in-group
14762 (concat "\\|"
14763 (mapconcat 'identity regexp-in-group
14764 "\\|"))))
14765 (setq tags-in-group
14766 (concat dir
14767 "{\\<"
14768 (regexp-opt tags-in-group)
14769 "\\>"
14770 regexp-in-group
14771 "}"))
14772 (when (stringp tags-in-group)
14773 (org-add-props tags-in-group '(grouptag t)))
14774 (setq return-match
14775 (replace-match tags-in-group t t return-match)))
14776 (setq tags-in-group
14777 (append regexp-in-group-escaped tags-in-group))))
14778 (setq taggroups-keys (delete tag taggroups-keys))))
14779 ;; Add the regular expressions back into the match-expression again.
14780 (while regexps-in-match
14781 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14782 (pop regexps-in-match)
14783 return-match t t))
14784 (cl-decf count))
14785 (if single-as-list
14786 (if tags-in-group tags-in-group (list return-match))
14787 return-match))
14788 (if single-as-list
14789 (list (if downcased (downcase match) match))
14790 match)))
14792 (defun org-op-to-function (op &optional stringp)
14793 "Turn an operator into the appropriate function."
14794 (setq op
14795 (cond
14796 ((equal op "<" ) '(< string< org-time<))
14797 ((equal op ">" ) '(> org-string> org-time>))
14798 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14799 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14800 ((member op '("=" "==")) '(= string= org-time=))
14801 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14802 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14804 (defun org<> (a b) (not (= a b)))
14805 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14806 (defun org-string>= (a b) (not (string< a b)))
14807 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14808 (defun org-string<> (a b) (not (string= a b)))
14809 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14810 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14811 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14812 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
14815 (defun org-2ft (s)
14816 "Convert S to a floating point time.
14817 If S is already a number, just return it. If it is a string, parse
14818 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14819 (cond
14820 ((numberp s) s)
14821 ((stringp s)
14822 (condition-case nil
14823 (float-time (apply 'encode-time (org-parse-time-string s)))
14824 (error 0.)))
14825 (t 0.)))
14827 (defun org-time-today ()
14828 "Time in seconds today at 0:00.
14829 Returns the float number of seconds since the beginning of the
14830 epoch to the beginning of today (00:00)."
14831 (float-time (apply 'encode-time
14832 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14834 (defun org-matcher-time (s)
14835 "Interpret a time comparison value."
14836 (save-match-data
14837 (cond
14838 ((string= s "<now>") (float-time))
14839 ((string= s "<today>") (org-time-today))
14840 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14841 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14842 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14843 (+ (org-time-today)
14844 (* (string-to-number (match-string 1 s))
14845 (cdr (assoc (match-string 2 s)
14846 '(("d" . 86400.0) ("w" . 604800.0)
14847 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14848 (t (org-2ft s)))))
14850 (defun org-match-any-p (re list)
14851 "Does re match any element of list?"
14852 (setq list (mapcar (lambda (x) (string-match re x)) list))
14853 (delq nil list))
14855 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14856 (defvar org-tags-overlay (make-overlay 1 1))
14857 (delete-overlay org-tags-overlay)
14859 (defun org-get-local-tags-at (&optional pos)
14860 "Get a list of tags defined in the current headline."
14861 (org-get-tags-at pos 'local))
14863 (defun org-get-local-tags ()
14864 "Get a list of tags defined in the current headline."
14865 (org-get-tags-at nil 'local))
14867 (defun org-get-tags-at (&optional pos local)
14868 "Get a list of all headline tags applicable at POS.
14869 POS defaults to point. If tags are inherited, the list contains
14870 the targets in the same sequence as the headlines appear, i.e.
14871 the tags of the current headline come last.
14872 When LOCAL is non-nil, only return tags from the current headline,
14873 ignore inherited ones."
14874 (interactive)
14875 (if (and org-trust-scanner-tags
14876 (or (not pos) (equal pos (point)))
14877 (not local))
14878 org-scanner-tags
14879 (let (tags ltags lastpos parent)
14880 (save-excursion
14881 (save-restriction
14882 (widen)
14883 (goto-char (or pos (point)))
14884 (save-match-data
14885 (catch 'done
14886 (condition-case nil
14887 (progn
14888 (org-back-to-heading t)
14889 (while (not (equal lastpos (point)))
14890 (setq lastpos (point))
14891 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14892 (setq ltags (org-split-string
14893 (match-string-no-properties 1) ":"))
14894 (when parent
14895 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14896 (setq tags (append
14897 (if parent
14898 (org-remove-uninherited-tags ltags)
14899 ltags)
14900 tags)))
14901 (or org-use-tag-inheritance (throw 'done t))
14902 (when local (throw 'done t))
14903 (or (org-up-heading-safe) (error nil))
14904 (setq parent t)))
14905 (error nil)))))
14906 (if local
14907 tags
14908 (reverse (delete-dups
14909 (reverse (append
14910 (org-remove-uninherited-tags
14911 org-file-tags)
14912 tags)))))))))
14914 (defun org-add-prop-inherited (s)
14915 (add-text-properties 0 (length s) '(inherited t) s)
14918 (defun org-toggle-tag (tag &optional onoff)
14919 "Toggle the tag TAG for the current line.
14920 If ONOFF is `on' or `off', don't toggle but set to this state."
14921 (let (res current)
14922 (save-excursion
14923 (org-back-to-heading t)
14924 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14925 (point-at-eol) t)
14926 (progn
14927 (setq current (match-string 1))
14928 (replace-match ""))
14929 (setq current ""))
14930 (setq current (nreverse (org-split-string current ":")))
14931 (cond
14932 ((eq onoff 'on)
14933 (setq res t)
14934 (or (member tag current) (push tag current)))
14935 ((eq onoff 'off)
14936 (or (not (member tag current)) (setq current (delete tag current))))
14937 (t (if (member tag current)
14938 (setq current (delete tag current))
14939 (setq res t)
14940 (push tag current))))
14941 (end-of-line 1)
14942 (if current
14943 (progn
14944 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14945 (org-set-tags nil t))
14946 (delete-horizontal-space))
14947 (run-hooks 'org-after-tags-change-hook))
14948 res))
14950 (defun org-align-tags-here (to-col)
14951 "Align tags on the current headline to TO-COL.
14952 Assume point is on a headline."
14953 (let ((pos (point)))
14954 (beginning-of-line)
14955 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14956 (>= pos (match-beginning 2)))
14957 ;; No tags or point within tags: do not align.
14958 (goto-char pos)
14959 (goto-char (match-beginning 1))
14960 (let ((shift (max (- (if (>= to-col 0) to-col
14961 (- (abs to-col) (string-width (match-string 2))))
14962 (current-column))
14963 1)))
14964 (replace-match (make-string shift ?\s) nil nil nil 1)
14965 ;; Preserve initial position, if possible. In any case, stop
14966 ;; before tags.
14967 (when (< pos (point)) (goto-char pos))))))
14969 (defun org-set-tags-command (&optional arg just-align)
14970 "Call the set-tags command for the current entry."
14971 (interactive "P")
14972 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14973 (org-set-tags arg just-align)
14974 (save-excursion
14975 (unless (and (org-region-active-p)
14976 org-loop-over-headlines-in-active-region)
14977 (org-back-to-heading t))
14978 (org-set-tags arg just-align))))
14980 (defun org-set-tags-to (data)
14981 "Set the tags of the current entry to DATA, replacing the current tags.
14982 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14983 If DATA is nil or the empty string, any tags will be removed."
14984 (interactive "sTags: ")
14985 (setq data
14986 (cond
14987 ((eq data nil) "")
14988 ((equal data "") "")
14989 ((stringp data)
14990 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14991 ":"))
14992 ((listp data)
14993 (concat ":" (mapconcat 'identity data ":") ":"))))
14994 (when data
14995 (save-excursion
14996 (org-back-to-heading t)
14997 (when (looking-at org-complex-heading-regexp)
14998 (if (match-end 5)
14999 (progn
15000 (goto-char (match-beginning 5))
15001 (insert data)
15002 (delete-region (point) (point-at-eol))
15003 (org-set-tags nil 'align))
15004 (goto-char (point-at-eol))
15005 (insert " " data)
15006 (org-set-tags nil 'align)))
15007 (beginning-of-line 1)
15008 (when (looking-at ".*?\\([ \t]+\\)$")
15009 (delete-region (match-beginning 1) (match-end 1))))))
15011 (defun org-align-all-tags ()
15012 "Align the tags in all headings."
15013 (interactive)
15014 (save-excursion
15015 (or (ignore-errors (org-back-to-heading t))
15016 (outline-next-heading))
15017 (if (org-at-heading-p)
15018 (org-set-tags t)
15019 (message "No headings"))))
15021 (defvar org-indent-indentation-per-level)
15022 (defun org-set-tags (&optional arg just-align)
15023 "Set the tags for the current headline.
15024 With prefix ARG, realign all tags in headings in the current buffer.
15025 When JUST-ALIGN is non-nil, only align tags."
15026 (interactive "P")
15027 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15028 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15029 'region-start-level
15030 'region))
15031 org-loop-over-headlines-in-active-region)
15032 (org-map-entries
15033 ;; We don't use ARG and JUST-ALIGN here because these args
15034 ;; are not useful when looping over headlines.
15035 #'org-set-tags
15036 org-loop-over-headlines-in-active-region
15038 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15039 (let ((org-setting-tags t))
15040 (if arg
15041 (save-excursion
15042 (goto-char (point-min))
15043 (while (re-search-forward org-outline-regexp-bol nil t)
15044 (org-set-tags nil t)
15045 (end-of-line))
15046 (message "All tags realigned to column %d" org-tags-column))
15047 (let* ((current (org-get-tags-string))
15048 (col (current-column))
15049 (tags
15050 (if just-align current
15051 ;; Get a new set of tags from the user.
15052 (save-excursion
15053 (let* ((seen)
15054 (table
15055 (setq
15056 org-last-tags-completion-table
15057 ;; Uniquify tags in alists, yet preserve
15058 ;; structure (i.e., keywords).
15059 (delq nil
15060 (mapcar
15061 (lambda (pair)
15062 (let ((head (car pair)))
15063 (cond ((symbolp head) pair)
15064 ((member head seen) nil)
15065 (t (push head seen)
15066 pair))))
15067 (append
15068 (or org-current-tag-alist
15069 (org-get-buffer-tags))
15070 (and
15071 org-complete-tags-always-offer-all-agenda-tags
15072 (org-global-tags-completion-table
15073 (org-agenda-files))))))))
15074 (current-tags (org-split-string current ":"))
15075 (inherited-tags
15076 (nreverse (nthcdr (length current-tags)
15077 (nreverse (org-get-tags-at))))))
15078 (replace-regexp-in-string
15079 "\\([-+&]+\\|,\\)"
15081 (if (or (eq t org-use-fast-tag-selection)
15082 (and org-use-fast-tag-selection
15083 (delq nil (mapcar #'cdr table))))
15084 (org-fast-tag-selection
15085 current-tags inherited-tags table
15086 (and org-fast-tag-selection-include-todo
15087 org-todo-key-alist))
15088 (let ((org-add-colon-after-tag-completion
15089 (< 1 (length table))))
15090 (org-trim
15091 (completing-read
15092 "Tags: "
15093 #'org-tags-completion-function
15094 nil nil current 'org-tags-history))))))))))
15096 (when org-tags-sort-function
15097 (setq tags
15098 (mapconcat
15099 #'identity
15100 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15101 org-tags-sort-function)
15102 ":")))
15104 (if (not (org-string-nw-p tags)) (setq tags "")
15105 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15106 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15108 ;; Insert new tags at the correct column
15109 (beginning-of-line)
15110 (let ((level (if (looking-at org-outline-regexp)
15111 (- (match-end 0) (point) 1)
15112 1)))
15113 (cond
15114 ((and (equal current "") (equal tags "")))
15115 ((re-search-forward
15116 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15117 (line-end-position)
15119 (if (equal tags "") (replace-match "" t t)
15120 (goto-char (match-beginning 0))
15121 (let* ((c0 (current-column))
15122 ;; Compute offset for the case of org-indent-mode
15123 ;; active.
15124 (di (if (bound-and-true-p org-indent-mode)
15125 (* (1- org-indent-indentation-per-level)
15126 (1- level))
15128 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15129 (tc (+ org-tags-column
15130 (if (> org-tags-column 0) (- di) di)))
15131 (c1 (max (1+ c0)
15132 (if (> tc 0) tc
15133 (- (- tc) (string-width tags)))))
15134 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15135 (replace-match rpl t t)
15136 (when indent-tabs-mode (tabify p0 (point))))))
15137 (t (error "Tags alignment failed"))))
15138 (org-move-to-column col))
15139 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15141 (defun org-change-tag-in-region (beg end tag off)
15142 "Add or remove TAG for each entry in the region.
15143 This works in the agenda, and also in an Org buffer."
15144 (interactive
15145 (list (region-beginning) (region-end)
15146 (let ((org-last-tags-completion-table
15147 (if (derived-mode-p 'org-mode)
15148 (org-uniquify
15149 (delq nil (append (org-get-buffer-tags)
15150 (org-global-tags-completion-table))))
15151 (org-global-tags-completion-table))))
15152 (completing-read
15153 "Tag: " 'org-tags-completion-function nil nil nil
15154 'org-tags-history))
15155 (progn
15156 (message "[s]et or [r]emove? ")
15157 (equal (read-char-exclusive) ?r))))
15158 (when (fboundp 'deactivate-mark) (deactivate-mark))
15159 (let ((agendap (equal major-mode 'org-agenda-mode))
15160 l1 l2 m buf pos newhead (cnt 0))
15161 (goto-char end)
15162 (setq l2 (1- (org-current-line)))
15163 (goto-char beg)
15164 (setq l1 (org-current-line))
15165 (cl-loop for l from l1 to l2 do
15166 (org-goto-line l)
15167 (setq m (get-text-property (point) 'org-hd-marker))
15168 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15169 (and agendap m))
15170 (setq buf (if agendap (marker-buffer m) (current-buffer))
15171 pos (if agendap m (point)))
15172 (with-current-buffer buf
15173 (save-excursion
15174 (save-restriction
15175 (goto-char pos)
15176 (setq cnt (1+ cnt))
15177 (org-toggle-tag tag (if off 'off 'on))
15178 (setq newhead (org-get-heading)))))
15179 (and agendap (org-agenda-change-all-lines newhead m))))
15180 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15182 (defun org-tags-completion-function (string _predicate &optional flag)
15183 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15184 (confirm (lambda (x) (stringp (car x)))))
15185 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15186 (setq s1 (match-string 1 string)
15187 s2 (match-string 2 string))
15188 (setq s1 "" s2 string))
15189 (cond
15190 ((eq flag nil)
15191 ;; try completion
15192 (setq rtn (try-completion s2 ctable confirm))
15193 (when (stringp rtn)
15194 (setq rtn
15195 (concat s1 s2 (substring rtn (length s2))
15196 (if (and org-add-colon-after-tag-completion
15197 (assoc rtn ctable))
15198 ":" ""))))
15199 rtn)
15200 ((eq flag t)
15201 ;; all-completions
15202 (all-completions s2 ctable confirm))
15203 ((eq flag 'lambda)
15204 ;; exact match?
15205 (assoc s2 ctable)))))
15207 (defun org-fast-tag-insert (kwd tags face &optional end)
15208 "Insert KDW, and the TAGS, the latter with face FACE.
15209 Also insert END."
15210 (insert (format "%-12s" (concat kwd ":"))
15211 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15212 (or end "")))
15214 (defun org-fast-tag-show-exit (flag)
15215 (save-excursion
15216 (org-goto-line 3)
15217 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15218 (replace-match ""))
15219 (when flag
15220 (end-of-line 1)
15221 (org-move-to-column (- (window-width) 19) t)
15222 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15224 (defun org-set-current-tags-overlay (current prefix)
15225 "Add an overlay to CURRENT tag with PREFIX."
15226 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15227 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15228 (org-overlay-display org-tags-overlay (concat prefix s))))
15230 (defvar org-last-tag-selection-key nil)
15231 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15232 "Fast tag selection with single keys.
15233 CURRENT is the current list of tags in the headline, INHERITED is the
15234 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15235 possibly with grouping information. TODO-TABLE is a similar table with
15236 TODO keywords, should these have keys assigned to them.
15237 If the keys are nil, a-z are automatically assigned.
15238 Returns the new tags string, or nil to not change the current settings."
15239 (let* ((fulltable (append table todo-table))
15240 (maxlen (apply 'max (mapcar
15241 (lambda (x)
15242 (if (stringp (car x)) (string-width (car x)) 0))
15243 fulltable)))
15244 (buf (current-buffer))
15245 (expert (eq org-fast-tag-selection-single-key 'expert))
15246 (buffer-tags nil)
15247 (fwidth (+ maxlen 3 1 3))
15248 (ncol (/ (- (window-width) 4) fwidth))
15249 (i-face 'org-done)
15250 (c-face 'org-todo)
15251 tg cnt e c char c1 c2 ntable tbl rtn
15252 ov-start ov-end ov-prefix
15253 (exit-after-next org-fast-tag-selection-single-key)
15254 (done-keywords org-done-keywords)
15255 groups ingroup intaggroup)
15256 (save-excursion
15257 (beginning-of-line 1)
15258 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15259 (setq ov-start (match-beginning 1)
15260 ov-end (match-end 1)
15261 ov-prefix "")
15262 (setq ov-start (1- (point-at-eol))
15263 ov-end (1+ ov-start))
15264 (skip-chars-forward "^\n\r")
15265 (setq ov-prefix
15266 (concat
15267 (buffer-substring (1- (point)) (point))
15268 (if (> (current-column) org-tags-column)
15270 (make-string (- org-tags-column (current-column)) ?\ ))))))
15271 (move-overlay org-tags-overlay ov-start ov-end)
15272 (save-window-excursion
15273 (if expert
15274 (set-buffer (get-buffer-create " *Org tags*"))
15275 (delete-other-windows)
15276 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15277 (org-switch-to-buffer-other-window " *Org tags*"))
15278 (erase-buffer)
15279 (setq-local org-done-keywords done-keywords)
15280 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15281 (org-fast-tag-insert "Current" current c-face "\n\n")
15282 (org-fast-tag-show-exit exit-after-next)
15283 (org-set-current-tags-overlay current ov-prefix)
15284 (setq tbl fulltable char ?a cnt 0)
15285 (while (setq e (pop tbl))
15286 (cond
15287 ((eq (car e) :startgroup)
15288 (push '() groups) (setq ingroup t)
15289 (unless (zerop cnt)
15290 (setq cnt 0)
15291 (insert "\n"))
15292 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15293 ((eq (car e) :endgroup)
15294 (setq ingroup nil cnt 0)
15295 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15296 ((eq (car e) :startgrouptag)
15297 (setq intaggroup t)
15298 (unless (zerop cnt)
15299 (setq cnt 0)
15300 (insert "\n"))
15301 (insert "[ "))
15302 ((eq (car e) :endgrouptag)
15303 (setq intaggroup nil cnt 0)
15304 (insert "]\n"))
15305 ((equal e '(:newline))
15306 (unless (zerop cnt)
15307 (setq cnt 0)
15308 (insert "\n")
15309 (setq e (car tbl))
15310 (while (equal (car tbl) '(:newline))
15311 (insert "\n")
15312 (setq tbl (cdr tbl)))))
15313 ((equal e '(:grouptags)) (insert " : "))
15315 (setq tg (copy-sequence (car e)) c2 nil)
15316 (if (cdr e)
15317 (setq c (cdr e))
15318 ;; automatically assign a character.
15319 (setq c1 (string-to-char
15320 (downcase (substring
15321 tg (if (= (string-to-char tg) ?@) 1 0)))))
15322 (if (or (rassoc c1 ntable) (rassoc c1 table))
15323 (while (or (rassoc char ntable) (rassoc char table))
15324 (setq char (1+ char)))
15325 (setq c2 c1))
15326 (setq c (or c2 char)))
15327 (when ingroup (push tg (car groups)))
15328 (setq tg (org-add-props tg nil 'face
15329 (cond
15330 ((not (assoc tg table))
15331 (org-get-todo-face tg))
15332 ((member tg current) c-face)
15333 ((member tg inherited) i-face))))
15334 (when (equal (caar tbl) :grouptags)
15335 (org-add-props tg nil 'face 'org-tag-group))
15336 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15337 (insert "[" c "] " tg (make-string
15338 (- fwidth 4 (length tg)) ?\ ))
15339 (push (cons tg c) ntable)
15340 (when (= (cl-incf cnt) ncol)
15341 (insert "\n")
15342 (when (or ingroup intaggroup) (insert " "))
15343 (setq cnt 0)))))
15344 (setq ntable (nreverse ntable))
15345 (insert "\n")
15346 (goto-char (point-min))
15347 (unless expert (org-fit-window-to-buffer))
15348 (setq rtn
15349 (catch 'exit
15350 (while t
15351 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15352 (if (not groups) "no " "")
15353 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15354 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15355 (setq org-last-tag-selection-key c)
15356 (cond
15357 ((= c ?\r) (throw 'exit t))
15358 ((= c ?!)
15359 (setq groups (not groups))
15360 (goto-char (point-min))
15361 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15362 ((= c ?\C-c)
15363 (if (not expert)
15364 (org-fast-tag-show-exit
15365 (setq exit-after-next (not exit-after-next)))
15366 (setq expert nil)
15367 (delete-other-windows)
15368 (set-window-buffer (split-window-vertically) " *Org tags*")
15369 (org-switch-to-buffer-other-window " *Org tags*")
15370 (org-fit-window-to-buffer)))
15371 ((or (= c ?\C-g)
15372 (and (= c ?q) (not (rassoc c ntable))))
15373 (delete-overlay org-tags-overlay)
15374 (setq quit-flag t))
15375 ((= c ?\ )
15376 (setq current nil)
15377 (when exit-after-next (setq exit-after-next 'now)))
15378 ((= c ?\t)
15379 (condition-case nil
15380 (setq tg (completing-read
15381 "Tag: "
15382 (or buffer-tags
15383 (with-current-buffer buf
15384 (setq buffer-tags
15385 (org-get-buffer-tags))))))
15386 (quit (setq tg "")))
15387 (when (string-match "\\S-" tg)
15388 (cl-pushnew (list tg) buffer-tags :test #'equal)
15389 (if (member tg current)
15390 (setq current (delete tg current))
15391 (push tg current)))
15392 (when exit-after-next (setq exit-after-next 'now)))
15393 ((setq e (rassoc c todo-table) tg (car e))
15394 (with-current-buffer buf
15395 (save-excursion (org-todo tg)))
15396 (when exit-after-next (setq exit-after-next 'now)))
15397 ((setq e (rassoc c ntable) tg (car e))
15398 (if (member tg current)
15399 (setq current (delete tg current))
15400 (cl-loop for g in groups do
15401 (when (member tg g)
15402 (dolist (x g) (setq current (delete x current)))))
15403 (push tg current))
15404 (when exit-after-next (setq exit-after-next 'now))))
15406 ;; Create a sorted list
15407 (setq current
15408 (sort current
15409 (lambda (a b)
15410 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15411 (when (eq exit-after-next 'now) (throw 'exit t))
15412 (goto-char (point-min))
15413 (beginning-of-line 2)
15414 (delete-region (point) (point-at-eol))
15415 (org-fast-tag-insert "Current" current c-face)
15416 (org-set-current-tags-overlay current ov-prefix)
15417 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15418 (setq tg (match-string 1))
15419 (add-text-properties
15420 (match-beginning 1) (match-end 1)
15421 (list 'face
15422 (cond
15423 ((member tg current) c-face)
15424 ((member tg inherited) i-face)
15425 (t (get-text-property (match-beginning 1) 'face))))))
15426 (goto-char (point-min)))))
15427 (delete-overlay org-tags-overlay)
15428 (if rtn
15429 (mapconcat 'identity current ":")
15430 nil))))
15432 (defun org-get-tags-string ()
15433 "Get the TAGS string in the current headline."
15434 (unless (org-at-heading-p t)
15435 (user-error "Not on a heading"))
15436 (save-excursion
15437 (beginning-of-line 1)
15438 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15439 (match-string-no-properties 1)
15440 "")))
15442 (defun org-get-tags ()
15443 "Get the list of tags specified in the current headline."
15444 (org-split-string (org-get-tags-string) ":"))
15446 (defun org-get-buffer-tags ()
15447 "Get a table of all tags used in the buffer, for completion."
15448 (org-with-wide-buffer
15449 (goto-char (point-min))
15450 (let ((tag-re (concat org-outline-regexp-bol
15451 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15452 tags)
15453 (while (re-search-forward tag-re nil t)
15454 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15455 (push tag tags)))
15456 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15458 ;;;; The mapping API
15460 (defvar org-agenda-skip-comment-trees)
15461 (defvar org-agenda-skip-function)
15462 (defun org-map-entries (func &optional match scope &rest skip)
15463 "Call FUNC at each headline selected by MATCH in SCOPE.
15465 FUNC is a function or a lisp form. The function will be called without
15466 arguments, with the cursor positioned at the beginning of the headline.
15467 The return values of all calls to the function will be collected and
15468 returned as a list.
15470 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15471 does not need to preserve point. After evaluation, the cursor will be
15472 moved to the end of the line (presumably of the headline of the
15473 processed entry) and search continues from there. Under some
15474 circumstances, this may not produce the wanted results. For example,
15475 if you have removed (e.g. archived) the current (sub)tree it could
15476 mean that the next entry will be skipped entirely. In such cases, you
15477 can specify the position from where search should continue by making
15478 FUNC set the variable `org-map-continue-from' to the desired buffer
15479 position.
15481 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15482 Only headlines that are matched by this query will be considered during
15483 the iteration. When MATCH is nil or t, all headlines will be
15484 visited by the iteration.
15486 SCOPE determines the scope of this command. It can be any of:
15488 nil The current buffer, respecting the restriction if any
15489 tree The subtree started with the entry at point
15490 region The entries within the active region, if any
15491 region-start-level
15492 The entries within the active region, but only those at
15493 the same level than the first one.
15494 file The current buffer, without restriction
15495 file-with-archives
15496 The current buffer, and any archives associated with it
15497 agenda All agenda files
15498 agenda-with-archives
15499 All agenda files with any archive files associated with them
15500 \(file1 file2 ...)
15501 If this is a list, all files in the list will be scanned
15503 The remaining args are treated as settings for the skipping facilities of
15504 the scanner. The following items can be given here:
15506 archive skip trees with the archive tag
15507 comment skip trees with the COMMENT keyword
15508 function or Emacs Lisp form:
15509 will be used as value for `org-agenda-skip-function', so
15510 whenever the function returns a position, FUNC will not be
15511 called for that entry and search will continue from the
15512 position returned
15514 If your function needs to retrieve the tags including inherited tags
15515 at the *current* entry, you can use the value of the variable
15516 `org-scanner-tags' which will be much faster than getting the value
15517 with `org-get-tags-at'. If your function gets properties with
15518 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15519 to t around the call to `org-entry-properties' to get the same speedup.
15520 Note that if your function moves around to retrieve tags and properties at
15521 a *different* entry, you cannot use these techniques."
15522 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15523 (not (org-region-active-p)))
15524 (let* ((org-agenda-archives-mode nil) ; just to make sure
15525 (org-agenda-skip-archived-trees (memq 'archive skip))
15526 (org-agenda-skip-comment-trees (memq 'comment skip))
15527 (org-agenda-skip-function
15528 (car (org-delete-all '(comment archive) skip)))
15529 (org-tags-match-list-sublevels t)
15530 (start-level (eq scope 'region-start-level))
15531 matcher res
15532 org-todo-keywords-for-agenda
15533 org-done-keywords-for-agenda
15534 org-todo-keyword-alist-for-agenda
15535 org-tag-alist-for-agenda
15536 org--matcher-tags-todo-only)
15538 (cond
15539 ((eq match t) (setq matcher t))
15540 ((eq match nil) (setq matcher t))
15541 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15543 (save-excursion
15544 (save-restriction
15545 (cond ((eq scope 'tree)
15546 (org-back-to-heading t)
15547 (org-narrow-to-subtree)
15548 (setq scope nil))
15549 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15550 (org-region-active-p))
15551 ;; If needed, set start-level to a string like "2"
15552 (when start-level
15553 (save-excursion
15554 (goto-char (region-beginning))
15555 (unless (org-at-heading-p) (outline-next-heading))
15556 (setq start-level (org-current-level))))
15557 (narrow-to-region (region-beginning)
15558 (save-excursion
15559 (goto-char (region-end))
15560 (unless (and (bolp) (org-at-heading-p))
15561 (outline-next-heading))
15562 (point)))
15563 (setq scope nil)))
15565 (if (not scope)
15566 (progn
15567 (org-agenda-prepare-buffers
15568 (and buffer-file-name (list buffer-file-name)))
15569 (setq res
15570 (org-scan-tags
15571 func matcher org--matcher-tags-todo-only start-level)))
15572 ;; Get the right scope
15573 (cond
15574 ((and scope (listp scope) (symbolp (car scope)))
15575 (setq scope (eval scope)))
15576 ((eq scope 'agenda)
15577 (setq scope (org-agenda-files t)))
15578 ((eq scope 'agenda-with-archives)
15579 (setq scope (org-agenda-files t))
15580 (setq scope (org-add-archive-files scope)))
15581 ((eq scope 'file)
15582 (setq scope (and buffer-file-name (list buffer-file-name))))
15583 ((eq scope 'file-with-archives)
15584 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15585 (org-agenda-prepare-buffers scope)
15586 (dolist (file scope)
15587 (with-current-buffer (org-find-base-buffer-visiting file)
15588 (org-with-wide-buffer
15589 (goto-char (point-min))
15590 (setq res
15591 (append
15593 (org-scan-tags
15594 func matcher org--matcher-tags-todo-only)))))))))
15595 res)))
15597 ;;; Properties API
15599 (defconst org-special-properties
15600 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15601 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15602 "The special properties valid in Org mode.
15603 These are properties that are not defined in the property drawer,
15604 but in some other way.")
15606 (defconst org-default-properties
15607 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15608 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15609 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15610 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15611 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15612 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15613 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15614 "Some properties that are used by Org mode for various purposes.
15615 Being in this list makes sure that they are offered for completion.")
15617 (defun org--valid-property-p (property)
15618 "Non nil when string PROPERTY is a valid property name."
15619 (not
15620 (or (equal property "")
15621 (string-match-p "\\s-" property))))
15623 (defun org--update-property-plist (key val props)
15624 "Associate KEY to VAL in alist PROPS.
15625 Modifications are made by side-effect. Return new alist."
15626 (let* ((appending (string= (substring key -1) "+"))
15627 (key (if appending (substring key 0 -1) key))
15628 (old (assoc-string key props t)))
15629 (if (not old) (cons (cons key val) props)
15630 (setcdr old (if appending (concat (cdr old) " " val) val))
15631 props)))
15633 (defun org-get-property-block (&optional beg force)
15634 "Return the (beg . end) range of the body of the property drawer.
15635 BEG is the beginning of the current subtree, or of the part
15636 before the first headline. If it is not given, it will be found.
15637 If the drawer does not exist, create it if FORCE is non-nil, or
15638 return nil."
15639 (org-with-wide-buffer
15640 (when beg (goto-char beg))
15641 (unless (org-before-first-heading-p)
15642 (let ((beg (cond (beg)
15643 ((or (not (featurep 'org-inlinetask))
15644 (org-inlinetask-in-task-p))
15645 (org-back-to-heading t))
15646 (t (org-with-limited-levels (org-back-to-heading t))))))
15647 (forward-line)
15648 (when (looking-at-p org-planning-line-re) (forward-line))
15649 (cond ((looking-at org-property-drawer-re)
15650 (forward-line)
15651 (cons (point) (progn (goto-char (match-end 0))
15652 (line-beginning-position))))
15653 (force
15654 (goto-char beg)
15655 (org-insert-property-drawer)
15656 (let ((pos (save-excursion (search-forward ":END:")
15657 (line-beginning-position))))
15658 (cons pos pos))))))))
15660 (defun org-at-property-p ()
15661 "Non-nil when point is inside a property drawer.
15662 See `org-property-re' for match data, if applicable."
15663 (save-excursion
15664 (beginning-of-line)
15665 (and (looking-at org-property-re)
15666 (let ((property-drawer (save-match-data (org-get-property-block))))
15667 (and property-drawer
15668 (>= (point) (car property-drawer))
15669 (< (point) (cdr property-drawer)))))))
15671 (defun org-property-action ()
15672 "Do an action on properties."
15673 (interactive)
15674 (unless (org-at-property-p) (user-error "Not at a property"))
15675 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15676 (let ((c (read-char-exclusive)))
15677 (cl-case c
15678 (?s (call-interactively #'org-set-property))
15679 (?d (call-interactively #'org-delete-property))
15680 (?D (call-interactively #'org-delete-property-globally))
15681 (?c (call-interactively #'org-compute-property-at-point))
15682 (otherwise (user-error "No such property action %c" c)))))
15684 (defun org-inc-effort ()
15685 "Increment the value of the effort property in the current entry."
15686 (interactive)
15687 (org-set-effort nil t))
15689 (defvar org-clock-effort) ; Defined in org-clock.el.
15690 (defvar org-clock-current-task) ; Defined in org-clock.el.
15691 (defun org-set-effort (&optional value increment)
15692 "Set the effort property of the current entry.
15693 With numerical prefix arg, use the nth allowed value, 0 stands for the
15694 10th allowed value.
15696 When INCREMENT is non-nil, set the property to the next allowed value."
15697 (interactive "P")
15698 (when (equal value 0) (setq value 10))
15699 (let* ((completion-ignore-case t)
15700 (prop org-effort-property)
15701 (cur (org-entry-get nil prop))
15702 (allowed (org-property-get-allowed-values nil prop 'table))
15703 (existing (mapcar 'list (org-property-values prop)))
15704 (heading (nth 4 (org-heading-components)))
15706 (val (cond
15707 ((stringp value) value)
15708 ((and allowed (integerp value))
15709 (or (car (nth (1- value) allowed))
15710 (car (org-last allowed))))
15711 ((and allowed increment)
15712 (or (cl-caadr (member (list cur) allowed))
15713 (user-error "Allowed effort values are not set")))
15714 (allowed
15715 (message "Select 1-9,0, [RET%s]: %s"
15716 (if cur (concat "=" cur) "")
15717 (mapconcat 'car allowed " "))
15718 (setq rpl (read-char-exclusive))
15719 (if (equal rpl ?\r)
15721 (setq rpl (- rpl ?0))
15722 (when (equal rpl 0) (setq rpl 10))
15723 (if (and (> rpl 0) (<= rpl (length allowed)))
15724 (car (nth (1- rpl) allowed))
15725 (org-completing-read "Effort: " allowed nil))))
15727 (org-completing-read
15728 (concat "Effort" (and cur (string-match "\\S-" cur)
15729 (concat " [" cur "]"))
15730 ": ")
15731 existing nil nil "" nil cur)))))
15732 (unless (equal (org-entry-get nil prop) val)
15733 (org-entry-put nil prop val))
15734 (org-refresh-property
15735 '((effort . identity)
15736 (effort-minutes . org-duration-string-to-minutes))
15737 val)
15738 (when (equal heading (bound-and-true-p org-clock-current-task))
15739 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15740 (org-clock-update-mode-line))
15741 (message "%s is now %s" prop val)))
15743 (defun org-entry-properties (&optional pom which)
15744 "Get all properties of the current entry.
15746 When POM is a buffer position, get all properties from the entry
15747 there instead.
15749 This includes the TODO keyword, the tags, time strings for
15750 deadline, scheduled, and clocking, and any additional properties
15751 defined in the entry.
15753 If WHICH is nil or `all', get all properties. If WHICH is
15754 `special' or `standard', only get that subclass. If WHICH is
15755 a string, only get that property.
15757 Return value is an alist. Keys are properties, as upcased
15758 strings."
15759 (org-with-point-at pom
15760 (when (and (derived-mode-p 'org-mode)
15761 (ignore-errors (org-back-to-heading t)))
15762 (catch 'exit
15763 (let* ((beg (point))
15764 (specific (and (stringp which) (upcase which)))
15765 (which (cond ((not specific) which)
15766 ((member specific org-special-properties) 'special)
15767 (t 'standard)))
15768 props)
15769 ;; Get the special properties, like TODO and TAGS.
15770 (when (memq which '(nil all special))
15771 (when (or (not specific) (string= specific "CLOCKSUM"))
15772 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15773 (when clocksum
15774 (push (cons "CLOCKSUM"
15775 (org-minutes-to-clocksum-string clocksum))
15776 props)))
15777 (when specific (throw 'exit props)))
15778 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15779 (let ((clocksumt (get-text-property (point)
15780 :org-clock-minutes-today)))
15781 (when clocksumt
15782 (push (cons "CLOCKSUM_T"
15783 (org-minutes-to-clocksum-string clocksumt))
15784 props)))
15785 (when specific (throw 'exit props)))
15786 (when (or (not specific) (string= specific "ITEM"))
15787 (when (looking-at org-complex-heading-regexp)
15788 (push (cons "ITEM"
15789 (let ((title (match-string-no-properties 4)))
15790 (if (org-string-nw-p title)
15791 (org-remove-tabs title)
15792 "")))
15793 props))
15794 (when specific (throw 'exit props)))
15795 (when (or (not specific) (string= specific "TODO"))
15796 (let ((case-fold-search nil))
15797 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15798 (push (cons "TODO" (match-string-no-properties 2)) props)))
15799 (when specific (throw 'exit props)))
15800 (when (or (not specific) (string= specific "PRIORITY"))
15801 (push (cons "PRIORITY"
15802 (if (looking-at org-priority-regexp)
15803 (match-string-no-properties 2)
15804 (char-to-string org-default-priority)))
15805 props)
15806 (when specific (throw 'exit props)))
15807 (when (or (not specific) (string= specific "FILE"))
15808 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15809 props)
15810 (when specific (throw 'exit props)))
15811 (when (or (not specific) (string= specific "TAGS"))
15812 (let ((value (org-string-nw-p (org-get-tags-string))))
15813 (when value (push (cons "TAGS" value) props)))
15814 (when specific (throw 'exit props)))
15815 (when (or (not specific) (string= specific "ALLTAGS"))
15816 (let ((value (org-get-tags-at)))
15817 (when value
15818 (push (cons "ALLTAGS"
15819 (format ":%s:" (mapconcat #'identity value ":")))
15820 props)))
15821 (when specific (throw 'exit props)))
15822 (when (or (not specific) (string= specific "BLOCKED"))
15823 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15824 (when specific (throw 'exit props)))
15825 (when (or (not specific)
15826 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15827 (forward-line)
15828 (when (looking-at-p org-planning-line-re)
15829 (end-of-line)
15830 (let ((bol (line-beginning-position))
15831 ;; Backward compatibility: time keywords used to
15832 ;; be configurable (before 8.3). Make sure we
15833 ;; get the correct keyword.
15834 (key-assoc `(("CLOSED" . ,org-closed-string)
15835 ("DEADLINE" . ,org-deadline-string)
15836 ("SCHEDULED" . ,org-scheduled-string))))
15837 (dolist (pair (if specific (list (assoc specific key-assoc))
15838 key-assoc))
15839 (save-excursion
15840 (when (search-backward (cdr pair) bol t)
15841 (goto-char (match-end 0))
15842 (skip-chars-forward " \t")
15843 (and (looking-at org-ts-regexp-both)
15844 (push (cons (car pair)
15845 (match-string-no-properties 0))
15846 props)))))))
15847 (when specific (throw 'exit props)))
15848 (when (or (not specific)
15849 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15850 (let ((find-ts
15851 (lambda (end ts)
15852 ;; Fix next time-stamp before END. TS is the
15853 ;; list of time-stamps found so far.
15854 (let ((ts ts)
15855 (regexp (cond
15856 ((string= specific "TIMESTAMP")
15857 org-ts-regexp)
15858 ((string= specific "TIMESTAMP_IA")
15859 org-ts-regexp-inactive)
15860 ((assoc "TIMESTAMP_IA" ts)
15861 org-ts-regexp)
15862 ((assoc "TIMESTAMP" ts)
15863 org-ts-regexp-inactive)
15864 (t org-ts-regexp-both))))
15865 (catch 'next
15866 (while (re-search-forward regexp end t)
15867 (backward-char)
15868 (let ((object (org-element-context)))
15869 ;; Accept to match timestamps in node
15870 ;; properties, too.
15871 (when (memq (org-element-type object)
15872 '(node-property timestamp))
15873 (let ((type
15874 (org-element-property :type object)))
15875 (cond
15876 ((and (memq type '(active active-range))
15877 (not (equal specific "TIMESTAMP_IA")))
15878 (unless (assoc "TIMESTAMP" ts)
15879 (push (cons "TIMESTAMP"
15880 (org-element-property
15881 :raw-value object))
15883 (when specific (throw 'exit ts))))
15884 ((and (memq type '(inactive inactive-range))
15885 (not (string= specific "TIMESTAMP")))
15886 (unless (assoc "TIMESTAMP_IA" ts)
15887 (push (cons "TIMESTAMP_IA"
15888 (org-element-property
15889 :raw-value object))
15891 (when specific (throw 'exit ts))))))
15892 ;; Both timestamp types are found,
15893 ;; move to next part.
15894 (when (= (length ts) 2) (throw 'next ts)))))
15895 ts)))))
15896 (goto-char beg)
15897 ;; First look for timestamps within headline.
15898 (let ((ts (funcall find-ts (line-end-position) nil)))
15899 (if (= (length ts) 2) (setq props (nconc ts props))
15900 (forward-line)
15901 ;; Then find timestamps in the section, skipping
15902 ;; planning line.
15903 (when (looking-at-p org-planning-line-re)
15904 (forward-line))
15905 (let ((end (save-excursion (outline-next-heading))))
15906 (setq props (nconc (funcall find-ts end ts) props))))))))
15907 ;; Get the standard properties, like :PROP:.
15908 (when (memq which '(nil all standard))
15909 ;; If we are looking after a specific property, delegate
15910 ;; to `org-entry-get', which is faster. However, make an
15911 ;; exception for "CATEGORY", since it can be also set
15912 ;; through keywords (i.e. #+CATEGORY).
15913 (if (and specific (not (equal specific "CATEGORY")))
15914 (let ((value (org-entry-get beg specific nil t)))
15915 (throw 'exit (and value (list (cons specific value)))))
15916 (let ((range (org-get-property-block beg)))
15917 (when range
15918 (let ((end (cdr range)) seen-base)
15919 (goto-char (car range))
15920 ;; Unlike to `org--update-property-plist', we
15921 ;; handle the case where base values is found
15922 ;; after its extension. We also forbid standard
15923 ;; properties to be named as special properties.
15924 (while (re-search-forward org-property-re end t)
15925 (let* ((key (upcase (match-string-no-properties 2)))
15926 (extendp (string-match-p "\\+\\'" key))
15927 (key-base (if extendp (substring key 0 -1) key))
15928 (value (match-string-no-properties 3)))
15929 (cond
15930 ((member-ignore-case key-base org-special-properties))
15931 (extendp
15932 (setq props
15933 (org--update-property-plist key value props)))
15934 ((member key seen-base))
15935 (t (push key seen-base)
15936 (let ((p (assoc-string key props t)))
15937 (if p (setcdr p (concat value " " (cdr p)))
15938 (push (cons key value) props))))))))))))
15939 (unless (assoc "CATEGORY" props)
15940 (push (cons "CATEGORY" (org-get-category beg)) props)
15941 (when (string= specific "CATEGORY") (throw 'exit props)))
15942 ;; Return value.
15943 props)))))
15945 (defun org-property--local-values (property literal-nil)
15946 "Return value for PROPERTY in current entry.
15947 Value is a list whose car is the base value for PROPERTY and cdr
15948 a list of accumulated values. Return nil if neither is found in
15949 the entry. Also return nil when PROPERTY is set to \"nil\",
15950 unless LITERAL-NIL is non-nil."
15951 (let ((range (org-get-property-block)))
15952 (when range
15953 (goto-char (car range))
15954 (let* ((case-fold-search t)
15955 (end (cdr range))
15956 (value
15957 ;; Base value.
15958 (save-excursion
15959 (let ((v (and (re-search-forward
15960 (org-re-property property nil t) end t)
15961 (match-string-no-properties 3))))
15962 (list (if literal-nil v (org-not-nil v)))))))
15963 ;; Find additional values.
15964 (let* ((property+ (org-re-property (concat property "+") nil t)))
15965 (while (re-search-forward property+ end t)
15966 (push (match-string-no-properties 3) value)))
15967 ;; Return final values.
15968 (and (not (equal value '(nil))) (nreverse value))))))
15970 (defun org-entry-get (pom property &optional inherit literal-nil)
15971 "Get value of PROPERTY for entry or content at point-or-marker POM.
15973 If INHERIT is non-nil and the entry does not have the property,
15974 then also check higher levels of the hierarchy. If INHERIT is
15975 the symbol `selective', use inheritance only if the setting in
15976 `org-use-property-inheritance' selects PROPERTY for inheritance.
15978 If the property is present but empty, the return value is the
15979 empty string. If the property is not present at all, nil is
15980 returned. In any other case, return the value as a string.
15981 Search is case-insensitive.
15983 If LITERAL-NIL is set, return the string value \"nil\" as
15984 a string, do not interpret it as the list atom nil. This is used
15985 for inheritance when a \"nil\" value can supersede a non-nil
15986 value higher up the hierarchy."
15987 (org-with-point-at pom
15988 (cond
15989 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15990 ;; We need a special property. Use `org-entry-properties' to
15991 ;; retrieve it, but specify the wanted property.
15992 (cdr (assoc-string property (org-entry-properties nil property))))
15993 ((and inherit
15994 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15995 (org-entry-get-with-inheritance property literal-nil))
15997 (let* ((local (org-property--local-values property literal-nil))
15998 (value (and local (mapconcat #'identity (delq nil local) " "))))
15999 (if literal-nil value (org-not-nil value)))))))
16001 (defun org-property-or-variable-value (var &optional inherit)
16002 "Check if there is a property fixing the value of VAR.
16003 If yes, return this value. If not, return the current value of the variable."
16004 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16005 (if (and prop (stringp prop) (string-match "\\S-" prop))
16006 (read prop)
16007 (symbol-value var))))
16009 (defun org-entry-delete (pom property)
16010 "Delete PROPERTY from entry at point-or-marker POM.
16011 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16012 non-nil when a property was removed."
16013 (unless (member property org-special-properties)
16014 (org-with-point-at pom
16015 (let ((range (org-get-property-block)))
16016 (when range
16017 (let* ((begin (car range))
16018 (origin (cdr range))
16019 (end (copy-marker origin))
16020 (re (org-re-property
16021 (concat (regexp-quote property) "\\+?") t t)))
16022 (goto-char begin)
16023 (while (re-search-forward re end t)
16024 (delete-region (match-beginning 0) (line-beginning-position 2)))
16025 ;; If drawer is empty, remove it altogether.
16026 (when (= begin end)
16027 (delete-region (line-beginning-position 0)
16028 (line-beginning-position 2)))
16029 ;; Return non-nil if some property was removed.
16030 (prog1 (/= end origin) (set-marker end nil))))))))
16032 ;; Multi-values properties are properties that contain multiple values
16033 ;; These values are assumed to be single words, separated by whitespace.
16034 (defun org-entry-add-to-multivalued-property (pom property value)
16035 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16036 (let* ((old (org-entry-get pom property))
16037 (values (and old (org-split-string old "[ \t]"))))
16038 (setq value (org-entry-protect-space value))
16039 (unless (member value values)
16040 (setq values (append values (list value)))
16041 (org-entry-put pom property
16042 (mapconcat 'identity values " ")))))
16044 (defun org-entry-remove-from-multivalued-property (pom property value)
16045 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16046 (let* ((old (org-entry-get pom property))
16047 (values (and old (org-split-string old "[ \t]"))))
16048 (setq value (org-entry-protect-space value))
16049 (when (member value values)
16050 (setq values (delete value values))
16051 (org-entry-put pom property
16052 (mapconcat 'identity values " ")))))
16054 (defun org-entry-member-in-multivalued-property (pom property value)
16055 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16056 (let* ((old (org-entry-get pom property))
16057 (values (and old (org-split-string old "[ \t]"))))
16058 (setq value (org-entry-protect-space value))
16059 (member value values)))
16061 (defun org-entry-get-multivalued-property (pom property)
16062 "Return a list of values in a multivalued property."
16063 (let* ((value (org-entry-get pom property))
16064 (values (and value (org-split-string value "[ \t]"))))
16065 (mapcar 'org-entry-restore-space values)))
16067 (defun org-entry-put-multivalued-property (pom property &rest values)
16068 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16069 VALUES should be a list of strings. Spaces will be protected."
16070 (org-entry-put pom property
16071 (mapconcat 'org-entry-protect-space values " "))
16072 (let* ((value (org-entry-get pom property))
16073 (values (and value (org-split-string value "[ \t]"))))
16074 (mapcar 'org-entry-restore-space values)))
16076 (defun org-entry-protect-space (s)
16077 "Protect spaces and newline in string S."
16078 (while (string-match " " s)
16079 (setq s (replace-match "%20" t t s)))
16080 (while (string-match "\n" s)
16081 (setq s (replace-match "%0A" t t s)))
16084 (defun org-entry-restore-space (s)
16085 "Restore spaces and newline in string S."
16086 (while (string-match "%20" s)
16087 (setq s (replace-match " " t t s)))
16088 (while (string-match "%0A" s)
16089 (setq s (replace-match "\n" t t s)))
16092 (defvar org-entry-property-inherited-from (make-marker)
16093 "Marker pointing to the entry from where a property was inherited.
16094 Each call to `org-entry-get-with-inheritance' will set this marker to the
16095 location of the entry where the inheritance search matched. If there was
16096 no match, the marker will point nowhere.
16097 Note that also `org-entry-get' calls this function, if the INHERIT flag
16098 is set.")
16100 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16101 "Get PROPERTY of entry or content at point, search higher levels if needed.
16102 The search will stop at the first ancestor which has the property defined.
16103 If the value found is \"nil\", return nil to show that the property
16104 should be considered as undefined (this is the meaning of nil here).
16105 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16106 (move-marker org-entry-property-inherited-from nil)
16107 (org-with-wide-buffer
16108 (let (value)
16109 (catch 'exit
16110 (while t
16111 (let ((v (org-property--local-values property literal-nil)))
16112 (when v
16113 (setq value
16114 (concat (mapconcat #'identity (delq nil v) " ")
16115 (and value " ")
16116 value)))
16117 (cond
16118 ((car v)
16119 (org-back-to-heading t)
16120 (move-marker org-entry-property-inherited-from (point))
16121 (throw 'exit nil))
16122 ((org-up-heading-safe))
16124 (let ((global
16125 (cdr (or (assoc-string property org-file-properties t)
16126 (assoc-string property org-global-properties t)
16127 (assoc-string property org-global-properties-fixed t)))))
16128 (cond ((not global))
16129 (value (setq value (concat global " " value)))
16130 (t (setq value global))))
16131 (throw 'exit nil))))))
16132 (if literal-nil value (org-not-nil value)))))
16134 (defvar org-property-changed-functions nil
16135 "Hook called when the value of a property has changed.
16136 Each hook function should accept two arguments, the name of the property
16137 and the new value.")
16139 (defun org-entry-put (pom property value)
16140 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16142 If the value is nil, it is converted to the empty string. If it
16143 is not a string, an error is raised. Also raise an error on
16144 invalid property names.
16146 PROPERTY can be any regular property (see
16147 `org-special-properties'). It can also be \"TODO\",
16148 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16150 For the last two properties, VALUE may have any of the special
16151 values \"earlier\" and \"later\". The function then increases or
16152 decreases scheduled or deadline date by one day."
16153 (cond ((null value) (setq value ""))
16154 ((not (stringp value)) (error "Properties values should be strings"))
16155 ((not (org--valid-property-p property))
16156 (user-error "Invalid property name: \"%s\"" property)))
16157 (org-with-point-at pom
16158 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16159 (org-back-to-heading t)
16160 (org-with-limited-levels (org-back-to-heading t)))
16161 (let ((beg (point)))
16162 (cond
16163 ((equal property "TODO")
16164 (cond ((not (org-string-nw-p value)) (setq value 'none))
16165 ((not (member value org-todo-keywords-1))
16166 (user-error "\"%s\" is not a valid TODO state" value)))
16167 (org-todo value)
16168 (org-set-tags nil 'align))
16169 ((equal property "PRIORITY")
16170 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16171 (org-set-tags nil 'align))
16172 ((equal property "SCHEDULED")
16173 (forward-line)
16174 (if (and (looking-at-p org-planning-line-re)
16175 (re-search-forward
16176 org-scheduled-time-regexp (line-end-position) t))
16177 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16178 ((string= value "later") (org-timestamp-change 1 'day))
16179 ((string= value "") (org-schedule '(4)))
16180 (t (org-schedule nil value)))
16181 (if (member value '("earlier" "later" ""))
16182 (call-interactively #'org-schedule)
16183 (org-schedule nil value))))
16184 ((equal property "DEADLINE")
16185 (forward-line)
16186 (if (and (looking-at-p org-planning-line-re)
16187 (re-search-forward
16188 org-deadline-time-regexp (line-end-position) t))
16189 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16190 ((string= value "later") (org-timestamp-change 1 'day))
16191 ((string= value "") (org-deadline '(4)))
16192 (t (org-deadline nil value)))
16193 (if (member value '("earlier" "later" ""))
16194 (call-interactively #'org-deadline)
16195 (org-deadline nil value))))
16196 ((member property org-special-properties)
16197 (error "The %s property cannot be set with `org-entry-put'" property))
16199 (let* ((range (org-get-property-block beg 'force))
16200 (end (cdr range))
16201 (case-fold-search t))
16202 (goto-char (car range))
16203 (if (re-search-forward (org-re-property property nil t) end t)
16204 (progn (delete-region (match-beginning 0) (match-end 0))
16205 (goto-char (match-beginning 0)))
16206 (goto-char end)
16207 (insert "\n")
16208 (backward-char))
16209 (insert ":" property ":")
16210 (when value (insert " " value))
16211 (org-indent-line)))))
16212 (run-hook-with-args 'org-property-changed-functions property value)))
16214 (defun org-buffer-property-keys
16215 (&optional specials defaults columns ignore-malformed)
16216 "Get all property keys in the current buffer.
16218 When SPECIALS is non-nil, also list the special properties that
16219 reflect things like tags and TODO state.
16221 When DEFAULTS is non-nil, also include properties that has
16222 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16223 DESCRIPTION, LOCATION, and LOGGING and others.
16225 When COLUMNS in non-nil, also include property names given in
16226 COLUMN formats in the current buffer.
16228 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16229 automatically performed, such drawers will be silently ignored."
16230 (let ((case-fold-search t)
16231 (props (append
16232 (and specials org-special-properties)
16233 (and defaults (cons org-effort-property org-default-properties))
16234 nil)))
16235 (org-with-wide-buffer
16236 (goto-char (point-min))
16237 (while (re-search-forward org-property-start-re nil t)
16238 (let ((range (org-get-property-block)))
16239 (catch 'skip
16240 (unless range
16241 (when (and (not ignore-malformed)
16242 (not (org-before-first-heading-p))
16243 (y-or-n-p (format "Malformed drawer at %d, repair?"
16244 (line-beginning-position))))
16245 (org-get-property-block nil t))
16246 (throw 'skip nil))
16247 (goto-char (car range))
16248 (let ((begin (car range))
16249 (end (cdr range)))
16250 ;; Make sure that found property block is not located
16251 ;; before current point, as it would generate an infloop.
16252 ;; It can happen, for example, in the following
16253 ;; situation:
16255 ;; * Headline
16256 ;; :PROPERTIES:
16257 ;; ...
16258 ;; :END:
16259 ;; *************** Inlinetask
16260 ;; #+BEGIN_EXAMPLE
16261 ;; :PROPERTIES:
16262 ;; #+END_EXAMPLE
16264 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16265 (while (< (point) end)
16266 (let ((p (progn (looking-at org-property-re)
16267 (match-string-no-properties 2))))
16268 ;; Only add true property name, not extension symbol.
16269 (push (if (not (string-match-p "\\+\\'" p)) p
16270 (substring p 0 -1))
16271 props))
16272 (forward-line))))
16273 (outline-next-heading)))
16274 (when columns
16275 (goto-char (point-min))
16276 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16277 (let ((element (org-element-at-point)))
16278 (when (memq (org-element-type element) '(keyword node-property))
16279 (let ((value (org-element-property :value element))
16280 (start 0))
16281 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16282 (setq start (match-end 0))
16283 (let ((p (match-string-no-properties 1 value)))
16284 (unless (member-ignore-case p org-special-properties)
16285 (push p props))))))))))
16286 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16288 (defun org-property-values (key)
16289 "List all non-nil values of property KEY in current buffer."
16290 (org-with-wide-buffer
16291 (goto-char (point-min))
16292 (let ((case-fold-search t)
16293 (re (org-re-property key))
16294 values)
16295 (while (re-search-forward re nil t)
16296 (push (org-entry-get (point) key) values))
16297 (delete-dups values))))
16299 (defun org-insert-property-drawer ()
16300 "Insert a property drawer into the current entry."
16301 (org-with-wide-buffer
16302 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16303 (org-back-to-heading t)
16304 (org-with-limited-levels (org-back-to-heading t)))
16305 (forward-line)
16306 (when (looking-at-p org-planning-line-re) (forward-line))
16307 (unless (looking-at-p org-property-drawer-re)
16308 ;; Make sure we start editing a line from current entry, not from
16309 ;; next one. It prevents extending text properties or overlays
16310 ;; belonging to the latter.
16311 (when (bolp) (backward-char))
16312 (let ((begin (1+ (point)))
16313 (inhibit-read-only t))
16314 (insert "\n:PROPERTIES:\n:END:")
16315 (when (eobp) (insert "\n"))
16316 (org-indent-region begin (point))))))
16318 (defun org-insert-drawer (&optional arg drawer)
16319 "Insert a drawer at point.
16321 When optional argument ARG is non-nil, insert a property drawer.
16323 Optional argument DRAWER, when non-nil, is a string representing
16324 drawer's name. Otherwise, the user is prompted for a name.
16326 If a region is active, insert the drawer around that region
16327 instead.
16329 Point is left between drawer's boundaries."
16330 (interactive "P")
16331 (let* ((drawer (if arg "PROPERTIES"
16332 (or drawer (read-from-minibuffer "Drawer: ")))))
16333 (cond
16334 ;; With C-u, fall back on `org-insert-property-drawer'
16335 (arg (org-insert-property-drawer))
16336 ;; Check validity of suggested drawer's name.
16337 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16338 (user-error "Invalid drawer name"))
16339 ;; With an active region, insert a drawer at point.
16340 ((not (org-region-active-p))
16341 (progn
16342 (unless (bolp) (insert "\n"))
16343 (insert (format ":%s:\n\n:END:\n" drawer))
16344 (forward-line -2)))
16345 ;; Otherwise, insert the drawer at point
16347 (let ((rbeg (region-beginning))
16348 (rend (copy-marker (region-end))))
16349 (unwind-protect
16350 (progn
16351 (goto-char rbeg)
16352 (beginning-of-line)
16353 (when (save-excursion
16354 (re-search-forward org-outline-regexp-bol rend t))
16355 (user-error "Drawers cannot contain headlines"))
16356 ;; Position point at the beginning of the first
16357 ;; non-blank line in region. Insert drawer's opening
16358 ;; there, then indent it.
16359 (org-skip-whitespace)
16360 (beginning-of-line)
16361 (insert ":" drawer ":\n")
16362 (forward-line -1)
16363 (indent-for-tab-command)
16364 ;; Move point to the beginning of the first blank line
16365 ;; after the last non-blank line in region. Insert
16366 ;; drawer's closing, then indent it.
16367 (goto-char rend)
16368 (skip-chars-backward " \r\t\n")
16369 (insert "\n:END:")
16370 (deactivate-mark t)
16371 (indent-for-tab-command)
16372 (unless (eolp) (insert "\n")))
16373 ;; Clear marker, whatever the outcome of insertion is.
16374 (set-marker rend nil)))))))
16376 (defvar org-property-set-functions-alist nil
16377 "Property set function alist.
16378 Each entry should have the following format:
16380 (PROPERTY . READ-FUNCTION)
16382 The read function will be called with the same argument as
16383 `org-completing-read'.")
16385 (defun org-set-property-function (property)
16386 "Get the function that should be used to set PROPERTY.
16387 This is computed according to `org-property-set-functions-alist'."
16388 (or (cdr (assoc property org-property-set-functions-alist))
16389 'org-completing-read))
16391 (defun org-read-property-value (property)
16392 "Read PROPERTY value from user."
16393 (let* ((completion-ignore-case t)
16394 (allowed (org-property-get-allowed-values nil property 'table))
16395 (cur (org-entry-get nil property))
16396 (prompt (concat property " value"
16397 (if (and cur (string-match "\\S-" cur))
16398 (concat " [" cur "]") "") ": "))
16399 (set-function (org-set-property-function property))
16400 (val (if allowed
16401 (funcall set-function prompt allowed nil
16402 (not (get-text-property 0 'org-unrestricted
16403 (caar allowed))))
16404 (funcall set-function prompt
16405 (mapcar 'list (org-property-values property))
16406 nil nil "" nil cur))))
16407 (org-trim val)))
16409 (defvar org-last-set-property nil)
16410 (defvar org-last-set-property-value nil)
16411 (defun org-read-property-name ()
16412 "Read a property name."
16413 (let ((completion-ignore-case t)
16414 (default-prop (or (and (org-at-property-p)
16415 (match-string-no-properties 2))
16416 org-last-set-property)))
16417 (org-completing-read
16418 (concat "Property"
16419 (if default-prop (concat " [" default-prop "]") "")
16420 ": ")
16421 (mapcar #'list (org-buffer-property-keys nil t t))
16422 nil nil nil nil default-prop)))
16424 (defun org-set-property-and-value (use-last)
16425 "Allow to set [PROPERTY]: [value] direction from prompt.
16426 When use-default, don't even ask, just use the last
16427 \"[PROPERTY]: [value]\" string from the history."
16428 (interactive "P")
16429 (let* ((completion-ignore-case t)
16430 (pv (or (and use-last org-last-set-property-value)
16431 (org-completing-read
16432 "Enter a \"[Property]: [value]\" pair: "
16433 nil nil nil nil nil
16434 org-last-set-property-value)))
16435 prop val)
16436 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16437 (setq prop (match-string 1 pv)
16438 val (match-string 2 pv))
16439 (org-set-property prop val))))
16441 (defun org-set-property (property value)
16442 "In the current entry, set PROPERTY to VALUE.
16444 When called interactively, this will prompt for a property name, offering
16445 completion on existing and default properties. And then it will prompt
16446 for a value, offering completion either on allowed values (via an inherited
16447 xxx_ALL property) or on existing values in other instances of this property
16448 in the current file.
16450 Throw an error when trying to set a property with an invalid name."
16451 (interactive (list nil nil))
16452 (let ((property (or property (org-read-property-name))))
16453 ;; `org-entry-put' also makes the following check, but this one
16454 ;; avoids polluting `org-last-set-property' and
16455 ;; `org-last-set-property-value' needlessly.
16456 (unless (org--valid-property-p property)
16457 (user-error "Invalid property name: \"%s\"" property))
16458 (let ((value (or value (org-read-property-value property)))
16459 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16460 (setq org-last-set-property property)
16461 (setq org-last-set-property-value (concat property ": " value))
16462 ;; Possibly postprocess the inserted value:
16463 (when fn (setq value (funcall fn value)))
16464 (unless (equal (org-entry-get nil property) value)
16465 (org-entry-put nil property value)))))
16467 (defun org-find-property (property &optional value)
16468 "Find first entry in buffer that sets PROPERTY.
16470 When optional argument VALUE is non-nil, only consider an entry
16471 if it contains PROPERTY set to this value. If PROPERTY should be
16472 explicitly set to nil, use string \"nil\" for VALUE.
16474 Return position where the entry begins, or nil if there is no
16475 such entry. If narrowing is in effect, only search the visible
16476 part of the buffer."
16477 (save-excursion
16478 (goto-char (point-min))
16479 (let ((case-fold-search t)
16480 (re (org-re-property property nil (not value) value)))
16481 (catch 'exit
16482 (while (re-search-forward re nil t)
16483 (when (if value (org-at-property-p)
16484 (org-entry-get (point) property nil t))
16485 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16487 (defun org-delete-property (property)
16488 "In the current entry, delete PROPERTY."
16489 (interactive
16490 (let* ((completion-ignore-case t)
16491 (cat (org-entry-get (point) "CATEGORY"))
16492 (props0 (org-entry-properties nil 'standard))
16493 (props (if cat props0
16494 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16495 (prop (if (< 1 (length props))
16496 (completing-read "Property: " props nil t)
16497 (caar props))))
16498 (list prop)))
16499 (if (not property)
16500 (message "No property to delete in this entry")
16501 (org-entry-delete nil property)
16502 (message "Property \"%s\" deleted" property)))
16504 (defun org-delete-property-globally (property)
16505 "Remove PROPERTY globally, from all entries.
16506 This function ignores narrowing, if any."
16507 (interactive
16508 (let* ((completion-ignore-case t)
16509 (prop (completing-read
16510 "Globally remove property: "
16511 (mapcar #'list (org-buffer-property-keys)))))
16512 (list prop)))
16513 (org-with-wide-buffer
16514 (goto-char (point-min))
16515 (let ((count 0)
16516 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16517 (while (re-search-forward re nil t)
16518 (when (org-entry-delete (point) property) (cl-incf count)))
16519 (message "Property \"%s\" removed from %d entries" property count))))
16521 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16523 (defun org-compute-property-at-point ()
16524 "Compute the property at point.
16525 This looks for an enclosing column format, extracts the operator and
16526 then applies it to the property in the column format's scope."
16527 (interactive)
16528 (unless (org-at-property-p)
16529 (user-error "Not at a property"))
16530 (let ((prop (match-string-no-properties 2)))
16531 (org-columns-get-format-and-top-level)
16532 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16533 (user-error "No operator defined for property %s" prop))
16534 (org-columns-compute prop)))
16536 (defvar org-property-allowed-value-functions nil
16537 "Hook for functions supplying allowed values for a specific property.
16538 The functions must take a single argument, the name of the property, and
16539 return a flat list of allowed values. If \":ETC\" is one of
16540 the values, this means that these values are intended as defaults for
16541 completion, but that other values should be allowed too.
16542 The functions must return nil if they are not responsible for this
16543 property.")
16545 (defun org-property-get-allowed-values (pom property &optional table)
16546 "Get allowed values for the property PROPERTY.
16547 When TABLE is non-nil, return an alist that can directly be used for
16548 completion."
16549 (let (vals)
16550 (cond
16551 ((equal property "TODO")
16552 (setq vals (org-with-point-at pom
16553 (append org-todo-keywords-1 '("")))))
16554 ((equal property "PRIORITY")
16555 (let ((n org-lowest-priority))
16556 (while (>= n org-highest-priority)
16557 (push (char-to-string n) vals)
16558 (setq n (1- n)))))
16559 ((equal property "CATEGORY"))
16560 ((member property org-special-properties))
16561 ((setq vals (run-hook-with-args-until-success
16562 'org-property-allowed-value-functions property)))
16564 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16565 (when (and vals (string-match "\\S-" vals))
16566 (setq vals (car (read-from-string (concat "(" vals ")"))))
16567 (setq vals (mapcar (lambda (x)
16568 (cond ((stringp x) x)
16569 ((numberp x) (number-to-string x))
16570 ((symbolp x) (symbol-name x))
16571 (t "???")))
16572 vals)))))
16573 (when (member ":ETC" vals)
16574 (setq vals (remove ":ETC" vals))
16575 (org-add-props (car vals) '(org-unrestricted t)))
16576 (if table (mapcar 'list vals) vals)))
16578 (defun org-property-previous-allowed-value (&optional _previous)
16579 "Switch to the next allowed value for this property."
16580 (interactive)
16581 (org-property-next-allowed-value t))
16583 (defun org-property-next-allowed-value (&optional previous)
16584 "Switch to the next allowed value for this property."
16585 (interactive)
16586 (unless (org-at-property-p)
16587 (user-error "Not at a property"))
16588 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16589 (key (match-string 2))
16590 (value (match-string 3))
16591 (allowed (or (org-property-get-allowed-values (point) key)
16592 (and (member value '("[ ]" "[-]" "[X]"))
16593 '("[ ]" "[X]"))))
16594 (heading (save-match-data (nth 4 (org-heading-components))))
16595 nval)
16596 (unless allowed
16597 (user-error "Allowed values for this property have not been defined"))
16598 (when previous (setq allowed (reverse allowed)))
16599 (when (member value allowed)
16600 (setq nval (car (cdr (member value allowed)))))
16601 (setq nval (or nval (car allowed)))
16602 (when (equal nval value)
16603 (user-error "Only one allowed value for this property"))
16604 (org-at-property-p)
16605 (replace-match (concat " :" key ": " nval) t t)
16606 (org-indent-line)
16607 (beginning-of-line 1)
16608 (skip-chars-forward " \t")
16609 (when (equal prop org-effort-property)
16610 (org-refresh-property
16611 '((effort . identity)
16612 (effort-minutes . org-duration-string-to-minutes))
16613 nval)
16614 (when (string= org-clock-current-task heading)
16615 (setq org-clock-effort nval)
16616 (org-clock-update-mode-line)))
16617 (run-hook-with-args 'org-property-changed-functions key nval)))
16619 (defun org-find-olp (path &optional this-buffer)
16620 "Return a marker pointing to the entry at outline path OLP.
16621 If anything goes wrong, throw an error.
16622 You can wrap this call to catch the error like this:
16624 \(condition-case msg
16625 \(org-mobile-locate-entry (match-string 4))
16626 \(error (nth 1 msg)))
16628 The return value will then be either a string with the error message,
16629 or a marker if everything is OK.
16631 If THIS-BUFFER is set, the outline path does not contain a file,
16632 only headings."
16633 (let* ((file (if this-buffer buffer-file-name (pop path)))
16634 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16635 (level 1)
16636 (lmin 1)
16637 (lmax 1)
16638 end found flevel)
16639 (unless buffer (error "File not found :%s" file))
16640 (with-current-buffer buffer
16641 (org-with-wide-buffer
16642 (goto-char (point-min))
16643 (dolist (heading path)
16644 (let ((re (format org-complex-heading-regexp-format
16645 (regexp-quote heading)))
16646 (cnt 0))
16647 (while (re-search-forward re end t)
16648 (setq level (- (match-end 1) (match-beginning 1)))
16649 (when (and (>= level lmin) (<= level lmax))
16650 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16651 (when (= cnt 0)
16652 (error "Heading not found on level %d: %s" lmax heading))
16653 (when (> cnt 1)
16654 (error "Heading not unique on level %d: %s" lmax heading))
16655 (goto-char found)
16656 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16657 (setq end (save-excursion (org-end-of-subtree t t)))))
16658 (when (org-at-heading-p)
16659 (point-marker))))))
16661 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16662 "Find node HEADING in BUFFER.
16663 Return a marker to the heading if it was found, or nil if not.
16664 If POS-ONLY is set, return just the position instead of a marker.
16666 The heading text must match exact, but it may have a TODO keyword,
16667 a priority cookie and tags in the standard locations."
16668 (with-current-buffer (or buffer (current-buffer))
16669 (org-with-wide-buffer
16670 (goto-char (point-min))
16671 (let (case-fold-search)
16672 (when (re-search-forward
16673 (format org-complex-heading-regexp-format
16674 (regexp-quote heading)) nil t)
16675 (if pos-only
16676 (match-beginning 0)
16677 (move-marker (make-marker) (match-beginning 0))))))))
16679 (defun org-find-exact-heading-in-directory (heading &optional dir)
16680 "Find Org node headline HEADING in all .org files in directory DIR.
16681 When the target headline is found, return a marker to this location."
16682 (let ((files (directory-files (or dir default-directory)
16683 t "\\`[^.#].*\\.org\\'"))
16684 visiting m buffer)
16685 (catch 'found
16686 (dolist (file files)
16687 (message "trying %s" file)
16688 (setq visiting (org-find-base-buffer-visiting file))
16689 (setq buffer (or visiting (find-file-noselect file)))
16690 (setq m (org-find-exact-headline-in-buffer
16691 heading buffer))
16692 (when (and (not m) (not visiting)) (kill-buffer buffer))
16693 (and m (throw 'found m))))))
16695 (defun org-find-entry-with-id (ident)
16696 "Locate the entry that contains the ID property with exact value IDENT.
16697 IDENT can be a string, a symbol or a number, this function will search for
16698 the string representation of it.
16699 Return the position where this entry starts, or nil if there is no such entry."
16700 (interactive "sID: ")
16701 (let ((id (cond
16702 ((stringp ident) ident)
16703 ((symbolp ident) (symbol-name ident))
16704 ((numberp ident) (number-to-string ident))
16705 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16706 (org-with-wide-buffer (org-find-property "ID" id))))
16708 ;;;; Timestamps
16710 (defvar org-last-changed-timestamp nil)
16711 (defvar org-last-inserted-timestamp nil
16712 "The last time stamp inserted with `org-insert-time-stamp'.")
16713 (defvar org-ts-what) ; dynamically scoped parameter
16715 (defun org-time-stamp (arg &optional inactive)
16716 "Prompt for a date/time and insert a time stamp.
16718 If the user specifies a time like HH:MM or if this command is
16719 called with at least one prefix argument, the time stamp contains
16720 the date and the time. Otherwise, only the date is included.
16722 All parts of a date not specified by the user are filled in from
16723 the timestamp at point, if any, or the current date/time
16724 otherwise.
16726 If there is already a timestamp at the cursor, it is replaced.
16728 With two universal prefix arguments, insert an active timestamp
16729 with the current time without prompting the user.
16731 When called from lisp, the timestamp is inactive if INACTIVE is
16732 non-nil."
16733 (interactive "P")
16734 (let* ((ts (cond
16735 ((org-at-date-range-p t)
16736 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16737 ((org-at-timestamp-p t) (match-string 0))))
16738 ;; Default time is either the timestamp at point or today.
16739 ;; When entering a range, only the range start is considered.
16740 (default-time (if (not ts) (current-time)
16741 (apply #'encode-time (org-parse-time-string ts))))
16742 (default-input (and ts (org-get-compact-tod ts)))
16743 (repeater (and ts
16744 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16745 (match-string 0 ts)))
16746 org-time-was-given
16747 org-end-time-was-given
16748 (time
16749 (and (if (equal arg '(16)) (current-time)
16750 ;; Preserve `this-command' and `last-command'.
16751 (let ((this-command this-command)
16752 (last-command last-command))
16753 (org-read-date
16754 arg 'totime nil nil default-time default-input
16755 inactive))))))
16756 (cond
16757 ((and ts
16758 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16759 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16760 (insert "--")
16761 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16763 ;; Make sure we're on a timestamp. When in the middle of a date
16764 ;; range, move arbitrarily to range end.
16765 (unless (org-at-timestamp-p t)
16766 (skip-chars-forward "-")
16767 (org-at-timestamp-p t))
16768 (replace-match "")
16769 (setq org-last-changed-timestamp
16770 (org-insert-time-stamp
16771 time (or org-time-was-given arg)
16772 inactive nil nil (list org-end-time-was-given)))
16773 (when repeater
16774 (backward-char)
16775 (insert " " repeater)
16776 (setq org-last-changed-timestamp
16777 (concat (substring org-last-inserted-timestamp 0 -1)
16778 " " repeater ">")))
16779 (message "Timestamp updated"))
16780 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16781 (t (org-insert-time-stamp
16782 time (or org-time-was-given arg) inactive nil nil
16783 (list org-end-time-was-given))))))
16785 ;; FIXME: can we use this for something else, like computing time differences?
16786 (defun org-get-compact-tod (s)
16787 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16788 (let* ((t1 (match-string 1 s))
16789 (h1 (string-to-number (match-string 2 s)))
16790 (m1 (string-to-number (match-string 3 s)))
16791 (t2 (and (match-end 4) (match-string 5 s)))
16792 (h2 (and t2 (string-to-number (match-string 6 s))))
16793 (m2 (and t2 (string-to-number (match-string 7 s))))
16794 dh dm)
16795 (if (not t2)
16797 (setq dh (- h2 h1) dm (- m2 m1))
16798 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16799 (concat t1 "+" (number-to-string dh)
16800 (and (/= 0 dm) (format ":%02d" dm)))))))
16802 (defun org-time-stamp-inactive (&optional arg)
16803 "Insert an inactive time stamp.
16804 An inactive time stamp is enclosed in square brackets instead of angle
16805 brackets. It is inactive in the sense that it does not trigger agenda entries,
16806 does not link to the calendar and cannot be changed with the S-cursor keys.
16807 So these are more for recording a certain time/date."
16808 (interactive "P")
16809 (org-time-stamp arg 'inactive))
16811 (defvar org-date-ovl (make-overlay 1 1))
16812 (overlay-put org-date-ovl 'face 'org-date-selected)
16813 (delete-overlay org-date-ovl)
16815 (defvar org-ans1) ; dynamically scoped parameter
16816 (defvar org-ans2) ; dynamically scoped parameter
16818 (defvar org-plain-time-of-day-regexp) ; defined below
16820 (defvar org-overriding-default-time nil) ; dynamically scoped
16821 (defvar org-read-date-overlay nil)
16822 (defvar org-dcst nil) ; dynamically scoped
16823 (defvar org-read-date-history nil)
16824 (defvar org-read-date-final-answer nil)
16825 (defvar org-read-date-analyze-futurep nil)
16826 (defvar org-read-date-analyze-forced-year nil)
16827 (defvar org-read-date-inactive)
16829 (defvar org-read-date-minibuffer-local-map
16830 (let* ((map (make-sparse-keymap)))
16831 (set-keymap-parent map minibuffer-local-map)
16832 (org-defkey map (kbd ".")
16833 (lambda () (interactive)
16834 ;; Are we at the beginning of the prompt?
16835 (if (looking-back "^[^:]+: "
16836 (let ((inhibit-field-text-motion t))
16837 (line-beginning-position)))
16838 (org-eval-in-calendar '(calendar-goto-today))
16839 (insert "."))))
16840 (org-defkey map (kbd "C-.")
16841 (lambda () (interactive)
16842 (org-eval-in-calendar '(calendar-goto-today))))
16843 (org-defkey map [(meta shift left)]
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-backward-month 1))))
16846 (org-defkey map [(meta shift right)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-forward-month 1))))
16849 (org-defkey map [(meta shift up)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-backward-year 1))))
16852 (org-defkey map [(meta shift down)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-forward-year 1))))
16855 (org-defkey map [?\e (shift left)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-backward-month 1))))
16858 (org-defkey map [?\e (shift right)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-forward-month 1))))
16861 (org-defkey map [?\e (shift up)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-backward-year 1))))
16864 (org-defkey map [?\e (shift down)]
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(calendar-forward-year 1))))
16867 (org-defkey map [(shift up)]
16868 (lambda () (interactive)
16869 (org-eval-in-calendar '(calendar-backward-week 1))))
16870 (org-defkey map [(shift down)]
16871 (lambda () (interactive)
16872 (org-eval-in-calendar '(calendar-forward-week 1))))
16873 (org-defkey map [(shift left)]
16874 (lambda () (interactive)
16875 (org-eval-in-calendar '(calendar-backward-day 1))))
16876 (org-defkey map [(shift right)]
16877 (lambda () (interactive)
16878 (org-eval-in-calendar '(calendar-forward-day 1))))
16879 (org-defkey map "!"
16880 (lambda () (interactive)
16881 (org-eval-in-calendar '(diary-view-entries))
16882 (message "")))
16883 (org-defkey map ">"
16884 (lambda () (interactive)
16885 (org-eval-in-calendar '(calendar-scroll-left 1))))
16886 (org-defkey map "<"
16887 (lambda () (interactive)
16888 (org-eval-in-calendar '(calendar-scroll-right 1))))
16889 (org-defkey map "\C-v"
16890 (lambda () (interactive)
16891 (org-eval-in-calendar
16892 '(calendar-scroll-left-three-months 1))))
16893 (org-defkey map "\M-v"
16894 (lambda () (interactive)
16895 (org-eval-in-calendar
16896 '(calendar-scroll-right-three-months 1))))
16897 map)
16898 "Keymap for minibuffer commands when using `org-read-date'.")
16900 (defvar org-def)
16901 (defvar org-defdecode)
16902 (defvar org-with-time)
16904 (defvar calendar-setup) ; Dynamically scoped.
16905 (defun org-read-date (&optional with-time to-time from-string prompt
16906 default-time default-input inactive)
16907 "Read a date, possibly a time, and make things smooth for the user.
16908 The prompt will suggest to enter an ISO date, but you can also enter anything
16909 which will at least partially be understood by `parse-time-string'.
16910 Unrecognized parts of the date will default to the current day, month, year,
16911 hour and minute. If this command is called to replace a timestamp at point,
16912 or to enter the second timestamp of a range, the default time is taken
16913 from the existing stamp. Furthermore, the command prefers the future,
16914 so if you are giving a date where the year is not given, and the day-month
16915 combination is already past in the current year, it will assume you
16916 mean next year. For details, see the manual. A few examples:
16918 3-2-5 --> 2003-02-05
16919 feb 15 --> currentyear-02-15
16920 2/15 --> currentyear-02-15
16921 sep 12 9 --> 2009-09-12
16922 12:45 --> today 12:45
16923 22 sept 0:34 --> currentyear-09-22 0:34
16924 12 --> currentyear-currentmonth-12
16925 Fri --> nearest Friday after today
16926 -Tue --> last Tuesday
16927 etc.
16929 Furthermore you can specify a relative date by giving, as the *first* thing
16930 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16931 change in days weeks, months, years.
16932 With a single plus or minus, the date is relative to today. With a double
16933 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16934 +4d --> four days from today
16935 +4 --> same as above
16936 +2w --> two weeks from today
16937 ++5 --> five days from default date
16939 The function understands only English month and weekday abbreviations.
16941 While prompting, a calendar is popped up - you can also select the
16942 date with the mouse (button 1). The calendar shows a period of three
16943 months. To scroll it to other months, use the keys `>' and `<'.
16944 If you don't like the calendar, turn it off with
16945 (setq org-read-date-popup-calendar nil)
16947 With optional argument TO-TIME, the date will immediately be converted
16948 to an internal time.
16949 With an optional argument WITH-TIME, the prompt will suggest to
16950 also insert a time. Note that when WITH-TIME is not set, you can
16951 still enter a time, and this function will inform the calling routine
16952 about this change. The calling routine may then choose to change the
16953 format used to insert the time stamp into the buffer to include the time.
16954 With optional argument FROM-STRING, read from this string instead from
16955 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16956 the time/date that is used for everything that is not specified by the
16957 user."
16958 (require 'parse-time)
16959 (let* ((org-with-time with-time)
16960 (org-time-stamp-rounding-minutes
16961 (if (equal org-with-time '(16))
16962 '(0 0)
16963 org-time-stamp-rounding-minutes))
16964 (org-dcst org-display-custom-times)
16965 (ct (org-current-time))
16966 (org-def (or org-overriding-default-time default-time ct))
16967 (org-defdecode (decode-time org-def))
16968 (cur-frame (selected-frame))
16969 (mouse-autoselect-window nil) ; Don't let the mouse jump
16970 (calendar-setup
16971 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16972 (calendar-move-hook nil)
16973 (calendar-view-diary-initially-flag nil)
16974 (calendar-view-holidays-initially-flag nil)
16975 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16976 ;; Rationalize `org-def' and `org-defdecode', if required.
16977 (when (< (nth 2 org-defdecode) org-extend-today-until)
16978 (setf (nth 2 org-defdecode) -1)
16979 (setf (nth 1 org-defdecode) 59)
16980 (setq org-def (apply #'encode-time org-defdecode))
16981 (setq org-defdecode (decode-time org-def)))
16982 (let* ((timestr (format-time-string
16983 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16984 org-def))
16985 (prompt (concat (if prompt (concat prompt " ") "")
16986 (format "Date+time [%s]: " timestr))))
16987 (cond
16988 (from-string (setq ans from-string))
16989 (org-read-date-popup-calendar
16990 (save-excursion
16991 (save-window-excursion
16992 (calendar)
16993 (when (eq calendar-setup 'calendar-only)
16994 (setq cal-frame
16995 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16996 (select-frame cal-frame))
16997 (org-eval-in-calendar '(setq cursor-type nil) t)
16998 (unwind-protect
16999 (progn
17000 (calendar-forward-day (- (time-to-days org-def)
17001 (calendar-absolute-from-gregorian
17002 (calendar-current-date))))
17003 (org-eval-in-calendar nil t)
17004 (let* ((old-map (current-local-map))
17005 (map (copy-keymap calendar-mode-map))
17006 (minibuffer-local-map
17007 (copy-keymap org-read-date-minibuffer-local-map)))
17008 (org-defkey map (kbd "RET") 'org-calendar-select)
17009 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17010 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17011 (unwind-protect
17012 (progn
17013 (use-local-map map)
17014 (setq org-read-date-inactive inactive)
17015 (add-hook 'post-command-hook 'org-read-date-display)
17016 (setq org-ans0
17017 (read-string prompt
17018 default-input
17019 'org-read-date-history
17020 nil))
17021 ;; org-ans0: from prompt
17022 ;; org-ans1: from mouse click
17023 ;; org-ans2: from calendar motion
17024 (setq ans
17025 (concat org-ans0 " " (or org-ans1 org-ans2))))
17026 (remove-hook 'post-command-hook 'org-read-date-display)
17027 (use-local-map old-map)
17028 (when org-read-date-overlay
17029 (delete-overlay org-read-date-overlay)
17030 (setq org-read-date-overlay nil)))))
17031 (bury-buffer "*Calendar*")
17032 (when cal-frame
17033 (delete-frame cal-frame)
17034 (select-frame-set-input-focus cur-frame))))))
17036 (t ; Naked prompt only
17037 (unwind-protect
17038 (setq ans (read-string prompt default-input
17039 'org-read-date-history timestr))
17040 (when org-read-date-overlay
17041 (delete-overlay org-read-date-overlay)
17042 (setq org-read-date-overlay nil))))))
17044 (setq final (org-read-date-analyze ans org-def org-defdecode))
17046 (when org-read-date-analyze-forced-year
17047 (message "Year was forced into %s"
17048 (if org-read-date-force-compatible-dates
17049 "compatible range (1970-2037)"
17050 "range representable on this machine"))
17051 (ding))
17053 ;; One round trip to get rid of 34th of August and stuff like that....
17054 (setq final (decode-time (apply 'encode-time final)))
17056 (setq org-read-date-final-answer ans)
17058 (if to-time
17059 (apply 'encode-time final)
17060 (if (and (boundp 'org-time-was-given) org-time-was-given)
17061 (format "%04d-%02d-%02d %02d:%02d"
17062 (nth 5 final) (nth 4 final) (nth 3 final)
17063 (nth 2 final) (nth 1 final))
17064 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17066 (defun org-read-date-display ()
17067 "Display the current date prompt interpretation in the minibuffer."
17068 (when org-read-date-display-live
17069 (when org-read-date-overlay
17070 (delete-overlay org-read-date-overlay))
17071 (when (minibufferp (current-buffer))
17072 (save-excursion
17073 (end-of-line 1)
17074 (while (not (equal (buffer-substring
17075 (max (point-min) (- (point) 4)) (point))
17076 " "))
17077 (insert " ")))
17078 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17079 " " (or org-ans1 org-ans2)))
17080 (org-end-time-was-given nil)
17081 (f (org-read-date-analyze ans org-def org-defdecode))
17082 (fmts (if org-dcst
17083 org-time-stamp-custom-formats
17084 org-time-stamp-formats))
17085 (fmt (if (or org-with-time
17086 (and (boundp 'org-time-was-given) org-time-was-given))
17087 (cdr fmts)
17088 (car fmts)))
17089 (txt (format-time-string fmt (apply 'encode-time f)))
17090 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17091 (txt (concat "=> " txt)))
17092 (when (and org-end-time-was-given
17093 (string-match org-plain-time-of-day-regexp txt))
17094 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17095 org-end-time-was-given
17096 (substring txt (match-end 0)))))
17097 (when org-read-date-analyze-futurep
17098 (setq txt (concat txt " (=>F)")))
17099 (setq org-read-date-overlay
17100 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17101 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17103 (defun org-read-date-analyze (ans def defdecode)
17104 "Analyze the combined answer of the date prompt."
17105 ;; FIXME: cleanup and comment
17106 ;; Pass `current-time' result to `decode-time' (instead of calling
17107 ;; without arguments) so that only `current-time' has to be
17108 ;; overriden in tests.
17109 (let ((org-def def)
17110 (org-defdecode defdecode)
17111 (nowdecode (decode-time (current-time)))
17112 delta deltan deltaw deltadef year month day
17113 hour minute second wday pm h2 m2 tl wday1
17114 iso-year iso-weekday iso-week iso-date futurep kill-year)
17115 (setq org-read-date-analyze-futurep nil
17116 org-read-date-analyze-forced-year nil)
17117 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17118 (setq ans "+0"))
17120 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17121 (setq ans (replace-match "" t t ans)
17122 deltan (car delta)
17123 deltaw (nth 1 delta)
17124 deltadef (nth 2 delta)))
17126 ;; Check if there is an iso week date in there. If yes, store the
17127 ;; info and postpone interpreting it until the rest of the parsing
17128 ;; is done.
17129 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17130 (setq iso-year (when (match-end 1)
17131 (org-small-year-to-year
17132 (string-to-number (match-string 1 ans))))
17133 iso-weekday (when (match-end 3)
17134 (string-to-number (match-string 3 ans)))
17135 iso-week (string-to-number (match-string 2 ans)))
17136 (setq ans (replace-match "" t t ans)))
17138 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17139 (when (string-match
17140 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17141 (setq year (if (match-end 2)
17142 (string-to-number (match-string 2 ans))
17143 (progn (setq kill-year t)
17144 (string-to-number (format-time-string "%Y"))))
17145 month (string-to-number (match-string 3 ans))
17146 day (string-to-number (match-string 4 ans)))
17147 (setq year (org-small-year-to-year year))
17148 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17149 t nil ans)))
17151 ;; Help matching dotted european dates
17152 (when (string-match
17153 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17154 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17155 (setq kill-year t)
17156 (string-to-number (format-time-string "%Y")))
17157 day (string-to-number (match-string 1 ans))
17158 month (string-to-number (match-string 2 ans))
17159 ans (replace-match (format "%04d-%02d-%02d" year month day)
17160 t nil ans)))
17162 ;; Help matching american dates, like 5/30 or 5/30/7
17163 (when (string-match
17164 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17165 (setq year (if (match-end 4)
17166 (string-to-number (match-string 4 ans))
17167 (progn (setq kill-year t)
17168 (string-to-number (format-time-string "%Y"))))
17169 month (string-to-number (match-string 1 ans))
17170 day (string-to-number (match-string 2 ans)))
17171 (setq year (org-small-year-to-year year))
17172 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17173 t nil ans)))
17174 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17175 ;; If there is a time with am/pm, and *no* time without it, we convert
17176 ;; so that matching will be successful.
17177 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17178 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17179 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17180 (setq hour (string-to-number (match-string 1 ans))
17181 minute (if (match-end 3)
17182 (string-to-number (match-string 3 ans))
17184 pm (equal ?p
17185 (string-to-char (downcase (match-string 4 ans)))))
17186 (if (and (= hour 12) (not pm))
17187 (setq hour 0)
17188 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17189 (setq ans (replace-match (format "%02d:%02d" hour minute)
17190 t t ans))))
17192 ;; Check if a time range is given as a duration
17193 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17194 (setq hour (string-to-number (match-string 1 ans))
17195 h2 (+ hour (string-to-number (match-string 3 ans)))
17196 minute (string-to-number (match-string 2 ans))
17197 m2 (+ minute (if (match-end 5) (string-to-number
17198 (match-string 5 ans))0)))
17199 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17200 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17201 t t ans)))
17203 ;; Check if there is a time range
17204 (when (boundp 'org-end-time-was-given)
17205 (setq org-time-was-given nil)
17206 (when (and (string-match org-plain-time-of-day-regexp ans)
17207 (match-end 8))
17208 (setq org-end-time-was-given (match-string 8 ans))
17209 (setq ans (concat (substring ans 0 (match-beginning 7))
17210 (substring ans (match-end 7))))))
17212 (setq tl (parse-time-string ans)
17213 day (or (nth 3 tl) (nth 3 org-defdecode))
17214 month
17215 (cond ((nth 4 tl))
17216 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17217 ;; Day was specified. Make sure DAY+MONTH
17218 ;; combination happens in the future.
17219 ((nth 3 tl)
17220 (setq futurep t)
17221 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17222 (nth 4 nowdecode)))
17223 (t (nth 4 org-defdecode)))
17224 year
17225 (cond ((and (not kill-year) (nth 5 tl)))
17226 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17227 ;; Month was guessed in the future and is at least
17228 ;; equal to NOWDECODE's. Fix year accordingly.
17229 (futurep
17230 (if (or (> month (nth 4 nowdecode))
17231 (>= day (nth 3 nowdecode)))
17232 (nth 5 nowdecode)
17233 (1+ (nth 5 nowdecode))))
17234 ;; Month was specified. Make sure MONTH+YEAR
17235 ;; combination happens in the future.
17236 ((nth 4 tl)
17237 (setq futurep t)
17238 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17239 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17240 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17241 (t (nth 5 nowdecode))))
17242 (t (nth 5 org-defdecode)))
17243 hour (or (nth 2 tl) (nth 2 org-defdecode))
17244 minute (or (nth 1 tl) (nth 1 org-defdecode))
17245 second (or (nth 0 tl) 0)
17246 wday (nth 6 tl))
17248 (when (and (eq org-read-date-prefer-future 'time)
17249 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17250 (equal day (nth 3 nowdecode))
17251 (equal month (nth 4 nowdecode))
17252 (equal year (nth 5 nowdecode))
17253 (nth 2 tl)
17254 (or (< (nth 2 tl) (nth 2 nowdecode))
17255 (and (= (nth 2 tl) (nth 2 nowdecode))
17256 (nth 1 tl)
17257 (< (nth 1 tl) (nth 1 nowdecode)))))
17258 (setq day (1+ day)
17259 futurep t))
17261 ;; Special date definitions below
17262 (cond
17263 (iso-week
17264 ;; There was an iso week
17265 (require 'cal-iso)
17266 (setq futurep nil)
17267 (setq year (or iso-year year)
17268 day (or iso-weekday wday 1)
17269 wday nil ; to make sure that the trigger below does not match
17270 iso-date (calendar-gregorian-from-absolute
17271 (calendar-iso-to-absolute
17272 (list iso-week day year))))
17273 ; FIXME: Should we also push ISO weeks into the future?
17274 ; (when (and org-read-date-prefer-future
17275 ; (not iso-year)
17276 ; (< (calendar-absolute-from-gregorian iso-date)
17277 ; (time-to-days (current-time))))
17278 ; (setq year (1+ year)
17279 ; iso-date (calendar-gregorian-from-absolute
17280 ; (calendar-iso-to-absolute
17281 ; (list iso-week day year)))))
17282 (setq month (car iso-date)
17283 year (nth 2 iso-date)
17284 day (nth 1 iso-date)))
17285 (deltan
17286 (setq futurep nil)
17287 (unless deltadef
17288 ;; Pass `current-time' result to `decode-time' (instead of
17289 ;; calling without arguments) so that only `current-time' has
17290 ;; to be overriden in tests.
17291 (let ((now (decode-time (current-time))))
17292 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17293 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17294 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17295 ((equal deltaw "m") (setq month (+ month deltan)))
17296 ((equal deltaw "y") (setq year (+ year deltan)))))
17297 ((and wday (not (nth 3 tl)))
17298 ;; Weekday was given, but no day, so pick that day in the week
17299 ;; on or after the derived date.
17300 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17301 (unless (equal wday wday1)
17302 (setq day (+ day (% (- wday wday1 -7) 7))))))
17303 (when (and (boundp 'org-time-was-given)
17304 (nth 2 tl))
17305 (setq org-time-was-given t))
17306 (when (< year 100) (setq year (+ 2000 year)))
17307 ;; Check of the date is representable
17308 (if org-read-date-force-compatible-dates
17309 (progn
17310 (when (< year 1970)
17311 (setq year 1970 org-read-date-analyze-forced-year t))
17312 (when (> year 2037)
17313 (setq year 2037 org-read-date-analyze-forced-year t)))
17314 (condition-case nil
17315 (ignore (encode-time second minute hour day month year))
17316 (error
17317 (setq year (nth 5 org-defdecode))
17318 (setq org-read-date-analyze-forced-year t))))
17319 (setq org-read-date-analyze-futurep futurep)
17320 (list second minute hour day month year)))
17322 (defvar parse-time-weekdays)
17323 (defun org-read-date-get-relative (s today default)
17324 "Check string S for special relative date string.
17325 TODAY and DEFAULT are internal times, for today and for a default.
17326 Return shift list (N what def-flag)
17327 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17328 N is the number of WHATs to shift.
17329 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17330 the DEFAULT date rather than TODAY."
17331 (require 'parse-time)
17332 (when (and
17333 (string-match
17334 (concat
17335 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17336 "\\([0-9]+\\)?"
17337 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17338 "\\([ \t]\\|$\\)") s)
17339 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17340 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17341 (string-to-char (substring (match-string 1 s) -1))
17342 ?+))
17343 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17344 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17345 (what (if (match-end 3) (match-string 3 s) "d"))
17346 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17347 (date (if rel default today))
17348 (wday (nth 6 (decode-time date)))
17349 delta)
17350 (if wday1
17351 (progn
17352 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17353 (when (= delta 0) (setq delta 7))
17354 (when (= dir ?-)
17355 (setq delta (- delta 7))
17356 (when (= delta 0) (setq delta -7)))
17357 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17358 (list delta "d" rel))
17359 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17361 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17362 "Turn a user-specified date into the internal representation.
17363 The internal representation needed by the calendar is (month day year).
17364 This is a wrapper to handle the brain-dead convention in calendar that
17365 user function argument order change dependent on argument order."
17366 (pcase calendar-date-style
17367 (`american (list arg1 arg2 arg3))
17368 (`european (list arg2 arg1 arg3))
17369 (`iso (list arg2 arg3 arg1))))
17371 (defun org-eval-in-calendar (form &optional keepdate)
17372 "Eval FORM in the calendar window and return to current window.
17373 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17374 (let ((sf (selected-frame))
17375 (sw (selected-window)))
17376 (select-window (get-buffer-window "*Calendar*" t))
17377 (eval form)
17378 (when (and (not keepdate) (calendar-cursor-to-date))
17379 (let* ((date (calendar-cursor-to-date))
17380 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17381 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17382 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17383 (select-window sw)
17384 (select-frame-set-input-focus sf)))
17386 (defun org-calendar-select ()
17387 "Return to `org-read-date' with the date currently selected.
17388 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17389 (interactive)
17390 (when (calendar-cursor-to-date)
17391 (let* ((date (calendar-cursor-to-date))
17392 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17393 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17394 (when (active-minibuffer-window) (exit-minibuffer))))
17396 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17397 "Insert a date stamp for the date given by the internal TIME.
17398 See `format-time-string' for the format of TIME.
17399 WITH-HM means use the stamp format that includes the time of the day.
17400 INACTIVE means use square brackets instead of angular ones, so that the
17401 stamp will not contribute to the agenda.
17402 PRE and POST are optional strings to be inserted before and after the
17403 stamp.
17404 The command returns the inserted time stamp."
17405 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17406 stamp)
17407 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17408 (insert-before-markers (or pre ""))
17409 (when (listp extra)
17410 (setq extra (car extra))
17411 (if (and (stringp extra)
17412 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17413 (setq extra (format "-%02d:%02d"
17414 (string-to-number (match-string 1 extra))
17415 (string-to-number (match-string 2 extra))))
17416 (setq extra nil)))
17417 (when extra
17418 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17419 (insert-before-markers (setq stamp (format-time-string fmt time)))
17420 (insert-before-markers (or post ""))
17421 (setq org-last-inserted-timestamp stamp)))
17423 (defun org-toggle-time-stamp-overlays ()
17424 "Toggle the use of custom time stamp formats."
17425 (interactive)
17426 (setq org-display-custom-times (not org-display-custom-times))
17427 (unless org-display-custom-times
17428 (let ((p (point-min)) (bmp (buffer-modified-p)))
17429 (while (setq p (next-single-property-change p 'display))
17430 (when (and (get-text-property p 'display)
17431 (eq (get-text-property p 'face) 'org-date))
17432 (remove-text-properties
17433 p (setq p (next-single-property-change p 'display))
17434 '(display t))))
17435 (set-buffer-modified-p bmp)))
17436 (org-restart-font-lock)
17437 (setq org-table-may-need-update t)
17438 (if org-display-custom-times
17439 (message "Time stamps are overlaid with custom format")
17440 (message "Time stamp overlays removed")))
17442 (defun org-display-custom-time (beg end)
17443 "Overlay modified time stamp format over timestamp between BEG and END."
17444 (let* ((ts (buffer-substring beg end))
17445 t1 w1 with-hm tf time str w2 (off 0))
17446 (save-match-data
17447 (setq t1 (org-parse-time-string ts t))
17448 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17449 (setq off (- (match-end 0) (match-beginning 0)))))
17450 (setq end (- end off))
17451 (setq w1 (- end beg)
17452 with-hm (and (nth 1 t1) (nth 2 t1))
17453 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17454 time (org-fix-decoded-time t1)
17455 str (org-add-props
17456 (format-time-string
17457 (substring tf 1 -1) (apply 'encode-time time))
17458 nil 'mouse-face 'highlight)
17459 w2 (length str))
17460 (unless (= w2 w1)
17461 (add-text-properties (1+ beg) (+ 2 beg)
17462 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17463 (put-text-property beg end 'display str)))
17465 (defun org-fix-decoded-time (time)
17466 "Set 0 instead of nil for the first 6 elements of time.
17467 Don't touch the rest."
17468 (let ((n 0))
17469 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17471 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17472 "Difference between TIMESTAMP-STRING and now in days.
17473 If SECONDS is non-nil, return the difference in seconds."
17474 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17475 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17476 (funcall fdiff (current-time)))))
17478 (defun org-deadline-close-p (timestamp-string &optional ndays)
17479 "Is the time in TIMESTAMP-STRING close to the current date?"
17480 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17481 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17482 (not (org-entry-is-done-p))))
17484 (defun org-get-wdays (ts &optional delay zero-delay)
17485 "Get the deadline lead time appropriate for timestring TS.
17486 When DELAY is non-nil, get the delay time for scheduled items
17487 instead of the deadline lead time. When ZERO-DELAY is non-nil
17488 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17489 don't try to find the delay cookie in the scheduled timestamp."
17490 (let ((tv (if delay org-scheduled-delay-days
17491 org-deadline-warning-days)))
17492 (cond
17493 ((or (and delay (< tv 0))
17494 (and delay zero-delay (<= tv 0))
17495 (and (not delay) (<= tv 0)))
17496 ;; Enforce this value no matter what
17497 (- tv))
17498 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17499 ;; lead time is specified.
17500 (floor (* (string-to-number (match-string 1 ts))
17501 (cdr (assoc (match-string 2 ts)
17502 '(("d" . 1) ("w" . 7)
17503 ("m" . 30.4) ("y" . 365.25)
17504 ("h" . 0.041667)))))))
17505 ;; go for the default.
17506 (t tv))))
17508 (defun org-calendar-select-mouse (ev)
17509 "Return to `org-read-date' with the date currently selected.
17510 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17511 (interactive "e")
17512 (mouse-set-point ev)
17513 (when (calendar-cursor-to-date)
17514 (let* ((date (calendar-cursor-to-date))
17515 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17516 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17517 (when (active-minibuffer-window) (exit-minibuffer))))
17519 (defun org-check-deadlines (ndays)
17520 "Check if there are any deadlines due or past due.
17521 A deadline is considered due if it happens within `org-deadline-warning-days'
17522 days from today's date. If the deadline appears in an entry marked DONE,
17523 it is not shown. The prefix arg NDAYS can be used to test that many
17524 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17525 (interactive "P")
17526 (let* ((org-warn-days
17527 (cond
17528 ((equal ndays '(4)) 100000)
17529 (ndays (prefix-numeric-value ndays))
17530 (t (abs org-deadline-warning-days))))
17531 (case-fold-search nil)
17532 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17533 (callback
17534 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17535 (message "%d deadlines past-due or due within %d days"
17536 (org-occur regexp nil callback)
17537 org-warn-days)))
17539 (defsubst org-re-timestamp (type)
17540 "Return a regexp for timestamp TYPE.
17541 Allowed values for TYPE are:
17543 all: all timestamps
17544 active: only active timestamps (<...>)
17545 inactive: only inactive timestamps ([...])
17546 scheduled: only scheduled timestamps
17547 deadline: only deadline timestamps
17548 closed: only closed time-stamps
17550 When TYPE is nil, fall back on returning a regexp that matches
17551 both scheduled and deadline timestamps."
17552 (cl-case type
17553 (all org-ts-regexp-both)
17554 (active org-ts-regexp)
17555 (inactive org-ts-regexp-inactive)
17556 (scheduled org-scheduled-time-regexp)
17557 (deadline org-deadline-time-regexp)
17558 (closed org-closed-time-regexp)
17559 (otherwise
17560 (concat "\\<"
17561 (regexp-opt (list org-deadline-string org-scheduled-string))
17562 " *<\\([^>]+\\)>"))))
17564 (defun org-check-before-date (d)
17565 "Check if there are deadlines or scheduled entries before date D."
17566 (interactive (list (org-read-date)))
17567 (let* ((case-fold-search nil)
17568 (regexp (org-re-timestamp org-ts-type))
17569 (ts-type org-ts-type)
17570 (callback
17571 (lambda ()
17572 (let ((match (match-string 1)))
17573 (and (if (memq ts-type '(active inactive all))
17574 (eq (org-element-type (save-excursion
17575 (backward-char)
17576 (org-element-context)))
17577 'timestamp)
17578 (org-at-planning-p))
17579 (time-less-p
17580 (org-time-string-to-time match)
17581 (org-time-string-to-time d)))))))
17582 (message "%d entries before %s"
17583 (org-occur regexp nil callback)
17584 d)))
17586 (defun org-check-after-date (d)
17587 "Check if there are deadlines or scheduled entries after date D."
17588 (interactive (list (org-read-date)))
17589 (let* ((case-fold-search nil)
17590 (regexp (org-re-timestamp org-ts-type))
17591 (ts-type org-ts-type)
17592 (callback
17593 (lambda ()
17594 (let ((match (match-string 1)))
17595 (and (if (memq ts-type '(active inactive all))
17596 (eq (org-element-type (save-excursion
17597 (backward-char)
17598 (org-element-context)))
17599 'timestamp)
17600 (org-at-planning-p))
17601 (not (time-less-p
17602 (org-time-string-to-time match)
17603 (org-time-string-to-time d))))))))
17604 (message "%d entries after %s"
17605 (org-occur regexp nil callback)
17606 d)))
17608 (defun org-check-dates-range (start-date end-date)
17609 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17610 (interactive (list (org-read-date nil nil nil "Range starts")
17611 (org-read-date nil nil nil "Range end")))
17612 (let ((case-fold-search nil)
17613 (regexp (org-re-timestamp org-ts-type))
17614 (callback
17615 (let ((type org-ts-type))
17616 (lambda ()
17617 (let ((match (match-string 1)))
17618 (and
17619 (if (memq type '(active inactive all))
17620 (eq (org-element-type (save-excursion
17621 (backward-char)
17622 (org-element-context)))
17623 'timestamp)
17624 (org-at-planning-p))
17625 (not (time-less-p
17626 (org-time-string-to-time match)
17627 (org-time-string-to-time start-date)))
17628 (time-less-p
17629 (org-time-string-to-time match)
17630 (org-time-string-to-time end-date))))))))
17631 (message "%d entries between %s and %s"
17632 (org-occur regexp nil callback) start-date end-date)))
17634 (defun org-evaluate-time-range (&optional to-buffer)
17635 "Evaluate a time range by computing the difference between start and end.
17636 Normally the result is just printed in the echo area, but with prefix arg
17637 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17638 If the time range is actually in a table, the result is inserted into the
17639 next column.
17640 For time difference computation, a year is assumed to be exactly 365
17641 days in order to avoid rounding problems."
17642 (interactive "P")
17644 (org-clock-update-time-maybe)
17645 (save-excursion
17646 (unless (org-at-date-range-p t)
17647 (goto-char (point-at-bol))
17648 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17649 (unless (org-at-date-range-p t)
17650 (user-error "Not at a time-stamp range, and none found in current line")))
17651 (let* ((ts1 (match-string 1))
17652 (ts2 (match-string 2))
17653 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17654 (match-end (match-end 0))
17655 (time1 (org-time-string-to-time ts1))
17656 (time2 (org-time-string-to-time ts2))
17657 (t1 (float-time time1))
17658 (t2 (float-time time2))
17659 (diff (abs (- t2 t1)))
17660 (negative (< (- t2 t1) 0))
17661 ;; (ys (floor (* 365 24 60 60)))
17662 (ds (* 24 60 60))
17663 (hs (* 60 60))
17664 (fy "%dy %dd %02d:%02d")
17665 (fy1 "%dy %dd")
17666 (fd "%dd %02d:%02d")
17667 (fd1 "%dd")
17668 (fh "%02d:%02d")
17669 y d h m align)
17670 (if havetime
17671 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17673 d (floor (/ diff ds)) diff (mod diff ds)
17674 h (floor (/ diff hs)) diff (mod diff hs)
17675 m (floor (/ diff 60)))
17676 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17678 d (floor (+ (/ diff ds) 0.5))
17679 h 0 m 0))
17680 (if (not to-buffer)
17681 (message "%s" (org-make-tdiff-string y d h m))
17682 (if (org-at-table-p)
17683 (progn
17684 (goto-char match-end)
17685 (setq align t)
17686 (and (looking-at " *|") (goto-char (match-end 0))))
17687 (goto-char match-end))
17688 (when (looking-at
17689 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17690 (replace-match ""))
17691 (when negative (insert " -"))
17692 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17693 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17694 (insert " " (format fh h m))))
17695 (when align (org-table-align))
17696 (message "Time difference inserted")))))
17698 (defun org-make-tdiff-string (y d h m)
17699 (let ((fmt "")
17700 (l nil))
17701 (when (> y 0)
17702 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17703 (push y l))
17704 (when (> d 0)
17705 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17706 (push d l))
17707 (when (> h 0)
17708 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17709 (push h l))
17710 (when (> m 0)
17711 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17712 (push m l))
17713 (apply 'format fmt (nreverse l))))
17715 (defun org-time-string-to-time (s &optional buffer pos)
17716 "Convert a timestamp string into internal time."
17717 (condition-case errdata
17718 (apply 'encode-time (org-parse-time-string s))
17719 (error (error "Bad timestamp `%s'%s\nError was: %s"
17720 s (if (not (and buffer pos))
17722 (format-message " at %d in buffer `%s'" pos buffer))
17723 (cdr errdata)))))
17725 (defun org-time-string-to-seconds (s)
17726 "Convert a timestamp string to a number of seconds."
17727 (float-time (org-time-string-to-time s)))
17729 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17731 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17732 "Convert time stamp S to an absolute day number.
17734 If DAYNR in non-nil, and there is a specifier for a cyclic time
17735 stamp, get the closest date to DAYNR. If PREFER is
17736 `past' (respectively `future') return a date past (respectively
17737 after) or equal to DAYNR.
17739 POS is the location of time stamp S, as a buffer position in
17740 BUFFER.
17742 Diary sexp timestamps are matched against DAYNR, when non-nil.
17743 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17744 signalled."
17745 (cond
17746 ((string-match "\\`%%\\((.*)\\)" s)
17747 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17748 ;; only able to match individual dates. If it fails, raise an
17749 ;; error.
17750 (if (and daynr
17751 (org-diary-sexp-entry
17752 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17753 daynr
17754 (signal 'org-diary-sexp-no-match (list s))))
17755 ((and daynr show-all) (org-closest-date s daynr prefer))
17756 (t (time-to-days
17757 (condition-case errdata
17758 (apply #'encode-time (org-parse-time-string s))
17759 (error (error "Bad timestamp `%s'%s\nError was: %s"
17761 (if (not (and buffer pos)) ""
17762 (format-message " at %d in buffer `%s'" pos buffer))
17763 (cdr errdata))))))))
17765 (defun org-days-to-iso-week (days)
17766 "Return the iso week number."
17767 (require 'cal-iso)
17768 (car (calendar-iso-from-absolute days)))
17770 (defun org-small-year-to-year (year)
17771 "Convert 2-digit years into 4-digit years.
17772 YEAR is expanded into one of the 30 next years, if possible, or
17773 into a past one. Any year larger than 99 is returned unchanged."
17774 (if (>= year 100) year
17775 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17776 (century (/ current 100))
17777 (offset (- year (% current 100))))
17778 (cond ((> offset 30) (+ (* (1- century) 100) year))
17779 ((> offset -70) (+ (* century 100) year))
17780 (t (+ (* (1+ century) 100) year))))))
17782 (defun org-time-from-absolute (d)
17783 "Return the time corresponding to date D.
17784 D may be an absolute day number, or a calendar-type list (month day year)."
17785 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17786 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17788 (defvar org-agenda-current-date)
17789 (defun org-calendar-holiday ()
17790 "List of holidays, for Diary display in Org mode."
17791 (require 'holidays)
17792 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17793 (and hl (mapconcat #'identity hl "; "))))
17795 (defun org-diary-sexp-entry (sexp entry d)
17796 "Process a SEXP diary ENTRY for date D."
17797 (require 'diary-lib)
17798 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17799 ;; dynamically.
17800 (let* ((sexp `(let ((entry ,entry)
17801 (date ',d))
17802 ,(car (read-from-string sexp))))
17803 (result (if calendar-debug-sexp (eval sexp)
17804 (condition-case nil
17805 (eval sexp)
17806 (error
17807 (beep)
17808 (message "Bad sexp at line %d in %s: %s"
17809 (org-current-line)
17810 (buffer-file-name) sexp)
17811 (sleep-for 2))))))
17812 (cond ((stringp result) (split-string result "; "))
17813 ((and (consp result)
17814 (not (consp (cdr result)))
17815 (stringp (cdr result))) (cdr result))
17816 ((and (consp result)
17817 (stringp (car result))) result)
17818 (result entry))))
17820 (defun org-diary-to-ical-string (frombuf)
17821 "Get iCalendar entries from diary entries in buffer FROMBUF.
17822 This uses the icalendar.el library."
17823 (let* ((tmpdir temporary-file-directory)
17824 (tmpfile (make-temp-name
17825 (expand-file-name "orgics" tmpdir)))
17826 buf rtn b e)
17827 (with-current-buffer frombuf
17828 (icalendar-export-region (point-min) (point-max) tmpfile)
17829 (setq buf (find-buffer-visiting tmpfile))
17830 (set-buffer buf)
17831 (goto-char (point-min))
17832 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17833 (setq b (match-beginning 0)))
17834 (goto-char (point-max))
17835 (when (re-search-backward "^END:VEVENT" nil t)
17836 (setq e (match-end 0)))
17837 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17838 (kill-buffer buf)
17839 (delete-file tmpfile)
17840 rtn))
17842 (defun org-closest-date (start current prefer)
17843 "Return closest date to CURRENT starting from START.
17845 CURRENT and START are both time stamps.
17847 When PREFER is `past', return a date that is either CURRENT or
17848 past. When PREFER is `future', return a date that is either
17849 CURRENT or future.
17851 Only time stamps with a repeater are modified. Any other time
17852 stamp stay unchanged. In any case, return value is an absolute
17853 day number."
17854 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17855 ;; No repeater. Do not shift time stamp.
17856 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17857 (let ((value (string-to-number (match-string 1 start)))
17858 (type (match-string 2 start)))
17859 (if (= 0 value)
17860 ;; Repeater with a 0-value is considered as void.
17861 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17862 (let* ((base (org-date-to-gregorian start))
17863 (target (org-date-to-gregorian current))
17864 (sday (calendar-absolute-from-gregorian base))
17865 (cday (calendar-absolute-from-gregorian target))
17866 n1 n2)
17867 ;; If START is already past CURRENT, just return START.
17868 (if (<= cday sday) sday
17869 ;; Compute closest date before (N1) and closest date past
17870 ;; (N2) CURRENT.
17871 (pcase type
17872 ("h"
17873 (let ((missing-hours
17874 (mod (+ (- (* 24 (- cday sday))
17875 (nth 2 (org-parse-time-string start)))
17876 org-extend-today-until)
17877 value)))
17878 (setf n1 (if (= missing-hours 0) cday
17879 (- cday (1+ (/ missing-hours 24)))))
17880 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17881 ((or "d" "w")
17882 (let ((value (if (equal type "w") (* 7 value) value)))
17883 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17884 (setf n2 (+ n1 value))))
17885 ("m"
17886 (let* ((add-months
17887 (lambda (d n)
17888 ;; Add N months to gregorian date D, i.e.,
17889 ;; a list (MONTH DAY YEAR). Return a valid
17890 ;; gregorian date.
17891 (let ((m (+ (nth 0 d) n)))
17892 (list (mod m 12)
17893 (nth 1 d)
17894 (+ (/ m 12) (nth 2 d))))))
17895 (months ; Complete months to TARGET.
17896 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17897 (- (nth 0 target) (nth 0 base))
17898 ;; If START's day is greater than
17899 ;; TARGET's, remove incomplete month.
17900 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17901 value)
17902 value))
17903 (before (funcall add-months base months)))
17904 (setf n1 (calendar-absolute-from-gregorian before))
17905 (setf n2
17906 (calendar-absolute-from-gregorian
17907 (funcall add-months before value)))))
17909 (let* ((d (nth 1 base))
17910 (m (nth 0 base))
17911 (y (nth 2 base))
17912 (years ; Complete years to TARGET.
17913 (* (/ (- (nth 2 target)
17915 ;; If START's month and day are
17916 ;; greater than TARGET's, remove
17917 ;; incomplete year.
17918 (if (or (> (nth 0 target) m)
17919 (and (= (nth 0 target) m)
17920 (> (nth 1 target) d)))
17923 value)
17924 value))
17925 (before (list m d (+ y years))))
17926 (setf n1 (calendar-absolute-from-gregorian before))
17927 (setf n2 (calendar-absolute-from-gregorian
17928 (list m d (+ (nth 2 before) value)))))))
17929 ;; Handle PREFER parameter, if any.
17930 (cond
17931 ((eq prefer 'past) (if (= cday n2) n2 n1))
17932 ((eq prefer 'future) (if (= cday n1) n1 n2))
17933 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17935 (defun org-date-to-gregorian (d)
17936 "Turn any specification of date D into a Gregorian date for the calendar."
17937 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17938 ((and (listp d) (= (length d) 3)) d)
17939 ((stringp d)
17940 (let ((d (org-parse-time-string d)))
17941 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17942 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17944 (defun org-parse-time-string (s &optional nodefault)
17945 "Parse the standard Org time string.
17946 This should be a lot faster than the normal `parse-time-string'.
17947 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17948 hour and minute fields will be nil if not given."
17949 (cond ((string-match org-ts-regexp0 s)
17950 (list 0
17951 (when (or (match-beginning 8) (not nodefault))
17952 (string-to-number (or (match-string 8 s) "0")))
17953 (when (or (match-beginning 7) (not nodefault))
17954 (string-to-number (or (match-string 7 s) "0")))
17955 (string-to-number (match-string 4 s))
17956 (string-to-number (match-string 3 s))
17957 (string-to-number (match-string 2 s))
17958 nil nil nil))
17959 ((string-match "^<[^>]+>$" s)
17960 (decode-time (seconds-to-time (org-matcher-time s))))
17961 (t (error "Not a standard Org time string: %s" s))))
17963 (defun org-timestamp-up (&optional arg)
17964 "Increase the date item at the cursor by one.
17965 If the cursor is on the year, change the year. If it is on the month,
17966 the day or the time, change that.
17967 With prefix ARG, change by that many units."
17968 (interactive "p")
17969 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17971 (defun org-timestamp-down (&optional arg)
17972 "Decrease the date item at the cursor by one.
17973 If the cursor is on the year, change the year. If it is on the month,
17974 the day or the time, change that.
17975 With prefix ARG, change by that many units."
17976 (interactive "p")
17977 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17979 (defun org-timestamp-up-day (&optional arg)
17980 "Increase the date in the time stamp by one day.
17981 With prefix ARG, change that many days."
17982 (interactive "p")
17983 (if (and (not (org-at-timestamp-p t))
17984 (org-at-heading-p))
17985 (org-todo 'up)
17986 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17988 (defun org-timestamp-down-day (&optional arg)
17989 "Decrease the date in the time stamp by one day.
17990 With prefix ARG, change that many days."
17991 (interactive "p")
17992 (if (and (not (org-at-timestamp-p t))
17993 (org-at-heading-p))
17994 (org-todo 'down)
17995 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17997 (defun org-at-timestamp-p (&optional inactive-ok)
17998 "Non-nil if point is inside a timestamp.
18000 When optional argument INACTIVE-OK is non-nil, also consider
18001 inactive timestamps.
18003 When this function returns a non-nil value, match data is set
18004 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18005 INACTIVE-OK."
18006 (interactive)
18007 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18008 (pos (point))
18009 (ans (or (looking-at tsr)
18010 (save-excursion
18011 (skip-chars-backward "^[<\n\r\t")
18012 (when (> (point) (point-min)) (backward-char 1))
18013 (and (looking-at tsr)
18014 (> (- (match-end 0) pos) -1))))))
18015 (and ans
18016 (boundp 'org-ts-what)
18017 (setq org-ts-what
18018 (cond
18019 ((= pos (match-beginning 0)) 'bracket)
18020 ;; Point is considered to be "on the bracket" whether
18021 ;; it's really on it or right after it.
18022 ((= pos (1- (match-end 0))) 'bracket)
18023 ((= pos (match-end 0)) 'after)
18024 ((org-pos-in-match-range pos 2) 'year)
18025 ((org-pos-in-match-range pos 3) 'month)
18026 ((org-pos-in-match-range pos 7) 'hour)
18027 ((org-pos-in-match-range pos 8) 'minute)
18028 ((or (org-pos-in-match-range pos 4)
18029 (org-pos-in-match-range pos 5)) 'day)
18030 ((and (> pos (or (match-end 8) (match-end 5)))
18031 (< pos (match-end 0)))
18032 (- pos (or (match-end 8) (match-end 5))))
18033 (t 'day))))
18034 ans))
18036 (defun org-toggle-timestamp-type ()
18037 "Toggle the type (<active> or [inactive]) of a time stamp."
18038 (interactive)
18039 (when (org-at-timestamp-p t)
18040 (let ((beg (match-beginning 0)) (end (match-end 0))
18041 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18042 (save-excursion
18043 (goto-char beg)
18044 (while (re-search-forward "[][<>]" end t)
18045 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18046 t t)))
18047 (message "Timestamp is now %sactive"
18048 (if (equal (char-after beg) ?<) "" "in")))))
18050 (defun org-at-clock-log-p nil
18051 "Is the cursor on the clock log line?"
18052 (save-excursion
18053 (move-beginning-of-line 1)
18054 (looking-at org-clock-line-re)))
18056 (defvar org-clock-history) ; defined in org-clock.el
18057 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18058 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18059 "Change the date in the time stamp at point.
18060 The date will be changed by N times WHAT. WHAT can be `day', `month',
18061 `year', `minute', `second'. If WHAT is not given, the cursor position
18062 in the timestamp determines what will be changed.
18063 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18064 (let ((origin (point)) origin-cat
18065 with-hm inactive
18066 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18067 org-ts-what
18068 extra rem
18069 ts time time0 fixnext clrgx)
18070 (unless (org-at-timestamp-p t)
18071 (user-error "Not at a timestamp"))
18072 (if (and (not what) (eq org-ts-what 'bracket))
18073 (org-toggle-timestamp-type)
18074 ;; Point isn't on brackets. Remember the part of the time-stamp
18075 ;; the point was in. Indeed, size of time-stamps may change,
18076 ;; but point must be kept in the same category nonetheless.
18077 (setq origin-cat org-ts-what)
18078 (when (and (not what) (not (eq org-ts-what 'day))
18079 org-display-custom-times
18080 (get-text-property (point) 'display)
18081 (not (get-text-property (1- (point)) 'display)))
18082 (setq org-ts-what 'day))
18083 (setq org-ts-what (or what org-ts-what)
18084 inactive (= (char-after (match-beginning 0)) ?\[)
18085 ts (match-string 0))
18086 (replace-match "")
18087 (when (string-match
18088 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18090 (setq extra (match-string 1 ts))
18091 (when suppress-tmp-delay
18092 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18093 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18094 (setq with-hm t))
18095 (setq time0 (org-parse-time-string ts))
18096 (when (and updown
18097 (eq org-ts-what 'minute)
18098 (not current-prefix-arg))
18099 ;; This looks like s-up and s-down. Change by one rounding step.
18100 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18101 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18102 (setcar (cdr time0) (+ (nth 1 time0)
18103 (if (> n 0) (- rem) (- dm rem))))))
18104 (setq time
18105 (apply #'encode-time
18106 (or (car time0) 0)
18107 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18108 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18109 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18110 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18111 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18112 (nthcdr 6 time0)))
18113 (when (and (member org-ts-what '(hour minute))
18114 extra
18115 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18116 (setq extra (org-modify-ts-extra
18117 extra
18118 (if (eq org-ts-what 'hour) 2 5)
18119 n dm)))
18120 (when (integerp org-ts-what)
18121 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18122 (when (eq what 'calendar)
18123 (let ((cal-date (org-get-date-from-calendar)))
18124 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18125 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18126 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18127 (setcar time0 (or (car time0) 0))
18128 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18129 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18130 (setq time (apply 'encode-time time0))))
18131 ;; Insert the new time-stamp, and ensure point stays in the same
18132 ;; category as before (i.e. not after the last position in that
18133 ;; category).
18134 (let ((pos (point)))
18135 ;; Stay before inserted string. `save-excursion' is of no use.
18136 (setq org-last-changed-timestamp
18137 (org-insert-time-stamp time with-hm inactive nil nil extra))
18138 (goto-char pos))
18139 (save-match-data
18140 (looking-at org-ts-regexp3)
18141 (goto-char (cond
18142 ;; `day' category ends before `hour' if any, or at
18143 ;; the end of the day name.
18144 ((eq origin-cat 'day)
18145 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18146 ((eq origin-cat 'hour) (min (match-end 7) origin))
18147 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18148 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18149 ;; `year' and `month' have both fixed size: point
18150 ;; couldn't have moved into another part.
18151 (t origin))))
18152 ;; Update clock if on a CLOCK line.
18153 (org-clock-update-time-maybe)
18154 ;; Maybe adjust the closest clock in `org-clock-history'
18155 (when org-clock-adjust-closest
18156 (if (not (and (org-at-clock-log-p)
18157 (< 1 (length (delq nil (mapcar 'marker-position
18158 org-clock-history))))))
18159 (message "No clock to adjust")
18160 (cond ((save-excursion ; fix previous clock?
18161 (re-search-backward org-ts-regexp0 nil t)
18162 (looking-back (concat org-clock-string " \\[")
18163 (line-beginning-position)))
18164 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18165 ((save-excursion ; fix next clock?
18166 (re-search-backward org-ts-regexp0 nil t)
18167 (looking-at (concat org-ts-regexp0 "\\] =>")))
18168 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18169 (save-window-excursion
18170 ;; Find closest clock to point, adjust the previous/next one in history
18171 (let* ((p (save-excursion (org-back-to-heading t)))
18172 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18173 (clfixnth
18174 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18175 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18176 (if (not clfixpos)
18177 (message "No clock to adjust")
18178 (save-excursion
18179 (org-goto-marker-or-bmk clfixpos)
18180 (org-show-subtree)
18181 (when (re-search-forward clrgx nil t)
18182 (goto-char (match-beginning 1))
18183 (let (org-clock-adjust-closest)
18184 (org-timestamp-change n org-ts-what updown))
18185 (message "Clock adjusted in %s for heading: %s"
18186 (file-name-nondirectory (buffer-file-name))
18187 (org-get-heading t t)))))))))
18188 ;; Try to recenter the calendar window, if any.
18189 (when (and org-calendar-follow-timestamp-change
18190 (get-buffer-window "*Calendar*" t)
18191 (memq org-ts-what '(day month year)))
18192 (org-recenter-calendar (time-to-days time))))))
18194 (defun org-modify-ts-extra (s pos n dm)
18195 "Change the different parts of the lead-time and repeat fields in timestamp."
18196 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18197 ng h m new rem)
18198 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18199 (cond
18200 ((or (org-pos-in-match-range pos 2)
18201 (org-pos-in-match-range pos 3))
18202 (setq m (string-to-number (match-string 3 s))
18203 h (string-to-number (match-string 2 s)))
18204 (if (org-pos-in-match-range pos 2)
18205 (setq h (+ h n))
18206 (setq n (* dm (with-no-warnings (signum n))))
18207 (unless (= 0 (setq rem (% m dm)))
18208 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18209 (setq m (+ m n)))
18210 (when (< m 0) (setq m (+ m 60) h (1- h)))
18211 (when (> m 59) (setq m (- m 60) h (1+ h)))
18212 (setq h (mod h 24))
18213 (setq ng 1 new (format "-%02d:%02d" h m)))
18214 ((org-pos-in-match-range pos 6)
18215 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18216 ((org-pos-in-match-range pos 5)
18217 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18219 ((org-pos-in-match-range pos 9)
18220 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18221 ((org-pos-in-match-range pos 8)
18222 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18224 (when ng
18225 (setq s (concat
18226 (substring s 0 (match-beginning ng))
18228 (substring s (match-end ng))))))
18231 (defun org-recenter-calendar (d)
18232 "If the calendar is visible, recenter it to date D."
18233 (let ((cwin (get-buffer-window "*Calendar*" t)))
18234 (when cwin
18235 (let ((calendar-move-hook nil))
18236 (with-selected-window cwin
18237 (calendar-goto-date
18238 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18240 (defun org-goto-calendar (&optional arg)
18241 "Go to the Emacs calendar at the current date.
18242 If there is a time stamp in the current line, go to that date.
18243 A prefix ARG can be used to force the current date."
18244 (interactive "P")
18245 (let ((tsr org-ts-regexp) diff
18246 (calendar-move-hook nil)
18247 (calendar-view-holidays-initially-flag nil)
18248 (calendar-view-diary-initially-flag nil))
18249 (when (or (org-at-timestamp-p)
18250 (save-excursion
18251 (beginning-of-line 1)
18252 (looking-at (concat ".*" tsr))))
18253 (let ((d1 (time-to-days (current-time)))
18254 (d2 (time-to-days
18255 (org-time-string-to-time (match-string 1)))))
18256 (setq diff (- d2 d1))))
18257 (calendar)
18258 (calendar-goto-today)
18259 (when (and diff (not arg)) (calendar-forward-day diff))))
18261 (defun org-get-date-from-calendar ()
18262 "Return a list (month day year) of date at point in calendar."
18263 (with-current-buffer "*Calendar*"
18264 (save-match-data
18265 (calendar-cursor-to-date))))
18267 (defun org-date-from-calendar ()
18268 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18269 If there is already a time stamp at the cursor position, update it."
18270 (interactive)
18271 (if (org-at-timestamp-p t)
18272 (org-timestamp-change 0 'calendar)
18273 (let ((cal-date (org-get-date-from-calendar)))
18274 (org-insert-time-stamp
18275 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18277 (defcustom org-effort-durations
18278 `(("min" . 1)
18279 ("h" . 60)
18280 ("d" . ,(* 60 8))
18281 ("w" . ,(* 60 8 5))
18282 ("m" . ,(* 60 8 5 4))
18283 ("y" . ,(* 60 8 5 40)))
18284 "Conversion factor to minutes for an effort modifier.
18286 Each entry has the form (MODIFIER . MINUTES).
18288 In an effort string, a number followed by MODIFIER is multiplied
18289 by the specified number of MINUTES to obtain an effort in
18290 minutes.
18292 For example, if the value of this variable is ((\"hours\" . 60)), then an
18293 effort string \"2hours\" is equivalent to 120 minutes."
18294 :group 'org-agenda
18295 :version "25.1"
18296 :package-version '(Org . "8.3")
18297 :type '(alist :key-type (string :tag "Modifier")
18298 :value-type (number :tag "Minutes")))
18300 (defun org-minutes-to-clocksum-string (m)
18301 "Format number of minutes as a clocksum string.
18302 The format is determined by `org-time-clocksum-format',
18303 `org-time-clocksum-use-fractional' and
18304 `org-time-clocksum-fractional-format' and
18305 `org-time-clocksum-use-effort-durations'."
18306 (let ((clocksum "")
18307 (m (round m)) ; Don't allow fractions of minutes
18308 h d w mo y fmt n)
18309 (setq h (if org-time-clocksum-use-effort-durations
18310 (cdr (assoc "h" org-effort-durations)) 60)
18311 d (if org-time-clocksum-use-effort-durations
18312 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18313 w (if org-time-clocksum-use-effort-durations
18314 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18315 mo (if org-time-clocksum-use-effort-durations
18316 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18317 y (if org-time-clocksum-use-effort-durations
18318 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18319 ;; fractional format
18320 (if org-time-clocksum-use-fractional
18321 (cond
18322 ;; single format string
18323 ((stringp org-time-clocksum-fractional-format)
18324 (format org-time-clocksum-fractional-format (/ m (float h))))
18325 ;; choice of fractional formats for different time units
18326 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18327 (> (/ (truncate m) (* y d h)) 0))
18328 (format fmt (/ m (* y d (float h)))))
18329 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18330 (> (/ (truncate m) (* mo d h)) 0))
18331 (format fmt (/ m (* mo d (float h)))))
18332 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18333 (> (/ (truncate m) (* w d h)) 0))
18334 (format fmt (/ m (* w d (float h)))))
18335 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18336 (> (/ (truncate m) (* d h)) 0))
18337 (format fmt (/ m (* d (float h)))))
18338 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18339 (> (/ (truncate m) h) 0))
18340 (format fmt (/ m (float h))))
18341 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18342 (format fmt m))
18343 ;; fall back to smallest time unit with a format
18344 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18345 (format fmt (/ m (float h))))
18346 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18347 (format fmt (/ m (* d (float h)))))
18348 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18349 (format fmt (/ m (* w d (float h)))))
18350 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18351 (format fmt (/ m (* mo d (float h)))))
18352 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18353 (format fmt (/ m (* y d (float h))))))
18354 ;; standard (non-fractional) format, with single format string
18355 (if (stringp org-time-clocksum-format)
18356 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18357 ;; separate formats components
18358 (and (setq fmt (plist-get org-time-clocksum-format :years))
18359 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18360 (plist-get org-time-clocksum-format :require-years))
18361 (setq clocksum (concat clocksum (format fmt n))
18362 m (- m (* n y d h))))
18363 (and (setq fmt (plist-get org-time-clocksum-format :months))
18364 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18365 (plist-get org-time-clocksum-format :require-months))
18366 (setq clocksum (concat clocksum (format fmt n))
18367 m (- m (* n mo d h))))
18368 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18369 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18370 (plist-get org-time-clocksum-format :require-weeks))
18371 (setq clocksum (concat clocksum (format fmt n))
18372 m (- m (* n w d h))))
18373 (and (setq fmt (plist-get org-time-clocksum-format :days))
18374 (or (> (setq n (/ (truncate m) (* d h))) 0)
18375 (plist-get org-time-clocksum-format :require-days))
18376 (setq clocksum (concat clocksum (format fmt n))
18377 m (- m (* n d h))))
18378 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18379 (or (> (setq n (/ (truncate m) h)) 0)
18380 (plist-get org-time-clocksum-format :require-hours))
18381 (setq clocksum (concat clocksum (format fmt n))
18382 m (- m (* n h))))
18383 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18384 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18385 (setq clocksum (concat clocksum (format fmt m))))
18386 ;; return formatted time duration
18387 clocksum))))
18389 (defun org-hours-to-clocksum-string (n)
18390 (org-minutes-to-clocksum-string (* n 60)))
18392 (defun org-hh:mm-string-to-minutes (s)
18393 "Convert a string H:MM to a number of minutes.
18394 If the string is just a number, interpret it as minutes.
18395 In fact, the first hh:mm or number in the string will be taken,
18396 there can be extra stuff in the string.
18397 If no number is found, the return value is 0."
18398 (cond
18399 ((integerp s) s)
18400 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18401 (+ (* (string-to-number (match-string 1 s)) 60)
18402 (string-to-number (match-string 2 s))))
18403 ((string-match "\\([0-9]+\\)" s)
18404 (string-to-number (match-string 1 s)))
18405 (t 0)))
18407 (defcustom org-image-actual-width t
18408 "Should we use the actual width of images when inlining them?
18410 When set to t, always use the image width.
18412 When set to a number, use imagemagick (when available) to set
18413 the image's width to this value.
18415 When set to a number in a list, try to get the width from any
18416 #+ATTR.* keyword if it matches a width specification like
18418 #+ATTR_HTML: :width 300px
18420 and fall back on that number if none is found.
18422 When set to nil, try to get the width from an #+ATTR.* keyword
18423 and fall back on the original width if none is found.
18425 This requires Emacs >= 24.1, build with imagemagick support."
18426 :group 'org-appearance
18427 :version "24.4"
18428 :package-version '(Org . "8.0")
18429 :type '(choice
18430 (const :tag "Use the image width" t)
18431 (integer :tag "Use a number of pixels")
18432 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18433 (const :tag "Use #+ATTR* or don't resize" nil)))
18435 (defcustom org-agenda-inhibit-startup nil
18436 "Inhibit startup when preparing agenda buffers.
18437 When this variable is t, the initialization of the Org agenda
18438 buffers is inhibited: e.g. the visibility state is not set, the
18439 tables are not re-aligned, etc."
18440 :type 'boolean
18441 :version "24.3"
18442 :group 'org-agenda)
18444 (defcustom org-agenda-ignore-properties nil
18445 "Avoid updating text properties when building the agenda.
18446 Properties are used to prepare buffers for effort estimates,
18447 appointments, statistics and subtree-local categories.
18448 If you don't use these in the agenda, you can add them to this
18449 list and agenda building will be a bit faster.
18450 The value is a list, with zero or more of the symbols `effort', `appt',
18451 `stats' or `category'."
18452 :type '(set :greedy t
18453 (const effort)
18454 (const appt)
18455 (const stats)
18456 (const category))
18457 :version "25.1"
18458 :package-version '(Org . "8.3")
18459 :group 'org-agenda)
18461 (defun org-duration-string-to-minutes (s &optional output-to-string)
18462 "Convert a duration string S to minutes.
18464 A bare number is interpreted as minutes, modifiers can be set by
18465 customizing `org-effort-durations' (which see).
18467 Entries containing a colon are interpreted as H:MM by
18468 `org-hh:mm-string-to-minutes'."
18469 (let ((result 0)
18470 (re (concat "\\([0-9.]+\\) *\\("
18471 (regexp-opt (mapcar 'car org-effort-durations))
18472 "\\)")))
18473 (while (string-match re s)
18474 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18475 (string-to-number (match-string 1 s))))
18476 (setq s (replace-match "" nil t s)))
18477 (setq result (floor result))
18478 (cl-incf result (org-hh:mm-string-to-minutes s))
18479 (if output-to-string (number-to-string result) result)))
18481 ;;;; Files
18483 (defun org-save-all-org-buffers ()
18484 "Save all Org buffers without user confirmation."
18485 (interactive)
18486 (message "Saving all Org buffers...")
18487 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18488 (when (featurep 'org-id) (org-id-locations-save))
18489 (message "Saving all Org buffers... done"))
18491 (defun org-revert-all-org-buffers ()
18492 "Revert all Org buffers.
18493 Prompt for confirmation when there are unsaved changes.
18494 Be sure you know what you are doing before letting this function
18495 overwrite your changes.
18497 This function is useful in a setup where one tracks org files
18498 with a version control system, to revert on one machine after pulling
18499 changes from another. I believe the procedure must be like this:
18501 1. M-x org-save-all-org-buffers
18502 2. Pull changes from the other machine, resolve conflicts
18503 3. M-x org-revert-all-org-buffers"
18504 (interactive)
18505 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18506 (user-error "Abort"))
18507 (save-excursion
18508 (save-window-excursion
18509 (dolist (b (buffer-list))
18510 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18511 (with-current-buffer b buffer-file-name))
18512 (pop-to-buffer-same-window b)
18513 (revert-buffer t 'no-confirm)))
18514 (when (and (featurep 'org-id) org-id-track-globally)
18515 (org-id-locations-load)))))
18517 ;;;; Agenda files
18519 ;;;###autoload
18520 (defun org-switchb (&optional arg)
18521 "Switch between Org buffers.
18523 With \\[universal-argument] prefix, restrict available buffers to files.
18525 With \\[universal-argument] \\[universal-argument] \
18526 prefix, restrict available buffers to agenda files."
18527 (interactive "P")
18528 (let ((blist (org-buffer-list
18529 (cond ((equal arg '(4)) 'files)
18530 ((equal arg '(16)) 'agenda)))))
18531 (pop-to-buffer-same-window
18532 (completing-read "Org buffer: "
18533 (mapcar #'list (mapcar #'buffer-name blist))
18534 nil t))))
18536 (defun org-buffer-list (&optional predicate exclude-tmp)
18537 "Return a list of Org buffers.
18538 PREDICATE can be `export', `files' or `agenda'.
18540 export restrict the list to Export buffers.
18541 files restrict the list to buffers visiting Org files.
18542 agenda restrict the list to buffers visiting agenda files.
18544 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18545 (let* ((bfn nil)
18546 (agenda-files (and (eq predicate 'agenda)
18547 (mapcar 'file-truename (org-agenda-files t))))
18548 (filter
18549 (cond
18550 ((eq predicate 'files)
18551 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18552 ((eq predicate 'export)
18553 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18554 ((eq predicate 'agenda)
18555 (lambda (b)
18556 (with-current-buffer b
18557 (and (derived-mode-p 'org-mode)
18558 (setq bfn (buffer-file-name b))
18559 (member (file-truename bfn) agenda-files)))))
18560 (t (lambda (b) (with-current-buffer b
18561 (or (derived-mode-p 'org-mode)
18562 (string-match "\\*Org .*Export"
18563 (buffer-name b)))))))))
18564 (delq nil
18565 (mapcar
18566 (lambda(b)
18567 (if (and (funcall filter b)
18568 (or (not exclude-tmp)
18569 (not (string-match "tmp" (buffer-name b)))))
18571 nil))
18572 (buffer-list)))))
18574 (defun org-agenda-files (&optional unrestricted archives)
18575 "Get the list of agenda files.
18576 Optional UNRESTRICTED means return the full list even if a restriction
18577 is currently in place.
18578 When ARCHIVES is t, include all archive files that are really being
18579 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18580 `org-agenda-archives-mode' is t."
18581 (let ((files
18582 (cond
18583 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18584 ((stringp org-agenda-files) (org-read-agenda-file-list))
18585 ((listp org-agenda-files) org-agenda-files)
18586 (t (error "Invalid value of `org-agenda-files'")))))
18587 (setq files (apply 'append
18588 (mapcar (lambda (f)
18589 (if (file-directory-p f)
18590 (directory-files
18591 f t org-agenda-file-regexp)
18592 (list f)))
18593 files)))
18594 (when org-agenda-skip-unavailable-files
18595 (setq files (delq nil
18596 (mapcar (function
18597 (lambda (file)
18598 (and (file-readable-p file) file)))
18599 files))))
18600 (when (or (eq archives t)
18601 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18602 (setq files (org-add-archive-files files)))
18603 files))
18605 (defun org-agenda-file-p (&optional file)
18606 "Return non-nil, if FILE is an agenda file.
18607 If FILE is omitted, use the file associated with the current
18608 buffer."
18609 (let ((fname (or file (buffer-file-name))))
18610 (and fname
18611 (member (file-truename fname)
18612 (mapcar #'file-truename (org-agenda-files t))))))
18614 (defun org-edit-agenda-file-list ()
18615 "Edit the list of agenda files.
18616 Depending on setup, this either uses customize to edit the variable
18617 `org-agenda-files', or it visits the file that is holding the list. In the
18618 latter case, the buffer is set up in a way that saving it automatically kills
18619 the buffer and restores the previous window configuration."
18620 (interactive)
18621 (if (stringp org-agenda-files)
18622 (let ((cw (current-window-configuration)))
18623 (find-file org-agenda-files)
18624 (setq-local org-window-configuration cw)
18625 (add-hook 'after-save-hook
18626 (lambda ()
18627 (set-window-configuration
18628 (prog1 org-window-configuration
18629 (kill-buffer (current-buffer))))
18630 (org-install-agenda-files-menu)
18631 (message "New agenda file list installed"))
18632 nil 'local)
18633 (message "%s" (substitute-command-keys
18634 "Edit list and finish with \\[save-buffer]")))
18635 (customize-variable 'org-agenda-files)))
18637 (defun org-store-new-agenda-file-list (list)
18638 "Set new value for the agenda file list and save it correctly."
18639 (if (stringp org-agenda-files)
18640 (let ((fe (org-read-agenda-file-list t)) b u)
18641 (while (setq b (find-buffer-visiting org-agenda-files))
18642 (kill-buffer b))
18643 (with-temp-file org-agenda-files
18644 (insert
18645 (mapconcat
18646 (lambda (f) ;; Keep un-expanded entries.
18647 (if (setq u (assoc f fe))
18648 (cdr u)
18650 list "\n")
18651 "\n")))
18652 (let ((org-mode-hook nil) (org-inhibit-startup t)
18653 (org-insert-mode-line-in-empty-file nil))
18654 (setq org-agenda-files list)
18655 (customize-save-variable 'org-agenda-files org-agenda-files))))
18657 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18658 "Read the list of agenda files from a file.
18659 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18660 filenames, used by `org-store-new-agenda-file-list' to write back
18661 un-expanded file names."
18662 (when (file-directory-p org-agenda-files)
18663 (error "`org-agenda-files' cannot be a single directory"))
18664 (when (stringp org-agenda-files)
18665 (with-temp-buffer
18666 (insert-file-contents org-agenda-files)
18667 (mapcar
18668 (lambda (f)
18669 (let ((e (expand-file-name (substitute-in-file-name f)
18670 org-directory)))
18671 (if pair-with-expansion
18672 (cons e f)
18673 e)))
18674 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18676 ;;;###autoload
18677 (defun org-cycle-agenda-files ()
18678 "Cycle through the files in `org-agenda-files'.
18679 If the current buffer visits an agenda file, find the next one in the list.
18680 If the current buffer does not, find the first agenda file."
18681 (interactive)
18682 (let* ((fs (or (org-agenda-files t)
18683 (user-error "No agenda files")))
18684 (files (copy-sequence fs))
18685 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18686 file)
18687 (when tcf
18688 (while (and (setq file (pop files))
18689 (not (equal (file-truename file) tcf)))))
18690 (find-file (car (or files fs)))
18691 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18693 (defun org-agenda-file-to-front (&optional to-end)
18694 "Move/add the current file to the top of the agenda file list.
18695 If the file is not present in the list, it is added to the front. If it is
18696 present, it is moved there. With optional argument TO-END, add/move to the
18697 end of the list."
18698 (interactive "P")
18699 (let ((org-agenda-skip-unavailable-files nil)
18700 (file-alist (mapcar (lambda (x)
18701 (cons (file-truename x) x))
18702 (org-agenda-files t)))
18703 (ctf (file-truename
18704 (or buffer-file-name
18705 (user-error "Please save the current buffer to a file"))))
18706 x had)
18707 (setq x (assoc ctf file-alist) had x)
18709 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18710 (if to-end
18711 (setq file-alist (append (delq x file-alist) (list x)))
18712 (setq file-alist (cons x (delq x file-alist))))
18713 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18714 (org-install-agenda-files-menu)
18715 (message "File %s to %s of agenda file list"
18716 (if had "moved" "added") (if to-end "end" "front"))))
18718 (defun org-remove-file (&optional file)
18719 "Remove current file from the list of files in variable `org-agenda-files'.
18720 These are the files which are being checked for agenda entries.
18721 Optional argument FILE means use this file instead of the current."
18722 (interactive)
18723 (let* ((org-agenda-skip-unavailable-files nil)
18724 (file (or file buffer-file-name
18725 (user-error "Current buffer does not visit a file")))
18726 (true-file (file-truename file))
18727 (afile (abbreviate-file-name file))
18728 (files (delq nil (mapcar
18729 (lambda (x)
18730 (unless (equal true-file
18731 (file-truename x))
18733 (org-agenda-files t)))))
18734 (if (not (= (length files) (length (org-agenda-files t))))
18735 (progn
18736 (org-store-new-agenda-file-list files)
18737 (org-install-agenda-files-menu)
18738 (message "Removed from Org Agenda list: %s" afile))
18739 (message "File was not in list: %s (not removed)" afile))))
18741 (defun org-file-menu-entry (file)
18742 (vector file (list 'find-file file) t))
18744 (defun org-check-agenda-file (file)
18745 "Make sure FILE exists. If not, ask user what to do."
18746 (unless (file-exists-p file)
18747 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18748 (abbreviate-file-name file))
18749 (let ((r (downcase (read-char-exclusive))))
18750 (cond
18751 ((equal r ?r)
18752 (org-remove-file file)
18753 (throw 'nextfile t))
18754 (t (user-error "Abort"))))))
18756 (defun org-get-agenda-file-buffer (file)
18757 "Get an agenda buffer visiting FILE.
18758 If the buffer needs to be created, add it to the list of buffers
18759 which might be released later."
18760 (let ((buf (org-find-base-buffer-visiting file)))
18761 (if buf
18762 buf ; just return it
18763 ;; Make a new buffer and remember it
18764 (setq buf (find-file-noselect file))
18765 (when buf (push buf org-agenda-new-buffers))
18766 buf)))
18768 (defun org-release-buffers (blist)
18769 "Release all buffers in list, asking the user for confirmation when needed.
18770 When a buffer is unmodified, it is just killed. When modified, it is saved
18771 \(if the user agrees) and then killed."
18772 (let (file)
18773 (dolist (buf blist)
18774 (setq file (buffer-file-name buf))
18775 (when (and (buffer-modified-p buf)
18776 file
18777 (y-or-n-p (format "Save file %s? " file)))
18778 (with-current-buffer buf (save-buffer)))
18779 (kill-buffer buf))))
18781 (defun org-agenda-prepare-buffers (files)
18782 "Create buffers for all agenda files, protect archived trees and comments."
18783 (interactive)
18784 (let ((pa '(:org-archived t))
18785 (pc '(:org-comment t))
18786 (pall '(:org-archived t :org-comment t))
18787 (inhibit-read-only t)
18788 (org-inhibit-startup org-agenda-inhibit-startup)
18789 (rea (concat ":" org-archive-tag ":"))
18790 re pos)
18791 (setq org-tag-alist-for-agenda nil
18792 org-tag-groups-alist-for-agenda nil)
18793 (save-excursion
18794 (save-restriction
18795 (dolist (file files)
18796 (catch 'nextfile
18797 (if (bufferp file)
18798 (set-buffer file)
18799 (org-check-agenda-file file)
18800 (set-buffer (org-get-agenda-file-buffer file)))
18801 (widen)
18802 (org-set-regexps-and-options 'tags-only)
18803 (setq pos (point))
18804 (or (memq 'category org-agenda-ignore-properties)
18805 (org-refresh-category-properties))
18806 (or (memq 'stats org-agenda-ignore-properties)
18807 (org-refresh-stats-properties))
18808 (or (memq 'effort org-agenda-ignore-properties)
18809 (org-refresh-effort-properties))
18810 (or (memq 'appt org-agenda-ignore-properties)
18811 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18812 (setq org-todo-keywords-for-agenda
18813 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18814 (setq org-done-keywords-for-agenda
18815 (append org-done-keywords-for-agenda org-done-keywords))
18816 (setq org-todo-keyword-alist-for-agenda
18817 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18818 (setq org-tag-alist-for-agenda
18819 (org-uniquify
18820 (append org-tag-alist-for-agenda
18821 org-current-tag-alist)))
18822 ;; Merge current file's tag groups into global
18823 ;; `org-tag-groups-alist-for-agenda'.
18824 (when org-group-tags
18825 (dolist (alist org-tag-groups-alist)
18826 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18827 (if old
18828 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18829 (push alist org-tag-groups-alist-for-agenda)))))
18830 (org-with-silent-modifications
18831 (save-excursion
18832 (remove-text-properties (point-min) (point-max) pall)
18833 (when org-agenda-skip-archived-trees
18834 (goto-char (point-min))
18835 (while (re-search-forward rea nil t)
18836 (when (org-at-heading-p t)
18837 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18838 (goto-char (point-min))
18839 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18840 (while (re-search-forward re nil t)
18841 (when (save-match-data (org-in-commented-heading-p t))
18842 (add-text-properties
18843 (match-beginning 0) (org-end-of-subtree t) pc)))))
18844 (goto-char pos)))))
18845 (setq org-todo-keywords-for-agenda
18846 (org-uniquify org-todo-keywords-for-agenda))
18847 (setq org-todo-keyword-alist-for-agenda
18848 (org-uniquify org-todo-keyword-alist-for-agenda))))
18851 ;;;; CDLaTeX minor mode
18853 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18854 "Keymap for the minor `org-cdlatex-mode'.")
18856 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18857 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18858 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18859 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18860 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18862 (defvar org-cdlatex-texmathp-advice-is-done nil
18863 "Flag remembering if we have applied the advice to texmathp already.")
18865 (define-minor-mode org-cdlatex-mode
18866 "Toggle the minor `org-cdlatex-mode'.
18867 This mode supports entering LaTeX environment and math in LaTeX fragments
18868 in Org-mode.
18869 \\{org-cdlatex-mode-map}"
18870 nil " OCDL" nil
18871 (when org-cdlatex-mode
18872 (require 'cdlatex)
18873 (run-hooks 'cdlatex-mode-hook)
18874 (cdlatex-compute-tables))
18875 (unless org-cdlatex-texmathp-advice-is-done
18876 (setq org-cdlatex-texmathp-advice-is-done t)
18877 (defadvice texmathp (around org-math-always-on activate)
18878 "Always return t in Org buffers.
18879 This is because we want to insert math symbols without dollars even outside
18880 the LaTeX math segments. If Orgmode thinks that point is actually inside
18881 an embedded LaTeX fragment, let texmathp do its job.
18882 \\[org-cdlatex-mode-map]"
18883 (interactive)
18884 (let (p)
18885 (cond
18886 ((not (derived-mode-p 'org-mode)) ad-do-it)
18887 ((eq this-command 'cdlatex-math-symbol)
18888 (setq ad-return-value t
18889 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18891 (let ((p (org-inside-LaTeX-fragment-p)))
18892 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18893 (setq ad-return-value t
18894 texmathp-why '("Org-mode embedded math" . 0))
18895 (when p ad-do-it)))))))))
18897 (defun turn-on-org-cdlatex ()
18898 "Unconditionally turn on `org-cdlatex-mode'."
18899 (org-cdlatex-mode 1))
18901 (defun org-try-cdlatex-tab ()
18902 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18903 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18904 - inside a LaTeX fragment, or
18905 - after the first word in a line, where an abbreviation expansion could
18906 insert a LaTeX environment."
18907 (when org-cdlatex-mode
18908 (cond
18909 ;; Before any word on the line: No expansion possible.
18910 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18911 ;; Just after first word on the line: Expand it. Make sure it
18912 ;; cannot happen on headlines, though.
18913 ((save-excursion
18914 (skip-chars-backward "a-zA-Z0-9*")
18915 (skip-chars-backward " \t")
18916 (and (bolp) (not (org-at-heading-p))))
18917 (cdlatex-tab) t)
18918 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18920 (defun org-cdlatex-underscore-caret (&optional _arg)
18921 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18922 Revert to the normal definition outside of these fragments."
18923 (interactive "P")
18924 (if (org-inside-LaTeX-fragment-p)
18925 (call-interactively 'cdlatex-sub-superscript)
18926 (let (org-cdlatex-mode)
18927 (call-interactively (key-binding (vector last-input-event))))))
18929 (defun org-cdlatex-math-modify (&optional _arg)
18930 "Execute `cdlatex-math-modify' in LaTeX fragments.
18931 Revert to the normal definition outside of these fragments."
18932 (interactive "P")
18933 (if (org-inside-LaTeX-fragment-p)
18934 (call-interactively 'cdlatex-math-modify)
18935 (let (org-cdlatex-mode)
18936 (call-interactively (key-binding (vector last-input-event))))))
18938 (defun org-cdlatex-environment-indent (&optional environment item)
18939 "Execute `cdlatex-environment' and indent the inserted environment.
18941 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18943 The inserted environment is indented to current indentation
18944 unless point is at the beginning of the line, in which the
18945 environment remains unintended."
18946 (interactive)
18947 ;; cdlatex-environment always return nil. Therefore, capture output
18948 ;; first and determine if an environment was selected.
18949 (let* ((beg (point-marker))
18950 (end (copy-marker (point) t))
18951 (inserted (progn
18952 (ignore-errors (cdlatex-environment environment item))
18953 (< beg end)))
18954 ;; Figure out how many lines to move forward after the
18955 ;; environment has been inserted.
18956 (lines (when inserted
18957 (save-excursion
18958 (- (cl-loop while (< beg (point))
18959 with x = 0
18960 do (forward-line -1)
18961 (cl-incf x)
18962 finally return x)
18963 (if (progn (goto-char beg)
18964 (and (progn (skip-chars-forward " \t") (eolp))
18965 (progn (skip-chars-backward " \t") (bolp))))
18966 1 0)))))
18967 (env (org-trim (delete-and-extract-region beg end))))
18968 (when inserted
18969 ;; Get indentation of next line unless at column 0.
18970 (let ((ind (if (bolp) 0
18971 (save-excursion
18972 (org-return-indent)
18973 (prog1 (org-get-indentation)
18974 (when (progn (skip-chars-forward " \t") (eolp))
18975 (delete-region beg (point)))))))
18976 (bol (progn (skip-chars-backward " \t") (bolp))))
18977 ;; Insert a newline before environment unless at column zero
18978 ;; to "escape" the current line. Insert a newline if
18979 ;; something is one the same line as \end{ENVIRONMENT}.
18980 (insert
18981 (concat (unless bol "\n") env
18982 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18983 (unless (zerop ind)
18984 (save-excursion
18985 (goto-char beg)
18986 (while (< (point) end)
18987 (unless (eolp) (indent-line-to ind))
18988 (forward-line))))
18989 (goto-char beg)
18990 (forward-line lines)
18991 (indent-line-to ind)))
18992 (set-marker beg nil)
18993 (set-marker end nil)))
18996 ;;;; LaTeX fragments
18998 (defun org-inside-LaTeX-fragment-p ()
18999 "Test if point is inside a LaTeX fragment.
19000 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19001 sequence appearing also before point.
19002 Even though the matchers for math are configurable, this function assumes
19003 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19004 delimiters are skipped when they have been removed by customization.
19005 The return value is nil, or a cons cell with the delimiter and the
19006 position of this delimiter.
19008 This function does a reasonably good job, but can locally be fooled by
19009 for example currency specifications. For example it will assume being in
19010 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19011 fragments that are properly closed, but during editing, we have to live
19012 with the uncertainty caused by missing closing delimiters. This function
19013 looks only before point, not after."
19014 (catch 'exit
19015 (let ((pos (point))
19016 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19017 (lim (progn
19018 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19019 (point)))
19020 dd-on str (start 0) m re)
19021 (goto-char pos)
19022 (when dodollar
19023 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19024 re (nth 1 (assoc "$" org-latex-regexps)))
19025 (while (string-match re str start)
19026 (cond
19027 ((= (match-end 0) (length str))
19028 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19029 ((= (match-end 0) (- (length str) 5))
19030 (throw 'exit nil))
19031 (t (setq start (match-end 0))))))
19032 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19033 (goto-char pos)
19034 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19035 (and (match-beginning 2) (throw 'exit nil))
19036 ;; count $$
19037 (while (re-search-backward "\\$\\$" lim t)
19038 (setq dd-on (not dd-on)))
19039 (goto-char pos)
19040 (when dd-on (cons "$$" m))))))
19042 (defun org-inside-latex-macro-p ()
19043 "Is point inside a LaTeX macro or its arguments?"
19044 (save-match-data
19045 (org-in-regexp
19046 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19048 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19049 "Build an overlay between BEG and END using IMAGE file.
19050 Argument IMAGETYPE is the extension of the displayed image,
19051 as a string. It defaults to \"png\"."
19052 (let ((ov (make-overlay beg end))
19053 (imagetype (or (intern imagetype) 'png)))
19054 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19055 (overlay-put ov 'evaporate t)
19056 (overlay-put ov
19057 'modification-hooks
19058 (list (lambda (o _flag _beg _end &optional _l)
19059 (delete-overlay o))))
19060 (overlay-put ov
19061 'display
19062 (list 'image :type imagetype :file image :ascent 'center))))
19064 (defun org--list-latex-overlays (&optional beg end)
19065 "List all Org LaTeX overlays in current buffer.
19066 Limit to overlays between BEG and END when those are provided."
19067 (cl-remove-if-not
19068 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19069 (overlays-in (or beg (point-min)) (or end (point-max)))))
19071 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19072 "Remove all overlays with LaTeX fragment images in current buffer.
19073 When optional arguments BEG and END are non-nil, remove all
19074 overlays between them instead. Return a non-nil value when some
19075 overlays were removed, nil otherwise."
19076 (let ((overlays (org--list-latex-overlays beg end)))
19077 (mapc #'delete-overlay overlays)
19078 overlays))
19080 (defun org-toggle-latex-fragment (&optional arg)
19081 "Preview the LaTeX fragment at point, or all locally or globally.
19083 If the cursor is on a LaTeX fragment, create the image and overlay
19084 it over the source code, if there is none. Remove it otherwise.
19085 If there is no fragment at point, display all fragments in the
19086 current section.
19088 With prefix ARG, preview or clear image for all fragments in the
19089 current subtree or in the whole buffer when used before the first
19090 headline. With a double prefix ARG \\[universal-argument] \
19091 \\[universal-argument] preview or clear images
19092 for all fragments in the buffer."
19093 (interactive "P")
19094 (when (display-graphic-p)
19095 (catch 'exit
19096 (save-excursion
19097 (let (beg end msg)
19098 (cond
19099 ((or (equal arg '(16))
19100 (and (equal arg '(4))
19101 (org-with-limited-levels (org-before-first-heading-p))))
19102 (if (org-remove-latex-fragment-image-overlays)
19103 (progn (message "LaTeX fragments images removed from buffer")
19104 (throw 'exit nil))
19105 (setq msg "Creating images for buffer...")))
19106 ((equal arg '(4))
19107 (org-with-limited-levels (org-back-to-heading t))
19108 (setq beg (point))
19109 (setq end (progn (org-end-of-subtree t) (point)))
19110 (if (org-remove-latex-fragment-image-overlays beg end)
19111 (progn
19112 (message "LaTeX fragment images removed from subtree")
19113 (throw 'exit nil))
19114 (setq msg "Creating images for subtree...")))
19115 ((let ((datum (org-element-context)))
19116 (when (memq (org-element-type datum)
19117 '(latex-environment latex-fragment))
19118 (setq beg (org-element-property :begin datum))
19119 (setq end (org-element-property :end datum))
19120 (if (org-remove-latex-fragment-image-overlays beg end)
19121 (progn (message "LaTeX fragment image removed")
19122 (throw 'exit nil))
19123 (setq msg "Creating image...")))))
19125 (org-with-limited-levels
19126 (setq beg (if (org-at-heading-p) (line-beginning-position)
19127 (outline-previous-heading)
19128 (point)))
19129 (setq end (progn (outline-next-heading) (point)))
19130 (if (org-remove-latex-fragment-image-overlays beg end)
19131 (progn
19132 (message "LaTeX fragment images removed from section")
19133 (throw 'exit nil))
19134 (setq msg "Creating images for section...")))))
19135 (let ((file (buffer-file-name (buffer-base-buffer))))
19136 (org-format-latex
19137 (concat org-preview-latex-image-directory "org-ltximg")
19138 beg end
19139 ;; Emacs cannot overlay images from remote hosts. Create
19140 ;; it in `temporary-file-directory' instead.
19141 (if (or (not file) (file-remote-p file))
19142 temporary-file-directory
19143 default-directory)
19144 'overlays msg 'forbuffer org-preview-latex-default-process))
19145 (message (concat msg "done")))))))
19147 (defun org-format-latex
19148 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19149 "Replace LaTeX fragments with links to an image.
19151 The function takes care of creating the replacement image.
19153 Only consider fragments between BEG and END when those are
19154 provided.
19156 When optional argument OVERLAYS is non-nil, display the image on
19157 top of the fragment instead of replacing it.
19159 PROCESSING-TYPE is the conversion method to use, as a symbol.
19161 Some of the options can be changed using the variable
19162 `org-format-latex-options', which see."
19163 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19164 (unless (eq processing-type 'verbatim)
19165 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19166 (cnt 0)
19167 checkdir-flag)
19168 (goto-char (or beg (point-min)))
19169 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19170 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19171 (overlay-recenter (or end (point-max))))
19172 (while (re-search-forward math-regexp end t)
19173 (unless (and overlays
19174 (eq (get-char-property (point) 'org-overlay-type)
19175 'org-latex-overlay))
19176 (let* ((context (org-element-context))
19177 (type (org-element-type context)))
19178 (when (memq type '(latex-environment latex-fragment))
19179 (let ((block-type (eq type 'latex-environment))
19180 (value (org-element-property :value context))
19181 (beg (org-element-property :begin context))
19182 (end (save-excursion
19183 (goto-char (org-element-property :end context))
19184 (skip-chars-backward " \r\t\n")
19185 (point))))
19186 (cond
19187 ((eq processing-type 'mathjax)
19188 ;; Prepare for MathJax processing.
19189 (if (not (string-match "\\`\\$\\$?" value))
19190 (goto-char end)
19191 (delete-region beg end)
19192 (if (string= (match-string 0 value) "$$")
19193 (insert "\\[" (substring value 2 -2) "\\]")
19194 (insert "\\(" (substring value 1 -1) "\\)"))))
19195 ((assq processing-type org-preview-latex-process-alist)
19196 ;; Process to an image.
19197 (cl-incf cnt)
19198 (goto-char beg)
19199 (let* ((processing-info
19200 (cdr (assq processing-type org-preview-latex-process-alist)))
19201 (face (face-at-point))
19202 ;; Get the colors from the face at point.
19204 (let ((color (plist-get org-format-latex-options
19205 :foreground)))
19206 (if (and forbuffer (eq color 'auto))
19207 (face-attribute face :foreground nil 'default)
19208 color)))
19210 (let ((color (plist-get org-format-latex-options
19211 :background)))
19212 (if (and forbuffer (eq color 'auto))
19213 (face-attribute face :background nil 'default)
19214 color)))
19215 (hash (sha1 (prin1-to-string
19216 (list org-format-latex-header
19217 org-latex-default-packages-alist
19218 org-latex-packages-alist
19219 org-format-latex-options
19220 forbuffer value fg bg))))
19221 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19222 (absprefix (expand-file-name prefix dir))
19223 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19224 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19225 (sep (and block-type "\n\n"))
19226 (link (concat sep "[[file:" linkfile "]]" sep))
19227 (options
19228 (org-combine-plists
19229 org-format-latex-options
19230 `(:foreground ,fg :background ,bg))))
19231 (when msg (message msg cnt))
19232 (unless checkdir-flag ; Ensure the directory exists.
19233 (setq checkdir-flag t)
19234 (let ((todir (file-name-directory absprefix)))
19235 (unless (file-directory-p todir)
19236 (make-directory todir t))))
19237 (unless (file-exists-p movefile)
19238 (org-create-formula-image
19239 value movefile options forbuffer processing-type))
19240 (if overlays
19241 (progn
19242 (dolist (o (overlays-in beg end))
19243 (when (eq (overlay-get o 'org-overlay-type)
19244 'org-latex-overlay)
19245 (delete-overlay o)))
19246 (org--format-latex-make-overlay beg end movefile imagetype)
19247 (goto-char end))
19248 (delete-region beg end)
19249 (insert
19250 (org-add-props link
19251 (list 'org-latex-src
19252 (replace-regexp-in-string "\"" "" value)
19253 'org-latex-src-embed-type
19254 (if block-type 'paragraph 'character)))))))
19255 ((eq processing-type 'mathml)
19256 ;; Process to MathML.
19257 (unless (org-format-latex-mathml-available-p)
19258 (user-error "LaTeX to MathML converter not configured"))
19259 (cl-incf cnt)
19260 (when msg (message msg cnt))
19261 (goto-char beg)
19262 (delete-region beg end)
19263 (insert (org-format-latex-as-mathml
19264 value block-type prefix dir)))
19266 (error "Unknown conversion process %s for LaTeX fragments"
19267 processing-type)))))))))))
19269 (defun org-create-math-formula (latex-frag &optional mathml-file)
19270 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19271 Use `org-latex-to-mathml-convert-command'. If the conversion is
19272 sucessful, return the portion between \"<math...> </math>\"
19273 elements otherwise return nil. When MATHML-FILE is specified,
19274 write the results in to that file. When invoked as an
19275 interactive command, prompt for LATEX-FRAG, with initial value
19276 set to the current active region and echo the results for user
19277 inspection."
19278 (interactive (list (let ((frag (when (org-region-active-p)
19279 (buffer-substring-no-properties
19280 (region-beginning) (region-end)))))
19281 (read-string "LaTeX Fragment: " frag nil frag))))
19282 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19283 (let* ((tmp-in-file
19284 (let ((file (file-relative-name
19285 (make-temp-name (expand-file-name "ltxmathml-in")))))
19286 (write-region latex-frag nil file)
19287 file))
19288 (tmp-out-file (file-relative-name
19289 (make-temp-name (expand-file-name "ltxmathml-out"))))
19290 (cmd (format-spec
19291 org-latex-to-mathml-convert-command
19292 `((?j . ,(and org-latex-to-mathml-jar-file
19293 (shell-quote-argument
19294 (expand-file-name
19295 org-latex-to-mathml-jar-file))))
19296 (?I . ,(shell-quote-argument tmp-in-file))
19297 (?i . ,latex-frag)
19298 (?o . ,(shell-quote-argument tmp-out-file)))))
19299 mathml shell-command-output)
19300 (when (called-interactively-p 'any)
19301 (unless (org-format-latex-mathml-available-p)
19302 (user-error "LaTeX to MathML converter not configured")))
19303 (message "Running %s" cmd)
19304 (setq shell-command-output (shell-command-to-string cmd))
19305 (setq mathml
19306 (when (file-readable-p tmp-out-file)
19307 (with-current-buffer (find-file-noselect tmp-out-file t)
19308 (goto-char (point-min))
19309 (when (re-search-forward
19310 (concat
19311 (regexp-quote
19312 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19313 "[^>]*?>"
19314 "\\(.\\|\n\\)*"
19315 "</math>")
19316 nil t)
19317 (prog1 (match-string 0) (kill-buffer))))))
19318 (cond
19319 (mathml
19320 (setq mathml
19321 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19322 (when mathml-file
19323 (write-region mathml nil mathml-file))
19324 (when (called-interactively-p 'any)
19325 (message mathml)))
19326 ((message "LaTeX to MathML conversion failed")
19327 (message shell-command-output)))
19328 (delete-file tmp-in-file)
19329 (when (file-exists-p tmp-out-file)
19330 (delete-file tmp-out-file))
19331 mathml))
19333 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19334 prefix &optional dir)
19335 "Use `org-create-math-formula' but check local cache first."
19336 (let* ((absprefix (expand-file-name prefix dir))
19337 (print-length nil) (print-level nil)
19338 (formula-id (concat
19339 "formula-"
19340 (sha1
19341 (prin1-to-string
19342 (list latex-frag
19343 org-latex-to-mathml-convert-command)))))
19344 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19345 (formula-cache-dir (file-name-directory formula-cache)))
19347 (unless (file-directory-p formula-cache-dir)
19348 (make-directory formula-cache-dir t))
19350 (unless (file-exists-p formula-cache)
19351 (org-create-math-formula latex-frag formula-cache))
19353 (if (file-exists-p formula-cache)
19354 ;; Successful conversion. Return the link to MathML file.
19355 (org-add-props
19356 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19357 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19358 'org-latex-src-embed-type (if latex-frag-type
19359 'paragraph 'character)))
19360 ;; Failed conversion. Return the LaTeX fragment verbatim
19361 latex-frag)))
19363 (declare-function org-export-get-backend "ox" (name))
19364 (declare-function org-export--get-global-options "ox" (&optional backend))
19365 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19366 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19367 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19368 (defun org-create-formula--latex-header ()
19369 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19370 (let ((info (org-combine-plists (org-export--get-global-options
19371 (org-export-get-backend 'latex))
19372 (org-export--get-inbuffer-options
19373 (org-export-get-backend 'latex)))))
19374 (org-latex-guess-babel-language
19375 (org-latex-guess-inputenc
19376 (org-splice-latex-header
19377 org-format-latex-header
19378 org-latex-default-packages-alist
19379 org-latex-packages-alist t
19380 (plist-get info :latex-header)))
19381 info)))
19383 (defun org--get-display-dpi ()
19384 "Get the DPI of the display.
19386 Assumes that the display has the same pixel width in the
19387 horizontal and vertical directions."
19388 (if (display-graphic-p)
19389 (round (/ (display-pixel-height)
19390 (/ (display-mm-height) 25.4)))
19391 (error "Attempt to calculate the dpi of a non-graphic display")))
19393 (defun org-create-formula-image
19394 (string tofile options buffer &optional processing-type)
19395 "Create an image from LaTeX source using external processes.
19397 The LaTeX STRING is saved to a temporary LaTeX file, then
19398 converted to an image file by process PROCESSING-TYPE defined in
19399 `org-preview-latex-process-alist'. A nil value defaults to
19400 `org-preview-latex-default-process'.
19402 The generated image file is eventually moved to TOFILE.
19404 The OPTIONS argument controls the size, foreground color and
19405 background color of the generated image.
19407 When BUFFER non-nil, this function is used for LaTeX previewing.
19408 Otherwise, it is used to deal with LaTeX snippets showed in
19409 a HTML file."
19410 (let* ((processing-type (or processing-type
19411 org-preview-latex-default-process))
19412 (processing-info
19413 (cdr (assq processing-type org-preview-latex-process-alist)))
19414 (programs (plist-get processing-info :programs))
19415 (error-message (or (plist-get processing-info :message) ""))
19416 (use-xcolor (plist-get processing-info :use-xcolor))
19417 (image-input-type (plist-get processing-info :image-input-type))
19418 (image-output-type (plist-get processing-info :image-output-type))
19419 (post-clean (or (plist-get processing-info :post-clean)
19420 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19421 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19422 (latex-header (or (plist-get processing-info :latex-header)
19423 (org-create-formula--latex-header)))
19424 (latex-compiler (plist-get processing-info :latex-compiler))
19425 (image-converter (plist-get processing-info :image-converter))
19426 (tmpdir temporary-file-directory)
19427 (texfilebase (make-temp-name
19428 (expand-file-name "orgtex" tmpdir)))
19429 (texfile (concat texfilebase ".tex"))
19430 (font-height (face-attribute 'default :height nil))
19431 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19432 '(1.0 . 1.0)))
19433 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19434 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19435 (dpi (* scale (floor (if buffer font-height 140.0))))
19436 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19437 "Black"))
19438 (bg (or (plist-get options (if buffer :background :html-background))
19439 "Transparent"))
19440 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19441 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19442 (dolist (program programs)
19443 (org-check-external-command program error-message))
19444 (if use-xcolor
19445 (progn (if (eq fg 'default)
19446 (setq fg (org-latex-color :foreground))
19447 (setq fg (org-latex-color-format fg)))
19448 (if (eq bg 'default)
19449 (setq bg (org-latex-color :background))
19450 (setq bg (org-latex-color-format
19451 (if (string= bg "Transparent") "white" bg))))
19452 (with-temp-file texfile
19453 (insert latex-header)
19454 (insert "\n\\begin{document}\n"
19455 "\\definecolor{fg}{rgb}{" fg "}\n"
19456 "\\definecolor{bg}{rgb}{" bg "}\n"
19457 "\n\\pagecolor{bg}\n"
19458 "\n{\\color{fg}\n"
19459 string
19460 "\n}\n"
19461 "\n\\end{document}\n")))
19462 (if (eq fg 'default)
19463 (setq fg (org-dvipng-color :foreground))
19464 (unless (string= fg "Transparent")
19465 (setq fg (org-dvipng-color-format fg))))
19466 (if (eq bg 'default)
19467 (setq bg (org-dvipng-color :background))
19468 (unless (string= bg "Transparent")
19469 (setq bg (org-dvipng-color-format bg))))
19470 (with-temp-file texfile
19471 (insert latex-header)
19472 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19474 (let* ((err-msg (format "Please adjust '%s' part of \
19475 `org-preview-latex-process-alist'."
19476 processing-type))
19477 (image-input-file
19478 (org-compile-file
19479 texfile latex-compiler image-input-type err-msg log-buf))
19480 (image-output-file
19481 (org-compile-file
19482 image-input-file image-converter image-output-type err-msg log-buf
19483 `((?F . ,(shell-quote-argument fg))
19484 (?B . ,(shell-quote-argument bg))
19485 (?D . ,(shell-quote-argument (format "%s" dpi)))
19486 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19487 (copy-file image-output-file tofile 'replace)
19488 (dolist (e post-clean)
19489 (when (file-exists-p (concat texfilebase e))
19490 (delete-file (concat texfilebase e))))
19491 image-output-file)))
19493 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19494 "Fill a LaTeX header template TPL.
19495 In the template, the following place holders will be recognized:
19497 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19498 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19499 [PACKAGES] \\usepackage statements for PKG
19500 [NO-PACKAGES] do not include PKG
19501 [EXTRA] the string EXTRA
19502 [NO-EXTRA] do not include EXTRA
19504 For backward compatibility, if both the positive and the negative place
19505 holder is missing, the positive one (without the \"NO-\") will be
19506 assumed to be present at the end of the template.
19507 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19508 EXTRA is a string.
19509 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19510 (let (rpl (end ""))
19511 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19512 (setq rpl (if (or (match-end 1) (not def-pkg))
19513 "" (org-latex-packages-to-string def-pkg snippets-p t))
19514 tpl (replace-match rpl t t tpl))
19515 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19517 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19518 (setq rpl (if (or (match-end 1) (not pkg))
19519 "" (org-latex-packages-to-string pkg snippets-p t))
19520 tpl (replace-match rpl t t tpl))
19521 (when pkg (setq end
19522 (concat end "\n"
19523 (org-latex-packages-to-string pkg snippets-p)))))
19525 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19526 (setq rpl (if (or (match-end 1) (not extra))
19527 "" (concat extra "\n"))
19528 tpl (replace-match rpl t t tpl))
19529 (when (and extra (string-match "\\S-" extra))
19530 (setq end (concat end "\n" extra))))
19532 (if (string-match "\\S-" end)
19533 (concat tpl "\n" end)
19534 tpl)))
19536 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19537 "Turn an alist of packages into a string with the \\usepackage macros."
19538 (setq pkg (mapconcat (lambda(p)
19539 (cond
19540 ((stringp p) p)
19541 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19542 (format "%% Package %s omitted" (cadr p)))
19543 ((equal "" (car p))
19544 (format "\\usepackage{%s}" (cadr p)))
19546 (format "\\usepackage[%s]{%s}"
19547 (car p) (cadr p)))))
19549 "\n"))
19550 (if newline (concat pkg "\n") pkg))
19552 (defun org-dvipng-color (attr)
19553 "Return a RGB color specification for dvipng."
19554 (org-dvipng-color-format (face-attribute 'default attr nil)))
19556 (defun org-dvipng-color-format (color-name)
19557 "Convert COLOR-NAME to a RGB color value for dvipng."
19558 (apply #'format "rgb %s %s %s"
19559 (mapcar 'org-normalize-color
19560 (color-values color-name))))
19562 (defun org-latex-color (attr)
19563 "Return a RGB color for the LaTeX color package."
19564 (org-latex-color-format (face-attribute 'default attr nil)))
19566 (defun org-latex-color-format (color-name)
19567 "Convert COLOR-NAME to a RGB color value."
19568 (apply #'format "%s,%s,%s"
19569 (mapcar 'org-normalize-color
19570 (color-values color-name))))
19572 (defun org-normalize-color (value)
19573 "Return string to be used as color value for an RGB component."
19574 (format "%g" (/ value 65535.0)))
19578 ;; Image display
19580 (defvar-local org-inline-image-overlays nil)
19582 (defun org-toggle-inline-images (&optional include-linked)
19583 "Toggle the display of inline images.
19584 INCLUDE-LINKED is passed to `org-display-inline-images'."
19585 (interactive "P")
19586 (if org-inline-image-overlays
19587 (progn
19588 (org-remove-inline-images)
19589 (when (called-interactively-p 'interactive)
19590 (message "Inline image display turned off")))
19591 (org-display-inline-images include-linked)
19592 (when (called-interactively-p 'interactive)
19593 (message (if org-inline-image-overlays
19594 (format "%d images displayed inline"
19595 (length org-inline-image-overlays))
19596 "No images to display inline")))))
19598 (defun org-redisplay-inline-images ()
19599 "Refresh the display of inline images."
19600 (interactive)
19601 (if (not org-inline-image-overlays)
19602 (org-toggle-inline-images)
19603 (org-toggle-inline-images)
19604 (org-toggle-inline-images)))
19606 (defun org-display-inline-images (&optional include-linked refresh beg end)
19607 "Display inline images.
19609 An inline image is a link which follows either of these
19610 conventions:
19612 1. Its path is a file with an extension matching return value
19613 from `image-file-name-regexp' and it has no contents.
19615 2. Its description consists in a single link of the previous
19616 type.
19618 When optional argument INCLUDE-LINKED is non-nil, also links with
19619 a text description part will be inlined. This can be nice for
19620 a quick look at those images, but it does not reflect what
19621 exported files will look like.
19623 When optional argument REFRESH is non-nil, refresh existing
19624 images between BEG and END. This will create new image displays
19625 only if necessary. BEG and END default to the buffer
19626 boundaries."
19627 (interactive "P")
19628 (when (display-graphic-p)
19629 (unless refresh
19630 (org-remove-inline-images)
19631 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19632 (org-with-wide-buffer
19633 (goto-char (or beg (point-min)))
19634 (let ((case-fold-search t)
19635 (file-extension-re (image-file-name-regexp)))
19636 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19637 (let ((link (save-match-data (org-element-context))))
19638 ;; Check if we're at an inline image.
19639 (when (and (equal (org-element-property :type link) "file")
19640 (or include-linked
19641 (not (org-element-property :contents-begin link)))
19642 (let ((parent (org-element-property :parent link)))
19643 (or (not (eq (org-element-type parent) 'link))
19644 (not (cdr (org-element-contents parent)))))
19645 (string-match-p file-extension-re
19646 (org-element-property :path link)))
19647 (let ((file (expand-file-name
19648 (org-link-unescape
19649 (org-element-property :path link)))))
19650 (when (file-exists-p file)
19651 (let ((width
19652 ;; Apply `org-image-actual-width' specifications.
19653 (cond
19654 ((not (image-type-available-p 'imagemagick)) nil)
19655 ((eq org-image-actual-width t) nil)
19656 ((listp org-image-actual-width)
19658 ;; First try to find a width among
19659 ;; attributes associated to the paragraph
19660 ;; containing link.
19661 (let ((paragraph
19662 (let ((e link))
19663 (while (and (setq e (org-element-property
19664 :parent e))
19665 (not (eq (org-element-type e)
19666 'paragraph))))
19667 e)))
19668 (when paragraph
19669 (save-excursion
19670 (goto-char (org-element-property :begin paragraph))
19671 (when
19672 (re-search-forward
19673 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19674 (org-element-property
19675 :post-affiliated paragraph)
19677 (string-to-number (match-string 1))))))
19678 ;; Otherwise, fall-back to provided number.
19679 (car org-image-actual-width)))
19680 ((numberp org-image-actual-width)
19681 org-image-actual-width)))
19682 (old (get-char-property-and-overlay
19683 (org-element-property :begin link)
19684 'org-image-overlay)))
19685 (if (and (car-safe old) refresh)
19686 (image-refresh (overlay-get (cdr old) 'display))
19687 (let ((image (create-image file
19688 (and width 'imagemagick)
19690 :width width)))
19691 (when image
19692 (let* ((link
19693 ;; If inline image is the description
19694 ;; of another link, be sure to
19695 ;; consider the latter as the one to
19696 ;; apply the overlay on.
19697 (let ((parent
19698 (org-element-property :parent link)))
19699 (if (eq (org-element-type parent) 'link)
19700 parent
19701 link)))
19702 (ov (make-overlay
19703 (org-element-property :begin link)
19704 (progn
19705 (goto-char
19706 (org-element-property :end link))
19707 (skip-chars-backward " \t")
19708 (point)))))
19709 (overlay-put ov 'display image)
19710 (overlay-put ov 'face 'default)
19711 (overlay-put ov 'org-image-overlay t)
19712 (overlay-put
19713 ov 'modification-hooks
19714 (list 'org-display-inline-remove-overlay))
19715 (push ov org-inline-image-overlays)))))))))))))))
19717 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19718 "Remove inline-display overlay if a corresponding region is modified."
19719 (let ((inhibit-modification-hooks t))
19720 (when (and ov after)
19721 (delete ov org-inline-image-overlays)
19722 (delete-overlay ov))))
19724 (defun org-remove-inline-images ()
19725 "Remove inline display of images."
19726 (interactive)
19727 (mapc #'delete-overlay org-inline-image-overlays)
19728 (setq org-inline-image-overlays nil))
19730 ;;;; Key bindings
19732 ;; Outline functions from `outline-mode-prefix-map'
19733 ;; that can be remapped in Org:
19734 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19735 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19736 (define-key org-mode-map [remap outline-forward-same-level]
19737 'org-forward-heading-same-level)
19738 (define-key org-mode-map [remap outline-backward-same-level]
19739 'org-backward-heading-same-level)
19740 (define-key org-mode-map [remap outline-show-branches]
19741 'org-kill-note-or-show-branches)
19742 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19743 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19744 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19745 (define-key org-mode-map [remap outline-next-visible-heading]
19746 'org-next-visible-heading)
19747 (define-key org-mode-map [remap outline-previous-visible-heading]
19748 'org-previous-visible-heading)
19749 (define-key org-mode-map [remap show-children] 'org-show-children)
19751 ;; Outline functions from `outline-mode-prefix-map' that can not
19752 ;; be remapped in Org:
19754 ;; - the column "key binding" shows whether the Outline function is still
19755 ;; available in Org mode on the same key that it has been bound to in
19756 ;; Outline mode:
19757 ;; - "overridden": key used for a different functionality in Org mode
19758 ;; - else: key still bound to the same Outline function in Org mode
19760 ;; | Outline function | key binding | Org replacement |
19761 ;; |------------------------------------+-------------+--------------------------|
19762 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19763 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19764 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19765 ;; | `show-entry' | overridden | no replacement |
19766 ;; | `show-branches' | `C-c C-k' | still same function |
19767 ;; | `show-subtree' | overridden | visibility cycling |
19768 ;; | `show-all' | overridden | no replacement |
19769 ;; | `hide-subtree' | overridden | visibility cycling |
19770 ;; | `hide-body' | overridden | no replacement |
19771 ;; | `hide-entry' | overridden | visibility cycling |
19772 ;; | `hide-leaves' | overridden | no replacement |
19773 ;; | `hide-sublevels' | overridden | no replacement |
19774 ;; | `hide-other' | overridden | no replacement |
19776 ;; Make `C-c C-x' a prefix key
19777 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19779 ;; TAB key with modifiers
19780 (org-defkey org-mode-map "\C-i" 'org-cycle)
19781 (org-defkey org-mode-map [(tab)] 'org-cycle)
19782 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19783 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19784 ;; The following line is necessary under Suse GNU/Linux
19785 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19786 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19787 (define-key org-mode-map [backtab] 'org-shifttab)
19789 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19790 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19791 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19793 ;; Cursor keys with modifiers
19794 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19795 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19796 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19797 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19799 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19800 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19801 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19802 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19803 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19804 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19806 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19807 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19808 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19809 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19811 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19812 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19813 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19814 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19816 ;; Babel keys
19817 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19818 (dolist (pair org-babel-key-bindings)
19819 (define-key org-babel-map (car pair) (cdr pair)))
19821 ;;; Extra keys for tty access.
19822 ;; We only set them when really needed because otherwise the
19823 ;; menus don't show the simple keys
19825 (when (or org-use-extra-keys (not window-system))
19826 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19827 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19828 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19829 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19830 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19831 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19832 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19833 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19834 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19835 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19836 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19837 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19838 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19839 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19840 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19841 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19842 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19843 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19844 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19845 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19846 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19847 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19848 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19849 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19850 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19851 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19852 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19853 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19855 ;; All the other keys
19857 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19858 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19859 (if (boundp 'narrow-map)
19860 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19861 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19862 (if (boundp 'narrow-map)
19863 (org-defkey narrow-map "b" 'org-narrow-to-block)
19864 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19865 (if (boundp 'narrow-map)
19866 (org-defkey narrow-map "e" 'org-narrow-to-element)
19867 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19868 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19869 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19870 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19871 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19872 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19873 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19874 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19875 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19876 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19877 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19878 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19879 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19880 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19881 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19882 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19883 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19884 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19885 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19886 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19887 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19888 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19889 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19890 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19891 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19892 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19893 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19894 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19895 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19896 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19897 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19898 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19899 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19900 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19901 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19902 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19903 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19904 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19905 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19906 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19907 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19908 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19909 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19910 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19911 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19912 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19913 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19914 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19915 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19916 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19917 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19918 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19919 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19920 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19921 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19922 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19923 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19924 (org-defkey org-mode-map "\C-c^" 'org-sort)
19925 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19926 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19927 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19928 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19929 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19930 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19931 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19932 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19933 (org-defkey org-mode-map "\C-m" 'org-return)
19934 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19935 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19936 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19937 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19938 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19939 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19940 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19941 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19942 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19943 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19944 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19945 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19946 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19947 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19948 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19949 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19950 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19951 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19952 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19953 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19954 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19955 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19956 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19957 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19958 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19960 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19961 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19962 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19964 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19965 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19966 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19967 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19968 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19969 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19970 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19971 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19972 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19973 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19974 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19975 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19976 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19977 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19978 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19979 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19980 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19981 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19982 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19983 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19984 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19985 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19987 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19988 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19989 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19990 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19991 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19993 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19995 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19997 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19998 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20000 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20003 (defconst org-speed-commands-default
20005 ("Outline Navigation")
20006 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20007 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20008 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20009 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20010 ("F" . org-next-block)
20011 ("B" . org-previous-block)
20012 ("u" . (org-speed-move-safe 'outline-up-heading))
20013 ("j" . org-goto)
20014 ("g" . (org-refile t))
20015 ("Outline Visibility")
20016 ("c" . org-cycle)
20017 ("C" . org-shifttab)
20018 (" " . org-display-outline-path)
20019 ("s" . org-narrow-to-subtree)
20020 ("=" . org-columns)
20021 ("Outline Structure Editing")
20022 ("U" . org-metaup)
20023 ("D" . org-metadown)
20024 ("r" . org-metaright)
20025 ("l" . org-metaleft)
20026 ("R" . org-shiftmetaright)
20027 ("L" . org-shiftmetaleft)
20028 ("i" . (progn (forward-char 1) (call-interactively
20029 'org-insert-heading-respect-content)))
20030 ("^" . org-sort)
20031 ("w" . org-refile)
20032 ("a" . org-archive-subtree-default-with-confirmation)
20033 ("@" . org-mark-subtree)
20034 ("#" . org-toggle-comment)
20035 ("Clock Commands")
20036 ("I" . org-clock-in)
20037 ("O" . org-clock-out)
20038 ("Meta Data Editing")
20039 ("t" . org-todo)
20040 ("," . (org-priority))
20041 ("0" . (org-priority ?\ ))
20042 ("1" . (org-priority ?A))
20043 ("2" . (org-priority ?B))
20044 ("3" . (org-priority ?C))
20045 (":" . org-set-tags-command)
20046 ("e" . org-set-effort)
20047 ("E" . org-inc-effort)
20048 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20049 (org-entry-put (point) "APPT_WARNTIME" m)))
20050 ("Agenda Views etc")
20051 ("v" . org-agenda)
20052 ("/" . org-sparse-tree)
20053 ("Misc")
20054 ("o" . org-open-at-point)
20055 ("?" . org-speed-command-help)
20056 ("<" . (org-agenda-set-restriction-lock 'subtree))
20057 (">" . (org-agenda-remove-restriction-lock))
20059 "The default speed commands.")
20061 (defun org-print-speed-command (e)
20062 (if (> (length (car e)) 1)
20063 (progn
20064 (princ "\n")
20065 (princ (car e))
20066 (princ "\n")
20067 (princ (make-string (length (car e)) ?-))
20068 (princ "\n"))
20069 (princ (car e))
20070 (princ " ")
20071 (if (symbolp (cdr e))
20072 (princ (symbol-name (cdr e)))
20073 (prin1 (cdr e)))
20074 (princ "\n")))
20076 (defun org-speed-command-help ()
20077 "Show the available speed commands."
20078 (interactive)
20079 (if (not org-use-speed-commands)
20080 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20081 (with-output-to-temp-buffer "*Help*"
20082 (princ "User-defined Speed commands\n===========================\n")
20083 (mapc #'org-print-speed-command org-speed-commands-user)
20084 (princ "\n")
20085 (princ "Built-in Speed commands\n=======================\n")
20086 (mapc #'org-print-speed-command org-speed-commands-default))
20087 (with-current-buffer "*Help*"
20088 (setq truncate-lines t))))
20090 (defun org-speed-move-safe (cmd)
20091 "Execute CMD, but make sure that the cursor always ends up in a headline.
20092 If not, return to the original position and throw an error."
20093 (interactive)
20094 (let ((pos (point)))
20095 (call-interactively cmd)
20096 (unless (and (bolp) (org-at-heading-p))
20097 (goto-char pos)
20098 (error "Boundary reached while executing %s" cmd))))
20100 (defvar org-self-insert-command-undo-counter 0)
20102 (defvar org-table-auto-blank-field) ; defined in org-table.el
20103 (defvar org-speed-command nil)
20105 (defun org-speed-command-activate (keys)
20106 "Hook for activating single-letter speed commands.
20107 `org-speed-commands-default' specifies a minimal command set.
20108 Use `org-speed-commands-user' for further customization."
20109 (when (or (and (bolp) (looking-at org-outline-regexp))
20110 (and (functionp org-use-speed-commands)
20111 (funcall org-use-speed-commands)))
20112 (cdr (assoc keys (append org-speed-commands-user
20113 org-speed-commands-default)))))
20115 (defun org-babel-speed-command-activate (keys)
20116 "Hook for activating single-letter code block commands."
20117 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20118 (cdr (assoc keys org-babel-key-bindings))))
20120 (defcustom org-speed-command-hook
20121 '(org-speed-command-default-hook org-babel-speed-command-hook)
20122 "Hook for activating speed commands at strategic locations.
20123 Hook functions are called in sequence until a valid handler is
20124 found.
20126 Each hook takes a single argument, a user-pressed command key
20127 which is also a `self-insert-command' from the global map.
20129 Within the hook, examine the cursor position and the command key
20130 and return nil or a valid handler as appropriate. Handler could
20131 be one of an interactive command, a function, or a form.
20133 Set `org-use-speed-commands' to non-nil value to enable this
20134 hook. The default setting is `org-speed-command-activate'."
20135 :group 'org-structure
20136 :version "24.1"
20137 :type 'hook)
20139 (defun org-self-insert-command (N)
20140 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20141 If the cursor is in a table looking at whitespace, the whitespace is
20142 overwritten, and the table is not marked as requiring realignment."
20143 (interactive "p")
20144 (org-check-before-invisible-edit 'insert)
20145 (cond
20146 ((and org-use-speed-commands
20147 (let ((kv (this-command-keys-vector)))
20148 (setq org-speed-command
20149 (run-hook-with-args-until-success
20150 'org-speed-command-hook
20151 (make-string 1 (aref kv (1- (length kv))))))))
20152 (cond
20153 ((commandp org-speed-command)
20154 (setq this-command org-speed-command)
20155 (call-interactively org-speed-command))
20156 ((functionp org-speed-command)
20157 (funcall org-speed-command))
20158 ((and org-speed-command (listp org-speed-command))
20159 (eval org-speed-command))
20160 (t (let (org-use-speed-commands)
20161 (call-interactively 'org-self-insert-command)))))
20162 ((and
20163 (org-at-table-p)
20164 (progn
20165 ;; Check if we blank the field, and if that triggers align.
20166 (and (featurep 'org-table) org-table-auto-blank-field
20167 (memq last-command
20168 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20169 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20170 ;; Got extra space, this field does not determine
20171 ;; column width.
20172 (let (org-table-may-need-update) (org-table-blank-field))
20173 ;; No extra space, this field may determine column
20174 ;; width.
20175 (org-table-blank-field)))
20177 (eq N 1)
20178 (looking-at "[^|\n]* \\( \\)|"))
20179 ;; There is room for insertion without re-aligning the table.
20180 (delete-region (match-beginning 1) (match-end 1))
20181 (self-insert-command N))
20183 (setq org-table-may-need-update t)
20184 (self-insert-command N)
20185 (org-fix-tags-on-the-fly)
20186 (when org-self-insert-cluster-for-undo
20187 (if (not (eq last-command 'org-self-insert-command))
20188 (setq org-self-insert-command-undo-counter 1)
20189 (if (>= org-self-insert-command-undo-counter 20)
20190 (setq org-self-insert-command-undo-counter 1)
20191 (and (> org-self-insert-command-undo-counter 0)
20192 buffer-undo-list (listp buffer-undo-list)
20193 (not (cadr buffer-undo-list)) ; remove nil entry
20194 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20195 (setq org-self-insert-command-undo-counter
20196 (1+ org-self-insert-command-undo-counter))))))))
20198 (defun org-check-before-invisible-edit (kind)
20199 "Check is editing if kind KIND would be dangerous with invisible text around.
20200 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20201 ;; First, try to get out of here as quickly as possible, to reduce overhead
20202 (when (and org-catch-invisible-edits
20203 (or (not (boundp 'visible-mode)) (not visible-mode))
20204 (or (get-char-property (point) 'invisible)
20205 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20206 ;; OK, we need to take a closer look
20207 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20208 (invisible-before-point (unless (bobp) (get-char-property
20209 (1- (point)) 'invisible)))
20210 (border-and-ok-direction
20212 ;; Check if we are acting predictably before invisible text
20213 (and invisible-at-point (not invisible-before-point)
20214 (memq kind '(insert delete-backward)))
20215 ;; Check if we are acting predictably after invisible text
20216 ;; This works not well, and I have turned it off. It seems
20217 ;; better to always show and stop after invisible text.
20218 ;; (and (not invisible-at-point) invisible-before-point
20219 ;; (memq kind '(insert delete)))
20221 (when (or (memq invisible-at-point '(outline org-hide-block t))
20222 (memq invisible-before-point '(outline org-hide-block t)))
20223 (when (eq org-catch-invisible-edits 'error)
20224 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20225 (if (and org-custom-properties-overlays
20226 (y-or-n-p "Display invisible properties in this buffer? "))
20227 (org-toggle-custom-properties-visibility)
20228 ;; Make the area visible
20229 (save-excursion
20230 (when invisible-before-point
20231 (goto-char (previous-single-char-property-change
20232 (point) 'invisible)))
20233 (outline-show-subtree))
20234 (cond
20235 ((eq org-catch-invisible-edits 'show)
20236 ;; That's it, we do the edit after showing
20237 (message
20238 "Unfolding invisible region around point before editing")
20239 (sit-for 1))
20240 ((and (eq org-catch-invisible-edits 'smart)
20241 border-and-ok-direction)
20242 (message "Unfolding invisible region around point before editing"))
20244 ;; Don't do the edit, make the user repeat it in full visibility
20245 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20247 (defun org-fix-tags-on-the-fly ()
20248 (when (and (equal (char-after (point-at-bol)) ?*)
20249 (org-at-heading-p))
20250 (org-align-tags-here org-tags-column)))
20252 (defun org-delete-backward-char (N)
20253 "Like `delete-backward-char', insert whitespace at field end in tables.
20254 When deleting backwards, in tables this function will insert whitespace in
20255 front of the next \"|\" separator, to keep the table aligned. The table will
20256 still be marked for re-alignment if the field did fill the entire column,
20257 because, in this case the deletion might narrow the column."
20258 (interactive "p")
20259 (save-match-data
20260 (org-check-before-invisible-edit 'delete-backward)
20261 (if (and (org-at-table-p)
20262 (eq N 1)
20263 (string-match "|" (buffer-substring (point-at-bol) (point)))
20264 (looking-at ".*?|"))
20265 (let ((pos (point))
20266 (noalign (looking-at "[^|\n\r]* |"))
20267 (c org-table-may-need-update))
20268 (backward-delete-char N)
20269 (unless overwrite-mode
20270 (skip-chars-forward "^|")
20271 (insert " ")
20272 (goto-char (1- pos)))
20273 ;; noalign: if there were two spaces at the end, this field
20274 ;; does not determine the width of the column.
20275 (when noalign (setq org-table-may-need-update c)))
20276 (backward-delete-char N)
20277 (org-fix-tags-on-the-fly))))
20279 (defun org-delete-char (N)
20280 "Like `delete-char', but insert whitespace at field end in tables.
20281 When deleting characters, in tables this function will insert whitespace in
20282 front of the next \"|\" separator, to keep the table aligned. The table will
20283 still be marked for re-alignment if the field did fill the entire column,
20284 because, in this case the deletion might narrow the column."
20285 (interactive "p")
20286 (save-match-data
20287 (org-check-before-invisible-edit 'delete)
20288 (if (and (org-at-table-p)
20289 (not (bolp))
20290 (not (= (char-after) ?|))
20291 (eq N 1))
20292 (if (looking-at ".*?|")
20293 (let ((pos (point))
20294 (noalign (looking-at "[^|\n\r]* |"))
20295 (c org-table-may-need-update))
20296 (replace-match
20297 (concat (substring (match-string 0) 1 -1) " |") nil t)
20298 (goto-char pos)
20299 ;; noalign: if there were two spaces at the end, this field
20300 ;; does not determine the width of the column.
20301 (when noalign (setq org-table-may-need-update c)))
20302 (delete-char N))
20303 (delete-char N)
20304 (org-fix-tags-on-the-fly))))
20306 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20307 (put 'org-self-insert-command 'delete-selection
20308 (lambda ()
20309 (not (run-hook-with-args-until-success
20310 'self-insert-uses-region-functions))))
20311 (put 'orgtbl-self-insert-command 'delete-selection
20312 (lambda ()
20313 (not (run-hook-with-args-until-success
20314 'self-insert-uses-region-functions))))
20315 (put 'org-delete-char 'delete-selection 'supersede)
20316 (put 'org-delete-backward-char 'delete-selection 'supersede)
20317 (put 'org-yank 'delete-selection 'yank)
20319 ;; Make `flyspell-mode' delay after some commands
20320 (put 'org-self-insert-command 'flyspell-delayed t)
20321 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20322 (put 'org-delete-char 'flyspell-delayed t)
20323 (put 'org-delete-backward-char 'flyspell-delayed t)
20325 ;; Make pabbrev-mode expand after Org mode commands
20326 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20327 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20329 (defun org-remap (map &rest commands)
20330 "In MAP, remap the functions given in COMMANDS.
20331 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20332 (let (new old)
20333 (while commands
20334 (setq old (pop commands) new (pop commands))
20335 (org-defkey map (vector 'remap old) new))))
20337 (defun org-transpose-words ()
20338 "Transpose words for Org.
20339 This uses the `org-mode-transpose-word-syntax-table' syntax
20340 table, which interprets characters in `org-emphasis-alist' as
20341 word constituents."
20342 (interactive)
20343 (with-syntax-table org-mode-transpose-word-syntax-table
20344 (call-interactively 'transpose-words)))
20345 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20347 (when (eq org-enable-table-editor 'optimized)
20348 ;; If the user wants maximum table support, we need to hijack
20349 ;; some standard editing functions
20350 (org-remap org-mode-map
20351 'self-insert-command 'org-self-insert-command
20352 'delete-char 'org-delete-char
20353 'delete-backward-char 'org-delete-backward-char)
20354 (org-defkey org-mode-map "|" 'org-force-self-insert))
20356 (defvar org-ctrl-c-ctrl-c-hook nil
20357 "Hook for functions attaching themselves to `C-c C-c'.
20359 This can be used to add additional functionality to the C-c C-c
20360 key which executes context-dependent commands. This hook is run
20361 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20362 run after the last test.
20364 Each function will be called with no arguments. The function
20365 must check if the context is appropriate for it to act. If yes,
20366 it should do its thing and then return a non-nil value. If the
20367 context is wrong, just do nothing and return nil.")
20369 (defvar org-ctrl-c-ctrl-c-final-hook nil
20370 "Hook for functions attaching themselves to `C-c C-c'.
20372 This can be used to add additional functionality to the C-c C-c
20373 key which executes context-dependent commands. This hook is run
20374 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20375 before the first test.
20377 Each function will be called with no arguments. The function
20378 must check if the context is appropriate for it to act. If yes,
20379 it should do its thing and then return a non-nil value. If the
20380 context is wrong, just do nothing and return nil.")
20382 (defvar org-tab-first-hook nil
20383 "Hook for functions to attach themselves to TAB.
20384 See `org-ctrl-c-ctrl-c-hook' for more information.
20385 This hook runs as the first action when TAB is pressed, even before
20386 `org-cycle' messes around with the `outline-regexp' to cater for
20387 inline tasks and plain list item folding.
20388 If any function in this hook returns t, any other actions that
20389 would have been caused by TAB (such as table field motion or visibility
20390 cycling) will not occur.")
20392 (defvar org-tab-after-check-for-table-hook nil
20393 "Hook for functions to attach themselves to TAB.
20394 See `org-ctrl-c-ctrl-c-hook' for more information.
20395 This hook runs after it has been established that the cursor is not in a
20396 table, but before checking if the cursor is in a headline or if global cycling
20397 should be done.
20398 If any function in this hook returns t, not other actions like visibility
20399 cycling will be done.")
20401 (defvar org-tab-after-check-for-cycling-hook nil
20402 "Hook for functions to attach themselves to TAB.
20403 See `org-ctrl-c-ctrl-c-hook' for more information.
20404 This hook runs after it has been established that not table field motion and
20405 not visibility should be done because of current context. This is probably
20406 the place where a package like yasnippets can hook in.")
20408 (defvar org-tab-before-tab-emulation-hook nil
20409 "Hook for functions to attach themselves to TAB.
20410 See `org-ctrl-c-ctrl-c-hook' for more information.
20411 This hook runs after every other options for TAB have been exhausted, but
20412 before indentation and \t insertion takes place.")
20414 (defvar org-metaleft-hook nil
20415 "Hook for functions attaching themselves to `M-left'.
20416 See `org-ctrl-c-ctrl-c-hook' for more information.")
20417 (defvar org-metaright-hook nil
20418 "Hook for functions attaching themselves to `M-right'.
20419 See `org-ctrl-c-ctrl-c-hook' for more information.")
20420 (defvar org-metaup-hook nil
20421 "Hook for functions attaching themselves to `M-up'.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.")
20423 (defvar org-metadown-hook nil
20424 "Hook for functions attaching themselves to `M-down'.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20426 (defvar org-shiftmetaleft-hook nil
20427 "Hook for functions attaching themselves to `M-S-left'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-shiftmetaright-hook nil
20430 "Hook for functions attaching themselves to `M-S-right'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-shiftmetaup-hook nil
20433 "Hook for functions attaching themselves to `M-S-up'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftmetadown-hook nil
20436 "Hook for functions attaching themselves to `M-S-down'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-metareturn-hook nil
20439 "Hook for functions attaching themselves to `M-RET'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftup-hook nil
20442 "Hook for functions attaching themselves to `S-up'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftup-final-hook nil
20445 "Hook for functions attaching themselves to `S-up'.
20446 This one runs after all other options except shift-select have been excluded.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-shiftdown-hook nil
20449 "Hook for functions attaching themselves to `S-down'.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-shiftdown-final-hook nil
20452 "Hook for functions attaching themselves to `S-down'.
20453 This one runs after all other options except shift-select have been excluded.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-shiftleft-hook nil
20456 "Hook for functions attaching themselves to `S-left'.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftleft-final-hook nil
20459 "Hook for functions attaching themselves to `S-left'.
20460 This one runs after all other options except shift-select have been excluded.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftright-hook nil
20463 "Hook for functions attaching themselves to `S-right'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftright-final-hook nil
20466 "Hook for functions attaching themselves to `S-right'.
20467 This one runs after all other options except shift-select have been excluded.
20468 See `org-ctrl-c-ctrl-c-hook' for more information.")
20470 (defun org-modifier-cursor-error ()
20471 "Throw an error, a modified cursor command was applied in wrong context."
20472 (user-error "This command is active in special context like tables, headlines or items"))
20474 (defun org-shiftselect-error ()
20475 "Throw an error because Shift-Cursor command was applied in wrong context."
20476 (if (and (boundp 'shift-select-mode) shift-select-mode)
20477 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20478 (user-error "This command works only in special context like headlines or timestamps")))
20480 (defun org-call-for-shift-select (cmd)
20481 (let ((this-command-keys-shift-translated t))
20482 (call-interactively cmd)))
20484 (defun org-shifttab (&optional arg)
20485 "Global visibility cycling or move to previous table field.
20486 Call `org-table-previous-field' within a table.
20487 When ARG is nil, cycle globally through visibility states.
20488 When ARG is a numeric prefix, show contents of this level."
20489 (interactive "P")
20490 (cond
20491 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20492 ((integerp arg)
20493 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20494 (message "Content view to level: %d" arg)
20495 (org-content (prefix-numeric-value arg2))
20496 (org-cycle-show-empty-lines t)
20497 (setq org-cycle-global-status 'overview)))
20498 (t (call-interactively 'org-global-cycle))))
20500 (defun org-shiftmetaleft ()
20501 "Promote subtree or delete table column.
20502 Calls `org-promote-subtree', `org-outdent-item-tree', or
20503 `org-table-delete-column', depending on context. See the
20504 individual commands for more information."
20505 (interactive)
20506 (cond
20507 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20508 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20509 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20510 ((if (not (org-region-active-p)) (org-at-item-p)
20511 (save-excursion (goto-char (region-beginning))
20512 (org-at-item-p)))
20513 (call-interactively 'org-outdent-item-tree))
20514 (t (org-modifier-cursor-error))))
20516 (defun org-shiftmetaright ()
20517 "Demote subtree or insert table column.
20518 Calls `org-demote-subtree', `org-indent-item-tree', or
20519 `org-table-insert-column', depending on context. See the
20520 individual commands for more information."
20521 (interactive)
20522 (cond
20523 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20524 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20525 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20526 ((if (not (org-region-active-p)) (org-at-item-p)
20527 (save-excursion (goto-char (region-beginning))
20528 (org-at-item-p)))
20529 (call-interactively 'org-indent-item-tree))
20530 (t (org-modifier-cursor-error))))
20532 (defun org-shiftmetaup (&optional _arg)
20533 "Drag the line at point up.
20534 In a table, kill the current row.
20535 On a clock timestamp, update the value of the timestamp like `S-<up>'
20536 but also adjust the previous clocked item in the clock history.
20537 Everywhere else, drag the line at point up."
20538 (interactive "P")
20539 (cond
20540 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20541 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20542 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20543 (call-interactively 'org-timestamp-up)))
20544 (t (call-interactively 'org-drag-line-backward))))
20546 (defun org-shiftmetadown (&optional _arg)
20547 "Drag the line at point down.
20548 In a table, insert an empty row at the current line.
20549 On a clock timestamp, update the value of the timestamp like `S-<down>'
20550 but also adjust the previous clocked item in the clock history.
20551 Everywhere else, drag the line at point down."
20552 (interactive "P")
20553 (cond
20554 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20555 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20556 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20557 (call-interactively 'org-timestamp-down)))
20558 (t (call-interactively 'org-drag-line-forward))))
20560 (defsubst org-hidden-tree-error ()
20561 (user-error
20562 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20564 (defun org-metaleft (&optional _arg)
20565 "Promote heading, list item at point or move table column left.
20567 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20568 depending on context. With no specific context, calls the Emacs
20569 default `backward-word'. See the individual commands for more
20570 information.
20572 This function runs the hook `org-metaleft-hook' as a first step,
20573 and returns at first non-nil value."
20574 (interactive "P")
20575 (cond
20576 ((run-hook-with-args-until-success 'org-metaleft-hook))
20577 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20578 ((org-with-limited-levels
20579 (or (org-at-heading-p)
20580 (and (org-region-active-p)
20581 (save-excursion
20582 (goto-char (region-beginning))
20583 (org-at-heading-p)))))
20584 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20585 (call-interactively 'org-do-promote))
20586 ;; At an inline task.
20587 ((org-at-heading-p)
20588 (call-interactively 'org-inlinetask-promote))
20589 ((or (org-at-item-p)
20590 (and (org-region-active-p)
20591 (save-excursion
20592 (goto-char (region-beginning))
20593 (org-at-item-p))))
20594 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20595 (call-interactively 'org-outdent-item))
20596 (t (call-interactively 'backward-word))))
20598 (defun org-metaright (&optional _arg)
20599 "Demote heading, list item at point or move table column right.
20601 In front of a drawer or a block keyword, indent it correctly.
20603 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20604 `org-indent-drawer' or `org-indent-block' depending on context.
20605 With no specific context, calls the Emacs default `forward-word'.
20606 See the individual commands for more information.
20608 This function runs the hook `org-metaright-hook' as a first step,
20609 and returns at first non-nil value."
20610 (interactive "P")
20611 (cond
20612 ((run-hook-with-args-until-success 'org-metaright-hook))
20613 ((org-at-table-p) (call-interactively 'org-table-move-column))
20614 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20615 ((org-at-block-p) (call-interactively 'org-indent-block))
20616 ((org-with-limited-levels
20617 (or (org-at-heading-p)
20618 (and (org-region-active-p)
20619 (save-excursion
20620 (goto-char (region-beginning))
20621 (org-at-heading-p)))))
20622 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20623 (call-interactively 'org-do-demote))
20624 ;; At an inline task.
20625 ((org-at-heading-p)
20626 (call-interactively 'org-inlinetask-demote))
20627 ((or (org-at-item-p)
20628 (and (org-region-active-p)
20629 (save-excursion
20630 (goto-char (region-beginning))
20631 (org-at-item-p))))
20632 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20633 (call-interactively 'org-indent-item))
20634 (t (call-interactively 'forward-word))))
20636 (defun org-check-for-hidden (what)
20637 "Check if there are hidden headlines/items in the current visual line.
20638 WHAT can be either `headlines' or `items'. If the current line is
20639 an outline or item heading and it has a folded subtree below it,
20640 this function returns t, nil otherwise."
20641 (let ((re (cond
20642 ((eq what 'headlines) org-outline-regexp-bol)
20643 ((eq what 'items) (org-item-beginning-re))
20644 (t (error "This should not happen"))))
20645 beg end)
20646 (save-excursion
20647 (catch 'exit
20648 (unless (org-region-active-p)
20649 (setq beg (point-at-bol))
20650 (beginning-of-line 2)
20651 (while (and (not (eobp)) ;; this is like `next-line'
20652 (get-char-property (1- (point)) 'invisible))
20653 (beginning-of-line 2))
20654 (setq end (point))
20655 (goto-char beg)
20656 (goto-char (point-at-eol))
20657 (setq end (max end (point)))
20658 (while (re-search-forward re end t)
20659 (when (get-char-property (match-beginning 0) 'invisible)
20660 (throw 'exit t))))
20661 nil))))
20663 (defun org-metaup (&optional _arg)
20664 "Move subtree up or move table row up.
20665 Calls `org-move-subtree-up' or `org-table-move-row' or
20666 `org-move-item-up', depending on context. See the individual commands
20667 for more information."
20668 (interactive "P")
20669 (cond
20670 ((run-hook-with-args-until-success 'org-metaup-hook))
20671 ((org-region-active-p)
20672 (let* ((a (min (region-beginning) (region-end)))
20673 (b (1- (max (region-beginning) (region-end))))
20674 (c (save-excursion (goto-char a)
20675 (move-beginning-of-line 0)))
20676 (d (save-excursion (goto-char a)
20677 (move-end-of-line 0) (point))))
20678 (transpose-regions a b c d)
20679 (goto-char c)))
20680 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20681 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20682 ((org-at-item-p) (call-interactively 'org-move-item-up))
20683 (t (org-drag-element-backward))))
20685 (defun org-metadown (&optional _arg)
20686 "Move subtree down or move table row down.
20687 Calls `org-move-subtree-down' or `org-table-move-row' or
20688 `org-move-item-down', depending on context. See the individual
20689 commands for more information."
20690 (interactive "P")
20691 (cond
20692 ((run-hook-with-args-until-success 'org-metadown-hook))
20693 ((org-region-active-p)
20694 (let* ((a (min (region-beginning) (region-end)))
20695 (b (max (region-beginning) (region-end)))
20696 (c (save-excursion (goto-char b)
20697 (move-beginning-of-line 1)))
20698 (d (save-excursion (goto-char b)
20699 (move-end-of-line 1) (1+ (point)))))
20700 (transpose-regions a b c d)
20701 (goto-char d)))
20702 ((org-at-table-p) (call-interactively 'org-table-move-row))
20703 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20704 ((org-at-item-p) (call-interactively 'org-move-item-down))
20705 (t (org-drag-element-forward))))
20707 (defun org-shiftup (&optional arg)
20708 "Increase item in timestamp or increase priority of current headline.
20709 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20710 depending on context. See the individual commands for more information."
20711 (interactive "P")
20712 (cond
20713 ((run-hook-with-args-until-success 'org-shiftup-hook))
20714 ((and org-support-shift-select (org-region-active-p))
20715 (org-call-for-shift-select 'previous-line))
20716 ((org-at-timestamp-p t)
20717 (call-interactively (if org-edit-timestamp-down-means-later
20718 'org-timestamp-down 'org-timestamp-up)))
20719 ((and (not (eq org-support-shift-select 'always))
20720 org-enable-priority-commands
20721 (org-at-heading-p))
20722 (call-interactively 'org-priority-up))
20723 ((and (not org-support-shift-select) (org-at-item-p))
20724 (call-interactively 'org-previous-item))
20725 ((org-clocktable-try-shift 'up arg))
20726 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20727 (org-support-shift-select
20728 (org-call-for-shift-select 'previous-line))
20729 (t (org-shiftselect-error))))
20731 (defun org-shiftdown (&optional arg)
20732 "Decrease item in timestamp or decrease priority of current headline.
20733 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20734 depending on context. See the individual commands for more information."
20735 (interactive "P")
20736 (cond
20737 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20738 ((and org-support-shift-select (org-region-active-p))
20739 (org-call-for-shift-select 'next-line))
20740 ((org-at-timestamp-p t)
20741 (call-interactively (if org-edit-timestamp-down-means-later
20742 'org-timestamp-up 'org-timestamp-down)))
20743 ((and (not (eq org-support-shift-select 'always))
20744 org-enable-priority-commands
20745 (org-at-heading-p))
20746 (call-interactively 'org-priority-down))
20747 ((and (not org-support-shift-select) (org-at-item-p))
20748 (call-interactively 'org-next-item))
20749 ((org-clocktable-try-shift 'down arg))
20750 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20751 (org-support-shift-select
20752 (org-call-for-shift-select 'next-line))
20753 (t (org-shiftselect-error))))
20755 (defun org-shiftright (&optional arg)
20756 "Cycle the thing at point or in the current line, depending on context.
20757 Depending on context, this does one of the following:
20759 - switch a timestamp at point one day into the future
20760 - on a headline, switch to the next TODO keyword.
20761 - on an item, switch entire list to the next bullet type
20762 - on a property line, switch to the next allowed value
20763 - on a clocktable definition line, move time block into the future"
20764 (interactive "P")
20765 (cond
20766 ((run-hook-with-args-until-success 'org-shiftright-hook))
20767 ((and org-support-shift-select (org-region-active-p))
20768 (org-call-for-shift-select 'forward-char))
20769 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20770 ((and (not (eq org-support-shift-select 'always))
20771 (org-at-heading-p))
20772 (let ((org-inhibit-logging
20773 (not org-treat-S-cursor-todo-selection-as-state-change))
20774 (org-inhibit-blocking
20775 (not org-treat-S-cursor-todo-selection-as-state-change)))
20776 (org-call-with-arg 'org-todo 'right)))
20777 ((or (and org-support-shift-select
20778 (not (eq org-support-shift-select 'always))
20779 (org-at-item-bullet-p))
20780 (and (not org-support-shift-select) (org-at-item-p)))
20781 (org-call-with-arg 'org-cycle-list-bullet nil))
20782 ((and (not (eq org-support-shift-select 'always))
20783 (org-at-property-p))
20784 (call-interactively 'org-property-next-allowed-value))
20785 ((org-clocktable-try-shift 'right arg))
20786 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20787 (org-support-shift-select
20788 (org-call-for-shift-select 'forward-char))
20789 (t (org-shiftselect-error))))
20791 (defun org-shiftleft (&optional arg)
20792 "Cycle the thing at point or in the current line, depending on context.
20793 Depending on context, this does one of the following:
20795 - switch a timestamp at point one day into the past
20796 - on a headline, switch to the previous TODO keyword.
20797 - on an item, switch entire list to the previous bullet type
20798 - on a property line, switch to the previous allowed value
20799 - on a clocktable definition line, move time block into the past"
20800 (interactive "P")
20801 (cond
20802 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20803 ((and org-support-shift-select (org-region-active-p))
20804 (org-call-for-shift-select 'backward-char))
20805 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20806 ((and (not (eq org-support-shift-select 'always))
20807 (org-at-heading-p))
20808 (let ((org-inhibit-logging
20809 (not org-treat-S-cursor-todo-selection-as-state-change))
20810 (org-inhibit-blocking
20811 (not org-treat-S-cursor-todo-selection-as-state-change)))
20812 (org-call-with-arg 'org-todo 'left)))
20813 ((or (and org-support-shift-select
20814 (not (eq org-support-shift-select 'always))
20815 (org-at-item-bullet-p))
20816 (and (not org-support-shift-select) (org-at-item-p)))
20817 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20818 ((and (not (eq org-support-shift-select 'always))
20819 (org-at-property-p))
20820 (call-interactively 'org-property-previous-allowed-value))
20821 ((org-clocktable-try-shift 'left arg))
20822 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20823 (org-support-shift-select
20824 (org-call-for-shift-select 'backward-char))
20825 (t (org-shiftselect-error))))
20827 (defun org-shiftcontrolright ()
20828 "Switch to next TODO set."
20829 (interactive)
20830 (cond
20831 ((and org-support-shift-select (org-region-active-p))
20832 (org-call-for-shift-select 'forward-word))
20833 ((and (not (eq org-support-shift-select 'always))
20834 (org-at-heading-p))
20835 (org-call-with-arg 'org-todo 'nextset))
20836 (org-support-shift-select
20837 (org-call-for-shift-select 'forward-word))
20838 (t (org-shiftselect-error))))
20840 (defun org-shiftcontrolleft ()
20841 "Switch to previous TODO set."
20842 (interactive)
20843 (cond
20844 ((and org-support-shift-select (org-region-active-p))
20845 (org-call-for-shift-select 'backward-word))
20846 ((and (not (eq org-support-shift-select 'always))
20847 (org-at-heading-p))
20848 (org-call-with-arg 'org-todo 'previousset))
20849 (org-support-shift-select
20850 (org-call-for-shift-select 'backward-word))
20851 (t (org-shiftselect-error))))
20853 (defun org-shiftcontrolup (&optional n)
20854 "Change timestamps synchronously up in CLOCK log lines.
20855 Optional argument N tells to change by that many units."
20856 (interactive "P")
20857 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20858 (let (org-support-shift-select)
20859 (org-clock-timestamps-up n))
20860 (user-error "Not at a clock log")))
20862 (defun org-shiftcontroldown (&optional n)
20863 "Change timestamps synchronously down in CLOCK log lines.
20864 Optional argument N tells to change by that many units."
20865 (interactive "P")
20866 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20867 (let (org-support-shift-select)
20868 (org-clock-timestamps-down n))
20869 (user-error "Not at a clock log")))
20871 (defun org-increase-number-at-point (&optional inc)
20872 "Increment the number at point.
20873 With an optional prefix numeric argument INC, increment using
20874 this numeric value."
20875 (interactive "p")
20876 (if (not (number-at-point))
20877 (user-error "Not on a number")
20878 (unless inc (setq inc 1))
20879 (let ((pos (point))
20880 (beg (skip-chars-backward "-+^/*0-9eE."))
20881 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20882 (setq nap (buffer-substring-no-properties
20883 (+ pos beg) (+ pos beg end)))
20884 (delete-region (+ pos beg) (+ pos beg end))
20885 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20886 (when (org-at-table-p)
20887 (org-table-align)
20888 (org-table-end-of-field 1))))
20890 (defun org-decrease-number-at-point (&optional inc)
20891 "Decrement the number at point.
20892 With an optional prefix numeric argument INC, decrement using
20893 this numeric value."
20894 (interactive "p")
20895 (org-increase-number-at-point (- (or inc 1))))
20897 (defun org-ctrl-c-ret ()
20898 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20899 (interactive)
20900 (cond
20901 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20902 (t (call-interactively 'org-insert-heading))))
20904 (defun org-find-visible ()
20905 (let ((s (point)))
20906 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20907 (get-char-property s 'invisible)))
20909 (defun org-find-invisible ()
20910 (let ((s (point)))
20911 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20912 (not (get-char-property s 'invisible))))
20915 (defun org-copy-visible (beg end)
20916 "Copy the visible parts of the region."
20917 (interactive "r")
20918 (let (snippets s)
20919 (save-excursion
20920 (save-restriction
20921 (narrow-to-region beg end)
20922 (setq s (goto-char (point-min)))
20923 (while (not (= (point) (point-max)))
20924 (goto-char (org-find-invisible))
20925 (push (buffer-substring s (point)) snippets)
20926 (setq s (goto-char (org-find-visible))))))
20927 (kill-new (apply 'concat (nreverse snippets)))))
20929 (defun org-copy-special ()
20930 "Copy region in table or copy current subtree.
20931 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20932 context. See the individual commands for more information."
20933 (interactive)
20934 (call-interactively
20935 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20937 (defun org-cut-special ()
20938 "Cut region in table or cut current subtree.
20939 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20940 context. See the individual commands for more information."
20941 (interactive)
20942 (call-interactively
20943 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20945 (defun org-paste-special (arg)
20946 "Paste rectangular region into table, or past subtree relative to level.
20947 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20948 See the individual commands for more information."
20949 (interactive "P")
20950 (if (org-at-table-p)
20951 (org-table-paste-rectangle)
20952 (org-paste-subtree arg)))
20954 (defun org-edit-special (&optional arg)
20955 "Call a special editor for the element at point.
20956 When at a table, call the formula editor with `org-table-edit-formulas'.
20957 When in a source code block, call `org-edit-src-code'.
20958 When in a fixed-width region, call `org-edit-fixed-width-region'.
20959 When in an export block, call `org-edit-export-block'.
20960 When at an #+INCLUDE keyword, visit the included file.
20961 When at a footnote reference, call `org-edit-footnote-reference'
20962 On a link, call `ffap' to visit the link at point.
20963 Otherwise, return a user error."
20964 (interactive "P")
20965 (let ((element (org-element-at-point)))
20966 (barf-if-buffer-read-only)
20967 (pcase (org-element-type element)
20968 (`src-block
20969 (if (not arg) (org-edit-src-code)
20970 (let* ((info (org-babel-get-src-block-info))
20971 (lang (nth 0 info))
20972 (params (nth 2 info))
20973 (session (cdr (assq :session params))))
20974 (if (not session) (org-edit-src-code)
20975 ;; At a src-block with a session and function called with
20976 ;; an ARG: switch to the buffer related to the inferior
20977 ;; process.
20978 (switch-to-buffer
20979 (funcall (intern (concat "org-babel-prep-session:" lang))
20980 session params))))))
20981 (`keyword
20982 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20983 (org-open-link-from-string
20984 (format "[[%s]]"
20985 (expand-file-name
20986 (let ((value (org-element-property :value element)))
20987 (cond ((not (org-string-nw-p value))
20988 (user-error "No file to edit"))
20989 ((string-match "\\`\"\\(.*?\\)\"" value)
20990 (match-string 1 value))
20991 ((string-match "\\`[^ \t\"]\\S-*" value)
20992 (match-string 0 value))
20993 (t (user-error "No valid file specified")))))))
20994 (user-error "No special environment to edit here")))
20995 (`table
20996 (if (eq (org-element-property :type element) 'table.el)
20997 (org-edit-table.el)
20998 (call-interactively 'org-table-edit-formulas)))
20999 ;; Only Org tables contain `table-row' type elements.
21000 (`table-row (call-interactively 'org-table-edit-formulas))
21001 (`example-block (org-edit-src-code))
21002 (`export-block (org-edit-export-block))
21003 (`fixed-width (org-edit-fixed-width-region))
21005 ;; No notable element at point. Though, we may be at a link or
21006 ;; a footnote reference, which are objects. Thus, scan deeper.
21007 (let ((context (org-element-context element)))
21008 (pcase (org-element-type context)
21009 (`footnote-reference (org-edit-footnote-reference))
21010 (`inline-src-block (org-edit-inline-src-code))
21011 (`link (call-interactively #'ffap))
21012 (_ (user-error "No special environment to edit here"))))))))
21014 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21015 (defun org-ctrl-c-ctrl-c (&optional arg)
21016 "Set tags in headline, or update according to changed information at point.
21018 This command does many different things, depending on context:
21020 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21021 this is what we do.
21023 - If the cursor is on a statistics cookie, update it.
21025 - If the cursor is in a headline, prompt for tags and insert them
21026 into the current line, aligned to `org-tags-column'. When called
21027 with prefix arg, realign all tags in the current buffer.
21029 - If the cursor is in one of the special #+KEYWORD lines, this
21030 triggers scanning the buffer for these lines and updating the
21031 information.
21033 - If the cursor is inside a table, realign the table. This command
21034 works even if the automatic table editor has been turned off.
21036 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21037 the entire table.
21039 - If the cursor is at a footnote reference or definition, jump to
21040 the corresponding definition or references, respectively.
21042 - If the cursor is a the beginning of a dynamic block, update it.
21044 - If the current buffer is a capture buffer, close note and file it.
21046 - If the cursor is on a <<<target>>>, update radio targets and
21047 corresponding links in this buffer.
21049 - If the cursor is on a numbered item in a plain list, renumber the
21050 ordered list.
21052 - If the cursor is on a checkbox, toggle it.
21054 - If the cursor is on a code block, evaluate it. The variable
21055 `org-confirm-babel-evaluate' can be used to control prompting
21056 before code block evaluation, by default every code block
21057 evaluation requires confirmation. Code block evaluation can be
21058 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21059 (interactive "P")
21060 (cond
21061 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21062 org-occur-highlights)
21063 (and (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 "C-c C-c can do nothing useful at this location"))
21074 (let* ((context (org-element-context))
21075 (type (org-element-type context)))
21076 (cl-case type
21077 ;; When at a link, act according to the parent instead.
21078 (link (setq context (org-element-property :parent context))
21079 (setq type (org-element-type context)))
21080 ;; Unsupported object types: refer to the first supported
21081 ;; element or object containing it.
21082 ((bold code entity export-snippet inline-babel-call inline-src-block
21083 italic latex-fragment line-break macro strike-through subscript
21084 superscript underline verbatim)
21085 (setq context
21086 (org-element-lineage
21087 context '(radio-target paragraph verse-block table-cell)))))
21088 ;; For convenience: at the first line of a paragraph on the
21089 ;; same line as an item, apply function on that item instead.
21090 (when (eq type 'paragraph)
21091 (let ((parent (org-element-property :parent context)))
21092 (when (and (eq (org-element-type parent) 'item)
21093 (= (line-beginning-position)
21094 (org-element-property :begin parent)))
21095 (setq context parent type 'item))))
21096 ;; Act according to type of element or object at point.
21097 (cl-case type
21098 (clock (org-clock-update-time-maybe))
21099 (dynamic-block
21100 (save-excursion
21101 (goto-char (org-element-property :post-affiliated context))
21102 (org-update-dblock)))
21103 (footnote-definition
21104 (goto-char (org-element-property :post-affiliated context))
21105 (call-interactively 'org-footnote-action))
21106 (footnote-reference (call-interactively 'org-footnote-action))
21107 ((headline inlinetask)
21108 (save-excursion (goto-char (org-element-property :begin context))
21109 (call-interactively 'org-set-tags)))
21110 (item
21111 ;; At an item: a double C-u set checkbox to "[-]"
21112 ;; unconditionally, whereas a single one will toggle its
21113 ;; presence. Without a universal argument, if the item
21114 ;; has a checkbox, toggle it. Otherwise repair the list.
21115 (let* ((box (org-element-property :checkbox context))
21116 (struct (org-element-property :structure context))
21117 (old-struct (copy-tree struct))
21118 (parents (org-list-parents-alist struct))
21119 (prevs (org-list-prevs-alist struct))
21120 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21121 (org-list-set-checkbox
21122 (org-element-property :begin context) struct
21123 (cond ((equal arg '(16)) "[-]")
21124 ((and (not box) (equal arg '(4))) "[ ]")
21125 ((or (not box) (equal arg '(4))) nil)
21126 ((eq box 'on) "[ ]")
21127 (t "[X]")))
21128 ;; Mimic `org-list-write-struct' but with grabbing
21129 ;; a return value from `org-list-struct-fix-box'.
21130 (org-list-struct-fix-ind struct parents 2)
21131 (org-list-struct-fix-item-end struct)
21132 (org-list-struct-fix-bul struct prevs)
21133 (org-list-struct-fix-ind struct parents)
21134 (let ((block-item
21135 (org-list-struct-fix-box struct parents prevs orderedp)))
21136 (if (and box (equal struct old-struct))
21137 (if (equal arg '(16))
21138 (message "Checkboxes already reset")
21139 (user-error "Cannot toggle this checkbox: %s"
21140 (if (eq box 'on)
21141 "all subitems checked"
21142 "unchecked subitems")))
21143 (org-list-struct-apply-struct struct old-struct)
21144 (org-update-checkbox-count-maybe))
21145 (when block-item
21146 (message "Checkboxes were removed due to empty box at line %d"
21147 (org-current-line block-item))))))
21148 (keyword
21149 (let ((org-inhibit-startup-visibility-stuff t)
21150 (org-startup-align-all-tables nil))
21151 (when (boundp 'org-table-coordinate-overlays)
21152 (mapc #'delete-overlay org-table-coordinate-overlays)
21153 (setq org-table-coordinate-overlays nil))
21154 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21155 (message "Local setup has been refreshed"))
21156 (plain-list
21157 ;; At a plain list, with a double C-u argument, set
21158 ;; checkboxes of each item to "[-]", whereas a single one
21159 ;; will toggle their presence according to the state of the
21160 ;; first item in the list. Without an argument, repair the
21161 ;; list.
21162 (let* ((begin (org-element-property :contents-begin context))
21163 (beginm (move-marker (make-marker) begin))
21164 (struct (org-element-property :structure context))
21165 (old-struct (copy-tree struct))
21166 (first-box (save-excursion
21167 (goto-char begin)
21168 (looking-at org-list-full-item-re)
21169 (match-string-no-properties 3)))
21170 (new-box (cond ((equal arg '(16)) "[-]")
21171 ((equal arg '(4)) (unless first-box "[ ]"))
21172 ((equal first-box "[X]") "[ ]")
21173 (t "[X]"))))
21174 (cond
21175 (arg
21176 (dolist (pos
21177 (org-list-get-all-items
21178 begin struct (org-list-prevs-alist struct)))
21179 (org-list-set-checkbox pos struct new-box)))
21180 ((and first-box (eq (point) begin))
21181 ;; For convenience, when point is at bol on the first
21182 ;; item of the list and no argument is provided, simply
21183 ;; toggle checkbox of that item, if any.
21184 (org-list-set-checkbox begin struct new-box)))
21185 (org-list-write-struct
21186 struct (org-list-parents-alist struct) old-struct)
21187 (org-update-checkbox-count-maybe)
21188 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21189 ((property-drawer node-property)
21190 (call-interactively 'org-property-action))
21191 ((radio-target target)
21192 (call-interactively 'org-update-radio-target-regexp))
21193 (statistics-cookie
21194 (call-interactively 'org-update-statistics-cookies))
21195 ((table table-cell table-row)
21196 ;; At a table, recalculate every field and align it. Also
21197 ;; send the table if necessary. If the table has
21198 ;; a `table.el' type, just give up. At a table row or
21199 ;; cell, maybe recalculate line but always align table.
21200 (if (eq (org-element-property :type context) 'table.el)
21201 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21202 Use \\[org-edit-special] to edit table.el tables"))
21203 (let ((org-enable-table-editor t))
21204 (if (or (eq type 'table)
21205 ;; Check if point is at a TBLFM line.
21206 (and (eq type 'table-row)
21207 (= (point) (org-element-property :end context))))
21208 (save-excursion
21209 (if (org-at-TBLFM-p)
21210 (progn (require 'org-table)
21211 (org-table-calc-current-TBLFM))
21212 (goto-char (org-element-property :contents-begin context))
21213 (org-call-with-arg 'org-table-recalculate (or arg t))
21214 (orgtbl-send-table 'maybe)))
21215 (org-table-maybe-eval-formula)
21216 (cond (arg (call-interactively 'org-table-recalculate))
21217 ((org-table-maybe-recalculate-line))
21218 (t (org-table-align)))))))
21219 (timestamp (org-timestamp-change 0 'day))
21220 (otherwise
21221 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21222 (user-error
21223 "C-c C-c can do nothing useful at this location")))))))))
21225 (defun org-mode-restart ()
21226 (interactive)
21227 (let ((indent-status (bound-and-true-p org-indent-mode)))
21228 (funcall major-mode)
21229 (hack-local-variables)
21230 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21231 (org-indent-mode -1)))
21232 (message "%s restarted" major-mode))
21234 (defun org-kill-note-or-show-branches ()
21235 "Abort storing current note, or call `outline-show-branches'."
21236 (interactive)
21237 (if (not org-finish-function)
21238 (progn
21239 (outline-hide-subtree)
21240 (call-interactively 'outline-show-branches))
21241 (let ((org-note-abort t))
21242 (funcall org-finish-function))))
21244 (defun org-delete-indentation (&optional ARG)
21245 "Join current line to previous and fix whitespace at join.
21247 If previous line is a headline add to headline title. Otherwise
21248 the function calls `delete-indentation'.
21250 With argument, join this line to following line."
21251 (interactive "*P")
21252 (if (save-excursion
21253 (if ARG (beginning-of-line)
21254 (forward-line -1))
21255 (looking-at org-complex-heading-regexp))
21256 ;; At headline.
21257 (let ((tags-column (when (match-beginning 5)
21258 (save-excursion (goto-char (match-beginning 5))
21259 (current-column))))
21260 (string (concat " " (progn (when ARG (forward-line 1))
21261 (org-trim (delete-and-extract-region
21262 (line-beginning-position)
21263 (line-end-position)))))))
21264 (unless (bobp) (delete-region (point) (1- (point))))
21265 (goto-char (or (match-end 4)
21266 (match-beginning 5)
21267 (match-end 0)))
21268 (skip-chars-backward " \t")
21269 (save-excursion (insert string))
21270 ;; Adjust alignment of tags.
21271 (when tags-column
21272 (org-align-tags-here (if org-auto-align-tags
21273 org-tags-column
21274 tags-column))))
21275 (delete-indentation ARG)))
21277 (defun org-open-line (n)
21278 "Insert a new row in tables, call `open-line' elsewhere.
21279 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21280 As a special case, when a document starts with a table, allow to
21281 call `open-line' on the very first character."
21282 (interactive "*p")
21283 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21284 (org-table-insert-row)
21285 (open-line n)))
21287 (defun org-return (&optional indent)
21288 "Goto next table row or insert a newline.
21290 Calls `org-table-next-row' or `newline', depending on context.
21292 When optional INDENT argument is non-nil, call
21293 `newline-and-indent' instead of `newline'.
21295 When `org-return-follows-link' is non-nil and point is on
21296 a timestamp or a link, call `org-open-at-point'. However, it
21297 will not happen if point is in a table or on a \"dead\"
21298 object (e.g., within a comment). In these case, you need to use
21299 `org-open-at-point' directly."
21300 (interactive)
21301 (let ((context (if org-return-follows-link (org-element-context)
21302 (org-element-at-point))))
21303 (cond
21304 ;; In a table, call `org-table-next-row'.
21305 ((or (and (eq (org-element-type context) 'table)
21306 (>= (point) (org-element-property :contents-begin context))
21307 (< (point) (org-element-property :contents-end context)))
21308 (org-element-lineage context '(table-row table-cell) t))
21309 (org-table-justify-field-maybe)
21310 (call-interactively #'org-table-next-row))
21311 ;; On a link or a timestamp, call `org-open-at-point' if
21312 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21313 ;; locations, e.g., in a comment, as `org-open-at-point'.
21314 ((and org-return-follows-link
21315 (or (org-in-regexp org-ts-regexp-both nil t)
21316 (org-in-regexp org-tsr-regexp-both nil t)
21317 (org-in-regexp org-any-link-re nil t)))
21318 (call-interactively #'org-open-at-point))
21319 ;; Insert newline in heading, but preserve tags.
21320 ((and (not (bolp))
21321 (save-excursion (beginning-of-line)
21322 (looking-at org-complex-heading-regexp)))
21323 ;; At headline. Split line. However, if point is on keyword,
21324 ;; priority cookie or tags, do not break any of them: add
21325 ;; a newline after the headline instead.
21326 (let ((tags-column (and (match-beginning 5)
21327 (save-excursion (goto-char (match-beginning 5))
21328 (current-column))))
21329 (string
21330 (when (and (match-end 4)
21331 (>= (point)
21332 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21333 (<= (point) (match-end 4)))
21334 (delete-and-extract-region (point) (match-end 4)))))
21335 (when (and tags-column string) ; Adjust tag alignment.
21336 (org-align-tags-here
21337 (if org-auto-align-tags org-tags-column tags-column)))
21338 (end-of-line)
21339 (org-show-entry)
21340 (if indent (newline-and-indent) (newline))
21341 (when string (save-excursion (insert (org-trim string))))))
21342 ;; In a list, make sure indenting keeps trailing text within.
21343 ((and indent
21344 (not (eolp))
21345 (org-element-lineage context '(item)))
21346 (let ((trailing-data
21347 (delete-and-extract-region (point) (line-end-position))))
21348 (newline-and-indent)
21349 (save-excursion (insert trailing-data))))
21350 (t (if indent (newline-and-indent) (newline))))))
21352 (defun org-return-indent ()
21353 "Goto next table row or insert a newline and indent.
21354 Calls `org-table-next-row' or `newline-and-indent', depending on
21355 context. See the individual commands for more information."
21356 (interactive)
21357 (org-return t))
21359 (defun org-ctrl-c-star ()
21360 "Compute table, or change heading status of lines.
21361 Calls `org-table-recalculate' or `org-toggle-heading',
21362 depending on context."
21363 (interactive)
21364 (cond
21365 ((org-at-table-p)
21366 (call-interactively 'org-table-recalculate))
21368 ;; Convert all lines in region to list items
21369 (call-interactively 'org-toggle-heading))))
21371 (defun org-ctrl-c-minus ()
21372 "Insert separator line in table or modify bullet status of line.
21373 Also turns a plain line or a region of lines into list items.
21374 Calls `org-table-insert-hline', `org-toggle-item', or
21375 `org-cycle-list-bullet', depending on context."
21376 (interactive)
21377 (cond
21378 ((org-at-table-p)
21379 (call-interactively 'org-table-insert-hline))
21380 ((org-region-active-p)
21381 (call-interactively 'org-toggle-item))
21382 ((org-in-item-p)
21383 (call-interactively 'org-cycle-list-bullet))
21385 (call-interactively 'org-toggle-item))))
21387 (defun org-toggle-heading (&optional nstars)
21388 "Convert headings to normal text, or items or text to headings.
21389 If there is no active region, only convert the current line.
21391 With a \\[universal-argument] prefix, convert the whole list at
21392 point into heading.
21394 In a region:
21396 - If the first non blank line is a headline, remove the stars
21397 from all headlines in the region.
21399 - If it is a normal line, turn each and every normal line (i.e.,
21400 not an heading or an item) in the region into headings. If you
21401 want to convert only the first line of this region, use one
21402 universal prefix argument.
21404 - If it is a plain list item, turn all plain list items into headings.
21406 When converting a line into a heading, the number of stars is chosen
21407 such that the lines become children of the current entry. However,
21408 when a numeric prefix argument is given, its value determines the
21409 number of stars to add."
21410 (interactive "P")
21411 (let ((skip-blanks
21412 (function
21413 ;; Return beginning of first non-blank line, starting from
21414 ;; line at POS.
21415 (lambda (pos)
21416 (save-excursion
21417 (goto-char pos)
21418 (while (org-at-comment-p) (forward-line))
21419 (skip-chars-forward " \r\t\n")
21420 (point-at-bol)))))
21421 beg end toggled)
21422 ;; Determine boundaries of changes. If a universal prefix has
21423 ;; been given, put the list in a region. If region ends at a bol,
21424 ;; do not consider the last line to be in the region.
21426 (when (and current-prefix-arg (org-at-item-p))
21427 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21428 (org-mark-element))
21430 (if (org-region-active-p)
21431 (setq beg (funcall skip-blanks (region-beginning))
21432 end (copy-marker (save-excursion
21433 (goto-char (region-end))
21434 (if (bolp) (point) (point-at-eol)))))
21435 (setq beg (funcall skip-blanks (point-at-bol))
21436 end (copy-marker (point-at-eol))))
21437 ;; Ensure inline tasks don't count as headings.
21438 (org-with-limited-levels
21439 (save-excursion
21440 (goto-char beg)
21441 (cond
21442 ;; Case 1. Started at an heading: de-star headings.
21443 ((org-at-heading-p)
21444 (while (< (point) end)
21445 (when (org-at-heading-p t)
21446 (looking-at org-outline-regexp) (replace-match "")
21447 (setq toggled t))
21448 (forward-line)))
21449 ;; Case 2. Started at an item: change items into headlines.
21450 ;; One star will be added by `org-list-to-subtree'.
21451 ((org-at-item-p)
21452 (while (< (point) end)
21453 (when (org-at-item-p)
21454 ;; Pay attention to cases when region ends before list.
21455 (let* ((struct (org-list-struct))
21456 (list-end
21457 (min (org-list-get-bottom-point struct) (1+ end))))
21458 (save-restriction
21459 (narrow-to-region (point) list-end)
21460 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21461 (setq toggled t))
21462 (forward-line)))
21463 ;; Case 3. Started at normal text: make every line an heading,
21464 ;; skipping headlines and items.
21465 (t (let* ((stars
21466 (make-string
21467 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21468 (add-stars
21469 (cond (nstars "") ; stars from prefix only
21470 ((equal stars "") "*") ; before first heading
21471 (org-odd-levels-only "**") ; inside heading, odd
21472 (t "*"))) ; inside heading, oddeven
21473 (rpl (concat stars add-stars " "))
21474 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21475 (while (< (point) (if (equal nstars '(4)) lend end))
21476 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21477 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21478 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21479 (forward-line)))))))
21480 (unless toggled (message "Cannot toggle heading from here"))))
21482 (defun org-meta-return (&optional _arg)
21483 "Insert a new heading or wrap a region in a table.
21484 Calls `org-insert-heading' or `org-table-wrap-region', depending
21485 on context. See the individual commands for more information."
21486 (interactive)
21487 (org-check-before-invisible-edit 'insert)
21488 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21489 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21490 #'org-insert-heading))))
21492 ;;; Menu entries
21494 (defsubst org-in-subtree-not-table-p ()
21495 "Are we in a subtree and not in a table?"
21496 (and (not (org-before-first-heading-p))
21497 (not (org-at-table-p))))
21499 ;; Define the Org mode menus
21500 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21501 '("Tbl"
21502 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21503 ["Next Field" org-cycle (org-at-table-p)]
21504 ["Previous Field" org-shifttab (org-at-table-p)]
21505 ["Next Row" org-return (org-at-table-p)]
21506 "--"
21507 ["Blank Field" org-table-blank-field (org-at-table-p)]
21508 ["Edit Field" org-table-edit-field (org-at-table-p)]
21509 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21510 "--"
21511 ("Column"
21512 ["Move Column Left" org-metaleft (org-at-table-p)]
21513 ["Move Column Right" org-metaright (org-at-table-p)]
21514 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21515 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21516 ("Row"
21517 ["Move Row Up" org-metaup (org-at-table-p)]
21518 ["Move Row Down" org-metadown (org-at-table-p)]
21519 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21520 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21521 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21522 "--"
21523 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21524 ("Rectangle"
21525 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21526 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21527 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21528 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21529 "--"
21530 ("Calculate"
21531 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21532 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21533 ["Edit Formulas" org-edit-special (org-at-table-p)]
21534 "--"
21535 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21536 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21537 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21538 "--"
21539 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21540 "--"
21541 ["Sum Column/Rectangle" org-table-sum
21542 (or (org-at-table-p) (org-region-active-p))]
21543 ["Which Column?" org-table-current-column (org-at-table-p)])
21544 ["Debug Formulas"
21545 org-table-toggle-formula-debugger
21546 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21547 ["Show Col/Row Numbers"
21548 org-table-toggle-coordinate-overlays
21549 :style toggle
21550 :selected (bound-and-true-p org-table-overlay-coordinates)]
21551 "--"
21552 ["Create" org-table-create (and (not (org-at-table-p))
21553 org-enable-table-editor)]
21554 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21555 ["Import from File" org-table-import (not (org-at-table-p))]
21556 ["Export to File" org-table-export (org-at-table-p)]
21557 "--"
21558 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21559 "--"
21560 ("Plot"
21561 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21562 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21564 (easy-menu-define org-org-menu org-mode-map "Org menu"
21565 '("Org"
21566 ("Show/Hide"
21567 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21568 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21569 ["Sparse Tree..." org-sparse-tree t]
21570 ["Reveal Context" org-reveal t]
21571 ["Show All" outline-show-all t]
21572 "--"
21573 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21574 "--"
21575 ["New Heading" org-insert-heading t]
21576 ("Navigate Headings"
21577 ["Up" outline-up-heading t]
21578 ["Next" outline-next-visible-heading t]
21579 ["Previous" outline-previous-visible-heading t]
21580 ["Next Same Level" outline-forward-same-level t]
21581 ["Previous Same Level" outline-backward-same-level t]
21582 "--"
21583 ["Jump" org-goto t])
21584 ("Edit Structure"
21585 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21586 "--"
21587 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21588 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21589 "--"
21590 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21591 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21593 "--"
21594 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21595 "--"
21596 ["Copy visible text" org-copy-visible t]
21597 "--"
21598 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21599 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21600 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21601 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21602 "--"
21603 ["Sort Region/Children" org-sort t]
21604 "--"
21605 ["Convert to odd levels" org-convert-to-odd-levels t]
21606 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21607 ("Editing"
21608 ["Emphasis..." org-emphasize t]
21609 ["Edit Source Example" org-edit-special t]
21610 "--"
21611 ["Footnote new/jump" org-footnote-action t]
21612 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21613 ("Archive"
21614 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21615 "--"
21616 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21617 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21618 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21620 "--"
21621 ("Hyperlinks"
21622 ["Store Link (Global)" org-store-link t]
21623 ["Find existing link to here" org-occur-link-in-agenda-files t]
21624 ["Insert Link" org-insert-link t]
21625 ["Follow Link" org-open-at-point t]
21626 "--"
21627 ["Next link" org-next-link t]
21628 ["Previous link" org-previous-link t]
21629 "--"
21630 ["Descriptive Links"
21631 org-toggle-link-display
21632 :style radio
21633 :selected org-descriptive-links
21635 ["Literal Links"
21636 org-toggle-link-display
21637 :style radio
21638 :selected (not org-descriptive-links)])
21639 "--"
21640 ("TODO Lists"
21641 ["TODO/DONE/-" org-todo t]
21642 ("Select keyword"
21643 ["Next keyword" org-shiftright (org-at-heading-p)]
21644 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21645 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21646 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21647 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21648 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21649 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21650 "--"
21651 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21652 :selected org-enforce-todo-dependencies :style toggle :active t]
21653 "Settings for tree at point"
21654 ["Do Children sequentially" org-toggle-ordered-property :style radio
21655 :selected (org-entry-get nil "ORDERED")
21656 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21657 ["Do Children parallel" org-toggle-ordered-property :style radio
21658 :selected (not (org-entry-get nil "ORDERED"))
21659 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21660 "--"
21661 ["Set Priority" org-priority t]
21662 ["Priority Up" org-shiftup t]
21663 ["Priority Down" org-shiftdown t]
21664 "--"
21665 ["Get news from all feeds" org-feed-update-all t]
21666 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21667 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21668 ("TAGS and Properties"
21669 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21670 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21671 "--"
21672 ["Set property" org-set-property (not (org-before-first-heading-p))]
21673 ["Column view of properties" org-columns t]
21674 ["Insert Column View DBlock" org-columns-insert-dblock t])
21675 ("Dates and Scheduling"
21676 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21677 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21678 ("Change Date"
21679 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21680 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21681 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21682 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21683 ["Compute Time Range" org-evaluate-time-range t]
21684 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21685 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21686 "--"
21687 ["Custom time format" org-toggle-time-stamp-overlays
21688 :style radio :selected org-display-custom-times]
21689 "--"
21690 ["Goto Calendar" org-goto-calendar t]
21691 ["Date from Calendar" org-date-from-calendar t]
21692 "--"
21693 ["Start/Restart Timer" org-timer-start t]
21694 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21695 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21696 ["Insert Timer String" org-timer t]
21697 ["Insert Timer Item" org-timer-item t])
21698 ("Logging work"
21699 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21700 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21701 ["Clock out" org-clock-out t]
21702 ["Clock cancel" org-clock-cancel t]
21703 "--"
21704 ["Mark as default task" org-clock-mark-default-task t]
21705 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21706 ["Goto running clock" org-clock-goto t]
21707 "--"
21708 ["Display times" org-clock-display t]
21709 ["Create clock table" org-clock-report t]
21710 "--"
21711 ["Record DONE time"
21712 (progn (setq org-log-done (not org-log-done))
21713 (message "Switching to %s will %s record a timestamp"
21714 (car org-done-keywords)
21715 (if org-log-done "automatically" "not")))
21716 :style toggle :selected org-log-done])
21717 "--"
21718 ["Agenda Command..." org-agenda t]
21719 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21720 ("File List for Agenda")
21721 ("Special views current file"
21722 ["TODO Tree" org-show-todo-tree t]
21723 ["Check Deadlines" org-check-deadlines t]
21724 ["Timeline" org-timeline t]
21725 ["Tags/Property tree" org-match-sparse-tree t])
21726 "--"
21727 ["Export/Publish..." org-export-dispatch t]
21728 ("LaTeX"
21729 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21730 :selected org-cdlatex-mode]
21731 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21732 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21733 ["Modify math symbol" org-cdlatex-math-modify
21734 (org-inside-LaTeX-fragment-p)]
21735 ["Insert citation" org-reftex-citation t])
21736 "--"
21737 ("MobileOrg"
21738 ["Push Files and Views" org-mobile-push t]
21739 ["Get Captured and Flagged" org-mobile-pull t]
21740 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21741 "--"
21742 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21743 "--"
21744 ("Documentation"
21745 ["Show Version" org-version t]
21746 ["Info Documentation" org-info t])
21747 ("Customize"
21748 ["Browse Org Group" org-customize t]
21749 "--"
21750 ["Expand This Menu" org-create-customize-menu
21751 (fboundp 'customize-menu-create)])
21752 ["Send bug report" org-submit-bug-report t]
21753 "--"
21754 ("Refresh/Reload"
21755 ["Refresh setup current buffer" org-mode-restart t]
21756 ["Reload Org (after update)" org-reload t]
21757 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21760 (defun org-info (&optional node)
21761 "Read documentation for Org in the info system.
21762 With optional NODE, go directly to that node."
21763 (interactive)
21764 (info (format "(org)%s" (or node ""))))
21766 ;;;###autoload
21767 (defun org-submit-bug-report ()
21768 "Submit a bug report on Org via mail.
21770 Don't hesitate to report any problems or inaccurate documentation.
21772 If you don't have setup sending mail from (X)Emacs, please copy the
21773 output buffer into your mail program, as it gives us important
21774 information about your Org version and configuration."
21775 (interactive)
21776 (require 'reporter)
21777 (defvar reporter-prompt-for-summary-p)
21778 (org-load-modules-maybe)
21779 (org-require-autoloaded-modules)
21780 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21781 (reporter-submit-bug-report
21782 "emacs-orgmode@gnu.org"
21783 (org-version nil 'full)
21784 (let (list)
21785 (save-window-excursion
21786 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21787 (delete-other-windows)
21788 (erase-buffer)
21789 (insert "You are about to submit a bug report to the Org mailing list.
21791 We would like to add your full Org and Outline configuration to the
21792 bug report. This greatly simplifies the work of the maintainer and
21793 other experts on the mailing list.
21795 HOWEVER, some variables you have customized may contain private
21796 information. The names of customers, colleagues, or friends, might
21797 appear in the form of file names, tags, todo states, or search strings.
21798 If you answer yes to the prompt, you might want to check and remove
21799 such private information before sending the email.")
21800 (add-text-properties (point-min) (point-max) '(face org-warning))
21801 (when (yes-or-no-p "Include your Org configuration ")
21802 (mapatoms
21803 (lambda (v)
21804 (and (boundp v)
21805 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21806 (or (and (symbol-value v)
21807 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21808 (and
21809 (get v 'custom-type) (get v 'standard-value)
21810 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21811 (push v list)))))
21812 (kill-buffer (get-buffer "*Warn about privacy*"))
21813 list))
21814 nil nil
21815 "Remember to cover the basics, that is, what you expected to happen and
21816 what in fact did happen. You don't know how to make a good report? See
21818 http://orgmode.org/manual/Feedback.html#Feedback
21820 Your bug report will be posted to the Org mailing list.
21821 ------------------------------------------------------------------------")
21822 (save-excursion
21823 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21824 (replace-match "\\1Bug: \\3 [\\2]")))))
21827 (defun org-install-agenda-files-menu ()
21828 (let ((bl (buffer-list)))
21829 (save-excursion
21830 (while bl
21831 (set-buffer (pop bl))
21832 (when (derived-mode-p 'org-mode) (setq bl nil)))
21833 (when (derived-mode-p 'org-mode)
21834 (easy-menu-change
21835 '("Org") "File List for Agenda"
21836 (append
21837 (list
21838 ["Edit File List" (org-edit-agenda-file-list) t]
21839 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21840 ["Remove Current File from List" org-remove-file t]
21841 ["Cycle through agenda files" org-cycle-agenda-files t]
21842 ["Occur in all agenda files" org-occur-in-agenda-files t]
21843 "--")
21844 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21846 ;;;; Documentation
21848 (defun org-require-autoloaded-modules ()
21849 (interactive)
21850 (mapc #'require
21851 '(org-agenda org-archive org-attach org-clock org-colview org-id
21852 org-table org-timer)))
21854 ;;;###autoload
21855 (defun org-reload (&optional uncompiled)
21856 "Reload all org lisp files.
21857 With prefix arg UNCOMPILED, load the uncompiled versions."
21858 (interactive "P")
21859 (require 'loadhist)
21860 (let* ((org-dir (org-find-library-dir "org"))
21861 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21862 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21863 (remove-re (format "\\`%s\\'"
21864 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21865 (feats (delete-dups
21866 (mapcar 'file-name-sans-extension
21867 (mapcar 'file-name-nondirectory
21868 (delq nil
21869 (mapcar 'feature-file
21870 features))))))
21871 (lfeat (append
21872 (sort
21873 (setq feats
21874 (delq nil (mapcar
21875 (lambda (f)
21876 (if (and (string-match feature-re f)
21877 (not (string-match remove-re f)))
21878 f nil))
21879 feats)))
21880 'string-lessp)
21881 (list "org-version" "org")))
21882 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21883 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21884 load-uncore load-misses)
21885 (setq load-misses
21886 (delq 't
21887 (mapcar (lambda (f)
21888 (or (org-load-noerror-mustsuffix (concat org-dir f))
21889 (and (string= org-dir contrib-dir)
21890 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21891 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21892 (add-to-list 'load-uncore f 'append)
21895 lfeat)))
21896 (when load-uncore
21897 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21898 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21899 (if load-misses
21900 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21901 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21902 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21904 ;;;###autoload
21905 (defun org-customize ()
21906 "Call the customize function with org as argument."
21907 (interactive)
21908 (org-load-modules-maybe)
21909 (org-require-autoloaded-modules)
21910 (customize-browse 'org))
21912 (defun org-create-customize-menu ()
21913 "Create a full customization menu for Org-mode, insert it into the menu."
21914 (interactive)
21915 (org-load-modules-maybe)
21916 (org-require-autoloaded-modules)
21917 (if (fboundp 'customize-menu-create)
21918 (progn
21919 (easy-menu-change
21920 '("Org") "Customize"
21921 `(["Browse Org group" org-customize t]
21922 "--"
21923 ,(customize-menu-create 'org)
21924 ["Set" Custom-set t]
21925 ["Save" Custom-save t]
21926 ["Reset to Current" Custom-reset-current t]
21927 ["Reset to Saved" Custom-reset-saved t]
21928 ["Reset to Standard Settings" Custom-reset-standard t]))
21929 (message "\"Org\"-menu now contains full customization menu"))
21930 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21932 ;;;; Miscellaneous stuff
21934 ;;; Generally useful functions
21936 (defun org-get-at-eol (property n)
21937 "Get text property PROPERTY at the end of line less N characters."
21938 (get-text-property (- (point-at-eol) n) property))
21940 (defun org-find-text-property-in-string (prop s)
21941 "Return the first non-nil value of property PROP in string S."
21942 (or (get-text-property 0 prop s)
21943 (get-text-property (or (next-single-property-change 0 prop s) 0)
21944 prop s)))
21946 (defun org-display-warning (message)
21947 "Display the given MESSAGE as a warning."
21948 (display-warning 'org message :warning))
21950 (defun org-eval (form)
21951 "Eval FORM and return result."
21952 (condition-case error
21953 (eval form)
21954 (error (format "%%![Error: %s]" error))))
21956 (defun org-in-clocktable-p ()
21957 "Check if the cursor is in a clocktable."
21958 (let ((pos (point)) start)
21959 (save-excursion
21960 (end-of-line 1)
21961 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21962 (setq start (match-beginning 0))
21963 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21964 (>= (match-end 0) pos)
21965 start))))
21967 (defun org-in-verbatim-emphasis ()
21968 (save-match-data
21969 (and (org-in-regexp org-emph-re 2)
21970 (>= (point) (match-beginning 3))
21971 (<= (point) (match-end 4))
21972 (member (match-string 3) '("=" "~")))))
21974 (defun org-overlay-display (ovl text &optional face evap)
21975 "Make overlay OVL display TEXT with face FACE."
21976 (overlay-put ovl 'display text)
21977 (if face (overlay-put ovl 'face face))
21978 (if evap (overlay-put ovl 'evaporate t)))
21980 (defun org-overlay-before-string (ovl text &optional face evap)
21981 "Make overlay OVL display TEXT with face FACE."
21982 (if face (org-add-props text nil 'face face))
21983 (overlay-put ovl 'before-string text)
21984 (if evap (overlay-put ovl 'evaporate t)))
21986 (defun org-find-overlays (prop &optional pos delete)
21987 "Find all overlays specifying PROP at POS or point.
21988 If DELETE is non-nil, delete all those overlays."
21989 (let (found)
21990 (dolist (ov (overlays-at (or pos (point))) found)
21991 (cond ((not (overlay-get ov prop)))
21992 (delete (delete-overlay ov))
21993 (t (push ov found))))))
21995 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21996 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21997 (if (and marker (marker-buffer marker)
21998 (buffer-live-p (marker-buffer marker)))
21999 (progn
22000 (pop-to-buffer-same-window (marker-buffer marker))
22001 (when (or (> marker (point-max)) (< marker (point-min)))
22002 (widen))
22003 (goto-char marker)
22004 (org-show-context 'org-goto))
22005 (if bookmark
22006 (bookmark-jump bookmark)
22007 (error "Cannot find location"))))
22009 (defun org-quote-csv-field (s)
22010 "Quote field for inclusion in CSV material."
22011 (if (string-match "[\",]" s)
22012 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22015 (defun org-force-self-insert (N)
22016 "Needed to enforce self-insert under remapping."
22017 (interactive "p")
22018 (self-insert-command N))
22020 (defun org-string-width (s)
22021 "Compute width of string, ignoring invisible characters.
22022 This ignores character with invisibility property `org-link', and also
22023 characters with property `org-cwidth', because these will become invisible
22024 upon the next fontification round."
22025 (let (b l)
22026 (when (or (eq t buffer-invisibility-spec)
22027 (assq 'org-link buffer-invisibility-spec))
22028 (while (setq b (text-property-any 0 (length s)
22029 'invisible 'org-link s))
22030 (setq s (concat (substring s 0 b)
22031 (substring s (or (next-single-property-change
22032 b 'invisible s)
22033 (length s)))))))
22034 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22035 (setq s (concat (substring s 0 b)
22036 (substring s (or (next-single-property-change
22037 b 'org-cwidth s)
22038 (length s))))))
22039 (setq l (string-width s) b -1)
22040 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22041 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22044 (defun org-shorten-string (s maxlength)
22045 "Shorten string S so that it is no longer than MAXLENGTH characters.
22046 If the string is shorter or has length MAXLENGTH, just return the
22047 original string. If it is longer, the functions finds a space in the
22048 string, breaks this string off at that locations and adds three dots
22049 as ellipsis. Including the ellipsis, the string will not be longer
22050 than MAXLENGTH. If finding a good breaking point in the string does
22051 not work, the string is just chopped off in the middle of a word
22052 if necessary."
22053 (if (<= (length s) maxlength)
22055 (let* ((n (max (- maxlength 4) 1))
22056 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22057 (if (string-match re s)
22058 (concat (match-string 1 s) "...")
22059 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22061 (defun org-get-indentation (&optional line)
22062 "Get the indentation of the current line, interpreting tabs.
22063 When LINE is given, assume it represents a line and compute its indentation."
22064 (if line
22065 (when (string-match "^ *" (org-remove-tabs line))
22066 (match-end 0))
22067 (save-excursion
22068 (beginning-of-line 1)
22069 (skip-chars-forward " \t")
22070 (current-column))))
22072 (defun org-get-string-indentation (s)
22073 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22074 (let ((n -1) (i 0) (w tab-width) c)
22075 (catch 'exit
22076 (while (< (setq n (1+ n)) (length s))
22077 (setq c (aref s n))
22078 (cond ((= c ?\ ) (setq i (1+ i)))
22079 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22080 (t (throw 'exit t)))))
22083 (defun org-remove-tabs (s &optional width)
22084 "Replace tabulators in S with spaces.
22085 Assumes that s is a single line, starting in column 0."
22086 (setq width (or width tab-width))
22087 (while (string-match "\t" s)
22088 (setq s (replace-match
22089 (make-string
22090 (- (* width (/ (+ (match-beginning 0) width) width))
22091 (match-beginning 0)) ?\ )
22092 t t s)))
22095 (defun org-fix-indentation (line ind)
22096 "Fix indentation in LINE.
22097 IND is a cons cell with target and minimum indentation.
22098 If the current indentation in LINE is smaller than the minimum,
22099 leave it alone. If it is larger than ind, set it to the target."
22100 (let* ((l (org-remove-tabs line))
22101 (i (org-get-indentation l))
22102 (i1 (car ind)) (i2 (cdr ind)))
22103 (when (>= i i2) (setq l (substring line i2)))
22104 (if (> i1 0)
22105 (concat (make-string i1 ?\ ) l)
22106 l)))
22108 (defun org-remove-indentation (code &optional n)
22109 "Remove maximum common indentation in string CODE and return it.
22110 N may optionally be the number of columns to remove. Return CODE
22111 as-is if removal failed."
22112 (with-temp-buffer
22113 (insert code)
22114 (if (org-do-remove-indentation n) (buffer-string) code)))
22116 (defun org-do-remove-indentation (&optional n)
22117 "Remove the maximum common indentation from the buffer.
22118 When optional argument N is a positive integer, remove exactly
22119 that much characters from indentation, if possible. Return nil
22120 if it fails."
22121 (catch :exit
22122 (goto-char (point-min))
22123 ;; Find maximum common indentation, if not specified.
22124 (let ((n (or n
22125 (let ((min-ind (point-max)))
22126 (save-excursion
22127 (while (re-search-forward "^[ \t]*\\S-" nil t)
22128 (let ((ind (1- (current-column))))
22129 (if (zerop ind) (throw :exit nil)
22130 (setq min-ind (min min-ind ind))))))
22131 min-ind))))
22132 (if (zerop n) (throw :exit nil)
22133 ;; Remove exactly N indentation, but give up if not possible.
22134 (while (not (eobp))
22135 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22136 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22137 ((< ind n) (throw :exit nil))
22138 (t (indent-line-to (- ind n))))
22139 (forward-line)))
22140 ;; Signal success.
22141 t))))
22143 (defun org-fill-template (template alist)
22144 "Find each %key of ALIST in TEMPLATE and replace it."
22145 (let ((case-fold-search nil))
22146 (dolist (entry (sort (copy-sequence alist)
22147 (lambda (a b) (< (length (car a)) (length (car b))))))
22148 (setq template
22149 (replace-regexp-in-string
22150 (concat "%" (regexp-quote (car entry)))
22151 (or (cdr entry) "") template t t)))
22152 template))
22154 (defun org-base-buffer (buffer)
22155 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22156 (if (not buffer)
22157 buffer
22158 (or (buffer-base-buffer buffer)
22159 buffer)))
22161 (defun org-wrap (string &optional width lines)
22162 "Wrap string to either a number of lines, or a width in characters.
22163 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22164 that costs. If there is a word longer than WIDTH, the text is actually
22165 wrapped to the length of that word.
22166 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22167 many lines, whatever width that takes.
22168 The return value is a list of lines, without newlines at the end."
22169 (let* ((words (org-split-string string "[ \t\n]+"))
22170 (maxword (apply 'max (mapcar 'org-string-width words)))
22171 w ll)
22172 (cond (width
22173 (org-do-wrap words (max maxword width)))
22174 (lines
22175 (setq w maxword)
22176 (setq ll (org-do-wrap words maxword))
22177 (if (<= (length ll) lines)
22179 (setq ll words)
22180 (while (> (length ll) lines)
22181 (setq w (1+ w))
22182 (setq ll (org-do-wrap words w)))
22183 ll))
22184 (t (error "Cannot wrap this")))))
22186 (defun org-do-wrap (words width)
22187 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22188 (let (lines line)
22189 (while words
22190 (setq line (pop words))
22191 (while (and words (< (+ (length line) (length (car words))) width))
22192 (setq line (concat line " " (pop words))))
22193 (setq lines (push line lines)))
22194 (nreverse lines)))
22196 (defun org-split-string (string &optional separators)
22197 "Splits STRING into substrings at SEPARATORS.
22198 SEPARATORS is a regular expression.
22199 No empty strings are returned if there are matches at the beginning
22200 and end of string."
22201 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22202 (let ((start 0) notfirst list)
22203 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22204 (if (and notfirst
22205 (= start (match-beginning 0))
22206 (< start (length string)))
22207 (1+ start) start))
22208 (< (match-beginning 0) (length string)))
22209 (setq notfirst t)
22210 (or (eq (match-beginning 0) 0)
22211 (and (eq (match-beginning 0) (match-end 0))
22212 (eq (match-beginning 0) start))
22213 (push (substring string start (match-beginning 0)) list))
22214 (setq start (match-end 0)))
22215 (or (eq start (length string))
22216 (push (substring string start) list))
22217 (nreverse list)))
22219 (defun org-quote-vert (s)
22220 "Replace \"|\" with \"\\vert\"."
22221 (while (string-match "|" s)
22222 (setq s (replace-match "\\vert" t t s)))
22225 (defun org-uuidgen-p (s)
22226 "Is S an ID created by UUIDGEN?"
22227 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22229 (defun org-in-src-block-p (&optional inside)
22230 "Whether point is in a code source block.
22231 When INSIDE is non-nil, don't consider we are within a src block
22232 when point is at #+BEGIN_SRC or #+END_SRC."
22233 (let ((case-fold-search t))
22234 (or (and (eq (get-char-property (point) 'src-block) t))
22235 (and (not inside)
22236 (save-match-data
22237 (save-excursion
22238 (beginning-of-line)
22239 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22241 (defun org-context ()
22242 "Return a list of contexts of the current cursor position.
22243 If several contexts apply, all are returned.
22244 Each context entry is a list with a symbol naming the context, and
22245 two positions indicating start and end of the context. Possible
22246 contexts are:
22248 :headline anywhere in a headline
22249 :headline-stars on the leading stars in a headline
22250 :todo-keyword on a TODO keyword (including DONE) in a headline
22251 :tags on the TAGS in a headline
22252 :priority on the priority cookie in a headline
22253 :item on the first line of a plain list item
22254 :item-bullet on the bullet/number of a plain list item
22255 :checkbox on the checkbox in a plain list item
22256 :table in an Org table
22257 :table-special on a special filed in a table
22258 :table-table in a table.el table
22259 :clocktable in a clocktable
22260 :src-block in a source block
22261 :link on a hyperlink
22262 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22263 :target on a <<target>>
22264 :radio-target on a <<<radio-target>>>
22265 :latex-fragment on a LaTeX fragment
22266 :latex-preview on a LaTeX fragment with overlaid preview image
22268 This function expects the position to be visible because it uses font-lock
22269 faces as a help to recognize the following contexts: :table-special, :link,
22270 and :keyword."
22271 (let* ((f (get-text-property (point) 'face))
22272 (faces (if (listp f) f (list f)))
22273 (case-fold-search t)
22274 (p (point)) clist o)
22275 ;; First the large context
22276 (cond
22277 ((org-at-heading-p t)
22278 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22279 (when (progn
22280 (beginning-of-line 1)
22281 (looking-at org-todo-line-tags-regexp))
22282 (push (org-point-in-group p 1 :headline-stars) clist)
22283 (push (org-point-in-group p 2 :todo-keyword) clist)
22284 (push (org-point-in-group p 4 :tags) clist))
22285 (goto-char p)
22286 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22287 (when (looking-at "\\[#[A-Z0-9]\\]")
22288 (push (org-point-in-group p 0 :priority) clist)))
22290 ((org-at-item-p)
22291 (push (org-point-in-group p 2 :item-bullet) clist)
22292 (push (list :item (point-at-bol)
22293 (save-excursion (org-end-of-item) (point)))
22294 clist)
22295 (and (org-at-item-checkbox-p)
22296 (push (org-point-in-group p 0 :checkbox) clist)))
22298 ((org-at-table-p)
22299 (push (list :table (org-table-begin) (org-table-end)) clist)
22300 (when (memq 'org-formula faces)
22301 (push (list :table-special
22302 (previous-single-property-change p 'face)
22303 (next-single-property-change p 'face)) clist)))
22304 ((org-at-table-p 'any)
22305 (push (list :table-table) clist)))
22306 (goto-char p)
22308 (let ((case-fold-search t))
22309 ;; New the "medium" contexts: clocktables, source blocks
22310 (cond ((org-in-clocktable-p)
22311 (push (list :clocktable
22312 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22313 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22314 (match-beginning 1))
22315 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22316 (match-end 0))) clist))
22317 ((org-in-src-block-p)
22318 (push (list :src-block
22319 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22320 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22321 (match-beginning 1))
22322 (and (search-forward "#+END_SRC" nil t)
22323 (match-beginning 0))) clist))))
22324 (goto-char p)
22326 ;; Now the small context
22327 (cond
22328 ((org-at-timestamp-p)
22329 (push (org-point-in-group p 0 :timestamp) clist))
22330 ((memq 'org-link faces)
22331 (push (list :link
22332 (previous-single-property-change p 'face)
22333 (next-single-property-change p 'face)) clist))
22334 ((memq 'org-special-keyword faces)
22335 (push (list :keyword
22336 (previous-single-property-change p 'face)
22337 (next-single-property-change p 'face)) clist))
22338 ((org-at-target-p)
22339 (push (org-point-in-group p 0 :target) clist)
22340 (goto-char (1- (match-beginning 0)))
22341 (when (looking-at org-radio-target-regexp)
22342 (push (org-point-in-group p 0 :radio-target) clist))
22343 (goto-char p))
22344 ((setq o (cl-some
22345 (lambda (o)
22346 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22348 (overlays-at (point))))
22349 (push (list :latex-fragment
22350 (overlay-start o) (overlay-end o)) clist)
22351 (push (list :latex-preview
22352 (overlay-start o) (overlay-end o)) clist))
22353 ((org-inside-LaTeX-fragment-p)
22354 ;; FIXME: positions wrong.
22355 (push (list :latex-fragment (point) (point)) clist)))
22357 (setq clist (nreverse (delq nil clist)))
22358 clist))
22360 (defun org-in-regexp (regexp &optional nlines visually)
22361 "Check if point is inside a match of REGEXP.
22363 Normally only the current line is checked, but you can include
22364 NLINES extra lines around point into the search. If VISUALLY is
22365 set, require that the cursor is not after the match but really
22366 on, so that the block visually is on the match.
22368 Return nil or a cons cell (BEG . END) where BEG and END are,
22369 respectively, the positions at the beginning and the end of the
22370 match."
22371 (catch :exit
22372 (let ((pos (point))
22373 (eol (line-end-position (if nlines (1+ nlines) 1))))
22374 (save-excursion
22375 (beginning-of-line (- 1 (or nlines 0)))
22376 (while (and (re-search-forward regexp eol t)
22377 (<= (match-beginning 0) pos))
22378 (let ((end (match-end 0)))
22379 (when (or (> end pos) (and (= end pos) (not visually)))
22380 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22382 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22383 "Non-nil when point is between matches of START-RE and END-RE.
22385 Also return a non-nil value when point is on one of the matches.
22387 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22388 buffer positions. Default values are the positions of headlines
22389 surrounding the point.
22391 The functions returns a cons cell whose car (resp. cdr) is the
22392 position before START-RE (resp. after END-RE)."
22393 (save-match-data
22394 (let ((pos (point))
22395 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22396 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22397 beg end)
22398 (save-excursion
22399 ;; Point is on a block when on START-RE or if START-RE can be
22400 ;; found before it...
22401 (and (or (org-in-regexp start-re)
22402 (re-search-backward start-re limit-up t))
22403 (setq beg (match-beginning 0))
22404 ;; ... and END-RE after it...
22405 (goto-char (match-end 0))
22406 (re-search-forward end-re limit-down t)
22407 (> (setq end (match-end 0)) pos)
22408 ;; ... without another START-RE in-between.
22409 (goto-char (match-beginning 0))
22410 (not (re-search-backward start-re (1+ beg) t))
22411 ;; Return value.
22412 (cons beg end))))))
22414 (defun org-in-block-p (names)
22415 "Non-nil when point belongs to a block whose name belongs to NAMES.
22417 NAMES is a list of strings containing names of blocks.
22419 Return first block name matched, or nil. Beware that in case of
22420 nested blocks, the returned name may not belong to the closest
22421 block from point."
22422 (save-match-data
22423 (catch 'exit
22424 (let ((case-fold-search t)
22425 (lim-up (save-excursion (outline-previous-heading)))
22426 (lim-down (save-excursion (outline-next-heading))))
22427 (dolist (name names)
22428 (let ((n (regexp-quote name)))
22429 (when (org-between-regexps-p
22430 (concat "^[ \t]*#\\+begin_" n)
22431 (concat "^[ \t]*#\\+end_" n)
22432 lim-up lim-down)
22433 (throw 'exit n)))))
22434 nil)))
22436 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22437 "Call `multi-occur' with buffers for all agenda files."
22438 (interactive "sOrg-files matching: ")
22439 (let* ((files (org-agenda-files))
22440 (tnames (mapcar #'file-truename files))
22441 (extra org-agenda-text-search-extra-files))
22442 (when (eq (car extra) 'agenda-archives)
22443 (setq extra (cdr extra))
22444 (setq files (org-add-archive-files files)))
22445 (dolist (f extra)
22446 (unless (member (file-truename f) tnames)
22447 (unless (member f files) (setq files (append files (list f))))
22448 (setq tnames (append tnames (list (file-truename f))))))
22449 (multi-occur
22450 (mapcar (lambda (x)
22451 (with-current-buffer
22452 ;; FIXME: Why not just (find-file-noselect x)?
22453 ;; Is it to avoid the "revert buffer" prompt?
22454 (or (get-file-buffer x) (find-file-noselect x))
22455 (widen)
22456 (current-buffer)))
22457 files)
22458 regexp)))
22460 (add-hook 'occur-mode-find-occurrence-hook
22461 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22463 (defun org-occur-link-in-agenda-files ()
22464 "Create a link and search for it in the agendas.
22465 The link is not stored in `org-stored-links', it is just created
22466 for the search purpose."
22467 (interactive)
22468 (let ((link (condition-case nil
22469 (org-store-link nil)
22470 (error "Unable to create a link to here"))))
22471 (org-occur-in-agenda-files (regexp-quote link))))
22473 (defun org-reverse-string (string)
22474 "Return the reverse of STRING."
22475 (apply 'string (reverse (string-to-list string))))
22477 ;; defsubst org-uniquify must be defined before first use
22479 (defun org-uniquify-alist (alist)
22480 "Merge elements of ALIST with the same key.
22482 For example, in this alist:
22484 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22485 => \\='((a 1 3) (b 2))
22487 merge (a 1) and (a 3) into (a 1 3).
22489 The function returns the new ALIST."
22490 (let (rtn)
22491 (dolist (e alist rtn)
22492 (let (n)
22493 (if (not (assoc (car e) rtn))
22494 (push e rtn)
22495 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22496 (setq rtn (assq-delete-all (car e) rtn))
22497 (push n rtn))))))
22499 (defun org-delete-all (elts list)
22500 "Remove all elements in ELTS from LIST.
22501 Comparison is done with `equal'. It is a destructive operation
22502 that may remove elements by altering the list structure."
22503 (while elts
22504 (setq list (delete (pop elts) list)))
22505 list)
22507 (defun org-back-over-empty-lines ()
22508 "Move backwards over whitespace, to the beginning of the first empty line.
22509 Returns the number of empty lines passed."
22510 (let ((pos (point)))
22511 (if (cdr (assq 'heading org-blank-before-new-entry))
22512 (skip-chars-backward " \t\n\r")
22513 (unless (eobp)
22514 (forward-line -1)))
22515 (beginning-of-line 2)
22516 (goto-char (min (point) pos))
22517 (count-lines (point) pos)))
22519 (defun org-skip-whitespace ()
22520 (skip-chars-forward " \t\n\r"))
22522 (defun org-point-in-group (point group &optional context)
22523 "Check if POINT is in match-group GROUP.
22524 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22525 match. If the match group does not exist or point is not inside it,
22526 return nil."
22527 (and (match-beginning group)
22528 (>= point (match-beginning group))
22529 (<= point (match-end group))
22530 (if context
22531 (list context (match-beginning group) (match-end group))
22532 t)))
22534 (defun org-switch-to-buffer-other-window (&rest args)
22535 "Switch to buffer in a second window on the current frame.
22536 In particular, do not allow pop-up frames.
22537 Returns the newly created buffer."
22538 (org-no-popups
22539 (apply 'switch-to-buffer-other-window args)))
22541 (defun org-combine-plists (&rest plists)
22542 "Create a single property list from all plists in PLISTS.
22543 The process starts by copying the first list, and then setting properties
22544 from the other lists. Settings in the last list are the most significant
22545 ones and overrule settings in the other lists."
22546 (let ((rtn (copy-sequence (pop plists)))
22547 p v ls)
22548 (while plists
22549 (setq ls (pop plists))
22550 (while ls
22551 (setq p (pop ls) v (pop ls))
22552 (setq rtn (plist-put rtn p v))))
22553 rtn))
22555 (defun org-replace-escapes (string table)
22556 "Replace %-escapes in STRING with values in TABLE.
22557 TABLE is an association list with keys like \"%a\" and string values.
22558 The sequences in STRING may contain normal field width and padding information,
22559 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22560 so values can contain further %-escapes if they are define later in TABLE."
22561 (let ((tbl (copy-alist table))
22562 (case-fold-search nil)
22563 (pchg 0)
22564 re rpl)
22565 (dolist (e tbl)
22566 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22567 (when (and (cdr e) (string-match re (cdr e)))
22568 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22569 (safe "SREF"))
22570 (add-text-properties 0 3 (list 'sref sref) safe)
22571 (setcdr e (replace-match safe t t (cdr e)))))
22572 (while (string-match re string)
22573 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22574 (cdr e)))
22575 (setq string (replace-match rpl t t string))))
22576 (while (setq pchg (next-property-change pchg string))
22577 (let ((sref (get-text-property pchg 'sref string)))
22578 (when (and sref (string-match "SREF" string pchg))
22579 (setq string (replace-match sref t t string)))))
22580 string))
22582 (defun org-find-base-buffer-visiting (file)
22583 "Like `find-buffer-visiting' but always return the base buffer and
22584 not an indirect buffer."
22585 (let ((buf (or (get-file-buffer file)
22586 (find-buffer-visiting file))))
22587 (if buf
22588 (or (buffer-base-buffer buf) buf)
22589 nil)))
22591 ;;; TODO: Only called once, from ox-odt which should probably use
22592 ;;; org-export-inline-image-p or something.
22593 (defun org-file-image-p (file)
22594 "Return non-nil if FILE is an image."
22595 (save-match-data
22596 (string-match (image-file-name-regexp) file)))
22598 (defun org-get-cursor-date (&optional with-time)
22599 "Return the date at cursor in as a time.
22600 This works in the calendar and in the agenda, anywhere else it just
22601 returns the current time.
22602 If WITH-TIME is non-nil, returns the time of the event at point (in
22603 the agenda) or the current time of the day."
22604 (let (date day defd tp hod mod)
22605 (when with-time
22606 (setq tp (get-text-property (point) 'time))
22607 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22608 (setq hod (string-to-number (match-string 1 tp))
22609 mod (string-to-number (match-string 2 tp))))
22610 (or tp (let ((now (decode-time)))
22611 (setq hod (nth 2 now)
22612 mod (nth 1 now)))))
22613 (cond
22614 ((eq major-mode 'calendar-mode)
22615 (setq date (calendar-cursor-to-date)
22616 defd (encode-time 0 (or mod 0) (or hod 0)
22617 (nth 1 date) (nth 0 date) (nth 2 date))))
22618 ((eq major-mode 'org-agenda-mode)
22619 (setq day (get-text-property (point) 'day))
22620 (when day
22621 (setq date (calendar-gregorian-from-absolute day)
22622 defd (encode-time 0 (or mod 0) (or hod 0)
22623 (nth 1 date) (nth 0 date) (nth 2 date))))))
22624 (or defd (current-time))))
22626 (defun org-mark-subtree (&optional up)
22627 "Mark the current subtree.
22628 This puts point at the start of the current subtree, and mark at
22629 the end. If a numeric prefix UP is given, move up into the
22630 hierarchy of headlines by UP levels before marking the subtree."
22631 (interactive "P")
22632 (org-with-limited-levels
22633 (cond ((org-at-heading-p) (beginning-of-line))
22634 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22635 (t (outline-previous-visible-heading 1))))
22636 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22637 (if (called-interactively-p 'any)
22638 (call-interactively 'org-mark-element)
22639 (org-mark-element)))
22641 (defun org-file-newer-than-p (file time)
22642 "Non-nil if FILE is newer than TIME.
22643 FILE is a filename, as a string, TIME is a list of integers, as
22644 returned by, e.g., `current-time'."
22645 (and (file-exists-p file)
22646 ;; Only compare times up to whole seconds as some file-systems
22647 ;; (e.g. HFS+) do not retain any finer granularity. As
22648 ;; a consequence, make sure we return non-nil when the two
22649 ;; times are equal.
22650 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22651 (cl-subseq time 0 2)))))
22653 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22654 "Compile a SOURCE file using PROCESS.
22656 PROCESS is either a function or a list of shell commands, as
22657 strings. EXT is a file extension, without the leading dot, as
22658 a string. It is used to check if the process actually succeeded.
22660 PROCESS must create a file with the same base name and directory
22661 as SOURCE, but ending with EXT. The function then returns its
22662 filename. Otherwise, it raises an error. The error message can
22663 then be refined by providing string ERR-MSG, which is appended to
22664 the standard message.
22666 If PROCESS is a function, it is called with a single argument:
22667 the SOURCE file.
22669 If it is a list of commands, each of them is called using
22670 `shell-command'. By default, in each command, %b, %f, %F and %o
22671 are replaced with, respectively, SOURCE base name, name, full
22672 name and directory. It is possible, however, to use more
22673 place-holders by specifying them in optional argument SPEC, as an
22674 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22676 When PROCESS is a list of commands, optional argument LOG-BUF can
22677 be set to a buffer or a buffer name. `shell-command' then uses
22678 it for output.
22680 `default-directory' is set to SOURCE directory during the whole
22681 process."
22682 (let* ((source-name (file-name-nondirectory source))
22683 (base-name (file-name-sans-extension source-name))
22684 (full-name (file-truename source))
22685 (out-dir (file-name-directory source))
22686 (time (current-time))
22687 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22688 (save-window-excursion
22689 (let ((default-directory (file-name-directory full-name)))
22690 (pcase process
22691 ((pred functionp) (funcall process (shell-quote-argument source)))
22692 ((pred consp)
22693 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22694 (spec (append spec
22695 `((?b . ,(shell-quote-argument base-name))
22696 (?f . ,(shell-quote-argument source-name))
22697 (?F . ,(shell-quote-argument full-name))
22698 (?o . ,(shell-quote-argument out-dir))))))
22699 (dolist (command process)
22700 (shell-command (format-spec command spec) log-buf))))
22701 (_ (error "No valid command to process %S%s" source err-msg)))))
22702 ;; Check for process failure.
22703 (let ((output (concat out-dir base-name "." ext)))
22704 (unless (org-file-newer-than-p output time)
22705 (error (format "File %S wasn't produced%s" output err-msg)))
22706 output)))
22708 ;;; Indentation
22710 (defun org--get-expected-indentation (element contentsp)
22711 "Expected indentation column for current line, according to ELEMENT.
22712 ELEMENT is an element containing point. CONTENTSP is non-nil
22713 when indentation is to be computed according to contents of
22714 ELEMENT."
22715 (let ((type (org-element-type element))
22716 (start (org-element-property :begin element))
22717 (post-affiliated (org-element-property :post-affiliated element)))
22718 (org-with-wide-buffer
22719 (cond
22720 (contentsp
22721 (cl-case type
22722 ((diary-sexp footnote-definition) 0)
22723 ((headline inlinetask nil)
22724 (if (not org-adapt-indentation) 0
22725 (let ((level (org-current-level)))
22726 (if level (1+ level) 0))))
22727 ((item plain-list) (org-list-item-body-column post-affiliated))
22729 (goto-char start)
22730 (org-get-indentation))))
22731 ((memq type '(headline inlinetask nil))
22732 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22733 (org--get-expected-indentation element t)
22735 ((memq type '(diary-sexp footnote-definition)) 0)
22736 ;; First paragraph of a footnote definition or an item.
22737 ;; Indent like parent.
22738 ((< (line-beginning-position) start)
22739 (org--get-expected-indentation
22740 (org-element-property :parent element) t))
22741 ;; At first line: indent according to previous sibling, if any,
22742 ;; ignoring footnote definitions and inline tasks, or parent's
22743 ;; contents.
22744 ((= (line-beginning-position) start)
22745 (catch 'exit
22746 (while t
22747 (if (= (point-min) start) (throw 'exit 0)
22748 (goto-char (1- start))
22749 (let* ((previous (org-element-at-point))
22750 (parent previous))
22751 (while (and parent (<= (org-element-property :end parent) start))
22752 (setq previous parent
22753 parent (org-element-property :parent parent)))
22754 (cond
22755 ((not previous) (throw 'exit 0))
22756 ((> (org-element-property :end previous) start)
22757 (throw 'exit (org--get-expected-indentation previous t)))
22758 ((memq (org-element-type previous)
22759 '(footnote-definition inlinetask))
22760 (setq start (org-element-property :begin previous)))
22761 (t (goto-char (org-element-property :begin previous))
22762 (throw 'exit
22763 (if (bolp) (org-get-indentation)
22764 ;; At first paragraph in an item or
22765 ;; a footnote definition.
22766 (org--get-expected-indentation
22767 (org-element-property :parent previous) t))))))))))
22768 ;; Otherwise, move to the first non-blank line above.
22770 (beginning-of-line)
22771 (let ((pos (point)))
22772 (skip-chars-backward " \r\t\n")
22773 (cond
22774 ;; Two blank lines end a footnote definition or a plain
22775 ;; list. When we indent an empty line after them, the
22776 ;; containing list or footnote definition is over, so it
22777 ;; qualifies as a previous sibling. Therefore, we indent
22778 ;; like its first line.
22779 ((and (memq type '(footnote-definition plain-list))
22780 (> (count-lines (point) pos) 2))
22781 (goto-char start)
22782 (org-get-indentation))
22783 ;; Line above is the first one of a paragraph at the
22784 ;; beginning of an item or a footnote definition. Indent
22785 ;; like parent.
22786 ((< (line-beginning-position) start)
22787 (org--get-expected-indentation
22788 (org-element-property :parent element) t))
22789 ;; Line above is the beginning of an element, i.e., point
22790 ;; was originally on the blank lines between element's start
22791 ;; and contents.
22792 ((= (line-beginning-position) post-affiliated)
22793 (org--get-expected-indentation element t))
22794 ;; POS is after contents in a greater element. Indent like
22795 ;; the beginning of the element.
22797 ;; As a special case, if point is at the end of a footnote
22798 ;; definition or an item, indent like the very last element
22799 ;; within. If that last element is an item, indent like its
22800 ;; contents.
22801 ((and (not (eq type 'paragraph))
22802 (let ((cend (org-element-property :contents-end element)))
22803 (and cend (<= cend pos))))
22804 (if (memq type '(footnote-definition item plain-list))
22805 (let ((last (org-element-at-point)))
22806 (org--get-expected-indentation
22807 last (eq (org-element-type last) 'item)))
22808 (goto-char start)
22809 (org-get-indentation)))
22810 ;; In any other case, indent like the current line.
22811 (t (org-get-indentation)))))))))
22813 (defun org--align-node-property ()
22814 "Align node property at point.
22815 Alignment is done according to `org-property-format', which see."
22816 (when (save-excursion
22817 (beginning-of-line)
22818 (looking-at org-property-re))
22819 (replace-match
22820 (concat (match-string 4)
22821 (org-trim
22822 (format org-property-format (match-string 1) (match-string 3))))
22823 t t)))
22825 (defun org-indent-line ()
22826 "Indent line depending on context.
22828 Indentation is done according to the following rules:
22830 - Footnote definitions, diary sexps, headlines and inline tasks
22831 have to start at column 0.
22833 - On the very first line of an element, consider, in order, the
22834 next rules until one matches:
22836 1. If there's a sibling element before, ignoring footnote
22837 definitions and inline tasks, indent like its first line.
22839 2. If element has a parent, indent like its contents. More
22840 precisely, if parent is an item, indent after the
22841 description part, if any, or the bullet (see
22842 `org-list-description-max-indent'). Else, indent like
22843 parent's first line.
22845 3. Otherwise, indent relatively to current level, if
22846 `org-adapt-indentation' is non-nil, or to left margin.
22848 - On a blank line at the end of an element, indent according to
22849 the type of the element. More precisely
22851 1. If element is a plain list, an item, or a footnote
22852 definition, indent like the very last element within.
22854 2. If element is a paragraph, indent like its last non blank
22855 line.
22857 3. Otherwise, indent like its very first line.
22859 - In the code part of a source block, use language major mode
22860 to indent current line if `org-src-tab-acts-natively' is
22861 non-nil. If it is nil, do nothing.
22863 - Otherwise, indent like the first non-blank line above.
22865 The function doesn't indent an item as it could break the whole
22866 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22867 \\[org-shiftmetaright].
22869 Also align node properties according to `org-property-format'."
22870 (interactive)
22871 (cond
22872 (orgstruct-is-++
22873 (let ((indent-line-function
22874 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22875 (indent-according-to-mode)))
22876 ((org-at-heading-p) 'noindent)
22878 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22879 (type (org-element-type element)))
22880 (cond ((and (memq type '(plain-list item))
22881 (= (line-beginning-position)
22882 (org-element-property :post-affiliated element)))
22883 'noindent)
22884 ((and (eq type 'src-block)
22885 org-src-tab-acts-natively
22886 (> (line-beginning-position)
22887 (org-element-property :post-affiliated element))
22888 (< (line-beginning-position)
22889 (org-with-wide-buffer
22890 (goto-char (org-element-property :end element))
22891 (skip-chars-backward " \r\t\n")
22892 (line-beginning-position))))
22893 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22895 (let ((column (org--get-expected-indentation element nil)))
22896 ;; Preserve current column.
22897 (if (<= (current-column) (current-indentation))
22898 (indent-line-to column)
22899 (save-excursion (indent-line-to column))))
22900 ;; Align node property. Also preserve current column.
22901 (when (eq type 'node-property)
22902 (let ((column (current-column)))
22903 (org--align-node-property)
22904 (org-move-to-column column)))))))))
22906 (defun org-indent-region (start end)
22907 "Indent each non-blank line in the region.
22908 Called from a program, START and END specify the region to
22909 indent. The function will not indent contents of example blocks,
22910 verse blocks and export blocks as leading white spaces are
22911 assumed to be significant there."
22912 (interactive "r")
22913 (save-excursion
22914 (goto-char start)
22915 (skip-chars-forward " \r\t\n")
22916 (unless (eobp) (beginning-of-line))
22917 (let ((indent-to
22918 (lambda (ind pos)
22919 ;; Set IND as indentation for all lines between point and
22920 ;; POS. Blank lines are ignored. Leave point after POS
22921 ;; once done.
22922 (let ((limit (copy-marker pos)))
22923 (while (< (point) limit)
22924 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22925 (forward-line))
22926 (set-marker limit nil))))
22927 (end (copy-marker end)))
22928 (while (< (point) end)
22929 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22930 (let* ((element (org-element-at-point))
22931 (type (org-element-type element))
22932 (element-end (copy-marker (org-element-property :end element)))
22933 (ind (org--get-expected-indentation element nil)))
22934 (cond
22935 ((or (memq type '(paragraph table table-row))
22936 (not (or (org-element-property :contents-begin element)
22937 (memq type
22938 '(example-block export-block src-block)))))
22939 ;; Elements here are indented as a single block. Also
22940 ;; align node properties.
22941 (when (eq type 'node-property)
22942 (org--align-node-property)
22943 (beginning-of-line))
22944 (funcall indent-to ind (min element-end end)))
22946 ;; Elements in this category consist of three parts:
22947 ;; before the contents, the contents, and after the
22948 ;; contents. The contents are treated specially,
22949 ;; according to the element type, or not indented at
22950 ;; all. Other parts are indented as a single block.
22951 (let* ((post (copy-marker
22952 (org-element-property :post-affiliated element)))
22953 (cbeg
22954 (copy-marker
22955 (cond
22956 ((not (org-element-property :contents-begin element))
22957 ;; Fake contents for source blocks.
22958 (org-with-wide-buffer
22959 (goto-char post)
22960 (forward-line)
22961 (point)))
22962 ((memq type '(footnote-definition item plain-list))
22963 ;; Contents in these elements could start on
22964 ;; the same line as the beginning of the
22965 ;; element. Make sure we start indenting
22966 ;; from the second line.
22967 (org-with-wide-buffer
22968 (goto-char post)
22969 (end-of-line)
22970 (skip-chars-forward " \r\t\n")
22971 (if (eobp) (point) (line-beginning-position))))
22972 (t (org-element-property :contents-begin element)))))
22973 (cend (copy-marker
22974 (or (org-element-property :contents-end element)
22975 ;; Fake contents for source blocks.
22976 (org-with-wide-buffer
22977 (goto-char element-end)
22978 (skip-chars-backward " \r\t\n")
22979 (line-beginning-position)))
22980 t)))
22981 ;; Do not change items indentation individually as it
22982 ;; might break the list as a whole. On the other
22983 ;; hand, when at a plain list, indent it as a whole.
22984 (cond ((eq type 'plain-list)
22985 (let ((offset (- ind (org-get-indentation))))
22986 (unless (zerop offset)
22987 (indent-rigidly (org-element-property :begin element)
22988 (org-element-property :end element)
22989 offset))
22990 (goto-char cbeg)))
22991 ((eq type 'item) (goto-char cbeg))
22992 (t (funcall indent-to ind (min cbeg end))))
22993 (when (< (point) end)
22994 (cl-case type
22995 ((example-block export-block verse-block))
22996 (src-block
22997 ;; In a source block, indent source code
22998 ;; according to language major mode, but only if
22999 ;; `org-src-tab-acts-natively' is non-nil.
23000 (when (and (< (point) end) org-src-tab-acts-natively)
23001 (ignore-errors
23002 (org-babel-do-in-edit-buffer
23003 (indent-region (point-min) (point-max))))))
23004 (t (org-indent-region (point) (min cend end))))
23005 (goto-char (min cend end))
23006 (when (< (point) end)
23007 (funcall indent-to ind (min element-end end))))
23008 (set-marker post nil)
23009 (set-marker cbeg nil)
23010 (set-marker cend nil))))
23011 (set-marker element-end nil))))
23012 (set-marker end nil))))
23014 (defun org-indent-drawer ()
23015 "Indent the drawer at point."
23016 (interactive)
23017 (unless (save-excursion
23018 (beginning-of-line)
23019 (looking-at-p org-drawer-regexp))
23020 (user-error "Not at a drawer"))
23021 (let ((element (org-element-at-point)))
23022 (unless (memq (org-element-type element) '(drawer property-drawer))
23023 (user-error "Not at a drawer"))
23024 (org-with-wide-buffer
23025 (org-indent-region (org-element-property :begin element)
23026 (org-element-property :end element))))
23027 (message "Drawer at point indented"))
23029 (defun org-indent-block ()
23030 "Indent the block at point."
23031 (interactive)
23032 (unless (save-excursion
23033 (beginning-of-line)
23034 (let ((case-fold-search t))
23035 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23036 (user-error "Not at a block"))
23037 (let ((element (org-element-at-point)))
23038 (unless (memq (org-element-type element)
23039 '(comment-block center-block dynamic-block example-block
23040 export-block quote-block special-block
23041 src-block verse-block))
23042 (user-error "Not at a block"))
23043 (org-with-wide-buffer
23044 (org-indent-region (org-element-property :begin element)
23045 (org-element-property :end element))))
23046 (message "Block at point indented"))
23049 ;;; Filling
23051 ;; We use our own fill-paragraph and auto-fill functions.
23053 ;; `org-fill-paragraph' relies on adaptive filling and context
23054 ;; checking. Appropriate `fill-prefix' is computed with
23055 ;; `org-adaptive-fill-function'.
23057 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23058 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23059 ;; `org-adaptive-fill-function' value. Internally,
23060 ;; `org-comment-line-break-function' breaks the line.
23062 ;; `org-setup-filling' installs filling and auto-filling related
23063 ;; variables during `org-mode' initialization.
23065 (defvar org-element-paragraph-separate) ; org-element.el
23066 (defun org-setup-filling ()
23067 (require 'org-element)
23068 ;; Prevent auto-fill from inserting unwanted new items.
23069 (when (boundp 'fill-nobreak-predicate)
23070 (setq-local
23071 fill-nobreak-predicate
23072 (org-uniquify
23073 (append fill-nobreak-predicate
23074 '(org-fill-line-break-nobreak-p
23075 org-fill-paragraph-with-timestamp-nobreak-p)))))
23076 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23077 (setq-local paragraph-start paragraph-ending)
23078 (setq-local paragraph-separate paragraph-ending))
23079 (setq-local fill-paragraph-function 'org-fill-paragraph)
23080 (setq-local auto-fill-inhibit-regexp nil)
23081 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23082 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23083 (setq-local comment-line-break-function 'org-comment-line-break-function))
23085 (defun org-fill-line-break-nobreak-p ()
23086 "Non-nil when a new line at point would create an Org line break."
23087 (save-excursion
23088 (skip-chars-backward "[ \t]")
23089 (skip-chars-backward "\\\\")
23090 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23092 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23093 "Non-nil when a new line at point would split a timestamp."
23094 (and (org-at-timestamp-p t)
23095 (not (looking-at org-ts-regexp-both))))
23097 (declare-function message-in-body-p "message" ())
23098 (defvar orgtbl-line-start-regexp) ; From org-table.el
23099 (defun org-adaptive-fill-function ()
23100 "Compute a fill prefix for the current line.
23101 Return fill prefix, as a string, or nil if current line isn't
23102 meant to be filled. For convenience, if `adaptive-fill-regexp'
23103 matches in paragraphs or comments, use it."
23104 (catch 'exit
23105 (when (derived-mode-p 'message-mode)
23106 (save-excursion
23107 (beginning-of-line)
23108 (cond ((not (message-in-body-p)) (throw 'exit nil))
23109 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23110 ((looking-at message-cite-prefix-regexp)
23111 (throw 'exit (match-string-no-properties 0)))
23112 ((looking-at org-outline-regexp)
23113 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23114 (org-with-wide-buffer
23115 (unless (org-at-heading-p)
23116 (let* ((p (line-beginning-position))
23117 (element (save-excursion
23118 (beginning-of-line)
23119 (org-element-at-point)))
23120 (type (org-element-type element))
23121 (post-affiliated (org-element-property :post-affiliated element)))
23122 (unless (< p post-affiliated)
23123 (cl-case type
23124 (comment
23125 (save-excursion
23126 (beginning-of-line)
23127 (looking-at "[ \t]*")
23128 (concat (match-string 0) "# ")))
23129 (footnote-definition "")
23130 ((item plain-list)
23131 (make-string (org-list-item-body-column post-affiliated) ?\s))
23132 (paragraph
23133 ;; Fill prefix is usually the same as the current line,
23134 ;; unless the paragraph is at the beginning of an item.
23135 (let ((parent (org-element-property :parent element)))
23136 (save-excursion
23137 (beginning-of-line)
23138 (cond ((eq (org-element-type parent) 'item)
23139 (make-string (org-list-item-body-column
23140 (org-element-property :begin parent))
23141 ?\s))
23142 ((and adaptive-fill-regexp
23143 ;; Locally disable
23144 ;; `adaptive-fill-function' to let
23145 ;; `fill-context-prefix' handle
23146 ;; `adaptive-fill-regexp' variable.
23147 (let (adaptive-fill-function)
23148 (fill-context-prefix
23149 post-affiliated
23150 (org-element-property :end element)))))
23151 ((looking-at "[ \t]+") (match-string 0))
23152 (t "")))))
23153 (comment-block
23154 ;; Only fill contents if P is within block boundaries.
23155 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23156 (forward-line)
23157 (point)))
23158 (cend (save-excursion
23159 (goto-char (org-element-property :end element))
23160 (skip-chars-backward " \r\t\n")
23161 (line-beginning-position))))
23162 (when (and (>= p cbeg) (< p cend))
23163 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23164 (match-string 0)
23165 "")))))))))))
23167 (declare-function message-goto-body "message" ())
23168 (defvar message-cite-prefix-regexp) ; From message.el
23169 (defun org-fill-paragraph (&optional justify)
23170 "Fill element at point, when applicable.
23172 This function only applies to comment blocks, comments, example
23173 blocks and paragraphs. Also, as a special case, re-align table
23174 when point is at one.
23176 If JUSTIFY is non-nil (interactively, with prefix argument),
23177 justify as well. If `sentence-end-double-space' is non-nil, then
23178 period followed by one space does not end a sentence, so don't
23179 break a line there. The variable `fill-column' controls the
23180 width for filling.
23182 For convenience, when point is at a plain list, an item or
23183 a footnote definition, try to fill the first paragraph within."
23184 (interactive)
23185 (if (and (derived-mode-p 'message-mode)
23186 (or (not (message-in-body-p))
23187 (save-excursion (move-beginning-of-line 1)
23188 (looking-at message-cite-prefix-regexp))))
23189 ;; First ensure filling is correct in message-mode.
23190 (let ((fill-paragraph-function
23191 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23192 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23193 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23194 (paragraph-separate
23195 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23196 (fill-paragraph nil))
23197 (with-syntax-table org-mode-transpose-word-syntax-table
23198 ;; Move to end of line in order to get the first paragraph
23199 ;; within a plain list or a footnote definition.
23200 (let ((element (save-excursion
23201 (end-of-line)
23202 (or (ignore-errors (org-element-at-point))
23203 (user-error "An element cannot be parsed line %d"
23204 (line-number-at-pos (point)))))))
23205 ;; First check if point is in a blank line at the beginning of
23206 ;; the buffer. In that case, ignore filling.
23207 (cl-case (org-element-type element)
23208 ;; Use major mode filling function is src blocks.
23209 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23210 ;; Align Org tables, leave table.el tables as-is.
23211 (table-row (org-table-align) t)
23212 (table
23213 (when (eq (org-element-property :type element) 'org)
23214 (save-excursion
23215 (goto-char (org-element-property :post-affiliated element))
23216 (org-table-align)))
23218 (paragraph
23219 ;; Paragraphs may contain `line-break' type objects.
23220 (let ((beg (max (point-min)
23221 (org-element-property :contents-begin element)))
23222 (end (min (point-max)
23223 (org-element-property :contents-end element))))
23224 ;; Do nothing if point is at an affiliated keyword.
23225 (if (< (line-end-position) beg) t
23226 (when (derived-mode-p 'message-mode)
23227 ;; In `message-mode', do not fill following citation
23228 ;; in current paragraph nor text before message body.
23229 (let ((body-start (save-excursion (message-goto-body))))
23230 (when body-start (setq beg (max body-start beg))))
23231 (when (save-excursion
23232 (re-search-forward
23233 (concat "^" message-cite-prefix-regexp) end t))
23234 (setq end (match-beginning 0))))
23235 ;; Fill paragraph, taking line breaks into account.
23236 (save-excursion
23237 (goto-char beg)
23238 (let ((cuts (list beg)))
23239 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23240 (when (eq 'line-break
23241 (org-element-type
23242 (save-excursion (backward-char)
23243 (org-element-context))))
23244 (push (point) cuts)))
23245 (dolist (c (delq end cuts))
23246 (fill-region-as-paragraph c end justify)
23247 (setq end c))))
23248 t)))
23249 ;; Contents of `comment-block' type elements should be
23250 ;; filled as plain text, but only if point is within block
23251 ;; markers.
23252 (comment-block
23253 (let* ((case-fold-search t)
23254 (beg (save-excursion
23255 (goto-char (org-element-property :begin element))
23256 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23257 (forward-line)
23258 (point)))
23259 (end (save-excursion
23260 (goto-char (org-element-property :end element))
23261 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23262 (line-beginning-position))))
23263 (if (or (< (point) beg) (> (point) end)) t
23264 (fill-region-as-paragraph
23265 (save-excursion (end-of-line)
23266 (re-search-backward "^[ \t]*$" beg 'move)
23267 (line-beginning-position))
23268 (save-excursion (beginning-of-line)
23269 (re-search-forward "^[ \t]*$" end 'move)
23270 (line-beginning-position))
23271 justify))))
23272 ;; Fill comments.
23273 (comment
23274 (let ((begin (org-element-property :post-affiliated element))
23275 (end (org-element-property :end element)))
23276 (when (and (>= (point) begin) (<= (point) end))
23277 (let ((begin (save-excursion
23278 (end-of-line)
23279 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23280 (progn (forward-line) (point))
23281 begin)))
23282 (end (save-excursion
23283 (end-of-line)
23284 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23285 (1- (line-beginning-position))
23286 (skip-chars-backward " \r\t\n")
23287 (line-end-position)))))
23288 ;; Do not fill comments when at a blank line.
23289 (when (> end begin)
23290 (let ((fill-prefix
23291 (save-excursion
23292 (beginning-of-line)
23293 (looking-at "[ \t]*#")
23294 (let ((comment-prefix (match-string 0)))
23295 (goto-char (match-end 0))
23296 (if (looking-at adaptive-fill-regexp)
23297 (concat comment-prefix (match-string 0))
23298 (concat comment-prefix " "))))))
23299 (save-excursion
23300 (fill-region-as-paragraph begin end justify))))))
23302 ;; Ignore every other element.
23303 (otherwise t))))))
23305 (defun org-auto-fill-function ()
23306 "Auto-fill function."
23307 ;; Check if auto-filling is meaningful.
23308 (let ((fc (current-fill-column)))
23309 (when (and fc (> (current-column) fc))
23310 (let* ((fill-prefix (org-adaptive-fill-function))
23311 ;; Enforce empty fill prefix, if required. Otherwise, it
23312 ;; will be computed again.
23313 (adaptive-fill-mode (not (equal fill-prefix ""))))
23314 (when fill-prefix (do-auto-fill))))))
23316 (defun org-comment-line-break-function (&optional soft)
23317 "Break line at point and indent, continuing comment if within one.
23318 The inserted newline is marked hard if variable
23319 `use-hard-newlines' is true, unless optional argument SOFT is
23320 non-nil."
23321 (if soft (insert-and-inherit ?\n) (newline 1))
23322 (save-excursion (forward-char -1) (delete-horizontal-space))
23323 (delete-horizontal-space)
23324 (indent-to-left-margin)
23325 (insert-before-markers-and-inherit fill-prefix))
23328 ;;; Fixed Width Areas
23330 (defun org-toggle-fixed-width ()
23331 "Toggle fixed-width markup.
23333 Add or remove fixed-width markup on current line, whenever it
23334 makes sense. Return an error otherwise.
23336 If a region is active and if it contains only fixed-width areas
23337 or blank lines, remove all fixed-width markup in it. If the
23338 region contains anything else, convert all non-fixed-width lines
23339 to fixed-width ones.
23341 Blank lines at the end of the region are ignored unless the
23342 region only contains such lines."
23343 (interactive)
23344 (if (not (org-region-active-p))
23345 ;; No region:
23347 ;; Remove fixed width marker only in a fixed-with element.
23349 ;; Add fixed width maker in paragraphs, in blank lines after
23350 ;; elements or at the beginning of a headline or an inlinetask,
23351 ;; and before any one-line elements (e.g., a clock).
23352 (progn
23353 (beginning-of-line)
23354 (let* ((element (org-element-at-point))
23355 (type (org-element-type element)))
23356 (cond
23357 ((and (eq type 'fixed-width)
23358 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23359 (replace-match
23360 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23361 ((and (memq type '(babel-call clock comment diary-sexp headline
23362 horizontal-rule keyword paragraph
23363 planning))
23364 (<= (org-element-property :post-affiliated element) (point)))
23365 (skip-chars-forward " \t")
23366 (insert ": "))
23367 ((and (looking-at-p "[ \t]*$")
23368 (or (eq type 'inlinetask)
23369 (save-excursion
23370 (skip-chars-forward " \r\t\n")
23371 (<= (org-element-property :end element) (point)))))
23372 (delete-region (point) (line-end-position))
23373 (org-indent-line)
23374 (insert ": "))
23375 (t (user-error "Cannot insert a fixed-width line here")))))
23376 ;; Region active.
23377 (let* ((begin (save-excursion
23378 (goto-char (region-beginning))
23379 (line-beginning-position)))
23380 (end (copy-marker
23381 (save-excursion
23382 (goto-char (region-end))
23383 (unless (eolp) (beginning-of-line))
23384 (if (save-excursion (re-search-backward "\\S-" begin t))
23385 (progn (skip-chars-backward " \r\t\n") (point))
23386 (point)))))
23387 (all-fixed-width-p
23388 (catch 'not-all-p
23389 (save-excursion
23390 (goto-char begin)
23391 (skip-chars-forward " \r\t\n")
23392 (when (eobp) (throw 'not-all-p nil))
23393 (while (< (point) end)
23394 (let ((element (org-element-at-point)))
23395 (if (eq (org-element-type element) 'fixed-width)
23396 (goto-char (org-element-property :end element))
23397 (throw 'not-all-p nil))))
23398 t))))
23399 (if all-fixed-width-p
23400 (save-excursion
23401 (goto-char begin)
23402 (while (< (point) end)
23403 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23404 (replace-match
23405 "" nil nil nil
23406 (if (= (line-end-position) (match-end 0)) 0 1)))
23407 (forward-line)))
23408 (let ((min-ind (point-max)))
23409 ;; Find minimum indentation across all lines.
23410 (save-excursion
23411 (goto-char begin)
23412 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23413 (setq min-ind 0)
23414 (catch 'zerop
23415 (while (< (point) end)
23416 (unless (looking-at-p "[ \t]*$")
23417 (let ((ind (org-get-indentation)))
23418 (setq min-ind (min min-ind ind))
23419 (when (zerop ind) (throw 'zerop t))))
23420 (forward-line)))))
23421 ;; Loop over all lines and add fixed-width markup everywhere
23422 ;; but in fixed-width lines.
23423 (save-excursion
23424 (goto-char begin)
23425 (while (< (point) end)
23426 (cond
23427 ((org-at-heading-p)
23428 (insert ": ")
23429 (forward-line)
23430 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23431 (insert ":")
23432 (forward-line)))
23433 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23434 (let* ((element (org-element-at-point))
23435 (element-end (org-element-property :end element)))
23436 (if (eq (org-element-type element) 'fixed-width)
23437 (progn (goto-char element-end)
23438 (skip-chars-backward " \r\t\n")
23439 (forward-line))
23440 (let ((limit (min end element-end)))
23441 (while (< (point) limit)
23442 (org-move-to-column min-ind t)
23443 (insert ": ")
23444 (forward-line))))))
23446 (org-move-to-column min-ind t)
23447 (insert ": ")
23448 (forward-line)))))))
23449 (set-marker end nil))))
23452 ;;; Comments
23454 ;; Org comments syntax is quite complex. It requires the entire line
23455 ;; to be just a comment. Also, even with the right syntax at the
23456 ;; beginning of line, some some elements (i.e. verse-block or
23457 ;; example-block) don't accept comments. Usual Emacs comment commands
23458 ;; cannot cope with those requirements. Therefore, Org replaces them.
23460 ;; Org still relies on `comment-dwim', but cannot trust
23461 ;; `comment-only-p'. So, `comment-region-function' and
23462 ;; `uncomment-region-function' both point
23463 ;; to`org-comment-or-uncomment-region'. Eventually,
23464 ;; `org-insert-comment' takes care of insertion of comments at the
23465 ;; beginning of line.
23467 ;; `org-setup-comments-handling' install comments related variables
23468 ;; during `org-mode' initialization.
23470 (defun org-setup-comments-handling ()
23471 (interactive)
23472 (setq-local comment-use-syntax nil)
23473 (setq-local comment-start "# ")
23474 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23475 (setq-local comment-insert-comment-function 'org-insert-comment)
23476 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23477 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23479 (defun org-insert-comment ()
23480 "Insert an empty comment above current line.
23481 If the line is empty, insert comment at its beginning. When
23482 point is within a source block, comment according to the related
23483 major mode."
23484 (if (let ((element (org-element-at-point)))
23485 (and (eq (org-element-type element) 'src-block)
23486 (< (save-excursion
23487 (goto-char (org-element-property :post-affiliated element))
23488 (line-end-position))
23489 (point))
23490 (> (save-excursion
23491 (goto-char (org-element-property :end element))
23492 (skip-chars-backward " \r\t\n")
23493 (line-beginning-position))
23494 (point))))
23495 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23496 (beginning-of-line)
23497 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23498 (open-line 1))
23499 (org-indent-line)
23500 (insert "# ")))
23502 (defvar comment-empty-lines) ; From newcomment.el.
23503 (defun org-comment-or-uncomment-region (beg end &rest _)
23504 "Comment or uncomment each non-blank line in the region.
23505 Uncomment each non-blank line between BEG and END if it only
23506 contains commented lines. Otherwise, comment them. If region is
23507 strictly within a source block, use appropriate comment syntax."
23508 (if (let ((element (org-element-at-point)))
23509 (and (eq (org-element-type element) 'src-block)
23510 (< (save-excursion
23511 (goto-char (org-element-property :post-affiliated element))
23512 (line-end-position))
23513 beg)
23514 (>= (save-excursion
23515 (goto-char (org-element-property :end element))
23516 (skip-chars-backward " \r\t\n")
23517 (line-beginning-position))
23518 end)))
23519 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23520 (save-restriction
23521 ;; Restrict region
23522 (narrow-to-region (save-excursion (goto-char beg)
23523 (skip-chars-forward " \r\t\n" end)
23524 (line-beginning-position))
23525 (save-excursion (goto-char end)
23526 (skip-chars-backward " \r\t\n" beg)
23527 (line-end-position)))
23528 (let ((uncommentp
23529 ;; UNCOMMENTP is non-nil when every non blank line between
23530 ;; BEG and END is a comment.
23531 (save-excursion
23532 (goto-char (point-min))
23533 (while (and (not (eobp))
23534 (let ((element (org-element-at-point)))
23535 (and (eq (org-element-type element) 'comment)
23536 (goto-char (min (point-max)
23537 (org-element-property
23538 :end element)))))))
23539 (eobp))))
23540 (if uncommentp
23541 ;; Only blank lines and comments in region: uncomment it.
23542 (save-excursion
23543 (goto-char (point-min))
23544 (while (not (eobp))
23545 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23546 (replace-match "" nil nil nil 1))
23547 (forward-line)))
23548 ;; Comment each line in region.
23549 (let ((min-indent (point-max)))
23550 ;; First find the minimum indentation across all lines.
23551 (save-excursion
23552 (goto-char (point-min))
23553 (while (and (not (eobp)) (not (zerop min-indent)))
23554 (unless (looking-at "[ \t]*$")
23555 (setq min-indent (min min-indent (current-indentation))))
23556 (forward-line)))
23557 ;; Then loop over all lines.
23558 (save-excursion
23559 (goto-char (point-min))
23560 (while (not (eobp))
23561 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23562 ;; Don't get fooled by invisible text (e.g. link path)
23563 ;; when moving to column MIN-INDENT.
23564 (let ((buffer-invisibility-spec nil))
23565 (org-move-to-column min-indent t))
23566 (insert comment-start))
23567 (forward-line)))))))))
23569 (defun org-comment-dwim (_arg)
23570 "Call `comment-dwim' within a source edit buffer if needed."
23571 (interactive "*P")
23572 (if (org-in-src-block-p)
23573 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23574 (call-interactively 'comment-dwim)))
23577 ;;; Timestamps API
23579 ;; This section contains tools to operate on timestamp objects, as
23580 ;; returned by, e.g. `org-element-context'.
23582 (defun org-timestamp--to-internal-time (timestamp &optional end)
23583 "Encode TIMESTAMP object into Emacs internal time.
23584 Use end of date range or time range when END is non-nil."
23585 (apply #'encode-time
23586 (cons 0
23587 (mapcar
23588 (lambda (prop) (or (org-element-property prop timestamp) 0))
23589 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23590 '(:minute-start :hour-start :day-start :month-start
23591 :year-start))))))
23593 (defun org-timestamp-has-time-p (timestamp)
23594 "Non-nil when TIMESTAMP has a time specified."
23595 (org-element-property :hour-start timestamp))
23597 (defun org-timestamp-format (timestamp format &optional end utc)
23598 "Format a TIMESTAMP object into a string.
23600 FORMAT is a format specifier to be passed to
23601 `format-time-string'.
23603 When optional argument END is non-nil, use end of date-range or
23604 time-range, if possible.
23606 When optional argument UTC is non-nil, time will be expressed as
23607 Universal Time."
23608 (format-time-string
23609 format (org-timestamp--to-internal-time timestamp end)
23610 (and utc t)))
23612 (defun org-timestamp-split-range (timestamp &optional end)
23613 "Extract a TIMESTAMP object from a date or time range.
23615 END, when non-nil, means extract the end of the range.
23616 Otherwise, extract its start.
23618 Return a new timestamp object."
23619 (let ((type (org-element-property :type timestamp)))
23620 (if (memq type '(active inactive diary)) timestamp
23621 (let ((split-ts (org-element-copy timestamp)))
23622 ;; Set new type.
23623 (org-element-put-property
23624 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23625 ;; Copy start properties over end properties if END is
23626 ;; non-nil. Otherwise, copy end properties over `start' ones.
23627 (let ((p-alist '((:minute-start . :minute-end)
23628 (:hour-start . :hour-end)
23629 (:day-start . :day-end)
23630 (:month-start . :month-end)
23631 (:year-start . :year-end))))
23632 (dolist (p-cell p-alist)
23633 (org-element-put-property
23634 split-ts
23635 (funcall (if end #'car #'cdr) p-cell)
23636 (org-element-property
23637 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23638 ;; Eventually refresh `:raw-value'.
23639 (org-element-put-property split-ts :raw-value nil)
23640 (org-element-put-property
23641 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23643 (defun org-timestamp-translate (timestamp &optional boundary)
23644 "Translate TIMESTAMP object to custom format.
23646 Format string is defined in `org-time-stamp-custom-formats',
23647 which see.
23649 When optional argument BOUNDARY is non-nil, it is either the
23650 symbol `start' or `end'. In this case, only translate the
23651 starting or ending part of TIMESTAMP if it is a date or time
23652 range. Otherwise, translate both parts.
23654 Return timestamp as-is if `org-display-custom-times' is nil or if
23655 it has a `diary' type."
23656 (let ((type (org-element-property :type timestamp)))
23657 (if (or (not org-display-custom-times) (eq type 'diary))
23658 (org-element-interpret-data timestamp)
23659 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23660 org-time-stamp-custom-formats)))
23661 (if (and (not boundary) (memq type '(active-range inactive-range)))
23662 (concat (org-timestamp-format timestamp fmt)
23663 "--"
23664 (org-timestamp-format timestamp fmt t))
23665 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23669 ;;; Other stuff.
23671 (defvar reftex-docstruct-symbol)
23672 (defvar org--rds)
23674 (defun org-reftex-citation ()
23675 "Use reftex-citation to insert a citation into the buffer.
23676 This looks for a line like
23678 #+BIBLIOGRAPHY: foo plain option:-d
23680 and derives from it that foo.bib is the bibliography file relevant
23681 for this document. It then installs the necessary environment for RefTeX
23682 to work in this buffer and calls `reftex-citation' to insert a citation
23683 into the buffer.
23685 Export of such citations to both LaTeX and HTML is handled by the contributed
23686 package ox-bibtex by Taru Karttunen."
23687 (interactive)
23688 (let ((reftex-docstruct-symbol 'org--rds)
23689 org--rds bib)
23690 (org-with-wide-buffer
23691 (let ((case-fold-search t)
23692 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23693 (if (not (save-excursion
23694 (or (re-search-forward re nil t)
23695 (re-search-backward re nil t))))
23696 (user-error "No bibliography defined in file")
23697 (setq bib (concat (match-string 1) ".bib")
23698 org--rds (list (list 'bib bib))))))
23699 (call-interactively 'reftex-citation)))
23701 ;;;; Functions extending outline functionality
23703 (defun org-beginning-of-line (&optional arg)
23704 "Go to the beginning of the current line. If that is invisible, continue
23705 to a visible line beginning. This makes the function of C-a more intuitive.
23706 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23707 first attempt, and only move to after the tags when the cursor is already
23708 beyond the end of the headline."
23709 (interactive "P")
23710 (let ((pos (point))
23711 (special (if (consp org-special-ctrl-a/e)
23712 (car org-special-ctrl-a/e)
23713 org-special-ctrl-a/e))
23714 deactivate-mark refpos)
23715 (call-interactively (if (bound-and-true-p visual-line-mode)
23716 #'beginning-of-visual-line
23717 #'move-beginning-of-line))
23718 (cond
23719 ((or arg (not special)))
23720 ((and (looking-at org-complex-heading-regexp)
23721 (eq (char-after (match-end 1)) ?\s))
23722 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23723 (point-at-eol)))
23724 (goto-char
23725 (if (eq special t)
23726 (cond ((> pos refpos) refpos)
23727 ((= pos (point)) refpos)
23728 (t (point)))
23729 (cond ((> pos (point)) (point))
23730 ((not (eq last-command this-command)) (point))
23731 (t refpos)))))
23732 ((org-at-item-p)
23733 ;; Being at an item and not looking at an the item means point
23734 ;; was previously moved to beginning of a visual line, which
23735 ;; doesn't contain the item. Therefore, do nothing special,
23736 ;; just stay here.
23737 (when (looking-at org-list-full-item-re)
23738 ;; Set special position at first white space character after
23739 ;; bullet, and check-box, if any.
23740 (let ((after-bullet
23741 (let ((box (match-end 3)))
23742 (if (not box) (match-end 1)
23743 (let ((after (char-after box)))
23744 (if (and after (= after ? )) (1+ box) box))))))
23745 ;; Special case: Move point to special position when
23746 ;; currently after it or at beginning of line.
23747 (if (eq special t)
23748 (when (or (> pos after-bullet) (= (point) pos))
23749 (goto-char after-bullet))
23750 ;; Reversed case: Move point to special position when
23751 ;; point was already at beginning of line and command is
23752 ;; repeated.
23753 (when (and (= (point) pos) (eq last-command this-command))
23754 (goto-char after-bullet))))))))
23755 (setq disable-point-adjustment
23756 (or (not (invisible-p (point)))
23757 (not (invisible-p (max (point-min) (1- (point))))))))
23759 (defun org-end-of-line (&optional arg)
23760 "Go to the end of the line.
23761 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23762 tags on the first attempt, and only move to after the tags when
23763 the cursor is already beyond the end of the headline."
23764 (interactive "P")
23765 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23766 org-special-ctrl-a/e))
23767 (move-fun (cond ((bound-and-true-p visual-line-mode)
23768 'end-of-visual-line)
23769 ((fboundp 'move-end-of-line) 'move-end-of-line)
23770 (t 'end-of-line)))
23771 deactivate-mark)
23772 (if (or (not special) arg) (call-interactively move-fun)
23773 (let* ((element (save-excursion (beginning-of-line)
23774 (org-element-at-point)))
23775 (type (org-element-type element)))
23776 (cond
23777 ((memq type '(headline inlinetask))
23778 (let ((pos (point)))
23779 (beginning-of-line 1)
23780 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23781 (if (eq special t)
23782 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23783 (goto-char (match-beginning 1))
23784 (goto-char (match-end 0)))
23785 (if (or (< pos (match-end 0))
23786 (not (eq this-command last-command)))
23787 (goto-char (match-end 0))
23788 (goto-char (match-beginning 1))))
23789 (call-interactively move-fun))))
23790 ((outline-invisible-p (line-end-position))
23791 ;; If element is hidden, `move-end-of-line' would put point
23792 ;; after it. Use `end-of-line' to stay on current line.
23793 (call-interactively 'end-of-line))
23794 (t (call-interactively move-fun))))))
23795 (setq disable-point-adjustment
23796 (or (not (invisible-p (point)))
23797 (not (invisible-p (max (point-min) (1- (point))))))))
23799 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23800 (define-key org-mode-map "\C-e" 'org-end-of-line)
23802 (defun org-backward-sentence (&optional _arg)
23803 "Go to beginning of sentence, or beginning of table field.
23804 This will call `backward-sentence' or `org-table-beginning-of-field',
23805 depending on context."
23806 (interactive)
23807 (let* ((element (org-element-at-point))
23808 (contents-begin (org-element-property :contents-begin element))
23809 (table (org-element-lineage element '(table) t)))
23810 (if (and table
23811 (> (point) contents-begin)
23812 (<= (point) (org-element-property :contents-end table)))
23813 (call-interactively #'org-table-beginning-of-field)
23814 (save-restriction
23815 (when (and contents-begin
23816 (< (point-min) contents-begin)
23817 (> (point) contents-begin))
23818 (narrow-to-region contents-begin
23819 (org-element-property :contents-end element)))
23820 (call-interactively #'backward-sentence)))))
23822 (defun org-forward-sentence (&optional _arg)
23823 "Go to end of sentence, or end of table field.
23824 This will call `forward-sentence' or `org-table-end-of-field',
23825 depending on context."
23826 (interactive)
23827 (let* ((element (org-element-at-point))
23828 (contents-end (org-element-property :contents-end element))
23829 (table (org-element-lineage element '(table) t)))
23830 (if (and table
23831 (>= (point) (org-element-property :contents-begin table))
23832 (< (point) contents-end))
23833 (call-interactively #'org-table-end-of-field)
23834 (save-restriction
23835 (when (and contents-end
23836 (> (point-max) contents-end)
23837 ;; Skip blank lines between elements.
23838 (< (org-element-property :end element)
23839 (save-excursion (goto-char contents-end)
23840 (skip-chars-forward " \r\t\n"))))
23841 (narrow-to-region (org-element-property :contents-begin element)
23842 contents-end))
23843 (call-interactively #'forward-sentence)))))
23845 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23846 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23848 (defun org-kill-line (&optional _arg)
23849 "Kill line, to tags or end of line."
23850 (interactive)
23851 (cond
23852 ((or (not org-special-ctrl-k)
23853 (bolp)
23854 (not (org-at-heading-p)))
23855 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23856 org-ctrl-k-protect-subtree
23857 (or (eq org-ctrl-k-protect-subtree 'error)
23858 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23859 (user-error "C-k aborted as it would kill a hidden subtree"))
23860 (call-interactively
23861 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23862 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23863 (kill-region (point) (match-beginning 1))
23864 (org-set-tags nil t))
23865 (t (kill-region (point) (point-at-eol)))))
23867 (define-key org-mode-map "\C-k" 'org-kill-line)
23869 (defun org-yank (&optional arg)
23870 "Yank. If the kill is a subtree, treat it specially.
23871 This command will look at the current kill and check if is a single
23872 subtree, or a series of subtrees[1]. If it passes the test, and if the
23873 cursor is at the beginning of a line or after the stars of a currently
23874 empty headline, then the yank is handled specially. How exactly depends
23875 on the value of the following variables.
23877 `org-yank-folded-subtrees'
23878 By default, this variable is non-nil, which results in
23879 subtree(s) being folded after insertion, except if doing so
23880 would swallow text after the yanked text.
23882 `org-yank-adjusted-subtrees'
23883 When non-nil (the default value is nil), the subtree will be
23884 promoted or demoted in order to fit into the local outline tree
23885 structure, which means that the level will be adjusted so that it
23886 becomes the smaller one of the two *visible* surrounding headings.
23888 Any prefix to this command will cause `yank' to be called directly with
23889 no special treatment. In particular, a simple \\[universal-argument] prefix \
23890 will just
23891 plainly yank the text as it is.
23893 \[1] The test checks if the first non-white line is a heading
23894 and if there are no other headings with fewer stars."
23895 (interactive "P")
23896 (org-yank-generic 'yank arg))
23898 (defun org-yank-generic (command arg)
23899 "Perform some yank-like command.
23901 This function implements the behavior described in the `org-yank'
23902 documentation. However, it has been generalized to work for any
23903 interactive command with similar behavior."
23905 ;; pretend to be command COMMAND
23906 (setq this-command command)
23908 (if arg
23909 (call-interactively command)
23911 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23912 (and (org-kill-is-subtree-p)
23913 (or (bolp)
23914 (and (looking-at "[ \t]*$")
23915 (string-match
23916 "\\`\\*+\\'"
23917 (buffer-substring (point-at-bol) (point)))))))
23918 swallowp)
23919 (cond
23920 ((and subtreep org-yank-folded-subtrees)
23921 (let ((beg (point))
23922 end)
23923 (if (and subtreep org-yank-adjusted-subtrees)
23924 (org-paste-subtree nil nil 'for-yank)
23925 (call-interactively command))
23927 (setq end (point))
23928 (goto-char beg)
23929 (when (and (bolp) subtreep
23930 (not (setq swallowp
23931 (org-yank-folding-would-swallow-text beg end))))
23932 (org-with-limited-levels
23933 (or (looking-at org-outline-regexp)
23934 (re-search-forward org-outline-regexp-bol end t))
23935 (while (and (< (point) end) (looking-at org-outline-regexp))
23936 (outline-hide-subtree)
23937 (org-cycle-show-empty-lines 'folded)
23938 (condition-case nil
23939 (outline-forward-same-level 1)
23940 (error (goto-char end))))))
23941 (when swallowp
23942 (message
23943 "Inserted text not folded because that would swallow text"))
23945 (goto-char end)
23946 (skip-chars-forward " \t\n\r")
23947 (beginning-of-line 1)
23948 (push-mark beg 'nomsg)))
23949 ((and subtreep org-yank-adjusted-subtrees)
23950 (let ((beg (point-at-bol)))
23951 (org-paste-subtree nil nil 'for-yank)
23952 (push-mark beg 'nomsg)))
23954 (call-interactively command))))))
23956 (defun org-yank-folding-would-swallow-text (beg end)
23957 "Would hide-subtree at BEG swallow any text after END?"
23958 (let (level)
23959 (org-with-limited-levels
23960 (save-excursion
23961 (goto-char beg)
23962 (when (or (looking-at org-outline-regexp)
23963 (re-search-forward org-outline-regexp-bol end t))
23964 (setq level (org-outline-level)))
23965 (goto-char end)
23966 (skip-chars-forward " \t\r\n\v\f")
23967 (not (or (eobp)
23968 (and (bolp) (looking-at-p org-outline-regexp)
23969 (<= (org-outline-level) level))))))))
23971 (define-key org-mode-map "\C-y" 'org-yank)
23973 (defun org-truely-invisible-p ()
23974 "Check if point is at a character currently not visible.
23975 This version does not only check the character property, but also
23976 `visible-mode'."
23977 ;; Early versions of noutline don't have `outline-invisible-p'.
23978 (unless (bound-and-true-p visible-mode)
23979 (outline-invisible-p)))
23981 (defun org-invisible-p2 ()
23982 "Check if point is at a character currently not visible."
23983 (save-excursion
23984 (when (and (eolp) (not (bobp))) (backward-char 1))
23985 ;; Early versions of noutline don't have `outline-invisible-p'.
23986 (outline-invisible-p)))
23988 (defun org-back-to-heading (&optional invisible-ok)
23989 "Call `outline-back-to-heading', but provide a better error message."
23990 (condition-case nil
23991 (outline-back-to-heading invisible-ok)
23992 (error (error "Before first headline at position %d in buffer %s"
23993 (point) (current-buffer)))))
23995 (defun org-before-first-heading-p ()
23996 "Before first heading?"
23997 (save-excursion
23998 (end-of-line)
23999 (null (re-search-backward org-outline-regexp-bol nil t))))
24001 (defun org-at-heading-p (&optional ignored)
24002 (outline-on-heading-p t))
24004 (defun org-in-commented-heading-p (&optional no-inheritance)
24005 "Non-nil if point is under a commented heading.
24006 This function also checks ancestors of the current headline,
24007 unless optional argument NO-INHERITANCE is non-nil."
24008 (cond
24009 ((org-before-first-heading-p) nil)
24010 ((let ((headline (nth 4 (org-heading-components))))
24011 (and headline
24012 (let ((case-fold-search nil))
24013 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24014 headline)))))
24015 (no-inheritance nil)
24017 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24019 (defun org-at-comment-p nil
24020 "Is cursor in a commented line?"
24021 (save-excursion
24022 (save-match-data
24023 (beginning-of-line)
24024 (looking-at "^[ \t]*# "))))
24026 (defun org-at-drawer-p nil
24027 "Is cursor at a drawer keyword?"
24028 (save-excursion
24029 (move-beginning-of-line 1)
24030 (looking-at org-drawer-regexp)))
24032 (defun org-at-block-p nil
24033 "Is cursor at a block keyword?"
24034 (save-excursion
24035 (move-beginning-of-line 1)
24036 (looking-at org-block-regexp)))
24038 (defun org-point-at-end-of-empty-headline ()
24039 "If point is at the end of an empty headline, return t, else nil.
24040 If the heading only contains a TODO keyword, it is still still considered
24041 empty."
24042 (and (looking-at "[ \t]*$")
24043 (when org-todo-line-regexp
24044 (save-excursion
24045 (beginning-of-line 1)
24046 (let ((case-fold-search nil))
24047 (looking-at org-todo-line-regexp)
24048 (string= (match-string 3) ""))))))
24050 (defun org-at-heading-or-item-p ()
24051 (or (org-at-heading-p) (org-at-item-p)))
24053 (defun org-at-target-p ()
24054 (or (org-in-regexp org-radio-target-regexp)
24055 (org-in-regexp org-target-regexp)))
24056 ;; Compatibility alias with Org versions < 7.8.03
24057 (defalias 'org-on-target-p 'org-at-target-p)
24059 (defun org-up-heading-all (arg)
24060 "Move to the heading line of which the present line is a subheading.
24061 This function considers both visible and invisible heading lines.
24062 With argument, move up ARG levels."
24063 (outline-up-heading arg t))
24065 (defun org-up-heading-safe ()
24066 "Move to the heading line of which the present line is a subheading.
24067 This version will not throw an error. It will return the level of the
24068 headline found, or nil if no higher level is found.
24070 Also, this function will be a lot faster than `outline-up-heading',
24071 because it relies on stars being the outline starters. This can really
24072 make a significant difference in outlines with very many siblings."
24073 (when (ignore-errors (org-back-to-heading t))
24074 (let ((level-up (1- (funcall outline-level))))
24075 (and (> level-up 0)
24076 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24077 (funcall outline-level)))))
24079 (defun org-first-sibling-p ()
24080 "Is this heading the first child of its parents?"
24081 (interactive)
24082 (let ((re org-outline-regexp-bol)
24083 level l)
24084 (unless (org-at-heading-p t)
24085 (user-error "Not at a heading"))
24086 (setq level (funcall outline-level))
24087 (save-excursion
24088 (if (not (re-search-backward re nil t))
24090 (setq l (funcall outline-level))
24091 (< l level)))))
24093 (defun org-goto-sibling (&optional previous)
24094 "Goto the next sibling, even if it is invisible.
24095 When PREVIOUS is set, go to the previous sibling instead. Returns t
24096 when a sibling was found. When none is found, return nil and don't
24097 move point."
24098 (let ((fun (if previous 're-search-backward 're-search-forward))
24099 (pos (point))
24100 (re org-outline-regexp-bol)
24101 level l)
24102 (when (ignore-errors (org-back-to-heading t))
24103 (setq level (funcall outline-level))
24104 (catch 'exit
24105 (or previous (forward-char 1))
24106 (while (funcall fun re nil t)
24107 (setq l (funcall outline-level))
24108 (when (< l level) (goto-char pos) (throw 'exit nil))
24109 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24110 (goto-char pos)
24111 nil))))
24113 (defun org-show-siblings ()
24114 "Show all siblings of the current headline."
24115 (save-excursion
24116 (while (org-goto-sibling) (org-flag-heading nil)))
24117 (save-excursion
24118 (while (org-goto-sibling 'previous)
24119 (org-flag-heading nil))))
24121 (defun org-goto-first-child ()
24122 "Goto the first child, even if it is invisible.
24123 Return t when a child was found. Otherwise don't move point and
24124 return nil."
24125 (let (level (pos (point)) (re org-outline-regexp-bol))
24126 (when (ignore-errors (org-back-to-heading t))
24127 (setq level (outline-level))
24128 (forward-char 1)
24129 (if (and (re-search-forward re nil t) (> (outline-level) level))
24130 (progn (goto-char (match-beginning 0)) t)
24131 (goto-char pos) nil))))
24133 (defun org-show-hidden-entry ()
24134 "Show an entry where even the heading is hidden."
24135 (save-excursion
24136 (org-show-entry)))
24138 (defun org-flag-heading (flag &optional entry)
24139 "Flag the current heading. FLAG non-nil means make invisible.
24140 When ENTRY is non-nil, show the entire entry."
24141 (save-excursion
24142 (org-back-to-heading t)
24143 ;; Check if we should show the entire entry
24144 (if entry
24145 (progn
24146 (org-show-entry)
24147 (save-excursion
24148 (and (outline-next-heading)
24149 (org-flag-heading nil))))
24150 (outline-flag-region (max (point-min) (1- (point)))
24151 (save-excursion (outline-end-of-heading) (point))
24152 flag))))
24154 (defun org-get-next-sibling ()
24155 "Move to next heading of the same level, and return point.
24156 If there is no such heading, return nil.
24157 This is like outline-next-sibling, but invisible headings are ok."
24158 (let ((level (funcall outline-level)))
24159 (outline-next-heading)
24160 (while (and (not (eobp)) (> (funcall outline-level) level))
24161 (outline-next-heading))
24162 (unless (or (eobp) (< (funcall outline-level) level))
24163 (point))))
24165 (defun org-get-last-sibling ()
24166 "Move to previous heading of the same level, and return point.
24167 If there is no such heading, return nil."
24168 (let ((opoint (point))
24169 (level (funcall outline-level)))
24170 (outline-previous-heading)
24171 (when (and (/= (point) opoint) (outline-on-heading-p t))
24172 (while (and (> (funcall outline-level) level)
24173 (not (bobp)))
24174 (outline-previous-heading))
24175 (unless (< (funcall outline-level) level)
24176 (point)))))
24178 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24179 "Goto to the end of a subtree."
24180 ;; This contains an exact copy of the original function, but it uses
24181 ;; `org-back-to-heading', to make it work also in invisible
24182 ;; trees. And is uses an invisible-ok argument.
24183 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24184 ;; Furthermore, when used inside Org, finding the end of a large subtree
24185 ;; with many children and grandchildren etc, this can be much faster
24186 ;; than the outline version.
24187 (org-back-to-heading invisible-ok)
24188 (let ((first t)
24189 (level (funcall outline-level)))
24190 (if (and (derived-mode-p 'org-mode) (< level 1000))
24191 ;; A true heading (not a plain list item), in Org
24192 ;; This means we can easily find the end by looking
24193 ;; only for the right number of stars. Using a regexp to do
24194 ;; this is so much faster than using a Lisp loop.
24195 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24196 (forward-char 1)
24197 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24198 ;; something else, do it the slow way
24199 (while (and (not (eobp))
24200 (or first (> (funcall outline-level) level)))
24201 (setq first nil)
24202 (outline-next-heading)))
24203 (unless to-heading
24204 (when (memq (preceding-char) '(?\n ?\^M))
24205 ;; Go to end of line before heading
24206 (forward-char -1)
24207 (when (memq (preceding-char) '(?\n ?\^M))
24208 ;; leave blank line before heading
24209 (forward-char -1)))))
24210 (point))
24212 (defun org-end-of-meta-data (&optional full)
24213 "Skip planning line and properties drawer in current entry.
24214 When optional argument FULL is non-nil, also skip empty lines,
24215 clocking lines and regular drawers at the beginning of the
24216 entry."
24217 (org-back-to-heading t)
24218 (forward-line)
24219 (when (looking-at-p org-planning-line-re) (forward-line))
24220 (when (looking-at org-property-drawer-re)
24221 (goto-char (match-end 0))
24222 (forward-line))
24223 (when (and full (not (org-at-heading-p)))
24224 (catch 'exit
24225 (let ((end (save-excursion (outline-next-heading) (point)))
24226 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24227 (while (not (eobp))
24228 (cond ((looking-at-p org-drawer-regexp)
24229 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24230 (forward-line)
24231 (throw 'exit t)))
24232 ((looking-at-p re) (forward-line))
24233 (t (throw 'exit t))))))))
24235 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24236 "Move forward to the ARG'th subheading at same level as this one.
24237 Stop at the first and last subheadings of a superior heading.
24238 Normally this only looks at visible headings, but when INVISIBLE-OK is
24239 non-nil it will also look at invisible ones."
24240 (interactive "p")
24241 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24242 (if (and arg (< arg 0))
24243 (goto-char (point-min))
24244 (outline-next-heading))
24245 (org-at-heading-p)
24246 (let ((level (- (match-end 0) (match-beginning 0) 1))
24247 (f (if (and arg (< arg 0))
24248 're-search-backward
24249 're-search-forward))
24250 (count (if arg (abs arg) 1))
24251 (result (point)))
24252 (while (and (prog1 (> count 0)
24253 (forward-char (if (and arg (< arg 0)) -1 1)))
24254 (funcall f org-outline-regexp-bol nil 'move))
24255 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24256 (cond ((< l level) (setq count 0))
24257 ((and (= l level)
24258 (or invisible-ok
24259 (progn
24260 (goto-char (line-beginning-position))
24261 (not (outline-invisible-p)))))
24262 (setq count (1- count))
24263 (when (eq l level)
24264 (setq result (point)))))))
24265 (goto-char result))
24266 (beginning-of-line 1)))
24268 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24269 "Move backward to the ARG'th subheading at same level as this one.
24270 Stop at the first and last subheadings of a superior heading."
24271 (interactive "p")
24272 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24274 (defun org-next-visible-heading (arg)
24275 "Move to the next visible heading.
24277 This function wraps `outline-next-visible-heading' with
24278 `org-with-limited-levels' in order to skip over inline tasks and
24279 respect customization of `org-odd-levels-only'."
24280 (interactive "p")
24281 (org-with-limited-levels
24282 (outline-next-visible-heading arg)))
24284 (defun org-previous-visible-heading (arg)
24285 "Move to the previous visible heading.
24287 This function wraps `outline-previous-visible-heading' with
24288 `org-with-limited-levels' in order to skip over inline tasks and
24289 respect customization of `org-odd-levels-only'."
24290 (interactive "p")
24291 (org-with-limited-levels
24292 (outline-previous-visible-heading arg)))
24294 (defun org-next-block (arg &optional backward block-regexp)
24295 "Jump to the next block.
24297 With a prefix argument ARG, jump forward ARG many blocks.
24299 When BACKWARD is non-nil, jump to the previous block.
24301 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24302 Match data is set according to this regexp when the function
24303 returns.
24305 Return point at beginning of the opening line of found block.
24306 Throw an error if no block is found."
24307 (interactive "p")
24308 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24309 (case-fold-search t)
24310 (search-fn (if backward #'re-search-backward #'re-search-forward))
24311 (count (or arg 1))
24312 (origin (point))
24313 last-element)
24314 (if backward (beginning-of-line) (end-of-line))
24315 (while (and (> count 0) (funcall search-fn re nil t))
24316 (let ((element (save-excursion
24317 (goto-char (match-beginning 0))
24318 (save-match-data (org-element-at-point)))))
24319 (when (and (memq (org-element-type element)
24320 '(center-block comment-block dynamic-block
24321 example-block export-block quote-block
24322 special-block src-block verse-block))
24323 (<= (match-beginning 0)
24324 (org-element-property :post-affiliated element)))
24325 (setq last-element element)
24326 (cl-decf count))))
24327 (if (= count 0)
24328 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24329 (save-match-data (org-show-context)))
24330 (goto-char origin)
24331 (user-error "No %s code blocks" (if backward "previous" "further")))))
24333 (defun org-previous-block (arg &optional block-regexp)
24334 "Jump to the previous block.
24335 With a prefix argument ARG, jump backward ARG many source blocks.
24336 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24337 (interactive "p")
24338 (org-next-block arg t block-regexp))
24340 (defun org-forward-paragraph ()
24341 "Move forward to beginning of next paragraph or equivalent.
24343 The function moves point to the beginning of the next visible
24344 structural element, which can be a paragraph, a table, a list
24345 item, etc. It also provides some special moves for convenience:
24347 - On an affiliated keyword, jump to the beginning of the
24348 relative element.
24349 - On an item or a footnote definition, move to the second
24350 element inside, if any.
24351 - On a table or a property drawer, jump after it.
24352 - On a verse or source block, stop after blank lines."
24353 (interactive)
24354 (when (eobp) (user-error "Cannot move further down"))
24355 (let* ((deactivate-mark nil)
24356 (element (org-element-at-point))
24357 (type (org-element-type element))
24358 (post-affiliated (org-element-property :post-affiliated element))
24359 (contents-begin (org-element-property :contents-begin element))
24360 (contents-end (org-element-property :contents-end element))
24361 (end (let ((end (org-element-property :end element)) (parent element))
24362 (while (and (setq parent (org-element-property :parent parent))
24363 (= (org-element-property :contents-end parent) end))
24364 (setq end (org-element-property :end parent)))
24365 end)))
24366 (cond ((not element)
24367 (skip-chars-forward " \r\t\n")
24368 (or (eobp) (beginning-of-line)))
24369 ;; On affiliated keywords, move to element's beginning.
24370 ((< (point) post-affiliated)
24371 (goto-char post-affiliated))
24372 ;; At a table row, move to the end of the table. Similarly,
24373 ;; at a node property, move to the end of the property
24374 ;; drawer.
24375 ((memq type '(node-property table-row))
24376 (goto-char (org-element-property
24377 :end (org-element-property :parent element))))
24378 ((memq type '(property-drawer table)) (goto-char end))
24379 ;; Consider blank lines as separators in verse and source
24380 ;; blocks to ease editing.
24381 ((memq type '(src-block verse-block))
24382 (when (eq type 'src-block)
24383 (setq contents-end
24384 (save-excursion (goto-char end)
24385 (skip-chars-backward " \r\t\n")
24386 (line-beginning-position))))
24387 (beginning-of-line)
24388 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24389 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24390 (goto-char end)
24391 (skip-chars-forward " \r\t\n")
24392 (if (= (point) contents-end) (goto-char end)
24393 (beginning-of-line))))
24394 ;; With no contents, just skip element.
24395 ((not contents-begin) (goto-char end))
24396 ;; If contents are invisible, skip the element altogether.
24397 ((outline-invisible-p (line-end-position))
24398 (cl-case type
24399 (headline
24400 (org-with-limited-levels (outline-next-visible-heading 1)))
24401 ;; At a plain list, make sure we move to the next item
24402 ;; instead of skipping the whole list.
24403 (plain-list (forward-char)
24404 (org-forward-paragraph))
24405 (otherwise (goto-char end))))
24406 ((>= (point) contents-end) (goto-char end))
24407 ((>= (point) contents-begin)
24408 ;; This can only happen on paragraphs and plain lists.
24409 (cl-case type
24410 (paragraph (goto-char end))
24411 ;; At a plain list, try to move to second element in
24412 ;; first item, if possible.
24413 (plain-list (end-of-line)
24414 (org-forward-paragraph))))
24415 ;; When contents start on the middle of a line (e.g. in
24416 ;; items and footnote definitions), try to reach first
24417 ;; element starting after current line.
24418 ((> (line-end-position) contents-begin)
24419 (end-of-line)
24420 (org-forward-paragraph))
24421 (t (goto-char contents-begin)))))
24423 (defun org-backward-paragraph ()
24424 "Move backward to start of previous paragraph or equivalent.
24426 The function moves point to the beginning of the current
24427 structural element, which can be a paragraph, a table, a list
24428 item, etc., or to the beginning of the previous visible one if
24429 point is already there. It also provides some special moves for
24430 convenience:
24432 - On an affiliated keyword, jump to the first one.
24433 - On a table or a property drawer, move to its beginning.
24434 - On a verse or source block, stop before blank lines."
24435 (interactive)
24436 (when (bobp) (user-error "Cannot move further up"))
24437 (let* ((deactivate-mark nil)
24438 (element (org-element-at-point))
24439 (type (org-element-type element))
24440 (contents-begin (org-element-property :contents-begin element))
24441 (contents-end (org-element-property :contents-end element))
24442 (post-affiliated (org-element-property :post-affiliated element))
24443 (begin (org-element-property :begin element)))
24444 (cond
24445 ((not element) (goto-char (point-min)))
24446 ((= (point) begin)
24447 (backward-char)
24448 (org-backward-paragraph))
24449 ((<= (point) post-affiliated) (goto-char begin))
24450 ((memq type '(node-property table-row))
24451 (goto-char (org-element-property
24452 :post-affiliated (org-element-property :parent element))))
24453 ((memq type '(property-drawer table)) (goto-char begin))
24454 ((memq type '(src-block verse-block))
24455 (when (eq type 'src-block)
24456 (setq contents-begin
24457 (save-excursion (goto-char begin) (forward-line) (point))))
24458 (if (= (point) contents-begin) (goto-char post-affiliated)
24459 ;; Inside a verse block, see blank lines as paragraph
24460 ;; separators.
24461 (let ((origin (point)))
24462 (skip-chars-backward " \r\t\n" contents-begin)
24463 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24464 (skip-chars-forward " \r\t\n" origin)
24465 (if (= (point) origin) (goto-char contents-begin)
24466 (beginning-of-line))))))
24467 ((not contents-begin) (goto-char (or post-affiliated begin)))
24468 ((eq type 'paragraph)
24469 (goto-char contents-begin)
24470 ;; When at first paragraph in an item or a footnote definition,
24471 ;; move directly to beginning of line.
24472 (let ((parent-contents
24473 (org-element-property
24474 :contents-begin (org-element-property :parent element))))
24475 (when (and parent-contents (= parent-contents contents-begin))
24476 (beginning-of-line))))
24477 ;; At the end of a greater element, move to the beginning of the
24478 ;; last element within.
24479 ((>= (point) contents-end)
24480 (goto-char (1- contents-end))
24481 (org-backward-paragraph))
24482 (t (goto-char (or post-affiliated begin))))
24483 ;; Ensure we never leave point invisible.
24484 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24486 (defun org-forward-element ()
24487 "Move forward by one element.
24488 Move to the next element at the same level, when possible."
24489 (interactive)
24490 (cond ((eobp) (user-error "Cannot move further down"))
24491 ((org-with-limited-levels (org-at-heading-p))
24492 (let ((origin (point)))
24493 (goto-char (org-end-of-subtree nil t))
24494 (unless (org-with-limited-levels (org-at-heading-p))
24495 (goto-char origin)
24496 (user-error "Cannot move further down"))))
24498 (let* ((elem (org-element-at-point))
24499 (end (org-element-property :end elem))
24500 (parent (org-element-property :parent elem)))
24501 (cond ((and parent (= (org-element-property :contents-end parent) end))
24502 (goto-char (org-element-property :end parent)))
24503 ((integer-or-marker-p end) (goto-char end))
24504 (t (message "No element at point")))))))
24506 (defun org-backward-element ()
24507 "Move backward by one element.
24508 Move to the previous element at the same level, when possible."
24509 (interactive)
24510 (cond ((bobp) (user-error "Cannot move further up"))
24511 ((org-with-limited-levels (org-at-heading-p))
24512 ;; At a headline, move to the previous one, if any, or stay
24513 ;; here.
24514 (let ((origin (point)))
24515 (org-with-limited-levels (org-backward-heading-same-level 1))
24516 ;; When current headline has no sibling above, move to its
24517 ;; parent.
24518 (when (= (point) origin)
24519 (or (org-with-limited-levels (org-up-heading-safe))
24520 (progn (goto-char origin)
24521 (user-error "Cannot move further up"))))))
24523 (let* ((elem (org-element-at-point))
24524 (beg (org-element-property :begin elem)))
24525 (cond
24526 ;; Move to beginning of current element if point isn't
24527 ;; there already.
24528 ((null beg) (message "No element at point"))
24529 ((/= (point) beg) (goto-char beg))
24530 (t (goto-char beg)
24531 (skip-chars-backward " \r\t\n")
24532 (unless (bobp)
24533 (let ((prev (org-element-at-point)))
24534 (goto-char (org-element-property :begin prev))
24535 (while (and (setq prev (org-element-property :parent prev))
24536 (<= (org-element-property :end prev) beg))
24537 (goto-char (org-element-property :begin prev)))))))))))
24539 (defun org-up-element ()
24540 "Move to upper element."
24541 (interactive)
24542 (if (org-with-limited-levels (org-at-heading-p))
24543 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24544 (let* ((elem (org-element-at-point))
24545 (parent (org-element-property :parent elem)))
24546 (if parent (goto-char (org-element-property :begin parent))
24547 (if (org-with-limited-levels (org-before-first-heading-p))
24548 (user-error "No surrounding element")
24549 (org-with-limited-levels (org-back-to-heading)))))))
24551 (defvar org-element-greater-elements)
24552 (defun org-down-element ()
24553 "Move to inner element."
24554 (interactive)
24555 (let ((element (org-element-at-point)))
24556 (cond
24557 ((memq (org-element-type element) '(plain-list table))
24558 (goto-char (org-element-property :contents-begin element))
24559 (forward-char))
24560 ((memq (org-element-type element) org-element-greater-elements)
24561 ;; If contents are hidden, first disclose them.
24562 (when (outline-invisible-p (line-end-position)) (org-cycle))
24563 (goto-char (or (org-element-property :contents-begin element)
24564 (user-error "No content for this element"))))
24565 (t (user-error "No inner element")))))
24567 (defun org-drag-element-backward ()
24568 "Move backward element at point."
24569 (interactive)
24570 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24571 (let* ((elem (org-element-at-point))
24572 (prev-elem
24573 (save-excursion
24574 (goto-char (org-element-property :begin elem))
24575 (skip-chars-backward " \r\t\n")
24576 (unless (bobp)
24577 (let* ((beg (org-element-property :begin elem))
24578 (prev (org-element-at-point))
24579 (up prev))
24580 (while (and (setq up (org-element-property :parent up))
24581 (<= (org-element-property :end up) beg))
24582 (setq prev up))
24583 prev)))))
24584 ;; Error out if no previous element or previous element is
24585 ;; a parent of the current one.
24586 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24587 (user-error "Cannot drag element backward")
24588 (let ((pos (point)))
24589 (org-element-swap-A-B prev-elem elem)
24590 (goto-char (+ (org-element-property :begin prev-elem)
24591 (- pos (org-element-property :begin elem)))))))))
24593 (defun org-drag-element-forward ()
24594 "Move forward element at point."
24595 (interactive)
24596 (let* ((pos (point))
24597 (elem (org-element-at-point)))
24598 (when (= (point-max) (org-element-property :end elem))
24599 (user-error "Cannot drag element forward"))
24600 (goto-char (org-element-property :end elem))
24601 (let ((next-elem (org-element-at-point)))
24602 (when (or (org-element-nested-p elem next-elem)
24603 (and (eq (org-element-type next-elem) 'headline)
24604 (not (eq (org-element-type elem) 'headline))))
24605 (goto-char pos)
24606 (user-error "Cannot drag element forward"))
24607 ;; Compute new position of point: it's shifted by NEXT-ELEM
24608 ;; body's length (without final blanks) and by the length of
24609 ;; blanks between ELEM and NEXT-ELEM.
24610 (let ((size-next (- (save-excursion
24611 (goto-char (org-element-property :end next-elem))
24612 (skip-chars-backward " \r\t\n")
24613 (forward-line)
24614 ;; Small correction if buffer doesn't end
24615 ;; with a newline character.
24616 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24617 (org-element-property :begin next-elem)))
24618 (size-blank (- (org-element-property :end elem)
24619 (save-excursion
24620 (goto-char (org-element-property :end elem))
24621 (skip-chars-backward " \r\t\n")
24622 (forward-line)
24623 (point)))))
24624 (org-element-swap-A-B elem next-elem)
24625 (goto-char (+ pos size-next size-blank))))))
24627 (defun org-drag-line-forward (arg)
24628 "Drag the line at point ARG lines forward."
24629 (interactive "p")
24630 (dotimes (_ (abs arg))
24631 (let ((c (current-column)))
24632 (if (< 0 arg)
24633 (progn
24634 (beginning-of-line 2)
24635 (transpose-lines 1)
24636 (beginning-of-line 0))
24637 (transpose-lines 1)
24638 (beginning-of-line -1))
24639 (org-move-to-column c))))
24641 (defun org-drag-line-backward (arg)
24642 "Drag the line at point ARG lines backward."
24643 (interactive "p")
24644 (org-drag-line-forward (- arg)))
24646 (defun org-mark-element ()
24647 "Put point at beginning of this element, mark at end.
24649 Interactively, if this command is repeated or (in Transient Mark
24650 mode) if the mark is active, it marks the next element after the
24651 ones already marked."
24652 (interactive)
24653 (let (deactivate-mark)
24654 (if (and (called-interactively-p 'any)
24655 (or (and (eq last-command this-command) (mark t))
24656 (and transient-mark-mode mark-active)))
24657 (set-mark
24658 (save-excursion
24659 (goto-char (mark))
24660 (goto-char (org-element-property :end (org-element-at-point)))))
24661 (let ((element (org-element-at-point)))
24662 (end-of-line)
24663 (push-mark (org-element-property :end element) t t)
24664 (goto-char (org-element-property :begin element))))))
24666 (defun org-narrow-to-element ()
24667 "Narrow buffer to current element."
24668 (interactive)
24669 (let ((elem (org-element-at-point)))
24670 (cond
24671 ((eq (car elem) 'headline)
24672 (narrow-to-region
24673 (org-element-property :begin elem)
24674 (org-element-property :end elem)))
24675 ((memq (car elem) org-element-greater-elements)
24676 (narrow-to-region
24677 (org-element-property :contents-begin elem)
24678 (org-element-property :contents-end elem)))
24680 (narrow-to-region
24681 (org-element-property :begin elem)
24682 (org-element-property :end elem))))))
24684 (defun org-transpose-element ()
24685 "Transpose current and previous elements, keeping blank lines between.
24686 Point is moved after both elements."
24687 (interactive)
24688 (org-skip-whitespace)
24689 (let ((end (org-element-property :end (org-element-at-point))))
24690 (org-drag-element-backward)
24691 (goto-char end)))
24693 (defun org-unindent-buffer ()
24694 "Un-indent the visible part of the buffer.
24695 Relative indentation (between items, inside blocks, etc.) isn't
24696 modified."
24697 (interactive)
24698 (unless (eq major-mode 'org-mode)
24699 (user-error "Cannot un-indent a buffer not in Org mode"))
24700 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24701 (unindent-tree
24702 (lambda (contents)
24703 (dolist (element (reverse contents))
24704 (if (memq (org-element-type element) '(headline section))
24705 (funcall unindent-tree (org-element-contents element))
24706 (save-excursion
24707 (save-restriction
24708 (narrow-to-region
24709 (org-element-property :begin element)
24710 (org-element-property :end element))
24711 (org-do-remove-indentation))))))))
24712 (funcall unindent-tree (org-element-contents parse-tree))))
24714 (defun org-show-children (&optional level)
24715 "Show all direct subheadings of this heading.
24716 Prefix arg LEVEL is how many levels below the current level
24717 should be shown. Default is enough to cause the following
24718 heading to appear."
24719 (interactive "p")
24720 ;; If `orgstruct-mode' is active, use the slower version.
24721 (if orgstruct-mode (call-interactively #'outline-show-children)
24722 (save-excursion
24723 (org-back-to-heading t)
24724 (let* ((current-level (funcall outline-level))
24725 (max-level (org-get-valid-level
24726 current-level
24727 (if level (prefix-numeric-value level) 1)))
24728 (end (save-excursion (org-end-of-subtree t t)))
24729 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24730 (past-first-child nil)
24731 ;; Make sure to skip inlinetasks.
24732 (re (format regexp-fmt
24733 current-level
24734 (cond
24735 ((not (featurep 'org-inlinetask)) "")
24736 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24738 (t (1- org-inlinetask-min-level))))))
24739 ;; Display parent heading.
24740 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24741 (forward-line)
24742 ;; Display children. First child may be deeper than expected
24743 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24744 ;; MAX-LEVEL accordingly.
24745 (while (re-search-forward re end t)
24746 (unless past-first-child
24747 (setq re (format regexp-fmt
24748 current-level
24749 (max (funcall outline-level) max-level)))
24750 (setq past-first-child t))
24751 (outline-flag-region
24752 (line-end-position 0) (line-end-position) nil))))))
24754 (defun org-show-subtree ()
24755 "Show everything after this heading at deeper levels."
24756 (interactive)
24757 (outline-flag-region
24758 (point)
24759 (save-excursion
24760 (org-end-of-subtree t t))
24761 nil))
24763 (defun org-show-entry ()
24764 "Show the body directly following this heading.
24765 Show the heading too, if it is currently invisible."
24766 (interactive)
24767 (save-excursion
24768 (ignore-errors
24769 (org-back-to-heading t)
24770 (outline-flag-region
24771 (max (point-min) (1- (point)))
24772 (save-excursion
24773 (if (re-search-forward
24774 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24775 (match-beginning 1)
24776 (point-max)))
24777 nil)
24778 (org-cycle-hide-drawers 'children))))
24780 (defun org-make-options-regexp (kwds &optional extra)
24781 "Make a regular expression for keyword lines.
24782 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24783 when non-nil, is a regexp matching keywords names."
24784 (concat "^[ \t]*#\\+\\("
24785 (regexp-opt kwds)
24786 (and extra (concat (and kwds "\\|") extra))
24787 "\\):[ \t]*\\(.*\\)"))
24789 ;;;; Integration with and fixes for other packages
24791 ;;; Imenu support
24793 (defvar-local org-imenu-markers nil
24794 "All markers currently used by Imenu.")
24796 (defun org-imenu-new-marker (&optional pos)
24797 "Return a new marker for use by Imenu, and remember the marker."
24798 (let ((m (make-marker)))
24799 (move-marker m (or pos (point)))
24800 (push m org-imenu-markers)
24803 (defun org-imenu-get-tree ()
24804 "Produce the index for Imenu."
24805 (dolist (x org-imenu-markers) (move-marker x nil))
24806 (setq org-imenu-markers nil)
24807 (let* ((case-fold-search nil)
24808 (n org-imenu-depth)
24809 (re (concat "^" (org-get-limited-outline-regexp)))
24810 (subs (make-vector (1+ n) nil))
24811 (last-level 0)
24812 m level head0 head)
24813 (org-with-wide-buffer
24814 (goto-char (point-max))
24815 (while (re-search-backward re nil t)
24816 (setq level (org-reduced-level (funcall outline-level)))
24817 (when (and (<= level n)
24818 (looking-at org-complex-heading-regexp)
24819 (setq head0 (match-string-no-properties 4)))
24820 (setq head (org-link-display-format head0)
24821 m (org-imenu-new-marker))
24822 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24823 (if (>= level last-level)
24824 (push (cons head m) (aref subs level))
24825 (push (cons head (aref subs (1+ level))) (aref subs level))
24826 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24827 (setq last-level level))))
24828 (aref subs 1)))
24830 (eval-after-load "imenu"
24831 '(progn
24832 (add-hook 'imenu-after-jump-hook
24833 (lambda ()
24834 (when (derived-mode-p 'org-mode)
24835 (org-show-context 'org-goto))))))
24837 (defun org-link-display-format (s)
24838 "Replace links in string S with their description.
24839 If there is no description, use the link target."
24840 (save-match-data
24841 (replace-regexp-in-string
24842 org-bracket-link-analytic-regexp
24843 (lambda (m)
24844 (if (match-end 5) (match-string 5 m)
24845 (concat (match-string 1 m) (match-string 3 m))))
24846 s nil t)))
24848 (defun org-toggle-link-display ()
24849 "Toggle the literal or descriptive display of links."
24850 (interactive)
24851 (if org-descriptive-links
24852 (progn (org-remove-from-invisibility-spec '(org-link))
24853 (org-restart-font-lock)
24854 (setq org-descriptive-links nil))
24855 (progn (add-to-invisibility-spec '(org-link))
24856 (org-restart-font-lock)
24857 (setq org-descriptive-links t))))
24859 ;; Speedbar support
24861 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24862 "Overlay marking the agenda restriction line in speedbar.")
24863 (overlay-put org-speedbar-restriction-lock-overlay
24864 'face 'org-agenda-restriction-lock)
24865 (overlay-put org-speedbar-restriction-lock-overlay
24866 'help-echo "Agendas are currently limited to this item.")
24867 (delete-overlay org-speedbar-restriction-lock-overlay)
24869 (defun org-speedbar-set-agenda-restriction ()
24870 "Restrict future agenda commands to the location at point in speedbar.
24871 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24872 (interactive)
24873 (require 'org-agenda)
24874 (let (p m tp np dir txt)
24875 (cond
24876 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24877 'org-imenu t))
24878 (setq m (get-text-property p 'org-imenu-marker))
24879 (with-current-buffer (marker-buffer m)
24880 (goto-char m)
24881 (org-agenda-set-restriction-lock 'subtree)))
24882 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24883 'speedbar-function 'speedbar-find-file))
24884 (setq tp (previous-single-property-change
24885 (1+ p) 'speedbar-function)
24886 np (next-single-property-change
24887 tp 'speedbar-function)
24888 dir (speedbar-line-directory)
24889 txt (buffer-substring-no-properties (or tp (point-min))
24890 (or np (point-max))))
24891 (with-current-buffer (find-file-noselect
24892 (let ((default-directory dir))
24893 (expand-file-name txt)))
24894 (unless (derived-mode-p 'org-mode)
24895 (user-error "Cannot restrict to non-Org-mode file"))
24896 (org-agenda-set-restriction-lock 'file)))
24897 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24898 (move-overlay org-speedbar-restriction-lock-overlay
24899 (point-at-bol) (point-at-eol))
24900 (setq current-prefix-arg nil)
24901 (org-agenda-maybe-redo)))
24903 (defvar speedbar-file-key-map)
24904 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24905 (eval-after-load "speedbar"
24906 '(progn
24907 (speedbar-add-supported-extension ".org")
24908 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24909 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24910 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24911 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24912 (add-hook 'speedbar-visiting-tag-hook
24913 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24915 ;;; Fixes and Hacks for problems with other packages
24917 (defun org--flyspell-object-check-p (element)
24918 "Non-nil when Flyspell can check object at point.
24919 ELEMENT is the element at point."
24920 (let ((object (save-excursion
24921 (when (looking-at-p "\\>") (backward-char))
24922 (org-element-context element))))
24923 (cl-case (org-element-type object)
24924 ;; Prevent checks in links due to keybinding conflict with
24925 ;; Flyspell.
24926 ((code entity export-snippet inline-babel-call
24927 inline-src-block line-break latex-fragment link macro
24928 statistics-cookie target timestamp verbatim)
24929 nil)
24930 (footnote-reference
24931 ;; Only in inline footnotes, within the definition.
24932 (and (eq (org-element-property :type object) 'inline)
24933 (< (save-excursion
24934 (goto-char (org-element-property :begin object))
24935 (search-forward ":" nil t 2))
24936 (point))))
24937 (otherwise t))))
24939 (defun org-mode-flyspell-verify ()
24940 "Function used for `flyspell-generic-check-word-predicate'."
24941 (if (org-at-heading-p)
24942 ;; At a headline or an inlinetask, check title only. This is
24943 ;; faster than relying on `org-element-at-point'.
24944 (and (save-excursion (beginning-of-line)
24945 (and (let ((case-fold-search t))
24946 (not (looking-at "\\*+ END[ \t]*$")))
24947 (looking-at org-complex-heading-regexp)))
24948 (match-beginning 4)
24949 (>= (point) (match-beginning 4))
24950 (or (not (match-beginning 5))
24951 (< (point) (match-beginning 5))))
24952 (let* ((element (org-element-at-point))
24953 (post-affiliated (org-element-property :post-affiliated element)))
24954 (cond
24955 ;; Ignore checks in all affiliated keywords but captions.
24956 ((< (point) post-affiliated)
24957 (and (save-excursion
24958 (beginning-of-line)
24959 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24960 (> (point) (match-end 0))
24961 (org--flyspell-object-check-p element)))
24962 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24963 ((let ((log (org-log-into-drawer)))
24964 (and log
24965 (let ((drawer (org-element-lineage element '(drawer))))
24966 (and drawer
24967 (eq (compare-strings
24968 log nil nil
24969 (org-element-property :drawer-name drawer) nil nil t)
24970 t)))))
24971 nil)
24973 (cl-case (org-element-type element)
24974 ((comment quote-section) t)
24975 (comment-block
24976 ;; Allow checks between block markers, not on them.
24977 (and (> (line-beginning-position) post-affiliated)
24978 (save-excursion
24979 (end-of-line)
24980 (skip-chars-forward " \r\t\n")
24981 (< (point) (org-element-property :end element)))))
24982 ;; Arbitrary list of keywords where checks are meaningful.
24983 ;; Make sure point is on the value part of the element.
24984 (keyword
24985 (and (member (org-element-property :key element)
24986 '("DESCRIPTION" "TITLE"))
24987 (save-excursion
24988 (search-backward ":" (line-beginning-position) t))))
24989 ;; Check is globally allowed in paragraphs verse blocks and
24990 ;; table rows (after affiliated keywords) but some objects
24991 ;; must not be affected.
24992 ((paragraph table-row verse-block)
24993 (let ((cbeg (org-element-property :contents-begin element))
24994 (cend (org-element-property :contents-end element)))
24995 (and cbeg (>= (point) cbeg) (< (point) cend)
24996 (org--flyspell-object-check-p element))))))))))
24997 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24999 (defun org-remove-flyspell-overlays-in (beg end)
25000 "Remove flyspell overlays in region."
25001 (and (bound-and-true-p flyspell-mode)
25002 (fboundp 'flyspell-delete-region-overlays)
25003 (flyspell-delete-region-overlays beg end)))
25005 (defvar flyspell-delayed-commands)
25006 (eval-after-load "flyspell"
25007 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25009 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25010 (eval-after-load "bookmark"
25011 '(if (boundp 'bookmark-after-jump-hook)
25012 ;; We can use the hook
25013 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25014 ;; Hook not available, use advice
25015 (defadvice bookmark-jump (after org-make-visible activate)
25016 "Make the position visible."
25017 (org-bookmark-jump-unhide))))
25019 ;; Make sure saveplace shows the location if it was hidden
25020 (eval-after-load "saveplace"
25021 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25022 "Make the position visible."
25023 (org-bookmark-jump-unhide)))
25025 ;; Make sure ecb shows the location if it was hidden
25026 (eval-after-load "ecb"
25027 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25028 "Make hierarchy visible when jumping into location from ECB tree buffer."
25029 (when (derived-mode-p 'org-mode)
25030 (org-show-context))))
25032 (defun org-bookmark-jump-unhide ()
25033 "Unhide the current position, to show the bookmark location."
25034 (and (derived-mode-p 'org-mode)
25035 (or (outline-invisible-p)
25036 (save-excursion (goto-char (max (point-min) (1- (point))))
25037 (outline-invisible-p)))
25038 (org-show-context 'bookmark-jump)))
25040 (defun org-mark-jump-unhide ()
25041 "Make the point visible with `org-show-context' after jumping to the mark."
25042 (when (and (derived-mode-p 'org-mode)
25043 (outline-invisible-p))
25044 (org-show-context 'mark-goto)))
25046 (eval-after-load "simple"
25047 '(defadvice pop-to-mark-command (after org-make-visible activate)
25048 "Make the point visible with `org-show-context'."
25049 (org-mark-jump-unhide)))
25051 (eval-after-load "simple"
25052 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25053 "Make the point visible with `org-show-context'."
25054 (org-mark-jump-unhide)))
25056 (eval-after-load "simple"
25057 '(defadvice pop-global-mark (after org-make-visible activate)
25058 "Make the point visible with `org-show-context'."
25059 (org-mark-jump-unhide)))
25061 ;; Make session.el ignore our circular variable
25062 (defvar session-globals-exclude)
25063 (eval-after-load "session"
25064 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25066 ;;;; Finish up
25068 (provide 'org)
25070 (run-hooks 'org-load-hook)
25072 ;;; org.el ends here