* ob-vbnet.el: Org-babel functions for VB.Net evaluation
[org-mode/org-tableheadings.git] / lisp / org.el
blob65d44dc8c16ea551a7f7302b2940e194acd1776d
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-mode 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 contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the doc/ directory.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda"
118 (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-edit-field "org-table" (arg))
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function org-table-next-row "org-table" ())
166 (declare-function org-table-paste-rectangle "org-table" ())
167 (declare-function org-table-wrap-region "org-table" (arg))
168 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
169 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
170 (declare-function orgtbl-mode "org-table" (&optional arg))
172 (defsubst org-uniquify (list)
173 "Non-destructively remove duplicate elements from LIST."
174 (let ((res (copy-sequence list))) (delete-dups res)))
176 (defsubst org-get-at-bol (property)
177 "Get text property PROPERTY at the beginning of line."
178 (get-text-property (point-at-bol) property))
180 (defsubst org-trim (s &optional keep-lead)
181 "Remove whitespace at the beginning and the end of string S.
182 When optional argument KEEP-LEAD is non-nil, removing blank lines
183 at the beginning of the string does not affect leading indentation."
184 (replace-regexp-in-string
185 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
186 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org-mode FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the org-mode file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org-mode buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Emacs Lisp" emacs-lisp)
261 (const :tag "Forth" forth)
262 (const :tag "Fortran" fortran)
263 (const :tag "Gnuplot" gnuplot)
264 (const :tag "Haskell" haskell)
265 (const :tag "IO" io)
266 (const :tag "J" J)
267 (const :tag "Java" java)
268 (const :tag "Javascript" js)
269 (const :tag "LaTeX" latex)
270 (const :tag "Ledger" ledger)
271 (const :tag "Lilypond" lilypond)
272 (const :tag "Lisp" lisp)
273 (const :tag "Makefile" makefile)
274 (const :tag "Maxima" maxima)
275 (const :tag "Matlab" matlab)
276 (const :tag "Mscgen" mscgen)
277 (const :tag "Ocaml" ocaml)
278 (const :tag "Octave" octave)
279 (const :tag "Org" org)
280 (const :tag "Perl" perl)
281 (const :tag "Pico Lisp" picolisp)
282 (const :tag "PlantUML" plantuml)
283 (const :tag "Python" python)
284 (const :tag "Ruby" ruby)
285 (const :tag "Sass" sass)
286 (const :tag "Scala" scala)
287 (const :tag "Scheme" scheme)
288 (const :tag "Screen" screen)
289 (const :tag "Shell Script" shell)
290 (const :tag "Shen" shen)
291 (const :tag "Sql" sql)
292 (const :tag "Sqlite" sqlite)
293 (const :tag "Stan" stan)
294 (const :tag "ebnf2ps" ebnf2ps))
295 :value-type (boolean :tag "Activate" :value t)))
297 ;;;; Customization variables
298 (defcustom org-clone-delete-id nil
299 "Remove ID property of clones of a subtree.
300 When non-nil, clones of a subtree don't inherit the ID property.
301 Otherwise they inherit the ID property with a new unique
302 identifier."
303 :type 'boolean
304 :version "24.1"
305 :group 'org-id)
307 ;;; Version
308 (org-check-version)
310 ;;;###autoload
311 (defun org-version (&optional here full message)
312 "Show the org-mode version.
313 Interactively, or when MESSAGE is non-nil, show it in echo area.
314 With prefix argument, or when HERE is non-nil, insert it at point.
315 In non-interactive uses, a reduced version string is output unless
316 FULL is given."
317 (interactive (list current-prefix-arg t (not current-prefix-arg)))
318 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
319 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
320 (load-suffixes (list ".el"))
321 (org-install-dir
322 (ignore-errors (org-find-library-dir "org-loaddefs"))))
323 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
324 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
325 (let* ((load-suffixes save-load-suffixes)
326 (release (org-release))
327 (git-version (org-git-version))
328 (version (format "Org-mode version %s (%s @ %s)"
329 release
330 git-version
331 (if org-install-dir
332 (if (string= org-dir org-install-dir)
333 org-install-dir
334 (concat "mixed installation! "
335 org-install-dir
336 " and "
337 org-dir))
338 "org-loaddefs.el can not be found!")))
339 (version1 (if full version release)))
340 (when here (insert version1))
341 (when message (message "%s" version1))
342 version1)))
344 (defconst org-version (org-version))
347 ;;; Syntax Constants
349 ;;;; Block
351 (defconst org-block-regexp
352 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
353 "Regular expression for hiding blocks.")
355 (defconst org-dblock-start-re
356 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
357 "Matches the start line of a dynamic block, with parameters.")
359 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
360 "Matches the end of a dynamic block.")
362 ;;;; Clock and Planning
364 (defconst org-clock-string "CLOCK:"
365 "String used as prefix for timestamps clocking work hours on an item.")
367 (defvar org-closed-string "CLOSED:"
368 "String used as the prefix for timestamps logging closing a TODO entry.")
370 (defvar org-deadline-string "DEADLINE:"
371 "String to mark deadline entries.
372 A deadline is this string, followed by a time stamp. Should be a word,
373 terminated by a colon. You can insert a schedule keyword and
374 a timestamp with \\[org-deadline].")
376 (defvar org-scheduled-string "SCHEDULED:"
377 "String to mark scheduled TODO entries.
378 A schedule is this string, followed by a time stamp. Should be a word,
379 terminated by a colon. You can insert a schedule keyword and
380 a timestamp with \\[org-schedule].")
382 (defconst org-ds-keyword-length
383 (+ 2
384 (apply #'max
385 (mapcar #'length
386 (list org-deadline-string org-scheduled-string
387 org-clock-string org-closed-string))))
388 "Maximum length of the DEADLINE and SCHEDULED keywords.")
390 (defconst org-planning-line-re
391 (concat "^[ \t]*"
392 (regexp-opt
393 (list org-closed-string org-deadline-string org-scheduled-string)
395 "Matches a line with planning info.
396 Matched keyword is in group 1.")
398 (defconst org-clock-line-re
399 (concat "^[ \t]*" org-clock-string)
400 "Matches a line with clock info.")
402 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
403 "Matches the DEADLINE keyword.")
405 (defconst org-deadline-time-regexp
406 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
407 "Matches the DEADLINE keyword together with a time stamp.")
409 (defconst org-deadline-time-hour-regexp
410 (concat "\\<" org-deadline-string
411 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
412 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
414 (defconst org-deadline-line-regexp
415 (concat "\\<\\(" org-deadline-string "\\).*")
416 "Matches the DEADLINE keyword and the rest of the line.")
418 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
419 "Matches the SCHEDULED keyword.")
421 (defconst org-scheduled-time-regexp
422 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
423 "Matches the SCHEDULED keyword together with a time stamp.")
425 (defconst org-scheduled-time-hour-regexp
426 (concat "\\<" org-scheduled-string
427 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
428 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
430 (defconst org-closed-time-regexp
431 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
432 "Matches the CLOSED keyword together with a time stamp.")
434 (defconst org-keyword-time-regexp
435 (concat "\\<"
436 (regexp-opt
437 (list org-scheduled-string org-deadline-string org-closed-string
438 org-clock-string)
440 " *[[<]\\([^]>]+\\)[]>]")
441 "Matches any of the 4 keywords, together with the time stamp.")
443 (defconst org-keyword-time-not-clock-regexp
444 (concat
445 "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string) t)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 3 keywords, together with the time stamp.")
451 (defconst org-maybe-keyword-time-regexp
452 (concat "\\(\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 "\\)?"
458 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
459 "\\|"
460 "<%%([^\r\n>]*>\\)")
461 "Matches a timestamp, possibly preceded by a keyword.")
463 (defconst org-all-time-keywords
464 (mapcar (lambda (w) (substring w 0 -1))
465 (list org-scheduled-string org-deadline-string
466 org-clock-string org-closed-string))
467 "List of time keywords.")
469 ;;;; Drawer
471 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
472 "Matches first or last line of a hidden block.
473 Group 1 contains drawer's name or \"END\".")
475 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
476 "Regular expression matching the first line of a property drawer.")
478 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
479 "Regular expression matching the last line of a property drawer.")
481 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
482 "Regular expression matching the first line of a clock drawer.")
484 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a clock drawer.")
487 (defconst org-property-drawer-re
488 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
489 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
490 "[ \t]*:END:[ \t]*$")
491 "Matches an entire property drawer.")
493 (defconst org-clock-drawer-re
494 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
495 org-clock-drawer-end-re "\\)\n?")
496 "Matches an entire clock drawer.")
498 ;;;; Headline
500 (defconst org-heading-keyword-regexp-format
501 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
502 "Printf format for a regexp matching a headline with some keyword.
503 This regexp will match the headline of any node which has the
504 exact keyword that is put into the format. The keyword isn't in
505 any group by default, but the stars and the body are.")
507 (defconst org-heading-keyword-maybe-regexp-format
508 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
509 "Printf format for a regexp matching a headline, possibly with some keyword.
510 This regexp can match any headline with the specified keyword, or
511 without a keyword. The keyword isn't in any group by default,
512 but the stars and the body are.")
514 (defconst org-archive-tag "ARCHIVE"
515 "The tag that marks a subtree as archived.
516 An archived subtree does not open during visibility cycling, and does
517 not contribute to the agenda listings.")
519 (defconst org-comment-string "COMMENT"
520 "Entries starting with this keyword will never be exported.
521 An entry can be toggled between COMMENT and normal with
522 \\[org-toggle-comment].")
525 ;;;; LaTeX Environments and Fragments
527 (defconst org-latex-regexps
528 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
529 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
530 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
531 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
532 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
533 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
534 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
535 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
536 "Regular expressions for matching embedded LaTeX.")
538 ;;;; Node Property
540 (defconst org-effort-property "Effort"
541 "The property that is being used to keep track of effort estimates.
542 Effort estimates given in this property need to have the format H:MM.")
544 ;;;; Table
546 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
547 "Detect an org-type or table-type table.")
549 (defconst org-table-line-regexp "^[ \t]*|"
550 "Detect an org-type table line.")
552 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
553 "Detect an org-type table line.")
555 (defconst org-table-hline-regexp "^[ \t]*|-"
556 "Detect an org-type table hline.")
558 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
559 "Detect a table-type table hline.")
561 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
562 "Detect the first line outside a table when searching from within it.
563 This works for both table types.")
565 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
566 "Detect a #+TBLFM line.")
568 ;;;; Timestamp
570 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
571 "Regular expression for fast time stamp matching.")
573 (defconst org-ts-regexp-inactive
574 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
575 "Regular expression for fast inactive time stamp matching.")
577 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp0
581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
582 "Regular expression matching time strings for analysis.
583 This one does not require the space after the date, so it can be used
584 on a string that terminates immediately after the date.")
586 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.")
589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
590 "Regular expression matching time stamps, with groups.")
592 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
593 "Regular expression matching time stamps (also [..]), with groups.")
595 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
596 "Regular expression matching a time stamp range.")
598 (defconst org-tr-regexp-both
599 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
600 "Regular expression matching a time stamp range.")
602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
603 org-ts-regexp "\\)?")
604 "Regular expression matching a time stamp or time stamp range.")
606 (defconst org-tsr-regexp-both
607 (concat org-ts-regexp-both "\\(--?-?"
608 org-ts-regexp-both "\\)?")
609 "Regular expression matching a time stamp or time stamp range.
610 The time stamps may be either active or inactive.")
612 (defconst org-repeat-re
613 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
614 "Regular expression for specifying repeated events.
615 After a match, group 1 contains the repeat expression.")
617 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
618 "Formats for `format-time-string' which are used for time stamps.")
621 ;;; The custom variables
623 (defgroup org nil
624 "Outline-based notes management and organizer."
625 :tag "Org"
626 :group 'outlines
627 :group 'calendar)
629 (defcustom org-mode-hook nil
630 "Mode hook for Org-mode, run after the mode was turned on."
631 :group 'org
632 :type 'hook)
634 (defcustom org-load-hook nil
635 "Hook that is run after org.el has been loaded."
636 :group 'org
637 :type 'hook)
639 (defcustom org-log-buffer-setup-hook nil
640 "Hook that is run after an Org log buffer is created."
641 :group 'org
642 :version "24.1"
643 :type 'hook)
645 (defvar org-modules) ; defined below
646 (defvar org-modules-loaded nil
647 "Have the modules been loaded already?")
649 (defun org-load-modules-maybe (&optional force)
650 "Load all extensions listed in `org-modules'."
651 (when (or force (not org-modules-loaded))
652 (dolist (ext org-modules)
653 (condition-case nil (require ext)
654 (error (message "Problems while trying to load feature `%s'" ext))))
655 (setq org-modules-loaded t)))
657 (defun org-set-modules (var value)
658 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
659 (set var value)
660 (when (featurep 'org)
661 (org-load-modules-maybe 'force)
662 (org-element-cache-reset 'all)))
664 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
665 "Modules that should always be loaded together with org.el.
667 If a description starts with <C>, the file is not part of Emacs
668 and loading it will require that you have downloaded and properly
669 installed the Org mode distribution.
671 You can also use this system to load external packages (i.e. neither Org
672 core modules, nor modules from the CONTRIB directory). Just add symbols
673 to the end of the list. If the package is called org-xyz.el, then you need
674 to add the symbol `xyz', and the package must have a call to:
676 (provide \\='org-xyz)
678 For export specific modules, see also `org-export-backends'."
679 :group 'org
680 :set 'org-set-modules
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type
684 '(set :greedy t
685 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
686 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
687 (const :tag " crypt: Encryption of subtrees" org-crypt)
688 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
689 (const :tag " docview: Links to doc-view buffers" org-docview)
690 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
691 (const :tag " habit: Track your consistency with habits" org-habit)
692 (const :tag " id: Global IDs for identifying entries" org-id)
693 (const :tag " info: Links to Info nodes" org-info)
694 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
695 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
696 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
697 (const :tag " mouse: Additional mouse support" org-mouse)
698 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
699 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
700 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
702 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
703 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
704 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
705 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
706 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
707 (const :tag "C collector: Collect properties into tables" org-collector)
708 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
709 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
710 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
711 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
712 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
713 (const :tag "C eval: Include command output as text" org-eval)
714 (const :tag "C eww: Store link to url of eww" org-eww)
715 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
716 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
717 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
718 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
719 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
720 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
721 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
722 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
723 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
724 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
725 (const :tag "C mew: Links to Mew folders/messages" org-mew)
726 (const :tag "C mtags: Support for muse-like tags" org-mtags)
727 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
728 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
729 (const :tag "C registry: A registry for Org-mode links" org-registry)
730 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
731 (const :tag "C secretary: Team management with org-mode" org-secretary)
732 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
733 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
734 (const :tag "C track: Keep up with Org-mode development" org-track)
735 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
736 (const :tag "C vm: Links to VM folders/messages" org-vm)
737 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
738 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
739 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
741 (defvar org-export-registered-backends) ; From ox.el.
742 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
743 (declare-function org-export-backend-name "ox" (backend) t)
744 (defcustom org-export-backends '(ascii html icalendar latex odt)
745 "List of export back-ends that should be always available.
747 If a description starts with <C>, the file is not part of Emacs
748 and loading it will require that you have downloaded and properly
749 installed the Org mode distribution.
751 Unlike to `org-modules', libraries in this list will not be
752 loaded along with Org, but only once the export framework is
753 needed.
755 This variable needs to be set before org.el is loaded. If you
756 need to make a change while Emacs is running, use the customize
757 interface or run the following code, where VAL stands for the new
758 value of the variable, after updating it:
760 (progn
761 (setq org-export-registered-backends
762 (cl-remove-if-not
763 (lambda (backend)
764 (let ((name (org-export-backend-name backend)))
765 (or (memq name val)
766 (catch \\='parentp
767 (dolist (b val)
768 (and (org-export-derived-backend-p b name)
769 (throw \\='parentp t)))))))
770 org-export-registered-backends))
771 (let ((new-list (mapcar #\\='org-export-backend-name
772 org-export-registered-backends)))
773 (dolist (backend val)
774 (cond
775 ((not (load (format \"ox-%s\" backend) t t))
776 (message \"Problems while trying to load export back-end \\=`%s\\='\"
777 backend))
778 ((not (memq backend new-list)) (push backend new-list))))
779 (set-default \\='org-export-backends new-list)))
781 Adding a back-end to this list will also pull the back-end it
782 depends on, if any."
783 :group 'org
784 :group 'org-export
785 :version "25.1"
786 :package-version '(Org . "9.0")
787 :initialize 'custom-initialize-set
788 :set (lambda (var val)
789 (if (not (featurep 'ox)) (set-default var val)
790 ;; Any back-end not required anymore (not present in VAL and not
791 ;; a parent of any back-end in the new value) is removed from the
792 ;; list of registered back-ends.
793 (setq org-export-registered-backends
794 (cl-remove-if-not
795 (lambda (backend)
796 (let ((name (org-export-backend-name backend)))
797 (or (memq name val)
798 (catch 'parentp
799 (dolist (b val)
800 (and (org-export-derived-backend-p b name)
801 (throw 'parentp t)))))))
802 org-export-registered-backends))
803 ;; Now build NEW-LIST of both new back-ends and required
804 ;; parents.
805 (let ((new-list (mapcar #'org-export-backend-name
806 org-export-registered-backends)))
807 (dolist (backend val)
808 (cond
809 ((not (load (format "ox-%s" backend) t t))
810 (message "Problems while trying to load export back-end `%s'"
811 backend))
812 ((not (memq backend new-list)) (push backend new-list))))
813 ;; Set VAR to that list with fixed dependencies.
814 (set-default var new-list))))
815 :type '(set :greedy t
816 (const :tag " ascii Export buffer to ASCII format" ascii)
817 (const :tag " beamer Export buffer to Beamer presentation" beamer)
818 (const :tag " html Export buffer to HTML format" html)
819 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
820 (const :tag " latex Export buffer to LaTeX format" latex)
821 (const :tag " man Export buffer to MAN format" man)
822 (const :tag " md Export buffer to Markdown format" md)
823 (const :tag " odt Export buffer to ODT format" odt)
824 (const :tag " org Export buffer to Org format" org)
825 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
826 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
827 (const :tag "C deck Export buffer to deck.js presentations" deck)
828 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
829 (const :tag "C groff Export buffer to Groff format" groff)
830 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
831 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
832 (const :tag "C s5 Export buffer to s5 presentations" s5)
833 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
835 (eval-after-load 'ox
836 '(dolist (backend org-export-backends)
837 (condition-case nil (require (intern (format "ox-%s" backend)))
838 (error (message "Problems while trying to load export back-end `%s'"
839 backend)))))
841 (defcustom org-support-shift-select nil
842 "Non-nil means make shift-cursor commands select text when possible.
843 \\<org-mode-map>\
845 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
846 start selecting a region, or enlarge regions started in this way.
847 In Org-mode, in special contexts, these same keys are used for
848 other purposes, important enough to compete with shift selection.
849 Org tries to balance these needs by supporting `shift-select-mode'
850 outside these special contexts, under control of this variable.
852 The default of this variable is nil, to avoid confusing behavior. Shifted
853 cursor keys will then execute Org commands in the following contexts:
854 - on a headline, changing TODO state (left/right) and priority (up/down)
855 - on a time stamp, changing the time
856 - in a plain list item, changing the bullet type
857 - in a property definition line, switching between allowed values
858 - in the BEGIN line of a clock table (changing the time block).
859 Outside these contexts, the commands will throw an error.
861 When this variable is t and the cursor is not in a special
862 context, Org-mode will support shift-selection for making and
863 enlarging regions. To make this more effective, the bullet
864 cycling will no longer happen anywhere in an item line, but only
865 if the cursor is exactly on the bullet.
867 If you set this variable to the symbol `always', then the keys
868 will not be special in headlines, property lines, and item lines,
869 to make shift selection work there as well. If this is what you
870 want, you can use the following alternative commands:
871 `\\[org-todo]' and `\\[org-priority]' \
872 to change TODO state and priority,
873 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
874 can be used to switch TODO sets,
875 `\\[org-ctrl-c-minus]' to cycle item bullet types,
876 and properties can be edited by hand or in column view.
878 However, when the cursor is on a timestamp, shift-cursor commands
879 will still edit the time stamp - this is just too good to give up."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped.
942 The variable `org-startup-truncated' allows to configure
943 truncation for Org mode different to the other modes that use the
944 variable `truncate-lines' and as a shortcut instead of putting
945 the variable `truncate-lines' into the `org-mode-hook'. If one
946 wants to configure truncation for Org mode not statically but
947 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
948 the variable `truncate-lines' has to be used because in such a
949 case it is too late to set the variable `org-startup-truncated'."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
958 #+STARTUP: indent
959 #+STARTUP: noindent"
960 :group 'org-structure
961 :type '(choice
962 (const :tag "Not" nil)
963 (const :tag "Globally (slow on startup in large files)" t)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
990 :group 'org-startup
991 :version "24.4"
992 :package-version '(Org . "8.0")
993 :type '(choice
994 (const :tag "Always interpret" t)
995 (const :tag "Only with braces" {})
996 (const :tag "Never interpret" nil)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1003 #+STARTUP: beamer"
1004 :group 'org-startup
1005 :version "24.1"
1006 :type 'boolean)
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This is useful when the column width in tables is forced with <N> cookies
1011 in table fields. Such tables will look correct only after the first re-align.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-with-inline-images nil
1020 "Non-nil means show inline images when loading a new Org file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: inlineimages
1024 #+STARTUP: noinlineimages"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-with-latex-preview nil
1030 "Non-nil means preview LaTeX fragments when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: latexpreview
1035 #+STARTUP: nolatexpreview"
1036 :group 'org-startup
1037 :version "24.4"
1038 :package-version '(Org . "8.0")
1039 :type 'boolean)
1041 (defcustom org-insert-mode-line-in-empty-file nil
1042 "Non-nil means insert the first line setting Org-mode in empty files.
1043 When the function `org-mode' is called interactively in an empty file, this
1044 normally means that the file name does not automatically trigger Org-mode.
1045 To ensure that the file will always be in Org-mode in the future, a
1046 line enforcing Org-mode will be inserted into the buffer, if this option
1047 has been set."
1048 :group 'org-startup
1049 :type 'boolean)
1051 (defcustom org-replace-disputed-keys nil
1052 "Non-nil means use alternative key bindings for some keys.
1053 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1054 These keys are also used by other packages like shift-selection-mode'
1055 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1056 If you want to use Org-mode together with one of these other modes,
1057 or more generally if you would like to move some Org-mode commands to
1058 other keys, set this variable and configure the keys with the variable
1059 `org-disputed-keys'.
1061 This option is only relevant at load-time of Org-mode, and must be set
1062 *before* org.el is loaded. Changing it requires a restart of Emacs to
1063 become effective."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-use-extra-keys nil
1068 "Non-nil means use extra key sequence definitions for certain commands.
1069 This happens automatically if `window-system' is nil. This
1070 variable lets you do the same manually. You must set it before
1071 loading Org."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1077 (defcustom org-disputed-keys
1078 '(([(shift up)] . [(meta p)])
1079 ([(shift down)] . [(meta n)])
1080 ([(shift left)] . [(meta -)])
1081 ([(shift right)] . [(meta +)])
1082 ([(control shift right)] . [(meta shift +)])
1083 ([(control shift left)] . [(meta shift -)]))
1084 "Keys for which Org-mode and other modes compete.
1085 This is an alist, cars are the default keys, second element specifies
1086 the alternative to use when `org-replace-disputed-keys' is t.
1088 Keys can be specified in any syntax supported by `define-key'.
1089 The value of this option takes effect only at Org-mode's startup,
1090 therefore you'll have to restart Emacs to apply it after changing."
1091 :group 'org-startup
1092 :type 'alist)
1094 (defun org-key (key)
1095 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1096 Or return the original if not disputed."
1097 (when org-replace-disputed-keys
1098 (let* ((nkey (key-description key))
1099 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1100 org-disputed-keys)))
1101 (setq key (if x (cdr x) key))))
1102 key)
1104 (defun org-defkey (keymap key def)
1105 "Define a key, possibly translated, as returned by `org-key'."
1106 (define-key keymap (org-key key) def))
1108 (defcustom org-ellipsis nil
1109 "The ellipsis to use in the Org-mode outline.
1110 When nil, just use the standard three dots.
1111 When a string, use that string instead.
1112 When a face, use the standard 3 dots, but with the specified face.
1113 The change affects only Org-mode (which will then use its own display table).
1114 Changing this requires executing \\[org-mode] in a buffer to become
1115 effective."
1116 :group 'org-startup
1117 :type '(choice (const :tag "Default" nil)
1118 (face :tag "Face" :value org-warning)
1119 (string :tag "String" :value "...#")))
1121 (defvar org-display-table nil
1122 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1124 (defgroup org-keywords nil
1125 "Keywords in Org-mode."
1126 :tag "Org Keywords"
1127 :group 'org)
1129 (defcustom org-closed-keep-when-no-todo nil
1130 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1131 :group 'org-todo
1132 :group 'org-keywords
1133 :version "24.4"
1134 :package-version '(Org . "8.0")
1135 :type 'boolean)
1137 (defgroup org-structure nil
1138 "Options concerning the general structure of Org-mode files."
1139 :tag "Org Structure"
1140 :group 'org)
1142 (defgroup org-reveal-location nil
1143 "Options about how to make context of a location visible."
1144 :tag "Org Reveal Location"
1145 :group 'org-structure)
1147 (defcustom org-show-context-detail '((agenda . local)
1148 (bookmark-jump . lineage)
1149 (isearch . lineage)
1150 (default . ancestors))
1151 "Alist between context and visibility span when revealing a location.
1153 \\<org-mode-map>Some actions may move point into invisible
1154 locations. As a consequence, Org always expose a neighborhood
1155 around point. How much is shown depends on the initial action,
1156 or context. Valid contexts are
1158 agenda when exposing an entry from the agenda
1159 org-goto when using the command `org-goto' (\\[org-goto])
1160 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1161 tags-tree when constructing a sparse tree based on tags matches
1162 link-search when exposing search matches associated with a link
1163 mark-goto when exposing the jump goal of a mark
1164 bookmark-jump when exposing a bookmark location
1165 isearch when exiting from an incremental search
1166 default default for all contexts not set explicitly
1168 Allowed visibility spans are
1170 minimal show current headline; if point is not on headline,
1171 also show entry
1173 local show current headline, entry and next headline
1175 ancestors show current headline and its direct ancestors; if
1176 point is not on headline, also show entry
1178 lineage show current headline, its direct ancestors and all
1179 their children; if point is not on headline, also show
1180 entry and first child
1182 tree show current headline, its direct ancestors and all
1183 their children; if point is not on headline, also show
1184 entry and all children
1186 canonical show current headline, its direct ancestors along with
1187 their entries and children; if point is not located on
1188 the headline, also show current entry and all children
1190 As special cases, a nil or t value means show all contexts in
1191 `minimal' or `canonical' view, respectively.
1193 Some views can make displayed information very compact, but also
1194 make it harder to edit the location of the match. In such
1195 a case, use the command `org-reveal' (\\[org-reveal]) to show
1196 more context."
1197 :group 'org-reveal-location
1198 :version "25.2"
1199 :package-version '(Org . "9.0")
1200 :type '(choice
1201 (const :tag "Canonical" t)
1202 (const :tag "Minimal" nil)
1203 (repeat :greedy t :tag "Individual contexts"
1204 (cons
1205 (choice :tag "Context"
1206 (const agenda)
1207 (const org-goto)
1208 (const occur-tree)
1209 (const tags-tree)
1210 (const link-search)
1211 (const mark-goto)
1212 (const bookmark-jump)
1213 (const isearch)
1214 (const default))
1215 (choice :tag "Detail level"
1216 (const minimal)
1217 (const local)
1218 (const ancestors)
1219 (const lineage)
1220 (const tree)
1221 (const canonical))))))
1223 (defcustom org-indirect-buffer-display 'other-window
1224 "How should indirect tree buffers be displayed?
1225 This applies to indirect buffers created with the commands
1226 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1227 Valid values are:
1228 current-window Display in the current window
1229 other-window Just display in another window.
1230 dedicated-frame Create one new frame, and re-use it each time.
1231 new-frame Make a new frame each time. Note that in this case
1232 previously-made indirect buffers are kept, and you need to
1233 kill these buffers yourself."
1234 :group 'org-structure
1235 :group 'org-agenda-windows
1236 :type '(choice
1237 (const :tag "In current window" current-window)
1238 (const :tag "In current frame, other window" other-window)
1239 (const :tag "Each time a new frame" new-frame)
1240 (const :tag "One dedicated frame" dedicated-frame)))
1242 (defcustom org-use-speed-commands nil
1243 "Non-nil means activate single letter commands at beginning of a headline.
1244 This may also be a function to test for appropriate locations where speed
1245 commands should be active.
1247 For example, to activate speed commands when the point is on any
1248 star at the beginning of the headline, you can do this:
1250 (setq org-use-speed-commands
1251 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1252 :group 'org-structure
1253 :type '(choice
1254 (const :tag "Never" nil)
1255 (const :tag "At beginning of headline stars" t)
1256 (function)))
1258 (defcustom org-speed-commands-user nil
1259 "Alist of additional speed commands.
1260 This list will be checked before `org-speed-commands-default'
1261 when the variable `org-use-speed-commands' is non-nil
1262 and when the cursor is at the beginning of a headline.
1263 The car if each entry is a string with a single letter, which must
1264 be assigned to `self-insert-command' in the global map.
1265 The cdr is either a command to be called interactively, a function
1266 to be called, or a form to be evaluated.
1267 An entry that is just a list with a single string will be interpreted
1268 as a descriptive headline that will be added when listing the speed
1269 commands in the Help buffer using the `?' speed command."
1270 :group 'org-structure
1271 :type '(repeat :value ("k" . ignore)
1272 (choice :value ("k" . ignore)
1273 (list :tag "Descriptive Headline" (string :tag "Headline"))
1274 (cons :tag "Letter and Command"
1275 (string :tag "Command letter")
1276 (choice
1277 (function)
1278 (sexp))))))
1280 (defcustom org-bookmark-names-plist
1281 '(:last-capture "org-capture-last-stored"
1282 :last-refile "org-refile-last-stored"
1283 :last-capture-marker "org-capture-last-stored-marker")
1284 "Names for bookmarks automatically set by some Org commands.
1285 This can provide strings as names for a number of bookmarks Org sets
1286 automatically. The following keys are currently implemented:
1287 :last-capture
1288 :last-capture-marker
1289 :last-refile
1290 When a key does not show up in the property list, the corresponding bookmark
1291 is not set."
1292 :group 'org-structure
1293 :type 'plist)
1295 (defgroup org-cycle nil
1296 "Options concerning visibility cycling in Org-mode."
1297 :tag "Org Cycle"
1298 :group 'org-structure)
1300 (defcustom org-cycle-skip-children-state-if-no-children t
1301 "Non-nil means skip CHILDREN state in entries that don't have any."
1302 :group 'org-cycle
1303 :type 'boolean)
1305 (defcustom org-cycle-max-level nil
1306 "Maximum level which should still be subject to visibility cycling.
1307 Levels higher than this will, for cycling, be treated as text, not a headline.
1308 When `org-odd-levels-only' is set, a value of N in this variable actually
1309 means 2N-1 stars as the limiting headline.
1310 When nil, cycle all levels.
1311 Note that the limiting level of cycling is also influenced by
1312 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1313 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1314 than its value."
1315 :group 'org-cycle
1316 :type '(choice
1317 (const :tag "No limit" nil)
1318 (integer :tag "Maximum level")))
1320 (defcustom org-hide-block-startup nil
1321 "Non-nil means entering Org-mode will fold all blocks.
1322 This can also be set in on a per-file basis with
1324 #+STARTUP: hideblocks
1325 #+STARTUP: showblocks"
1326 :group 'org-startup
1327 :group 'org-cycle
1328 :type 'boolean)
1330 (defcustom org-cycle-global-at-bob nil
1331 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1332 This makes it possible to do global cycling without having to use S-TAB or
1333 \\[universal-argument] TAB. For this special case to work, the first line
1334 of the buffer must not be a headline -- it may be empty or some other text.
1335 When used in this way, `org-cycle-hook' is disabled temporarily to make
1336 sure the cursor stays at the beginning of the buffer. When this option is
1337 nil, don't do anything special at the beginning of the buffer."
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-level-after-item/entry-creation t
1342 "Non-nil means cycle entry level or item indentation in new empty entries.
1344 When the cursor is at the end of an empty headline, i.e., with only stars
1345 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1346 and then all possible ancestor states, before returning to the original state.
1347 This makes data entry extremely fast: M-RET to create a new headline,
1348 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1350 When the cursor is at the end of an empty plain list item, one TAB will
1351 make it a subitem, two or more tabs will back up to make this an item
1352 higher up in the item hierarchy."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-emulate-tab t
1357 "Where should `org-cycle' emulate TAB.
1358 nil Never
1359 white Only in completely white lines
1360 whitestart Only at the beginning of lines, before the first non-white char
1361 t Everywhere except in headlines
1362 exc-hl-bol Everywhere except at the start of a headline
1363 If TAB is used in a place where it does not emulate TAB, the current subtree
1364 visibility is cycled."
1365 :group 'org-cycle
1366 :type '(choice (const :tag "Never" nil)
1367 (const :tag "Only in completely white lines" white)
1368 (const :tag "Before first char in a line" whitestart)
1369 (const :tag "Everywhere except in headlines" t)
1370 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1372 (defcustom org-cycle-separator-lines 2
1373 "Number of empty lines needed to keep an empty line between collapsed trees.
1374 If you leave an empty line between the end of a subtree and the following
1375 headline, this empty line is hidden when the subtree is folded.
1376 Org-mode will leave (exactly) one empty line visible if the number of
1377 empty lines is equal or larger to the number given in this variable.
1378 So the default 2 means at least 2 empty lines after the end of a subtree
1379 are needed to produce free space between a collapsed subtree and the
1380 following headline.
1382 If the number is negative, and the number of empty lines is at least -N,
1383 all empty lines are shown.
1385 Special case: when 0, never leave empty lines in collapsed view."
1386 :group 'org-cycle
1387 :type 'integer)
1388 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1390 (defcustom org-pre-cycle-hook nil
1391 "Hook that is run before visibility cycling is happening.
1392 The function(s) in this hook must accept a single argument which indicates
1393 the new state that will be set right after running this hook. The
1394 argument is a symbol. Before a global state change, it can have the values
1395 `overview', `content', or `all'. Before a local state change, it can have
1396 the values `folded', `children', or `subtree'."
1397 :group 'org-cycle
1398 :type 'hook)
1400 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1401 org-cycle-hide-drawers
1402 org-cycle-show-empty-lines
1403 org-optimize-window-after-visibility-change)
1404 "Hook that is run after `org-cycle' has changed the buffer visibility.
1405 The function(s) in this hook must accept a single argument which indicates
1406 the new state that was set by the most recent `org-cycle' command. The
1407 argument is a symbol. After a global state change, it can have the values
1408 `overview', `contents', or `all'. After a local state change, it can have
1409 the values `folded', `children', or `subtree'."
1410 :group 'org-cycle
1411 :type 'hook
1412 :version "25.1"
1413 :package-version '(Org . "8.3"))
1415 (defgroup org-edit-structure nil
1416 "Options concerning structure editing in Org-mode."
1417 :tag "Org Edit Structure"
1418 :group 'org-structure)
1420 (defcustom org-odd-levels-only nil
1421 "Non-nil means skip even levels and only use odd levels for the outline.
1422 This has the effect that two stars are being added/taken away in
1423 promotion/demotion commands. It also influences how levels are
1424 handled by the exporters.
1425 Changing it requires restart of `font-lock-mode' to become effective
1426 for fontification also in regions already fontified.
1427 You may also set this on a per-file basis by adding one of the following
1428 lines to the buffer:
1430 #+STARTUP: odd
1431 #+STARTUP: oddeven"
1432 :group 'org-edit-structure
1433 :group 'org-appearance
1434 :type 'boolean)
1436 (defcustom org-adapt-indentation t
1437 "Non-nil means adapt indentation to outline node level.
1439 When this variable is set, Org assumes that you write outlines by
1440 indenting text in each node to align with the headline (after the
1441 stars). The following issues are influenced by this variable:
1443 - The indentation is increased by one space in a demotion
1444 command, and decreased by one in a promotion command. However,
1445 in the latter case, if shifting some line in the entry body
1446 would alter document structure (e.g., insert a new headline),
1447 indentation is not changed at all.
1449 - Property drawers and planning information is inserted indented
1450 when this variable is set. When nil, they will not be indented.
1452 - TAB indents a line relative to current level. The lines below
1453 a headline will be indented when this variable is set.
1455 Note that this is all about true indentation, by adding and
1456 removing space characters. See also `org-indent.el' which does
1457 level-dependent indentation in a virtual way, i.e. at display
1458 time in Emacs."
1459 :group 'org-edit-structure
1460 :type 'boolean)
1462 (defcustom org-special-ctrl-a/e nil
1463 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1465 When t, `C-a' will bring back the cursor to the beginning of the
1466 headline text, i.e. after the stars and after a possible TODO
1467 keyword. In an item, this will be the position after bullet and
1468 check-box, if any. When the cursor is already at that position,
1469 another `C-a' will bring it to the beginning of the line.
1471 `C-e' will jump to the end of the headline, ignoring the presence
1472 of tags in the headline. A second `C-e' will then jump to the
1473 true end of the line, after any tags. This also means that, when
1474 this variable is non-nil, `C-e' also will never jump beyond the
1475 end of the heading of a folded section, i.e. not after the
1476 ellipses.
1478 When set to the symbol `reversed', the first `C-a' or `C-e' works
1479 normally, going to the true line boundary first. Only a directly
1480 following, identical keypress will bring the cursor to the
1481 special positions.
1483 This may also be a cons cell where the behavior for `C-a' and
1484 `C-e' is set separately."
1485 :group 'org-edit-structure
1486 :type '(choice
1487 (const :tag "off" nil)
1488 (const :tag "on: after stars/bullet and before tags first" t)
1489 (const :tag "reversed: true line boundary first" reversed)
1490 (cons :tag "Set C-a and C-e separately"
1491 (choice :tag "Special C-a"
1492 (const :tag "off" nil)
1493 (const :tag "on: after stars/bullet first" t)
1494 (const :tag "reversed: before stars/bullet first" reversed))
1495 (choice :tag "Special C-e"
1496 (const :tag "off" nil)
1497 (const :tag "on: before tags first" t)
1498 (const :tag "reversed: after tags first" reversed)))))
1499 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1501 (defcustom org-special-ctrl-k nil
1502 "Non-nil means `C-k' will behave specially in headlines.
1503 When nil, `C-k' will call the default `kill-line' command.
1504 When t, the following will happen while the cursor is in the headline:
1506 - When the cursor is at the beginning of a headline, kill the entire
1507 line and possible the folded subtree below the line.
1508 - When in the middle of the headline text, kill the headline up to the tags.
1509 - When after the headline text, kill the tags."
1510 :group 'org-edit-structure
1511 :type 'boolean)
1513 (defcustom org-ctrl-k-protect-subtree nil
1514 "Non-nil means, do not delete a hidden subtree with C-k.
1515 When set to the symbol `error', simply throw an error when C-k is
1516 used to kill (part-of) a headline that has hidden text behind it.
1517 Any other non-nil value will result in a query to the user, if it is
1518 OK to kill that hidden subtree. When nil, kill without remorse."
1519 :group 'org-edit-structure
1520 :version "24.1"
1521 :type '(choice
1522 (const :tag "Do not protect hidden subtrees" nil)
1523 (const :tag "Protect hidden subtrees with a security query" t)
1524 (const :tag "Never kill a hidden subtree with C-k" error)))
1526 (defcustom org-special-ctrl-o t
1527 "Non-nil means, make `C-o' insert a row in tables."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-catch-invisible-edits nil
1532 "Check if in invisible region before inserting or deleting a character.
1533 Valid values are:
1535 nil Do not check, so just do invisible edits.
1536 error Throw an error and do nothing.
1537 show Make point visible, and do the requested edit.
1538 show-and-error Make point visible, then throw an error and abort the edit.
1539 smart Make point visible, and do insertion/deletion if it is
1540 adjacent to visible text and the change feels predictable.
1541 Never delete a previously invisible character or add in the
1542 middle or right after an invisible region. Basically, this
1543 allows insertion and backward-delete right before ellipses.
1544 FIXME: maybe in this case we should not even show?"
1545 :group 'org-edit-structure
1546 :version "24.1"
1547 :type '(choice
1548 (const :tag "Do not check" nil)
1549 (const :tag "Throw error when trying to edit" error)
1550 (const :tag "Unhide, but do not do the edit" show-and-error)
1551 (const :tag "Show invisible part and do the edit" show)
1552 (const :tag "Be smart and do the right thing" smart)))
1554 (defcustom org-yank-folded-subtrees t
1555 "Non-nil means when yanking subtrees, fold them.
1556 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1557 it starts with a heading and all other headings in it are either children
1558 or siblings, then fold all the subtrees. However, do this only if no
1559 text after the yank would be swallowed into a folded tree by this action."
1560 :group 'org-edit-structure
1561 :type 'boolean)
1563 (defcustom org-yank-adjusted-subtrees nil
1564 "Non-nil means when yanking subtrees, adjust the level.
1565 With this setting, `org-paste-subtree' is used to insert the subtree, see
1566 this function for details."
1567 :group 'org-edit-structure
1568 :type 'boolean)
1570 (defcustom org-M-RET-may-split-line '((default . t))
1571 "Non-nil means M-RET will split the line at the cursor position.
1572 When nil, it will go to the end of the line before making a
1573 new line.
1574 You may also set this option in a different way for different
1575 contexts. Valid contexts are:
1577 headline when creating a new headline
1578 item when creating a new item
1579 table in a table field
1580 default the value to be used for all contexts not explicitly
1581 customized"
1582 :group 'org-structure
1583 :group 'org-table
1584 :type '(choice
1585 (const :tag "Always" t)
1586 (const :tag "Never" nil)
1587 (repeat :greedy t :tag "Individual contexts"
1588 (cons
1589 (choice :tag "Context"
1590 (const headline)
1591 (const item)
1592 (const table)
1593 (const default))
1594 (boolean)))))
1597 (defcustom org-insert-heading-respect-content nil
1598 "Non-nil means insert new headings after the current subtree.
1599 When nil, the new heading is created directly after the current line.
1600 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1601 this variable on for the duration of the command."
1602 :group 'org-structure
1603 :type 'boolean)
1605 (defcustom org-blank-before-new-entry '((heading . auto)
1606 (plain-list-item . auto))
1607 "Should `org-insert-heading' leave a blank line before new heading/item?
1608 The value is an alist, with `heading' and `plain-list-item' as CAR,
1609 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1610 which case Org will look at the surrounding headings/items and try to
1611 make an intelligent decision whether to insert a blank line or not."
1612 :group 'org-edit-structure
1613 :type '(list
1614 (cons (const heading)
1615 (choice (const :tag "Never" nil)
1616 (const :tag "Always" t)
1617 (const :tag "Auto" auto)))
1618 (cons (const plain-list-item)
1619 (choice (const :tag "Never" nil)
1620 (const :tag "Always" t)
1621 (const :tag "Auto" auto)))))
1623 (defcustom org-insert-heading-hook nil
1624 "Hook being run after inserting a new heading."
1625 :group 'org-edit-structure
1626 :type 'hook)
1628 (defcustom org-enable-fixed-width-editor t
1629 "Non-nil means lines starting with \":\" are treated as fixed-width.
1630 This currently only means they are never auto-wrapped.
1631 When nil, such lines will be treated like ordinary lines."
1632 :group 'org-edit-structure
1633 :type 'boolean)
1635 (defcustom org-goto-auto-isearch t
1636 "Non-nil means typing characters in `org-goto' starts incremental search.
1637 When nil, you can use these keybindings to navigate the buffer:
1639 q Quit the org-goto interface
1640 n Go to the next visible heading
1641 p Go to the previous visible heading
1642 f Go one heading forward on same level
1643 b Go one heading backward on same level
1644 u Go one heading up"
1645 :group 'org-edit-structure
1646 :type 'boolean)
1648 (defgroup org-sparse-trees nil
1649 "Options concerning sparse trees in Org-mode."
1650 :tag "Org Sparse Trees"
1651 :group 'org-structure)
1653 (defcustom org-highlight-sparse-tree-matches t
1654 "Non-nil means highlight all matches that define a sparse tree.
1655 The highlights will automatically disappear the next time the buffer is
1656 changed by an edit command."
1657 :group 'org-sparse-trees
1658 :type 'boolean)
1660 (defcustom org-remove-highlights-with-change t
1661 "Non-nil means any change to the buffer will remove temporary highlights.
1662 \\<org-mode-map>\
1663 Such highlights are created by `org-occur' and `org-clock-display'.
1664 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1665 to get rid of the highlights.
1666 The highlights created by `org-toggle-latex-fragment' always need
1667 `\\[org-toggle-latex-fragment]' to be removed."
1668 :group 'org-sparse-trees
1669 :group 'org-time
1670 :type 'boolean)
1672 (defcustom org-occur-case-fold-search t
1673 "Non-nil means `org-occur' should be case-insensitive.
1674 If set to `smart' the search will be case-insensitive only if it
1675 doesn't specify any upper case character."
1676 :group 'org-sparse-trees
1677 :version "25.1"
1678 :type '(choice
1679 (const :tag "Case-sensitive" nil)
1680 (const :tag "Case-insensitive" t)
1681 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1683 (defcustom org-occur-hook '(org-first-headline-recenter)
1684 "Hook that is run after `org-occur' has constructed a sparse tree.
1685 This can be used to recenter the window to show as much of the structure
1686 as possible."
1687 :group 'org-sparse-trees
1688 :type 'hook)
1690 (defgroup org-imenu-and-speedbar nil
1691 "Options concerning imenu and speedbar in Org-mode."
1692 :tag "Org Imenu and Speedbar"
1693 :group 'org-structure)
1695 (defcustom org-imenu-depth 2
1696 "The maximum level for Imenu access to Org-mode headlines.
1697 This also applied for speedbar access."
1698 :group 'org-imenu-and-speedbar
1699 :type 'integer)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org-mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-enable-table-editor 'optimized
1707 "Non-nil means lines starting with \"|\" are handled by the table editor.
1708 When nil, such lines will be treated like ordinary lines.
1710 When equal to the symbol `optimized', the table editor will be optimized to
1711 do the following:
1712 - Automatic overwrite mode in front of whitespace in table fields.
1713 This makes the structure of the table stay in tact as long as the edited
1714 field does not exceed the column width.
1715 - Minimize the number of realigns. Normally, the table is aligned each time
1716 TAB or RET are pressed to move to another field. With optimization this
1717 happens only if changes to a field might have changed the column width.
1718 Optimization requires replacing the functions `self-insert-command',
1719 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1720 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1721 very good at guessing when a re-align will be necessary, but you can always
1722 force one with \\[org-ctrl-c-ctrl-c].
1724 If you would like to use the optimized version in Org-mode, but the
1725 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1727 This variable can be used to turn on and off the table editor during a session,
1728 but in order to toggle optimization, a restart is required.
1730 See also the variable `org-table-auto-blank-field'."
1731 :group 'org-table
1732 :type '(choice
1733 (const :tag "off" nil)
1734 (const :tag "on" t)
1735 (const :tag "on, optimized" optimized)))
1737 (defcustom org-self-insert-cluster-for-undo nil
1738 "Non-nil means cluster self-insert commands for undo when possible.
1739 If this is set, then, like in the Emacs command loop, 20 consecutive
1740 characters will be undone together.
1741 This is configurable, because there is some impact on typing performance."
1742 :group 'org-table
1743 :type 'boolean)
1745 (defcustom org-table-tab-recognizes-table.el t
1746 "Non-nil means TAB will automatically notice a table.el table.
1747 When it sees such a table, it moves point into it and - if necessary -
1748 calls `table-recognize-table'."
1749 :group 'org-table-editing
1750 :type 'boolean)
1752 (defgroup org-link nil
1753 "Options concerning links in Org-mode."
1754 :tag "Org Link"
1755 :group 'org)
1757 (defvar-local org-link-abbrev-alist-local nil
1758 "Buffer-local version of `org-link-abbrev-alist', which see.
1759 The value of this is taken from the #+LINK lines.")
1761 (defcustom org-link-abbrev-alist nil
1762 "Alist of link abbreviations.
1763 The car of each element is a string, to be replaced at the start of a link.
1764 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1765 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1767 [[linkkey:tag][description]]
1769 The `linkkey' must be a word word, starting with a letter, followed
1770 by letters, numbers, `-' or `_'.
1772 If REPLACE is a string, the tag will simply be appended to create the link.
1773 If the string contains \"%s\", the tag will be inserted there. If the string
1774 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1775 at that point (see the function `url-hexify-string'). If the string contains
1776 the specifier \"%(my-function)\", then the custom function `my-function' will
1777 be invoked: this function takes the tag as its only argument and must return
1778 a string.
1780 REPLACE may also be a function that will be called with the tag as the
1781 only argument to create the link, which should be returned as a string.
1783 See the manual for examples."
1784 :group 'org-link
1785 :type '(repeat
1786 (cons
1787 (string :tag "Protocol")
1788 (choice
1789 (string :tag "Format")
1790 (function)))))
1792 (defcustom org-descriptive-links t
1793 "Non-nil means Org will display descriptive links.
1794 E.g. [[http://orgmode.org][Org website]] will be displayed as
1795 \"Org Website\", hiding the link itself and just displaying its
1796 description. When set to nil, Org will display the full links
1797 literally.
1799 You can interactively set the value of this variable by calling
1800 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1801 :group 'org-link
1802 :type 'boolean)
1804 (defcustom org-link-file-path-type 'adaptive
1805 "How the path name in file links should be stored.
1806 Valid values are:
1808 relative Relative to the current directory, i.e. the directory of the file
1809 into which the link is being inserted.
1810 absolute Absolute path, if possible with ~ for home directory.
1811 noabbrev Absolute path, no abbreviation of home directory.
1812 adaptive Use relative path for files in the current directory and sub-
1813 directories of it. For other files, use an absolute path."
1814 :group 'org-link
1815 :type '(choice
1816 (const relative)
1817 (const absolute)
1818 (const noabbrev)
1819 (const adaptive)))
1821 (defvaralias 'org-activate-links 'org-highlight-links)
1822 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1823 "Types of links that should be highlighted in Org-mode files.
1825 This is a list of symbols, each one of them leading to the
1826 highlighting of a certain link type.
1828 You can still open links that are not highlighted.
1830 In principle, it does not hurt to turn on highlighting for all
1831 link types. There may be a small gain when turning off unused
1832 link types. The types are:
1834 bracket The recommended [[link][description]] or [[link]] links with hiding.
1835 angle Links in angular brackets that may contain whitespace like
1836 <bbdb:Carsten Dominik>.
1837 plain Plain links in normal text, no whitespace, like http://google.com.
1838 radio Text that is matched by a radio target, see manual for details.
1839 tag Tag settings in a headline (link to tag search).
1840 date Time stamps (link to calendar).
1841 footnote Footnote labels.
1843 If you set this variable during an Emacs session, use `org-mode-restart'
1844 in the Org buffer so that the change takes effect."
1845 :group 'org-link
1846 :group 'org-appearance
1847 :type '(set :greedy t
1848 (const :tag "Double bracket links" bracket)
1849 (const :tag "Angular bracket links" angle)
1850 (const :tag "Plain text links" plain)
1851 (const :tag "Radio target matches" radio)
1852 (const :tag "Tags" tag)
1853 (const :tag "Timestamps" date)
1854 (const :tag "Footnotes" footnote)))
1856 (defcustom org-make-link-description-function nil
1857 "Function to use for generating link descriptions from links.
1858 When nil, the link location will be used. This function must take
1859 two parameters: the first one is the link, the second one is the
1860 description generated by `org-insert-link'. The function should
1861 return the description to use."
1862 :group 'org-link
1863 :type '(choice (const nil) (function)))
1865 (defgroup org-link-store nil
1866 "Options concerning storing links in Org-mode."
1867 :tag "Org Store Link"
1868 :group 'org-link)
1870 (defcustom org-url-hexify-p t
1871 "When non-nil, hexify URL when creating a link."
1872 :type 'boolean
1873 :version "24.3"
1874 :group 'org-link-store)
1876 (defcustom org-email-link-description-format "Email %c: %.30s"
1877 "Format of the description part of a link to an email or usenet message.
1878 The following %-escapes will be replaced by corresponding information:
1880 %F full \"From\" field
1881 %f name, taken from \"From\" field, address if no name
1882 %T full \"To\" field
1883 %t first name in \"To\" field, address if no name
1884 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1885 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1886 %s subject
1887 %d date
1888 %m message-id.
1890 You may use normal field width specification between the % and the letter.
1891 This is for example useful to limit the length of the subject.
1893 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1894 :group 'org-link-store
1895 :type 'string)
1897 (defcustom org-from-is-user-regexp
1898 (let (r1 r2)
1899 (when (and user-mail-address (not (string= user-mail-address "")))
1900 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1901 (when (and user-full-name (not (string= user-full-name "")))
1902 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1903 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1904 "Regexp matched against the \"From:\" header of an email or usenet message.
1905 It should match if the message is from the user him/herself."
1906 :group 'org-link-store
1907 :type 'regexp)
1909 (defcustom org-context-in-file-links t
1910 "Non-nil means file links from `org-store-link' contain context.
1911 A search string will be added to the file name with :: as separator and
1912 used to find the context when the link is activated by the command
1913 `org-open-at-point'. When this option is t, the entire active region
1914 will be placed in the search string of the file link. If set to a
1915 positive integer, only the first n lines of context will be stored.
1917 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1918 negates this setting for the duration of the command."
1919 :group 'org-link-store
1920 :type '(choice boolean integer))
1922 (defcustom org-keep-stored-link-after-insertion nil
1923 "Non-nil means keep link in list for entire session.
1925 The command `org-store-link' adds a link pointing to the current
1926 location to an internal list. These links accumulate during a session.
1927 The command `org-insert-link' can be used to insert links into any
1928 Org-mode file (offering completion for all stored links). When this
1929 option is nil, every link which has been inserted once using \\[org-insert-link]
1930 will be removed from the list, to make completing the unused links
1931 more efficient."
1932 :group 'org-link-store
1933 :type 'boolean)
1935 (defgroup org-link-follow nil
1936 "Options concerning following links in Org-mode."
1937 :tag "Org Follow Link"
1938 :group 'org-link)
1940 (defcustom org-link-translation-function nil
1941 "Function to translate links with different syntax to Org syntax.
1942 This can be used to translate links created for example by the Planner
1943 or emacs-wiki packages to Org syntax.
1944 The function must accept two parameters, a TYPE containing the link
1945 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1946 which is everything after the link protocol. It should return a cons
1947 with possibly modified values of type and path.
1948 Org contains a function for this, so if you set this variable to
1949 `org-translate-link-from-planner', you should be able follow many
1950 links created by planner."
1951 :group 'org-link-follow
1952 :type '(choice (const nil) (function)))
1954 (defcustom org-follow-link-hook nil
1955 "Hook that is run after a link has been followed."
1956 :group 'org-link-follow
1957 :type 'hook)
1959 (defcustom org-tab-follows-link nil
1960 "Non-nil means on links TAB will follow the link.
1961 Needs to be set before org.el is loaded.
1962 This really should not be used, it does not make sense, and the
1963 implementation is bad."
1964 :group 'org-link-follow
1965 :type 'boolean)
1967 (defcustom org-return-follows-link nil
1968 "Non-nil means on links RET will follow the link.
1969 In tables, the special behavior of RET has precedence."
1970 :group 'org-link-follow
1971 :type 'boolean)
1973 (defcustom org-mouse-1-follows-link
1974 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1975 "Non-nil means mouse-1 on a link will follow the link.
1976 A longer mouse click will still set point. Needs to be set
1977 before org.el is loaded."
1978 :group 'org-link-follow
1979 :version "24.4"
1980 :package-version '(Org . "8.3")
1981 :type '(choice
1982 (const :tag "A double click follows the link" double)
1983 (const :tag "Unconditionally follow the link with mouse-1" t)
1984 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1986 (defcustom org-mark-ring-length 4
1987 "Number of different positions to be recorded in the ring.
1988 Changing this requires a restart of Emacs to work correctly."
1989 :group 'org-link-follow
1990 :type 'integer)
1992 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1993 "Non-nil means internal links in Org files must exactly match a headline.
1994 When nil, the link search tries to match a phrase with all words
1995 in the search text."
1996 :group 'org-link-follow
1997 :version "24.1"
1998 :type '(choice
1999 (const :tag "Use fuzzy text search" nil)
2000 (const :tag "Match only exact headline" t)
2001 (const :tag "Match exact headline or query to create it"
2002 query-to-create)))
2004 (defcustom org-link-frame-setup
2005 '((vm . vm-visit-folder-other-frame)
2006 (vm-imap . vm-visit-imap-folder-other-frame)
2007 (gnus . org-gnus-no-new-news)
2008 (file . find-file-other-window)
2009 (wl . wl-other-frame))
2010 "Setup the frame configuration for following links.
2011 When following a link with Emacs, it may often be useful to display
2012 this link in another window or frame. This variable can be used to
2013 set this up for the different types of links.
2014 For VM, use any of
2015 `vm-visit-folder'
2016 `vm-visit-folder-other-window'
2017 `vm-visit-folder-other-frame'
2018 For Gnus, use any of
2019 `gnus'
2020 `gnus-other-frame'
2021 `org-gnus-no-new-news'
2022 For FILE, use any of
2023 `find-file'
2024 `find-file-other-window'
2025 `find-file-other-frame'
2026 For Wanderlust use any of
2027 `wl'
2028 `wl-other-frame'
2029 For the calendar, use the variable `calendar-setup'.
2030 For BBDB, it is currently only possible to display the matches in
2031 another window."
2032 :group 'org-link-follow
2033 :type '(list
2034 (cons (const vm)
2035 (choice
2036 (const vm-visit-folder)
2037 (const vm-visit-folder-other-window)
2038 (const vm-visit-folder-other-frame)))
2039 (cons (const vm-imap)
2040 (choice
2041 (const vm-visit-imap-folder)
2042 (const vm-visit-imap-folder-other-window)
2043 (const vm-visit-imap-folder-other-frame)))
2044 (cons (const gnus)
2045 (choice
2046 (const gnus)
2047 (const gnus-other-frame)
2048 (const org-gnus-no-new-news)))
2049 (cons (const file)
2050 (choice
2051 (const find-file)
2052 (const find-file-other-window)
2053 (const find-file-other-frame)))
2054 (cons (const wl)
2055 (choice
2056 (const wl)
2057 (const wl-other-frame)))))
2059 (defcustom org-display-internal-link-with-indirect-buffer nil
2060 "Non-nil means use indirect buffer to display infile links.
2061 Activating internal links (from one location in a file to another location
2062 in the same file) normally just jumps to the location. When the link is
2063 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2064 is displayed in
2065 another window. When this option is set, the other window actually displays
2066 an indirect buffer clone of the current buffer, to avoid any visibility
2067 changes to the current buffer."
2068 :group 'org-link-follow
2069 :type 'boolean)
2071 (defcustom org-open-non-existing-files nil
2072 "Non-nil means `org-open-file' will open non-existing files.
2073 When nil, an error will be generated.
2074 This variable applies only to external applications because they
2075 might choke on non-existing files. If the link is to a file that
2076 will be opened in Emacs, the variable is ignored."
2077 :group 'org-link-follow
2078 :type 'boolean)
2080 (defcustom org-open-directory-means-index-dot-org nil
2081 "Non-nil means a link to a directory really means to index.org.
2082 When nil, following a directory link will run dired or open a finder/explorer
2083 window on that directory."
2084 :group 'org-link-follow
2085 :type 'boolean)
2087 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2088 "Non-nil means ask for confirmation before executing shell links.
2089 Shell links can be dangerous: just think about a link
2091 [[shell:rm -rf ~/*][Google Search]]
2093 This link would show up in your Org-mode document as \"Google Search\",
2094 but really it would remove your entire home directory.
2095 Therefore we advise against setting this variable to nil.
2096 Just change it to `y-or-n-p' if you want to confirm with a
2097 single keystroke rather than having to type \"yes\"."
2098 :group 'org-link-follow
2099 :type '(choice
2100 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2101 (const :tag "with y-or-n (faster)" y-or-n-p)
2102 (const :tag "no confirmation (dangerous)" nil)))
2103 (put 'org-confirm-shell-link-function
2104 'safe-local-variable
2105 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2107 (defcustom org-confirm-shell-link-not-regexp ""
2108 "A regexp to skip confirmation for shell links."
2109 :group 'org-link-follow
2110 :version "24.1"
2111 :type 'regexp)
2113 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2114 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2115 Elisp links can be dangerous: just think about a link
2117 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2119 This link would show up in your Org-mode document as \"Google Search\",
2120 but really it would remove your entire home directory.
2121 Therefore we advise against setting this variable to nil.
2122 Just change it to `y-or-n-p' if you want to confirm with a
2123 single keystroke rather than having to type \"yes\"."
2124 :group 'org-link-follow
2125 :type '(choice
2126 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2127 (const :tag "with y-or-n (faster)" y-or-n-p)
2128 (const :tag "no confirmation (dangerous)" nil)))
2129 (put 'org-confirm-shell-link-function
2130 'safe-local-variable
2131 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2133 (defcustom org-confirm-elisp-link-not-regexp ""
2134 "A regexp to skip confirmation for Elisp links."
2135 :group 'org-link-follow
2136 :version "24.1"
2137 :type 'regexp)
2139 (defconst org-file-apps-defaults-gnu
2140 '((remote . emacs)
2141 (system . mailcap)
2142 (t . mailcap))
2143 "Default file applications on a UNIX or GNU/Linux system.
2144 See `org-file-apps'.")
2146 (defconst org-file-apps-defaults-macosx
2147 '((remote . emacs)
2148 (system . "open %s")
2149 ("ps.gz" . "gv %s")
2150 ("eps.gz" . "gv %s")
2151 ("dvi" . "xdvi %s")
2152 ("fig" . "xfig %s")
2153 (t . "open %s"))
2154 "Default file applications on a MacOS X system.
2155 The system \"open\" is known as a default, but we use X11 applications
2156 for some files for which the OS does not have a good default.
2157 See `org-file-apps'.")
2159 (defconst org-file-apps-defaults-windowsnt
2160 (list '(remote . emacs)
2161 (cons 'system (lambda (file _path)
2162 (with-no-warnings (w32-shell-execute "open" file))))
2163 (cons t (lambda (file _path)
2164 (with-no-warnings (w32-shell-execute "open" file)))))
2165 "Default file applications on a Windows NT system.
2166 The system \"open\" is used for most files.
2167 See `org-file-apps'.")
2169 (defcustom org-file-apps
2170 '((auto-mode . emacs)
2171 ("\\.mm\\'" . default)
2172 ("\\.x?html?\\'" . default)
2173 ("\\.pdf\\'" . default))
2174 "External applications for opening `file:path' items in a document.
2175 \\<org-mode-map>\
2176 Org mode uses system defaults for different file types, but
2177 you can use this variable to set the application for a given file
2178 extension. The entries in this list are cons cells where the car identifies
2179 files and the cdr the corresponding command. Possible values for the
2180 file identifier are
2181 \"string\" A string as a file identifier can be interpreted in different
2182 ways, depending on its contents:
2184 - Alphanumeric characters only:
2185 Match links with this file extension.
2186 Example: (\"pdf\" . \"evince %s\")
2187 to open PDFs with evince.
2189 - Regular expression: Match links where the
2190 filename matches the regexp. If you want to
2191 use groups here, use shy groups.
2193 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2194 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2195 to open *.html and *.xhtml with firefox.
2197 - Regular expression which contains (non-shy) groups:
2198 Match links where the whole link, including \"::\", and
2199 anything after that, matches the regexp.
2200 In a custom command string, %1, %2, etc. are replaced with
2201 the parts of the link that were matched by the groups.
2202 For backwards compatibility, if a command string is given
2203 that does not use any of the group matches, this case is
2204 handled identically to the second one (i.e. match against
2205 file name only).
2206 In a custom function, you can access the group matches with
2207 \(match-string n link).
2209 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2210 to open [[file:document.pdf::5]] with evince at page 5.
2212 `directory' Matches a directory
2213 `remote' Matches a remote file, accessible through tramp or efs.
2214 Remote files most likely should be visited through Emacs
2215 because external applications cannot handle such paths.
2216 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2217 so all files Emacs knows how to handle. Using this with
2218 command `emacs' will open most files in Emacs. Beware that this
2219 will also open html files inside Emacs, unless you add
2220 \(\"html\" . default) to the list as well.
2221 `system' The system command to open files, like `open' on Windows
2222 and Mac OS X, and mailcap under GNU/Linux. This is the command
2223 that will be selected if you call \\[org-open-at-point] with a double
2224 \\[universal-argument] \\[universal-argument] prefix.
2225 t Default for files not matched by any of the other options.
2227 Possible values for the command are:
2228 `emacs' The file will be visited by the current Emacs process.
2229 `default' Use the default application for this file type, which is the
2230 association for t in the list, most likely in the system-specific
2231 part. This can be used to overrule an unwanted setting in the
2232 system-specific variable.
2233 `system' Use the system command for opening files, like \"open\".
2234 This command is specified by the entry whose car is `system'.
2235 Most likely, the system-specific version of this variable
2236 does define this command, but you can overrule/replace it
2237 here.
2238 `mailcap' Use command specified in the mailcaps.
2239 string A command to be executed by a shell; %s will be replaced
2240 by the path to the file.
2242 function A Lisp function, which will be called with two arguments:
2243 the file path and the original link string, without the
2244 \"file:\" prefix.
2246 For more examples, see the system specific constants
2247 `org-file-apps-defaults-macosx'
2248 `org-file-apps-defaults-windowsnt'
2249 `org-file-apps-defaults-gnu'."
2250 :group 'org-link-follow
2251 :type '(repeat
2252 (cons (choice :value ""
2253 (string :tag "Extension")
2254 (const :tag "System command to open files" system)
2255 (const :tag "Default for unrecognized files" t)
2256 (const :tag "Remote file" remote)
2257 (const :tag "Links to a directory" directory)
2258 (const :tag "Any files that have Emacs modes"
2259 auto-mode))
2260 (choice :value ""
2261 (const :tag "Visit with Emacs" emacs)
2262 (const :tag "Use default" default)
2263 (const :tag "Use the system command" system)
2264 (string :tag "Command")
2265 (function :tag "Function")))))
2267 (defcustom org-doi-server-url "http://dx.doi.org/"
2268 "The URL of the DOI server."
2269 :type 'string
2270 :version "24.3"
2271 :group 'org-link-follow)
2273 (defgroup org-refile nil
2274 "Options concerning refiling entries in Org-mode."
2275 :tag "Org Refile"
2276 :group 'org)
2278 (defcustom org-directory "~/org"
2279 "Directory with Org files.
2280 This is just a default location to look for Org files. There is no need
2281 at all to put your files into this directory. It is used in the
2282 following situations:
2284 1. When a capture template specifies a target file that is not an
2285 absolute path. The path will then be interpreted relative to
2286 `org-directory'
2287 2. When the value of variable `org-agenda-files' is a single file, any
2288 relative paths in this file will be taken as relative to
2289 `org-directory'."
2290 :group 'org-refile
2291 :group 'org-capture
2292 :type 'directory)
2294 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2295 "Default target for storing notes.
2296 Used as a fall back file for org-capture.el, for templates that
2297 do not specify a target file."
2298 :group 'org-refile
2299 :group 'org-capture
2300 :type 'file)
2302 (defcustom org-goto-interface 'outline
2303 "The default interface to be used for `org-goto'.
2304 Allowed values are:
2305 outline The interface shows an outline of the relevant file
2306 and the correct heading is found by moving through
2307 the outline or by searching with incremental search.
2308 outline-path-completion Headlines in the current buffer are offered via
2309 completion. This is the interface also used by
2310 the refile command."
2311 :group 'org-refile
2312 :type '(choice
2313 (const :tag "Outline" outline)
2314 (const :tag "Outline-path-completion" outline-path-completion)))
2316 (defcustom org-goto-max-level 5
2317 "Maximum target level when running `org-goto' with refile interface."
2318 :group 'org-refile
2319 :type 'integer)
2321 (defcustom org-reverse-note-order nil
2322 "Non-nil means store new notes at the beginning of a file or entry.
2323 When nil, new notes will be filed to the end of a file or entry.
2324 This can also be a list with cons cells of regular expressions that
2325 are matched against file names, and values."
2326 :group 'org-capture
2327 :group 'org-refile
2328 :type '(choice
2329 (const :tag "Reverse always" t)
2330 (const :tag "Reverse never" nil)
2331 (repeat :tag "By file name regexp"
2332 (cons regexp boolean))))
2334 (defcustom org-log-refile nil
2335 "Information to record when a task is refiled.
2337 Possible values are:
2339 nil Don't add anything
2340 time Add a time stamp to the task
2341 note Prompt for a note and add it with template `org-log-note-headings'
2343 This option can also be set with on a per-file-basis with
2345 #+STARTUP: nologrefile
2346 #+STARTUP: logrefile
2347 #+STARTUP: lognoterefile
2349 You can have local logging settings for a subtree by setting the LOGGING
2350 property to one or more of these keywords.
2352 When bulk-refiling from the agenda, the value `note' is forbidden and
2353 will temporarily be changed to `time'."
2354 :group 'org-refile
2355 :group 'org-progress
2356 :version "24.1"
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record timestamp" time)
2360 (const :tag "Record timestamp with note." note)))
2362 (defcustom org-refile-targets nil
2363 "Targets for refiling entries with \\[org-refile].
2364 This is a list of cons cells. Each cell contains:
2365 - a specification of the files to be considered, either a list of files,
2366 or a symbol whose function or variable value will be used to retrieve
2367 a file name or a list of file names. If you use `org-agenda-files' for
2368 that, all agenda files will be scanned for targets. Nil means consider
2369 headings in the current buffer.
2370 - A specification of how to find candidate refile targets. This may be
2371 any of:
2372 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2373 This tag has to be present in all target headlines, inheritance will
2374 not be considered.
2375 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2376 todo keyword.
2377 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2378 headlines that are refiling targets.
2379 - a cons cell (:level . N). Any headline of level N is considered a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2382 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2383 Note that, when `org-odd-levels-only' is set, level corresponds to
2384 order in hierarchy, not to the number of stars.
2386 Each element of this list generates a set of possible targets.
2387 The union of these sets is presented (with completion) to
2388 the user by `org-refile'.
2390 You can set the variable `org-refile-target-verify-function' to a function
2391 to verify each headline found by the simple criteria above.
2393 When this variable is nil, all top-level headlines in the current buffer
2394 are used, equivalent to the value `((nil . (:level . 1))'."
2395 :group 'org-refile
2396 :type '(repeat
2397 (cons
2398 (choice :value org-agenda-files
2399 (const :tag "All agenda files" org-agenda-files)
2400 (const :tag "Current buffer" nil)
2401 (function) (variable) (file))
2402 (choice :tag "Identify target headline by"
2403 (cons :tag "Specific tag" (const :value :tag) (string))
2404 (cons :tag "TODO keyword" (const :value :todo) (string))
2405 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2406 (cons :tag "Level number" (const :value :level) (integer))
2407 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2409 (defcustom org-refile-target-verify-function nil
2410 "Function to verify if the headline at point should be a refile target.
2411 The function will be called without arguments, with point at the
2412 beginning of the headline. It should return t and leave point
2413 where it is if the headline is a valid target for refiling.
2415 If the target should not be selected, the function must return nil.
2416 In addition to this, it may move point to a place from where the search
2417 should be continued. For example, the function may decide that the entire
2418 subtree of the current entry should be excluded and move point to the end
2419 of the subtree."
2420 :group 'org-refile
2421 :type '(choice
2422 (const nil)
2423 (function)))
2425 (defcustom org-refile-use-cache nil
2426 "Non-nil means cache refile targets to speed up the process.
2427 \\<org-mode-map>\
2428 The cache for a particular file will be updated automatically when
2429 the buffer has been killed, or when any of the marker used for flagging
2430 refile targets no longer points at a live buffer.
2431 If you have added new entries to a buffer that might themselves be targets,
2432 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2433 if you find that easier, \
2434 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2435 \\[org-refile]'."
2436 :group 'org-refile
2437 :version "24.1"
2438 :type 'boolean)
2440 (defcustom org-refile-use-outline-path nil
2441 "Non-nil means provide refile targets as paths.
2442 So a level 3 headline will be available as level1/level2/level3.
2444 When the value is `file', also include the file name (without directory)
2445 into the path. In this case, you can also stop the completion after
2446 the file name, to get entries inserted as top level in the file.
2448 When `full-file-path', include the full file path."
2449 :group 'org-refile
2450 :type '(choice
2451 (const :tag "Not" nil)
2452 (const :tag "Yes" t)
2453 (const :tag "Start with file name" file)
2454 (const :tag "Start with full file path" full-file-path)))
2456 (defcustom org-outline-path-complete-in-steps t
2457 "Non-nil means complete the outline path in hierarchical steps.
2458 When Org-mode uses the refile interface to select an outline path
2459 \(see variable `org-refile-use-outline-path'), the completion of
2460 the path can be done in a single go, or it can be done in steps down
2461 the headline hierarchy. Going in steps is probably the best if you
2462 do not use a special completion package like `ido' or `icicles'.
2463 However, when using these packages, going in one step can be very
2464 fast, while still showing the whole path to the entry."
2465 :group 'org-refile
2466 :type 'boolean)
2468 (defcustom org-refile-allow-creating-parent-nodes nil
2469 "Non-nil means allow the creation of new nodes as refile targets.
2470 New nodes are then created by adding \"/new node name\" to the completion
2471 of an existing node. When the value of this variable is `confirm',
2472 new node creation must be confirmed by the user (recommended).
2473 When nil, the completion must match an existing entry.
2475 Note that, if the new heading is not seen by the criteria
2476 listed in `org-refile-targets', multiple instances of the same
2477 heading would be created by trying again to file under the new
2478 heading."
2479 :group 'org-refile
2480 :type '(choice
2481 (const :tag "Never" nil)
2482 (const :tag "Always" t)
2483 (const :tag "Prompt for confirmation" confirm)))
2485 (defcustom org-refile-active-region-within-subtree nil
2486 "Non-nil means also refile active region within a subtree.
2488 By default `org-refile' doesn't allow refiling regions if they
2489 don't contain a set of subtrees, but it might be convenient to
2490 do so sometimes: in that case, the first line of the region is
2491 converted to a headline before refiling."
2492 :group 'org-refile
2493 :version "24.1"
2494 :type 'boolean)
2496 (defgroup org-todo nil
2497 "Options concerning TODO items in Org-mode."
2498 :tag "Org TODO"
2499 :group 'org)
2501 (defgroup org-progress nil
2502 "Options concerning Progress logging in Org-mode."
2503 :tag "Org Progress"
2504 :group 'org-time)
2506 (defvar org-todo-interpretation-widgets
2507 '((:tag "Sequence (cycling hits every state)" sequence)
2508 (:tag "Type (cycling directly to DONE)" type))
2509 "The available interpretation symbols for customizing `org-todo-keywords'.
2510 Interested libraries should add to this list.")
2512 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2513 "List of TODO entry keyword sequences and their interpretation.
2514 \\<org-mode-map>This is a list of sequences.
2516 Each sequence starts with a symbol, either `sequence' or `type',
2517 indicating if the keywords should be interpreted as a sequence of
2518 action steps, or as different types of TODO items. The first
2519 keywords are states requiring action - these states will select a headline
2520 for inclusion into the global TODO list Org-mode produces. If one of
2521 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2522 signify that no further action is necessary. If \"|\" is not found,
2523 the last keyword is treated as the only DONE state of the sequence.
2525 The command \\[org-todo] cycles an entry through these states, and one
2526 additional state where no keyword is present. For details about this
2527 cycling, see the manual.
2529 TODO keywords and interpretation can also be set on a per-file basis with
2530 the special #+SEQ_TODO and #+TYP_TODO lines.
2532 Each keyword can optionally specify a character for fast state selection
2533 \(in combination with the variable `org-use-fast-todo-selection')
2534 and specifiers for state change logging, using the same syntax that
2535 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2536 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2537 indicates to record a time stamp each time this state is selected.
2539 Each keyword may also specify if a timestamp or a note should be
2540 recorded when entering or leaving the state, by adding additional
2541 characters in the parenthesis after the keyword. This looks like this:
2542 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2543 record only the time of the state change. With X and Y being either
2544 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2545 Y when leaving the state if and only if the *target* state does not
2546 define X. You may omit any of the fast-selection key or X or /Y,
2547 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2549 For backward compatibility, this variable may also be just a list
2550 of keywords. In this case the interpretation (sequence or type) will be
2551 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2552 :group 'org-todo
2553 :group 'org-keywords
2554 :type '(choice
2555 (repeat :tag "Old syntax, just keywords"
2556 (string :tag "Keyword"))
2557 (repeat :tag "New syntax"
2558 (cons
2559 (choice
2560 :tag "Interpretation"
2561 ;;Quick and dirty way to see
2562 ;;`org-todo-interpretations'. This takes the
2563 ;;place of item arguments
2564 :convert-widget
2565 (lambda (widget)
2566 (widget-put widget
2567 :args (mapcar
2568 (lambda (x)
2569 (widget-convert
2570 (cons 'const x)))
2571 org-todo-interpretation-widgets))
2572 widget))
2573 (repeat
2574 (string :tag "Keyword"))))))
2576 (defvar-local org-todo-keywords-1 nil
2577 "All TODO and DONE keywords active in a buffer.")
2578 (defvar org-todo-keywords-for-agenda nil)
2579 (defvar org-done-keywords-for-agenda nil)
2580 (defvar org-todo-keyword-alist-for-agenda nil)
2581 (defvar org-tag-alist-for-agenda nil
2582 "Alist of all tags from all agenda files.")
2583 (defvar org-tag-groups-alist-for-agenda nil
2584 "Alist of all groups tags from all current agenda files.")
2585 (defvar-local org-tag-groups-alist nil)
2586 (defvar org-agenda-contributing-files nil)
2587 (defvar-local org-current-tag-alist nil
2588 "Alist of all tag groups in current buffer.
2589 This variable takes into consideration `org-tag-alist',
2590 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2591 (defvar-local org-not-done-keywords nil)
2592 (defvar-local org-done-keywords nil)
2593 (defvar-local org-todo-heads nil)
2594 (defvar-local org-todo-sets nil)
2595 (defvar-local org-todo-log-states nil)
2596 (defvar-local org-todo-kwd-alist nil)
2597 (defvar-local org-todo-key-alist nil)
2598 (defvar-local org-todo-key-trigger nil)
2600 (defcustom org-todo-interpretation 'sequence
2601 "Controls how TODO keywords are interpreted.
2602 This variable is in principle obsolete and is only used for
2603 backward compatibility, if the interpretation of todo keywords is
2604 not given already in `org-todo-keywords'. See that variable for
2605 more information."
2606 :group 'org-todo
2607 :group 'org-keywords
2608 :type '(choice (const sequence)
2609 (const type)))
2611 (defcustom org-use-fast-todo-selection t
2612 "\\<org-mode-map>\
2613 Non-nil means use the fast todo selection scheme with \\[org-todo].
2614 This variable describes if and under what circumstances the cycling
2615 mechanism for TODO keywords will be replaced by a single-key, direct
2616 selection scheme.
2618 When nil, fast selection is never used.
2620 When the symbol `prefix', it will be used when `org-todo' is called
2621 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2622 in an Org-mode buffer, and
2623 `\\[universal-argument] t' in an agenda buffer.
2625 When t, fast selection is used by default. In this case, the prefix
2626 argument forces cycling instead.
2628 In all cases, the special interface is only used if access keys have
2629 actually been assigned by the user, i.e. if keywords in the configuration
2630 are followed by a letter in parenthesis, like TODO(t)."
2631 :group 'org-todo
2632 :type '(choice
2633 (const :tag "Never" nil)
2634 (const :tag "By default" t)
2635 (const :tag "Only with C-u C-c C-t" prefix)))
2637 (defcustom org-provide-todo-statistics t
2638 "Non-nil means update todo statistics after insert and toggle.
2639 ALL-HEADLINES means update todo statistics by including headlines
2640 with no TODO keyword as well, counting them as not done.
2641 A list of TODO keywords means the same, but skip keywords that are
2642 not in this list.
2643 When set to a list of two lists, the first list contains keywords
2644 to consider as TODO keywords, the second list contains keywords
2645 to consider as DONE keywords.
2647 When this is set, todo statistics is updated in the parent of the
2648 current entry each time a todo state is changed."
2649 :group 'org-todo
2650 :type '(choice
2651 (const :tag "Yes, only for TODO entries" t)
2652 (const :tag "Yes, including all entries" all-headlines)
2653 (repeat :tag "Yes, for TODOs in this list"
2654 (string :tag "TODO keyword"))
2655 (list :tag "Yes, for TODOs and DONEs in these lists"
2656 (repeat (string :tag "TODO keyword"))
2657 (repeat (string :tag "DONE keyword")))
2658 (other :tag "No TODO statistics" nil)))
2660 (defcustom org-hierarchical-todo-statistics t
2661 "Non-nil means TODO statistics covers just direct children.
2662 When nil, all entries in the subtree are considered.
2663 This has only an effect if `org-provide-todo-statistics' is set.
2664 To set this to nil for only a single subtree, use a COOKIE_DATA
2665 property and include the word \"recursive\" into the value."
2666 :group 'org-todo
2667 :type 'boolean)
2669 (defcustom org-after-todo-state-change-hook nil
2670 "Hook which is run after the state of a TODO item was changed.
2671 The new state (a string with a TODO keyword, or nil) is available in the
2672 Lisp variable `org-state'."
2673 :group 'org-todo
2674 :type 'hook)
2676 (defvar org-blocker-hook nil
2677 "Hook for functions that are allowed to block a state change.
2679 Functions in this hook should not modify the buffer.
2680 Each function gets as its single argument a property list,
2681 see `org-trigger-hook' for more information about this list.
2683 If any of the functions in this hook returns nil, the state change
2684 is blocked.")
2686 (defvar org-trigger-hook nil
2687 "Hook for functions that are triggered by a state change.
2689 Each function gets as its single argument a property list with at
2690 least the following elements:
2692 (:type type-of-change :position pos-at-entry-start
2693 :from old-state :to new-state)
2695 Depending on the type, more properties may be present.
2697 This mechanism is currently implemented for:
2699 TODO state changes
2700 ------------------
2701 :type todo-state-change
2702 :from previous state (keyword as a string), or nil, or a symbol
2703 `todo' or `done', to indicate the general type of state.
2704 :to new state, like in :from")
2706 (defcustom org-enforce-todo-dependencies nil
2707 "Non-nil means undone TODO entries will block switching the parent to DONE.
2708 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2709 be blocked if any prior sibling is not yet done.
2710 Finally, if the parent is blocked because of ordered siblings of its own,
2711 the child will also be blocked."
2712 :set (lambda (var val)
2713 (set var val)
2714 (if val
2715 (add-hook 'org-blocker-hook
2716 'org-block-todo-from-children-or-siblings-or-parent)
2717 (remove-hook 'org-blocker-hook
2718 'org-block-todo-from-children-or-siblings-or-parent)))
2719 :group 'org-todo
2720 :type 'boolean)
2722 (defcustom org-enforce-todo-checkbox-dependencies nil
2723 "Non-nil means unchecked boxes will block switching the parent to DONE.
2724 When this is nil, checkboxes have no influence on switching TODO states.
2725 When non-nil, you first need to check off all check boxes before the TODO
2726 entry can be switched to DONE.
2727 This variable needs to be set before org.el is loaded, and you need to
2728 restart Emacs after a change to make the change effective. The only way
2729 to change is while Emacs is running is through the customize interface."
2730 :set (lambda (var val)
2731 (set var val)
2732 (if val
2733 (add-hook 'org-blocker-hook
2734 'org-block-todo-from-checkboxes)
2735 (remove-hook 'org-blocker-hook
2736 'org-block-todo-from-checkboxes)))
2737 :group 'org-todo
2738 :type 'boolean)
2740 (defcustom org-treat-insert-todo-heading-as-state-change nil
2741 "Non-nil means inserting a TODO heading is treated as state change.
2742 So when the command \\[org-insert-todo-heading] is used, state change
2743 logging will apply if appropriate. When nil, the new TODO item will
2744 be inserted directly, and no logging will take place."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2749 "Non-nil means switching TODO states with S-cursor counts as state change.
2750 This is the default behavior. However, setting this to nil allows a
2751 convenient way to select a TODO state and bypass any logging associated
2752 with that."
2753 :group 'org-todo
2754 :type 'boolean)
2756 (defcustom org-todo-state-tags-triggers nil
2757 "Tag changes that should be triggered by TODO state changes.
2758 This is a list. Each entry is
2760 (state-change (tag . flag) .......)
2762 State-change can be a string with a state, and empty string to indicate the
2763 state that has no TODO keyword, or it can be one of the symbols `todo'
2764 or `done', meaning any not-done or done state, respectively."
2765 :group 'org-todo
2766 :group 'org-tags
2767 :type '(repeat
2768 (cons (choice :tag "When changing to"
2769 (const :tag "Not-done state" todo)
2770 (const :tag "Done state" done)
2771 (string :tag "State"))
2772 (repeat
2773 (cons :tag "Tag action"
2774 (string :tag "Tag")
2775 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2777 (defcustom org-log-done nil
2778 "Information to record when a task moves to the DONE state.
2780 Possible values are:
2782 nil Don't add anything, just change the keyword
2783 time Add a time stamp to the task
2784 note Prompt for a note and add it with template `org-log-note-headings'
2786 This option can also be set with on a per-file-basis with
2788 #+STARTUP: nologdone
2789 #+STARTUP: logdone
2790 #+STARTUP: lognotedone
2792 You can have local logging settings for a subtree by setting the LOGGING
2793 property to one or more of these keywords."
2794 :group 'org-todo
2795 :group 'org-progress
2796 :type '(choice
2797 (const :tag "No logging" nil)
2798 (const :tag "Record CLOSED timestamp" time)
2799 (const :tag "Record CLOSED timestamp with note." note)))
2801 ;; Normalize old uses of org-log-done.
2802 (cond
2803 ((eq org-log-done t) (setq org-log-done 'time))
2804 ((and (listp org-log-done) (memq 'done org-log-done))
2805 (setq org-log-done 'note)))
2807 (defcustom org-log-reschedule nil
2808 "Information to record when the scheduling date of a tasks is modified.
2810 Possible values are:
2812 nil Don't add anything, just change the date
2813 time Add a time stamp to the task
2814 note Prompt for a note and add it with template `org-log-note-headings'
2816 This option can also be set with on a per-file-basis with
2818 #+STARTUP: nologreschedule
2819 #+STARTUP: logreschedule
2820 #+STARTUP: lognotereschedule"
2821 :group 'org-todo
2822 :group 'org-progress
2823 :type '(choice
2824 (const :tag "No logging" nil)
2825 (const :tag "Record timestamp" time)
2826 (const :tag "Record timestamp with note." note)))
2828 (defcustom org-log-redeadline nil
2829 "Information to record when the deadline date of a tasks is modified.
2831 Possible values are:
2833 nil Don't add anything, just change the date
2834 time Add a time stamp to the task
2835 note Prompt for a note and add it with template `org-log-note-headings'
2837 This option can also be set with on a per-file-basis with
2839 #+STARTUP: nologredeadline
2840 #+STARTUP: logredeadline
2841 #+STARTUP: lognoteredeadline
2843 You can have local logging settings for a subtree by setting the LOGGING
2844 property to one or more of these keywords."
2845 :group 'org-todo
2846 :group 'org-progress
2847 :type '(choice
2848 (const :tag "No logging" nil)
2849 (const :tag "Record timestamp" time)
2850 (const :tag "Record timestamp with note." note)))
2852 (defcustom org-log-note-clock-out nil
2853 "Non-nil means record a note when clocking out of an item.
2854 This can also be configured on a per-file basis by adding one of
2855 the following lines anywhere in the buffer:
2857 #+STARTUP: lognoteclock-out
2858 #+STARTUP: nolognoteclock-out"
2859 :group 'org-todo
2860 :group 'org-progress
2861 :type 'boolean)
2863 (defcustom org-log-done-with-time t
2864 "Non-nil means the CLOSED time stamp will contain date and time.
2865 When nil, only the date will be recorded."
2866 :group 'org-progress
2867 :type 'boolean)
2869 (defcustom org-log-note-headings
2870 '((done . "CLOSING NOTE %t")
2871 (state . "State %-12s from %-12S %t")
2872 (note . "Note taken on %t")
2873 (reschedule . "Rescheduled from %S on %t")
2874 (delschedule . "Not scheduled, was %S on %t")
2875 (redeadline . "New deadline from %S on %t")
2876 (deldeadline . "Removed deadline, was %S on %t")
2877 (refile . "Refiled on %t")
2878 (clock-out . ""))
2879 "Headings for notes added to entries.
2881 The value is an alist, with the car being a symbol indicating the
2882 note context, and the cdr is the heading to be used. The heading
2883 may also be the empty string. The following placeholders can be
2884 used:
2886 %t a time stamp.
2887 %T an active time stamp instead the default inactive one
2888 %d a short-format time stamp.
2889 %D an active short-format time stamp.
2890 %s the new TODO state or time stamp (inactive), in double quotes.
2891 %S the old TODO state or time stamp (inactive), in double quotes.
2892 %u the user name.
2893 %U full user name.
2895 In fact, it is not a good idea to change the `state' entry,
2896 because Agenda Log mode depends on the format of these entries."
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type '(list :greedy t
2900 (cons (const :tag "Heading when closing an item" done) string)
2901 (cons (const :tag
2902 "Heading when changing todo state (todo sequence only)"
2903 state) string)
2904 (cons (const :tag "Heading when just taking a note" note) string)
2905 (cons (const :tag "Heading when rescheduling" reschedule) string)
2906 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2907 (cons (const :tag "Heading when changing deadline" redeadline) string)
2908 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2909 (cons (const :tag "Heading when refiling" refile) string)
2910 (cons (const :tag "Heading when clocking out" clock-out) string)))
2912 (unless (assq 'note org-log-note-headings)
2913 (push '(note . "%t") org-log-note-headings))
2915 (defcustom org-log-into-drawer nil
2916 "Non-nil means insert state change notes and time stamps into a drawer.
2917 When nil, state changes notes will be inserted after the headline and
2918 any scheduling and clock lines, but not inside a drawer.
2920 The value of this variable should be the name of the drawer to use.
2921 LOGBOOK is proposed as the default drawer for this purpose, you can
2922 also set this to a string to define the drawer of your choice.
2924 A value of t is also allowed, representing \"LOGBOOK\".
2926 A value of t or nil can also be set with on a per-file-basis with
2928 #+STARTUP: logdrawer
2929 #+STARTUP: nologdrawer
2931 If this variable is set, `org-log-state-notes-insert-after-drawers'
2932 will be ignored.
2934 You can set the property LOG_INTO_DRAWER to overrule this setting for
2935 a subtree.
2937 Do not check directly this variable in a Lisp program. Call
2938 function `org-log-into-drawer' instead."
2939 :group 'org-todo
2940 :group 'org-progress
2941 :type '(choice
2942 (const :tag "Not into a drawer" nil)
2943 (const :tag "LOGBOOK" t)
2944 (string :tag "Other")))
2946 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2948 (defun org-log-into-drawer ()
2949 "Name of the log drawer, as a string, or nil.
2950 This is the value of `org-log-into-drawer'. However, if the
2951 current entry has or inherits a LOG_INTO_DRAWER property, it will
2952 be used instead of the default value."
2953 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2954 (cond ((equal p "nil") nil)
2955 ((equal p "t") "LOGBOOK")
2956 ((stringp p) p)
2957 (p "LOGBOOK")
2958 ((stringp org-log-into-drawer) org-log-into-drawer)
2959 (org-log-into-drawer "LOGBOOK"))))
2961 (defcustom org-log-state-notes-insert-after-drawers nil
2962 "Non-nil means insert state change notes after any drawers in entry.
2963 Only the drawers that *immediately* follow the headline and the
2964 deadline/scheduled line are skipped.
2965 When nil, insert notes right after the heading and perhaps the line
2966 with deadline/scheduling if present.
2968 This variable will have no effect if `org-log-into-drawer' is
2969 set."
2970 :group 'org-todo
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-states-order-reversed t
2975 "Non-nil means the latest state note will be directly after heading.
2976 When nil, the state change notes will be ordered according to time.
2978 This option can also be set with on a per-file-basis with
2980 #+STARTUP: logstatesreversed
2981 #+STARTUP: nologstatesreversed"
2982 :group 'org-todo
2983 :group 'org-progress
2984 :type 'boolean)
2986 (defcustom org-todo-repeat-to-state nil
2987 "The TODO state to which a repeater should return the repeating task.
2988 By default this is the first task in a TODO sequence, or the previous state
2989 in a TODO_TYP set. But you can specify another task here.
2990 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2991 :group 'org-todo
2992 :version "24.1"
2993 :type '(choice (const :tag "Head of sequence" nil)
2994 (string :tag "Specific state")))
2996 (defcustom org-log-repeat 'time
2997 "Non-nil means record moving through the DONE state when triggering repeat.
2998 An auto-repeating task is immediately switched back to TODO when
2999 marked DONE. If you are not logging state changes (by adding \"@\"
3000 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3001 record a closing note, there will be no record of the task moving
3002 through DONE. This variable forces taking a note anyway.
3004 nil Don't force a record
3005 time Record a time stamp
3006 note Prompt for a note and add it with template `org-log-note-headings'
3008 This option can also be set with on a per-file-basis with
3010 #+STARTUP: nologrepeat
3011 #+STARTUP: logrepeat
3012 #+STARTUP: lognoterepeat
3014 You can have local logging settings for a subtree by setting the LOGGING
3015 property to one or more of these keywords."
3016 :group 'org-todo
3017 :group 'org-progress
3018 :type '(choice
3019 (const :tag "Don't force a record" nil)
3020 (const :tag "Force recording the DONE state" time)
3021 (const :tag "Force recording a note with the DONE state" note)))
3024 (defgroup org-priorities nil
3025 "Priorities in Org-mode."
3026 :tag "Org Priorities"
3027 :group 'org-todo)
3029 (defcustom org-enable-priority-commands t
3030 "Non-nil means priority commands are active.
3031 When nil, these commands will be disabled, so that you never accidentally
3032 set a priority."
3033 :group 'org-priorities
3034 :type 'boolean)
3036 (defcustom org-highest-priority ?A
3037 "The highest priority of TODO items. A character like ?A, ?B etc.
3038 Must have a smaller ASCII number than `org-lowest-priority'."
3039 :group 'org-priorities
3040 :type 'character)
3042 (defcustom org-lowest-priority ?C
3043 "The lowest priority of TODO items. A character like ?A, ?B etc.
3044 Must have a larger ASCII number than `org-highest-priority'."
3045 :group 'org-priorities
3046 :type 'character)
3048 (defcustom org-default-priority ?B
3049 "The default priority of TODO items.
3050 This is the priority an item gets if no explicit priority is given.
3051 When starting to cycle on an empty priority the first step in the cycle
3052 depends on `org-priority-start-cycle-with-default'. The resulting first
3053 step priority must not exceed the range from `org-highest-priority' to
3054 `org-lowest-priority' which means that `org-default-priority' has to be
3055 in this range exclusive or inclusive the range boundaries. Else the
3056 first step refuses to set the default and the second will fall back
3057 to (depending on the command used) the highest or lowest priority."
3058 :group 'org-priorities
3059 :type 'character)
3061 (defcustom org-priority-start-cycle-with-default t
3062 "Non-nil means start with default priority when starting to cycle.
3063 When this is nil, the first step in the cycle will be (depending on the
3064 command used) one higher or lower than the default priority.
3065 See also `org-default-priority'."
3066 :group 'org-priorities
3067 :type 'boolean)
3069 (defcustom org-get-priority-function nil
3070 "Function to extract the priority from a string.
3071 The string is normally the headline. If this is nil Org computes the
3072 priority from the priority cookie like [#A] in the headline. It returns
3073 an integer, increasing by 1000 for each priority level.
3074 The user can set a different function here, which should take a string
3075 as an argument and return the numeric priority."
3076 :group 'org-priorities
3077 :version "24.1"
3078 :type '(choice
3079 (const nil)
3080 (function)))
3082 (defgroup org-time nil
3083 "Options concerning time stamps and deadlines in Org-mode."
3084 :tag "Org Time"
3085 :group 'org)
3087 (defcustom org-time-stamp-rounding-minutes '(0 5)
3088 "Number of minutes to round time stamps to.
3089 \\<org-mode-map>\
3090 These are two values, the first applies when first creating a time stamp.
3091 The second applies when changing it with the commands `S-up' and `S-down'.
3092 When changing the time stamp, this means that it will change in steps
3093 of N minutes, as given by the second value.
3095 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3096 numbers should be factors of 60, so for example 5, 10, 15.
3098 When this is larger than 1, you can still force an exact time stamp by using
3099 a double prefix argument to a time stamp command like \
3100 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3101 and by using a prefix arg to `S-up/down' to specify the exact number
3102 of minutes to shift."
3103 :group 'org-time
3104 :get (lambda (var) ; Make sure both elements are there
3105 (if (integerp (default-value var))
3106 (list (default-value var) 5)
3107 (default-value var)))
3108 :type '(list
3109 (integer :tag "when inserting times")
3110 (integer :tag "when modifying times")))
3112 ;; Normalize old customizations of this variable.
3113 (when (integerp org-time-stamp-rounding-minutes)
3114 (setq org-time-stamp-rounding-minutes
3115 (list org-time-stamp-rounding-minutes
3116 org-time-stamp-rounding-minutes)))
3118 (defcustom org-display-custom-times nil
3119 "Non-nil means overlay custom formats over all time stamps.
3120 The formats are defined through the variable `org-time-stamp-custom-formats'.
3121 To turn this on on a per-file basis, insert anywhere in the file:
3122 #+STARTUP: customtime"
3123 :group 'org-time
3124 :set 'set-default
3125 :type 'sexp)
3126 (make-variable-buffer-local 'org-display-custom-times)
3128 (defcustom org-time-stamp-custom-formats
3129 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3130 "Custom formats for time stamps. See `format-time-string' for the syntax.
3131 These are overlaid over the default ISO format if the variable
3132 `org-display-custom-times' is set. Time like %H:%M should be at the
3133 end of the second format. The custom formats are also honored by export
3134 commands, if custom time display is turned on at the time of export."
3135 :group 'org-time
3136 :type 'sexp)
3138 (defun org-time-stamp-format (&optional long inactive)
3139 "Get the right format for a time string."
3140 (let ((f (if long (cdr org-time-stamp-formats)
3141 (car org-time-stamp-formats))))
3142 (if inactive
3143 (concat "[" (substring f 1 -1) "]")
3144 f)))
3146 (defcustom org-time-clocksum-format
3147 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3148 "The format string used when creating CLOCKSUM lines.
3149 This is also used when Org mode generates a time duration.
3151 The value can be a single format string containing two
3152 %-sequences, which will be filled with the number of hours and
3153 minutes in that order.
3155 Alternatively, the value can be a plist associating any of the
3156 keys :years, :months, :weeks, :days, :hours or :minutes with
3157 format strings. The time duration is formatted using only the
3158 time components that are needed and concatenating the results.
3159 If a time unit in absent, it falls back to the next smallest
3160 unit.
3162 The keys :require-years, :require-months, :require-days,
3163 :require-weeks, :require-hours, :require-minutes are also
3164 meaningful. A non-nil value for these keys indicates that the
3165 corresponding time component should always be included, even if
3166 its value is 0.
3169 For example,
3171 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3172 :require-minutes t)
3174 means durations longer than a day will be expressed in days,
3175 hours and minutes, and durations less than a day will always be
3176 expressed in hours and minutes (even for durations less than an
3177 hour).
3179 The value
3181 (:days \"%dd\" :minutes \"%dm\")
3183 means durations longer than a day will be expressed in days and
3184 minutes, and durations less than a day will be expressed entirely
3185 in minutes (even for durations longer than an hour)."
3186 :group 'org-time
3187 :group 'org-clock
3188 :version "24.4"
3189 :package-version '(Org . "8.0")
3190 :type '(choice (string :tag "Format string")
3191 (set :tag "Plist"
3192 (group :inline t (const :tag "Years" :years)
3193 (string :tag "Format string"))
3194 (group :inline t
3195 (const :tag "Always show years" :require-years)
3196 (const t))
3197 (group :inline t (const :tag "Months" :months)
3198 (string :tag "Format string"))
3199 (group :inline t
3200 (const :tag "Always show months" :require-months)
3201 (const t))
3202 (group :inline t (const :tag "Weeks" :weeks)
3203 (string :tag "Format string"))
3204 (group :inline t
3205 (const :tag "Always show weeks" :require-weeks)
3206 (const t))
3207 (group :inline t (const :tag "Days" :days)
3208 (string :tag "Format string"))
3209 (group :inline t
3210 (const :tag "Always show days" :require-days)
3211 (const t))
3212 (group :inline t (const :tag "Hours" :hours)
3213 (string :tag "Format string"))
3214 (group :inline t
3215 (const :tag "Always show hours" :require-hours)
3216 (const t))
3217 (group :inline t (const :tag "Minutes" :minutes)
3218 (string :tag "Format string"))
3219 (group :inline t
3220 (const :tag "Always show minutes" :require-minutes)
3221 (const t)))))
3223 (defcustom org-time-clocksum-use-fractional nil
3224 "When non-nil, \\[org-clock-display] uses fractional times.
3225 See `org-time-clocksum-format' for more on time clock formats."
3226 :group 'org-time
3227 :group 'org-clock
3228 :version "24.3"
3229 :type 'boolean)
3231 (defcustom org-time-clocksum-use-effort-durations nil
3232 "When non-nil, \\[org-clock-display] uses effort durations.
3233 E.g. by default, one day is considered to be a 8 hours effort,
3234 so a task that has been clocked for 16 hours will be displayed
3235 as during 2 days in the clock display or in the clocktable.
3237 See `org-effort-durations' on how to set effort durations
3238 and `org-time-clocksum-format' for more on time clock formats."
3239 :group 'org-time
3240 :group 'org-clock
3241 :version "24.4"
3242 :package-version '(Org . "8.0")
3243 :type 'boolean)
3245 (defcustom org-time-clocksum-fractional-format "%.2f"
3246 "The format string used when creating CLOCKSUM lines,
3247 or when Org mode generates a time duration, if
3248 `org-time-clocksum-use-fractional' is enabled.
3250 The value can be a single format string containing one
3251 %-sequence, which will be filled with the number of hours as
3252 a float.
3254 Alternatively, the value can be a plist associating any of the
3255 keys :years, :months, :weeks, :days, :hours or :minutes with
3256 a format string. The time duration is formatted using the
3257 largest time unit which gives a non-zero integer part. If all
3258 specified formats have zero integer part, the smallest time unit
3259 is used."
3260 :group 'org-time
3261 :type '(choice (string :tag "Format string")
3262 (set (group :inline t (const :tag "Years" :years)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Months" :months)
3265 (string :tag "Format string"))
3266 (group :inline t (const :tag "Weeks" :weeks)
3267 (string :tag "Format string"))
3268 (group :inline t (const :tag "Days" :days)
3269 (string :tag "Format string"))
3270 (group :inline t (const :tag "Hours" :hours)
3271 (string :tag "Format string"))
3272 (group :inline t (const :tag "Minutes" :minutes)
3273 (string :tag "Format string")))))
3275 (defcustom org-deadline-warning-days 14
3276 "Number of days before expiration during which a deadline becomes active.
3277 This variable governs the display in sparse trees and in the agenda.
3278 When 0 or negative, it means use this number (the absolute value of it)
3279 even if a deadline has a different individual lead time specified.
3281 Custom commands can set this variable in the options section."
3282 :group 'org-time
3283 :group 'org-agenda-daily/weekly
3284 :type 'integer)
3286 (defcustom org-scheduled-delay-days 0
3287 "Number of days before a scheduled item becomes active.
3288 This variable governs the display in sparse trees and in the agenda.
3289 The default value (i.e. 0) means: don't delay scheduled item.
3290 When negative, it means use this number (the absolute value of it)
3291 even if a scheduled item has a different individual delay time
3292 specified.
3294 Custom commands can set this variable in the options section."
3295 :group 'org-time
3296 :group 'org-agenda-daily/weekly
3297 :version "24.4"
3298 :package-version '(Org . "8.0")
3299 :type 'integer)
3301 (defcustom org-read-date-prefer-future t
3302 "Non-nil means assume future for incomplete date input from user.
3303 This affects the following situations:
3304 1. The user gives a month but not a year.
3305 For example, if it is April and you enter \"feb 2\", this will be read
3306 as Feb 2, *next* year. \"May 5\", however, will be this year.
3307 2. The user gives a day, but no month.
3308 For example, if today is the 15th, and you enter \"3\", Org-mode will
3309 read this as the third of *next* month. However, if you enter \"17\",
3310 it will be considered as *this* month.
3312 If you set this variable to the symbol `time', then also the following
3313 will work:
3315 3. If the user gives a time.
3316 If the time is before now, it will be interpreted as tomorrow.
3318 Currently none of this works for ISO week specifications.
3320 When this option is nil, the current day, month and year will always be
3321 used as defaults.
3323 See also `org-agenda-jump-prefer-future'."
3324 :group 'org-time
3325 :type '(choice
3326 (const :tag "Never" nil)
3327 (const :tag "Check month and day" t)
3328 (const :tag "Check month, day, and time" time)))
3330 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3331 "Should the agenda jump command prefer the future for incomplete dates?
3332 The default is to do the same as configured in `org-read-date-prefer-future'.
3333 But you can also set a deviating value here.
3334 This may t or nil, or the symbol `org-read-date-prefer-future'."
3335 :group 'org-agenda
3336 :group 'org-time
3337 :version "24.1"
3338 :type '(choice
3339 (const :tag "Use org-read-date-prefer-future"
3340 org-read-date-prefer-future)
3341 (const :tag "Never" nil)
3342 (const :tag "Always" t)))
3344 (defcustom org-read-date-force-compatible-dates t
3345 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3347 Depending on the system Emacs is running on, certain dates cannot
3348 be represented with the type used internally to represent time.
3349 Dates between 1970-1-1 and 2038-1-1 can always be represented
3350 correctly. Some systems allow for earlier dates, some for later,
3351 some for both. One way to find out it to insert any date into an
3352 Org buffer, putting the cursor on the year and hitting S-up and
3353 S-down to test the range.
3355 When this variable is set to t, the date/time prompt will not let
3356 you specify dates outside the 1970-2037 range, so it is certain that
3357 these dates will work in whatever version of Emacs you are
3358 running, and also that you can move a file from one Emacs implementation
3359 to another. WHenever Org is forcing the year for you, it will display
3360 a message and beep.
3362 When this variable is nil, Org will check if the date is
3363 representable in the specific Emacs implementation you are using.
3364 If not, it will force a year, usually the current year, and beep
3365 to remind you. Currently this setting is not recommended because
3366 the likelihood that you will open your Org files in an Emacs that
3367 has limited date range is not negligible.
3369 A workaround for this problem is to use diary sexp dates for time
3370 stamps outside of this range."
3371 :group 'org-time
3372 :version "24.1"
3373 :type 'boolean)
3375 (defcustom org-read-date-display-live t
3376 "Non-nil means display current interpretation of date prompt live.
3377 This display will be in an overlay, in the minibuffer."
3378 :group 'org-time
3379 :type 'boolean)
3381 (defcustom org-read-date-popup-calendar t
3382 "Non-nil means pop up a calendar when prompting for a date.
3383 In the calendar, the date can be selected with mouse-1. However, the
3384 minibuffer will also be active, and you can simply enter the date as well.
3385 When nil, only the minibuffer will be available."
3386 :group 'org-time
3387 :type 'boolean)
3388 (defvaralias 'org-popup-calendar-for-date-prompt
3389 'org-read-date-popup-calendar)
3391 (defcustom org-extend-today-until 0
3392 "The hour when your day really ends. Must be an integer.
3393 This has influence for the following applications:
3394 - When switching the agenda to \"today\". It it is still earlier than
3395 the time given here, the day recognized as TODAY is actually yesterday.
3396 - When a date is read from the user and it is still before the time given
3397 here, the current date and time will be assumed to be yesterday, 23:59.
3398 Also, timestamps inserted in capture templates follow this rule.
3400 IMPORTANT: This is a feature whose implementation is and likely will
3401 remain incomplete. Really, it is only here because past midnight seems to
3402 be the favorite working time of John Wiegley :-)"
3403 :group 'org-time
3404 :type 'integer)
3406 (defcustom org-use-effective-time nil
3407 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3408 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3409 \"effective time\" of any timestamps between midnight and 8am will be
3410 23:59 of the previous day."
3411 :group 'org-time
3412 :version "24.1"
3413 :type 'boolean)
3415 (defcustom org-use-last-clock-out-time-as-effective-time nil
3416 "When non-nil, use the last clock out time for `org-todo'.
3417 Note that this option has precedence over the combined use of
3418 `org-use-effective-time' and `org-extend-today-until'."
3419 :group 'org-time
3420 :version "24.4"
3421 :package-version '(Org . "8.0")
3422 :type 'boolean)
3424 (defcustom org-edit-timestamp-down-means-later nil
3425 "Non-nil means S-down will increase the time in a time stamp.
3426 When nil, S-up will increase."
3427 :group 'org-time
3428 :type 'boolean)
3430 (defcustom org-calendar-follow-timestamp-change t
3431 "Non-nil means make the calendar window follow timestamp changes.
3432 When a timestamp is modified and the calendar window is visible, it will be
3433 moved to the new date."
3434 :group 'org-time
3435 :type 'boolean)
3437 (defgroup org-tags nil
3438 "Options concerning tags in Org-mode."
3439 :tag "Org Tags"
3440 :group 'org)
3442 (defcustom org-tag-alist nil
3443 "Default tags available in Org files.
3445 The value of this variable is an alist. Associations either:
3447 (TAG)
3448 (TAG . SELECT)
3449 (SPECIAL)
3451 where TAG is a tag as a string, SELECT is a character, used to
3452 select that tag through the fast tag selection interface, and
3453 SPECIAL is one of the following keywords: `:startgroup',
3454 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3455 `:newline'. These keywords are used to define a hierarchy of
3456 tags. See manual for details.
3458 When this variable is nil, Org mode bases tag input on what is
3459 already in the buffer. The value can be overridden locally by
3460 using a TAGS keyword, e.g.,
3462 #+TAGS: tag1 tag2
3464 See also `org-tag-persistent-alist' to sidestep this behavior."
3465 :group 'org-tags
3466 :type '(repeat
3467 (choice
3468 (cons (string :tag "Tag name")
3469 (character :tag "Access char"))
3470 (const :tag "Start radio group" (:startgroup))
3471 (const :tag "Start tag group, non distinct" (:startgrouptag))
3472 (const :tag "Group tags delimiter" (:grouptags))
3473 (const :tag "End radio group" (:endgroup))
3474 (const :tag "End tag group, non distinct" (:endgrouptag))
3475 (const :tag "New line" (:newline)))))
3477 (defcustom org-tag-persistent-alist nil
3478 "Tags always available in Org files.
3480 The value of this variable is an alist. Associations either:
3482 (TAG)
3483 (TAG . SELECT)
3484 (SPECIAL)
3486 where TAG is a tag as a string, SELECT is a character, used to
3487 select that tag through the fast tag selection interface, and
3488 SPECIAL is one of the following keywords: `:startgroup',
3489 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3490 `:newline'. These keywords are used to define a hierarchy of
3491 tags. See manual for details.
3493 Unlike to `org-tag-alist', tags defined in this variable do not
3494 depend on a local TAGS keyword. Instead, to disable these tags
3495 on a per-file basis, insert anywhere in the file:
3497 #+STARTUP: noptag"
3498 :group 'org-tags
3499 :type '(repeat
3500 (choice
3501 (cons (string :tag "Tag name")
3502 (character :tag "Access char"))
3503 (const :tag "Start radio group" (:startgroup))
3504 (const :tag "Start tag group, non distinct" (:startgrouptag))
3505 (const :tag "Group tags delimiter" (:grouptags))
3506 (const :tag "End radio group" (:endgroup))
3507 (const :tag "End tag group, non distinct" (:endgrouptag))
3508 (const :tag "New line" (:newline)))))
3510 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3511 "If non-nil, always offer completion for all tags of all agenda files.
3512 Instead of customizing this variable directly, you might want to
3513 set it locally for capture buffers, because there no list of
3514 tags in that file can be created dynamically (there are none).
3516 (add-hook \\='org-capture-mode-hook
3517 (lambda ()
3518 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3519 :group 'org-tags
3520 :version "24.1"
3521 :type 'boolean)
3523 (defvar org-file-tags nil
3524 "List of tags that can be inherited by all entries in the file.
3525 The tags will be inherited if the variable `org-use-tag-inheritance'
3526 says they should be.
3527 This variable is populated from #+FILETAGS lines.")
3529 (defcustom org-use-fast-tag-selection 'auto
3530 "Non-nil means use fast tag selection scheme.
3531 This is a special interface to select and deselect tags with single keys.
3532 When nil, fast selection is never used.
3533 When the symbol `auto', fast selection is used if and only if selection
3534 characters for tags have been configured, either through the variable
3535 `org-tag-alist' or through a #+TAGS line in the buffer.
3536 When t, fast selection is always used and selection keys are assigned
3537 automatically if necessary."
3538 :group 'org-tags
3539 :type '(choice
3540 (const :tag "Always" t)
3541 (const :tag "Never" nil)
3542 (const :tag "When selection characters are configured" auto)))
3544 (defcustom org-fast-tag-selection-single-key nil
3545 "Non-nil means fast tag selection exits after first change.
3546 When nil, you have to press RET to exit it.
3547 During fast tag selection, you can toggle this flag with `C-c'.
3548 This variable can also have the value `expert'. In this case, the window
3549 displaying the tags menu is not even shown, until you press C-c again."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "No" nil)
3553 (const :tag "Yes" t)
3554 (const :tag "Expert" expert)))
3556 (defvar org-fast-tag-selection-include-todo nil
3557 "Non-nil means fast tags selection interface will also offer TODO states.
3558 This is an undocumented feature, you should not rely on it.")
3560 (defcustom org-tags-column -77
3561 "The column to which tags should be indented in a headline.
3562 If this number is positive, it specifies the column. If it is negative,
3563 it means that the tags should be flushright to that column. For example,
3564 -80 works well for a normal 80 character screen.
3565 When 0, place tags directly after headline text, with only one space in
3566 between."
3567 :group 'org-tags
3568 :type 'integer)
3570 (defcustom org-auto-align-tags t
3571 "Non-nil keeps tags aligned when modifying headlines.
3572 Some operations (i.e. demoting) change the length of a headline and
3573 therefore shift the tags around. With this option turned on, after
3574 each such operation the tags are again aligned to `org-tags-column'."
3575 :group 'org-tags
3576 :type 'boolean)
3578 (defcustom org-use-tag-inheritance t
3579 "Non-nil means tags in levels apply also for sublevels.
3580 When nil, only the tags directly given in a specific line apply there.
3581 This may also be a list of tags that should be inherited, or a regexp that
3582 matches tags that should be inherited. Additional control is possible
3583 with the variable `org-tags-exclude-from-inheritance' which gives an
3584 explicit list of tags to be excluded from inheritance, even if the value of
3585 `org-use-tag-inheritance' would select it for inheritance.
3587 If this option is t, a match early-on in a tree can lead to a large
3588 number of matches in the subtree when constructing the agenda or creating
3589 a sparse tree. If you only want to see the first match in a tree during
3590 a search, check out the variable `org-tags-match-list-sublevels'."
3591 :group 'org-tags
3592 :type '(choice
3593 (const :tag "Not" nil)
3594 (const :tag "Always" t)
3595 (repeat :tag "Specific tags" (string :tag "Tag"))
3596 (regexp :tag "Tags matched by regexp")))
3598 (defcustom org-tags-exclude-from-inheritance nil
3599 "List of tags that should never be inherited.
3600 This is a way to exclude a few tags from inheritance. For way to do
3601 the opposite, to actively allow inheritance for selected tags,
3602 see the variable `org-use-tag-inheritance'."
3603 :group 'org-tags
3604 :type '(repeat (string :tag "Tag")))
3606 (defun org-tag-inherit-p (tag)
3607 "Check if TAG is one that should be inherited."
3608 (cond
3609 ((member tag org-tags-exclude-from-inheritance) nil)
3610 ((eq org-use-tag-inheritance t) t)
3611 ((not org-use-tag-inheritance) nil)
3612 ((stringp org-use-tag-inheritance)
3613 (string-match org-use-tag-inheritance tag))
3614 ((listp org-use-tag-inheritance)
3615 (member tag org-use-tag-inheritance))
3616 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3618 (defcustom org-tags-match-list-sublevels t
3619 "Non-nil means list also sublevels of headlines matching a search.
3620 This variable applies to tags/property searches, and also to stuck
3621 projects because this search is based on a tags match as well.
3623 When set to the symbol `indented', sublevels are indented with
3624 leading dots.
3626 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3627 the sublevels of a headline matching a tag search often also match
3628 the same search. Listing all of them can create very long lists.
3629 Setting this variable to nil causes subtrees of a match to be skipped.
3631 This variable is semi-obsolete and probably should always be true. It
3632 is better to limit inheritance to certain tags using the variables
3633 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3634 :group 'org-tags
3635 :type '(choice
3636 (const :tag "No, don't list them" nil)
3637 (const :tag "Yes, do list them" t)
3638 (const :tag "List them, indented with leading dots" indented)))
3640 (defcustom org-tags-sort-function nil
3641 "When set, tags are sorted using this function as a comparator."
3642 :group 'org-tags
3643 :type '(choice
3644 (const :tag "No sorting" nil)
3645 (const :tag "Alphabetical" string<)
3646 (const :tag "Reverse alphabetical" string>)
3647 (function :tag "Custom function" nil)))
3649 (defvar org-tags-history nil
3650 "History of minibuffer reads for tags.")
3651 (defvar org-last-tags-completion-table nil
3652 "The last used completion table for tags.")
3653 (defvar org-after-tags-change-hook nil
3654 "Hook that is run after the tags in a line have changed.")
3656 (defgroup org-properties nil
3657 "Options concerning properties in Org-mode."
3658 :tag "Org Properties"
3659 :group 'org)
3661 (defcustom org-property-format "%-10s %s"
3662 "How property key/value pairs should be formatted by `indent-line'.
3663 When `indent-line' hits a property definition, it will format the line
3664 according to this format, mainly to make sure that the values are
3665 lined-up with respect to each other."
3666 :group 'org-properties
3667 :type 'string)
3669 (defcustom org-properties-postprocess-alist nil
3670 "Alist of properties and functions to adjust inserted values.
3671 Elements of this alist must be of the form
3673 ([string] [function])
3675 where [string] must be a property name and [function] must be a
3676 lambda expression: this lambda expression must take one argument,
3677 the value to adjust, and return the new value as a string.
3679 For example, this element will allow the property \"Remaining\"
3680 to be updated wrt the relation between the \"Effort\" property
3681 and the clock summary:
3683 ((\"Remaining\" (lambda(value)
3684 (let ((clocksum (org-clock-sum-current-item))
3685 (effort (org-duration-string-to-minutes
3686 (org-entry-get (point) \"Effort\"))))
3687 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3688 :group 'org-properties
3689 :version "24.1"
3690 :type '(alist :key-type (string :tag "Property")
3691 :value-type (function :tag "Function")))
3693 (defcustom org-use-property-inheritance nil
3694 "Non-nil means properties apply also for sublevels.
3696 This setting is chiefly used during property searches. Turning it on can
3697 cause significant overhead when doing a search, which is why it is not
3698 on by default.
3700 When nil, only the properties directly given in the current entry count.
3701 When t, every property is inherited. The value may also be a list of
3702 properties that should have inheritance, or a regular expression matching
3703 properties that should be inherited.
3705 However, note that some special properties use inheritance under special
3706 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3707 and the properties ending in \"_ALL\" when they are used as descriptor
3708 for valid values of a property.
3710 Note for programmers:
3711 When querying an entry with `org-entry-get', you can control if inheritance
3712 should be used. By default, `org-entry-get' looks only at the local
3713 properties. You can request inheritance by setting the inherit argument
3714 to t (to force inheritance) or to `selective' (to respect the setting
3715 in this variable)."
3716 :group 'org-properties
3717 :type '(choice
3718 (const :tag "Not" nil)
3719 (const :tag "Always" t)
3720 (repeat :tag "Specific properties" (string :tag "Property"))
3721 (regexp :tag "Properties matched by regexp")))
3723 (defun org-property-inherit-p (property)
3724 "Check if PROPERTY is one that should be inherited."
3725 (cond
3726 ((eq org-use-property-inheritance t) t)
3727 ((not org-use-property-inheritance) nil)
3728 ((stringp org-use-property-inheritance)
3729 (string-match org-use-property-inheritance property))
3730 ((listp org-use-property-inheritance)
3731 (member property org-use-property-inheritance))
3732 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3734 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3735 "The default column format, if no other format has been defined.
3736 This variable can be set on the per-file basis by inserting a line
3738 #+COLUMNS: %25ITEM ....."
3739 :group 'org-properties
3740 :type 'string)
3742 (defcustom org-columns-ellipses ".."
3743 "The ellipses to be used when a field in column view is truncated.
3744 When this is the empty string, as many characters as possible are shown,
3745 but then there will be no visual indication that the field has been truncated.
3746 When this is a string of length N, the last N characters of a truncated
3747 field are replaced by this string. If the column is narrower than the
3748 ellipses string, only part of the ellipses string will be shown."
3749 :group 'org-properties
3750 :type 'string)
3752 (defconst org-global-properties-fixed
3753 '(("VISIBILITY_ALL" . "folded children content all")
3754 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3755 "List of property/value pairs that can be inherited by any entry.
3757 These are fixed values, for the preset properties. The user variable
3758 that can be used to add to this list is `org-global-properties'.
3760 The entries in this list are cons cells where the car is a property
3761 name and cdr is a string with the value. If the value represents
3762 multiple items like an \"_ALL\" property, separate the items by
3763 spaces.")
3765 (defcustom org-global-properties nil
3766 "List of property/value pairs that can be inherited by any entry.
3768 This list will be combined with the constant `org-global-properties-fixed'.
3770 The entries in this list are cons cells where the car is a property
3771 name and cdr is a string with the value.
3773 You can set buffer-local values for the same purpose in the variable
3774 `org-file-properties' this by adding lines like
3776 #+PROPERTY: NAME VALUE"
3777 :group 'org-properties
3778 :type '(repeat
3779 (cons (string :tag "Property")
3780 (string :tag "Value"))))
3782 (defvar-local org-file-properties nil
3783 "List of property/value pairs that can be inherited by any entry.
3784 Valid for the current buffer.
3785 This variable is populated from #+PROPERTY lines.")
3787 (defgroup org-agenda nil
3788 "Options concerning agenda views in Org-mode."
3789 :tag "Org Agenda"
3790 :group 'org)
3792 (defvar-local org-category nil
3793 "Variable used by org files to set a category for agenda display.
3794 Such files should use a file variable to set it, for example
3796 # -*- mode: org; org-category: \"ELisp\"
3798 or contain a special line
3800 #+CATEGORY: ELisp
3802 If the file does not specify a category, then file's base name
3803 is used instead.")
3804 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3806 (defcustom org-agenda-files nil
3807 "The files to be used for agenda display.
3808 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3809 \\[org-remove-file]. You can also use customize to edit the list.
3811 If an entry is a directory, all files in that directory that are matched by
3812 `org-agenda-file-regexp' will be part of the file list.
3814 If the value of the variable is not a list but a single file name, then
3815 the list of agenda files is actually stored and maintained in that file, one
3816 agenda file per line. In this file paths can be given relative to
3817 `org-directory'. Tilde expansion and environment variable substitution
3818 are also made."
3819 :group 'org-agenda
3820 :type '(choice
3821 (repeat :tag "List of files and directories" file)
3822 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3824 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3825 "Regular expression to match files for `org-agenda-files'.
3826 If any element in the list in that variable contains a directory instead
3827 of a normal file, all files in that directory that are matched by this
3828 regular expression will be included."
3829 :group 'org-agenda
3830 :type 'regexp)
3832 (defcustom org-agenda-text-search-extra-files nil
3833 "List of extra files to be searched by text search commands.
3834 These files will be searched in addition to the agenda files by the
3835 commands `org-search-view' (`\\[org-agenda] s') \
3836 and `org-occur-in-agenda-files'.
3837 Note that these files will only be searched for text search commands,
3838 not for the other agenda views like todo lists, tag searches or the weekly
3839 agenda. This variable is intended to list notes and possibly archive files
3840 that should also be searched by these two commands.
3841 In fact, if the first element in the list is the symbol `agenda-archives',
3842 then all archive files of all agenda files will be added to the search
3843 scope."
3844 :group 'org-agenda
3845 :type '(set :greedy t
3846 (const :tag "Agenda Archives" agenda-archives)
3847 (repeat :inline t (file))))
3849 (defvaralias 'org-agenda-multi-occur-extra-files
3850 'org-agenda-text-search-extra-files)
3852 (defcustom org-agenda-skip-unavailable-files nil
3853 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3854 A nil value means to remove them, after a query, from the list."
3855 :group 'org-agenda
3856 :type 'boolean)
3858 (defcustom org-calendar-to-agenda-key [?c]
3859 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3860 The command `org-calendar-goto-agenda' will be bound to this key. The
3861 default is the character `c' because then `c' can be used to switch back and
3862 forth between agenda and calendar."
3863 :group 'org-agenda
3864 :type 'sexp)
3866 (defcustom org-calendar-insert-diary-entry-key [?i]
3867 "The key to be installed in `calendar-mode-map' for adding diary entries.
3868 This option is irrelevant until `org-agenda-diary-file' has been configured
3869 to point to an Org-mode file. When that is the case, the command
3870 `org-agenda-diary-entry' will be bound to the key given here, by default
3871 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3872 if you want to continue doing this, you need to change this to a different
3873 key."
3874 :group 'org-agenda
3875 :type 'sexp)
3877 (defcustom org-agenda-diary-file 'diary-file
3878 "File to which to add new entries with the `i' key in agenda and calendar.
3879 When this is the symbol `diary-file', the functionality in the Emacs
3880 calendar will be used to add entries to the `diary-file'. But when this
3881 points to a file, `org-agenda-diary-entry' will be used instead."
3882 :group 'org-agenda
3883 :type '(choice
3884 (const :tag "The standard Emacs diary file" diary-file)
3885 (file :tag "Special Org file diary entries")))
3887 (eval-after-load "calendar"
3888 '(progn
3889 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3890 'org-calendar-goto-agenda)
3891 (add-hook 'calendar-mode-hook
3892 (lambda ()
3893 (unless (eq org-agenda-diary-file 'diary-file)
3894 (define-key calendar-mode-map
3895 org-calendar-insert-diary-entry-key
3896 'org-agenda-diary-entry))))))
3898 (defgroup org-latex nil
3899 "Options for embedding LaTeX code into Org-mode."
3900 :tag "Org LaTeX"
3901 :group 'org)
3903 (defcustom org-format-latex-options
3904 '(:foreground default :background default :scale 1.0
3905 :html-foreground "Black" :html-background "Transparent"
3906 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3907 "Options for creating images from LaTeX fragments.
3908 This is a property list with the following properties:
3909 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3910 `default' means use the foreground of the default face.
3911 `auto' means use the foreground from the text face.
3912 :background the background color, or \"Transparent\".
3913 `default' means use the background of the default face.
3914 `auto' means use the background from the text face.
3915 :scale a scaling factor for the size of the images, to get more pixels
3916 :html-foreground, :html-background, :html-scale
3917 the same numbers for HTML export.
3918 :matchers a list indicating which matchers should be used to
3919 find LaTeX fragments. Valid members of this list are:
3920 \"begin\" find environments
3921 \"$1\" find single characters surrounded by $.$
3922 \"$\" find math expressions surrounded by $...$
3923 \"$$\" find math expressions surrounded by $$....$$
3924 \"\\(\" find math expressions surrounded by \\(...\\)
3925 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3926 :group 'org-latex
3927 :type 'plist)
3929 (defcustom org-format-latex-signal-error t
3930 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3931 When nil, just push out a message."
3932 :group 'org-latex
3933 :version "24.1"
3934 :type 'boolean)
3936 (defcustom org-latex-to-mathml-jar-file nil
3937 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3938 Use this to specify additional executable file say a jar file.
3940 When using MathToWeb as the converter, specify the full-path to
3941 your mathtoweb.jar file."
3942 :group 'org-latex
3943 :version "24.1"
3944 :type '(choice
3945 (const :tag "None" nil)
3946 (file :tag "JAR file" :must-match t)))
3948 (defcustom org-latex-to-mathml-convert-command nil
3949 "Command to convert LaTeX fragments to MathML.
3950 Replace format-specifiers in the command as noted below and use
3951 `shell-command' to convert LaTeX to MathML.
3952 %j: Executable file in fully expanded form as specified by
3953 `org-latex-to-mathml-jar-file'.
3954 %I: Input LaTeX file in fully expanded form.
3955 %i: The latex fragment to be converted.
3956 %o: Output MathML file.
3958 This command is used by `org-create-math-formula'.
3960 When using MathToWeb as the converter, set this option to
3961 \"java -jar %j -unicode -force -df %o %I\".
3963 When using LaTeXML set this option to
3964 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3965 :group 'org-latex
3966 :version "24.1"
3967 :type '(choice
3968 (const :tag "None" nil)
3969 (string :tag "\nShell command")))
3971 (defcustom org-preview-latex-default-process 'dvipng
3972 "The default process to convert LaTeX fragments to image files.
3973 All available processes and theirs documents can be found in
3974 `org-preview-latex-process-alist', which see."
3975 :group 'org-latex
3976 :version "25.2"
3977 :package-version '(Org . "9.0")
3978 :type 'symbol)
3980 (defcustom org-preview-latex-process-alist
3981 '((dvipng
3982 :programs ("latex" "dvipng" "gs")
3983 :description "dvi > png"
3984 :message "you need to install the programs: latex, dvipng and ghostscript."
3985 :image-input-type "dvi"
3986 :image-output-type "png"
3987 :image-size-adjust (1.0 . 1.0)
3988 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3989 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
3990 (dvisvgm
3991 :programs ("latex" "dvisvgm" "gs")
3992 :description "dvi > svg"
3993 :message "you need to install the programs: latex, dvisvgm and ghostscript."
3994 :use-xcolor t
3995 :image-input-type "dvi"
3996 :image-output-type "svg"
3997 :image-size-adjust (1.7 . 1.5)
3998 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3999 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4000 (imagemagick
4001 :programs ("latex" "convert" "gs")
4002 :description "pdf > png"
4003 :message
4004 "you need to install the programs: latex, imagemagick and ghostscript."
4005 :use-xcolor t
4006 :image-input-type "pdf"
4007 :image-output-type "png"
4008 :image-size-adjust (1.0 . 1.0)
4009 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4010 :image-converter
4011 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4012 "Definitions of external processes for LaTeX previewing.
4013 Org mode can use some external commands to generate TeX snippet's images for
4014 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4015 `org-create-formula-image' how to call them.
4017 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4018 PROPERTIES accepts the following attributes:
4020 :programs list of strings, required programs.
4021 :description string, describe the process.
4022 :message string, message it when required programs cannot be found.
4023 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4024 :image-output-type string, output file type of image converter (e.g., \"png\").
4025 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4026 deal with background and foreground color of image.
4027 Otherwise, dvipng style background and foregroud color
4028 format are generated. You may then refer to them in
4029 command options with \"%F\" and \"%B\".
4030 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4031 image size showed in buffer and the cdr element is for
4032 HTML file. This option is only useful for process
4033 developers, users should use variable
4034 `org-format-latex-options' instead.
4035 :post-clean list of strings, files matched are to be cleaned up once
4036 the image is generated. When nil, the files with \".dvi\",
4037 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4038 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4039 be cleaned up.
4040 :latex-header list of strings, the LaTeX header of the snippet file.
4041 When nil, the fallback value is used instead, which is
4042 controlled by `org-format-latex-header',
4043 `org-latex-default-packages-alist' and
4044 `org-latex-packages-alist', which see.
4045 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4046 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4047 replaced with values defined below.
4048 :image-converter list of image converter commands strings. Each of them is
4049 given to the shell and supports any of the following
4050 place-holders defined below.
4052 Place-holders used by `:image-converter' and `:latex-compiler':
4054 %f input file name.
4055 %b base name of input file.
4056 %o base directory of input file.
4058 Place-holders only used by `:image-converter':
4060 %F foreground of image
4061 %B background of image
4062 %D dpi, which is used to adjust image size by some processing commands.
4063 %S the image size scale ratio, which is used to adjust image size by some
4064 processing commands."
4065 :group 'org-latex
4066 :version "25.2"
4067 :package-version '(Org . "9.0")
4068 :type '(alist :tag "LaTeX to image backends"
4069 :value-type (plist)))
4071 (defcustom org-preview-latex-image-directory "ltximg/"
4072 "Path to store latex preview images.
4073 A relative path here creates many directories relative to the
4074 processed org files paths. An absolute path puts all preview
4075 images at the same place."
4076 :group 'org-latex
4077 :version "25.1"
4078 :package-version '(Org . "9.0")
4079 :type 'string)
4081 (defun org-format-latex-mathml-available-p ()
4082 "Return t if `org-latex-to-mathml-convert-command' is usable."
4083 (save-match-data
4084 (when (and (boundp 'org-latex-to-mathml-convert-command)
4085 org-latex-to-mathml-convert-command)
4086 (let ((executable (car (split-string
4087 org-latex-to-mathml-convert-command))))
4088 (when (executable-find executable)
4089 (if (string-match
4090 "%j" org-latex-to-mathml-convert-command)
4091 (file-readable-p org-latex-to-mathml-jar-file)
4092 t))))))
4094 (defcustom org-format-latex-header "\\documentclass{article}
4095 \\usepackage[usenames]{color}
4096 \[PACKAGES]
4097 \[DEFAULT-PACKAGES]
4098 \\pagestyle{empty} % do not remove
4099 % The settings below are copied from fullpage.sty
4100 \\setlength{\\textwidth}{\\paperwidth}
4101 \\addtolength{\\textwidth}{-3cm}
4102 \\setlength{\\oddsidemargin}{1.5cm}
4103 \\addtolength{\\oddsidemargin}{-2.54cm}
4104 \\setlength{\\evensidemargin}{\\oddsidemargin}
4105 \\setlength{\\textheight}{\\paperheight}
4106 \\addtolength{\\textheight}{-\\headheight}
4107 \\addtolength{\\textheight}{-\\headsep}
4108 \\addtolength{\\textheight}{-\\footskip}
4109 \\addtolength{\\textheight}{-3cm}
4110 \\setlength{\\topmargin}{1.5cm}
4111 \\addtolength{\\topmargin}{-2.54cm}"
4112 "The document header used for processing LaTeX fragments.
4113 It is imperative that this header make sure that no page number
4114 appears on the page. The package defined in the variables
4115 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4116 will either replace the placeholder \"[PACKAGES]\" in this
4117 header, or they will be appended."
4118 :group 'org-latex
4119 :type 'string)
4121 (defun org-set-packages-alist (var val)
4122 "Set the packages alist and make sure it has 3 elements per entry."
4123 (set var (mapcar (lambda (x)
4124 (if (and (consp x) (= (length x) 2))
4125 (list (car x) (nth 1 x) t)
4127 val)))
4129 (defun org-get-packages-alist (var)
4130 "Get the packages alist and make sure it has 3 elements per entry."
4131 (mapcar (lambda (x)
4132 (if (and (consp x) (= (length x) 2))
4133 (list (car x) (nth 1 x) t)
4135 (default-value var)))
4137 (defcustom org-latex-default-packages-alist
4138 '(("AUTO" "inputenc" t ("pdflatex"))
4139 ("T1" "fontenc" t ("pdflatex"))
4140 ("" "graphicx" t)
4141 ("" "grffile" t)
4142 ("" "longtable" nil)
4143 ("" "wrapfig" nil)
4144 ("" "rotating" nil)
4145 ("normalem" "ulem" t)
4146 ("" "amsmath" t)
4147 ("" "textcomp" t)
4148 ("" "amssymb" t)
4149 ("" "capt-of" nil)
4150 ("" "hyperref" nil))
4151 "Alist of default packages to be inserted in the header.
4153 Change this only if one of the packages here causes an
4154 incompatibility with another package you are using.
4156 The packages in this list are needed by one part or another of
4157 Org mode to function properly:
4159 - inputenc, fontenc: for basic font and character selection
4160 - graphicx: for including images
4161 - grffile: allow periods and spaces in graphics file names
4162 - longtable: For multipage tables
4163 - wrapfig: for figure placement
4164 - rotating: for sideways figures and tables
4165 - ulem: for underline and strike-through
4166 - amsmath: for subscript and superscript and math environments
4167 - textcomp, amssymb: for various symbols used
4168 for interpreting the entities in `org-entities'. You can skip
4169 some of these packages if you don't use any of their symbols.
4170 - capt-of: for captions outside of floats
4171 - hyperref: for cross references
4173 Therefore you should not modify this variable unless you know
4174 what you are doing. The one reason to change it anyway is that
4175 you might be loading some other package that conflicts with one
4176 of the default packages. Each element is either a cell or
4177 a string.
4179 A cell is of the format
4181 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4183 If SNIPPET-FLAG is non-nil, the package also needs to be included
4184 when compiling LaTeX snippets into images for inclusion into
4185 non-LaTeX output. COMPILERS is a list of compilers that should
4186 include the package, see `org-latex-compiler'. If the document
4187 compiler is not in the list, and the list is non-nil, the package
4188 will not be inserted in the final document.
4190 A string will be inserted as-is in the header of the document."
4191 :group 'org-latex
4192 :group 'org-export-latex
4193 :set 'org-set-packages-alist
4194 :get 'org-get-packages-alist
4195 :version "25.1"
4196 :package-version '(Org . "8.3")
4197 :type '(repeat
4198 (choice
4199 (list :tag "options/package pair"
4200 (string :tag "options")
4201 (string :tag "package")
4202 (boolean :tag "Snippet"))
4203 (string :tag "A line of LaTeX"))))
4205 (defcustom org-latex-packages-alist nil
4206 "Alist of packages to be inserted in every LaTeX header.
4208 These will be inserted after `org-latex-default-packages-alist'.
4209 Each element is either a cell or a string.
4211 A cell is of the format:
4213 (\"options\" \"package\" SNIPPET-FLAG)
4215 SNIPPET-FLAG, when non-nil, indicates that this package is also
4216 needed when turning LaTeX snippets into images for inclusion into
4217 non-LaTeX output.
4219 A string will be inserted as-is in the header of the document.
4221 Make sure that you only list packages here which:
4223 - you want in every file;
4224 - do not conflict with the setup in `org-format-latex-header';
4225 - do not conflict with the default packages in
4226 `org-latex-default-packages-alist'."
4227 :group 'org-latex
4228 :group 'org-export-latex
4229 :set 'org-set-packages-alist
4230 :get 'org-get-packages-alist
4231 :type '(repeat
4232 (choice
4233 (list :tag "options/package pair"
4234 (string :tag "options")
4235 (string :tag "package")
4236 (boolean :tag "Snippet"))
4237 (string :tag "A line of LaTeX"))))
4239 (defgroup org-appearance nil
4240 "Settings for Org-mode appearance."
4241 :tag "Org Appearance"
4242 :group 'org)
4244 (defcustom org-level-color-stars-only nil
4245 "Non-nil means fontify only the stars in each headline.
4246 When nil, the entire headline is fontified.
4247 Changing it requires restart of `font-lock-mode' to become effective
4248 also in regions already fontified."
4249 :group 'org-appearance
4250 :type 'boolean)
4252 (defcustom org-hide-leading-stars nil
4253 "Non-nil means hide the first N-1 stars in a headline.
4254 This works by using the face `org-hide' for these stars. This
4255 face is white for a light background, and black for a dark
4256 background. You may have to customize the face `org-hide' to
4257 make this work.
4258 Changing it requires restart of `font-lock-mode' to become effective
4259 also in regions already fontified.
4260 You may also set this on a per-file basis by adding one of the following
4261 lines to the buffer:
4263 #+STARTUP: hidestars
4264 #+STARTUP: showstars"
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-hidden-keywords nil
4269 "List of symbols corresponding to keywords to be hidden the org buffer.
4270 For example, a value \\='(title) for this list will make the document's title
4271 appear in the buffer without the initial #+TITLE: keyword."
4272 :group 'org-appearance
4273 :version "24.1"
4274 :type '(set (const :tag "#+AUTHOR" author)
4275 (const :tag "#+DATE" date)
4276 (const :tag "#+EMAIL" email)
4277 (const :tag "#+TITLE" title)))
4279 (defcustom org-custom-properties nil
4280 "List of properties (as strings) with a special meaning.
4281 The default use of these custom properties is to let the user
4282 hide them with `org-toggle-custom-properties-visibility'."
4283 :group 'org-properties
4284 :group 'org-appearance
4285 :version "24.3"
4286 :type '(repeat (string :tag "Property Name")))
4288 (defcustom org-fontify-done-headline nil
4289 "Non-nil means change the face of a headline if it is marked DONE.
4290 Normally, only the TODO/DONE keyword indicates the state of a headline.
4291 When this is non-nil, the headline after the keyword is set to the
4292 `org-headline-done' as an additional indication."
4293 :group 'org-appearance
4294 :type 'boolean)
4296 (defcustom org-fontify-emphasized-text t
4297 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4298 Changing this variable requires a restart of Emacs to take effect."
4299 :group 'org-appearance
4300 :type 'boolean)
4302 (defcustom org-fontify-whole-heading-line nil
4303 "Non-nil means fontify the whole line for headings.
4304 This is useful when setting a background color for the
4305 org-level-* faces."
4306 :group 'org-appearance
4307 :type 'boolean)
4309 (defcustom org-highlight-latex-and-related nil
4310 "Non-nil means highlight LaTeX related syntax in the buffer.
4311 When non nil, the value should be a list containing any of the
4312 following symbols:
4313 `latex' Highlight LaTeX snippets and environments.
4314 `script' Highlight subscript and superscript.
4315 `entities' Highlight entities."
4316 :group 'org-appearance
4317 :version "24.4"
4318 :package-version '(Org . "8.0")
4319 :type '(choice
4320 (const :tag "No highlighting" nil)
4321 (set :greedy t :tag "Highlight"
4322 (const :tag "LaTeX snippets and environments" latex)
4323 (const :tag "Subscript and superscript" script)
4324 (const :tag "Entities" entities))))
4326 (defcustom org-hide-emphasis-markers nil
4327 "Non-nil mean font-lock should hide the emphasis marker characters."
4328 :group 'org-appearance
4329 :type 'boolean)
4331 (defcustom org-hide-macro-markers nil
4332 "Non-nil mean font-lock should hide the brackets marking macro calls."
4333 :group 'org-appearance
4334 :type 'boolean)
4336 (defcustom org-pretty-entities nil
4337 "Non-nil means show entities as UTF8 characters.
4338 When nil, the \\name form remains in the buffer."
4339 :group 'org-appearance
4340 :version "24.1"
4341 :type 'boolean)
4343 (defcustom org-pretty-entities-include-sub-superscripts t
4344 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4345 :group 'org-appearance
4346 :version "24.1"
4347 :type 'boolean)
4349 (defvar org-emph-re nil
4350 "Regular expression for matching emphasis.
4351 After a match, the match groups contain these elements:
4352 0 The match of the full regular expression, including the characters
4353 before and after the proper match
4354 1 The character before the proper match, or empty at beginning of line
4355 2 The proper match, including the leading and trailing markers
4356 3 The leading marker like * or /, indicating the type of highlighting
4357 4 The text between the emphasis markers, not including the markers
4358 5 The character after the match, empty at the end of a line")
4359 (defvar org-verbatim-re nil
4360 "Regular expression for matching verbatim text.")
4361 (defvar org-emphasis-regexp-components) ; defined just below
4362 (defvar org-emphasis-alist) ; defined just below
4363 (defun org-set-emph-re (var val)
4364 "Set variable and compute the emphasis regular expression."
4365 (set var val)
4366 (when (and (boundp 'org-emphasis-alist)
4367 (boundp 'org-emphasis-regexp-components)
4368 org-emphasis-alist org-emphasis-regexp-components)
4369 (let* ((e org-emphasis-regexp-components)
4370 (pre (car e))
4371 (post (nth 1 e))
4372 (border (nth 2 e))
4373 (body (nth 3 e))
4374 (nl (nth 4 e))
4375 (body1 (concat body "*?"))
4376 (markers (mapconcat 'car org-emphasis-alist ""))
4377 (vmarkers (mapconcat
4378 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4379 org-emphasis-alist "")))
4380 ;; make sure special characters appear at the right position in the class
4381 (if (string-match "\\^" markers)
4382 (setq markers (concat (replace-match "" t t markers) "^")))
4383 (if (string-match "-" markers)
4384 (setq markers (concat (replace-match "" t t markers) "-")))
4385 (if (string-match "\\^" vmarkers)
4386 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4387 (if (string-match "-" vmarkers)
4388 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4389 (if (> nl 0)
4390 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4391 (int-to-string nl) "\\}")))
4392 ;; Make the regexp
4393 (setq org-emph-re
4394 (concat "\\([" pre "]\\|^\\)"
4395 "\\("
4396 "\\([" markers "]\\)"
4397 "\\("
4398 "[^" border "]\\|"
4399 "[^" border "]"
4400 body1
4401 "[^" border "]"
4402 "\\)"
4403 "\\3\\)"
4404 "\\([" post "]\\|$\\)"))
4405 (setq org-verbatim-re
4406 (concat "\\([" pre "]\\|^\\)"
4407 "\\("
4408 "\\([" vmarkers "]\\)"
4409 "\\("
4410 "[^" border "]\\|"
4411 "[^" border "]"
4412 body1
4413 "[^" border "]"
4414 "\\)"
4415 "\\3\\)"
4416 "\\([" post "]\\|$\\)")))))
4418 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4419 ;; set this option proved cumbersome. See this message/thread:
4420 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4421 (defvar org-emphasis-regexp-components
4422 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4423 "Components used to build the regular expression for emphasis.
4424 This is a list with five entries. Terminology: In an emphasis string
4425 like \" *strong word* \", we call the initial space PREMATCH, the final
4426 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4427 and \"trong wor\" is the body. The different components in this variable
4428 specify what is allowed/forbidden in each part:
4430 pre Chars allowed as prematch. Beginning of line will be allowed too.
4431 post Chars allowed as postmatch. End of line will be allowed too.
4432 border The chars *forbidden* as border characters.
4433 body-regexp A regexp like \".\" to match a body character. Don't use
4434 non-shy groups here, and don't allow newline here.
4435 newline The maximum number of newlines allowed in an emphasis exp.
4437 You need to reload Org or to restart Emacs after customizing this.")
4439 (defcustom org-emphasis-alist
4440 '(("*" bold)
4441 ("/" italic)
4442 ("_" underline)
4443 ("=" org-verbatim verbatim)
4444 ("~" org-code verbatim)
4445 ("+" (:strike-through t)))
4446 "Alist of characters and faces to emphasize text.
4447 Text starting and ending with a special character will be emphasized,
4448 for example *bold*, _underlined_ and /italic/. This variable sets the
4449 marker characters and the face to be used by font-lock for highlighting
4450 in Org-mode Emacs buffers.
4452 You need to reload Org or to restart Emacs after customizing this."
4453 :group 'org-appearance
4454 :set 'org-set-emph-re
4455 :version "24.4"
4456 :package-version '(Org . "8.0")
4457 :type '(repeat
4458 (list
4459 (string :tag "Marker character")
4460 (choice
4461 (face :tag "Font-lock-face")
4462 (plist :tag "Face property list"))
4463 (option (const verbatim)))))
4465 (defvar org-protecting-blocks '("src" "example" "export")
4466 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4467 This is needed for font-lock setup.")
4469 ;;; Functions and variables from their packages
4470 ;; Declared here to avoid compiler warnings
4471 (defvar mark-active)
4473 ;; Various packages
4474 (declare-function calc-eval "calc" (str &optional separator &rest args))
4475 (declare-function calendar-forward-day "cal-move" (arg))
4476 (declare-function calendar-goto-date "cal-move" (date))
4477 (declare-function calendar-goto-today "cal-move" ())
4478 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4479 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4480 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4481 (declare-function cdlatex-tab "ext:cdlatex" ())
4482 (declare-function dired-get-filename
4483 "dired"
4484 (&optional localp no-error-if-not-filep))
4485 (declare-function iswitchb-read-buffer
4486 "iswitchb"
4487 (prompt &optional
4488 default require-match _predicate start matches-set))
4489 (declare-function org-agenda-change-all-lines
4490 "org-agenda"
4491 (newhead hdmarker &optional fixface just-this))
4492 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4493 "org-agenda"
4494 (&optional end))
4495 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4496 (declare-function org-agenda-format-item
4497 "org-agenda"
4498 (extra txt &optional level category tags dotime
4499 remove-re habitp))
4500 (declare-function org-agenda-maybe-redo "org-agenda" ())
4501 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4502 (declare-function org-agenda-save-markers-for-cut-and-paste
4503 "org-agenda"
4504 (beg end))
4505 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4506 (declare-function org-agenda-skip "org-agenda" ())
4507 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4508 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4509 (declare-function org-indent-mode "org-indent" (&optional arg))
4510 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4511 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4512 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4513 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4514 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4515 (declare-function parse-time-string "parse-time" (string))
4516 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4517 (declare-function table--at-cell-p
4518 "table"
4519 (position &optional object at-column))
4521 (defvar align-mode-rules-list)
4522 (defvar calc-embedded-close-formula)
4523 (defvar calc-embedded-open-formula)
4524 (defvar calc-embedded-open-mode)
4525 (defvar font-lock-unfontify-region-function)
4526 (defvar iswitchb-temp-buflist)
4527 (defvar org-agenda-tags-todo-honor-ignore-options)
4528 (defvar remember-data-file)
4529 (defvar texmathp-why)
4531 ;;;###autoload
4532 (defun turn-on-orgtbl ()
4533 "Unconditionally turn on `orgtbl-mode'."
4534 (require 'org-table)
4535 (orgtbl-mode 1))
4537 (defun org-at-table-p (&optional table-type)
4538 "Non-nil if the cursor is inside an Org table.
4539 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4540 If `org-enable-table-editor' is nil, return nil unconditionally."
4541 (and
4542 org-enable-table-editor
4543 (save-excursion
4544 (beginning-of-line)
4545 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4546 (or (not (derived-mode-p 'org-mode))
4547 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4548 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4550 (defun org-at-table.el-p ()
4551 "Non-nil when point is at a table.el table."
4552 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4553 (let ((element (org-element-at-point)))
4554 (and (eq (org-element-type element) 'table)
4555 (eq (org-element-property :type element) 'table.el)))))
4557 (defun org-table-recognize-table.el ()
4558 "If there is a table.el table nearby, recognize it and move into it."
4559 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4560 (beginning-of-line)
4561 (unless (or (looking-at org-table-dataline-regexp)
4562 (not (looking-at org-table1-hline-regexp)))
4563 (forward-line)
4564 (when (looking-at org-table-any-border-regexp)
4565 (forward-line -2)))
4566 (if (re-search-forward "|" (org-table-end t) t)
4567 (progn
4568 (require 'table)
4569 (if (table--at-cell-p (point)) t
4570 (message "recognizing table.el table...")
4571 (table-recognize-table)
4572 (message "recognizing table.el table...done")))
4573 (error "This should not happen"))))
4574 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4575 (make-obsolete 'org-table-recognize-table.el
4576 "please notify the org mailing list if you use this function."
4577 "Org 9.0")
4579 (defun org-at-table-hline-p ()
4580 "Non-nil when point is inside a hline in a table.
4581 Assume point is already in a table. If `org-enable-table-editor'
4582 is nil, return nil unconditionally."
4583 (and org-enable-table-editor
4584 (save-excursion
4585 (beginning-of-line)
4586 (looking-at org-table-hline-regexp))))
4588 (defun org-table-map-tables (function &optional quietly)
4589 "Apply FUNCTION to the start of all tables in the buffer."
4590 (save-excursion
4591 (save-restriction
4592 (widen)
4593 (goto-char (point-min))
4594 (while (re-search-forward org-table-any-line-regexp nil t)
4595 (unless quietly
4596 (message "Mapping tables: %d%%"
4597 (floor (* 100.0 (point)) (buffer-size))))
4598 (beginning-of-line 1)
4599 (when (and (looking-at org-table-line-regexp)
4600 ;; Exclude tables in src/example/verbatim/clocktable blocks
4601 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4602 (save-excursion (funcall function))
4603 (or (looking-at org-table-line-regexp)
4604 (forward-char 1)))
4605 (re-search-forward org-table-any-border-regexp nil 1))))
4606 (unless quietly (message "Mapping tables: done")))
4608 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4609 (declare-function org-clock-update-mode-line "org-clock" ())
4610 (declare-function org-resolve-clocks "org-clock"
4611 (&optional also-non-dangling-p prompt last-valid))
4613 (defun org-at-TBLFM-p (&optional pos)
4614 "Non-nil when point (or POS) is in #+TBLFM line."
4615 (save-excursion
4616 (goto-char (or pos (point)))
4617 (beginning-of-line)
4618 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4619 (eq (org-element-type (org-element-at-point)) 'table))))
4621 (defvar org-clock-start-time)
4622 (defvar org-clock-marker (make-marker)
4623 "Marker recording the last clock-in.")
4624 (defvar org-clock-hd-marker (make-marker)
4625 "Marker recording the last clock-in, but the headline position.")
4626 (defvar org-clock-heading ""
4627 "The heading of the current clock entry.")
4628 (defun org-clock-is-active ()
4629 "Return the buffer where the clock is currently running.
4630 Return nil if no clock is running."
4631 (marker-buffer org-clock-marker))
4633 (defun org-check-running-clock ()
4634 "Check if the current buffer contains the running clock.
4635 If yes, offer to stop it and to save the buffer with the changes."
4636 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4637 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4638 (buffer-name))))
4639 (org-clock-out)
4640 (when (y-or-n-p "Save changed buffer?")
4641 (save-buffer))))
4643 (defun org-clocktable-try-shift (dir n)
4644 "Check if this line starts a clock table, if yes, shift the time block."
4645 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4646 (org-clocktable-shift dir n)))
4648 ;;;###autoload
4649 (defun org-clock-persistence-insinuate ()
4650 "Set up hooks for clock persistence."
4651 (require 'org-clock)
4652 (add-hook 'org-mode-hook 'org-clock-load)
4653 (add-hook 'kill-emacs-hook 'org-clock-save))
4655 (defgroup org-archive nil
4656 "Options concerning archiving in Org-mode."
4657 :tag "Org Archive"
4658 :group 'org-structure)
4660 (defcustom org-archive-location "%s_archive::"
4661 "The location where subtrees should be archived.
4663 The value of this variable is a string, consisting of two parts,
4664 separated by a double-colon. The first part is a filename and
4665 the second part is a headline.
4667 When the filename is omitted, archiving happens in the same file.
4668 %s in the filename will be replaced by the current file
4669 name (without the directory part). Archiving to a different file
4670 is useful to keep archived entries from contributing to the
4671 Org-mode Agenda.
4673 The archived entries will be filed as subtrees of the specified
4674 headline. When the headline is omitted, the subtrees are simply
4675 filed away at the end of the file, as top-level entries. Also in
4676 the heading you can use %s to represent the file name, this can be
4677 useful when using the same archive for a number of different files.
4679 Here are a few examples:
4680 \"%s_archive::\"
4681 If the current file is Projects.org, archive in file
4682 Projects.org_archive, as top-level trees. This is the default.
4684 \"::* Archived Tasks\"
4685 Archive in the current file, under the top-level headline
4686 \"* Archived Tasks\".
4688 \"~/org/archive.org::\"
4689 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4691 \"~/org/archive.org::* From %s\"
4692 Archive in file ~/org/archive.org (absolute path), under headlines
4693 \"From FILENAME\" where file name is the current file name.
4695 \"~/org/datetree.org::datetree/* Finished Tasks\"
4696 The \"datetree/\" string is special, signifying to archive
4697 items to the datetree. Items are placed in either the CLOSED
4698 date of the item, or the current date if there is no CLOSED date.
4699 The heading will be a subentry to the current date. There doesn't
4700 need to be a heading, but there always needs to be a slash after
4701 datetree. For example, to store archived items directly in the
4702 datetree, use \"~/org/datetree.org::datetree/\".
4704 \"basement::** Finished Tasks\"
4705 Archive in file ./basement (relative path), as level 3 trees
4706 below the level 2 heading \"** Finished Tasks\".
4708 You may set this option on a per-file basis by adding to the buffer a
4709 line like
4711 #+ARCHIVE: basement::** Finished Tasks
4713 You may also define it locally for a subtree by setting an ARCHIVE property
4714 in the entry. If such a property is found in an entry, or anywhere up
4715 the hierarchy, it will be used."
4716 :group 'org-archive
4717 :type 'string)
4719 (defcustom org-agenda-skip-archived-trees t
4720 "Non-nil means the agenda will skip any items located in archived trees.
4721 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4722 variable is no longer recommended, you should leave it at the value t.
4723 Instead, use the key `v' to cycle the archives-mode in the agenda."
4724 :group 'org-archive
4725 :group 'org-agenda-skip
4726 :type 'boolean)
4728 (defcustom org-columns-skip-archived-trees t
4729 "Non-nil means ignore archived trees when creating column view."
4730 :group 'org-archive
4731 :group 'org-properties
4732 :type 'boolean)
4734 (defcustom org-cycle-open-archived-trees nil
4735 "Non-nil means `org-cycle' will open archived trees.
4736 An archived tree is a tree marked with the tag ARCHIVE.
4737 When nil, archived trees will stay folded. You can still open them with
4738 normal outline commands like `show-all', but not with the cycling commands."
4739 :group 'org-archive
4740 :group 'org-cycle
4741 :type 'boolean)
4743 (defcustom org-sparse-tree-open-archived-trees nil
4744 "Non-nil means sparse tree construction shows matches in archived trees.
4745 When nil, matches in these trees are highlighted, but the trees are kept in
4746 collapsed state."
4747 :group 'org-archive
4748 :group 'org-sparse-trees
4749 :type 'boolean)
4751 (defcustom org-sparse-tree-default-date-type nil
4752 "The default date type when building a sparse tree.
4753 When this is nil, a date is a scheduled or a deadline timestamp.
4754 Otherwise, these types are allowed:
4756 all: all timestamps
4757 active: only active timestamps (<...>)
4758 inactive: only inactive timestamps ([...])
4759 scheduled: only scheduled timestamps
4760 deadline: only deadline timestamps"
4761 :type '(choice (const :tag "Scheduled or deadline" nil)
4762 (const :tag "All timestamps" all)
4763 (const :tag "Only active timestamps" active)
4764 (const :tag "Only inactive timestamps" inactive)
4765 (const :tag "Only scheduled timestamps" scheduled)
4766 (const :tag "Only deadline timestamps" deadline)
4767 (const :tag "Only closed timestamps" closed))
4768 :version "25.1"
4769 :package-version '(Org . "8.3")
4770 :group 'org-sparse-trees)
4772 (defun org-cycle-hide-archived-subtrees (state)
4773 "Re-hide all archived subtrees after a visibility state change."
4774 (when (and (not org-cycle-open-archived-trees)
4775 (not (memq state '(overview folded))))
4776 (save-excursion
4777 (let* ((globalp (memq state '(contents all)))
4778 (beg (if globalp (point-min) (point)))
4779 (end (if globalp (point-max) (org-end-of-subtree t))))
4780 (org-hide-archived-subtrees beg end)
4781 (goto-char beg)
4782 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4783 (message "%s" (substitute-command-keys
4784 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4786 (defun org-force-cycle-archived ()
4787 "Cycle subtree even if it is archived."
4788 (interactive)
4789 (setq this-command 'org-cycle)
4790 (let ((org-cycle-open-archived-trees t))
4791 (call-interactively 'org-cycle)))
4793 (defun org-hide-archived-subtrees (beg end)
4794 "Re-hide all archived subtrees after a visibility state change."
4795 (org-with-wide-buffer
4796 (let ((case-fold-search nil)
4797 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4798 (goto-char beg)
4799 ;; Include headline point is currently on.
4800 (beginning-of-line)
4801 (while (and (< (point) end) (re-search-forward re end t))
4802 (when (member org-archive-tag (org-get-tags))
4803 (org-flag-subtree t)
4804 (org-end-of-subtree t))))))
4806 (declare-function outline-end-of-heading "outline" ())
4807 (declare-function outline-flag-region "outline" (from to flag))
4808 (defun org-flag-subtree (flag)
4809 (save-excursion
4810 (org-back-to-heading t)
4811 (outline-end-of-heading)
4812 (outline-flag-region (point)
4813 (progn (org-end-of-subtree t) (point))
4814 flag)))
4816 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4818 ;; Declare Column View Code
4820 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4821 (declare-function org-columns-compute "org-colview" (property))
4823 ;; Declare ID code
4825 (declare-function org-id-store-link "org-id")
4826 (declare-function org-id-locations-load "org-id")
4827 (declare-function org-id-locations-save "org-id")
4828 (defvar org-id-track-globally)
4830 ;;; Variables for pre-computed regular expressions, all buffer local
4832 (defvar-local org-todo-regexp nil
4833 "Matches any of the TODO state keywords.")
4834 (defvar-local org-not-done-regexp nil
4835 "Matches any of the TODO state keywords except the last one.")
4836 (defvar-local org-not-done-heading-regexp nil
4837 "Matches a TODO headline that is not done.")
4838 (defvar-local org-todo-line-regexp nil
4839 "Matches a headline and puts TODO state into group 2 if present.")
4840 (defvar-local org-complex-heading-regexp nil
4841 "Matches a headline and puts everything into groups:
4842 group 1: the stars
4843 group 2: The todo keyword, maybe
4844 group 3: Priority cookie
4845 group 4: True headline
4846 group 5: Tags")
4847 (defvar-local org-complex-heading-regexp-format nil
4848 "Printf format to make regexp to match an exact headline.
4849 This regexp will match the headline of any node which has the
4850 exact headline text that is put into the format, but may have any
4851 TODO state, priority and tags.")
4852 (defvar-local org-todo-line-tags-regexp nil
4853 "Matches a headline and puts TODO state into group 2 if present.
4854 Also put tags into group 4 if tags are present.")
4856 (defconst org-plain-time-of-day-regexp
4857 (concat
4858 "\\(\\<[012]?[0-9]"
4859 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4860 "\\(--?"
4861 "\\(\\<[012]?[0-9]"
4862 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4863 "\\)?")
4864 "Regular expression to match a plain time or time range.
4865 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4866 groups carry important information:
4867 0 the full match
4868 1 the first time, range or not
4869 8 the second time, if it is a range.")
4871 (defconst org-plain-time-extension-regexp
4872 (concat
4873 "\\(\\<[012]?[0-9]"
4874 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4875 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4876 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4877 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4878 groups carry important information:
4879 0 the full match
4880 7 hours of duration
4881 9 minutes of duration")
4883 (defconst org-stamp-time-of-day-regexp
4884 (concat
4885 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4886 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4887 "\\(--?"
4888 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4889 "Regular expression to match a timestamp time or time range.
4890 After a match, the following groups carry important information:
4891 0 the full match
4892 1 date plus weekday, for back referencing to make sure both times are on the same day
4893 2 the first time, range or not
4894 4 the second time, if it is a range.")
4896 (defconst org-startup-options
4897 '(("fold" org-startup-folded t)
4898 ("overview" org-startup-folded t)
4899 ("nofold" org-startup-folded nil)
4900 ("showall" org-startup-folded nil)
4901 ("showeverything" org-startup-folded showeverything)
4902 ("content" org-startup-folded content)
4903 ("indent" org-startup-indented t)
4904 ("noindent" org-startup-indented nil)
4905 ("hidestars" org-hide-leading-stars t)
4906 ("showstars" org-hide-leading-stars nil)
4907 ("odd" org-odd-levels-only t)
4908 ("oddeven" org-odd-levels-only nil)
4909 ("align" org-startup-align-all-tables t)
4910 ("noalign" org-startup-align-all-tables nil)
4911 ("inlineimages" org-startup-with-inline-images t)
4912 ("noinlineimages" org-startup-with-inline-images nil)
4913 ("latexpreview" org-startup-with-latex-preview t)
4914 ("nolatexpreview" org-startup-with-latex-preview nil)
4915 ("customtime" org-display-custom-times t)
4916 ("logdone" org-log-done time)
4917 ("lognotedone" org-log-done note)
4918 ("nologdone" org-log-done nil)
4919 ("lognoteclock-out" org-log-note-clock-out t)
4920 ("nolognoteclock-out" org-log-note-clock-out nil)
4921 ("logrepeat" org-log-repeat state)
4922 ("lognoterepeat" org-log-repeat note)
4923 ("logdrawer" org-log-into-drawer t)
4924 ("nologdrawer" org-log-into-drawer nil)
4925 ("logstatesreversed" org-log-states-order-reversed t)
4926 ("nologstatesreversed" org-log-states-order-reversed nil)
4927 ("nologrepeat" org-log-repeat nil)
4928 ("logreschedule" org-log-reschedule time)
4929 ("lognotereschedule" org-log-reschedule note)
4930 ("nologreschedule" org-log-reschedule nil)
4931 ("logredeadline" org-log-redeadline time)
4932 ("lognoteredeadline" org-log-redeadline note)
4933 ("nologredeadline" org-log-redeadline nil)
4934 ("logrefile" org-log-refile time)
4935 ("lognoterefile" org-log-refile note)
4936 ("nologrefile" org-log-refile nil)
4937 ("fninline" org-footnote-define-inline t)
4938 ("nofninline" org-footnote-define-inline nil)
4939 ("fnlocal" org-footnote-section nil)
4940 ("fnauto" org-footnote-auto-label t)
4941 ("fnprompt" org-footnote-auto-label nil)
4942 ("fnconfirm" org-footnote-auto-label confirm)
4943 ("fnplain" org-footnote-auto-label plain)
4944 ("fnadjust" org-footnote-auto-adjust t)
4945 ("nofnadjust" org-footnote-auto-adjust nil)
4946 ("constcgs" constants-unit-system cgs)
4947 ("constSI" constants-unit-system SI)
4948 ("noptag" org-tag-persistent-alist nil)
4949 ("hideblocks" org-hide-block-startup t)
4950 ("nohideblocks" org-hide-block-startup nil)
4951 ("beamer" org-startup-with-beamer-mode t)
4952 ("entitiespretty" org-pretty-entities t)
4953 ("entitiesplain" org-pretty-entities nil))
4954 "Variable associated with STARTUP options for org-mode.
4955 Each element is a list of three items: the startup options (as written
4956 in the #+STARTUP line), the corresponding variable, and the value to set
4957 this variable to if the option is found. An optional forth element PUSH
4958 means to push this value onto the list in the variable.")
4960 (defcustom org-group-tags t
4961 "When non-nil (the default), use group tags.
4962 This can be turned on/off through `org-toggle-tags-groups'."
4963 :group 'org-tags
4964 :group 'org-startup
4965 :type 'boolean)
4967 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4969 (defun org-toggle-tags-groups ()
4970 "Toggle support for group tags.
4971 Support for group tags is controlled by the option
4972 `org-group-tags', which is non-nil by default."
4973 (interactive)
4974 (setq org-group-tags (not org-group-tags))
4975 (cond ((and (derived-mode-p 'org-agenda-mode)
4976 org-group-tags)
4977 (org-agenda-redo))
4978 ((derived-mode-p 'org-mode)
4979 (let ((org-inhibit-startup t)) (org-mode))))
4980 (message "Groups tags support has been turned %s"
4981 (if org-group-tags "on" "off")))
4983 (defun org-set-regexps-and-options (&optional tags-only)
4984 "Precompute regular expressions used in the current buffer.
4985 When optional argument TAGS-ONLY is non-nil, only compute tags
4986 related expressions."
4987 (when (derived-mode-p 'org-mode)
4988 (let ((alist (org--setup-collect-keywords
4989 (org-make-options-regexp
4990 (append '("FILETAGS" "TAGS" "SETUPFILE")
4991 (and (not tags-only)
4992 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4993 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4994 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4995 ;; Startup options. Get this early since it does change
4996 ;; behavior for other options (e.g., tags).
4997 (let ((startup (cdr (assq 'startup alist))))
4998 (dolist (option startup)
4999 (let ((entry (assoc-string option org-startup-options t)))
5000 (when entry
5001 (let ((var (nth 1 entry))
5002 (val (nth 2 entry)))
5003 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5004 (unless (listp (symbol-value var))
5005 (set (make-local-variable var) nil))
5006 (add-to-list var val)))))))
5007 (setq-local org-file-tags
5008 (mapcar #'org-add-prop-inherited
5009 (cdr (assq 'filetags alist))))
5010 (setq org-current-tag-alist
5011 (append org-tag-persistent-alist
5012 (let ((tags (cdr (assq 'tags alist))))
5013 (if tags (org-tag-string-to-alist tags)
5014 org-tag-alist))))
5015 (setq org-tag-groups-alist
5016 (org-tag-alist-to-groups org-current-tag-alist))
5017 (unless tags-only
5018 ;; File properties.
5019 (setq-local org-file-properties (cdr (assq 'property alist)))
5020 ;; Archive location.
5021 (let ((archive (cdr (assq 'archive alist))))
5022 (when archive (setq-local org-archive-location archive)))
5023 ;; Category.
5024 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5025 (when cat
5026 (setq-local org-category (intern cat))
5027 (setq-local org-file-properties
5028 (org--update-property-plist
5029 "CATEGORY" cat org-file-properties))))
5030 ;; Columns.
5031 (let ((column (cdr (assq 'columns alist))))
5032 (when column (setq-local org-columns-default-format column)))
5033 ;; Constants.
5034 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5035 ;; Link abbreviations.
5036 (let ((links (cdr (assq 'link alist))))
5037 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5038 ;; Priorities.
5039 (let ((priorities (cdr (assq 'priorities alist))))
5040 (when priorities
5041 (setq-local org-highest-priority (nth 0 priorities))
5042 (setq-local org-lowest-priority (nth 1 priorities))
5043 (setq-local org-default-priority (nth 2 priorities))))
5044 ;; Scripts.
5045 (let ((scripts (assq 'scripts alist)))
5046 (when scripts
5047 (setq-local org-use-sub-superscripts (cdr scripts))))
5048 ;; TODO keywords.
5049 (setq-local org-todo-kwd-alist nil)
5050 (setq-local org-todo-key-alist nil)
5051 (setq-local org-todo-key-trigger nil)
5052 (setq-local org-todo-keywords-1 nil)
5053 (setq-local org-done-keywords nil)
5054 (setq-local org-todo-heads nil)
5055 (setq-local org-todo-sets nil)
5056 (setq-local org-todo-log-states nil)
5057 (let ((todo-sequences
5058 (or (nreverse (cdr (assq 'todo alist)))
5059 (let ((d (default-value 'org-todo-keywords)))
5060 (if (not (stringp (car d))) d
5061 ;; XXX: Backward compatibility code.
5062 (list (cons org-todo-interpretation d)))))))
5063 (dolist (sequence todo-sequences)
5064 (let* ((sequence (or (run-hook-with-args-until-success
5065 'org-todo-setup-filter-hook sequence)
5066 sequence))
5067 (sequence-type (car sequence))
5068 (keywords (cdr sequence))
5069 (sep (member "|" keywords))
5070 names alist)
5071 (dolist (k (remove "|" keywords))
5072 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5074 (error "Invalid TODO keyword %s" k))
5075 (let ((name (match-string 1 k))
5076 (key (match-string 2 k))
5077 (log (org-extract-log-state-settings k)))
5078 (push name names)
5079 (push (cons name (and key (string-to-char key))) alist)
5080 (when log (push log org-todo-log-states))))
5081 (let* ((names (nreverse names))
5082 (done (if sep (org-remove-keyword-keys (cdr sep))
5083 (last names)))
5084 (head (car names))
5085 (tail (list sequence-type head (car done) (org-last done))))
5086 (add-to-list 'org-todo-heads head 'append)
5087 (push names org-todo-sets)
5088 (setq org-done-keywords (append org-done-keywords done nil))
5089 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5090 (setq org-todo-key-alist
5091 (append org-todo-key-alist
5092 (and alist
5093 (append '((:startgroup))
5094 (nreverse alist)
5095 '((:endgroup))))))
5096 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5097 (setq org-todo-sets (nreverse org-todo-sets)
5098 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5099 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5100 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5101 ;; Compute the regular expressions and other local variables.
5102 ;; Using `org-outline-regexp-bol' would complicate them much,
5103 ;; because of the fixed white space at the end of that string.
5104 (unless org-done-keywords
5105 (setq org-done-keywords
5106 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5107 (setq org-not-done-keywords
5108 (org-delete-all org-done-keywords
5109 (copy-sequence org-todo-keywords-1))
5110 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5111 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5112 org-not-done-heading-regexp
5113 (format org-heading-keyword-regexp-format org-not-done-regexp)
5114 org-todo-line-regexp
5115 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5116 org-complex-heading-regexp
5117 (concat "^\\(\\*+\\)"
5118 "\\(?: +" org-todo-regexp "\\)?"
5119 "\\(?: +\\(\\[#.\\]\\)\\)?"
5120 "\\(?: +\\(.*?\\)\\)??"
5121 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5122 "[ \t]*$")
5123 org-complex-heading-regexp-format
5124 (concat "^\\(\\*+\\)"
5125 "\\(?: +" org-todo-regexp "\\)?"
5126 "\\(?: +\\(\\[#.\\]\\)\\)?"
5127 "\\(?: +"
5128 ;; Stats cookies can be stuck to body.
5129 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5130 "\\(%s\\)"
5131 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5132 "\\)"
5133 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5134 "[ \t]*$")
5135 org-todo-line-tags-regexp
5136 (concat "^\\(\\*+\\)"
5137 "\\(?: +" org-todo-regexp "\\)?"
5138 "\\(?: +\\(.*?\\)\\)??"
5139 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5140 "[ \t]*$"))
5141 (org-compute-latex-and-related-regexp)))))
5143 (defun org--setup-collect-keywords (regexp &optional files alist)
5144 "Return setup keywords values as an alist.
5146 REGEXP matches a subset of setup keywords. FILES is a list of
5147 file names already visited. It is used to avoid circular setup
5148 files. ALIST, when non-nil, is the alist computed so far.
5150 Return value contains the following keys: `archive', `category',
5151 `columns', `constants', `filetags', `link', `priorities',
5152 `property', `scripts', `startup', `tags' and `todo'."
5153 (org-with-wide-buffer
5154 (goto-char (point-min))
5155 (let ((case-fold-search t))
5156 (while (re-search-forward regexp nil t)
5157 (let ((element (org-element-at-point)))
5158 (when (eq (org-element-type element) 'keyword)
5159 (let ((key (org-element-property :key element))
5160 (value (org-element-property :value element)))
5161 (cond
5162 ((equal key "ARCHIVE")
5163 (when (org-string-nw-p value)
5164 (push (cons 'archive value) alist)))
5165 ((equal key "CATEGORY") (push (cons 'category value) alist))
5166 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5167 ((equal key "CONSTANTS")
5168 (let* ((constants (assq 'constants alist))
5169 (store (cdr constants)))
5170 (dolist (pair (org-split-string value))
5171 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5172 pair)
5173 (let* ((name (match-string 1 pair))
5174 (value (match-string 2 pair))
5175 (old (assoc name store)))
5176 (if old (setcdr old value)
5177 (push (cons name value) store)))))
5178 (if constants (setcdr constants store)
5179 (push (cons 'constants store) alist))))
5180 ((equal key "FILETAGS")
5181 (when (org-string-nw-p value)
5182 (let ((old (assq 'filetags alist))
5183 (new (apply #'nconc
5184 (mapcar (lambda (x) (org-split-string x ":"))
5185 (org-split-string value)))))
5186 (if old (setcdr old (append new (cdr old)))
5187 (push (cons 'filetags new) alist)))))
5188 ((equal key "LINK")
5189 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5190 (let ((links (assq 'link alist))
5191 (pair (cons (match-string-no-properties 1 value)
5192 (match-string-no-properties 2 value))))
5193 (if links (push pair (cdr links))
5194 (push (list 'link pair) alist)))))
5195 ((equal key "OPTIONS")
5196 (when (and (org-string-nw-p value)
5197 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5198 (push (cons 'scripts (read (match-string 1 value))) alist)))
5199 ((equal key "PRIORITIES")
5200 (push (cons 'priorities
5201 (let ((prio (org-split-string value)))
5202 (if (< (length prio) 3) '(?A ?C ?B)
5203 (mapcar #'string-to-char prio))))
5204 alist))
5205 ((equal key "PROPERTY")
5206 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5207 (let* ((property (assq 'property alist))
5208 (value (org--update-property-plist
5209 (match-string-no-properties 1 value)
5210 (match-string-no-properties 2 value)
5211 (cdr property))))
5212 (if property (setcdr property value)
5213 (push (cons 'property value) alist)))))
5214 ((equal key "STARTUP")
5215 (let ((startup (assq 'startup alist)))
5216 (if startup
5217 (setcdr startup
5218 (append (cdr startup) (org-split-string value)))
5219 (push (cons 'startup (org-split-string value)) alist))))
5220 ((equal key "TAGS")
5221 (let ((tag-cell (assq 'tags alist)))
5222 (if tag-cell
5223 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5224 (push (cons 'tags value) alist))))
5225 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5226 (let ((todo (assq 'todo alist))
5227 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5228 (org-split-string value))))
5229 (if todo (push value (cdr todo))
5230 (push (list 'todo value) alist))))
5231 ((equal key "SETUPFILE")
5232 (unless buffer-read-only ; Do not check in Gnus messages.
5233 (let ((f (and (org-string-nw-p value)
5234 (expand-file-name
5235 (org-remove-double-quotes value)))))
5236 (when (and f (file-readable-p f) (not (member f files)))
5237 (with-temp-buffer
5238 (setq default-directory (file-name-directory f))
5239 (insert-file-contents f)
5240 (setq alist
5241 ;; Fake Org mode to benefit from cache
5242 ;; without recurring needlessly.
5243 (let ((major-mode 'org-mode))
5244 (org--setup-collect-keywords
5245 regexp (cons f files) alist)))))))))))))))
5246 alist)
5248 (defun org-tag-string-to-alist (s)
5249 "Return tag alist associated to string S.
5250 S is a value for TAGS keyword or produced with
5251 `org-tag-alist-to-string'. Return value is an alist suitable for
5252 `org-tag-alist' or `org-tag-persistent-alist'."
5253 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5254 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5255 "\\|{.+?}\\)" ; regular expression
5256 "\\(?:(\\(.\\))\\)?\\'"))
5257 alist group-flag)
5258 (dolist (tokens lines (cdr (nreverse alist)))
5259 (push '(:newline) alist)
5260 (while tokens
5261 (let ((token (pop tokens)))
5262 (pcase token
5263 ("{"
5264 (push '(:startgroup) alist)
5265 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5266 ("}"
5267 (push '(:endgroup) alist)
5268 (setq group-flag nil))
5269 ("["
5270 (push '(:startgrouptag) alist)
5271 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5272 ("]"
5273 (push '(:endgrouptag) alist)
5274 (setq group-flag nil))
5275 (":"
5276 (push '(:grouptags) alist))
5277 ((guard (string-match tag-re token))
5278 (let ((tag (match-string 1 token))
5279 (key (and (match-beginning 2)
5280 (string-to-char (match-string 2 token)))))
5281 ;; Push all tags in groups, no matter if they already
5282 ;; appear somewhere else in the list.
5283 (when (or group-flag (not (assoc tag alist)))
5284 (push (cons tag key) alist))))))))))
5286 (defun org-tag-alist-to-string (alist &optional skip-key)
5287 "Return tag string associated to ALIST.
5289 ALIST is an alist, as defined in `org-tag-alist' or
5290 `org-tag-persistent-alist', or produced with
5291 `org-tag-string-to-alist'.
5293 Return value is a string suitable as a value for \"TAGS\"
5294 keyword.
5296 When optional argument SKIP-KEY is non-nil, skip selection keys
5297 next to tags."
5298 (mapconcat (lambda (token)
5299 (pcase token
5300 (`(:startgroup) "{")
5301 (`(:endgroup) "}")
5302 (`(:startgrouptag) "[")
5303 (`(:endgrouptag) "]")
5304 (`(:grouptags) ":")
5305 (`(:newline) "\\n")
5306 ((and
5307 (guard (not skip-key))
5308 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5309 (format "%s(%c)" tag key))
5310 (`(,(and tag (pred stringp)) . ,_) tag)
5311 (_ (user-error "Invalid tag token: %S" token))))
5312 alist
5313 " "))
5315 (defun org-tag-alist-to-groups (alist)
5316 "Return group alist from tag ALIST.
5317 ALIST is an alist, as defined in `org-tag-alist' or
5318 `org-tag-persistent-alist', or produced with
5319 `org-tag-string-to-alist'. Return value is an alist following
5320 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5321 a string, summarizing TAGS, as a list of strings."
5322 (let (groups group-status current-group)
5323 (dolist (token alist (nreverse groups))
5324 (pcase token
5325 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5326 (`(,(or :endgroup :endgrouptag))
5327 (when (eq group-status 'append)
5328 (push (nreverse current-group) groups))
5329 (setq group-status nil))
5330 (`(:grouptags) (setq group-status 'append))
5331 ((and `(,tag . ,_) (guard group-status))
5332 (if (eq group-status 'append) (push tag current-group)
5333 (setq current-group (list tag))))
5334 (_ nil)))))
5336 (defun org-file-contents (file &optional noerror)
5337 "Return the contents of FILE, as a string."
5338 (if (and file (file-readable-p file))
5339 (with-temp-buffer
5340 (insert-file-contents file)
5341 (buffer-string))
5342 (funcall (if noerror 'message 'error)
5343 "Cannot read file \"%s\"%s"
5344 file
5345 (let ((from (buffer-file-name (buffer-base-buffer))))
5346 (if from (concat " (referenced in file \"" from "\")") "")))))
5348 (defun org-extract-log-state-settings (x)
5349 "Extract the log state setting from a TODO keyword string.
5350 This will extract info from a string like \"WAIT(w@/!)\"."
5351 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5352 (let ((kw (match-string 1 x))
5353 (log1 (and (match-end 3) (match-string 3 x)))
5354 (log2 (and (match-end 4) (match-string 4 x))))
5355 (and (or log1 log2)
5356 (list kw
5357 (and log1 (if (equal log1 "!") 'time 'note))
5358 (and log2 (if (equal log2 "!") 'time 'note)))))))
5360 (defun org-remove-keyword-keys (list)
5361 "Remove a pair of parenthesis at the end of each string in LIST."
5362 (mapcar (lambda (x)
5363 (if (string-match "(.*)$" x)
5364 (substring x 0 (match-beginning 0))
5366 list))
5368 (defun org-assign-fast-keys (alist)
5369 "Assign fast keys to a keyword-key alist.
5370 Respect keys that are already there."
5371 (let (new e (alt ?0))
5372 (while (setq e (pop alist))
5373 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5374 (cdr e)) ;; Key already assigned.
5375 (push e new)
5376 (let ((clist (string-to-list (downcase (car e))))
5377 (used (append new alist)))
5378 (when (= (car clist) ?@)
5379 (pop clist))
5380 (while (and clist (rassoc (car clist) used))
5381 (pop clist))
5382 (unless clist
5383 (while (rassoc alt used)
5384 (cl-incf alt)))
5385 (push (cons (car e) (or (car clist) alt)) new))))
5386 (nreverse new)))
5388 ;;; Some variables used in various places
5390 (defvar org-window-configuration nil
5391 "Used in various places to store a window configuration.")
5392 (defvar org-selected-window nil
5393 "Used in various places to store a window configuration.")
5394 (defvar org-finish-function nil
5395 "Function to be called when `C-c C-c' is used.
5396 This is for getting out of special buffers like capture.")
5397 (defvar org-last-state)
5399 ;; Defined somewhere in this file, but used before definition.
5400 (defvar org-entities) ;; defined in org-entities.el
5401 (defvar org-struct-menu)
5402 (defvar org-org-menu)
5403 (defvar org-tbl-menu)
5405 ;;;; Define the Org-mode
5407 ;; We use a before-change function to check if a table might need
5408 ;; an update.
5409 (defvar org-table-may-need-update t
5410 "Indicates that a table might need an update.
5411 This variable is set by `org-before-change-function'.
5412 `org-table-align' sets it back to nil.")
5413 (defun org-before-change-function (_beg _end)
5414 "Every change indicates that a table might need an update."
5415 (setq org-table-may-need-update t))
5416 (defvar org-mode-map)
5417 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5418 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5419 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5420 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5421 (defvar org-table-buffer-is-an nil)
5423 (defvar bidi-paragraph-direction)
5424 (defvar buffer-face-mode-face)
5426 (require 'outline)
5428 ;; Other stuff we need.
5429 (require 'time-date)
5430 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5431 (require 'easymenu)
5432 (autoload 'easy-menu-add "easymenu")
5433 (require 'overlay)
5435 ;; (require 'org-macs) moved higher up in the file before it is first used
5436 (require 'org-entities)
5437 ;; (require 'org-compat) moved higher up in the file before it is first used
5438 (require 'org-faces)
5439 (require 'org-list)
5440 (require 'org-pcomplete)
5441 (require 'org-src)
5442 (require 'org-footnote)
5443 (require 'org-macro)
5445 ;; babel
5446 (require 'ob)
5448 ;;;###autoload
5449 (define-derived-mode org-mode outline-mode "Org"
5450 "Outline-based notes management and organizer, alias
5451 \"Carsten's outline-mode for keeping track of everything.\"
5453 Org-mode develops organizational tasks around a NOTES file which
5454 contains information about projects as plain text. Org-mode is
5455 implemented on top of outline-mode, which is ideal to keep the content
5456 of large files well structured. It supports ToDo items, deadlines and
5457 time stamps, which magically appear in the diary listing of the Emacs
5458 calendar. Tables are easily created with a built-in table editor.
5459 Plain text URL-like links connect to websites, emails (VM), Usenet
5460 messages (Gnus), BBDB entries, and any files related to the project.
5461 For printing and sharing of notes, an Org-mode file (or a part of it)
5462 can be exported as a structured ASCII or HTML file.
5464 The following commands are available:
5466 \\{org-mode-map}"
5468 ;; Get rid of Outline menus, they are not needed
5469 ;; Need to do this here because define-derived-mode sets up
5470 ;; the keymap so late. Still, it is a waste to call this each time
5471 ;; we switch another buffer into Org mode.
5472 (define-key org-mode-map [menu-bar headings] 'undefined)
5473 (define-key org-mode-map [menu-bar hide] 'undefined)
5474 (define-key org-mode-map [menu-bar show] 'undefined)
5476 (org-load-modules-maybe)
5477 (org-install-agenda-files-menu)
5478 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5479 (add-to-invisibility-spec '(org-cwidth))
5480 (add-to-invisibility-spec '(org-hide-block . t))
5481 (setq-local outline-regexp org-outline-regexp)
5482 (setq-local outline-level 'org-outline-level)
5483 (setq bidi-paragraph-direction 'left-to-right)
5484 (when (and org-ellipsis
5485 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5486 (fboundp 'make-glyph-code))
5487 (unless org-display-table
5488 (setq org-display-table (make-display-table)))
5489 (set-display-table-slot
5490 org-display-table 4
5491 (vconcat (mapcar
5492 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5493 org-ellipsis)))
5494 (if (stringp org-ellipsis) org-ellipsis "..."))))
5495 (setq buffer-display-table org-display-table))
5496 (org-set-regexps-and-options)
5497 (org-set-font-lock-defaults)
5498 (when (and org-tag-faces (not org-tags-special-faces-re))
5499 ;; tag faces set outside customize.... force initialization.
5500 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5501 ;; Calc embedded
5502 (setq-local calc-embedded-open-mode "# ")
5503 ;; Modify a few syntax entries
5504 (modify-syntax-entry ?@ "w")
5505 (modify-syntax-entry ?\" "\"")
5506 (modify-syntax-entry ?\\ "_")
5507 (modify-syntax-entry ?~ "_")
5508 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5509 ;; Activate before-change-function
5510 (setq-local org-table-may-need-update t)
5511 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5512 ;; Check for running clock before killing a buffer
5513 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5514 ;; Initialize macros templates.
5515 (org-macro-initialize-templates)
5516 ;; Initialize radio targets.
5517 (org-update-radio-target-regexp)
5518 ;; Indentation.
5519 (setq-local indent-line-function 'org-indent-line)
5520 (setq-local indent-region-function 'org-indent-region)
5521 ;; Filling and auto-filling.
5522 (org-setup-filling)
5523 ;; Comments.
5524 (org-setup-comments-handling)
5525 ;; Initialize cache.
5526 (org-element-cache-reset)
5527 ;; Beginning/end of defun
5528 (setq-local beginning-of-defun-function 'org-backward-element)
5529 (setq-local end-of-defun-function
5530 (lambda ()
5531 (if (not (org-at-heading-p))
5532 (org-forward-element)
5533 (org-forward-element)
5534 (forward-char -1))))
5535 ;; Next error for sparse trees
5536 (setq-local next-error-function 'org-occur-next-match)
5537 ;; Make sure dependence stuff works reliably, even for users who set it
5538 ;; too late :-(
5539 (if org-enforce-todo-dependencies
5540 (add-hook 'org-blocker-hook
5541 'org-block-todo-from-children-or-siblings-or-parent)
5542 (remove-hook 'org-blocker-hook
5543 'org-block-todo-from-children-or-siblings-or-parent))
5544 (if org-enforce-todo-checkbox-dependencies
5545 (add-hook 'org-blocker-hook
5546 'org-block-todo-from-checkboxes)
5547 (remove-hook 'org-blocker-hook
5548 'org-block-todo-from-checkboxes))
5550 ;; Align options lines
5551 (setq-local
5552 align-mode-rules-list
5553 '((org-in-buffer-settings
5554 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5555 (modes . '(org-mode)))))
5557 ;; Imenu
5558 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5560 ;; Make isearch reveal context
5561 (setq-local outline-isearch-open-invisible-function
5562 (lambda (&rest _) (org-show-context 'isearch)))
5564 ;; Setup the pcomplete hooks
5565 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5566 (setq-local pcomplete-command-name-function 'org-command-at-point)
5567 (setq-local pcomplete-default-completion-function 'ignore)
5568 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5569 (setq-local pcomplete-termination-string "")
5570 (setq-local buffer-face-mode-face 'org-default)
5572 ;; If empty file that did not turn on Org mode automatically, make
5573 ;; it to.
5574 (when (and org-insert-mode-line-in-empty-file
5575 (called-interactively-p 'any)
5576 (= (point-min) (point-max)))
5577 (insert "# -*- mode: org -*-\n\n"))
5578 (unless org-inhibit-startup
5579 (org-unmodified
5580 (when org-startup-with-beamer-mode (org-beamer-mode))
5581 (when org-startup-align-all-tables
5582 (org-table-map-tables #'org-table-align t))
5583 (when org-startup-with-inline-images (org-display-inline-images))
5584 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5585 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5586 (when org-startup-truncated (setq truncate-lines t))
5587 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5588 (org-refresh-effort-properties)))
5589 ;; Try to set `org-hide' face correctly.
5590 (let ((foreground (org-find-invisible-foreground)))
5591 (when foreground
5592 (set-face-foreground 'org-hide foreground))))
5594 ;; Update `customize-package-emacs-version-alist'
5595 (add-to-list 'customize-package-emacs-version-alist
5596 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5597 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5598 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5600 (defvar org-mode-transpose-word-syntax-table
5601 (let ((st (make-syntax-table text-mode-syntax-table)))
5602 (dolist (c org-emphasis-alist st)
5603 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5605 (when (fboundp 'abbrev-table-put)
5606 (abbrev-table-put org-mode-abbrev-table
5607 :parents (list text-mode-abbrev-table)))
5609 (defun org-find-invisible-foreground ()
5610 (let ((candidates (remove
5611 "unspecified-bg"
5612 (nconc
5613 (list (face-background 'default)
5614 (face-background 'org-default))
5615 (mapcar
5616 (lambda (alist)
5617 (when (boundp alist)
5618 (cdr (assoc 'background-color (symbol-value alist)))))
5619 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5620 (list (face-foreground 'org-hide))))))
5621 (car (remove nil candidates))))
5623 (defun org-current-time (&optional rounding-minutes past)
5624 "Current time, possibly rounded to ROUNDING-MINUTES.
5625 When ROUNDING-MINUTES is not an integer, fall back on the car of
5626 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5627 the rounding returns a past time."
5628 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5629 (car org-time-stamp-rounding-minutes)))
5630 (time (decode-time)) res)
5631 (if (< r 1)
5632 (current-time)
5633 (setq res
5634 (apply 'encode-time
5635 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5636 (nthcdr 2 time))))
5637 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5638 (seconds-to-time (- (float-time res) (* r 60)))
5639 res))))
5641 (defun org-today ()
5642 "Return today date, considering `org-extend-today-until'."
5643 (time-to-days
5644 (time-subtract (current-time)
5645 (list 0 (* 3600 org-extend-today-until) 0))))
5647 ;;;; Font-Lock stuff, including the activators
5649 (defvar org-mouse-map (make-sparse-keymap))
5650 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5651 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5652 (when org-mouse-1-follows-link
5653 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5654 (when org-tab-follows-link
5655 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5656 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5658 (require 'font-lock)
5660 (defconst org-non-link-chars "]\t\n\r<>")
5661 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5662 "file+sys" "news" "shell" "elisp" "doi" "message"
5663 "help"))
5664 (defvar org-link-types-re nil
5665 "Matches a link that has a url-like prefix like \"http:\"")
5666 (defvar org-link-re-with-space nil
5667 "Matches a link with spaces, optional angular brackets around it.")
5668 (defvar org-link-re-with-space2 nil
5669 "Matches a link with spaces, optional angular brackets around it.")
5670 (defvar org-link-re-with-space3 nil
5671 "Matches a link with spaces, only for internal part in bracket links.")
5672 (defvar org-angle-link-re nil
5673 "Matches link with angular brackets, spaces are allowed.")
5674 (defvar org-plain-link-re nil
5675 "Matches plain link, without spaces.")
5676 (defvar org-bracket-link-regexp nil
5677 "Matches a link in double brackets.")
5678 (defvar org-bracket-link-analytic-regexp nil
5679 "Regular expression used to analyze links.
5680 Here is what the match groups contain after a match:
5681 1: http:
5682 2: http
5683 3: path
5684 4: [desc]
5685 5: desc")
5686 (defvar org-bracket-link-analytic-regexp++ nil
5687 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5688 (defvar org-any-link-re nil
5689 "Regular expression matching any link.")
5691 (defconst org-match-sexp-depth 3
5692 "Number of stacked braces for sub/superscript matching.")
5694 (defun org-create-multibrace-regexp (left right n)
5695 "Create a regular expression which will match a balanced sexp.
5696 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5697 as single character strings.
5698 The regexp returned will match the entire expression including the
5699 delimiters. It will also define a single group which contains the
5700 match except for the outermost delimiters. The maximum depth of
5701 stacked delimiters is N. Escaping delimiters is not possible."
5702 (let* ((nothing (concat "[^" left right "]*?"))
5703 (or "\\|")
5704 (re nothing)
5705 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5706 (while (> n 1)
5707 (setq n (1- n)
5708 re (concat re or next)
5709 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5710 (concat left "\\(" re "\\)" right)))
5712 (defconst org-match-substring-regexp
5713 (concat
5714 "\\(\\S-\\)\\([_^]\\)\\("
5715 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5716 "\\|"
5717 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5718 "\\|"
5719 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5720 "The regular expression matching a sub- or superscript.")
5722 (defconst org-match-substring-with-braces-regexp
5723 (concat
5724 "\\(\\S-\\)\\([_^]\\)"
5725 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5726 "The regular expression matching a sub- or superscript, forcing braces.")
5728 (defun org-make-link-regexps ()
5729 "Update the link regular expressions.
5730 This should be called after the variable `org-link-types' has changed."
5731 (let ((types-re (regexp-opt org-link-types t)))
5732 (setq org-link-types-re
5733 (concat "\\`" types-re ":")
5734 org-link-re-with-space
5735 (concat "<?" types-re ":"
5736 "\\([^" org-non-link-chars " ]"
5737 "[^" org-non-link-chars "]*"
5738 "[^" org-non-link-chars " ]\\)>?")
5739 org-link-re-with-space2
5740 (concat "<?" types-re ":"
5741 "\\([^" org-non-link-chars " ]"
5742 "[^\t\n\r]*"
5743 "[^" org-non-link-chars " ]\\)>?")
5744 org-link-re-with-space3
5745 (concat "<?" types-re ":"
5746 "\\([^" org-non-link-chars " ]"
5747 "[^\t\n\r]*\\)")
5748 org-angle-link-re
5749 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5750 types-re)
5751 org-plain-link-re
5752 (concat
5753 "\\<" types-re ":"
5754 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5755 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5756 org-bracket-link-regexp
5757 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5758 org-bracket-link-analytic-regexp
5759 (concat
5760 "\\[\\["
5761 "\\(" types-re ":\\)?"
5762 "\\([^]]+\\)"
5763 "\\]"
5764 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5765 "\\]")
5766 org-bracket-link-analytic-regexp++
5767 (concat
5768 "\\[\\["
5769 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5770 "\\([^]]+\\)"
5771 "\\]"
5772 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5773 "\\]")
5774 org-any-link-re
5775 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5776 org-angle-link-re "\\)\\|\\("
5777 org-plain-link-re "\\)"))))
5779 (org-make-link-regexps)
5781 (defvar org-emph-face nil)
5783 (defun org-do-emphasis-faces (limit)
5784 "Run through the buffer and emphasize strings."
5785 (let (rtn a)
5786 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5787 (let* ((border (char-after (match-beginning 3)))
5788 (bre (regexp-quote (char-to-string border))))
5789 (when (and (not (= border (char-after (match-beginning 4))))
5790 (not (string-match-p (concat bre ".*" bre)
5791 (replace-regexp-in-string
5792 "\n" " "
5793 (substring (match-string 2) 1 -1)))))
5794 (setq rtn t)
5795 (setq a (assoc (match-string 3) org-emphasis-alist))
5796 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5797 'face
5798 (nth 1 a))
5799 (and (nth 2 a)
5800 (org-remove-flyspell-overlays-in
5801 (match-beginning 0) (match-end 0)))
5802 (add-text-properties (match-beginning 2) (match-end 2)
5803 '(font-lock-multiline t org-emphasis t))
5804 (when org-hide-emphasis-markers
5805 (add-text-properties (match-end 4) (match-beginning 5)
5806 '(invisible org-link))
5807 (add-text-properties (match-beginning 3) (match-end 3)
5808 '(invisible org-link)))))
5809 (goto-char (1+ (match-beginning 0))))
5810 rtn))
5812 (defun org-emphasize (&optional char)
5813 "Insert or change an emphasis, i.e. a font like bold or italic.
5814 If there is an active region, change that region to a new emphasis.
5815 If there is no region, just insert the marker characters and position
5816 the cursor between them.
5817 CHAR should be the marker character. If it is a space, it means to
5818 remove the emphasis of the selected region.
5819 If CHAR is not given (for example in an interactive call) it will be
5820 prompted for."
5821 (interactive)
5822 (let ((erc org-emphasis-regexp-components)
5823 (string "") beg end move s)
5824 (if (org-region-active-p)
5825 (setq beg (region-beginning)
5826 end (region-end)
5827 string (buffer-substring beg end))
5828 (setq move t))
5830 (unless char
5831 (message "Emphasis marker or tag: [%s]"
5832 (mapconcat #'car org-emphasis-alist ""))
5833 (setq char (read-char-exclusive)))
5834 (if (equal char ?\s)
5835 (setq s ""
5836 move nil)
5837 (unless (assoc (char-to-string char) org-emphasis-alist)
5838 (user-error "No such emphasis marker: \"%c\"" char))
5839 (setq s (char-to-string char)))
5840 (while (and (> (length string) 1)
5841 (equal (substring string 0 1) (substring string -1))
5842 (assoc (substring string 0 1) org-emphasis-alist))
5843 (setq string (substring string 1 -1)))
5844 (setq string (concat s string s))
5845 (when beg (delete-region beg end))
5846 (unless (or (bolp)
5847 (string-match (concat "[" (nth 0 erc) "\n]")
5848 (char-to-string (char-before (point)))))
5849 (insert " "))
5850 (unless (or (eobp)
5851 (string-match (concat "[" (nth 1 erc) "\n]")
5852 (char-to-string (char-after (point)))))
5853 (insert " ") (backward-char 1))
5854 (insert string)
5855 (and move (backward-char 1))))
5857 (defconst org-nonsticky-props
5858 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5860 (defsubst org-rear-nonsticky-at (pos)
5861 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5863 (defun org-activate-plain-links (limit)
5864 "Add link properties for plain links."
5865 (when (and (re-search-forward org-plain-link-re limit t)
5866 (not (org-in-src-block-p)))
5867 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5868 'face))
5869 (link (match-string-no-properties 0)))
5870 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5871 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5872 (add-text-properties (match-beginning 0) (match-end 0)
5873 (list 'mouse-face 'highlight
5874 'face 'org-link
5875 'htmlize-link `(:uri ,link)
5876 'keymap org-mouse-map))
5877 (org-rear-nonsticky-at (match-end 0))
5878 t))))
5880 (defun org-activate-code (limit)
5881 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5882 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5883 (remove-text-properties (match-beginning 0) (match-end 0)
5884 '(display t invisible t intangible t))
5887 (defcustom org-src-fontify-natively t
5888 "When non-nil, fontify code in code blocks.
5889 See also the `org-block' face."
5890 :type 'boolean
5891 :version "24.4"
5892 :package-version '(Org . "8.3")
5893 :group 'org-appearance
5894 :group 'org-babel)
5896 (defcustom org-allow-promoting-top-level-subtree nil
5897 "When non-nil, allow promoting a top level subtree.
5898 The leading star of the top level headline will be replaced
5899 by a #."
5900 :type 'boolean
5901 :version "24.1"
5902 :group 'org-appearance)
5904 (defun org-fontify-meta-lines-and-blocks (limit)
5905 (condition-case nil
5906 (org-fontify-meta-lines-and-blocks-1 limit)
5907 (error (message "org-mode fontification error in %S at %d"
5908 (current-buffer)
5909 (line-number-at-pos)))))
5911 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5912 "Fontify #+ lines and blocks."
5913 (let ((case-fold-search t))
5914 (when (re-search-forward
5915 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5916 limit t)
5917 (let ((beg (match-beginning 0))
5918 (block-start (match-end 0))
5919 (block-end nil)
5920 (lang (match-string 7))
5921 (beg1 (line-beginning-position 2))
5922 (dc1 (downcase (match-string 2)))
5923 (dc3 (downcase (match-string 3)))
5924 end end1 quoting block-type)
5925 (cond
5926 ((and (match-end 4) (equal dc3 "+begin"))
5927 ;; Truly a block
5928 (setq block-type (downcase (match-string 5))
5929 quoting (member block-type org-protecting-blocks))
5930 (when (re-search-forward
5931 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5932 nil t) ;; on purpose, we look further than LIMIT
5933 (setq end (min (point-max) (match-end 0))
5934 end1 (min (point-max) (1- (match-beginning 0))))
5935 (setq block-end (match-beginning 0))
5936 (when quoting
5937 (org-remove-flyspell-overlays-in beg1 end1)
5938 (remove-text-properties beg end
5939 '(display t invisible t intangible t)))
5940 (add-text-properties
5941 beg end '(font-lock-fontified t font-lock-multiline t))
5942 (add-text-properties beg beg1 '(face org-meta-line))
5943 (org-remove-flyspell-overlays-in beg beg1)
5944 (add-text-properties ; For end_src
5945 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5946 (org-remove-flyspell-overlays-in end1 end)
5947 (cond
5948 ((and lang (not (string= lang "")) org-src-fontify-natively)
5949 (org-src-font-lock-fontify-block lang block-start block-end)
5950 (add-text-properties beg1 block-end '(src-block t)))
5951 (quoting
5952 (add-text-properties beg1 (min (point-max) (1+ end1))
5953 (list 'face
5954 (list :inherit
5955 (let ((face-name
5956 (intern (format "org-block-%s" lang))))
5957 (append (and (facep face-name) (list face-name))
5958 '(org-block))))))) ; end of source block
5959 ((not org-fontify-quote-and-verse-blocks))
5960 ((string= block-type "quote")
5961 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5962 ((string= block-type "verse")
5963 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5964 (add-text-properties beg beg1 '(face org-block-begin-line))
5965 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5966 '(face org-block-end-line))
5968 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5969 (org-remove-flyspell-overlays-in
5970 (match-beginning 0)
5971 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5972 (add-text-properties
5973 beg (match-end 3)
5974 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5975 '(font-lock-fontified t invisible t)
5976 '(font-lock-fontified t face org-document-info-keyword)))
5977 (add-text-properties
5978 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5979 (if (string-equal dc1 "+title:")
5980 '(font-lock-fontified t face org-document-title)
5981 '(font-lock-fontified t face org-document-info))))
5982 ((equal dc1 "+caption:")
5983 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5984 (remove-text-properties (match-beginning 0) (match-end 0)
5985 '(display t invisible t intangible t))
5986 (add-text-properties (match-beginning 1) (match-end 3)
5987 '(font-lock-fontified t face org-meta-line))
5988 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5989 '(font-lock-fontified t face org-block))
5991 ((member dc3 '(" " ""))
5992 (org-remove-flyspell-overlays-in beg (match-end 0))
5993 (add-text-properties
5994 beg (match-end 0)
5995 '(font-lock-fontified t face font-lock-comment-face)))
5996 (t ;; just any other in-buffer setting, but not indented
5997 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (remove-text-properties (match-beginning 0) (match-end 0)
5999 '(display t invisible t intangible t))
6000 (add-text-properties beg (match-end 0)
6001 '(font-lock-fontified t face org-meta-line))
6002 t))))))
6004 (defun org-fontify-drawers (limit)
6005 "Fontify drawers."
6006 (when (re-search-forward org-drawer-regexp limit t)
6007 (add-text-properties
6008 (match-beginning 0) (match-end 0)
6009 '(font-lock-fontified t face org-special-keyword))
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (defun org-fontify-macros (limit)
6014 "Fontify macros."
6015 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6016 (add-text-properties
6017 (match-beginning 0) (match-end 0)
6018 '(font-lock-fontified t face org-macro))
6019 (when org-hide-macro-markers
6020 (add-text-properties (match-end 2) (match-beginning 2)
6021 '(invisible t))
6022 (add-text-properties (match-beginning 1) (match-end 1)
6023 '(invisible t)))
6024 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6027 (defun org-activate-angle-links (limit)
6028 "Add text properties for angle links."
6029 (when (and (re-search-forward org-angle-link-re limit t)
6030 (not (org-in-src-block-p)))
6031 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6032 (add-text-properties (match-beginning 0) (match-end 0)
6033 (list 'mouse-face 'highlight
6034 'keymap org-mouse-map
6035 'font-lock-multiline t))
6036 (org-rear-nonsticky-at (match-end 0))
6039 (defun org-activate-footnote-links (limit)
6040 "Add text properties for footnotes."
6041 (let ((fn (org-footnote-next-reference-or-definition limit)))
6042 (when fn
6043 (let* ((beg (nth 1 fn))
6044 (end (nth 2 fn))
6045 (label (car fn))
6046 (referencep (/= (line-beginning-position) beg)))
6047 (when (and referencep (nth 3 fn))
6048 (save-excursion
6049 (goto-char beg)
6050 (search-forward (or label "fn:"))
6051 (org-remove-flyspell-overlays-in beg (match-end 0))))
6052 (add-text-properties beg end
6053 (list 'mouse-face 'highlight
6054 'keymap org-mouse-map
6055 'help-echo
6056 (if referencep "Footnote reference"
6057 "Footnote definition")
6058 'font-lock-fontified t
6059 'font-lock-multiline t
6060 'face 'org-footnote))))))
6062 (defun org-activate-bracket-links (limit)
6063 "Add text properties for bracketed links."
6064 (when (and (re-search-forward org-bracket-link-regexp limit t)
6065 (not (org-in-src-block-p)))
6066 (let* ((hl (match-string-no-properties 1))
6067 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6068 (ip (list 'invisible 'org-link
6069 'keymap org-mouse-map 'mouse-face 'highlight
6070 'font-lock-multiline t 'help-echo help
6071 'htmlize-link `(:uri ,hl)))
6072 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6073 'font-lock-multiline t 'help-echo help
6074 'htmlize-link `(:uri ,hl))))
6075 ;; We need to remove the invisible property here. Table narrowing
6076 ;; may have made some of this invisible.
6077 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6078 (remove-text-properties (match-beginning 0) (match-end 0)
6079 '(invisible nil))
6080 (if (match-end 3)
6081 (progn
6082 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6083 (org-rear-nonsticky-at (match-beginning 3))
6084 (add-text-properties (match-beginning 3) (match-end 3) vp)
6085 (org-rear-nonsticky-at (match-end 3))
6086 (add-text-properties (match-end 3) (match-end 0) ip)
6087 (org-rear-nonsticky-at (match-end 0)))
6088 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6089 (org-rear-nonsticky-at (match-beginning 1))
6090 (add-text-properties (match-beginning 1) (match-end 1) vp)
6091 (org-rear-nonsticky-at (match-end 1))
6092 (add-text-properties (match-end 1) (match-end 0) ip)
6093 (org-rear-nonsticky-at (match-end 0)))
6094 t)))
6096 (defun org-activate-dates (limit)
6097 "Add text properties for dates."
6098 (when (and (re-search-forward org-tsr-regexp-both limit t)
6099 (not (equal (char-before (match-beginning 0)) 91)))
6100 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6101 (add-text-properties (match-beginning 0) (match-end 0)
6102 (list 'mouse-face 'highlight
6103 'keymap org-mouse-map))
6104 (org-rear-nonsticky-at (match-end 0))
6105 (when org-display-custom-times
6106 (if (match-end 3)
6107 (org-display-custom-time (match-beginning 3) (match-end 3))
6108 (org-display-custom-time (match-beginning 1) (match-end 1))))
6111 (defvar-local org-target-link-regexp nil
6112 "Regular expression matching radio targets in plain text.")
6114 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6115 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6116 border border border))
6117 "Regular expression matching a link target.")
6119 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6120 "Regular expression matching a radio target.")
6122 (defconst org-any-target-regexp
6123 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6124 "Regular expression matching any target.")
6126 (defun org-activate-target-links (limit)
6127 "Add text properties for target matches."
6128 (when org-target-link-regexp
6129 (let ((case-fold-search t))
6130 (when (re-search-forward org-target-link-regexp limit t)
6131 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6132 (add-text-properties (match-beginning 1) (match-end 1)
6133 (list 'mouse-face 'highlight
6134 'keymap org-mouse-map
6135 'help-echo "Radio target link"
6136 'org-linked-text t))
6137 (org-rear-nonsticky-at (match-end 1))
6138 t))))
6140 (defun org-update-radio-target-regexp ()
6141 "Find all radio targets in this file and update the regular expression.
6142 Also refresh fontification if needed."
6143 (interactive)
6144 (let ((old-regexp org-target-link-regexp)
6145 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6146 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6147 (targets
6148 (org-with-wide-buffer
6149 (goto-char (point-min))
6150 (let (rtn)
6151 (while (re-search-forward org-radio-target-regexp nil t)
6152 ;; Make sure point is really within the object.
6153 (backward-char)
6154 (let ((obj (org-element-context)))
6155 (when (eq (org-element-type obj) 'radio-target)
6156 (cl-pushnew (org-element-property :value obj) rtn
6157 :test #'equal))))
6158 rtn))))
6159 (setq org-target-link-regexp
6160 (and targets
6161 (concat before-re
6162 (mapconcat
6163 (lambda (x)
6164 (replace-regexp-in-string
6165 " +" "\\s-+" (regexp-quote x) t t))
6166 targets
6167 "\\|")
6168 after-re)))
6169 (unless (equal old-regexp org-target-link-regexp)
6170 ;; Clean-up cache.
6171 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6172 ((not org-target-link-regexp) old-regexp)
6174 (concat before-re
6175 (mapconcat
6176 (lambda (re)
6177 (substring re (length before-re)
6178 (- (length after-re))))
6179 (list old-regexp org-target-link-regexp)
6180 "\\|")
6181 after-re)))))
6182 (org-with-wide-buffer
6183 (goto-char (point-min))
6184 (while (re-search-forward regexp nil t)
6185 (org-element-cache-refresh (match-beginning 1)))))
6186 ;; Re fontify buffer.
6187 (when (memq 'radio org-highlight-links)
6188 (org-restart-font-lock)))))
6190 (defun org-hide-wide-columns (limit)
6191 (let (s e)
6192 (setq s (text-property-any (point) (or limit (point-max))
6193 'org-cwidth t))
6194 (when s
6195 (setq e (next-single-property-change s 'org-cwidth))
6196 (add-text-properties s e '(invisible org-cwidth))
6197 (goto-char e)
6198 t)))
6200 (defvar org-latex-and-related-regexp nil
6201 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6203 (defun org-compute-latex-and-related-regexp ()
6204 "Compute regular expression for LaTeX, entities and sub/superscript.
6205 Result depends on variable `org-highlight-latex-and-related'."
6206 (setq-local
6207 org-latex-and-related-regexp
6208 (let* ((re-sub
6209 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6210 ((eq org-use-sub-superscripts '{})
6211 (list org-match-substring-with-braces-regexp))
6212 (org-use-sub-superscripts (list org-match-substring-regexp))))
6213 (re-latex
6214 (when (memq 'latex org-highlight-latex-and-related)
6215 (let ((matchers (plist-get org-format-latex-options :matchers)))
6216 (delq nil
6217 (mapcar (lambda (x)
6218 (and (member (car x) matchers) (nth 1 x)))
6219 org-latex-regexps)))))
6220 (re-entities
6221 (when (memq 'entities org-highlight-latex-and-related)
6222 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6223 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6225 (defun org-do-latex-and-related (limit)
6226 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6227 LIMIT bounds the search for syntax to highlight. Stop at first
6228 highlighted object, if any. Return t if some highlighting was
6229 done, nil otherwise."
6230 (when (org-string-nw-p org-latex-and-related-regexp)
6231 (catch 'found
6232 (while (re-search-forward org-latex-and-related-regexp limit t)
6233 (unless
6234 (cl-some
6235 (lambda (f)
6236 (memq f '(org-code org-verbatim underline org-special-keyword)))
6237 (save-excursion
6238 (goto-char (1+ (match-beginning 0)))
6239 (face-at-point nil t)))
6240 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6241 '(?_ ?^))
6243 0)))
6244 (font-lock-prepend-text-property
6245 (+ offset (match-beginning 0)) (match-end 0)
6246 'face 'org-latex-and-related)
6247 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6248 '(font-lock-multiline t)))
6249 (throw 'found t)))
6250 nil)))
6252 (defun org-restart-font-lock ()
6253 "Restart `font-lock-mode', to force refontification."
6254 (when (and (boundp 'font-lock-mode) font-lock-mode)
6255 (font-lock-mode -1)
6256 (font-lock-mode 1)))
6258 (defun org-activate-tags (limit)
6259 (when (re-search-forward
6260 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6261 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6262 (add-text-properties (match-beginning 1) (match-end 1)
6263 (list 'mouse-face 'highlight
6264 'keymap org-mouse-map))
6265 (org-rear-nonsticky-at (match-end 1))
6268 (defun org-outline-level ()
6269 "Compute the outline level of the heading at point.
6271 If this is called at a normal headline, the level is the number
6272 of stars. Use `org-reduced-level' to remove the effect of
6273 `org-odd-levels'. Unlike to `org-current-level', this function
6274 takes into consideration inlinetasks."
6275 (org-with-wide-buffer
6276 (end-of-line)
6277 (if (re-search-backward org-outline-regexp-bol nil t)
6278 (1- (- (match-end 0) (match-beginning 0)))
6279 0)))
6281 (defvar org-font-lock-keywords nil)
6283 (defsubst org-re-property (property &optional literal allow-null value)
6284 "Return a regexp matching a PROPERTY line.
6286 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6287 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6288 non-nil, match properties even without a value.
6290 Match group 3 is set to the value when it exists. If there is no
6291 value and ALLOW-NULL is non-nil, it is set to the empty string.
6293 With optional argument VALUE, match only property lines with
6294 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6295 unless LITERAL is non-nil."
6296 (concat
6297 "^\\(?4:[ \t]*\\)"
6298 (format "\\(?1::\\(?2:%s\\):\\)"
6299 (if literal property (regexp-quote property)))
6300 (cond (value
6301 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6302 (if literal value (regexp-quote value))))
6303 (allow-null
6304 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6306 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6308 (defconst org-property-re
6309 (org-re-property "\\S-+" 'literal t)
6310 "Regular expression matching a property line.
6311 There are four matching groups:
6312 1: :PROPKEY: including the leading and trailing colon,
6313 2: PROPKEY without the leading and trailing colon,
6314 3: PROPVAL without leading or trailing spaces,
6315 4: the indentation of the current line,
6316 5: trailing whitespace.")
6318 (defvar org-font-lock-hook nil
6319 "Functions to be called for special font lock stuff.")
6321 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6323 (defvar org-font-lock-set-keywords-hook nil
6324 "Functions that can manipulate `org-font-lock-extra-keywords'.
6325 This is called after `org-font-lock-extra-keywords' is defined, but before
6326 it is installed to be used by font lock. This can be useful if something
6327 needs to be inserted at a specific position in the font-lock sequence.")
6329 (defun org-font-lock-hook (limit)
6330 "Run `org-font-lock-hook' within LIMIT."
6331 (run-hook-with-args 'org-font-lock-hook limit))
6333 (defun org-set-font-lock-defaults ()
6334 "Set font lock defaults for the current buffer."
6335 (let* ((em org-fontify-emphasized-text)
6336 (lk org-highlight-links)
6337 (org-font-lock-extra-keywords
6338 (list
6339 ;; Call the hook
6340 '(org-font-lock-hook)
6341 ;; Headlines
6342 `(,(if org-fontify-whole-heading-line
6343 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6344 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6345 (1 (org-get-level-face 1))
6346 (2 (org-get-level-face 2))
6347 (3 (org-get-level-face 3)))
6348 ;; Table lines
6349 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6350 (1 'org-table t))
6351 ;; Table internals
6352 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6353 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6354 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6355 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6356 ;; Drawers
6357 '(org-fontify-drawers)
6358 ;; Properties
6359 (list org-property-re
6360 '(1 'org-special-keyword t)
6361 '(3 'org-property-value t))
6362 ;; Links
6363 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6364 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6365 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6366 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6367 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6368 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6369 (when (memq 'footnote lk) '(org-activate-footnote-links))
6370 ;; Targets.
6371 (list org-any-target-regexp '(0 'org-target t))
6372 ;; Diary sexps.
6373 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6374 ;; Macro
6375 '(org-fontify-macros)
6376 '(org-hide-wide-columns (0 nil append))
6377 ;; TODO keyword
6378 (list (format org-heading-keyword-regexp-format
6379 org-todo-regexp)
6380 '(2 (org-get-todo-face 2) t))
6381 ;; DONE
6382 (if org-fontify-done-headline
6383 (list (format org-heading-keyword-regexp-format
6384 (concat
6385 "\\(?:"
6386 (mapconcat 'regexp-quote org-done-keywords "\\|")
6387 "\\)"))
6388 '(2 'org-headline-done t))
6389 nil)
6390 ;; Priorities
6391 '(org-font-lock-add-priority-faces)
6392 ;; Tags
6393 '(org-font-lock-add-tag-faces)
6394 ;; Tags groups
6395 (when (and org-group-tags org-tag-groups-alist)
6396 (list (concat org-outline-regexp-bol ".+\\(:"
6397 (regexp-opt (mapcar 'car org-tag-groups-alist))
6398 ":\\).*$")
6399 '(1 'org-tag-group prepend)))
6400 ;; Special keywords
6401 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6402 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6403 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6404 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6405 ;; Emphasis
6406 (when em '(org-do-emphasis-faces))
6407 ;; Checkboxes
6408 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6409 1 'org-checkbox prepend)
6410 (when (cdr (assq 'checkbox org-list-automatic-rules))
6411 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6412 (0 (org-get-checkbox-statistics-face) t)))
6413 ;; Description list items
6414 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6415 1 'org-list-dt prepend)
6416 ;; ARCHIVEd headings
6417 (list (concat
6418 org-outline-regexp-bol
6419 "\\(.*:" org-archive-tag ":.*\\)")
6420 '(1 'org-archived prepend))
6421 ;; Specials
6422 '(org-do-latex-and-related)
6423 '(org-fontify-entities)
6424 '(org-raise-scripts)
6425 ;; Code
6426 '(org-activate-code (1 'org-code t))
6427 ;; COMMENT
6428 (list (format
6429 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6430 org-todo-regexp
6431 org-comment-string)
6432 '(9 'org-special-keyword t))
6433 ;; Blocks and meta lines
6434 '(org-fontify-meta-lines-and-blocks))))
6435 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6436 (run-hooks 'org-font-lock-set-keywords-hook)
6437 ;; Now set the full font-lock-keywords
6438 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6439 (setq-local font-lock-defaults
6440 '(org-font-lock-keywords t nil nil backward-paragraph))
6441 (kill-local-variable 'font-lock-keywords)
6442 nil))
6444 (defun org-toggle-pretty-entities ()
6445 "Toggle the composition display of entities as UTF8 characters."
6446 (interactive)
6447 (setq-local org-pretty-entities (not org-pretty-entities))
6448 (org-restart-font-lock)
6449 (if org-pretty-entities
6450 (message "Entities are now displayed as UTF8 characters")
6451 (save-restriction
6452 (widen)
6453 (decompose-region (point-min) (point-max))
6454 (message "Entities are now displayed as plain text"))))
6456 (defvar-local org-custom-properties-overlays nil
6457 "List of overlays used for custom properties.")
6459 (defun org-toggle-custom-properties-visibility ()
6460 "Display or hide properties in `org-custom-properties'."
6461 (interactive)
6462 (if org-custom-properties-overlays
6463 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6464 (setq org-custom-properties-overlays nil))
6465 (when org-custom-properties
6466 (org-with-wide-buffer
6467 (goto-char (point-min))
6468 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6469 (while (re-search-forward regexp nil t)
6470 (let ((end (cdr (save-match-data (org-get-property-block)))))
6471 (when (and end (< (point) end))
6472 ;; Hide first custom property in current drawer.
6473 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6474 (overlay-put o 'invisible t)
6475 (overlay-put o 'org-custom-property t)
6476 (push o org-custom-properties-overlays))
6477 ;; Hide additional custom properties in the same drawer.
6478 (while (re-search-forward regexp end t)
6479 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6480 (overlay-put o 'invisible t)
6481 (overlay-put o 'org-custom-property t)
6482 (push o org-custom-properties-overlays)))))
6483 ;; Each entry is limited to a single property drawer.
6484 (outline-next-heading)))))))
6486 (defun org-fontify-entities (limit)
6487 "Find an entity to fontify."
6488 (let (ee)
6489 (when org-pretty-entities
6490 (catch 'match
6491 ;; "\_ "-family is left out on purpose. Only the first one,
6492 ;; i.e., "\_ ", could be fontified anyway, and it would be
6493 ;; confusing when adding a second white space character.
6494 (while (re-search-forward
6495 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6496 limit t)
6497 (when (and (not (org-at-comment-p))
6498 (setq ee (org-entity-get (match-string 1)))
6499 (= (length (nth 6 ee)) 1))
6500 (let* ((end (if (equal (match-string 2) "{}")
6501 (match-end 2)
6502 (match-end 1))))
6503 (add-text-properties
6504 (match-beginning 0) end
6505 (list 'font-lock-fontified t))
6506 (compose-region (match-beginning 0) end
6507 (nth 6 ee) nil)
6508 (backward-char 1)
6509 (throw 'match t))))
6510 nil))))
6512 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6513 "Fontify string S like in Org-mode."
6514 (with-temp-buffer
6515 (insert s)
6516 (let ((org-odd-levels-only odd-levels))
6517 (org-mode)
6518 (org-font-lock-ensure)
6519 (buffer-string))))
6521 (defvar org-m nil)
6522 (defvar org-l nil)
6523 (defvar org-f nil)
6524 (defun org-get-level-face (n)
6525 "Get the right face for match N in font-lock matching of headlines."
6526 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6527 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6528 (if org-cycle-level-faces
6529 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6530 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6531 (cond
6532 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6533 ((eq n 2) org-f)
6534 (t (unless org-level-color-stars-only org-f))))
6536 (defun org-face-from-face-or-color (context inherit face-or-color)
6537 "Create a face list that inherits INHERIT, but sets the foreground color.
6538 When FACE-OR-COLOR is not a string, just return it."
6539 (if (stringp face-or-color)
6540 (list :inherit inherit
6541 (cdr (assoc context org-faces-easy-properties))
6542 face-or-color)
6543 face-or-color))
6545 (defun org-get-todo-face (kwd)
6546 "Get the right face for a TODO keyword KWD.
6547 If KWD is a number, get the corresponding match group."
6548 (when (numberp kwd) (setq kwd (match-string kwd)))
6549 (or (org-face-from-face-or-color
6550 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6551 (and (member kwd org-done-keywords) 'org-done)
6552 'org-todo))
6554 (defun org-get-priority-face (priority)
6555 "Get the right face for PRIORITY.
6556 PRIORITY is a character."
6557 (or (org-face-from-face-or-color
6558 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6559 'org-priority))
6561 (defun org-get-tag-face (tag)
6562 "Get the right face for TAG.
6563 If TAG is a number, get the corresponding match group."
6564 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6565 (or (org-face-from-face-or-color
6566 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6567 'org-tag)))
6569 (defun org-font-lock-add-priority-faces (limit)
6570 "Add the special priority faces."
6571 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6572 (add-text-properties
6573 (match-beginning 1) (match-end 1)
6574 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6575 'font-lock-fontified t))))
6577 (defun org-font-lock-add-tag-faces (limit)
6578 "Add the special tag faces."
6579 (when (and org-tag-faces org-tags-special-faces-re)
6580 (while (re-search-forward org-tags-special-faces-re limit t)
6581 (add-text-properties (match-beginning 1) (match-end 1)
6582 (list 'face (org-get-tag-face 1)
6583 'font-lock-fontified t))
6584 (backward-char 1))))
6586 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6587 "Remove fontification and activation overlays from links."
6588 (font-lock-default-unfontify-region beg end)
6589 (let* ((buffer-undo-list t)
6590 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6591 (inhibit-modification-hooks t)
6592 deactivate-mark buffer-file-name buffer-file-truename)
6593 (decompose-region beg end)
6594 (remove-text-properties beg end
6595 '(mouse-face t keymap t org-linked-text t
6596 invisible t intangible t
6597 org-emphasis t))
6598 (org-remove-font-lock-display-properties beg end)))
6600 (defconst org-script-display '(((raise -0.3) (height 0.7))
6601 ((raise 0.3) (height 0.7))
6602 ((raise -0.5))
6603 ((raise 0.5)))
6604 "Display properties for showing superscripts and subscripts.")
6606 (defun org-remove-font-lock-display-properties (beg end)
6607 "Remove specific display properties that have been added by font lock.
6608 The will remove the raise properties that are used to show superscripts
6609 and subscripts."
6610 (let (next prop)
6611 (while (< beg end)
6612 (setq next (next-single-property-change beg 'display nil end)
6613 prop (get-text-property beg 'display))
6614 (when (member prop org-script-display)
6615 (put-text-property beg next 'display nil))
6616 (setq beg next))))
6618 (defun org-raise-scripts (limit)
6619 "Add raise properties to sub/superscripts."
6620 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6621 (re-search-forward
6622 (if (eq org-use-sub-superscripts t)
6623 org-match-substring-regexp
6624 org-match-substring-with-braces-regexp)
6625 limit t))
6626 (let* ((pos (point)) table-p comment-p
6627 (mpos (match-beginning 3))
6628 (emph-p (get-text-property mpos 'org-emphasis))
6629 (link-p (get-text-property mpos 'mouse-face))
6630 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6631 (goto-char (point-at-bol))
6632 (setq table-p (looking-at-p org-table-dataline-regexp)
6633 comment-p (looking-at-p "^[ \t]*#[ +]"))
6634 (goto-char pos)
6635 ;; Handle a_b^c
6636 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6637 (unless (or comment-p emph-p link-p keyw-p)
6638 (put-text-property (match-beginning 3) (match-end 0)
6639 'display
6640 (if (equal (char-after (match-beginning 2)) ?^)
6641 (nth (if table-p 3 1) org-script-display)
6642 (nth (if table-p 2 0) org-script-display)))
6643 (add-text-properties (match-beginning 2) (match-end 2)
6644 (list 'invisible t
6645 'org-dwidth t 'org-dwidth-n 1))
6646 (if (and (eq (char-after (match-beginning 3)) ?{)
6647 (eq (char-before (match-end 3)) ?}))
6648 (progn
6649 (add-text-properties
6650 (match-beginning 3) (1+ (match-beginning 3))
6651 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6652 (add-text-properties
6653 (1- (match-end 3)) (match-end 3)
6654 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6655 t)))
6657 ;;;; Visibility cycling, including org-goto and indirect buffer
6659 ;;; Cycling
6661 (defvar-local org-cycle-global-status nil)
6662 (put 'org-cycle-global-status 'org-state t)
6663 (defvar-local org-cycle-subtree-status nil)
6664 (put 'org-cycle-subtree-status 'org-state t)
6666 (defvar org-inlinetask-min-level)
6668 (defun org-unlogged-message (&rest args)
6669 "Display a message, but avoid logging it in the *Messages* buffer."
6670 (let ((message-log-max nil))
6671 (apply 'message args)))
6673 ;;;###autoload
6674 (defun org-cycle (&optional arg)
6675 "TAB-action and visibility cycling for Org-mode.
6677 This is the command invoked in Org-mode by the TAB key. Its main purpose
6678 is outline visibility cycling, but it also invokes other actions
6679 in special contexts.
6681 - When this function is called with a prefix argument, rotate the entire
6682 buffer through 3 states (global cycling)
6683 1. OVERVIEW: Show only top-level headlines.
6684 2. CONTENTS: Show all headlines of all levels, but no body text.
6685 3. SHOW ALL: Show everything.
6686 With a double \\[universal-argument] prefix argument, \
6687 switch to the startup visibility,
6688 determined by the variable `org-startup-folded', and by any VISIBILITY
6689 properties in the buffer.
6690 With a triple \\[universal-argument] prefix argument, \
6691 show the entire buffer, including any drawers.
6693 - When inside a table, re-align the table and move to the next field.
6695 - When point is at the beginning of a headline, rotate the subtree started
6696 by this line through 3 different states (local cycling)
6697 1. FOLDED: Only the main headline is shown.
6698 2. CHILDREN: The main headline and the direct children are shown.
6699 From this state, you can move to one of the children
6700 and zoom in further.
6701 3. SUBTREE: Show the entire subtree, including body text.
6702 If there is no subtree, switch directly from CHILDREN to FOLDED.
6704 - When point is at the beginning of an empty headline and the variable
6705 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6706 of the headline by demoting and promoting it to likely levels. This
6707 speeds up creation document structure by pressing TAB once or several
6708 times right after creating a new headline.
6710 - When there is a numeric prefix, go up to a heading with level ARG, do
6711 a `show-subtree' and return to the previous cursor position. If ARG
6712 is negative, go up that many levels.
6714 - When point is not at the beginning of a headline, execute the global
6715 binding for TAB, which is re-indenting the line. See the option
6716 `org-cycle-emulate-tab' for details.
6718 - Special case: if point is at the beginning of the buffer and there is
6719 no headline in line 1, this function will act as if called with prefix arg
6720 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6721 But only if also the variable `org-cycle-global-at-bob' is t."
6722 (interactive "P")
6723 (org-load-modules-maybe)
6724 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6725 (and org-cycle-level-after-item/entry-creation
6726 (or (org-cycle-level)
6727 (org-cycle-item-indentation))))
6728 (let* ((limit-level
6729 (or org-cycle-max-level
6730 (and (boundp 'org-inlinetask-min-level)
6731 org-inlinetask-min-level
6732 (1- org-inlinetask-min-level))))
6733 (nstars (and limit-level
6734 (if org-odd-levels-only
6735 (and limit-level (1- (* limit-level 2)))
6736 limit-level)))
6737 (org-outline-regexp
6738 (if (not (derived-mode-p 'org-mode))
6739 outline-regexp
6740 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6741 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6742 (not (looking-at org-outline-regexp))))
6743 (org-cycle-hook
6744 (if bob-special
6745 (delq 'org-optimize-window-after-visibility-change
6746 (copy-sequence org-cycle-hook))
6747 org-cycle-hook))
6748 (pos (point)))
6750 (when (or bob-special (equal arg '(4)))
6751 ;; special case: use global cycling
6752 (setq arg t))
6754 (cond
6756 ((equal arg '(16))
6757 (setq last-command 'dummy)
6758 (org-set-startup-visibility)
6759 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6761 ((equal arg '(64))
6762 (outline-show-all)
6763 (org-unlogged-message "Entire buffer visible, including drawers"))
6765 ;; Try cdlatex TAB completion
6766 ((org-try-cdlatex-tab))
6768 ;; Table: enter it or move to the next field.
6769 ((org-at-table-p 'any)
6770 (if (org-at-table.el-p)
6771 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6772 Use \\[org-edit-special] to edit table.el tables"))
6773 (if arg (org-table-edit-field t)
6774 (org-table-justify-field-maybe)
6775 (call-interactively 'org-table-next-field))))
6777 ((run-hook-with-args-until-success
6778 'org-tab-after-check-for-table-hook))
6780 ;; Global cycling: delegate to `org-cycle-internal-global'.
6781 ((eq arg t) (org-cycle-internal-global))
6783 ;; Drawers: delegate to `org-flag-drawer'.
6784 ((save-excursion
6785 (beginning-of-line 1)
6786 (looking-at org-drawer-regexp))
6787 (org-flag-drawer ; toggle block visibility
6788 (not (get-char-property (match-end 0) 'invisible))))
6790 ;; Show-subtree, ARG levels up from here.
6791 ((integerp arg)
6792 (save-excursion
6793 (org-back-to-heading)
6794 (outline-up-heading (if (< arg 0) (- arg)
6795 (- (funcall outline-level) arg)))
6796 (org-show-subtree)))
6798 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6799 ((and (featurep 'org-inlinetask)
6800 (org-inlinetask-at-task-p)
6801 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6802 (org-inlinetask-toggle-visibility))
6804 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6805 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6806 (save-excursion (move-beginning-of-line 1)
6807 (looking-at org-outline-regexp)))
6808 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6809 (org-cycle-internal-local))
6811 ;; From there: TAB emulation and template completion.
6812 (buffer-read-only (org-back-to-heading))
6814 ((run-hook-with-args-until-success
6815 'org-tab-after-check-for-cycling-hook))
6817 ((org-try-structure-completion))
6819 ((run-hook-with-args-until-success
6820 'org-tab-before-tab-emulation-hook))
6822 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6823 (or (not (bolp))
6824 (not (looking-at org-outline-regexp))))
6825 (call-interactively (global-key-binding "\t")))
6827 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6828 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6829 (or (and (eq org-cycle-emulate-tab 'white)
6830 (= (match-end 0) (point-at-eol)))
6831 (and (eq org-cycle-emulate-tab 'whitestart)
6832 (>= (match-end 0) pos))))
6834 (eq org-cycle-emulate-tab t))
6835 (call-interactively (global-key-binding "\t")))
6837 (t (save-excursion
6838 (org-back-to-heading)
6839 (org-cycle)))))))
6841 (defun org-cycle-internal-global ()
6842 "Do the global cycling action."
6843 ;; Hack to avoid display of messages for .org attachments in Gnus
6844 (let ((ga (string-match "\\*fontification" (buffer-name))))
6845 (cond
6846 ((and (eq last-command this-command)
6847 (eq org-cycle-global-status 'overview))
6848 ;; We just created the overview - now do table of contents
6849 ;; This can be slow in very large buffers, so indicate action
6850 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6851 (unless ga (org-unlogged-message "CONTENTS..."))
6852 (org-content)
6853 (unless ga (org-unlogged-message "CONTENTS...done"))
6854 (setq org-cycle-global-status 'contents)
6855 (run-hook-with-args 'org-cycle-hook 'contents))
6857 ((and (eq last-command this-command)
6858 (eq org-cycle-global-status 'contents))
6859 ;; We just showed the table of contents - now show everything
6860 (run-hook-with-args 'org-pre-cycle-hook 'all)
6861 (outline-show-all)
6862 (unless ga (org-unlogged-message "SHOW ALL"))
6863 (setq org-cycle-global-status 'all)
6864 (run-hook-with-args 'org-cycle-hook 'all))
6867 ;; Default action: go to overview
6868 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6869 (org-overview)
6870 (unless ga (org-unlogged-message "OVERVIEW"))
6871 (setq org-cycle-global-status 'overview)
6872 (run-hook-with-args 'org-cycle-hook 'overview)))))
6874 (defvar org-called-with-limited-levels nil
6875 "Non-nil when `org-with-limited-levels' is currently active.")
6877 (defun org-cycle-internal-local ()
6878 "Do the local cycling action."
6879 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6880 ;; First, determine end of headline (EOH), end of subtree or item
6881 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6882 (save-excursion
6883 (if (org-at-item-p)
6884 (progn
6885 (beginning-of-line)
6886 (setq struct (org-list-struct))
6887 (setq eoh (point-at-eol))
6888 (setq eos (org-list-get-item-end-before-blank (point) struct))
6889 (setq has-children (org-list-has-child-p (point) struct)))
6890 (org-back-to-heading)
6891 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6892 (setq eos (save-excursion (org-end-of-subtree t t)
6893 (when (bolp) (backward-char)) (point)))
6894 (setq has-children
6895 (or (save-excursion
6896 (let ((level (funcall outline-level)))
6897 (outline-next-heading)
6898 (and (org-at-heading-p t)
6899 (> (funcall outline-level) level))))
6900 (save-excursion
6901 (org-list-search-forward (org-item-beginning-re) eos t)))))
6902 ;; Determine end invisible part of buffer (EOL)
6903 (beginning-of-line 2)
6904 (while (and (not (eobp)) ;This is like `next-line'.
6905 (get-char-property (1- (point)) 'invisible))
6906 (goto-char (next-single-char-property-change (point) 'invisible))
6907 (and (eolp) (beginning-of-line 2)))
6908 (setq eol (point)))
6909 ;; Find out what to do next and set `this-command'
6910 (cond
6911 ((= eos eoh)
6912 ;; Nothing is hidden behind this heading
6913 (unless (org-before-first-heading-p)
6914 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6915 (org-unlogged-message "EMPTY ENTRY")
6916 (setq org-cycle-subtree-status nil)
6917 (save-excursion
6918 (goto-char eos)
6919 (outline-next-heading)
6920 (when (outline-invisible-p) (org-flag-heading nil))))
6921 ((and (or (>= eol eos)
6922 (not (string-match "\\S-" (buffer-substring eol eos))))
6923 (or has-children
6924 (not (setq children-skipped
6925 org-cycle-skip-children-state-if-no-children))))
6926 ;; Entire subtree is hidden in one line: children view
6927 (unless (org-before-first-heading-p)
6928 (run-hook-with-args 'org-pre-cycle-hook 'children))
6929 (if (org-at-item-p)
6930 (org-list-set-item-visibility (point-at-bol) struct 'children)
6931 (org-show-entry)
6932 (org-with-limited-levels (org-show-children))
6933 ;; FIXME: This slows down the func way too much.
6934 ;; How keep drawers hidden in subtree anyway?
6935 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6936 ;; (org-cycle-hide-drawers 'subtree))
6938 ;; Fold every list in subtree to top-level items.
6939 (when (eq org-cycle-include-plain-lists 'integrate)
6940 (save-excursion
6941 (org-back-to-heading)
6942 (while (org-list-search-forward (org-item-beginning-re) eos t)
6943 (beginning-of-line 1)
6944 (let* ((struct (org-list-struct))
6945 (prevs (org-list-prevs-alist struct))
6946 (end (org-list-get-bottom-point struct)))
6947 (dolist (e (org-list-get-all-items (point) struct prevs))
6948 (org-list-set-item-visibility e struct 'folded))
6949 (goto-char (if (< end eos) end eos)))))))
6950 (org-unlogged-message "CHILDREN")
6951 (save-excursion
6952 (goto-char eos)
6953 (outline-next-heading)
6954 (when (outline-invisible-p) (org-flag-heading nil)))
6955 (setq org-cycle-subtree-status 'children)
6956 (unless (org-before-first-heading-p)
6957 (run-hook-with-args 'org-cycle-hook 'children)))
6958 ((or children-skipped
6959 (and (eq last-command this-command)
6960 (eq org-cycle-subtree-status 'children)))
6961 ;; We just showed the children, or no children are there,
6962 ;; now show everything.
6963 (unless (org-before-first-heading-p)
6964 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6965 (outline-flag-region eoh eos nil)
6966 (org-unlogged-message
6967 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6968 (setq org-cycle-subtree-status 'subtree)
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-cycle-hook 'subtree)))
6972 ;; Default action: hide the subtree.
6973 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6974 (outline-flag-region eoh eos t)
6975 (org-unlogged-message "FOLDED")
6976 (setq org-cycle-subtree-status 'folded)
6977 (unless (org-before-first-heading-p)
6978 (run-hook-with-args 'org-cycle-hook 'folded))))))
6980 ;;;###autoload
6981 (defun org-global-cycle (&optional arg)
6982 "Cycle the global visibility. For details see `org-cycle'.
6983 With \\[universal-argument] prefix arg, switch to startup visibility.
6984 With a numeric prefix, show all headlines up to that level."
6985 (interactive "P")
6986 (let ((org-cycle-include-plain-lists
6987 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6988 (cond
6989 ((integerp arg)
6990 (outline-show-all)
6991 (outline-hide-sublevels arg)
6992 (setq org-cycle-global-status 'contents))
6993 ((equal arg '(4))
6994 (org-set-startup-visibility)
6995 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6997 (org-cycle '(4))))))
6999 (defun org-set-startup-visibility ()
7000 "Set the visibility required by startup options and properties."
7001 (cond
7002 ((eq org-startup-folded t)
7003 (org-overview))
7004 ((eq org-startup-folded 'content)
7005 (org-content))
7006 ((or (eq org-startup-folded 'showeverything)
7007 (eq org-startup-folded nil))
7008 (outline-show-all)))
7009 (unless (eq org-startup-folded 'showeverything)
7010 (when org-hide-block-startup (org-hide-block-all))
7011 (org-set-visibility-according-to-property 'no-cleanup)
7012 (org-cycle-hide-archived-subtrees 'all)
7013 (org-cycle-hide-drawers 'all)
7014 (org-cycle-show-empty-lines t)))
7016 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7017 "Switch subtree visibilities according to :VISIBILITY: property."
7018 (interactive)
7019 (org-with-wide-buffer
7020 (goto-char (point-min))
7021 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7022 (if (not (org-at-property-p)) (outline-next-heading)
7023 (let ((state (match-string 3)))
7024 (save-excursion
7025 (org-back-to-heading t)
7026 (outline-hide-subtree)
7027 (org-reveal)
7028 (cond
7029 ((equal state "folded")
7030 (outline-hide-subtree))
7031 ((equal state "children")
7032 (org-show-hidden-entry)
7033 (org-show-children))
7034 ((equal state "content")
7035 (save-excursion
7036 (save-restriction
7037 (org-narrow-to-subtree)
7038 (org-content))))
7039 ((member state '("all" "showall"))
7040 (outline-show-subtree)))))))
7041 (unless no-cleanup
7042 (org-cycle-hide-archived-subtrees 'all)
7043 (org-cycle-hide-drawers 'all)
7044 (org-cycle-show-empty-lines 'all))))
7046 ;; This function uses outline-regexp instead of the more fundamental
7047 ;; org-outline-regexp so that org-cycle-global works outside of Org
7048 ;; buffers, where outline-regexp is needed.
7049 (defun org-overview ()
7050 "Switch to overview mode, showing only top-level headlines.
7051 This shows all headlines with a level equal or greater than the level
7052 of the first headline in the buffer. This is important, because if the
7053 first headline is not level one, then (hide-sublevels 1) gives confusing
7054 results."
7055 (interactive)
7056 (save-excursion
7057 (let ((level
7058 (save-excursion
7059 (goto-char (point-min))
7060 (when (re-search-forward (concat "^" outline-regexp) nil t)
7061 (goto-char (match-beginning 0))
7062 (funcall outline-level)))))
7063 (and level (outline-hide-sublevels level)))))
7065 (defun org-content (&optional arg)
7066 "Show all headlines in the buffer, like a table of contents.
7067 With numerical argument N, show content up to level N."
7068 (interactive "P")
7069 (org-overview)
7070 (save-excursion
7071 ;; Visit all headings and show their offspring
7072 (and (integerp arg) (org-overview))
7073 (goto-char (point-max))
7074 (catch 'exit
7075 (while (and (progn (condition-case nil
7076 (outline-previous-visible-heading 1)
7077 (error (goto-char (point-min))))
7079 (looking-at org-outline-regexp))
7080 (if (integerp arg)
7081 (org-show-children (1- arg))
7082 (outline-show-branches))
7083 (when (bobp) (throw 'exit nil))))))
7085 (defun org-optimize-window-after-visibility-change (state)
7086 "Adjust the window after a change in outline visibility.
7087 This function is the default value of the hook `org-cycle-hook'."
7088 (when (get-buffer-window (current-buffer))
7089 (cond
7090 ((eq state 'content) nil)
7091 ((eq state 'all) nil)
7092 ((eq state 'folded) nil)
7093 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7094 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7096 (defun org-remove-empty-overlays-at (pos)
7097 "Remove outline overlays that do not contain non-white stuff."
7098 (dolist (o (overlays-at pos))
7099 (and (eq 'outline (overlay-get o 'invisible))
7100 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7101 (overlay-end o))))
7102 (delete-overlay o))))
7104 (defun org-clean-visibility-after-subtree-move ()
7105 "Fix visibility issues after moving a subtree."
7106 ;; First, find a reasonable region to look at:
7107 ;; Start two siblings above, end three below
7108 (let* ((beg (save-excursion
7109 (and (org-get-last-sibling)
7110 (org-get-last-sibling))
7111 (point)))
7112 (end (save-excursion
7113 (and (org-get-next-sibling)
7114 (org-get-next-sibling)
7115 (org-get-next-sibling))
7116 (if (org-at-heading-p)
7117 (point-at-eol)
7118 (point))))
7119 (level (looking-at "\\*+"))
7120 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7121 (save-excursion
7122 (save-restriction
7123 (narrow-to-region beg end)
7124 (when re
7125 ;; Properly fold already folded siblings
7126 (goto-char (point-min))
7127 (while (re-search-forward re nil t)
7128 (when (and (not (outline-invisible-p))
7129 (save-excursion
7130 (goto-char (point-at-eol)) (outline-invisible-p)))
7131 (outline-hide-entry))))
7132 (org-cycle-show-empty-lines 'overview)
7133 (org-cycle-hide-drawers 'overview)))))
7135 (defun org-cycle-show-empty-lines (state)
7136 "Show empty lines above all visible headlines.
7137 The region to be covered depends on STATE when called through
7138 `org-cycle-hook'. Lisp program can use t for STATE to get the
7139 entire buffer covered. Note that an empty line is only shown if there
7140 are at least `org-cycle-separator-lines' empty lines before the headline."
7141 (when (/= org-cycle-separator-lines 0)
7142 (save-excursion
7143 (let* ((n (abs org-cycle-separator-lines))
7144 (re (cond
7145 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7146 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7147 (t (let ((ns (number-to-string (- n 2))))
7148 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7149 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7150 beg end)
7151 (cond
7152 ((memq state '(overview contents t))
7153 (setq beg (point-min) end (point-max)))
7154 ((memq state '(children folded))
7155 (setq beg (point)
7156 end (progn (org-end-of-subtree t t)
7157 (line-beginning-position 2)))))
7158 (when beg
7159 (goto-char beg)
7160 (while (re-search-forward re end t)
7161 (unless (get-char-property (match-end 1) 'invisible)
7162 (let ((e (match-end 1))
7163 (b (if (>= org-cycle-separator-lines 0)
7164 (match-beginning 1)
7165 (save-excursion
7166 (goto-char (match-beginning 0))
7167 (skip-chars-backward " \t\n")
7168 (line-end-position)))))
7169 (outline-flag-region b e nil))))))))
7170 ;; Never hide empty lines at the end of the file.
7171 (save-excursion
7172 (goto-char (point-max))
7173 (outline-previous-heading)
7174 (outline-end-of-heading)
7175 (when (and (looking-at "[ \t\n]+")
7176 (= (match-end 0) (point-max)))
7177 (outline-flag-region (point) (match-end 0) nil))))
7179 (defun org-show-empty-lines-in-parent ()
7180 "Move to the parent and re-show empty lines before visible headlines."
7181 (save-excursion
7182 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7183 (org-cycle-show-empty-lines context))))
7185 (defun org-files-list ()
7186 "Return `org-agenda-files' list, plus all open org-mode files.
7187 This is useful for operations that need to scan all of a user's
7188 open and agenda-wise Org files."
7189 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7190 (dolist (buf (buffer-list))
7191 (with-current-buffer buf
7192 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7193 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7194 files))
7196 (defsubst org-entry-beginning-position ()
7197 "Return the beginning position of the current entry."
7198 (save-excursion (org-back-to-heading t) (point)))
7200 (defsubst org-entry-end-position ()
7201 "Return the end position of the current entry."
7202 (save-excursion (outline-next-heading) (point)))
7204 (defun org-cycle-hide-drawers (state &optional exceptions)
7205 "Re-hide all drawers after a visibility state change.
7206 When non-nil, optional argument EXCEPTIONS is a list of strings
7207 specifying which drawers should not be hidden."
7208 (when (and (derived-mode-p 'org-mode)
7209 (not (memq state '(overview folded contents))))
7210 (save-excursion
7211 (let* ((globalp (memq state '(contents all)))
7212 (beg (if globalp (point-min) (point)))
7213 (end (if globalp (point-max)
7214 (if (eq state 'children)
7215 (save-excursion (outline-next-heading) (point))
7216 (org-end-of-subtree t)))))
7217 (goto-char beg)
7218 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7219 (unless (member-ignore-case (match-string 1) exceptions)
7220 (let ((drawer (org-element-at-point)))
7221 (when (memq (org-element-type drawer) '(drawer property-drawer))
7222 (org-flag-drawer t drawer)
7223 ;; Make sure to skip drawer entirely or we might flag
7224 ;; it another time when matching its ending line with
7225 ;; `org-drawer-regexp'.
7226 (goto-char (org-element-property :end drawer))))))))))
7228 (defun org-flag-drawer (flag &optional element)
7229 "When FLAG is non-nil, hide the drawer we are at.
7230 Otherwise make it visible. When optional argument ELEMENT is
7231 a parsed drawer, as returned by `org-element-at-point', hide or
7232 show that drawer instead."
7233 (let ((drawer (or element
7234 (and (save-excursion
7235 (beginning-of-line)
7236 (looking-at-p org-drawer-regexp))
7237 (org-element-at-point)))))
7238 (when (memq (org-element-type drawer) '(drawer property-drawer))
7239 (let ((post (org-element-property :post-affiliated drawer)))
7240 (save-excursion
7241 (outline-flag-region
7242 (progn (goto-char post) (line-end-position))
7243 (progn (goto-char (org-element-property :end drawer))
7244 (skip-chars-backward " \r\t\n")
7245 (line-end-position))
7246 flag))
7247 ;; When the drawer is hidden away, make sure point lies in
7248 ;; a visible part of the buffer.
7249 (when (and flag (> (line-beginning-position) post))
7250 (goto-char post))))))
7252 (defun org-subtree-end-visible-p ()
7253 "Is the end of the current subtree visible?"
7254 (pos-visible-in-window-p
7255 (save-excursion (org-end-of-subtree t) (point))))
7257 (defun org-first-headline-recenter ()
7258 "Move cursor to the first headline and recenter the headline."
7259 (let ((window (get-buffer-window)))
7260 (when window
7261 (goto-char (point-min))
7262 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7263 (set-window-start window (line-beginning-position))))))
7265 ;;; Saving and restoring visibility
7267 (defun org-outline-overlay-data (&optional use-markers)
7268 "Return a list of the locations of all outline overlays.
7269 These are overlays with the `invisible' property value `outline'.
7270 The return value is a list of cons cells, with start and stop
7271 positions for each overlay.
7272 If USE-MARKERS is set, return the positions as markers."
7273 (let (beg end)
7274 (save-excursion
7275 (save-restriction
7276 (widen)
7277 (delq nil
7278 (mapcar (lambda (o)
7279 (when (eq (overlay-get o 'invisible) 'outline)
7280 (setq beg (overlay-start o)
7281 end (overlay-end o))
7282 (and beg end (> end beg)
7283 (if use-markers
7284 (cons (copy-marker beg)
7285 (copy-marker end t))
7286 (cons beg end)))))
7287 (overlays-in (point-min) (point-max))))))))
7289 (defun org-set-outline-overlay-data (data)
7290 "Create visibility overlays for all positions in DATA.
7291 DATA should have been made by `org-outline-overlay-data'."
7292 (org-with-wide-buffer
7293 (outline-show-all)
7294 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7296 ;;; Folding of blocks
7298 (defvar-local org-hide-block-overlays nil
7299 "Overlays hiding blocks.")
7301 (defun org-block-map (function &optional start end)
7302 "Call FUNCTION at the head of all source blocks in the current buffer.
7303 Optional arguments START and END can be used to limit the range."
7304 (let ((start (or start (point-min)))
7305 (end (or end (point-max))))
7306 (save-excursion
7307 (goto-char start)
7308 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7309 (save-excursion
7310 (save-match-data
7311 (goto-char (match-beginning 0))
7312 (funcall function)))))))
7314 (defun org-hide-block-toggle-all ()
7315 "Toggle the visibility of all blocks in the current buffer."
7316 (org-block-map 'org-hide-block-toggle))
7318 (defun org-hide-block-all ()
7319 "Fold all blocks in the current buffer."
7320 (interactive)
7321 (org-show-block-all)
7322 (org-block-map 'org-hide-block-toggle-maybe))
7324 (defun org-show-block-all ()
7325 "Unfold all blocks in the current buffer."
7326 (interactive)
7327 (mapc #'delete-overlay org-hide-block-overlays)
7328 (setq org-hide-block-overlays nil))
7330 (defun org-hide-block-toggle-maybe ()
7331 "Toggle visibility of block at point.
7332 Unlike to `org-hide-block-toggle', this function does not throw
7333 an error. Return a non-nil value when toggling is successful."
7334 (interactive)
7335 (ignore-errors (org-hide-block-toggle)))
7337 (defun org-hide-block-toggle (&optional force)
7338 "Toggle the visibility of the current block.
7339 When optional argument FORCE is `off', make block visible. If it
7340 is non-nil, hide it unconditionally. Throw an error when not at
7341 a block. Return a non-nil value when toggling is successful."
7342 (interactive)
7343 (let ((element (org-element-at-point)))
7344 (unless (memq (org-element-type element)
7345 '(center-block comment-block dynamic-block example-block
7346 export-block quote-block special-block
7347 src-block verse-block))
7348 (user-error "Not at a block"))
7349 (let* ((start (save-excursion
7350 (goto-char (org-element-property :post-affiliated element))
7351 (line-end-position)))
7352 (end (save-excursion
7353 (goto-char (org-element-property :end element))
7354 (skip-chars-backward " \r\t\n")
7355 (line-end-position)))
7356 (overlays (overlays-at start)))
7357 (cond
7358 ;; Do nothing when not before or at the block opening line or
7359 ;; at the block closing line.
7360 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7361 ((and (not (eq force 'off))
7362 (not (memq t (mapcar
7363 (lambda (o)
7364 (eq (overlay-get o 'invisible) 'org-hide-block))
7365 overlays))))
7366 (let ((ov (make-overlay start end)))
7367 (overlay-put ov 'invisible 'org-hide-block)
7368 ;; Make the block accessible to `isearch'.
7369 (overlay-put
7370 ov 'isearch-open-invisible
7371 (lambda (ov)
7372 (when (memq ov org-hide-block-overlays)
7373 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7374 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7375 (delete-overlay ov))))
7376 (push ov org-hide-block-overlays)
7377 ;; When the block is hidden away, make sure point is left in
7378 ;; a visible part of the buffer.
7379 (when (> (line-beginning-position) start)
7380 (goto-char start)
7381 (beginning-of-line))
7382 ;; Signal successful toggling.
7384 ((or (not force) (eq force 'off))
7385 (dolist (ov overlays t)
7386 (when (memq ov org-hide-block-overlays)
7387 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7388 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7389 (delete-overlay ov))))))))
7391 ;; org-tab-after-check-for-cycling-hook
7392 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7393 ;; Remove overlays when changing major mode
7394 (add-hook 'org-mode-hook
7395 (lambda () (add-hook 'change-major-mode-hook
7396 'org-show-block-all 'append 'local)))
7398 ;;; Org-goto
7400 (defvar org-goto-window-configuration nil)
7401 (defvar org-goto-marker nil)
7402 (defvar org-goto-map)
7403 (defun org-goto-map ()
7404 "Set the keymap `org-goto'."
7405 (setq org-goto-map
7406 (let ((map (make-sparse-keymap)))
7407 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7408 mouse-drag-region universal-argument org-occur)))
7409 (dolist (cmd cmds)
7410 (substitute-key-definition cmd cmd map global-map)))
7411 (suppress-keymap map)
7412 (org-defkey map "\C-m" 'org-goto-ret)
7413 (org-defkey map [(return)] 'org-goto-ret)
7414 (org-defkey map [(left)] 'org-goto-left)
7415 (org-defkey map [(right)] 'org-goto-right)
7416 (org-defkey map [(control ?g)] 'org-goto-quit)
7417 (org-defkey map "\C-i" 'org-cycle)
7418 (org-defkey map [(tab)] 'org-cycle)
7419 (org-defkey map [(down)] 'outline-next-visible-heading)
7420 (org-defkey map [(up)] 'outline-previous-visible-heading)
7421 (if org-goto-auto-isearch
7422 (if (fboundp 'define-key-after)
7423 (define-key-after map [t] 'org-goto-local-auto-isearch)
7424 nil)
7425 (org-defkey map "q" 'org-goto-quit)
7426 (org-defkey map "n" 'outline-next-visible-heading)
7427 (org-defkey map "p" 'outline-previous-visible-heading)
7428 (org-defkey map "f" 'outline-forward-same-level)
7429 (org-defkey map "b" 'outline-backward-same-level)
7430 (org-defkey map "u" 'outline-up-heading))
7431 (org-defkey map "/" 'org-occur)
7432 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7433 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7434 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7435 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7436 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7437 map)))
7439 (defconst org-goto-help
7440 "Browse buffer copy, to find location or copy text.%s
7441 RET=jump to location C-g=quit and return to previous location
7442 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7444 (defvar org-goto-start-pos) ; dynamically scoped parameter
7446 (defun org-goto (&optional alternative-interface)
7447 "Look up a different location in the current file, keeping current visibility.
7449 When you want look-up or go to a different location in a
7450 document, the fastest way is often to fold the entire buffer and
7451 then dive into the tree. This method has the disadvantage, that
7452 the previous location will be folded, which may not be what you
7453 want.
7455 This command works around this by showing a copy of the current
7456 buffer in an indirect buffer, in overview mode. You can dive
7457 into the tree in that copy, use org-occur and incremental search
7458 to find a location. When pressing RET or `Q', the command
7459 returns to the original buffer in which the visibility is still
7460 unchanged. After RET it will also jump to the location selected
7461 in the indirect buffer and expose the headline hierarchy above.
7463 With a prefix argument, use the alternative interface: e.g., if
7464 `org-goto-interface' is `outline' use `outline-path-completion'."
7465 (interactive "P")
7466 (org-goto-map)
7467 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7468 (org-refile-use-outline-path t)
7469 (org-refile-target-verify-function nil)
7470 (interface
7471 (if (not alternative-interface)
7472 org-goto-interface
7473 (if (eq org-goto-interface 'outline)
7474 'outline-path-completion
7475 'outline)))
7476 (org-goto-start-pos (point))
7477 (selected-point
7478 (if (eq interface 'outline)
7479 (car (org-get-location (current-buffer) org-goto-help))
7480 (let ((pa (org-refile-get-location "Goto")))
7481 (org-refile-check-position pa)
7482 (nth 3 pa)))))
7483 (if selected-point
7484 (progn
7485 (org-mark-ring-push org-goto-start-pos)
7486 (goto-char selected-point)
7487 (when (or (outline-invisible-p) (org-invisible-p2))
7488 (org-show-context 'org-goto)))
7489 (message "Quit"))))
7491 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7492 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7493 (defvar org-goto-local-auto-isearch-map) ; defined below
7495 (defun org-get-location (_buf help)
7496 "Let the user select a location in current buffer.
7497 This function uses a recursive edit. It returns the selected position
7498 or nil."
7499 (org-no-popups
7500 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7501 (isearch-hide-immediately nil)
7502 (isearch-search-fun-function
7503 (lambda () 'org-goto-local-search-headings))
7504 (org-goto-selected-point org-goto-exit-command))
7505 (save-excursion
7506 (save-window-excursion
7507 (delete-other-windows)
7508 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7509 (pop-to-buffer-same-window
7510 (condition-case nil
7511 (make-indirect-buffer (current-buffer) "*org-goto*")
7512 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7513 (with-output-to-temp-buffer "*Org Help*"
7514 (princ (format help (if org-goto-auto-isearch
7515 " Just type for auto-isearch."
7516 " n/p/f/b/u to navigate, q to quit."))))
7517 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7518 (setq buffer-read-only nil)
7519 (let ((org-startup-truncated t)
7520 (org-startup-folded nil)
7521 (org-startup-align-all-tables nil))
7522 (org-mode)
7523 (org-overview))
7524 (setq buffer-read-only t)
7525 (if (and (boundp 'org-goto-start-pos)
7526 (integer-or-marker-p org-goto-start-pos))
7527 (progn (goto-char org-goto-start-pos)
7528 (when (outline-invisible-p)
7529 (org-show-set-visibility 'lineage)))
7530 (goto-char (point-min)))
7531 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7532 (message "Select location and press RET")
7533 (use-local-map org-goto-map)
7534 (recursive-edit)))
7535 (kill-buffer "*org-goto*")
7536 (cons org-goto-selected-point org-goto-exit-command))))
7538 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7539 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7540 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7541 (if (fboundp 'isearch-other-control-char)
7542 (progn
7543 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7544 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7545 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7546 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7547 (define-key org-goto-local-auto-isearch-map [return] nil))
7549 (defun org-goto-local-search-headings (string bound noerror)
7550 "Search and make sure that any matches are in headlines."
7551 (catch 'return
7552 (while (if isearch-forward
7553 (search-forward string bound noerror)
7554 (search-backward string bound noerror))
7555 (when (save-match-data
7556 (and (save-excursion
7557 (beginning-of-line)
7558 (looking-at org-complex-heading-regexp))
7559 (or (not (match-beginning 5))
7560 (< (point) (match-beginning 5)))))
7561 (throw 'return (point))))))
7563 (defun org-goto-local-auto-isearch ()
7564 "Start isearch."
7565 (interactive)
7566 (goto-char (point-min))
7567 (let ((keys (this-command-keys)))
7568 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7569 (isearch-mode t)
7570 (isearch-process-search-char (string-to-char keys)))))
7572 (defun org-goto-ret (&optional _arg)
7573 "Finish `org-goto' by going to the new location."
7574 (interactive "P")
7575 (setq org-goto-selected-point (point))
7576 (setq org-goto-exit-command 'return)
7577 (throw 'exit nil))
7579 (defun org-goto-left ()
7580 "Finish `org-goto' by going to the new location."
7581 (interactive)
7582 (if (org-at-heading-p)
7583 (progn
7584 (beginning-of-line 1)
7585 (setq org-goto-selected-point (point)
7586 org-goto-exit-command 'left)
7587 (throw 'exit nil))
7588 (user-error "Not on a heading")))
7590 (defun org-goto-right ()
7591 "Finish `org-goto' by going to the new location."
7592 (interactive)
7593 (if (org-at-heading-p)
7594 (progn
7595 (setq org-goto-selected-point (point)
7596 org-goto-exit-command 'right)
7597 (throw 'exit nil))
7598 (user-error "Not on a heading")))
7600 (defun org-goto-quit ()
7601 "Finish `org-goto' without cursor motion."
7602 (interactive)
7603 (setq org-goto-selected-point nil)
7604 (setq org-goto-exit-command 'quit)
7605 (throw 'exit nil))
7607 ;;; Indirect buffer display of subtrees
7609 (defvar org-indirect-dedicated-frame nil
7610 "This is the frame being used for indirect tree display.")
7611 (defvar org-last-indirect-buffer nil)
7613 (defun org-tree-to-indirect-buffer (&optional arg)
7614 "Create indirect buffer and narrow it to current subtree.
7615 With a numerical prefix ARG, go up to this level and then take that tree.
7616 If ARG is negative, go up that many levels.
7618 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7619 indirect buffer previously made with this command, to avoid proliferation of
7620 indirect buffers. However, when you call the command with a \
7621 \\[universal-argument] prefix, or
7622 when `org-indirect-buffer-display' is `new-frame', the last buffer
7623 is kept so that you can work with several indirect buffers at the same time.
7624 If `org-indirect-buffer-display' is `dedicated-frame', the \
7625 \\[universal-argument] prefix also
7626 requests that a new frame be made for the new buffer, so that the dedicated
7627 frame is not changed."
7628 (interactive "P")
7629 (let ((cbuf (current-buffer))
7630 (cwin (selected-window))
7631 (pos (point))
7632 beg end level heading ibuf)
7633 (save-excursion
7634 (org-back-to-heading t)
7635 (when (numberp arg)
7636 (setq level (org-outline-level))
7637 (when (< arg 0) (setq arg (+ level arg)))
7638 (while (> (setq level (org-outline-level)) arg)
7639 (org-up-heading-safe)))
7640 (setq beg (point)
7641 heading (org-get-heading 'no-tags))
7642 (org-end-of-subtree t t)
7643 (when (org-at-heading-p) (backward-char 1))
7644 (setq end (point)))
7645 (when (and (buffer-live-p org-last-indirect-buffer)
7646 (not (eq org-indirect-buffer-display 'new-frame))
7647 (not arg))
7648 (kill-buffer org-last-indirect-buffer))
7649 (setq ibuf (org-get-indirect-buffer cbuf heading)
7650 org-last-indirect-buffer ibuf)
7651 (cond
7652 ((or (eq org-indirect-buffer-display 'new-frame)
7653 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7654 (select-frame (make-frame))
7655 (delete-other-windows)
7656 (pop-to-buffer-same-window ibuf)
7657 (org-set-frame-title heading))
7658 ((eq org-indirect-buffer-display 'dedicated-frame)
7659 (raise-frame
7660 (select-frame (or (and org-indirect-dedicated-frame
7661 (frame-live-p org-indirect-dedicated-frame)
7662 org-indirect-dedicated-frame)
7663 (setq org-indirect-dedicated-frame (make-frame)))))
7664 (delete-other-windows)
7665 (pop-to-buffer-same-window ibuf)
7666 (org-set-frame-title (concat "Indirect: " heading)))
7667 ((eq org-indirect-buffer-display 'current-window)
7668 (pop-to-buffer-same-window ibuf))
7669 ((eq org-indirect-buffer-display 'other-window)
7670 (pop-to-buffer ibuf))
7671 (t (error "Invalid value")))
7672 (narrow-to-region beg end)
7673 (outline-show-all)
7674 (goto-char pos)
7675 (run-hook-with-args 'org-cycle-hook 'all)
7676 (and (window-live-p cwin) (select-window cwin))))
7678 (defun org-get-indirect-buffer (&optional buffer heading)
7679 (setq buffer (or buffer (current-buffer)))
7680 (let ((n 1) (base (buffer-name buffer)) bname)
7681 (while (buffer-live-p
7682 (get-buffer
7683 (setq bname
7684 (concat base "-"
7685 (if heading (concat heading "-" (number-to-string n))
7686 (number-to-string n))))))
7687 (setq n (1+ n)))
7688 (condition-case nil
7689 (make-indirect-buffer buffer bname 'clone)
7690 (error (make-indirect-buffer buffer bname)))))
7692 (defun org-set-frame-title (title)
7693 "Set the title of the current frame to the string TITLE."
7694 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7696 ;;;; Structure editing
7698 ;;; Inserting headlines
7700 (defun org--line-empty-p (n)
7701 "Is the Nth next line empty?
7703 Counts the current line as N = 1 and the previous line as N = 0;
7704 see `beginning-of-line'."
7705 (save-excursion
7706 (and (not (bobp))
7707 (or (beginning-of-line n) t)
7708 (save-match-data
7709 (looking-at "[ \t]*$")))))
7711 (defun org-previous-line-empty-p ()
7712 "Is the previous line a blank line?
7713 When NEXT is non-nil, check the next line instead."
7714 (org--line-empty-p 0))
7716 (defun org-next-line-empty-p ()
7717 "Is the previous line a blank line?
7718 When NEXT is non-nil, check the next line instead."
7719 (org--line-empty-p 2))
7721 (defun org-insert-heading (&optional arg invisible-ok top)
7722 "Insert a new heading or an item with the same depth at point.
7724 If point is at the beginning of a heading or a list item, insert
7725 a new heading or a new item above the current one. If point is
7726 at the beginning of a normal line, turn the line into a heading.
7728 If point is in the middle of a headline or a list item, split the
7729 headline or the item and create a new headline/item with the text
7730 in the current line after point \(see `org-M-RET-may-split-line'
7731 on how to modify this behavior).
7733 With one universal prefix argument, set the user option
7734 `org-insert-heading-respect-content' to t for the duration of
7735 the command. This modifies the behavior described above in this
7736 ways: on list items and at the beginning of normal lines, force
7737 the insertion of a heading after the current subtree.
7739 With two universal prefix arguments, insert the heading at the
7740 end of the grandparent subtree. For example, if point is within
7741 a 2nd-level heading, then it will insert a 2nd-level heading at
7742 the end of the 1st-level parent heading.
7744 If point is at the beginning of a headline, insert a sibling
7745 before the current headline. If point is not at the beginning,
7746 split the line and create a new headline with the text in the
7747 current line after point \(see `org-M-RET-may-split-line' on how
7748 to modify this behavior).
7750 If point is at the beginning of a normal line, turn this line
7751 into a heading.
7753 When INVISIBLE-OK is set, stop at invisible headlines when going
7754 back. This is important for non-interactive uses of the
7755 command.
7757 When optional argument TOP is non-nil, insert a level 1 heading,
7758 unconditionally."
7759 (interactive "P")
7760 (let ((itemp (and (not top) (org-in-item-p)))
7761 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7762 (respect-content (or org-insert-heading-respect-content
7763 (equal arg '(4))))
7764 (initial-content ""))
7766 (cond
7768 ((or (= (buffer-size) 0)
7769 (and (not (save-excursion
7770 (and (ignore-errors (org-back-to-heading invisible-ok))
7771 (org-at-heading-p))))
7772 (or arg (not itemp))))
7773 ;; At beginning of buffer or so high up that only a heading
7774 ;; makes sense.
7775 (cond ((and (bolp) (not respect-content)) (insert "* "))
7776 ((not respect-content)
7777 (unless may-split (end-of-line))
7778 (insert "\n* "))
7779 ((re-search-forward org-outline-regexp-bol nil t)
7780 (beginning-of-line)
7781 (insert "* \n")
7782 (backward-char))
7783 (t (goto-char (point-max))
7784 (insert "\n* ")))
7785 (run-hooks 'org-insert-heading-hook))
7787 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7790 ;; Maybe move at the end of the subtree
7791 (when (equal arg '(16))
7792 (org-up-heading-safe)
7793 (org-end-of-subtree t))
7794 ;; Insert a heading
7795 (save-restriction
7796 (widen)
7797 (let* ((level nil)
7798 (on-heading (org-at-heading-p))
7799 (empty-line-p (if on-heading
7800 (org-previous-line-empty-p)
7801 ;; We will decide later
7802 nil))
7803 ;; Get a level string to fall back on.
7804 (fix-level
7805 (if (org-before-first-heading-p) "*"
7806 (save-excursion
7807 (org-back-to-heading t)
7808 (when (org-previous-line-empty-p) (setq empty-line-p t))
7809 (looking-at org-outline-regexp)
7810 (make-string (1- (length (match-string 0))) ?*))))
7811 (stars
7812 (save-excursion
7813 (condition-case nil
7814 (if top "* "
7815 (org-back-to-heading invisible-ok)
7816 (when (and (not on-heading)
7817 (featurep 'org-inlinetask)
7818 (integerp org-inlinetask-min-level)
7819 (>= (length (match-string 0))
7820 org-inlinetask-min-level))
7821 ;; Find a heading level before the inline
7822 ;; task.
7823 (while (and (setq level (org-up-heading-safe))
7824 (>= level org-inlinetask-min-level)))
7825 (if (org-at-heading-p)
7826 (org-back-to-heading invisible-ok)
7827 (error "This should not happen")))
7828 (unless (and (save-excursion
7829 (save-match-data
7830 (org-backward-heading-same-level
7831 1 invisible-ok))
7832 (= (point) (match-beginning 0)))
7833 (not (org-next-line-empty-p)))
7834 (setq empty-line-p (or empty-line-p
7835 (org-previous-line-empty-p))))
7836 (match-string 0))
7837 (error (or fix-level "* ")))))
7838 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7839 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7841 ;; If we insert after content, move there and clean up
7842 ;; whitespace.
7843 (when (and respect-content
7844 (not (looking-at-p org-outline-regexp-bol)))
7845 (if (not (org-before-first-heading-p))
7846 (org-end-of-subtree nil t)
7847 (re-search-forward org-outline-regexp-bol)
7848 (beginning-of-line 0))
7849 (skip-chars-backward " \r\t\n")
7850 (and (not (looking-back "^\\*+" (line-beginning-position)))
7851 (looking-at "[ \t]+") (replace-match ""))
7852 (unless (eobp) (forward-char 1))
7853 (when (looking-at "^\\*")
7854 (unless (bobp) (backward-char 1))
7855 (insert "\n")))
7857 ;; If we are splitting, grab the text that should be moved
7858 ;; to the new headline.
7859 (when may-split
7860 (if (org-at-heading-p)
7861 ;; This is a heading: split intelligently (keeping
7862 ;; tags).
7863 (let ((pos (point)))
7864 (beginning-of-line)
7865 (unless (looking-at org-complex-heading-regexp)
7866 (error "This should not happen"))
7867 (when (and (match-beginning 4)
7868 (> pos (match-beginning 4))
7869 (< pos (match-end 4)))
7870 (setq initial-content (buffer-substring pos (match-end 4)))
7871 (goto-char pos)
7872 (delete-region (point) (match-end 4))
7873 (if (looking-at "[ \t]*$")
7874 (replace-match "")
7875 (insert (make-string (length initial-content) ?\s)))
7876 (setq initial-content (org-trim initial-content)))
7877 (goto-char pos))
7878 ;; A normal line.
7879 (setq initial-content
7880 (org-trim
7881 (delete-and-extract-region (point) (line-end-position))))))
7883 ;; If we are at the beginning of the line, insert before it.
7884 ;; Otherwise, after it.
7885 (cond
7886 ((and (bolp) (looking-at "[ \t]*$")))
7887 ((bolp) (save-excursion (insert "\n")))
7888 (t (end-of-line)
7889 (insert "\n")))
7891 ;; Insert the new heading
7892 (insert stars)
7893 (just-one-space)
7894 (insert initial-content)
7895 (unless (and blank (org-previous-line-empty-p))
7896 (org-N-empty-lines-before-current (if blank 1 0)))
7897 ;; Adjust visibility, which may be messed up if we removed
7898 ;; blank lines while previous entry was hidden.
7899 (let ((bol (line-beginning-position)))
7900 (dolist (o (overlays-at (1- bol)))
7901 (when (and (eq (overlay-get o 'invisible) 'outline)
7902 (eq (overlay-end o) bol))
7903 (move-overlay o (overlay-start o) (1- bol)))))
7904 (run-hooks 'org-insert-heading-hook)))))))
7906 (defun org-N-empty-lines-before-current (N)
7907 "Make the number of empty lines before current exactly N.
7908 So this will delete or add empty lines."
7909 (save-excursion
7910 (beginning-of-line)
7911 (let ((p (point)))
7912 (skip-chars-backward " \r\t\n")
7913 (unless (bolp) (forward-line))
7914 (delete-region (point) p))
7915 (when (> N 0) (insert (make-string N ?\n)))))
7917 (defun org-get-heading (&optional no-tags no-todo)
7918 "Return the heading of the current entry, without the stars.
7919 When NO-TAGS is non-nil, don't include tags.
7920 When NO-TODO is non-nil, don't include TODO keywords."
7921 (save-excursion
7922 (org-back-to-heading t)
7923 (let ((case-fold-search nil))
7924 (cond
7925 ((and no-tags no-todo)
7926 (looking-at org-complex-heading-regexp)
7927 (match-string 4))
7928 (no-tags
7929 (looking-at (concat org-outline-regexp
7930 "\\(.*?\\)"
7931 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7932 (match-string 1))
7933 (no-todo
7934 (looking-at org-todo-line-regexp)
7935 (match-string 3))
7936 (t (looking-at org-heading-regexp)
7937 (match-string 2))))))
7939 (defvar orgstruct-mode) ; defined below
7941 (defun org-heading-components ()
7942 "Return the components of the current heading.
7943 This is a list with the following elements:
7944 - the level as an integer
7945 - the reduced level, different if `org-odd-levels-only' is set.
7946 - the TODO keyword, or nil
7947 - the priority character, like ?A, or nil if no priority is given
7948 - the headline text itself, or the tags string if no headline text
7949 - the tags string, or nil."
7950 (save-excursion
7951 (org-back-to-heading t)
7952 (when (let (case-fold-search)
7953 (looking-at
7954 (if orgstruct-mode
7955 org-heading-regexp
7956 org-complex-heading-regexp)))
7957 (if orgstruct-mode
7958 (list (length (match-string 1))
7959 (org-reduced-level (length (match-string 1)))
7962 (match-string 2)
7963 nil)
7964 (list (length (match-string 1))
7965 (org-reduced-level (length (match-string 1)))
7966 (match-string-no-properties 2)
7967 (and (match-end 3) (aref (match-string 3) 2))
7968 (match-string-no-properties 4)
7969 (match-string-no-properties 5))))))
7971 (defun org-get-entry ()
7972 "Get the entry text, after heading, entire subtree."
7973 (save-excursion
7974 (org-back-to-heading t)
7975 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7977 (defun org-edit-headline (&optional heading)
7978 "Edit the current headline.
7979 Set it to HEADING when provided."
7980 (interactive)
7981 (org-with-wide-buffer
7982 (org-back-to-heading t)
7983 (when (looking-at org-complex-heading-regexp)
7984 (let* ((old (match-string-no-properties 4))
7985 (new (save-match-data
7986 (org-trim (or heading (read-string "Edit: " old))))))
7987 (unless (equal old new)
7988 (if old (replace-match new t t nil 4)
7989 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7990 (insert " " new))
7991 (org-set-tags nil t)
7992 (when (looking-at "[ \t]*$") (replace-match "")))))))
7994 (defun org-insert-heading-after-current ()
7995 "Insert a new heading with same level as current, after current subtree."
7996 (interactive)
7997 (org-back-to-heading)
7998 (org-insert-heading)
7999 (org-move-subtree-down)
8000 (end-of-line 1))
8002 (defun org-insert-heading-respect-content (&optional invisible-ok)
8003 "Insert heading with `org-insert-heading-respect-content' set to t."
8004 (interactive)
8005 (org-insert-heading '(4) invisible-ok))
8007 (defun org-insert-todo-heading-respect-content (&optional force-state)
8008 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8009 (interactive)
8010 (org-insert-todo-heading force-state '(4)))
8012 (defun org-insert-todo-heading (arg &optional force-heading)
8013 "Insert a new heading with the same level and TODO state as current heading.
8014 If the heading has no TODO state, or if the state is DONE, use the first
8015 state (TODO by default). Also with one prefix arg, force first state. With
8016 two prefix args, force inserting at the end of the parent subtree."
8017 (interactive "P")
8018 (when (or force-heading (not (org-insert-item 'checkbox)))
8019 (org-insert-heading (or (and (equal arg '(16)) '(16))
8020 force-heading))
8021 (save-excursion
8022 (org-back-to-heading)
8023 (outline-previous-heading)
8024 (looking-at org-todo-line-regexp))
8025 (let*
8026 ((new-mark-x
8027 (if (or (equal arg '(4))
8028 (not (match-beginning 2))
8029 (member (match-string 2) org-done-keywords))
8030 (car org-todo-keywords-1)
8031 (match-string 2)))
8032 (new-mark
8034 (run-hook-with-args-until-success
8035 'org-todo-get-default-hook new-mark-x nil)
8036 new-mark-x)))
8037 (beginning-of-line 1)
8038 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8039 (if org-treat-insert-todo-heading-as-state-change
8040 (org-todo new-mark)
8041 (insert new-mark " "))))
8042 (when org-provide-todo-statistics
8043 (org-update-parent-todo-statistics))))
8045 (defun org-insert-subheading (arg)
8046 "Insert a new subheading and demote it.
8047 Works for outline headings and for plain lists alike."
8048 (interactive "P")
8049 (org-insert-heading arg)
8050 (cond
8051 ((org-at-heading-p) (org-do-demote))
8052 ((org-at-item-p) (org-indent-item))))
8054 (defun org-insert-todo-subheading (arg)
8055 "Insert a new subheading with TODO keyword or checkbox and demote it.
8056 Works for outline headings and for plain lists alike."
8057 (interactive "P")
8058 (org-insert-todo-heading arg)
8059 (cond
8060 ((org-at-heading-p) (org-do-demote))
8061 ((org-at-item-p) (org-indent-item))))
8063 ;;; Promotion and Demotion
8065 (defvar org-after-demote-entry-hook nil
8066 "Hook run after an entry has been demoted.
8067 The cursor will be at the beginning of the entry.
8068 When a subtree is being demoted, the hook will be called for each node.")
8070 (defvar org-after-promote-entry-hook nil
8071 "Hook run after an entry has been promoted.
8072 The cursor will be at the beginning of the entry.
8073 When a subtree is being promoted, the hook will be called for each node.")
8075 (defun org-promote-subtree ()
8076 "Promote the entire subtree.
8077 See also `org-promote'."
8078 (interactive)
8079 (save-excursion
8080 (org-with-limited-levels (org-map-tree 'org-promote)))
8081 (org-fix-position-after-promote))
8083 (defun org-demote-subtree ()
8084 "Demote the entire subtree.
8085 See `org-demote' and `org-promote'."
8086 (interactive)
8087 (save-excursion
8088 (org-with-limited-levels (org-map-tree 'org-demote)))
8089 (org-fix-position-after-promote))
8091 (defun org-do-promote ()
8092 "Promote the current heading higher up the tree.
8093 If the region is active in `transient-mark-mode', promote all
8094 headings in the region."
8095 (interactive)
8096 (save-excursion
8097 (if (org-region-active-p)
8098 (org-map-region 'org-promote (region-beginning) (region-end))
8099 (org-promote)))
8100 (org-fix-position-after-promote))
8102 (defun org-do-demote ()
8103 "Demote the current heading lower down the tree.
8104 If the region is active in `transient-mark-mode', demote all
8105 headings in the region."
8106 (interactive)
8107 (save-excursion
8108 (if (org-region-active-p)
8109 (org-map-region 'org-demote (region-beginning) (region-end))
8110 (org-demote)))
8111 (org-fix-position-after-promote))
8113 (defun org-fix-position-after-promote ()
8114 "Fix cursor position and indentation after demoting/promoting."
8115 (let ((pos (point)))
8116 (when (save-excursion
8117 (beginning-of-line 1)
8118 (looking-at org-todo-line-regexp)
8119 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8120 (cond ((eobp) (insert " "))
8121 ((eolp) (insert " "))
8122 ((equal (char-after) ?\ ) (forward-char 1))))))
8124 (defun org-current-level ()
8125 "Return the level of the current entry, or nil if before the first headline.
8126 The level is the number of stars at the beginning of the
8127 headline. Use `org-reduced-level' to remove the effect of
8128 `org-odd-levels'. Unlike to `org-outline-level', this function
8129 ignores inlinetasks."
8130 (let ((level (org-with-limited-levels (org-outline-level))))
8131 (and (> level 0) level)))
8133 (defun org-get-previous-line-level ()
8134 "Return the outline depth of the last headline before the current line.
8135 Returns 0 for the first headline in the buffer, and nil if before the
8136 first headline."
8137 (and (org-current-level)
8138 (or (and (/= (line-beginning-position) (point-min))
8139 (save-excursion (beginning-of-line 0) (org-current-level)))
8140 0)))
8142 (defun org-reduced-level (l)
8143 "Compute the effective level of a heading.
8144 This takes into account the setting of `org-odd-levels-only'."
8145 (cond
8146 ((zerop l) 0)
8147 (org-odd-levels-only (1+ (floor (/ l 2))))
8148 (t l)))
8150 (defun org-level-increment ()
8151 "Return the number of stars that will be added or removed at a
8152 time to headlines when structure editing, based on the value of
8153 `org-odd-levels-only'."
8154 (if org-odd-levels-only 2 1))
8156 (defun org-get-valid-level (level &optional change)
8157 "Rectify a level change under the influence of `org-odd-levels-only'
8158 LEVEL is a current level, CHANGE is by how much the level should be
8159 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8160 even level numbers will become the next higher odd number."
8161 (if org-odd-levels-only
8162 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8163 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8164 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8165 (max 1 (+ level (or change 0)))))
8167 (defun org-promote ()
8168 "Promote the current heading higher up the tree."
8169 (org-with-wide-buffer
8170 (org-back-to-heading t)
8171 (let* ((after-change-functions (remq 'flyspell-after-change-function
8172 after-change-functions))
8173 (level (save-match-data (funcall outline-level)))
8174 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8175 (diff (abs (- level (length up-head) -1))))
8176 (cond
8177 ((and (= level 1) org-allow-promoting-top-level-subtree)
8178 (replace-match "# " nil t))
8179 ((= level 1)
8180 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8181 (t (replace-match up-head nil t)))
8182 (unless (= level 1)
8183 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8184 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8185 (run-hooks 'org-after-promote-entry-hook))))
8187 (defun org-demote ()
8188 "Demote the current heading lower down the tree."
8189 (org-with-wide-buffer
8190 (org-back-to-heading t)
8191 (let* ((after-change-functions (remq 'flyspell-after-change-function
8192 after-change-functions))
8193 (level (save-match-data (funcall outline-level)))
8194 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8195 (diff (abs (- level (length down-head) -1))))
8196 (replace-match down-head nil t)
8197 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8198 (when org-adapt-indentation (org-fixup-indentation diff))
8199 (run-hooks 'org-after-demote-entry-hook))))
8201 (defun org-cycle-level ()
8202 "Cycle the level of an empty headline through possible states.
8203 This goes first to child, then to parent, level, then up the hierarchy.
8204 After top level, it switches back to sibling level."
8205 (interactive)
8206 (let ((org-adapt-indentation nil))
8207 (when (org-point-at-end-of-empty-headline)
8208 (setq this-command 'org-cycle-level) ; Only needed for caching
8209 (let ((cur-level (org-current-level))
8210 (prev-level (org-get-previous-line-level)))
8211 (cond
8212 ;; If first headline in file, promote to top-level.
8213 ((= prev-level 0)
8214 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8215 do (org-do-promote)))
8216 ;; If same level as prev, demote one.
8217 ((= prev-level cur-level)
8218 (org-do-demote))
8219 ;; If parent is top-level, promote to top level if not already.
8220 ((= prev-level 1)
8221 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8222 do (org-do-promote)))
8223 ;; If top-level, return to prev-level.
8224 ((= cur-level 1)
8225 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8226 do (org-do-demote)))
8227 ;; If less than prev-level, promote one.
8228 ((< cur-level prev-level)
8229 (org-do-promote))
8230 ;; If deeper than prev-level, promote until higher than
8231 ;; prev-level.
8232 ((> cur-level prev-level)
8233 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8234 do (org-do-promote))))
8235 t))))
8237 (defun org-map-tree (fun)
8238 "Call FUN for every heading underneath the current one."
8239 (org-back-to-heading)
8240 (let ((level (funcall outline-level)))
8241 (save-excursion
8242 (funcall fun)
8243 (while (and (progn
8244 (outline-next-heading)
8245 (> (funcall outline-level) level))
8246 (not (eobp)))
8247 (funcall fun)))))
8249 (defun org-map-region (fun beg end)
8250 "Call FUN for every heading between BEG and END."
8251 (let ((org-ignore-region t))
8252 (save-excursion
8253 (setq end (copy-marker end))
8254 (goto-char beg)
8255 (when (and (re-search-forward org-outline-regexp-bol nil t)
8256 (< (point) end))
8257 (funcall fun))
8258 (while (and (progn
8259 (outline-next-heading)
8260 (< (point) end))
8261 (not (eobp)))
8262 (funcall fun)))))
8264 (defun org-fixup-indentation (diff)
8265 "Change the indentation in the current entry by DIFF.
8267 DIFF is an integer. Indentation is done according to the
8268 following rules:
8270 - Planning information and property drawers are always indented
8271 according to the new level of the headline;
8273 - Footnote definitions and their contents are ignored;
8275 - Inlinetasks' boundaries are not shifted;
8277 - Empty lines are ignored;
8279 - Other lines' indentation are shifted by DIFF columns, unless
8280 it would introduce a structural change in the document, in
8281 which case no shifting is done at all.
8283 Assume point is at a heading or an inlinetask beginning."
8284 (org-with-wide-buffer
8285 (narrow-to-region (line-beginning-position)
8286 (save-excursion
8287 (if (org-with-limited-levels (org-at-heading-p))
8288 (org-with-limited-levels (outline-next-heading))
8289 (org-inlinetask-goto-end))
8290 (point)))
8291 (forward-line)
8292 ;; Indent properly planning info and property drawer.
8293 (when (looking-at-p org-planning-line-re)
8294 (org-indent-line)
8295 (forward-line))
8296 (when (looking-at org-property-drawer-re)
8297 (goto-char (match-end 0))
8298 (forward-line)
8299 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8300 (catch 'no-shift
8301 (when (zerop diff) (throw 'no-shift nil))
8302 ;; If DIFF is negative, first check if a shift is possible at all
8303 ;; (e.g., it doesn't break structure). This can only happen if
8304 ;; some contents are not properly indented.
8305 (let ((case-fold-search t))
8306 (when (< diff 0)
8307 (let ((diff (- diff))
8308 (forbidden-re (concat org-outline-regexp
8309 "\\|"
8310 (substring org-footnote-definition-re 1))))
8311 (save-excursion
8312 (while (not (eobp))
8313 (cond
8314 ((looking-at-p "[ \t]*$") (forward-line))
8315 ((and (looking-at-p org-footnote-definition-re)
8316 (let ((e (org-element-at-point)))
8317 (and (eq (org-element-type e) 'footnote-definition)
8318 (goto-char (org-element-property :end e))))))
8319 ((looking-at-p org-outline-regexp) (forward-line))
8320 ;; Give up if shifting would move before column 0 or
8321 ;; if it would introduce a headline or a footnote
8322 ;; definition.
8324 (skip-chars-forward " \t")
8325 (let ((ind (current-column)))
8326 (when (or (< ind diff)
8327 (and (= ind diff) (looking-at-p forbidden-re)))
8328 (throw 'no-shift nil)))
8329 ;; Ignore contents of example blocks and source
8330 ;; blocks if their indentation is meant to be
8331 ;; preserved. Jump to block's closing line.
8332 (beginning-of-line)
8333 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8334 (let ((e (org-element-at-point)))
8335 (and (memq (org-element-type e)
8336 '(example-block src-block))
8337 (or org-src-preserve-indentation
8338 (org-element-property :preserve-indent e))
8339 (goto-char (org-element-property :end e))
8340 (progn (skip-chars-backward " \r\t\n")
8341 (beginning-of-line)
8342 t))))
8343 (forward-line))))))))
8344 ;; Shift lines but footnote definitions, inlinetasks boundaries
8345 ;; by DIFF. Also skip contents of source or example blocks
8346 ;; when indentation is meant to be preserved.
8347 (while (not (eobp))
8348 (cond
8349 ((and (looking-at-p org-footnote-definition-re)
8350 (let ((e (org-element-at-point)))
8351 (and (eq (org-element-type e) 'footnote-definition)
8352 (goto-char (org-element-property :end e))))))
8353 ((looking-at-p org-outline-regexp) (forward-line))
8354 ((looking-at-p "[ \t]*$") (forward-line))
8356 (indent-line-to (+ (org-get-indentation) diff))
8357 (beginning-of-line)
8358 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8359 (let ((e (org-element-at-point)))
8360 (and (memq (org-element-type e)
8361 '(example-block src-block))
8362 (or org-src-preserve-indentation
8363 (org-element-property :preserve-indent e))
8364 (goto-char (org-element-property :end e))
8365 (progn (skip-chars-backward " \r\t\n")
8366 (beginning-of-line)
8367 t))))
8368 (forward-line)))))))))
8370 (defun org-convert-to-odd-levels ()
8371 "Convert an org-mode file with all levels allowed to one with odd levels.
8372 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8373 level 5 etc."
8374 (interactive)
8375 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8376 (let ((outline-level 'org-outline-level)
8377 (org-odd-levels-only nil) n)
8378 (save-excursion
8379 (goto-char (point-min))
8380 (while (re-search-forward "^\\*\\*+ " nil t)
8381 (setq n (- (length (match-string 0)) 2))
8382 (while (>= (setq n (1- n)) 0)
8383 (org-demote))
8384 (end-of-line 1))))))
8386 (defun org-convert-to-oddeven-levels ()
8387 "Convert an org-mode file with only odd levels to one with odd/even levels.
8388 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8389 file contains a section with an even level, conversion would
8390 destroy the structure of the file. An error is signaled in this
8391 case."
8392 (interactive)
8393 (goto-char (point-min))
8394 ;; First check if there are no even levels
8395 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8396 (org-show-set-visibility 'canonical)
8397 (error "Not all levels are odd in this file. Conversion not possible"))
8398 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8399 (let ((outline-regexp org-outline-regexp)
8400 (outline-level 'org-outline-level)
8401 (org-odd-levels-only nil) n)
8402 (save-excursion
8403 (goto-char (point-min))
8404 (while (re-search-forward "^\\*\\*+ " nil t)
8405 (setq n (/ (1- (length (match-string 0))) 2))
8406 (while (>= (setq n (1- n)) 0)
8407 (org-promote))
8408 (end-of-line 1))))))
8410 (defun org-tr-level (n)
8411 "Make N odd if required."
8412 (if org-odd-levels-only (1+ (/ n 2)) n))
8414 ;;; Vertical tree motion, cutting and pasting of subtrees
8416 (defun org-move-subtree-up (&optional arg)
8417 "Move the current subtree up past ARG headlines of the same level."
8418 (interactive "p")
8419 (org-move-subtree-down (- (prefix-numeric-value arg))))
8421 (defun org-move-subtree-down (&optional arg)
8422 "Move the current subtree down past ARG headlines of the same level."
8423 (interactive "p")
8424 (setq arg (prefix-numeric-value arg))
8425 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8426 'org-get-last-sibling))
8427 (ins-point (make-marker))
8428 (cnt (abs arg))
8429 (col (current-column))
8430 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8431 ;; Select the tree
8432 (org-back-to-heading)
8433 (setq beg0 (point))
8434 (save-excursion
8435 (setq ne-beg (org-back-over-empty-lines))
8436 (setq beg (point)))
8437 (save-match-data
8438 (save-excursion (outline-end-of-heading)
8439 (setq folded (outline-invisible-p)))
8440 (progn (org-end-of-subtree nil t)
8441 (unless (eobp) (backward-char))))
8442 (outline-next-heading)
8443 (setq ne-end (org-back-over-empty-lines))
8444 (setq end (point))
8445 (goto-char beg0)
8446 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8447 ;; include less whitespace
8448 (save-excursion
8449 (goto-char beg)
8450 (forward-line (- ne-beg ne-end))
8451 (setq beg (point))))
8452 ;; Find insertion point, with error handling
8453 (while (> cnt 0)
8454 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8455 (progn (goto-char beg0)
8456 (user-error "Cannot move past superior level or buffer limit")))
8457 (setq cnt (1- cnt)))
8458 (when (> arg 0)
8459 ;; Moving forward - still need to move over subtree
8460 (org-end-of-subtree t t)
8461 (save-excursion
8462 (org-back-over-empty-lines)
8463 (or (bolp) (newline))))
8464 (setq ne-ins (org-back-over-empty-lines))
8465 (move-marker ins-point (point))
8466 (setq txt (buffer-substring beg end))
8467 (org-save-markers-in-region beg end)
8468 (delete-region beg end)
8469 (org-remove-empty-overlays-at beg)
8470 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8471 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8472 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8473 (let ((bbb (point)))
8474 (insert-before-markers txt)
8475 (org-reinstall-markers-in-region bbb)
8476 (move-marker ins-point bbb))
8477 (or (bolp) (insert "\n"))
8478 (setq ins-end (point))
8479 (goto-char ins-point)
8480 (org-skip-whitespace)
8481 (when (and (< arg 0)
8482 (org-first-sibling-p)
8483 (> ne-ins ne-beg))
8484 ;; Move whitespace back to beginning
8485 (save-excursion
8486 (goto-char ins-end)
8487 (let ((kill-whole-line t))
8488 (kill-line (- ne-ins ne-beg)) (point)))
8489 (insert (make-string (- ne-ins ne-beg) ?\n)))
8490 (move-marker ins-point nil)
8491 (if folded
8492 (outline-hide-subtree)
8493 (org-show-entry)
8494 (org-show-children)
8495 (org-cycle-hide-drawers 'children))
8496 (org-clean-visibility-after-subtree-move)
8497 ;; move back to the initial column we were at
8498 (move-to-column col)))
8500 (defvar org-subtree-clip ""
8501 "Clipboard for cut and paste of subtrees.
8502 This is actually only a copy of the kill, because we use the normal kill
8503 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8505 (defvar org-subtree-clip-folded nil
8506 "Was the last copied subtree folded?
8507 This is used to fold the tree back after pasting.")
8509 (defun org-cut-subtree (&optional n)
8510 "Cut the current subtree into the clipboard.
8511 With prefix arg N, cut this many sequential subtrees.
8512 This is a short-hand for marking the subtree and then cutting it."
8513 (interactive "p")
8514 (org-copy-subtree n 'cut))
8516 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8517 "Copy the current subtree it in the clipboard.
8518 With prefix arg N, copy this many sequential subtrees.
8519 This is a short-hand for marking the subtree and then copying it.
8520 If CUT is non-nil, actually cut the subtree.
8521 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8522 of some markers in the region, even if CUT is non-nil. This is
8523 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8524 (interactive "p")
8525 (let (beg end folded (beg0 (point)))
8526 (if (called-interactively-p 'any)
8527 (org-back-to-heading nil) ; take what looks like a subtree
8528 (org-back-to-heading t)) ; take what is really there
8529 (setq beg (point))
8530 (skip-chars-forward " \t\r\n")
8531 (save-match-data
8532 (if nosubtrees
8533 (outline-next-heading)
8534 (save-excursion (outline-end-of-heading)
8535 (setq folded (outline-invisible-p)))
8536 (ignore-errors (org-forward-heading-same-level (1- n) t))
8537 (org-end-of-subtree t t)))
8538 ;; Include the end of an inlinetask
8539 (when (and (featurep 'org-inlinetask)
8540 (looking-at-p (concat (org-inlinetask-outline-regexp)
8541 "END[ \t]*$")))
8542 (end-of-line))
8543 (setq end (point))
8544 (goto-char beg0)
8545 (when (> end beg)
8546 (setq org-subtree-clip-folded folded)
8547 (when (or cut force-store-markers)
8548 (org-save-markers-in-region beg end))
8549 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8550 (setq org-subtree-clip (current-kill 0))
8551 (message "%s: Subtree(s) with %d characters"
8552 (if cut "Cut" "Copied")
8553 (length org-subtree-clip)))))
8555 (defun org-paste-subtree (&optional level tree for-yank remove)
8556 "Paste the clipboard as a subtree, with modification of headline level.
8557 The entire subtree is promoted or demoted in order to match a new headline
8558 level.
8560 If the cursor is at the beginning of a headline, the same level as
8561 that headline is used to paste the tree.
8563 If not, the new level is derived from the *visible* headings
8564 before and after the insertion point, and taken to be the inferior headline
8565 level of the two. So if the previous visible heading is level 3 and the
8566 next is level 4 (or vice versa), level 4 will be used for insertion.
8567 This makes sure that the subtree remains an independent subtree and does
8568 not swallow low level entries.
8570 You can also force a different level, either by using a numeric prefix
8571 argument, or by inserting the heading marker by hand. For example, if the
8572 cursor is after \"*****\", then the tree will be shifted to level 5.
8574 If optional TREE is given, use this text instead of the kill ring.
8576 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8577 move back over whitespace before inserting, and move point to the end of
8578 the inserted text when done.
8580 When REMOVE is non-nil, remove the subtree from the clipboard."
8581 (interactive "P")
8582 (setq tree (or tree (and kill-ring (current-kill 0))))
8583 (unless (org-kill-is-subtree-p tree)
8584 (user-error "%s"
8585 (substitute-command-keys
8586 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8587 (org-with-limited-levels
8588 (let* ((visp (not (outline-invisible-p)))
8589 (txt tree)
8590 (^re_ "\\(\\*+\\)[ \t]*")
8591 (old-level (if (string-match org-outline-regexp-bol txt)
8592 (- (match-end 0) (match-beginning 0) 1)
8593 -1))
8594 (force-level (cond (level (prefix-numeric-value level))
8595 ((and (looking-at "[ \t]*$")
8596 (string-match
8597 "^\\*+$" (buffer-substring
8598 (point-at-bol) (point))))
8599 (- (match-end 0) (match-beginning 0)))
8600 ((and (bolp)
8601 (looking-at org-outline-regexp))
8602 (- (match-end 0) (point) 1))))
8603 (previous-level (save-excursion
8604 (condition-case nil
8605 (progn
8606 (outline-previous-visible-heading 1)
8607 (if (looking-at ^re_)
8608 (- (match-end 0) (match-beginning 0) 1)
8610 (error 1))))
8611 (next-level (save-excursion
8612 (condition-case nil
8613 (progn
8614 (or (looking-at org-outline-regexp)
8615 (outline-next-visible-heading 1))
8616 (if (looking-at ^re_)
8617 (- (match-end 0) (match-beginning 0) 1)
8619 (error 1))))
8620 (new-level (or force-level (max previous-level next-level)))
8621 (shift (if (or (= old-level -1)
8622 (= new-level -1)
8623 (= old-level new-level))
8625 (- new-level old-level)))
8626 (delta (if (> shift 0) -1 1))
8627 (func (if (> shift 0) 'org-demote 'org-promote))
8628 (org-odd-levels-only nil)
8629 beg end newend)
8630 ;; Remove the forced level indicator
8631 (when force-level
8632 (delete-region (point-at-bol) (point)))
8633 ;; Paste
8634 (beginning-of-line (if (bolp) 1 2))
8635 (setq beg (point))
8636 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8637 (insert-before-markers txt)
8638 (unless (string-match "\n\\'" txt) (insert "\n"))
8639 (setq newend (point))
8640 (org-reinstall-markers-in-region beg)
8641 (setq end (point))
8642 (goto-char beg)
8643 (skip-chars-forward " \t\n\r")
8644 (setq beg (point))
8645 (when (and (outline-invisible-p) visp)
8646 (save-excursion (outline-show-heading)))
8647 ;; Shift if necessary
8648 (unless (= shift 0)
8649 (save-restriction
8650 (narrow-to-region beg end)
8651 (while (not (= shift 0))
8652 (org-map-region func (point-min) (point-max))
8653 (setq shift (+ delta shift)))
8654 (goto-char (point-min))
8655 (setq newend (point-max))))
8656 (when (or (called-interactively-p 'interactive) for-yank)
8657 (message "Clipboard pasted as level %d subtree" new-level))
8658 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8659 kill-ring
8660 (eq org-subtree-clip (current-kill 0))
8661 org-subtree-clip-folded)
8662 ;; The tree was folded before it was killed/copied
8663 (outline-hide-subtree))
8664 (and for-yank (goto-char newend))
8665 (and remove (setq kill-ring (cdr kill-ring))))))
8667 (defun org-kill-is-subtree-p (&optional txt)
8668 "Check if the current kill is an outline subtree, or a set of trees.
8669 Returns nil if kill does not start with a headline, or if the first
8670 headline level is not the largest headline level in the tree.
8671 So this will actually accept several entries of equal levels as well,
8672 which is OK for `org-paste-subtree'.
8673 If optional TXT is given, check this string instead of the current kill."
8674 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8675 (re (org-get-limited-outline-regexp))
8676 (^re (concat "^" re))
8677 (start-level (and kill
8678 (string-match
8679 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8680 kill)
8681 (- (match-end 2) (match-beginning 2) 1)))
8682 (start (1+ (or (match-beginning 2) -1))))
8683 (if (not start-level)
8684 (progn
8685 nil) ;; does not even start with a heading
8686 (catch 'exit
8687 (while (setq start (string-match ^re kill (1+ start)))
8688 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8689 (throw 'exit nil)))
8690 t))))
8692 (defvar org-markers-to-move nil
8693 "Markers that should be moved with a cut-and-paste operation.
8694 Those markers are stored together with their positions relative to
8695 the start of the region.")
8697 (defun org-save-markers-in-region (beg end)
8698 "Check markers in region.
8699 If these markers are between BEG and END, record their position relative
8700 to BEG, so that after moving the block of text, we can put the markers back
8701 into place.
8702 This function gets called just before an entry or tree gets cut from the
8703 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8704 called immediately, to move the markers with the entries."
8705 (setq org-markers-to-move nil)
8706 (when (featurep 'org-clock)
8707 (org-clock-save-markers-for-cut-and-paste beg end))
8708 (when (featurep 'org-agenda)
8709 (org-agenda-save-markers-for-cut-and-paste beg end)))
8711 (defun org-check-and-save-marker (marker beg end)
8712 "Check if MARKER is between BEG and END.
8713 If yes, remember the marker and the distance to BEG."
8714 (when (and (marker-buffer marker)
8715 (equal (marker-buffer marker) (current-buffer))
8716 (>= marker beg) (< marker end))
8717 (push (cons marker (- marker beg)) org-markers-to-move)))
8719 (defun org-reinstall-markers-in-region (beg)
8720 "Move all remembered markers to their position relative to BEG."
8721 (dolist (x org-markers-to-move)
8722 (move-marker (car x) (+ beg (cdr x))))
8723 (setq org-markers-to-move nil))
8725 (defun org-narrow-to-subtree ()
8726 "Narrow buffer to the current subtree."
8727 (interactive)
8728 (save-excursion
8729 (save-match-data
8730 (org-with-limited-levels
8731 (narrow-to-region
8732 (progn (org-back-to-heading t) (point))
8733 (progn (org-end-of-subtree t t)
8734 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8735 (point)))))))
8737 (defun org-narrow-to-block ()
8738 "Narrow buffer to the current block."
8739 (interactive)
8740 (let* ((case-fold-search t)
8741 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8742 "^[ \t]*#\\+end_.*")))
8743 (if blockp
8744 (narrow-to-region (car blockp) (cdr blockp))
8745 (user-error "Not in a block"))))
8747 (defun org-clone-subtree-with-time-shift (n &optional shift)
8748 "Clone the task (subtree) at point N times.
8749 The clones will be inserted as siblings.
8751 In interactive use, the user will be prompted for the number of
8752 clones to be produced. If the entry has a timestamp, the user
8753 will also be prompted for a time shift, which may be a repeater
8754 as used in time stamps, for example `+3d'. To disable this,
8755 you can call the function with a universal prefix argument.
8757 When a valid repeater is given and the entry contains any time
8758 stamps, the clones will become a sequence in time, with time
8759 stamps in the subtree shifted for each clone produced. If SHIFT
8760 is nil or the empty string, time stamps will be left alone. The
8761 ID property of the original subtree is removed.
8763 If the original subtree did contain time stamps with a repeater,
8764 the following will happen:
8765 - the repeater will be removed in each clone
8766 - an additional clone will be produced, with the current, unshifted
8767 date(s) in the entry.
8768 - the original entry will be placed *after* all the clones, with
8769 repeater intact.
8770 - the start days in the repeater in the original entry will be shifted
8771 to past the last clone.
8772 In this way you can spell out a number of instances of a repeating task,
8773 and still retain the repeater to cover future instances of the task.
8775 As described above, N+1 clones are produced when the original
8776 subtree has a repeater. Setting N to 0, then, can be used to
8777 remove the repeater from a subtree and create a shifted clone
8778 with the original repeater."
8779 (interactive "nNumber of clones to produce: ")
8780 (let ((shift
8781 (or shift
8782 (if (and (not (equal current-prefix-arg '(4)))
8783 (save-excursion
8784 (re-search-forward org-ts-regexp-both
8785 (save-excursion
8786 (org-end-of-subtree t)
8787 (point)) t)))
8788 (read-from-minibuffer
8789 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8790 ""))) ;; No time shift
8791 (n-no-remove -1)
8792 (drawer-re org-drawer-regexp)
8793 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8794 beg end template task idprop
8795 shift-n shift-what doshift nmin nmax)
8796 (unless (wholenump n)
8797 (user-error "Invalid number of replications %s" n))
8798 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8799 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8800 shift)))
8801 (user-error "Invalid shift specification %s" shift))
8802 (when doshift
8803 (setq shift-n (string-to-number (match-string 1 shift))
8804 shift-what (cdr (assoc (match-string 2 shift)
8805 '(("d" . day) ("w" . week)
8806 ("m" . month) ("y" . year))))))
8807 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8808 (setq nmin 1 nmax n)
8809 (org-back-to-heading t)
8810 (setq beg (point))
8811 (setq idprop (org-entry-get nil "ID"))
8812 (org-end-of-subtree t t)
8813 (or (bolp) (insert "\n"))
8814 (setq end (point))
8815 (setq template (buffer-substring beg end))
8816 (when (and doshift
8817 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8818 (delete-region beg end)
8819 (setq end beg)
8820 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8821 (goto-char end)
8822 (cl-loop for n from nmin to nmax do
8823 ;; prepare clone
8824 (with-temp-buffer
8825 (insert template)
8826 (org-mode)
8827 (goto-char (point-min))
8828 (org-show-subtree)
8829 (and idprop (if org-clone-delete-id
8830 (org-entry-delete nil "ID")
8831 (org-id-get-create t)))
8832 (unless (= n 0)
8833 (while (re-search-forward org-clock-re nil t)
8834 (kill-whole-line))
8835 (goto-char (point-min))
8836 (while (re-search-forward drawer-re nil t)
8837 (org-remove-empty-drawer-at (point))))
8838 (goto-char (point-min))
8839 (when doshift
8840 (while (re-search-forward org-ts-regexp-both nil t)
8841 (org-timestamp-change (* n shift-n) shift-what))
8842 (unless (= n n-no-remove)
8843 (goto-char (point-min))
8844 (while (re-search-forward org-ts-regexp nil t)
8845 (save-excursion
8846 (goto-char (match-beginning 0))
8847 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8848 (delete-region (match-beginning 1) (match-end 1)))))))
8849 (setq task (buffer-string)))
8850 (insert task))
8851 (goto-char beg)))
8853 ;;; Outline Sorting
8855 (defun org-sort (with-case)
8856 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8857 Optional argument WITH-CASE means sort case-sensitively."
8858 (interactive "P")
8859 (cond
8860 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8861 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8863 (org-call-with-arg 'org-sort-entries with-case))))
8865 (defun org-sort-remove-invisible (s)
8866 "Remove invisible links from string S."
8867 (remove-text-properties 0 (length s) org-rm-props s)
8868 (while (string-match org-bracket-link-regexp s)
8869 (setq s (replace-match (if (match-end 2)
8870 (match-string 3 s)
8871 (match-string 1 s))
8872 t t s)))
8873 (let ((st (format " %s " s)))
8874 (while (string-match org-emph-re st)
8875 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8876 (setq s (substring st 1 -1)))
8879 (defvar org-priority-regexp) ; defined later in the file
8881 (defvar org-after-sorting-entries-or-items-hook nil
8882 "Hook that is run after a bunch of entries or items have been sorted.
8883 When children are sorted, the cursor is in the parent line when this
8884 hook gets called. When a region or a plain list is sorted, the cursor
8885 will be in the first entry of the sorted region/list.")
8887 (defun org-sort-entries
8888 (&optional with-case sorting-type getkey-func compare-func property)
8889 "Sort entries on a certain level of an outline tree.
8890 If there is an active region, the entries in the region are sorted.
8891 Else, if the cursor is before the first entry, sort the top-level items.
8892 Else, the children of the entry at point are sorted.
8894 Sorting can be alphabetically, numerically, by date/time as given by
8895 a time stamp, by a property, by priority order, or by a custom function.
8897 The command prompts for the sorting type unless it has been given to the
8898 function through the SORTING-TYPE argument, which needs to be a character,
8899 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8900 the precise meaning of each character:
8902 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8903 c By creation time, which is assumed to be the first inactive time stamp
8904 at the beginning of a line.
8905 d By deadline date/time.
8906 k By clocking time.
8907 n Numerically, by converting the beginning of the entry/item to a number.
8908 o By order of TODO keywords.
8909 p By priority according to the cookie.
8910 r By the value of a property.
8911 s By scheduled date/time.
8912 t By date/time, either the first active time stamp in the entry, or, if
8913 none exist, by the first inactive one.
8915 Capital letters will reverse the sort order.
8917 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8918 called with point at the beginning of the record. It must return either
8919 a string or a number that should serve as the sorting key for that record.
8921 Comparing entries ignores case by default. However, with an optional argument
8922 WITH-CASE, the sorting considers case as well.
8924 Sorting is done against the visible part of the headlines, it ignores hidden
8925 links.
8927 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8928 (interactive "P")
8929 (let ((case-func (if with-case 'identity 'downcase))
8930 (cmstr
8931 ;; The clock marker is lost when using `sort-subr', let's
8932 ;; store the clocking string.
8933 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8934 (save-excursion
8935 (goto-char org-clock-marker)
8936 (buffer-substring-no-properties (line-beginning-position)
8937 (point)))))
8938 start beg end stars re re2
8939 txt what tmp)
8940 ;; Find beginning and end of region to sort
8941 (cond
8942 ((org-region-active-p)
8943 ;; we will sort the region
8944 (setq end (region-end)
8945 what "region")
8946 (goto-char (region-beginning))
8947 (unless (org-at-heading-p) (outline-next-heading))
8948 (setq start (point)))
8949 ((or (org-at-heading-p)
8950 (ignore-errors (progn (org-back-to-heading) t)))
8951 ;; we will sort the children of the current headline
8952 (org-back-to-heading)
8953 (setq start (point)
8954 end (progn (org-end-of-subtree t t)
8955 (or (bolp) (insert "\n"))
8956 (when (>= (org-back-over-empty-lines) 1)
8957 (forward-line 1))
8958 (point))
8959 what "children")
8960 (goto-char start)
8961 (outline-show-subtree)
8962 (outline-next-heading))
8964 ;; we will sort the top-level entries in this file
8965 (goto-char (point-min))
8966 (or (org-at-heading-p) (outline-next-heading))
8967 (setq start (point))
8968 (goto-char (point-max))
8969 (beginning-of-line 1)
8970 (when (looking-at ".*?\\S-")
8971 ;; File ends in a non-white line
8972 (end-of-line 1)
8973 (insert "\n"))
8974 (setq end (point-max))
8975 (setq what "top-level")
8976 (goto-char start)
8977 (outline-show-all)))
8979 (setq beg (point))
8980 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8982 (looking-at "\\(\\*+\\)")
8983 (setq stars (match-string 1)
8984 re (concat "^" (regexp-quote stars) " +")
8985 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8986 txt (buffer-substring beg end))
8987 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8988 (when (and (not (equal stars "*")) (string-match re2 txt))
8989 (user-error "Region to sort contains a level above the first entry"))
8991 (unless sorting-type
8992 (message
8993 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8994 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8995 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8996 what)
8997 (setq sorting-type (read-char-exclusive))
8999 (unless getkey-func
9000 (and (= (downcase sorting-type) ?f)
9001 (setq getkey-func
9002 (completing-read "Sort using function: "
9003 obarray 'fboundp t nil nil))
9004 (setq getkey-func (intern getkey-func))))
9006 (and (= (downcase sorting-type) ?r)
9007 (not property)
9008 (setq property
9009 (completing-read "Property: "
9010 (mapcar #'list (org-buffer-property-keys t))
9011 nil t))))
9013 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9014 (message "Sorting entries...")
9016 (save-restriction
9017 (narrow-to-region start end)
9018 (let ((dcst (downcase sorting-type))
9019 (case-fold-search nil)
9020 (now (current-time)))
9021 (sort-subr
9022 (/= dcst sorting-type)
9023 ;; This function moves to the beginning character of the "record" to
9024 ;; be sorted.
9025 (lambda nil
9026 (if (re-search-forward re nil t)
9027 (goto-char (match-beginning 0))
9028 (goto-char (point-max))))
9029 ;; This function moves to the last character of the "record" being
9030 ;; sorted.
9031 (lambda nil
9032 (save-match-data
9033 (condition-case nil
9034 (outline-forward-same-level 1)
9035 (error
9036 (goto-char (point-max))))))
9037 ;; This function returns the value that gets sorted against.
9038 (lambda nil
9039 (cond
9040 ((= dcst ?n)
9041 (if (looking-at org-complex-heading-regexp)
9042 (string-to-number (org-sort-remove-invisible (match-string 4)))
9043 nil))
9044 ((= dcst ?a)
9045 (if (looking-at org-complex-heading-regexp)
9046 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9047 nil))
9048 ((= dcst ?k)
9049 (or (get-text-property (point) :org-clock-minutes) 0))
9050 ((= dcst ?t)
9051 (let ((end (save-excursion (outline-next-heading) (point))))
9052 (if (or (re-search-forward org-ts-regexp end t)
9053 (re-search-forward org-ts-regexp-both end t))
9054 (org-time-string-to-seconds (match-string 0))
9055 (float-time now))))
9056 ((= dcst ?c)
9057 (let ((end (save-excursion (outline-next-heading) (point))))
9058 (if (re-search-forward
9059 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9060 end t)
9061 (org-time-string-to-seconds (match-string 0))
9062 (float-time now))))
9063 ((= dcst ?s)
9064 (let ((end (save-excursion (outline-next-heading) (point))))
9065 (if (re-search-forward org-scheduled-time-regexp end t)
9066 (org-time-string-to-seconds (match-string 1))
9067 (float-time now))))
9068 ((= dcst ?d)
9069 (let ((end (save-excursion (outline-next-heading) (point))))
9070 (if (re-search-forward org-deadline-time-regexp end t)
9071 (org-time-string-to-seconds (match-string 1))
9072 (float-time now))))
9073 ((= dcst ?p)
9074 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9075 (string-to-char (match-string 2))
9076 org-default-priority))
9077 ((= dcst ?r)
9078 (or (org-entry-get nil property) ""))
9079 ((= dcst ?o)
9080 (when (looking-at org-complex-heading-regexp)
9081 (let* ((m (match-string 2))
9082 (s (if (member m org-done-keywords) '- '+)))
9083 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9084 ((= dcst ?f)
9085 (if getkey-func
9086 (progn
9087 (setq tmp (funcall getkey-func))
9088 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9089 tmp)
9090 (error "Invalid key function `%s'" getkey-func)))
9091 (t (error "Invalid sorting type `%c'" sorting-type))))
9093 (cond
9094 ((= dcst ?a) 'string<)
9095 ((= dcst ?f) compare-func)
9096 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9097 (run-hooks 'org-after-sorting-entries-or-items-hook)
9098 ;; Reset the clock marker if needed
9099 (when cmstr
9100 (save-excursion
9101 (goto-char start)
9102 (search-forward cmstr nil t)
9103 (move-marker org-clock-marker (point))))
9104 (message "Sorting entries...done")))
9106 ;;; The orgstruct minor mode
9108 ;; Define a minor mode which can be used in other modes in order to
9109 ;; integrate the org-mode structure editing commands.
9111 ;; This is really a hack, because the org-mode structure commands use
9112 ;; keys which normally belong to the major mode. Here is how it
9113 ;; works: The minor mode defines all the keys necessary to operate the
9114 ;; structure commands, but wraps the commands into a function which
9115 ;; tests if the cursor is currently at a headline or a plain list
9116 ;; item. If that is the case, the structure command is used,
9117 ;; temporarily setting many Org-mode variables like regular
9118 ;; expressions for filling etc. However, when any of those keys is
9119 ;; used at a different location, function uses `key-binding' to look
9120 ;; up if the key has an associated command in another currently active
9121 ;; keymap (minor modes, major mode, global), and executes that
9122 ;; command. There might be problems if any of the keys is otherwise
9123 ;; used as a prefix key.
9125 (defcustom orgstruct-heading-prefix-regexp ""
9126 "Regexp that matches the custom prefix of Org headlines in
9127 orgstruct(++)-mode."
9128 :group 'org
9129 :version "24.4"
9130 :package-version '(Org . "8.3")
9131 :type 'regexp)
9132 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9134 (defcustom orgstruct-setup-hook nil
9135 "Hook run after orgstruct-mode-map is filled."
9136 :group 'org
9137 :version "24.4"
9138 :package-version '(Org . "8.0")
9139 :type 'hook)
9141 (defvar orgstruct-initialized nil)
9143 (defvar org-local-vars nil
9144 "List of local variables, for use by `orgstruct-mode'.")
9146 ;;;###autoload
9147 (define-minor-mode orgstruct-mode
9148 "Toggle the minor mode `orgstruct-mode'.
9149 This mode is for using Org-mode structure commands in other
9150 modes. The following keys behave as if Org-mode were active, if
9151 the cursor is on a headline, or on a plain list item (both as
9152 defined by Org-mode)."
9153 nil " OrgStruct" (make-sparse-keymap)
9154 (funcall (if orgstruct-mode
9155 'add-to-invisibility-spec
9156 'remove-from-invisibility-spec)
9157 '(outline . t))
9158 (when orgstruct-mode
9159 (org-load-modules-maybe)
9160 (unless orgstruct-initialized
9161 (orgstruct-setup)
9162 (setq orgstruct-initialized t))))
9164 ;;;###autoload
9165 (defun turn-on-orgstruct ()
9166 "Unconditionally turn on `orgstruct-mode'."
9167 (orgstruct-mode 1))
9169 (defvar-local orgstruct-is-++ nil
9170 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9171 (defvar-local org-fb-vars nil)
9172 (defun orgstruct++-mode (&optional arg)
9173 "Toggle `orgstruct-mode', the enhanced version of it.
9174 In addition to setting orgstruct-mode, this also exports all
9175 indentation and autofilling variables from org-mode into the
9176 buffer. It will also recognize item context in multiline items."
9177 (interactive "P")
9178 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9179 (if (< arg 1)
9180 (progn (orgstruct-mode -1)
9181 (dolist (v org-fb-vars)
9182 (set (make-local-variable (car v))
9183 (if (eq (car-safe (cadr v)) 'quote)
9184 (cl-cadadr v)
9185 (nth 1 v)))))
9186 (orgstruct-mode 1)
9187 (setq org-fb-vars nil)
9188 (unless org-local-vars
9189 (setq org-local-vars (org-get-local-variables)))
9190 (let (var val)
9191 (dolist (x org-local-vars)
9192 (when (string-match
9193 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9194 \\|fill-prefix\\|indent-\\)"
9195 (symbol-name (car x)))
9196 (setq var (car x) val (nth 1 x))
9197 (push (list var `(quote ,(eval var))) org-fb-vars)
9198 (set (make-local-variable var)
9199 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9200 (setq-local orgstruct-is-++ t))))
9202 ;;;###autoload
9203 (defun turn-on-orgstruct++ ()
9204 "Unconditionally turn on `orgstruct++-mode'."
9205 (orgstruct++-mode 1))
9207 (defun orgstruct-error ()
9208 "Error when there is no default binding for a structure key."
9209 (interactive)
9210 (funcall (if (fboundp 'user-error)
9211 'user-error
9212 'error)
9213 "This key has no function outside structure elements"))
9215 (defun orgstruct-setup ()
9216 "Setup orgstruct keymap."
9217 (dolist (cell '((org-demote . t)
9218 (org-metaleft . t)
9219 (org-metaright . t)
9220 (org-promote . t)
9221 (org-shiftmetaleft . t)
9222 (org-shiftmetaright . t)
9223 org-backward-element
9224 org-backward-heading-same-level
9225 org-ctrl-c-ret
9226 org-ctrl-c-minus
9227 org-ctrl-c-star
9228 org-cycle
9229 org-force-cycle-archived
9230 org-forward-heading-same-level
9231 org-insert-heading
9232 org-insert-heading-respect-content
9233 org-kill-note-or-show-branches
9234 org-mark-subtree
9235 org-meta-return
9236 org-metadown
9237 org-metaup
9238 org-narrow-to-subtree
9239 org-promote-subtree
9240 org-reveal
9241 org-shiftdown
9242 org-shiftleft
9243 org-shiftmetadown
9244 org-shiftmetaup
9245 org-shiftright
9246 org-shifttab
9247 org-shifttab
9248 org-shiftup
9249 org-show-children
9250 org-show-subtree
9251 org-sort
9252 org-up-element
9253 outline-demote
9254 outline-next-visible-heading
9255 outline-previous-visible-heading
9256 outline-promote
9257 outline-up-heading))
9258 (let ((f (or (car-safe cell) cell))
9259 (disable-when-heading-prefix (cdr-safe cell)))
9260 (when (fboundp f)
9261 (let ((new-bindings))
9262 (dolist (binding (nconc (where-is-internal f org-mode-map)
9263 (where-is-internal f outline-mode-map)))
9264 (push binding new-bindings)
9265 ;; TODO use local-function-key-map
9266 (dolist (rep '(("<tab>" . "TAB")
9267 ("<return>" . "RET")
9268 ("<escape>" . "ESC")
9269 ("<delete>" . "DEL")))
9270 (setq binding (read-kbd-macro
9271 (let ((case-fold-search))
9272 (replace-regexp-in-string
9273 (regexp-quote (cdr rep))
9274 (car rep)
9275 (key-description binding)))))
9276 (cl-pushnew binding new-bindings :test 'equal)))
9277 (dolist (binding new-bindings)
9278 (let ((key (lookup-key orgstruct-mode-map binding)))
9279 (when (or (not key) (numberp key))
9280 (ignore-errors
9281 (org-defkey orgstruct-mode-map
9282 binding
9283 (orgstruct-make-binding
9284 f binding disable-when-heading-prefix))))))))))
9285 (run-hooks 'orgstruct-setup-hook))
9287 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9288 "Create a function for binding in the structure minor mode.
9289 FUN is the command to call inside a table. KEY is the key that
9290 should be checked in for a command to execute outside of tables.
9291 Non-nil `disable-when-heading-prefix' means to disable the command
9292 if `orgstruct-heading-prefix-regexp' is not empty."
9293 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9294 (let ((nname name)
9295 (i 0))
9296 (while (fboundp (intern nname))
9297 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9298 (setq name (intern nname)))
9299 (eval
9300 (let ((bindings '((org-heading-regexp
9301 (concat "^"
9302 orgstruct-heading-prefix-regexp
9303 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9304 (org-outline-regexp
9305 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9306 (org-outline-regexp-bol
9307 (concat "^" org-outline-regexp))
9308 (outline-regexp org-outline-regexp)
9309 (outline-heading-end-regexp "\n")
9310 (outline-level 'org-outline-level)
9311 (outline-heading-alist))))
9312 `(defun ,name (arg)
9313 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9314 "Outside of structure, run the binding of `"
9315 (key-description key) "'."
9316 (when disable-when-heading-prefix
9317 (concat
9318 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9319 "back to the default binding due to limitations of Org's implementation of\n"
9320 "`" (symbol-name fun) "'.")))
9321 (interactive "p")
9322 (let* ((disable
9323 ,(and disable-when-heading-prefix
9324 '(not (string= orgstruct-heading-prefix-regexp ""))))
9325 (fallback
9326 (or disable
9327 (not
9328 (let* ,bindings
9329 (org-context-p 'headline 'item
9330 ,(when (memq fun
9331 '(org-insert-heading
9332 org-insert-heading-respect-content
9333 org-meta-return))
9334 '(when orgstruct-is-++
9335 'item-body))))))))
9336 (if fallback
9337 (let* ((orgstruct-mode)
9338 (binding
9339 (let ((key ,key))
9340 (catch 'exit
9341 (dolist
9342 (rep
9343 '(nil
9344 ("<\\([^>]*\\)tab>" . "\\1TAB")
9345 ("<\\([^>]*\\)return>" . "\\1RET")
9346 ("<\\([^>]*\\)escape>" . "\\1ESC")
9347 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9348 nil)
9349 (when rep
9350 (setq key (read-kbd-macro
9351 (let ((case-fold-search))
9352 (replace-regexp-in-string
9353 (car rep)
9354 (cdr rep)
9355 (key-description key))))))
9356 (when (key-binding key)
9357 (throw 'exit (key-binding key))))))))
9358 (if (keymapp binding)
9359 (org-set-transient-map binding)
9360 (let ((func (or binding
9361 (unless disable
9362 'orgstruct-error))))
9363 (when func
9364 (call-interactively func)))))
9365 (org-run-like-in-org-mode
9366 (lambda ()
9367 (interactive)
9368 (let* ,bindings
9369 (call-interactively ',fun)))))))))
9370 name))
9372 (defun org-contextualize-keys (alist contexts)
9373 "Return valid elements in ALIST depending on CONTEXTS.
9375 `org-agenda-custom-commands' or `org-capture-templates' are the
9376 values used for ALIST, and `org-agenda-custom-commands-contexts'
9377 or `org-capture-templates-contexts' are the associated contexts
9378 definitions."
9379 (let ((contexts
9380 ;; normalize contexts
9381 (mapcar
9382 (lambda(c) (cond ((listp (cadr c))
9383 (list (car c) (car c) (nth 1 c)))
9384 ((string= "" (cadr c))
9385 (list (car c) (car c) (nth 2 c)))
9386 (t c)))
9387 contexts))
9388 (a alist) r s)
9389 ;; loop over all commands or templates
9390 (dolist (c a)
9391 (let (vrules repl)
9392 (cond
9393 ((not (assoc (car c) contexts))
9394 (push c r))
9395 ((and (assoc (car c) contexts)
9396 (setq vrules (org-contextualize-validate-key
9397 (car c) contexts)))
9398 (mapc (lambda (vr)
9399 (unless (equal (car vr) (cadr vr))
9400 (setq repl vr)))
9401 vrules)
9402 (if (not repl) (push c r)
9403 (push (cadr repl) s)
9404 (push
9405 (cons (car c)
9406 (cdr (or (assoc (cadr repl) alist)
9407 (error "Undefined key `%s' as contextual replacement for `%s'"
9408 (cadr repl) (car c)))))
9409 r))))))
9410 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9411 (delq
9413 (delete-dups
9414 (mapcar (lambda (x)
9415 (let ((tpl (car x)))
9416 (unless (delq
9418 (mapcar (lambda (y)
9419 (equal y tpl))
9421 x)))
9422 (reverse r))))))
9424 (defun org-contextualize-validate-key (key contexts)
9425 "Check CONTEXTS for agenda or capture KEY."
9426 (let (res)
9427 (dolist (r contexts)
9428 (dolist (rr (car (last r)))
9429 (when
9430 (and (equal key (car r))
9431 (if (functionp rr) (funcall rr)
9432 (or (and (eq (car rr) 'in-file)
9433 (buffer-file-name)
9434 (string-match (cdr rr) (buffer-file-name)))
9435 (and (eq (car rr) 'in-mode)
9436 (string-match (cdr rr) (symbol-name major-mode)))
9437 (and (eq (car rr) 'in-buffer)
9438 (string-match (cdr rr) (buffer-name)))
9439 (when (and (eq (car rr) 'not-in-file)
9440 (buffer-file-name))
9441 (not (string-match (cdr rr) (buffer-file-name))))
9442 (when (eq (car rr) 'not-in-mode)
9443 (not (string-match (cdr rr) (symbol-name major-mode))))
9444 (when (eq (car rr) 'not-in-buffer)
9445 (not (string-match (cdr rr) (buffer-name)))))))
9446 (push r res))))
9447 (delete-dups (delq nil res))))
9449 (defun org-context-p (&rest contexts)
9450 "Check if local context is any of CONTEXTS.
9451 Possible values in the list of contexts are `table', `headline', and `item'."
9452 (let ((pos (point)))
9453 (goto-char (point-at-bol))
9454 (prog1 (or (and (memq 'table contexts)
9455 (looking-at "[ \t]*|"))
9456 (and (memq 'headline contexts)
9457 (looking-at org-outline-regexp))
9458 (and (memq 'item contexts)
9459 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9460 (and (memq 'item-body contexts)
9461 (org-in-item-p)))
9462 (goto-char pos))))
9464 (defconst org-unique-local-variables
9465 '(org-element--cache
9466 org-element--cache-objects
9467 org-element--cache-sync-keys
9468 org-element--cache-sync-requests
9469 org-element--cache-sync-timer)
9470 "List of local variables that cannot be transferred to another buffer.")
9472 (defun org-get-local-variables ()
9473 "Return a list of all local variables in an Org mode buffer."
9474 (delq nil
9475 (mapcar
9476 (lambda (x)
9477 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9478 (name (car binding)))
9479 (and (not (get name 'org-state))
9480 (not (memq name org-unique-local-variables))
9481 (string-match-p
9482 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9483 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9484 (symbol-name name))
9485 binding)))
9486 (with-temp-buffer
9487 (org-mode)
9488 (buffer-local-variables)))))
9490 (defun org-clone-local-variables (from-buffer &optional regexp)
9491 "Clone local variables from FROM-BUFFER.
9492 Optional argument REGEXP selects variables to clone."
9493 (dolist (pair (buffer-local-variables from-buffer))
9494 (let ((name (car pair)))
9495 (when (and (symbolp name)
9496 (not (memq name org-unique-local-variables))
9497 (or (null regexp) (string-match regexp (symbol-name name))))
9498 (set (make-local-variable name) (cdr pair))))))
9500 ;;;###autoload
9501 (defun org-run-like-in-org-mode (cmd)
9502 "Run a command, pretending that the current buffer is in Org-mode.
9503 This will temporarily bind local variables that are typically bound in
9504 Org-mode to the values they have in Org-mode, and then interactively
9505 call CMD."
9506 (org-load-modules-maybe)
9507 (unless org-local-vars
9508 (setq org-local-vars (org-get-local-variables)))
9509 (let (binds)
9510 (dolist (var org-local-vars)
9511 (when (or (not (boundp (car var)))
9512 (eq (symbol-value (car var))
9513 (default-value (car var))))
9514 (push (list (car var) `(quote ,(cadr var))) binds)))
9515 (eval `(let ,binds
9516 (call-interactively (quote ,cmd))))))
9518 (defun org-get-category (&optional pos force-refresh)
9519 "Get the category applying to position POS."
9520 (save-match-data
9521 (when force-refresh (org-refresh-category-properties))
9522 (let ((pos (or pos (point))))
9523 (or (get-text-property pos 'org-category)
9524 (progn (org-refresh-category-properties)
9525 (get-text-property pos 'org-category))))))
9527 ;;; Refresh properties
9529 (defun org-refresh-properties (dprop tprop)
9530 "Refresh buffer text properties.
9531 DPROP is the drawer property and TPROP is either the
9532 corresponding text property to set, or an alist with each element
9533 being a text property (as a symbol) and a function to apply to
9534 the value of the drawer property."
9535 (let ((case-fold-search t)
9536 (inhibit-read-only t))
9537 (org-with-silent-modifications
9538 (save-excursion
9539 (save-restriction
9540 (widen)
9541 (goto-char (point-min))
9542 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9543 (org-refresh-property tprop (match-string-no-properties 1))))))))
9545 (defun org-refresh-property (tprop p)
9546 "Refresh the buffer text property TPROP from the drawer property P.
9547 The refresh happens only for the current tree (not subtree)."
9548 (unless (org-before-first-heading-p)
9549 (save-excursion
9550 (org-back-to-heading t)
9551 (if (symbolp tprop)
9552 ;; TPROP is a text property symbol
9553 (put-text-property
9554 (point) (or (outline-next-heading) (point-max)) tprop p)
9555 ;; TPROP is an alist with (properties . function) elements
9556 (dolist (al tprop)
9557 (save-excursion
9558 (put-text-property
9559 (line-beginning-position) (or (outline-next-heading) (point-max))
9560 (car al)
9561 (funcall (cdr al) p))))))))
9563 (defun org-refresh-category-properties ()
9564 "Refresh category text properties in the buffer."
9565 (let ((case-fold-search t)
9566 (inhibit-read-only t)
9567 (default-category
9568 (cond ((null org-category)
9569 (if buffer-file-name
9570 (file-name-sans-extension
9571 (file-name-nondirectory buffer-file-name))
9572 "???"))
9573 ((symbolp org-category) (symbol-name org-category))
9574 (t org-category))))
9575 (org-with-silent-modifications
9576 (org-with-wide-buffer
9577 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9578 ;; This is the default category for the buffer. If none is
9579 ;; found, fall-back to `org-category' or buffer file name.
9580 (put-text-property
9581 (point-min) (point-max)
9582 'org-category
9583 (catch 'buffer-category
9584 (goto-char (point-max))
9585 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9586 (let ((element (org-element-at-point)))
9587 (when (eq (org-element-type element) 'keyword)
9588 (throw 'buffer-category
9589 (org-element-property :value element)))))
9590 default-category))
9591 ;; Set sub-tree specific categories.
9592 (goto-char (point-min))
9593 (let ((regexp (org-re-property "CATEGORY")))
9594 (while (re-search-forward regexp nil t)
9595 (let ((value (match-string-no-properties 3)))
9596 (when (org-at-property-p)
9597 (put-text-property
9598 (save-excursion (org-back-to-heading t) (point))
9599 (save-excursion (org-end-of-subtree t t) (point))
9600 'org-category
9601 value)))))))))
9603 (defun org-refresh-stats-properties ()
9604 "Refresh stats text properties in the buffer."
9605 (let (stats)
9606 (org-with-silent-modifications
9607 (save-excursion
9608 (save-restriction
9609 (widen)
9610 (goto-char (point-min))
9611 (while (re-search-forward
9612 (concat org-outline-regexp-bol ".*"
9613 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9614 nil t)
9615 (setq stats (cond ((equal (match-string 3) "0") 0)
9616 ((match-string 2)
9617 (/ (* (string-to-number (match-string 2)) 100)
9618 (string-to-number (match-string 3))))
9619 (t (string-to-number (match-string 1)))))
9620 (org-back-to-heading t)
9621 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9622 'org-stats stats)))))))
9624 (defun org-refresh-effort-properties ()
9625 "Refresh effort properties"
9626 (org-refresh-properties
9627 org-effort-property
9628 '((effort . identity)
9629 (effort-minutes . org-duration-string-to-minutes))))
9631 ;;;; Link Stuff
9633 ;;; Link abbreviations
9635 (defun org-link-expand-abbrev (link)
9636 "Apply replacements as defined in `org-link-abbrev-alist'."
9637 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9638 (let* ((key (match-string 1 link))
9639 (as (or (assoc key org-link-abbrev-alist-local)
9640 (assoc key org-link-abbrev-alist)))
9641 (tag (and (match-end 2) (match-string 3 link)))
9642 rpl)
9643 (if (not as)
9644 link
9645 (setq rpl (cdr as))
9646 (cond
9647 ((symbolp rpl) (funcall rpl tag))
9648 ((string-match "%(\\([^)]+\\))" rpl)
9649 (replace-match
9650 (save-match-data
9651 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9652 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9653 ((string-match "%h" rpl)
9654 (replace-match (url-hexify-string (or tag "")) t t rpl))
9655 (t (concat rpl tag)))))
9656 link))
9658 ;;; Storing and inserting links
9660 (defvar org-insert-link-history nil
9661 "Minibuffer history for links inserted with `org-insert-link'.")
9663 (defvar org-stored-links nil
9664 "Contains the links stored with `org-store-link'.")
9666 (defvar org-store-link-plist nil
9667 "Plist with info about the most recently link created with `org-store-link'.")
9669 (defvar org-link-protocols nil
9670 "Link protocols added to Org-mode using `org-add-link-type'.")
9672 (defvar org-store-link-functions nil
9673 "List of functions that are called to create and store a link.
9674 Each function will be called in turn until one returns a non-nil
9675 value. Each function should check if it is responsible for creating
9676 this link (for example by looking at the major mode).
9677 If not, it must exit and return nil.
9678 If yes, it should return a non-nil value after a calling
9679 `org-store-link-props' with a list of properties and values.
9680 Special properties are:
9682 :type The link prefix, like \"http\". This must be given.
9683 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9684 This is obligatory as well.
9685 :description Optional default description for the second pair
9686 of brackets in an Org-mode link. The user can still change
9687 this when inserting this link into an Org-mode buffer.
9689 In addition to these, any additional properties can be specified
9690 and then used in capture templates.")
9692 (defun org-add-link-type (type &optional follow export)
9693 "Add TYPE to the list of `org-link-types'.
9694 Re-compute all regular expressions depending on `org-link-types'
9696 FOLLOW and EXPORT are two functions.
9698 FOLLOW should take the link path as the single argument and do whatever
9699 is necessary to follow the link, for example find a file or display
9700 a mail message.
9702 EXPORT should format the link path for export to one of the export formats.
9703 It should be a function accepting three arguments:
9705 path the path of the link, the text after the prefix (like \"http:\")
9706 desc the description of the link, if any
9707 format the export format, a symbol like `html' or `latex' or `ascii'.
9709 The function may use the FORMAT information to return different values
9710 depending on the format. The return value will be put literally into
9711 the exported file. If the return value is nil, this means Org should
9712 do what it normally does with links which do not have EXPORT defined.
9714 Org mode has a built-in default for exporting links. If you are happy with
9715 this default, there is no need to define an export function for the link
9716 type. For a simple example of an export function, see `org-bbdb.el'."
9717 (add-to-list 'org-link-types type t)
9718 (org-make-link-regexps)
9719 (org-element-update-syntax)
9720 (if (assoc type org-link-protocols)
9721 (setcdr (assoc type org-link-protocols) (list follow export))
9722 (push (list type follow export) org-link-protocols)))
9724 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9725 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9727 ;;;###autoload
9728 (defun org-store-link (arg)
9729 "\\<org-mode-map>Store an org-link to the current location.
9730 This link is added to `org-stored-links' and can later be inserted
9731 into an Org buffer with \\[org-insert-link].
9733 For some link types, a prefix ARG is interpreted.
9734 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9735 For file links, ARG negates `org-context-in-file-links'.
9737 A double prefix ARG force skipping storing functions that are not
9738 part of Org's core.
9740 A triple prefix ARG force storing a link for each line in the
9741 active region."
9742 (interactive "P")
9743 (org-load-modules-maybe)
9744 (if (and (equal arg '(64)) (org-region-active-p))
9745 (save-excursion
9746 (let ((end (region-end)))
9747 (goto-char (region-beginning))
9748 (set-mark (point))
9749 (while (< (point-at-eol) end)
9750 (move-end-of-line 1) (activate-mark)
9751 (let (current-prefix-arg)
9752 (call-interactively 'org-store-link))
9753 (move-beginning-of-line 2)
9754 (set-mark (point)))))
9755 (org-with-limited-levels
9756 (setq org-store-link-plist nil)
9757 (let (link cpltxt desc description search
9758 txt custom-id agenda-link sfuns sfunsn)
9759 (cond
9761 ;; Store a link using an external link type
9762 ((and (not (equal arg '(16)))
9763 (setq sfuns
9764 (delq
9765 nil (mapcar (lambda (f)
9766 (let (fs) (if (funcall f) (push f fs))))
9767 org-store-link-functions))
9768 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9769 (or (and (cdr sfuns)
9770 (funcall (intern
9771 (completing-read
9772 "Which function for creating the link? "
9773 sfunsn nil t (car sfunsn)))))
9774 (funcall (caar sfuns)))
9775 (setq link (plist-get org-store-link-plist :link)
9776 desc (or (plist-get org-store-link-plist
9777 :description)
9778 link))))
9780 ;; Store a link from a source code buffer.
9781 ((org-src-edit-buffer-p)
9782 (cond
9783 ((save-excursion
9784 (beginning-of-line)
9785 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9786 "[ \t]*$")))
9787 (setq link (format "(%s)" (match-string-no-properties 1))))
9788 ((called-interactively-p 'any)
9789 (let (label)
9790 (while (or (not label)
9791 (org-with-wide-buffer
9792 (goto-char (point-min))
9793 (re-search-forward
9794 (regexp-quote (format org-coderef-label-format label))
9795 nil t)))
9796 (when label (message "Label exists already") (sit-for 2))
9797 (setq label (read-string "Code line label: " label)))
9798 (end-of-line)
9799 (setq link (format org-coderef-label-format label))
9800 (let ((gc (- 79 (length link))))
9801 (if (< (current-column) gc) (org-move-to-column gc t)
9802 (insert " ")))
9803 (insert link)
9804 (setq link (concat "(" label ")") desc nil)))
9805 (t (setq link nil))))
9807 ;; We are in the agenda, link to referenced location
9808 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9809 (let ((m (or (get-text-property (point) 'org-hd-marker)
9810 (get-text-property (point) 'org-marker))))
9811 (when m
9812 (org-with-point-at m
9813 (setq agenda-link
9814 (if (called-interactively-p 'any)
9815 (call-interactively 'org-store-link)
9816 (org-store-link nil)))))))
9818 ((eq major-mode 'calendar-mode)
9819 (let ((cd (calendar-cursor-to-date)))
9820 (setq link
9821 (format-time-string
9822 (car org-time-stamp-formats)
9823 (apply 'encode-time
9824 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9825 nil nil nil))))
9826 (org-store-link-props :type "calendar" :date cd)))
9828 ((eq major-mode 'help-mode)
9829 (setq link (concat "help:" (save-excursion
9830 (goto-char (point-min))
9831 (looking-at "^[^ ]+")
9832 (match-string 0))))
9833 (org-store-link-props :type "help"))
9835 ((eq major-mode 'w3-mode)
9836 (setq cpltxt (if (and (buffer-name)
9837 (not (string-match "Untitled" (buffer-name))))
9838 (buffer-name)
9839 (url-view-url t))
9840 link (url-view-url t))
9841 (org-store-link-props :type "w3" :url (url-view-url t)))
9843 ((eq major-mode 'image-mode)
9844 (setq cpltxt (concat "file:"
9845 (abbreviate-file-name buffer-file-name))
9846 link cpltxt)
9847 (org-store-link-props :type "image" :file buffer-file-name))
9849 ;; In dired, store a link to the file of the current line
9850 ((derived-mode-p 'dired-mode)
9851 (let ((file (dired-get-filename nil t)))
9852 (setq file (if file
9853 (abbreviate-file-name
9854 (expand-file-name (dired-get-filename nil t)))
9855 ;; otherwise, no file so use current directory.
9856 default-directory))
9857 (setq cpltxt (concat "file:" file)
9858 link cpltxt)))
9860 ((setq search (run-hook-with-args-until-success
9861 'org-create-file-search-functions))
9862 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9863 "::" search))
9864 (setq cpltxt (or description link)))
9866 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9867 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9868 (cond
9869 ;; Store a link using the target at point
9870 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9871 (setq cpltxt
9872 (concat "file:"
9873 (abbreviate-file-name
9874 (buffer-file-name (buffer-base-buffer)))
9875 "::" (match-string 1))
9876 link cpltxt))
9877 ((and (featurep 'org-id)
9878 (or (eq org-id-link-to-org-use-id t)
9879 (and (called-interactively-p 'any)
9880 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9881 (and (eq org-id-link-to-org-use-id
9882 'create-if-interactive-and-no-custom-id)
9883 (not custom-id))))
9884 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9885 ;; Store a link using the ID at point
9886 (setq link (condition-case nil
9887 (prog1 (org-id-store-link)
9888 (setq desc (or (plist-get org-store-link-plist
9889 :description)
9890 "")))
9891 (error
9892 ;; Probably before first headline, link only to file
9893 (concat "file:"
9894 (abbreviate-file-name
9895 (buffer-file-name (buffer-base-buffer))))))))
9897 ;; Just link to current headline
9898 (setq cpltxt (concat "file:"
9899 (abbreviate-file-name
9900 (buffer-file-name (buffer-base-buffer)))))
9901 ;; Add a context search string
9902 (when (org-xor org-context-in-file-links arg)
9903 (let* ((element (org-element-at-point))
9904 (name (org-element-property :name element)))
9905 (setq txt (cond
9906 ((org-at-heading-p) nil)
9907 (name)
9908 ((org-region-active-p)
9909 (buffer-substring (region-beginning) (region-end)))))
9910 (when (or (null txt) (string-match "\\S-" txt))
9911 (setq cpltxt
9912 (concat cpltxt "::"
9913 (condition-case nil
9914 (org-make-org-heading-search-string txt)
9915 (error "")))
9916 desc (or name
9917 (nth 4 (ignore-errors (org-heading-components)))
9918 "NONE")))))
9919 (when (string-match "::\\'" cpltxt)
9920 (setq cpltxt (substring cpltxt 0 -2)))
9921 (setq link cpltxt))))
9923 ((buffer-file-name (buffer-base-buffer))
9924 ;; Just link to this file here.
9925 (setq cpltxt (concat "file:"
9926 (abbreviate-file-name
9927 (buffer-file-name (buffer-base-buffer)))))
9928 ;; Add a context string.
9929 (when (org-xor org-context-in-file-links arg)
9930 (setq txt (if (org-region-active-p)
9931 (buffer-substring (region-beginning) (region-end))
9932 (buffer-substring (point-at-bol) (point-at-eol))))
9933 ;; Only use search option if there is some text.
9934 (when (string-match "\\S-" txt)
9935 (setq cpltxt
9936 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9937 desc "NONE")))
9938 (setq link cpltxt))
9940 ((called-interactively-p 'interactive)
9941 (user-error "No method for storing a link from this buffer"))
9943 (t (setq link nil)))
9945 ;; We're done setting link and desc, clean up
9946 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9947 (setq link (or link cpltxt)
9948 desc (or desc cpltxt))
9949 (cond ((not desc))
9950 ((equal desc "NONE") (setq desc nil))
9951 (t (setq desc
9952 (replace-regexp-in-string
9953 org-bracket-link-analytic-regexp
9954 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9955 desc))))
9956 ;; Return the link
9957 (if (not (and (or (called-interactively-p 'any)
9958 executing-kbd-macro)
9959 link))
9960 (or agenda-link (and link (org-make-link-string link desc)))
9961 (push (list link desc) org-stored-links)
9962 (message "Stored: %s" (or desc link))
9963 (when custom-id
9964 (setq link (concat "file:" (abbreviate-file-name
9965 (buffer-file-name)) "::#" custom-id))
9966 (push (list link desc) org-stored-links))
9967 (car org-stored-links))))))
9969 (defun org-store-link-props (&rest plist)
9970 "Store link properties, extract names, addresses and dates."
9971 (let ((x (plist-get plist :from)))
9972 (when x
9973 (let ((adr (mail-extract-address-components x)))
9974 (setq plist (plist-put plist :fromname (car adr)))
9975 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9976 (let ((x (plist-get plist :to)))
9977 (when x
9978 (let ((adr (mail-extract-address-components x)))
9979 (setq plist (plist-put plist :toname (car adr)))
9980 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9981 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9982 (when x
9983 (setq plist (plist-put plist :date-timestamp
9984 (format-time-string
9985 (org-time-stamp-format t) x)))
9986 (setq plist (plist-put plist :date-timestamp-inactive
9987 (format-time-string
9988 (org-time-stamp-format t t) x)))))
9989 (let ((from (plist-get plist :from))
9990 (to (plist-get plist :to)))
9991 (when (and from to org-from-is-user-regexp)
9992 (setq plist
9993 (plist-put plist :fromto
9994 (if (string-match org-from-is-user-regexp from)
9995 (concat "to %t")
9996 (concat "from %f"))))))
9997 (setq org-store-link-plist plist))
9999 (defun org-add-link-props (&rest plist)
10000 "Add these properties to the link property list."
10001 (let (key value)
10002 (while plist
10003 (setq key (pop plist) value (pop plist))
10004 (setq org-store-link-plist
10005 (plist-put org-store-link-plist key value)))))
10007 (defun org-email-link-description (&optional fmt)
10008 "Return the description part of an email link.
10009 This takes information from `org-store-link-plist' and formats it
10010 according to FMT (default from `org-email-link-description-format')."
10011 (setq fmt (or fmt org-email-link-description-format))
10012 (let* ((p org-store-link-plist)
10013 (to (plist-get p :toaddress))
10014 (from (plist-get p :fromaddress))
10015 (table
10016 (list
10017 (cons "%c" (plist-get p :fromto))
10018 (cons "%F" (plist-get p :from))
10019 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10020 (cons "%T" (plist-get p :to))
10021 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10022 (cons "%s" (plist-get p :subject))
10023 (cons "%d" (plist-get p :date))
10024 (cons "%m" (plist-get p :message-id)))))
10025 (when (string-match "%c" fmt)
10026 ;; Check if the user wrote this message
10027 (if (and org-from-is-user-regexp from to
10028 (save-match-data (string-match org-from-is-user-regexp from)))
10029 (setq fmt (replace-match "to %t" t t fmt))
10030 (setq fmt (replace-match "from %f" t t fmt))))
10031 (org-replace-escapes fmt table)))
10033 (defun org-make-org-heading-search-string (&optional string)
10034 "Make search string for the current headline or STRING."
10035 (let ((s (or string
10036 (and (derived-mode-p 'org-mode)
10037 (save-excursion
10038 (org-back-to-heading t)
10039 (org-element-property :raw-value (org-element-at-point))))))
10040 (lines org-context-in-file-links))
10041 (or string (setq s (concat "*" s))) ; Add * for headlines
10042 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10043 (when (and string (integerp lines) (> lines 0))
10044 (let ((slines (org-split-string s "\n")))
10045 (when (< lines (length slines))
10046 (setq s (mapconcat
10047 'identity
10048 (reverse (nthcdr (- (length slines) lines)
10049 (reverse slines))) "\n")))))
10050 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10052 (defun org-make-link-string (link &optional description)
10053 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10054 (unless (org-string-nw-p link) (error "Empty link"))
10055 (let ((uri (cond ((string-match org-link-types-re link)
10056 (concat (match-string 1 link)
10057 (org-link-escape (substring link (match-end 1)))))
10058 ;; For readability, url-encode internal links only
10059 ;; when absolutely needed (i.e, when they contain
10060 ;; square brackets). File links however, are
10061 ;; encoded since, e.g., spaces are significant.
10062 ((or (file-name-absolute-p link)
10063 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10064 (org-link-escape link))
10065 (t link)))
10066 (description
10067 (and (org-string-nw-p description)
10068 ;; Remove brackets from description, as they are fatal.
10069 (replace-regexp-in-string
10070 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10071 (org-trim description)))))
10072 (format "[[%s]%s]"
10074 (if description (format "[%s]" description) ""))))
10076 (defconst org-link-escape-chars
10077 ;;%20 %5B %5D %25
10078 '(?\s ?\[ ?\] ?%)
10079 "List of characters that should be escaped in a link when stored to Org.
10080 This is the list that is used for internal purposes.")
10082 (defun org-link-escape (text &optional table merge)
10083 "Return percent escaped representation of TEXT.
10084 TEXT is a string with the text to escape.
10085 Optional argument TABLE is a list with characters that should be
10086 escaped. When nil, `org-link-escape-chars' is used.
10087 If optional argument MERGE is set, merge TABLE into
10088 `org-link-escape-chars'."
10089 (let ((characters-to-encode
10090 (cond ((null table) org-link-escape-chars)
10091 (merge (append org-link-escape-chars table))
10092 (t table))))
10093 (mapconcat
10094 (lambda (c)
10095 (if (or (memq c characters-to-encode)
10096 (and org-url-hexify-p (or (< c 32) (> c 126))))
10097 (mapconcat (lambda (e) (format "%%%.2X" e))
10098 (or (encode-coding-char c 'utf-8)
10099 (error "Unable to percent escape character: %c" c))
10101 (char-to-string c)))
10102 text "")))
10104 (defun org-link-unescape (str)
10105 "Unhex hexified Unicode parts in string STR.
10106 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10107 reciprocal of `org-link-escape', which see."
10108 (if (org-string-nw-p str)
10109 (replace-regexp-in-string
10110 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10111 str))
10113 (defun org-link-unescape-compound (hex)
10114 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10115 Note: this function also decodes single byte encodings like
10116 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10117 (save-match-data
10118 (let* ((bytes (cdr (split-string hex "%")))
10119 (ret "")
10120 (eat 0)
10121 (sum 0))
10122 (while bytes
10123 (let* ((val (string-to-number (pop bytes) 16))
10124 (shift-xor
10125 (if (= 0 eat)
10126 (cond
10127 ((>= val 252) (cons 6 252))
10128 ((>= val 248) (cons 5 248))
10129 ((>= val 240) (cons 4 240))
10130 ((>= val 224) (cons 3 224))
10131 ((>= val 192) (cons 2 192))
10132 (t (cons 0 0)))
10133 (cons 6 128))))
10134 (when (>= val 192) (setq eat (car shift-xor)))
10135 (setq val (logxor val (cdr shift-xor)))
10136 (setq sum (+ (lsh sum (car shift-xor)) val))
10137 (when (> eat 0) (setq eat (- eat 1)))
10138 (cond
10139 ((= 0 eat) ;multi byte
10140 (setq ret (concat ret (char-to-string sum)))
10141 (setq sum 0))
10142 ((not bytes) ; single byte(s)
10143 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10144 ret)))
10146 (defun org-link-unescape-single-byte-sequence (hex)
10147 "Unhexify hex-encoded single byte character sequences."
10148 (mapconcat (lambda (byte)
10149 (char-to-string (string-to-number byte 16)))
10150 (cdr (split-string hex "%")) ""))
10152 (defun org-xor (a b)
10153 "Exclusive or."
10154 (if a (not b) b))
10156 (defun org-fixup-message-id-for-http (s)
10157 "Replace special characters in a message id, so it can be used in an http query."
10158 (when (string-match "%" s)
10159 (setq s (mapconcat (lambda (c)
10160 (if (eq c ?%)
10161 "%25"
10162 (char-to-string c)))
10163 s "")))
10164 (while (string-match "<" s)
10165 (setq s (replace-match "%3C" t t s)))
10166 (while (string-match ">" s)
10167 (setq s (replace-match "%3E" t t s)))
10168 (while (string-match "@" s)
10169 (setq s (replace-match "%40" t t s)))
10172 (defun org-link-prettify (link)
10173 "Return a human-readable representation of LINK.
10174 The car of LINK must be a raw link.
10175 The cdr of LINK must be either a link description or nil."
10176 (let ((desc (or (cadr link) "<no description>")))
10177 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10178 "<" (car link) ">")))
10180 ;;;###autoload
10181 (defun org-insert-link-global ()
10182 "Insert a link like Org-mode does.
10183 This command can be called in any mode to insert a link in Org-mode syntax."
10184 (interactive)
10185 (org-load-modules-maybe)
10186 (org-run-like-in-org-mode 'org-insert-link))
10188 (defun org-insert-all-links (arg &optional pre post)
10189 "Insert all links in `org-stored-links'.
10190 When a universal prefix, do not delete the links from `org-stored-links'.
10191 When `ARG' is a number, insert the last N link(s).
10192 `PRE' and `POST' are optional arguments to define a string to
10193 prepend or to append."
10194 (interactive "P")
10195 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10196 (links (copy-sequence org-stored-links))
10197 (pr (or pre "- "))
10198 (po (or post "\n"))
10199 (cnt 1) l)
10200 (if (null org-stored-links)
10201 (message "No link to insert")
10202 (while (and (or (listp arg) (>= arg cnt))
10203 (setq l (if (listp arg)
10204 (pop links)
10205 (pop org-stored-links))))
10206 (setq cnt (1+ cnt))
10207 (insert pr)
10208 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10209 (insert po)))))
10211 (defun org-insert-last-stored-link (arg)
10212 "Insert the last link stored in `org-stored-links'."
10213 (interactive "p")
10214 (org-insert-all-links arg "" "\n"))
10216 (defun org-link-fontify-links-to-this-file ()
10217 "Fontify links to the current file in `org-stored-links'."
10218 (let ((f (buffer-file-name)) a b)
10219 (setq a (mapcar (lambda(l)
10220 (let ((ll (car l)))
10221 (when (and (string-match "^file:\\(.+\\)::" ll)
10222 (equal f (expand-file-name (match-string 1 ll))))
10223 ll)))
10224 org-stored-links))
10225 (when (featurep 'org-id)
10226 (setq b (mapcar (lambda(l)
10227 (let ((ll (car l)))
10228 (when (and (string-match "^id:\\(.+\\)$" ll)
10229 (equal f (expand-file-name
10230 (or (org-id-find-id-file
10231 (match-string 1 ll)) ""))))
10232 ll)))
10233 org-stored-links)))
10234 (mapcar (lambda(l)
10235 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10236 (delq nil (append a b)))))
10238 (defvar org--links-history nil)
10239 (defun org-insert-link (&optional complete-file link-location default-description)
10240 "Insert a link. At the prompt, enter the link.
10242 Completion can be used to insert any of the link protocol prefixes like
10243 http or ftp in use.
10245 The history can be used to select a link previously stored with
10246 `org-store-link'. When the empty string is entered (i.e. if you just
10247 press RET at the prompt), the link defaults to the most recently
10248 stored link. As SPC triggers completion in the minibuffer, you need to
10249 use M-SPC or C-q SPC to force the insertion of a space character.
10251 You will also be prompted for a description, and if one is given, it will
10252 be displayed in the buffer instead of the link.
10254 If there is already a link at point, this command will allow you to edit link
10255 and description parts.
10257 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10258 be selected using completion. The path to the file will be relative to the
10259 current directory if the file is in the current directory or a subdirectory.
10260 Otherwise, the link will be the absolute path as completed in the minibuffer
10261 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10262 option `org-link-file-path-type'.
10264 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10265 the current directory or below.
10267 With three \\[universal-argument] prefixes, negate the meaning of
10268 `org-keep-stored-link-after-insertion'.
10270 If `org-make-link-description-function' is non-nil, this function will be
10271 called with the link target, and the result will be the default
10272 link description.
10274 If the LINK-LOCATION parameter is non-nil, this value will be
10275 used as the link location instead of reading one interactively.
10277 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10278 be used as the default description."
10279 (interactive "P")
10280 (let* ((wcf (current-window-configuration))
10281 (origbuf (current-buffer))
10282 (region (when (org-region-active-p)
10283 (buffer-substring (region-beginning) (region-end))))
10284 (remove (and region (list (region-beginning) (region-end))))
10285 (desc region)
10286 (link link-location)
10287 (abbrevs org-link-abbrev-alist-local)
10288 entry all-prefixes auto-desc)
10289 (cond
10290 (link-location) ; specified by arg, just use it.
10291 ((org-in-regexp org-bracket-link-regexp 1)
10292 ;; We do have a link at point, and we are going to edit it.
10293 (setq remove (list (match-beginning 0) (match-end 0)))
10294 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10295 (setq link (read-string "Link: "
10296 (org-link-unescape
10297 (match-string-no-properties 1)))))
10298 ((or (org-in-regexp org-angle-link-re)
10299 (org-in-regexp org-plain-link-re))
10300 ;; Convert to bracket link
10301 (setq remove (list (match-beginning 0) (match-end 0))
10302 link (read-string "Link: "
10303 (org-remove-angle-brackets (match-string 0)))))
10304 ((member complete-file '((4) (16)))
10305 ;; Completing read for file names.
10306 (setq link (org-file-complete-link complete-file)))
10308 ;; Read link, with completion for stored links.
10309 (org-link-fontify-links-to-this-file)
10310 (org-switch-to-buffer-other-window "*Org Links*")
10311 (with-current-buffer "*Org Links*"
10312 (erase-buffer)
10313 (insert "Insert a link.
10314 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10315 (when org-stored-links
10316 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10317 (insert (mapconcat 'org-link-prettify
10318 (reverse org-stored-links) "\n")))
10319 (goto-char (point-min)))
10320 (let ((cw (selected-window)))
10321 (select-window (get-buffer-window "*Org Links*" 'visible))
10322 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10323 (unless (pos-visible-in-window-p (point-max))
10324 (org-fit-window-to-buffer))
10325 (and (window-live-p cw) (select-window cw)))
10326 (setq all-prefixes (append (mapcar 'car abbrevs)
10327 (mapcar 'car org-link-abbrev-alist)
10328 org-link-types))
10329 (unwind-protect
10330 ;; Fake a link history, containing the stored links.
10331 (let ((org--links-history
10332 (append (mapcar #'car org-stored-links)
10333 org-insert-link-history)))
10334 (setq link
10335 (org-completing-read
10336 "Link: "
10337 (append
10338 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10339 (mapcar #'car org-stored-links))
10340 nil nil nil
10341 'org--links-history
10342 (caar org-stored-links)))
10343 (unless (org-string-nw-p link) (user-error "No link selected"))
10344 (dolist (l org-stored-links)
10345 (when (equal link (cadr l))
10346 (setq link (car l))
10347 (setq auto-desc t)))
10348 (when (or (member link all-prefixes)
10349 (and (equal ":" (substring link -1))
10350 (member (substring link 0 -1) all-prefixes)
10351 (setq link (substring link 0 -1))))
10352 (setq link (with-current-buffer origbuf
10353 (org-link-try-special-completion link)))))
10354 (set-window-configuration wcf)
10355 (kill-buffer "*Org Links*"))
10356 (setq entry (assoc link org-stored-links))
10357 (or entry (push link org-insert-link-history))
10358 (setq desc (or desc (nth 1 entry)))))
10360 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10361 (not org-keep-stored-link-after-insertion))
10362 (setq org-stored-links (delq (assoc link org-stored-links)
10363 org-stored-links)))
10365 (when (and (string-match org-plain-link-re link)
10366 (not (string-match org-ts-regexp link)))
10367 ;; URL-like link, normalize the use of angular brackets.
10368 (setq link (org-remove-angle-brackets link)))
10370 ;; Check if we are linking to the current file with a search
10371 ;; option If yes, simplify the link by using only the search
10372 ;; option.
10373 (when (and buffer-file-name
10374 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10375 (let* ((path (match-string 1 link))
10376 (case-fold-search nil)
10377 (search (match-string 2 link)))
10378 (save-match-data
10379 (when (equal (file-truename buffer-file-name) (file-truename path))
10380 ;; We are linking to this same file, with a search option
10381 (setq link search)))))
10383 ;; Check if we can/should use a relative path. If yes, simplify the link
10384 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10385 (let* ((type (match-string 1 link))
10386 (path (match-string 2 link))
10387 (origpath path)
10388 (case-fold-search nil))
10389 (cond
10390 ((or (eq org-link-file-path-type 'absolute)
10391 (equal complete-file '(16)))
10392 (setq path (abbreviate-file-name (expand-file-name path))))
10393 ((eq org-link-file-path-type 'noabbrev)
10394 (setq path (expand-file-name path)))
10395 ((eq org-link-file-path-type 'relative)
10396 (setq path (file-relative-name path)))
10398 (save-match-data
10399 (if (string-match (concat "^" (regexp-quote
10400 (expand-file-name
10401 (file-name-as-directory
10402 default-directory))))
10403 (expand-file-name path))
10404 ;; We are linking a file with relative path name.
10405 (setq path (substring (expand-file-name path)
10406 (match-end 0)))
10407 (setq path (abbreviate-file-name (expand-file-name path)))))))
10408 (setq link (concat type path))
10409 (when (equal desc origpath)
10410 (setq desc path))))
10412 (if org-make-link-description-function
10413 (setq desc
10414 (or (condition-case nil
10415 (funcall org-make-link-description-function link desc)
10416 (error (progn (message "Can't get link description from `%s'"
10417 (symbol-name org-make-link-description-function))
10418 (sit-for 2) nil)))
10419 (read-string "Description: " default-description)))
10420 (if default-description (setq desc default-description)
10421 (setq desc (or (and auto-desc desc)
10422 (read-string "Description: " desc)))))
10424 (unless (string-match "\\S-" desc) (setq desc nil))
10425 (when remove (apply 'delete-region remove))
10426 (insert (org-make-link-string link desc))
10427 ;; Redisplay so as the new link has proper invisible characters.
10428 (sit-for 0)))
10430 (defun org-link-try-special-completion (type)
10431 "If there is completion support for link type TYPE, offer it."
10432 (let ((fun (intern (concat "org-" type "-complete-link"))))
10433 (if (functionp fun)
10434 (funcall fun)
10435 (read-string "Link (no completion support): " (concat type ":")))))
10437 (defun org-file-complete-link (&optional arg)
10438 "Create a file link using completion."
10439 (let ((file (read-file-name "File: "))
10440 (pwd (file-name-as-directory (expand-file-name ".")))
10441 (pwd1 (file-name-as-directory (abbreviate-file-name
10442 (expand-file-name ".")))))
10443 (cond ((equal arg '(16))
10444 (concat "file:"
10445 (abbreviate-file-name (expand-file-name file))))
10446 ((string-match
10447 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10448 (concat "file:" (match-string 1 file)))
10449 ((string-match
10450 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10451 (expand-file-name file))
10452 (concat "file:"
10453 (match-string 1 (expand-file-name file))))
10454 (t (concat "file:" file)))))
10456 (defun org-completing-read (&rest args)
10457 "Completing-read with SPACE being a normal character."
10458 (let ((enable-recursive-minibuffers t)
10459 (minibuffer-local-completion-map
10460 (copy-keymap minibuffer-local-completion-map)))
10461 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10462 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10463 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10464 'org-time-stamp-inactive)
10465 (apply #'completing-read args)))
10467 ;;; Opening/following a link
10469 (defvar org-link-search-failed nil)
10471 (defvar org-open-link-functions nil
10472 "Hook for functions finding a plain text link.
10473 These functions must take a single argument, the link content.
10474 They will be called for links that look like [[link text][description]]
10475 when LINK TEXT does not have a protocol like \"http:\" and does not look
10476 like a filename (e.g. \"./blue.png\").
10478 These functions will be called *before* Org attempts to resolve the
10479 link by doing text searches in the current buffer - so if you want a
10480 link \"[[target]]\" to still find \"<<target>>\", your function should
10481 handle this as a special case.
10483 When the function does handle the link, it must return a non-nil value.
10484 If it decides that it is not responsible for this link, it must return
10485 nil to indicate that that Org-mode can continue with other options
10486 like exact and fuzzy text search.")
10488 (defun org-next-link (&optional search-backward)
10489 "Move forward to the next link.
10490 If the link is in hidden text, expose it."
10491 (interactive "P")
10492 (when (and org-link-search-failed (eq this-command last-command))
10493 (goto-char (point-min))
10494 (message "Link search wrapped back to beginning of buffer"))
10495 (setq org-link-search-failed nil)
10496 (let* ((pos (point))
10497 (ct (org-context))
10498 (a (assoc :link ct))
10499 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10500 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10501 ((looking-at org-any-link-re)
10502 ;; Don't stay stuck at link without an org-link face
10503 (forward-char (if search-backward -1 1))))
10504 (if (funcall srch-fun org-any-link-re nil t)
10505 (progn
10506 (goto-char (match-beginning 0))
10507 (when (outline-invisible-p) (org-show-context)))
10508 (goto-char pos)
10509 (setq org-link-search-failed t)
10510 (message "No further link found"))))
10512 (defun org-previous-link ()
10513 "Move backward to the previous link.
10514 If the link is in hidden text, expose it."
10515 (interactive)
10516 (funcall 'org-next-link t))
10518 (defun org-translate-link (s)
10519 "Translate a link string if a translation function has been defined."
10520 (with-temp-buffer
10521 (insert (org-trim s))
10522 (org-trim (org-element-interpret-data (org-element-context)))))
10524 (defun org-translate-link-from-planner (type path)
10525 "Translate a link from Emacs Planner syntax so that Org can follow it.
10526 This is still an experimental function, your mileage may vary."
10527 (cond
10528 ((member type '("http" "https" "news" "ftp"))
10529 ;; standard Internet links are the same.
10530 nil)
10531 ((and (equal type "irc") (string-match "^//" path))
10532 ;; Planner has two / at the beginning of an irc link, we have 1.
10533 ;; We should have zero, actually....
10534 (setq path (substring path 1)))
10535 ((and (equal type "lisp") (string-match "^/" path))
10536 ;; Planner has a slash, we do not.
10537 (setq type "elisp" path (substring path 1)))
10538 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10539 ;; A typical message link. Planner has the id after the final slash,
10540 ;; we separate it with a hash mark
10541 (setq path (concat (match-string 1 path) "#"
10542 (org-remove-angle-brackets (match-string 2 path))))))
10543 (cons type path))
10545 (defun org-find-file-at-mouse (ev)
10546 "Open file link or URL at mouse."
10547 (interactive "e")
10548 (mouse-set-point ev)
10549 (org-open-at-point 'in-emacs))
10551 (defun org-open-at-mouse (ev)
10552 "Open file link or URL at mouse.
10553 See the docstring of `org-open-file' for details."
10554 (interactive "e")
10555 (mouse-set-point ev)
10556 (when (eq major-mode 'org-agenda-mode)
10557 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10558 (org-open-at-point))
10560 (defvar org-window-config-before-follow-link nil
10561 "The window configuration before following a link.
10562 This is saved in case the need arises to restore it.")
10564 ;;;###autoload
10565 (defun org-open-at-point-global ()
10566 "Follow a link or time-stamp like Org mode does.
10567 This command can be called in any mode to follow an external link
10568 or a time-stamp that has Org mode syntax. Its behavior is
10569 undefined when called on internal links (e.g., fuzzy links).
10570 Raise an error when there is nothing to follow. "
10571 (interactive)
10572 (cond ((org-in-regexp org-any-link-re)
10573 (org-open-link-from-string (match-string-no-properties 0)))
10574 ((or (org-in-regexp org-ts-regexp-both nil t)
10575 (org-in-regexp org-tsr-regexp-both nil t))
10576 (org-follow-timestamp-link))
10577 (t (user-error "No link found"))))
10579 ;;;###autoload
10580 (defun org-open-link-from-string (s &optional arg reference-buffer)
10581 "Open a link in the string S, as if it was in Org-mode."
10582 (interactive "sLink: \nP")
10583 (let ((reference-buffer (or reference-buffer (current-buffer))))
10584 (with-temp-buffer
10585 (let ((org-inhibit-startup (not reference-buffer)))
10586 (org-mode)
10587 (insert s)
10588 (goto-char (point-min))
10589 (when reference-buffer
10590 (setq org-link-abbrev-alist-local
10591 (with-current-buffer reference-buffer
10592 org-link-abbrev-alist-local)))
10593 (org-open-at-point arg reference-buffer)))))
10595 (defvar org-open-at-point-functions nil
10596 "Hook that is run when following a link at point.
10598 Functions in this hook must return t if they identify and follow
10599 a link at point. If they don't find anything interesting at point,
10600 they must return nil.")
10602 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10603 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10604 (defun org-open-at-point (&optional arg reference-buffer)
10605 "Open link, timestamp, footnote or tags at point.
10607 When point is on a link, follow it. Normally, files will be
10608 opened by an appropriate application. If the optional prefix
10609 argument ARG is non-nil, Emacs will visit the file. With
10610 a double prefix argument, try to open outside of Emacs, in the
10611 application the system uses for this file type.
10613 When point is on a timestamp, open the agenda at the day
10614 specified.
10616 When point is a footnote definition, move to the first reference
10617 found. If it is on a reference, move to the associated
10618 definition.
10620 When point is on a headline, display a list of every link in the
10621 entry, so it is possible to pick one, or all, of them. If point
10622 is on a tag, call `org-tags-view' instead.
10624 When optional argument REFERENCE-BUFFER is non-nil, it should
10625 specify a buffer from where the link search should happen. This
10626 is used internally by `org-open-link-from-string'.
10628 On top of syntactically correct links, this function will open
10629 the link at point in comments or comment blocks and the first
10630 link in a property drawer line."
10631 (interactive "P")
10632 ;; On a code block, open block's results.
10633 (unless (call-interactively 'org-babel-open-src-block-result)
10634 (org-load-modules-maybe)
10635 (setq org-window-config-before-follow-link (current-window-configuration))
10636 (org-remove-occur-highlights nil nil t)
10637 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10638 (let* ((context
10639 ;; Only consider supported types, even if they are not
10640 ;; the closest one.
10641 (org-element-lineage
10642 (org-element-context)
10643 '(clock comment comment-block footnote-definition
10644 footnote-reference headline inlinetask keyword link
10645 node-property timestamp)
10647 (type (org-element-type context))
10648 (value (org-element-property :value context)))
10649 (cond
10650 ((not context) (user-error "No link found"))
10651 ;; Exception: open timestamps and links in properties
10652 ;; drawers, keywords and comments.
10653 ((memq type '(comment comment-block keyword node-property))
10654 (call-interactively #'org-open-at-point-global))
10655 ;; On a headline or an inlinetask, but not on a timestamp,
10656 ;; a link, a footnote reference or on tags.
10657 ((and (memq type '(headline inlinetask))
10658 ;; Not on tags.
10659 (progn (save-excursion (beginning-of-line)
10660 (looking-at org-complex-heading-regexp))
10661 (or (not (match-beginning 5))
10662 (< (point) (match-beginning 5)))))
10663 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10664 (links (car data))
10665 (links-end (cdr data)))
10666 (if links
10667 (dolist (link (if (stringp links) (list links) links))
10668 (search-forward link nil links-end)
10669 (goto-char (match-beginning 0))
10670 (org-open-at-point))
10671 (require 'org-attach)
10672 (org-attach-reveal 'if-exists))))
10673 ;; On a clock line, make sure point is on the timestamp
10674 ;; before opening it.
10675 ((and (eq type 'clock)
10676 value
10677 (>= (point) (org-element-property :begin value))
10678 (<= (point) (org-element-property :end value)))
10679 (org-follow-timestamp-link))
10680 ;; Do nothing on white spaces after an object.
10681 ((>= (point)
10682 (save-excursion
10683 (goto-char (org-element-property :end context))
10684 (skip-chars-backward " \t")
10685 (point)))
10686 (user-error "No link found"))
10687 ((eq type 'timestamp) (org-follow-timestamp-link))
10688 ;; On tags within a headline or an inlinetask.
10689 ((and (memq type '(headline inlinetask))
10690 (progn (save-excursion (beginning-of-line)
10691 (looking-at org-complex-heading-regexp))
10692 (and (match-beginning 5)
10693 (>= (point) (match-beginning 5)))))
10694 (org-tags-view arg (substring (match-string 5) 0 -1)))
10695 ((eq type 'link)
10696 ;; When link is located within the description of another
10697 ;; link (e.g., an inline image), always open the parent
10698 ;; link.
10699 (let*((link (let ((up (org-element-property :parent context)))
10700 (if (eq (org-element-type up) 'link) up context)))
10701 (type (org-element-property :type link))
10702 (path (org-link-unescape (org-element-property :path link))))
10703 ;; Switch back to REFERENCE-BUFFER needed when called in
10704 ;; a temporary buffer through `org-open-link-from-string'.
10705 (with-current-buffer (or reference-buffer (current-buffer))
10706 (cond
10707 ((equal type "file")
10708 (if (string-match "[*?{]" (file-name-nondirectory path))
10709 (dired path)
10710 ;; Look into `org-link-protocols' in order to find
10711 ;; a DEDICATED-FUNCTION to open file. The function
10712 ;; will be applied on raw link instead of parsed
10713 ;; link due to the limitation in `org-add-link-type'
10714 ;; ("open" function called with a single argument).
10715 ;; If no such function is found, fallback to
10716 ;; `org-open-file'.
10718 ;; Note : "file+emacs" and "file+sys" types are
10719 ;; hard-coded in order to escape the previous
10720 ;; limitation.
10721 (let* ((option (org-element-property :search-option link))
10722 (app (org-element-property :application link))
10723 (dedicated-function
10724 (nth 1 (assoc app org-link-protocols))))
10725 (if dedicated-function
10726 (funcall dedicated-function
10727 (concat path
10728 (and option (concat "::" option))))
10729 (apply #'org-open-file
10730 path
10731 (cond (arg)
10732 ((equal app "emacs") 'emacs)
10733 ((equal app "sys") 'system))
10734 (cond ((not option) nil)
10735 ((org-string-match-p "\\`[0-9]+\\'" option)
10736 (list (string-to-number option)))
10737 (t (list nil
10738 (org-link-unescape option)))))))))
10739 ((assoc type org-link-protocols)
10740 (funcall (nth 1 (assoc type org-link-protocols)) path))
10741 ((equal type "help")
10742 (let ((f-or-v (intern path)))
10743 (cond ((fboundp f-or-v) (describe-function f-or-v))
10744 ((boundp f-or-v) (describe-variable f-or-v))
10745 (t (error "Not a known function or variable")))))
10746 ((member type '("http" "https" "ftp" "mailto" "news"))
10747 (browse-url (url-encode-url (concat type ":" path))))
10748 ((equal type "doi")
10749 (browse-url (url-encode-url (concat org-doi-server-url path))))
10750 ((equal type "message") (browse-url (concat type ":" path)))
10751 ((equal type "shell")
10752 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10753 (cmd path))
10754 (if (or (and (org-string-nw-p
10755 org-confirm-shell-link-not-regexp)
10756 (string-match
10757 org-confirm-shell-link-not-regexp cmd))
10758 (not org-confirm-shell-link-function)
10759 (funcall org-confirm-shell-link-function
10760 (format "Execute \"%s\" in shell? "
10761 (org-add-props cmd nil
10762 'face 'org-warning))))
10763 (progn
10764 (message "Executing %s" cmd)
10765 (shell-command cmd buf)
10766 (when (featurep 'midnight)
10767 (setq clean-buffer-list-kill-buffer-names
10768 (cons (buffer-name buf)
10769 clean-buffer-list-kill-buffer-names))))
10770 (user-error "Abort"))))
10771 ((equal type "elisp")
10772 (let ((cmd path))
10773 (if (or (and (org-string-nw-p
10774 org-confirm-elisp-link-not-regexp)
10775 (org-string-match-p
10776 org-confirm-elisp-link-not-regexp cmd))
10777 (not org-confirm-elisp-link-function)
10778 (funcall org-confirm-elisp-link-function
10779 (format "Execute \"%s\" as elisp? "
10780 (org-add-props cmd nil
10781 'face 'org-warning))))
10782 (message "%s => %s" cmd
10783 (if (eq (string-to-char cmd) ?\()
10784 (eval (read cmd))
10785 (call-interactively (read cmd))))
10786 (user-error "Abort"))))
10787 ((equal type "id")
10788 (require 'org-id)
10789 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10790 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10791 (unless (run-hook-with-args-until-success
10792 'org-open-link-functions path)
10793 (if (not arg) (org-mark-ring-push)
10794 (switch-to-buffer-other-window
10795 (org-get-buffer-for-internal-link (current-buffer))))
10796 (let ((destination
10797 (org-with-wide-buffer
10798 (if (equal type "radio")
10799 (org-search-radio-target
10800 (org-element-property :path link))
10801 (org-link-search
10802 (if (member type '("custom-id" "coderef"))
10803 (org-element-property :raw-link link)
10804 path)
10805 ;; Prevent fuzzy links from matching
10806 ;; themselves.
10807 (and (equal type "fuzzy")
10808 (+ 2 (org-element-property :begin link)))))
10809 (point))))
10810 (unless (and (<= (point-min) destination)
10811 (>= (point-max) destination))
10812 (widen))
10813 (goto-char destination))))
10814 (t (browse-url-at-point))))))
10815 ;; On a footnote reference or at a footnote definition's label.
10816 ((or (eq type 'footnote-reference)
10817 (and (eq type 'footnote-definition)
10818 (save-excursion
10819 ;; Do not validate action when point is on the
10820 ;; spaces right after the footnote label, in
10821 ;; order to be on par with behaviour on links.
10822 (skip-chars-forward " \t")
10823 (let ((begin
10824 (org-element-property :contents-begin context)))
10825 (if begin (< (point) begin)
10826 (= (org-element-property :post-affiliated context)
10827 (line-beginning-position)))))))
10828 (org-footnote-action))
10829 (t (user-error "No link found")))))
10830 (run-hook-with-args 'org-follow-link-hook)))
10832 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10833 "Offer links in the current entry and return the selected link.
10834 If there is only one link, return it.
10835 If NTH is an integer, return the NTH link found.
10836 If ZERO is a string, check also this string for a link, and if
10837 there is one, return it."
10838 (with-current-buffer buffer
10839 (save-excursion
10840 (save-restriction
10841 (widen)
10842 (goto-char marker)
10843 (let ((cnt ?0)
10844 have-zero end links link c)
10845 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10846 (push (match-string 0 zero) links)
10847 (setq cnt (1- cnt) have-zero t))
10848 (save-excursion
10849 (org-back-to-heading t)
10850 (setq end (save-excursion (outline-next-heading) (point)))
10851 (while (re-search-forward org-any-link-re end t)
10852 (push (match-string 0) links))
10853 (setq links (org-uniquify (reverse links))))
10854 (cond
10855 ((null links)
10856 (message "No links"))
10857 ((equal (length links) 1)
10858 (setq link (car links)))
10859 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10860 (setq link (nth (if have-zero nth (1- nth)) links)))
10861 (t ; we have to select a link
10862 (save-excursion
10863 (save-window-excursion
10864 (delete-other-windows)
10865 (with-output-to-temp-buffer "*Select Link*"
10866 (dolist (l links)
10867 (cond
10868 ((not (string-match org-bracket-link-regexp l))
10869 (princ (format "[%c] %s\n" (cl-incf cnt)
10870 (org-remove-angle-brackets l))))
10871 ((match-end 3)
10872 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10873 (match-string 3 l) (match-string 1 l))))
10874 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10875 (match-string 1 l)))))))
10876 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10877 (message "Select link to open, RET to open all:")
10878 (setq c (read-char-exclusive))
10879 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10880 (when (equal c ?q) (user-error "Abort"))
10881 (if (equal c ?\C-m)
10882 (setq link links)
10883 (setq nth (- c ?0))
10884 (when have-zero (setq nth (1+ nth)))
10885 (unless (and (integerp nth) (>= (length links) nth))
10886 (user-error "Invalid link selection"))
10887 (setq link (nth (1- nth) links)))))
10888 (cons link end))))))
10890 ;; TODO: These functions are deprecated since `org-open-at-point'
10891 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10892 (defun org-open-file-with-system (path)
10893 "Open file at PATH using the system way of opening it."
10894 (org-open-file path 'system))
10895 (defun org-open-file-with-emacs (path)
10896 "Open file at PATH in Emacs."
10897 (org-open-file path 'emacs))
10900 ;;; File search
10902 (defvar org-create-file-search-functions nil
10903 "List of functions to construct the right search string for a file link.
10904 These functions are called in turn with point at the location to
10905 which the link should point.
10907 A function in the hook should first test if it would like to
10908 handle this file type, for example by checking the `major-mode'
10909 or the file extension. If it decides not to handle this file, it
10910 should just return nil to give other functions a chance. If it
10911 does handle the file, it must return the search string to be used
10912 when following the link. The search string will be part of the
10913 file link, given after a double colon, and `org-open-at-point'
10914 will automatically search for it. If special measures must be
10915 taken to make the search successful, another function should be
10916 added to the companion hook `org-execute-file-search-functions',
10917 which see.
10919 A function in this hook may also use `setq' to set the variable
10920 `description' to provide a suggestion for the descriptive text to
10921 be used for this link when it gets inserted into an Org-mode
10922 buffer with \\[org-insert-link].")
10924 (defvar org-execute-file-search-functions nil
10925 "List of functions to execute a file search triggered by a link.
10927 Functions added to this hook must accept a single argument, the
10928 search string that was part of the file link, the part after the
10929 double colon. The function must first check if it would like to
10930 handle this search, for example by checking the `major-mode' or
10931 the file extension. If it decides not to handle this search, it
10932 should just return nil to give other functions a chance. If it
10933 does handle the search, it must return a non-nil value to keep
10934 other functions from trying.
10936 Each function can access the current prefix argument through the
10937 variable `current-prefix-arg'. Note that a single prefix is used
10938 to force opening a link in Emacs, so it may be good to only use a
10939 numeric or double prefix to guide the search function.
10941 In case this is needed, a function in this hook can also restore
10942 the window configuration before `org-open-at-point' was called using:
10944 \(set-window-configuration org-window-config-before-follow-link)")
10946 (defun org-search-radio-target (target)
10947 "Search a radio target matching TARGET in current buffer.
10948 White spaces are not significant."
10949 (let ((re (format "<<<%s>>>"
10950 (mapconcat #'regexp-quote
10951 (org-split-string target "[ \t\n]+")
10952 "[ \t]+\\(?:\n[ \t]*\\)?")))
10953 (origin (point)))
10954 (goto-char (point-min))
10955 (catch :radio-match
10956 (while (re-search-forward re nil t)
10957 (backward-char)
10958 (let ((object (org-element-context)))
10959 (when (eq (org-element-type object) 'radio-target)
10960 (goto-char (org-element-property :begin object))
10961 (org-show-context 'link-search)
10962 (throw :radio-match nil))))
10963 (goto-char origin)
10964 (user-error "No match for radio target: %s" target))))
10966 (defun org-link-search (s &optional avoid-pos stealth)
10967 "Search for a search string S.
10969 If S starts with \"#\", it triggers a custom ID search.
10971 If S is enclosed within parenthesis, it initiates a coderef
10972 search.
10974 If S is surrounded by forward slashes, it is interpreted as
10975 a regular expression. In Org mode files, this will create an
10976 `org-occur' sparse tree. In ordinary files, `occur' will be used
10977 to list matches. If the current buffer is in `dired-mode', grep
10978 will be used to search in all files.
10980 When AVOID-POS is given, ignore matches near that position.
10982 When optional argument STEALTH is non-nil, do not modify
10983 visibility around point, thus ignoring `org-show-context-detail'
10984 variable.
10986 Search is case-insensitive and ignores white spaces. Return type
10987 of matched result, with is either `dedicated' or `fuzzy'."
10988 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10989 (let* ((case-fold-search t)
10990 (origin (point))
10991 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10992 (words (org-split-string s "[ \t\n]+"))
10993 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10994 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10995 type)
10996 (cond
10997 ;; Check if there are any special search functions.
10998 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10999 ((eq (string-to-char s) ?#)
11000 ;; Look for a custom ID S if S starts with "#".
11001 (let* ((id (substring normalized 1))
11002 (match (org-find-property "CUSTOM_ID" id)))
11003 (if match (progn (goto-char match) (setf type 'dedicated))
11004 (error "No match for custom ID: %s" id))))
11005 ((string-match "\\`(\\(.*\\))\\'" normalized)
11006 ;; Look for coderef targets if S is enclosed within parenthesis.
11007 (let ((coderef (match-string-no-properties 1 normalized))
11008 (re (substring s-single-re 1 -1)))
11009 (goto-char (point-min))
11010 (catch :coderef-match
11011 (while (re-search-forward re nil t)
11012 (let ((element (org-element-at-point)))
11013 (when (and (memq (org-element-type element)
11014 '(example-block src-block))
11015 ;; Build proper regexp according to current
11016 ;; block's label format.
11017 (let ((label-fmt
11018 (regexp-quote
11019 (or (org-element-property :label-fmt element)
11020 org-coderef-label-format))))
11021 (save-excursion
11022 (beginning-of-line)
11023 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11024 (format label-fmt coderef))))))
11025 (setq type 'dedicated)
11026 (goto-char (match-beginning 1))
11027 (throw :coderef-match nil))))
11028 (goto-char origin)
11029 (error "No match for coderef: %s" coderef))))
11030 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11031 ;; Look for a regular expression.
11032 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11033 (match-string 1 s)))
11034 ;; Fuzzy links.
11036 (let ((starred (eq (string-to-char normalized) ?*)))
11037 (cond
11038 ;; Look for targets, only if not in a headline search.
11039 ((and (not starred)
11040 (let ((target (format "<<%s>>" s-multi-re)))
11041 (catch :target-match
11042 (goto-char (point-min))
11043 (while (re-search-forward target nil t)
11044 (backward-char)
11045 (let ((context (org-element-context)))
11046 (when (eq (org-element-type context) 'target)
11047 (setq type 'dedicated)
11048 (goto-char (org-element-property :begin context))
11049 (throw :target-match t))))
11050 nil))))
11051 ;; Look for elements named after S, only if not in a headline
11052 ;; search.
11053 ((and (not starred)
11054 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11055 (catch :name-match
11056 (goto-char (point-min))
11057 (while (re-search-forward name nil t)
11058 (let ((element (org-element-at-point)))
11059 (when (equal (org-split-string
11060 (org-element-property :name element)
11061 "[ \t]+")
11062 words)
11063 (setq type 'dedicated)
11064 (beginning-of-line)
11065 (throw :name-match t))))
11066 nil))))
11067 ;; Regular text search. Prefer headlines in Org mode
11068 ;; buffers.
11069 ((and (derived-mode-p 'org-mode)
11070 (let* ((wspace "[ \t]")
11071 (wspaceopt (concat wspace "*"))
11072 (cookie (concat "\\(?:"
11073 wspaceopt
11074 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11075 wspaceopt
11076 "\\)"))
11077 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11078 (re (concat
11079 org-outline-regexp-bol
11080 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11081 "\\(?:\\[#.\\][ \t]+\\)?"
11082 "\\(?:" org-comment-string "[ \t]+\\)?"
11083 sep "?"
11084 (let ((title (mapconcat #'regexp-quote
11085 words
11086 sep)))
11087 (if starred (substring title 1) title))
11088 sep "?"
11089 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11090 "[ \t]*$")))
11091 (goto-char (point-min))
11092 (re-search-forward re nil t)))
11093 (goto-char (match-beginning 0))
11094 (setq type 'dedicated))
11095 ;; Offer to create non-existent headline depending on
11096 ;; `org-link-search-must-match-exact-headline'.
11097 ((and (derived-mode-p 'org-mode)
11098 (not org-link-search-inhibit-query)
11099 (eq org-link-search-must-match-exact-headline 'query-to-create)
11100 (yes-or-no-p "No match - create this as a new heading? "))
11101 (goto-char (point-max))
11102 (unless (bolp) (newline))
11103 (org-insert-heading nil t t)
11104 (insert s "\n")
11105 (beginning-of-line 0))
11106 ;; Only headlines are looked after. No need to process
11107 ;; further: throw an error.
11108 ((and (derived-mode-p 'org-mode)
11109 (or starred org-link-search-must-match-exact-headline))
11110 (goto-char origin)
11111 (error "No match for fuzzy expression: %s" normalized))
11112 ;; Regular text search.
11113 ((catch :fuzzy-match
11114 (goto-char (point-min))
11115 (while (re-search-forward s-multi-re nil t)
11116 ;; Skip match if it contains AVOID-POS or it is included
11117 ;; in a link with a description but outside the
11118 ;; description.
11119 (unless (or (and avoid-pos
11120 (<= (match-beginning 0) avoid-pos)
11121 (> (match-end 0) avoid-pos))
11122 (and (save-match-data
11123 (org-in-regexp org-bracket-link-regexp))
11124 (match-beginning 3)
11125 (or (> (match-beginning 3) (point))
11126 (<= (match-end 3) (point)))
11127 (org-element-lineage
11128 (save-match-data (org-element-context))
11129 '(link) t)))
11130 (goto-char (match-beginning 0))
11131 (setq type 'fuzzy)
11132 (throw :fuzzy-match t)))
11133 nil))
11134 ;; All failed. Throw an error.
11135 (t (goto-char origin)
11136 (error "No match for fuzzy expression: %s" normalized))))))
11137 ;; Disclose surroundings of match, if appropriate.
11138 (when (and (derived-mode-p 'org-mode) (not stealth))
11139 (org-show-context 'link-search))
11140 type))
11142 (defun org-get-buffer-for-internal-link (buffer)
11143 "Return a buffer to be used for displaying the link target of internal links."
11144 (cond
11145 ((not org-display-internal-link-with-indirect-buffer)
11146 buffer)
11147 ((string-match "(Clone)$" (buffer-name buffer))
11148 (message "Buffer is already a clone, not making another one")
11149 ;; we also do not modify visibility in this case
11150 buffer)
11151 (t ; make a new indirect buffer for displaying the link
11152 (let* ((bn (buffer-name buffer))
11153 (ibn (concat bn "(Clone)"))
11154 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11155 (with-current-buffer ib (org-overview))
11156 ib))))
11158 (defun org-do-occur (regexp &optional cleanup)
11159 "Call the Emacs command `occur'.
11160 If CLEANUP is non-nil, remove the printout of the regular expression
11161 in the *Occur* buffer. This is useful if the regex is long and not useful
11162 to read."
11163 (occur regexp)
11164 (when cleanup
11165 (let ((cwin (selected-window)) win beg end)
11166 (when (setq win (get-buffer-window "*Occur*"))
11167 (select-window win))
11168 (goto-char (point-min))
11169 (when (re-search-forward "match[a-z]+" nil t)
11170 (setq beg (match-end 0))
11171 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11172 (setq end (1- (match-beginning 0)))))
11173 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11174 (goto-char (point-min))
11175 (select-window cwin))))
11177 ;;; The mark ring for links jumps
11179 (defvar org-mark-ring nil
11180 "Mark ring for positions before jumps in Org-mode.")
11181 (defvar org-mark-ring-last-goto nil
11182 "Last position in the mark ring used to go back.")
11183 ;; Fill and close the ring
11184 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11185 (dotimes (_ org-mark-ring-length)
11186 (push (make-marker) org-mark-ring))
11187 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11188 org-mark-ring)
11190 (defun org-mark-ring-push (&optional pos buffer)
11191 "Put the current position or POS into the mark ring and rotate it."
11192 (interactive)
11193 (setq pos (or pos (point)))
11194 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11195 (move-marker (car org-mark-ring)
11196 (or pos (point))
11197 (or buffer (current-buffer)))
11198 (message "%s"
11199 (substitute-command-keys
11200 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11202 (defun org-mark-ring-goto (&optional n)
11203 "Jump to the previous position in the mark ring.
11204 With prefix arg N, jump back that many stored positions. When
11205 called several times in succession, walk through the entire ring.
11206 Org-mode commands jumping to a different position in the current file,
11207 or to another Org-mode file, automatically push the old position
11208 onto the ring."
11209 (interactive "p")
11210 (let (p m)
11211 (if (eq last-command this-command)
11212 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11213 (setq p org-mark-ring))
11214 (setq org-mark-ring-last-goto p)
11215 (setq m (car p))
11216 (pop-to-buffer-same-window (marker-buffer m))
11217 (goto-char m)
11218 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11220 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11221 ;;; Emacs 24.4+
11222 (defun org-remove-angle-brackets (s)
11223 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11224 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11226 (defun org-add-angle-brackets (s)
11227 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11228 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11230 (defun org-remove-double-quotes (s)
11231 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11232 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11235 ;;; Following specific links
11237 (defvar org-agenda-buffer-tmp-name)
11238 (defvar org-agenda-start-on-weekday)
11239 (defun org-follow-timestamp-link ()
11240 "Open an agenda view for the time-stamp date/range at point."
11241 (cond
11242 ((org-at-date-range-p t)
11243 (let ((org-agenda-start-on-weekday)
11244 (t1 (match-string 1))
11245 (t2 (match-string 2)) tt1 tt2)
11246 (setq tt1 (time-to-days (org-time-string-to-time t1))
11247 tt2 (time-to-days (org-time-string-to-time t2)))
11248 (let ((org-agenda-buffer-tmp-name
11249 (format "*Org Agenda(a:%s)"
11250 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11251 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11252 ((org-at-timestamp-p t)
11253 (let ((org-agenda-buffer-tmp-name
11254 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11255 (org-agenda-list nil (time-to-days (org-time-string-to-time
11256 (substring (match-string 1) 0 10)))
11257 1)))
11258 (t (error "This should not happen"))))
11261 ;;; Following file links
11262 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11263 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11264 (declare-function mailcap-mime-info
11265 "mailcap" (string &optional request no-decode))
11266 (defvar org-wait nil)
11267 (defun org-open-file (path &optional in-emacs line search)
11268 "Open the file at PATH.
11269 First, this expands any special file name abbreviations. Then the
11270 configuration variable `org-file-apps' is checked if it contains an
11271 entry for this file type, and if yes, the corresponding command is launched.
11273 If no application is found, Emacs simply visits the file.
11275 With optional prefix argument IN-EMACS, Emacs will visit the file.
11276 With a double \\[universal-argument] \\[universal-argument] \
11277 prefix arg, Org tries to avoid opening in Emacs
11278 and to use an external application to visit the file.
11280 Optional LINE specifies a line to go to, optional SEARCH a string
11281 to search for. If LINE or SEARCH is given, the file will be
11282 opened in Emacs, unless an entry from org-file-apps that makes
11283 use of groups in a regexp matches.
11285 If you want to change the way frames are used when following a
11286 link, please customize `org-link-frame-setup'.
11288 If the file does not exist, an error is thrown."
11289 (let* ((file (if (equal path "")
11290 buffer-file-name
11291 (substitute-in-file-name (expand-file-name path))))
11292 (file-apps (append org-file-apps (org-default-apps)))
11293 (apps (cl-remove-if
11294 'org-file-apps-entry-match-against-dlink-p file-apps))
11295 (apps-dlink (cl-remove-if-not
11296 'org-file-apps-entry-match-against-dlink-p file-apps))
11297 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11298 (dirp (unless remp (file-directory-p file)))
11299 (file (if (and dirp org-open-directory-means-index-dot-org)
11300 (concat (file-name-as-directory file) "index.org")
11301 file))
11302 (a-m-a-p (assq 'auto-mode apps))
11303 (dfile (downcase file))
11304 ;; Reconstruct the original link from the PATH, LINE and
11305 ;; SEARCH args.
11306 (link (cond (line (concat file "::" (number-to-string line)))
11307 (search (concat file "::" search))
11308 (t file)))
11309 (dlink (downcase link))
11310 (old-buffer (current-buffer))
11311 (old-pos (point))
11312 (old-mode major-mode)
11313 (ext
11314 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11315 (match-string 1 dfile)))
11316 cmd link-match-data)
11317 (cond
11318 ((member in-emacs '((16) system))
11319 (setq cmd (cdr (assq 'system apps))))
11320 (in-emacs (setq cmd 'emacs))
11322 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11323 (and dirp (cdr (assq 'directory apps)))
11324 ;; First, try matching against apps-dlink if we
11325 ;; get a match here, store the match data for
11326 ;; later.
11327 (let ((match (assoc-default dlink apps-dlink
11328 'string-match)))
11329 (if match
11330 (progn (setq link-match-data (match-data))
11331 match)
11332 (progn (setq in-emacs (or in-emacs line search))
11333 nil))) ; if we have no match in apps-dlink,
11334 ; always open the file in emacs if line or search
11335 ; is given (for backwards compatibility)
11336 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11337 'string-match)
11338 (cdr (assoc ext apps))
11339 (cdr (assq t apps))))))
11340 (when (eq cmd 'system)
11341 (setq cmd (cdr (assoc 'system apps))))
11342 (when (eq cmd 'default)
11343 (setq cmd (cdr (assoc t apps))))
11344 (when (eq cmd 'mailcap)
11345 (require 'mailcap)
11346 (mailcap-parse-mailcaps)
11347 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11348 (command (mailcap-mime-info mime-type)))
11349 (if (stringp command)
11350 (setq cmd command)
11351 (setq cmd 'emacs))))
11352 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11353 (not (file-exists-p file))
11354 (not org-open-non-existing-files))
11355 (user-error "No such file: %s" file))
11356 (cond
11357 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11358 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11359 (while (string-match "['\"]%s['\"]" cmd)
11360 (setq cmd (replace-match "%s" t t cmd)))
11361 (while (string-match "%s" cmd)
11362 (setq cmd (replace-match
11363 (save-match-data
11364 (shell-quote-argument
11365 (convert-standard-filename file)))
11366 t t cmd)))
11368 ;; Replace "%1", "%2" etc. in command with group matches from regex
11369 (save-match-data
11370 (let ((match-index 1)
11371 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11372 (set-match-data link-match-data)
11373 (while (<= match-index number-of-groups)
11374 (let ((regex (concat "%" (number-to-string match-index)))
11375 (replace-with (match-string match-index dlink)))
11376 (while (string-match regex cmd)
11377 (setq cmd (replace-match replace-with t t cmd))))
11378 (setq match-index (+ match-index 1)))))
11380 (save-window-excursion
11381 (message "Running %s...done" cmd)
11382 (start-process-shell-command cmd nil cmd)
11383 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11384 ((or (stringp cmd)
11385 (eq cmd 'emacs))
11386 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11387 (widen)
11388 (cond (line (org-goto-line line)
11389 (when (derived-mode-p 'org-mode) (org-reveal)))
11390 (search (org-link-search search))))
11391 ((functionp cmd)
11392 (save-match-data
11393 (set-match-data link-match-data)
11394 (condition-case nil
11395 (funcall cmd file link)
11396 ;; FIXME: Remove this check when most default installations
11397 ;; of Emacs have at least Org 9.0.
11398 ((debug wrong-number-of-arguments wrong-type-argument
11399 invalid-function)
11400 (user-error "Please see Org News for version 9.0 about \
11401 `org-file-apps'--Lisp error: %S" cmd)))))
11402 ((consp cmd)
11403 ;; FIXME: Remove this check when most default installations of
11404 ;; Emacs have at least Org 9.0.
11405 ;; Heads-up instead of silently fall back to
11406 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11407 ;; with sexp instead of a function for `cmd'.
11408 (user-error "Please see Org News for version 9.0 about \
11409 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11410 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11411 (and (derived-mode-p 'org-mode)
11412 (eq old-mode 'org-mode)
11413 (or (not (eq old-buffer (current-buffer)))
11414 (not (eq old-pos (point))))
11415 (org-mark-ring-push old-pos old-buffer))))
11417 (defun org-file-apps-entry-match-against-dlink-p (entry)
11418 "This function returns non-nil if `entry' uses a regular
11419 expression which should be matched against the whole link by
11420 org-open-file.
11422 It assumes that is the case when the entry uses a regular
11423 expression which has at least one grouping construct and the
11424 action is either a lisp form or a command string containing
11425 `%1', i.e. using at least one subexpression match as a
11426 parameter."
11427 (let ((selector (car entry))
11428 (action (cdr entry)))
11429 (if (stringp selector)
11430 (and (> (regexp-opt-depth selector) 0)
11431 (or (and (stringp action)
11432 (string-match "%[0-9]" action))
11433 (consp action)))
11434 nil)))
11436 (defun org-default-apps ()
11437 "Return the default applications for this operating system."
11438 (cond
11439 ((eq system-type 'darwin)
11440 org-file-apps-defaults-macosx)
11441 ((eq system-type 'windows-nt)
11442 org-file-apps-defaults-windowsnt)
11443 (t org-file-apps-defaults-gnu)))
11445 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11446 "Convert extensions to regular expressions in the cars of LIST.
11447 Also, weed out any non-string entries, because the return value is used
11448 only for regexp matching.
11449 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11450 point to the symbol `emacs', indicating that the file should
11451 be opened in Emacs."
11452 (append
11453 (delq nil
11454 (mapcar (lambda (x)
11455 (unless (not (stringp (car x)))
11456 (if (string-match "\\W" (car x))
11458 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11459 list))
11460 (when add-auto-mode
11461 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11463 (defvar ange-ftp-name-format)
11464 (defun org-file-remote-p (file)
11465 "Test whether FILE specifies a location on a remote system.
11466 Return non-nil if the location is indeed remote.
11468 For example, the filename \"/user@host:/foo\" specifies a location
11469 on the system \"/user@host:\"."
11470 (cond ((fboundp 'file-remote-p)
11471 (file-remote-p file))
11472 ((fboundp 'tramp-handle-file-remote-p)
11473 (tramp-handle-file-remote-p file))
11474 ((and (boundp 'ange-ftp-name-format)
11475 (string-match (car ange-ftp-name-format) file))
11476 t)))
11479 ;;;; Refiling
11481 (defun org-get-org-file ()
11482 "Read a filename, with default directory `org-directory'."
11483 (let ((default (or org-default-notes-file remember-data-file)))
11484 (read-file-name (format "File name [%s]: " default)
11485 (file-name-as-directory org-directory)
11486 default)))
11488 (defun org-notes-order-reversed-p ()
11489 "Check if the current file should receive notes in reversed order."
11490 (cond
11491 ((not org-reverse-note-order) nil)
11492 ((eq t org-reverse-note-order) t)
11493 ((not (listp org-reverse-note-order)) nil)
11494 (t (catch 'exit
11495 (dolist (entry org-reverse-note-order)
11496 (when (string-match (car entry) buffer-file-name)
11497 (throw 'exit (cdr entry))))))))
11499 (defvar org-refile-target-table nil
11500 "The list of refile targets, created by `org-refile'.")
11502 (defvar org-agenda-new-buffers nil
11503 "Buffers created to visit agenda files.")
11505 (defvar org-refile-cache nil
11506 "Cache for refile targets.")
11508 (defvar org-refile-markers nil
11509 "All the markers used for caching refile locations.")
11511 (defun org-refile-marker (pos)
11512 "Get a new refile marker, but only if caching is in use."
11513 (if (not org-refile-use-cache)
11515 (let ((m (make-marker)))
11516 (move-marker m pos)
11517 (push m org-refile-markers)
11518 m)))
11520 (defun org-refile-cache-clear ()
11521 "Clear the refile cache and disable all the markers."
11522 (dolist (m org-refile-markers) (move-marker m nil))
11523 (setq org-refile-markers nil)
11524 (setq org-refile-cache nil)
11525 (message "Refile cache has been cleared"))
11527 (defun org-refile-cache-check-set (set)
11528 "Check if all the markers in the cache still have live buffers."
11529 (let (marker)
11530 (catch 'exit
11531 (while (and set (setq marker (nth 3 (pop set))))
11532 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11533 (when (and marker (null (marker-buffer marker)))
11534 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11535 (sit-for 3)
11536 (throw 'exit nil)))
11537 t)))
11539 (defun org-refile-cache-put (set &rest identifiers)
11540 "Push the refile targets SET into the cache, under IDENTIFIERS."
11541 (let* ((key (sha1 (prin1-to-string identifiers)))
11542 (entry (assoc key org-refile-cache)))
11543 (if entry
11544 (setcdr entry set)
11545 (push (cons key set) org-refile-cache))))
11547 (defun org-refile-cache-get (&rest identifiers)
11548 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11549 (cond
11550 ((not org-refile-cache) nil)
11551 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11553 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11554 org-refile-cache))))
11555 (and set (org-refile-cache-check-set set) set)))))
11557 (defvar org-outline-path-cache nil
11558 "Alist between buffer positions and outline paths.
11559 It value is an alist (POSITION . PATH) where POSITION is the
11560 buffer position at the beginning of an entry and PATH is a list
11561 of strings describing the outline path for that entry, in reverse
11562 order.")
11564 (defun org-refile-get-targets (&optional default-buffer)
11565 "Produce a table with refile targets."
11566 (let ((case-fold-search nil)
11567 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11568 (entries (or org-refile-targets '((nil . (:level . 1)))))
11569 targets tgs files desc descre)
11570 (message "Getting targets...")
11571 (with-current-buffer (or default-buffer (current-buffer))
11572 (dolist (entry entries)
11573 (setq files (car entry) desc (cdr entry))
11574 (cond
11575 ((null files) (setq files (list (current-buffer))))
11576 ((eq files 'org-agenda-files)
11577 (setq files (org-agenda-files 'unrestricted)))
11578 ((and (symbolp files) (fboundp files))
11579 (setq files (funcall files)))
11580 ((and (symbolp files) (boundp files))
11581 (setq files (symbol-value files))))
11582 (when (stringp files) (setq files (list files)))
11583 (cond
11584 ((eq (car desc) :tag)
11585 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11586 ((eq (car desc) :todo)
11587 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11588 ((eq (car desc) :regexp)
11589 (setq descre (cdr desc)))
11590 ((eq (car desc) :level)
11591 (setq descre (concat "^\\*\\{" (number-to-string
11592 (if org-odd-levels-only
11593 (1- (* 2 (cdr desc)))
11594 (cdr desc)))
11595 "\\}[ \t]")))
11596 ((eq (car desc) :maxlevel)
11597 (setq descre (concat "^\\*\\{1," (number-to-string
11598 (if org-odd-levels-only
11599 (1- (* 2 (cdr desc)))
11600 (cdr desc)))
11601 "\\}[ \t]")))
11602 (t (error "Bad refiling target description %s" desc)))
11603 (dolist (f files)
11604 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11606 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11607 (progn
11608 (when (bufferp f)
11609 (setq f (buffer-file-name (buffer-base-buffer f))))
11610 (setq f (and f (expand-file-name f)))
11611 (when (eq org-refile-use-outline-path 'file)
11612 (push (list (file-name-nondirectory f) f nil nil) tgs))
11613 (org-with-wide-buffer
11614 (goto-char (point-min))
11615 (setq org-outline-path-cache nil)
11616 (while (re-search-forward descre nil t)
11617 (beginning-of-line)
11618 (looking-at org-complex-heading-regexp)
11619 (let ((begin (point))
11620 (heading (match-string-no-properties 4)))
11621 (unless (or (and
11622 org-refile-target-verify-function
11623 (not
11624 (funcall org-refile-target-verify-function)))
11625 (not heading))
11626 (let ((re (format org-complex-heading-regexp-format
11627 (regexp-quote heading)))
11628 (target
11629 (if (not org-refile-use-outline-path) heading
11630 (mapconcat
11631 #'org-protect-slash
11632 (append
11633 (pcase org-refile-use-outline-path
11634 (`file (list (file-name-nondirectory
11635 (buffer-file-name
11636 (buffer-base-buffer)))))
11637 (`full-file-path
11638 (list (buffer-file-name
11639 (buffer-base-buffer))))
11640 (_ nil))
11641 (org-get-outline-path t t))
11642 "/"))))
11643 (push (list target f re (org-refile-marker (point)))
11644 tgs)))
11645 (when (= (point) begin)
11646 ;; Verification function has not moved point.
11647 (end-of-line)))))))
11648 (when org-refile-use-cache
11649 (org-refile-cache-put tgs (buffer-file-name) descre))
11650 (setq targets (append tgs targets))))))
11651 (message "Getting targets...done")
11652 (nreverse targets)))
11654 (defun org-protect-slash (s)
11655 (while (string-match "/" s)
11656 (setq s (replace-match "\\" t t s)))
11659 (defun org--get-outline-path-1 (&optional use-cache)
11660 "Return outline path to current headline.
11662 Outline path is a list of strings, in reverse order. When
11663 optional argument USE-CACHE is non-nil, make use of a cache. See
11664 `org-get-outline-path' for details.
11666 Assume buffer is widened and point is on a headline."
11667 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11668 (let ((p (point))
11669 (heading (progn
11670 (looking-at org-complex-heading-regexp)
11671 (if (not (match-end 4)) ""
11672 ;; Remove statistics cookies.
11673 (org-trim
11674 (org-link-display-format
11675 (replace-regexp-in-string
11676 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11677 (match-string-no-properties 4))))))))
11678 (if (org-up-heading-safe)
11679 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11680 (when use-cache
11681 (push (cons p path) org-outline-path-cache))
11682 path)
11683 ;; This is a new root node. Since we assume we are moving
11684 ;; forward, we can drop previous cache so as to limit number
11685 ;; of associations there.
11686 (let ((path (list heading)))
11687 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11688 path)))))
11690 (defun org-get-outline-path (&optional with-self use-cache)
11691 "Return the outline path to the current entry.
11693 An outline path is a list of ancestors for current headline, as
11694 a list of strings. Statistics cookies are removed and links are
11695 replaced with their description, if any, or their path otherwise.
11697 When optional argument WITH-SELF is non-nil, the path also
11698 includes the current headline.
11700 When optional argument USE-CACHE is non-nil, cache outline paths
11701 between calls to this function so as to avoid backtracking. This
11702 argument is useful when planning to find more than one outline
11703 path in the same document. In that case, there are two
11704 conditions to satisfy:
11705 - `org-outline-path-cache' is set to nil before starting the
11706 process;
11707 - outline paths are computed by increasing buffer positions."
11708 (org-with-wide-buffer
11709 (and (or (and with-self (org-back-to-heading t))
11710 (org-up-heading-safe))
11711 (reverse (org--get-outline-path-1 use-cache)))))
11713 (defun org-format-outline-path (path &optional width prefix separator)
11714 "Format the outline path PATH for display.
11715 WIDTH is the maximum number of characters that is available.
11716 PREFIX is a prefix to be included in the returned string,
11717 such as the file name.
11718 SEPARATOR is inserted between the different parts of the path,
11719 the default is \"/\"."
11720 (setq width (or width 79))
11721 (setq path (delq nil path))
11722 (unless (> width 0)
11723 (user-error "Argument `width' must be positive"))
11724 (setq separator (or separator "/"))
11725 (let* ((org-odd-levels-only nil)
11726 (fpath (concat
11727 prefix (and prefix path separator)
11728 (mapconcat
11729 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11730 (cl-loop for head in path
11731 for n from 0
11732 collect (org-add-props
11733 head nil 'face
11734 (nth (% n org-n-level-faces) org-level-faces)))
11735 separator))))
11736 (when (> (length fpath) width)
11737 (if (< width 7)
11738 ;; It's unlikely that `width' will be this small, but don't
11739 ;; waste characters by adding ".." if it is.
11740 (setq fpath (substring fpath 0 width))
11741 (setf (substring fpath (- width 2)) "..")))
11742 fpath))
11744 (defun org-display-outline-path (&optional file current separator just-return-string)
11745 "Display the current outline path in the echo area.
11747 If FILE is non-nil, prepend the output with the file name.
11748 If CURRENT is non-nil, append the current heading to the output.
11749 SEPARATOR is passed through to `org-format-outline-path'. It separates
11750 the different parts of the path and defaults to \"/\".
11751 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11752 (interactive "P")
11753 (let* (case-fold-search
11754 (bfn (buffer-file-name (buffer-base-buffer)))
11755 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11756 res)
11757 (when current (setq path (append path
11758 (save-excursion
11759 (org-back-to-heading t)
11760 (when (looking-at org-complex-heading-regexp)
11761 (list (match-string 4)))))))
11762 (setq res
11763 (org-format-outline-path
11764 path
11765 (1- (frame-width))
11766 (and file bfn (concat (file-name-nondirectory bfn) separator))
11767 separator))
11768 (if just-return-string
11769 (org-no-properties res)
11770 (org-unlogged-message "%s" res))))
11772 (defvar org-refile-history nil
11773 "History for refiling operations.")
11775 (defvar org-after-refile-insert-hook nil
11776 "Hook run after `org-refile' has inserted its stuff at the new location.
11777 Note that this is still *before* the stuff will be removed from
11778 the *old* location.")
11780 (defvar org-capture-last-stored-marker)
11781 (defvar org-refile-keep nil
11782 "Non-nil means `org-refile' will copy instead of refile.")
11784 (defun org-copy ()
11785 "Like `org-refile', but copy."
11786 (interactive)
11787 (let ((org-refile-keep t))
11788 (funcall 'org-refile nil nil nil "Copy")))
11790 (defun org-refile (&optional arg default-buffer rfloc msg)
11791 "Move the entry or entries at point to another heading.
11792 The list of target headings is compiled using the information in
11793 `org-refile-targets', which see.
11795 At the target location, the entry is filed as a subitem of the
11796 target heading. Depending on `org-reverse-note-order', the new
11797 subitem will either be the first or the last subitem.
11799 If there is an active region, all entries in that region will be
11800 refiled. However, the region must fulfill the requirement that
11801 the first heading sets the top-level of the moved text.
11803 With prefix arg ARG, the command will only visit the target
11804 location and not actually move anything.
11806 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11807 refiling operation has put the subtree.
11809 With a numeric prefix argument of `2', refile to the running clock.
11811 With a numeric prefix argument of `3', emulate `org-refile-keep'
11812 being set to t and copy to the target location, don't move it.
11813 Beware that keeping refiled entries may result in duplicated ID
11814 properties.
11816 RFLOC can be a refile location obtained in a different way.
11818 MSG is a string to replace \"Refile\" in the default prompt with
11819 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11821 See also `org-refile-use-outline-path'.
11823 If you are using target caching (see `org-refile-use-cache'), you
11824 have to clear the target cache in order to find new targets.
11825 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11826 prefix argument (`C-u C-u C-u C-c C-w')."
11827 (interactive "P")
11828 (if (member arg '(0 (64)))
11829 (org-refile-cache-clear)
11830 (let* ((actionmsg (cond (msg msg)
11831 ((equal arg 3) "Refile (and keep)")
11832 (t "Refile")))
11833 (regionp (org-region-active-p))
11834 (region-start (and regionp (region-beginning)))
11835 (region-end (and regionp (region-end)))
11836 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11837 pos it nbuf file level reversed)
11838 (setq last-command nil)
11839 (when regionp
11840 (goto-char region-start)
11841 (or (bolp) (goto-char (point-at-bol)))
11842 (setq region-start (point))
11843 (unless (or (org-kill-is-subtree-p
11844 (buffer-substring region-start region-end))
11845 (prog1 org-refile-active-region-within-subtree
11846 (let ((s (point-at-eol)))
11847 (org-toggle-heading)
11848 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11849 (user-error "The region is not a (sequence of) subtree(s)")))
11850 (if (equal arg '(16))
11851 (org-refile-goto-last-stored)
11852 (when (or
11853 (and (equal arg 2)
11854 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11855 (prog1
11856 (setq it (list (or org-clock-heading "running clock")
11857 (buffer-file-name
11858 (marker-buffer org-clock-hd-marker))
11860 (marker-position org-clock-hd-marker)))
11861 (setq arg nil)))
11862 (setq it
11863 (or rfloc
11864 (let (heading-text)
11865 (save-excursion
11866 (unless (and arg (listp arg))
11867 (org-back-to-heading t)
11868 (setq heading-text
11869 (replace-regexp-in-string
11870 org-bracket-link-regexp
11871 "\\3"
11872 (or (nth 4 (org-heading-components))
11873 ""))))
11874 (org-refile-get-location
11875 (cond ((and arg (listp arg)) "Goto")
11876 (regionp (concat actionmsg " region to"))
11877 (t (concat actionmsg " subtree \""
11878 heading-text "\" to")))
11879 default-buffer
11880 (and (not (equal '(4) arg))
11881 org-refile-allow-creating-parent-nodes)))))))
11882 (setq file (nth 1 it)
11883 pos (nth 3 it))
11884 (when (and (not arg)
11886 (equal (buffer-file-name) file)
11887 (if regionp
11888 (and (>= pos region-start)
11889 (<= pos region-end))
11890 (and (>= pos (point))
11891 (< pos (save-excursion
11892 (org-end-of-subtree t t))))))
11893 (error "Cannot refile to position inside the tree or region"))
11894 (setq nbuf (or (find-buffer-visiting file)
11895 (find-file-noselect file)))
11896 (if (and arg (not (equal arg 3)))
11897 (progn
11898 (pop-to-buffer-same-window nbuf)
11899 (goto-char pos)
11900 (org-show-context 'org-goto))
11901 (if regionp
11902 (progn
11903 (org-kill-new (buffer-substring region-start region-end))
11904 (org-save-markers-in-region region-start region-end))
11905 (org-copy-subtree 1 nil t))
11906 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11907 (find-file-noselect file)))
11908 (setq reversed (org-notes-order-reversed-p))
11909 (save-excursion
11910 (save-restriction
11911 (widen)
11912 (if pos
11913 (progn
11914 (goto-char pos)
11915 (looking-at org-outline-regexp)
11916 (setq level (org-get-valid-level (funcall outline-level) 1))
11917 (goto-char
11918 (if reversed
11919 (or (outline-next-heading) (point-max))
11920 (or (save-excursion (org-get-next-sibling))
11921 (org-end-of-subtree t t)
11922 (point-max)))))
11923 (setq level 1)
11924 (if (not reversed)
11925 (goto-char (point-max))
11926 (goto-char (point-min))
11927 (or (outline-next-heading) (goto-char (point-max)))))
11928 (unless (bolp) (newline))
11929 (org-paste-subtree level nil nil t)
11930 (when org-log-refile
11931 (org-add-log-setup 'refile nil nil org-log-refile)
11932 (unless (eq org-log-refile 'note)
11933 (save-excursion (org-add-log-note))))
11934 (and org-auto-align-tags
11935 (let ((org-loop-over-headlines-in-active-region nil))
11936 (org-set-tags nil t)))
11937 (let ((bookmark-name (plist-get org-bookmark-names-plist
11938 :last-refile)))
11939 (when bookmark-name
11940 (with-demoted-errors
11941 (bookmark-set bookmark-name))))
11942 ;; If we are refiling for capture, make sure that the
11943 ;; last-capture pointers point here
11944 (when (bound-and-true-p org-capture-is-refiling)
11945 (let ((bookmark-name (plist-get org-bookmark-names-plist
11946 :last-capture-marker)))
11947 (when bookmark-name
11948 (with-demoted-errors
11949 (bookmark-set bookmark-name))))
11950 (move-marker org-capture-last-stored-marker (point)))
11951 (when (fboundp 'deactivate-mark) (deactivate-mark))
11952 (run-hooks 'org-after-refile-insert-hook))))
11953 (unless org-refile-keep
11954 (if regionp
11955 (delete-region (point) (+ (point) (- region-end region-start)))
11956 (delete-region
11957 (and (org-back-to-heading t) (point))
11958 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11959 (when (featurep 'org-inlinetask)
11960 (org-inlinetask-remove-END-maybe))
11961 (setq org-markers-to-move nil)
11962 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11964 (defun org-refile-goto-last-stored ()
11965 "Go to the location where the last refile was stored."
11966 (interactive)
11967 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11968 (message "This is the location of the last refile"))
11970 (defun org-refile--get-location (refloc tbl)
11971 "When user refile to REFLOC, find the associated target in TBL.
11972 Also check `org-refile-target-table'."
11973 (car (delq
11975 (mapcar
11976 (lambda (r) (or (assoc r tbl)
11977 (assoc r org-refile-target-table)))
11978 (list (replace-regexp-in-string "/$" "" refloc)
11979 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11981 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11982 "Prompt the user for a refile location, using PROMPT.
11983 PROMPT should not be suffixed with a colon and a space, because
11984 this function appends the default value from
11985 `org-refile-history' automatically, if that is not empty."
11986 (let ((org-refile-targets org-refile-targets)
11987 (org-refile-use-outline-path org-refile-use-outline-path))
11988 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11989 (unless org-refile-target-table
11990 (user-error "No refile targets"))
11991 (let* ((cbuf (current-buffer))
11992 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11993 (cfunc (if (and org-refile-use-outline-path
11994 org-outline-path-complete-in-steps)
11995 #'org-olpath-completing-read
11996 #'completing-read))
11997 (extra (if org-refile-use-outline-path "/" ""))
11998 (cbnex (concat (buffer-name) extra))
11999 (filename (and cfn (expand-file-name cfn)))
12000 (tbl (mapcar
12001 (lambda (x)
12002 (if (and (not (member org-refile-use-outline-path
12003 '(file full-file-path)))
12004 (not (equal filename (nth 1 x))))
12005 (cons (concat (car x) extra " ("
12006 (file-name-nondirectory (nth 1 x)) ")")
12007 (cdr x))
12008 (cons (concat (car x) extra) (cdr x))))
12009 org-refile-target-table))
12010 (completion-ignore-case t)
12011 cdef
12012 (prompt (concat prompt
12013 (or (and (car org-refile-history)
12014 (concat " (default " (car org-refile-history) ")"))
12015 (and (assoc cbnex tbl) (setq cdef cbnex)
12016 (concat " (default " cbnex ")"))) ": "))
12017 pa answ parent-target child parent old-hist)
12018 (setq old-hist org-refile-history)
12019 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12020 nil 'org-refile-history (or cdef (car org-refile-history))))
12021 (if (setq pa (org-refile--get-location answ tbl))
12022 (progn
12023 (org-refile-check-position pa)
12024 (when (or (not org-refile-history)
12025 (not (eq old-hist org-refile-history))
12026 (not (equal (car pa) (car org-refile-history))))
12027 (setq org-refile-history
12028 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12029 org-refile-history
12030 (cdr org-refile-history))))
12031 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12032 (pop org-refile-history)))
12034 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12035 (progn
12036 (setq parent (match-string 1 answ)
12037 child (match-string 2 answ))
12038 (setq parent-target (org-refile--get-location parent tbl))
12039 (when (and parent-target
12040 (or (eq new-nodes t)
12041 (and (eq new-nodes 'confirm)
12042 (y-or-n-p (format "Create new node \"%s\"? "
12043 child)))))
12044 (org-refile-new-child parent-target child)))
12045 (user-error "Invalid target location")))))
12047 (declare-function org-string-nw-p "org-macs" (s))
12048 (defun org-refile-check-position (refile-pointer)
12049 "Check if the refile pointer matches the headline to which it points."
12050 (let* ((file (nth 1 refile-pointer))
12051 (re (nth 2 refile-pointer))
12052 (pos (nth 3 refile-pointer))
12053 buffer)
12054 (if (and (not (markerp pos)) (not file))
12055 (user-error "Please indicate a target file in the refile path")
12056 (when (org-string-nw-p re)
12057 (setq buffer (if (markerp pos)
12058 (marker-buffer pos)
12059 (or (find-buffer-visiting file)
12060 (find-file-noselect file))))
12061 (with-current-buffer buffer
12062 (save-excursion
12063 (save-restriction
12064 (widen)
12065 (goto-char pos)
12066 (beginning-of-line 1)
12067 (unless (looking-at-p re)
12068 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12070 (defun org-refile-new-child (parent-target child)
12071 "Use refile target PARENT-TARGET to add new CHILD below it."
12072 (unless parent-target
12073 (error "Cannot find parent for new node"))
12074 (let ((file (nth 1 parent-target))
12075 (pos (nth 3 parent-target))
12076 level)
12077 (with-current-buffer (or (find-buffer-visiting file)
12078 (find-file-noselect file))
12079 (save-excursion
12080 (save-restriction
12081 (widen)
12082 (if pos
12083 (goto-char pos)
12084 (goto-char (point-max))
12085 (unless (bolp) (newline)))
12086 (when (looking-at org-outline-regexp)
12087 (setq level (funcall outline-level))
12088 (org-end-of-subtree t t))
12089 (org-back-over-empty-lines)
12090 (insert "\n" (make-string
12091 (if pos (org-get-valid-level level 1) 1) ?*)
12092 " " child "\n")
12093 (beginning-of-line 0)
12094 (list (concat (car parent-target) "/" child) file "" (point)))))))
12096 (defun org-olpath-completing-read (prompt collection &rest args)
12097 "Read an outline path like a file name."
12098 (let ((thetable collection))
12099 (apply #'completing-read
12100 prompt
12101 (lambda (string predicate &optional flag)
12102 (cond
12103 ((eq flag nil) (try-completion string thetable))
12104 ((eq flag t)
12105 (let ((l (length string)))
12106 (mapcar (lambda (x)
12107 (let ((r (substring x l))
12108 (f (if (string-match " ([^)]*)$" x)
12109 (match-string 0 x)
12110 "")))
12111 (if (string-match "/" r)
12112 (concat string (substring r 0 (match-end 0)) f)
12113 x)))
12114 (all-completions string thetable predicate))))
12115 ;; Exact match?
12116 ((eq flag 'lambda) (assoc string thetable))))
12117 args)))
12119 ;;;; Dynamic blocks
12121 (defun org-find-dblock (name)
12122 "Find the first dynamic block with name NAME in the buffer.
12123 If not found, stay at current position and return nil."
12124 (let ((case-fold-search t) pos)
12125 (save-excursion
12126 (goto-char (point-min))
12127 (setq pos (and (re-search-forward
12128 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12129 (match-beginning 0))))
12130 (when pos (goto-char pos))
12131 pos))
12133 (defun org-create-dblock (plist)
12134 "Create a dynamic block section, with parameters taken from PLIST.
12135 PLIST must contain a :name entry which is used as the name of the block."
12136 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12137 (end-of-line 1)
12138 (newline))
12139 (let ((col (current-column))
12140 (name (plist-get plist :name)))
12141 (insert "#+BEGIN: " name)
12142 (while plist
12143 (if (eq (car plist) :name)
12144 (setq plist (cddr plist))
12145 (insert " " (prin1-to-string (pop plist)))))
12146 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12147 (beginning-of-line -2)))
12149 (defun org-prepare-dblock ()
12150 "Prepare dynamic block for refresh.
12151 This empties the block, puts the cursor at the insert position and returns
12152 the property list including an extra property :name with the block name."
12153 (unless (looking-at org-dblock-start-re)
12154 (user-error "Not at a dynamic block"))
12155 (let* ((begdel (1+ (match-end 0)))
12156 (name (org-no-properties (match-string 1)))
12157 (params (append (list :name name)
12158 (read (concat "(" (match-string 3) ")")))))
12159 (save-excursion
12160 (beginning-of-line 1)
12161 (skip-chars-forward " \t")
12162 (setq params (plist-put params :indentation-column (current-column))))
12163 (unless (re-search-forward org-dblock-end-re nil t)
12164 (error "Dynamic block not terminated"))
12165 (setq params
12166 (append params
12167 (list :content (buffer-substring
12168 begdel (match-beginning 0)))))
12169 (delete-region begdel (match-beginning 0))
12170 (goto-char begdel)
12171 (open-line 1)
12172 params))
12174 (defun org-map-dblocks (&optional command)
12175 "Apply COMMAND to all dynamic blocks in the current buffer.
12176 If COMMAND is not given, use `org-update-dblock'."
12177 (let ((cmd (or command 'org-update-dblock)))
12178 (save-excursion
12179 (goto-char (point-min))
12180 (while (re-search-forward org-dblock-start-re nil t)
12181 (goto-char (match-beginning 0))
12182 (save-excursion
12183 (condition-case nil
12184 (funcall cmd)
12185 (error (message "Error during update of dynamic block"))))
12186 (unless (re-search-forward org-dblock-end-re nil t)
12187 (error "Dynamic block not terminated"))))))
12189 (defun org-dblock-update (&optional arg)
12190 "User command for updating dynamic blocks.
12191 Update the dynamic block at point. With prefix ARG, update all dynamic
12192 blocks in the buffer."
12193 (interactive "P")
12194 (if arg
12195 (org-update-all-dblocks)
12196 (or (looking-at org-dblock-start-re)
12197 (org-beginning-of-dblock))
12198 (org-update-dblock)))
12200 (defun org-update-dblock ()
12201 "Update the dynamic block at point.
12202 This means to empty the block, parse for parameters and then call
12203 the correct writing function."
12204 (interactive)
12205 (save-excursion
12206 (let* ((win (selected-window))
12207 (pos (point))
12208 (line (org-current-line))
12209 (params (org-prepare-dblock))
12210 (name (plist-get params :name))
12211 (indent (plist-get params :indentation-column))
12212 (cmd (intern (concat "org-dblock-write:" name))))
12213 (message "Updating dynamic block `%s' at line %d..." name line)
12214 (funcall cmd params)
12215 (message "Updating dynamic block `%s' at line %d...done" name line)
12216 (goto-char pos)
12217 (when (and indent (> indent 0))
12218 (setq indent (make-string indent ?\ ))
12219 (save-excursion
12220 (select-window win)
12221 (org-beginning-of-dblock)
12222 (forward-line 1)
12223 (while (not (looking-at org-dblock-end-re))
12224 (insert indent)
12225 (beginning-of-line 2))
12226 (when (looking-at org-dblock-end-re)
12227 (and (looking-at "[ \t]+")
12228 (replace-match ""))
12229 (insert indent)))))))
12231 (defun org-beginning-of-dblock ()
12232 "Find the beginning of the dynamic block at point.
12233 Error if there is no such block at point."
12234 (let ((pos (point))
12235 beg)
12236 (end-of-line 1)
12237 (if (and (re-search-backward org-dblock-start-re nil t)
12238 (setq beg (match-beginning 0))
12239 (re-search-forward org-dblock-end-re nil t)
12240 (> (match-end 0) pos))
12241 (goto-char beg)
12242 (goto-char pos)
12243 (error "Not in a dynamic block"))))
12245 (defun org-update-all-dblocks ()
12246 "Update all dynamic blocks in the buffer.
12247 This function can be used in a hook."
12248 (interactive)
12249 (when (derived-mode-p 'org-mode)
12250 (org-map-dblocks 'org-update-dblock)))
12253 ;;;; Completion
12255 (declare-function org-export-backend-options "ox" (cl-x) t)
12256 (defun org-get-export-keywords ()
12257 "Return a list of all currently understood export keywords.
12258 Export keywords include options, block names, attributes and
12259 keywords relative to each registered export back-end."
12260 (let (keywords)
12261 (dolist (backend
12262 (bound-and-true-p org-export-registered-backends)
12263 (delq nil keywords))
12264 ;; Back-end name (for keywords, like #+LATEX:)
12265 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12266 (dolist (option-entry (org-export-backend-options backend))
12267 ;; Back-end options.
12268 (push (nth 1 option-entry) keywords)))))
12270 (defconst org-options-keywords
12271 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12272 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12273 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12274 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12275 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12277 (defcustom org-structure-template-alist
12278 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12279 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12280 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12281 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12282 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12283 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12284 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12285 ("L" "#+LaTeX: ")
12286 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12287 ("H" "#+HTML: ")
12288 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12289 ("A" "#+ASCII: ")
12290 ("i" "#+INDEX: ?")
12291 ("I" "#+INCLUDE: %file ?"))
12292 "Structure completion elements.
12293 This is a list of abbreviation keys and values. The value gets inserted
12294 if you type `<' followed by the key and then press the completion key,
12295 usually `TAB'. %file will be replaced by a file name after prompting
12296 for the file using completion. The cursor will be placed at the position
12297 of the `?' in the template.
12298 There are two templates for each key, the first uses the original Org syntax,
12299 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12300 the default when the /org-mtags.el/ module has been loaded. See also the
12301 variable `org-mtags-prefer-muse-templates'."
12302 :group 'org-completion
12303 :type '(repeat
12304 (list
12305 (string :tag "Key")
12306 (string :tag "Template")))
12307 :version "25.1"
12308 :package-version '(Org . "8.3"))
12310 (defun org-try-structure-completion ()
12311 "Try to complete a structure template before point.
12312 This looks for strings like \"<e\" on an otherwise empty line and
12313 expands them."
12314 (let ((l (buffer-substring (point-at-bol) (point)))
12316 (when (and (looking-at "[ \t]*$")
12317 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12318 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12319 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12320 (match-beginning 1)) a)
12321 t)))
12323 (defun org-complete-expand-structure-template (start cell)
12324 "Expand a structure template."
12325 (let ((rpl (nth 1 cell))
12326 (ind ""))
12327 (delete-region start (point))
12328 (when (string-match "\\`[ \t]*#\\+" rpl)
12329 (cond
12330 ((bolp))
12331 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12332 (setq ind (buffer-substring (point-at-bol) (point))))
12333 (t (newline))))
12334 (setq start (point))
12335 (when (string-match "%file" rpl)
12336 (setq rpl (replace-match
12337 (concat
12338 "\""
12339 (save-match-data
12340 (abbreviate-file-name (read-file-name "Include file: ")))
12341 "\"")
12342 t t rpl)))
12343 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12344 (concat "\n" ind)))
12345 (insert rpl)
12346 (when (re-search-backward "\\?" start t) (delete-char 1))))
12348 ;;;; TODO, DEADLINE, Comments
12350 (defun org-toggle-comment ()
12351 "Change the COMMENT state of an entry."
12352 (interactive)
12353 (save-excursion
12354 (org-back-to-heading)
12355 (looking-at org-complex-heading-regexp)
12356 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12357 (skip-chars-forward " \t")
12358 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12359 (if (org-in-commented-heading-p t)
12360 (delete-region (point)
12361 (progn (search-forward " " (line-end-position) 'move)
12362 (skip-chars-forward " \t")
12363 (point)))
12364 (insert org-comment-string)
12365 (unless (eolp) (insert " ")))))
12367 (defvar org-last-todo-state-is-todo nil
12368 "This is non-nil when the last TODO state change led to a TODO state.
12369 If the last change removed the TODO tag or switched to DONE, then
12370 this is nil.")
12372 (defvar org-setting-tags nil) ; dynamically skipped
12374 (defvar org-todo-setup-filter-hook nil
12375 "Hook for functions that pre-filter todo specs.
12376 Each function takes a todo spec and returns either nil or the spec
12377 transformed into canonical form." )
12379 (defvar org-todo-get-default-hook nil
12380 "Hook for functions that get a default item for todo.
12381 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12382 nil or a string to be used for the todo mark." )
12384 (defvar org-agenda-headline-snapshot-before-repeat)
12386 (defun org-current-effective-time ()
12387 "Return current time adjusted for `org-extend-today-until' variable."
12388 (let* ((ct (org-current-time))
12389 (dct (decode-time ct))
12390 (ct1
12391 (cond
12392 (org-use-last-clock-out-time-as-effective-time
12393 (or (org-clock-get-last-clock-out-time) ct))
12394 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12395 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12396 (t ct))))
12397 ct1))
12399 (defun org-todo-yesterday (&optional arg)
12400 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12401 (interactive "P")
12402 (if (eq major-mode 'org-agenda-mode)
12403 (apply 'org-agenda-todo-yesterday arg)
12404 (let* ((org-use-effective-time t)
12405 (hour (nth 2 (decode-time (org-current-time))))
12406 (org-extend-today-until (1+ hour)))
12407 (org-todo arg))))
12409 (defvar org-block-entry-blocking ""
12410 "First entry preventing the TODO state change.")
12412 (defun org-cancel-repeater ()
12413 "Cancel a repeater by setting its numeric value to zero."
12414 (interactive)
12415 (save-excursion
12416 (org-back-to-heading t)
12417 (let ((bound1 (point))
12418 (bound0 (save-excursion (outline-next-heading) (point))))
12419 (when (and (re-search-forward
12420 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12421 org-deadline-time-regexp "\\)\\|\\("
12422 org-ts-regexp "\\)")
12423 bound0 t)
12424 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12425 bound1 t))
12426 (replace-match "0" t nil nil 1)))))
12428 (defvar org-state) ;; dynamically scoped into this function
12429 (defun org-todo (&optional arg)
12430 "Change the TODO state of an item.
12431 The state of an item is given by a keyword at the start of the heading,
12432 like
12433 *** TODO Write paper
12434 *** DONE Call mom
12436 The different keywords are specified in the variable `org-todo-keywords'.
12437 By default the available states are \"TODO\" and \"DONE\".
12438 So for this example: when the item starts with TODO, it is changed to DONE.
12439 When it starts with DONE, the DONE is removed. And when neither TODO nor
12440 DONE are present, add TODO at the beginning of the heading.
12442 With \\[universal-argument] prefix arg, use completion to determine the new \
12443 state.
12444 With numeric prefix arg, switch to that state.
12445 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12446 keywords (nextset).
12447 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12448 With a numeric prefix arg of 0, inhibit note taking for the change.
12449 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12451 When called through ELisp, arg is also interpreted in the following way:
12452 `none' -> empty state
12453 \"\"(empty string) -> switch to empty state
12454 `done' -> switch to DONE
12455 `nextset' -> switch to the next set of keywords
12456 `previousset' -> switch to the previous set of keywords
12457 \"WAITING\" -> switch to the specified keyword, but only if it
12458 really is a member of `org-todo-keywords'."
12459 (interactive "P")
12460 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12461 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12462 'region-start-level 'region))
12463 org-loop-over-headlines-in-active-region)
12464 (org-map-entries
12465 `(org-todo ,arg)
12466 org-loop-over-headlines-in-active-region
12467 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12468 (when (equal arg '(16)) (setq arg 'nextset))
12469 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12470 (let ((org-blocker-hook org-blocker-hook)
12471 commentp
12472 case-fold-search)
12473 (when (equal arg '(64))
12474 (setq arg nil org-blocker-hook nil))
12475 (when (and org-blocker-hook
12476 (or org-inhibit-blocking
12477 (org-entry-get nil "NOBLOCKING")))
12478 (setq org-blocker-hook nil))
12479 (save-excursion
12480 (catch 'exit
12481 (org-back-to-heading t)
12482 (when (org-in-commented-heading-p t)
12483 (org-toggle-comment)
12484 (setq commentp t))
12485 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12486 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12487 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12488 (let* ((match-data (match-data))
12489 (startpos (point-at-bol))
12490 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12491 (org-log-done org-log-done)
12492 (org-log-repeat org-log-repeat)
12493 (org-todo-log-states org-todo-log-states)
12494 (org-inhibit-logging
12495 (if (equal arg 0)
12496 (progn (setq arg nil) 'note) org-inhibit-logging))
12497 (this (match-string 1))
12498 (hl-pos (match-beginning 0))
12499 (head (org-get-todo-sequence-head this))
12500 (ass (assoc head org-todo-kwd-alist))
12501 (interpret (nth 1 ass))
12502 (done-word (nth 3 ass))
12503 (final-done-word (nth 4 ass))
12504 (org-last-state (or this ""))
12505 (completion-ignore-case t)
12506 (member (member this org-todo-keywords-1))
12507 (tail (cdr member))
12508 (org-state (cond
12509 ((and org-todo-key-trigger
12510 (or (and (equal arg '(4))
12511 (eq org-use-fast-todo-selection 'prefix))
12512 (and (not arg) org-use-fast-todo-selection
12513 (not (eq org-use-fast-todo-selection
12514 'prefix)))))
12515 ;; Use fast selection
12516 (org-fast-todo-selection))
12517 ((and (equal arg '(4))
12518 (or (not org-use-fast-todo-selection)
12519 (not org-todo-key-trigger)))
12520 ;; Read a state with completion
12521 (completing-read
12522 "State: " (mapcar #'list org-todo-keywords-1)
12523 nil t))
12524 ((eq arg 'right)
12525 (if this
12526 (if tail (car tail) nil)
12527 (car org-todo-keywords-1)))
12528 ((eq arg 'left)
12529 (unless (equal member org-todo-keywords-1)
12530 (if this
12531 (nth (- (length org-todo-keywords-1)
12532 (length tail) 2)
12533 org-todo-keywords-1)
12534 (org-last org-todo-keywords-1))))
12535 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12536 (setq arg nil))) ; hack to fall back to cycling
12537 (arg
12538 ;; user or caller requests a specific state
12539 (cond
12540 ((equal arg "") nil)
12541 ((eq arg 'none) nil)
12542 ((eq arg 'done) (or done-word (car org-done-keywords)))
12543 ((eq arg 'nextset)
12544 (or (car (cdr (member head org-todo-heads)))
12545 (car org-todo-heads)))
12546 ((eq arg 'previousset)
12547 (let ((org-todo-heads (reverse org-todo-heads)))
12548 (or (car (cdr (member head org-todo-heads)))
12549 (car org-todo-heads))))
12550 ((car (member arg org-todo-keywords-1)))
12551 ((stringp arg)
12552 (user-error "State `%s' not valid in this file" arg))
12553 ((nth (1- (prefix-numeric-value arg))
12554 org-todo-keywords-1))))
12555 ((null member) (or head (car org-todo-keywords-1)))
12556 ((equal this final-done-word) nil) ;; -> make empty
12557 ((null tail) nil) ;; -> first entry
12558 ((memq interpret '(type priority))
12559 (if (eq this-command last-command)
12560 (car tail)
12561 (if (> (length tail) 0)
12562 (or done-word (car org-done-keywords))
12563 nil)))
12565 (car tail))))
12566 (org-state (or
12567 (run-hook-with-args-until-success
12568 'org-todo-get-default-hook org-state org-last-state)
12569 org-state))
12570 (next (if org-state (concat " " org-state " ") " "))
12571 (change-plist (list :type 'todo-state-change :from this :to org-state
12572 :position startpos))
12573 dolog now-done-p)
12574 (when org-blocker-hook
12575 (setq org-last-todo-state-is-todo
12576 (not (member this org-done-keywords)))
12577 (unless (save-excursion
12578 (save-match-data
12579 (org-with-wide-buffer
12580 (run-hook-with-args-until-failure
12581 'org-blocker-hook change-plist))))
12582 (if (called-interactively-p 'interactive)
12583 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12584 this org-state org-block-entry-blocking)
12585 ;; fail silently
12586 (message "TODO state change from %s to %s blocked (by \"%s\")"
12587 this org-state org-block-entry-blocking)
12588 (throw 'exit nil))))
12589 (store-match-data match-data)
12590 (replace-match next t t)
12591 (cond ((equal this org-state)
12592 (message "TODO state was already %s" (org-trim next)))
12593 ((pos-visible-in-window-p hl-pos)
12594 (message "TODO state changed to %s" (org-trim next))))
12595 (unless head
12596 (setq head (org-get-todo-sequence-head org-state)
12597 ass (assoc head org-todo-kwd-alist)
12598 interpret (nth 1 ass)
12599 done-word (nth 3 ass)
12600 final-done-word (nth 4 ass)))
12601 (when (memq arg '(nextset previousset))
12602 (message "Keyword-Set %d/%d: %s"
12603 (- (length org-todo-sets) -1
12604 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12605 (length org-todo-sets)
12606 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12607 (setq org-last-todo-state-is-todo
12608 (not (member org-state org-done-keywords)))
12609 (setq now-done-p (and (member org-state org-done-keywords)
12610 (not (member this org-done-keywords))))
12611 (and logging (org-local-logging logging))
12612 (when (and (or org-todo-log-states org-log-done)
12613 (not (eq org-inhibit-logging t))
12614 (not (memq arg '(nextset previousset))))
12615 ;; we need to look at recording a time and note
12616 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12617 (nth 2 (assoc this org-todo-log-states))))
12618 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12619 (setq dolog 'time))
12620 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12621 (and org-state
12622 (member org-state org-not-done-keywords)
12623 (not (member this org-not-done-keywords))))
12624 ;; This is now a todo state and was not one before
12625 ;; If there was a CLOSED time stamp, get rid of it.
12626 (org-add-planning-info nil nil 'closed))
12627 (when (and now-done-p org-log-done)
12628 ;; It is now done, and it was not done before
12629 (org-add-planning-info 'closed (org-current-effective-time))
12630 (when (and (not dolog) (eq 'note org-log-done))
12631 (org-add-log-setup 'done org-state this 'note)))
12632 (when (and org-state dolog)
12633 ;; This is a non-nil state, and we need to log it
12634 (org-add-log-setup 'state org-state this dolog)))
12635 ;; Fixup tag positioning
12636 (org-todo-trigger-tag-changes org-state)
12637 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12638 (when org-provide-todo-statistics
12639 (org-update-parent-todo-statistics))
12640 (run-hooks 'org-after-todo-state-change-hook)
12641 (when (and arg (not (member org-state org-done-keywords)))
12642 (setq head (org-get-todo-sequence-head org-state)))
12643 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12644 ;; Do we need to trigger a repeat?
12645 (when now-done-p
12646 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12647 ;; This is for the agenda, take a snapshot of the headline.
12648 (save-match-data
12649 (setq org-agenda-headline-snapshot-before-repeat
12650 (org-get-heading))))
12651 (org-auto-repeat-maybe org-state))
12652 ;; Fixup cursor location if close to the keyword
12653 (when (and (outline-on-heading-p)
12654 (not (bolp))
12655 (save-excursion (beginning-of-line 1)
12656 (looking-at org-todo-line-regexp))
12657 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12658 (goto-char (or (match-end 2) (match-end 1)))
12659 (and (looking-at " ") (just-one-space)))
12660 (when org-trigger-hook
12661 (save-excursion
12662 (run-hook-with-args 'org-trigger-hook change-plist)))
12663 (when commentp (org-toggle-comment))))))))
12665 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12666 "Block turning an entry into a TODO, using the hierarchy.
12667 This checks whether the current task should be blocked from state
12668 changes. Such blocking occurs when:
12670 1. The task has children which are not all in a completed state.
12672 2. A task has a parent with the property :ORDERED:, and there
12673 are siblings prior to the current task with incomplete
12674 status.
12676 3. The parent of the task is blocked because it has siblings that should
12677 be done first, or is child of a block grandparent TODO entry."
12679 (if (not org-enforce-todo-dependencies)
12680 t ; if locally turned off don't block
12681 (catch 'dont-block
12682 ;; If this is not a todo state change, or if this entry is already DONE,
12683 ;; do not block
12684 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12685 (member (plist-get change-plist :from)
12686 (cons 'done org-done-keywords))
12687 (member (plist-get change-plist :to)
12688 (cons 'todo org-not-done-keywords))
12689 (not (plist-get change-plist :to)))
12690 (throw 'dont-block t))
12691 ;; If this task has children, and any are undone, it's blocked
12692 (save-excursion
12693 (org-back-to-heading t)
12694 (let ((this-level (funcall outline-level)))
12695 (outline-next-heading)
12696 (let ((child-level (funcall outline-level)))
12697 (while (and (not (eobp))
12698 (> child-level this-level))
12699 ;; this todo has children, check whether they are all
12700 ;; completed
12701 (when (and (not (org-entry-is-done-p))
12702 (org-entry-is-todo-p))
12703 (setq org-block-entry-blocking (org-get-heading))
12704 (throw 'dont-block nil))
12705 (outline-next-heading)
12706 (setq child-level (funcall outline-level))))))
12707 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12708 ;; any previous siblings are undone, it's blocked
12709 (save-excursion
12710 (org-back-to-heading t)
12711 (let* ((pos (point))
12712 (parent-pos (and (org-up-heading-safe) (point))))
12713 (unless parent-pos (throw 'dont-block t)) ; no parent
12714 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12715 (forward-line 1)
12716 (re-search-forward org-not-done-heading-regexp pos t))
12717 (setq org-block-entry-blocking (match-string 0))
12718 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12719 ;; Search further up the hierarchy, to see if an ancestor is blocked
12720 (while t
12721 (goto-char parent-pos)
12722 (unless (looking-at org-not-done-heading-regexp)
12723 (throw 'dont-block t)) ; do not block, parent is not a TODO
12724 (setq pos (point))
12725 (setq parent-pos (and (org-up-heading-safe) (point)))
12726 (unless parent-pos (throw 'dont-block t)) ; no parent
12727 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12728 (forward-line 1)
12729 (re-search-forward org-not-done-heading-regexp pos t)
12730 (setq org-block-entry-blocking (org-get-heading)))
12731 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12733 (defcustom org-track-ordered-property-with-tag nil
12734 "Should the ORDERED property also be shown as a tag?
12735 The ORDERED property decides if an entry should require subtasks to be
12736 completed in sequence. Since a property is not very visible, setting
12737 this option means that toggling the ORDERED property with the command
12738 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12739 not relevant for the behavior, but it makes things more visible.
12741 Note that toggling the tag with tags commands will not change the property
12742 and therefore not influence behavior!
12744 This can be t, meaning the tag ORDERED should be used, It can also be a
12745 string to select a different tag for this task."
12746 :group 'org-todo
12747 :type '(choice
12748 (const :tag "No tracking" nil)
12749 (const :tag "Track with ORDERED tag" t)
12750 (string :tag "Use other tag")))
12752 (defun org-toggle-ordered-property ()
12753 "Toggle the ORDERED property of the current entry.
12754 For better visibility, you can track the value of this property with a tag.
12755 See variable `org-track-ordered-property-with-tag'."
12756 (interactive)
12757 (let* ((t1 org-track-ordered-property-with-tag)
12758 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12759 (save-excursion
12760 (org-back-to-heading)
12761 (if (org-entry-get nil "ORDERED")
12762 (progn
12763 (org-delete-property "ORDERED")
12764 (and tag (org-toggle-tag tag 'off))
12765 (message "Subtasks can be completed in arbitrary order"))
12766 (org-entry-put nil "ORDERED" "t")
12767 (and tag (org-toggle-tag tag 'on))
12768 (message "Subtasks must be completed in sequence")))))
12770 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12771 (defun org-block-todo-from-checkboxes (change-plist)
12772 "Block turning an entry into a TODO, using checkboxes.
12773 This checks whether the current task should be blocked from state
12774 changes because there are unchecked boxes in this entry."
12775 (if (not org-enforce-todo-checkbox-dependencies)
12776 t ; if locally turned off don't block
12777 (catch 'dont-block
12778 ;; If this is not a todo state change, or if this entry is already DONE,
12779 ;; do not block
12780 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12781 (member (plist-get change-plist :from)
12782 (cons 'done org-done-keywords))
12783 (member (plist-get change-plist :to)
12784 (cons 'todo org-not-done-keywords))
12785 (not (plist-get change-plist :to)))
12786 (throw 'dont-block t))
12787 ;; If this task has checkboxes that are not checked, it's blocked
12788 (save-excursion
12789 (org-back-to-heading t)
12790 (let ((beg (point)) end)
12791 (outline-next-heading)
12792 (setq end (point))
12793 (goto-char beg)
12794 (when (org-list-search-forward
12795 (concat (org-item-beginning-re)
12796 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12797 "\\[[- ]\\]")
12798 end t)
12799 (when (boundp 'org-blocked-by-checkboxes)
12800 (setq org-blocked-by-checkboxes t))
12801 (throw 'dont-block nil))))
12802 t))) ; do not block
12804 (defun org-entry-blocked-p ()
12805 "Non-nil if entry at point is blocked."
12806 (and (not (org-entry-get nil "NOBLOCKING"))
12807 (member (org-entry-get nil "TODO") org-not-done-keywords)
12808 (not (run-hook-with-args-until-failure
12809 'org-blocker-hook
12810 (list :type 'todo-state-change
12811 :position (point)
12812 :from 'todo
12813 :to 'done)))))
12815 (defun org-update-statistics-cookies (all)
12816 "Update the statistics cookie, either from TODO or from checkboxes.
12817 This should be called with the cursor in a line with a statistics cookie."
12818 (interactive "P")
12819 (if all
12820 (progn
12821 (org-update-checkbox-count 'all)
12822 (org-map-entries 'org-update-parent-todo-statistics))
12823 (if (not (org-at-heading-p))
12824 (org-update-checkbox-count)
12825 (let ((pos (point-marker))
12826 end l1 l2)
12827 (ignore-errors (org-back-to-heading t))
12828 (if (not (org-at-heading-p))
12829 (org-update-checkbox-count)
12830 (setq l1 (org-outline-level))
12831 (setq end (save-excursion
12832 (outline-next-heading)
12833 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12834 (point)))
12835 (if (and (save-excursion
12836 (re-search-forward
12837 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12838 (not (save-excursion (re-search-forward
12839 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12840 (org-update-checkbox-count)
12841 (if (and l2 (> l2 l1))
12842 (progn
12843 (goto-char end)
12844 (org-update-parent-todo-statistics))
12845 (goto-char pos)
12846 (beginning-of-line 1)
12847 (while (re-search-forward
12848 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12849 (point-at-eol) t)
12850 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12851 (goto-char pos)
12852 (move-marker pos nil)))))
12854 (defvar org-entry-property-inherited-from) ;; defined below
12855 (defun org-update-parent-todo-statistics ()
12856 "Update any statistics cookie in the parent of the current headline.
12857 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12858 the entire subtree and this will travel up the hierarchy and update
12859 statistics everywhere."
12860 (let* ((prop (save-excursion (org-up-heading-safe)
12861 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12862 (recursive (or (not org-hierarchical-todo-statistics)
12863 (and prop (string-match "\\<recursive\\>" prop))))
12864 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12866 (first t)
12867 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12868 level ltoggle l1 new ndel
12869 (cnt-all 0) (cnt-done 0) is-percent kwd
12870 checkbox-beg ov ovs ove cookie-present)
12871 (catch 'exit
12872 (save-excursion
12873 (beginning-of-line 1)
12874 (setq ltoggle (funcall outline-level))
12875 ;; Three situations are to consider:
12877 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12878 ;; to the top-level ancestor on the headline;
12880 ;; 2. If parent has "recursive" property, repeat up to the
12881 ;; headline setting that property, taking inheritance into
12882 ;; account;
12884 ;; 3. Else, move up to direct parent and proceed only once.
12885 (while (and (setq level (org-up-heading-safe))
12886 (or recursive first)
12887 (>= (point) lim))
12888 (setq first nil cookie-present nil)
12889 (unless (and level
12890 (not (string-match
12891 "\\<checkbox\\>"
12892 (downcase (or (org-entry-get nil "COOKIE_DATA")
12893 "")))))
12894 (throw 'exit nil))
12895 (while (re-search-forward box-re (point-at-eol) t)
12896 (setq cnt-all 0 cnt-done 0 cookie-present t)
12897 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12898 (save-match-data
12899 (unless (outline-next-heading) (throw 'exit nil))
12900 (while (and (looking-at org-complex-heading-regexp)
12901 (> (setq l1 (length (match-string 1))) level))
12902 (setq kwd (and (or recursive (= l1 ltoggle))
12903 (match-string 2)))
12904 (if (or (eq org-provide-todo-statistics 'all-headlines)
12905 (and (eq org-provide-todo-statistics t)
12906 (or (member kwd org-done-keywords)))
12907 (and (listp org-provide-todo-statistics)
12908 (stringp (car org-provide-todo-statistics))
12909 (or (member kwd org-provide-todo-statistics)
12910 (member kwd org-done-keywords)))
12911 (and (listp org-provide-todo-statistics)
12912 (listp (car org-provide-todo-statistics))
12913 (or (member kwd (car org-provide-todo-statistics))
12914 (and (member kwd org-done-keywords)
12915 (member kwd (cadr org-provide-todo-statistics))))))
12916 (setq cnt-all (1+ cnt-all))
12917 (and (eq org-provide-todo-statistics t)
12919 (setq cnt-all (1+ cnt-all))))
12920 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12921 (member kwd org-done-keywords))
12922 (and (listp org-provide-todo-statistics)
12923 (listp (car org-provide-todo-statistics))
12924 (member kwd org-done-keywords)
12925 (member kwd (cadr org-provide-todo-statistics)))
12926 (and (listp org-provide-todo-statistics)
12927 (stringp (car org-provide-todo-statistics))
12928 (member kwd org-done-keywords)))
12929 (setq cnt-done (1+ cnt-done)))
12930 (outline-next-heading)))
12931 (setq new
12932 (if is-percent
12933 (format "[%d%%]" (floor (* 100.0 cnt-done)
12934 (max 1 cnt-all)))
12935 (format "[%d/%d]" cnt-done cnt-all))
12936 ndel (- (match-end 0) checkbox-beg))
12937 ;; handle overlays when updating cookie from column view
12938 (when (setq ov (car (overlays-at checkbox-beg)))
12939 (setq ovs (overlay-start ov) ove (overlay-end ov))
12940 (delete-overlay ov))
12941 (goto-char checkbox-beg)
12942 (insert new)
12943 (delete-region (point) (+ (point) ndel))
12944 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12945 (when ov (move-overlay ov ovs ove)))
12946 (when cookie-present
12947 (run-hook-with-args 'org-after-todo-statistics-hook
12948 cnt-done (- cnt-all cnt-done))))))
12949 (run-hooks 'org-todo-statistics-hook)))
12951 (defvar org-after-todo-statistics-hook nil
12952 "Hook that is called after a TODO statistics cookie has been updated.
12953 Each function is called with two arguments: the number of not-done entries
12954 and the number of done entries.
12956 For example, the following function, when added to this hook, will switch
12957 an entry to DONE when all children are done, and back to TODO when new
12958 entries are set to a TODO status. Note that this hook is only called
12959 when there is a statistics cookie in the headline!
12961 \(defun org-summary-todo (n-done n-not-done)
12962 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12963 \(let (org-log-done org-log-states) ; turn off logging
12964 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12967 (defvar org-todo-statistics-hook nil
12968 "Hook that is run whenever Org thinks TODO statistics should be updated.
12969 This hook runs even if there is no statistics cookie present, in which case
12970 `org-after-todo-statistics-hook' would not run.")
12972 (defun org-todo-trigger-tag-changes (state)
12973 "Apply the changes defined in `org-todo-state-tags-triggers'."
12974 (let ((l org-todo-state-tags-triggers)
12975 changes)
12976 (when (or (not state) (equal state ""))
12977 (setq changes (append changes (cdr (assoc "" l)))))
12978 (when (and (stringp state) (> (length state) 0))
12979 (setq changes (append changes (cdr (assoc state l)))))
12980 (when (member state org-not-done-keywords)
12981 (setq changes (append changes (cdr (assoc 'todo l)))))
12982 (when (member state org-done-keywords)
12983 (setq changes (append changes (cdr (assoc 'done l)))))
12984 (dolist (c changes)
12985 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12987 (defun org-local-logging (value)
12988 "Get logging settings from a property VALUE."
12989 ;; Directly set the variables, they are already local.
12990 (setq org-log-done nil
12991 org-log-repeat nil
12992 org-todo-log-states nil)
12993 (dolist (w (org-split-string value))
12994 (let (a)
12995 (cond
12996 ((setq a (assoc w org-startup-options))
12997 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12998 (set (nth 1 a) (nth 2 a))))
12999 ((setq a (org-extract-log-state-settings w))
13000 (and (member (car a) org-todo-keywords-1)
13001 (push a org-todo-log-states)))))))
13003 (defun org-get-todo-sequence-head (kwd)
13004 "Return the head of the TODO sequence to which KWD belongs.
13005 If KWD is not set, check if there is a text property remembering the
13006 right sequence."
13007 (let (p)
13008 (cond
13009 ((not kwd)
13010 (or (get-text-property (point-at-bol) 'org-todo-head)
13011 (progn
13012 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13013 nil (point-at-eol)))
13014 (get-text-property p 'org-todo-head))))
13015 ((not (member kwd org-todo-keywords-1))
13016 (car org-todo-keywords-1))
13017 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13019 (defun org-fast-todo-selection ()
13020 "Fast TODO keyword selection with single keys.
13021 Returns the new TODO keyword, or nil if no state change should occur."
13022 (let* ((fulltable org-todo-key-alist)
13023 (done-keywords org-done-keywords) ;; needed for the faces.
13024 (maxlen (apply 'max (mapcar
13025 (lambda (x)
13026 (if (stringp (car x)) (string-width (car x)) 0))
13027 fulltable)))
13028 (expert nil)
13029 (fwidth (+ maxlen 3 1 3))
13030 (ncol (/ (- (window-width) 4) fwidth))
13031 tg cnt e c tbl
13032 groups ingroup)
13033 (save-excursion
13034 (save-window-excursion
13035 (if expert
13036 (set-buffer (get-buffer-create " *Org todo*"))
13037 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13038 (erase-buffer)
13039 (setq-local org-done-keywords done-keywords)
13040 (setq tbl fulltable cnt 0)
13041 (while (setq e (pop tbl))
13042 (cond
13043 ((equal e '(:startgroup))
13044 (push '() groups) (setq ingroup t)
13045 (unless (= cnt 0)
13046 (setq cnt 0)
13047 (insert "\n"))
13048 (insert "{ "))
13049 ((equal e '(:endgroup))
13050 (setq ingroup nil cnt 0)
13051 (insert "}\n"))
13052 ((equal e '(:newline))
13053 (unless (= cnt 0)
13054 (setq cnt 0)
13055 (insert "\n")
13056 (setq e (car tbl))
13057 (while (equal (car tbl) '(:newline))
13058 (insert "\n")
13059 (setq tbl (cdr tbl)))))
13061 (setq tg (car e) c (cdr e))
13062 (when ingroup (push tg (car groups)))
13063 (setq tg (org-add-props tg nil 'face
13064 (org-get-todo-face tg)))
13065 (when (and (= cnt 0) (not ingroup)) (insert " "))
13066 (insert "[" c "] " tg (make-string
13067 (- fwidth 4 (length tg)) ?\ ))
13068 (when (= (setq cnt (1+ cnt)) ncol)
13069 (insert "\n")
13070 (when ingroup (insert " "))
13071 (setq cnt 0)))))
13072 (insert "\n")
13073 (goto-char (point-min))
13074 (unless expert (org-fit-window-to-buffer))
13075 (message "[a-z..]:Set [SPC]:clear")
13076 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13077 (cond
13078 ((or (= c ?\C-g)
13079 (and (= c ?q) (not (rassoc c fulltable))))
13080 (setq quit-flag t))
13081 ((= c ?\ ) nil)
13082 ((setq e (rassoc c fulltable) tg (car e))
13084 (t (setq quit-flag t)))))))
13086 (defun org-entry-is-todo-p ()
13087 (member (org-get-todo-state) org-not-done-keywords))
13089 (defun org-entry-is-done-p ()
13090 (member (org-get-todo-state) org-done-keywords))
13092 (defun org-get-todo-state ()
13093 "Return the TODO keyword of the current subtree."
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (and (looking-at org-todo-line-regexp)
13097 (match-end 2)
13098 (match-string 2))))
13100 (defun org-at-date-range-p (&optional inactive-ok)
13101 "Non-nil if point is inside a date range.
13103 When optional argument INACTIVE-OK is non-nil, also consider
13104 inactive time ranges.
13106 When this function returns a non-nil value, match data is set
13107 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13108 on INACTIVE-OK."
13109 (interactive)
13110 (save-excursion
13111 (catch 'exit
13112 (let ((pos (point)))
13113 (skip-chars-backward "^[<\r\n")
13114 (skip-chars-backward "<[")
13115 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13116 (>= (match-end 0) pos)
13117 (throw 'exit t))
13118 (skip-chars-backward "^<[\r\n")
13119 (skip-chars-backward "<[")
13120 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13121 (>= (match-end 0) pos)
13122 (throw 'exit t)))
13123 nil)))
13125 (defun org-get-repeat (&optional tagline)
13126 "Check if there is a deadline/schedule with repeater in this entry."
13127 (save-match-data
13128 (save-excursion
13129 (org-back-to-heading t)
13130 (and (re-search-forward (if tagline
13131 (concat tagline "\\s-*" org-repeat-re)
13132 org-repeat-re)
13133 (org-entry-end-position) t)
13134 (match-string-no-properties 1)))))
13136 (defvar org-last-changed-timestamp)
13137 (defvar org-last-inserted-timestamp)
13138 (defvar org-log-post-message)
13139 (defvar org-log-note-purpose)
13140 (defvar org-log-note-how nil)
13141 (defvar org-log-note-extra)
13142 (defun org-auto-repeat-maybe (done-word)
13143 "Check if the current headline contains a repeated time-stamp.
13145 If yes, set TODO state back to what it was and change the base date
13146 of repeating deadline/scheduled time stamps to new date.
13148 This function is run automatically after each state change to a DONE state."
13149 (let* ((repeat (org-get-repeat))
13150 (aa (assoc org-last-state org-todo-kwd-alist))
13151 (interpret (nth 1 aa))
13152 (head (nth 2 aa))
13153 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13154 (msg "Entry repeats: ")
13155 (org-log-done nil)
13156 (org-todo-log-states nil))
13157 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13158 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13159 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13160 org-todo-repeat-to-state)))
13161 (unless (and to-state (member to-state org-todo-keywords-1))
13162 (setq to-state (if (eq interpret 'type) org-last-state head)))
13163 (org-todo to-state))
13164 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13165 (org-entry-put nil "LAST_REPEAT" (format-time-string
13166 (org-time-stamp-format t t))))
13167 (when org-log-repeat
13168 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13169 (memq 'org-add-log-note post-command-hook))
13170 ;; We are already setup for some record.
13171 (when (eq org-log-repeat 'note)
13172 ;; Make sure we take a note, not only a time stamp.
13173 (setq org-log-note-how 'note))
13174 ;; Set up for taking a record.
13175 (org-add-log-setup 'state
13176 (or done-word (car org-done-keywords))
13177 org-last-state
13178 org-log-repeat)))
13179 (org-back-to-heading t)
13180 (org-add-planning-info nil nil 'closed)
13181 (let ((end (save-excursion (outline-next-heading) (point))))
13182 (while (re-search-forward org-ts-regexp end t)
13183 (when (save-match-data
13184 (or (org-at-planning-p)
13185 (org-at-property-p)
13186 (eq (org-element-type (save-excursion
13187 (backward-char)
13188 (org-element-context)))
13189 'timestamp)))
13190 (let ((type (cond ((match-end 1) org-scheduled-string)
13191 ((match-end 3) org-deadline-string)
13192 (t "Plain:")))
13193 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13194 (cond
13195 ((not
13196 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13197 ;; Time-stamps without a repeater are usually skipped.
13198 ;; However, a SCHEDULED time-stamp without one is
13199 ;; removed, as it is considered as no longer relevant.
13200 (when (equal type org-scheduled-string)
13201 (org-remove-timestamp-with-keyword type)))
13203 (let ((n (string-to-number (match-string 2 ts)))
13204 (what (match-string 3 ts)))
13205 (when (equal what "w") (setq n (* n 7) what "d"))
13206 (when (and (equal what "h")
13207 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13208 ts)))
13209 (user-error
13210 "Cannot repeat in Repeat in %d hour(s) because no hour \
13211 has been set"
13213 ;; Preparation, see if we need to modify the start
13214 ;; date for the change.
13215 (when (match-end 1)
13216 (let ((time (save-match-data (org-time-string-to-time ts))))
13217 (cond
13218 ((equal (match-string 1 ts) ".")
13219 ;; Shift starting date to today
13220 (org-timestamp-change
13221 (- (org-today) (time-to-days time))
13222 'day))
13223 ((equal (match-string 1 ts) "+")
13224 (let ((nshiftmax 10)
13225 (nshift 0))
13226 (while (or (= nshift 0)
13227 (not (time-less-p (current-time) time)))
13228 (when (= (cl-incf nshift) nshiftmax)
13229 (or (y-or-n-p
13230 (format "%d repeater intervals were not \
13231 enough to shift date past today. Continue? "
13232 nshift))
13233 (user-error "Abort")))
13234 (org-timestamp-change n (cdr (assoc what whata)))
13235 (org-at-timestamp-p t)
13236 (setq ts (match-string 1))
13237 (setq time
13238 (save-match-data
13239 (org-time-string-to-time ts)))))
13240 (org-timestamp-change (- n) (cdr (assoc what whata)))
13241 ;; Rematch, so that we have everything in
13242 ;; place for the real shift.
13243 (org-at-timestamp-p t)
13244 (setq ts (match-string 1))
13245 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13246 ts)))))
13247 (save-excursion
13248 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13249 (setq msg
13250 (concat
13251 msg type " " org-last-changed-timestamp " ")))))))))
13252 (setq org-log-post-message msg)
13253 (message "%s" msg))))
13255 (defun org-show-todo-tree (arg)
13256 "Make a compact tree which shows all headlines marked with TODO.
13257 The tree will show the lines where the regexp matches, and all higher
13258 headlines above the match.
13259 With a \\[universal-argument] prefix, prompt for a regexp to match.
13260 With a numeric prefix N, construct a sparse tree for the Nth element
13261 of `org-todo-keywords-1'."
13262 (interactive "P")
13263 (let ((case-fold-search nil)
13264 (kwd-re
13265 (cond ((null arg) org-not-done-regexp)
13266 ((equal arg '(4))
13267 (let ((kwd
13268 (completing-read "Keyword (or KWD1|KWD2|...): "
13269 (mapcar #'list org-todo-keywords-1))))
13270 (concat "\\("
13271 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13272 "\\)\\>")))
13273 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13274 (regexp-quote (nth (1- (prefix-numeric-value arg))
13275 org-todo-keywords-1)))
13276 (t (user-error "Invalid prefix argument: %s" arg)))))
13277 (message "%d TODO entries found"
13278 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13280 (defun org-deadline (arg &optional time)
13281 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13282 With one universal prefix argument, remove any deadline from the item.
13283 With two universal prefix arguments, prompt for a warning delay.
13284 With argument TIME, set the deadline at the corresponding date. TIME
13285 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13286 (interactive "P")
13287 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13288 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13289 'region-start-level 'region))
13290 org-loop-over-headlines-in-active-region)
13291 (org-map-entries
13292 `(org-deadline ',arg ,time)
13293 org-loop-over-headlines-in-active-region
13294 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13295 (let* ((old-date (org-entry-get nil "DEADLINE"))
13296 (old-date-time (when old-date (org-time-string-to-time old-date)))
13297 (repeater (and old-date
13298 (string-match
13299 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13300 old-date)
13301 (match-string 1 old-date))))
13302 (cond
13303 ((equal arg '(4))
13304 (when (and old-date org-log-redeadline)
13305 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13306 (org-remove-timestamp-with-keyword org-deadline-string)
13307 (message "Item no longer has a deadline."))
13308 ((equal arg '(16))
13309 (save-excursion
13310 (org-back-to-heading t)
13311 (if (re-search-forward
13312 org-deadline-time-regexp
13313 (save-excursion (outline-next-heading) (point)) t)
13314 (let* ((rpl0 (match-string 1))
13315 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13316 (replace-match
13317 (concat org-deadline-string
13318 " <" rpl
13319 (format " -%dd"
13320 (abs
13321 (- (time-to-days
13322 (save-match-data
13323 (org-read-date nil t nil "Warn starting from" old-date-time)))
13324 (time-to-days old-date-time))))
13325 ">") t t))
13326 (user-error "No deadline information to update"))))
13328 (org-add-planning-info 'deadline time 'closed)
13329 (when (and old-date
13330 org-log-redeadline
13331 (not (equal old-date org-last-inserted-timestamp)))
13332 (org-add-log-setup
13333 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13334 (when repeater
13335 (save-excursion
13336 (org-back-to-heading t)
13337 (when (re-search-forward (concat org-deadline-string " "
13338 org-last-inserted-timestamp)
13339 (save-excursion
13340 (outline-next-heading) (point)) t)
13341 (goto-char (1- (match-end 0)))
13342 (insert " " repeater)
13343 (setq org-last-inserted-timestamp
13344 (concat (substring org-last-inserted-timestamp 0 -1)
13345 " " repeater
13346 (substring org-last-inserted-timestamp -1))))))
13347 (message "Deadline on %s" org-last-inserted-timestamp))))))
13349 (defun org-schedule (arg &optional time)
13350 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13351 With one universal prefix argument, remove any scheduling date from the item.
13352 With two universal prefix arguments, prompt for a delay cookie.
13353 With argument TIME, scheduled at the corresponding date. TIME can
13354 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13355 (interactive "P")
13356 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13357 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13358 'region-start-level 'region))
13359 org-loop-over-headlines-in-active-region)
13360 (org-map-entries
13361 `(org-schedule ',arg ,time)
13362 org-loop-over-headlines-in-active-region
13363 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13364 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13365 (old-date-time (when old-date (org-time-string-to-time old-date)))
13366 (repeater (and old-date
13367 (string-match
13368 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13369 old-date)
13370 (match-string 1 old-date))))
13371 (cond
13372 ((equal arg '(4))
13373 (progn
13374 (when (and old-date org-log-reschedule)
13375 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13376 (org-remove-timestamp-with-keyword org-scheduled-string)
13377 (message "Item is no longer scheduled.")))
13378 ((equal arg '(16))
13379 (save-excursion
13380 (org-back-to-heading t)
13381 (if (re-search-forward
13382 org-scheduled-time-regexp
13383 (save-excursion (outline-next-heading) (point)) t)
13384 (let* ((rpl0 (match-string 1))
13385 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13386 (replace-match
13387 (concat org-scheduled-string
13388 " <" rpl
13389 (format " -%dd"
13390 (abs
13391 (- (time-to-days
13392 (save-match-data
13393 (org-read-date nil t nil "Delay until" old-date-time)))
13394 (time-to-days old-date-time))))
13395 ">") t t))
13396 (user-error "No scheduled information to update"))))
13398 (org-add-planning-info 'scheduled time 'closed)
13399 (when (and old-date
13400 org-log-reschedule
13401 (not (equal old-date org-last-inserted-timestamp)))
13402 (org-add-log-setup
13403 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13404 (when repeater
13405 (save-excursion
13406 (org-back-to-heading t)
13407 (when (re-search-forward (concat org-scheduled-string " "
13408 org-last-inserted-timestamp)
13409 (save-excursion
13410 (outline-next-heading) (point)) t)
13411 (goto-char (1- (match-end 0)))
13412 (insert " " repeater)
13413 (setq org-last-inserted-timestamp
13414 (concat (substring org-last-inserted-timestamp 0 -1)
13415 " " repeater
13416 (substring org-last-inserted-timestamp -1))))))
13417 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13419 (defun org-get-scheduled-time (pom &optional inherit)
13420 "Get the scheduled time as a time tuple, of a format suitable
13421 for calling org-schedule with, or if there is no scheduling,
13422 returns nil."
13423 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13424 (when time
13425 (apply 'encode-time (org-parse-time-string time)))))
13427 (defun org-get-deadline-time (pom &optional inherit)
13428 "Get the deadline as a time tuple, of a format suitable for
13429 calling org-deadline with, or if there is no scheduling, returns
13430 nil."
13431 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13432 (when time
13433 (apply 'encode-time (org-parse-time-string time)))))
13435 (defun org-remove-timestamp-with-keyword (keyword)
13436 "Remove all time stamps with KEYWORD in the current entry."
13437 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13438 beg)
13439 (save-excursion
13440 (org-back-to-heading t)
13441 (setq beg (point))
13442 (outline-next-heading)
13443 (while (re-search-backward re beg t)
13444 (replace-match "")
13445 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13446 (equal (char-before) ?\ ))
13447 (backward-delete-char 1)
13448 (when (string-match "^[ \t]*$" (buffer-substring
13449 (point-at-bol) (point-at-eol)))
13450 (delete-region (point-at-bol)
13451 (min (point-max) (1+ (point-at-eol))))))))))
13453 (defvar org-time-was-given) ; dynamically scoped parameter
13454 (defvar org-end-time-was-given) ; dynamically scoped parameter
13456 (defun org-at-planning-p ()
13457 "Non-nil when point is on a planning info line."
13458 ;; This is as accurate and faster than `org-element-at-point' since
13459 ;; planning info location is fixed in the section.
13460 (org-with-wide-buffer
13461 (beginning-of-line)
13462 (and (looking-at-p org-planning-line-re)
13463 (eq (point)
13464 (ignore-errors
13465 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13466 (org-back-to-heading t)
13467 (org-with-limited-levels (org-back-to-heading t)))
13468 (line-beginning-position 2))))))
13470 (defun org-add-planning-info (what &optional time &rest remove)
13471 "Insert new timestamp with keyword in the planning line.
13472 WHAT indicates what kind of time stamp to add. It is a symbol
13473 among `closed', `deadline', `scheduled' and nil. TIME indicates
13474 the time to use. If none is given, the user is prompted for
13475 a date. REMOVE indicates what kind of entries to remove. An old
13476 WHAT entry will also be removed."
13477 (let (org-time-was-given org-end-time-was-given default-time default-input)
13478 (catch 'exit
13479 (when (and (memq what '(scheduled deadline))
13480 (or (not time)
13481 (and (stringp time)
13482 (string-match "^[-+]+[0-9]" time))))
13483 ;; Try to get a default date/time from existing timestamp
13484 (save-excursion
13485 (org-back-to-heading t)
13486 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13487 (when (re-search-forward (if (eq what 'scheduled)
13488 org-scheduled-time-regexp
13489 org-deadline-time-regexp)
13490 end t)
13491 (setq ts (match-string 1)
13492 default-time (apply 'encode-time (org-parse-time-string ts))
13493 default-input (and ts (org-get-compact-tod ts)))))))
13494 (when what
13495 (setq time
13496 (if (stringp time)
13497 ;; This is a string (relative or absolute), set
13498 ;; proper date.
13499 (apply #'encode-time
13500 (org-read-date-analyze
13501 time default-time (decode-time default-time)))
13502 ;; If necessary, get the time from the user
13503 (or time (org-read-date nil 'to-time nil nil
13504 default-time default-input)))))
13506 (org-with-wide-buffer
13507 (org-back-to-heading t)
13508 (forward-line)
13509 (unless (bolp) (insert "\n"))
13510 (cond ((looking-at-p org-planning-line-re)
13511 ;; Move to current indentation.
13512 (skip-chars-forward " \t")
13513 ;; Check if we have to remove something.
13514 (dolist (type (if what (cons what remove) remove))
13515 (save-excursion
13516 (when (re-search-forward
13517 (cl-case type
13518 (closed org-closed-time-regexp)
13519 (deadline org-deadline-time-regexp)
13520 (scheduled org-scheduled-time-regexp)
13521 (otherwise
13522 (error "Invalid planning type: %s" type)))
13523 (line-end-position) t)
13524 ;; Delete until next keyword or end of line.
13525 (delete-region
13526 (match-beginning 0)
13527 (if (re-search-forward org-keyword-time-not-clock-regexp
13528 (line-end-position)
13530 (match-beginning 0)
13531 (line-end-position))))))
13532 ;; If there is nothing more to add and no more keyword
13533 ;; is left, remove the line completely.
13534 (if (and (looking-at-p "[ \t]*$") (not what))
13535 (delete-region (line-beginning-position)
13536 (line-beginning-position 2))
13537 ;; If we removed last keyword, do not leave trailing
13538 ;; white space at the end of line.
13539 (let ((p (point)))
13540 (save-excursion
13541 (end-of-line)
13542 (unless (= (skip-chars-backward " \t" p) 0)
13543 (delete-region (point) (line-end-position)))))))
13544 ((not what) (throw 'exit nil)) ; Nothing to do.
13545 (t (insert-before-markers "\n")
13546 (backward-char 1)
13547 (when org-adapt-indentation
13548 (indent-to-column (1+ (org-outline-level))))))
13549 (when what
13550 ;; Insert planning keyword.
13551 (insert (cl-case what
13552 (closed org-closed-string)
13553 (deadline org-deadline-string)
13554 (scheduled org-scheduled-string)
13555 (otherwise (error "Invalid planning type: %s" what)))
13556 " ")
13557 ;; Insert associated timestamp.
13558 (let ((ts (org-insert-time-stamp
13559 time
13560 (or org-time-was-given
13561 (and (eq what 'closed) org-log-done-with-time))
13562 (eq what 'closed)
13563 nil nil (list org-end-time-was-given))))
13564 (unless (eolp) (insert " "))
13565 ts))))))
13567 (defvar org-log-note-marker (make-marker)
13568 "Marker pointing at the entry where the note is to be inserted.")
13569 (defvar org-log-note-purpose nil)
13570 (defvar org-log-note-state nil)
13571 (defvar org-log-note-previous-state nil)
13572 (defvar org-log-note-extra nil)
13573 (defvar org-log-note-window-configuration nil)
13574 (defvar org-log-note-return-to (make-marker))
13575 (defvar org-log-note-effective-time nil
13576 "Remembered current time so that dynamically scoped
13577 `org-extend-today-until' affects timestamps in state change log")
13579 (defvar org-log-post-message nil
13580 "Message to be displayed after a log note has been stored.
13581 The auto-repeater uses this.")
13583 (defun org-add-note ()
13584 "Add a note to the current entry.
13585 This is done in the same way as adding a state change note."
13586 (interactive)
13587 (org-add-log-setup 'note))
13589 (defun org-log-beginning (&optional create)
13590 "Return expected start of log notes in current entry.
13591 When optional argument CREATE is non-nil, the function creates
13592 a drawer to store notes, if necessary. Returned position ignores
13593 narrowing."
13594 (org-with-wide-buffer
13595 (let ((drawer (org-log-into-drawer)))
13596 (cond
13597 (drawer
13598 (org-end-of-meta-data)
13599 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13600 (end (if (org-at-heading-p) (point)
13601 (save-excursion (outline-next-heading) (point))))
13602 (case-fold-search t))
13603 (catch 'exit
13604 ;; Try to find existing drawer.
13605 (while (re-search-forward regexp end t)
13606 (let ((element (org-element-at-point)))
13607 (when (eq (org-element-type element) 'drawer)
13608 (let ((cend (org-element-property :contents-end element)))
13609 (when (and (not org-log-states-order-reversed) cend)
13610 (goto-char cend)))
13611 (throw 'exit nil))))
13612 ;; No drawer found. Create one, if permitted.
13613 (when create
13614 (unless (bolp) (insert "\n"))
13615 (let ((beg (point)))
13616 (insert ":" drawer ":\n:END:\n")
13617 (org-indent-region beg (point)))
13618 (end-of-line -1)))))
13620 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13621 (skip-chars-forward " \t\n")
13622 (beginning-of-line)
13623 (unless org-log-states-order-reversed
13624 (org-skip-over-state-notes)
13625 (skip-chars-backward " \t\n")
13626 (forward-line)))))
13627 (if (bolp) (point) (line-beginning-position 2))))
13629 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13630 "Set up the post command hook to take a note.
13631 If this is about to TODO state change, the new state is expected in STATE.
13632 HOW is an indicator what kind of note should be created.
13633 EXTRA is additional text that will be inserted into the notes buffer."
13634 (move-marker org-log-note-marker (point))
13635 (setq org-log-note-purpose purpose
13636 org-log-note-state state
13637 org-log-note-previous-state prev-state
13638 org-log-note-how how
13639 org-log-note-extra extra
13640 org-log-note-effective-time (org-current-effective-time))
13641 (add-hook 'post-command-hook 'org-add-log-note 'append))
13643 (defun org-skip-over-state-notes ()
13644 "Skip past the list of State notes in an entry."
13645 (when (ignore-errors (goto-char (org-in-item-p)))
13646 (let* ((struct (org-list-struct))
13647 (prevs (org-list-prevs-alist struct))
13648 (regexp
13649 (concat "[ \t]*- +"
13650 (replace-regexp-in-string
13651 " +" " +"
13652 (org-replace-escapes
13653 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13654 `(("%d" . ,org-ts-regexp-inactive)
13655 ("%D" . ,org-ts-regexp)
13656 ("%s" . "\"\\S-+\"")
13657 ("%S" . "\"\\S-+\"")
13658 ("%t" . ,org-ts-regexp-inactive)
13659 ("%T" . ,org-ts-regexp)
13660 ("%u" . ".*?")
13661 ("%U" . ".*?")))))))
13662 (while (looking-at-p regexp)
13663 (goto-char (or (org-list-get-next-item (point) struct prevs)
13664 (org-list-get-item-end (point) struct)))))))
13666 (defun org-add-log-note (&optional _purpose)
13667 "Pop up a window for taking a note, and add this note later."
13668 (remove-hook 'post-command-hook 'org-add-log-note)
13669 (setq org-log-note-window-configuration (current-window-configuration))
13670 (delete-other-windows)
13671 (move-marker org-log-note-return-to (point))
13672 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13673 (goto-char org-log-note-marker)
13674 (org-switch-to-buffer-other-window "*Org Note*")
13675 (erase-buffer)
13676 (if (memq org-log-note-how '(time state))
13677 (let (current-prefix-arg) (org-store-log-note))
13678 (let ((org-inhibit-startup t)) (org-mode))
13679 (insert (format "# Insert note for %s.
13680 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13681 (cond
13682 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13683 ((eq org-log-note-purpose 'done) "closed todo item")
13684 ((eq org-log-note-purpose 'state)
13685 (format "state change from \"%s\" to \"%s\""
13686 (or org-log-note-previous-state "")
13687 (or org-log-note-state "")))
13688 ((eq org-log-note-purpose 'reschedule)
13689 "rescheduling")
13690 ((eq org-log-note-purpose 'delschedule)
13691 "no longer scheduled")
13692 ((eq org-log-note-purpose 'redeadline)
13693 "changing deadline")
13694 ((eq org-log-note-purpose 'deldeadline)
13695 "removing deadline")
13696 ((eq org-log-note-purpose 'refile)
13697 "refiling")
13698 ((eq org-log-note-purpose 'note)
13699 "this entry")
13700 (t (error "This should not happen")))))
13701 (when org-log-note-extra (insert org-log-note-extra))
13702 (setq-local org-finish-function 'org-store-log-note)
13703 (run-hooks 'org-log-buffer-setup-hook)))
13705 (defvar org-note-abort nil) ; dynamically scoped
13706 (defun org-store-log-note ()
13707 "Finish taking a log note, and insert it to where it belongs."
13708 (let ((txt (prog1 (buffer-string)
13709 (kill-buffer)))
13710 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13711 lines)
13712 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13713 (setq txt (replace-match "" t t txt)))
13714 (when (string-match "\\s-+\\'" txt)
13715 (setq txt (replace-match "" t t txt)))
13716 (setq lines (org-split-string txt "\n"))
13717 (when (org-string-nw-p note)
13718 (setq note
13719 (org-replace-escapes
13720 note
13721 (list (cons "%u" (user-login-name))
13722 (cons "%U" user-full-name)
13723 (cons "%t" (format-time-string
13724 (org-time-stamp-format 'long 'inactive)
13725 org-log-note-effective-time))
13726 (cons "%T" (format-time-string
13727 (org-time-stamp-format 'long nil)
13728 org-log-note-effective-time))
13729 (cons "%d" (format-time-string
13730 (org-time-stamp-format nil 'inactive)
13731 org-log-note-effective-time))
13732 (cons "%D" (format-time-string
13733 (org-time-stamp-format nil nil)
13734 org-log-note-effective-time))
13735 (cons "%s" (cond
13736 ((not org-log-note-state) "")
13737 ((org-string-match-p org-ts-regexp
13738 org-log-note-state)
13739 (format "\"[%s]\""
13740 (substring org-log-note-state 1 -1)))
13741 (t (format "\"%s\"" org-log-note-state))))
13742 (cons "%S"
13743 (cond
13744 ((not org-log-note-previous-state) "")
13745 ((org-string-match-p org-ts-regexp
13746 org-log-note-previous-state)
13747 (format "\"[%s]\""
13748 (substring
13749 org-log-note-previous-state 1 -1)))
13750 (t (format "\"%s\""
13751 org-log-note-previous-state)))))))
13752 (when lines (setq note (concat note " \\\\")))
13753 (push note lines))
13754 (when (and lines (not (or current-prefix-arg org-note-abort)))
13755 (with-current-buffer (marker-buffer org-log-note-marker)
13756 (org-with-wide-buffer
13757 ;; Find location for the new note.
13758 (goto-char org-log-note-marker)
13759 (set-marker org-log-note-marker nil)
13760 (goto-char (org-log-beginning t))
13761 ;; Make sure point is at the beginning of an empty line.
13762 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13763 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13764 ;; In an existing list, add a new item at the top level.
13765 ;; Otherwise, indent line like a regular one.
13766 (let ((itemp (org-in-item-p)))
13767 (if itemp
13768 (indent-line-to
13769 (let ((struct (save-excursion
13770 (goto-char itemp) (org-list-struct))))
13771 (org-list-get-ind (org-list-get-top-point struct) struct)))
13772 (org-indent-line)))
13773 (insert (org-list-bullet-string "-") (pop lines))
13774 (let ((ind (org-list-item-body-column (line-beginning-position))))
13775 (dolist (line lines)
13776 (insert "\n")
13777 (indent-line-to ind)
13778 (insert line)))
13779 (message "Note stored")
13780 (org-back-to-heading t)
13781 (org-cycle-hide-drawers 'children))
13782 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13783 ;; from within `org-add-log-note' because `buffer-undo-list'
13784 ;; is then modified outside of `org-with-remote-undo'.
13785 (when (eq this-command 'org-agenda-todo)
13786 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13787 ;; Don't add undo information when called from `org-agenda-todo'.
13788 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13789 (set-window-configuration org-log-note-window-configuration)
13790 (with-current-buffer (marker-buffer org-log-note-return-to)
13791 (goto-char org-log-note-return-to))
13792 (move-marker org-log-note-return-to nil)
13793 (when org-log-post-message (message "%s" org-log-post-message))))
13795 (defun org-remove-empty-drawer-at (pos)
13796 "Remove an empty drawer at position POS.
13797 POS may also be a marker."
13798 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13799 (org-with-wide-buffer
13800 (goto-char pos)
13801 (let ((drawer (org-element-at-point)))
13802 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13803 (not (org-element-property :contents-begin drawer)))
13804 (delete-region (org-element-property :begin drawer)
13805 (progn (goto-char (org-element-property :end drawer))
13806 (skip-chars-backward " \r\t\n")
13807 (forward-line)
13808 (point))))))))
13810 (defvar org-ts-type nil)
13811 (defun org-sparse-tree (&optional arg type)
13812 "Create a sparse tree, prompt for the details.
13813 This command can create sparse trees. You first need to select the type
13814 of match used to create the tree:
13816 t Show all TODO entries.
13817 T Show entries with a specific TODO keyword.
13818 m Show entries selected by a tags/property match.
13819 p Enter a property name and its value (both with completion on existing
13820 names/values) and show entries with that property.
13821 r Show entries matching a regular expression (`/' can be used as well).
13822 b Show deadlines and scheduled items before a date.
13823 a Show deadlines and scheduled items after a date.
13824 d Show deadlines due within `org-deadline-warning-days'.
13825 D Show deadlines and scheduled items between a date range."
13826 (interactive "P")
13827 (setq type (or type org-sparse-tree-default-date-type))
13828 (setq org-ts-type type)
13829 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13830 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13831 \[c]ycle through date types: %s"
13832 (cl-case type
13833 (all "all timestamps")
13834 (scheduled "only scheduled")
13835 (deadline "only deadline")
13836 (active "only active timestamps")
13837 (inactive "only inactive timestamps")
13838 (closed "with a closed time-stamp")
13839 (otherwise "scheduled/deadline")))
13840 (let ((answer (read-char-exclusive)))
13841 (cl-case answer
13843 (org-sparse-tree
13845 (cadr
13846 (memq type '(nil all scheduled deadline active inactive closed)))))
13847 (?d (call-interactively 'org-check-deadlines))
13848 (?b (call-interactively 'org-check-before-date))
13849 (?a (call-interactively 'org-check-after-date))
13850 (?D (call-interactively 'org-check-dates-range))
13851 (?t (call-interactively 'org-show-todo-tree))
13852 (?T (org-show-todo-tree '(4)))
13853 (?m (call-interactively 'org-match-sparse-tree))
13854 ((?p ?P)
13855 (let* ((kwd (completing-read
13856 "Property: " (mapcar #'list (org-buffer-property-keys))))
13857 (value (completing-read
13858 "Value: " (mapcar #'list (org-property-values kwd)))))
13859 (unless (string-match "\\`{.*}\\'" value)
13860 (setq value (concat "\"" value "\"")))
13861 (org-match-sparse-tree arg (concat kwd "=" value))))
13862 ((?r ?R ?/) (call-interactively 'org-occur))
13863 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13865 (defvar-local org-occur-highlights nil
13866 "List of overlays used for occur matches.")
13867 (defvar-local org-occur-parameters nil
13868 "Parameters of the active org-occur calls.
13869 This is a list, each call to org-occur pushes as cons cell,
13870 containing the regular expression and the callback, onto the list.
13871 The list can contain several entries if `org-occur' has been called
13872 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13873 will only contain one set of parameters. When the highlights are
13874 removed (for example with `C-c C-c', or with the next edit (depending
13875 on `org-remove-highlights-with-change'), this variable is emptied
13876 as well.")
13878 (defun org-occur (regexp &optional keep-previous callback)
13879 "Make a compact tree which shows all matches of REGEXP.
13881 The tree will show the lines where the regexp matches, and any other context
13882 defined in `org-show-context-detail', which see.
13884 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13885 done by a previous call to `org-occur' will be kept, to allow stacking of
13886 calls to this command.
13888 Optional argument CALLBACK can be a function of no argument. In this case,
13889 it is called with point at the end of the match, match data being set
13890 accordingly. Current match is shown only if the return value is non-nil.
13891 The function must neither move point nor alter narrowing."
13892 (interactive "sRegexp: \nP")
13893 (when (equal regexp "")
13894 (user-error "Regexp cannot be empty"))
13895 (unless keep-previous
13896 (org-remove-occur-highlights nil nil t))
13897 (push (cons regexp callback) org-occur-parameters)
13898 (let ((cnt 0))
13899 (save-excursion
13900 (goto-char (point-min))
13901 (when (or (not keep-previous) ; do not want to keep
13902 (not org-occur-highlights)) ; no previous matches
13903 ;; hide everything
13904 (org-overview))
13905 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13906 (isearch-no-upper-case-p regexp t)
13907 org-occur-case-fold-search)))
13908 (while (re-search-forward regexp nil t)
13909 (when (or (not callback)
13910 (save-match-data (funcall callback)))
13911 (setq cnt (1+ cnt))
13912 (when org-highlight-sparse-tree-matches
13913 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13914 (org-show-context 'occur-tree)))))
13915 (when org-remove-highlights-with-change
13916 (add-hook 'before-change-functions 'org-remove-occur-highlights
13917 nil 'local))
13918 (unless org-sparse-tree-open-archived-trees
13919 (org-hide-archived-subtrees (point-min) (point-max)))
13920 (run-hooks 'org-occur-hook)
13921 (when (called-interactively-p 'interactive)
13922 (message "%d match(es) for regexp %s" cnt regexp))
13923 cnt))
13925 (defun org-occur-next-match (&optional n _reset)
13926 "Function for `next-error-function' to find sparse tree matches.
13927 N is the number of matches to move, when negative move backwards.
13928 This function always goes back to the starting point when no
13929 match is found."
13930 (let* ((limit (if (< n 0) (point-min) (point-max)))
13931 (search-func (if (< n 0)
13932 'previous-single-char-property-change
13933 'next-single-char-property-change))
13934 (n (abs n))
13935 (pos (point))
13937 (catch 'exit
13938 (while (setq p1 (funcall search-func (point) 'org-type))
13939 (when (equal p1 limit)
13940 (goto-char pos)
13941 (user-error "No more matches"))
13942 (when (equal (get-char-property p1 'org-type) 'org-occur)
13943 (setq n (1- n))
13944 (when (= n 0)
13945 (goto-char p1)
13946 (throw 'exit (point))))
13947 (goto-char p1))
13948 (goto-char p1)
13949 (user-error "No more matches"))))
13951 (defun org-show-context (&optional key)
13952 "Make sure point and context are visible.
13953 Optional argument KEY, when non-nil, is a symbol. See
13954 `org-show-context-detail' for allowed values and how much is to
13955 be shown."
13956 (org-show-set-visibility
13957 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13958 ((cdr (assq key org-show-context-detail)))
13959 (t (cdr (assq 'default org-show-context-detail))))))
13961 (defun org-show-set-visibility (detail)
13962 "Set visibility around point according to DETAIL.
13963 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13964 `tree', `canonical' or t. See `org-show-context-detail' for more
13965 information."
13966 ;; Show current heading and possibly its entry, following headline
13967 ;; or all children.
13968 (if (and (org-at-heading-p) (not (eq detail 'local)))
13969 (org-flag-heading nil)
13970 (org-show-entry)
13971 ;; If point is hidden within a drawer or a block, make sure to
13972 ;; expose it.
13973 (dolist (o (overlays-at (point)))
13974 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13975 (delete-overlay o)))
13976 (unless (org-before-first-heading-p)
13977 (org-with-limited-levels
13978 (cl-case detail
13979 ((tree canonical t) (org-show-children))
13980 ((nil minimal ancestors))
13981 (t (save-excursion
13982 (outline-next-heading)
13983 (org-flag-heading nil)))))))
13984 ;; Show all siblings.
13985 (when (eq detail 'lineage) (org-show-siblings))
13986 ;; Show ancestors, possibly with their children.
13987 (when (memq detail '(ancestors lineage tree canonical t))
13988 (save-excursion
13989 (while (org-up-heading-safe)
13990 (org-flag-heading nil)
13991 (when (memq detail '(canonical t)) (org-show-entry))
13992 (when (memq detail '(tree canonical t)) (org-show-children))))))
13994 (defvar org-reveal-start-hook nil
13995 "Hook run before revealing a location.")
13997 (defun org-reveal (&optional siblings)
13998 "Show current entry, hierarchy above it, and the following headline.
14000 This can be used to show a consistent set of context around
14001 locations exposed with `org-show-context'.
14003 With optional argument SIBLINGS, on each level of the hierarchy all
14004 siblings are shown. This repairs the tree structure to what it would
14005 look like when opened with hierarchical calls to `org-cycle'.
14007 With double optional argument \\[universal-argument] \\[universal-argument], \
14008 go to the parent and show the
14009 entire tree."
14010 (interactive "P")
14011 (run-hooks 'org-reveal-start-hook)
14012 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14013 ((equal siblings '(16))
14014 (save-excursion
14015 (when (org-up-heading-safe)
14016 (org-show-subtree)
14017 (run-hook-with-args 'org-cycle-hook 'subtree))))
14018 (t (org-show-set-visibility 'lineage))))
14020 (defun org-highlight-new-match (beg end)
14021 "Highlight from BEG to END and mark the highlight is an occur headline."
14022 (let ((ov (make-overlay beg end)))
14023 (overlay-put ov 'face 'secondary-selection)
14024 (overlay-put ov 'org-type 'org-occur)
14025 (push ov org-occur-highlights)))
14027 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14028 "Remove the occur highlights from the buffer.
14029 BEG and END are ignored. If NOREMOVE is nil, remove this function
14030 from the `before-change-functions' in the current buffer."
14031 (interactive)
14032 (unless org-inhibit-highlight-removal
14033 (mapc #'delete-overlay org-occur-highlights)
14034 (setq org-occur-highlights nil)
14035 (setq org-occur-parameters nil)
14036 (unless noremove
14037 (remove-hook 'before-change-functions
14038 'org-remove-occur-highlights 'local))))
14040 ;;;; Priorities
14042 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14043 "Regular expression matching the priority indicator.")
14045 (defvar org-remove-priority-next-time nil)
14047 (defun org-priority-up ()
14048 "Increase the priority of the current item."
14049 (interactive)
14050 (org-priority 'up))
14052 (defun org-priority-down ()
14053 "Decrease the priority of the current item."
14054 (interactive)
14055 (org-priority 'down))
14057 (defun org-priority (&optional action _show)
14058 "Change the priority of an item.
14059 ACTION can be `set', `up', `down', or a character."
14060 (interactive "P")
14061 (if (equal action '(4))
14062 (org-show-priority)
14063 (unless org-enable-priority-commands
14064 (user-error "Priority commands are disabled"))
14065 (setq action (or action 'set))
14066 (let (current new news have remove)
14067 (save-excursion
14068 (org-back-to-heading t)
14069 (when (looking-at org-priority-regexp)
14070 (setq current (string-to-char (match-string 2))
14071 have t))
14072 (cond
14073 ((eq action 'remove)
14074 (setq remove t new ?\ ))
14075 ((or (eq action 'set)
14076 (integerp action))
14077 (if (not (eq action 'set))
14078 (setq new action)
14079 (message "Priority %c-%c, SPC to remove: "
14080 org-highest-priority org-lowest-priority)
14081 (save-match-data
14082 (setq new (read-char-exclusive))))
14083 (when (and (= (upcase org-highest-priority) org-highest-priority)
14084 (= (upcase org-lowest-priority) org-lowest-priority))
14085 (setq new (upcase new)))
14086 (cond ((equal new ?\ ) (setq remove t))
14087 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14088 (user-error "Priority must be between `%c' and `%c'"
14089 org-highest-priority org-lowest-priority))))
14090 ((eq action 'up)
14091 (setq new (if have
14092 (1- current) ; normal cycling
14093 ;; last priority was empty
14094 (if (eq last-command this-command)
14095 org-lowest-priority ; wrap around empty to lowest
14096 ;; default
14097 (if org-priority-start-cycle-with-default
14098 org-default-priority
14099 (1- org-default-priority))))))
14100 ((eq action 'down)
14101 (setq new (if have
14102 (1+ current) ; normal cycling
14103 ;; last priority was empty
14104 (if (eq last-command this-command)
14105 org-highest-priority ; wrap around empty to highest
14106 ;; default
14107 (if org-priority-start-cycle-with-default
14108 org-default-priority
14109 (1+ org-default-priority))))))
14110 (t (user-error "Invalid action")))
14111 (when (or (< (upcase new) org-highest-priority)
14112 (> (upcase new) org-lowest-priority))
14113 (if (and (memq action '(up down))
14114 (not have) (not (eq last-command this-command)))
14115 ;; `new' is from default priority
14116 (error
14117 "The default can not be set, see `org-default-priority' why")
14118 ;; normal cycling: `new' is beyond highest/lowest priority
14119 ;; and is wrapped around to the empty priority
14120 (setq remove t)))
14121 (setq news (format "%c" new))
14122 (if have
14123 (if remove
14124 (replace-match "" t t nil 1)
14125 (replace-match news t t nil 2))
14126 (if remove
14127 (user-error "No priority cookie found in line")
14128 (let ((case-fold-search nil))
14129 (looking-at org-todo-line-regexp))
14130 (if (match-end 2)
14131 (progn
14132 (goto-char (match-end 2))
14133 (insert " [#" news "]"))
14134 (goto-char (match-beginning 3))
14135 (insert "[#" news "] "))))
14136 (org-set-tags nil 'align))
14137 (if remove
14138 (message "Priority removed")
14139 (message "Priority of current item set to %s" news)))))
14141 (defun org-show-priority ()
14142 "Show the priority of the current item.
14143 This priority is composed of the main priority given with the [#A] cookies,
14144 and by additional input from the age of a schedules or deadline entry."
14145 (interactive)
14146 (let ((pri (if (eq major-mode 'org-agenda-mode)
14147 (org-get-at-bol 'priority)
14148 (save-excursion
14149 (save-match-data
14150 (beginning-of-line)
14151 (and (looking-at org-heading-regexp)
14152 (org-get-priority (match-string 0))))))))
14153 (message "Priority is %d" (if pri pri -1000))))
14155 (defun org-get-priority (s)
14156 "Find priority cookie and return priority."
14157 (save-match-data
14158 (if (functionp org-get-priority-function)
14159 (funcall org-get-priority-function)
14160 (if (not (string-match org-priority-regexp s))
14161 (* 1000 (- org-lowest-priority org-default-priority))
14162 (* 1000 (- org-lowest-priority
14163 (string-to-char (match-string 2 s))))))))
14165 ;;;; Tags
14167 (defvar org-agenda-archives-mode)
14168 (defvar org-map-continue-from nil
14169 "Position from where mapping should continue.
14170 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14172 (defvar org-scanner-tags nil
14173 "The current tag list while the tags scanner is running.")
14175 (defvar org-trust-scanner-tags nil
14176 "Should `org-get-tags-at' use the tags for the scanner.
14177 This is for internal dynamical scoping only.
14178 When this is non-nil, the function `org-get-tags-at' will return the value
14179 of `org-scanner-tags' instead of building the list by itself. This
14180 can lead to large speed-ups when the tags scanner is used in a file with
14181 many entries, and when the list of tags is retrieved, for example to
14182 obtain a list of properties. Building the tags list for each entry in such
14183 a file becomes an N^2 operation - but with this variable set, it scales
14184 as N.")
14186 (defvar org--matcher-tags-todo-only nil)
14188 (defun org-scan-tags (action matcher todo-only &optional start-level)
14189 "Scan headline tags with inheritance and produce output ACTION.
14191 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14192 or `agenda' to produce an entry list for an agenda view. It can also be
14193 a Lisp form or a function that should be called at each matched headline, in
14194 this case the return value is a list of all return values from these calls.
14196 MATCHER is a function accepting three arguments, returning
14197 a non-nil value whenever a given set of tags qualifies a headline
14198 for inclusion. See `org-make-tags-matcher' for more information.
14199 As a special case, it can also be set to t (respectively nil) in
14200 order to match all (respectively none) headline.
14202 When TODO-ONLY is non-nil, only lines with a not-done TODO
14203 keyword are included in the output.
14205 START-LEVEL can be a string with asterisks, reducing the scope to
14206 headlines matching this string."
14207 (require 'org-agenda)
14208 (let* ((re (concat "^"
14209 (if start-level
14210 ;; Get the correct level to match
14211 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14212 org-outline-regexp)
14213 " *\\(\\<\\("
14214 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14215 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14216 (props (list 'face 'default
14217 'done-face 'org-agenda-done
14218 'undone-face 'default
14219 'mouse-face 'highlight
14220 'org-not-done-regexp org-not-done-regexp
14221 'org-todo-regexp org-todo-regexp
14222 'org-complex-heading-regexp org-complex-heading-regexp
14223 'help-echo
14224 (format "mouse-2 or RET jump to org file %s"
14225 (abbreviate-file-name
14226 (or (buffer-file-name (buffer-base-buffer))
14227 (buffer-name (buffer-base-buffer)))))))
14228 (org-map-continue-from nil)
14229 lspos tags tags-list
14230 (tags-alist (list (cons 0 org-file-tags)))
14231 (llast 0) rtn rtn1 level category i txt
14232 todo marker entry priority
14233 ts-date ts-date-type ts-date-pair)
14234 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14235 (setq action (list 'lambda nil action)))
14236 (save-excursion
14237 (goto-char (point-min))
14238 (when (eq action 'sparse-tree)
14239 (org-overview)
14240 (org-remove-occur-highlights))
14241 (while (let (case-fold-search)
14242 (re-search-forward re nil t))
14243 (setq org-map-continue-from nil)
14244 (catch :skip
14245 (setq todo
14246 ;; TODO: is the 1-2 difference a bug?
14247 (when (match-end 1) (match-string-no-properties 2))
14248 tags (when (match-end 4) (match-string-no-properties 4)))
14249 (goto-char (setq lspos (match-beginning 0)))
14250 (setq level (org-reduced-level (org-outline-level))
14251 category (org-get-category))
14252 (when (eq action 'agenda)
14253 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14254 ts-date (car ts-date-pair)
14255 ts-date-type (cdr ts-date-pair)))
14256 (setq i llast llast level)
14257 ;; remove tag lists from same and sublevels
14258 (while (>= i level)
14259 (when (setq entry (assoc i tags-alist))
14260 (setq tags-alist (delete entry tags-alist)))
14261 (setq i (1- i)))
14262 ;; add the next tags
14263 (when tags
14264 (setq tags (org-split-string tags ":")
14265 tags-alist
14266 (cons (cons level tags) tags-alist)))
14267 ;; compile tags for current headline
14268 (setq tags-list
14269 (if org-use-tag-inheritance
14270 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14271 tags)
14272 org-scanner-tags tags-list)
14273 (when org-use-tag-inheritance
14274 (setcdr (car tags-alist)
14275 (mapcar (lambda (x)
14276 (setq x (copy-sequence x))
14277 (org-add-prop-inherited x))
14278 (cdar tags-alist))))
14279 (when (and tags org-use-tag-inheritance
14280 (or (not (eq t org-use-tag-inheritance))
14281 org-tags-exclude-from-inheritance))
14282 ;; Selective inheritance, remove uninherited ones.
14283 (setcdr (car tags-alist)
14284 (org-remove-uninherited-tags (cdar tags-alist))))
14285 (when (and
14287 ;; eval matcher only when the todo condition is OK
14288 (and (or (not todo-only) (member todo org-not-done-keywords))
14289 (if (functionp matcher)
14290 (let ((case-fold-search t) (org-trust-scanner-tags t))
14291 (funcall matcher todo tags-list level))
14292 matcher))
14294 ;; Call the skipper, but return t if it does not
14295 ;; skip, so that the `and' form continues evaluating.
14296 (progn
14297 (unless (eq action 'sparse-tree) (org-agenda-skip))
14300 ;; Check if timestamps are deselecting this entry
14301 (or (not todo-only)
14302 (and (member todo org-not-done-keywords)
14303 (or (not org-agenda-tags-todo-honor-ignore-options)
14304 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14306 ;; select this headline
14307 (cond
14308 ((eq action 'sparse-tree)
14309 (and org-highlight-sparse-tree-matches
14310 (org-get-heading) (match-end 0)
14311 (org-highlight-new-match
14312 (match-beginning 1) (match-end 1)))
14313 (org-show-context 'tags-tree))
14314 ((eq action 'agenda)
14315 (setq txt (org-agenda-format-item
14317 (concat
14318 (if (eq org-tags-match-list-sublevels 'indented)
14319 (make-string (1- level) ?.) "")
14320 (org-get-heading))
14321 (make-string level ?\s)
14322 category
14323 tags-list)
14324 priority (org-get-priority txt))
14325 (goto-char lspos)
14326 (setq marker (org-agenda-new-marker))
14327 (org-add-props txt props
14328 'org-marker marker 'org-hd-marker marker 'org-category category
14329 'todo-state todo
14330 'ts-date ts-date
14331 'priority priority
14332 'type (concat "tagsmatch" ts-date-type))
14333 (push txt rtn))
14334 ((functionp action)
14335 (setq org-map-continue-from nil)
14336 (save-excursion
14337 (setq rtn1 (funcall action))
14338 (push rtn1 rtn)))
14339 (t (user-error "Invalid action")))
14341 ;; if we are to skip sublevels, jump to end of subtree
14342 (unless org-tags-match-list-sublevels
14343 (org-end-of-subtree t)
14344 (backward-char 1))))
14345 ;; Get the correct position from where to continue
14346 (if org-map-continue-from
14347 (goto-char org-map-continue-from)
14348 (and (= (point) lspos) (end-of-line 1)))))
14349 (when (and (eq action 'sparse-tree)
14350 (not org-sparse-tree-open-archived-trees))
14351 (org-hide-archived-subtrees (point-min) (point-max)))
14352 (nreverse rtn)))
14354 (defun org-remove-uninherited-tags (tags)
14355 "Remove all tags that are not inherited from the list TAGS."
14356 (cond
14357 ((eq org-use-tag-inheritance t)
14358 (if org-tags-exclude-from-inheritance
14359 (org-delete-all org-tags-exclude-from-inheritance tags)
14360 tags))
14361 ((not org-use-tag-inheritance) nil)
14362 ((stringp org-use-tag-inheritance)
14363 (delq nil (mapcar
14364 (lambda (x)
14365 (if (and (string-match org-use-tag-inheritance x)
14366 (not (member x org-tags-exclude-from-inheritance)))
14367 x nil))
14368 tags)))
14369 ((listp org-use-tag-inheritance)
14370 (delq nil (mapcar
14371 (lambda (x)
14372 (if (member x org-use-tag-inheritance) x nil))
14373 tags)))))
14375 (defun org-match-sparse-tree (&optional todo-only match)
14376 "Create a sparse tree according to tags string MATCH.
14377 MATCH can contain positive and negative selection of tags, like
14378 \"+WORK+URGENT-WITHBOSS\".
14379 If optional argument TODO-ONLY is non-nil, only select lines that are
14380 also TODO lines."
14381 (interactive "P")
14382 (org-agenda-prepare-buffers (list (current-buffer)))
14383 (let ((org--matcher-tags-todo-only todo-only))
14384 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14385 org--matcher-tags-todo-only)))
14387 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14389 (defvar org-cached-props nil)
14390 (defun org-cached-entry-get (pom property)
14391 (if (or (eq t org-use-property-inheritance)
14392 (and (stringp org-use-property-inheritance)
14393 (let ((case-fold-search t))
14394 (org-string-match-p org-use-property-inheritance property)))
14395 (and (listp org-use-property-inheritance)
14396 (member-ignore-case property org-use-property-inheritance)))
14397 ;; Caching is not possible, check it directly.
14398 (org-entry-get pom property 'inherit)
14399 ;; Get all properties, so we can do complicated checks easily.
14400 (cdr (assoc-string property
14401 (or org-cached-props
14402 (setq org-cached-props (org-entry-properties pom)))
14403 t))))
14405 (defun org-global-tags-completion-table (&optional files)
14406 "Return the list of all tags in all agenda buffer/files.
14407 Optional FILES argument is a list of files which can be used
14408 instead of the agenda files."
14409 (save-excursion
14410 (org-uniquify
14411 (delq nil
14412 (apply #'append
14413 (mapcar
14414 (lambda (file)
14415 (set-buffer (find-file-noselect file))
14416 (mapcar (lambda (x)
14417 (and (stringp (car-safe x))
14418 (list (car-safe x))))
14419 (or org-current-tag-alist (org-get-buffer-tags))))
14420 (if (car-safe files) files
14421 (org-agenda-files))))))))
14423 (defun org-make-tags-matcher (match)
14424 "Create the TAGS/TODO matcher form for the selection string MATCH.
14426 Returns a cons of the selection string MATCH and a function
14427 implementing the matcher.
14429 The matcher is to be called at an Org entry, with point on the
14430 headline, and returns non-nil if the entry matches the selection
14431 string MATCH. It must be called with three arguments: the TODO
14432 keyword at the entry (or nil if none), the list of all tags at
14433 the entry including inherited ones and the reduced level of the
14434 headline. Additionally, the category of the entry, if any, must
14435 be specified as the text property `org-category' on the headline.
14437 This function sets the variable `org--matcher-tags-todo-only' to
14438 a non-nil value if the matcher restricts matching to TODO
14439 entries, otherwise it is not touched.
14441 See also `org-scan-tags'."
14442 (unless match
14443 ;; Get a new match request, with completion against the global
14444 ;; tags table and the local tags in current buffer.
14445 (let ((org-last-tags-completion-table
14446 (org-uniquify
14447 (delq nil (append (org-get-buffer-tags)
14448 (org-global-tags-completion-table))))))
14449 (setq match
14450 (completing-read
14451 "Match: "
14452 'org-tags-completion-function nil nil nil 'org-tags-history))))
14454 (let ((match0 match)
14455 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14456 (start 0)
14457 tagsmatch todomatch tagsmatcher todomatcher)
14459 ;; Expand group tags.
14460 (setq match (org-tags-expand match))
14462 ;; Check if there is a TODO part of this match, which would be the
14463 ;; part after a "/". To make sure that this slash is not part of
14464 ;; a property value to be matched against, we also check that
14465 ;; there is no / after that slash. First, find the last slash.
14466 (let ((s 0))
14467 (while (string-match "/+" match s)
14468 (setq start (match-beginning 0))
14469 (setq s (match-end 0))))
14470 (if (and (string-match "/+" match start)
14471 (not (string-match-p "\"" match start)))
14472 ;; Match contains also a TODO-matching request.
14473 (progn
14474 (setq tagsmatch (substring match 0 (match-beginning 0)))
14475 (setq todomatch (substring match (match-end 0)))
14476 (when (string-match "\\`!" todomatch)
14477 (setq org--matcher-tags-todo-only t)
14478 (setq todomatch (substring todomatch 1)))
14479 (when (string-match "\\`\\s-*\\'" todomatch)
14480 (setq todomatch nil)))
14481 ;; Only matching tags.
14482 (setq tagsmatch match)
14483 (setq todomatch nil))
14485 ;; Make the tags matcher.
14486 (when (org-string-nw-p tagsmatch)
14487 (let ((orlist nil)
14488 (orterms (org-split-string tagsmatch "|"))
14489 term)
14490 (while (setq term (pop orterms))
14491 (while (and (equal (substring term -1) "\\") orterms)
14492 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14493 (while (string-match re term)
14494 (let* ((rest (substring term (match-end 0)))
14495 (minus (and (match-end 1)
14496 (equal (match-string 1 term) "-")))
14497 (tag (save-match-data
14498 (replace-regexp-in-string
14499 "\\\\-" "-" (match-string 2 term))))
14500 (regexp (eq (string-to-char tag) ?{))
14501 (levelp (match-end 4))
14502 (propp (match-end 5))
14504 (cond
14505 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14506 (levelp
14507 `(,(org-op-to-function (match-string 3 term))
14508 level
14509 ,(string-to-number (match-string 4 term))))
14510 (propp
14511 (let* ((gv (pcase (upcase (match-string 5 term))
14512 ("CATEGORY"
14513 '(get-text-property (point) 'org-category))
14514 ("TODO" 'todo)
14515 (p `(org-cached-entry-get nil ,p))))
14516 (pv (match-string 7 term))
14517 (regexp (eq (string-to-char pv) ?{))
14518 (strp (eq (string-to-char pv) ?\"))
14519 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14520 (po (org-op-to-function (match-string 6 term)
14521 (if timep 'time strp))))
14522 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14523 (when timep (setq pv (org-matcher-time pv)))
14524 (cond ((and regexp (eq po 'org<>))
14525 `(not (string-match ,pv (or ,gv ""))))
14526 (regexp `(string-match ,pv (or ,gv "")))
14527 (strp `(,po (or ,gv "") ,pv))
14529 `(,po
14530 (string-to-number (or ,gv ""))
14531 ,(string-to-number pv))))))
14532 (t `(member ,tag tags-list)))))
14533 (push (if minus `(not ,mm) mm) tagsmatcher)
14534 (setq term rest)))
14535 (push `(and ,@tagsmatcher) orlist)
14536 (setq tagsmatcher nil))
14537 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14539 ;; Make the TODO matcher.
14540 (when (org-string-nw-p todomatch)
14541 (let ((orlist nil))
14542 (dolist (term (org-split-string todomatch "|"))
14543 (while (string-match re term)
14544 (let* ((minus (and (match-end 1)
14545 (equal (match-string 1 term) "-")))
14546 (kwd (match-string 2 term))
14547 (regexp (eq (string-to-char kwd) ?{))
14548 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14549 `(equal todo ,kwd))))
14550 (push (if minus `(not ,mm) mm) todomatcher))
14551 (setq term (substring term (match-end 0))))
14552 (push (if (> (length todomatcher) 1)
14553 (cons 'and todomatcher)
14554 (car todomatcher))
14555 orlist)
14556 (setq todomatcher nil))
14557 (setq todomatcher (cons 'or orlist))))
14559 ;; Return the string and function of the matcher. If no
14560 ;; tags-specific or todo-specific matcher exists, match
14561 ;; everything.
14562 (let ((matcher (if (and tagsmatcher todomatcher)
14563 `(and ,tagsmatcher ,todomatcher)
14564 (or tagsmatcher todomatcher t))))
14565 (when org--matcher-tags-todo-only
14566 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14567 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14569 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14570 "Expand group tags in MATCH.
14572 This replaces every group tag in MATCH with a regexp tag search.
14573 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14574 will be replaced like this:
14576 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14577 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14578 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14580 Replacing by a regexp preserves the structure of the match.
14581 E.g., this expansion
14583 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14585 will match anything tagged with \"Lab\" and \"Home\", or tagged
14586 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14588 A group tag in MATCH can contain regular expressions of its own.
14589 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14590 will be replaced like this:
14592 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14594 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14595 assumed to be a single group tag, and the function will return
14596 the list of tags in this group.
14598 When DOWNCASE is non-nil, expand downcased TAGS."
14599 (if org-group-tags
14600 (let* ((case-fold-search t)
14601 (stable org-mode-syntax-table)
14602 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14603 (taggroups (if downcased
14604 (mapcar (lambda (tg) (mapcar #'downcase tg))
14605 taggroups)
14606 taggroups))
14607 (taggroups-keys (mapcar #'car taggroups))
14608 (return-match (if downcased (downcase match) match))
14609 (count 0)
14610 (work-already-expanded tags-already-expanded)
14611 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14612 ;; @ and _ are allowed as word-components in tags.
14613 (modify-syntax-entry ?@ "w" stable)
14614 (modify-syntax-entry ?_ "w" stable)
14615 ;; Temporarily replace regexp-expressions in the match-expression.
14616 (while (string-match "{.+?}" return-match)
14617 (cl-incf count)
14618 (push (match-string 0 return-match) regexps-in-match)
14619 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14620 (while (and taggroups-keys
14621 (with-syntax-table stable
14622 (string-match
14623 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14624 (regexp-opt taggroups-keys) "\\>\\)")
14625 return-match)))
14626 (let* ((dir (match-string 1 return-match))
14627 (tag (match-string 2 return-match))
14628 (tag (if downcased (downcase tag) tag)))
14629 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14630 (member tag work-already-expanded))
14631 (setq tags-in-group (assoc tag taggroups))
14632 (push tag work-already-expanded)
14633 ;; Recursively expand each tag in the group, if the tag hasn't
14634 ;; already been expanded. Restore the match-data after all recursive calls.
14635 (save-match-data
14636 (let (tags-expanded)
14637 (dolist (x (cdr tags-in-group))
14638 (if (and (member x taggroups-keys)
14639 (not (member x work-already-expanded)))
14640 (setq tags-expanded
14641 (delete-dups
14642 (append
14643 (org-tags-expand x t downcased
14644 work-already-expanded)
14645 tags-expanded)))
14646 (setq tags-expanded
14647 (append (list x) tags-expanded)))
14648 (setq work-already-expanded
14649 (delete-dups
14650 (append tags-expanded
14651 work-already-expanded))))
14652 (setq tags-in-group
14653 (delete-dups (cons (car tags-in-group)
14654 tags-expanded)))))
14655 ;; Filter tag-regexps from tags.
14656 (setq regexp-in-group-escaped
14657 (delq nil (mapcar (lambda (x)
14658 (if (stringp x)
14659 (and (equal "{" (substring x 0 1))
14660 (equal "}" (substring x -1))
14663 tags-in-group))
14664 regexp-in-group
14665 (mapcar (lambda (x)
14666 (substring x 1 -1))
14667 regexp-in-group-escaped)
14668 tags-in-group
14669 (delq nil (mapcar (lambda (x)
14670 (if (stringp x)
14671 (and (not (equal "{" (substring x 0 1)))
14672 (not (equal "}" (substring x -1)))
14675 tags-in-group)))
14676 ;; If single-as-list, do no more in the while-loop.
14677 (if (not single-as-list)
14678 (progn
14679 (when regexp-in-group
14680 (setq regexp-in-group
14681 (concat "\\|"
14682 (mapconcat 'identity regexp-in-group
14683 "\\|"))))
14684 (setq tags-in-group
14685 (concat dir
14686 "{\\<"
14687 (regexp-opt tags-in-group)
14688 "\\>"
14689 regexp-in-group
14690 "}"))
14691 (when (stringp tags-in-group)
14692 (org-add-props tags-in-group '(grouptag t)))
14693 (setq return-match
14694 (replace-match tags-in-group t t return-match)))
14695 (setq tags-in-group
14696 (append regexp-in-group-escaped tags-in-group))))
14697 (setq taggroups-keys (delete tag taggroups-keys))))
14698 ;; Add the regular expressions back into the match-expression again.
14699 (while regexps-in-match
14700 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14701 (pop regexps-in-match)
14702 return-match t t))
14703 (cl-decf count))
14704 (if single-as-list
14705 (if tags-in-group tags-in-group (list return-match))
14706 return-match))
14707 (if single-as-list
14708 (list (if downcased (downcase match) match))
14709 match)))
14711 (defun org-op-to-function (op &optional stringp)
14712 "Turn an operator into the appropriate function."
14713 (setq op
14714 (cond
14715 ((equal op "<" ) '(< string< org-time<))
14716 ((equal op ">" ) '(> org-string> org-time>))
14717 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14718 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14719 ((member op '("=" "==")) '(= string= org-time=))
14720 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14721 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14723 (defun org<> (a b) (not (= a b)))
14724 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14725 (defun org-string>= (a b) (not (string< a b)))
14726 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14727 (defun org-string<> (a b) (not (string= a b)))
14728 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14729 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14730 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14731 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14732 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14733 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14734 (defun org-2ft (s)
14735 "Convert S to a floating point time.
14736 If S is already a number, just return it. If it is a string, parse
14737 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14738 (cond
14739 ((numberp s) s)
14740 ((stringp s)
14741 (condition-case nil
14742 (float-time (apply 'encode-time (org-parse-time-string s)))
14743 (error 0.)))
14744 (t 0.)))
14746 (defun org-time-today ()
14747 "Time in seconds today at 0:00.
14748 Returns the float number of seconds since the beginning of the
14749 epoch to the beginning of today (00:00)."
14750 (float-time (apply 'encode-time
14751 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14753 (defun org-matcher-time (s)
14754 "Interpret a time comparison value."
14755 (save-match-data
14756 (cond
14757 ((string= s "<now>") (float-time))
14758 ((string= s "<today>") (org-time-today))
14759 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14760 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14761 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14762 (+ (org-time-today)
14763 (* (string-to-number (match-string 1 s))
14764 (cdr (assoc (match-string 2 s)
14765 '(("d" . 86400.0) ("w" . 604800.0)
14766 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14767 (t (org-2ft s)))))
14769 (defun org-match-any-p (re list)
14770 "Does re match any element of list?"
14771 (setq list (mapcar (lambda (x) (string-match re x)) list))
14772 (delq nil list))
14774 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14775 (defvar org-tags-overlay (make-overlay 1 1))
14776 (delete-overlay org-tags-overlay)
14778 (defun org-get-local-tags-at (&optional pos)
14779 "Get a list of tags defined in the current headline."
14780 (org-get-tags-at pos 'local))
14782 (defun org-get-local-tags ()
14783 "Get a list of tags defined in the current headline."
14784 (org-get-tags-at nil 'local))
14786 (defun org-get-tags-at (&optional pos local)
14787 "Get a list of all headline tags applicable at POS.
14788 POS defaults to point. If tags are inherited, the list contains
14789 the targets in the same sequence as the headlines appear, i.e.
14790 the tags of the current headline come last.
14791 When LOCAL is non-nil, only return tags from the current headline,
14792 ignore inherited ones."
14793 (interactive)
14794 (if (and org-trust-scanner-tags
14795 (or (not pos) (equal pos (point)))
14796 (not local))
14797 org-scanner-tags
14798 (let (tags ltags lastpos parent)
14799 (save-excursion
14800 (save-restriction
14801 (widen)
14802 (goto-char (or pos (point)))
14803 (save-match-data
14804 (catch 'done
14805 (condition-case nil
14806 (progn
14807 (org-back-to-heading t)
14808 (while (not (equal lastpos (point)))
14809 (setq lastpos (point))
14810 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14811 (setq ltags (org-split-string
14812 (match-string-no-properties 1) ":"))
14813 (when parent
14814 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14815 (setq tags (append
14816 (if parent
14817 (org-remove-uninherited-tags ltags)
14818 ltags)
14819 tags)))
14820 (or org-use-tag-inheritance (throw 'done t))
14821 (when local (throw 'done t))
14822 (or (org-up-heading-safe) (error nil))
14823 (setq parent t)))
14824 (error nil)))))
14825 (if local
14826 tags
14827 (reverse (delete-dups
14828 (reverse (append
14829 (org-remove-uninherited-tags
14830 org-file-tags)
14831 tags)))))))))
14833 (defun org-add-prop-inherited (s)
14834 (add-text-properties 0 (length s) '(inherited t) s)
14837 (defun org-toggle-tag (tag &optional onoff)
14838 "Toggle the tag TAG for the current line.
14839 If ONOFF is `on' or `off', don't toggle but set to this state."
14840 (let (res current)
14841 (save-excursion
14842 (org-back-to-heading t)
14843 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14844 (point-at-eol) t)
14845 (progn
14846 (setq current (match-string 1))
14847 (replace-match ""))
14848 (setq current ""))
14849 (setq current (nreverse (org-split-string current ":")))
14850 (cond
14851 ((eq onoff 'on)
14852 (setq res t)
14853 (or (member tag current) (push tag current)))
14854 ((eq onoff 'off)
14855 (or (not (member tag current)) (setq current (delete tag current))))
14856 (t (if (member tag current)
14857 (setq current (delete tag current))
14858 (setq res t)
14859 (push tag current))))
14860 (end-of-line 1)
14861 (if current
14862 (progn
14863 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14864 (org-set-tags nil t))
14865 (delete-horizontal-space))
14866 (run-hooks 'org-after-tags-change-hook))
14867 res))
14869 (defun org-align-tags-here (to-col)
14870 ;; Assumes that this is a headline
14871 "Align tags on the current headline to TO-COL."
14872 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14873 (beginning-of-line 1)
14874 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14875 (< pos (match-beginning 2)))
14876 (progn
14877 (setq tags-l (string-width (match-string 2)))
14878 (goto-char (match-beginning 1))
14879 (insert " ")
14880 (delete-region (point) (1+ (match-beginning 2)))
14881 (setq ncol (max (current-column)
14882 (1+ col)
14883 (if (> to-col 0)
14884 to-col
14885 (- (abs to-col) tags-l))))
14886 (setq p (point))
14887 (insert (make-string (- ncol (current-column)) ?\ ))
14888 (setq ncol (current-column))
14889 (when indent-tabs-mode (tabify p (point-at-eol)))
14890 (org-move-to-column (min ncol col)))
14891 (goto-char pos))))
14893 (defun org-set-tags-command (&optional arg just-align)
14894 "Call the set-tags command for the current entry."
14895 (interactive "P")
14896 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14897 (org-set-tags arg just-align)
14898 (save-excursion
14899 (unless (and (org-region-active-p)
14900 org-loop-over-headlines-in-active-region)
14901 (org-back-to-heading t))
14902 (org-set-tags arg just-align))))
14904 (defun org-set-tags-to (data)
14905 "Set the tags of the current entry to DATA, replacing the current tags.
14906 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14907 If DATA is nil or the empty string, any tags will be removed."
14908 (interactive "sTags: ")
14909 (setq data
14910 (cond
14911 ((eq data nil) "")
14912 ((equal data "") "")
14913 ((stringp data)
14914 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14915 ":"))
14916 ((listp data)
14917 (concat ":" (mapconcat 'identity data ":") ":"))))
14918 (when data
14919 (save-excursion
14920 (org-back-to-heading t)
14921 (when (looking-at org-complex-heading-regexp)
14922 (if (match-end 5)
14923 (progn
14924 (goto-char (match-beginning 5))
14925 (insert data)
14926 (delete-region (point) (point-at-eol))
14927 (org-set-tags nil 'align))
14928 (goto-char (point-at-eol))
14929 (insert " " data)
14930 (org-set-tags nil 'align)))
14931 (beginning-of-line 1)
14932 (when (looking-at ".*?\\([ \t]+\\)$")
14933 (delete-region (match-beginning 1) (match-end 1))))))
14935 (defun org-align-all-tags ()
14936 "Align the tags in all headings."
14937 (interactive)
14938 (save-excursion
14939 (or (ignore-errors (org-back-to-heading t))
14940 (outline-next-heading))
14941 (if (org-at-heading-p)
14942 (org-set-tags t)
14943 (message "No headings"))))
14945 (defvar org-indent-indentation-per-level)
14946 (defun org-set-tags (&optional arg just-align)
14947 "Set the tags for the current headline.
14948 With prefix ARG, realign all tags in headings in the current buffer.
14949 When JUST-ALIGN is non-nil, only align tags."
14950 (interactive "P")
14951 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14952 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14953 'region-start-level
14954 'region))
14955 org-loop-over-headlines-in-active-region)
14956 (org-map-entries
14957 ;; We don't use ARG and JUST-ALIGN here because these args
14958 ;; are not useful when looping over headlines.
14959 #'org-set-tags
14960 org-loop-over-headlines-in-active-region
14962 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14963 (let ((org-setting-tags t))
14964 (if arg
14965 (save-excursion
14966 (goto-char (point-min))
14967 (while (re-search-forward org-outline-regexp-bol nil t)
14968 (org-set-tags nil t)
14969 (end-of-line))
14970 (message "All tags realigned to column %d" org-tags-column))
14971 (let* ((current (org-get-tags-string))
14972 (col (current-column))
14973 (tags
14974 (if just-align current
14975 ;; Get a new set of tags from the user.
14976 (save-excursion
14977 (let* ((seen)
14978 (table
14979 (setq
14980 org-last-tags-completion-table
14981 ;; Uniquify tags in alists, yet preserve
14982 ;; structure (i.e., keywords).
14983 (delq nil
14984 (mapcar
14985 (lambda (pair)
14986 (let ((head (car pair)))
14987 (cond ((symbolp head) pair)
14988 ((member head seen) nil)
14989 (t (push head seen)
14990 pair))))
14991 (append
14992 (or org-current-tag-alist
14993 (org-get-buffer-tags))
14994 (and
14995 org-complete-tags-always-offer-all-agenda-tags
14996 (org-global-tags-completion-table
14997 (org-agenda-files))))))))
14998 (current-tags (org-split-string current ":"))
14999 (inherited-tags
15000 (nreverse (nthcdr (length current-tags)
15001 (nreverse (org-get-tags-at))))))
15002 (replace-regexp-in-string
15003 "\\([-+&]+\\|,\\)"
15005 (if (or (eq t org-use-fast-tag-selection)
15006 (and org-use-fast-tag-selection
15007 (delq nil (mapcar #'cdr table))))
15008 (org-fast-tag-selection
15009 current-tags inherited-tags table
15010 (and org-fast-tag-selection-include-todo
15011 org-todo-key-alist))
15012 (let ((org-add-colon-after-tag-completion
15013 (< 1 (length table))))
15014 (org-trim
15015 (completing-read
15016 "Tags: "
15017 #'org-tags-completion-function
15018 nil nil current 'org-tags-history))))))))))
15020 (when org-tags-sort-function
15021 (setq tags
15022 (mapconcat
15023 #'identity
15024 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15025 org-tags-sort-function)
15026 ":")))
15028 (if (not (org-string-nw-p tags)) (setq tags "")
15029 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15030 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15032 ;; Insert new tags at the correct column
15033 (beginning-of-line)
15034 (let ((level (if (looking-at org-outline-regexp)
15035 (- (match-end 0) (point) 1)
15036 1)))
15037 (cond
15038 ((and (equal current "") (equal tags "")))
15039 ((re-search-forward
15040 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15041 (line-end-position)
15043 (if (equal tags "") (replace-match "" t t)
15044 (goto-char (match-beginning 0))
15045 (let* ((c0 (current-column))
15046 ;; Compute offset for the case of org-indent-mode
15047 ;; active.
15048 (di (if (bound-and-true-p org-indent-mode)
15049 (* (1- org-indent-indentation-per-level)
15050 (1- level))
15052 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15053 (tc (+ org-tags-column
15054 (if (> org-tags-column 0) (- di) di)))
15055 (c1 (max (1+ c0)
15056 (if (> tc 0) tc
15057 (- (- tc) (string-width tags)))))
15058 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15059 (replace-match rpl t t)
15060 (when indent-tabs-mode (tabify p0 (point))))))
15061 (t (error "Tags alignment failed"))))
15062 (org-move-to-column col))
15063 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15065 (defun org-change-tag-in-region (beg end tag off)
15066 "Add or remove TAG for each entry in the region.
15067 This works in the agenda, and also in an org-mode buffer."
15068 (interactive
15069 (list (region-beginning) (region-end)
15070 (let ((org-last-tags-completion-table
15071 (if (derived-mode-p 'org-mode)
15072 (org-uniquify
15073 (delq nil (append (org-get-buffer-tags)
15074 (org-global-tags-completion-table))))
15075 (org-global-tags-completion-table))))
15076 (completing-read
15077 "Tag: " 'org-tags-completion-function nil nil nil
15078 'org-tags-history))
15079 (progn
15080 (message "[s]et or [r]emove? ")
15081 (equal (read-char-exclusive) ?r))))
15082 (when (fboundp 'deactivate-mark) (deactivate-mark))
15083 (let ((agendap (equal major-mode 'org-agenda-mode))
15084 l1 l2 m buf pos newhead (cnt 0))
15085 (goto-char end)
15086 (setq l2 (1- (org-current-line)))
15087 (goto-char beg)
15088 (setq l1 (org-current-line))
15089 (cl-loop for l from l1 to l2 do
15090 (org-goto-line l)
15091 (setq m (get-text-property (point) 'org-hd-marker))
15092 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15093 (and agendap m))
15094 (setq buf (if agendap (marker-buffer m) (current-buffer))
15095 pos (if agendap m (point)))
15096 (with-current-buffer buf
15097 (save-excursion
15098 (save-restriction
15099 (goto-char pos)
15100 (setq cnt (1+ cnt))
15101 (org-toggle-tag tag (if off 'off 'on))
15102 (setq newhead (org-get-heading)))))
15103 (and agendap (org-agenda-change-all-lines newhead m))))
15104 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15106 (defun org-tags-completion-function (string _predicate &optional flag)
15107 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15108 (confirm (lambda (x) (stringp (car x)))))
15109 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15110 (setq s1 (match-string 1 string)
15111 s2 (match-string 2 string))
15112 (setq s1 "" s2 string))
15113 (cond
15114 ((eq flag nil)
15115 ;; try completion
15116 (setq rtn (try-completion s2 ctable confirm))
15117 (when (stringp rtn)
15118 (setq rtn
15119 (concat s1 s2 (substring rtn (length s2))
15120 (if (and org-add-colon-after-tag-completion
15121 (assoc rtn ctable))
15122 ":" ""))))
15123 rtn)
15124 ((eq flag t)
15125 ;; all-completions
15126 (all-completions s2 ctable confirm))
15127 ((eq flag 'lambda)
15128 ;; exact match?
15129 (assoc s2 ctable)))))
15131 (defun org-fast-tag-insert (kwd tags face &optional end)
15132 "Insert KDW, and the TAGS, the latter with face FACE.
15133 Also insert END."
15134 (insert (format "%-12s" (concat kwd ":"))
15135 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15136 (or end "")))
15138 (defun org-fast-tag-show-exit (flag)
15139 (save-excursion
15140 (org-goto-line 3)
15141 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15142 (replace-match ""))
15143 (when flag
15144 (end-of-line 1)
15145 (org-move-to-column (- (window-width) 19) t)
15146 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15148 (defun org-set-current-tags-overlay (current prefix)
15149 "Add an overlay to CURRENT tag with PREFIX."
15150 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15151 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15152 (org-overlay-display org-tags-overlay (concat prefix s))))
15154 (defvar org-last-tag-selection-key nil)
15155 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15156 "Fast tag selection with single keys.
15157 CURRENT is the current list of tags in the headline, INHERITED is the
15158 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15159 possibly with grouping information. TODO-TABLE is a similar table with
15160 TODO keywords, should these have keys assigned to them.
15161 If the keys are nil, a-z are automatically assigned.
15162 Returns the new tags string, or nil to not change the current settings."
15163 (let* ((fulltable (append table todo-table))
15164 (maxlen (apply 'max (mapcar
15165 (lambda (x)
15166 (if (stringp (car x)) (string-width (car x)) 0))
15167 fulltable)))
15168 (buf (current-buffer))
15169 (expert (eq org-fast-tag-selection-single-key 'expert))
15170 (buffer-tags nil)
15171 (fwidth (+ maxlen 3 1 3))
15172 (ncol (/ (- (window-width) 4) fwidth))
15173 (i-face 'org-done)
15174 (c-face 'org-todo)
15175 tg cnt e c char c1 c2 ntable tbl rtn
15176 ov-start ov-end ov-prefix
15177 (exit-after-next org-fast-tag-selection-single-key)
15178 (done-keywords org-done-keywords)
15179 groups ingroup intaggroup)
15180 (save-excursion
15181 (beginning-of-line 1)
15182 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15183 (setq ov-start (match-beginning 1)
15184 ov-end (match-end 1)
15185 ov-prefix "")
15186 (setq ov-start (1- (point-at-eol))
15187 ov-end (1+ ov-start))
15188 (skip-chars-forward "^\n\r")
15189 (setq ov-prefix
15190 (concat
15191 (buffer-substring (1- (point)) (point))
15192 (if (> (current-column) org-tags-column)
15194 (make-string (- org-tags-column (current-column)) ?\ ))))))
15195 (move-overlay org-tags-overlay ov-start ov-end)
15196 (save-window-excursion
15197 (if expert
15198 (set-buffer (get-buffer-create " *Org tags*"))
15199 (delete-other-windows)
15200 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15201 (org-switch-to-buffer-other-window " *Org tags*"))
15202 (erase-buffer)
15203 (setq-local org-done-keywords done-keywords)
15204 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15205 (org-fast-tag-insert "Current" current c-face "\n\n")
15206 (org-fast-tag-show-exit exit-after-next)
15207 (org-set-current-tags-overlay current ov-prefix)
15208 (setq tbl fulltable char ?a cnt 0)
15209 (while (setq e (pop tbl))
15210 (cond
15211 ((eq (car e) :startgroup)
15212 (push '() groups) (setq ingroup t)
15213 (unless (zerop cnt)
15214 (setq cnt 0)
15215 (insert "\n"))
15216 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15217 ((eq (car e) :endgroup)
15218 (setq ingroup nil cnt 0)
15219 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15220 ((eq (car e) :startgrouptag)
15221 (setq intaggroup t)
15222 (unless (zerop cnt)
15223 (setq cnt 0)
15224 (insert "\n"))
15225 (insert "[ "))
15226 ((eq (car e) :endgrouptag)
15227 (setq intaggroup nil cnt 0)
15228 (insert "]\n"))
15229 ((equal e '(:newline))
15230 (unless (zerop cnt)
15231 (setq cnt 0)
15232 (insert "\n")
15233 (setq e (car tbl))
15234 (while (equal (car tbl) '(:newline))
15235 (insert "\n")
15236 (setq tbl (cdr tbl)))))
15237 ((equal e '(:grouptags)) (insert " : "))
15239 (setq tg (copy-sequence (car e)) c2 nil)
15240 (if (cdr e)
15241 (setq c (cdr e))
15242 ;; automatically assign a character.
15243 (setq c1 (string-to-char
15244 (downcase (substring
15245 tg (if (= (string-to-char tg) ?@) 1 0)))))
15246 (if (or (rassoc c1 ntable) (rassoc c1 table))
15247 (while (or (rassoc char ntable) (rassoc char table))
15248 (setq char (1+ char)))
15249 (setq c2 c1))
15250 (setq c (or c2 char)))
15251 (when ingroup (push tg (car groups)))
15252 (setq tg (org-add-props tg nil 'face
15253 (cond
15254 ((not (assoc tg table))
15255 (org-get-todo-face tg))
15256 ((member tg current) c-face)
15257 ((member tg inherited) i-face))))
15258 (when (equal (caar tbl) :grouptags)
15259 (org-add-props tg nil 'face 'org-tag-group))
15260 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15261 (insert "[" c "] " tg (make-string
15262 (- fwidth 4 (length tg)) ?\ ))
15263 (push (cons tg c) ntable)
15264 (when (= (cl-incf cnt) ncol)
15265 (insert "\n")
15266 (when (or ingroup intaggroup) (insert " "))
15267 (setq cnt 0)))))
15268 (setq ntable (nreverse ntable))
15269 (insert "\n")
15270 (goto-char (point-min))
15271 (unless expert (org-fit-window-to-buffer))
15272 (setq rtn
15273 (catch 'exit
15274 (while t
15275 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15276 (if (not groups) "no " "")
15277 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15278 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15279 (setq org-last-tag-selection-key c)
15280 (cond
15281 ((= c ?\r) (throw 'exit t))
15282 ((= c ?!)
15283 (setq groups (not groups))
15284 (goto-char (point-min))
15285 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15286 ((= c ?\C-c)
15287 (if (not expert)
15288 (org-fast-tag-show-exit
15289 (setq exit-after-next (not exit-after-next)))
15290 (setq expert nil)
15291 (delete-other-windows)
15292 (set-window-buffer (split-window-vertically) " *Org tags*")
15293 (org-switch-to-buffer-other-window " *Org tags*")
15294 (org-fit-window-to-buffer)))
15295 ((or (= c ?\C-g)
15296 (and (= c ?q) (not (rassoc c ntable))))
15297 (delete-overlay org-tags-overlay)
15298 (setq quit-flag t))
15299 ((= c ?\ )
15300 (setq current nil)
15301 (when exit-after-next (setq exit-after-next 'now)))
15302 ((= c ?\t)
15303 (condition-case nil
15304 (setq tg (completing-read
15305 "Tag: "
15306 (or buffer-tags
15307 (with-current-buffer buf
15308 (setq buffer-tags
15309 (org-get-buffer-tags))))))
15310 (quit (setq tg "")))
15311 (when (string-match "\\S-" tg)
15312 (cl-pushnew (list tg) buffer-tags :test #'equal)
15313 (if (member tg current)
15314 (setq current (delete tg current))
15315 (push tg current)))
15316 (when exit-after-next (setq exit-after-next 'now)))
15317 ((setq e (rassoc c todo-table) tg (car e))
15318 (with-current-buffer buf
15319 (save-excursion (org-todo tg)))
15320 (when exit-after-next (setq exit-after-next 'now)))
15321 ((setq e (rassoc c ntable) tg (car e))
15322 (if (member tg current)
15323 (setq current (delete tg current))
15324 (cl-loop for g in groups do
15325 (when (member tg g)
15326 (dolist (x g) (setq current (delete x current)))))
15327 (push tg current))
15328 (when exit-after-next (setq exit-after-next 'now))))
15330 ;; Create a sorted list
15331 (setq current
15332 (sort current
15333 (lambda (a b)
15334 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15335 (when (eq exit-after-next 'now) (throw 'exit t))
15336 (goto-char (point-min))
15337 (beginning-of-line 2)
15338 (delete-region (point) (point-at-eol))
15339 (org-fast-tag-insert "Current" current c-face)
15340 (org-set-current-tags-overlay current ov-prefix)
15341 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15342 (setq tg (match-string 1))
15343 (add-text-properties
15344 (match-beginning 1) (match-end 1)
15345 (list 'face
15346 (cond
15347 ((member tg current) c-face)
15348 ((member tg inherited) i-face)
15349 (t (get-text-property (match-beginning 1) 'face))))))
15350 (goto-char (point-min)))))
15351 (delete-overlay org-tags-overlay)
15352 (if rtn
15353 (mapconcat 'identity current ":")
15354 nil))))
15356 (defun org-get-tags-string ()
15357 "Get the TAGS string in the current headline."
15358 (unless (org-at-heading-p t)
15359 (user-error "Not on a heading"))
15360 (save-excursion
15361 (beginning-of-line 1)
15362 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15363 (match-string-no-properties 1)
15364 "")))
15366 (defun org-get-tags ()
15367 "Get the list of tags specified in the current headline."
15368 (org-split-string (org-get-tags-string) ":"))
15370 (defun org-get-buffer-tags ()
15371 "Get a table of all tags used in the buffer, for completion."
15372 (org-with-wide-buffer
15373 (goto-char (point-min))
15374 (let ((tag-re (concat org-outline-regexp-bol
15375 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15376 tags)
15377 (while (re-search-forward tag-re nil t)
15378 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15379 (push tag tags)))
15380 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15382 ;;;; The mapping API
15384 (defvar org-agenda-skip-comment-trees)
15385 (defvar org-agenda-skip-function)
15386 (defun org-map-entries (func &optional match scope &rest skip)
15387 "Call FUNC at each headline selected by MATCH in SCOPE.
15389 FUNC is a function or a lisp form. The function will be called without
15390 arguments, with the cursor positioned at the beginning of the headline.
15391 The return values of all calls to the function will be collected and
15392 returned as a list.
15394 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15395 does not need to preserve point. After evaluation, the cursor will be
15396 moved to the end of the line (presumably of the headline of the
15397 processed entry) and search continues from there. Under some
15398 circumstances, this may not produce the wanted results. For example,
15399 if you have removed (e.g. archived) the current (sub)tree it could
15400 mean that the next entry will be skipped entirely. In such cases, you
15401 can specify the position from where search should continue by making
15402 FUNC set the variable `org-map-continue-from' to the desired buffer
15403 position.
15405 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15406 Only headlines that are matched by this query will be considered during
15407 the iteration. When MATCH is nil or t, all headlines will be
15408 visited by the iteration.
15410 SCOPE determines the scope of this command. It can be any of:
15412 nil The current buffer, respecting the restriction if any
15413 tree The subtree started with the entry at point
15414 region The entries within the active region, if any
15415 region-start-level
15416 The entries within the active region, but only those at
15417 the same level than the first one.
15418 file The current buffer, without restriction
15419 file-with-archives
15420 The current buffer, and any archives associated with it
15421 agenda All agenda files
15422 agenda-with-archives
15423 All agenda files with any archive files associated with them
15424 \(file1 file2 ...)
15425 If this is a list, all files in the list will be scanned
15427 The remaining args are treated as settings for the skipping facilities of
15428 the scanner. The following items can be given here:
15430 archive skip trees with the archive tag
15431 comment skip trees with the COMMENT keyword
15432 function or Emacs Lisp form:
15433 will be used as value for `org-agenda-skip-function', so
15434 whenever the function returns a position, FUNC will not be
15435 called for that entry and search will continue from the
15436 position returned
15438 If your function needs to retrieve the tags including inherited tags
15439 at the *current* entry, you can use the value of the variable
15440 `org-scanner-tags' which will be much faster than getting the value
15441 with `org-get-tags-at'. If your function gets properties with
15442 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15443 to t around the call to `org-entry-properties' to get the same speedup.
15444 Note that if your function moves around to retrieve tags and properties at
15445 a *different* entry, you cannot use these techniques."
15446 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15447 (not (org-region-active-p)))
15448 (let* ((org-agenda-archives-mode nil) ; just to make sure
15449 (org-agenda-skip-archived-trees (memq 'archive skip))
15450 (org-agenda-skip-comment-trees (memq 'comment skip))
15451 (org-agenda-skip-function
15452 (car (org-delete-all '(comment archive) skip)))
15453 (org-tags-match-list-sublevels t)
15454 (start-level (eq scope 'region-start-level))
15455 matcher res
15456 org-todo-keywords-for-agenda
15457 org-done-keywords-for-agenda
15458 org-todo-keyword-alist-for-agenda
15459 org-tag-alist-for-agenda
15460 org--matcher-tags-todo-only)
15462 (cond
15463 ((eq match t) (setq matcher t))
15464 ((eq match nil) (setq matcher t))
15465 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15467 (save-excursion
15468 (save-restriction
15469 (cond ((eq scope 'tree)
15470 (org-back-to-heading t)
15471 (org-narrow-to-subtree)
15472 (setq scope nil))
15473 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15474 (org-region-active-p))
15475 ;; If needed, set start-level to a string like "2"
15476 (when start-level
15477 (save-excursion
15478 (goto-char (region-beginning))
15479 (unless (org-at-heading-p) (outline-next-heading))
15480 (setq start-level (org-current-level))))
15481 (narrow-to-region (region-beginning)
15482 (save-excursion
15483 (goto-char (region-end))
15484 (unless (and (bolp) (org-at-heading-p))
15485 (outline-next-heading))
15486 (point)))
15487 (setq scope nil)))
15489 (if (not scope)
15490 (progn
15491 (org-agenda-prepare-buffers
15492 (and buffer-file-name (list buffer-file-name)))
15493 (setq res
15494 (org-scan-tags
15495 func matcher org--matcher-tags-todo-only start-level)))
15496 ;; Get the right scope
15497 (cond
15498 ((and scope (listp scope) (symbolp (car scope)))
15499 (setq scope (eval scope)))
15500 ((eq scope 'agenda)
15501 (setq scope (org-agenda-files t)))
15502 ((eq scope 'agenda-with-archives)
15503 (setq scope (org-agenda-files t))
15504 (setq scope (org-add-archive-files scope)))
15505 ((eq scope 'file)
15506 (setq scope (and buffer-file-name (list buffer-file-name))))
15507 ((eq scope 'file-with-archives)
15508 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15509 (org-agenda-prepare-buffers scope)
15510 (dolist (file scope)
15511 (with-current-buffer (org-find-base-buffer-visiting file)
15512 (save-excursion
15513 (save-restriction
15514 (widen)
15515 (goto-char (point-min))
15516 (setq res
15517 (append
15519 (org-scan-tags
15520 func matcher org--matcher-tags-todo-only))))))))))
15521 res)))
15523 ;;; Properties API
15525 (defconst org-special-properties
15526 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15527 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15528 "The special properties valid in Org mode.
15529 These are properties that are not defined in the property drawer,
15530 but in some other way.")
15532 (defconst org-default-properties
15533 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15534 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15535 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15536 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15537 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15538 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15539 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15540 "Some properties that are used by Org mode for various purposes.
15541 Being in this list makes sure that they are offered for completion.")
15543 (defun org--valid-property-p (property)
15544 "Non nil when string PROPERTY is a valid property name."
15545 (not
15546 (or (equal property "")
15547 (org-string-match-p "\\s-" property))))
15549 (defun org--update-property-plist (key val props)
15550 "Associate KEY to VAL in alist PROPS.
15551 Modifications are made by side-effect. Return new alist."
15552 (let* ((appending (string= (substring key -1) "+"))
15553 (key (if appending (substring key 0 -1) key))
15554 (old (assoc-string key props t)))
15555 (if (not old) (cons (cons key val) props)
15556 (setcdr old (if appending (concat (cdr old) " " val) val))
15557 props)))
15559 (defun org-get-property-block (&optional beg force)
15560 "Return the (beg . end) range of the body of the property drawer.
15561 BEG is the beginning of the current subtree, or of the part
15562 before the first headline. If it is not given, it will be found.
15563 If the drawer does not exist, create it if FORCE is non-nil, or
15564 return nil."
15565 (org-with-wide-buffer
15566 (when beg (goto-char beg))
15567 (unless (org-before-first-heading-p)
15568 (let ((beg (cond (beg)
15569 ((or (not (featurep 'org-inlinetask))
15570 (org-inlinetask-in-task-p))
15571 (org-back-to-heading t))
15572 (t (org-with-limited-levels (org-back-to-heading t))))))
15573 (forward-line)
15574 (when (looking-at-p org-planning-line-re) (forward-line))
15575 (cond ((looking-at org-property-drawer-re)
15576 (forward-line)
15577 (cons (point) (progn (goto-char (match-end 0))
15578 (line-beginning-position))))
15579 (force
15580 (goto-char beg)
15581 (org-insert-property-drawer)
15582 (let ((pos (save-excursion (search-forward ":END:")
15583 (line-beginning-position))))
15584 (cons pos pos))))))))
15586 (defun org-at-property-p ()
15587 "Non-nil when point is inside a property drawer.
15588 See `org-property-re' for match data, if applicable."
15589 (save-excursion
15590 (beginning-of-line)
15591 (and (looking-at org-property-re)
15592 (let ((property-drawer (save-match-data (org-get-property-block))))
15593 (and property-drawer
15594 (>= (point) (car property-drawer))
15595 (< (point) (cdr property-drawer)))))))
15597 (defun org-property-action ()
15598 "Do an action on properties."
15599 (interactive)
15600 (unless (org-at-property-p) (user-error "Not at a property"))
15601 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15602 (let ((c (read-char-exclusive)))
15603 (cl-case c
15604 (?s (call-interactively #'org-set-property))
15605 (?d (call-interactively #'org-delete-property))
15606 (?D (call-interactively #'org-delete-property-globally))
15607 (?c (call-interactively #'org-compute-property-at-point))
15608 (otherwise (user-error "No such property action %c" c)))))
15610 (defun org-inc-effort ()
15611 "Increment the value of the effort property in the current entry."
15612 (interactive)
15613 (org-set-effort nil t))
15615 (defvar org-clock-effort) ; Defined in org-clock.el.
15616 (defvar org-clock-current-task) ; Defined in org-clock.el.
15617 (defun org-set-effort (&optional value increment)
15618 "Set the effort property of the current entry.
15619 With numerical prefix arg, use the nth allowed value, 0 stands for the
15620 10th allowed value.
15622 When INCREMENT is non-nil, set the property to the next allowed value."
15623 (interactive "P")
15624 (when (equal value 0) (setq value 10))
15625 (let* ((completion-ignore-case t)
15626 (prop org-effort-property)
15627 (cur (org-entry-get nil prop))
15628 (allowed (org-property-get-allowed-values nil prop 'table))
15629 (existing (mapcar 'list (org-property-values prop)))
15630 (heading (nth 4 (org-heading-components)))
15632 (val (cond
15633 ((stringp value) value)
15634 ((and allowed (integerp value))
15635 (or (car (nth (1- value) allowed))
15636 (car (org-last allowed))))
15637 ((and allowed increment)
15638 (or (cl-caadr (member (list cur) allowed))
15639 (user-error "Allowed effort values are not set")))
15640 (allowed
15641 (message "Select 1-9,0, [RET%s]: %s"
15642 (if cur (concat "=" cur) "")
15643 (mapconcat 'car allowed " "))
15644 (setq rpl (read-char-exclusive))
15645 (if (equal rpl ?\r)
15647 (setq rpl (- rpl ?0))
15648 (when (equal rpl 0) (setq rpl 10))
15649 (if (and (> rpl 0) (<= rpl (length allowed)))
15650 (car (nth (1- rpl) allowed))
15651 (org-completing-read "Effort: " allowed nil))))
15653 (org-completing-read
15654 (concat "Effort" (and cur (string-match "\\S-" cur)
15655 (concat " [" cur "]"))
15656 ": ")
15657 existing nil nil "" nil cur)))))
15658 (unless (equal (org-entry-get nil prop) val)
15659 (org-entry-put nil prop val))
15660 (org-refresh-property
15661 '((effort . identity)
15662 (effort-minutes . org-duration-string-to-minutes))
15663 val)
15664 (when (equal heading (bound-and-true-p org-clock-current-task))
15665 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15666 (org-clock-update-mode-line))
15667 (message "%s is now %s" prop val)))
15669 (defun org-entry-properties (&optional pom which)
15670 "Get all properties of the current entry.
15672 When POM is a buffer position, get all properties from the entry
15673 there instead.
15675 This includes the TODO keyword, the tags, time strings for
15676 deadline, scheduled, and clocking, and any additional properties
15677 defined in the entry.
15679 If WHICH is nil or `all', get all properties. If WHICH is
15680 `special' or `standard', only get that subclass. If WHICH is
15681 a string, only get that property.
15683 Return value is an alist. Keys are properties, as upcased
15684 strings."
15685 (org-with-point-at pom
15686 (when (and (derived-mode-p 'org-mode)
15687 (ignore-errors (org-back-to-heading t)))
15688 (catch 'exit
15689 (let* ((beg (point))
15690 (specific (and (stringp which) (upcase which)))
15691 (which (cond ((not specific) which)
15692 ((member specific org-special-properties) 'special)
15693 (t 'standard)))
15694 props)
15695 ;; Get the special properties, like TODO and TAGS.
15696 (when (memq which '(nil all special))
15697 (when (or (not specific) (string= specific "CLOCKSUM"))
15698 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15699 (when clocksum
15700 (push (cons "CLOCKSUM"
15701 (org-minutes-to-clocksum-string clocksum))
15702 props)))
15703 (when specific (throw 'exit props)))
15704 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15705 (let ((clocksumt (get-text-property (point)
15706 :org-clock-minutes-today)))
15707 (when clocksumt
15708 (push (cons "CLOCKSUM_T"
15709 (org-minutes-to-clocksum-string clocksumt))
15710 props)))
15711 (when specific (throw 'exit props)))
15712 (when (or (not specific) (string= specific "ITEM"))
15713 (when (looking-at org-complex-heading-regexp)
15714 (push (cons "ITEM"
15715 (let ((title (match-string-no-properties 4)))
15716 (if (org-string-nw-p title)
15717 (org-remove-tabs title)
15718 "")))
15719 props))
15720 (when specific (throw 'exit props)))
15721 (when (or (not specific) (string= specific "TODO"))
15722 (let ((case-fold-search nil))
15723 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15724 (push (cons "TODO" (match-string-no-properties 2)) props)))
15725 (when specific (throw 'exit props)))
15726 (when (or (not specific) (string= specific "PRIORITY"))
15727 (push (cons "PRIORITY"
15728 (if (looking-at org-priority-regexp)
15729 (match-string-no-properties 2)
15730 (char-to-string org-default-priority)))
15731 props)
15732 (when specific (throw 'exit props)))
15733 (when (or (not specific) (string= specific "FILE"))
15734 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15735 props)
15736 (when specific (throw 'exit props)))
15737 (when (or (not specific) (string= specific "TAGS"))
15738 (let ((value (org-string-nw-p (org-get-tags-string))))
15739 (when value (push (cons "TAGS" value) props)))
15740 (when specific (throw 'exit props)))
15741 (when (or (not specific) (string= specific "ALLTAGS"))
15742 (let ((value (org-get-tags-at)))
15743 (when value
15744 (push (cons "ALLTAGS"
15745 (format ":%s:" (mapconcat #'identity value ":")))
15746 props)))
15747 (when specific (throw 'exit props)))
15748 (when (or (not specific) (string= specific "BLOCKED"))
15749 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15750 (when specific (throw 'exit props)))
15751 (when (or (not specific)
15752 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15753 (forward-line)
15754 (when (looking-at-p org-planning-line-re)
15755 (end-of-line)
15756 (let ((bol (line-beginning-position))
15757 ;; Backward compatibility: time keywords used to
15758 ;; be configurable (before 8.3). Make sure we
15759 ;; get the correct keyword.
15760 (key-assoc `(("CLOSED" . ,org-closed-string)
15761 ("DEADLINE" . ,org-deadline-string)
15762 ("SCHEDULED" . ,org-scheduled-string))))
15763 (dolist (pair (if specific (list (assoc specific key-assoc))
15764 key-assoc))
15765 (save-excursion
15766 (when (search-backward (cdr pair) bol t)
15767 (goto-char (match-end 0))
15768 (skip-chars-forward " \t")
15769 (and (looking-at org-ts-regexp-both)
15770 (push (cons (car pair)
15771 (match-string-no-properties 0))
15772 props)))))))
15773 (when specific (throw 'exit props)))
15774 (when (or (not specific)
15775 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15776 (let ((find-ts
15777 (lambda (end ts)
15778 ;; Fix next time-stamp before END. TS is the
15779 ;; list of time-stamps found so far.
15780 (let ((ts ts)
15781 (regexp (cond
15782 ((string= specific "TIMESTAMP")
15783 org-ts-regexp)
15784 ((string= specific "TIMESTAMP_IA")
15785 org-ts-regexp-inactive)
15786 ((assoc "TIMESTAMP_IA" ts)
15787 org-ts-regexp)
15788 ((assoc "TIMESTAMP" ts)
15789 org-ts-regexp-inactive)
15790 (t org-ts-regexp-both))))
15791 (catch 'next
15792 (while (re-search-forward regexp end t)
15793 (backward-char)
15794 (let ((object (org-element-context)))
15795 ;; Accept to match timestamps in node
15796 ;; properties, too.
15797 (when (memq (org-element-type object)
15798 '(node-property timestamp))
15799 (let ((type
15800 (org-element-property :type object)))
15801 (cond
15802 ((and (memq type '(active active-range))
15803 (not (equal specific "TIMESTAMP_IA")))
15804 (unless (assoc "TIMESTAMP" ts)
15805 (push (cons "TIMESTAMP"
15806 (org-element-property
15807 :raw-value object))
15809 (when specific (throw 'exit ts))))
15810 ((and (memq type '(inactive inactive-range))
15811 (not (string= specific "TIMESTAMP")))
15812 (unless (assoc "TIMESTAMP_IA" ts)
15813 (push (cons "TIMESTAMP_IA"
15814 (org-element-property
15815 :raw-value object))
15817 (when specific (throw 'exit ts))))))
15818 ;; Both timestamp types are found,
15819 ;; move to next part.
15820 (when (= (length ts) 2) (throw 'next ts)))))
15821 ts)))))
15822 (goto-char beg)
15823 ;; First look for timestamps within headline.
15824 (let ((ts (funcall find-ts (line-end-position) nil)))
15825 (if (= (length ts) 2) (setq props (nconc ts props))
15826 (forward-line)
15827 ;; Then find timestamps in the section, skipping
15828 ;; planning line.
15829 (when (looking-at-p org-planning-line-re)
15830 (forward-line))
15831 (let ((end (save-excursion (outline-next-heading))))
15832 (setq props (nconc (funcall find-ts end ts) props))))))))
15833 ;; Get the standard properties, like :PROP:.
15834 (when (memq which '(nil all standard))
15835 ;; If we are looking after a specific property, delegate
15836 ;; to `org-entry-get', which is faster. However, make an
15837 ;; exception for "CATEGORY", since it can be also set
15838 ;; through keywords (i.e. #+CATEGORY).
15839 (if (and specific (not (equal specific "CATEGORY")))
15840 (let ((value (org-entry-get beg specific nil t)))
15841 (throw 'exit (and value (list (cons specific value)))))
15842 (let ((range (org-get-property-block beg)))
15843 (when range
15844 (let ((end (cdr range)) seen-base)
15845 (goto-char (car range))
15846 ;; Unlike to `org--update-property-plist', we
15847 ;; handle the case where base values is found
15848 ;; after its extension. We also forbid standard
15849 ;; properties to be named as special properties.
15850 (while (re-search-forward org-property-re end t)
15851 (let* ((key (upcase (match-string-no-properties 2)))
15852 (extendp (org-string-match-p "\\+\\'" key))
15853 (key-base (if extendp (substring key 0 -1) key))
15854 (value (match-string-no-properties 3)))
15855 (cond
15856 ((member-ignore-case key-base org-special-properties))
15857 (extendp
15858 (setq props
15859 (org--update-property-plist key value props)))
15860 ((member key seen-base))
15861 (t (push key seen-base)
15862 (let ((p (assoc-string key props t)))
15863 (if p (setcdr p (concat value " " (cdr p)))
15864 (push (cons key value) props))))))))))))
15865 (unless (assoc "CATEGORY" props)
15866 (push (cons "CATEGORY" (org-get-category beg)) props)
15867 (when (string= specific "CATEGORY") (throw 'exit props)))
15868 ;; Return value.
15869 props)))))
15871 (defun org-property--local-values (property literal-nil)
15872 "Return value for PROPERTY in current entry.
15873 Value is a list whose car is the base value for PROPERTY and cdr
15874 a list of accumulated values. Return nil if neither is found in
15875 the entry. Also return nil when PROPERTY is set to \"nil\",
15876 unless LITERAL-NIL is non-nil."
15877 (let ((range (org-get-property-block)))
15878 (when range
15879 (goto-char (car range))
15880 (let* ((case-fold-search t)
15881 (end (cdr range))
15882 (value
15883 ;; Base value.
15884 (save-excursion
15885 (let ((v (and (re-search-forward
15886 (org-re-property property nil t) end t)
15887 (match-string-no-properties 3))))
15888 (list (if literal-nil v (org-not-nil v)))))))
15889 ;; Find additional values.
15890 (let* ((property+ (org-re-property (concat property "+") nil t)))
15891 (while (re-search-forward property+ end t)
15892 (push (match-string-no-properties 3) value)))
15893 ;; Return final values.
15894 (and (not (equal value '(nil))) (nreverse value))))))
15896 (defun org-entry-get (pom property &optional inherit literal-nil)
15897 "Get value of PROPERTY for entry or content at point-or-marker POM.
15899 If INHERIT is non-nil and the entry does not have the property,
15900 then also check higher levels of the hierarchy. If INHERIT is
15901 the symbol `selective', use inheritance only if the setting in
15902 `org-use-property-inheritance' selects PROPERTY for inheritance.
15904 If the property is present but empty, the return value is the
15905 empty string. If the property is not present at all, nil is
15906 returned. In any other case, return the value as a string.
15907 Search is case-insensitive.
15909 If LITERAL-NIL is set, return the string value \"nil\" as
15910 a string, do not interpret it as the list atom nil. This is used
15911 for inheritance when a \"nil\" value can supersede a non-nil
15912 value higher up the hierarchy."
15913 (org-with-point-at pom
15914 (cond
15915 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15916 ;; We need a special property. Use `org-entry-properties' to
15917 ;; retrieve it, but specify the wanted property.
15918 (cdr (assoc-string property (org-entry-properties nil property))))
15919 ((and inherit
15920 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15921 (org-entry-get-with-inheritance property literal-nil))
15923 (let* ((local (org-property--local-values property literal-nil))
15924 (value (and local (mapconcat #'identity (delq nil local) " "))))
15925 (if literal-nil value (org-not-nil value)))))))
15927 (defun org-property-or-variable-value (var &optional inherit)
15928 "Check if there is a property fixing the value of VAR.
15929 If yes, return this value. If not, return the current value of the variable."
15930 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15931 (if (and prop (stringp prop) (string-match "\\S-" prop))
15932 (read prop)
15933 (symbol-value var))))
15935 (defun org-entry-delete (pom property)
15936 "Delete PROPERTY from entry at point-or-marker POM.
15937 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15938 non-nil when a property was removed."
15939 (unless (member property org-special-properties)
15940 (org-with-point-at pom
15941 (let ((range (org-get-property-block)))
15942 (when range
15943 (let* ((begin (car range))
15944 (origin (cdr range))
15945 (end (copy-marker origin))
15946 (re (org-re-property
15947 (concat (regexp-quote property) "\\+?") t t)))
15948 (goto-char begin)
15949 (while (re-search-forward re end t)
15950 (delete-region (match-beginning 0) (line-beginning-position 2)))
15951 ;; If drawer is empty, remove it altogether.
15952 (when (= begin end)
15953 (delete-region (line-beginning-position 0)
15954 (line-beginning-position 2)))
15955 ;; Return non-nil if some property was removed.
15956 (prog1 (/= end origin) (set-marker end nil))))))))
15958 ;; Multi-values properties are properties that contain multiple values
15959 ;; These values are assumed to be single words, separated by whitespace.
15960 (defun org-entry-add-to-multivalued-property (pom property value)
15961 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15962 (let* ((old (org-entry-get pom property))
15963 (values (and old (org-split-string old "[ \t]"))))
15964 (setq value (org-entry-protect-space value))
15965 (unless (member value values)
15966 (setq values (append values (list value)))
15967 (org-entry-put pom property
15968 (mapconcat 'identity values " ")))))
15970 (defun org-entry-remove-from-multivalued-property (pom property value)
15971 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15972 (let* ((old (org-entry-get pom property))
15973 (values (and old (org-split-string old "[ \t]"))))
15974 (setq value (org-entry-protect-space value))
15975 (when (member value values)
15976 (setq values (delete value values))
15977 (org-entry-put pom property
15978 (mapconcat 'identity values " ")))))
15980 (defun org-entry-member-in-multivalued-property (pom property value)
15981 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15982 (let* ((old (org-entry-get pom property))
15983 (values (and old (org-split-string old "[ \t]"))))
15984 (setq value (org-entry-protect-space value))
15985 (member value values)))
15987 (defun org-entry-get-multivalued-property (pom property)
15988 "Return a list of values in a multivalued property."
15989 (let* ((value (org-entry-get pom property))
15990 (values (and value (org-split-string value "[ \t]"))))
15991 (mapcar 'org-entry-restore-space values)))
15993 (defun org-entry-put-multivalued-property (pom property &rest values)
15994 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15995 VALUES should be a list of strings. Spaces will be protected."
15996 (org-entry-put pom property
15997 (mapconcat 'org-entry-protect-space values " "))
15998 (let* ((value (org-entry-get pom property))
15999 (values (and value (org-split-string value "[ \t]"))))
16000 (mapcar 'org-entry-restore-space values)))
16002 (defun org-entry-protect-space (s)
16003 "Protect spaces and newline in string S."
16004 (while (string-match " " s)
16005 (setq s (replace-match "%20" t t s)))
16006 (while (string-match "\n" s)
16007 (setq s (replace-match "%0A" t t s)))
16010 (defun org-entry-restore-space (s)
16011 "Restore spaces and newline in string S."
16012 (while (string-match "%20" s)
16013 (setq s (replace-match " " t t s)))
16014 (while (string-match "%0A" s)
16015 (setq s (replace-match "\n" t t s)))
16018 (defvar org-entry-property-inherited-from (make-marker)
16019 "Marker pointing to the entry from where a property was inherited.
16020 Each call to `org-entry-get-with-inheritance' will set this marker to the
16021 location of the entry where the inheritance search matched. If there was
16022 no match, the marker will point nowhere.
16023 Note that also `org-entry-get' calls this function, if the INHERIT flag
16024 is set.")
16026 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16027 "Get PROPERTY of entry or content at point, search higher levels if needed.
16028 The search will stop at the first ancestor which has the property defined.
16029 If the value found is \"nil\", return nil to show that the property
16030 should be considered as undefined (this is the meaning of nil here).
16031 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16032 (move-marker org-entry-property-inherited-from nil)
16033 (org-with-wide-buffer
16034 (let (value)
16035 (catch 'exit
16036 (while t
16037 (let ((v (org-property--local-values property literal-nil)))
16038 (when v
16039 (setq value
16040 (concat (mapconcat #'identity (delq nil v) " ")
16041 (and value " ")
16042 value)))
16043 (cond
16044 ((car v)
16045 (org-back-to-heading t)
16046 (move-marker org-entry-property-inherited-from (point))
16047 (throw 'exit nil))
16048 ((org-up-heading-safe))
16050 (let ((global
16051 (cdr (or (assoc-string property org-file-properties t)
16052 (assoc-string property org-global-properties t)
16053 (assoc-string property org-global-properties-fixed t)))))
16054 (cond ((not global))
16055 (value (setq value (concat global " " value)))
16056 (t (setq value global))))
16057 (throw 'exit nil))))))
16058 (if literal-nil value (org-not-nil value)))))
16060 (defvar org-property-changed-functions nil
16061 "Hook called when the value of a property has changed.
16062 Each hook function should accept two arguments, the name of the property
16063 and the new value.")
16065 (defun org-entry-put (pom property value)
16066 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16068 If the value is nil, it is converted to the empty string. If it
16069 is not a string, an error is raised. Also raise an error on
16070 invalid property names.
16072 PROPERTY can be any regular property (see
16073 `org-special-properties'). It can also be \"TODO\",
16074 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16076 For the last two properties, VALUE may have any of the special
16077 values \"earlier\" and \"later\". The function then increases or
16078 decreases scheduled or deadline date by one day."
16079 (cond ((null value) (setq value ""))
16080 ((not (stringp value)) (error "Properties values should be strings"))
16081 ((not (org--valid-property-p property))
16082 (user-error "Invalid property name: \"%s\"" property)))
16083 (org-with-point-at pom
16084 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16085 (org-back-to-heading t)
16086 (org-with-limited-levels (org-back-to-heading t)))
16087 (let ((beg (point)))
16088 (cond
16089 ((equal property "TODO")
16090 (cond ((not (org-string-nw-p value)) (setq value 'none))
16091 ((not (member value org-todo-keywords-1))
16092 (user-error "\"%s\" is not a valid TODO state" value)))
16093 (org-todo value)
16094 (org-set-tags nil 'align))
16095 ((equal property "PRIORITY")
16096 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16097 (org-set-tags nil 'align))
16098 ((equal property "SCHEDULED")
16099 (forward-line)
16100 (if (and (looking-at-p org-planning-line-re)
16101 (re-search-forward
16102 org-scheduled-time-regexp (line-end-position) t))
16103 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16104 ((string= value "later") (org-timestamp-change 1 'day))
16105 ((string= value "") (org-schedule '(4)))
16106 (t (org-schedule nil value)))
16107 (if (member value '("earlier" "later" ""))
16108 (call-interactively #'org-schedule)
16109 (org-schedule nil value))))
16110 ((equal property "DEADLINE")
16111 (forward-line)
16112 (if (and (looking-at-p org-planning-line-re)
16113 (re-search-forward
16114 org-deadline-time-regexp (line-end-position) t))
16115 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16116 ((string= value "later") (org-timestamp-change 1 'day))
16117 ((string= value "") (org-deadline '(4)))
16118 (t (org-deadline nil value)))
16119 (if (member value '("earlier" "later" ""))
16120 (call-interactively #'org-deadline)
16121 (org-deadline nil value))))
16122 ((member property org-special-properties)
16123 (error "The %s property cannot be set with `org-entry-put'" property))
16125 (let* ((range (org-get-property-block beg 'force))
16126 (end (cdr range))
16127 (case-fold-search t))
16128 (goto-char (car range))
16129 (if (re-search-forward (org-re-property property nil t) end t)
16130 (progn (delete-region (match-beginning 0) (match-end 0))
16131 (goto-char (match-beginning 0)))
16132 (goto-char end)
16133 (insert "\n")
16134 (backward-char))
16135 (insert ":" property ":")
16136 (when value (insert " " value))
16137 (org-indent-line)))))
16138 (run-hook-with-args 'org-property-changed-functions property value)))
16140 (defun org-buffer-property-keys
16141 (&optional specials defaults columns ignore-malformed)
16142 "Get all property keys in the current buffer.
16144 When SPECIALS is non-nil, also list the special properties that
16145 reflect things like tags and TODO state.
16147 When DEFAULTS is non-nil, also include properties that has
16148 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16149 DESCRIPTION, LOCATION, and LOGGING and others.
16151 When COLUMNS in non-nil, also include property names given in
16152 COLUMN formats in the current buffer.
16154 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16155 automatically performed, such drawers will be silently ignored."
16156 (let ((case-fold-search t)
16157 (props (append
16158 (and specials org-special-properties)
16159 (and defaults (cons org-effort-property org-default-properties))
16160 nil)))
16161 (org-with-wide-buffer
16162 (goto-char (point-min))
16163 (while (re-search-forward org-property-start-re nil t)
16164 (let ((range (org-get-property-block)))
16165 (catch 'skip
16166 (unless range
16167 (when (and (not ignore-malformed)
16168 (not (org-before-first-heading-p))
16169 (y-or-n-p (format "Malformed drawer at %d, repair?"
16170 (line-beginning-position))))
16171 (org-get-property-block nil t))
16172 (throw 'skip nil))
16173 (goto-char (car range))
16174 (let ((begin (car range))
16175 (end (cdr range)))
16176 ;; Make sure that found property block is not located
16177 ;; before current point, as it would generate an infloop.
16178 ;; It can happen, for example, in the following
16179 ;; situation:
16181 ;; * Headline
16182 ;; :PROPERTIES:
16183 ;; ...
16184 ;; :END:
16185 ;; *************** Inlinetask
16186 ;; #+BEGIN_EXAMPLE
16187 ;; :PROPERTIES:
16188 ;; #+END_EXAMPLE
16190 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16191 (while (< (point) end)
16192 (let ((p (progn (looking-at org-property-re)
16193 (match-string-no-properties 2))))
16194 ;; Only add true property name, not extension symbol.
16195 (push (if (not (org-string-match-p "\\+\\'" p)) p
16196 (substring p 0 -1))
16197 props))
16198 (forward-line))))
16199 (outline-next-heading)))
16200 (when columns
16201 (goto-char (point-min))
16202 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16203 (let ((element (org-element-at-point)))
16204 (when (memq (org-element-type element) '(keyword node-property))
16205 (let ((value (org-element-property :value element))
16206 (start 0))
16207 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16208 (setq start (match-end 0))
16209 (let ((p (match-string-no-properties 1 value)))
16210 (unless (member-ignore-case p org-special-properties)
16211 (push p props))))))))))
16212 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16214 (defun org-property-values (key)
16215 "List all non-nil values of property KEY in current buffer."
16216 (org-with-wide-buffer
16217 (goto-char (point-min))
16218 (let ((case-fold-search t)
16219 (re (org-re-property key))
16220 values)
16221 (while (re-search-forward re nil t)
16222 (push (org-entry-get (point) key) values))
16223 (delete-dups values))))
16225 (defun org-insert-property-drawer ()
16226 "Insert a property drawer into the current entry."
16227 (org-with-wide-buffer
16228 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16229 (org-back-to-heading t)
16230 (org-with-limited-levels (org-back-to-heading t)))
16231 (forward-line)
16232 (when (looking-at-p org-planning-line-re) (forward-line))
16233 (unless (looking-at-p org-property-drawer-re)
16234 ;; Make sure we start editing a line from current entry, not from
16235 ;; next one. It prevents extending text properties or overlays
16236 ;; belonging to the latter.
16237 (when (bolp) (backward-char))
16238 (let ((begin (1+ (point)))
16239 (inhibit-read-only t))
16240 (insert "\n:PROPERTIES:\n:END:")
16241 (when (eobp) (insert "\n"))
16242 (org-indent-region begin (point))))))
16244 (defun org-insert-drawer (&optional arg drawer)
16245 "Insert a drawer at point.
16247 When optional argument ARG is non-nil, insert a property drawer.
16249 Optional argument DRAWER, when non-nil, is a string representing
16250 drawer's name. Otherwise, the user is prompted for a name.
16252 If a region is active, insert the drawer around that region
16253 instead.
16255 Point is left between drawer's boundaries."
16256 (interactive "P")
16257 (let* ((drawer (if arg "PROPERTIES"
16258 (or drawer (read-from-minibuffer "Drawer: ")))))
16259 (cond
16260 ;; With C-u, fall back on `org-insert-property-drawer'
16261 (arg (org-insert-property-drawer))
16262 ;; Check validity of suggested drawer's name.
16263 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16264 (user-error "Invalid drawer name"))
16265 ;; With an active region, insert a drawer at point.
16266 ((not (org-region-active-p))
16267 (progn
16268 (unless (bolp) (insert "\n"))
16269 (insert (format ":%s:\n\n:END:\n" drawer))
16270 (forward-line -2)))
16271 ;; Otherwise, insert the drawer at point
16273 (let ((rbeg (region-beginning))
16274 (rend (copy-marker (region-end))))
16275 (unwind-protect
16276 (progn
16277 (goto-char rbeg)
16278 (beginning-of-line)
16279 (when (save-excursion
16280 (re-search-forward org-outline-regexp-bol rend t))
16281 (user-error "Drawers cannot contain headlines"))
16282 ;; Position point at the beginning of the first
16283 ;; non-blank line in region. Insert drawer's opening
16284 ;; there, then indent it.
16285 (org-skip-whitespace)
16286 (beginning-of-line)
16287 (insert ":" drawer ":\n")
16288 (forward-line -1)
16289 (indent-for-tab-command)
16290 ;; Move point to the beginning of the first blank line
16291 ;; after the last non-blank line in region. Insert
16292 ;; drawer's closing, then indent it.
16293 (goto-char rend)
16294 (skip-chars-backward " \r\t\n")
16295 (insert "\n:END:")
16296 (deactivate-mark t)
16297 (indent-for-tab-command)
16298 (unless (eolp) (insert "\n")))
16299 ;; Clear marker, whatever the outcome of insertion is.
16300 (set-marker rend nil)))))))
16302 (defvar org-property-set-functions-alist nil
16303 "Property set function alist.
16304 Each entry should have the following format:
16306 (PROPERTY . READ-FUNCTION)
16308 The read function will be called with the same argument as
16309 `org-completing-read'.")
16311 (defun org-set-property-function (property)
16312 "Get the function that should be used to set PROPERTY.
16313 This is computed according to `org-property-set-functions-alist'."
16314 (or (cdr (assoc property org-property-set-functions-alist))
16315 'org-completing-read))
16317 (defun org-read-property-value (property)
16318 "Read PROPERTY value from user."
16319 (let* ((completion-ignore-case t)
16320 (allowed (org-property-get-allowed-values nil property 'table))
16321 (cur (org-entry-get nil property))
16322 (prompt (concat property " value"
16323 (if (and cur (string-match "\\S-" cur))
16324 (concat " [" cur "]") "") ": "))
16325 (set-function (org-set-property-function property))
16326 (val (if allowed
16327 (funcall set-function prompt allowed nil
16328 (not (get-text-property 0 'org-unrestricted
16329 (caar allowed))))
16330 (funcall set-function prompt
16331 (mapcar 'list (org-property-values property))
16332 nil nil "" nil cur))))
16333 (org-trim val)))
16335 (defvar org-last-set-property nil)
16336 (defvar org-last-set-property-value nil)
16337 (defun org-read-property-name ()
16338 "Read a property name."
16339 (let ((completion-ignore-case t)
16340 (default-prop (or (and (org-at-property-p)
16341 (match-string-no-properties 2))
16342 org-last-set-property)))
16343 (org-completing-read
16344 (concat "Property"
16345 (if default-prop (concat " [" default-prop "]") "")
16346 ": ")
16347 (mapcar #'list (org-buffer-property-keys nil t t))
16348 nil nil nil nil default-prop)))
16350 (defun org-set-property-and-value (use-last)
16351 "Allow to set [PROPERTY]: [value] direction from prompt.
16352 When use-default, don't even ask, just use the last
16353 \"[PROPERTY]: [value]\" string from the history."
16354 (interactive "P")
16355 (let* ((completion-ignore-case t)
16356 (pv (or (and use-last org-last-set-property-value)
16357 (org-completing-read
16358 "Enter a \"[Property]: [value]\" pair: "
16359 nil nil nil nil nil
16360 org-last-set-property-value)))
16361 prop val)
16362 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16363 (setq prop (match-string 1 pv)
16364 val (match-string 2 pv))
16365 (org-set-property prop val))))
16367 (defun org-set-property (property value)
16368 "In the current entry, set PROPERTY to VALUE.
16370 When called interactively, this will prompt for a property name, offering
16371 completion on existing and default properties. And then it will prompt
16372 for a value, offering completion either on allowed values (via an inherited
16373 xxx_ALL property) or on existing values in other instances of this property
16374 in the current file.
16376 Throw an error when trying to set a property with an invalid name."
16377 (interactive (list nil nil))
16378 (let ((property (or property (org-read-property-name))))
16379 ;; `org-entry-put' also makes the following check, but this one
16380 ;; avoids polluting `org-last-set-property' and
16381 ;; `org-last-set-property-value' needlessly.
16382 (unless (org--valid-property-p property)
16383 (user-error "Invalid property name: \"%s\"" property))
16384 (let ((value (or value (org-read-property-value property)))
16385 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16386 (setq org-last-set-property property)
16387 (setq org-last-set-property-value (concat property ": " value))
16388 ;; Possibly postprocess the inserted value:
16389 (when fn (setq value (funcall fn value)))
16390 (unless (equal (org-entry-get nil property) value)
16391 (org-entry-put nil property value)))))
16393 (defun org-find-property (property &optional value)
16394 "Find first entry in buffer that sets PROPERTY.
16396 When optional argument VALUE is non-nil, only consider an entry
16397 if it contains PROPERTY set to this value. If PROPERTY should be
16398 explicitly set to nil, use string \"nil\" for VALUE.
16400 Return position where the entry begins, or nil if there is no
16401 such entry. If narrowing is in effect, only search the visible
16402 part of the buffer."
16403 (save-excursion
16404 (goto-char (point-min))
16405 (let ((case-fold-search t)
16406 (re (org-re-property property nil (not value) value)))
16407 (catch 'exit
16408 (while (re-search-forward re nil t)
16409 (when (if value (org-at-property-p)
16410 (org-entry-get (point) property nil t))
16411 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16413 (defun org-delete-property (property)
16414 "In the current entry, delete PROPERTY."
16415 (interactive
16416 (let* ((completion-ignore-case t)
16417 (cat (org-entry-get (point) "CATEGORY"))
16418 (props0 (org-entry-properties nil 'standard))
16419 (props (if cat props0
16420 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16421 (prop (if (< 1 (length props))
16422 (completing-read "Property: " props nil t)
16423 (caar props))))
16424 (list prop)))
16425 (if (not property)
16426 (message "No property to delete in this entry")
16427 (org-entry-delete nil property)
16428 (message "Property \"%s\" deleted" property)))
16430 (defun org-delete-property-globally (property)
16431 "Remove PROPERTY globally, from all entries.
16432 This function ignores narrowing, if any."
16433 (interactive
16434 (let* ((completion-ignore-case t)
16435 (prop (completing-read
16436 "Globally remove property: "
16437 (mapcar #'list (org-buffer-property-keys)))))
16438 (list prop)))
16439 (org-with-wide-buffer
16440 (goto-char (point-min))
16441 (let ((count 0)
16442 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16443 (while (re-search-forward re nil t)
16444 (when (org-entry-delete (point) property) (cl-incf count)))
16445 (message "Property \"%s\" removed from %d entries" property count))))
16447 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16449 (defun org-compute-property-at-point ()
16450 "Compute the property at point.
16451 This looks for an enclosing column format, extracts the operator and
16452 then applies it to the property in the column format's scope."
16453 (interactive)
16454 (unless (org-at-property-p)
16455 (user-error "Not at a property"))
16456 (let ((prop (match-string-no-properties 2)))
16457 (org-columns-get-format-and-top-level)
16458 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16459 (user-error "No operator defined for property %s" prop))
16460 (org-columns-compute prop)))
16462 (defvar org-property-allowed-value-functions nil
16463 "Hook for functions supplying allowed values for a specific property.
16464 The functions must take a single argument, the name of the property, and
16465 return a flat list of allowed values. If \":ETC\" is one of
16466 the values, this means that these values are intended as defaults for
16467 completion, but that other values should be allowed too.
16468 The functions must return nil if they are not responsible for this
16469 property.")
16471 (defun org-property-get-allowed-values (pom property &optional table)
16472 "Get allowed values for the property PROPERTY.
16473 When TABLE is non-nil, return an alist that can directly be used for
16474 completion."
16475 (let (vals)
16476 (cond
16477 ((equal property "TODO")
16478 (setq vals (org-with-point-at pom
16479 (append org-todo-keywords-1 '("")))))
16480 ((equal property "PRIORITY")
16481 (let ((n org-lowest-priority))
16482 (while (>= n org-highest-priority)
16483 (push (char-to-string n) vals)
16484 (setq n (1- n)))))
16485 ((equal property "CATEGORY"))
16486 ((member property org-special-properties))
16487 ((setq vals (run-hook-with-args-until-success
16488 'org-property-allowed-value-functions property)))
16490 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16491 (when (and vals (string-match "\\S-" vals))
16492 (setq vals (car (read-from-string (concat "(" vals ")"))))
16493 (setq vals (mapcar (lambda (x)
16494 (cond ((stringp x) x)
16495 ((numberp x) (number-to-string x))
16496 ((symbolp x) (symbol-name x))
16497 (t "???")))
16498 vals)))))
16499 (when (member ":ETC" vals)
16500 (setq vals (remove ":ETC" vals))
16501 (org-add-props (car vals) '(org-unrestricted t)))
16502 (if table (mapcar 'list vals) vals)))
16504 (defun org-property-previous-allowed-value (&optional _previous)
16505 "Switch to the next allowed value for this property."
16506 (interactive)
16507 (org-property-next-allowed-value t))
16509 (defun org-property-next-allowed-value (&optional previous)
16510 "Switch to the next allowed value for this property."
16511 (interactive)
16512 (unless (org-at-property-p)
16513 (user-error "Not at a property"))
16514 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16515 (key (match-string 2))
16516 (value (match-string 3))
16517 (allowed (or (org-property-get-allowed-values (point) key)
16518 (and (member value '("[ ]" "[-]" "[X]"))
16519 '("[ ]" "[X]"))))
16520 (heading (save-match-data (nth 4 (org-heading-components))))
16521 nval)
16522 (unless allowed
16523 (user-error "Allowed values for this property have not been defined"))
16524 (when previous (setq allowed (reverse allowed)))
16525 (when (member value allowed)
16526 (setq nval (car (cdr (member value allowed)))))
16527 (setq nval (or nval (car allowed)))
16528 (when (equal nval value)
16529 (user-error "Only one allowed value for this property"))
16530 (org-at-property-p)
16531 (replace-match (concat " :" key ": " nval) t t)
16532 (org-indent-line)
16533 (beginning-of-line 1)
16534 (skip-chars-forward " \t")
16535 (when (equal prop org-effort-property)
16536 (org-refresh-property
16537 '((effort . identity)
16538 (effort-minutes . org-duration-string-to-minutes))
16539 nval)
16540 (when (string= org-clock-current-task heading)
16541 (setq org-clock-effort nval)
16542 (org-clock-update-mode-line)))
16543 (run-hook-with-args 'org-property-changed-functions key nval)))
16545 (defun org-find-olp (path &optional this-buffer)
16546 "Return a marker pointing to the entry at outline path OLP.
16547 If anything goes wrong, throw an error.
16548 You can wrap this call to catch the error like this:
16550 \(condition-case msg
16551 \(org-mobile-locate-entry (match-string 4))
16552 \(error (nth 1 msg)))
16554 The return value will then be either a string with the error message,
16555 or a marker if everything is OK.
16557 If THIS-BUFFER is set, the outline path does not contain a file,
16558 only headings."
16559 (let* ((file (if this-buffer buffer-file-name (pop path)))
16560 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16561 (level 1)
16562 (lmin 1)
16563 (lmax 1)
16564 end found flevel)
16565 (unless buffer (error "File not found :%s" file))
16566 (with-current-buffer buffer
16567 (org-with-wide-buffer
16568 (goto-char (point-min))
16569 (dolist (heading path)
16570 (let ((re (format org-complex-heading-regexp-format
16571 (regexp-quote heading)))
16572 (cnt 0))
16573 (while (re-search-forward re end t)
16574 (setq level (- (match-end 1) (match-beginning 1)))
16575 (when (and (>= level lmin) (<= level lmax))
16576 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16577 (when (= cnt 0)
16578 (error "Heading not found on level %d: %s" lmax heading))
16579 (when (> cnt 1)
16580 (error "Heading not unique on level %d: %s" lmax heading))
16581 (goto-char found)
16582 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16583 (setq end (save-excursion (org-end-of-subtree t t)))))
16584 (when (org-at-heading-p)
16585 (point-marker))))))
16587 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16588 "Find node HEADING in BUFFER.
16589 Return a marker to the heading if it was found, or nil if not.
16590 If POS-ONLY is set, return just the position instead of a marker.
16592 The heading text must match exact, but it may have a TODO keyword,
16593 a priority cookie and tags in the standard locations."
16594 (with-current-buffer (or buffer (current-buffer))
16595 (save-excursion
16596 (save-restriction
16597 (widen)
16598 (goto-char (point-min))
16599 (let (case-fold-search)
16600 (when (re-search-forward
16601 (format org-complex-heading-regexp-format
16602 (regexp-quote heading)) nil t)
16603 (if pos-only
16604 (match-beginning 0)
16605 (move-marker (make-marker) (match-beginning 0)))))))))
16607 (defun org-find-exact-heading-in-directory (heading &optional dir)
16608 "Find Org node headline HEADING in all .org files in directory DIR.
16609 When the target headline is found, return a marker to this location."
16610 (let ((files (directory-files (or dir default-directory)
16611 t "\\`[^.#].*\\.org\\'"))
16612 visiting m buffer)
16613 (catch 'found
16614 (dolist (file files)
16615 (message "trying %s" file)
16616 (setq visiting (org-find-base-buffer-visiting file))
16617 (setq buffer (or visiting (find-file-noselect file)))
16618 (setq m (org-find-exact-headline-in-buffer
16619 heading buffer))
16620 (when (and (not m) (not visiting)) (kill-buffer buffer))
16621 (and m (throw 'found m))))))
16623 (defun org-find-entry-with-id (ident)
16624 "Locate the entry that contains the ID property with exact value IDENT.
16625 IDENT can be a string, a symbol or a number, this function will search for
16626 the string representation of it.
16627 Return the position where this entry starts, or nil if there is no such entry."
16628 (interactive "sID: ")
16629 (let ((id (cond
16630 ((stringp ident) ident)
16631 ((symbolp ident) (symbol-name ident))
16632 ((numberp ident) (number-to-string ident))
16633 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16634 (org-with-wide-buffer (org-find-property "ID" id))))
16636 ;;;; Timestamps
16638 (defvar org-last-changed-timestamp nil)
16639 (defvar org-last-inserted-timestamp nil
16640 "The last time stamp inserted with `org-insert-time-stamp'.")
16641 (defvar org-ts-what) ; dynamically scoped parameter
16643 (defun org-time-stamp (arg &optional inactive)
16644 "Prompt for a date/time and insert a time stamp.
16646 If the user specifies a time like HH:MM or if this command is
16647 called with at least one prefix argument, the time stamp contains
16648 the date and the time. Otherwise, only the date is included.
16650 All parts of a date not specified by the user are filled in from
16651 the timestamp at point, if any, or the current date/time
16652 otherwise.
16654 If there is already a timestamp at the cursor, it is replaced.
16656 With two universal prefix arguments, insert an active timestamp
16657 with the current time without prompting the user.
16659 When called from lisp, the timestamp is inactive if INACTIVE is
16660 non-nil."
16661 (interactive "P")
16662 (let* ((ts (cond
16663 ((org-at-date-range-p t)
16664 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16665 ((org-at-timestamp-p t) (match-string 0))))
16666 ;; Default time is either the timestamp at point or today.
16667 ;; When entering a range, only the range start is considered.
16668 (default-time (if (not ts) (current-time)
16669 (apply #'encode-time (org-parse-time-string ts))))
16670 (default-input (and ts (org-get-compact-tod ts)))
16671 (repeater (and ts
16672 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16673 (match-string 0 ts)))
16674 org-time-was-given
16675 org-end-time-was-given
16676 (time
16677 (and (if (equal arg '(16)) (current-time)
16678 ;; Preserve `this-command' and `last-command'.
16679 (let ((this-command this-command)
16680 (last-command last-command))
16681 (org-read-date
16682 arg 'totime nil nil default-time default-input
16683 inactive))))))
16684 (cond
16685 ((and ts
16686 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16687 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16688 (insert "--")
16689 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16691 ;; Make sure we're on a timestamp. When in the middle of a date
16692 ;; range, move arbitrarily to range end.
16693 (unless (org-at-timestamp-p t)
16694 (skip-chars-forward "-")
16695 (org-at-timestamp-p t))
16696 (replace-match "")
16697 (setq org-last-changed-timestamp
16698 (org-insert-time-stamp
16699 time (or org-time-was-given arg)
16700 inactive nil nil (list org-end-time-was-given)))
16701 (when repeater
16702 (backward-char)
16703 (insert " " repeater)
16704 (setq org-last-changed-timestamp
16705 (concat (substring org-last-inserted-timestamp 0 -1)
16706 " " repeater ">")))
16707 (message "Timestamp updated"))
16708 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16709 (t (org-insert-time-stamp
16710 time (or org-time-was-given arg) inactive nil nil
16711 (list org-end-time-was-given))))))
16713 ;; FIXME: can we use this for something else, like computing time differences?
16714 (defun org-get-compact-tod (s)
16715 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16716 (let* ((t1 (match-string 1 s))
16717 (h1 (string-to-number (match-string 2 s)))
16718 (m1 (string-to-number (match-string 3 s)))
16719 (t2 (and (match-end 4) (match-string 5 s)))
16720 (h2 (and t2 (string-to-number (match-string 6 s))))
16721 (m2 (and t2 (string-to-number (match-string 7 s))))
16722 dh dm)
16723 (if (not t2)
16725 (setq dh (- h2 h1) dm (- m2 m1))
16726 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16727 (concat t1 "+" (number-to-string dh)
16728 (and (/= 0 dm) (format ":%02d" dm)))))))
16730 (defun org-time-stamp-inactive (&optional arg)
16731 "Insert an inactive time stamp.
16732 An inactive time stamp is enclosed in square brackets instead of angle
16733 brackets. It is inactive in the sense that it does not trigger agenda entries,
16734 does not link to the calendar and cannot be changed with the S-cursor keys.
16735 So these are more for recording a certain time/date."
16736 (interactive "P")
16737 (org-time-stamp arg 'inactive))
16739 (defvar org-date-ovl (make-overlay 1 1))
16740 (overlay-put org-date-ovl 'face 'org-date-selected)
16741 (delete-overlay org-date-ovl)
16743 (defvar org-ans1) ; dynamically scoped parameter
16744 (defvar org-ans2) ; dynamically scoped parameter
16746 (defvar org-plain-time-of-day-regexp) ; defined below
16748 (defvar org-overriding-default-time nil) ; dynamically scoped
16749 (defvar org-read-date-overlay nil)
16750 (defvar org-dcst nil) ; dynamically scoped
16751 (defvar org-read-date-history nil)
16752 (defvar org-read-date-final-answer nil)
16753 (defvar org-read-date-analyze-futurep nil)
16754 (defvar org-read-date-analyze-forced-year nil)
16755 (defvar org-read-date-inactive)
16757 (defvar org-read-date-minibuffer-local-map
16758 (let* ((map (make-sparse-keymap)))
16759 (set-keymap-parent map minibuffer-local-map)
16760 (org-defkey map (kbd ".")
16761 (lambda () (interactive)
16762 ;; Are we at the beginning of the prompt?
16763 (if (looking-back "^[^:]+: "
16764 (let ((inhibit-field-text-motion t))
16765 (line-beginning-position)))
16766 (org-eval-in-calendar '(calendar-goto-today))
16767 (insert "."))))
16768 (org-defkey map (kbd "C-.")
16769 (lambda () (interactive)
16770 (org-eval-in-calendar '(calendar-goto-today))))
16771 (org-defkey map [(meta shift left)]
16772 (lambda () (interactive)
16773 (org-eval-in-calendar '(calendar-backward-month 1))))
16774 (org-defkey map [(meta shift right)]
16775 (lambda () (interactive)
16776 (org-eval-in-calendar '(calendar-forward-month 1))))
16777 (org-defkey map [(meta shift up)]
16778 (lambda () (interactive)
16779 (org-eval-in-calendar '(calendar-backward-year 1))))
16780 (org-defkey map [(meta shift down)]
16781 (lambda () (interactive)
16782 (org-eval-in-calendar '(calendar-forward-year 1))))
16783 (org-defkey map [?\e (shift left)]
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-backward-month 1))))
16786 (org-defkey map [?\e (shift right)]
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-forward-month 1))))
16789 (org-defkey map [?\e (shift up)]
16790 (lambda () (interactive)
16791 (org-eval-in-calendar '(calendar-backward-year 1))))
16792 (org-defkey map [?\e (shift down)]
16793 (lambda () (interactive)
16794 (org-eval-in-calendar '(calendar-forward-year 1))))
16795 (org-defkey map [(shift up)]
16796 (lambda () (interactive)
16797 (org-eval-in-calendar '(calendar-backward-week 1))))
16798 (org-defkey map [(shift down)]
16799 (lambda () (interactive)
16800 (org-eval-in-calendar '(calendar-forward-week 1))))
16801 (org-defkey map [(shift left)]
16802 (lambda () (interactive)
16803 (org-eval-in-calendar '(calendar-backward-day 1))))
16804 (org-defkey map [(shift right)]
16805 (lambda () (interactive)
16806 (org-eval-in-calendar '(calendar-forward-day 1))))
16807 (org-defkey map "!"
16808 (lambda () (interactive)
16809 (org-eval-in-calendar '(diary-view-entries))
16810 (message "")))
16811 (org-defkey map ">"
16812 (lambda () (interactive)
16813 (org-eval-in-calendar '(calendar-scroll-left 1))))
16814 (org-defkey map "<"
16815 (lambda () (interactive)
16816 (org-eval-in-calendar '(calendar-scroll-right 1))))
16817 (org-defkey map "\C-v"
16818 (lambda () (interactive)
16819 (org-eval-in-calendar
16820 '(calendar-scroll-left-three-months 1))))
16821 (org-defkey map "\M-v"
16822 (lambda () (interactive)
16823 (org-eval-in-calendar
16824 '(calendar-scroll-right-three-months 1))))
16825 map)
16826 "Keymap for minibuffer commands when using `org-read-date'.")
16828 (defvar org-def)
16829 (defvar org-defdecode)
16830 (defvar org-with-time)
16832 (defvar calendar-setup) ; Dynamically scoped.
16833 (defun org-read-date (&optional with-time to-time from-string prompt
16834 default-time default-input inactive)
16835 "Read a date, possibly a time, and make things smooth for the user.
16836 The prompt will suggest to enter an ISO date, but you can also enter anything
16837 which will at least partially be understood by `parse-time-string'.
16838 Unrecognized parts of the date will default to the current day, month, year,
16839 hour and minute. If this command is called to replace a timestamp at point,
16840 or to enter the second timestamp of a range, the default time is taken
16841 from the existing stamp. Furthermore, the command prefers the future,
16842 so if you are giving a date where the year is not given, and the day-month
16843 combination is already past in the current year, it will assume you
16844 mean next year. For details, see the manual. A few examples:
16846 3-2-5 --> 2003-02-05
16847 feb 15 --> currentyear-02-15
16848 2/15 --> currentyear-02-15
16849 sep 12 9 --> 2009-09-12
16850 12:45 --> today 12:45
16851 22 sept 0:34 --> currentyear-09-22 0:34
16852 12 --> currentyear-currentmonth-12
16853 Fri --> nearest Friday after today
16854 -Tue --> last Tuesday
16855 etc.
16857 Furthermore you can specify a relative date by giving, as the *first* thing
16858 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16859 change in days weeks, months, years.
16860 With a single plus or minus, the date is relative to today. With a double
16861 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16862 +4d --> four days from today
16863 +4 --> same as above
16864 +2w --> two weeks from today
16865 ++5 --> five days from default date
16867 The function understands only English month and weekday abbreviations.
16869 While prompting, a calendar is popped up - you can also select the
16870 date with the mouse (button 1). The calendar shows a period of three
16871 months. To scroll it to other months, use the keys `>' and `<'.
16872 If you don't like the calendar, turn it off with
16873 (setq org-read-date-popup-calendar nil)
16875 With optional argument TO-TIME, the date will immediately be converted
16876 to an internal time.
16877 With an optional argument WITH-TIME, the prompt will suggest to
16878 also insert a time. Note that when WITH-TIME is not set, you can
16879 still enter a time, and this function will inform the calling routine
16880 about this change. The calling routine may then choose to change the
16881 format used to insert the time stamp into the buffer to include the time.
16882 With optional argument FROM-STRING, read from this string instead from
16883 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16884 the time/date that is used for everything that is not specified by the
16885 user."
16886 (require 'parse-time)
16887 (let* ((org-with-time with-time)
16888 (org-time-stamp-rounding-minutes
16889 (if (equal org-with-time '(16))
16890 '(0 0)
16891 org-time-stamp-rounding-minutes))
16892 (org-dcst org-display-custom-times)
16893 (ct (org-current-time))
16894 (org-def (or org-overriding-default-time default-time ct))
16895 (org-defdecode (decode-time org-def))
16896 (cur-frame (selected-frame))
16897 (mouse-autoselect-window nil) ; Don't let the mouse jump
16898 (calendar-setup
16899 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16900 (calendar-move-hook nil)
16901 (calendar-view-diary-initially-flag nil)
16902 (calendar-view-holidays-initially-flag nil)
16903 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16904 ;; Rationalize `org-def' and `org-defdecode', if required.
16905 (when (< (nth 2 org-defdecode) org-extend-today-until)
16906 (setf (nth 2 org-defdecode) -1)
16907 (setf (nth 1 org-defdecode) 59)
16908 (setq org-def (apply #'encode-time org-defdecode))
16909 (setq org-defdecode (decode-time org-def)))
16910 (let* ((timestr (format-time-string
16911 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16912 org-def))
16913 (prompt (concat (if prompt (concat prompt " ") "")
16914 (format "Date+time [%s]: " timestr))))
16915 (cond
16916 (from-string (setq ans from-string))
16917 (org-read-date-popup-calendar
16918 (save-excursion
16919 (save-window-excursion
16920 (calendar)
16921 (when (eq calendar-setup 'calendar-only)
16922 (setq cal-frame
16923 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16924 (select-frame cal-frame))
16925 (org-eval-in-calendar '(setq cursor-type nil) t)
16926 (unwind-protect
16927 (progn
16928 (calendar-forward-day (- (time-to-days org-def)
16929 (calendar-absolute-from-gregorian
16930 (calendar-current-date))))
16931 (org-eval-in-calendar nil t)
16932 (let* ((old-map (current-local-map))
16933 (map (copy-keymap calendar-mode-map))
16934 (minibuffer-local-map
16935 (copy-keymap org-read-date-minibuffer-local-map)))
16936 (org-defkey map (kbd "RET") 'org-calendar-select)
16937 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16938 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16939 (unwind-protect
16940 (progn
16941 (use-local-map map)
16942 (setq org-read-date-inactive inactive)
16943 (add-hook 'post-command-hook 'org-read-date-display)
16944 (setq org-ans0
16945 (read-string prompt
16946 default-input
16947 'org-read-date-history
16948 nil))
16949 ;; org-ans0: from prompt
16950 ;; org-ans1: from mouse click
16951 ;; org-ans2: from calendar motion
16952 (setq ans
16953 (concat org-ans0 " " (or org-ans1 org-ans2))))
16954 (remove-hook 'post-command-hook 'org-read-date-display)
16955 (use-local-map old-map)
16956 (when org-read-date-overlay
16957 (delete-overlay org-read-date-overlay)
16958 (setq org-read-date-overlay nil)))))
16959 (bury-buffer "*Calendar*")
16960 (when cal-frame
16961 (delete-frame cal-frame)
16962 (select-frame-set-input-focus cur-frame))))))
16964 (t ; Naked prompt only
16965 (unwind-protect
16966 (setq ans (read-string prompt default-input
16967 'org-read-date-history timestr))
16968 (when org-read-date-overlay
16969 (delete-overlay org-read-date-overlay)
16970 (setq org-read-date-overlay nil))))))
16972 (setq final (org-read-date-analyze ans org-def org-defdecode))
16974 (when org-read-date-analyze-forced-year
16975 (message "Year was forced into %s"
16976 (if org-read-date-force-compatible-dates
16977 "compatible range (1970-2037)"
16978 "range representable on this machine"))
16979 (ding))
16981 ;; One round trip to get rid of 34th of August and stuff like that....
16982 (setq final (decode-time (apply 'encode-time final)))
16984 (setq org-read-date-final-answer ans)
16986 (if to-time
16987 (apply 'encode-time final)
16988 (if (and (boundp 'org-time-was-given) org-time-was-given)
16989 (format "%04d-%02d-%02d %02d:%02d"
16990 (nth 5 final) (nth 4 final) (nth 3 final)
16991 (nth 2 final) (nth 1 final))
16992 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16994 (defun org-read-date-display ()
16995 "Display the current date prompt interpretation in the minibuffer."
16996 (when org-read-date-display-live
16997 (when org-read-date-overlay
16998 (delete-overlay org-read-date-overlay))
16999 (when (minibufferp (current-buffer))
17000 (save-excursion
17001 (end-of-line 1)
17002 (while (not (equal (buffer-substring
17003 (max (point-min) (- (point) 4)) (point))
17004 " "))
17005 (insert " ")))
17006 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17007 " " (or org-ans1 org-ans2)))
17008 (org-end-time-was-given nil)
17009 (f (org-read-date-analyze ans org-def org-defdecode))
17010 (fmts (if org-dcst
17011 org-time-stamp-custom-formats
17012 org-time-stamp-formats))
17013 (fmt (if (or org-with-time
17014 (and (boundp 'org-time-was-given) org-time-was-given))
17015 (cdr fmts)
17016 (car fmts)))
17017 (txt (format-time-string fmt (apply 'encode-time f)))
17018 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17019 (txt (concat "=> " txt)))
17020 (when (and org-end-time-was-given
17021 (string-match org-plain-time-of-day-regexp txt))
17022 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17023 org-end-time-was-given
17024 (substring txt (match-end 0)))))
17025 (when org-read-date-analyze-futurep
17026 (setq txt (concat txt " (=>F)")))
17027 (setq org-read-date-overlay
17028 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17029 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17031 (defun org-read-date-analyze (ans def defdecode)
17032 "Analyze the combined answer of the date prompt."
17033 ;; FIXME: cleanup and comment
17034 ;; Pass `current-time' result to `decode-time' (instead of calling
17035 ;; without arguments) so that only `current-time' has to be
17036 ;; overriden in tests.
17037 (let ((org-def def)
17038 (org-defdecode defdecode)
17039 (nowdecode (decode-time (current-time)))
17040 delta deltan deltaw deltadef year month day
17041 hour minute second wday pm h2 m2 tl wday1
17042 iso-year iso-weekday iso-week iso-date futurep kill-year)
17043 (setq org-read-date-analyze-futurep nil
17044 org-read-date-analyze-forced-year nil)
17045 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17046 (setq ans "+0"))
17048 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17049 (setq ans (replace-match "" t t ans)
17050 deltan (car delta)
17051 deltaw (nth 1 delta)
17052 deltadef (nth 2 delta)))
17054 ;; Check if there is an iso week date in there. If yes, store the
17055 ;; info and postpone interpreting it until the rest of the parsing
17056 ;; is done.
17057 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17058 (setq iso-year (when (match-end 1)
17059 (org-small-year-to-year
17060 (string-to-number (match-string 1 ans))))
17061 iso-weekday (when (match-end 3)
17062 (string-to-number (match-string 3 ans)))
17063 iso-week (string-to-number (match-string 2 ans)))
17064 (setq ans (replace-match "" t t ans)))
17066 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17067 (when (string-match
17068 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17069 (setq year (if (match-end 2)
17070 (string-to-number (match-string 2 ans))
17071 (progn (setq kill-year t)
17072 (string-to-number (format-time-string "%Y"))))
17073 month (string-to-number (match-string 3 ans))
17074 day (string-to-number (match-string 4 ans)))
17075 (setq year (org-small-year-to-year year))
17076 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17077 t nil ans)))
17079 ;; Help matching dotted european dates
17080 (when (string-match
17081 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17082 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17083 (setq kill-year t)
17084 (string-to-number (format-time-string "%Y")))
17085 day (string-to-number (match-string 1 ans))
17086 month (string-to-number (match-string 2 ans))
17087 ans (replace-match (format "%04d-%02d-%02d" year month day)
17088 t nil ans)))
17090 ;; Help matching american dates, like 5/30 or 5/30/7
17091 (when (string-match
17092 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17093 (setq year (if (match-end 4)
17094 (string-to-number (match-string 4 ans))
17095 (progn (setq kill-year t)
17096 (string-to-number (format-time-string "%Y"))))
17097 month (string-to-number (match-string 1 ans))
17098 day (string-to-number (match-string 2 ans)))
17099 (setq year (org-small-year-to-year year))
17100 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17101 t nil ans)))
17102 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17103 ;; If there is a time with am/pm, and *no* time without it, we convert
17104 ;; so that matching will be successful.
17105 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17106 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17107 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17108 (setq hour (string-to-number (match-string 1 ans))
17109 minute (if (match-end 3)
17110 (string-to-number (match-string 3 ans))
17112 pm (equal ?p
17113 (string-to-char (downcase (match-string 4 ans)))))
17114 (if (and (= hour 12) (not pm))
17115 (setq hour 0)
17116 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17117 (setq ans (replace-match (format "%02d:%02d" hour minute)
17118 t t ans))))
17120 ;; Check if a time range is given as a duration
17121 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17122 (setq hour (string-to-number (match-string 1 ans))
17123 h2 (+ hour (string-to-number (match-string 3 ans)))
17124 minute (string-to-number (match-string 2 ans))
17125 m2 (+ minute (if (match-end 5) (string-to-number
17126 (match-string 5 ans))0)))
17127 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17128 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17129 t t ans)))
17131 ;; Check if there is a time range
17132 (when (boundp 'org-end-time-was-given)
17133 (setq org-time-was-given nil)
17134 (when (and (string-match org-plain-time-of-day-regexp ans)
17135 (match-end 8))
17136 (setq org-end-time-was-given (match-string 8 ans))
17137 (setq ans (concat (substring ans 0 (match-beginning 7))
17138 (substring ans (match-end 7))))))
17140 (setq tl (parse-time-string ans)
17141 day (or (nth 3 tl) (nth 3 org-defdecode))
17142 month
17143 (cond ((nth 4 tl))
17144 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17145 ;; Day was specified. Make sure DAY+MONTH
17146 ;; combination happens in the future.
17147 ((nth 3 tl)
17148 (setq futurep t)
17149 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17150 (nth 4 nowdecode)))
17151 (t (nth 4 org-defdecode)))
17152 year
17153 (cond ((and (not kill-year) (nth 5 tl)))
17154 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17155 ;; Month was guessed in the future and is at least
17156 ;; equal to NOWDECODE's. Fix year accordingly.
17157 (futurep
17158 (if (or (> month (nth 4 nowdecode))
17159 (>= day (nth 3 nowdecode)))
17160 (nth 5 nowdecode)
17161 (1+ (nth 5 nowdecode))))
17162 ;; Month was specified. Make sure MONTH+YEAR
17163 ;; combination happens in the future.
17164 ((nth 4 tl)
17165 (setq futurep t)
17166 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17167 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17168 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17169 (t (nth 5 nowdecode))))
17170 (t (nth 5 org-defdecode)))
17171 hour (or (nth 2 tl) (nth 2 org-defdecode))
17172 minute (or (nth 1 tl) (nth 1 org-defdecode))
17173 second (or (nth 0 tl) 0)
17174 wday (nth 6 tl))
17176 (when (and (eq org-read-date-prefer-future 'time)
17177 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17178 (equal day (nth 3 nowdecode))
17179 (equal month (nth 4 nowdecode))
17180 (equal year (nth 5 nowdecode))
17181 (nth 2 tl)
17182 (or (< (nth 2 tl) (nth 2 nowdecode))
17183 (and (= (nth 2 tl) (nth 2 nowdecode))
17184 (nth 1 tl)
17185 (< (nth 1 tl) (nth 1 nowdecode)))))
17186 (setq day (1+ day)
17187 futurep t))
17189 ;; Special date definitions below
17190 (cond
17191 (iso-week
17192 ;; There was an iso week
17193 (require 'cal-iso)
17194 (setq futurep nil)
17195 (setq year (or iso-year year)
17196 day (or iso-weekday wday 1)
17197 wday nil ; to make sure that the trigger below does not match
17198 iso-date (calendar-gregorian-from-absolute
17199 (calendar-iso-to-absolute
17200 (list iso-week day year))))
17201 ; FIXME: Should we also push ISO weeks into the future?
17202 ; (when (and org-read-date-prefer-future
17203 ; (not iso-year)
17204 ; (< (calendar-absolute-from-gregorian iso-date)
17205 ; (time-to-days (current-time))))
17206 ; (setq year (1+ year)
17207 ; iso-date (calendar-gregorian-from-absolute
17208 ; (calendar-iso-to-absolute
17209 ; (list iso-week day year)))))
17210 (setq month (car iso-date)
17211 year (nth 2 iso-date)
17212 day (nth 1 iso-date)))
17213 (deltan
17214 (setq futurep nil)
17215 (unless deltadef
17216 ;; Pass `current-time' result to `decode-time' (instead of
17217 ;; calling without arguments) so that only `current-time' has
17218 ;; to be overriden in tests.
17219 (let ((now (decode-time (current-time))))
17220 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17221 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17222 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17223 ((equal deltaw "m") (setq month (+ month deltan)))
17224 ((equal deltaw "y") (setq year (+ year deltan)))))
17225 ((and wday (not (nth 3 tl)))
17226 ;; Weekday was given, but no day, so pick that day in the week
17227 ;; on or after the derived date.
17228 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17229 (unless (equal wday wday1)
17230 (setq day (+ day (% (- wday wday1 -7) 7))))))
17231 (when (and (boundp 'org-time-was-given)
17232 (nth 2 tl))
17233 (setq org-time-was-given t))
17234 (when (< year 100) (setq year (+ 2000 year)))
17235 ;; Check of the date is representable
17236 (if org-read-date-force-compatible-dates
17237 (progn
17238 (when (< year 1970)
17239 (setq year 1970 org-read-date-analyze-forced-year t))
17240 (when (> year 2037)
17241 (setq year 2037 org-read-date-analyze-forced-year t)))
17242 (condition-case nil
17243 (ignore (encode-time second minute hour day month year))
17244 (error
17245 (setq year (nth 5 org-defdecode))
17246 (setq org-read-date-analyze-forced-year t))))
17247 (setq org-read-date-analyze-futurep futurep)
17248 (list second minute hour day month year)))
17250 (defvar parse-time-weekdays)
17251 (defun org-read-date-get-relative (s today default)
17252 "Check string S for special relative date string.
17253 TODAY and DEFAULT are internal times, for today and for a default.
17254 Return shift list (N what def-flag)
17255 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17256 N is the number of WHATs to shift.
17257 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17258 the DEFAULT date rather than TODAY."
17259 (require 'parse-time)
17260 (when (and
17261 (string-match
17262 (concat
17263 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17264 "\\([0-9]+\\)?"
17265 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17266 "\\([ \t]\\|$\\)") s)
17267 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17268 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17269 (string-to-char (substring (match-string 1 s) -1))
17270 ?+))
17271 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17272 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17273 (what (if (match-end 3) (match-string 3 s) "d"))
17274 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17275 (date (if rel default today))
17276 (wday (nth 6 (decode-time date)))
17277 delta)
17278 (if wday1
17279 (progn
17280 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17281 (when (= delta 0) (setq delta 7))
17282 (when (= dir ?-)
17283 (setq delta (- delta 7))
17284 (when (= delta 0) (setq delta -7)))
17285 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17286 (list delta "d" rel))
17287 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17289 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17290 "Turn a user-specified date into the internal representation.
17291 The internal representation needed by the calendar is (month day year).
17292 This is a wrapper to handle the brain-dead convention in calendar that
17293 user function argument order change dependent on argument order."
17294 (pcase calendar-date-style
17295 (`american (list arg1 arg2 arg3))
17296 (`european (list arg2 arg1 arg3))
17297 (`iso (list arg2 arg3 arg1))))
17299 (defun org-eval-in-calendar (form &optional keepdate)
17300 "Eval FORM in the calendar window and return to current window.
17301 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17302 (let ((sf (selected-frame))
17303 (sw (selected-window)))
17304 (select-window (get-buffer-window "*Calendar*" t))
17305 (eval form)
17306 (when (and (not keepdate) (calendar-cursor-to-date))
17307 (let* ((date (calendar-cursor-to-date))
17308 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17309 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17310 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17311 (select-window sw)
17312 (select-frame-set-input-focus sf)))
17314 (defun org-calendar-select ()
17315 "Return to `org-read-date' with the date currently selected.
17316 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17317 (interactive)
17318 (when (calendar-cursor-to-date)
17319 (let* ((date (calendar-cursor-to-date))
17320 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17321 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17322 (when (active-minibuffer-window) (exit-minibuffer))))
17324 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17325 "Insert a date stamp for the date given by the internal TIME.
17326 See `format-time-string' for the format of TIME.
17327 WITH-HM means use the stamp format that includes the time of the day.
17328 INACTIVE means use square brackets instead of angular ones, so that the
17329 stamp will not contribute to the agenda.
17330 PRE and POST are optional strings to be inserted before and after the
17331 stamp.
17332 The command returns the inserted time stamp."
17333 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17334 stamp)
17335 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17336 (insert-before-markers (or pre ""))
17337 (when (listp extra)
17338 (setq extra (car extra))
17339 (if (and (stringp extra)
17340 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17341 (setq extra (format "-%02d:%02d"
17342 (string-to-number (match-string 1 extra))
17343 (string-to-number (match-string 2 extra))))
17344 (setq extra nil)))
17345 (when extra
17346 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17347 (insert-before-markers (setq stamp (format-time-string fmt time)))
17348 (insert-before-markers (or post ""))
17349 (setq org-last-inserted-timestamp stamp)))
17351 (defun org-toggle-time-stamp-overlays ()
17352 "Toggle the use of custom time stamp formats."
17353 (interactive)
17354 (setq org-display-custom-times (not org-display-custom-times))
17355 (unless org-display-custom-times
17356 (let ((p (point-min)) (bmp (buffer-modified-p)))
17357 (while (setq p (next-single-property-change p 'display))
17358 (when (and (get-text-property p 'display)
17359 (eq (get-text-property p 'face) 'org-date))
17360 (remove-text-properties
17361 p (setq p (next-single-property-change p 'display))
17362 '(display t))))
17363 (set-buffer-modified-p bmp)))
17364 (org-restart-font-lock)
17365 (setq org-table-may-need-update t)
17366 (if org-display-custom-times
17367 (message "Time stamps are overlaid with custom format")
17368 (message "Time stamp overlays removed")))
17370 (defun org-display-custom-time (beg end)
17371 "Overlay modified time stamp format over timestamp between BEG and END."
17372 (let* ((ts (buffer-substring beg end))
17373 t1 w1 with-hm tf time str w2 (off 0))
17374 (save-match-data
17375 (setq t1 (org-parse-time-string ts t))
17376 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17377 (setq off (- (match-end 0) (match-beginning 0)))))
17378 (setq end (- end off))
17379 (setq w1 (- end beg)
17380 with-hm (and (nth 1 t1) (nth 2 t1))
17381 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17382 time (org-fix-decoded-time t1)
17383 str (org-add-props
17384 (format-time-string
17385 (substring tf 1 -1) (apply 'encode-time time))
17386 nil 'mouse-face 'highlight)
17387 w2 (length str))
17388 (unless (= w2 w1)
17389 (add-text-properties (1+ beg) (+ 2 beg)
17390 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17391 (put-text-property beg end 'display str)))
17393 (defun org-fix-decoded-time (time)
17394 "Set 0 instead of nil for the first 6 elements of time.
17395 Don't touch the rest."
17396 (let ((n 0))
17397 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17399 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17400 "Difference between TIMESTAMP-STRING and now in days.
17401 If SECONDS is non-nil, return the difference in seconds."
17402 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17403 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17404 (funcall fdiff (current-time)))))
17406 (defun org-deadline-close-p (timestamp-string &optional ndays)
17407 "Is the time in TIMESTAMP-STRING close to the current date?"
17408 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17409 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17410 (not (org-entry-is-done-p))))
17412 (defun org-get-wdays (ts &optional delay zero-delay)
17413 "Get the deadline lead time appropriate for timestring TS.
17414 When DELAY is non-nil, get the delay time for scheduled items
17415 instead of the deadline lead time. When ZERO-DELAY is non-nil
17416 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17417 don't try to find the delay cookie in the scheduled timestamp."
17418 (let ((tv (if delay org-scheduled-delay-days
17419 org-deadline-warning-days)))
17420 (cond
17421 ((or (and delay (< tv 0))
17422 (and delay zero-delay (<= tv 0))
17423 (and (not delay) (<= tv 0)))
17424 ;; Enforce this value no matter what
17425 (- tv))
17426 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17427 ;; lead time is specified.
17428 (floor (* (string-to-number (match-string 1 ts))
17429 (cdr (assoc (match-string 2 ts)
17430 '(("d" . 1) ("w" . 7)
17431 ("m" . 30.4) ("y" . 365.25)
17432 ("h" . 0.041667)))))))
17433 ;; go for the default.
17434 (t tv))))
17436 (defun org-calendar-select-mouse (ev)
17437 "Return to `org-read-date' with the date currently selected.
17438 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17439 (interactive "e")
17440 (mouse-set-point ev)
17441 (when (calendar-cursor-to-date)
17442 (let* ((date (calendar-cursor-to-date))
17443 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17444 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17445 (when (active-minibuffer-window) (exit-minibuffer))))
17447 (defun org-check-deadlines (ndays)
17448 "Check if there are any deadlines due or past due.
17449 A deadline is considered due if it happens within `org-deadline-warning-days'
17450 days from today's date. If the deadline appears in an entry marked DONE,
17451 it is not shown. The prefix arg NDAYS can be used to test that many
17452 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17453 (interactive "P")
17454 (let* ((org-warn-days
17455 (cond
17456 ((equal ndays '(4)) 100000)
17457 (ndays (prefix-numeric-value ndays))
17458 (t (abs org-deadline-warning-days))))
17459 (case-fold-search nil)
17460 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17461 (callback
17462 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17463 (message "%d deadlines past-due or due within %d days"
17464 (org-occur regexp nil callback)
17465 org-warn-days)))
17467 (defsubst org-re-timestamp (type)
17468 "Return a regexp for timestamp TYPE.
17469 Allowed values for TYPE are:
17471 all: all timestamps
17472 active: only active timestamps (<...>)
17473 inactive: only inactive timestamps ([...])
17474 scheduled: only scheduled timestamps
17475 deadline: only deadline timestamps
17476 closed: only closed time-stamps
17478 When TYPE is nil, fall back on returning a regexp that matches
17479 both scheduled and deadline timestamps."
17480 (cl-case type
17481 (all org-ts-regexp-both)
17482 (active org-ts-regexp)
17483 (inactive org-ts-regexp-inactive)
17484 (scheduled org-scheduled-time-regexp)
17485 (deadline org-deadline-time-regexp)
17486 (closed org-closed-time-regexp)
17487 (otherwise
17488 (concat "\\<"
17489 (regexp-opt (list org-deadline-string org-scheduled-string))
17490 " *<\\([^>]+\\)>"))))
17492 (defun org-check-before-date (d)
17493 "Check if there are deadlines or scheduled entries before date D."
17494 (interactive (list (org-read-date)))
17495 (let* ((case-fold-search nil)
17496 (regexp (org-re-timestamp org-ts-type))
17497 (ts-type org-ts-type)
17498 (callback
17499 (lambda ()
17500 (let ((match (match-string 1)))
17501 (and (if (memq ts-type '(active inactive all))
17502 (eq (org-element-type (save-excursion
17503 (backward-char)
17504 (org-element-context)))
17505 'timestamp)
17506 (org-at-planning-p))
17507 (time-less-p
17508 (org-time-string-to-time match)
17509 (org-time-string-to-time d)))))))
17510 (message "%d entries before %s"
17511 (org-occur regexp nil callback)
17512 d)))
17514 (defun org-check-after-date (d)
17515 "Check if there are deadlines or scheduled entries after date D."
17516 (interactive (list (org-read-date)))
17517 (let* ((case-fold-search nil)
17518 (regexp (org-re-timestamp org-ts-type))
17519 (ts-type org-ts-type)
17520 (callback
17521 (lambda ()
17522 (let ((match (match-string 1)))
17523 (and (if (memq ts-type '(active inactive all))
17524 (eq (org-element-type (save-excursion
17525 (backward-char)
17526 (org-element-context)))
17527 'timestamp)
17528 (org-at-planning-p))
17529 (not (time-less-p
17530 (org-time-string-to-time match)
17531 (org-time-string-to-time d))))))))
17532 (message "%d entries after %s"
17533 (org-occur regexp nil callback)
17534 d)))
17536 (defun org-check-dates-range (start-date end-date)
17537 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17538 (interactive (list (org-read-date nil nil nil "Range starts")
17539 (org-read-date nil nil nil "Range end")))
17540 (let ((case-fold-search nil)
17541 (regexp (org-re-timestamp org-ts-type))
17542 (callback
17543 (let ((type org-ts-type))
17544 (lambda ()
17545 (let ((match (match-string 1)))
17546 (and
17547 (if (memq type '(active inactive all))
17548 (eq (org-element-type (save-excursion
17549 (backward-char)
17550 (org-element-context)))
17551 'timestamp)
17552 (org-at-planning-p))
17553 (not (time-less-p
17554 (org-time-string-to-time match)
17555 (org-time-string-to-time start-date)))
17556 (time-less-p
17557 (org-time-string-to-time match)
17558 (org-time-string-to-time end-date))))))))
17559 (message "%d entries between %s and %s"
17560 (org-occur regexp nil callback) start-date end-date)))
17562 (defun org-evaluate-time-range (&optional to-buffer)
17563 "Evaluate a time range by computing the difference between start and end.
17564 Normally the result is just printed in the echo area, but with prefix arg
17565 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17566 If the time range is actually in a table, the result is inserted into the
17567 next column.
17568 For time difference computation, a year is assumed to be exactly 365
17569 days in order to avoid rounding problems."
17570 (interactive "P")
17572 (org-clock-update-time-maybe)
17573 (save-excursion
17574 (unless (org-at-date-range-p t)
17575 (goto-char (point-at-bol))
17576 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17577 (unless (org-at-date-range-p t)
17578 (user-error "Not at a time-stamp range, and none found in current line")))
17579 (let* ((ts1 (match-string 1))
17580 (ts2 (match-string 2))
17581 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17582 (match-end (match-end 0))
17583 (time1 (org-time-string-to-time ts1))
17584 (time2 (org-time-string-to-time ts2))
17585 (t1 (float-time time1))
17586 (t2 (float-time time2))
17587 (diff (abs (- t2 t1)))
17588 (negative (< (- t2 t1) 0))
17589 ;; (ys (floor (* 365 24 60 60)))
17590 (ds (* 24 60 60))
17591 (hs (* 60 60))
17592 (fy "%dy %dd %02d:%02d")
17593 (fy1 "%dy %dd")
17594 (fd "%dd %02d:%02d")
17595 (fd1 "%dd")
17596 (fh "%02d:%02d")
17597 y d h m align)
17598 (if havetime
17599 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17601 d (floor (/ diff ds)) diff (mod diff ds)
17602 h (floor (/ diff hs)) diff (mod diff hs)
17603 m (floor (/ diff 60)))
17604 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17606 d (floor (+ (/ diff ds) 0.5))
17607 h 0 m 0))
17608 (if (not to-buffer)
17609 (message "%s" (org-make-tdiff-string y d h m))
17610 (if (org-at-table-p)
17611 (progn
17612 (goto-char match-end)
17613 (setq align t)
17614 (and (looking-at " *|") (goto-char (match-end 0))))
17615 (goto-char match-end))
17616 (when (looking-at
17617 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17618 (replace-match ""))
17619 (when negative (insert " -"))
17620 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17621 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17622 (insert " " (format fh h m))))
17623 (when align (org-table-align))
17624 (message "Time difference inserted")))))
17626 (defun org-make-tdiff-string (y d h m)
17627 (let ((fmt "")
17628 (l nil))
17629 (when (> y 0)
17630 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17631 (push y l))
17632 (when (> d 0)
17633 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17634 (push d l))
17635 (when (> h 0)
17636 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17637 (push h l))
17638 (when (> m 0)
17639 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17640 (push m l))
17641 (apply 'format fmt (nreverse l))))
17643 (defun org-time-string-to-time (s &optional buffer pos)
17644 "Convert a timestamp string into internal time."
17645 (condition-case errdata
17646 (apply 'encode-time (org-parse-time-string s))
17647 (error (error "Bad timestamp `%s'%s\nError was: %s"
17648 s (if (not (and buffer pos))
17650 (format-message " at %d in buffer `%s'" pos buffer))
17651 (cdr errdata)))))
17653 (defun org-time-string-to-seconds (s)
17654 "Convert a timestamp string to a number of seconds."
17655 (float-time (org-time-string-to-time s)))
17657 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17659 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17660 "Convert time stamp S to an absolute day number.
17662 If DAYNR in non-nil, and there is a specifier for a cyclic time
17663 stamp, get the closest date to DAYNR. If PREFER is
17664 `past' (respectively `future') return a date past (respectively
17665 after) or equal to DAYNR.
17667 POS is the location of time stamp S, as a buffer position in
17668 BUFFER.
17670 Diary sexp timestamps are matched against DAYNR, when non-nil.
17671 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17672 signalled."
17673 (cond
17674 ((string-match "\\`%%\\((.*)\\)" s)
17675 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17676 ;; only able to match individual dates. If it fails, raise an
17677 ;; error.
17678 (if (and daynr
17679 (org-diary-sexp-entry
17680 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17681 daynr
17682 (signal 'org-diary-sexp-no-match (list s))))
17683 ((and daynr show-all) (org-closest-date s daynr prefer))
17684 (t (time-to-days
17685 (condition-case errdata
17686 (apply #'encode-time (org-parse-time-string s))
17687 (error (error "Bad timestamp `%s'%s\nError was: %s"
17689 (if (not (and buffer pos)) ""
17690 (format-message " at %d in buffer `%s'" pos buffer))
17691 (cdr errdata))))))))
17693 (defun org-days-to-iso-week (days)
17694 "Return the iso week number."
17695 (require 'cal-iso)
17696 (car (calendar-iso-from-absolute days)))
17698 (defun org-small-year-to-year (year)
17699 "Convert 2-digit years into 4-digit years.
17700 YEAR is expanded into one of the 30 next years, if possible, or
17701 into a past one. Any year larger than 99 is returned unchanged."
17702 (if (>= year 100) year
17703 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17704 (century (/ current 100))
17705 (offset (- year (% current 100))))
17706 (cond ((> offset 30) (+ (* (1- century) 100) year))
17707 ((> offset -70) (+ (* century 100) year))
17708 (t (+ (* (1+ century) 100) year))))))
17710 (defun org-time-from-absolute (d)
17711 "Return the time corresponding to date D.
17712 D may be an absolute day number, or a calendar-type list (month day year)."
17713 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17714 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17716 (defvar org-agenda-current-date)
17717 (defun org-calendar-holiday ()
17718 "List of holidays, for Diary display in Org mode."
17719 (require 'holidays)
17720 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17721 (and hl (mapconcat #'identity hl "; "))))
17723 (defun org-diary-sexp-entry (sexp entry d)
17724 "Process a SEXP diary ENTRY for date D."
17725 (require 'diary-lib)
17726 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17727 ;; dynamically.
17728 (let* ((sexp `(let ((entry ,entry)
17729 (date ',d))
17730 ,(car (read-from-string sexp))))
17731 (result (if calendar-debug-sexp (eval sexp)
17732 (condition-case nil
17733 (eval sexp)
17734 (error
17735 (beep)
17736 (message "Bad sexp at line %d in %s: %s"
17737 (org-current-line)
17738 (buffer-file-name) sexp)
17739 (sleep-for 2))))))
17740 (cond ((stringp result) (split-string result "; "))
17741 ((and (consp result)
17742 (not (consp (cdr result)))
17743 (stringp (cdr result))) (cdr result))
17744 ((and (consp result)
17745 (stringp (car result))) result)
17746 (result entry))))
17748 (defun org-diary-to-ical-string (frombuf)
17749 "Get iCalendar entries from diary entries in buffer FROMBUF.
17750 This uses the icalendar.el library."
17751 (let* ((tmpdir temporary-file-directory)
17752 (tmpfile (make-temp-name
17753 (expand-file-name "orgics" tmpdir)))
17754 buf rtn b e)
17755 (with-current-buffer frombuf
17756 (icalendar-export-region (point-min) (point-max) tmpfile)
17757 (setq buf (find-buffer-visiting tmpfile))
17758 (set-buffer buf)
17759 (goto-char (point-min))
17760 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17761 (setq b (match-beginning 0)))
17762 (goto-char (point-max))
17763 (when (re-search-backward "^END:VEVENT" nil t)
17764 (setq e (match-end 0)))
17765 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17766 (kill-buffer buf)
17767 (delete-file tmpfile)
17768 rtn))
17770 (defun org-closest-date (start current prefer)
17771 "Return closest date to CURRENT starting from START.
17773 CURRENT and START are both time stamps.
17775 When PREFER is `past', return a date that is either CURRENT or
17776 past. When PREFER is `future', return a date that is either
17777 CURRENT or future.
17779 Only time stamps with a repeater are modified. Any other time
17780 stamp stay unchanged. In any case, return value is an absolute
17781 day number."
17782 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17783 ;; No repeater. Do not shift time stamp.
17784 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17785 (let ((value (string-to-number (match-string 1 start)))
17786 (type (match-string 2 start)))
17787 (if (= 0 value)
17788 ;; Repeater with a 0-value is considered as void.
17789 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17790 (let* ((base (org-date-to-gregorian start))
17791 (target (org-date-to-gregorian current))
17792 (sday (calendar-absolute-from-gregorian base))
17793 (cday (calendar-absolute-from-gregorian target))
17794 n1 n2)
17795 ;; If START is already past CURRENT, just return START.
17796 (if (<= cday sday) sday
17797 ;; Compute closest date before (N1) and closest date past
17798 ;; (N2) CURRENT.
17799 (pcase type
17800 ("h"
17801 (let ((missing-hours
17802 (mod (+ (- (* 24 (- cday sday))
17803 (nth 2 (org-parse-time-string start)))
17804 org-extend-today-until)
17805 value)))
17806 (setf n1 (if (= missing-hours 0) cday
17807 (- cday (1+ (/ missing-hours 24)))))
17808 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17809 ((or "d" "w")
17810 (let ((value (if (equal type "w") (* 7 value) value)))
17811 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17812 (setf n2 (+ n1 value))))
17813 ("m"
17814 (let* ((add-months
17815 (lambda (d n)
17816 ;; Add N months to gregorian date D, i.e.,
17817 ;; a list (MONTH DAY YEAR). Return a valid
17818 ;; gregorian date.
17819 (let ((m (+ (nth 0 d) n)))
17820 (list (mod m 12)
17821 (nth 1 d)
17822 (+ (/ m 12) (nth 2 d))))))
17823 (months ; Complete months to TARGET.
17824 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17825 (- (nth 0 target) (nth 0 base))
17826 ;; If START's day is greater than
17827 ;; TARGET's, remove incomplete month.
17828 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17829 value)
17830 value))
17831 (before (funcall add-months base months)))
17832 (setf n1 (calendar-absolute-from-gregorian before))
17833 (setf n2
17834 (calendar-absolute-from-gregorian
17835 (funcall add-months before value)))))
17837 (let* ((d (nth 1 base))
17838 (m (nth 0 base))
17839 (y (nth 2 base))
17840 (years ; Complete years to TARGET.
17841 (* (/ (- (nth 2 target)
17843 ;; If START's month and day are
17844 ;; greater than TARGET's, remove
17845 ;; incomplete year.
17846 (if (or (> (nth 0 target) m)
17847 (and (= (nth 0 target) m)
17848 (> (nth 1 target) d)))
17851 value)
17852 value))
17853 (before (list m d (+ y years))))
17854 (setf n1 (calendar-absolute-from-gregorian before))
17855 (setf n2 (calendar-absolute-from-gregorian
17856 (list m d (+ (nth 2 before) value)))))))
17857 ;; Handle PREFER parameter, if any.
17858 (cond
17859 ((eq prefer 'past) (if (= cday n2) n2 n1))
17860 ((eq prefer 'future) (if (= cday n1) n1 n2))
17861 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17863 (defun org-date-to-gregorian (d)
17864 "Turn any specification of date D into a Gregorian date for the calendar."
17865 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17866 ((and (listp d) (= (length d) 3)) d)
17867 ((stringp d)
17868 (let ((d (org-parse-time-string d)))
17869 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17870 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17872 (defun org-parse-time-string (s &optional nodefault)
17873 "Parse the standard Org-mode time string.
17874 This should be a lot faster than the normal `parse-time-string'.
17875 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17876 hour and minute fields will be nil if not given."
17877 (cond ((string-match org-ts-regexp0 s)
17878 (list 0
17879 (when (or (match-beginning 8) (not nodefault))
17880 (string-to-number (or (match-string 8 s) "0")))
17881 (when (or (match-beginning 7) (not nodefault))
17882 (string-to-number (or (match-string 7 s) "0")))
17883 (string-to-number (match-string 4 s))
17884 (string-to-number (match-string 3 s))
17885 (string-to-number (match-string 2 s))
17886 nil nil nil))
17887 ((string-match "^<[^>]+>$" s)
17888 (decode-time (seconds-to-time (org-matcher-time s))))
17889 (t (error "Not a standard Org-mode time string: %s" s))))
17891 (defun org-timestamp-up (&optional arg)
17892 "Increase the date item at the cursor by one.
17893 If the cursor is on the year, change the year. If it is on the month,
17894 the day or the time, change that.
17895 With prefix ARG, change by that many units."
17896 (interactive "p")
17897 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17899 (defun org-timestamp-down (&optional arg)
17900 "Decrease the date item at the cursor by one.
17901 If the cursor is on the year, change the year. If it is on the month,
17902 the day or the time, change that.
17903 With prefix ARG, change by that many units."
17904 (interactive "p")
17905 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17907 (defun org-timestamp-up-day (&optional arg)
17908 "Increase the date in the time stamp by one day.
17909 With prefix ARG, change that many days."
17910 (interactive "p")
17911 (if (and (not (org-at-timestamp-p t))
17912 (org-at-heading-p))
17913 (org-todo 'up)
17914 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17916 (defun org-timestamp-down-day (&optional arg)
17917 "Decrease the date in the time stamp by one day.
17918 With prefix ARG, change that many days."
17919 (interactive "p")
17920 (if (and (not (org-at-timestamp-p t))
17921 (org-at-heading-p))
17922 (org-todo 'down)
17923 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17925 (defun org-at-timestamp-p (&optional inactive-ok)
17926 "Non-nil if point is inside a timestamp.
17928 When optional argument INACTIVE-OK is non-nil, also consider
17929 inactive timestamps.
17931 When this function returns a non-nil value, match data is set
17932 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17933 INACTIVE-OK."
17934 (interactive)
17935 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17936 (pos (point))
17937 (ans (or (looking-at tsr)
17938 (save-excursion
17939 (skip-chars-backward "^[<\n\r\t")
17940 (when (> (point) (point-min)) (backward-char 1))
17941 (and (looking-at tsr)
17942 (> (- (match-end 0) pos) -1))))))
17943 (and ans
17944 (boundp 'org-ts-what)
17945 (setq org-ts-what
17946 (cond
17947 ((= pos (match-beginning 0)) 'bracket)
17948 ;; Point is considered to be "on the bracket" whether
17949 ;; it's really on it or right after it.
17950 ((= pos (1- (match-end 0))) 'bracket)
17951 ((= pos (match-end 0)) 'after)
17952 ((org-pos-in-match-range pos 2) 'year)
17953 ((org-pos-in-match-range pos 3) 'month)
17954 ((org-pos-in-match-range pos 7) 'hour)
17955 ((org-pos-in-match-range pos 8) 'minute)
17956 ((or (org-pos-in-match-range pos 4)
17957 (org-pos-in-match-range pos 5)) 'day)
17958 ((and (> pos (or (match-end 8) (match-end 5)))
17959 (< pos (match-end 0)))
17960 (- pos (or (match-end 8) (match-end 5))))
17961 (t 'day))))
17962 ans))
17964 (defun org-toggle-timestamp-type ()
17965 "Toggle the type (<active> or [inactive]) of a time stamp."
17966 (interactive)
17967 (when (org-at-timestamp-p t)
17968 (let ((beg (match-beginning 0)) (end (match-end 0))
17969 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17970 (save-excursion
17971 (goto-char beg)
17972 (while (re-search-forward "[][<>]" end t)
17973 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17974 t t)))
17975 (message "Timestamp is now %sactive"
17976 (if (equal (char-after beg) ?<) "" "in")))))
17978 (defun org-at-clock-log-p nil
17979 "Is the cursor on the clock log line?"
17980 (save-excursion
17981 (move-beginning-of-line 1)
17982 (looking-at org-clock-line-re)))
17984 (defvar org-clock-history) ; defined in org-clock.el
17985 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17986 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17987 "Change the date in the time stamp at point.
17988 The date will be changed by N times WHAT. WHAT can be `day', `month',
17989 `year', `minute', `second'. If WHAT is not given, the cursor position
17990 in the timestamp determines what will be changed.
17991 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17992 (let ((origin (point)) origin-cat
17993 with-hm inactive
17994 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17995 org-ts-what
17996 extra rem
17997 ts time time0 fixnext clrgx)
17998 (unless (org-at-timestamp-p t)
17999 (user-error "Not at a timestamp"))
18000 (if (and (not what) (eq org-ts-what 'bracket))
18001 (org-toggle-timestamp-type)
18002 ;; Point isn't on brackets. Remember the part of the time-stamp
18003 ;; the point was in. Indeed, size of time-stamps may change,
18004 ;; but point must be kept in the same category nonetheless.
18005 (setq origin-cat org-ts-what)
18006 (when (and (not what) (not (eq org-ts-what 'day))
18007 org-display-custom-times
18008 (get-text-property (point) 'display)
18009 (not (get-text-property (1- (point)) 'display)))
18010 (setq org-ts-what 'day))
18011 (setq org-ts-what (or what org-ts-what)
18012 inactive (= (char-after (match-beginning 0)) ?\[)
18013 ts (match-string 0))
18014 (replace-match "")
18015 (when (string-match
18016 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18018 (setq extra (match-string 1 ts))
18019 (when suppress-tmp-delay
18020 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18021 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18022 (setq with-hm t))
18023 (setq time0 (org-parse-time-string ts))
18024 (when (and updown
18025 (eq org-ts-what 'minute)
18026 (not current-prefix-arg))
18027 ;; This looks like s-up and s-down. Change by one rounding step.
18028 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18029 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18030 (setcar (cdr time0) (+ (nth 1 time0)
18031 (if (> n 0) (- rem) (- dm rem))))))
18032 (setq time
18033 (apply #'encode-time
18034 (or (car time0) 0)
18035 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18036 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18037 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18038 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18039 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18040 (nthcdr 6 time0)))
18041 (when (and (member org-ts-what '(hour minute))
18042 extra
18043 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18044 (setq extra (org-modify-ts-extra
18045 extra
18046 (if (eq org-ts-what 'hour) 2 5)
18047 n dm)))
18048 (when (integerp org-ts-what)
18049 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18050 (when (eq what 'calendar)
18051 (let ((cal-date (org-get-date-from-calendar)))
18052 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18053 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18054 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18055 (setcar time0 (or (car time0) 0))
18056 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18057 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18058 (setq time (apply 'encode-time time0))))
18059 ;; Insert the new time-stamp, and ensure point stays in the same
18060 ;; category as before (i.e. not after the last position in that
18061 ;; category).
18062 (let ((pos (point)))
18063 ;; Stay before inserted string. `save-excursion' is of no use.
18064 (setq org-last-changed-timestamp
18065 (org-insert-time-stamp time with-hm inactive nil nil extra))
18066 (goto-char pos))
18067 (save-match-data
18068 (looking-at org-ts-regexp3)
18069 (goto-char (cond
18070 ;; `day' category ends before `hour' if any, or at
18071 ;; the end of the day name.
18072 ((eq origin-cat 'day)
18073 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18074 ((eq origin-cat 'hour) (min (match-end 7) origin))
18075 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18076 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18077 ;; `year' and `month' have both fixed size: point
18078 ;; couldn't have moved into another part.
18079 (t origin))))
18080 ;; Update clock if on a CLOCK line.
18081 (org-clock-update-time-maybe)
18082 ;; Maybe adjust the closest clock in `org-clock-history'
18083 (when org-clock-adjust-closest
18084 (if (not (and (org-at-clock-log-p)
18085 (< 1 (length (delq nil (mapcar 'marker-position
18086 org-clock-history))))))
18087 (message "No clock to adjust")
18088 (cond ((save-excursion ; fix previous clock?
18089 (re-search-backward org-ts-regexp0 nil t)
18090 (looking-back (concat org-clock-string " \\[")
18091 (line-beginning-position)))
18092 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18093 ((save-excursion ; fix next clock?
18094 (re-search-backward org-ts-regexp0 nil t)
18095 (looking-at (concat org-ts-regexp0 "\\] =>")))
18096 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18097 (save-window-excursion
18098 ;; Find closest clock to point, adjust the previous/next one in history
18099 (let* ((p (save-excursion (org-back-to-heading t)))
18100 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18101 (clfixnth
18102 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18103 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18104 (if (not clfixpos)
18105 (message "No clock to adjust")
18106 (save-excursion
18107 (org-goto-marker-or-bmk clfixpos)
18108 (org-show-subtree)
18109 (when (re-search-forward clrgx nil t)
18110 (goto-char (match-beginning 1))
18111 (let (org-clock-adjust-closest)
18112 (org-timestamp-change n org-ts-what updown))
18113 (message "Clock adjusted in %s for heading: %s"
18114 (file-name-nondirectory (buffer-file-name))
18115 (org-get-heading t t)))))))))
18116 ;; Try to recenter the calendar window, if any.
18117 (when (and org-calendar-follow-timestamp-change
18118 (get-buffer-window "*Calendar*" t)
18119 (memq org-ts-what '(day month year)))
18120 (org-recenter-calendar (time-to-days time))))))
18122 (defun org-modify-ts-extra (s pos n dm)
18123 "Change the different parts of the lead-time and repeat fields in timestamp."
18124 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18125 ng h m new rem)
18126 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18127 (cond
18128 ((or (org-pos-in-match-range pos 2)
18129 (org-pos-in-match-range pos 3))
18130 (setq m (string-to-number (match-string 3 s))
18131 h (string-to-number (match-string 2 s)))
18132 (if (org-pos-in-match-range pos 2)
18133 (setq h (+ h n))
18134 (setq n (* dm (with-no-warnings (signum n))))
18135 (unless (= 0 (setq rem (% m dm)))
18136 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18137 (setq m (+ m n)))
18138 (when (< m 0) (setq m (+ m 60) h (1- h)))
18139 (when (> m 59) (setq m (- m 60) h (1+ h)))
18140 (setq h (mod h 24))
18141 (setq ng 1 new (format "-%02d:%02d" h m)))
18142 ((org-pos-in-match-range pos 6)
18143 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18144 ((org-pos-in-match-range pos 5)
18145 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18147 ((org-pos-in-match-range pos 9)
18148 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18149 ((org-pos-in-match-range pos 8)
18150 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18152 (when ng
18153 (setq s (concat
18154 (substring s 0 (match-beginning ng))
18156 (substring s (match-end ng))))))
18159 (defun org-recenter-calendar (d)
18160 "If the calendar is visible, recenter it to date D."
18161 (let ((cwin (get-buffer-window "*Calendar*" t)))
18162 (when cwin
18163 (let ((calendar-move-hook nil))
18164 (with-selected-window cwin
18165 (calendar-goto-date
18166 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18168 (defun org-goto-calendar (&optional arg)
18169 "Go to the Emacs calendar at the current date.
18170 If there is a time stamp in the current line, go to that date.
18171 A prefix ARG can be used to force the current date."
18172 (interactive "P")
18173 (let ((tsr org-ts-regexp) diff
18174 (calendar-move-hook nil)
18175 (calendar-view-holidays-initially-flag nil)
18176 (calendar-view-diary-initially-flag nil))
18177 (when (or (org-at-timestamp-p)
18178 (save-excursion
18179 (beginning-of-line 1)
18180 (looking-at (concat ".*" tsr))))
18181 (let ((d1 (time-to-days (current-time)))
18182 (d2 (time-to-days
18183 (org-time-string-to-time (match-string 1)))))
18184 (setq diff (- d2 d1))))
18185 (calendar)
18186 (calendar-goto-today)
18187 (when (and diff (not arg)) (calendar-forward-day diff))))
18189 (defun org-get-date-from-calendar ()
18190 "Return a list (month day year) of date at point in calendar."
18191 (with-current-buffer "*Calendar*"
18192 (save-match-data
18193 (calendar-cursor-to-date))))
18195 (defun org-date-from-calendar ()
18196 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18197 If there is already a time stamp at the cursor position, update it."
18198 (interactive)
18199 (if (org-at-timestamp-p t)
18200 (org-timestamp-change 0 'calendar)
18201 (let ((cal-date (org-get-date-from-calendar)))
18202 (org-insert-time-stamp
18203 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18205 (defcustom org-effort-durations
18206 `(("min" . 1)
18207 ("h" . 60)
18208 ("d" . ,(* 60 8))
18209 ("w" . ,(* 60 8 5))
18210 ("m" . ,(* 60 8 5 4))
18211 ("y" . ,(* 60 8 5 40)))
18212 "Conversion factor to minutes for an effort modifier.
18214 Each entry has the form (MODIFIER . MINUTES).
18216 In an effort string, a number followed by MODIFIER is multiplied
18217 by the specified number of MINUTES to obtain an effort in
18218 minutes.
18220 For example, if the value of this variable is ((\"hours\" . 60)), then an
18221 effort string \"2hours\" is equivalent to 120 minutes."
18222 :group 'org-agenda
18223 :version "25.1"
18224 :package-version '(Org . "8.3")
18225 :type '(alist :key-type (string :tag "Modifier")
18226 :value-type (number :tag "Minutes")))
18228 (defun org-minutes-to-clocksum-string (m)
18229 "Format number of minutes as a clocksum string.
18230 The format is determined by `org-time-clocksum-format',
18231 `org-time-clocksum-use-fractional' and
18232 `org-time-clocksum-fractional-format' and
18233 `org-time-clocksum-use-effort-durations'."
18234 (let ((clocksum "")
18235 (m (round m)) ; Don't allow fractions of minutes
18236 h d w mo y fmt n)
18237 (setq h (if org-time-clocksum-use-effort-durations
18238 (cdr (assoc "h" org-effort-durations)) 60)
18239 d (if org-time-clocksum-use-effort-durations
18240 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18241 w (if org-time-clocksum-use-effort-durations
18242 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18243 mo (if org-time-clocksum-use-effort-durations
18244 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18245 y (if org-time-clocksum-use-effort-durations
18246 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18247 ;; fractional format
18248 (if org-time-clocksum-use-fractional
18249 (cond
18250 ;; single format string
18251 ((stringp org-time-clocksum-fractional-format)
18252 (format org-time-clocksum-fractional-format (/ m (float h))))
18253 ;; choice of fractional formats for different time units
18254 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18255 (> (/ (truncate m) (* y d h)) 0))
18256 (format fmt (/ m (* y d (float h)))))
18257 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18258 (> (/ (truncate m) (* mo d h)) 0))
18259 (format fmt (/ m (* mo d (float h)))))
18260 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18261 (> (/ (truncate m) (* w d h)) 0))
18262 (format fmt (/ m (* w d (float h)))))
18263 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18264 (> (/ (truncate m) (* d h)) 0))
18265 (format fmt (/ m (* d (float h)))))
18266 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18267 (> (/ (truncate m) h) 0))
18268 (format fmt (/ m (float h))))
18269 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18270 (format fmt m))
18271 ;; fall back to smallest time unit with a format
18272 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18273 (format fmt (/ m (float h))))
18274 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18275 (format fmt (/ m (* d (float h)))))
18276 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18277 (format fmt (/ m (* w d (float h)))))
18278 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18279 (format fmt (/ m (* mo d (float h)))))
18280 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18281 (format fmt (/ m (* y d (float h))))))
18282 ;; standard (non-fractional) format, with single format string
18283 (if (stringp org-time-clocksum-format)
18284 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18285 ;; separate formats components
18286 (and (setq fmt (plist-get org-time-clocksum-format :years))
18287 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18288 (plist-get org-time-clocksum-format :require-years))
18289 (setq clocksum (concat clocksum (format fmt n))
18290 m (- m (* n y d h))))
18291 (and (setq fmt (plist-get org-time-clocksum-format :months))
18292 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18293 (plist-get org-time-clocksum-format :require-months))
18294 (setq clocksum (concat clocksum (format fmt n))
18295 m (- m (* n mo d h))))
18296 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18297 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18298 (plist-get org-time-clocksum-format :require-weeks))
18299 (setq clocksum (concat clocksum (format fmt n))
18300 m (- m (* n w d h))))
18301 (and (setq fmt (plist-get org-time-clocksum-format :days))
18302 (or (> (setq n (/ (truncate m) (* d h))) 0)
18303 (plist-get org-time-clocksum-format :require-days))
18304 (setq clocksum (concat clocksum (format fmt n))
18305 m (- m (* n d h))))
18306 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18307 (or (> (setq n (/ (truncate m) h)) 0)
18308 (plist-get org-time-clocksum-format :require-hours))
18309 (setq clocksum (concat clocksum (format fmt n))
18310 m (- m (* n h))))
18311 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18312 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18313 (setq clocksum (concat clocksum (format fmt m))))
18314 ;; return formatted time duration
18315 clocksum))))
18317 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18318 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18319 "Org mode version 8.0")
18321 (defun org-hours-to-clocksum-string (n)
18322 (org-minutes-to-clocksum-string (* n 60)))
18324 (defun org-hh:mm-string-to-minutes (s)
18325 "Convert a string H:MM to a number of minutes.
18326 If the string is just a number, interpret it as minutes.
18327 In fact, the first hh:mm or number in the string will be taken,
18328 there can be extra stuff in the string.
18329 If no number is found, the return value is 0."
18330 (cond
18331 ((integerp s) s)
18332 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18333 (+ (* (string-to-number (match-string 1 s)) 60)
18334 (string-to-number (match-string 2 s))))
18335 ((string-match "\\([0-9]+\\)" s)
18336 (string-to-number (match-string 1 s)))
18337 (t 0)))
18339 (defcustom org-image-actual-width t
18340 "Should we use the actual width of images when inlining them?
18342 When set to t, always use the image width.
18344 When set to a number, use imagemagick (when available) to set
18345 the image's width to this value.
18347 When set to a number in a list, try to get the width from any
18348 #+ATTR.* keyword if it matches a width specification like
18350 #+ATTR_HTML: :width 300px
18352 and fall back on that number if none is found.
18354 When set to nil, try to get the width from an #+ATTR.* keyword
18355 and fall back on the original width if none is found.
18357 This requires Emacs >= 24.1, build with imagemagick support."
18358 :group 'org-appearance
18359 :version "24.4"
18360 :package-version '(Org . "8.0")
18361 :type '(choice
18362 (const :tag "Use the image width" t)
18363 (integer :tag "Use a number of pixels")
18364 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18365 (const :tag "Use #+ATTR* or don't resize" nil)))
18367 (defcustom org-agenda-inhibit-startup nil
18368 "Inhibit startup when preparing agenda buffers.
18369 When this variable is t, the initialization of the Org agenda
18370 buffers is inhibited: e.g. the visibility state is not set, the
18371 tables are not re-aligned, etc."
18372 :type 'boolean
18373 :version "24.3"
18374 :group 'org-agenda)
18376 (defcustom org-agenda-ignore-properties nil
18377 "Avoid updating text properties when building the agenda.
18378 Properties are used to prepare buffers for effort estimates,
18379 appointments, statistics and subtree-local categories.
18380 If you don't use these in the agenda, you can add them to this
18381 list and agenda building will be a bit faster.
18382 The value is a list, with zero or more of the symbols `effort', `appt',
18383 `stats' or `category'."
18384 :type '(set :greedy t
18385 (const effort)
18386 (const appt)
18387 (const stats)
18388 (const category))
18389 :version "25.1"
18390 :package-version '(Org . "8.3")
18391 :group 'org-agenda)
18393 (defun org-duration-string-to-minutes (s &optional output-to-string)
18394 "Convert a duration string S to minutes.
18396 A bare number is interpreted as minutes, modifiers can be set by
18397 customizing `org-effort-durations' (which see).
18399 Entries containing a colon are interpreted as H:MM by
18400 `org-hh:mm-string-to-minutes'."
18401 (let ((result 0)
18402 (re (concat "\\([0-9.]+\\) *\\("
18403 (regexp-opt (mapcar 'car org-effort-durations))
18404 "\\)")))
18405 (while (string-match re s)
18406 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18407 (string-to-number (match-string 1 s))))
18408 (setq s (replace-match "" nil t s)))
18409 (setq result (floor result))
18410 (cl-incf result (org-hh:mm-string-to-minutes s))
18411 (if output-to-string (number-to-string result) result)))
18413 ;;;; Files
18415 (defun org-save-all-org-buffers ()
18416 "Save all Org-mode buffers without user confirmation."
18417 (interactive)
18418 (message "Saving all Org-mode buffers...")
18419 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18420 (when (featurep 'org-id) (org-id-locations-save))
18421 (message "Saving all Org-mode buffers... done"))
18423 (defun org-revert-all-org-buffers ()
18424 "Revert all Org-mode buffers.
18425 Prompt for confirmation when there are unsaved changes.
18426 Be sure you know what you are doing before letting this function
18427 overwrite your changes.
18429 This function is useful in a setup where one tracks org files
18430 with a version control system, to revert on one machine after pulling
18431 changes from another. I believe the procedure must be like this:
18433 1. M-x org-save-all-org-buffers
18434 2. Pull changes from the other machine, resolve conflicts
18435 3. M-x org-revert-all-org-buffers"
18436 (interactive)
18437 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18438 (user-error "Abort"))
18439 (save-excursion
18440 (save-window-excursion
18441 (dolist (b (buffer-list))
18442 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18443 (with-current-buffer b buffer-file-name))
18444 (pop-to-buffer-same-window b)
18445 (revert-buffer t 'no-confirm)))
18446 (when (and (featurep 'org-id) org-id-track-globally)
18447 (org-id-locations-load)))))
18449 ;;;; Agenda files
18451 ;;;###autoload
18452 (defun org-switchb (&optional arg)
18453 "Switch between Org buffers.
18455 With \\[universal-argument] prefix, restrict available buffers to files.
18457 With \\[universal-argument] \\[universal-argument] \
18458 prefix, restrict available buffers to agenda files."
18459 (interactive "P")
18460 (let ((blist (org-buffer-list
18461 (cond ((equal arg '(4)) 'files)
18462 ((equal arg '(16)) 'agenda)))))
18463 (pop-to-buffer-same-window
18464 (completing-read "Org buffer: "
18465 (mapcar #'list (mapcar #'buffer-name blist))
18466 nil t))))
18468 (defun org-buffer-list (&optional predicate exclude-tmp)
18469 "Return a list of Org buffers.
18470 PREDICATE can be `export', `files' or `agenda'.
18472 export restrict the list to Export buffers.
18473 files restrict the list to buffers visiting Org files.
18474 agenda restrict the list to buffers visiting agenda files.
18476 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18477 (let* ((bfn nil)
18478 (agenda-files (and (eq predicate 'agenda)
18479 (mapcar 'file-truename (org-agenda-files t))))
18480 (filter
18481 (cond
18482 ((eq predicate 'files)
18483 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18484 ((eq predicate 'export)
18485 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18486 ((eq predicate 'agenda)
18487 (lambda (b)
18488 (with-current-buffer b
18489 (and (derived-mode-p 'org-mode)
18490 (setq bfn (buffer-file-name b))
18491 (member (file-truename bfn) agenda-files)))))
18492 (t (lambda (b) (with-current-buffer b
18493 (or (derived-mode-p 'org-mode)
18494 (string-match "\\*Org .*Export"
18495 (buffer-name b)))))))))
18496 (delq nil
18497 (mapcar
18498 (lambda(b)
18499 (if (and (funcall filter b)
18500 (or (not exclude-tmp)
18501 (not (string-match "tmp" (buffer-name b)))))
18503 nil))
18504 (buffer-list)))))
18506 (defun org-agenda-files (&optional unrestricted archives)
18507 "Get the list of agenda files.
18508 Optional UNRESTRICTED means return the full list even if a restriction
18509 is currently in place.
18510 When ARCHIVES is t, include all archive files that are really being
18511 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18512 `org-agenda-archives-mode' is t."
18513 (let ((files
18514 (cond
18515 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18516 ((stringp org-agenda-files) (org-read-agenda-file-list))
18517 ((listp org-agenda-files) org-agenda-files)
18518 (t (error "Invalid value of `org-agenda-files'")))))
18519 (setq files (apply 'append
18520 (mapcar (lambda (f)
18521 (if (file-directory-p f)
18522 (directory-files
18523 f t org-agenda-file-regexp)
18524 (list f)))
18525 files)))
18526 (when org-agenda-skip-unavailable-files
18527 (setq files (delq nil
18528 (mapcar (function
18529 (lambda (file)
18530 (and (file-readable-p file) file)))
18531 files))))
18532 (when (or (eq archives t)
18533 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18534 (setq files (org-add-archive-files files)))
18535 files))
18537 (defun org-agenda-file-p (&optional file)
18538 "Return non-nil, if FILE is an agenda file.
18539 If FILE is omitted, use the file associated with the current
18540 buffer."
18541 (let ((fname (or file (buffer-file-name))))
18542 (and fname
18543 (member (file-truename fname)
18544 (mapcar #'file-truename (org-agenda-files t))))))
18546 (defun org-edit-agenda-file-list ()
18547 "Edit the list of agenda files.
18548 Depending on setup, this either uses customize to edit the variable
18549 `org-agenda-files', or it visits the file that is holding the list. In the
18550 latter case, the buffer is set up in a way that saving it automatically kills
18551 the buffer and restores the previous window configuration."
18552 (interactive)
18553 (if (stringp org-agenda-files)
18554 (let ((cw (current-window-configuration)))
18555 (find-file org-agenda-files)
18556 (setq-local org-window-configuration cw)
18557 (add-hook 'after-save-hook
18558 (lambda ()
18559 (set-window-configuration
18560 (prog1 org-window-configuration
18561 (kill-buffer (current-buffer))))
18562 (org-install-agenda-files-menu)
18563 (message "New agenda file list installed"))
18564 nil 'local)
18565 (message "%s" (substitute-command-keys
18566 "Edit list and finish with \\[save-buffer]")))
18567 (customize-variable 'org-agenda-files)))
18569 (defun org-store-new-agenda-file-list (list)
18570 "Set new value for the agenda file list and save it correctly."
18571 (if (stringp org-agenda-files)
18572 (let ((fe (org-read-agenda-file-list t)) b u)
18573 (while (setq b (find-buffer-visiting org-agenda-files))
18574 (kill-buffer b))
18575 (with-temp-file org-agenda-files
18576 (insert
18577 (mapconcat
18578 (lambda (f) ;; Keep un-expanded entries.
18579 (if (setq u (assoc f fe))
18580 (cdr u)
18582 list "\n")
18583 "\n")))
18584 (let ((org-mode-hook nil) (org-inhibit-startup t)
18585 (org-insert-mode-line-in-empty-file nil))
18586 (setq org-agenda-files list)
18587 (customize-save-variable 'org-agenda-files org-agenda-files))))
18589 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18590 "Read the list of agenda files from a file.
18591 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18592 filenames, used by `org-store-new-agenda-file-list' to write back
18593 un-expanded file names."
18594 (when (file-directory-p org-agenda-files)
18595 (error "`org-agenda-files' cannot be a single directory"))
18596 (when (stringp org-agenda-files)
18597 (with-temp-buffer
18598 (insert-file-contents org-agenda-files)
18599 (mapcar
18600 (lambda (f)
18601 (let ((e (expand-file-name (substitute-in-file-name f)
18602 org-directory)))
18603 (if pair-with-expansion
18604 (cons e f)
18605 e)))
18606 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18608 ;;;###autoload
18609 (defun org-cycle-agenda-files ()
18610 "Cycle through the files in `org-agenda-files'.
18611 If the current buffer visits an agenda file, find the next one in the list.
18612 If the current buffer does not, find the first agenda file."
18613 (interactive)
18614 (let* ((fs (or (org-agenda-files t)
18615 (user-error "No agenda files")))
18616 (files (copy-sequence fs))
18617 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18618 file)
18619 (when tcf
18620 (while (and (setq file (pop files))
18621 (not (equal (file-truename file) tcf)))))
18622 (find-file (car (or files fs)))
18623 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18625 (defun org-agenda-file-to-front (&optional to-end)
18626 "Move/add the current file to the top of the agenda file list.
18627 If the file is not present in the list, it is added to the front. If it is
18628 present, it is moved there. With optional argument TO-END, add/move to the
18629 end of the list."
18630 (interactive "P")
18631 (let ((org-agenda-skip-unavailable-files nil)
18632 (file-alist (mapcar (lambda (x)
18633 (cons (file-truename x) x))
18634 (org-agenda-files t)))
18635 (ctf (file-truename
18636 (or buffer-file-name
18637 (user-error "Please save the current buffer to a file"))))
18638 x had)
18639 (setq x (assoc ctf file-alist) had x)
18641 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18642 (if to-end
18643 (setq file-alist (append (delq x file-alist) (list x)))
18644 (setq file-alist (cons x (delq x file-alist))))
18645 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18646 (org-install-agenda-files-menu)
18647 (message "File %s to %s of agenda file list"
18648 (if had "moved" "added") (if to-end "end" "front"))))
18650 (defun org-remove-file (&optional file)
18651 "Remove current file from the list of files in variable `org-agenda-files'.
18652 These are the files which are being checked for agenda entries.
18653 Optional argument FILE means use this file instead of the current."
18654 (interactive)
18655 (let* ((org-agenda-skip-unavailable-files nil)
18656 (file (or file buffer-file-name
18657 (user-error "Current buffer does not visit a file")))
18658 (true-file (file-truename file))
18659 (afile (abbreviate-file-name file))
18660 (files (delq nil (mapcar
18661 (lambda (x)
18662 (unless (equal true-file
18663 (file-truename x))
18665 (org-agenda-files t)))))
18666 (if (not (= (length files) (length (org-agenda-files t))))
18667 (progn
18668 (org-store-new-agenda-file-list files)
18669 (org-install-agenda-files-menu)
18670 (message "Removed from Org Agenda list: %s" afile))
18671 (message "File was not in list: %s (not removed)" afile))))
18673 (defun org-file-menu-entry (file)
18674 (vector file (list 'find-file file) t))
18676 (defun org-check-agenda-file (file)
18677 "Make sure FILE exists. If not, ask user what to do."
18678 (unless (file-exists-p file)
18679 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18680 (abbreviate-file-name file))
18681 (let ((r (downcase (read-char-exclusive))))
18682 (cond
18683 ((equal r ?r)
18684 (org-remove-file file)
18685 (throw 'nextfile t))
18686 (t (user-error "Abort"))))))
18688 (defun org-get-agenda-file-buffer (file)
18689 "Get an agenda buffer visiting FILE.
18690 If the buffer needs to be created, add it to the list of buffers
18691 which might be released later."
18692 (let ((buf (org-find-base-buffer-visiting file)))
18693 (if buf
18694 buf ; just return it
18695 ;; Make a new buffer and remember it
18696 (setq buf (find-file-noselect file))
18697 (when buf (push buf org-agenda-new-buffers))
18698 buf)))
18700 (defun org-release-buffers (blist)
18701 "Release all buffers in list, asking the user for confirmation when needed.
18702 When a buffer is unmodified, it is just killed. When modified, it is saved
18703 \(if the user agrees) and then killed."
18704 (let (file)
18705 (dolist (buf blist)
18706 (setq file (buffer-file-name buf))
18707 (when (and (buffer-modified-p buf)
18708 file
18709 (y-or-n-p (format "Save file %s? " file)))
18710 (with-current-buffer buf (save-buffer)))
18711 (kill-buffer buf))))
18713 (defun org-agenda-prepare-buffers (files)
18714 "Create buffers for all agenda files, protect archived trees and comments."
18715 (interactive)
18716 (let ((pa '(:org-archived t))
18717 (pc '(:org-comment t))
18718 (pall '(:org-archived t :org-comment t))
18719 (inhibit-read-only t)
18720 (org-inhibit-startup org-agenda-inhibit-startup)
18721 (rea (concat ":" org-archive-tag ":"))
18722 re pos)
18723 (setq org-tag-alist-for-agenda nil
18724 org-tag-groups-alist-for-agenda nil)
18725 (save-excursion
18726 (save-restriction
18727 (dolist (file files)
18728 (catch 'nextfile
18729 (if (bufferp file)
18730 (set-buffer file)
18731 (org-check-agenda-file file)
18732 (set-buffer (org-get-agenda-file-buffer file)))
18733 (widen)
18734 (org-set-regexps-and-options 'tags-only)
18735 (setq pos (point))
18736 (or (memq 'category org-agenda-ignore-properties)
18737 (org-refresh-category-properties))
18738 (or (memq 'stats org-agenda-ignore-properties)
18739 (org-refresh-stats-properties))
18740 (or (memq 'effort org-agenda-ignore-properties)
18741 (org-refresh-effort-properties))
18742 (or (memq 'appt org-agenda-ignore-properties)
18743 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18744 (setq org-todo-keywords-for-agenda
18745 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18746 (setq org-done-keywords-for-agenda
18747 (append org-done-keywords-for-agenda org-done-keywords))
18748 (setq org-todo-keyword-alist-for-agenda
18749 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18750 (setq org-tag-alist-for-agenda
18751 (org-uniquify
18752 (append org-tag-alist-for-agenda
18753 org-current-tag-alist)))
18754 ;; Merge current file's tag groups into global
18755 ;; `org-tag-groups-alist-for-agenda'.
18756 (when org-group-tags
18757 (dolist (alist org-tag-groups-alist)
18758 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18759 (if old
18760 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18761 (push alist org-tag-groups-alist-for-agenda)))))
18762 (org-with-silent-modifications
18763 (save-excursion
18764 (remove-text-properties (point-min) (point-max) pall)
18765 (when org-agenda-skip-archived-trees
18766 (goto-char (point-min))
18767 (while (re-search-forward rea nil t)
18768 (when (org-at-heading-p t)
18769 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18770 (goto-char (point-min))
18771 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18772 (while (re-search-forward re nil t)
18773 (when (save-match-data (org-in-commented-heading-p t))
18774 (add-text-properties
18775 (match-beginning 0) (org-end-of-subtree t) pc)))))
18776 (goto-char pos)))))
18777 (setq org-todo-keywords-for-agenda
18778 (org-uniquify org-todo-keywords-for-agenda))
18779 (setq org-todo-keyword-alist-for-agenda
18780 (org-uniquify org-todo-keyword-alist-for-agenda))))
18783 ;;;; CDLaTeX minor mode
18785 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18786 "Keymap for the minor `org-cdlatex-mode'.")
18788 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18789 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18790 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18791 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18792 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18794 (defvar org-cdlatex-texmathp-advice-is-done nil
18795 "Flag remembering if we have applied the advice to texmathp already.")
18797 (define-minor-mode org-cdlatex-mode
18798 "Toggle the minor `org-cdlatex-mode'.
18799 This mode supports entering LaTeX environment and math in LaTeX fragments
18800 in Org-mode.
18801 \\{org-cdlatex-mode-map}"
18802 nil " OCDL" nil
18803 (when org-cdlatex-mode
18804 (require 'cdlatex)
18805 (run-hooks 'cdlatex-mode-hook)
18806 (cdlatex-compute-tables))
18807 (unless org-cdlatex-texmathp-advice-is-done
18808 (setq org-cdlatex-texmathp-advice-is-done t)
18809 (defadvice texmathp (around org-math-always-on activate)
18810 "Always return t in org-mode buffers.
18811 This is because we want to insert math symbols without dollars even outside
18812 the LaTeX math segments. If Orgmode thinks that point is actually inside
18813 an embedded LaTeX fragment, let texmathp do its job.
18814 \\[org-cdlatex-mode-map]"
18815 (interactive)
18816 (let (p)
18817 (cond
18818 ((not (derived-mode-p 'org-mode)) ad-do-it)
18819 ((eq this-command 'cdlatex-math-symbol)
18820 (setq ad-return-value t
18821 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18823 (let ((p (org-inside-LaTeX-fragment-p)))
18824 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18825 (setq ad-return-value t
18826 texmathp-why '("Org-mode embedded math" . 0))
18827 (when p ad-do-it)))))))))
18829 (defun turn-on-org-cdlatex ()
18830 "Unconditionally turn on `org-cdlatex-mode'."
18831 (org-cdlatex-mode 1))
18833 (defun org-try-cdlatex-tab ()
18834 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18835 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18836 - inside a LaTeX fragment, or
18837 - after the first word in a line, where an abbreviation expansion could
18838 insert a LaTeX environment."
18839 (when org-cdlatex-mode
18840 (cond
18841 ;; Before any word on the line: No expansion possible.
18842 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18843 ;; Just after first word on the line: Expand it. Make sure it
18844 ;; cannot happen on headlines, though.
18845 ((save-excursion
18846 (skip-chars-backward "a-zA-Z0-9*")
18847 (skip-chars-backward " \t")
18848 (and (bolp) (not (org-at-heading-p))))
18849 (cdlatex-tab) t)
18850 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18852 (defun org-cdlatex-underscore-caret (&optional _arg)
18853 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18854 Revert to the normal definition outside of these fragments."
18855 (interactive "P")
18856 (if (org-inside-LaTeX-fragment-p)
18857 (call-interactively 'cdlatex-sub-superscript)
18858 (let (org-cdlatex-mode)
18859 (call-interactively (key-binding (vector last-input-event))))))
18861 (defun org-cdlatex-math-modify (&optional _arg)
18862 "Execute `cdlatex-math-modify' in LaTeX fragments.
18863 Revert to the normal definition outside of these fragments."
18864 (interactive "P")
18865 (if (org-inside-LaTeX-fragment-p)
18866 (call-interactively 'cdlatex-math-modify)
18867 (let (org-cdlatex-mode)
18868 (call-interactively (key-binding (vector last-input-event))))))
18870 (defun org-cdlatex-environment-indent (&optional environment item)
18871 "Execute `cdlatex-environment' and indent the inserted environment.
18873 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18875 The inserted environment is indented to current indentation
18876 unless point is at the beginning of the line, in which the
18877 environment remains unintended."
18878 (interactive)
18879 ;; cdlatex-environment always return nil. Therefore, capture output
18880 ;; first and determine if an environment was selected.
18881 (let* ((beg (point-marker))
18882 (end (copy-marker (point) t))
18883 (inserted (progn
18884 (ignore-errors (cdlatex-environment environment item))
18885 (< beg end)))
18886 ;; Figure out how many lines to move forward after the
18887 ;; environment has been inserted.
18888 (lines (when inserted
18889 (save-excursion
18890 (- (cl-loop while (< beg (point))
18891 with x = 0
18892 do (forward-line -1)
18893 (cl-incf x)
18894 finally return x)
18895 (if (progn (goto-char beg)
18896 (and (progn (skip-chars-forward " \t") (eolp))
18897 (progn (skip-chars-backward " \t") (bolp))))
18898 1 0)))))
18899 (env (org-trim (delete-and-extract-region beg end))))
18900 (when inserted
18901 ;; Get indentation of next line unless at column 0.
18902 (let ((ind (if (bolp) 0
18903 (save-excursion
18904 (org-return-indent)
18905 (prog1 (org-get-indentation)
18906 (when (progn (skip-chars-forward " \t") (eolp))
18907 (delete-region beg (point)))))))
18908 (bol (progn (skip-chars-backward " \t") (bolp))))
18909 ;; Insert a newline before environment unless at column zero
18910 ;; to "escape" the current line. Insert a newline if
18911 ;; something is one the same line as \end{ENVIRONMENT}.
18912 (insert
18913 (concat (unless bol "\n") env
18914 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18915 (unless (zerop ind)
18916 (save-excursion
18917 (goto-char beg)
18918 (while (< (point) end)
18919 (unless (eolp) (indent-line-to ind))
18920 (forward-line))))
18921 (goto-char beg)
18922 (forward-line lines)
18923 (indent-line-to ind)))
18924 (set-marker beg nil)
18925 (set-marker end nil)))
18928 ;;;; LaTeX fragments
18930 (defun org-inside-LaTeX-fragment-p ()
18931 "Test if point is inside a LaTeX fragment.
18932 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18933 sequence appearing also before point.
18934 Even though the matchers for math are configurable, this function assumes
18935 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18936 delimiters are skipped when they have been removed by customization.
18937 The return value is nil, or a cons cell with the delimiter and the
18938 position of this delimiter.
18940 This function does a reasonably good job, but can locally be fooled by
18941 for example currency specifications. For example it will assume being in
18942 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18943 fragments that are properly closed, but during editing, we have to live
18944 with the uncertainty caused by missing closing delimiters. This function
18945 looks only before point, not after."
18946 (catch 'exit
18947 (let ((pos (point))
18948 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18949 (lim (progn
18950 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18951 (point)))
18952 dd-on str (start 0) m re)
18953 (goto-char pos)
18954 (when dodollar
18955 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18956 re (nth 1 (assoc "$" org-latex-regexps)))
18957 (while (string-match re str start)
18958 (cond
18959 ((= (match-end 0) (length str))
18960 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18961 ((= (match-end 0) (- (length str) 5))
18962 (throw 'exit nil))
18963 (t (setq start (match-end 0))))))
18964 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18965 (goto-char pos)
18966 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18967 (and (match-beginning 2) (throw 'exit nil))
18968 ;; count $$
18969 (while (re-search-backward "\\$\\$" lim t)
18970 (setq dd-on (not dd-on)))
18971 (goto-char pos)
18972 (when dd-on (cons "$$" m))))))
18974 (defun org-inside-latex-macro-p ()
18975 "Is point inside a LaTeX macro or its arguments?"
18976 (save-match-data
18977 (org-in-regexp
18978 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18980 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18981 "Build an overlay between BEG and END using IMAGE file.
18982 Argument IMAGETYPE is the extension of the displayed image,
18983 as a string. It defaults to \"png\"."
18984 (let ((ov (make-overlay beg end))
18985 (imagetype (or (intern imagetype) 'png)))
18986 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18987 (overlay-put ov 'evaporate t)
18988 (overlay-put ov
18989 'modification-hooks
18990 (list (lambda (o _flag _beg _end &optional _l)
18991 (delete-overlay o))))
18992 (overlay-put ov
18993 'display
18994 (list 'image :type imagetype :file image :ascent 'center))))
18996 (defun org--list-latex-overlays (&optional beg end)
18997 "List all Org LaTeX overlays in current buffer.
18998 Limit to overlays between BEG and END when those are provided."
18999 (cl-remove-if-not
19000 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19001 (overlays-in (or beg (point-min)) (or end (point-max)))))
19003 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19004 "Remove all overlays with LaTeX fragment images in current buffer.
19005 When optional arguments BEG and END are non-nil, remove all
19006 overlays between them instead. Return a non-nil value when some
19007 overlays were removed, nil otherwise."
19008 (let ((overlays (org--list-latex-overlays beg end)))
19009 (mapc #'delete-overlay overlays)
19010 overlays))
19012 (defun org-toggle-latex-fragment (&optional arg)
19013 "Preview the LaTeX fragment at point, or all locally or globally.
19015 If the cursor is on a LaTeX fragment, create the image and overlay
19016 it over the source code, if there is none. Remove it otherwise.
19017 If there is no fragment at point, display all fragments in the
19018 current section.
19020 With prefix ARG, preview or clear image for all fragments in the
19021 current subtree or in the whole buffer when used before the first
19022 headline. With a double prefix ARG \\[universal-argument] \
19023 \\[universal-argument] preview or clear images
19024 for all fragments in the buffer."
19025 (interactive "P")
19026 (when (display-graphic-p)
19027 (catch 'exit
19028 (save-excursion
19029 (let (beg end msg)
19030 (cond
19031 ((or (equal arg '(16))
19032 (and (equal arg '(4))
19033 (org-with-limited-levels (org-before-first-heading-p))))
19034 (if (org-remove-latex-fragment-image-overlays)
19035 (progn (message "LaTeX fragments images removed from buffer")
19036 (throw 'exit nil))
19037 (setq msg "Creating images for buffer...")))
19038 ((equal arg '(4))
19039 (org-with-limited-levels (org-back-to-heading t))
19040 (setq beg (point))
19041 (setq end (progn (org-end-of-subtree t) (point)))
19042 (if (org-remove-latex-fragment-image-overlays beg end)
19043 (progn
19044 (message "LaTeX fragment images removed from subtree")
19045 (throw 'exit nil))
19046 (setq msg "Creating images for subtree...")))
19047 ((let ((datum (org-element-context)))
19048 (when (memq (org-element-type datum)
19049 '(latex-environment latex-fragment))
19050 (setq beg (org-element-property :begin datum))
19051 (setq end (org-element-property :end datum))
19052 (if (org-remove-latex-fragment-image-overlays beg end)
19053 (progn (message "LaTeX fragment image removed")
19054 (throw 'exit nil))
19055 (setq msg "Creating image...")))))
19057 (org-with-limited-levels
19058 (setq beg (if (org-at-heading-p) (line-beginning-position)
19059 (outline-previous-heading)
19060 (point)))
19061 (setq end (progn (outline-next-heading) (point)))
19062 (if (org-remove-latex-fragment-image-overlays beg end)
19063 (progn
19064 (message "LaTeX fragment images removed from section")
19065 (throw 'exit nil))
19066 (setq msg "Creating images for section...")))))
19067 (let ((file (buffer-file-name (buffer-base-buffer))))
19068 (org-format-latex
19069 (concat org-preview-latex-image-directory "org-ltximg")
19070 beg end
19071 ;; Emacs cannot overlay images from remote hosts. Create
19072 ;; it in `temporary-file-directory' instead.
19073 (if (or (not file) (file-remote-p file))
19074 temporary-file-directory
19075 default-directory)
19076 'overlays msg 'forbuffer org-preview-latex-default-process))
19077 (message (concat msg "done")))))))
19079 (defun org-format-latex
19080 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19081 "Replace LaTeX fragments with links to an image.
19083 The function takes care of creating the replacement image.
19085 Only consider fragments between BEG and END when those are
19086 provided.
19088 When optional argument OVERLAYS is non-nil, display the image on
19089 top of the fragment instead of replacing it.
19091 PROCESSING-TYPE is the conversion method to use, as a symbol.
19093 Some of the options can be changed using the variable
19094 `org-format-latex-options', which see."
19095 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19096 (unless (eq processing-type 'verbatim)
19097 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19098 (cnt 0)
19099 checkdir-flag)
19100 (goto-char (or beg (point-min)))
19101 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19102 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19103 (overlay-recenter (or end (point-max))))
19104 (while (re-search-forward math-regexp end t)
19105 (unless (and overlays
19106 (eq (get-char-property (point) 'org-overlay-type)
19107 'org-latex-overlay))
19108 (let* ((context (org-element-context))
19109 (type (org-element-type context)))
19110 (when (memq type '(latex-environment latex-fragment))
19111 (let ((block-type (eq type 'latex-environment))
19112 (value (org-element-property :value context))
19113 (beg (org-element-property :begin context))
19114 (end (save-excursion
19115 (goto-char (org-element-property :end context))
19116 (skip-chars-backward " \r\t\n")
19117 (point))))
19118 (cond
19119 ((eq processing-type 'mathjax)
19120 ;; Prepare for MathJax processing.
19121 (if (not (string-match "\\`\\$\\$?" value))
19122 (goto-char end)
19123 (delete-region beg end)
19124 (if (string= (match-string 0 value) "$$")
19125 (insert "\\[" (substring value 2 -2) "\\]")
19126 (insert "\\(" (substring value 1 -1) "\\)"))))
19127 ((assq processing-type org-preview-latex-process-alist)
19128 ;; Process to an image.
19129 (cl-incf cnt)
19130 (goto-char beg)
19131 (let* ((processing-info
19132 (cdr (assq processing-type org-preview-latex-process-alist)))
19133 (face (face-at-point))
19134 ;; Get the colors from the face at point.
19136 (let ((color (plist-get org-format-latex-options
19137 :foreground)))
19138 (if (and forbuffer (eq color 'auto))
19139 (face-attribute face :foreground nil 'default)
19140 color)))
19142 (let ((color (plist-get org-format-latex-options
19143 :background)))
19144 (if (and forbuffer (eq color 'auto))
19145 (face-attribute face :background nil 'default)
19146 color)))
19147 (hash (sha1 (prin1-to-string
19148 (list org-format-latex-header
19149 org-latex-default-packages-alist
19150 org-latex-packages-alist
19151 org-format-latex-options
19152 forbuffer value fg bg))))
19153 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19154 (absprefix (expand-file-name prefix dir))
19155 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19156 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19157 (sep (and block-type "\n\n"))
19158 (link (concat sep "[[file:" linkfile "]]" sep))
19159 (options
19160 (org-combine-plists
19161 org-format-latex-options
19162 `(:foreground ,fg :background ,bg))))
19163 (when msg (message msg cnt))
19164 (unless checkdir-flag ; Ensure the directory exists.
19165 (setq checkdir-flag t)
19166 (let ((todir (file-name-directory absprefix)))
19167 (unless (file-directory-p todir)
19168 (make-directory todir t))))
19169 (unless (file-exists-p movefile)
19170 (org-create-formula-image
19171 value movefile options forbuffer processing-type))
19172 (if overlays
19173 (progn
19174 (dolist (o (overlays-in beg end))
19175 (when (eq (overlay-get o 'org-overlay-type)
19176 'org-latex-overlay)
19177 (delete-overlay o)))
19178 (org--format-latex-make-overlay beg end movefile imagetype)
19179 (goto-char end))
19180 (delete-region beg end)
19181 (insert
19182 (org-add-props link
19183 (list 'org-latex-src
19184 (replace-regexp-in-string "\"" "" value)
19185 'org-latex-src-embed-type
19186 (if block-type 'paragraph 'character)))))))
19187 ((eq processing-type 'mathml)
19188 ;; Process to MathML.
19189 (unless (org-format-latex-mathml-available-p)
19190 (user-error "LaTeX to MathML converter not configured"))
19191 (cl-incf cnt)
19192 (when msg (message msg cnt))
19193 (goto-char beg)
19194 (delete-region beg end)
19195 (insert (org-format-latex-as-mathml
19196 value block-type prefix dir)))
19198 (error "Unknown conversion process %s for LaTeX fragments"
19199 processing-type)))))))))))
19201 (defun org-create-math-formula (latex-frag &optional mathml-file)
19202 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19203 Use `org-latex-to-mathml-convert-command'. If the conversion is
19204 sucessful, return the portion between \"<math...> </math>\"
19205 elements otherwise return nil. When MATHML-FILE is specified,
19206 write the results in to that file. When invoked as an
19207 interactive command, prompt for LATEX-FRAG, with initial value
19208 set to the current active region and echo the results for user
19209 inspection."
19210 (interactive (list (let ((frag (when (org-region-active-p)
19211 (buffer-substring-no-properties
19212 (region-beginning) (region-end)))))
19213 (read-string "LaTeX Fragment: " frag nil frag))))
19214 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19215 (let* ((tmp-in-file
19216 (let ((file (file-relative-name
19217 (make-temp-name (expand-file-name "ltxmathml-in")))))
19218 (write-region latex-frag nil file)
19219 file))
19220 (tmp-out-file (file-relative-name
19221 (make-temp-name (expand-file-name "ltxmathml-out"))))
19222 (cmd (format-spec
19223 org-latex-to-mathml-convert-command
19224 `((?j . ,(and org-latex-to-mathml-jar-file
19225 (shell-quote-argument
19226 (expand-file-name
19227 org-latex-to-mathml-jar-file))))
19228 (?I . ,(shell-quote-argument tmp-in-file))
19229 (?i . ,latex-frag)
19230 (?o . ,(shell-quote-argument tmp-out-file)))))
19231 mathml shell-command-output)
19232 (when (called-interactively-p 'any)
19233 (unless (org-format-latex-mathml-available-p)
19234 (user-error "LaTeX to MathML converter not configured")))
19235 (message "Running %s" cmd)
19236 (setq shell-command-output (shell-command-to-string cmd))
19237 (setq mathml
19238 (when (file-readable-p tmp-out-file)
19239 (with-current-buffer (find-file-noselect tmp-out-file t)
19240 (goto-char (point-min))
19241 (when (re-search-forward
19242 (concat
19243 (regexp-quote
19244 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19245 "[^>]*?>"
19246 "\\(.\\|\n\\)*"
19247 "</math>")
19248 nil t)
19249 (prog1 (match-string 0) (kill-buffer))))))
19250 (cond
19251 (mathml
19252 (setq mathml
19253 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19254 (when mathml-file
19255 (write-region mathml nil mathml-file))
19256 (when (called-interactively-p 'any)
19257 (message mathml)))
19258 ((message "LaTeX to MathML conversion failed")
19259 (message shell-command-output)))
19260 (delete-file tmp-in-file)
19261 (when (file-exists-p tmp-out-file)
19262 (delete-file tmp-out-file))
19263 mathml))
19265 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19266 prefix &optional dir)
19267 "Use `org-create-math-formula' but check local cache first."
19268 (let* ((absprefix (expand-file-name prefix dir))
19269 (print-length nil) (print-level nil)
19270 (formula-id (concat
19271 "formula-"
19272 (sha1
19273 (prin1-to-string
19274 (list latex-frag
19275 org-latex-to-mathml-convert-command)))))
19276 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19277 (formula-cache-dir (file-name-directory formula-cache)))
19279 (unless (file-directory-p formula-cache-dir)
19280 (make-directory formula-cache-dir t))
19282 (unless (file-exists-p formula-cache)
19283 (org-create-math-formula latex-frag formula-cache))
19285 (if (file-exists-p formula-cache)
19286 ;; Successful conversion. Return the link to MathML file.
19287 (org-add-props
19288 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19289 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19290 'org-latex-src-embed-type (if latex-frag-type
19291 'paragraph 'character)))
19292 ;; Failed conversion. Return the LaTeX fragment verbatim
19293 latex-frag)))
19295 (declare-function org-export-get-backend "ox" (name))
19296 (declare-function org-export--get-global-options "ox" (&optional backend))
19297 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19298 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19299 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19300 (defun org-create-formula--latex-header ()
19301 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19302 (let ((info (org-combine-plists (org-export--get-global-options
19303 (org-export-get-backend 'latex))
19304 (org-export--get-inbuffer-options
19305 (org-export-get-backend 'latex)))))
19306 (org-latex-guess-babel-language
19307 (org-latex-guess-inputenc
19308 (org-splice-latex-header
19309 org-format-latex-header
19310 org-latex-default-packages-alist
19311 org-latex-packages-alist t
19312 (plist-get info :latex-header)))
19313 info)))
19315 (defun org--get-display-dpi ()
19316 "Get the DPI of the display.
19318 Assumes that the display has the same pixel width in the
19319 horizontal and vertical directions."
19320 (if (display-graphic-p)
19321 (round (/ (display-pixel-height)
19322 (/ (display-mm-height) 25.4)))
19323 (error "Attempt to calculate the dpi of a non-graphic display")))
19325 (defun org-create-formula-image
19326 (string tofile options buffer &optional processing-type)
19327 "Create an image from LaTeX source using external processes.
19329 The LaTeX STRING is saved to a temporary LaTeX file, then
19330 converted to an image file by process PROCESSING-TYPE defined in
19331 `org-preview-latex-process-alist'. A nil value defaults to
19332 `org-preview-latex-default-process'.
19334 The generated image file is eventually moved to TOFILE.
19336 The OPTIONS argument controls the size, foreground color and
19337 background color of the generated image.
19339 When BUFFER non-nil, this function is used for LaTeX previewing.
19340 Otherwise, it is used to deal with LaTeX snippets showed in
19341 a HTML file."
19342 (let* ((processing-type (or processing-type
19343 org-preview-latex-default-process))
19344 (processing-info
19345 (cdr (assq processing-type org-preview-latex-process-alist)))
19346 (programs (plist-get processing-info :programs))
19347 (error-message (or (plist-get processing-info :message) ""))
19348 (use-xcolor (plist-get processing-info :use-xcolor))
19349 (image-input-type (plist-get processing-info :image-input-type))
19350 (image-output-type (plist-get processing-info :image-output-type))
19351 (post-clean (or (plist-get processing-info :post-clean)
19352 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19353 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19354 (latex-header (or (plist-get processing-info :latex-header)
19355 (org-create-formula--latex-header)))
19356 (latex-compiler (plist-get processing-info :latex-compiler))
19357 (image-converter (plist-get processing-info :image-converter))
19358 (tmpdir temporary-file-directory)
19359 (texfilebase (make-temp-name
19360 (expand-file-name "orgtex" tmpdir)))
19361 (texfile (concat texfilebase ".tex"))
19362 (font-height (face-attribute 'default :height nil))
19363 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19364 '(1.0 . 1.0)))
19365 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19366 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19367 (dpi (* scale (floor (if buffer font-height 140.0))))
19368 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19369 "Black"))
19370 (bg (or (plist-get options (if buffer :background :html-background))
19371 "Transparent"))
19372 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19373 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19374 (dolist (program programs)
19375 (org-check-external-command program error-message))
19376 (if use-xcolor
19377 (progn (if (eq fg 'default)
19378 (setq fg (org-latex-color :foreground))
19379 (setq fg (org-latex-color-format fg)))
19380 (if (eq bg 'default)
19381 (setq bg (org-latex-color :background))
19382 (setq bg (org-latex-color-format
19383 (if (string= bg "Transparent") "white" bg))))
19384 (with-temp-file texfile
19385 (insert latex-header)
19386 (insert "\n\\begin{document}\n"
19387 "\\definecolor{fg}{rgb}{" fg "}\n"
19388 "\\definecolor{bg}{rgb}{" bg "}\n"
19389 "\n\\pagecolor{bg}\n"
19390 "\n{\\color{fg}\n"
19391 string
19392 "\n}\n"
19393 "\n\\end{document}\n")))
19394 (if (eq fg 'default)
19395 (setq fg (org-dvipng-color :foreground))
19396 (unless (string= fg "Transparent")
19397 (setq fg (org-dvipng-color-format fg))))
19398 (if (eq bg 'default)
19399 (setq bg (org-dvipng-color :background))
19400 (unless (string= bg "Transparent")
19401 (setq bg (org-dvipng-color-format bg))))
19402 (with-temp-file texfile
19403 (insert latex-header)
19404 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19406 (let* ((err-msg (format "Please adjust '%s' part of \
19407 `org-preview-latex-process-alist'."
19408 processing-type))
19409 (image-input-file
19410 (org-compile-file
19411 texfile latex-compiler image-input-type err-msg log-buf))
19412 (image-output-file
19413 (org-compile-file
19414 image-input-file image-converter image-output-type err-msg log-buf
19415 `((?F . ,(shell-quote-argument fg))
19416 (?B . ,(shell-quote-argument bg))
19417 (?D . ,(shell-quote-argument (format "%s" dpi)))
19418 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19419 (copy-file image-output-file tofile 'replace)
19420 (dolist (e post-clean)
19421 (when (file-exists-p (concat texfilebase e))
19422 (delete-file (concat texfilebase e))))
19423 image-output-file)))
19425 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19426 "Fill a LaTeX header template TPL.
19427 In the template, the following place holders will be recognized:
19429 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19430 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19431 [PACKAGES] \\usepackage statements for PKG
19432 [NO-PACKAGES] do not include PKG
19433 [EXTRA] the string EXTRA
19434 [NO-EXTRA] do not include EXTRA
19436 For backward compatibility, if both the positive and the negative place
19437 holder is missing, the positive one (without the \"NO-\") will be
19438 assumed to be present at the end of the template.
19439 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19440 EXTRA is a string.
19441 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19442 (let (rpl (end ""))
19443 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19444 (setq rpl (if (or (match-end 1) (not def-pkg))
19445 "" (org-latex-packages-to-string def-pkg snippets-p t))
19446 tpl (replace-match rpl t t tpl))
19447 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19449 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19450 (setq rpl (if (or (match-end 1) (not pkg))
19451 "" (org-latex-packages-to-string pkg snippets-p t))
19452 tpl (replace-match rpl t t tpl))
19453 (when pkg (setq end
19454 (concat end "\n"
19455 (org-latex-packages-to-string pkg snippets-p)))))
19457 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19458 (setq rpl (if (or (match-end 1) (not extra))
19459 "" (concat extra "\n"))
19460 tpl (replace-match rpl t t tpl))
19461 (when (and extra (string-match "\\S-" extra))
19462 (setq end (concat end "\n" extra))))
19464 (if (string-match "\\S-" end)
19465 (concat tpl "\n" end)
19466 tpl)))
19468 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19469 "Turn an alist of packages into a string with the \\usepackage macros."
19470 (setq pkg (mapconcat (lambda(p)
19471 (cond
19472 ((stringp p) p)
19473 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19474 (format "%% Package %s omitted" (cadr p)))
19475 ((equal "" (car p))
19476 (format "\\usepackage{%s}" (cadr p)))
19478 (format "\\usepackage[%s]{%s}"
19479 (car p) (cadr p)))))
19481 "\n"))
19482 (if newline (concat pkg "\n") pkg))
19484 (defun org-dvipng-color (attr)
19485 "Return a RGB color specification for dvipng."
19486 (apply #'format "rgb %s %s %s"
19487 (mapcar #'org-normalize-color
19488 (color-values (face-attribute 'default attr nil)))))
19490 (defun org-dvipng-color-format (color-name)
19491 "Convert COLOR-NAME to a RGB color value for dvipng."
19492 (apply 'format "rgb %s %s %s"
19493 (mapcar 'org-normalize-color
19494 (color-values color-name))))
19496 (defun org-latex-color (attr)
19497 "Return a RGB color for the LaTeX color package."
19498 (apply #'format "%s,%s,%s"
19499 (mapcar #'org-normalize-color
19500 (color-values (face-attribute 'default attr nil)))))
19502 (defun org-latex-color-format (color-name)
19503 "Convert COLOR-NAME to a RGB color value."
19504 (apply 'format "%s,%s,%s"
19505 (mapcar 'org-normalize-color
19506 (color-values color-name))))
19508 (defun org-normalize-color (value)
19509 "Return string to be used as color value for an RGB component."
19510 (format "%g" (/ value 65535.0)))
19514 ;; Image display
19516 (defvar-local org-inline-image-overlays nil)
19518 (defun org-toggle-inline-images (&optional include-linked)
19519 "Toggle the display of inline images.
19520 INCLUDE-LINKED is passed to `org-display-inline-images'."
19521 (interactive "P")
19522 (if org-inline-image-overlays
19523 (progn
19524 (org-remove-inline-images)
19525 (when (called-interactively-p 'interactive)
19526 (message "Inline image display turned off")))
19527 (org-display-inline-images include-linked)
19528 (when (called-interactively-p 'interactive)
19529 (message (if org-inline-image-overlays
19530 (format "%d images displayed inline"
19531 (length org-inline-image-overlays))
19532 "No images to display inline")))))
19534 (defun org-redisplay-inline-images ()
19535 "Refresh the display of inline images."
19536 (interactive)
19537 (if (not org-inline-image-overlays)
19538 (org-toggle-inline-images)
19539 (org-toggle-inline-images)
19540 (org-toggle-inline-images)))
19542 (defun org-display-inline-images (&optional include-linked refresh beg end)
19543 "Display inline images.
19545 An inline image is a link which follows either of these
19546 conventions:
19548 1. Its path is a file with an extension matching return value
19549 from `image-file-name-regexp' and it has no contents.
19551 2. Its description consists in a single link of the previous
19552 type.
19554 When optional argument INCLUDE-LINKED is non-nil, also links with
19555 a text description part will be inlined. This can be nice for
19556 a quick look at those images, but it does not reflect what
19557 exported files will look like.
19559 When optional argument REFRESH is non-nil, refresh existing
19560 images between BEG and END. This will create new image displays
19561 only if necessary. BEG and END default to the buffer
19562 boundaries."
19563 (interactive "P")
19564 (when (display-graphic-p)
19565 (unless refresh
19566 (org-remove-inline-images)
19567 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19568 (org-with-wide-buffer
19569 (goto-char (or beg (point-min)))
19570 (let ((case-fold-search t)
19571 (file-extension-re (image-file-name-regexp)))
19572 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19573 (let ((link (save-match-data (org-element-context))))
19574 ;; Check if we're at an inline image.
19575 (when (and (equal (org-element-property :type link) "file")
19576 (or include-linked
19577 (not (org-element-property :contents-begin link)))
19578 (let ((parent (org-element-property :parent link)))
19579 (or (not (eq (org-element-type parent) 'link))
19580 (not (cdr (org-element-contents parent)))))
19581 (org-string-match-p file-extension-re
19582 (org-element-property :path link)))
19583 (let ((file (expand-file-name
19584 (org-link-unescape
19585 (org-element-property :path link)))))
19586 (when (file-exists-p file)
19587 (let ((width
19588 ;; Apply `org-image-actual-width' specifications.
19589 (cond
19590 ((not (image-type-available-p 'imagemagick)) nil)
19591 ((eq org-image-actual-width t) nil)
19592 ((listp org-image-actual-width)
19594 ;; First try to find a width among
19595 ;; attributes associated to the paragraph
19596 ;; containing link.
19597 (let ((paragraph
19598 (let ((e link))
19599 (while (and (setq e (org-element-property
19600 :parent e))
19601 (not (eq (org-element-type e)
19602 'paragraph))))
19603 e)))
19604 (when paragraph
19605 (save-excursion
19606 (goto-char (org-element-property :begin paragraph))
19607 (when
19608 (re-search-forward
19609 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19610 (org-element-property
19611 :post-affiliated paragraph)
19613 (string-to-number (match-string 1))))))
19614 ;; Otherwise, fall-back to provided number.
19615 (car org-image-actual-width)))
19616 ((numberp org-image-actual-width)
19617 org-image-actual-width)))
19618 (old (get-char-property-and-overlay
19619 (org-element-property :begin link)
19620 'org-image-overlay)))
19621 (if (and (car-safe old) refresh)
19622 (image-refresh (overlay-get (cdr old) 'display))
19623 (let ((image (create-image file
19624 (and width 'imagemagick)
19626 :width width)))
19627 (when image
19628 (let* ((link
19629 ;; If inline image is the description
19630 ;; of another link, be sure to
19631 ;; consider the latter as the one to
19632 ;; apply the overlay on.
19633 (let ((parent
19634 (org-element-property :parent link)))
19635 (if (eq (org-element-type parent) 'link)
19636 parent
19637 link)))
19638 (ov (make-overlay
19639 (org-element-property :begin link)
19640 (progn
19641 (goto-char
19642 (org-element-property :end link))
19643 (skip-chars-backward " \t")
19644 (point)))))
19645 (overlay-put ov 'display image)
19646 (overlay-put ov 'face 'default)
19647 (overlay-put ov 'org-image-overlay t)
19648 (overlay-put
19649 ov 'modification-hooks
19650 (list 'org-display-inline-remove-overlay))
19651 (push ov org-inline-image-overlays)))))))))))))))
19653 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19654 "Remove inline-display overlay if a corresponding region is modified."
19655 (let ((inhibit-modification-hooks t))
19656 (when (and ov after)
19657 (delete ov org-inline-image-overlays)
19658 (delete-overlay ov))))
19660 (defun org-remove-inline-images ()
19661 "Remove inline display of images."
19662 (interactive)
19663 (mapc #'delete-overlay org-inline-image-overlays)
19664 (setq org-inline-image-overlays nil))
19666 ;;;; Key bindings
19668 ;; Outline functions from `outline-mode-prefix-map'
19669 ;; that can be remapped in Org:
19670 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19671 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19672 (define-key org-mode-map [remap outline-forward-same-level]
19673 'org-forward-heading-same-level)
19674 (define-key org-mode-map [remap outline-backward-same-level]
19675 'org-backward-heading-same-level)
19676 (define-key org-mode-map [remap outline-show-branches]
19677 'org-kill-note-or-show-branches)
19678 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19679 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19680 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19681 (define-key org-mode-map [remap outline-next-visible-heading]
19682 'org-next-visible-heading)
19683 (define-key org-mode-map [remap outline-previous-visible-heading]
19684 'org-previous-visible-heading)
19685 (define-key org-mode-map [remap show-children] 'org-show-children)
19687 ;; Outline functions from `outline-mode-prefix-map' that can not
19688 ;; be remapped in Org:
19690 ;; - the column "key binding" shows whether the Outline function is still
19691 ;; available in Org mode on the same key that it has been bound to in
19692 ;; Outline mode:
19693 ;; - "overridden": key used for a different functionality in Org mode
19694 ;; - else: key still bound to the same Outline function in Org mode
19696 ;; | Outline function | key binding | Org replacement |
19697 ;; |------------------------------------+-------------+--------------------------|
19698 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19699 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19700 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19701 ;; | `show-entry' | overridden | no replacement |
19702 ;; | `show-branches' | `C-c C-k' | still same function |
19703 ;; | `show-subtree' | overridden | visibility cycling |
19704 ;; | `show-all' | overridden | no replacement |
19705 ;; | `hide-subtree' | overridden | visibility cycling |
19706 ;; | `hide-body' | overridden | no replacement |
19707 ;; | `hide-entry' | overridden | visibility cycling |
19708 ;; | `hide-leaves' | overridden | no replacement |
19709 ;; | `hide-sublevels' | overridden | no replacement |
19710 ;; | `hide-other' | overridden | no replacement |
19712 ;; Make `C-c C-x' a prefix key
19713 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19715 ;; TAB key with modifiers
19716 (org-defkey org-mode-map "\C-i" 'org-cycle)
19717 (org-defkey org-mode-map [(tab)] 'org-cycle)
19718 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19719 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19720 ;; The following line is necessary under Suse GNU/Linux
19721 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19722 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19723 (define-key org-mode-map [backtab] 'org-shifttab)
19725 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19726 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19727 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19729 ;; Cursor keys with modifiers
19730 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19731 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19732 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19733 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19735 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19736 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19737 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19738 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19739 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19740 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19742 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19743 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19744 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19745 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19747 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19748 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19749 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19750 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19752 ;; Babel keys
19753 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19754 (dolist (pair org-babel-key-bindings)
19755 (define-key org-babel-map (car pair) (cdr pair)))
19757 ;;; Extra keys for tty access.
19758 ;; We only set them when really needed because otherwise the
19759 ;; menus don't show the simple keys
19761 (when (or org-use-extra-keys (not window-system))
19762 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19763 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19764 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19765 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19766 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19767 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19768 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19769 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19770 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19771 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19772 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19773 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19774 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19775 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19776 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19777 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19778 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19779 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19780 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19781 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19782 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19783 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19784 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19785 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19786 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19787 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19788 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19789 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19791 ;; All the other keys
19793 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19794 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19795 (if (boundp 'narrow-map)
19796 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19797 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19798 (if (boundp 'narrow-map)
19799 (org-defkey narrow-map "b" 'org-narrow-to-block)
19800 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19801 (if (boundp 'narrow-map)
19802 (org-defkey narrow-map "e" 'org-narrow-to-element)
19803 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19804 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19805 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19806 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19807 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19808 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19809 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19810 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19811 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19812 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19813 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19814 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19815 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19816 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19817 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19818 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19819 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19820 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19821 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19822 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19823 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19824 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19825 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19826 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19827 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19828 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19829 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19830 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19831 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19832 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19833 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19834 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19835 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19836 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19837 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19838 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19839 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19840 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19841 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19842 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19843 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19844 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19845 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19846 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19847 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19848 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19849 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19850 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19851 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19852 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19853 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19854 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19855 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19856 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19857 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19858 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19859 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19860 (org-defkey org-mode-map "\C-c^" 'org-sort)
19861 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19862 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19863 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19864 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19865 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19866 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19867 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19868 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19869 (org-defkey org-mode-map "\C-m" 'org-return)
19870 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19871 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19872 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19873 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19874 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19875 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19876 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19877 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19878 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19879 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19880 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19881 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19882 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19883 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19884 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19885 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19886 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19887 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19888 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19889 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19890 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19891 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19892 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19893 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19894 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19896 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19897 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19898 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19900 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19901 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19902 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19903 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19904 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19905 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19906 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19907 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19908 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19909 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19910 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19911 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19912 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19913 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19914 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19915 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19916 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19917 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19918 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19919 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19920 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19921 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19923 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19924 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19925 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19926 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19927 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19929 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19931 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19933 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19934 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19936 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19939 (defconst org-speed-commands-default
19941 ("Outline Navigation")
19942 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19943 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19944 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19945 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19946 ("F" . org-next-block)
19947 ("B" . org-previous-block)
19948 ("u" . (org-speed-move-safe 'outline-up-heading))
19949 ("j" . org-goto)
19950 ("g" . (org-refile t))
19951 ("Outline Visibility")
19952 ("c" . org-cycle)
19953 ("C" . org-shifttab)
19954 (" " . org-display-outline-path)
19955 ("s" . org-narrow-to-subtree)
19956 ("=" . org-columns)
19957 ("Outline Structure Editing")
19958 ("U" . org-metaup)
19959 ("D" . org-metadown)
19960 ("r" . org-metaright)
19961 ("l" . org-metaleft)
19962 ("R" . org-shiftmetaright)
19963 ("L" . org-shiftmetaleft)
19964 ("i" . (progn (forward-char 1) (call-interactively
19965 'org-insert-heading-respect-content)))
19966 ("^" . org-sort)
19967 ("w" . org-refile)
19968 ("a" . org-archive-subtree-default-with-confirmation)
19969 ("@" . org-mark-subtree)
19970 ("#" . org-toggle-comment)
19971 ("Clock Commands")
19972 ("I" . org-clock-in)
19973 ("O" . org-clock-out)
19974 ("Meta Data Editing")
19975 ("t" . org-todo)
19976 ("," . (org-priority))
19977 ("0" . (org-priority ?\ ))
19978 ("1" . (org-priority ?A))
19979 ("2" . (org-priority ?B))
19980 ("3" . (org-priority ?C))
19981 (":" . org-set-tags-command)
19982 ("e" . org-set-effort)
19983 ("E" . org-inc-effort)
19984 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19985 (org-entry-put (point) "APPT_WARNTIME" m)))
19986 ("Agenda Views etc")
19987 ("v" . org-agenda)
19988 ("/" . org-sparse-tree)
19989 ("Misc")
19990 ("o" . org-open-at-point)
19991 ("?" . org-speed-command-help)
19992 ("<" . (org-agenda-set-restriction-lock 'subtree))
19993 (">" . (org-agenda-remove-restriction-lock))
19995 "The default speed commands.")
19997 (defun org-print-speed-command (e)
19998 (if (> (length (car e)) 1)
19999 (progn
20000 (princ "\n")
20001 (princ (car e))
20002 (princ "\n")
20003 (princ (make-string (length (car e)) ?-))
20004 (princ "\n"))
20005 (princ (car e))
20006 (princ " ")
20007 (if (symbolp (cdr e))
20008 (princ (symbol-name (cdr e)))
20009 (prin1 (cdr e)))
20010 (princ "\n")))
20012 (defun org-speed-command-help ()
20013 "Show the available speed commands."
20014 (interactive)
20015 (if (not org-use-speed-commands)
20016 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20017 (with-output-to-temp-buffer "*Help*"
20018 (princ "User-defined Speed commands\n===========================\n")
20019 (mapc #'org-print-speed-command org-speed-commands-user)
20020 (princ "\n")
20021 (princ "Built-in Speed commands\n=======================\n")
20022 (mapc #'org-print-speed-command org-speed-commands-default))
20023 (with-current-buffer "*Help*"
20024 (setq truncate-lines t))))
20026 (defun org-speed-move-safe (cmd)
20027 "Execute CMD, but make sure that the cursor always ends up in a headline.
20028 If not, return to the original position and throw an error."
20029 (interactive)
20030 (let ((pos (point)))
20031 (call-interactively cmd)
20032 (unless (and (bolp) (org-at-heading-p))
20033 (goto-char pos)
20034 (error "Boundary reached while executing %s" cmd))))
20036 (defvar org-self-insert-command-undo-counter 0)
20038 (defvar org-table-auto-blank-field) ; defined in org-table.el
20039 (defvar org-speed-command nil)
20041 (defun org-speed-command-activate (keys)
20042 "Hook for activating single-letter speed commands.
20043 `org-speed-commands-default' specifies a minimal command set.
20044 Use `org-speed-commands-user' for further customization."
20045 (when (or (and (bolp) (looking-at org-outline-regexp))
20046 (and (functionp org-use-speed-commands)
20047 (funcall org-use-speed-commands)))
20048 (cdr (assoc keys (append org-speed-commands-user
20049 org-speed-commands-default)))))
20051 (defun org-babel-speed-command-activate (keys)
20052 "Hook for activating single-letter code block commands."
20053 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20054 (cdr (assoc keys org-babel-key-bindings))))
20056 (defcustom org-speed-command-hook
20057 '(org-speed-command-default-hook org-babel-speed-command-hook)
20058 "Hook for activating speed commands at strategic locations.
20059 Hook functions are called in sequence until a valid handler is
20060 found.
20062 Each hook takes a single argument, a user-pressed command key
20063 which is also a `self-insert-command' from the global map.
20065 Within the hook, examine the cursor position and the command key
20066 and return nil or a valid handler as appropriate. Handler could
20067 be one of an interactive command, a function, or a form.
20069 Set `org-use-speed-commands' to non-nil value to enable this
20070 hook. The default setting is `org-speed-command-activate'."
20071 :group 'org-structure
20072 :version "24.1"
20073 :type 'hook)
20075 (defun org-self-insert-command (N)
20076 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20077 If the cursor is in a table looking at whitespace, the whitespace is
20078 overwritten, and the table is not marked as requiring realignment."
20079 (interactive "p")
20080 (org-check-before-invisible-edit 'insert)
20081 (cond
20082 ((and org-use-speed-commands
20083 (let ((kv (this-command-keys-vector)))
20084 (setq org-speed-command
20085 (run-hook-with-args-until-success
20086 'org-speed-command-hook
20087 (make-string 1 (aref kv (1- (length kv))))))))
20088 (cond
20089 ((commandp org-speed-command)
20090 (setq this-command org-speed-command)
20091 (call-interactively org-speed-command))
20092 ((functionp org-speed-command)
20093 (funcall org-speed-command))
20094 ((and org-speed-command (listp org-speed-command))
20095 (eval org-speed-command))
20096 (t (let (org-use-speed-commands)
20097 (call-interactively 'org-self-insert-command)))))
20098 ((and
20099 (org-at-table-p)
20100 (progn
20101 ;; Check if we blank the field, and if that triggers align.
20102 (and (featurep 'org-table) org-table-auto-blank-field
20103 (memq last-command
20104 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20105 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20106 ;; Got extra space, this field does not determine
20107 ;; column width.
20108 (let (org-table-may-need-update) (org-table-blank-field))
20109 ;; No extra space, this field may determine column
20110 ;; width.
20111 (org-table-blank-field)))
20113 (eq N 1)
20114 (looking-at "[^|\n]* \\( \\)|"))
20115 ;; There is room for insertion without re-aligning the table.
20116 (delete-region (match-beginning 1) (match-end 1))
20117 (self-insert-command N))
20119 (setq org-table-may-need-update t)
20120 (self-insert-command N)
20121 (org-fix-tags-on-the-fly)
20122 (when org-self-insert-cluster-for-undo
20123 (if (not (eq last-command 'org-self-insert-command))
20124 (setq org-self-insert-command-undo-counter 1)
20125 (if (>= org-self-insert-command-undo-counter 20)
20126 (setq org-self-insert-command-undo-counter 1)
20127 (and (> org-self-insert-command-undo-counter 0)
20128 buffer-undo-list (listp buffer-undo-list)
20129 (not (cadr buffer-undo-list)) ; remove nil entry
20130 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20131 (setq org-self-insert-command-undo-counter
20132 (1+ org-self-insert-command-undo-counter))))))))
20134 (defun org-check-before-invisible-edit (kind)
20135 "Check is editing if kind KIND would be dangerous with invisible text around.
20136 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20137 ;; First, try to get out of here as quickly as possible, to reduce overhead
20138 (when (and org-catch-invisible-edits
20139 (or (not (boundp 'visible-mode)) (not visible-mode))
20140 (or (get-char-property (point) 'invisible)
20141 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20142 ;; OK, we need to take a closer look
20143 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20144 (invisible-before-point (unless (bobp) (get-char-property
20145 (1- (point)) 'invisible)))
20146 (border-and-ok-direction
20148 ;; Check if we are acting predictably before invisible text
20149 (and invisible-at-point (not invisible-before-point)
20150 (memq kind '(insert delete-backward)))
20151 ;; Check if we are acting predictably after invisible text
20152 ;; This works not well, and I have turned it off. It seems
20153 ;; better to always show and stop after invisible text.
20154 ;; (and (not invisible-at-point) invisible-before-point
20155 ;; (memq kind '(insert delete)))
20157 (when (or (memq invisible-at-point '(outline org-hide-block t))
20158 (memq invisible-before-point '(outline org-hide-block t)))
20159 (when (eq org-catch-invisible-edits 'error)
20160 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20161 (if (and org-custom-properties-overlays
20162 (y-or-n-p "Display invisible properties in this buffer? "))
20163 (org-toggle-custom-properties-visibility)
20164 ;; Make the area visible
20165 (save-excursion
20166 (when invisible-before-point
20167 (goto-char (previous-single-char-property-change
20168 (point) 'invisible)))
20169 (outline-show-subtree))
20170 (cond
20171 ((eq org-catch-invisible-edits 'show)
20172 ;; That's it, we do the edit after showing
20173 (message
20174 "Unfolding invisible region around point before editing")
20175 (sit-for 1))
20176 ((and (eq org-catch-invisible-edits 'smart)
20177 border-and-ok-direction)
20178 (message "Unfolding invisible region around point before editing"))
20180 ;; Don't do the edit, make the user repeat it in full visibility
20181 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20183 (defun org-fix-tags-on-the-fly ()
20184 (when (and (equal (char-after (point-at-bol)) ?*)
20185 (org-at-heading-p))
20186 (org-align-tags-here org-tags-column)))
20188 (defun org-delete-backward-char (N)
20189 "Like `delete-backward-char', insert whitespace at field end in tables.
20190 When deleting backwards, in tables this function will insert whitespace in
20191 front of the next \"|\" separator, to keep the table aligned. The table will
20192 still be marked for re-alignment if the field did fill the entire column,
20193 because, in this case the deletion might narrow the column."
20194 (interactive "p")
20195 (save-match-data
20196 (org-check-before-invisible-edit 'delete-backward)
20197 (if (and (org-at-table-p)
20198 (eq N 1)
20199 (string-match "|" (buffer-substring (point-at-bol) (point)))
20200 (looking-at ".*?|"))
20201 (let ((pos (point))
20202 (noalign (looking-at "[^|\n\r]* |"))
20203 (c org-table-may-need-update))
20204 (backward-delete-char N)
20205 (unless overwrite-mode
20206 (skip-chars-forward "^|")
20207 (insert " ")
20208 (goto-char (1- pos)))
20209 ;; noalign: if there were two spaces at the end, this field
20210 ;; does not determine the width of the column.
20211 (when noalign (setq org-table-may-need-update c)))
20212 (backward-delete-char N)
20213 (org-fix-tags-on-the-fly))))
20215 (defun org-delete-char (N)
20216 "Like `delete-char', but insert whitespace at field end in tables.
20217 When deleting characters, in tables this function will insert whitespace in
20218 front of the next \"|\" separator, to keep the table aligned. The table will
20219 still be marked for re-alignment if the field did fill the entire column,
20220 because, in this case the deletion might narrow the column."
20221 (interactive "p")
20222 (save-match-data
20223 (org-check-before-invisible-edit 'delete)
20224 (if (and (org-at-table-p)
20225 (not (bolp))
20226 (not (= (char-after) ?|))
20227 (eq N 1))
20228 (if (looking-at ".*?|")
20229 (let ((pos (point))
20230 (noalign (looking-at "[^|\n\r]* |"))
20231 (c org-table-may-need-update))
20232 (replace-match
20233 (concat (substring (match-string 0) 1 -1) " |") nil t)
20234 (goto-char pos)
20235 ;; noalign: if there were two spaces at the end, this field
20236 ;; does not determine the width of the column.
20237 (when noalign (setq org-table-may-need-update c)))
20238 (delete-char N))
20239 (delete-char N)
20240 (org-fix-tags-on-the-fly))))
20242 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20243 (put 'org-self-insert-command 'delete-selection
20244 (lambda ()
20245 (not (run-hook-with-args-until-success
20246 'self-insert-uses-region-functions))))
20247 (put 'orgtbl-self-insert-command 'delete-selection
20248 (lambda ()
20249 (not (run-hook-with-args-until-success
20250 'self-insert-uses-region-functions))))
20251 (put 'org-delete-char 'delete-selection 'supersede)
20252 (put 'org-delete-backward-char 'delete-selection 'supersede)
20253 (put 'org-yank 'delete-selection 'yank)
20255 ;; Make `flyspell-mode' delay after some commands
20256 (put 'org-self-insert-command 'flyspell-delayed t)
20257 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20258 (put 'org-delete-char 'flyspell-delayed t)
20259 (put 'org-delete-backward-char 'flyspell-delayed t)
20261 ;; Make pabbrev-mode expand after org-mode commands
20262 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20263 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20265 (defun org-remap (map &rest commands)
20266 "In MAP, remap the functions given in COMMANDS.
20267 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20268 (let (new old)
20269 (while commands
20270 (setq old (pop commands) new (pop commands))
20271 (if (fboundp 'command-remapping)
20272 (org-defkey map (vector 'remap old) new)
20273 (substitute-key-definition old new map global-map)))))
20275 (defun org-transpose-words ()
20276 "Transpose words for Org.
20277 This uses the `org-mode-transpose-word-syntax-table' syntax
20278 table, which interprets characters in `org-emphasis-alist' as
20279 word constituents."
20280 (interactive)
20281 (with-syntax-table org-mode-transpose-word-syntax-table
20282 (call-interactively 'transpose-words)))
20283 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20285 (when (eq org-enable-table-editor 'optimized)
20286 ;; If the user wants maximum table support, we need to hijack
20287 ;; some standard editing functions
20288 (org-remap org-mode-map
20289 'self-insert-command 'org-self-insert-command
20290 'delete-char 'org-delete-char
20291 'delete-backward-char 'org-delete-backward-char)
20292 (org-defkey org-mode-map "|" 'org-force-self-insert))
20294 (defvar org-ctrl-c-ctrl-c-hook nil
20295 "Hook for functions attaching themselves to `C-c C-c'.
20297 This can be used to add additional functionality to the C-c C-c
20298 key which executes context-dependent commands. This hook is run
20299 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20300 run after the last test.
20302 Each function will be called with no arguments. The function
20303 must check if the context is appropriate for it to act. If yes,
20304 it should do its thing and then return a non-nil value. If the
20305 context is wrong, just do nothing and return nil.")
20307 (defvar org-ctrl-c-ctrl-c-final-hook nil
20308 "Hook for functions attaching themselves to `C-c C-c'.
20310 This can be used to add additional functionality to the C-c C-c
20311 key which executes context-dependent commands. This hook is run
20312 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20313 before the first test.
20315 Each function will be called with no arguments. The function
20316 must check if the context is appropriate for it to act. If yes,
20317 it should do its thing and then return a non-nil value. If the
20318 context is wrong, just do nothing and return nil.")
20320 (defvar org-tab-first-hook nil
20321 "Hook for functions to attach themselves to TAB.
20322 See `org-ctrl-c-ctrl-c-hook' for more information.
20323 This hook runs as the first action when TAB is pressed, even before
20324 `org-cycle' messes around with the `outline-regexp' to cater for
20325 inline tasks and plain list item folding.
20326 If any function in this hook returns t, any other actions that
20327 would have been caused by TAB (such as table field motion or visibility
20328 cycling) will not occur.")
20330 (defvar org-tab-after-check-for-table-hook nil
20331 "Hook for functions to attach themselves to TAB.
20332 See `org-ctrl-c-ctrl-c-hook' for more information.
20333 This hook runs after it has been established that the cursor is not in a
20334 table, but before checking if the cursor is in a headline or if global cycling
20335 should be done.
20336 If any function in this hook returns t, not other actions like visibility
20337 cycling will be done.")
20339 (defvar org-tab-after-check-for-cycling-hook nil
20340 "Hook for functions to attach themselves to TAB.
20341 See `org-ctrl-c-ctrl-c-hook' for more information.
20342 This hook runs after it has been established that not table field motion and
20343 not visibility should be done because of current context. This is probably
20344 the place where a package like yasnippets can hook in.")
20346 (defvar org-tab-before-tab-emulation-hook nil
20347 "Hook for functions to attach themselves to TAB.
20348 See `org-ctrl-c-ctrl-c-hook' for more information.
20349 This hook runs after every other options for TAB have been exhausted, but
20350 before indentation and \t insertion takes place.")
20352 (defvar org-metaleft-hook nil
20353 "Hook for functions attaching themselves to `M-left'.
20354 See `org-ctrl-c-ctrl-c-hook' for more information.")
20355 (defvar org-metaright-hook nil
20356 "Hook for functions attaching themselves to `M-right'.
20357 See `org-ctrl-c-ctrl-c-hook' for more information.")
20358 (defvar org-metaup-hook nil
20359 "Hook for functions attaching themselves to `M-up'.
20360 See `org-ctrl-c-ctrl-c-hook' for more information.")
20361 (defvar org-metadown-hook nil
20362 "Hook for functions attaching themselves to `M-down'.
20363 See `org-ctrl-c-ctrl-c-hook' for more information.")
20364 (defvar org-shiftmetaleft-hook nil
20365 "Hook for functions attaching themselves to `M-S-left'.
20366 See `org-ctrl-c-ctrl-c-hook' for more information.")
20367 (defvar org-shiftmetaright-hook nil
20368 "Hook for functions attaching themselves to `M-S-right'.
20369 See `org-ctrl-c-ctrl-c-hook' for more information.")
20370 (defvar org-shiftmetaup-hook nil
20371 "Hook for functions attaching themselves to `M-S-up'.
20372 See `org-ctrl-c-ctrl-c-hook' for more information.")
20373 (defvar org-shiftmetadown-hook nil
20374 "Hook for functions attaching themselves to `M-S-down'.
20375 See `org-ctrl-c-ctrl-c-hook' for more information.")
20376 (defvar org-metareturn-hook nil
20377 "Hook for functions attaching themselves to `M-RET'.
20378 See `org-ctrl-c-ctrl-c-hook' for more information.")
20379 (defvar org-shiftup-hook nil
20380 "Hook for functions attaching themselves to `S-up'.
20381 See `org-ctrl-c-ctrl-c-hook' for more information.")
20382 (defvar org-shiftup-final-hook nil
20383 "Hook for functions attaching themselves to `S-up'.
20384 This one runs after all other options except shift-select have been excluded.
20385 See `org-ctrl-c-ctrl-c-hook' for more information.")
20386 (defvar org-shiftdown-hook nil
20387 "Hook for functions attaching themselves to `S-down'.
20388 See `org-ctrl-c-ctrl-c-hook' for more information.")
20389 (defvar org-shiftdown-final-hook nil
20390 "Hook for functions attaching themselves to `S-down'.
20391 This one runs after all other options except shift-select have been excluded.
20392 See `org-ctrl-c-ctrl-c-hook' for more information.")
20393 (defvar org-shiftleft-hook nil
20394 "Hook for functions attaching themselves to `S-left'.
20395 See `org-ctrl-c-ctrl-c-hook' for more information.")
20396 (defvar org-shiftleft-final-hook nil
20397 "Hook for functions attaching themselves to `S-left'.
20398 This one runs after all other options except shift-select have been excluded.
20399 See `org-ctrl-c-ctrl-c-hook' for more information.")
20400 (defvar org-shiftright-hook nil
20401 "Hook for functions attaching themselves to `S-right'.
20402 See `org-ctrl-c-ctrl-c-hook' for more information.")
20403 (defvar org-shiftright-final-hook nil
20404 "Hook for functions attaching themselves to `S-right'.
20405 This one runs after all other options except shift-select have been excluded.
20406 See `org-ctrl-c-ctrl-c-hook' for more information.")
20408 (defun org-modifier-cursor-error ()
20409 "Throw an error, a modified cursor command was applied in wrong context."
20410 (user-error "This command is active in special context like tables, headlines or items"))
20412 (defun org-shiftselect-error ()
20413 "Throw an error because Shift-Cursor command was applied in wrong context."
20414 (if (and (boundp 'shift-select-mode) shift-select-mode)
20415 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20416 (user-error "This command works only in special context like headlines or timestamps")))
20418 (defun org-call-for-shift-select (cmd)
20419 (let ((this-command-keys-shift-translated t))
20420 (call-interactively cmd)))
20422 (defun org-shifttab (&optional arg)
20423 "Global visibility cycling or move to previous table field.
20424 Call `org-table-previous-field' within a table.
20425 When ARG is nil, cycle globally through visibility states.
20426 When ARG is a numeric prefix, show contents of this level."
20427 (interactive "P")
20428 (cond
20429 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20430 ((integerp arg)
20431 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20432 (message "Content view to level: %d" arg)
20433 (org-content (prefix-numeric-value arg2))
20434 (org-cycle-show-empty-lines t)
20435 (setq org-cycle-global-status 'overview)))
20436 (t (call-interactively 'org-global-cycle))))
20438 (defun org-shiftmetaleft ()
20439 "Promote subtree or delete table column.
20440 Calls `org-promote-subtree', `org-outdent-item-tree', or
20441 `org-table-delete-column', depending on context. See the
20442 individual commands for more information."
20443 (interactive)
20444 (cond
20445 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20446 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20447 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20448 ((if (not (org-region-active-p)) (org-at-item-p)
20449 (save-excursion (goto-char (region-beginning))
20450 (org-at-item-p)))
20451 (call-interactively 'org-outdent-item-tree))
20452 (t (org-modifier-cursor-error))))
20454 (defun org-shiftmetaright ()
20455 "Demote subtree or insert table column.
20456 Calls `org-demote-subtree', `org-indent-item-tree', or
20457 `org-table-insert-column', depending on context. See the
20458 individual commands for more information."
20459 (interactive)
20460 (cond
20461 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20462 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20463 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20464 ((if (not (org-region-active-p)) (org-at-item-p)
20465 (save-excursion (goto-char (region-beginning))
20466 (org-at-item-p)))
20467 (call-interactively 'org-indent-item-tree))
20468 (t (org-modifier-cursor-error))))
20470 (defun org-shiftmetaup (&optional _arg)
20471 "Drag the line at point up.
20472 In a table, kill the current row.
20473 On a clock timestamp, update the value of the timestamp like `S-<up>'
20474 but also adjust the previous clocked item in the clock history.
20475 Everywhere else, drag the line at point up."
20476 (interactive "P")
20477 (cond
20478 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20479 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20480 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20481 (call-interactively 'org-timestamp-up)))
20482 (t (call-interactively 'org-drag-line-backward))))
20484 (defun org-shiftmetadown (&optional _arg)
20485 "Drag the line at point down.
20486 In a table, insert an empty row at the current line.
20487 On a clock timestamp, update the value of the timestamp like `S-<down>'
20488 but also adjust the previous clocked item in the clock history.
20489 Everywhere else, drag the line at point down."
20490 (interactive "P")
20491 (cond
20492 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20493 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20494 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20495 (call-interactively 'org-timestamp-down)))
20496 (t (call-interactively 'org-drag-line-forward))))
20498 (defsubst org-hidden-tree-error ()
20499 (user-error
20500 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20502 (defun org-metaleft (&optional _arg)
20503 "Promote heading, list item at point or move table column left.
20505 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20506 depending on context. With no specific context, calls the Emacs
20507 default `backward-word'. See the individual commands for more
20508 information.
20510 This function runs the hook `org-metaleft-hook' as a first step,
20511 and returns at first non-nil value."
20512 (interactive "P")
20513 (cond
20514 ((run-hook-with-args-until-success 'org-metaleft-hook))
20515 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20516 ((org-with-limited-levels
20517 (or (org-at-heading-p)
20518 (and (org-region-active-p)
20519 (save-excursion
20520 (goto-char (region-beginning))
20521 (org-at-heading-p)))))
20522 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20523 (call-interactively 'org-do-promote))
20524 ;; At an inline task.
20525 ((org-at-heading-p)
20526 (call-interactively 'org-inlinetask-promote))
20527 ((or (org-at-item-p)
20528 (and (org-region-active-p)
20529 (save-excursion
20530 (goto-char (region-beginning))
20531 (org-at-item-p))))
20532 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20533 (call-interactively 'org-outdent-item))
20534 (t (call-interactively 'backward-word))))
20536 (defun org-metaright (&optional _arg)
20537 "Demote heading, list item at point or move table column right.
20539 In front of a drawer or a block keyword, indent it correctly.
20541 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20542 `org-indnet-drawer' or `org-indent-block' depending on context.
20543 With no specific context, calls the Emacs default `forward-word'.
20544 See the individual commands for more information.
20546 This function runs the hook `org-metaright-hook' as a first step,
20547 and returns at first non-nil value."
20548 (interactive "P")
20549 (cond
20550 ((run-hook-with-args-until-success 'org-metaright-hook))
20551 ((org-at-table-p) (call-interactively 'org-table-move-column))
20552 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20553 ((org-at-block-p) (call-interactively 'org-indent-block))
20554 ((org-with-limited-levels
20555 (or (org-at-heading-p)
20556 (and (org-region-active-p)
20557 (save-excursion
20558 (goto-char (region-beginning))
20559 (org-at-heading-p)))))
20560 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20561 (call-interactively 'org-do-demote))
20562 ;; At an inline task.
20563 ((org-at-heading-p)
20564 (call-interactively 'org-inlinetask-demote))
20565 ((or (org-at-item-p)
20566 (and (org-region-active-p)
20567 (save-excursion
20568 (goto-char (region-beginning))
20569 (org-at-item-p))))
20570 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20571 (call-interactively 'org-indent-item))
20572 (t (call-interactively 'forward-word))))
20574 (defun org-check-for-hidden (what)
20575 "Check if there are hidden headlines/items in the current visual line.
20576 WHAT can be either `headlines' or `items'. If the current line is
20577 an outline or item heading and it has a folded subtree below it,
20578 this function returns t, nil otherwise."
20579 (let ((re (cond
20580 ((eq what 'headlines) org-outline-regexp-bol)
20581 ((eq what 'items) (org-item-beginning-re))
20582 (t (error "This should not happen"))))
20583 beg end)
20584 (save-excursion
20585 (catch 'exit
20586 (unless (org-region-active-p)
20587 (setq beg (point-at-bol))
20588 (beginning-of-line 2)
20589 (while (and (not (eobp)) ;; this is like `next-line'
20590 (get-char-property (1- (point)) 'invisible))
20591 (beginning-of-line 2))
20592 (setq end (point))
20593 (goto-char beg)
20594 (goto-char (point-at-eol))
20595 (setq end (max end (point)))
20596 (while (re-search-forward re end t)
20597 (when (get-char-property (match-beginning 0) 'invisible)
20598 (throw 'exit t))))
20599 nil))))
20601 (defun org-metaup (&optional _arg)
20602 "Move subtree up or move table row up.
20603 Calls `org-move-subtree-up' or `org-table-move-row' or
20604 `org-move-item-up', depending on context. See the individual commands
20605 for more information."
20606 (interactive "P")
20607 (cond
20608 ((run-hook-with-args-until-success 'org-metaup-hook))
20609 ((org-region-active-p)
20610 (let* ((a (min (region-beginning) (region-end)))
20611 (b (1- (max (region-beginning) (region-end))))
20612 (c (save-excursion (goto-char a)
20613 (move-beginning-of-line 0)))
20614 (d (save-excursion (goto-char a)
20615 (move-end-of-line 0) (point))))
20616 (transpose-regions a b c d)
20617 (goto-char c)))
20618 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20619 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20620 ((org-at-item-p) (call-interactively 'org-move-item-up))
20621 (t (org-drag-element-backward))))
20623 (defun org-metadown (&optional _arg)
20624 "Move subtree down or move table row down.
20625 Calls `org-move-subtree-down' or `org-table-move-row' or
20626 `org-move-item-down', depending on context. See the individual
20627 commands for more information."
20628 (interactive "P")
20629 (cond
20630 ((run-hook-with-args-until-success 'org-metadown-hook))
20631 ((org-region-active-p)
20632 (let* ((a (min (region-beginning) (region-end)))
20633 (b (max (region-beginning) (region-end)))
20634 (c (save-excursion (goto-char b)
20635 (move-beginning-of-line 1)))
20636 (d (save-excursion (goto-char b)
20637 (move-end-of-line 1) (1+ (point)))))
20638 (transpose-regions a b c d)
20639 (goto-char d)))
20640 ((org-at-table-p) (call-interactively 'org-table-move-row))
20641 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20642 ((org-at-item-p) (call-interactively 'org-move-item-down))
20643 (t (org-drag-element-forward))))
20645 (defun org-shiftup (&optional arg)
20646 "Increase item in timestamp or increase priority of current headline.
20647 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20648 depending on context. See the individual commands for more information."
20649 (interactive "P")
20650 (cond
20651 ((run-hook-with-args-until-success 'org-shiftup-hook))
20652 ((and org-support-shift-select (org-region-active-p))
20653 (org-call-for-shift-select 'previous-line))
20654 ((org-at-timestamp-p t)
20655 (call-interactively (if org-edit-timestamp-down-means-later
20656 'org-timestamp-down 'org-timestamp-up)))
20657 ((and (not (eq org-support-shift-select 'always))
20658 org-enable-priority-commands
20659 (org-at-heading-p))
20660 (call-interactively 'org-priority-up))
20661 ((and (not org-support-shift-select) (org-at-item-p))
20662 (call-interactively 'org-previous-item))
20663 ((org-clocktable-try-shift 'up arg))
20664 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20665 (org-support-shift-select
20666 (org-call-for-shift-select 'previous-line))
20667 (t (org-shiftselect-error))))
20669 (defun org-shiftdown (&optional arg)
20670 "Decrease item in timestamp or decrease priority of current headline.
20671 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20672 depending on context. See the individual commands for more information."
20673 (interactive "P")
20674 (cond
20675 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20676 ((and org-support-shift-select (org-region-active-p))
20677 (org-call-for-shift-select 'next-line))
20678 ((org-at-timestamp-p t)
20679 (call-interactively (if org-edit-timestamp-down-means-later
20680 'org-timestamp-up 'org-timestamp-down)))
20681 ((and (not (eq org-support-shift-select 'always))
20682 org-enable-priority-commands
20683 (org-at-heading-p))
20684 (call-interactively 'org-priority-down))
20685 ((and (not org-support-shift-select) (org-at-item-p))
20686 (call-interactively 'org-next-item))
20687 ((org-clocktable-try-shift 'down arg))
20688 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20689 (org-support-shift-select
20690 (org-call-for-shift-select 'next-line))
20691 (t (org-shiftselect-error))))
20693 (defun org-shiftright (&optional arg)
20694 "Cycle the thing at point or in the current line, depending on context.
20695 Depending on context, this does one of the following:
20697 - switch a timestamp at point one day into the future
20698 - on a headline, switch to the next TODO keyword.
20699 - on an item, switch entire list to the next bullet type
20700 - on a property line, switch to the next allowed value
20701 - on a clocktable definition line, move time block into the future"
20702 (interactive "P")
20703 (cond
20704 ((run-hook-with-args-until-success 'org-shiftright-hook))
20705 ((and org-support-shift-select (org-region-active-p))
20706 (org-call-for-shift-select 'forward-char))
20707 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20708 ((and (not (eq org-support-shift-select 'always))
20709 (org-at-heading-p))
20710 (let ((org-inhibit-logging
20711 (not org-treat-S-cursor-todo-selection-as-state-change))
20712 (org-inhibit-blocking
20713 (not org-treat-S-cursor-todo-selection-as-state-change)))
20714 (org-call-with-arg 'org-todo 'right)))
20715 ((or (and org-support-shift-select
20716 (not (eq org-support-shift-select 'always))
20717 (org-at-item-bullet-p))
20718 (and (not org-support-shift-select) (org-at-item-p)))
20719 (org-call-with-arg 'org-cycle-list-bullet nil))
20720 ((and (not (eq org-support-shift-select 'always))
20721 (org-at-property-p))
20722 (call-interactively 'org-property-next-allowed-value))
20723 ((org-clocktable-try-shift 'right arg))
20724 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20725 (org-support-shift-select
20726 (org-call-for-shift-select 'forward-char))
20727 (t (org-shiftselect-error))))
20729 (defun org-shiftleft (&optional arg)
20730 "Cycle the thing at point or in the current line, depending on context.
20731 Depending on context, this does one of the following:
20733 - switch a timestamp at point one day into the past
20734 - on a headline, switch to the previous TODO keyword.
20735 - on an item, switch entire list to the previous bullet type
20736 - on a property line, switch to the previous allowed value
20737 - on a clocktable definition line, move time block into the past"
20738 (interactive "P")
20739 (cond
20740 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20741 ((and org-support-shift-select (org-region-active-p))
20742 (org-call-for-shift-select 'backward-char))
20743 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20744 ((and (not (eq org-support-shift-select 'always))
20745 (org-at-heading-p))
20746 (let ((org-inhibit-logging
20747 (not org-treat-S-cursor-todo-selection-as-state-change))
20748 (org-inhibit-blocking
20749 (not org-treat-S-cursor-todo-selection-as-state-change)))
20750 (org-call-with-arg 'org-todo 'left)))
20751 ((or (and org-support-shift-select
20752 (not (eq org-support-shift-select 'always))
20753 (org-at-item-bullet-p))
20754 (and (not org-support-shift-select) (org-at-item-p)))
20755 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20756 ((and (not (eq org-support-shift-select 'always))
20757 (org-at-property-p))
20758 (call-interactively 'org-property-previous-allowed-value))
20759 ((org-clocktable-try-shift 'left arg))
20760 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20761 (org-support-shift-select
20762 (org-call-for-shift-select 'backward-char))
20763 (t (org-shiftselect-error))))
20765 (defun org-shiftcontrolright ()
20766 "Switch to next TODO set."
20767 (interactive)
20768 (cond
20769 ((and org-support-shift-select (org-region-active-p))
20770 (org-call-for-shift-select 'forward-word))
20771 ((and (not (eq org-support-shift-select 'always))
20772 (org-at-heading-p))
20773 (org-call-with-arg 'org-todo 'nextset))
20774 (org-support-shift-select
20775 (org-call-for-shift-select 'forward-word))
20776 (t (org-shiftselect-error))))
20778 (defun org-shiftcontrolleft ()
20779 "Switch to previous TODO set."
20780 (interactive)
20781 (cond
20782 ((and org-support-shift-select (org-region-active-p))
20783 (org-call-for-shift-select 'backward-word))
20784 ((and (not (eq org-support-shift-select 'always))
20785 (org-at-heading-p))
20786 (org-call-with-arg 'org-todo 'previousset))
20787 (org-support-shift-select
20788 (org-call-for-shift-select 'backward-word))
20789 (t (org-shiftselect-error))))
20791 (defun org-shiftcontrolup (&optional n)
20792 "Change timestamps synchronously up in CLOCK log lines.
20793 Optional argument N tells to change by that many units."
20794 (interactive "P")
20795 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20796 (let (org-support-shift-select)
20797 (org-clock-timestamps-up n))
20798 (user-error "Not at a clock log")))
20800 (defun org-shiftcontroldown (&optional n)
20801 "Change timestamps synchronously down in CLOCK log lines.
20802 Optional argument N tells to change by that many units."
20803 (interactive "P")
20804 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20805 (let (org-support-shift-select)
20806 (org-clock-timestamps-down n))
20807 (user-error "Not at a clock log")))
20809 (defun org-increase-number-at-point (&optional inc)
20810 "Increment the number at point.
20811 With an optional prefix numeric argument INC, increment using
20812 this numeric value."
20813 (interactive "p")
20814 (if (not (number-at-point))
20815 (user-error "Not on a number")
20816 (unless inc (setq inc 1))
20817 (let ((pos (point))
20818 (beg (skip-chars-backward "-+^/*0-9eE."))
20819 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20820 (setq nap (buffer-substring-no-properties
20821 (+ pos beg) (+ pos beg end)))
20822 (delete-region (+ pos beg) (+ pos beg end))
20823 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20824 (when (org-at-table-p)
20825 (org-table-align)
20826 (org-table-end-of-field 1))))
20828 (defun org-decrease-number-at-point (&optional inc)
20829 "Decrement the number at point.
20830 With an optional prefix numeric argument INC, decrement using
20831 this numeric value."
20832 (interactive "p")
20833 (org-increase-number-at-point (- (or inc 1))))
20835 (defun org-ctrl-c-ret ()
20836 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20837 (interactive)
20838 (cond
20839 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20840 (t (call-interactively 'org-insert-heading))))
20842 (defun org-find-visible ()
20843 (let ((s (point)))
20844 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20845 (get-char-property s 'invisible)))
20847 (defun org-find-invisible ()
20848 (let ((s (point)))
20849 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20850 (not (get-char-property s 'invisible))))
20853 (defun org-copy-visible (beg end)
20854 "Copy the visible parts of the region."
20855 (interactive "r")
20856 (let (snippets s)
20857 (save-excursion
20858 (save-restriction
20859 (narrow-to-region beg end)
20860 (setq s (goto-char (point-min)))
20861 (while (not (= (point) (point-max)))
20862 (goto-char (org-find-invisible))
20863 (push (buffer-substring s (point)) snippets)
20864 (setq s (goto-char (org-find-visible))))))
20865 (kill-new (apply 'concat (nreverse snippets)))))
20867 (defun org-copy-special ()
20868 "Copy region in table or copy current subtree.
20869 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20870 See the individual commands for more information."
20871 (interactive)
20872 (call-interactively
20873 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20875 (defun org-cut-special ()
20876 "Cut region in table or cut current subtree.
20877 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20878 See the individual commands for more information."
20879 (interactive)
20880 (call-interactively
20881 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20883 (defun org-paste-special (arg)
20884 "Paste rectangular region into table, or past subtree relative to level.
20885 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20886 See the individual commands for more information."
20887 (interactive "P")
20888 (if (org-at-table-p)
20889 (org-table-paste-rectangle)
20890 (org-paste-subtree arg)))
20892 (defsubst org-in-fixed-width-region-p ()
20893 "Is point in a fixed-width region?"
20894 (save-match-data
20895 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20897 (defun org-edit-special (&optional arg)
20898 "Call a special editor for the element at point.
20899 When at a table, call the formula editor with `org-table-edit-formulas'.
20900 When in a source code block, call `org-edit-src-code'.
20901 When in a fixed-width region, call `org-edit-fixed-width-region'.
20902 When in an export block, call `org-edit-export-block'.
20903 When at an #+INCLUDE keyword, visit the included file.
20904 When at a footnote reference, call `org-edit-footnote-reference'
20905 On a link, call `ffap' to visit the link at point.
20906 Otherwise, return a user error."
20907 (interactive "P")
20908 (let ((element (org-element-at-point)))
20909 (cl-assert (not buffer-read-only) nil
20910 "Buffer is read-only: %s" (buffer-name))
20911 (pcase (org-element-type element)
20912 (`src-block
20913 (if (not arg) (org-edit-src-code)
20914 (let* ((info (org-babel-get-src-block-info))
20915 (lang (nth 0 info))
20916 (params (nth 2 info))
20917 (session (cdr (assq :session params))))
20918 (if (not session) (org-edit-src-code)
20919 ;; At a src-block with a session and function called with
20920 ;; an ARG: switch to the buffer related to the inferior
20921 ;; process.
20922 (switch-to-buffer
20923 (funcall (intern (concat "org-babel-prep-session:" lang))
20924 session params))))))
20925 (`keyword
20926 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20927 (org-open-link-from-string
20928 (format "[[%s]]"
20929 (expand-file-name
20930 (let ((value (org-element-property :value element)))
20931 (cond ((not (org-string-nw-p value))
20932 (user-error "No file to edit"))
20933 ((string-match "\\`\"\\(.*?\\)\"" value)
20934 (match-string 1 value))
20935 ((string-match "\\`[^ \t\"]\\S-*" value)
20936 (match-string 0 value))
20937 (t (user-error "No valid file specified")))))))
20938 (user-error "No special environment to edit here")))
20939 (`table
20940 (if (eq (org-element-property :type element) 'table.el)
20941 (org-edit-table.el)
20942 (call-interactively 'org-table-edit-formulas)))
20943 ;; Only Org tables contain `table-row' type elements.
20944 (`table-row (call-interactively 'org-table-edit-formulas))
20945 (`example-block (org-edit-src-code))
20946 (`export-block (org-edit-export-block))
20947 (`fixed-width (org-edit-fixed-width-region))
20949 ;; No notable element at point. Though, we may be at a link or
20950 ;; a footnote reference, which are objects. Thus, scan deeper.
20951 (let ((context (org-element-context element)))
20952 (pcase (org-element-type context)
20953 (`footnote-reference (org-edit-footnote-reference))
20954 (`inline-src-block (org-edit-inline-src-code))
20955 (`link (call-interactively #'ffap))
20956 (_ (user-error "No special environment to edit here"))))))))
20958 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20959 (defun org-ctrl-c-ctrl-c (&optional arg)
20960 "Set tags in headline, or update according to changed information at point.
20962 This command does many different things, depending on context:
20964 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20965 this is what we do.
20967 - If the cursor is on a statistics cookie, update it.
20969 - If the cursor is in a headline, prompt for tags and insert them
20970 into the current line, aligned to `org-tags-column'. When called
20971 with prefix arg, realign all tags in the current buffer.
20973 - If the cursor is in one of the special #+KEYWORD lines, this
20974 triggers scanning the buffer for these lines and updating the
20975 information.
20977 - If the cursor is inside a table, realign the table. This command
20978 works even if the automatic table editor has been turned off.
20980 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20981 the entire table.
20983 - If the cursor is at a footnote reference or definition, jump to
20984 the corresponding definition or references, respectively.
20986 - If the cursor is a the beginning of a dynamic block, update it.
20988 - If the current buffer is a capture buffer, close note and file it.
20990 - If the cursor is on a <<<target>>>, update radio targets and
20991 corresponding links in this buffer.
20993 - If the cursor is on a numbered item in a plain list, renumber the
20994 ordered list.
20996 - If the cursor is on a checkbox, toggle it.
20998 - If the cursor is on a code block, evaluate it. The variable
20999 `org-confirm-babel-evaluate' can be used to control prompting
21000 before code block evaluation, by default every code block
21001 evaluation requires confirmation. Code block evaluation can be
21002 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21003 (interactive "P")
21004 (cond
21005 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21006 org-occur-highlights)
21007 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21008 (org-remove-occur-highlights)
21009 (message "Temporary highlights/overlays removed from current buffer"))
21010 ((and (local-variable-p 'org-finish-function (current-buffer))
21011 (fboundp org-finish-function))
21012 (funcall org-finish-function))
21013 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21015 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21016 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21017 (user-error "C-c C-c can do nothing useful at this location"))
21018 (let* ((context (org-element-context))
21019 (type (org-element-type context)))
21020 (cl-case type
21021 ;; When at a link, act according to the parent instead.
21022 (link (setq context (org-element-property :parent context))
21023 (setq type (org-element-type context)))
21024 ;; Unsupported object types: refer to the first supported
21025 ;; element or object containing it.
21026 ((bold code entity export-snippet inline-babel-call inline-src-block
21027 italic latex-fragment line-break macro strike-through subscript
21028 superscript underline verbatim)
21029 (setq context
21030 (org-element-lineage
21031 context '(radio-target paragraph verse-block table-cell)))))
21032 ;; For convenience: at the first line of a paragraph on the
21033 ;; same line as an item, apply function on that item instead.
21034 (when (eq type 'paragraph)
21035 (let ((parent (org-element-property :parent context)))
21036 (when (and (eq (org-element-type parent) 'item)
21037 (= (line-beginning-position)
21038 (org-element-property :begin parent)))
21039 (setq context parent type 'item))))
21040 ;; Act according to type of element or object at point.
21041 (cl-case type
21042 (clock (org-clock-update-time-maybe))
21043 (dynamic-block
21044 (save-excursion
21045 (goto-char (org-element-property :post-affiliated context))
21046 (org-update-dblock)))
21047 (footnote-definition
21048 (goto-char (org-element-property :post-affiliated context))
21049 (call-interactively 'org-footnote-action))
21050 (footnote-reference (call-interactively 'org-footnote-action))
21051 ((headline inlinetask)
21052 (save-excursion (goto-char (org-element-property :begin context))
21053 (call-interactively 'org-set-tags)))
21054 (item
21055 ;; At an item: a double C-u set checkbox to "[-]"
21056 ;; unconditionally, whereas a single one will toggle its
21057 ;; presence. Without a universal argument, if the item
21058 ;; has a checkbox, toggle it. Otherwise repair the list.
21059 (let* ((box (org-element-property :checkbox context))
21060 (struct (org-element-property :structure context))
21061 (old-struct (copy-tree struct))
21062 (parents (org-list-parents-alist struct))
21063 (prevs (org-list-prevs-alist struct))
21064 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21065 (org-list-set-checkbox
21066 (org-element-property :begin context) struct
21067 (cond ((equal arg '(16)) "[-]")
21068 ((and (not box) (equal arg '(4))) "[ ]")
21069 ((or (not box) (equal arg '(4))) nil)
21070 ((eq box 'on) "[ ]")
21071 (t "[X]")))
21072 ;; Mimic `org-list-write-struct' but with grabbing
21073 ;; a return value from `org-list-struct-fix-box'.
21074 (org-list-struct-fix-ind struct parents 2)
21075 (org-list-struct-fix-item-end struct)
21076 (org-list-struct-fix-bul struct prevs)
21077 (org-list-struct-fix-ind struct parents)
21078 (let ((block-item
21079 (org-list-struct-fix-box struct parents prevs orderedp)))
21080 (if (and box (equal struct old-struct))
21081 (if (equal arg '(16))
21082 (message "Checkboxes already reset")
21083 (user-error "Cannot toggle this checkbox: %s"
21084 (if (eq box 'on)
21085 "all subitems checked"
21086 "unchecked subitems")))
21087 (org-list-struct-apply-struct struct old-struct)
21088 (org-update-checkbox-count-maybe))
21089 (when block-item
21090 (message "Checkboxes were removed due to empty box at line %d"
21091 (org-current-line block-item))))))
21092 (keyword
21093 (let ((org-inhibit-startup-visibility-stuff t)
21094 (org-startup-align-all-tables nil))
21095 (when (boundp 'org-table-coordinate-overlays)
21096 (mapc #'delete-overlay org-table-coordinate-overlays)
21097 (setq org-table-coordinate-overlays nil))
21098 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21099 (message "Local setup has been refreshed"))
21100 (plain-list
21101 ;; At a plain list, with a double C-u argument, set
21102 ;; checkboxes of each item to "[-]", whereas a single one
21103 ;; will toggle their presence according to the state of the
21104 ;; first item in the list. Without an argument, repair the
21105 ;; list.
21106 (let* ((begin (org-element-property :contents-begin context))
21107 (beginm (move-marker (make-marker) begin))
21108 (struct (org-element-property :structure context))
21109 (old-struct (copy-tree struct))
21110 (first-box (save-excursion
21111 (goto-char begin)
21112 (looking-at org-list-full-item-re)
21113 (match-string-no-properties 3)))
21114 (new-box (cond ((equal arg '(16)) "[-]")
21115 ((equal arg '(4)) (unless first-box "[ ]"))
21116 ((equal first-box "[X]") "[ ]")
21117 (t "[X]"))))
21118 (cond
21119 (arg
21120 (dolist (pos
21121 (org-list-get-all-items
21122 begin struct (org-list-prevs-alist struct)))
21123 (org-list-set-checkbox pos struct new-box)))
21124 ((and first-box (eq (point) begin))
21125 ;; For convenience, when point is at bol on the first
21126 ;; item of the list and no argument is provided, simply
21127 ;; toggle checkbox of that item, if any.
21128 (org-list-set-checkbox begin struct new-box)))
21129 (org-list-write-struct
21130 struct (org-list-parents-alist struct) old-struct)
21131 (org-update-checkbox-count-maybe)
21132 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21133 ((property-drawer node-property)
21134 (call-interactively 'org-property-action))
21135 ((radio-target target)
21136 (call-interactively 'org-update-radio-target-regexp))
21137 (statistics-cookie
21138 (call-interactively 'org-update-statistics-cookies))
21139 ((table table-cell table-row)
21140 ;; At a table, recalculate every field and align it. Also
21141 ;; send the table if necessary. If the table has
21142 ;; a `table.el' type, just give up. At a table row or
21143 ;; cell, maybe recalculate line but always align table.
21144 (if (eq (org-element-property :type context) 'table.el)
21145 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21146 Use \\[org-edit-special] to edit table.el tables"))
21147 (let ((org-enable-table-editor t))
21148 (if (or (eq type 'table)
21149 ;; Check if point is at a TBLFM line.
21150 (and (eq type 'table-row)
21151 (= (point) (org-element-property :end context))))
21152 (save-excursion
21153 (if (org-at-TBLFM-p)
21154 (progn (require 'org-table)
21155 (org-table-calc-current-TBLFM))
21156 (goto-char (org-element-property :contents-begin context))
21157 (org-call-with-arg 'org-table-recalculate (or arg t))
21158 (orgtbl-send-table 'maybe)))
21159 (org-table-maybe-eval-formula)
21160 (cond (arg (call-interactively 'org-table-recalculate))
21161 ((org-table-maybe-recalculate-line))
21162 (t (org-table-align)))))))
21163 (timestamp (org-timestamp-change 0 'day))
21164 (otherwise
21165 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21166 (user-error
21167 "C-c C-c can do nothing useful at this location")))))))))
21169 (defun org-mode-restart ()
21170 (interactive)
21171 (let ((indent-status (bound-and-true-p org-indent-mode)))
21172 (funcall major-mode)
21173 (hack-local-variables)
21174 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21175 (org-indent-mode -1)))
21176 (message "%s restarted" major-mode))
21178 (defun org-kill-note-or-show-branches ()
21179 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21180 (interactive)
21181 (if (not org-finish-function)
21182 (progn
21183 (outline-hide-subtree)
21184 (call-interactively 'outline-show-branches))
21185 (let ((org-note-abort t))
21186 (funcall org-finish-function))))
21188 (defun org-delete-indentation (&optional ARG)
21189 "Join current line to previous and fix whitespace at join.
21191 If previous line is a headline add to headline title. Otherwise
21192 the function calls `delete-indentation'.
21194 With argument, join this line to following line."
21195 (interactive "*P")
21196 (if (save-excursion
21197 (if ARG (beginning-of-line)
21198 (forward-line -1))
21199 (looking-at org-complex-heading-regexp))
21200 ;; At headline.
21201 (let ((tags-column (when (match-beginning 5)
21202 (save-excursion (goto-char (match-beginning 5))
21203 (current-column))))
21204 (string (concat " " (progn (when ARG (forward-line 1))
21205 (org-trim (delete-and-extract-region
21206 (line-beginning-position)
21207 (line-end-position)))))))
21208 (unless (bobp) (delete-region (point) (1- (point))))
21209 (goto-char (or (match-end 4)
21210 (match-beginning 5)
21211 (match-end 0)))
21212 (skip-chars-backward " \t")
21213 (save-excursion (insert string))
21214 ;; Adjust alignment of tags.
21215 (when tags-column
21216 (org-align-tags-here (if org-auto-align-tags
21217 org-tags-column
21218 tags-column))))
21219 (delete-indentation ARG)))
21221 (defun org-open-line (n)
21222 "Insert a new row in tables, call `open-line' elsewhere.
21223 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21224 (interactive "*p")
21225 (cond
21226 ((not org-special-ctrl-o)
21227 (open-line n))
21228 ((org-at-table-p)
21229 (org-table-insert-row))
21231 (open-line n))))
21233 (defun org-return (&optional indent)
21234 "Goto next table row or insert a newline.
21236 Calls `org-table-next-row' or `newline', depending on context.
21238 When optional INDENT argument is non-nil, call
21239 `newline-and-indent' instead of `newline'.
21241 When `org-return-follows-link' is non-nil and point is on
21242 a timestamp or a link, call `org-open-at-point'. However, it
21243 will not happen if point is in a table or on a \"dead\"
21244 object (e.g., within a comment). In these case, you need to use
21245 `org-open-at-point' directly."
21246 (interactive)
21247 (let ((context (if org-return-follows-link (org-element-context)
21248 (org-element-at-point))))
21249 (cond
21250 ;; In a table, call `org-table-next-row'.
21251 ((or (and (eq (org-element-type context) 'table)
21252 (>= (point) (org-element-property :contents-begin context))
21253 (< (point) (org-element-property :contents-end context)))
21254 (org-element-lineage context '(table-row table-cell) t))
21255 (org-table-justify-field-maybe)
21256 (call-interactively #'org-table-next-row))
21257 ;; On a link or a timestamp, call `org-open-at-point' if
21258 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21259 ;; locations, e.g., in a comment, as `org-open-at-point'.
21260 ((and org-return-follows-link
21261 (or (org-in-regexp org-ts-regexp-both nil t)
21262 (org-in-regexp org-tsr-regexp-both nil t)
21263 (org-in-regexp org-any-link-re nil t)))
21264 (call-interactively #'org-open-at-point))
21265 ;; Insert newline in heading, but preserve tags.
21266 ((and (not (bolp))
21267 (save-excursion (beginning-of-line)
21268 (looking-at org-complex-heading-regexp)))
21269 ;; At headline. Split line. However, if point is on keyword,
21270 ;; priority cookie or tags, do not break any of them: add
21271 ;; a newline after the headline instead.
21272 (let ((tags-column (and (match-beginning 5)
21273 (save-excursion (goto-char (match-beginning 5))
21274 (current-column))))
21275 (string
21276 (when (and (match-end 4)
21277 (>= (point)
21278 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21279 (<= (point) (match-end 4)))
21280 (delete-and-extract-region (point) (match-end 4)))))
21281 (when (and tags-column string) ; Adjust tag alignment.
21282 (org-align-tags-here
21283 (if org-auto-align-tags org-tags-column tags-column)))
21284 (end-of-line)
21285 (org-show-entry)
21286 (if indent (newline-and-indent) (newline))
21287 (when string (save-excursion (insert (org-trim string))))))
21288 ;; In a list, make sure indenting keeps trailing text within.
21289 ((and indent
21290 (not (eolp))
21291 (org-element-lineage context '(item)))
21292 (let ((trailing-data
21293 (delete-and-extract-region (point) (line-end-position))))
21294 (newline-and-indent)
21295 (save-excursion (insert trailing-data))))
21296 (t (if indent (newline-and-indent) (newline))))))
21298 (defun org-return-indent ()
21299 "Goto next table row or insert a newline and indent.
21300 Calls `org-table-next-row' or `newline-and-indent', depending on
21301 context. See the individual commands for more information."
21302 (interactive)
21303 (org-return t))
21305 (defun org-ctrl-c-star ()
21306 "Compute table, or change heading status of lines.
21307 Calls `org-table-recalculate' or `org-toggle-heading',
21308 depending on context."
21309 (interactive)
21310 (cond
21311 ((org-at-table-p)
21312 (call-interactively 'org-table-recalculate))
21314 ;; Convert all lines in region to list items
21315 (call-interactively 'org-toggle-heading))))
21317 (defun org-ctrl-c-minus ()
21318 "Insert separator line in table or modify bullet status of line.
21319 Also turns a plain line or a region of lines into list items.
21320 Calls `org-table-insert-hline', `org-toggle-item', or
21321 `org-cycle-list-bullet', depending on context."
21322 (interactive)
21323 (cond
21324 ((org-at-table-p)
21325 (call-interactively 'org-table-insert-hline))
21326 ((org-region-active-p)
21327 (call-interactively 'org-toggle-item))
21328 ((org-in-item-p)
21329 (call-interactively 'org-cycle-list-bullet))
21331 (call-interactively 'org-toggle-item))))
21333 (defun org-toggle-heading (&optional nstars)
21334 "Convert headings to normal text, or items or text to headings.
21335 If there is no active region, only convert the current line.
21337 With a \\[universal-argument] prefix, convert the whole list at
21338 point into heading.
21340 In a region:
21342 - If the first non blank line is a headline, remove the stars
21343 from all headlines in the region.
21345 - If it is a normal line, turn each and every normal line (i.e.,
21346 not an heading or an item) in the region into headings. If you
21347 want to convert only the first line of this region, use one
21348 universal prefix argument.
21350 - If it is a plain list item, turn all plain list items into headings.
21352 When converting a line into a heading, the number of stars is chosen
21353 such that the lines become children of the current entry. However,
21354 when a numeric prefix argument is given, its value determines the
21355 number of stars to add."
21356 (interactive "P")
21357 (let ((skip-blanks
21358 (function
21359 ;; Return beginning of first non-blank line, starting from
21360 ;; line at POS.
21361 (lambda (pos)
21362 (save-excursion
21363 (goto-char pos)
21364 (while (org-at-comment-p) (forward-line))
21365 (skip-chars-forward " \r\t\n")
21366 (point-at-bol)))))
21367 beg end toggled)
21368 ;; Determine boundaries of changes. If a universal prefix has
21369 ;; been given, put the list in a region. If region ends at a bol,
21370 ;; do not consider the last line to be in the region.
21372 (when (and current-prefix-arg (org-at-item-p))
21373 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21374 (org-mark-element))
21376 (if (org-region-active-p)
21377 (setq beg (funcall skip-blanks (region-beginning))
21378 end (copy-marker (save-excursion
21379 (goto-char (region-end))
21380 (if (bolp) (point) (point-at-eol)))))
21381 (setq beg (funcall skip-blanks (point-at-bol))
21382 end (copy-marker (point-at-eol))))
21383 ;; Ensure inline tasks don't count as headings.
21384 (org-with-limited-levels
21385 (save-excursion
21386 (goto-char beg)
21387 (cond
21388 ;; Case 1. Started at an heading: de-star headings.
21389 ((org-at-heading-p)
21390 (while (< (point) end)
21391 (when (org-at-heading-p t)
21392 (looking-at org-outline-regexp) (replace-match "")
21393 (setq toggled t))
21394 (forward-line)))
21395 ;; Case 2. Started at an item: change items into headlines.
21396 ;; One star will be added by `org-list-to-subtree'.
21397 ((org-at-item-p)
21398 (while (< (point) end)
21399 (when (org-at-item-p)
21400 ;; Pay attention to cases when region ends before list.
21401 (let* ((struct (org-list-struct))
21402 (list-end
21403 (min (org-list-get-bottom-point struct) (1+ end))))
21404 (save-restriction
21405 (narrow-to-region (point) list-end)
21406 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21407 (setq toggled t))
21408 (forward-line)))
21409 ;; Case 3. Started at normal text: make every line an heading,
21410 ;; skipping headlines and items.
21411 (t (let* ((stars
21412 (make-string
21413 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21414 (add-stars
21415 (cond (nstars "") ; stars from prefix only
21416 ((equal stars "") "*") ; before first heading
21417 (org-odd-levels-only "**") ; inside heading, odd
21418 (t "*"))) ; inside heading, oddeven
21419 (rpl (concat stars add-stars " "))
21420 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21421 (while (< (point) (if (equal nstars '(4)) lend end))
21422 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21423 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21424 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21425 (forward-line)))))))
21426 (unless toggled (message "Cannot toggle heading from here"))))
21428 (defun org-meta-return (&optional _arg)
21429 "Insert a new heading or wrap a region in a table.
21430 Calls `org-insert-heading' or `org-table-wrap-region', depending
21431 on context. See the individual commands for more information."
21432 (interactive)
21433 (org-check-before-invisible-edit 'insert)
21434 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21435 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21436 #'org-insert-heading))))
21438 ;;; Menu entries
21440 (defsubst org-in-subtree-not-table-p ()
21441 "Are we in a subtree and not in a table?"
21442 (and (not (org-before-first-heading-p))
21443 (not (org-at-table-p))))
21445 ;; Define the Org-mode menus
21446 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21447 '("Tbl"
21448 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21449 ["Next Field" org-cycle (org-at-table-p)]
21450 ["Previous Field" org-shifttab (org-at-table-p)]
21451 ["Next Row" org-return (org-at-table-p)]
21452 "--"
21453 ["Blank Field" org-table-blank-field (org-at-table-p)]
21454 ["Edit Field" org-table-edit-field (org-at-table-p)]
21455 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21456 "--"
21457 ("Column"
21458 ["Move Column Left" org-metaleft (org-at-table-p)]
21459 ["Move Column Right" org-metaright (org-at-table-p)]
21460 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21461 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21462 ("Row"
21463 ["Move Row Up" org-metaup (org-at-table-p)]
21464 ["Move Row Down" org-metadown (org-at-table-p)]
21465 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21466 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21467 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21468 "--"
21469 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21470 ("Rectangle"
21471 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21472 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21473 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21474 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21475 "--"
21476 ("Calculate"
21477 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21478 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21479 ["Edit Formulas" org-edit-special (org-at-table-p)]
21480 "--"
21481 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21482 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21483 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21484 "--"
21485 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21486 "--"
21487 ["Sum Column/Rectangle" org-table-sum
21488 (or (org-at-table-p) (org-region-active-p))]
21489 ["Which Column?" org-table-current-column (org-at-table-p)])
21490 ["Debug Formulas"
21491 org-table-toggle-formula-debugger
21492 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21493 ["Show Col/Row Numbers"
21494 org-table-toggle-coordinate-overlays
21495 :style toggle
21496 :selected (bound-and-true-p org-table-overlay-coordinates)]
21497 "--"
21498 ["Create" org-table-create (and (not (org-at-table-p))
21499 org-enable-table-editor)]
21500 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21501 ["Import from File" org-table-import (not (org-at-table-p))]
21502 ["Export to File" org-table-export (org-at-table-p)]
21503 "--"
21504 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21505 "--"
21506 ("Plot"
21507 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21508 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21510 (easy-menu-define org-org-menu org-mode-map "Org menu"
21511 '("Org"
21512 ("Show/Hide"
21513 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21514 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21515 ["Sparse Tree..." org-sparse-tree t]
21516 ["Reveal Context" org-reveal t]
21517 ["Show All" outline-show-all t]
21518 "--"
21519 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21520 "--"
21521 ["New Heading" org-insert-heading t]
21522 ("Navigate Headings"
21523 ["Up" outline-up-heading t]
21524 ["Next" outline-next-visible-heading t]
21525 ["Previous" outline-previous-visible-heading t]
21526 ["Next Same Level" outline-forward-same-level t]
21527 ["Previous Same Level" outline-backward-same-level t]
21528 "--"
21529 ["Jump" org-goto t])
21530 ("Edit Structure"
21531 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21532 "--"
21533 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21534 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21535 "--"
21536 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21537 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21538 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21539 "--"
21540 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21541 "--"
21542 ["Copy visible text" org-copy-visible t]
21543 "--"
21544 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21545 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21546 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21547 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21548 "--"
21549 ["Sort Region/Children" org-sort t]
21550 "--"
21551 ["Convert to odd levels" org-convert-to-odd-levels t]
21552 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21553 ("Editing"
21554 ["Emphasis..." org-emphasize t]
21555 ["Edit Source Example" org-edit-special t]
21556 "--"
21557 ["Footnote new/jump" org-footnote-action t]
21558 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21559 ("Archive"
21560 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21561 "--"
21562 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21563 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21564 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21566 "--"
21567 ("Hyperlinks"
21568 ["Store Link (Global)" org-store-link t]
21569 ["Find existing link to here" org-occur-link-in-agenda-files t]
21570 ["Insert Link" org-insert-link t]
21571 ["Follow Link" org-open-at-point t]
21572 "--"
21573 ["Next link" org-next-link t]
21574 ["Previous link" org-previous-link t]
21575 "--"
21576 ["Descriptive Links"
21577 org-toggle-link-display
21578 :style radio
21579 :selected org-descriptive-links
21581 ["Literal Links"
21582 org-toggle-link-display
21583 :style radio
21584 :selected (not org-descriptive-links)])
21585 "--"
21586 ("TODO Lists"
21587 ["TODO/DONE/-" org-todo t]
21588 ("Select keyword"
21589 ["Next keyword" org-shiftright (org-at-heading-p)]
21590 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21591 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21592 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21593 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21594 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21595 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21596 "--"
21597 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21598 :selected org-enforce-todo-dependencies :style toggle :active t]
21599 "Settings for tree at point"
21600 ["Do Children sequentially" org-toggle-ordered-property :style radio
21601 :selected (org-entry-get nil "ORDERED")
21602 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21603 ["Do Children parallel" org-toggle-ordered-property :style radio
21604 :selected (not (org-entry-get nil "ORDERED"))
21605 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21606 "--"
21607 ["Set Priority" org-priority t]
21608 ["Priority Up" org-shiftup t]
21609 ["Priority Down" org-shiftdown t]
21610 "--"
21611 ["Get news from all feeds" org-feed-update-all t]
21612 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21613 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21614 ("TAGS and Properties"
21615 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21616 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21617 "--"
21618 ["Set property" org-set-property (not (org-before-first-heading-p))]
21619 ["Column view of properties" org-columns t]
21620 ["Insert Column View DBlock" org-columns-insert-dblock t])
21621 ("Dates and Scheduling"
21622 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21623 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21624 ("Change Date"
21625 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21626 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21627 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21628 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21629 ["Compute Time Range" org-evaluate-time-range t]
21630 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21631 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21632 "--"
21633 ["Custom time format" org-toggle-time-stamp-overlays
21634 :style radio :selected org-display-custom-times]
21635 "--"
21636 ["Goto Calendar" org-goto-calendar t]
21637 ["Date from Calendar" org-date-from-calendar t]
21638 "--"
21639 ["Start/Restart Timer" org-timer-start t]
21640 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21641 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21642 ["Insert Timer String" org-timer t]
21643 ["Insert Timer Item" org-timer-item t])
21644 ("Logging work"
21645 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21646 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21647 ["Clock out" org-clock-out t]
21648 ["Clock cancel" org-clock-cancel t]
21649 "--"
21650 ["Mark as default task" org-clock-mark-default-task t]
21651 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21652 ["Goto running clock" org-clock-goto t]
21653 "--"
21654 ["Display times" org-clock-display t]
21655 ["Create clock table" org-clock-report t]
21656 "--"
21657 ["Record DONE time"
21658 (progn (setq org-log-done (not org-log-done))
21659 (message "Switching to %s will %s record a timestamp"
21660 (car org-done-keywords)
21661 (if org-log-done "automatically" "not")))
21662 :style toggle :selected org-log-done])
21663 "--"
21664 ["Agenda Command..." org-agenda t]
21665 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21666 ("File List for Agenda")
21667 ("Special views current file"
21668 ["TODO Tree" org-show-todo-tree t]
21669 ["Check Deadlines" org-check-deadlines t]
21670 ["Timeline" org-timeline t]
21671 ["Tags/Property tree" org-match-sparse-tree t])
21672 "--"
21673 ["Export/Publish..." org-export-dispatch t]
21674 ("LaTeX"
21675 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21676 :selected org-cdlatex-mode]
21677 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21678 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21679 ["Modify math symbol" org-cdlatex-math-modify
21680 (org-inside-LaTeX-fragment-p)]
21681 ["Insert citation" org-reftex-citation t])
21682 "--"
21683 ("MobileOrg"
21684 ["Push Files and Views" org-mobile-push t]
21685 ["Get Captured and Flagged" org-mobile-pull t]
21686 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21687 "--"
21688 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21689 "--"
21690 ("Documentation"
21691 ["Show Version" org-version t]
21692 ["Info Documentation" org-info t])
21693 ("Customize"
21694 ["Browse Org Group" org-customize t]
21695 "--"
21696 ["Expand This Menu" org-create-customize-menu
21697 (fboundp 'customize-menu-create)])
21698 ["Send bug report" org-submit-bug-report t]
21699 "--"
21700 ("Refresh/Reload"
21701 ["Refresh setup current buffer" org-mode-restart t]
21702 ["Reload Org (after update)" org-reload t]
21703 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21706 (defun org-info (&optional node)
21707 "Read documentation for Org-mode in the info system.
21708 With optional NODE, go directly to that node."
21709 (interactive)
21710 (info (format "(org)%s" (or node ""))))
21712 ;;;###autoload
21713 (defun org-submit-bug-report ()
21714 "Submit a bug report on Org-mode via mail.
21716 Don't hesitate to report any problems or inaccurate documentation.
21718 If you don't have setup sending mail from (X)Emacs, please copy the
21719 output buffer into your mail program, as it gives us important
21720 information about your Org-mode version and configuration."
21721 (interactive)
21722 (require 'reporter)
21723 (defvar reporter-prompt-for-summary-p)
21724 (org-load-modules-maybe)
21725 (org-require-autoloaded-modules)
21726 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21727 (reporter-submit-bug-report
21728 "emacs-orgmode@gnu.org"
21729 (org-version nil 'full)
21730 (let (list)
21731 (save-window-excursion
21732 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21733 (delete-other-windows)
21734 (erase-buffer)
21735 (insert "You are about to submit a bug report to the Org-mode mailing list.
21737 We would like to add your full Org-mode and Outline configuration to the
21738 bug report. This greatly simplifies the work of the maintainer and
21739 other experts on the mailing list.
21741 HOWEVER, some variables you have customized may contain private
21742 information. The names of customers, colleagues, or friends, might
21743 appear in the form of file names, tags, todo states, or search strings.
21744 If you answer yes to the prompt, you might want to check and remove
21745 such private information before sending the email.")
21746 (add-text-properties (point-min) (point-max) '(face org-warning))
21747 (when (yes-or-no-p "Include your Org-mode configuration ")
21748 (mapatoms
21749 (lambda (v)
21750 (and (boundp v)
21751 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21752 (or (and (symbol-value v)
21753 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21754 (and
21755 (get v 'custom-type) (get v 'standard-value)
21756 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21757 (push v list)))))
21758 (kill-buffer (get-buffer "*Warn about privacy*"))
21759 list))
21760 nil nil
21761 "Remember to cover the basics, that is, what you expected to happen and
21762 what in fact did happen. You don't know how to make a good report? See
21764 http://orgmode.org/manual/Feedback.html#Feedback
21766 Your bug report will be posted to the Org-mode mailing list.
21767 ------------------------------------------------------------------------")
21768 (save-excursion
21769 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21770 (replace-match "\\1Bug: \\3 [\\2]")))))
21773 (defun org-install-agenda-files-menu ()
21774 (let ((bl (buffer-list)))
21775 (save-excursion
21776 (while bl
21777 (set-buffer (pop bl))
21778 (when (derived-mode-p 'org-mode) (setq bl nil)))
21779 (when (derived-mode-p 'org-mode)
21780 (easy-menu-change
21781 '("Org") "File List for Agenda"
21782 (append
21783 (list
21784 ["Edit File List" (org-edit-agenda-file-list) t]
21785 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21786 ["Remove Current File from List" org-remove-file t]
21787 ["Cycle through agenda files" org-cycle-agenda-files t]
21788 ["Occur in all agenda files" org-occur-in-agenda-files t]
21789 "--")
21790 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21792 ;;;; Documentation
21794 (defun org-require-autoloaded-modules ()
21795 (interactive)
21796 (mapc #'require
21797 '(org-agenda org-archive org-attach org-clock org-colview org-id
21798 org-table org-timer)))
21800 ;;;###autoload
21801 (defun org-reload (&optional uncompiled)
21802 "Reload all org lisp files.
21803 With prefix arg UNCOMPILED, load the uncompiled versions."
21804 (interactive "P")
21805 (require 'loadhist)
21806 (let* ((org-dir (org-find-library-dir "org"))
21807 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21808 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21809 (remove-re (format "\\`%s\\'"
21810 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21811 (feats (delete-dups
21812 (mapcar 'file-name-sans-extension
21813 (mapcar 'file-name-nondirectory
21814 (delq nil
21815 (mapcar 'feature-file
21816 features))))))
21817 (lfeat (append
21818 (sort
21819 (setq feats
21820 (delq nil (mapcar
21821 (lambda (f)
21822 (if (and (string-match feature-re f)
21823 (not (string-match remove-re f)))
21824 f nil))
21825 feats)))
21826 'string-lessp)
21827 (list "org-version" "org")))
21828 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21829 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21830 load-uncore load-misses)
21831 (setq load-misses
21832 (delq 't
21833 (mapcar (lambda (f)
21834 (or (org-load-noerror-mustsuffix (concat org-dir f))
21835 (and (string= org-dir contrib-dir)
21836 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21837 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21838 (add-to-list 'load-uncore f 'append)
21841 lfeat)))
21842 (when load-uncore
21843 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21844 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21845 (if load-misses
21846 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21847 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21848 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21850 ;;;###autoload
21851 (defun org-customize ()
21852 "Call the customize function with org as argument."
21853 (interactive)
21854 (org-load-modules-maybe)
21855 (org-require-autoloaded-modules)
21856 (customize-browse 'org))
21858 (defun org-create-customize-menu ()
21859 "Create a full customization menu for Org-mode, insert it into the menu."
21860 (interactive)
21861 (org-load-modules-maybe)
21862 (org-require-autoloaded-modules)
21863 (if (fboundp 'customize-menu-create)
21864 (progn
21865 (easy-menu-change
21866 '("Org") "Customize"
21867 `(["Browse Org group" org-customize t]
21868 "--"
21869 ,(customize-menu-create 'org)
21870 ["Set" Custom-set t]
21871 ["Save" Custom-save t]
21872 ["Reset to Current" Custom-reset-current t]
21873 ["Reset to Saved" Custom-reset-saved t]
21874 ["Reset to Standard Settings" Custom-reset-standard t]))
21875 (message "\"Org\"-menu now contains full customization menu"))
21876 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21878 ;;;; Miscellaneous stuff
21880 ;;; Generally useful functions
21882 (defun org-get-at-eol (property n)
21883 "Get text property PROPERTY at the end of line less N characters."
21884 (get-text-property (- (point-at-eol) n) property))
21886 (defun org-find-text-property-in-string (prop s)
21887 "Return the first non-nil value of property PROP in string S."
21888 (or (get-text-property 0 prop s)
21889 (get-text-property (or (next-single-property-change 0 prop s) 0)
21890 prop s)))
21892 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21893 "Display the given MESSAGE as a warning."
21894 (if (fboundp 'display-warning)
21895 (display-warning 'org message :warning)
21896 (let ((buf (get-buffer-create "*Org warnings*")))
21897 (with-current-buffer buf
21898 (goto-char (point-max))
21899 (insert "Warning (Org): " message)
21900 (unless (bolp)
21901 (newline)))
21902 (display-buffer buf)
21903 (sit-for 0))))
21905 (defun org-eval (form)
21906 "Eval FORM and return result."
21907 (condition-case error
21908 (eval form)
21909 (error (format "%%![Error: %s]" error))))
21911 (defun org-in-clocktable-p ()
21912 "Check if the cursor is in a clocktable."
21913 (let ((pos (point)) start)
21914 (save-excursion
21915 (end-of-line 1)
21916 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21917 (setq start (match-beginning 0))
21918 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21919 (>= (match-end 0) pos)
21920 start))))
21922 (defun org-in-verbatim-emphasis ()
21923 (save-match-data
21924 (and (org-in-regexp org-emph-re 2)
21925 (>= (point) (match-beginning 3))
21926 (<= (point) (match-end 4))
21927 (member (match-string 3) '("=" "~")))))
21929 (defun org-overlay-display (ovl text &optional face evap)
21930 "Make overlay OVL display TEXT with face FACE."
21931 (overlay-put ovl 'display text)
21932 (if face (overlay-put ovl 'face face))
21933 (if evap (overlay-put ovl 'evaporate t)))
21935 (defun org-overlay-before-string (ovl text &optional face evap)
21936 "Make overlay OVL display TEXT with face FACE."
21937 (if face (org-add-props text nil 'face face))
21938 (overlay-put ovl 'before-string text)
21939 (if evap (overlay-put ovl 'evaporate t)))
21941 (defun org-find-overlays (prop &optional pos delete)
21942 "Find all overlays specifying PROP at POS or point.
21943 If DELETE is non-nil, delete all those overlays."
21944 (let (found)
21945 (dolist (ov (overlays-at (or pos (point))) found)
21946 (cond ((not (overlay-get ov prop)))
21947 (delete (delete-overlay ov))
21948 (t (push ov found))))))
21950 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21951 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21952 (if (and marker (marker-buffer marker)
21953 (buffer-live-p (marker-buffer marker)))
21954 (progn
21955 (pop-to-buffer-same-window (marker-buffer marker))
21956 (when (or (> marker (point-max)) (< marker (point-min)))
21957 (widen))
21958 (goto-char marker)
21959 (org-show-context 'org-goto))
21960 (if bookmark
21961 (bookmark-jump bookmark)
21962 (error "Cannot find location"))))
21964 (defun org-quote-csv-field (s)
21965 "Quote field for inclusion in CSV material."
21966 (if (string-match "[\",]" s)
21967 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21970 (defun org-force-self-insert (N)
21971 "Needed to enforce self-insert under remapping."
21972 (interactive "p")
21973 (self-insert-command N))
21975 (defun org-string-width (s)
21976 "Compute width of string, ignoring invisible characters.
21977 This ignores character with invisibility property `org-link', and also
21978 characters with property `org-cwidth', because these will become invisible
21979 upon the next fontification round."
21980 (let (b l)
21981 (when (or (eq t buffer-invisibility-spec)
21982 (assq 'org-link buffer-invisibility-spec))
21983 (while (setq b (text-property-any 0 (length s)
21984 'invisible 'org-link s))
21985 (setq s (concat (substring s 0 b)
21986 (substring s (or (next-single-property-change
21987 b 'invisible s)
21988 (length s)))))))
21989 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21990 (setq s (concat (substring s 0 b)
21991 (substring s (or (next-single-property-change
21992 b 'org-cwidth s)
21993 (length s))))))
21994 (setq l (string-width s) b -1)
21995 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21996 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21999 (defun org-shorten-string (s maxlength)
22000 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22001 If the string is shorter or has length MAXLENGTH, just return the
22002 original string. If it is longer, the functions finds a space in the
22003 string, breaks this string off at that locations and adds three dots
22004 as ellipsis. Including the ellipsis, the string will not be longer
22005 than MAXLENGTH. If finding a good breaking point in the string does
22006 not work, the string is just chopped off in the middle of a word
22007 if necessary."
22008 (if (<= (length s) maxlength)
22010 (let* ((n (max (- maxlength 4) 1))
22011 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22012 (if (string-match re s)
22013 (concat (match-string 1 s) "...")
22014 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22016 (defun org-get-indentation (&optional line)
22017 "Get the indentation of the current line, interpreting tabs.
22018 When LINE is given, assume it represents a line and compute its indentation."
22019 (if line
22020 (when (string-match "^ *" (org-remove-tabs line))
22021 (match-end 0))
22022 (save-excursion
22023 (beginning-of-line 1)
22024 (skip-chars-forward " \t")
22025 (current-column))))
22027 (defun org-get-string-indentation (s)
22028 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22029 (let ((n -1) (i 0) (w tab-width) c)
22030 (catch 'exit
22031 (while (< (setq n (1+ n)) (length s))
22032 (setq c (aref s n))
22033 (cond ((= c ?\ ) (setq i (1+ i)))
22034 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22035 (t (throw 'exit t)))))
22038 (defun org-remove-tabs (s &optional width)
22039 "Replace tabulators in S with spaces.
22040 Assumes that s is a single line, starting in column 0."
22041 (setq width (or width tab-width))
22042 (while (string-match "\t" s)
22043 (setq s (replace-match
22044 (make-string
22045 (- (* width (/ (+ (match-beginning 0) width) width))
22046 (match-beginning 0)) ?\ )
22047 t t s)))
22050 (defun org-fix-indentation (line ind)
22051 "Fix indentation in LINE.
22052 IND is a cons cell with target and minimum indentation.
22053 If the current indentation in LINE is smaller than the minimum,
22054 leave it alone. If it is larger than ind, set it to the target."
22055 (let* ((l (org-remove-tabs line))
22056 (i (org-get-indentation l))
22057 (i1 (car ind)) (i2 (cdr ind)))
22058 (when (>= i i2) (setq l (substring line i2)))
22059 (if (> i1 0)
22060 (concat (make-string i1 ?\ ) l)
22061 l)))
22063 (defun org-remove-indentation (code &optional n)
22064 "Remove maximum common indentation in string CODE and return it.
22065 N may optionally be the number of columns to remove. Return CODE
22066 as-is if removal failed."
22067 (with-temp-buffer
22068 (insert code)
22069 (if (org-do-remove-indentation n) (buffer-string) code)))
22071 (defun org-do-remove-indentation (&optional n)
22072 "Remove the maximum common indentation from the buffer.
22073 When optional argument N is a positive integer, remove exactly
22074 that much characters from indentation, if possible. Return nil
22075 if it fails."
22076 (catch :exit
22077 (goto-char (point-min))
22078 ;; Find maximum common indentation, if not specified.
22079 (let ((n (or n
22080 (let ((min-ind (point-max)))
22081 (save-excursion
22082 (while (re-search-forward "^[ \t]*\\S-" nil t)
22083 (let ((ind (1- (current-column))))
22084 (if (zerop ind) (throw :exit nil)
22085 (setq min-ind (min min-ind ind))))))
22086 min-ind))))
22087 (if (zerop n) (throw :exit nil)
22088 ;; Remove exactly N indentation, but give up if not possible.
22089 (while (not (eobp))
22090 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22091 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22092 ((< ind n) (throw :exit nil))
22093 (t (indent-line-to (- ind n))))
22094 (forward-line)))
22095 ;; Signal success.
22096 t))))
22098 (defun org-fill-template (template alist)
22099 "Find each %key of ALIST in TEMPLATE and replace it."
22100 (let ((case-fold-search nil))
22101 (dolist (entry (sort (copy-sequence alist)
22102 (lambda (a b) (< (length (car a)) (length (car b))))))
22103 (setq template
22104 (replace-regexp-in-string
22105 (concat "%" (regexp-quote (car entry)))
22106 (or (cdr entry) "") template t t)))
22107 template))
22109 (defun org-base-buffer (buffer)
22110 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22111 (if (not buffer)
22112 buffer
22113 (or (buffer-base-buffer buffer)
22114 buffer)))
22116 (defun org-wrap (string &optional width lines)
22117 "Wrap string to either a number of lines, or a width in characters.
22118 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22119 that costs. If there is a word longer than WIDTH, the text is actually
22120 wrapped to the length of that word.
22121 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22122 many lines, whatever width that takes.
22123 The return value is a list of lines, without newlines at the end."
22124 (let* ((words (org-split-string string "[ \t\n]+"))
22125 (maxword (apply 'max (mapcar 'org-string-width words)))
22126 w ll)
22127 (cond (width
22128 (org-do-wrap words (max maxword width)))
22129 (lines
22130 (setq w maxword)
22131 (setq ll (org-do-wrap words maxword))
22132 (if (<= (length ll) lines)
22134 (setq ll words)
22135 (while (> (length ll) lines)
22136 (setq w (1+ w))
22137 (setq ll (org-do-wrap words w)))
22138 ll))
22139 (t (error "Cannot wrap this")))))
22141 (defun org-do-wrap (words width)
22142 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22143 (let (lines line)
22144 (while words
22145 (setq line (pop words))
22146 (while (and words (< (+ (length line) (length (car words))) width))
22147 (setq line (concat line " " (pop words))))
22148 (setq lines (push line lines)))
22149 (nreverse lines)))
22151 (defun org-split-string (string &optional separators)
22152 "Splits STRING into substrings at SEPARATORS.
22153 SEPARATORS is a regular expression.
22154 No empty strings are returned if there are matches at the beginning
22155 and end of string."
22156 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22157 (let ((start 0) notfirst list)
22158 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22159 (if (and notfirst
22160 (= start (match-beginning 0))
22161 (< start (length string)))
22162 (1+ start) start))
22163 (< (match-beginning 0) (length string)))
22164 (setq notfirst t)
22165 (or (eq (match-beginning 0) 0)
22166 (and (eq (match-beginning 0) (match-end 0))
22167 (eq (match-beginning 0) start))
22168 (push (substring string start (match-beginning 0)) list))
22169 (setq start (match-end 0)))
22170 (or (eq start (length string))
22171 (push (substring string start) list))
22172 (nreverse list)))
22174 (defun org-quote-vert (s)
22175 "Replace \"|\" with \"\\vert\"."
22176 (while (string-match "|" s)
22177 (setq s (replace-match "\\vert" t t s)))
22180 (defun org-uuidgen-p (s)
22181 "Is S an ID created by UUIDGEN?"
22182 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22184 (defun org-in-src-block-p (&optional inside)
22185 "Whether point is in a code source block.
22186 When INSIDE is non-nil, don't consider we are within a src block
22187 when point is at #+BEGIN_SRC or #+END_SRC."
22188 (let ((case-fold-search t))
22189 (or (and (eq (get-char-property (point) 'src-block) t))
22190 (and (not inside)
22191 (save-match-data
22192 (save-excursion
22193 (beginning-of-line)
22194 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22196 (defun org-context ()
22197 "Return a list of contexts of the current cursor position.
22198 If several contexts apply, all are returned.
22199 Each context entry is a list with a symbol naming the context, and
22200 two positions indicating start and end of the context. Possible
22201 contexts are:
22203 :headline anywhere in a headline
22204 :headline-stars on the leading stars in a headline
22205 :todo-keyword on a TODO keyword (including DONE) in a headline
22206 :tags on the TAGS in a headline
22207 :priority on the priority cookie in a headline
22208 :item on the first line of a plain list item
22209 :item-bullet on the bullet/number of a plain list item
22210 :checkbox on the checkbox in a plain list item
22211 :table in an org-mode table
22212 :table-special on a special filed in a table
22213 :table-table in a table.el table
22214 :clocktable in a clocktable
22215 :src-block in a source block
22216 :link on a hyperlink
22217 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22218 :target on a <<target>>
22219 :radio-target on a <<<radio-target>>>
22220 :latex-fragment on a LaTeX fragment
22221 :latex-preview on a LaTeX fragment with overlaid preview image
22223 This function expects the position to be visible because it uses font-lock
22224 faces as a help to recognize the following contexts: :table-special, :link,
22225 and :keyword."
22226 (let* ((f (get-text-property (point) 'face))
22227 (faces (if (listp f) f (list f)))
22228 (case-fold-search t)
22229 (p (point)) clist o)
22230 ;; First the large context
22231 (cond
22232 ((org-at-heading-p t)
22233 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22234 (when (progn
22235 (beginning-of-line 1)
22236 (looking-at org-todo-line-tags-regexp))
22237 (push (org-point-in-group p 1 :headline-stars) clist)
22238 (push (org-point-in-group p 2 :todo-keyword) clist)
22239 (push (org-point-in-group p 4 :tags) clist))
22240 (goto-char p)
22241 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22242 (when (looking-at "\\[#[A-Z0-9]\\]")
22243 (push (org-point-in-group p 0 :priority) clist)))
22245 ((org-at-item-p)
22246 (push (org-point-in-group p 2 :item-bullet) clist)
22247 (push (list :item (point-at-bol)
22248 (save-excursion (org-end-of-item) (point)))
22249 clist)
22250 (and (org-at-item-checkbox-p)
22251 (push (org-point-in-group p 0 :checkbox) clist)))
22253 ((org-at-table-p)
22254 (push (list :table (org-table-begin) (org-table-end)) clist)
22255 (when (memq 'org-formula faces)
22256 (push (list :table-special
22257 (previous-single-property-change p 'face)
22258 (next-single-property-change p 'face)) clist)))
22259 ((org-at-table-p 'any)
22260 (push (list :table-table) clist)))
22261 (goto-char p)
22263 (let ((case-fold-search t))
22264 ;; New the "medium" contexts: clocktables, source blocks
22265 (cond ((org-in-clocktable-p)
22266 (push (list :clocktable
22267 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22268 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22269 (match-beginning 1))
22270 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22271 (match-end 0))) clist))
22272 ((org-in-src-block-p)
22273 (push (list :src-block
22274 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22275 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22276 (match-beginning 1))
22277 (and (search-forward "#+END_SRC" nil t)
22278 (match-beginning 0))) clist))))
22279 (goto-char p)
22281 ;; Now the small context
22282 (cond
22283 ((org-at-timestamp-p)
22284 (push (org-point-in-group p 0 :timestamp) clist))
22285 ((memq 'org-link faces)
22286 (push (list :link
22287 (previous-single-property-change p 'face)
22288 (next-single-property-change p 'face)) clist))
22289 ((memq 'org-special-keyword faces)
22290 (push (list :keyword
22291 (previous-single-property-change p 'face)
22292 (next-single-property-change p 'face)) clist))
22293 ((org-at-target-p)
22294 (push (org-point-in-group p 0 :target) clist)
22295 (goto-char (1- (match-beginning 0)))
22296 (when (looking-at org-radio-target-regexp)
22297 (push (org-point-in-group p 0 :radio-target) clist))
22298 (goto-char p))
22299 ((setq o (cl-some
22300 (lambda (o)
22301 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22303 (overlays-at (point))))
22304 (push (list :latex-fragment
22305 (overlay-start o) (overlay-end o)) clist)
22306 (push (list :latex-preview
22307 (overlay-start o) (overlay-end o)) clist))
22308 ((org-inside-LaTeX-fragment-p)
22309 ;; FIXME: positions wrong.
22310 (push (list :latex-fragment (point) (point)) clist)))
22312 (setq clist (nreverse (delq nil clist)))
22313 clist))
22315 (defun org-in-regexp (regexp &optional nlines visually)
22316 "Check if point is inside a match of REGEXP.
22318 Normally only the current line is checked, but you can include
22319 NLINES extra lines around point into the search. If VISUALLY is
22320 set, require that the cursor is not after the match but really
22321 on, so that the block visually is on the match.
22323 Return nil or a cons cell (BEG . END) where BEG and END are,
22324 respectively, the positions at the beginning and the end of the
22325 match."
22326 (catch :exit
22327 (let ((pos (point))
22328 (eol (line-end-position (if nlines (1+ nlines) 1))))
22329 (save-excursion
22330 (beginning-of-line (- 1 (or nlines 0)))
22331 (while (and (re-search-forward regexp eol t)
22332 (<= (match-beginning 0) pos))
22333 (let ((end (match-end 0)))
22334 (when (or (> end pos) (and (= end pos) (not visually)))
22335 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22337 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22338 "Non-nil when point is between matches of START-RE and END-RE.
22340 Also return a non-nil value when point is on one of the matches.
22342 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22343 buffer positions. Default values are the positions of headlines
22344 surrounding the point.
22346 The functions returns a cons cell whose car (resp. cdr) is the
22347 position before START-RE (resp. after END-RE)."
22348 (save-match-data
22349 (let ((pos (point))
22350 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22351 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22352 beg end)
22353 (save-excursion
22354 ;; Point is on a block when on START-RE or if START-RE can be
22355 ;; found before it...
22356 (and (or (org-in-regexp start-re)
22357 (re-search-backward start-re limit-up t))
22358 (setq beg (match-beginning 0))
22359 ;; ... and END-RE after it...
22360 (goto-char (match-end 0))
22361 (re-search-forward end-re limit-down t)
22362 (> (setq end (match-end 0)) pos)
22363 ;; ... without another START-RE in-between.
22364 (goto-char (match-beginning 0))
22365 (not (re-search-backward start-re (1+ beg) t))
22366 ;; Return value.
22367 (cons beg end))))))
22369 (defun org-in-block-p (names)
22370 "Non-nil when point belongs to a block whose name belongs to NAMES.
22372 NAMES is a list of strings containing names of blocks.
22374 Return first block name matched, or nil. Beware that in case of
22375 nested blocks, the returned name may not belong to the closest
22376 block from point."
22377 (save-match-data
22378 (catch 'exit
22379 (let ((case-fold-search t)
22380 (lim-up (save-excursion (outline-previous-heading)))
22381 (lim-down (save-excursion (outline-next-heading))))
22382 (dolist (name names)
22383 (let ((n (regexp-quote name)))
22384 (when (org-between-regexps-p
22385 (concat "^[ \t]*#\\+begin_" n)
22386 (concat "^[ \t]*#\\+end_" n)
22387 lim-up lim-down)
22388 (throw 'exit n)))))
22389 nil)))
22391 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22392 "Call `multi-occur' with buffers for all agenda files."
22393 (interactive "sOrg-files matching: ")
22394 (let* ((files (org-agenda-files))
22395 (tnames (mapcar #'file-truename files))
22396 (extra org-agenda-text-search-extra-files))
22397 (when (eq (car extra) 'agenda-archives)
22398 (setq extra (cdr extra))
22399 (setq files (org-add-archive-files files)))
22400 (dolist (f extra)
22401 (unless (member (file-truename f) tnames)
22402 (unless (member f files) (setq files (append files (list f))))
22403 (setq tnames (append tnames (list (file-truename f))))))
22404 (multi-occur
22405 (mapcar (lambda (x)
22406 (with-current-buffer
22407 ;; FIXME: Why not just (find-file-noselect x)?
22408 ;; Is it to avoid the "revert buffer" prompt?
22409 (or (get-file-buffer x) (find-file-noselect x))
22410 (widen)
22411 (current-buffer)))
22412 files)
22413 regexp)))
22415 (add-hook 'occur-mode-find-occurrence-hook
22416 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22418 (defun org-occur-link-in-agenda-files ()
22419 "Create a link and search for it in the agendas.
22420 The link is not stored in `org-stored-links', it is just created
22421 for the search purpose."
22422 (interactive)
22423 (let ((link (condition-case nil
22424 (org-store-link nil)
22425 (error "Unable to create a link to here"))))
22426 (org-occur-in-agenda-files (regexp-quote link))))
22428 (defun org-reverse-string (string)
22429 "Return the reverse of STRING."
22430 (apply 'string (reverse (string-to-list string))))
22432 ;; defsubst org-uniquify must be defined before first use
22434 (defun org-uniquify-alist (alist)
22435 "Merge elements of ALIST with the same key.
22437 For example, in this alist:
22439 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22440 => \\='((a 1 3) (b 2))
22442 merge (a 1) and (a 3) into (a 1 3).
22444 The function returns the new ALIST."
22445 (let (rtn)
22446 (dolist (e alist rtn)
22447 (let (n)
22448 (if (not (assoc (car e) rtn))
22449 (push e rtn)
22450 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22451 (setq rtn (assq-delete-all (car e) rtn))
22452 (push n rtn))))))
22454 (defun org-delete-all (elts list)
22455 "Remove all elements in ELTS from LIST.
22456 Comparison is done with `equal'. It is a destructive operation
22457 that may remove elements by altering the list structure."
22458 (while elts
22459 (setq list (delete (pop elts) list)))
22460 list)
22462 (defun org-back-over-empty-lines ()
22463 "Move backwards over whitespace, to the beginning of the first empty line.
22464 Returns the number of empty lines passed."
22465 (let ((pos (point)))
22466 (if (cdr (assoc 'heading org-blank-before-new-entry))
22467 (skip-chars-backward " \t\n\r")
22468 (unless (eobp)
22469 (forward-line -1)))
22470 (beginning-of-line 2)
22471 (goto-char (min (point) pos))
22472 (count-lines (point) pos)))
22474 (defun org-skip-whitespace ()
22475 (skip-chars-forward " \t\n\r"))
22477 (defun org-point-in-group (point group &optional context)
22478 "Check if POINT is in match-group GROUP.
22479 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22480 match. If the match group does not exist or point is not inside it,
22481 return nil."
22482 (and (match-beginning group)
22483 (>= point (match-beginning group))
22484 (<= point (match-end group))
22485 (if context
22486 (list context (match-beginning group) (match-end group))
22487 t)))
22489 (defun org-switch-to-buffer-other-window (&rest args)
22490 "Switch to buffer in a second window on the current frame.
22491 In particular, do not allow pop-up frames.
22492 Returns the newly created buffer."
22493 (org-no-popups
22494 (apply 'switch-to-buffer-other-window args)))
22496 (defun org-combine-plists (&rest plists)
22497 "Create a single property list from all plists in PLISTS.
22498 The process starts by copying the first list, and then setting properties
22499 from the other lists. Settings in the last list are the most significant
22500 ones and overrule settings in the other lists."
22501 (let ((rtn (copy-sequence (pop plists)))
22502 p v ls)
22503 (while plists
22504 (setq ls (pop plists))
22505 (while ls
22506 (setq p (pop ls) v (pop ls))
22507 (setq rtn (plist-put rtn p v))))
22508 rtn))
22510 (defun org-replace-escapes (string table)
22511 "Replace %-escapes in STRING with values in TABLE.
22512 TABLE is an association list with keys like \"%a\" and string values.
22513 The sequences in STRING may contain normal field width and padding information,
22514 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22515 so values can contain further %-escapes if they are define later in TABLE."
22516 (let ((tbl (copy-alist table))
22517 (case-fold-search nil)
22518 (pchg 0)
22519 re rpl)
22520 (dolist (e tbl)
22521 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22522 (when (and (cdr e) (string-match re (cdr e)))
22523 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22524 (safe "SREF"))
22525 (add-text-properties 0 3 (list 'sref sref) safe)
22526 (setcdr e (replace-match safe t t (cdr e)))))
22527 (while (string-match re string)
22528 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22529 (cdr e)))
22530 (setq string (replace-match rpl t t string))))
22531 (while (setq pchg (next-property-change pchg string))
22532 (let ((sref (get-text-property pchg 'sref string)))
22533 (when (and sref (string-match "SREF" string pchg))
22534 (setq string (replace-match sref t t string)))))
22535 string))
22537 (defun org-sublist (list start end)
22538 "Return a section of LIST, from START to END.
22540 Counting starts at 1."
22541 (cl-subseq list (1- start) end))
22542 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22544 (defun org-find-base-buffer-visiting (file)
22545 "Like `find-buffer-visiting' but always return the base buffer and
22546 not an indirect buffer."
22547 (let ((buf (or (get-file-buffer file)
22548 (find-buffer-visiting file))))
22549 (if buf
22550 (or (buffer-base-buffer buf) buf)
22551 nil)))
22553 ;;; TODO: Only called once, from ox-odt which should probably use
22554 ;;; org-export-inline-image-p or something.
22555 (defun org-file-image-p (file)
22556 "Return non-nil if FILE is an image."
22557 (save-match-data
22558 (string-match (image-file-name-regexp) file)))
22560 (defun org-get-cursor-date (&optional with-time)
22561 "Return the date at cursor in as a time.
22562 This works in the calendar and in the agenda, anywhere else it just
22563 returns the current time.
22564 If WITH-TIME is non-nil, returns the time of the event at point (in
22565 the agenda) or the current time of the day."
22566 (let (date day defd tp hod mod)
22567 (when with-time
22568 (setq tp (get-text-property (point) 'time))
22569 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22570 (setq hod (string-to-number (match-string 1 tp))
22571 mod (string-to-number (match-string 2 tp))))
22572 (or tp (let ((now (decode-time)))
22573 (setq hod (nth 2 now)
22574 mod (nth 1 now)))))
22575 (cond
22576 ((eq major-mode 'calendar-mode)
22577 (setq date (calendar-cursor-to-date)
22578 defd (encode-time 0 (or mod 0) (or hod 0)
22579 (nth 1 date) (nth 0 date) (nth 2 date))))
22580 ((eq major-mode 'org-agenda-mode)
22581 (setq day (get-text-property (point) 'day))
22582 (when day
22583 (setq date (calendar-gregorian-from-absolute day)
22584 defd (encode-time 0 (or mod 0) (or hod 0)
22585 (nth 1 date) (nth 0 date) (nth 2 date))))))
22586 (or defd (current-time))))
22588 (defun org-mark-subtree (&optional up)
22589 "Mark the current subtree.
22590 This puts point at the start of the current subtree, and mark at
22591 the end. If a numeric prefix UP is given, move up into the
22592 hierarchy of headlines by UP levels before marking the subtree."
22593 (interactive "P")
22594 (org-with-limited-levels
22595 (cond ((org-at-heading-p) (beginning-of-line))
22596 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22597 (t (outline-previous-visible-heading 1))))
22598 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22599 (if (called-interactively-p 'any)
22600 (call-interactively 'org-mark-element)
22601 (org-mark-element)))
22603 (defun org-file-newer-than-p (file time)
22604 "Non-nil if FILE is newer than TIME.
22605 FILE is a filename, as a string, TIME is a list of integers, as
22606 returned by, e.g., `current-time'."
22607 (and (file-exists-p file)
22608 ;; Only compare times up to whole seconds as some file-systems
22609 ;; (e.g. HFS+) do not retain any finer granularity. As
22610 ;; a consequence, make sure we return non-nil when the two
22611 ;; times are equal.
22612 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22613 (cl-subseq time 0 2)))))
22615 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22616 "Compile a SOURCE file using PROCESS.
22618 PROCESS is either a function or a list of shell commands, as
22619 strings. EXT is a file extension, without the leading dot, as
22620 a string. It is used to check if the process actually succeeded.
22622 PROCESS must create a file with the same base name and directory
22623 as SOURCE, but ending with EXT. The function then returns its
22624 filename. Otherwise, it raises an error. The error message can
22625 then be refined by providing string ERR-MSG, which is appended to
22626 the standard message.
22628 If PROCESS is a function, it is called with a single argument:
22629 the SOURCE file.
22631 If it is a list of commands, each of them is called using
22632 `shell-command'. By default, in each command, %b, %f, %F and %o
22633 are replaced with, respectively, SOURCE base name, name, full
22634 name and directory. It is possible, however, to use more
22635 place-holders by specifying them in optional argument SPEC, as an
22636 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22638 When PROCESS is a list of commands, optional argument LOG-BUF can
22639 be set to a buffer or a buffer name. `shell-command' then uses
22640 it for output.
22642 `default-directory' is set to SOURCE directory during the whole
22643 process."
22644 (let* ((source-name (file-name-nondirectory source))
22645 (base-name (file-name-sans-extension source-name))
22646 (full-name (file-truename source))
22647 (out-dir (file-name-directory source))
22648 ;; Properly set working directory for compilation.
22649 (default-directory (file-name-directory full-name))
22650 (time (current-time))
22651 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22652 (save-window-excursion
22653 (pcase process
22654 ((pred functionp) (funcall process (shell-quote-argument source)))
22655 ((pred consp)
22656 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22657 (spec (append spec
22658 `((?b . ,(shell-quote-argument base-name))
22659 (?f . ,(shell-quote-argument source-name))
22660 (?F . ,(shell-quote-argument full-name))
22661 (?o . ,(shell-quote-argument out-dir))))))
22662 (dolist (command process)
22663 (shell-command (format-spec command spec) log-buf))))
22664 (_ (error "No valid command to process %S%s" source err-msg)))
22665 ;; Check for process failure.
22666 (let ((output (concat out-dir base-name "." ext)))
22667 (unless (org-file-newer-than-p output time)
22668 (error (format "File %S wasn't produced%s" output err-msg)))
22669 output))))
22671 ;;; Indentation
22673 (defun org--get-expected-indentation (element contentsp)
22674 "Expected indentation column for current line, according to ELEMENT.
22675 ELEMENT is an element containing point. CONTENTSP is non-nil
22676 when indentation is to be computed according to contents of
22677 ELEMENT."
22678 (let ((type (org-element-type element))
22679 (start (org-element-property :begin element))
22680 (post-affiliated (org-element-property :post-affiliated element)))
22681 (org-with-wide-buffer
22682 (cond
22683 (contentsp
22684 (cl-case type
22685 ((diary-sexp footnote-definition) 0)
22686 ((headline inlinetask nil)
22687 (if (not org-adapt-indentation) 0
22688 (let ((level (org-current-level)))
22689 (if level (1+ level) 0))))
22690 ((item plain-list) (org-list-item-body-column post-affiliated))
22692 (goto-char start)
22693 (org-get-indentation))))
22694 ((memq type '(headline inlinetask nil))
22695 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22696 (org--get-expected-indentation element t)
22698 ((memq type '(diary-sexp footnote-definition)) 0)
22699 ;; First paragraph of a footnote definition or an item.
22700 ;; Indent like parent.
22701 ((< (line-beginning-position) start)
22702 (org--get-expected-indentation
22703 (org-element-property :parent element) t))
22704 ;; At first line: indent according to previous sibling, if any,
22705 ;; ignoring footnote definitions and inline tasks, or parent's
22706 ;; contents.
22707 ((= (line-beginning-position) start)
22708 (catch 'exit
22709 (while t
22710 (if (= (point-min) start) (throw 'exit 0)
22711 (goto-char (1- start))
22712 (let* ((previous (org-element-at-point))
22713 (parent previous))
22714 (while (and parent (<= (org-element-property :end parent) start))
22715 (setq previous parent
22716 parent (org-element-property :parent parent)))
22717 (cond
22718 ((not previous) (throw 'exit 0))
22719 ((> (org-element-property :end previous) start)
22720 (throw 'exit (org--get-expected-indentation previous t)))
22721 ((memq (org-element-type previous)
22722 '(footnote-definition inlinetask))
22723 (setq start (org-element-property :begin previous)))
22724 (t (goto-char (org-element-property :begin previous))
22725 (throw 'exit
22726 (if (bolp) (org-get-indentation)
22727 ;; At first paragraph in an item or
22728 ;; a footnote definition.
22729 (org--get-expected-indentation
22730 (org-element-property :parent previous) t))))))))))
22731 ;; Otherwise, move to the first non-blank line above.
22733 (beginning-of-line)
22734 (let ((pos (point)))
22735 (skip-chars-backward " \r\t\n")
22736 (cond
22737 ;; Two blank lines end a footnote definition or a plain
22738 ;; list. When we indent an empty line after them, the
22739 ;; containing list or footnote definition is over, so it
22740 ;; qualifies as a previous sibling. Therefore, we indent
22741 ;; like its first line.
22742 ((and (memq type '(footnote-definition plain-list))
22743 (> (count-lines (point) pos) 2))
22744 (goto-char start)
22745 (org-get-indentation))
22746 ;; Line above is the first one of a paragraph at the
22747 ;; beginning of an item or a footnote definition. Indent
22748 ;; like parent.
22749 ((< (line-beginning-position) start)
22750 (org--get-expected-indentation
22751 (org-element-property :parent element) t))
22752 ;; Line above is the beginning of an element, i.e., point
22753 ;; was originally on the blank lines between element's start
22754 ;; and contents.
22755 ((= (line-beginning-position) post-affiliated)
22756 (org--get-expected-indentation element t))
22757 ;; POS is after contents in a greater element. Indent like
22758 ;; the beginning of the element.
22760 ;; As a special case, if point is at the end of a footnote
22761 ;; definition or an item, indent like the very last element
22762 ;; within. If that last element is an item, indent like its
22763 ;; contents.
22764 ((and (not (eq type 'paragraph))
22765 (let ((cend (org-element-property :contents-end element)))
22766 (and cend (<= cend pos))))
22767 (if (memq type '(footnote-definition item plain-list))
22768 (let ((last (org-element-at-point)))
22769 (org--get-expected-indentation
22770 last (eq (org-element-type last) 'item)))
22771 (goto-char start)
22772 (org-get-indentation)))
22773 ;; In any other case, indent like the current line.
22774 (t (org-get-indentation)))))))))
22776 (defun org--align-node-property ()
22777 "Align node property at point.
22778 Alignment is done according to `org-property-format', which see."
22779 (when (save-excursion
22780 (beginning-of-line)
22781 (looking-at org-property-re))
22782 (replace-match
22783 (concat (match-string 4)
22784 (org-trim
22785 (format org-property-format (match-string 1) (match-string 3))))
22786 t t)))
22788 (defun org-indent-line ()
22789 "Indent line depending on context.
22791 Indentation is done according to the following rules:
22793 - Footnote definitions, diary sexps, headlines and inline tasks
22794 have to start at column 0.
22796 - On the very first line of an element, consider, in order, the
22797 next rules until one matches:
22799 1. If there's a sibling element before, ignoring footnote
22800 definitions and inline tasks, indent like its first line.
22802 2. If element has a parent, indent like its contents. More
22803 precisely, if parent is an item, indent after the
22804 description part, if any, or the bullet (see
22805 `org-list-description-max-indent'). Else, indent like
22806 parent's first line.
22808 3. Otherwise, indent relatively to current level, if
22809 `org-adapt-indentation' is non-nil, or to left margin.
22811 - On a blank line at the end of an element, indent according to
22812 the type of the element. More precisely
22814 1. If element is a plain list, an item, or a footnote
22815 definition, indent like the very last element within.
22817 2. If element is a paragraph, indent like its last non blank
22818 line.
22820 3. Otherwise, indent like its very first line.
22822 - In the code part of a source block, use language major mode
22823 to indent current line if `org-src-tab-acts-natively' is
22824 non-nil. If it is nil, do nothing.
22826 - Otherwise, indent like the first non-blank line above.
22828 The function doesn't indent an item as it could break the whole
22829 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22830 \\[org-shiftmetaright].
22832 Also align node properties according to `org-property-format'."
22833 (interactive)
22834 (cond
22835 (orgstruct-is-++
22836 (let ((indent-line-function
22837 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22838 (indent-according-to-mode)))
22839 ((org-at-heading-p) 'noindent)
22841 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22842 (type (org-element-type element)))
22843 (cond ((and (memq type '(plain-list item))
22844 (= (line-beginning-position)
22845 (org-element-property :post-affiliated element)))
22846 'noindent)
22847 ((and (eq type 'src-block)
22848 org-src-tab-acts-natively
22849 (> (line-beginning-position)
22850 (org-element-property :post-affiliated element))
22851 (< (line-beginning-position)
22852 (org-with-wide-buffer
22853 (goto-char (org-element-property :end element))
22854 (skip-chars-backward " \r\t\n")
22855 (line-beginning-position))))
22856 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22858 (let ((column (org--get-expected-indentation element nil)))
22859 ;; Preserve current column.
22860 (if (<= (current-column) (current-indentation))
22861 (indent-line-to column)
22862 (save-excursion (indent-line-to column))))
22863 ;; Align node property. Also preserve current column.
22864 (when (eq type 'node-property)
22865 (let ((column (current-column)))
22866 (org--align-node-property)
22867 (org-move-to-column column)))))))))
22869 (defun org-indent-region (start end)
22870 "Indent each non-blank line in the region.
22871 Called from a program, START and END specify the region to
22872 indent. The function will not indent contents of example blocks,
22873 verse blocks and export blocks as leading white spaces are
22874 assumed to be significant there."
22875 (interactive "r")
22876 (save-excursion
22877 (goto-char start)
22878 (skip-chars-forward " \r\t\n")
22879 (unless (eobp) (beginning-of-line))
22880 (let ((indent-to
22881 (lambda (ind pos)
22882 ;; Set IND as indentation for all lines between point and
22883 ;; POS. Blank lines are ignored. Leave point after POS
22884 ;; once done.
22885 (let ((limit (copy-marker pos)))
22886 (while (< (point) limit)
22887 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22888 (forward-line))
22889 (set-marker limit nil))))
22890 (end (copy-marker end)))
22891 (while (< (point) end)
22892 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22893 (let* ((element (org-element-at-point))
22894 (type (org-element-type element))
22895 (element-end (copy-marker (org-element-property :end element)))
22896 (ind (org--get-expected-indentation element nil)))
22897 (cond
22898 ((or (memq type '(paragraph table table-row))
22899 (not (or (org-element-property :contents-begin element)
22900 (memq type
22901 '(example-block export-block src-block)))))
22902 ;; Elements here are indented as a single block. Also
22903 ;; align node properties.
22904 (when (eq type 'node-property)
22905 (org--align-node-property)
22906 (beginning-of-line))
22907 (funcall indent-to ind (min element-end end)))
22909 ;; Elements in this category consist of three parts:
22910 ;; before the contents, the contents, and after the
22911 ;; contents. The contents are treated specially,
22912 ;; according to the element type, or not indented at
22913 ;; all. Other parts are indented as a single block.
22914 (let* ((post (copy-marker
22915 (org-element-property :post-affiliated element)))
22916 (cbeg
22917 (copy-marker
22918 (cond
22919 ((not (org-element-property :contents-begin element))
22920 ;; Fake contents for source blocks.
22921 (org-with-wide-buffer
22922 (goto-char post)
22923 (forward-line)
22924 (point)))
22925 ((memq type '(footnote-definition item plain-list))
22926 ;; Contents in these elements could start on
22927 ;; the same line as the beginning of the
22928 ;; element. Make sure we start indenting
22929 ;; from the second line.
22930 (org-with-wide-buffer
22931 (goto-char post)
22932 (end-of-line)
22933 (skip-chars-forward " \r\t\n")
22934 (if (eobp) (point) (line-beginning-position))))
22935 (t (org-element-property :contents-begin element)))))
22936 (cend (copy-marker
22937 (or (org-element-property :contents-end element)
22938 ;; Fake contents for source blocks.
22939 (org-with-wide-buffer
22940 (goto-char element-end)
22941 (skip-chars-backward " \r\t\n")
22942 (line-beginning-position)))
22943 t)))
22944 ;; Do not change items indentation individually as it
22945 ;; might break the list as a whole. On the other
22946 ;; hand, when at a plain list, indent it as a whole.
22947 (cond ((eq type 'plain-list)
22948 (let ((offset (- ind (org-get-indentation))))
22949 (unless (zerop offset)
22950 (indent-rigidly (org-element-property :begin element)
22951 (org-element-property :end element)
22952 offset))
22953 (goto-char cbeg)))
22954 ((eq type 'item) (goto-char cbeg))
22955 (t (funcall indent-to ind (min cbeg end))))
22956 (when (< (point) end)
22957 (cl-case type
22958 ((example-block export-block verse-block))
22959 (src-block
22960 ;; In a source block, indent source code
22961 ;; according to language major mode, but only if
22962 ;; `org-src-tab-acts-natively' is non-nil.
22963 (when (and (< (point) end) org-src-tab-acts-natively)
22964 (ignore-errors
22965 (org-babel-do-in-edit-buffer
22966 (indent-region (point-min) (point-max))))))
22967 (t (org-indent-region (point) (min cend end))))
22968 (goto-char (min cend end))
22969 (when (< (point) end)
22970 (funcall indent-to ind (min element-end end))))
22971 (set-marker post nil)
22972 (set-marker cbeg nil)
22973 (set-marker cend nil))))
22974 (set-marker element-end nil))))
22975 (set-marker end nil))))
22977 (defun org-indent-drawer ()
22978 "Indent the drawer at point."
22979 (interactive)
22980 (unless (save-excursion
22981 (beginning-of-line)
22982 (looking-at-p org-drawer-regexp))
22983 (user-error "Not at a drawer"))
22984 (let ((element (org-element-at-point)))
22985 (unless (memq (org-element-type element) '(drawer property-drawer))
22986 (user-error "Not at a drawer"))
22987 (org-with-wide-buffer
22988 (org-indent-region (org-element-property :begin element)
22989 (org-element-property :end element))))
22990 (message "Drawer at point indented"))
22992 (defun org-indent-block ()
22993 "Indent the block at point."
22994 (interactive)
22995 (unless (save-excursion
22996 (beginning-of-line)
22997 (let ((case-fold-search t))
22998 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22999 (user-error "Not at a block"))
23000 (let ((element (org-element-at-point)))
23001 (unless (memq (org-element-type element)
23002 '(comment-block center-block dynamic-block example-block
23003 export-block quote-block special-block
23004 src-block verse-block))
23005 (user-error "Not at a block"))
23006 (org-with-wide-buffer
23007 (org-indent-region (org-element-property :begin element)
23008 (org-element-property :end element))))
23009 (message "Block at point indented"))
23012 ;;; Filling
23014 ;; We use our own fill-paragraph and auto-fill functions.
23016 ;; `org-fill-paragraph' relies on adaptive filling and context
23017 ;; checking. Appropriate `fill-prefix' is computed with
23018 ;; `org-adaptive-fill-function'.
23020 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23021 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23022 ;; `org-adaptive-fill-function' value. Internally,
23023 ;; `org-comment-line-break-function' breaks the line.
23025 ;; `org-setup-filling' installs filling and auto-filling related
23026 ;; variables during `org-mode' initialization.
23028 (defvar org-element-paragraph-separate) ; org-element.el
23029 (defun org-setup-filling ()
23030 (require 'org-element)
23031 ;; Prevent auto-fill from inserting unwanted new items.
23032 (when (boundp 'fill-nobreak-predicate)
23033 (setq-local
23034 fill-nobreak-predicate
23035 (org-uniquify
23036 (append fill-nobreak-predicate
23037 '(org-fill-line-break-nobreak-p
23038 org-fill-paragraph-with-timestamp-nobreak-p)))))
23039 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23040 (setq-local paragraph-start paragraph-ending)
23041 (setq-local paragraph-separate paragraph-ending))
23042 (setq-local fill-paragraph-function 'org-fill-paragraph)
23043 (setq-local auto-fill-inhibit-regexp nil)
23044 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23045 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23046 (setq-local comment-line-break-function 'org-comment-line-break-function))
23048 (defun org-fill-line-break-nobreak-p ()
23049 "Non-nil when a new line at point would create an Org line break."
23050 (save-excursion
23051 (skip-chars-backward "[ \t]")
23052 (skip-chars-backward "\\\\")
23053 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23055 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23056 "Non-nil when a new line at point would split a timestamp."
23057 (and (org-at-timestamp-p t)
23058 (not (looking-at org-ts-regexp-both))))
23060 (declare-function message-in-body-p "message" ())
23061 (defvar orgtbl-line-start-regexp) ; From org-table.el
23062 (defun org-adaptive-fill-function ()
23063 "Compute a fill prefix for the current line.
23064 Return fill prefix, as a string, or nil if current line isn't
23065 meant to be filled. For convenience, if `adaptive-fill-regexp'
23066 matches in paragraphs or comments, use it."
23067 (catch 'exit
23068 (when (derived-mode-p 'message-mode)
23069 (save-excursion
23070 (beginning-of-line)
23071 (cond ((not (message-in-body-p)) (throw 'exit nil))
23072 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23073 ((looking-at message-cite-prefix-regexp)
23074 (throw 'exit (match-string-no-properties 0)))
23075 ((looking-at org-outline-regexp)
23076 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23077 (org-with-wide-buffer
23078 (unless (org-at-heading-p)
23079 (let* ((p (line-beginning-position))
23080 (element (save-excursion
23081 (beginning-of-line)
23082 (org-element-at-point)))
23083 (type (org-element-type element))
23084 (post-affiliated (org-element-property :post-affiliated element)))
23085 (unless (< p post-affiliated)
23086 (cl-case type
23087 (comment
23088 (save-excursion
23089 (beginning-of-line)
23090 (looking-at "[ \t]*")
23091 (concat (match-string 0) "# ")))
23092 (footnote-definition "")
23093 ((item plain-list)
23094 (make-string (org-list-item-body-column post-affiliated) ?\s))
23095 (paragraph
23096 ;; Fill prefix is usually the same as the current line,
23097 ;; unless the paragraph is at the beginning of an item.
23098 (let ((parent (org-element-property :parent element)))
23099 (save-excursion
23100 (beginning-of-line)
23101 (cond ((eq (org-element-type parent) 'item)
23102 (make-string (org-list-item-body-column
23103 (org-element-property :begin parent))
23104 ?\s))
23105 ((and adaptive-fill-regexp
23106 ;; Locally disable
23107 ;; `adaptive-fill-function' to let
23108 ;; `fill-context-prefix' handle
23109 ;; `adaptive-fill-regexp' variable.
23110 (let (adaptive-fill-function)
23111 (fill-context-prefix
23112 post-affiliated
23113 (org-element-property :end element)))))
23114 ((looking-at "[ \t]+") (match-string 0))
23115 (t "")))))
23116 (comment-block
23117 ;; Only fill contents if P is within block boundaries.
23118 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23119 (forward-line)
23120 (point)))
23121 (cend (save-excursion
23122 (goto-char (org-element-property :end element))
23123 (skip-chars-backward " \r\t\n")
23124 (line-beginning-position))))
23125 (when (and (>= p cbeg) (< p cend))
23126 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23127 (match-string 0)
23128 "")))))))))))
23130 (declare-function message-goto-body "message" ())
23131 (defvar message-cite-prefix-regexp) ; From message.el
23132 (defun org-fill-paragraph (&optional justify)
23133 "Fill element at point, when applicable.
23135 This function only applies to comment blocks, comments, example
23136 blocks and paragraphs. Also, as a special case, re-align table
23137 when point is at one.
23139 If JUSTIFY is non-nil (interactively, with prefix argument),
23140 justify as well. If `sentence-end-double-space' is non-nil, then
23141 period followed by one space does not end a sentence, so don't
23142 break a line there. The variable `fill-column' controls the
23143 width for filling.
23145 For convenience, when point is at a plain list, an item or
23146 a footnote definition, try to fill the first paragraph within."
23147 (interactive)
23148 (if (and (derived-mode-p 'message-mode)
23149 (or (not (message-in-body-p))
23150 (save-excursion (move-beginning-of-line 1)
23151 (looking-at message-cite-prefix-regexp))))
23152 ;; First ensure filling is correct in message-mode.
23153 (let ((fill-paragraph-function
23154 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23155 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23156 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23157 (paragraph-separate
23158 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23159 (fill-paragraph nil))
23160 (with-syntax-table org-mode-transpose-word-syntax-table
23161 ;; Move to end of line in order to get the first paragraph
23162 ;; within a plain list or a footnote definition.
23163 (let ((element (save-excursion
23164 (end-of-line)
23165 (or (ignore-errors (org-element-at-point))
23166 (user-error "An element cannot be parsed line %d"
23167 (line-number-at-pos (point)))))))
23168 ;; First check if point is in a blank line at the beginning of
23169 ;; the buffer. In that case, ignore filling.
23170 (cl-case (org-element-type element)
23171 ;; Use major mode filling function is src blocks.
23172 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23173 ;; Align Org tables, leave table.el tables as-is.
23174 (table-row (org-table-align) t)
23175 (table
23176 (when (eq (org-element-property :type element) 'org)
23177 (save-excursion
23178 (goto-char (org-element-property :post-affiliated element))
23179 (org-table-align)))
23181 (paragraph
23182 ;; Paragraphs may contain `line-break' type objects.
23183 (let ((beg (max (point-min)
23184 (org-element-property :contents-begin element)))
23185 (end (min (point-max)
23186 (org-element-property :contents-end element))))
23187 ;; Do nothing if point is at an affiliated keyword.
23188 (if (< (line-end-position) beg) t
23189 (when (derived-mode-p 'message-mode)
23190 ;; In `message-mode', do not fill following citation
23191 ;; in current paragraph nor text before message body.
23192 (let ((body-start (save-excursion (message-goto-body))))
23193 (when body-start (setq beg (max body-start beg))))
23194 (when (save-excursion
23195 (re-search-forward
23196 (concat "^" message-cite-prefix-regexp) end t))
23197 (setq end (match-beginning 0))))
23198 ;; Fill paragraph, taking line breaks into account.
23199 (save-excursion
23200 (goto-char beg)
23201 (let ((cuts (list beg)))
23202 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23203 (when (eq 'line-break
23204 (org-element-type
23205 (save-excursion (backward-char)
23206 (org-element-context))))
23207 (push (point) cuts)))
23208 (dolist (c (delq end cuts))
23209 (fill-region-as-paragraph c end justify)
23210 (setq end c))))
23211 t)))
23212 ;; Contents of `comment-block' type elements should be
23213 ;; filled as plain text, but only if point is within block
23214 ;; markers.
23215 (comment-block
23216 (let* ((case-fold-search t)
23217 (beg (save-excursion
23218 (goto-char (org-element-property :begin element))
23219 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23220 (forward-line)
23221 (point)))
23222 (end (save-excursion
23223 (goto-char (org-element-property :end element))
23224 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23225 (line-beginning-position))))
23226 (if (or (< (point) beg) (> (point) end)) t
23227 (fill-region-as-paragraph
23228 (save-excursion (end-of-line)
23229 (re-search-backward "^[ \t]*$" beg 'move)
23230 (line-beginning-position))
23231 (save-excursion (beginning-of-line)
23232 (re-search-forward "^[ \t]*$" end 'move)
23233 (line-beginning-position))
23234 justify))))
23235 ;; Fill comments.
23236 (comment
23237 (let ((begin (org-element-property :post-affiliated element))
23238 (end (org-element-property :end element)))
23239 (when (and (>= (point) begin) (<= (point) end))
23240 (let ((begin (save-excursion
23241 (end-of-line)
23242 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23243 (progn (forward-line) (point))
23244 begin)))
23245 (end (save-excursion
23246 (end-of-line)
23247 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23248 (1- (line-beginning-position))
23249 (skip-chars-backward " \r\t\n")
23250 (line-end-position)))))
23251 ;; Do not fill comments when at a blank line.
23252 (when (> end begin)
23253 (let ((fill-prefix
23254 (save-excursion
23255 (beginning-of-line)
23256 (looking-at "[ \t]*#")
23257 (let ((comment-prefix (match-string 0)))
23258 (goto-char (match-end 0))
23259 (if (looking-at adaptive-fill-regexp)
23260 (concat comment-prefix (match-string 0))
23261 (concat comment-prefix " "))))))
23262 (save-excursion
23263 (fill-region-as-paragraph begin end justify))))))
23265 ;; Ignore every other element.
23266 (otherwise t))))))
23268 (defun org-auto-fill-function ()
23269 "Auto-fill function."
23270 ;; Check if auto-filling is meaningful.
23271 (let ((fc (current-fill-column)))
23272 (when (and fc (> (current-column) fc))
23273 (let* ((fill-prefix (org-adaptive-fill-function))
23274 ;; Enforce empty fill prefix, if required. Otherwise, it
23275 ;; will be computed again.
23276 (adaptive-fill-mode (not (equal fill-prefix ""))))
23277 (when fill-prefix (do-auto-fill))))))
23279 (defun org-comment-line-break-function (&optional soft)
23280 "Break line at point and indent, continuing comment if within one.
23281 The inserted newline is marked hard if variable
23282 `use-hard-newlines' is true, unless optional argument SOFT is
23283 non-nil."
23284 (if soft (insert-and-inherit ?\n) (newline 1))
23285 (save-excursion (forward-char -1) (delete-horizontal-space))
23286 (delete-horizontal-space)
23287 (indent-to-left-margin)
23288 (insert-before-markers-and-inherit fill-prefix))
23291 ;;; Fixed Width Areas
23293 (defun org-toggle-fixed-width ()
23294 "Toggle fixed-width markup.
23296 Add or remove fixed-width markup on current line, whenever it
23297 makes sense. Return an error otherwise.
23299 If a region is active and if it contains only fixed-width areas
23300 or blank lines, remove all fixed-width markup in it. If the
23301 region contains anything else, convert all non-fixed-width lines
23302 to fixed-width ones.
23304 Blank lines at the end of the region are ignored unless the
23305 region only contains such lines."
23306 (interactive)
23307 (if (not (org-region-active-p))
23308 ;; No region:
23310 ;; Remove fixed width marker only in a fixed-with element.
23312 ;; Add fixed width maker in paragraphs, in blank lines after
23313 ;; elements or at the beginning of a headline or an inlinetask,
23314 ;; and before any one-line elements (e.g., a clock).
23315 (progn
23316 (beginning-of-line)
23317 (let* ((element (org-element-at-point))
23318 (type (org-element-type element)))
23319 (cond
23320 ((and (eq type 'fixed-width)
23321 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23322 (replace-match
23323 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23324 ((and (memq type '(babel-call clock comment diary-sexp headline
23325 horizontal-rule keyword paragraph
23326 planning))
23327 (<= (org-element-property :post-affiliated element) (point)))
23328 (skip-chars-forward " \t")
23329 (insert ": "))
23330 ((and (looking-at-p "[ \t]*$")
23331 (or (eq type 'inlinetask)
23332 (save-excursion
23333 (skip-chars-forward " \r\t\n")
23334 (<= (org-element-property :end element) (point)))))
23335 (delete-region (point) (line-end-position))
23336 (org-indent-line)
23337 (insert ": "))
23338 (t (user-error "Cannot insert a fixed-width line here")))))
23339 ;; Region active.
23340 (let* ((begin (save-excursion
23341 (goto-char (region-beginning))
23342 (line-beginning-position)))
23343 (end (copy-marker
23344 (save-excursion
23345 (goto-char (region-end))
23346 (unless (eolp) (beginning-of-line))
23347 (if (save-excursion (re-search-backward "\\S-" begin t))
23348 (progn (skip-chars-backward " \r\t\n") (point))
23349 (point)))))
23350 (all-fixed-width-p
23351 (catch 'not-all-p
23352 (save-excursion
23353 (goto-char begin)
23354 (skip-chars-forward " \r\t\n")
23355 (when (eobp) (throw 'not-all-p nil))
23356 (while (< (point) end)
23357 (let ((element (org-element-at-point)))
23358 (if (eq (org-element-type element) 'fixed-width)
23359 (goto-char (org-element-property :end element))
23360 (throw 'not-all-p nil))))
23361 t))))
23362 (if all-fixed-width-p
23363 (save-excursion
23364 (goto-char begin)
23365 (while (< (point) end)
23366 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23367 (replace-match
23368 "" nil nil nil
23369 (if (= (line-end-position) (match-end 0)) 0 1)))
23370 (forward-line)))
23371 (let ((min-ind (point-max)))
23372 ;; Find minimum indentation across all lines.
23373 (save-excursion
23374 (goto-char begin)
23375 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23376 (setq min-ind 0)
23377 (catch 'zerop
23378 (while (< (point) end)
23379 (unless (looking-at-p "[ \t]*$")
23380 (let ((ind (org-get-indentation)))
23381 (setq min-ind (min min-ind ind))
23382 (when (zerop ind) (throw 'zerop t))))
23383 (forward-line)))))
23384 ;; Loop over all lines and add fixed-width markup everywhere
23385 ;; but in fixed-width lines.
23386 (save-excursion
23387 (goto-char begin)
23388 (while (< (point) end)
23389 (cond
23390 ((org-at-heading-p)
23391 (insert ": ")
23392 (forward-line)
23393 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23394 (insert ":")
23395 (forward-line)))
23396 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23397 (let* ((element (org-element-at-point))
23398 (element-end (org-element-property :end element)))
23399 (if (eq (org-element-type element) 'fixed-width)
23400 (progn (goto-char element-end)
23401 (skip-chars-backward " \r\t\n")
23402 (forward-line))
23403 (let ((limit (min end element-end)))
23404 (while (< (point) limit)
23405 (org-move-to-column min-ind t)
23406 (insert ": ")
23407 (forward-line))))))
23409 (org-move-to-column min-ind t)
23410 (insert ": ")
23411 (forward-line)))))))
23412 (set-marker end nil))))
23415 ;;; Comments
23417 ;; Org comments syntax is quite complex. It requires the entire line
23418 ;; to be just a comment. Also, even with the right syntax at the
23419 ;; beginning of line, some some elements (i.e. verse-block or
23420 ;; example-block) don't accept comments. Usual Emacs comment commands
23421 ;; cannot cope with those requirements. Therefore, Org replaces them.
23423 ;; Org still relies on `comment-dwim', but cannot trust
23424 ;; `comment-only-p'. So, `comment-region-function' and
23425 ;; `uncomment-region-function' both point
23426 ;; to`org-comment-or-uncomment-region'. Eventually,
23427 ;; `org-insert-comment' takes care of insertion of comments at the
23428 ;; beginning of line.
23430 ;; `org-setup-comments-handling' install comments related variables
23431 ;; during `org-mode' initialization.
23433 (defun org-setup-comments-handling ()
23434 (interactive)
23435 (setq-local comment-use-syntax nil)
23436 (setq-local comment-start "# ")
23437 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23438 (setq-local comment-insert-comment-function 'org-insert-comment)
23439 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23440 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23442 (defun org-insert-comment ()
23443 "Insert an empty comment above current line.
23444 If the line is empty, insert comment at its beginning. When
23445 point is within a source block, comment according to the related
23446 major mode."
23447 (if (let ((element (org-element-at-point)))
23448 (and (eq (org-element-type element) 'src-block)
23449 (< (save-excursion
23450 (goto-char (org-element-property :post-affiliated element))
23451 (line-end-position))
23452 (point))
23453 (> (save-excursion
23454 (goto-char (org-element-property :end element))
23455 (skip-chars-backward " \r\t\n")
23456 (line-beginning-position))
23457 (point))))
23458 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23459 (beginning-of-line)
23460 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23461 (open-line 1))
23462 (org-indent-line)
23463 (insert "# ")))
23465 (defvar comment-empty-lines) ; From newcomment.el.
23466 (defun org-comment-or-uncomment-region (beg end &rest _)
23467 "Comment or uncomment each non-blank line in the region.
23468 Uncomment each non-blank line between BEG and END if it only
23469 contains commented lines. Otherwise, comment them. If region is
23470 strictly within a source block, use appropriate comment syntax."
23471 (if (let ((element (org-element-at-point)))
23472 (and (eq (org-element-type element) 'src-block)
23473 (< (save-excursion
23474 (goto-char (org-element-property :post-affiliated element))
23475 (line-end-position))
23476 beg)
23477 (>= (save-excursion
23478 (goto-char (org-element-property :end element))
23479 (skip-chars-backward " \r\t\n")
23480 (line-beginning-position))
23481 end)))
23482 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23483 (save-restriction
23484 ;; Restrict region
23485 (narrow-to-region (save-excursion (goto-char beg)
23486 (skip-chars-forward " \r\t\n" end)
23487 (line-beginning-position))
23488 (save-excursion (goto-char end)
23489 (skip-chars-backward " \r\t\n" beg)
23490 (line-end-position)))
23491 (let ((uncommentp
23492 ;; UNCOMMENTP is non-nil when every non blank line between
23493 ;; BEG and END is a comment.
23494 (save-excursion
23495 (goto-char (point-min))
23496 (while (and (not (eobp))
23497 (let ((element (org-element-at-point)))
23498 (and (eq (org-element-type element) 'comment)
23499 (goto-char (min (point-max)
23500 (org-element-property
23501 :end element)))))))
23502 (eobp))))
23503 (if uncommentp
23504 ;; Only blank lines and comments in region: uncomment it.
23505 (save-excursion
23506 (goto-char (point-min))
23507 (while (not (eobp))
23508 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23509 (replace-match "" nil nil nil 1))
23510 (forward-line)))
23511 ;; Comment each line in region.
23512 (let ((min-indent (point-max)))
23513 ;; First find the minimum indentation across all lines.
23514 (save-excursion
23515 (goto-char (point-min))
23516 (while (and (not (eobp)) (not (zerop min-indent)))
23517 (unless (looking-at "[ \t]*$")
23518 (setq min-indent (min min-indent (current-indentation))))
23519 (forward-line)))
23520 ;; Then loop over all lines.
23521 (save-excursion
23522 (goto-char (point-min))
23523 (while (not (eobp))
23524 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23525 ;; Don't get fooled by invisible text (e.g. link path)
23526 ;; when moving to column MIN-INDENT.
23527 (let ((buffer-invisibility-spec nil))
23528 (org-move-to-column min-indent t))
23529 (insert comment-start))
23530 (forward-line)))))))))
23532 (defun org-comment-dwim (_arg)
23533 "Call `comment-dwim' within a source edit buffer if needed."
23534 (interactive "*P")
23535 (if (org-in-src-block-p)
23536 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23537 (call-interactively 'comment-dwim)))
23540 ;;; Timestamps API
23542 ;; This section contains tools to operate on timestamp objects, as
23543 ;; returned by, e.g. `org-element-context'.
23545 (defun org-timestamp--to-internal-time (timestamp &optional end)
23546 "Encode TIMESTAMP object into Emacs internal time.
23547 Use end of date range or time range when END is non-nil."
23548 (apply #'encode-time
23549 (cons 0
23550 (mapcar
23551 (lambda (prop) (or (org-element-property prop timestamp) 0))
23552 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23553 '(:minute-start :hour-start :day-start :month-start
23554 :year-start))))))
23556 (defun org-timestamp-has-time-p (timestamp)
23557 "Non-nil when TIMESTAMP has a time specified."
23558 (org-element-property :hour-start timestamp))
23560 (defun org-timestamp-format (timestamp format &optional end utc)
23561 "Format a TIMESTAMP object into a string.
23563 FORMAT is a format specifier to be passed to
23564 `format-time-string'.
23566 When optional argument END is non-nil, use end of date-range or
23567 time-range, if possible.
23569 When optional argument UTC is non-nil, time will be expressed as
23570 Universal Time."
23571 (format-time-string
23572 format (org-timestamp--to-internal-time timestamp end)
23573 (and utc t)))
23575 (defun org-timestamp-split-range (timestamp &optional end)
23576 "Extract a TIMESTAMP object from a date or time range.
23578 END, when non-nil, means extract the end of the range.
23579 Otherwise, extract its start.
23581 Return a new timestamp object."
23582 (let ((type (org-element-property :type timestamp)))
23583 (if (memq type '(active inactive diary)) timestamp
23584 (let ((split-ts (org-element-copy timestamp)))
23585 ;; Set new type.
23586 (org-element-put-property
23587 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23588 ;; Copy start properties over end properties if END is
23589 ;; non-nil. Otherwise, copy end properties over `start' ones.
23590 (let ((p-alist '((:minute-start . :minute-end)
23591 (:hour-start . :hour-end)
23592 (:day-start . :day-end)
23593 (:month-start . :month-end)
23594 (:year-start . :year-end))))
23595 (dolist (p-cell p-alist)
23596 (org-element-put-property
23597 split-ts
23598 (funcall (if end #'car #'cdr) p-cell)
23599 (org-element-property
23600 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23601 ;; Eventually refresh `:raw-value'.
23602 (org-element-put-property split-ts :raw-value nil)
23603 (org-element-put-property
23604 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23606 (defun org-timestamp-translate (timestamp &optional boundary)
23607 "Translate TIMESTAMP object to custom format.
23609 Format string is defined in `org-time-stamp-custom-formats',
23610 which see.
23612 When optional argument BOUNDARY is non-nil, it is either the
23613 symbol `start' or `end'. In this case, only translate the
23614 starting or ending part of TIMESTAMP if it is a date or time
23615 range. Otherwise, translate both parts.
23617 Return timestamp as-is if `org-display-custom-times' is nil or if
23618 it has a `diary' type."
23619 (let ((type (org-element-property :type timestamp)))
23620 (if (or (not org-display-custom-times) (eq type 'diary))
23621 (org-element-interpret-data timestamp)
23622 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23623 org-time-stamp-custom-formats)))
23624 (if (and (not boundary) (memq type '(active-range inactive-range)))
23625 (concat (org-timestamp-format timestamp fmt)
23626 "--"
23627 (org-timestamp-format timestamp fmt t))
23628 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23632 ;;; Other stuff.
23634 (defvar reftex-docstruct-symbol)
23635 (defvar reftex-cite-format)
23636 (defvar org--rds)
23638 (defun org-reftex-citation ()
23639 "Use reftex-citation to insert a citation into the buffer.
23640 This looks for a line like
23642 #+BIBLIOGRAPHY: foo plain option:-d
23644 and derives from it that foo.bib is the bibliography file relevant
23645 for this document. It then installs the necessary environment for RefTeX
23646 to work in this buffer and calls `reftex-citation' to insert a citation
23647 into the buffer.
23649 Export of such citations to both LaTeX and HTML is handled by the contributed
23650 package ox-bibtex by Taru Karttunen."
23651 (interactive)
23652 (let ((reftex-docstruct-symbol 'org--rds)
23653 (reftex-cite-format "\\cite{%l}")
23654 org--rds bib)
23655 (save-excursion
23656 (save-restriction
23657 (widen)
23658 (let ((case-fold-search t)
23659 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23660 (if (not (save-excursion
23661 (or (re-search-forward re nil t)
23662 (re-search-backward re nil t))))
23663 (user-error "No bibliography defined in file")
23664 (setq bib (concat (match-string 1) ".bib")
23665 org--rds (list (list 'bib bib)))))))
23666 (call-interactively 'reftex-citation)))
23668 ;;;; Functions extending outline functionality
23670 (defun org-beginning-of-line (&optional arg)
23671 "Go to the beginning of the current line. If that is invisible, continue
23672 to a visible line beginning. This makes the function of C-a more intuitive.
23673 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23674 first attempt, and only move to after the tags when the cursor is already
23675 beyond the end of the headline."
23676 (interactive "P")
23677 (let ((pos (point))
23678 (special (if (consp org-special-ctrl-a/e)
23679 (car org-special-ctrl-a/e)
23680 org-special-ctrl-a/e))
23681 deactivate-mark refpos)
23682 (call-interactively (if (bound-and-true-p visual-line-mode)
23683 #'beginning-of-visual-line
23684 #'move-beginning-of-line))
23685 (cond
23686 ((or arg (not special)))
23687 ((and (looking-at org-complex-heading-regexp)
23688 (eq (char-after (match-end 1)) ?\s))
23689 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23690 (point-at-eol)))
23691 (goto-char
23692 (if (eq special t)
23693 (cond ((> pos refpos) refpos)
23694 ((= pos (point)) refpos)
23695 (t (point)))
23696 (cond ((> pos (point)) (point))
23697 ((not (eq last-command this-command)) (point))
23698 (t refpos)))))
23699 ((org-at-item-p)
23700 ;; Being at an item and not looking at an the item means point
23701 ;; was previously moved to beginning of a visual line, which
23702 ;; doesn't contain the item. Therefore, do nothing special,
23703 ;; just stay here.
23704 (when (looking-at org-list-full-item-re)
23705 ;; Set special position at first white space character after
23706 ;; bullet, and check-box, if any.
23707 (let ((after-bullet
23708 (let ((box (match-end 3)))
23709 (if (not box) (match-end 1)
23710 (let ((after (char-after box)))
23711 (if (and after (= after ? )) (1+ box) box))))))
23712 ;; Special case: Move point to special position when
23713 ;; currently after it or at beginning of line.
23714 (if (eq special t)
23715 (when (or (> pos after-bullet) (= (point) pos))
23716 (goto-char after-bullet))
23717 ;; Reversed case: Move point to special position when
23718 ;; point was already at beginning of line and command is
23719 ;; repeated.
23720 (when (and (= (point) pos) (eq last-command this-command))
23721 (goto-char after-bullet))))))))
23722 (setq disable-point-adjustment
23723 (or (not (invisible-p (point)))
23724 (not (invisible-p (max (point-min) (1- (point))))))))
23726 (defun org-end-of-line (&optional arg)
23727 "Go to the end of the line.
23728 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23729 tags on the first attempt, and only move to after the tags when
23730 the cursor is already beyond the end of the headline."
23731 (interactive "P")
23732 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23733 org-special-ctrl-a/e))
23734 (move-fun (cond ((bound-and-true-p visual-line-mode)
23735 'end-of-visual-line)
23736 ((fboundp 'move-end-of-line) 'move-end-of-line)
23737 (t 'end-of-line)))
23738 deactivate-mark)
23739 (if (or (not special) arg) (call-interactively move-fun)
23740 (let* ((element (save-excursion (beginning-of-line)
23741 (org-element-at-point)))
23742 (type (org-element-type element)))
23743 (cond
23744 ((memq type '(headline inlinetask))
23745 (let ((pos (point)))
23746 (beginning-of-line 1)
23747 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23748 (if (eq special t)
23749 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23750 (goto-char (match-beginning 1))
23751 (goto-char (match-end 0)))
23752 (if (or (< pos (match-end 0))
23753 (not (eq this-command last-command)))
23754 (goto-char (match-end 0))
23755 (goto-char (match-beginning 1))))
23756 (call-interactively move-fun))))
23757 ((outline-invisible-p (line-end-position))
23758 ;; If element is hidden, `move-end-of-line' would put point
23759 ;; after it. Use `end-of-line' to stay on current line.
23760 (call-interactively 'end-of-line))
23761 (t (call-interactively move-fun))))))
23762 (setq disable-point-adjustment
23763 (or (not (invisible-p (point)))
23764 (not (invisible-p (max (point-min) (1- (point))))))))
23766 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23767 (define-key org-mode-map "\C-e" 'org-end-of-line)
23769 (defun org-backward-sentence (&optional _arg)
23770 "Go to beginning of sentence, or beginning of table field.
23771 This will call `backward-sentence' or `org-table-beginning-of-field',
23772 depending on context."
23773 (interactive)
23774 (let* ((element (org-element-at-point))
23775 (contents-begin (org-element-property :contents-begin element))
23776 (table (org-element-lineage element '(table) t)))
23777 (if (and table
23778 (> (point) contents-begin)
23779 (<= (point) (org-element-property :contents-end table)))
23780 (call-interactively #'org-table-beginning-of-field)
23781 (save-restriction
23782 (when (and contents-begin
23783 (< (point-min) contents-begin)
23784 (> (point) contents-begin))
23785 (narrow-to-region contents-begin
23786 (org-element-property :contents-end element)))
23787 (call-interactively #'backward-sentence)))))
23789 (defun org-forward-sentence (&optional _arg)
23790 "Go to end of sentence, or end of table field.
23791 This will call `forward-sentence' or `org-table-end-of-field',
23792 depending on context."
23793 (interactive)
23794 (let* ((element (org-element-at-point))
23795 (contents-end (org-element-property :contents-end element))
23796 (table (org-element-lineage element '(table) t)))
23797 (if (and table
23798 (>= (point) (org-element-property :contents-begin table))
23799 (< (point) contents-end))
23800 (call-interactively #'org-table-end-of-field)
23801 (save-restriction
23802 (when (and contents-end
23803 (> (point-max) contents-end)
23804 ;; Skip blank lines between elements.
23805 (< (org-element-property :end element)
23806 (save-excursion (goto-char contents-end)
23807 (skip-chars-forward " \r\t\n"))))
23808 (narrow-to-region (org-element-property :contents-begin element)
23809 contents-end))
23810 (call-interactively #'forward-sentence)))))
23812 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23813 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23815 (defun org-kill-line (&optional _arg)
23816 "Kill line, to tags or end of line."
23817 (interactive)
23818 (cond
23819 ((or (not org-special-ctrl-k)
23820 (bolp)
23821 (not (org-at-heading-p)))
23822 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23823 org-ctrl-k-protect-subtree
23824 (or (eq org-ctrl-k-protect-subtree 'error)
23825 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23826 (user-error "C-k aborted as it would kill a hidden subtree"))
23827 (call-interactively
23828 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23829 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23830 (kill-region (point) (match-beginning 1))
23831 (org-set-tags nil t))
23832 (t (kill-region (point) (point-at-eol)))))
23834 (define-key org-mode-map "\C-k" 'org-kill-line)
23836 (defun org-yank (&optional arg)
23837 "Yank. If the kill is a subtree, treat it specially.
23838 This command will look at the current kill and check if is a single
23839 subtree, or a series of subtrees[1]. If it passes the test, and if the
23840 cursor is at the beginning of a line or after the stars of a currently
23841 empty headline, then the yank is handled specially. How exactly depends
23842 on the value of the following variables.
23844 `org-yank-folded-subtrees'
23845 By default, this variable is non-nil, which results in subtree(s)
23846 being folded after insertion, but only if doing so would now
23847 swallow text after the yanked text.
23849 `org-yank-adjusted-subtrees'
23850 When non-nil (the default value is nil), the subtree will be
23851 promoted or demoted in order to fit into the local outline tree
23852 structure, which means that the level will be adjusted so that it
23853 becomes the smaller one of the two *visible* surrounding headings.
23855 Any prefix to this command will cause `yank' to be called directly with
23856 no special treatment. In particular, a simple \\[universal-argument] prefix \
23857 will just
23858 plainly yank the text as it is.
23860 \[1] The test checks if the first non-white line is a heading
23861 and if there are no other headings with fewer stars."
23862 (interactive "P")
23863 (org-yank-generic 'yank arg))
23865 (defun org-yank-generic (command arg)
23866 "Perform some yank-like command.
23868 This function implements the behavior described in the `org-yank'
23869 documentation. However, it has been generalized to work for any
23870 interactive command with similar behavior."
23872 ;; pretend to be command COMMAND
23873 (setq this-command command)
23875 (if arg
23876 (call-interactively command)
23878 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23879 (and (org-kill-is-subtree-p)
23880 (or (bolp)
23881 (and (looking-at "[ \t]*$")
23882 (string-match
23883 "\\`\\*+\\'"
23884 (buffer-substring (point-at-bol) (point)))))))
23885 swallowp)
23886 (cond
23887 ((and subtreep org-yank-folded-subtrees)
23888 (let ((beg (point))
23889 end)
23890 (if (and subtreep org-yank-adjusted-subtrees)
23891 (org-paste-subtree nil nil 'for-yank)
23892 (call-interactively command))
23894 (setq end (point))
23895 (goto-char beg)
23896 (when (and (bolp) subtreep
23897 (not (setq swallowp
23898 (org-yank-folding-would-swallow-text beg end))))
23899 (org-with-limited-levels
23900 (or (looking-at org-outline-regexp)
23901 (re-search-forward org-outline-regexp-bol end t))
23902 (while (and (< (point) end) (looking-at org-outline-regexp))
23903 (outline-hide-subtree)
23904 (org-cycle-show-empty-lines 'folded)
23905 (condition-case nil
23906 (outline-forward-same-level 1)
23907 (error (goto-char end))))))
23908 (when swallowp
23909 (message
23910 "Inserted text not folded because that would swallow text"))
23912 (goto-char end)
23913 (skip-chars-forward " \t\n\r")
23914 (beginning-of-line 1)
23915 (push-mark beg 'nomsg)))
23916 ((and subtreep org-yank-adjusted-subtrees)
23917 (let ((beg (point-at-bol)))
23918 (org-paste-subtree nil nil 'for-yank)
23919 (push-mark beg 'nomsg)))
23921 (call-interactively command))))))
23923 (defun org-yank-folding-would-swallow-text (beg end)
23924 "Would hide-subtree at BEG swallow any text after END?"
23925 (let (level)
23926 (org-with-limited-levels
23927 (save-excursion
23928 (goto-char beg)
23929 (when (or (looking-at org-outline-regexp)
23930 (re-search-forward org-outline-regexp-bol end t))
23931 (setq level (org-outline-level)))
23932 (goto-char end)
23933 (skip-chars-forward " \t\r\n\v\f")
23934 (not (or (eobp)
23935 (and (bolp) (looking-at-p org-outline-regexp)
23936 (<= (org-outline-level) level))))))))
23938 (define-key org-mode-map "\C-y" 'org-yank)
23940 (defun org-truely-invisible-p ()
23941 "Check if point is at a character currently not visible.
23942 This version does not only check the character property, but also
23943 `visible-mode'."
23944 ;; Early versions of noutline don't have `outline-invisible-p'.
23945 (unless (bound-and-true-p visible-mode)
23946 (outline-invisible-p)))
23948 (defun org-invisible-p2 ()
23949 "Check if point is at a character currently not visible."
23950 (save-excursion
23951 (when (and (eolp) (not (bobp))) (backward-char 1))
23952 ;; Early versions of noutline don't have `outline-invisible-p'.
23953 (outline-invisible-p)))
23955 (defun org-back-to-heading (&optional invisible-ok)
23956 "Call `outline-back-to-heading', but provide a better error message."
23957 (condition-case nil
23958 (outline-back-to-heading invisible-ok)
23959 (error (error "Before first headline at position %d in buffer %s"
23960 (point) (current-buffer)))))
23962 (defun org-before-first-heading-p ()
23963 "Before first heading?"
23964 (save-excursion
23965 (end-of-line)
23966 (null (re-search-backward org-outline-regexp-bol nil t))))
23968 (defun org-at-heading-p (&optional ignored)
23969 (outline-on-heading-p t))
23971 (defun org-in-commented-heading-p (&optional no-inheritance)
23972 "Non-nil if point is under a commented heading.
23973 This function also checks ancestors of the current headline,
23974 unless optional argument NO-INHERITANCE is non-nil."
23975 (cond
23976 ((org-before-first-heading-p) nil)
23977 ((let ((headline (nth 4 (org-heading-components))))
23978 (and headline
23979 (let ((case-fold-search nil))
23980 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23981 headline)))))
23982 (no-inheritance nil)
23984 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23986 (defun org-at-comment-p nil
23987 "Is cursor in a commented line?"
23988 (save-excursion
23989 (save-match-data
23990 (beginning-of-line)
23991 (looking-at "^[ \t]*# "))))
23993 (defun org-at-drawer-p nil
23994 "Is cursor at a drawer keyword?"
23995 (save-excursion
23996 (move-beginning-of-line 1)
23997 (looking-at org-drawer-regexp)))
23999 (defun org-at-block-p nil
24000 "Is cursor at a block keyword?"
24001 (save-excursion
24002 (move-beginning-of-line 1)
24003 (looking-at org-block-regexp)))
24005 (defun org-point-at-end-of-empty-headline ()
24006 "If point is at the end of an empty headline, return t, else nil.
24007 If the heading only contains a TODO keyword, it is still still considered
24008 empty."
24009 (and (looking-at "[ \t]*$")
24010 (when org-todo-line-regexp
24011 (save-excursion
24012 (beginning-of-line 1)
24013 (let ((case-fold-search nil))
24014 (looking-at org-todo-line-regexp)
24015 (string= (match-string 3) ""))))))
24017 (defun org-at-heading-or-item-p ()
24018 (or (org-at-heading-p) (org-at-item-p)))
24020 (defun org-at-target-p ()
24021 (or (org-in-regexp org-radio-target-regexp)
24022 (org-in-regexp org-target-regexp)))
24023 ;; Compatibility alias with Org versions < 7.8.03
24024 (defalias 'org-on-target-p 'org-at-target-p)
24026 (defun org-up-heading-all (arg)
24027 "Move to the heading line of which the present line is a subheading.
24028 This function considers both visible and invisible heading lines.
24029 With argument, move up ARG levels."
24030 (outline-up-heading arg t))
24032 (defun org-up-heading-safe ()
24033 "Move to the heading line of which the present line is a subheading.
24034 This version will not throw an error. It will return the level of the
24035 headline found, or nil if no higher level is found.
24037 Also, this function will be a lot faster than `outline-up-heading',
24038 because it relies on stars being the outline starters. This can really
24039 make a significant difference in outlines with very many siblings."
24040 (when (ignore-errors (org-back-to-heading t))
24041 (let ((level-up (1- (funcall outline-level))))
24042 (and (> level-up 0)
24043 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24044 (funcall outline-level)))))
24046 (defun org-first-sibling-p ()
24047 "Is this heading the first child of its parents?"
24048 (interactive)
24049 (let ((re org-outline-regexp-bol)
24050 level l)
24051 (unless (org-at-heading-p t)
24052 (user-error "Not at a heading"))
24053 (setq level (funcall outline-level))
24054 (save-excursion
24055 (if (not (re-search-backward re nil t))
24057 (setq l (funcall outline-level))
24058 (< l level)))))
24060 (defun org-goto-sibling (&optional previous)
24061 "Goto the next sibling, even if it is invisible.
24062 When PREVIOUS is set, go to the previous sibling instead. Returns t
24063 when a sibling was found. When none is found, return nil and don't
24064 move point."
24065 (let ((fun (if previous 're-search-backward 're-search-forward))
24066 (pos (point))
24067 (re org-outline-regexp-bol)
24068 level l)
24069 (when (ignore-errors (org-back-to-heading t))
24070 (setq level (funcall outline-level))
24071 (catch 'exit
24072 (or previous (forward-char 1))
24073 (while (funcall fun re nil t)
24074 (setq l (funcall outline-level))
24075 (when (< l level) (goto-char pos) (throw 'exit nil))
24076 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24077 (goto-char pos)
24078 nil))))
24080 (defun org-show-siblings ()
24081 "Show all siblings of the current headline."
24082 (save-excursion
24083 (while (org-goto-sibling) (org-flag-heading nil)))
24084 (save-excursion
24085 (while (org-goto-sibling 'previous)
24086 (org-flag-heading nil))))
24088 (defun org-goto-first-child ()
24089 "Goto the first child, even if it is invisible.
24090 Return t when a child was found. Otherwise don't move point and
24091 return nil."
24092 (let (level (pos (point)) (re org-outline-regexp-bol))
24093 (when (ignore-errors (org-back-to-heading t))
24094 (setq level (outline-level))
24095 (forward-char 1)
24096 (if (and (re-search-forward re nil t) (> (outline-level) level))
24097 (progn (goto-char (match-beginning 0)) t)
24098 (goto-char pos) nil))))
24100 (defun org-show-hidden-entry ()
24101 "Show an entry where even the heading is hidden."
24102 (save-excursion
24103 (org-show-entry)))
24105 (defun org-flag-heading (flag &optional entry)
24106 "Flag the current heading. FLAG non-nil means make invisible.
24107 When ENTRY is non-nil, show the entire entry."
24108 (save-excursion
24109 (org-back-to-heading t)
24110 ;; Check if we should show the entire entry
24111 (if entry
24112 (progn
24113 (org-show-entry)
24114 (save-excursion
24115 (and (outline-next-heading)
24116 (org-flag-heading nil))))
24117 (outline-flag-region (max (point-min) (1- (point)))
24118 (save-excursion (outline-end-of-heading) (point))
24119 flag))))
24121 (defun org-get-next-sibling ()
24122 "Move to next heading of the same level, and return point.
24123 If there is no such heading, return nil.
24124 This is like outline-next-sibling, but invisible headings are ok."
24125 (let ((level (funcall outline-level)))
24126 (outline-next-heading)
24127 (while (and (not (eobp)) (> (funcall outline-level) level))
24128 (outline-next-heading))
24129 (unless (or (eobp) (< (funcall outline-level) level))
24130 (point))))
24132 (defun org-get-last-sibling ()
24133 "Move to previous heading of the same level, and return point.
24134 If there is no such heading, return nil."
24135 (let ((opoint (point))
24136 (level (funcall outline-level)))
24137 (outline-previous-heading)
24138 (when (and (/= (point) opoint) (outline-on-heading-p t))
24139 (while (and (> (funcall outline-level) level)
24140 (not (bobp)))
24141 (outline-previous-heading))
24142 (unless (< (funcall outline-level) level)
24143 (point)))))
24145 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24146 "Goto to the end of a subtree."
24147 ;; This contains an exact copy of the original function, but it uses
24148 ;; `org-back-to-heading', to make it work also in invisible
24149 ;; trees. And is uses an invisible-ok argument.
24150 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24151 ;; Furthermore, when used inside Org, finding the end of a large subtree
24152 ;; with many children and grandchildren etc, this can be much faster
24153 ;; than the outline version.
24154 (org-back-to-heading invisible-ok)
24155 (let ((first t)
24156 (level (funcall outline-level)))
24157 (if (and (derived-mode-p 'org-mode) (< level 1000))
24158 ;; A true heading (not a plain list item), in Org-mode
24159 ;; This means we can easily find the end by looking
24160 ;; only for the right number of stars. Using a regexp to do
24161 ;; this is so much faster than using a Lisp loop.
24162 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24163 (forward-char 1)
24164 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24165 ;; something else, do it the slow way
24166 (while (and (not (eobp))
24167 (or first (> (funcall outline-level) level)))
24168 (setq first nil)
24169 (outline-next-heading)))
24170 (unless to-heading
24171 (when (memq (preceding-char) '(?\n ?\^M))
24172 ;; Go to end of line before heading
24173 (forward-char -1)
24174 (when (memq (preceding-char) '(?\n ?\^M))
24175 ;; leave blank line before heading
24176 (forward-char -1)))))
24177 (point))
24179 (defun org-end-of-meta-data (&optional full)
24180 "Skip planning line and properties drawer in current entry.
24181 When optional argument FULL is non-nil, also skip empty lines,
24182 clocking lines and regular drawers at the beginning of the
24183 entry."
24184 (org-back-to-heading t)
24185 (forward-line)
24186 (when (looking-at-p org-planning-line-re) (forward-line))
24187 (when (looking-at org-property-drawer-re)
24188 (goto-char (match-end 0))
24189 (forward-line))
24190 (when (and full (not (org-at-heading-p)))
24191 (catch 'exit
24192 (let ((end (save-excursion (outline-next-heading) (point)))
24193 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24194 (while (not (eobp))
24195 (cond ((looking-at-p org-drawer-regexp)
24196 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24197 (forward-line)
24198 (throw 'exit t)))
24199 ((looking-at-p re) (forward-line))
24200 (t (throw 'exit t))))))))
24202 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24203 "Move forward to the ARG'th subheading at same level as this one.
24204 Stop at the first and last subheadings of a superior heading.
24205 Normally this only looks at visible headings, but when INVISIBLE-OK is
24206 non-nil it will also look at invisible ones."
24207 (interactive "p")
24208 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24209 (if (and arg (< arg 0))
24210 (goto-char (point-min))
24211 (outline-next-heading))
24212 (org-at-heading-p)
24213 (let ((level (- (match-end 0) (match-beginning 0) 1))
24214 (f (if (and arg (< arg 0))
24215 're-search-backward
24216 're-search-forward))
24217 (count (if arg (abs arg) 1))
24218 (result (point)))
24219 (while (and (prog1 (> count 0)
24220 (forward-char (if (and arg (< arg 0)) -1 1)))
24221 (funcall f org-outline-regexp-bol nil 'move))
24222 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24223 (cond ((< l level) (setq count 0))
24224 ((and (= l level)
24225 (or invisible-ok
24226 (progn
24227 (goto-char (line-beginning-position))
24228 (not (outline-invisible-p)))))
24229 (setq count (1- count))
24230 (when (eq l level)
24231 (setq result (point)))))))
24232 (goto-char result))
24233 (beginning-of-line 1)))
24235 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24236 "Move backward to the ARG'th subheading at same level as this one.
24237 Stop at the first and last subheadings of a superior heading."
24238 (interactive "p")
24239 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24241 (defun org-next-visible-heading (arg)
24242 "Move to the next visible heading.
24244 This function wraps `outline-next-visible-heading' with
24245 `org-with-limited-levels' in order to skip over inline tasks and
24246 respect customization of `org-odd-levels-only'."
24247 (interactive "p")
24248 (org-with-limited-levels
24249 (outline-next-visible-heading arg)))
24251 (defun org-previous-visible-heading (arg)
24252 "Move to the previous visible heading.
24254 This function wraps `outline-previous-visible-heading' with
24255 `org-with-limited-levels' in order to skip over inline tasks and
24256 respect customization of `org-odd-levels-only'."
24257 (interactive "p")
24258 (org-with-limited-levels
24259 (outline-previous-visible-heading arg)))
24261 (defun org-next-block (arg &optional backward block-regexp)
24262 "Jump to the next block.
24264 With a prefix argument ARG, jump forward ARG many blocks.
24266 When BACKWARD is non-nil, jump to the previous block.
24268 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24269 Match data is set according to this regexp when the function
24270 returns.
24272 Return point at beginning of the opening line of found block.
24273 Throw an error if no block is found."
24274 (interactive "p")
24275 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24276 (case-fold-search t)
24277 (search-fn (if backward #'re-search-backward #'re-search-forward))
24278 (count (or arg 1))
24279 (origin (point))
24280 last-element)
24281 (if backward (beginning-of-line) (end-of-line))
24282 (while (and (> count 0) (funcall search-fn re nil t))
24283 (let ((element (save-excursion
24284 (goto-char (match-beginning 0))
24285 (save-match-data (org-element-at-point)))))
24286 (when (and (memq (org-element-type element)
24287 '(center-block comment-block dynamic-block
24288 example-block export-block quote-block
24289 special-block src-block verse-block))
24290 (<= (match-beginning 0)
24291 (org-element-property :post-affiliated element)))
24292 (setq last-element element)
24293 (cl-decf count))))
24294 (if (= count 0)
24295 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24296 (save-match-data (org-show-context)))
24297 (goto-char origin)
24298 (user-error "No %s code blocks" (if backward "previous" "further")))))
24300 (defun org-previous-block (arg &optional block-regexp)
24301 "Jump to the previous block.
24302 With a prefix argument ARG, jump backward ARG many source blocks.
24303 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24304 (interactive "p")
24305 (org-next-block arg t block-regexp))
24307 (defun org-forward-paragraph ()
24308 "Move forward to beginning of next paragraph or equivalent.
24310 The function moves point to the beginning of the next visible
24311 structural element, which can be a paragraph, a table, a list
24312 item, etc. It also provides some special moves for convenience:
24314 - On an affiliated keyword, jump to the beginning of the
24315 relative element.
24316 - On an item or a footnote definition, move to the second
24317 element inside, if any.
24318 - On a table or a property drawer, jump after it.
24319 - On a verse or source block, stop after blank lines."
24320 (interactive)
24321 (when (eobp) (user-error "Cannot move further down"))
24322 (let* ((deactivate-mark nil)
24323 (element (org-element-at-point))
24324 (type (org-element-type element))
24325 (post-affiliated (org-element-property :post-affiliated element))
24326 (contents-begin (org-element-property :contents-begin element))
24327 (contents-end (org-element-property :contents-end element))
24328 (end (let ((end (org-element-property :end element)) (parent element))
24329 (while (and (setq parent (org-element-property :parent parent))
24330 (= (org-element-property :contents-end parent) end))
24331 (setq end (org-element-property :end parent)))
24332 end)))
24333 (cond ((not element)
24334 (skip-chars-forward " \r\t\n")
24335 (or (eobp) (beginning-of-line)))
24336 ;; On affiliated keywords, move to element's beginning.
24337 ((< (point) post-affiliated)
24338 (goto-char post-affiliated))
24339 ;; At a table row, move to the end of the table. Similarly,
24340 ;; at a node property, move to the end of the property
24341 ;; drawer.
24342 ((memq type '(node-property table-row))
24343 (goto-char (org-element-property
24344 :end (org-element-property :parent element))))
24345 ((memq type '(property-drawer table)) (goto-char end))
24346 ;; Consider blank lines as separators in verse and source
24347 ;; blocks to ease editing.
24348 ((memq type '(src-block verse-block))
24349 (when (eq type 'src-block)
24350 (setq contents-end
24351 (save-excursion (goto-char end)
24352 (skip-chars-backward " \r\t\n")
24353 (line-beginning-position))))
24354 (beginning-of-line)
24355 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24356 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24357 (goto-char end)
24358 (skip-chars-forward " \r\t\n")
24359 (if (= (point) contents-end) (goto-char end)
24360 (beginning-of-line))))
24361 ;; With no contents, just skip element.
24362 ((not contents-begin) (goto-char end))
24363 ;; If contents are invisible, skip the element altogether.
24364 ((outline-invisible-p (line-end-position))
24365 (cl-case type
24366 (headline
24367 (org-with-limited-levels (outline-next-visible-heading 1)))
24368 ;; At a plain list, make sure we move to the next item
24369 ;; instead of skipping the whole list.
24370 (plain-list (forward-char)
24371 (org-forward-paragraph))
24372 (otherwise (goto-char end))))
24373 ((>= (point) contents-end) (goto-char end))
24374 ((>= (point) contents-begin)
24375 ;; This can only happen on paragraphs and plain lists.
24376 (cl-case type
24377 (paragraph (goto-char end))
24378 ;; At a plain list, try to move to second element in
24379 ;; first item, if possible.
24380 (plain-list (end-of-line)
24381 (org-forward-paragraph))))
24382 ;; When contents start on the middle of a line (e.g. in
24383 ;; items and footnote definitions), try to reach first
24384 ;; element starting after current line.
24385 ((> (line-end-position) contents-begin)
24386 (end-of-line)
24387 (org-forward-paragraph))
24388 (t (goto-char contents-begin)))))
24390 (defun org-backward-paragraph ()
24391 "Move backward to start of previous paragraph or equivalent.
24393 The function moves point to the beginning of the current
24394 structural element, which can be a paragraph, a table, a list
24395 item, etc., or to the beginning of the previous visible one if
24396 point is already there. It also provides some special moves for
24397 convenience:
24399 - On an affiliated keyword, jump to the first one.
24400 - On a table or a property drawer, move to its beginning.
24401 - On a verse or source block, stop before blank lines."
24402 (interactive)
24403 (when (bobp) (user-error "Cannot move further up"))
24404 (let* ((deactivate-mark nil)
24405 (element (org-element-at-point))
24406 (type (org-element-type element))
24407 (contents-begin (org-element-property :contents-begin element))
24408 (contents-end (org-element-property :contents-end element))
24409 (post-affiliated (org-element-property :post-affiliated element))
24410 (begin (org-element-property :begin element)))
24411 (cond
24412 ((not element) (goto-char (point-min)))
24413 ((= (point) begin)
24414 (backward-char)
24415 (org-backward-paragraph))
24416 ((<= (point) post-affiliated) (goto-char begin))
24417 ((memq type '(node-property table-row))
24418 (goto-char (org-element-property
24419 :post-affiliated (org-element-property :parent element))))
24420 ((memq type '(property-drawer table)) (goto-char begin))
24421 ((memq type '(src-block verse-block))
24422 (when (eq type 'src-block)
24423 (setq contents-begin
24424 (save-excursion (goto-char begin) (forward-line) (point))))
24425 (if (= (point) contents-begin) (goto-char post-affiliated)
24426 ;; Inside a verse block, see blank lines as paragraph
24427 ;; separators.
24428 (let ((origin (point)))
24429 (skip-chars-backward " \r\t\n" contents-begin)
24430 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24431 (skip-chars-forward " \r\t\n" origin)
24432 (if (= (point) origin) (goto-char contents-begin)
24433 (beginning-of-line))))))
24434 ((not contents-begin) (goto-char (or post-affiliated begin)))
24435 ((eq type 'paragraph)
24436 (goto-char contents-begin)
24437 ;; When at first paragraph in an item or a footnote definition,
24438 ;; move directly to beginning of line.
24439 (let ((parent-contents
24440 (org-element-property
24441 :contents-begin (org-element-property :parent element))))
24442 (when (and parent-contents (= parent-contents contents-begin))
24443 (beginning-of-line))))
24444 ;; At the end of a greater element, move to the beginning of the
24445 ;; last element within.
24446 ((>= (point) contents-end)
24447 (goto-char (1- contents-end))
24448 (org-backward-paragraph))
24449 (t (goto-char (or post-affiliated begin))))
24450 ;; Ensure we never leave point invisible.
24451 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24453 (defun org-forward-element ()
24454 "Move forward by one element.
24455 Move to the next element at the same level, when possible."
24456 (interactive)
24457 (cond ((eobp) (user-error "Cannot move further down"))
24458 ((org-with-limited-levels (org-at-heading-p))
24459 (let ((origin (point)))
24460 (goto-char (org-end-of-subtree nil t))
24461 (unless (org-with-limited-levels (org-at-heading-p))
24462 (goto-char origin)
24463 (user-error "Cannot move further down"))))
24465 (let* ((elem (org-element-at-point))
24466 (end (org-element-property :end elem))
24467 (parent (org-element-property :parent elem)))
24468 (cond ((and parent (= (org-element-property :contents-end parent) end))
24469 (goto-char (org-element-property :end parent)))
24470 ((integer-or-marker-p end) (goto-char end))
24471 (t (message "No element at point")))))))
24473 (defun org-backward-element ()
24474 "Move backward by one element.
24475 Move to the previous element at the same level, when possible."
24476 (interactive)
24477 (cond ((bobp) (user-error "Cannot move further up"))
24478 ((org-with-limited-levels (org-at-heading-p))
24479 ;; At a headline, move to the previous one, if any, or stay
24480 ;; here.
24481 (let ((origin (point)))
24482 (org-with-limited-levels (org-backward-heading-same-level 1))
24483 ;; When current headline has no sibling above, move to its
24484 ;; parent.
24485 (when (= (point) origin)
24486 (or (org-with-limited-levels (org-up-heading-safe))
24487 (progn (goto-char origin)
24488 (user-error "Cannot move further up"))))))
24490 (let* ((elem (org-element-at-point))
24491 (beg (org-element-property :begin elem)))
24492 (cond
24493 ;; Move to beginning of current element if point isn't
24494 ;; there already.
24495 ((null beg) (message "No element at point"))
24496 ((/= (point) beg) (goto-char beg))
24497 (t (goto-char beg)
24498 (skip-chars-backward " \r\t\n")
24499 (unless (bobp)
24500 (let ((prev (org-element-at-point)))
24501 (goto-char (org-element-property :begin prev))
24502 (while (and (setq prev (org-element-property :parent prev))
24503 (<= (org-element-property :end prev) beg))
24504 (goto-char (org-element-property :begin prev)))))))))))
24506 (defun org-up-element ()
24507 "Move to upper element."
24508 (interactive)
24509 (if (org-with-limited-levels (org-at-heading-p))
24510 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24511 (let* ((elem (org-element-at-point))
24512 (parent (org-element-property :parent elem)))
24513 (if parent (goto-char (org-element-property :begin parent))
24514 (if (org-with-limited-levels (org-before-first-heading-p))
24515 (user-error "No surrounding element")
24516 (org-with-limited-levels (org-back-to-heading)))))))
24518 (defvar org-element-greater-elements)
24519 (defun org-down-element ()
24520 "Move to inner element."
24521 (interactive)
24522 (let ((element (org-element-at-point)))
24523 (cond
24524 ((memq (org-element-type element) '(plain-list table))
24525 (goto-char (org-element-property :contents-begin element))
24526 (forward-char))
24527 ((memq (org-element-type element) org-element-greater-elements)
24528 ;; If contents are hidden, first disclose them.
24529 (when (outline-invisible-p (line-end-position)) (org-cycle))
24530 (goto-char (or (org-element-property :contents-begin element)
24531 (user-error "No content for this element"))))
24532 (t (user-error "No inner element")))))
24534 (defun org-drag-element-backward ()
24535 "Move backward element at point."
24536 (interactive)
24537 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24538 (let* ((elem (org-element-at-point))
24539 (prev-elem
24540 (save-excursion
24541 (goto-char (org-element-property :begin elem))
24542 (skip-chars-backward " \r\t\n")
24543 (unless (bobp)
24544 (let* ((beg (org-element-property :begin elem))
24545 (prev (org-element-at-point))
24546 (up prev))
24547 (while (and (setq up (org-element-property :parent up))
24548 (<= (org-element-property :end up) beg))
24549 (setq prev up))
24550 prev)))))
24551 ;; Error out if no previous element or previous element is
24552 ;; a parent of the current one.
24553 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24554 (user-error "Cannot drag element backward")
24555 (let ((pos (point)))
24556 (org-element-swap-A-B prev-elem elem)
24557 (goto-char (+ (org-element-property :begin prev-elem)
24558 (- pos (org-element-property :begin elem)))))))))
24560 (defun org-drag-element-forward ()
24561 "Move forward element at point."
24562 (interactive)
24563 (let* ((pos (point))
24564 (elem (org-element-at-point)))
24565 (when (= (point-max) (org-element-property :end elem))
24566 (user-error "Cannot drag element forward"))
24567 (goto-char (org-element-property :end elem))
24568 (let ((next-elem (org-element-at-point)))
24569 (when (or (org-element-nested-p elem next-elem)
24570 (and (eq (org-element-type next-elem) 'headline)
24571 (not (eq (org-element-type elem) 'headline))))
24572 (goto-char pos)
24573 (user-error "Cannot drag element forward"))
24574 ;; Compute new position of point: it's shifted by NEXT-ELEM
24575 ;; body's length (without final blanks) and by the length of
24576 ;; blanks between ELEM and NEXT-ELEM.
24577 (let ((size-next (- (save-excursion
24578 (goto-char (org-element-property :end next-elem))
24579 (skip-chars-backward " \r\t\n")
24580 (forward-line)
24581 ;; Small correction if buffer doesn't end
24582 ;; with a newline character.
24583 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24584 (org-element-property :begin next-elem)))
24585 (size-blank (- (org-element-property :end elem)
24586 (save-excursion
24587 (goto-char (org-element-property :end elem))
24588 (skip-chars-backward " \r\t\n")
24589 (forward-line)
24590 (point)))))
24591 (org-element-swap-A-B elem next-elem)
24592 (goto-char (+ pos size-next size-blank))))))
24594 (defun org-drag-line-forward (arg)
24595 "Drag the line at point ARG lines forward."
24596 (interactive "p")
24597 (dotimes (_ (abs arg))
24598 (let ((c (current-column)))
24599 (if (< 0 arg)
24600 (progn
24601 (beginning-of-line 2)
24602 (transpose-lines 1)
24603 (beginning-of-line 0))
24604 (transpose-lines 1)
24605 (beginning-of-line -1))
24606 (org-move-to-column c))))
24608 (defun org-drag-line-backward (arg)
24609 "Drag the line at point ARG lines backward."
24610 (interactive "p")
24611 (org-drag-line-forward (- arg)))
24613 (defun org-mark-element ()
24614 "Put point at beginning of this element, mark at end.
24616 Interactively, if this command is repeated or (in Transient Mark
24617 mode) if the mark is active, it marks the next element after the
24618 ones already marked."
24619 (interactive)
24620 (let (deactivate-mark)
24621 (if (and (called-interactively-p 'any)
24622 (or (and (eq last-command this-command) (mark t))
24623 (and transient-mark-mode mark-active)))
24624 (set-mark
24625 (save-excursion
24626 (goto-char (mark))
24627 (goto-char (org-element-property :end (org-element-at-point)))))
24628 (let ((element (org-element-at-point)))
24629 (end-of-line)
24630 (push-mark (org-element-property :end element) t t)
24631 (goto-char (org-element-property :begin element))))))
24633 (defun org-narrow-to-element ()
24634 "Narrow buffer to current element."
24635 (interactive)
24636 (let ((elem (org-element-at-point)))
24637 (cond
24638 ((eq (car elem) 'headline)
24639 (narrow-to-region
24640 (org-element-property :begin elem)
24641 (org-element-property :end elem)))
24642 ((memq (car elem) org-element-greater-elements)
24643 (narrow-to-region
24644 (org-element-property :contents-begin elem)
24645 (org-element-property :contents-end elem)))
24647 (narrow-to-region
24648 (org-element-property :begin elem)
24649 (org-element-property :end elem))))))
24651 (defun org-transpose-element ()
24652 "Transpose current and previous elements, keeping blank lines between.
24653 Point is moved after both elements."
24654 (interactive)
24655 (org-skip-whitespace)
24656 (let ((end (org-element-property :end (org-element-at-point))))
24657 (org-drag-element-backward)
24658 (goto-char end)))
24660 (defun org-unindent-buffer ()
24661 "Un-indent the visible part of the buffer.
24662 Relative indentation (between items, inside blocks, etc.) isn't
24663 modified."
24664 (interactive)
24665 (unless (eq major-mode 'org-mode)
24666 (user-error "Cannot un-indent a buffer not in Org mode"))
24667 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24668 (unindent-tree
24669 (lambda (contents)
24670 (dolist (element (reverse contents))
24671 (if (memq (org-element-type element) '(headline section))
24672 (funcall unindent-tree (org-element-contents element))
24673 (save-excursion
24674 (save-restriction
24675 (narrow-to-region
24676 (org-element-property :begin element)
24677 (org-element-property :end element))
24678 (org-do-remove-indentation))))))))
24679 (funcall unindent-tree (org-element-contents parse-tree))))
24681 (defun org-show-children (&optional level)
24682 "Show all direct subheadings of this heading.
24683 Prefix arg LEVEL is how many levels below the current level
24684 should be shown. Default is enough to cause the following
24685 heading to appear."
24686 (interactive "p")
24687 ;; If `orgstruct-mode' is active, use the slower version.
24688 (if orgstruct-mode (call-interactively #'outline-show-children)
24689 (save-excursion
24690 (org-back-to-heading t)
24691 (let* ((current-level (funcall outline-level))
24692 (max-level (org-get-valid-level
24693 current-level
24694 (if level (prefix-numeric-value level) 1)))
24695 (end (save-excursion (org-end-of-subtree t t)))
24696 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24697 (past-first-child nil)
24698 ;; Make sure to skip inlinetasks.
24699 (re (format regexp-fmt
24700 current-level
24701 (cond
24702 ((not (featurep 'org-inlinetask)) "")
24703 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24705 (t (1- org-inlinetask-min-level))))))
24706 ;; Display parent heading.
24707 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24708 (forward-line)
24709 ;; Display children. First child may be deeper than expected
24710 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24711 ;; MAX-LEVEL accordingly.
24712 (while (re-search-forward re end t)
24713 (unless past-first-child
24714 (setq re (format regexp-fmt
24715 current-level
24716 (max (funcall outline-level) max-level)))
24717 (setq past-first-child t))
24718 (outline-flag-region
24719 (line-end-position 0) (line-end-position) nil))))))
24721 (defun org-show-subtree ()
24722 "Show everything after this heading at deeper levels."
24723 (interactive)
24724 (outline-flag-region
24725 (point)
24726 (save-excursion
24727 (org-end-of-subtree t t))
24728 nil))
24730 (defun org-show-entry ()
24731 "Show the body directly following this heading.
24732 Show the heading too, if it is currently invisible."
24733 (interactive)
24734 (save-excursion
24735 (ignore-errors
24736 (org-back-to-heading t)
24737 (outline-flag-region
24738 (max (point-min) (1- (point)))
24739 (save-excursion
24740 (if (re-search-forward
24741 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24742 (match-beginning 1)
24743 (point-max)))
24744 nil)
24745 (org-cycle-hide-drawers 'children))))
24747 (defun org-make-options-regexp (kwds &optional extra)
24748 "Make a regular expression for keyword lines.
24749 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24750 when non-nil, is a regexp matching keywords names."
24751 (concat "^[ \t]*#\\+\\("
24752 (regexp-opt kwds)
24753 (and extra (concat (and kwds "\\|") extra))
24754 "\\):[ \t]*\\(.*\\)"))
24756 ;;;; Integration with and fixes for other packages
24758 ;;; Imenu support
24760 (defvar-local org-imenu-markers nil
24761 "All markers currently used by Imenu.")
24763 (defun org-imenu-new-marker (&optional pos)
24764 "Return a new marker for use by Imenu, and remember the marker."
24765 (let ((m (make-marker)))
24766 (move-marker m (or pos (point)))
24767 (push m org-imenu-markers)
24770 (defun org-imenu-get-tree ()
24771 "Produce the index for Imenu."
24772 (dolist (x org-imenu-markers) (move-marker x nil))
24773 (setq org-imenu-markers nil)
24774 (let* ((case-fold-search nil)
24775 (n org-imenu-depth)
24776 (re (concat "^" (org-get-limited-outline-regexp)))
24777 (subs (make-vector (1+ n) nil))
24778 (last-level 0)
24779 m level head0 head)
24780 (save-excursion
24781 (save-restriction
24782 (widen)
24783 (goto-char (point-max))
24784 (while (re-search-backward re nil t)
24785 (setq level (org-reduced-level (funcall outline-level)))
24786 (when (and (<= level n)
24787 (looking-at org-complex-heading-regexp)
24788 (setq head0 (match-string-no-properties 4)))
24789 (setq head (org-link-display-format head0)
24790 m (org-imenu-new-marker))
24791 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24792 (if (>= level last-level)
24793 (push (cons head m) (aref subs level))
24794 (push (cons head (aref subs (1+ level))) (aref subs level))
24795 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24796 (setq last-level level)))))
24797 (aref subs 1)))
24799 (eval-after-load "imenu"
24800 '(progn
24801 (add-hook 'imenu-after-jump-hook
24802 (lambda ()
24803 (when (derived-mode-p 'org-mode)
24804 (org-show-context 'org-goto))))))
24806 (defun org-link-display-format (s)
24807 "Replace links in string S with their description.
24808 If there is no description, use the link target."
24809 (save-match-data
24810 (replace-regexp-in-string
24811 org-bracket-link-analytic-regexp
24812 (lambda (m)
24813 (if (match-end 5) (match-string 5 m)
24814 (concat (match-string 1 m) (match-string 3 m))))
24815 s nil t)))
24817 (defun org-toggle-link-display ()
24818 "Toggle the literal or descriptive display of links."
24819 (interactive)
24820 (if org-descriptive-links
24821 (progn (org-remove-from-invisibility-spec '(org-link))
24822 (org-restart-font-lock)
24823 (setq org-descriptive-links nil))
24824 (progn (add-to-invisibility-spec '(org-link))
24825 (org-restart-font-lock)
24826 (setq org-descriptive-links t))))
24828 ;; Speedbar support
24830 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24831 "Overlay marking the agenda restriction line in speedbar.")
24832 (overlay-put org-speedbar-restriction-lock-overlay
24833 'face 'org-agenda-restriction-lock)
24834 (overlay-put org-speedbar-restriction-lock-overlay
24835 'help-echo "Agendas are currently limited to this item.")
24836 (delete-overlay org-speedbar-restriction-lock-overlay)
24838 (defun org-speedbar-set-agenda-restriction ()
24839 "Restrict future agenda commands to the location at point in speedbar.
24840 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24841 (interactive)
24842 (require 'org-agenda)
24843 (let (p m tp np dir txt)
24844 (cond
24845 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24846 'org-imenu t))
24847 (setq m (get-text-property p 'org-imenu-marker))
24848 (with-current-buffer (marker-buffer m)
24849 (goto-char m)
24850 (org-agenda-set-restriction-lock 'subtree)))
24851 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24852 'speedbar-function 'speedbar-find-file))
24853 (setq tp (previous-single-property-change
24854 (1+ p) 'speedbar-function)
24855 np (next-single-property-change
24856 tp 'speedbar-function)
24857 dir (speedbar-line-directory)
24858 txt (buffer-substring-no-properties (or tp (point-min))
24859 (or np (point-max))))
24860 (with-current-buffer (find-file-noselect
24861 (let ((default-directory dir))
24862 (expand-file-name txt)))
24863 (unless (derived-mode-p 'org-mode)
24864 (user-error "Cannot restrict to non-Org-mode file"))
24865 (org-agenda-set-restriction-lock 'file)))
24866 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24867 (move-overlay org-speedbar-restriction-lock-overlay
24868 (point-at-bol) (point-at-eol))
24869 (setq current-prefix-arg nil)
24870 (org-agenda-maybe-redo)))
24872 (defvar speedbar-file-key-map)
24873 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24874 (eval-after-load "speedbar"
24875 '(progn
24876 (speedbar-add-supported-extension ".org")
24877 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24878 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24879 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24880 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24881 (add-hook 'speedbar-visiting-tag-hook
24882 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24884 ;;; Fixes and Hacks for problems with other packages
24886 (defun org--flyspell-object-check-p (element)
24887 "Non-nil when Flyspell can check object at point.
24888 ELEMENT is the element at point."
24889 (let ((object (save-excursion
24890 (when (looking-at-p "\\>") (backward-char))
24891 (org-element-context element))))
24892 (cl-case (org-element-type object)
24893 ;; Prevent checks in links due to keybinding conflict with
24894 ;; Flyspell.
24895 ((code entity export-snippet inline-babel-call
24896 inline-src-block line-break latex-fragment link macro
24897 statistics-cookie target timestamp verbatim)
24898 nil)
24899 (footnote-reference
24900 ;; Only in inline footnotes, within the definition.
24901 (and (eq (org-element-property :type object) 'inline)
24902 (< (save-excursion
24903 (goto-char (org-element-property :begin object))
24904 (search-forward ":" nil t 2))
24905 (point))))
24906 (otherwise t))))
24908 (defun org-mode-flyspell-verify ()
24909 "Function used for `flyspell-generic-check-word-predicate'."
24910 (if (org-at-heading-p)
24911 ;; At a headline or an inlinetask, check title only. This is
24912 ;; faster than relying on `org-element-at-point'.
24913 (and (save-excursion (beginning-of-line)
24914 (and (let ((case-fold-search t))
24915 (not (looking-at "\\*+ END[ \t]*$")))
24916 (looking-at org-complex-heading-regexp)))
24917 (match-beginning 4)
24918 (>= (point) (match-beginning 4))
24919 (or (not (match-beginning 5))
24920 (< (point) (match-beginning 5))))
24921 (let* ((element (org-element-at-point))
24922 (post-affiliated (org-element-property :post-affiliated element)))
24923 (cond
24924 ;; Ignore checks in all affiliated keywords but captions.
24925 ((< (point) post-affiliated)
24926 (and (save-excursion
24927 (beginning-of-line)
24928 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24929 (> (point) (match-end 0))
24930 (org--flyspell-object-check-p element)))
24931 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24932 ((let ((log (org-log-into-drawer)))
24933 (and log
24934 (let ((drawer (org-element-lineage element '(drawer))))
24935 (and drawer
24936 (eq (compare-strings
24937 log nil nil
24938 (org-element-property :drawer-name drawer) nil nil t)
24939 t)))))
24940 nil)
24942 (cl-case (org-element-type element)
24943 ((comment quote-section) t)
24944 (comment-block
24945 ;; Allow checks between block markers, not on them.
24946 (and (> (line-beginning-position) post-affiliated)
24947 (save-excursion
24948 (end-of-line)
24949 (skip-chars-forward " \r\t\n")
24950 (< (point) (org-element-property :end element)))))
24951 ;; Arbitrary list of keywords where checks are meaningful.
24952 ;; Make sure point is on the value part of the element.
24953 (keyword
24954 (and (member (org-element-property :key element)
24955 '("DESCRIPTION" "TITLE"))
24956 (save-excursion
24957 (search-backward ":" (line-beginning-position) t))))
24958 ;; Check is globally allowed in paragraphs verse blocks and
24959 ;; table rows (after affiliated keywords) but some objects
24960 ;; must not be affected.
24961 ((paragraph table-row verse-block)
24962 (let ((cbeg (org-element-property :contents-begin element))
24963 (cend (org-element-property :contents-end element)))
24964 (and cbeg (>= (point) cbeg) (< (point) cend)
24965 (org--flyspell-object-check-p element))))))))))
24966 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24968 (defun org-remove-flyspell-overlays-in (beg end)
24969 "Remove flyspell overlays in region."
24970 (and (bound-and-true-p flyspell-mode)
24971 (fboundp 'flyspell-delete-region-overlays)
24972 (flyspell-delete-region-overlays beg end)))
24974 (defvar flyspell-delayed-commands)
24975 (eval-after-load "flyspell"
24976 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24978 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24979 (eval-after-load "bookmark"
24980 '(if (boundp 'bookmark-after-jump-hook)
24981 ;; We can use the hook
24982 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24983 ;; Hook not available, use advice
24984 (defadvice bookmark-jump (after org-make-visible activate)
24985 "Make the position visible."
24986 (org-bookmark-jump-unhide))))
24988 ;; Make sure saveplace shows the location if it was hidden
24989 (eval-after-load "saveplace"
24990 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24991 "Make the position visible."
24992 (org-bookmark-jump-unhide)))
24994 ;; Make sure ecb shows the location if it was hidden
24995 (eval-after-load "ecb"
24996 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24997 "Make hierarchy visible when jumping into location from ECB tree buffer."
24998 (when (derived-mode-p 'org-mode)
24999 (org-show-context))))
25001 (defun org-bookmark-jump-unhide ()
25002 "Unhide the current position, to show the bookmark location."
25003 (and (derived-mode-p 'org-mode)
25004 (or (outline-invisible-p)
25005 (save-excursion (goto-char (max (point-min) (1- (point))))
25006 (outline-invisible-p)))
25007 (org-show-context 'bookmark-jump)))
25009 (defun org-mark-jump-unhide ()
25010 "Make the point visible with `org-show-context' after jumping to the mark."
25011 (when (and (derived-mode-p 'org-mode)
25012 (outline-invisible-p))
25013 (org-show-context 'mark-goto)))
25015 (eval-after-load "simple"
25016 '(defadvice pop-to-mark-command (after org-make-visible activate)
25017 "Make the point visible with `org-show-context'."
25018 (org-mark-jump-unhide)))
25020 (eval-after-load "simple"
25021 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25022 "Make the point visible with `org-show-context'."
25023 (org-mark-jump-unhide)))
25025 (eval-after-load "simple"
25026 '(defadvice pop-global-mark (after org-make-visible activate)
25027 "Make the point visible with `org-show-context'."
25028 (org-mark-jump-unhide)))
25030 ;; Make session.el ignore our circular variable
25031 (defvar session-globals-exclude)
25032 (eval-after-load "session"
25033 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25035 ;;;; Finish up
25037 (provide 'org)
25039 (run-hooks 'org-load-hook)
25041 ;;; org.el ends here