config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

org.el (892326B)


      1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
      2 
      3 ;; Carstens outline-mode for keeping track of everything.
      4 ;; Copyright (C) 2004-2024 Free Software Foundation, Inc.
      5 ;;
      6 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
      7 ;; Maintainer: Bastien Guerry <bzg@gnu.org>
      8 ;; Keywords: outlines, hypermedia, calendar, text
      9 ;; URL: https://orgmode.org
     10 ;; Package-Requires: ((emacs "26.1"))
     11 
     12 ;; Version: 9.7.16
     13 
     14 ;; This file is part of GNU Emacs.
     15 ;;
     16 ;; GNU Emacs is free software: you can redistribute it and/or modify
     17 ;; it under the terms of the GNU General Public License as published by
     18 ;; the Free Software Foundation, either version 3 of the License, or
     19 ;; (at your option) any later version.
     20 
     21 ;; GNU Emacs is distributed in the hope that it will be useful,
     22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     24 ;; GNU General Public License for more details.
     25 
     26 ;; You should have received a copy of the GNU General Public License
     27 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     28 ;;
     29 ;;; Commentary:
     30 ;;
     31 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
     32 ;; project planning with a fast and effective plain-text system.
     33 ;;
     34 ;; Org mode develops organizational tasks around NOTES files that
     35 ;; contain information about projects as plain text.  Org mode is
     36 ;; implemented on top of outline-mode, which makes it possible to keep
     37 ;; the content of large files well structured.  Visibility cycling and
     38 ;; structure editing help to work with the tree.  Tables are easily
     39 ;; created with a built-in table editor.  Org mode supports ToDo
     40 ;; items, deadlines, time stamps, and scheduling.  It dynamically
     41 ;; compiles entries into an agenda that utilizes and smoothly
     42 ;; integrates much of the Emacs calendar and diary.  Plain text
     43 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
     44 ;; entries, and any files related to the projects.  For printing and
     45 ;; sharing of notes, an Org file can be exported as a structured ASCII
     46 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
     47 ;; file.  It can also serve as a publishing tool for a set of linked
     48 ;; webpages.
     49 ;;
     50 ;; Installation and Activation
     51 ;; ---------------------------
     52 ;; See the corresponding sections in the manual at
     53 ;;
     54 ;;   https://orgmode.org/org.html#Installation
     55 ;;
     56 ;; Documentation
     57 ;; -------------
     58 ;; The documentation of Org mode can be found in the TeXInfo file.  The
     59 ;; distribution also contains a PDF version of it.  At the Org mode website,
     60 ;; you can read the same text online as HTML.  There is also an excellent
     61 ;; reference card made by Philip Rooke.  This card can be found in the
     62 ;; doc/ directory.
     63 ;;
     64 ;; A list of recent changes can be found at
     65 ;; https://orgmode.org/Changes.html
     66 ;;
     67 ;;; Code:
     68 
     69 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
     70 (defvar org-inlinetask-min-level)
     71 
     72 ;;;; Require other packages
     73 
     74 (require 'org-compat)
     75 (org-assert-version)
     76 
     77 (require 'cl-lib)
     78 
     79 (eval-when-compile (require 'gnus-sum))
     80 
     81 (require 'calendar)
     82 (require 'find-func)
     83 (require 'format-spec)
     84 (require 'thingatpt)
     85 
     86 (condition-case nil
     87     (load (concat (file-name-directory load-file-name)
     88 		  "org-loaddefs")
     89 	  nil t nil t)
     90   (error
     91    (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
     92    (sit-for 3)
     93    (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
     94    (sit-for 3)))
     95 
     96 (eval-and-compile (require 'org-macs))
     97 (require 'org-compat)
     98 (require 'org-keys)
     99 (require 'ol)
    100 (require 'oc)
    101 (require 'org-table)
    102 (require 'org-fold)
    103 
    104 (require 'org-cycle)
    105 (defalias 'org-global-cycle #'org-cycle-global)
    106 (defalias 'org-overview #'org-cycle-overview)
    107 (defalias 'org-content #'org-cycle-content)
    108 (defalias 'org-reveal #'org-fold-reveal)
    109 (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
    110 
    111 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
    112 ;; some places -- e.g. see the macro `org-with-limited-levels'.
    113 (defvar org-outline-regexp "\\*+ "
    114   "Regexp to match Org headlines.")
    115 
    116 (defvar org-outline-regexp-bol "^\\*+ "
    117   "Regexp to match Org headlines.
    118 This is similar to `org-outline-regexp' but additionally makes
    119 sure that we are at the beginning of the line.")
    120 
    121 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
    122   "Matches a headline, putting stars and text into groups.
    123 Stars are put in group 1 and the trimmed body in group 2.")
    124 
    125 (declare-function calendar-check-holidays "holidays" (date))
    126 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
    127 (declare-function cdlatex-math-symbol "ext:cdlatex")
    128 (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
    129 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
    130 (declare-function org-add-archive-files "org-archive" (files))
    131 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
    132 (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
    133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
    134 (declare-function org-agenda-redo "org-agenda" (&optional all))
    135 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
    136 (declare-function org-archive-subtree "org-archive" (&optional find-done))
    137 (declare-function org-archive-subtree-default "org-archive" ())
    138 (declare-function org-archive-to-archive-sibling "org-archive" ())
    139 (declare-function org-attach "org-attach" ())
    140 (declare-function org-attach-dir "org-attach"
    141 		  (&optional create-if-not-exists-p no-fs-check))
    142 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
    143 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
    144 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
    145 (declare-function org-clock-auto-clockout "org-clock" ())
    146 (declare-function org-clock-cancel "org-clock" ())
    147 (declare-function org-clock-display "org-clock" (&optional arg))
    148 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
    149 (declare-function org-clock-goto "org-clock" (&optional select))
    150 (declare-function org-clock-in "org-clock" (&optional select start-time))
    151 (declare-function org-clock-in-last "org-clock" (&optional arg))
    152 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
    153 (declare-function org-clock-out-if-current "org-clock" ())
    154 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
    155 (declare-function org-clock-report "org-clock" (&optional arg))
    156 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
    157 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
    158 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
    159 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
    160 (declare-function org-clock-update-time-maybe "org-clock" ())
    161 (declare-function org-clocktable-shift "org-clock" (dir n))
    162 (declare-function org-columns-quit "org-colview" ())
    163 (declare-function org-columns-insert-dblock "org-colview" ())
    164 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
    165 (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
    166 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
    167 (declare-function org-element-at-point-no-context "org-element" (&optional pom))
    168 (declare-function org-element-cache-refresh "org-element" (pos))
    169 (declare-function org-element-cache-reset "org-element" (&optional all no-persistence))
    170 (declare-function org-element-cache-map "org-element" (func &rest keys))
    171 (declare-function org-element-contents "org-element-ast" (node))
    172 (declare-function org-element-context "org-element" (&optional element))
    173 (declare-function org-element-copy "org-element-ast" (datum))
    174 (declare-function org-element-create "org-element-ast" (type &optional props &rest children))
    175 (declare-function org-element-extract "org-element-ast" (node))
    176 (declare-function org-element-insert-before "org-element-ast" (node location))
    177 (declare-function org-element-interpret-data "org-element" (data))
    178 (declare-function org-element-keyword-parser "org-element" (limit affiliated))
    179 (declare-function org-element-lineage "org-element-ast" (blob &optional types with-self))
    180 (declare-function org-element-property-inherited "org-element-ast"
    181                   (property node &optional with-self accumulate literal-nil include-nil))
    182 (declare-function org-element-lineage-map "org-element-ast"
    183                   (datum fun &optional types with-self first-match))
    184 (declare-function org-element-link-parser "org-element" ())
    185 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
    186 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
    187 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only keep-deferred))
    188 (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
    189 (declare-function org-element-property "org-element-ast" (property node))
    190 (declare-function org-element-begin "org-element" (node))
    191 (declare-function org-element-end "org-element" (node))
    192 (declare-function org-element-contents-begin "org-element" (node))
    193 (declare-function org-element-contents-end "org-element" (node))
    194 (declare-function org-element-post-affiliated "org-element" (node))
    195 (declare-function org-element-post-blank "org-element" (node))
    196 (declare-function org-element-parent "org-element-ast" (node))
    197 (declare-function org-element-put-property "org-element-ast" (node property value))
    198 (declare-function org-element-restriction "org-element" (element))
    199 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
    200 (declare-function org-element-timestamp-parser "org-element" ())
    201 (declare-function org-element-type "org-element-ast" (node &optional anonymous))
    202 (declare-function org-element-type-p "org-element-ast" (node types))
    203 (declare-function org-export-dispatch "ox" (&optional arg))
    204 (declare-function org-export-get-backend "ox" (name))
    205 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
    206 (declare-function org-feed-goto-inbox "org-feed" (feed))
    207 (declare-function org-feed-update-all "org-feed" ())
    208 (declare-function org-goto "org-goto" (&optional alternative-interface))
    209 (declare-function org-id-find-id-file "org-id" (id))
    210 (declare-function org-id-get-create "org-id" (&optional force))
    211 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
    212 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
    213 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
    214 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
    215 (declare-function org-num-mode "org-num" (&optional arg))
    216 (declare-function org-plot/gnuplot "org-plot" (&optional params))
    217 (declare-function org-persist-load "org-persist")
    218 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
    219 (declare-function org-timer "org-timer" (&optional restart no-insert))
    220 (declare-function org-timer-item "org-timer" (&optional arg))
    221 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
    222 (declare-function org-timer-set-timer "org-timer" (&optional opt))
    223 (declare-function org-timer-start "org-timer" (&optional offset))
    224 (declare-function org-timer-stop "org-timer" ())
    225 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
    226 (declare-function org-update-radio-target-regexp "ol" ())
    227 
    228 (defvar org-agenda-buffer-name)
    229 (defvar org-element-paragraph-separate)
    230 (defvar org-element-cache-map-continue-from)
    231 (defvar org-element--timestamp-regexp)
    232 (defvar org-indent-indentation-per-level)
    233 (defvar org-radio-target-regexp)
    234 (defvar org-target-link-regexp)
    235 (defvar org-target-regexp)
    236 (defvar org-id-overriding-file-name)
    237 
    238 ;; load languages based on value of `org-babel-load-languages'
    239 (defvar org-babel-load-languages)
    240 
    241 (defvar crm-separator)  ; dynamically scoped param
    242 
    243 ;;;###autoload
    244 (defun org-babel-do-load-languages (sym value)
    245   "Load the languages defined in `org-babel-load-languages'."
    246   (set-default-toplevel-value sym value)
    247   (dolist (pair org-babel-load-languages)
    248     (let ((active (cdr pair)) (lang (symbol-name (car pair))))
    249       (if active
    250 	  (require (intern (concat "ob-" lang)))
    251 	(fmakunbound
    252 	 (intern (concat "org-babel-execute:" lang)))
    253 	(fmakunbound
    254 	 (intern (concat "org-babel-expand-body:" lang)))))))
    255 
    256 
    257 ;;;###autoload
    258 (defun org-babel-load-file (file &optional compile)
    259   "Load Emacs Lisp source code blocks in the Org FILE.
    260 This function exports the source code using `org-babel-tangle'
    261 and then loads the resulting file using `load-file'.  With
    262 optional prefix argument COMPILE, the tangled Emacs Lisp file is
    263 byte-compiled before it is loaded."
    264   (interactive "fFile to load: \nP")
    265   (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
    266     ;; Tangle only if the Elisp file is older than the Org file.
    267     ;; Catch the case when the .el file exists while the .org file is missing.
    268     (unless (file-exists-p file)
    269       (error "File to tangle does not exist: %s" file))
    270     (when (file-newer-than-file-p file tangled-file)
    271       (org-babel-tangle-file file
    272                              tangled-file
    273                              (rx string-start
    274                                  (or "emacs-lisp" "elisp")
    275                                  string-end))
    276       ;; Make sure that tangled file modification time is
    277       ;; updated even when `org-babel-tangle-file' does not make changes.
    278       ;; This avoids re-tangling changed FILE where the changes did
    279       ;; not affect the tangled code.
    280       (when (file-exists-p tangled-file)
    281         (set-file-times tangled-file)))
    282     (if compile
    283 	(progn
    284 	  (byte-compile-file tangled-file)
    285 	  (load-file (byte-compile-dest-file tangled-file))
    286 	  (message "Compiled and loaded %s" tangled-file))
    287       (load-file tangled-file)
    288       (message "Loaded %s" tangled-file))))
    289 
    290 (defcustom org-babel-load-languages '((emacs-lisp . t))
    291   "Languages which can be evaluated in Org buffers.
    292 \\<org-mode-map>
    293 This list can be used to load support for any of the available
    294 languages with babel support (see info node `(org) Languages').  Each
    295 language will depend on a different set of system executables and/or
    296 Emacs modes.
    297 
    298 When a language is \"loaded\", code blocks in that language can
    299 be evaluated with `org-babel-execute-src-block', which is bound
    300 by default to \\[org-ctrl-c-ctrl-c].
    301 
    302 The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
    303 remove code block evaluation from \\[org-ctrl-c-ctrl-c].  By
    304 default, only Emacs Lisp is loaded, since it has no specific
    305 requirement."
    306   :group 'org-babel
    307   :set 'org-babel-do-load-languages
    308   :package-version '(Org . "9.6")
    309   :type '(alist :tag "Babel Languages"
    310 		:key-type
    311 		(choice
    312 		 (const :tag "Awk" awk)
    313 		 (const :tag "C, D, C++, and cpp" C)
    314 		 (const :tag "R" R)
    315                  (const :tag "Calc" calc)
    316 		 (const :tag "Clojure and ClojureScript" clojure)
    317 		 (const :tag "CSS" css)
    318 		 (const :tag "Ditaa" ditaa)
    319 		 (const :tag "Dot" dot)
    320                  (const :tag "Emacs Lisp" emacs-lisp)
    321                  (const :tag "Eshell" eshell)
    322 		 (const :tag "Forth" forth)
    323 		 (const :tag "Fortran" fortran)
    324 		 (const :tag "GnuPlot" gnuplot)
    325 		 (const :tag "Groovy" groovy)
    326 		 (const :tag "Haskell" haskell)
    327                  (const :tag "Java" java)
    328 		 (const :tag "JavaScript" js)
    329                  (const :tag "Julia" julia)
    330                  (const :tag "LaTeX" latex)
    331                  (const :tag "LilyPond" lilypond)
    332 		 (const :tag "Lisp" lisp)
    333                  (const :tag "Lua" lua)
    334 		 (const :tag "Makefile" makefile)
    335 		 (const :tag "Maxima" maxima)
    336                  (const :tag "OCaml" ocaml)
    337 		 (const :tag "Octave and MatLab" octave)
    338 		 (const :tag "Org" org)
    339 		 (const :tag "Perl" perl)
    340                  (const :tag "Processing" processing)
    341 		 (const :tag "PlantUML" plantuml)
    342 		 (const :tag "Python" python)
    343 		 (const :tag "Ruby" ruby)
    344 		 (const :tag "Sass" sass)
    345 		 (const :tag "Scheme" scheme)
    346 		 (const :tag "Screen" screen)
    347                  (const :tag "Sed" sed)
    348 		 (const :tag "Shell Script" shell)
    349                  (const :tag "Sql" sql)
    350 		 (const :tag "Sqlite" sqlite))
    351 		:value-type (boolean :tag "Activate" :value t)))
    352 
    353 ;;;; Customization variables
    354 (defcustom org-clone-delete-id nil
    355   "Remove ID property of clones of a subtree.
    356 When non-nil, clones of a subtree don't inherit the ID property.
    357 Otherwise they inherit the ID property with a new unique
    358 identifier."
    359   :type 'boolean
    360   :version "24.1"
    361   :group 'org-id)
    362 
    363 ;;; Version
    364 (org-check-version)
    365 
    366 ;;;###autoload
    367 (defun org-version (&optional here full message)
    368   "Show the Org version.
    369 Interactively, or when MESSAGE is non-nil, show it in echo area.
    370 With prefix argument, or when HERE is non-nil, insert it at point.
    371 In non-interactive uses, a reduced version string is output unless
    372 FULL is given."
    373   (interactive (list current-prefix-arg t (not current-prefix-arg)))
    374   (let ((org-dir (ignore-errors (org-find-library-dir "org")))
    375         (save-load-suffixes load-suffixes)
    376 	(load-suffixes (list ".el"))
    377 	(org-install-dir
    378 	 (ignore-errors (org-find-library-dir "org-loaddefs"))))
    379     (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
    380       (org-load-noerror-mustsuffix (concat org-dir "org-version")))
    381     (let* ((load-suffixes save-load-suffixes)
    382 	   (release (org-release))
    383 	   (git-version (org-git-version))
    384 	   (version (format "Org mode version %s (%s @ %s)"
    385 			    release
    386 			    git-version
    387 			    (if org-install-dir
    388 				(if (string= org-dir org-install-dir)
    389 				    org-install-dir
    390 				  (concat "mixed installation! "
    391 					  org-install-dir
    392 					  " and "
    393 					  org-dir))
    394 			      "org-loaddefs.el can not be found!")))
    395 	   (version1 (if full version release)))
    396       (when here (insert version1))
    397       (when message (message "%s" version1))
    398       version1)))
    399 
    400 (defconst org-version (org-version))
    401 
    402 
    403 ;;; Syntax Constants
    404 ;;;; Comments
    405 (defconst org-comment-regexp
    406   (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
    407   "Regular expression for comment lines.")
    408 
    409 ;;;; Keyword
    410 (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
    411   "Regular expression for keyword-lines.")
    412 
    413 ;;;; Block
    414 
    415 (defconst org-block-regexp
    416   "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\(\\(?:.\\|\n\\)+?\\)#\\+end_?\\1[ \t]*$"
    417   "Regular expression for hiding blocks.")
    418 
    419 (defconst org-dblock-start-re
    420   "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
    421   "Matches the start line of a dynamic block, with parameters.")
    422 
    423 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
    424   "Matches the end of a dynamic block.")
    425 
    426 ;;;; Timestamp
    427 
    428 (defconst org-ts--internal-regexp
    429   (rx (seq
    430        (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
    431        (optional " " (*? nonl))))
    432   "Regular expression matching the innards of a time stamp.")
    433 
    434 (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
    435   "Regular expression for fast time stamp matching.")
    436 
    437 (defconst org-ts-regexp-inactive
    438   (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
    439   "Regular expression for fast inactive time stamp matching.")
    440 
    441 (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
    442   "Regular expression for fast time stamp matching.")
    443 
    444 (defconst org-ts-regexp0
    445   "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
    446   "Regular expression matching time strings for analysis.
    447 This one does not require the space after the date, so it can be used
    448 on a string that terminates immediately after the date.")
    449 
    450 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\(?: *\\([^]+0-9>\r\n -]+\\)\\)?\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
    451   "Regular expression matching time strings for analysis.")
    452 
    453 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
    454   "Regular expression matching time stamps, with groups.")
    455 
    456 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
    457   "Regular expression matching time stamps (also [..]), with groups.")
    458 
    459 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
    460   "Regular expression matching a time stamp range.")
    461 
    462 (defconst org-tr-regexp-both
    463   (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
    464   "Regular expression matching a time stamp range.")
    465 
    466 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
    467 				 org-ts-regexp "\\)?")
    468   "Regular expression matching a time stamp or time stamp range.")
    469 
    470 (defconst org-tsr-regexp-both
    471   (concat org-ts-regexp-both "\\(--?-?"
    472 	  org-ts-regexp-both "\\)?")
    473   "Regular expression matching a time stamp or time stamp range.
    474 The time stamps may be either active or inactive.")
    475 
    476 (defconst org-repeat-re
    477   "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
    478 \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
    479   "Regular expression for specifying repeated events.
    480 After a match, group 1 contains the repeat expression.")
    481 
    482 (defvaralias 'org-time-stamp-formats 'org-timestamp-formats)
    483 (defconst org-timestamp-formats '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")
    484   "Formats for `format-time-string' which are used for time stamps.
    485 
    486 The value is a cons cell containing two strings.  The `car' and `cdr'
    487 of the cons cell are used to format time stamps that do not and do
    488 contain time, respectively.
    489 
    490 Leading \"<\"/\"[\" and trailing \">\"/\"]\" pair will be stripped
    491 from the format strings.
    492 
    493 Also, see `org-time-stamp-format'.")
    494 
    495 ;;;; Clock and Planning
    496 
    497 (defconst org-clock-string "CLOCK:"
    498   "String used as prefix for timestamps clocking work hours on an item.")
    499 
    500 (defvar org-closed-string "CLOSED:"
    501   "String used as the prefix for timestamps logging closing a TODO entry.")
    502 
    503 (defvar org-deadline-string "DEADLINE:"
    504   "String to mark deadline entries.
    505 \\<org-mode-map>
    506 A deadline is this string, followed by a time stamp.  It must be
    507 a word, terminated by a colon.  You can insert a schedule keyword
    508 and a timestamp with `\\[org-deadline]'.")
    509 
    510 (defvar org-scheduled-string "SCHEDULED:"
    511   "String to mark scheduled TODO entries.
    512 \\<org-mode-map>
    513 A schedule is this string, followed by a time stamp.  It must be
    514 a word, terminated by a colon.  You can insert a schedule keyword
    515 and a timestamp with `\\[org-schedule]'.")
    516 
    517 (defconst org-ds-keyword-length
    518   (+ 2
    519      (apply #'max
    520 	    (mapcar #'length
    521 		    (list org-deadline-string org-scheduled-string
    522 			  org-clock-string org-closed-string))))
    523   "Maximum length of the DEADLINE and SCHEDULED keywords.")
    524 
    525 (defconst org-planning-line-re
    526   (concat "^[ \t]*"
    527 	  (regexp-opt
    528 	   (list org-closed-string org-deadline-string org-scheduled-string)
    529 	   t))
    530   "Matches a line with planning info.
    531 Matched keyword is in group 1.")
    532 
    533 (defconst org-clock-line-re
    534   (concat "^[ \t]*" org-clock-string)
    535   "Matches a line with clock info.")
    536 
    537 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
    538   "Matches the DEADLINE keyword.")
    539 
    540 (defconst org-deadline-time-regexp
    541   (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
    542   "Matches the DEADLINE keyword together with a time stamp.")
    543 
    544 (defconst org-deadline-time-hour-regexp
    545   (concat "\\<" org-deadline-string
    546 	  " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
    547   "Matches the DEADLINE keyword together with a time-and-hour stamp.")
    548 
    549 (defconst org-deadline-line-regexp
    550   (concat "\\<\\(" org-deadline-string "\\).*")
    551   "Matches the DEADLINE keyword and the rest of the line.")
    552 
    553 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
    554   "Matches the SCHEDULED keyword.")
    555 
    556 (defconst org-scheduled-time-regexp
    557   (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
    558   "Matches the SCHEDULED keyword together with a time stamp.")
    559 
    560 (defconst org-scheduled-time-hour-regexp
    561   (concat "\\<" org-scheduled-string
    562 	  " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
    563   "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
    564 
    565 (defconst org-closed-time-regexp
    566   (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
    567   "Matches the CLOSED keyword together with a time stamp.")
    568 
    569 (defconst org-keyword-time-regexp
    570   (concat "\\<"
    571 	  (regexp-opt
    572 	   (list org-scheduled-string org-deadline-string org-closed-string
    573 		 org-clock-string)
    574 	   t)
    575 	  " *[[<]\\([^]>]+\\)[]>]")
    576   "Matches any of the 4 keywords, together with the time stamp.")
    577 
    578 (defconst org-keyword-time-not-clock-regexp
    579   (concat
    580    "\\<"
    581    (regexp-opt
    582     (list org-scheduled-string org-deadline-string org-closed-string) t)
    583    " *[[<]\\([^]>]+\\)[]>]")
    584   "Matches any of the 3 keywords, together with the time stamp.")
    585 
    586 (defconst org-all-time-keywords
    587   (mapcar (lambda (w) (substring w 0 -1))
    588 	  (list org-scheduled-string org-deadline-string
    589 		org-clock-string org-closed-string))
    590   "List of time keywords.")
    591 
    592 ;;;; Drawer
    593 
    594 (defconst org-drawer-regexp
    595   ;; FIXME: Duplicate of `org-element-drawer-re'.
    596   (rx line-start (0+ (any ?\s ?\t))
    597       ":" (group (1+ (any ?- ?_ word))) ":"
    598       (0+ (any ?\s ?\t)) line-end)
    599   "Matches first or last line of a hidden block.
    600 Group 1 contains drawer's name or \"END\".")
    601 
    602 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
    603   "Regular expression matching the first line of a property drawer.")
    604 
    605 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
    606   "Regular expression matching the last line of a property drawer.")
    607 
    608 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
    609   "Regular expression matching the first line of a clock drawer.")
    610 
    611 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
    612   "Regular expression matching the last line of a clock drawer.")
    613 
    614 (defconst org-logbook-drawer-re
    615   (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
    616 	   (*? (0+ nonl) "\n")
    617 	   (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
    618   "Matches an entire LOGBOOK drawer.")
    619 
    620 (defconst org-property-drawer-re
    621   (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
    622 	  "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
    623 	  "[ \t]*:END:[ \t]*$")
    624   "Matches an entire property drawer.")
    625 
    626 (defconst org-clock-drawer-re
    627   (concat "\\(" org-clock-drawer-start-re "\\)\\(?:.\\|\n\\)*?\\("
    628 	  org-clock-drawer-end-re "\\)\n?")
    629   "Matches an entire clock drawer.")
    630 
    631 ;;;; Headline
    632 
    633 (defconst org-heading-keyword-regexp-format
    634   "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
    635   "Printf format for a regexp matching a headline with some keyword.
    636 This regexp will match the headline of any node which has the
    637 exact keyword that is put into the format.  The keyword isn't in
    638 any group by default, but the stars and the body are.")
    639 
    640 (defconst org-heading-keyword-maybe-regexp-format
    641   "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
    642   "Printf format for a regexp matching a headline, possibly with some keyword.
    643 This regexp can match any headline with the specified keyword, or
    644 without a keyword.  The keyword isn't in any group by default,
    645 but the stars and the body are.")
    646 
    647 (defconst org-archive-tag "ARCHIVE"
    648   "The tag that marks a subtree as archived.
    649 An archived subtree does not open during visibility cycling, and does
    650 not contribute to the agenda listings.")
    651 
    652 (defconst org-tag-re "[[:alnum:]_@#%]+"
    653   "Regexp matching a single tag.")
    654 
    655 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
    656   "Regexp matching the tag group at the end of a line, with leading spaces.
    657 Tags are stored in match group 1.  Match group 2 stores the tags
    658 without the enclosing colons.")
    659 
    660 (defconst org-tag-line-re
    661   "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
    662   "Regexp matching tags in a headline.
    663 Tags are stored in match group 1.  Match group 2 stores the tags
    664 without the enclosing colons.")
    665 
    666 (eval-and-compile
    667   (defconst org-comment-string "COMMENT"
    668     "Entries starting with this keyword will never be exported.
    669 \\<org-mode-map>
    670 An entry can be toggled between COMMENT and normal with
    671 `\\[org-toggle-comment]'."))
    672 
    673 
    674 ;;;; LaTeX Environments and Fragments
    675 
    676 (defconst org-latex-regexps
    677   '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)\\(?:.\\|\n\\)+?\\\\end{\\2}\\)" 1 t)
    678     ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
    679     ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)" 2 nil)
    680     ("$"  "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)" 2 nil)
    681     ("\\(" "\\\\(\\(?:.\\|\n\\)*?\\\\)" 0 nil)
    682     ("\\[" "\\\\\\[\\(?:.\\|\n\\)*?\\\\\\]" 0 nil)
    683     ("$$" "\\$\\$\\(?:.\\|\n\\)*?\\$\\$" 0 nil))
    684   "Regular expressions for matching embedded LaTeX.")
    685 
    686 ;;;; Node Property
    687 
    688 (defconst org-effort-property "Effort"
    689   "The property that is being used to keep track of effort estimates.
    690 Effort estimates given in this property need to be in the format
    691 defined in org-duration.el.")
    692 
    693 
    694 ;;; The custom variables
    695 
    696 (defgroup org nil
    697   "Outline-based notes management and organizer."
    698   :tag "Org"
    699   :group 'outlines
    700   :group 'calendar)
    701 
    702 (defcustom org-mode-hook nil
    703   "Mode hook for Org mode, run after the mode was turned on."
    704   :group 'org
    705   :type 'hook)
    706 
    707 (defcustom org-load-hook nil
    708   "Hook that is run after org.el has been loaded."
    709   :group 'org
    710   :type 'hook)
    711 
    712 (make-obsolete-variable
    713  'org-load-hook
    714  "use `with-eval-after-load' instead." "9.5")
    715 
    716 (defcustom org-log-buffer-setup-hook nil
    717   "Hook that is run after an Org log buffer is created."
    718   :group 'org
    719   :version "24.1"
    720   :type 'hook)
    721 
    722 (defvar org-modules)  ; defined below
    723 (defvar org-modules-loaded nil
    724   "Have the modules been loaded already?")
    725 
    726 ;;;###autoload
    727 (defun org-load-modules-maybe (&optional force)
    728   "Load all extensions listed in `org-modules'."
    729   (when (or force (not org-modules-loaded))
    730     (dolist (ext org-modules)
    731       (condition-case-unless-debug nil (require ext)
    732 	(error (message "Problems while trying to load feature `%s'" ext))))
    733     (setq org-modules-loaded t)))
    734 
    735 (defun org-set-modules (var value)
    736   "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
    737   (set-default-toplevel-value var value)
    738   (when (featurep 'org)
    739     (org-load-modules-maybe 'force)
    740     ;; FIXME: We can't have all the requires at top-level due to
    741     ;; circular dependencies.  Yet, this function might sometimes be
    742     ;; called when 'org-element is not loaded.
    743     (require 'org-element)
    744     (org-element-cache-reset 'all)))
    745 
    746 (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
    747   "Modules that should always be loaded together with org.el.
    748 
    749 If a description starts with <C>, the file is not part of Emacs and Org mode,
    750 so loading it will require that you have properly installed org-contrib
    751 package from NonGNU Emacs Lisp Package Archive
    752 https://elpa.nongnu.org/nongnu/org-contrib.html
    753 
    754 You can also use this system to load external packages (i.e. neither Org
    755 core modules, nor org-contrib modules).  Just add symbols
    756 to the end of the list.  If the package is called org-xyz.el, then you need
    757 to add the symbol `xyz', and the package must have a call to:
    758 
    759    (provide \\='org-xyz)
    760 
    761 For export specific modules, see also `org-export-backends'."
    762   :group 'org
    763   :set 'org-set-modules
    764   :package-version '(Org . "9.5")
    765   :type
    766   '(set :greedy t
    767 	(const :tag "   bbdb:              Links to BBDB entries" ol-bbdb)
    768 	(const :tag "   bibtex:            Links to BibTeX entries" ol-bibtex)
    769 	(const :tag "   crypt:             Encryption of subtrees" org-crypt)
    770 	(const :tag "   ctags:             Access to Emacs tags with links" org-ctags)
    771 	(const :tag "   docview:           Links to Docview buffers" ol-docview)
    772         (const :tag "   doi:               Links to DOI references" ol-doi)
    773 	(const :tag "   eww:               Store link to URL of Eww" ol-eww)
    774 	(const :tag "   gnus:              Links to GNUS folders/messages" ol-gnus)
    775 	(const :tag "   habit:             Track your consistency with habits" org-habit)
    776 	(const :tag "   id:                Global IDs for identifying entries" org-id)
    777 	(const :tag "   info:              Links to Info nodes" ol-info)
    778 	(const :tag "   inlinetask:        Tasks independent of outline hierarchy" org-inlinetask)
    779 	(const :tag "   irc:               Links to IRC/ERC chat sessions" ol-irc)
    780 	(const :tag "   mhe:               Links to MHE folders/messages" ol-mhe)
    781 	(const :tag "   mouse:             Additional mouse support" org-mouse)
    782 	(const :tag "   protocol:          Intercept calls from emacsclient" org-protocol)
    783 	(const :tag "   rmail:             Links to RMAIL folders/messages" ol-rmail)
    784 	(const :tag "   tempo:             Fast completion for structures" org-tempo)
    785 	(const :tag "   w3m:               Special cut/paste from w3m to Org mode." ol-w3m)
    786 	(const :tag "   eshell:            Links to working directories in Eshell" ol-eshell)
    787 
    788 	(const :tag "C  annotate-file:     Annotate a file with Org syntax" org-annotate-file)
    789 	(const :tag "C  bookmark:          Links to bookmarks" ol-bookmark)
    790 	(const :tag "C  checklist:         Extra functions for checklists in repeated tasks" org-checklist)
    791 	(const :tag "C  choose:            Use TODO keywords to mark decisions states" org-choose)
    792 	(const :tag "C  collector:         Collect properties into tables" org-collector)
    793 	(const :tag "C  depend:            TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
    794 	(const :tag "C  elisp-symbol:      Links to emacs-lisp symbols" ol-elisp-symbol)
    795 	(const :tag "C  eval-light:        Evaluate inbuffer-code on demand" org-eval-light)
    796 	(const :tag "C  eval:              Include command output as text" org-eval)
    797 	(const :tag "C  expiry:            Expiry mechanism for Org entries" org-expiry)
    798 	(const :tag "C  git-link:          Links to specific file version" ol-git-link)
    799 	(const :tag "C  interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
    800         (const :tag "C  invoice:           Help manage client invoices in Org mode" org-invoice)
    801 	(const :tag "C  learn:             SuperMemo's incremental learning algorithm" org-learn)
    802 	(const :tag "C  mac-iCal:          Imports events from iCal.app to the Emacs diary" org-mac-iCal)
    803 	(const :tag "C  mac-link:          Grab links and url from various mac Applications" org-mac-link)
    804 	(const :tag "C  mairix:            Hook mairix search into Org for different MUAs" org-mairix)
    805 	(const :tag "C  man:               Links to man pages in Org mode" ol-man)
    806 	(const :tag "C  mew:               Links to Mew folders/messages" ol-mew)
    807 	(const :tag "C  notify:            Notifications for Org mode" org-notify)
    808 	(const :tag "C  notmuch:           Provide Org links to notmuch searches or messages" ol-notmuch)
    809 	(const :tag "C  panel:             Simple routines for us with bad memory" org-panel)
    810 	(const :tag "C  registry:          A registry for Org links" org-registry)
    811 	(const :tag "C  screen:            Visit screen sessions through links" org-screen)
    812 	(const :tag "C  screenshot:        Take and manage screenshots in Org files" org-screenshot)
    813 	(const :tag "C  secretary:         Team management with Org" org-secretary)
    814 	(const :tag "C  sqlinsert:         Convert Org tables to SQL insertions" orgtbl-sqlinsert)
    815 	(const :tag "C  toc:               Table of contents for Org buffer" org-toc)
    816 	(const :tag "C  track:             Keep up with Org mode development" org-track)
    817 	(const :tag "C  velocity           Something like Notational Velocity for Org" org-velocity)
    818 	(const :tag "C  vm:                Links to VM folders/messages" ol-vm)
    819 	(const :tag "C  wikinodes:         CamelCase wiki-like links" org-wikinodes)
    820 	(const :tag "C  wl:                Links to Wanderlust folders/messages" ol-wl)
    821 	(repeat :tag "External packages" :inline t (symbol :tag "Package"))))
    822 
    823 (defvar org-export-registered-backends) ; From ox.el.
    824 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
    825 (declare-function org-export-backend-name "ox" (backend) t)
    826 (defcustom org-export-backends '(ascii html icalendar latex odt)
    827   "List of export backends that should be always available.
    828 
    829 If a description starts with <C>, the file is not part of Emacs and Org mode,
    830 so loading it will require that you have properly installed org-contrib
    831 package from NonGNU Emacs Lisp Package Archive
    832 https://elpa.nongnu.org/nongnu/org-contrib.html
    833 
    834 Unlike to `org-modules', libraries in this list will not be
    835 loaded along with Org, but only once the export framework is
    836 needed.
    837 
    838 This variable needs to be set before org.el is loaded.  If you
    839 need to make a change while Emacs is running, use the customize
    840 interface or run the following code, where VAL stands for the new
    841 value of the variable, after updating it:
    842 
    843   (progn
    844     (setq org-export-registered-backends
    845           (cl-remove-if-not
    846            (lambda (backend)
    847              (let ((name (org-export-backend-name backend)))
    848                (or (memq name val)
    849                    (catch \\='parentp
    850                      (dolist (b val)
    851                        (and (org-export-derived-backend-p b name)
    852                             (throw \\='parentp t)))))))
    853            org-export-registered-backends))
    854     (let ((new-list (mapcar #\\='org-export-backend-name
    855                             org-export-registered-backends)))
    856       (dolist (backend val)
    857         (cond
    858          ((not (load (format \"ox-%s\" backend) t t))
    859           (message \"Problems while trying to load export backend \\=`%s\\='\"
    860                    backend))
    861          ((not (memq backend new-list)) (push backend new-list))))
    862       (set-default \\='org-export-backends new-list)))
    863 
    864 Adding a backend to this list will also pull the backend it
    865 depends on, if any."
    866   :group 'org
    867   :group 'org-export
    868   :version "26.1"
    869   :package-version '(Org . "9.0")
    870   :initialize 'custom-initialize-set
    871   :set (lambda (var val)
    872 	 (if (not (featurep 'ox)) (set-default-toplevel-value var val)
    873 	   ;; Any backend not required anymore (not present in VAL and not
    874 	   ;; a parent of any backend in the new value) is removed from the
    875 	   ;; list of registered backends.
    876 	   (setq org-export-registered-backends
    877 		 (cl-remove-if-not
    878 		  (lambda (backend)
    879 		    (let ((name (org-export-backend-name backend)))
    880 		      (or (memq name val)
    881 			  (catch 'parentp
    882 			    (dolist (b val)
    883 			      (and (org-export-derived-backend-p b name)
    884 				   (throw 'parentp t)))))))
    885 		  org-export-registered-backends))
    886 	   ;; Now build NEW-LIST of both new backends and required
    887 	   ;; parents.
    888 	   (let ((new-list (mapcar #'org-export-backend-name
    889 				   org-export-registered-backends)))
    890 	     (dolist (backend val)
    891 	       (cond
    892 		((not (load (format "ox-%s" backend) t t))
    893 		 (message "Problems while trying to load export backend `%s'"
    894 			  backend))
    895 		((not (memq backend new-list)) (push backend new-list))))
    896 	     ;; Set VAR to that list with fixed dependencies.
    897 	     (set-default-toplevel-value var new-list))))
    898   :type '(set :greedy t
    899 	      (const :tag "   ascii       Export buffer to ASCII format" ascii)
    900 	      (const :tag "   beamer      Export buffer to Beamer presentation" beamer)
    901 	      (const :tag "   html        Export buffer to HTML format" html)
    902 	      (const :tag "   icalendar   Export buffer to iCalendar format" icalendar)
    903 	      (const :tag "   latex       Export buffer to LaTeX format" latex)
    904 	      (const :tag "   man         Export buffer to MAN format" man)
    905 	      (const :tag "   md          Export buffer to Markdown format" md)
    906 	      (const :tag "   odt         Export buffer to ODT format" odt)
    907 	      (const :tag "   org         Export buffer to Org format" org)
    908 	      (const :tag "   texinfo     Export buffer to Texinfo format" texinfo)
    909 	      (const :tag "C  confluence  Export buffer to Confluence Wiki format" confluence)
    910 	      (const :tag "C  deck        Export buffer to deck.js presentations" deck)
    911 	      (const :tag "C  freemind    Export buffer to Freemind mindmap format" freemind)
    912 	      (const :tag "C  groff       Export buffer to Groff format" groff)
    913 	      (const :tag "C  koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
    914 	      (const :tag "C  RSS 2.0     Export buffer to RSS 2.0 format" rss)
    915 	      (const :tag "C  s5          Export buffer to s5 presentations" s5)
    916 	      (const :tag "C  taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
    917 
    918 (eval-after-load 'ox
    919   '(dolist (backend org-export-backends)
    920      (condition-case-unless-debug nil (require (intern (format "ox-%s" backend)))
    921        (error (message "Problems while trying to load export backend `%s'"
    922 		       backend)))))
    923 
    924 (defcustom org-support-shift-select nil
    925   "Non-nil means make shift-cursor commands select text when possible.
    926 \\<org-mode-map>
    927 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
    928 start selecting a region, or enlarge regions started in this way.
    929 In Org mode, in special contexts, these same keys are used for
    930 other purposes, important enough to compete with shift selection.
    931 Org tries to balance these needs by supporting `shift-select-mode'
    932 outside these special contexts, under control of this variable.
    933 
    934 The default of this variable is nil, to avoid confusing behavior.  Shifted
    935 cursor keys will then execute Org commands in the following contexts:
    936 - on a headline, changing TODO state (left/right) and priority (up/down)
    937 - on a time stamp, changing the time
    938 - in a plain list item, changing the bullet type
    939 - in a property definition line, switching between allowed values
    940 - in the BEGIN line of a clock table (changing the time block).
    941 - in a table, moving the cell in the specified direction.
    942 Outside these contexts, the commands will throw an error.
    943 
    944 When this variable is t and the cursor is not in a special
    945 context, Org mode will support shift-selection for making and
    946 enlarging regions.  To make this more effective, the bullet
    947 cycling will no longer happen anywhere in an item line, but only
    948 if the cursor is exactly on the bullet.
    949 
    950 If you set this variable to the symbol `always', then the keys
    951 will not be special in headlines, property lines, item lines, and
    952 table cells, to make shift selection work there as well.  If this is
    953 what you want, you can use the following alternative commands:
    954 `\\[org-todo]' and `\\[org-priority]' \
    955 to change TODO state and priority,
    956 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
    957 can be used to switch TODO sets,
    958 `\\[org-ctrl-c-minus]' to cycle item bullet types,
    959 and properties can be edited by hand or in column view.
    960 
    961 However, when the cursor is on a timestamp, shift-cursor commands
    962 will still edit the time stamp - this is just too good to give up."
    963   :group 'org
    964   :type '(choice
    965 	  (const :tag "Never" nil)
    966 	  (const :tag "When outside special context" t)
    967 	  (const :tag "Everywhere except timestamps" always)))
    968 
    969 (defcustom org-loop-over-headlines-in-active-region t
    970   "Shall some commands act upon headlines in the active region?
    971 
    972 When set to t, some commands will be performed in all headlines
    973 within the active region.
    974 
    975 When set to `start-level', some commands will be performed in all
    976 headlines within the active region, provided that these headlines
    977 are of the same level than the first one.
    978 
    979 When set to a string, those commands will be performed on the
    980 matching headlines within the active region.  Such string must be
    981 a tags/property/todo match as it is used in the agenda tags view.
    982 
    983 The list of commands is: `org-schedule', `org-deadline',
    984 `org-todo', `org-set-tags-command', `org-archive-subtree',
    985 `org-archive-set-tag', `org-toggle-archive-tag' and
    986 `org-archive-to-archive-sibling'.  The archiving commands skip
    987 already archived entries.
    988 
    989 See `org-agenda-loop-over-headlines-in-active-region' for the
    990 equivalent option for agenda views."
    991   :type '(choice (const :tag "Don't loop" nil)
    992 		 (const :tag "All headlines in active region" t)
    993 		 (const :tag "In active region, headlines at the same level than the first one" start-level)
    994 		 (string :tag "Tags/Property/Todo matcher"))
    995   :package-version '(Org . "9.4")
    996   :group 'org-todo
    997   :group 'org-archive)
    998 
    999 (defgroup org-startup nil
   1000   "Startup options Org uses when first visiting a file."
   1001   :tag "Org Startup"
   1002   :group 'org)
   1003 
   1004 (defcustom org-startup-folded 'showeverything
   1005   "Initial folding state of headings when entering Org mode.
   1006 
   1007 Allowed values are:
   1008 
   1009 symbol `nofold'
   1010   Do not fold headings.
   1011 
   1012 symbol `fold'
   1013   Fold everything, leaving only top-level headings visible.
   1014 
   1015 symbol `content'
   1016   Leave all the headings and sub-headings visible, but hide their
   1017   text.  This is an equivalent of table of contents.
   1018 
   1019 symbol `show2levels', `show3levels', `show4levels', `show5levels'
   1020   Show headings up to Nth level.
   1021 
   1022 symbol `showeverything' (default)
   1023   Start Org mode in fully unfolded state.  Unlike all other allowed
   1024   values, this value prevents drawers, blocks, and archived subtrees
   1025   from being folded even when `org-cycle-hide-block-startup',
   1026   `org-cycle-open-archived-trees', or `org-cycle-hide-drawer-startup'
   1027   are non-nil.  Per-subtree visibility settings (see manual node
   1028   `(org)Initial visibility)') are also ignored.
   1029 
   1030 This can also be configured on a per-file basis by adding one of
   1031 the following lines anywhere in the buffer:
   1032 
   1033    #+STARTUP: fold              (or `overview', this is equivalent)
   1034    #+STARTUP: nofold            (or `showall', this is equivalent)
   1035    #+STARTUP: content
   1036    #+STARTUP: show<n>levels (<n> = 2..5)
   1037    #+STARTUP: showeverything
   1038 
   1039 Set `org-agenda-inhibit-startup' to a non-nil value if you want
   1040 to ignore this option when Org opens agenda files for the first
   1041 time."
   1042   :group 'org-startup
   1043   :package-version '(Org . "9.4")
   1044   :type '(choice
   1045 	  (const :tag "nofold: show all" nofold)
   1046 	  (const :tag "fold: overview" fold)
   1047 	  (const :tag "fold: show two levels" show2levels)
   1048 	  (const :tag "fold: show three levels" show3levels)
   1049 	  (const :tag "fold: show four levels" show4evels)
   1050 	  (const :tag "fold: show five levels" show5levels)
   1051 	  (const :tag "content: all headlines" content)
   1052 	  (const :tag "show everything, even drawers" showeverything)))
   1053 
   1054 (defcustom org-startup-truncated t
   1055   "Non-nil means entering Org mode will set `truncate-lines'.
   1056 This is useful since some lines containing links can be very long and
   1057 uninteresting.  Also tables look terrible when wrapped.
   1058 
   1059 The variable `org-startup-truncated' enables you to configure
   1060 truncation for Org mode different to the other modes that use the
   1061 variable `truncate-lines' and as a shortcut instead of putting
   1062 the variable `truncate-lines' into the `org-mode-hook'.  If one
   1063 wants to configure truncation for Org mode not statically but
   1064 dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
   1065 the variable `truncate-lines' has to be used because in such a
   1066 case it is too late to set the variable `org-startup-truncated'."
   1067   :group 'org-startup
   1068   :type 'boolean)
   1069 
   1070 (defcustom org-startup-indented nil
   1071   "Non-nil means turn on `org-indent-mode' on startup.
   1072 This can also be configured on a per-file basis by adding one of
   1073 the following lines anywhere in the buffer:
   1074 
   1075    #+STARTUP: indent
   1076    #+STARTUP: noindent"
   1077   :group 'org-structure
   1078   :type '(choice
   1079 	  (const :tag "Not" nil)
   1080 	  (const :tag "Globally (slow on startup in large files)" t)))
   1081 
   1082 (defcustom org-startup-numerated nil
   1083   "Non-nil means turn on `org-num-mode' on startup.
   1084 This can also be configured on a per-file basis by adding one of
   1085 the following lines anywhere in the buffer:
   1086 
   1087    #+STARTUP: num
   1088    #+STARTUP: nonum"
   1089   :group 'org-structure
   1090   :package-version '(Org . "9.4")
   1091   :type '(choice
   1092 	  (const :tag "Not" nil)
   1093 	  (const :tag "Globally" t)))
   1094 
   1095 (defcustom org-use-sub-superscripts t
   1096   "Non-nil means interpret \"_\" and \"^\" for display.
   1097 
   1098 If you want to control how Org exports those characters, see
   1099 `org-export-with-sub-superscripts'.
   1100 
   1101 When this option is turned on, you can use TeX-like syntax for
   1102 sub- and superscripts within the buffer.  Several characters after
   1103 \"_\" or \"^\" will be considered as a single item - so grouping
   1104 with {} is normally not needed.  For example, the following things
   1105 will be parsed as single sub- or superscripts:
   1106 
   1107  10^24   or   10^tau     several digits will be considered 1 item.
   1108  10^-12  or   10^-tau    a leading sign with digits or a word
   1109  x^2-y^3                 will be read as x^2 - y^3, because items are
   1110 			 terminated by almost any nonword/nondigit char.
   1111  x^(2 - i)               expression inside round braces, including the
   1112                          braces is read as a sub/superscript.
   1113  x_{i^2}                 curly braces do grouping; braces are not
   1114                          considered a part of the sub/superscript.
   1115 
   1116 Still, ambiguity is possible.  So when in doubt, use {} to enclose
   1117 the sub/superscript.  If you set this variable to the symbol `{}',
   1118 the curly braces are *required* in order to trigger interpretations as
   1119 sub/superscript.  This can be helpful in documents that need \"_\"
   1120 frequently in plain text.
   1121 
   1122 Setting this variable does not change Org mode markup.  Org mode will
   1123 still parse the matching text as sub/superscript internally.  It is
   1124 only the visual appearance that will be changed."
   1125   :group 'org-startup
   1126   :version "24.4"
   1127   :package-version '(Org . "8.0")
   1128   :type '(choice
   1129 	  (const :tag "Always interpret" t)
   1130 	  (const :tag "Only with curly braces" {})
   1131 	  (const :tag "Never interpret" nil)))
   1132 
   1133 (defcustom org-startup-with-beamer-mode nil
   1134   "Non-nil means turn on `org-beamer-mode' on startup.
   1135 This can also be configured on a per-file basis by adding one of
   1136 the following lines anywhere in the buffer:
   1137 
   1138    #+STARTUP: beamer"
   1139   :group 'org-startup
   1140   :version "24.1"
   1141   :type 'boolean)
   1142 
   1143 (defcustom org-startup-align-all-tables nil
   1144   "Non-nil means align all tables when visiting a file.
   1145 This can also be configured on a per-file basis by adding one of
   1146 the following lines anywhere in the buffer:
   1147    #+STARTUP: align
   1148    #+STARTUP: noalign"
   1149   :group 'org-startup
   1150   :type 'boolean)
   1151 
   1152 (defcustom org-startup-shrink-all-tables nil
   1153   "Non-nil means shrink all table columns with a width cookie.
   1154 This can also be configured on a per-file basis by adding one of
   1155 the following lines anywhere in the buffer:
   1156    #+STARTUP: shrink"
   1157   :group 'org-startup
   1158   :type 'boolean
   1159   :version "27.1"
   1160   :package-version '(Org . "9.2")
   1161   :safe #'booleanp)
   1162 
   1163 (defcustom org-startup-with-inline-images nil
   1164   "Non-nil means show inline images when loading a new Org file.
   1165 This can also be configured on a per-file basis by adding one of
   1166 the following lines anywhere in the buffer:
   1167    #+STARTUP: inlineimages
   1168    #+STARTUP: noinlineimages"
   1169   :group 'org-startup
   1170   :version "24.1"
   1171   :type 'boolean)
   1172 
   1173 (defcustom org-startup-with-latex-preview nil
   1174   "Non-nil means preview LaTeX fragments when loading a new Org file.
   1175 
   1176 This can also be configured on a per-file basis by adding one of
   1177 the following lines anywhere in the buffer:
   1178    #+STARTUP: latexpreview
   1179    #+STARTUP: nolatexpreview"
   1180   :group 'org-startup
   1181   :version "24.4"
   1182   :package-version '(Org . "8.0")
   1183   :type 'boolean)
   1184 
   1185 (unless (boundp 'untrusted-content)
   1186   (defvar untrusted-content nil))
   1187 (defvar untrusted-content) ; defined in files.el since Emacs 29.3
   1188 (defvar org--latex-preview-when-risky nil
   1189   "If non-nil, enable LaTeX preview in Org buffers from unsafe source.
   1190 
   1191 Some specially designed LaTeX code may generate huge pdf or log files
   1192 that may exhaust disk space.
   1193 
   1194 This variable controls how to handle LaTeX preview when rendering LaTeX
   1195 fragments that originate from incoming email messages.  It has no effect
   1196 when Org mode is unable to determine the origin of the Org buffer.
   1197 
   1198 An Org buffer is considered to be from unsafe source when the
   1199 variable `untrusted-content' has a non-nil value in the buffer.
   1200 
   1201 If this variable is non-nil, LaTeX previews are rendered unconditionally.
   1202 
   1203 This variable may be renamed or changed in the future.")
   1204 
   1205 (defcustom org-insert-mode-line-in-empty-file nil
   1206   "Non-nil means insert the first line setting Org mode in empty files.
   1207 When the function `org-mode' is called interactively in an empty file, this
   1208 normally means that the file name does not automatically trigger Org mode.
   1209 To ensure that the file will always be in Org mode in the future, a
   1210 line enforcing Org mode will be inserted into the buffer, if this option
   1211 has been set."
   1212   :group 'org-startup
   1213   :type 'boolean)
   1214 
   1215 (defcustom org-ellipsis nil
   1216   "The ellipsis to use in the Org mode outline.
   1217 
   1218 When nil, just use the standard three dots.  When a non-empty string,
   1219 use that string instead.
   1220 
   1221 The change affects only Org mode (which will then use its own display table).
   1222 Changing this requires executing `\\[org-mode]' in a buffer to become
   1223 effective.  It cannot be set as a local variable."
   1224   :group 'org-startup
   1225   :type '(choice (const :tag "Default" nil)
   1226 		 (string :tag "String" :value "...#")))
   1227 
   1228 (defvar org-display-table nil
   1229   "The display table for Org mode, in case `org-ellipsis' is non-nil.")
   1230 
   1231 (defcustom org-directory "~/org"
   1232   "Directory with Org files.
   1233 This is just a default location to look for Org files.  There is no need
   1234 at all to put your files into this directory.  It is used in the
   1235 following situations:
   1236 
   1237 1. When a capture template specifies a target file that is not an
   1238    absolute path.  The path will then be interpreted relative to
   1239    `org-directory'
   1240 2. When the value of variable `org-agenda-files' is a single file, any
   1241    relative paths in this file will be taken as relative to
   1242    `org-directory'."
   1243   :group 'org-refile
   1244   :group 'org-capture
   1245   :type 'directory)
   1246 
   1247 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
   1248   "Default target for storing notes.
   1249 Used as a fall back file for org-capture.el, for templates that
   1250 do not specify a target file."
   1251   :group 'org-refile
   1252   :group 'org-capture
   1253   :type 'file)
   1254 
   1255 (defcustom org-reverse-note-order nil
   1256   "Non-nil means store new notes at the beginning of a file or entry.
   1257 When nil, new notes will be filed to the end of a file or entry.
   1258 This can also be a list with cons cells of regular expressions that
   1259 are matched against file names, and values."
   1260   :group 'org-capture
   1261   :group 'org-refile
   1262   :type '(choice
   1263 	  (const :tag "Reverse always" t)
   1264 	  (const :tag "Reverse never" nil)
   1265 	  (repeat :tag "By file name regexp"
   1266 		  (cons regexp boolean))))
   1267 
   1268 (defgroup org-keywords nil
   1269   "Keywords in Org mode."
   1270   :tag "Org Keywords"
   1271   :group 'org)
   1272 
   1273 (defcustom org-closed-keep-when-no-todo nil
   1274   "Remove CLOSED: timestamp when switching back to a non-todo state?"
   1275   :group 'org-todo
   1276   :group 'org-keywords
   1277   :version "24.4"
   1278   :package-version '(Org . "8.0")
   1279   :type 'boolean)
   1280 
   1281 (defgroup org-structure nil
   1282   "Options concerning the general structure of Org files."
   1283   :tag "Org Structure"
   1284   :group 'org)
   1285 
   1286 (defcustom org-indirect-buffer-display 'other-window
   1287   "How should indirect tree buffers be displayed?
   1288 
   1289 This applies to indirect buffers created with the commands
   1290 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
   1291 
   1292 Valid values are:
   1293 current-window   Display in the current window
   1294 other-window     Just display in another window.
   1295 dedicated-frame  Create one new frame, and reuse it each time.
   1296 new-frame        Make a new frame each time.  Note that in this case
   1297                  previously-made indirect buffers are kept, and you need to
   1298                  kill these buffers yourself."
   1299   :group 'org-structure
   1300   :group 'org-agenda-windows
   1301   :type '(choice
   1302 	  (const :tag "In current window" current-window)
   1303 	  (const :tag "In current frame, other window" other-window)
   1304 	  (const :tag "Each time a new frame" new-frame)
   1305 	  (const :tag "One dedicated frame" dedicated-frame)))
   1306 
   1307 (defconst org-file-apps-gnu
   1308   '((remote . emacs)
   1309     (system . mailcap)
   1310     (t . mailcap))
   1311   "Default file applications on a UNIX or GNU/Linux system.
   1312 See `org-file-apps'.")
   1313 
   1314 (defconst org-file-apps-macos
   1315   '((remote . emacs)
   1316     (system . "open %s")
   1317     ("ps.gz"  . "gv %s")
   1318     ("eps.gz" . "gv %s")
   1319     ("dvi"    . "xdvi %s")
   1320     ("fig"    . "xfig %s")
   1321     (t . "open %s"))
   1322   "Default file applications on a macOS system.
   1323 The system \"open\" is known as a default, but we use X11 applications
   1324 for some files for which the OS does not have a good default.
   1325 See `org-file-apps'.")
   1326 
   1327 (defconst org-file-apps-windowsnt
   1328   (list '(remote . emacs)
   1329 	(cons 'system (lambda (file _path)
   1330 			(with-no-warnings (w32-shell-execute "open" file))))
   1331 	(cons t (lambda (file _path)
   1332 		  (with-no-warnings (w32-shell-execute "open" file)))))
   1333   "Default file applications on a Windows NT system.
   1334 The system \"open\" is used for most files.
   1335 See `org-file-apps'.")
   1336 
   1337 (defcustom org-file-apps
   1338   '((auto-mode . emacs)
   1339     (directory . emacs)
   1340     ("\\.mm\\'" . default)
   1341     ("\\.x?html?\\'" . default)
   1342     ("\\.pdf\\'" . default))
   1343   "Applications for opening `file:path' items in a document.
   1344 
   1345 \\<org-mode-map>
   1346 Org mode uses system defaults for different file types, but you
   1347 can use this variable to set the application for a given file
   1348 extension.  The entries in this list are cons cells where the car
   1349 identifies files and the cdr the corresponding command.
   1350 
   1351 Possible values for the file identifier are:
   1352 
   1353  \"string\"    A string as a file identifier can be interpreted in different
   1354                ways, depending on its contents:
   1355 
   1356                - Alphanumeric characters only:
   1357                  Match links with this file extension.
   1358                  Example: (\"pdf\" . \"evince %s\")
   1359                           to open PDFs with evince.
   1360 
   1361                - Regular expression: Match links where the
   1362                  filename matches the regexp.  If you want to
   1363                  use groups here, use shy groups.
   1364 
   1365                  Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
   1366                           (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
   1367                           to open *.html and *.xhtml with firefox.
   1368 
   1369                - Regular expression which contains (non-shy) groups:
   1370                  Match links where the whole link, including \"::\", and
   1371                  anything after that, matches the regexp.
   1372                  In a custom command string, %1, %2, etc. are replaced with
   1373                  the parts of the link that were matched by the groups.
   1374                  For backwards compatibility, if a command string is given
   1375                  that does not use any of the group matches, this case is
   1376                  handled identically to the second one (i.e. match against
   1377                  file name only).
   1378                  In a custom function, you can access the group matches with
   1379                  (match-string n link).
   1380 
   1381                  Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
   1382 \"evince -p %1 %s\")
   1383                      to open [[file:document.pdf::5]] with evince at page 5.
   1384 
   1385                  Likely, you will need more entries: without page
   1386                  number; with search pattern; with
   1387                  cross-reference anchor; some combination of
   1388                  options.  Consider simple pattern here and a
   1389                  Lisp function to determine command line
   1390                  arguments instead.  Passing an argument list to
   1391                  `call-process' or `make-process' directly avoids
   1392                  treating some character in peculiar file names
   1393                  as shell specials that prompt parts of said file
   1394                  names to be executed as subcommands.
   1395 
   1396  `directory'   Matches a directory
   1397  `remote'      Matches a remote file, accessible through tramp.
   1398                Remote files most likely should be visited through Emacs
   1399                because external applications cannot handle such paths.
   1400 `auto-mode'    Matches files that are matched by any entry in `auto-mode-alist',
   1401                so all files Emacs knows how to handle.  Using this with
   1402                command `emacs' will open most files in Emacs.  Beware that this
   1403                will also open html files inside Emacs, unless you add
   1404                (\"html\" . default) to the list as well.
   1405  `system'      The system command to open files, like `open' on Windows
   1406                and macOS, and mailcap under GNU/Linux.  This is the command
   1407                that will be selected if you call `org-open-at-point' with a
   1408                double prefix argument (`\\[universal-argument] \
   1409 \\[universal-argument] \\[org-open-at-point]').
   1410  t             Default for files not matched by any of the other options.
   1411 
   1412 Possible values for the command are:
   1413 
   1414  `emacs'       The file will be visited by the current Emacs process.
   1415  `default'     Use the default application for this file type, which is the
   1416                association for t in the list, most likely in the system-specific
   1417                part.  This can be used to overrule an unwanted setting in the
   1418                system-specific variable.
   1419  `system'      Use the system command for opening files, like \"open\".
   1420                This command is specified by the entry whose car is `system'.
   1421                Most likely, the system-specific version of this variable
   1422                does define this command, but you can overrule/replace it
   1423                here.
   1424 `mailcap'      Use command specified in the mailcaps.
   1425  string        A command to be executed by a shell; %s will be replaced
   1426                by the path to the file.
   1427  function      A Lisp function, which will be called with two arguments:
   1428                the file path and the original link string, without the
   1429                \"file:\" prefix.
   1430 
   1431 For more examples, see the system specific constants
   1432 `org-file-apps-macos'
   1433 `org-file-apps-windowsnt'
   1434 `org-file-apps-gnu'."
   1435   :group 'org
   1436   :package-version '(Org . "9.4")
   1437   :type '(repeat
   1438 	  (cons (choice :value ""
   1439 			(string :tag "Extension")
   1440 			(const :tag "System command to open files" system)
   1441 			(const :tag "Default for unrecognized files" t)
   1442 			(const :tag "Remote file" remote)
   1443 			(const :tag "Links to a directory" directory)
   1444 			(const :tag "Any files that have Emacs modes"
   1445 			       auto-mode))
   1446 		(choice :value ""
   1447 			(const :tag "Visit with Emacs" emacs)
   1448 			(const :tag "Use default" default)
   1449 			(const :tag "Use the system command" system)
   1450 			(string :tag "Command")
   1451 			(function :tag "Function")))))
   1452 
   1453 (defcustom org-resource-download-policy 'prompt
   1454   "The policy applied to requests to obtain remote resources.
   1455 
   1456 This affects keywords like #+setupfile and #+include on export,
   1457 `org-persist-write:url',and `org-attach-url' in non-interactive
   1458 Emacs sessions.
   1459 
   1460 This recognizes four possible values:
   1461 - t (dangerous), remote resources should always be downloaded.
   1462 - prompt, you will be prompted to download resources not considered safe.
   1463 - safe, only resources considered safe will be downloaded.
   1464 - nil, never download remote resources.
   1465 
   1466 A resource is considered safe if it matches one of the patterns
   1467 in `org-safe-remote-resources'."
   1468   :group 'org
   1469   :package-version '(Org . "9.6")
   1470   :type '(choice (const :tag "Always download remote resources (dangerous)" t)
   1471                  (const :tag "Prompt before downloading an unsafe resource" prompt)
   1472                  (const :tag "Only download resources considered safe" safe)
   1473                  (const :tag "Never download any resources" nil)))
   1474 
   1475 (defcustom org-safe-remote-resources nil
   1476   "A list of regexp patterns matching safe URIs.
   1477 URI regexps are applied to both URLs and Org files requesting
   1478 remote resources."
   1479   :group 'org
   1480   :package-version '(Org . "9.6")
   1481   :type '(repeat regexp))
   1482 
   1483 (defcustom org-open-non-existing-files nil
   1484   "Non-nil means `org-open-file' opens non-existing files.
   1485 
   1486 When nil, an error is thrown.
   1487 
   1488 This variable applies only to external applications because they
   1489 might choke on non-existing files.  If the link is to a file that
   1490 will be opened in Emacs, the variable is ignored."
   1491   :group 'org
   1492   :type 'boolean
   1493   :safe #'booleanp)
   1494 
   1495 (defcustom org-open-directory-means-index-dot-org nil
   1496   "When non-nil a link to a directory really means to \"index.org\".
   1497 When nil, following a directory link runs Dired or opens
   1498 a finder/explorer window on that directory."
   1499   :group 'org
   1500   :type 'boolean
   1501   :safe #'booleanp)
   1502 
   1503 (defcustom org-bookmark-names-plist
   1504   '(:last-capture "org-capture-last-stored"
   1505 		  :last-refile "org-refile-last-stored"
   1506 		  :last-capture-marker "org-capture-last-stored-marker")
   1507   "Names for bookmarks automatically set by some Org commands.
   1508 This can provide strings as names for a number of bookmarks Org sets
   1509 automatically.  The following keys are currently implemented:
   1510   :last-capture
   1511   :last-capture-marker
   1512   :last-refile
   1513 When a key does not show up in the property list, the corresponding bookmark
   1514 is not set."
   1515   :group 'org-structure
   1516   :type 'plist)
   1517 
   1518 (defgroup org-edit-structure nil
   1519   "Options concerning structure editing in Org mode."
   1520   :tag "Org Edit Structure"
   1521   :group 'org-structure)
   1522 
   1523 (defcustom org-odd-levels-only nil
   1524   "Non-nil means skip even levels and only use odd levels for the outline.
   1525 This has the effect that two stars are being added/taken away in
   1526 promotion/demotion commands.  It also influences how levels are
   1527 handled by the exporters.
   1528 Changing it requires restart of `font-lock-mode' to become effective
   1529 for fontification also in regions already fontified.
   1530 You may also set this on a per-file basis by adding one of the following
   1531 lines to the buffer:
   1532 
   1533    #+STARTUP: odd
   1534    #+STARTUP: oddeven"
   1535   :group 'org-edit-structure
   1536   :group 'org-appearance
   1537   :type 'boolean)
   1538 
   1539 (defcustom org-adapt-indentation nil
   1540   "Non-nil means adapt indentation to outline node level.
   1541 
   1542 When set to t, Org assumes that you write outlines by indenting
   1543 text in each node to align with the headline, after the stars.
   1544 
   1545 When this variable is set to `headline-data', Org only adapts the
   1546 indentation of the data lines right below the headline, such as
   1547 planning/clock lines and property/logbook drawers.
   1548 
   1549 The following issues are influenced by this variable:
   1550 
   1551 - The indentation is increased by one space in a demotion
   1552   command, and decreased by one in a promotion command.  However,
   1553   in the latter case, if shifting some line in the entry body
   1554   would alter document structure (e.g., insert a new headline),
   1555   indentation is not changed at all.
   1556 
   1557 - Property drawers and planning information is inserted indented
   1558   when this variable is set.  When nil, they will not be indented.
   1559 
   1560 - TAB indents a line relative to current level.  The lines below
   1561   a headline will be indented when this variable is set to t.
   1562 
   1563 Note that this is all about true indentation, by adding and
   1564 removing space characters.  See also \"org-indent.el\" which does
   1565 level-dependent indentation in a virtual way, i.e. at display
   1566 time in Emacs."
   1567   :group 'org-edit-structure
   1568   :type '(choice
   1569 	  (const :tag "Adapt indentation for all lines" t)
   1570 	  (const :tag "Adapt indentation for headline data lines"
   1571 		 headline-data)
   1572 	  (const :tag "Do not adapt indentation at all" nil))
   1573   :safe (lambda (x) (memq x '(t nil headline-data))))
   1574 
   1575 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
   1576 
   1577 (defcustom org-special-ctrl-a/e nil
   1578   "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
   1579 
   1580 When t, `C-a' will bring back the cursor to the beginning of the
   1581 headline text, i.e. after the stars and after a possible TODO
   1582 keyword.  In an item, this will be the position after bullet and
   1583 check-box, if any.  When the cursor is already at that position,
   1584 another `C-a' will bring it to the beginning of the line.
   1585 
   1586 `C-e' will jump to the end of the headline, ignoring the presence
   1587 of tags in the headline.  A second `C-e' will then jump to the
   1588 true end of the line, after any tags.  This also means that, when
   1589 this variable is non-nil, `C-e' also will never jump beyond the
   1590 end of the heading of a folded section, i.e. not after the
   1591 ellipses.
   1592 
   1593 When set to the symbol `reversed', the first `C-a' or `C-e' works
   1594 normally, going to the true line boundary first.  Only a directly
   1595 following, identical keypress will bring the cursor to the
   1596 special positions.
   1597 
   1598 This may also be a cons cell where the behavior for `C-a' and
   1599 `C-e' is set separately."
   1600   :group 'org-edit-structure
   1601   :type '(choice
   1602 	  (const :tag "off" nil)
   1603 	  (const :tag "on: after stars/bullet and before tags first" t)
   1604 	  (const :tag "reversed: true line boundary first" reversed)
   1605 	  (cons :tag "Set C-a and C-e separately"
   1606 		(choice :tag "Special C-a"
   1607 			(const :tag "off" nil)
   1608 			(const :tag "on: after  stars/bullet first" t)
   1609 			(const :tag "reversed: before stars/bullet first" reversed))
   1610 		(choice :tag "Special C-e"
   1611 			(const :tag "off" nil)
   1612 			(const :tag "on: before tags first" t)
   1613 			(const :tag "reversed: after tags first" reversed)))))
   1614 
   1615 (defcustom org-special-ctrl-k nil
   1616   "Non-nil means that \\<org-mode-map>\\[org-kill-line] \
   1617 will behave specially in headlines.
   1618 
   1619 When nil, \\[org-kill-line] will call the default `kill-line' command.
   1620 Otherwise, the following will happen when point is in a headline:
   1621 
   1622 - At the beginning of a headline, kill the entire line.
   1623 - In the middle of the headline text, kill the text up to the tags.
   1624 - After the headline text and before the tags, kill all the tags."
   1625   :group 'org-edit-structure
   1626   :type 'boolean)
   1627 
   1628 (defcustom org-ctrl-k-protect-subtree nil
   1629   "Non-nil means, do not delete a hidden subtree with `C-k'.
   1630 When set to the symbol `error', simply throw an error when `C-k' is
   1631 used to kill (part-of) a headline that has hidden text behind it.
   1632 Any other non-nil value will result in a query to the user, if it is
   1633 OK to kill that hidden subtree.  When nil, kill without remorse."
   1634   :group 'org-edit-structure
   1635   :version "24.1"
   1636   :type '(choice
   1637 	  (const :tag "Do not protect hidden subtrees" nil)
   1638 	  (const :tag "Protect hidden subtrees with a security query" t)
   1639 	  (const :tag "Never kill a hidden subtree with C-k" error)))
   1640 
   1641 (defcustom org-special-ctrl-o t
   1642   "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
   1643   :group 'org-edit-structure
   1644   :type 'boolean)
   1645 
   1646 (defcustom org-yank-folded-subtrees t
   1647   "Non-nil means when yanking subtrees, fold them.
   1648 If the kill is a single subtree, or a sequence of subtrees, i.e. if
   1649 it starts with a heading and all other headings in it are either children
   1650 or siblings, then fold all the subtrees.  However, do this only if no
   1651 text after the yank would be swallowed into a folded tree by this action."
   1652   :group 'org-edit-structure
   1653   :type 'boolean)
   1654 
   1655 (defcustom org-yank-adjusted-subtrees nil
   1656   "Non-nil means when yanking subtrees, adjust the level.
   1657 With this setting, `org-paste-subtree' is used to insert the subtree, see
   1658 this function for details."
   1659   :group 'org-edit-structure
   1660   :type 'boolean)
   1661 
   1662 (defcustom org-M-RET-may-split-line '((default . t))
   1663   "Non-nil means M-RET will split the line at the cursor position.
   1664 When nil, it will go to the end of the line before making a
   1665 new line.
   1666 You may also set this option in a different way for different
   1667 contexts.  Valid contexts are:
   1668 
   1669 headline  when creating a new headline
   1670 item      when creating a new item
   1671 table     in a table field
   1672 default   the value to be used for all contexts not explicitly
   1673           customized"
   1674   :group 'org-structure
   1675   :group 'org-table
   1676   :type '(choice
   1677 	  (const :tag "Always" t)
   1678 	  (const :tag "Never" nil)
   1679 	  (repeat :greedy t :tag "Individual contexts"
   1680 		  (cons
   1681 		   (choice :tag "Context"
   1682 			   (const headline)
   1683 			   (const item)
   1684 			   (const table)
   1685 			   (const default))
   1686 		   (boolean)))))
   1687 
   1688 (defcustom org-insert-heading-respect-content nil
   1689   "Non-nil means insert new headings after the current subtree.
   1690 \\<org-mode-map>
   1691 When nil, the new heading is created directly after the current line.
   1692 The commands `\\[org-insert-heading-respect-content]' and \
   1693 `\\[org-insert-todo-heading-respect-content]' turn this variable on
   1694 for the duration of the command."
   1695   :group 'org-structure
   1696   :type 'boolean)
   1697 
   1698 (defcustom org-blank-before-new-entry '((heading . auto)
   1699 					(plain-list-item . auto))
   1700   "Should `org-insert-heading' leave a blank line before new heading/item?
   1701 The value is an alist, with `heading' and `plain-list-item' as CAR,
   1702 and a boolean flag as CDR.  The cdr may also be the symbol `auto', in
   1703 which case Org will look at the surrounding headings/items and try to
   1704 make an intelligent decision whether to insert a blank line or not."
   1705   :group 'org-edit-structure
   1706   :type '(list
   1707 	  (cons (const heading)
   1708 		(choice (const :tag "Never" nil)
   1709 			(const :tag "Always" t)
   1710 			(const :tag "Auto" auto)))
   1711 	  (cons (const plain-list-item)
   1712 		(choice (const :tag "Never" nil)
   1713 			(const :tag "Always" t)
   1714 			(const :tag "Auto" auto)))))
   1715 
   1716 (defcustom org-insert-heading-hook nil
   1717   "Hook being run after inserting a new heading."
   1718   :group 'org-edit-structure
   1719   :type 'hook)
   1720 
   1721 (defgroup org-sparse-trees nil
   1722   "Options concerning sparse trees in Org mode."
   1723   :tag "Org Sparse Trees"
   1724   :group 'org-structure)
   1725 
   1726 (defcustom org-highlight-sparse-tree-matches t
   1727   "Non-nil means highlight all matches that define a sparse tree.
   1728 The highlights will automatically disappear the next time the buffer is
   1729 changed by an edit command."
   1730   :group 'org-sparse-trees
   1731   :type 'boolean)
   1732 
   1733 (defcustom org-remove-highlights-with-change t
   1734   "Non-nil means any change to the buffer will remove temporary highlights.
   1735 \\<org-mode-map>\
   1736 Such highlights are created by `org-occur' and `org-clock-display'.
   1737 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
   1738 to get rid of the highlights.
   1739 The highlights created by `org-latex-preview' always need
   1740 `\\[org-latex-preview]' to be removed."
   1741   :group 'org-sparse-trees
   1742   :group 'org-time
   1743   :type 'boolean)
   1744 
   1745 (defcustom org-occur-case-fold-search t
   1746   "Non-nil means `org-occur' should be case-insensitive.
   1747 If set to `smart' the search will be case-insensitive only if it
   1748 doesn't specify any upper case character."
   1749   :group 'org-sparse-trees
   1750   :version "26.1"
   1751   :type '(choice
   1752 	  (const :tag "Case-sensitive" nil)
   1753 	  (const :tag "Case-insensitive" t)
   1754 	  (const :tag "Case-insensitive for lower case searches only" smart)))
   1755 
   1756 (defcustom org-occur-hook '(org-first-headline-recenter)
   1757   "Hook that is run after `org-occur' has constructed a sparse tree.
   1758 This can be used to recenter the window to show as much of the structure
   1759 as possible."
   1760   :group 'org-sparse-trees
   1761   :type 'hook)
   1762 
   1763 (defcustom org-self-insert-cluster-for-undo nil
   1764   "Non-nil means cluster self-insert commands for undo when possible.
   1765 If this is set, then, like in the Emacs command loop, 20 consecutive
   1766 characters will be undone together.
   1767 This is configurable, because there is some impact on typing performance."
   1768   :group 'org-table
   1769   :type 'boolean)
   1770 
   1771 (defvaralias 'org-activate-links 'org-highlight-links)
   1772 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
   1773   "Types of links that should be highlighted in Org files.
   1774 
   1775 This is a list of symbols, each one of them leading to the
   1776 highlighting of a certain link type.
   1777 
   1778 You can still open links that are not highlighted.
   1779 
   1780 In principle, it does not hurt to turn on highlighting for all
   1781 link types.  There may be a small gain when turning off unused
   1782 link types.  The types are:
   1783 
   1784 bracket   The recommended [[link][description]] or [[link]] links with hiding.
   1785 angle     Links in angular brackets that may contain whitespace like
   1786           <bbdb:Carsten Dominik>.
   1787 plain     Plain links in normal text, no whitespace, like https://gnu.org.
   1788 radio     Text that is matched by a radio target, see manual for details.
   1789 tag       Tag settings in a headline (link to tag search).
   1790 date      Time stamps (link to calendar).
   1791 footnote  Footnote labels.
   1792 
   1793 If you set this variable during an Emacs session, use `org-mode-restart'
   1794 in the Org buffer so that the change takes effect."
   1795   :group 'org-appearance
   1796   :type '(set :greedy t
   1797 	      (const :tag "Double bracket links" bracket)
   1798 	      (const :tag "Angular bracket links" angle)
   1799 	      (const :tag "Plain text links" plain)
   1800 	      (const :tag "Radio target matches" radio)
   1801 	      (const :tag "Tags" tag)
   1802 	      (const :tag "Timestamps" date)
   1803 	      (const :tag "Footnotes" footnote)))
   1804 
   1805 (defcustom org-mark-ring-length 4
   1806   "Number of different positions to be recorded in the ring.
   1807 Changing this requires a restart of Emacs to work correctly."
   1808   :group 'org-link-follow
   1809   :type 'integer)
   1810 
   1811 (defgroup org-todo nil
   1812   "Options concerning TODO items in Org mode."
   1813   :tag "Org TODO"
   1814   :group 'org)
   1815 
   1816 (defgroup org-progress nil
   1817   "Options concerning Progress logging in Org mode."
   1818   :tag "Org Progress"
   1819   :group 'org-time)
   1820 
   1821 (defvar org-todo-interpretation-widgets
   1822   '((:tag "Sequence (cycling hits every state)" sequence)
   1823     (:tag "Type     (cycling directly to DONE)" type))
   1824   "The available interpretation symbols for customizing `org-todo-keywords'.
   1825 Interested libraries should add to this list.")
   1826 
   1827 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
   1828   "List of TODO entry keyword sequences and their interpretation.
   1829 \\<org-mode-map>This is a list of sequences.
   1830 
   1831 Each sequence starts with a symbol, either `sequence' or `type',
   1832 indicating if the keywords should be interpreted as a sequence of
   1833 action steps, or as different types of TODO items.  The first
   1834 keywords are states requiring action - these states will select a headline
   1835 for inclusion into the global TODO list Org produces.  If one of the
   1836 \"keywords\" is the vertical bar, \"|\", the remaining keywords
   1837 signify that no further action is necessary.  If \"|\" is not found,
   1838 the last keyword is treated as the only DONE state of the sequence.
   1839 
   1840 The command `\\[org-todo]' cycles an entry through these states, and one
   1841 additional state where no keyword is present.  For details about this
   1842 cycling, see the manual.
   1843 
   1844 TODO keywords and interpretation can also be set on a per-file basis with
   1845 the special #+SEQ_TODO and #+TYP_TODO lines.
   1846 
   1847 Each keyword can optionally specify a character for fast state selection
   1848 \(in combination with the variable `org-use-fast-todo-selection')
   1849 and specifiers for state change logging, using the same syntax that
   1850 is used in the \"#+TODO:\" lines.  For example, \"WAIT(w)\" says that
   1851 the WAIT state can be selected with the \"w\" key.  \"WAIT(w!)\"
   1852 indicates to record a time stamp each time this state is selected.
   1853 
   1854 Each keyword may also specify if a timestamp or a note should be
   1855 recorded when entering or leaving the state, by adding additional
   1856 characters in the parenthesis after the keyword.  This looks like this:
   1857 \"WAIT(w@/!)\".  \"@\" means to add a note (with time), \"!\" means to
   1858 record only the time of the state change.  With X and Y being either
   1859 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
   1860 Y when leaving the state if and only if the *target* state does not
   1861 define X.  You may omit any of the fast-selection key or X or /Y,
   1862 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
   1863 
   1864 For backward compatibility, this variable may also be just a list
   1865 of keywords.  In this case the interpretation (sequence or type) will be
   1866 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
   1867   :group 'org-todo
   1868   :group 'org-keywords
   1869   :type '(choice
   1870 	  (repeat :tag "Old syntax, just keywords"
   1871 		  (string :tag "Keyword"))
   1872 	  (repeat :tag "New syntax"
   1873 		  (cons
   1874 		   (choice
   1875 		    :tag "Interpretation"
   1876 		    ;;Quick and dirty way to see
   1877                     ;;`org-todo-interpretation'.  This takes the
   1878 		    ;;place of item arguments
   1879 		    :convert-widget
   1880 		    (lambda (widget)
   1881 		      (widget-put widget
   1882 				  :args (mapcar
   1883 					 (lambda (x)
   1884 					   (widget-convert
   1885 					    (cons 'const x)))
   1886 					 org-todo-interpretation-widgets))
   1887 		      widget))
   1888 		   (repeat
   1889 		    (string :tag "Keyword"))))))
   1890 
   1891 (defvar-local org-todo-keywords-1 nil
   1892   "All TODO and DONE keywords active in a buffer.")
   1893 (defvar org-todo-keywords-for-agenda nil)
   1894 (defvar org-done-keywords-for-agenda nil)
   1895 (defvar org-todo-keyword-alist-for-agenda nil)
   1896 (defvar org-tag-alist-for-agenda nil
   1897   "Alist of all tags from all agenda files.")
   1898 (defvar org-tag-groups-alist-for-agenda nil
   1899   "Alist of all groups tags from all current agenda files.")
   1900 (defvar-local org-tag-groups-alist nil)
   1901 (defvar org-agenda-contributing-files nil)
   1902 (defvar-local org-current-tag-alist nil
   1903   "Alist of all tag groups in current buffer.
   1904 This variable takes into consideration `org-tag-alist',
   1905 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
   1906 (defvar-local org-not-done-keywords nil)
   1907 (defvar-local org-done-keywords nil)
   1908 (defvar-local org-todo-heads nil)
   1909 (defvar-local org-todo-sets nil)
   1910 (defvar-local org-todo-log-states nil)
   1911 (defvar-local org-todo-kwd-alist nil)
   1912 (defvar-local org-todo-key-alist nil)
   1913 (defvar-local org-todo-key-trigger nil)
   1914 
   1915 (defcustom org-todo-interpretation 'sequence
   1916   "Controls how TODO keywords are interpreted.
   1917 This variable is in principle obsolete and is only used for
   1918 backward compatibility, if the interpretation of todo keywords is
   1919 not given already in `org-todo-keywords'.  See that variable for
   1920 more information."
   1921   :group 'org-todo
   1922   :group 'org-keywords
   1923   :type '(choice (const sequence)
   1924 		 (const type)))
   1925 
   1926 (defcustom org-use-fast-todo-selection 'auto
   1927   "\\<org-mode-map>\
   1928 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
   1929 This variable describes if and under what circumstances the cycling
   1930 mechanism for TODO keywords will be replaced by a single-key, direct
   1931 selection scheme, where the choices are displayed in a little window.
   1932 
   1933 When nil, fast selection is never used.  This means that the command
   1934 will always switch to the next state.
   1935 
   1936 When it is the symbol `auto', fast selection is whenever selection
   1937 keys have been defined.
   1938 
   1939 `expert' is like `auto', but no special window with the keyword
   1940 will be shown, choices will only be listed in the prompt.
   1941 
   1942 In all cases, the special interface is only used if access keys have
   1943 actually been assigned by the user, i.e. if keywords in the configuration
   1944 are followed by a letter in parenthesis, like TODO(t)."
   1945   :group 'org-todo
   1946   :set (lambda (var val)
   1947 	 (cond
   1948 	  ((eq var t) (set-default-toplevel-value var 'auto))
   1949 	  ((eq var 'prefix) (set-default-toplevel-value var nil))
   1950 	  (t (set-default-toplevel-value var val))))
   1951   :type '(choice
   1952 	  (const :tag "Never" nil)
   1953 	  (const :tag "Automatically, when key letter have been defined" auto)
   1954 	  (const :tag "Automatically, but don't show the selection window" expert)))
   1955 
   1956 (defcustom org-provide-todo-statistics t
   1957   "Non-nil means update todo statistics after insert and toggle.
   1958 ALL-HEADLINES means update todo statistics by including headlines
   1959 with no TODO keyword as well, counting them as not done.
   1960 A list of TODO keywords means the same, but skip keywords that are
   1961 not in this list.
   1962 When set to a list of two lists, the first list contains keywords
   1963 to consider as TODO keywords, the second list contains keywords
   1964 to consider as DONE keywords.
   1965 
   1966 When this is set, todo statistics is updated in the parent of the
   1967 current entry each time a todo state is changed."
   1968   :group 'org-todo
   1969   :type '(choice
   1970 	  (const :tag "Yes, only for TODO entries" t)
   1971 	  (const :tag "Yes, including all entries" all-headlines)
   1972 	  (repeat :tag "Yes, for TODOs in this list"
   1973 		  (string :tag "TODO keyword"))
   1974 	  (list :tag "Yes, for TODOs and DONEs in these lists"
   1975 		(repeat (string :tag "TODO keyword"))
   1976 		(repeat (string :tag "DONE keyword")))
   1977 	  (other :tag "No TODO statistics" nil)))
   1978 
   1979 (defcustom org-hierarchical-todo-statistics t
   1980   "Non-nil means TODO statistics covers just direct children.
   1981 When nil, all entries in the subtree are considered.
   1982 This has only an effect if `org-provide-todo-statistics' is set.
   1983 To set this to nil for only a single subtree, use a COOKIE_DATA
   1984 property and include the word \"recursive\" into the value."
   1985   :group 'org-todo
   1986   :type 'boolean)
   1987 
   1988 (defcustom org-after-todo-state-change-hook nil
   1989   "Hook which is run after the state of a TODO item was changed.
   1990 The new state (a string with a TODO keyword, or nil) is available in the
   1991 Lisp variable `org-state'."
   1992   :group 'org-todo
   1993   :type 'hook)
   1994 
   1995 (defcustom org-after-note-stored-hook nil
   1996   "Hook triggered after a note is stored.
   1997 The point is at the stored note when the hook is executed."
   1998   :group 'org-progress
   1999   :type 'hook
   2000   :package-version '(Org . "9.7"))
   2001 
   2002 (defvar org-blocker-hook nil
   2003   "Hook for functions that are allowed to block a state change.
   2004 
   2005 Functions in this hook should not modify the buffer.
   2006 Each function gets as its single argument a property list,
   2007 see `org-trigger-hook' for more information about this list.
   2008 
   2009 If any of the functions in this hook returns nil, the state change
   2010 is blocked.")
   2011 
   2012 (defvar org-trigger-hook nil
   2013   "Hook for functions that are triggered by a state change.
   2014 
   2015 Each function gets as its single argument a property list with at
   2016 least the following elements:
   2017 
   2018  (:type type-of-change :position pos-at-entry-start
   2019   :from old-state :to new-state)
   2020 
   2021 Depending on the type, more properties may be present.
   2022 
   2023 This mechanism is currently implemented for:
   2024 
   2025 TODO state changes
   2026 ------------------
   2027 :type  todo-state-change
   2028 :from  previous state (keyword as a string), or nil, or a symbol
   2029        `todo' or `done', to indicate the general type of state.
   2030 :to    new state, like in :from")
   2031 
   2032 (defcustom org-enforce-todo-dependencies nil
   2033   "Non-nil means undone TODO entries will block switching the parent to DONE.
   2034 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
   2035 be blocked if any prior sibling is not yet done.
   2036 Finally, if the parent is blocked because of ordered siblings of its own,
   2037 the child will also be blocked."
   2038   :set (lambda (var val)
   2039 	 (set-default-toplevel-value var val)
   2040 	 (if val
   2041 	     (add-hook 'org-blocker-hook
   2042 		       'org-block-todo-from-children-or-siblings-or-parent)
   2043 	   (remove-hook 'org-blocker-hook
   2044 			'org-block-todo-from-children-or-siblings-or-parent)))
   2045   :group 'org-todo
   2046   :type 'boolean)
   2047 
   2048 (defcustom org-enforce-todo-checkbox-dependencies nil
   2049   "Non-nil means unchecked boxes will block switching the parent to DONE.
   2050 When this is nil, checkboxes have no influence on switching TODO states.
   2051 When non-nil, you first need to check off all check boxes before the TODO
   2052 entry can be switched to DONE.
   2053 This variable needs to be set before org.el is loaded, and you need to
   2054 restart Emacs after a change to make the change effective.  The only way
   2055 to change it while Emacs is running is through the customize interface."
   2056   :set (lambda (var val)
   2057 	 (set-default-toplevel-value var val)
   2058 	 (if val
   2059 	     (add-hook 'org-blocker-hook
   2060 		       'org-block-todo-from-checkboxes)
   2061 	   (remove-hook 'org-blocker-hook
   2062 			'org-block-todo-from-checkboxes)))
   2063   :group 'org-todo
   2064   :type 'boolean)
   2065 
   2066 (defcustom org-treat-insert-todo-heading-as-state-change nil
   2067   "Non-nil means inserting a TODO heading is treated as state change.
   2068 So when the command `\\[org-insert-todo-heading]' is used, state change
   2069 logging will apply if appropriate.  When nil, the new TODO item will
   2070 be inserted directly, and no logging will take place."
   2071   :group 'org-todo
   2072   :type 'boolean)
   2073 
   2074 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
   2075   "Non-nil means switching TODO states with S-cursor counts as state change.
   2076 This is the default behavior.  However, setting this to nil allows a
   2077 convenient way to select a TODO state and bypass any logging associated
   2078 with that."
   2079   :group 'org-todo
   2080   :type 'boolean)
   2081 
   2082 (defcustom org-todo-state-tags-triggers nil
   2083   "Tag changes that should be triggered by TODO state changes.
   2084 This is a list.  Each entry is
   2085 
   2086   (state-change (tag . flag) .......)
   2087 
   2088 State-change can be a string with a state, and empty string to indicate the
   2089 state that has no TODO keyword, or it can be one of the symbols `todo'
   2090 or `done', meaning any not-done or done state, respectively."
   2091   :group 'org-todo
   2092   :group 'org-tags
   2093   :type '(repeat
   2094 	  (cons (choice :tag "When changing to"
   2095 			(const :tag "Not-done state" todo)
   2096 			(const :tag "Done state" done)
   2097 			(string :tag "State"))
   2098 		(repeat
   2099 		 (cons :tag "Tag action"
   2100 		       (string :tag "Tag")
   2101 		       (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
   2102 
   2103 (defcustom org-log-done nil
   2104   "Information to record when a task moves to the DONE state.
   2105 
   2106 Possible values are:
   2107 
   2108 nil     Don't add anything, just change the keyword
   2109 time    Add a time stamp to the task
   2110 note    Prompt for a note and add it with template `org-log-note-headings'
   2111 
   2112 This option can also be set with on a per-file-basis with
   2113 
   2114    #+STARTUP: nologdone
   2115    #+STARTUP: logdone
   2116    #+STARTUP: lognotedone
   2117 
   2118 You can have local logging settings for a subtree by setting the LOGGING
   2119 property to one or more of these keywords."
   2120   :group 'org-todo
   2121   :group 'org-progress
   2122   :type '(choice
   2123 	  (const :tag "No logging" nil)
   2124 	  (const :tag "Record CLOSED timestamp" time)
   2125 	  (const :tag "Record CLOSED timestamp with note." note)))
   2126 
   2127 ;; Normalize old uses of org-log-done.
   2128 (cond
   2129  ((eq org-log-done t) (setq org-log-done 'time))
   2130  ((and (listp org-log-done) (memq 'done org-log-done))
   2131   (setq org-log-done 'note)))
   2132 
   2133 (defcustom org-log-reschedule nil
   2134   "Information to record when the scheduling date of a task is modified.
   2135 
   2136 Possible values are:
   2137 
   2138 nil     Don't add anything, just change the date
   2139 time    Add a time stamp to the task
   2140 note    Prompt for a note and add it with template `org-log-note-headings'
   2141 
   2142 This option can also be set with on a per-file-basis with
   2143 
   2144    #+STARTUP: nologreschedule
   2145    #+STARTUP: logreschedule
   2146    #+STARTUP: lognotereschedule
   2147 
   2148 You can have local logging settings for a subtree by setting the LOGGING
   2149 property to one or more of these keywords.
   2150 
   2151 This variable has an effect when calling `org-schedule' or
   2152 `org-agenda-schedule' only."
   2153   :group 'org-todo
   2154   :group 'org-progress
   2155   :type '(choice
   2156 	  (const :tag "No logging" nil)
   2157 	  (const :tag "Record timestamp" time)
   2158 	  (const :tag "Record timestamp with note" note)))
   2159 
   2160 (defcustom org-log-redeadline nil
   2161   "Information to record when the deadline date of a task is modified.
   2162 
   2163 Possible values are:
   2164 
   2165 nil     Don't add anything, just change the date
   2166 time    Add a time stamp to the task
   2167 note    Prompt for a note and add it with template `org-log-note-headings'
   2168 
   2169 This option can also be set with on a per-file-basis with
   2170 
   2171    #+STARTUP: nologredeadline
   2172    #+STARTUP: logredeadline
   2173    #+STARTUP: lognoteredeadline
   2174 
   2175 You can have local logging settings for a subtree by setting the LOGGING
   2176 property to one or more of these keywords.
   2177 
   2178 This variable has an effect when calling `org-deadline' or
   2179 `org-agenda-deadline' only."
   2180   :group 'org-todo
   2181   :group 'org-progress
   2182   :type '(choice
   2183 	  (const :tag "No logging" nil)
   2184 	  (const :tag "Record timestamp" time)
   2185 	  (const :tag "Record timestamp with note." note)))
   2186 
   2187 (defcustom org-log-note-clock-out nil
   2188   "Non-nil means record a note when clocking out of an item.
   2189 This can also be configured on a per-file basis by adding one of
   2190 the following lines anywhere in the buffer:
   2191 
   2192    #+STARTUP: lognoteclock-out
   2193    #+STARTUP: nolognoteclock-out"
   2194   :group 'org-todo
   2195   :group 'org-progress
   2196   :type 'boolean)
   2197 
   2198 (defcustom org-log-done-with-time t
   2199   "Non-nil means the CLOSED time stamp will contain date and time.
   2200 When nil, only the date will be recorded."
   2201   :group 'org-progress
   2202   :type 'boolean)
   2203 
   2204 (defcustom org-log-note-headings
   2205   '((done .  "CLOSING NOTE %t")
   2206     (state . "State %-12s from %-12S %t")
   2207     (note .  "Note taken on %t")
   2208     (reschedule .  "Rescheduled from %S on %t")
   2209     (delschedule .  "Not scheduled, was %S on %t")
   2210     (redeadline .  "New deadline from %S on %t")
   2211     (deldeadline .  "Removed deadline, was %S on %t")
   2212     (refile . "Refiled on %t")
   2213     (clock-out . ""))
   2214   "Headings for notes added to entries.
   2215 
   2216 The value is an alist, with the car being a symbol indicating the
   2217 note context, and the cdr is the heading to be used.  The heading
   2218 may also be the empty string.  The following placeholders can be
   2219 used:
   2220 
   2221   %t  a time stamp.
   2222   %T  an active time stamp instead the default inactive one
   2223   %d  a short-format time stamp.
   2224   %D  an active short-format time stamp.
   2225   %s  the new TODO state or time stamp (inactive), in double quotes.
   2226   %S  the old TODO state or time stamp (inactive), in double quotes.
   2227   %u  the user name.
   2228   %U  full user name.
   2229 
   2230 In fact, it is not a good idea to change the `state' entry,
   2231 because Agenda Log mode depends on the format of these entries."
   2232   :group  'org-todo
   2233   :group  'org-progress
   2234   :type '(list :greedy t
   2235 	       (cons (const :tag "Heading when closing an item" done) string)
   2236 	       (cons (const :tag
   2237 			    "Heading when changing todo state (todo sequence only)"
   2238 			    state) string)
   2239 	       (cons (const :tag "Heading when just taking a note" note) string)
   2240 	       (cons (const :tag "Heading when rescheduling" reschedule) string)
   2241 	       (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
   2242 	       (cons (const :tag "Heading when changing deadline"  redeadline) string)
   2243 	       (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
   2244 	       (cons (const :tag "Heading when refiling" refile) string)
   2245 	       (cons (const :tag "Heading when clocking out" clock-out) string)))
   2246 
   2247 (unless (assq 'note org-log-note-headings)
   2248   (push '(note . "%t") org-log-note-headings))
   2249 
   2250 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
   2251 
   2252 (defcustom org-log-into-drawer nil
   2253   "Non-nil means insert state change notes and time stamps into a drawer.
   2254 When nil, state changes notes will be inserted after the headline and
   2255 any scheduling and clock lines, but not inside a drawer.
   2256 
   2257 The value of this variable should be the name of the drawer to use.
   2258 LOGBOOK is proposed as the default drawer for this purpose, you can
   2259 also set this to a string to define the drawer of your choice.
   2260 
   2261 A value of t is also allowed, representing \"LOGBOOK\".
   2262 
   2263 A value of t or nil can also be set with on a per-file-basis with
   2264 
   2265    #+STARTUP: logdrawer
   2266    #+STARTUP: nologdrawer
   2267 
   2268 If this variable is set, `org-log-state-notes-insert-after-drawers'
   2269 will be ignored.
   2270 
   2271 You can set the property LOG_INTO_DRAWER to overrule this setting for
   2272 a subtree.
   2273 
   2274 Do not check directly this variable in a Lisp program.  Call
   2275 function `org-log-into-drawer' instead."
   2276   :group 'org-todo
   2277   :group 'org-progress
   2278   :type '(choice
   2279 	  (const :tag "Not into a drawer" nil)
   2280 	  (const :tag "LOGBOOK" t)
   2281 	  (string :tag "Other")))
   2282 
   2283 (defun org-log-into-drawer ()
   2284   "Name of the log drawer, as a string, or nil.
   2285 This is the value of `org-log-into-drawer'.  However, if the
   2286 current entry has or inherits a LOG_INTO_DRAWER property, it will
   2287 be used instead of the default value."
   2288   (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
   2289     (cond ((equal p "nil") nil)
   2290 	  ((equal p "t") "LOGBOOK")
   2291 	  ((stringp p) p)
   2292 	  (p "LOGBOOK")
   2293 	  ((stringp org-log-into-drawer) org-log-into-drawer)
   2294 	  (org-log-into-drawer "LOGBOOK"))))
   2295 
   2296 (defcustom org-log-state-notes-insert-after-drawers nil
   2297   "Non-nil means insert state change notes after any drawers in entry.
   2298 Only the drawers that *immediately* follow the headline and the
   2299 deadline/scheduled line are skipped.
   2300 When nil, insert notes right after the heading and perhaps the line
   2301 with deadline/scheduling if present.
   2302 
   2303 This variable will have no effect if `org-log-into-drawer' is
   2304 set."
   2305   :group 'org-todo
   2306   :group 'org-progress
   2307   :type 'boolean)
   2308 
   2309 (defcustom org-log-states-order-reversed t
   2310   "Non-nil means the latest state note will be directly after heading.
   2311 When nil, the state change notes will be ordered according to time.
   2312 
   2313 This option can also be set with on a per-file-basis with
   2314 
   2315    #+STARTUP: logstatesreversed
   2316    #+STARTUP: nologstatesreversed"
   2317   :group 'org-todo
   2318   :group 'org-progress
   2319   :type 'boolean)
   2320 
   2321 (defcustom org-todo-repeat-to-state nil
   2322   "The TODO state to which a repeater should return the repeating task.
   2323 By default this is the first task of a TODO sequence or the
   2324 previous state of a TYPE_TODO set.  But you can specify to use
   2325 the previous state in a TODO sequence or a string.
   2326 
   2327 Alternatively, you can set the :REPEAT_TO_STATE: property of the
   2328 entry, which has precedence over this option."
   2329   :group 'org-todo
   2330   :version "24.1"
   2331   :type '(choice (const :tag "Use the previous TODO state" t)
   2332 		 (const :tag "Use the head of the TODO sequence" nil)
   2333 		 (string :tag "Use a specific TODO state")))
   2334 
   2335 (defcustom org-log-repeat 'time
   2336   "Non-nil means record moving through the DONE state when triggering repeat.
   2337 An auto-repeating task is immediately switched back to TODO when
   2338 marked DONE.  If you are not logging state changes (by adding \"@\"
   2339 or \"!\" to the TODO keyword definition), or set `org-log-done' to
   2340 record a closing note, there will be no record of the task moving
   2341 through DONE.  This variable forces taking a note anyway.
   2342 
   2343 nil     Don't force a record
   2344 time    Record a time stamp
   2345 note    Prompt for a note and add it with template `org-log-note-headings'
   2346 
   2347 This option can also be set with on a per-file-basis with
   2348 
   2349    #+STARTUP: nologrepeat
   2350    #+STARTUP: logrepeat
   2351    #+STARTUP: lognoterepeat
   2352 
   2353 You can have local logging settings for a subtree by setting the LOGGING
   2354 property to one or more of these keywords."
   2355   :group 'org-todo
   2356   :group 'org-progress
   2357   :type '(choice
   2358 	  (const :tag "Don't force a record" nil)
   2359 	  (const :tag "Force recording the DONE state" time)
   2360 	  (const :tag "Force recording a note with the DONE state" note)))
   2361 
   2362 (defcustom org-todo-repeat-hook nil
   2363   "Hook that is run after a task has been repeated."
   2364   :package-version '(Org . "9.2")
   2365   :group 'org-todo
   2366   :type 'hook)
   2367 
   2368 (defgroup org-priorities nil
   2369   "Priorities in Org mode."
   2370   :tag "Org Priorities"
   2371   :group 'org-todo)
   2372 
   2373 (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
   2374 (defcustom org-priority-enable-commands t
   2375   "Non-nil means priority commands are active.
   2376 When nil, these commands will be disabled, so that you never accidentally
   2377 set a priority."
   2378   :group 'org-priorities
   2379   :type 'boolean)
   2380 
   2381 (defvaralias 'org-highest-priority 'org-priority-highest)
   2382 
   2383 (defcustom org-priority-highest ?A
   2384   "The highest priority of TODO items.
   2385 
   2386 A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
   2387 
   2388 The default is the character ?A, which is 65 as a numeric value.
   2389 
   2390 If you set `org-priority-highest' to a numeric value inferior to
   2391 65, Org assumes you want to use digits for the priority cookie.
   2392 If you set it to >=65, Org assumes you want to use alphabetical
   2393 characters.
   2394 
   2395 In both cases, the value of `org-priority-highest' must be
   2396 smaller than `org-priority-lowest': for example, if \"A\" is the
   2397 highest priority, it is smaller than the lowest \"C\" priority:
   2398 65 < 67."
   2399   :group 'org-priorities
   2400   :type '(choice
   2401 	  (character :tag "Character")
   2402 	  (integer :tag "Integer (< 65)")))
   2403 
   2404 (defvaralias 'org-lowest-priority 'org-priority-lowest)
   2405 (defcustom org-priority-lowest ?C
   2406   "The lowest priority of TODO items.
   2407 
   2408 A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
   2409 
   2410 The default is the character ?C, which is 67 as a numeric value.
   2411 
   2412 If you set `org-priority-lowest' to a numeric value inferior to
   2413 65, Org assumes you want to use digits for the priority cookie.
   2414 If you set it to >=65, Org assumes you want to use alphabetical
   2415 characters.
   2416 
   2417 In both cases, the value of `org-priority-lowest' must be greater
   2418 than `org-priority-highest': for example, if \"C\" is the lowest
   2419 priority, it is greater than the highest \"A\" priority: 67 >
   2420 65."
   2421   :group 'org-priorities
   2422   :type '(choice
   2423 	  (character :tag "Character")
   2424 	  (integer :tag "Integer (< 65)")))
   2425 
   2426 (defvaralias 'org-default-priority 'org-priority-default)
   2427 (defcustom org-priority-default ?B
   2428   "The default priority of TODO items.
   2429 This is the priority an item gets if no explicit priority is given.
   2430 When starting to cycle on an empty priority the first step in the cycle
   2431 depends on `org-priority-start-cycle-with-default'.  The resulting first
   2432 step priority must not exceed the range from `org-priority-highest' to
   2433 `org-priority-lowest' which means that `org-priority-default' has to be
   2434 in this range exclusive or inclusive to the range boundaries.  Else the
   2435 first step refuses to set the default and the second will fall back on
   2436 \(depending on the command used) the highest or lowest priority."
   2437   :group 'org-priorities
   2438   :type '(choice
   2439 	  (character :tag "Character")
   2440 	  (integer :tag "Integer (< 65)")))
   2441 
   2442 (defcustom org-priority-start-cycle-with-default t
   2443   "Non-nil means start with default priority when starting to cycle.
   2444 When this is nil, the first step in the cycle will be (depending on the
   2445 command used) one higher or lower than the default priority.
   2446 See also `org-priority-default'."
   2447   :group 'org-priorities
   2448   :type 'boolean)
   2449 
   2450 (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
   2451 (defcustom org-priority-get-priority-function nil
   2452   "Function to extract the priority from a string.
   2453 The string is normally the headline.  If this is nil, Org
   2454 computes the priority from the priority cookie like [#A] in the
   2455 headline.  It returns an integer, increasing by 1000 for each
   2456 priority level.
   2457 
   2458 The user can set a different function here, which should take a
   2459 string as an argument and return the numeric priority."
   2460   :group 'org-priorities
   2461   :version "24.1"
   2462   :type '(choice
   2463 	  (const nil)
   2464 	  (function)))
   2465 
   2466 (defgroup org-time nil
   2467   "Options concerning time stamps and deadlines in Org mode."
   2468   :tag "Org Time"
   2469   :group 'org)
   2470 
   2471 (defvaralias 'org-time-stamp-rounding-minutes 'org-timestamp-rounding-minutes)
   2472 (defcustom org-timestamp-rounding-minutes '(0 5)
   2473   "Number of minutes to round time stamps to.
   2474 \\<org-mode-map>\
   2475 These are two values, the first applies when first creating a time stamp.
   2476 The second applies when changing it with the commands `S-up' and `S-down'.
   2477 When changing the time stamp, this means that it will change in steps
   2478 of N minutes, as given by the second value.
   2479 
   2480 When a setting is 0 or 1, insert the time unmodified.  Useful rounding
   2481 numbers should be factors of 60, so for example 5, 10, 15.
   2482 
   2483 When this is larger than 1, you can still force an exact time stamp by using
   2484 a double prefix argument to a time stamp command like \
   2485 `\\[org-timestamp]' or `\\[org-timestamp-inactive],
   2486 and by using a prefix arg to `S-up/down' to specify the exact number
   2487 of minutes to shift."
   2488   :group 'org-time
   2489   :get (lambda (var) ; Make sure both elements are there
   2490 	 (if (integerp (default-value var))
   2491 	     (list (default-value var) 5)
   2492 	   (default-value var)))
   2493   :type '(list
   2494 	  (integer :tag "when inserting times")
   2495 	  (integer :tag "when modifying times")))
   2496 
   2497 ;; Normalize old customizations of this variable.
   2498 (when (integerp org-timestamp-rounding-minutes)
   2499   (setq org-timestamp-rounding-minutes
   2500 	(list org-timestamp-rounding-minutes
   2501 	      org-timestamp-rounding-minutes)))
   2502 
   2503 (defcustom org-display-custom-times nil
   2504   "Non-nil means overlay custom formats over all time stamps.
   2505 The formats are defined through the variable `org-timestamp-custom-formats'.
   2506 To turn this on on a per-file basis, insert anywhere in the file:
   2507    #+STARTUP: customtime"
   2508   :group 'org-time
   2509   :type 'sexp)
   2510 (make-variable-buffer-local 'org-display-custom-times)
   2511 
   2512 (defvaralias 'org-time-stamp-custom-formats 'org-timestamp-custom-formats)
   2513 (defcustom org-timestamp-custom-formats
   2514   '("%m/%d/%y %a" . "%m/%d/%y %a %H:%M") ; american
   2515   "Custom formats for time stamps.
   2516 
   2517 See `format-time-string' for the syntax.
   2518 
   2519 These are overlaid over the default ISO format if the variable
   2520 `org-display-custom-times' is set.  Time like %H:%M should be at the
   2521 end of the second format.  The custom formats are also honored by export
   2522 commands, if custom time display is turned on at the time of export.
   2523 
   2524 This variable also affects how timestamps are exported.
   2525 
   2526 Leading \"<\" and trailing \">\" pair will be stripped from the format
   2527 strings."
   2528   :group 'org-time
   2529   :package-version '(Org . "9.6")
   2530   :type '(cons string string))
   2531 
   2532 (defun org-time-stamp-format (&optional with-time inactive custom)
   2533   "Get timestamp format for a time string.
   2534 
   2535 The format is based on `org-timestamp-formats' (if CUSTOM is nil) or or
   2536 `org-timestamp-custom-formats' (if CUSTOM if non-nil).
   2537 
   2538 When optional argument WITH-TIME is non-nil, the timestamp will contain
   2539 time.
   2540 
   2541 When optional argument INACTIVE is nil, format active timestamp.
   2542 When `no-brackets', strip timestamp brackets.
   2543 Otherwise, format inactive timestamp."
   2544   (let ((format (funcall
   2545                  (if with-time #'cdr #'car)
   2546                  (if custom
   2547                      org-timestamp-custom-formats
   2548                    org-timestamp-formats))))
   2549     ;; Strip brackets, if any.
   2550     (when (or (and (string-prefix-p "<" format)
   2551                    (string-suffix-p ">" format))
   2552               (and (string-prefix-p "[" format)
   2553                    (string-suffix-p "]" format)))
   2554       (setq format (substring format 1 -1)))
   2555     (pcase inactive
   2556       (`no-brackets format)
   2557       (`nil (concat "<" format ">"))
   2558       (_ (concat "[" format "]")))))
   2559 
   2560 (defcustom org-deadline-warning-days 14
   2561   "Number of days before expiration during which a deadline becomes active.
   2562 This variable governs the display in sparse trees and in the agenda.
   2563 When 0 or negative, it means use this number (the absolute value of it)
   2564 even if a deadline has a different individual lead time specified.
   2565 
   2566 Custom commands can set this variable in the options section."
   2567   :group 'org-time
   2568   :group 'org-agenda-daily/weekly
   2569   :type 'integer)
   2570 
   2571 (defcustom org-scheduled-delay-days 0
   2572   "Number of days before a scheduled item becomes active.
   2573 This variable governs the display in sparse trees and in the agenda.
   2574 The default value (i.e. 0) means: don't delay scheduled item.
   2575 When negative, it means use this number (the absolute value of it)
   2576 even if a scheduled item has a different individual delay time
   2577 specified.
   2578 
   2579 Custom commands can set this variable in the options section."
   2580   :group 'org-time
   2581   :group 'org-agenda-daily/weekly
   2582   :version "24.4"
   2583   :package-version '(Org . "8.0")
   2584   :type 'integer)
   2585 
   2586 (defcustom org-read-date-prefer-future t
   2587   "Non-nil means assume future for incomplete date input from user.
   2588 This affects the following situations:
   2589 1. The user gives a month but not a year.
   2590    For example, if it is April and you enter \"feb 2\", this will be read
   2591    as Feb 2, *next* year.  \"May 5\", however, will be this year.
   2592 2. The user gives a day, but no month.
   2593    For example, if today is the 15th, and you enter \"3\", Org will read
   2594    this as the third of *next* month.  However, if you enter \"17\",
   2595    it will be considered as *this* month.
   2596 
   2597 If you set this variable to the symbol `time', then also the following
   2598 will work:
   2599 
   2600 3. If the user gives a time.
   2601    If the time is before now, it will be interpreted as tomorrow.
   2602 
   2603 Currently none of this works for ISO week specifications.
   2604 
   2605 When this option is nil, the current day, month and year will always be
   2606 used as defaults.
   2607 
   2608 See also `org-agenda-jump-prefer-future'."
   2609   :group 'org-time
   2610   :type '(choice
   2611 	  (const :tag "Never" nil)
   2612 	  (const :tag "Check month and day" t)
   2613 	  (const :tag "Check month, day, and time" time)))
   2614 
   2615 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
   2616   "Should the agenda jump command prefer the future for incomplete dates?
   2617 The default is to do the same as configured in `org-read-date-prefer-future'.
   2618 But you can also set a deviating value here.
   2619 This may t or nil, or the symbol `org-read-date-prefer-future'."
   2620   :group 'org-agenda
   2621   :group 'org-time
   2622   :version "24.1"
   2623   :type '(choice
   2624 	  (const :tag "Use org-read-date-prefer-future"
   2625 		 org-read-date-prefer-future)
   2626 	  (const :tag "Never" nil)
   2627 	  (const :tag "Always" t)))
   2628 
   2629 (defcustom org-read-date-force-compatible-dates t
   2630   "Should date/time prompt force dates that are guaranteed to work in Emacs?
   2631 
   2632 Depending on the system Emacs is running on, certain dates cannot
   2633 be represented with the type used internally to represent time.
   2634 Dates between 1970-1-1 and 2038-1-1 can always be represented
   2635 correctly.  Some systems allow for earlier dates, some for later,
   2636 some for both.  One way to find out is to insert any date into an
   2637 Org buffer, putting the cursor on the year and hitting S-up and
   2638 S-down to test the range.
   2639 
   2640 When this variable is set to t, the date/time prompt will not let
   2641 you specify dates outside the 1970-2037 range, so it is certain that
   2642 these dates will work in whatever version of Emacs you are
   2643 running, and also that you can move a file from one Emacs implementation
   2644 to another.  Whenever Org is forcing the year for you, it will display
   2645 a message and beep.
   2646 
   2647 When this variable is nil, Org will check if the date is
   2648 representable in the specific Emacs implementation you are using.
   2649 If not, it will force a year, usually the current year, and beep
   2650 to remind you.  Currently this setting is not recommended because
   2651 the likelihood that you will open your Org files in an Emacs that
   2652 has limited date range is not negligible.
   2653 
   2654 A workaround for this problem is to use diary sexp dates for time
   2655 stamps outside of this range."
   2656   :group 'org-time
   2657   :version "24.1"
   2658   :type 'boolean)
   2659 
   2660 (defcustom org-read-date-display-live t
   2661   "Non-nil means display current interpretation of date prompt live.
   2662 This display will be in an overlay, in the minibuffer.  Note that
   2663 live display is only active when `org-read-date-popup-calendar'
   2664 is non-nil."
   2665   :group 'org-time
   2666   :type 'boolean)
   2667 
   2668 (defvaralias 'org-popup-calendar-for-date-prompt
   2669   'org-read-date-popup-calendar)
   2670 
   2671 (defcustom org-read-date-popup-calendar t
   2672   "Non-nil means pop up a calendar when prompting for a date.
   2673 In the calendar, the date can be selected with \\`mouse-1'.  However, the
   2674 minibuffer will also be active, and you can simply enter the date as well.
   2675 When nil, only the minibuffer will be available."
   2676   :group 'org-time
   2677   :type 'boolean)
   2678 
   2679 (defcustom org-extend-today-until 0
   2680   "The hour when your day really ends.  Must be an integer.
   2681 This has influence for the following applications:
   2682 - When switching the agenda to \"today\".  If it is still earlier than
   2683   the time given here, the day recognized as TODAY is actually yesterday.
   2684 - When a date is read from the user and it is still before the time given
   2685   here, the current date and time will be assumed to be yesterday, 23:59.
   2686   Also, timestamps inserted in capture templates follow this rule.
   2687 
   2688 IMPORTANT:  This is a feature whose implementation is and likely will
   2689 remain incomplete.  Really, it is only here because past midnight seems to
   2690 be the favorite working time of John Wiegley :-)"
   2691   :group 'org-time
   2692   :type 'integer)
   2693 
   2694 (defcustom org-use-effective-time nil
   2695   "If non-nil, consider `org-extend-today-until' when creating timestamps.
   2696 For example, if `org-extend-today-until' is 8, and it's 4am, then the
   2697 \"effective time\" of any timestamps between midnight and 8am will be
   2698 23:59 of the previous day."
   2699   :group 'org-time
   2700   :version "24.1"
   2701   :type 'boolean)
   2702 
   2703 (defcustom org-use-last-clock-out-time-as-effective-time nil
   2704   "When non-nil, use the last clock out time for `org-todo'.
   2705 Note that this option has precedence over the combined use of
   2706 `org-use-effective-time' and `org-extend-today-until'."
   2707   :group 'org-time
   2708   :version "24.4"
   2709   :package-version '(Org . "8.0")
   2710   :type 'boolean)
   2711 
   2712 (defcustom org-edit-timestamp-down-means-later nil
   2713   "Non-nil means S-down will increase the time in a time stamp.
   2714 When nil, S-up will increase."
   2715   :group 'org-time
   2716   :type 'boolean)
   2717 
   2718 (defcustom org-calendar-follow-timestamp-change t
   2719   "Non-nil means make the calendar window follow timestamp changes.
   2720 When a timestamp is modified and the calendar window is visible, it will be
   2721 moved to the new date."
   2722   :group 'org-time
   2723   :type 'boolean)
   2724 
   2725 (defgroup org-tags nil
   2726   "Options concerning tags in Org mode."
   2727   :tag "Org Tags"
   2728   :group 'org)
   2729 
   2730 (defcustom org-tag-alist nil
   2731   "Default tags available in Org files.
   2732 
   2733 The value of this variable is an alist.  Associations either:
   2734 
   2735   (TAG)
   2736   (TAG . SELECT)
   2737   (SPECIAL)
   2738 
   2739 where TAG is a tag as a string, SELECT is character, used to
   2740 select that tag through the fast tag selection interface, and
   2741 SPECIAL is one of the following keywords: `:startgroup',
   2742 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
   2743 `:newline'.  These keywords are used to define a hierarchy of
   2744 tags.  See manual for details.
   2745 
   2746 When this variable is nil, Org mode bases tag input on what is
   2747 already in the buffer.  The value can be overridden locally by
   2748 using a TAGS keyword, e.g.,
   2749 
   2750   #+TAGS: tag1 tag2
   2751 
   2752 See also `org-tag-persistent-alist' to sidestep this behavior."
   2753   :group 'org-tags
   2754   :type '(repeat
   2755 	  (choice
   2756 	   (cons :tag "Tag with key"
   2757 		 (string    :tag "Tag name")
   2758 		 (character :tag "Access char"))
   2759 	   (list :tag "Tag" (string :tag "Tag name"))
   2760 	   (const :tag "Start radio group" (:startgroup))
   2761 	   (const :tag "Start tag group, non distinct" (:startgrouptag))
   2762 	   (const :tag "Group tags delimiter" (:grouptags))
   2763 	   (const :tag "End radio group" (:endgroup))
   2764 	   (const :tag "End tag group, non distinct" (:endgrouptag))
   2765 	   (const :tag "New line" (:newline)))))
   2766 
   2767 (defcustom org-tag-persistent-alist nil
   2768   "Tags always available in Org files.
   2769 
   2770 The value of this variable is an alist.  Associations either:
   2771 
   2772   (TAG)
   2773   (TAG . SELECT)
   2774   (SPECIAL)
   2775 
   2776 where TAG is a tag as a string, SELECT is a character, used to
   2777 select that tag through the fast tag selection interface, and
   2778 SPECIAL is one of the following keywords: `:startgroup',
   2779 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
   2780 `:newline'.  These keywords are used to define a hierarchy of
   2781 tags.  See manual for details.
   2782 
   2783 Unlike to `org-tag-alist', tags defined in this variable do not
   2784 depend on a local TAGS keyword.  Instead, to disable these tags
   2785 on a per-file basis, insert anywhere in the file:
   2786 
   2787   #+STARTUP: noptag"
   2788   :group 'org-tags
   2789   :type '(repeat
   2790 	  (choice
   2791 	   (cons :tag "Tag with key"
   2792 		 (string    :tag "Tag name")
   2793 		 (character :tag "Access char"))
   2794 	   (list :tag "Tag" (string :tag "Tag name"))
   2795 	   (const :tag "Start radio group" (:startgroup))
   2796 	   (const :tag "Start tag group, non distinct" (:startgrouptag))
   2797 	   (const :tag "Group tags delimiter" (:grouptags))
   2798 	   (const :tag "End radio group" (:endgroup))
   2799 	   (const :tag "End tag group, non distinct" (:endgrouptag))
   2800 	   (const :tag "New line" (:newline)))))
   2801 
   2802 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
   2803   "If non-nil, always offer completion for all tags of all agenda files.
   2804 
   2805 Setting this variable locally allows for dynamic generation of tag
   2806 completions in capture buffers.
   2807 
   2808   (add-hook \\='org-capture-mode-hook
   2809             (lambda ()
   2810               (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
   2811   :group 'org-tags
   2812   :version "24.1"
   2813   :type 'boolean)
   2814 
   2815 (defvar org-file-tags nil
   2816   "List of tags that can be inherited by all entries in the file.
   2817 The tags will be inherited if the variable `org-use-tag-inheritance'
   2818 says they should be.
   2819 This variable is populated from #+FILETAGS lines.")
   2820 
   2821 (defcustom org-use-fast-tag-selection 'auto
   2822   "Non-nil means use fast tag selection scheme.
   2823 This is a special interface to select and deselect tags with single keys.
   2824 When nil, fast selection is never used.
   2825 When the symbol `auto', fast selection is used if and only if selection
   2826 characters for tags have been configured, either through the variable
   2827 `org-tag-alist' or through a #+TAGS line in the buffer.
   2828 When t, fast selection is always used and selection keys are assigned
   2829 automatically if necessary."
   2830   :group 'org-tags
   2831   :type '(choice
   2832 	  (const :tag "Always" t)
   2833 	  (const :tag "Never" nil)
   2834 	  (const :tag "When selection characters are configured" auto)))
   2835 
   2836 (defcustom org-fast-tag-selection-single-key nil
   2837   "Non-nil means fast tag selection exits after first change.
   2838 When nil, you have to press RET to exit it.
   2839 During fast tag selection, you can toggle this flag with `C-c'.
   2840 This variable can also have the value `expert'.  In this case, the window
   2841 displaying the tags menu is not even shown, until you press `C-c' again."
   2842   :group 'org-tags
   2843   :type '(choice
   2844 	  (const :tag "No" nil)
   2845 	  (const :tag "Yes" t)
   2846 	  (const :tag "Expert" expert)))
   2847 
   2848 (defvar org--fast-tag-selection-keys
   2849   (string-to-list "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~")
   2850   "List of chars to be used as bindings by `org-fast-tag-selection'.")
   2851 
   2852 (defcustom org-fast-tag-selection-maximum-tags (length org--fast-tag-selection-keys)
   2853   "Set the maximum tags number for fast tag selection.
   2854 This variable only affects tags without explicit key bindings outside
   2855 tag groups.  All the tags with user bindings and all the tags
   2856 corresponding to tag groups are always displayed.
   2857 
   2858 When the number of tags with bindings + tags inside tag groups is
   2859 smaller than `org-fast-tag-selection-maximum-tags', tags without
   2860 explicit bindings will be assigned a binding and displayed up to the
   2861 limit."
   2862   :package-version '(Org . "9.7")
   2863   :group 'org-tags
   2864   :type 'number
   2865   :safe #'numberp)
   2866 
   2867 (defvar org-fast-tag-selection-include-todo nil
   2868   "Non-nil means fast tags selection interface will also offer TODO states.
   2869 This is an undocumented feature, you should not rely on it.")
   2870 
   2871 (defcustom org-tags-column -77
   2872   "The column to which tags should be indented in a headline.
   2873 If this number is positive, it specifies the column.  If it is negative,
   2874 it means that the tags should be flushright to that column.  For example,
   2875 -80 works well for a normal 80 character screen.
   2876 When 0, place tags directly after headline text, with only one space in
   2877 between."
   2878   :group 'org-tags
   2879   :type 'integer)
   2880 
   2881 (defcustom org-auto-align-tags t
   2882   "Non-nil keeps tags aligned when modifying headlines.
   2883 Some operations (i.e. demoting) change the length of a headline and
   2884 therefore shift the tags around.  With this option turned on, after
   2885 each such operation the tags are again aligned to `org-tags-column'."
   2886   :group 'org-tags
   2887   :type 'boolean)
   2888 
   2889 (defcustom org-use-tag-inheritance t
   2890   "Non-nil means tags in levels apply also for sublevels.
   2891 When nil, only the tags directly given in a specific line apply there.
   2892 This may also be a list of tags that should be inherited, or a regexp that
   2893 matches tags that should be inherited.  Additional control is possible
   2894 with the variable  `org-tags-exclude-from-inheritance' which gives an
   2895 explicit list of tags to be excluded from inheritance, even if the value of
   2896 `org-use-tag-inheritance' would select it for inheritance.
   2897 
   2898 If this option is t, a match early-on in a tree can lead to a large
   2899 number of matches in the subtree when constructing the agenda or creating
   2900 a sparse tree.  If you only want to see the first match in a tree during
   2901 a search, check out the variable `org-tags-match-list-sublevels'."
   2902   :group 'org-tags
   2903   :type '(choice
   2904 	  (const :tag "Not" nil)
   2905 	  (const :tag "Always" t)
   2906 	  (repeat :tag "Specific tags" (string :tag "Tag"))
   2907 	  (regexp :tag "Tags matched by regexp")))
   2908 
   2909 (defcustom org-tags-exclude-from-inheritance nil
   2910   "List of tags that should never be inherited.
   2911 This is a way to exclude a few tags from inheritance.  For way to do
   2912 the opposite, to actively allow inheritance for selected tags,
   2913 see the variable `org-use-tag-inheritance'."
   2914   :group 'org-tags
   2915   :type '(repeat (string :tag "Tag")))
   2916 
   2917 (defun org-tag-inherit-p (tag)
   2918   "Check if TAG is one that should be inherited."
   2919   (cond
   2920    ((member tag org-tags-exclude-from-inheritance) nil)
   2921    ((eq org-use-tag-inheritance t) t)
   2922    ((not org-use-tag-inheritance) nil)
   2923    ((stringp org-use-tag-inheritance)
   2924     (string-match org-use-tag-inheritance tag))
   2925    ((listp org-use-tag-inheritance)
   2926     (member tag org-use-tag-inheritance))
   2927    (t (error "Invalid setting of `org-use-tag-inheritance'"))))
   2928 
   2929 (defcustom org-tags-match-list-sublevels t
   2930   "Non-nil means list also sublevels of headlines matching a search.
   2931 This variable applies to tags/property searches, and also to stuck
   2932 projects because this search is based on a tags match as well.
   2933 
   2934 When set to the symbol `indented', sublevels are indented with
   2935 leading dots.
   2936 
   2937 Because of tag inheritance (see variable `org-use-tag-inheritance'),
   2938 the sublevels of a headline matching a tag search often also match
   2939 the same search.  Listing all of them can create very long lists.
   2940 Setting this variable to nil causes subtrees of a match to be skipped.
   2941 
   2942 This variable is semi-obsolete and probably should always be true.  It
   2943 is better to limit inheritance to certain tags using the variables
   2944 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
   2945   :group 'org-tags
   2946   :type '(choice
   2947 	  (const :tag "No, don't list them" nil)
   2948 	  (const :tag "Yes, do list them" t)
   2949 	  (const :tag "List them, indented with leading dots" indented)))
   2950 
   2951 (defcustom org-tags-sort-function nil
   2952   "When set, tags are sorted using this function as a comparator."
   2953   :group 'org-tags
   2954   :type '(choice
   2955 	  (const :tag "No sorting" nil)
   2956 	  (const :tag "Alphabetical" org-string<)
   2957 	  (const :tag "Reverse alphabetical" org-string>)
   2958 	  (function :tag "Custom function" nil)))
   2959 
   2960 (defvar org-tags-history nil
   2961   "History of minibuffer reads for tags.")
   2962 (defvar org-last-tags-completion-table nil
   2963   "The last used completion table for tags.")
   2964 (defvar org-after-tags-change-hook nil
   2965   "Hook that is run after the tags in a line have changed.")
   2966 
   2967 (defgroup org-properties nil
   2968   "Options concerning properties in Org mode."
   2969   :tag "Org Properties"
   2970   :group 'org)
   2971 
   2972 (defcustom org-property-format "%-10s %s"
   2973   "How property key/value pairs should be formatted by `indent-line'.
   2974 When `indent-line' hits a property definition, it will format the line
   2975 according to this format, mainly to make sure that the values are
   2976 lined-up with respect to each other."
   2977   :group 'org-properties
   2978   :type 'string)
   2979 
   2980 (defcustom org-properties-postprocess-alist nil
   2981   "Alist of properties and functions to adjust inserted values.
   2982 Elements of this alist must be of the form
   2983 
   2984   ([string] [function])
   2985 
   2986 where [string] must be a property name and [function] must be a
   2987 lambda expression: this lambda expression must take one argument,
   2988 the value to adjust, and return the new value as a string.
   2989 
   2990 For example, this element will allow the property \"Remaining\"
   2991 to be updated wrt the relation between the \"Effort\" property
   2992 and the clock summary:
   2993 
   2994  ((\"Remaining\" (lambda(value)
   2995                    (let ((clocksum (org-clock-sum-current-item))
   2996                          (effort (org-duration-to-minutes
   2997                                    (org-entry-get (point) \"Effort\"))))
   2998                      (org-minutes-to-clocksum-string (- effort clocksum))))))"
   2999   :group 'org-properties
   3000   :version "24.1"
   3001   :type '(alist :key-type (string     :tag "Property")
   3002 		:value-type (function :tag "Function")))
   3003 
   3004 (defcustom org-use-property-inheritance nil
   3005   "Non-nil means properties apply also for sublevels.
   3006 
   3007 This setting is chiefly used during property searches.  Turning it on can
   3008 cause significant overhead when doing a search, which is why it is not
   3009 on by default.
   3010 
   3011 When nil, only the properties directly given in the current entry count.
   3012 When t, every property is inherited.  The value may also be a list of
   3013 properties that should have inheritance, or a regular expression matching
   3014 properties that should be inherited.
   3015 
   3016 However, note that some special properties use inheritance under special
   3017 circumstances (not in searches).  Examples are CATEGORY, ARCHIVE, COLUMNS,
   3018 and the properties ending in \"_ALL\" when they are used as descriptor
   3019 for valid values of a property.
   3020 
   3021 Note for programmers:
   3022 When querying an entry with `org-entry-get', you can control if inheritance
   3023 should be used.  By default, `org-entry-get' looks only at the local
   3024 properties.  You can request inheritance by setting the inherit argument
   3025 to t (to force inheritance) or to `selective' (to respect the setting
   3026 in this variable)."
   3027   :group 'org-properties
   3028   :type '(choice
   3029 	  (const :tag "Not" nil)
   3030 	  (const :tag "Always" t)
   3031 	  (repeat :tag "Specific properties" (string :tag "Property"))
   3032 	  (regexp :tag "Properties matched by regexp")))
   3033 
   3034 (defun org-property-inherit-p (property)
   3035   "Return a non-nil value if PROPERTY should be inherited."
   3036   (cond
   3037    ((eq org-use-property-inheritance t) t)
   3038    ((not org-use-property-inheritance) nil)
   3039    ((stringp org-use-property-inheritance)
   3040     (string-match org-use-property-inheritance property))
   3041    ((listp org-use-property-inheritance)
   3042     (member-ignore-case property org-use-property-inheritance))
   3043    (t (error "Invalid setting of `org-use-property-inheritance'"))))
   3044 
   3045 (defcustom org-property-separators nil
   3046   "An alist to control how properties are combined.
   3047 
   3048 The car of each item should be either a list of property names or
   3049 a regular expression, while the cdr should be the separator to
   3050 use when combining that property.
   3051 
   3052 If an alist item cannot be found that matches a given property, a
   3053 single space will be used as the separator."
   3054   :group 'org-properties
   3055   :package-version '(Org . "9.6")
   3056   :type '(alist :key-type (choice (repeat :tag "Properties" string)
   3057                                   (string :tag "Regular Expression"))
   3058                 :value-type (restricted-sexp :tag "Separator"
   3059                                              :match-alternatives (stringp)
   3060                                              :value " ")))
   3061 
   3062 (defun org--property-get-separator (property)
   3063   "Get the separator to use for combining PROPERTY."
   3064   (or
   3065    (catch 'separator
   3066      (dolist (spec org-property-separators)
   3067        (if (listp (car spec))
   3068            (if (member property (car spec))
   3069                (throw 'separator (cdr spec)))
   3070          (if (string-match-p (car spec) property)
   3071              (throw 'separator (cdr spec))))))
   3072    " "))
   3073 
   3074 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
   3075   "The default column format, if no other format has been defined.
   3076 This variable can be set on the per-file basis by inserting a line
   3077 
   3078 #+COLUMNS: %25ITEM ....."
   3079   :group 'org-properties
   3080   :type 'string)
   3081 
   3082 (defcustom org-columns-default-format-for-agenda nil
   3083   "The default column format in an agenda buffer.
   3084 This will be used for column view in the agenda unless a format has
   3085 been set by adding `org-overriding-columns-format' to the local
   3086 settings list of a custom agenda view.  When nil, the columns format
   3087 for the first item in the agenda list will be used, or as a fall-back,
   3088 `org-columns-default-format'."
   3089   :group 'org-properties
   3090   :type '(choice
   3091 	  (const :tag "No default" nil)
   3092 	  (string :tag "Format string")))
   3093 
   3094 (defcustom org-columns-ellipses ".."
   3095   "The ellipses to be used when a field in column view is truncated.
   3096 When this is the empty string, as many characters as possible are shown,
   3097 but then there will be no visual indication that the field has been truncated.
   3098 When this is a string of length N, the last N characters of a truncated
   3099 field are replaced by this string.  If the column is narrower than the
   3100 ellipses string, only part of the ellipses string will be shown."
   3101   :group 'org-properties
   3102   :type 'string)
   3103 
   3104 (defconst org-global-properties-fixed
   3105   '(("VISIBILITY_ALL" . "folded children content all")
   3106     ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
   3107   "List of property/value pairs that can be inherited by any entry.
   3108 
   3109 These are fixed values, for the preset properties.  The user variable
   3110 that can be used to add to this list is `org-global-properties'.
   3111 
   3112 The entries in this list are cons cells where the car is a property
   3113 name and cdr is a string with the value.  If the value represents
   3114 multiple items like an \"_ALL\" property, separate the items by
   3115 spaces.")
   3116 
   3117 (defcustom org-global-properties nil
   3118   "List of property/value pairs that can be inherited by any entry.
   3119 
   3120 This list will be combined with the constant `org-global-properties-fixed'.
   3121 
   3122 The entries in this list are cons cells where the car is a property
   3123 name and cdr is a string with the value.
   3124 
   3125 Buffer local properties are added either by a document property drawer
   3126 
   3127 :PROPERTIES:
   3128 :NAME: VALUE
   3129 :END:
   3130 
   3131 or by adding lines like
   3132 
   3133 #+PROPERTY: NAME VALUE"
   3134   :group 'org-properties
   3135   :type '(repeat
   3136 	  (cons (string :tag "Property")
   3137 		(string :tag "Value"))))
   3138 
   3139 (defvar-local org-keyword-properties nil
   3140   "List of property/value pairs inherited by any entry.
   3141 
   3142 Valid for the current buffer.  This variable is populated from
   3143 PROPERTY keywords.
   3144 
   3145 Note that properties are defined also in property drawers.
   3146 Properties defined there take precedence over properties defined
   3147 as keywords.")
   3148 
   3149 (defgroup org-agenda nil
   3150   "Options concerning agenda views in Org mode."
   3151   :tag "Org Agenda"
   3152   :group 'org)
   3153 
   3154 (defvar-local org-category nil
   3155   "Variable used by Org files to set a category for agenda display.
   3156 There are multiple ways to set the category.  One way is to set
   3157 it in the document property drawer.  For example:
   3158 
   3159 :PROPERTIES:
   3160 :CATEGORY: ELisp
   3161 :END:
   3162 
   3163 Other ways to define it is as an Emacs file variable, for example
   3164 
   3165 #   -*- mode: org; org-category: \"ELisp\"
   3166 
   3167 or for the file to contain a special line:
   3168 
   3169 #+CATEGORY: ELisp
   3170 
   3171 If the file does not specify a category, then file's base name
   3172 is used instead.")
   3173 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
   3174 
   3175 (defcustom org-agenda-files nil
   3176   "The files to be used for agenda display.
   3177 
   3178 If an entry is a directory, all files in that directory that are matched
   3179 by `org-agenda-file-regexp' will be part of the file list.
   3180 
   3181 If the value of the variable is not a list but a single file name, then
   3182 the list of agenda files is actually stored and maintained in that file,
   3183 one agenda file per line.  In this file paths can be given relative to
   3184 `org-directory'.  Tilde expansion and environment variable substitution
   3185 are also made.
   3186 
   3187 Entries may be added to this list with `\\[org-agenda-file-to-front]'
   3188 and removed with `\\[org-remove-file]'."
   3189   :group 'org-agenda
   3190   :type '(choice
   3191 	  (repeat :tag "List of files and directories" file)
   3192 	  (file :tag "Store list in a file\n" :value "~/.agenda_files")))
   3193 
   3194 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
   3195   "Regular expression to match files for `org-agenda-files'.
   3196 If any element in the list in that variable contains a directory instead
   3197 of a normal file, all files in that directory that are matched by this
   3198 regular expression will be included."
   3199   :group 'org-agenda
   3200   :type 'regexp)
   3201 
   3202 (defvaralias 'org-agenda-multi-occur-extra-files
   3203   'org-agenda-text-search-extra-files)
   3204 
   3205 (defcustom org-agenda-text-search-extra-files nil
   3206   "List of extra files to be searched by text search commands.
   3207 These files will be searched in addition to the agenda files by the
   3208 commands `org-search-view' (`\\[org-agenda] s') \
   3209 and `org-occur-in-agenda-files'.
   3210 Note that these files will only be searched for text search commands,
   3211 not for the other agenda views like todo lists, tag searches or the weekly
   3212 agenda.  This variable is intended to list notes and possibly archive files
   3213 that should also be searched by these two commands.
   3214 In fact, if the first element in the list is the symbol `agenda-archives',
   3215 then all archive files of all agenda files will be added to the search
   3216 scope."
   3217   :group 'org-agenda
   3218   :type '(set :greedy t
   3219 	      (const :tag "Agenda Archives" agenda-archives)
   3220 	      (repeat :inline t (file))))
   3221 
   3222 (defcustom org-agenda-skip-unavailable-files nil
   3223   "Non-nil means to just skip non-reachable files in `org-agenda-files'.
   3224 A nil value means to remove them, after a query, from the list."
   3225   :group 'org-agenda
   3226   :type 'boolean)
   3227 
   3228 (defgroup org-latex nil
   3229   "Options for embedding LaTeX code into Org mode."
   3230   :tag "Org LaTeX"
   3231   :group 'org)
   3232 
   3233 (defcustom org-format-latex-options
   3234   '(:foreground default :background default :scale 1.0
   3235 		:html-foreground "Black" :html-background "Transparent"
   3236 		:html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
   3237   "Options for creating images from LaTeX fragments.
   3238 This is a property list with the following properties:
   3239 :foreground  the foreground color for images embedded in Emacs, e.g. \"Black\".
   3240              `default' means use the foreground of the default face.
   3241              `auto' means use the foreground from the text face.
   3242 :background  the background color, or \"Transparent\".
   3243              `default' means use the background of the default face.
   3244              `auto' means use the background from the text face.
   3245 :scale       a scaling factor for the size of the images, to get more pixels
   3246 :html-foreground, :html-background, :html-scale
   3247              the same numbers for HTML export.
   3248 :matchers    a list indicating which matchers should be used to
   3249              find LaTeX fragments.  Valid members of this list are:
   3250              \"begin\" find environments
   3251              \"$1\"    find single characters surrounded by $.$
   3252              \"$\"     find math expressions surrounded by $...$
   3253              \"$$\"    find math expressions surrounded by $$....$$
   3254              \"\\(\"    find math expressions surrounded by \\(...\\)
   3255              \"\\=\\[\"    find math expressions surrounded by \\=\\[...\\]"
   3256   :group 'org-latex
   3257   :type 'plist)
   3258 
   3259 (defcustom org-format-latex-signal-error t
   3260   "Non-nil means signal an error when image creation of LaTeX snippets fails.
   3261 When nil, just push out a message."
   3262   :group 'org-latex
   3263   :version "24.1"
   3264   :type 'boolean)
   3265 
   3266 (defcustom org-latex-to-mathml-jar-file nil
   3267   "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
   3268 Use this to specify additional executable file say a jar file.
   3269 
   3270 When using MathToWeb as the converter, specify the full-path to
   3271 your mathtoweb.jar file."
   3272   :group 'org-latex
   3273   :version "24.1"
   3274   :type '(choice
   3275 	  (const :tag "None" nil)
   3276 	  (file :tag "JAR file" :must-match t)))
   3277 
   3278 (defcustom org-latex-to-mathml-convert-command nil
   3279   "Command to convert LaTeX fragments to MathML.
   3280 Replace format-specifiers in the command as noted below and use
   3281 `shell-command' to convert LaTeX to MathML.
   3282 %j:     Executable file in fully expanded form as specified by
   3283         `org-latex-to-mathml-jar-file'.
   3284 %I:     Input LaTeX file in fully expanded form.
   3285 %i:     Shell-escaped LaTeX fragment to be converted.
   3286         It must not be used inside a quoted argument, the result of %i
   3287         expansion inside a quoted argument is undefined.
   3288 %o:     Output MathML file.
   3289 
   3290 This command is used by `org-create-math-formula'.
   3291 
   3292 When using MathToWeb as the converter, set this option to
   3293 \"java -jar %j -unicode -force -df %o %I\".
   3294 
   3295 When using LaTeXML set this option to
   3296 \"latexmlmath %i --presentationmathml=%o\"."
   3297   :group 'org-latex
   3298   :package-version '(Org . "9.7")
   3299   :type '(choice
   3300 	  (const :tag "None" nil)
   3301 	  (string :tag "\nShell command")))
   3302 
   3303 (defcustom org-latex-to-html-convert-command nil
   3304   "Shell command to convert LaTeX fragments to HTML.
   3305 This command is very open-ended: the output of the command will
   3306 directly replace the LaTeX fragment in the resulting HTML.
   3307 Replace format-specifiers in the command as noted below and use
   3308 `shell-command' to convert LaTeX to HTML.
   3309 %i:     The LaTeX fragment to be converted (shell-escaped).
   3310         It must not be used inside a quoted argument, the result of %i
   3311         expansion inside a quoted argument is undefined.
   3312 
   3313 For example, this could be used with LaTeXML as
   3314 \"latexmlc literal:%i --profile=math --preload=siunitx.sty 2>/dev/null\"."
   3315   :group 'org-latex
   3316   :package-version '(Org . "9.7")
   3317   :type '(choice
   3318 	  (const :tag "None" nil)
   3319 	  (string :tag "Shell command")))
   3320 
   3321 (defcustom org-preview-latex-default-process 'dvipng
   3322   "The default process to convert LaTeX fragments to image files.
   3323 All available processes and theirs documents can be found in
   3324 `org-preview-latex-process-alist', which see."
   3325   :group 'org-latex
   3326   :version "26.1"
   3327   :package-version '(Org . "9.0")
   3328   :type 'symbol)
   3329 
   3330 (defcustom org-preview-latex-process-alist
   3331   '((dvipng
   3332      :programs ("latex" "dvipng")
   3333      :description "dvi > png"
   3334      :message "you need to install the programs: latex and dvipng."
   3335      :image-input-type "dvi"
   3336      :image-output-type "png"
   3337      :image-size-adjust (1.0 . 1.0)
   3338      :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
   3339      :image-converter ("dvipng -D %D -T tight -o %O %f")
   3340      :transparent-image-converter
   3341      ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
   3342     (dvisvgm
   3343      :programs ("latex" "dvisvgm")
   3344      :description "dvi > svg"
   3345      :message "you need to install the programs: latex and dvisvgm."
   3346      :image-input-type "dvi"
   3347      :image-output-type "svg"
   3348      :image-size-adjust (1.7 . 1.5)
   3349      :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
   3350      :image-converter ("dvisvgm %f --no-fonts --exact-bbox --scale=%S --output=%O"))
   3351     (imagemagick
   3352      :programs ("latex" "convert")
   3353      :description "pdf > png"
   3354      :message "you need to install the programs: latex and imagemagick."
   3355      :image-input-type "pdf"
   3356      :image-output-type "png"
   3357      :image-size-adjust (1.0 . 1.0)
   3358      :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
   3359      :image-converter
   3360      ("convert -density %D -trim -antialias %f -quality 100 %O")))
   3361   "Definitions of external processes for LaTeX previewing.
   3362 Org mode can use some external commands to generate TeX snippet's images for
   3363 previewing or inserting into HTML files, e.g., \"dvipng\".  This variable tells
   3364 `org-create-formula-image' how to call them.
   3365 
   3366 The value is an alist with the pattern (NAME . PROPERTIES).  NAME is a symbol.
   3367 PROPERTIES accepts the following attributes:
   3368 
   3369   :programs           list of strings, required programs.
   3370   :description        string, describe the process.
   3371   :message            string, message it when required programs cannot be found.
   3372   :image-input-type   string, input file type of image converter (e.g., \"dvi\").
   3373   :image-output-type  string, output file type of image converter (e.g., \"png\").
   3374   :image-size-adjust  cons of numbers, the car element is used to adjust LaTeX
   3375                       image size showed in buffer and the cdr element is for
   3376                       HTML file.  This option is only useful for process
   3377                       developers, users should use variable
   3378                       `org-format-latex-options' instead.
   3379   :post-clean         list of strings, files matched are to be cleaned up once
   3380                       the image is generated.  When nil, the files with \".dvi\",
   3381                       \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
   3382                       \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
   3383                       be cleaned up.
   3384   :latex-header       list of strings, the LaTeX header of the snippet file.
   3385                       When nil, the fallback value is used instead, which is
   3386                       controlled by `org-format-latex-header',
   3387                       `org-latex-default-packages-alist' and
   3388                       `org-latex-packages-alist', which see.
   3389   :latex-compiler     list of LaTeX commands, as strings.  Each of them is given
   3390                       to the shell.  Place-holders \"%t\", \"%b\" and \"%o\" are
   3391                       replaced with values defined below.
   3392   :image-converter    list of image converter commands strings.  Each of them is
   3393                       given to the shell and supports any of the following
   3394                       place-holders defined below.
   3395 
   3396 If set, :transparent-image-converter is used instead of :image-converter to
   3397 convert an image when the background color is nil or \"Transparent\".
   3398 
   3399 Place-holders used by `:image-converter' and `:latex-compiler':
   3400 
   3401   %f    input file name
   3402   %b    base name of input file
   3403   %o    base directory of input file
   3404   %O    absolute output file name
   3405 
   3406 Place-holders only used by `:image-converter':
   3407 
   3408   %D    dpi, which is used to adjust image size by some processing commands.
   3409   %S    the image size scale ratio, which is used to adjust image size by some
   3410         processing commands."
   3411   :group 'org-latex
   3412   :package-version '(Org . "9.6")
   3413   :type '(alist :tag "LaTeX to image backends"
   3414 		:value-type (plist)))
   3415 
   3416 (defcustom org-preview-latex-image-directory "ltximg/"
   3417   "Path to store latex preview images.
   3418 A relative path here creates many directories relative to the
   3419 processed Org files paths.  An absolute path puts all preview
   3420 images at the same place."
   3421   :group 'org-latex
   3422   :version "26.1"
   3423   :package-version '(Org . "9.0")
   3424   :type 'string)
   3425 
   3426 (defun org-format-latex-mathml-available-p ()
   3427   "Return t if `org-latex-to-mathml-convert-command' is usable."
   3428   (save-match-data
   3429     (when (and (boundp 'org-latex-to-mathml-convert-command)
   3430 	       org-latex-to-mathml-convert-command)
   3431       (let ((executable (car (split-string
   3432 			      org-latex-to-mathml-convert-command))))
   3433 	(when (executable-find executable)
   3434 	  (if (string-match
   3435 	       "%j" org-latex-to-mathml-convert-command)
   3436 	      (file-readable-p org-latex-to-mathml-jar-file)
   3437 	    t))))))
   3438 
   3439 (defcustom org-format-latex-header "\\documentclass{article}
   3440 \\usepackage[usenames]{color}
   3441 \[DEFAULT-PACKAGES]
   3442 \[PACKAGES]
   3443 \\pagestyle{empty}             % do not remove
   3444 % The settings below are copied from fullpage.sty
   3445 \\setlength{\\textwidth}{\\paperwidth}
   3446 \\addtolength{\\textwidth}{-3cm}
   3447 \\setlength{\\oddsidemargin}{1.5cm}
   3448 \\addtolength{\\oddsidemargin}{-2.54cm}
   3449 \\setlength{\\evensidemargin}{\\oddsidemargin}
   3450 \\setlength{\\textheight}{\\paperheight}
   3451 \\addtolength{\\textheight}{-\\headheight}
   3452 \\addtolength{\\textheight}{-\\headsep}
   3453 \\addtolength{\\textheight}{-\\footskip}
   3454 \\addtolength{\\textheight}{-3cm}
   3455 \\setlength{\\topmargin}{1.5cm}
   3456 \\addtolength{\\topmargin}{-2.54cm}"
   3457   "The document header used for processing LaTeX fragments.
   3458 It is imperative that this header make sure that no page number
   3459 appears on the page.  The package defined in the variables
   3460 `org-latex-default-packages-alist' and `org-latex-packages-alist'
   3461 will either replace the placeholder \"[PACKAGES]\" in this
   3462 header, or they will be appended."
   3463   :group 'org-latex
   3464   :type 'string)
   3465 
   3466 (defun org-set-packages-alist (var val)
   3467   "Set the packages alist and make sure it has 3 elements per entry."
   3468   (set-default-toplevel-value var (mapcar (lambda (x)
   3469 		     (if (and (consp x) (= (length x) 2))
   3470 			 (list (car x) (nth 1 x) t)
   3471 		       x))
   3472 		   val)))
   3473 
   3474 (defun org-get-packages-alist (var)
   3475   "Get the packages alist and make sure it has 3 elements per entry."
   3476   (mapcar (lambda (x)
   3477 	    (if (and (consp x) (= (length x) 2))
   3478 		(list (car x) (nth 1 x) t)
   3479 	      x))
   3480 	  (default-value var)))
   3481 
   3482 (defcustom org-latex-default-packages-alist
   3483   '(;; amsmath before fontspec for lualatex and xetex
   3484     (""     "amsmath"   t ("lualatex" "xetex"))
   3485     ;; fontspec ASAP for lualatex and xetex
   3486     (""     "fontspec"  t ("lualatex" "xetex"))
   3487     ;; inputenc and fontenc are for pdflatex only
   3488     ("AUTO" "inputenc"  t ("pdflatex"))
   3489     ("T1"   "fontenc"   t ("pdflatex"))
   3490     (""     "graphicx"  t)
   3491     (""     "longtable" nil)
   3492     (""     "wrapfig"   nil)
   3493     (""     "rotating"  nil)
   3494     ("normalem" "ulem"  t)
   3495     ;; amsmath and amssymb after inputenc/fontenc for pdflatex
   3496     (""     "amsmath"   t ("pdflatex"))
   3497     (""     "amssymb"   t ("pdflatex"))
   3498     (""     "capt-of"   nil)
   3499     (""     "hyperref"  nil))
   3500   "Alist of default packages to be inserted in the header.
   3501 
   3502 Change this only if one of the packages here causes an
   3503 incompatibility with another package you are using.
   3504 
   3505 The packages in this list are needed by one part or another of
   3506 Org mode to function properly:
   3507 
   3508 - fontspec: for font and character selection in lualatex and xetex
   3509 - inputenc, fontenc:  for basic font and character selection
   3510   in pdflatex
   3511 - graphicx: for including images
   3512 - longtable: For multipage tables
   3513 - wrapfig: for figure placement
   3514 - rotating: for sideways figures and tables
   3515 - ulem: for underline and strike-through
   3516 - amsmath: for subscript and superscript and math environments
   3517 - amssymb: for various symbols used for interpreting the entities
   3518   in `org-entities'.  You can skip some of this package if you don't
   3519   use any of the symbols.
   3520 - capt-of: for captions outside of floats
   3521 - hyperref: for cross references
   3522 
   3523 Therefore you should not modify this variable unless you know
   3524 what you are doing.  The one reason to change it anyway is that
   3525 you might be loading some other package that conflicts with one
   3526 of the default packages.  Each element is either a cell or
   3527 a string.
   3528 
   3529 A cell is of the format
   3530 
   3531   (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
   3532 
   3533 If SNIPPET-FLAG is non-nil, the package also needs to be included
   3534 when compiling LaTeX snippets into images for inclusion into
   3535 non-LaTeX output.
   3536 
   3537 COMPILERS is a list of compilers that should include the package,
   3538 see `org-latex-compiler'.  If the document compiler is not in the
   3539 list, and the list is non-nil, the package will not be inserted
   3540 in the final document.
   3541 
   3542 A string will be inserted as-is in the header of the document."
   3543   :group 'org-latex
   3544   :group 'org-export-latex
   3545   :set 'org-set-packages-alist
   3546   :get 'org-get-packages-alist
   3547   :package-version '(Org . "9.7")
   3548   :type '(repeat
   3549 	  (choice
   3550 	   (list :tag "options/package pair"
   3551 		 (string :tag "options")
   3552 		 (string :tag "package")
   3553 		 (boolean :tag "Snippet")
   3554 		 (choice
   3555 		  (const :tag "For all compilers" nil)
   3556 		  (repeat :tag "Allowed compiler" string)))
   3557 	   (string :tag "A line of LaTeX"))))
   3558 
   3559 (defcustom org-latex-packages-alist nil
   3560   "Alist of packages to be inserted in every LaTeX header.
   3561 
   3562 These will be inserted after `org-latex-default-packages-alist'.
   3563 Each element is either a cell or a string.
   3564 
   3565 A cell is of the format:
   3566 
   3567     (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
   3568 
   3569 SNIPPET-FLAG, when non-nil, indicates that this package is also
   3570 needed when turning LaTeX snippets into images for inclusion into
   3571 non-LaTeX output.
   3572 
   3573 COMPILERS is a list of compilers that should include the package,
   3574 see `org-latex-compiler'.  If the document compiler is not in the
   3575 list, and the list is non-nil, the package will not be inserted
   3576 in the final document.
   3577 
   3578 A string will be inserted as-is in the header of the document.
   3579 
   3580 Make sure that you only list packages here which:
   3581 
   3582   - you want in every file;
   3583   - do not conflict with the setup in `org-format-latex-header';
   3584   - do not conflict with the default packages in
   3585     `org-latex-default-packages-alist'."
   3586   :group 'org-latex
   3587   :group 'org-export-latex
   3588   :set 'org-set-packages-alist
   3589   :get 'org-get-packages-alist
   3590   :type
   3591   '(repeat
   3592     (choice
   3593      (list :tag "options/package pair"
   3594            (string :tag "options")
   3595            (string :tag "package")
   3596            (boolean :tag "snippet")
   3597            (choice
   3598             (const :tag "All compilers include this package" nil)
   3599             (repeat :tag "Only include from these compilers" string)))
   3600      (string :tag "A line of LaTeX"))))
   3601 
   3602 (defgroup org-appearance nil
   3603   "Settings for Org mode appearance."
   3604   :tag "Org Appearance"
   3605   :group 'org)
   3606 
   3607 (defcustom org-level-color-stars-only nil
   3608   "Non-nil means fontify only the stars in each headline.
   3609 When nil, the entire headline is fontified.
   3610 Changing it requires restart of `font-lock-mode' to become effective
   3611 also in regions already fontified."
   3612   :group 'org-appearance
   3613   :type 'boolean)
   3614 
   3615 (defcustom org-hide-leading-stars nil
   3616   "Non-nil means hide the first N-1 stars in a headline.
   3617 This works by using the face `org-hide' for these stars.  This
   3618 face is white for a light background, and black for a dark
   3619 background.  You may have to customize the face `org-hide' to
   3620 make this work.
   3621 Changing it requires restart of `font-lock-mode' to become effective
   3622 also in regions already fontified.
   3623 You may also set this on a per-file basis by adding one of the following
   3624 lines to the buffer:
   3625 
   3626    #+STARTUP: hidestars
   3627    #+STARTUP: showstars"
   3628   :group 'org-appearance
   3629   :type 'boolean)
   3630 
   3631 (defcustom org-hidden-keywords nil
   3632   "List of symbols corresponding to keywords to be hidden in the Org buffer.
   3633 For example, a value (title) for this list makes the document's title
   3634 appear in the buffer without the initial \"#+TITLE:\" part."
   3635   :group 'org-appearance
   3636   :package-version '(Org . "9.5")
   3637   :type '(set (const :tag "#+AUTHOR" author)
   3638 	      (const :tag "#+DATE" date)
   3639 	      (const :tag "#+EMAIL" email)
   3640 	      (const :tag "#+SUBTITLE" subtitle)
   3641 	      (const :tag "#+TITLE" title)))
   3642 
   3643 (defcustom org-custom-properties nil
   3644   "List of properties (as strings) with a special meaning.
   3645 The default use of these custom properties is to let the user
   3646 hide them with `org-toggle-custom-properties-visibility'."
   3647   :group 'org-properties
   3648   :group 'org-appearance
   3649   :version "24.3"
   3650   :type '(repeat (string :tag "Property Name")))
   3651 
   3652 (defcustom org-fontify-todo-headline nil
   3653   "Non-nil means change the face of a headline if it is marked as TODO.
   3654 Normally, only the TODO/DONE keyword indicates the state of a headline.
   3655 When this is non-nil, the headline after the keyword is set to the
   3656 `org-headline-todo' as an additional indication."
   3657   :group 'org-appearance
   3658   :package-version '(Org . "9.4")
   3659   :type 'boolean
   3660   :safe #'booleanp)
   3661 
   3662 (defcustom org-fontify-done-headline t
   3663   "Non-nil means change the face of a headline if it is marked DONE.
   3664 Normally, only the TODO/DONE keyword indicates the state of a headline.
   3665 When this is non-nil, the headline after the keyword is set to the
   3666 `org-headline-done' as an additional indication."
   3667   :group 'org-appearance
   3668   :package-version '(Org . "9.4")
   3669   :type 'boolean)
   3670 
   3671 (defcustom org-fontify-emphasized-text t
   3672   "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
   3673 Changing this variable requires a restart of Emacs to take effect."
   3674   :group 'org-appearance
   3675   :type 'boolean)
   3676 
   3677 (defcustom org-fontify-whole-heading-line nil
   3678   "Non-nil means fontify the whole line for headings.
   3679 This is useful when setting a background color for the
   3680 org-level-* faces."
   3681   :group 'org-appearance
   3682   :type 'boolean)
   3683 
   3684 (defcustom org-fontify-whole-block-delimiter-line t
   3685   "Non-nil means fontify the whole line for begin/end lines of blocks.
   3686 This is useful when setting a background color for the
   3687 org-block-begin-line and org-block-end-line faces."
   3688   :group 'org-appearance
   3689   :type 'boolean)
   3690 
   3691 (defcustom org-highlight-latex-and-related nil
   3692   "Non-nil means highlight LaTeX related syntax in the buffer.
   3693 When non-nil, the value should be a list containing any of the
   3694 following symbols:
   3695   `native'   Highlight LaTeX snippets and environments natively.
   3696   `latex'    Highlight LaTeX snippets and environments.
   3697   `script'   Highlight subscript and superscript.
   3698   `entities' Highlight entities."
   3699   :group 'org-appearance
   3700   :version "24.4"
   3701   :package-version '(Org . "8.0")
   3702   :type '(choice
   3703 	  (const :tag "No highlighting" nil)
   3704 	  (set :greedy t :tag "Highlight"
   3705 	       (const :tag "LaTeX snippets and environments (native)" native)
   3706 	       (const :tag "LaTeX snippets and environments" latex)
   3707 	       (const :tag "Subscript and superscript" script)
   3708 	       (const :tag "Entities" entities))))
   3709 
   3710 (defcustom org-hide-emphasis-markers nil
   3711   "Non-nil means font-lock should hide the emphasis marker characters."
   3712   :group 'org-appearance
   3713   :type 'boolean
   3714   :safe #'booleanp)
   3715 
   3716 (defcustom org-hide-macro-markers nil
   3717   "Non-nil means font-lock should hide the brackets marking macro calls."
   3718   :group 'org-appearance
   3719   :type 'boolean)
   3720 
   3721 (defcustom org-pretty-entities nil
   3722   "Non-nil means show entities as UTF8 characters.
   3723 When nil, the \\name form remains in the buffer."
   3724   :group 'org-appearance
   3725   :version "24.1"
   3726   :type 'boolean)
   3727 
   3728 (defcustom org-pretty-entities-include-sub-superscripts t
   3729   "Non-nil means pretty entity display includes formatting sub/superscripts."
   3730   :group 'org-appearance
   3731   :version "24.1"
   3732   :type 'boolean)
   3733 
   3734 (defvar org-emph-re nil
   3735   "Regular expression for matching emphasis.
   3736 After a match, the match groups contain these elements:
   3737 0  The match of the full regular expression, including the characters
   3738    before and after the proper match
   3739 1  The character before the proper match, or empty at beginning of line
   3740 2  The proper match, including the leading and trailing markers
   3741 3  The leading marker like * or /, indicating the type of highlighting
   3742 4  The text between the emphasis markers, not including the markers
   3743 5  The character after the match, empty at the end of a line")
   3744 
   3745 (defvar org-verbatim-re nil
   3746   "Regular expression for matching verbatim text.")
   3747 
   3748 (defvar org-emphasis-regexp-components) ; defined just below
   3749 (defvar org-emphasis-alist) ; defined just below
   3750 (defun org-set-emph-re (var val)
   3751   "Set variable and compute the emphasis regular expression."
   3752   (set-default-toplevel-value var val)
   3753   (when (and (boundp 'org-emphasis-alist)
   3754 	     (boundp 'org-emphasis-regexp-components)
   3755 	     org-emphasis-alist org-emphasis-regexp-components)
   3756     (pcase-let*
   3757 	((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
   3758 	 (body (if (<= nl 0) body
   3759 		 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
   3760 	 (template
   3761 	  (format (concat "\\([%s]\\|^\\)" ;before markers
   3762 			  "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
   3763 			  "\\([%s]\\|$\\)") ;after markers
   3764 		  pre border border body border post)))
   3765       (setq org-emph-re (format template "*/_+"))
   3766       (setq org-verbatim-re (format template "=~")))))
   3767 
   3768 ;; This used to be a defcustom (Org <8.0) but allowing the users to
   3769 ;; set this option proved cumbersome.  See this message/thread:
   3770 ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
   3771 (defvar org-emphasis-regexp-components
   3772   '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
   3773   "Components used to build the regular expression for emphasis.
   3774 This is a list with five entries.  Terminology:  In an emphasis string
   3775 like \" *strong word* \", we call the initial space PREMATCH, the final
   3776 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
   3777 and \"trong wor\" is the body.  The different components in this variable
   3778 specify what is allowed/forbidden in each part:
   3779 
   3780 pre          Chars allowed as prematch.  Beginning of line will be allowed too.
   3781 post         Chars allowed as postmatch.  End of line will be allowed too.
   3782 border       The chars *forbidden* as border characters.
   3783 body-regexp  A regexp like \".\" to match a body character.  Don't use
   3784              non-shy groups here, and don't allow newline here.
   3785 newline      The maximum number of newlines allowed in an emphasis exp.
   3786 
   3787 You need to reload Org or to restart Emacs after setting this.")
   3788 
   3789 (defcustom org-emphasis-alist
   3790   '(("*" bold)
   3791     ("/" italic)
   3792     ("_" underline)
   3793     ("=" org-verbatim verbatim)
   3794     ("~" org-code verbatim)
   3795     ("+" (:strike-through t)))
   3796   "Alist of characters and faces to emphasize text.
   3797 Text starting and ending with a special character will be emphasized,
   3798 for example *bold*, _underlined_ and /italic/.  This variable sets the
   3799 face to be used by font-lock for highlighting in Org buffers.
   3800 Marker characters must be one of */_=~+.
   3801 
   3802 You need to reload Org or to restart Emacs after customizing this."
   3803   :group 'org-appearance
   3804   :set 'org-set-emph-re
   3805   :version "24.4"
   3806   :package-version '(Org . "8.0")
   3807   :type '(repeat
   3808 	  (list
   3809            (choice
   3810 	    (const :tag "Bold" "*")
   3811             (const :tag "Italic" "/")
   3812             (const :tag "Underline" "_")
   3813             (const :tag "Verbatim" "=")
   3814             (const :tag "Code" "~")
   3815             (const :tag "Strike through" "+"))
   3816 	   (choice
   3817 	    (face :tag "Font-lock-face")
   3818 	    (plist :tag "Face property list"))
   3819 	   (option (const verbatim)))))
   3820 
   3821 (defvar org-protecting-blocks '("src" "example" "export")
   3822   "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
   3823 This is needed for font-lock setup.")
   3824 
   3825 ;;; Functions and variables from their packages
   3826 ;;  Declared here to avoid compiler warnings
   3827 (defvar mark-active)
   3828 
   3829 ;; Various packages
   3830 (declare-function calc-eval "calc" (str &optional separator &rest args))
   3831 (declare-function calendar-forward-day "cal-move" (arg))
   3832 (declare-function calendar-goto-date "cal-move" (date))
   3833 (declare-function calendar-goto-today "cal-move" ())
   3834 (declare-function calendar-iso-from-absolute "cal-iso" (date))
   3835 (declare-function calendar-iso-to-absolute "cal-iso" (date))
   3836 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
   3837 (declare-function cdlatex-tab "ext:cdlatex" ())
   3838 (declare-function dired-get-filename
   3839 		  "dired"
   3840 		  (&optional localp no-error-if-not-filep))
   3841 (declare-function org-agenda-change-all-lines
   3842 		  "org-agenda"
   3843 		  (newhead hdmarker &optional fixface just-this))
   3844 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
   3845 		  "org-agenda"
   3846 		  (&optional end))
   3847 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
   3848 (declare-function org-agenda-format-item
   3849 		  "org-agenda"
   3850 		  (extra txt &optional level category tags dotime
   3851 			 remove-re habitp))
   3852 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
   3853 (declare-function org-agenda-save-markers-for-cut-and-paste
   3854 		  "org-agenda"
   3855 		  (beg end))
   3856 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
   3857 (declare-function org-agenda-skip "org-agenda" (&optional element))
   3858 (declare-function org-attach-expand "org-attach" (file))
   3859 (declare-function org-attach-reveal "org-attach" ())
   3860 (declare-function org-attach-reveal-in-emacs "org-attach" ())
   3861 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
   3862 (declare-function org-indent-mode "org-indent" (&optional arg))
   3863 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
   3864 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
   3865 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
   3866 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
   3867 (declare-function parse-time-string "parse-time" (string))
   3868 
   3869 (defvar align-mode-rules-list)
   3870 (defvar calc-embedded-close-formula)
   3871 (defvar calc-embedded-open-formula)
   3872 (defvar calc-embedded-open-mode)
   3873 (defvar org-agenda-tags-todo-honor-ignore-options)
   3874 (defvar remember-data-file)
   3875 (defvar texmathp-why)
   3876 
   3877 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
   3878 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
   3879 (declare-function org-resolve-clocks "org-clock"
   3880 		  (&optional also-non-dangling-p prompt last-valid))
   3881 
   3882 (defvar org-clock-start-time)
   3883 (defvar org-clock-marker (make-marker)
   3884   "Marker recording the last clock-in.")
   3885 (defvar org-clock-hd-marker (make-marker)
   3886   "Marker recording the last clock-in, but the headline position.")
   3887 (defvar org-clock-heading ""
   3888   "The heading of the current clock entry.")
   3889 (defun org-clocking-buffer ()
   3890   "Return the buffer where the clock is currently running.
   3891 Return nil if no clock is running."
   3892   (marker-buffer org-clock-marker))
   3893 (defalias 'org-clock-is-active #'org-clocking-buffer)
   3894 
   3895 (defun org-check-running-clock ()
   3896   "Check if the current buffer contains the running clock.
   3897 If yes, offer to stop it and to save the buffer with the changes."
   3898   (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
   3899 	     (y-or-n-p (format "Clock-out in buffer %s before killing it? "
   3900 			       (buffer-name))))
   3901     (org-clock-out)
   3902     (when (y-or-n-p "Save changed buffer?")
   3903       (save-buffer))))
   3904 
   3905 (defun org-clocktable-try-shift (dir n)
   3906   "Check if this line starts a clock table, if yes, shift the time block."
   3907   (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
   3908     (org-clocktable-shift dir n)))
   3909 
   3910 ;;;###autoload
   3911 (defun org-clock-persistence-insinuate ()
   3912   "Set up hooks for clock persistence."
   3913   (require 'org-clock)
   3914   (add-hook 'org-mode-hook 'org-clock-load)
   3915   (add-hook 'kill-emacs-hook 'org-clock-save))
   3916 
   3917 (defun org-clock-auto-clockout-insinuate ()
   3918   "Set up hook for auto clocking out when Emacs is idle.
   3919 See `org-clock-auto-clockout-timer'.
   3920 
   3921 This function is meant to be added to the user configuration."
   3922   (require 'org-clock)
   3923   (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
   3924 
   3925 (defgroup org-archive nil
   3926   "Options concerning archiving in Org mode."
   3927   :tag "Org Archive"
   3928   :group 'org-structure)
   3929 
   3930 (defcustom org-archive-location "%s_archive::"
   3931   "The location where subtrees should be archived.
   3932 
   3933 The value of this variable is a string, consisting of two parts,
   3934 separated by a double-colon.  The first part is a filename and
   3935 the second part is a headline.
   3936 
   3937 When the filename is omitted, archiving happens in the same file.
   3938 %s in the filename will be replaced by the current file
   3939 name (without the directory part).  Archiving to a different file
   3940 is useful to keep archived entries from contributing to the
   3941 Org Agenda.
   3942 
   3943 The archived entries will be filed as subtrees of the specified
   3944 headline.  When the headline is omitted, the subtrees are simply
   3945 filed away at the end of the file, as top-level entries.  Also in
   3946 the heading you can use %s to represent the file name, this can be
   3947 useful when using the same archive for a number of different files.
   3948 
   3949 Here are a few examples:
   3950 \"%s_archive::\"
   3951 	If the current file is Projects.org, archive in file
   3952 	Projects.org_archive, as top-level trees.  This is the default.
   3953 
   3954 \"::* Archived Tasks\"
   3955 	Archive in the current file, under the top-level headline
   3956 	\"* Archived Tasks\".
   3957 
   3958 \"~/org/archive.org::\"
   3959 	Archive in file ~/org/archive.org (absolute path), as top-level trees.
   3960 
   3961 \"~/org/archive.org::* From %s\"
   3962 	Archive in file ~/org/archive.org (absolute path), under headlines
   3963         \"From FILENAME\" where file name is the current file name.
   3964 
   3965 \"~/org/datetree.org::datetree/* Finished Tasks\"
   3966         The \"datetree/\" string is special, signifying to archive
   3967         items to the datetree.  Items are placed in either the CLOSED
   3968         date of the item, or the current date if there is no CLOSED date.
   3969         The heading will be a subentry to the current date.  There doesn't
   3970         need to be a heading, but there always needs to be a slash after
   3971         datetree.  For example, to store archived items directly in the
   3972         datetree, use \"~/org/datetree.org::datetree/\".
   3973 
   3974 \"basement::** Finished Tasks\"
   3975 	Archive in file ./basement (relative path), as level 3 trees
   3976 	below the level 2 heading \"** Finished Tasks\".
   3977 
   3978 You may define it locally by setting an ARCHIVE property.  If
   3979 such a property is found in the file or in an entry, and anywhere
   3980 up the hierarchy, it will be used.
   3981 
   3982 You can also set it for the whole file using the keyword-syntax:
   3983 
   3984 #+ARCHIVE: basement::** Finished Tasks"
   3985   :group 'org-archive
   3986   :type 'string)
   3987 
   3988 (defcustom org-agenda-skip-archived-trees t
   3989   "Non-nil means the agenda will skip any items located in archived trees.
   3990 An archived tree is a tree marked with the tag ARCHIVE.  The use of this
   3991 variable is no longer recommended, you should leave it at the value t.
   3992 Instead, use the key `v' to cycle the archives-mode in the agenda."
   3993   :group 'org-archive
   3994   :group 'org-agenda-skip
   3995   :type 'boolean)
   3996 
   3997 (defcustom org-columns-skip-archived-trees t
   3998   "Non-nil means ignore archived trees when creating column view."
   3999   :group 'org-archive
   4000   :group 'org-properties
   4001   :type 'boolean)
   4002 
   4003 (defcustom org-sparse-tree-open-archived-trees nil
   4004   "Non-nil means sparse tree construction shows matches in archived trees.
   4005 When nil, matches in these trees are highlighted, but the trees are kept in
   4006 collapsed state."
   4007   :group 'org-archive
   4008   :group 'org-sparse-trees
   4009   :type 'boolean)
   4010 
   4011 (defcustom org-sparse-tree-default-date-type nil
   4012   "The default date type when building a sparse tree.
   4013 When this is nil, a date is a scheduled or a deadline timestamp.
   4014 Otherwise, these types are allowed:
   4015 
   4016         all: all timestamps
   4017      active: only active timestamps (<...>)
   4018    inactive: only inactive timestamps ([...])
   4019   scheduled: only scheduled timestamps
   4020    deadline: only deadline timestamps"
   4021   :type '(choice (const :tag "Scheduled or deadline" nil)
   4022 		 (const :tag "All timestamps" all)
   4023 		 (const :tag "Only active timestamps" active)
   4024 		 (const :tag "Only inactive timestamps" inactive)
   4025 		 (const :tag "Only scheduled timestamps" scheduled)
   4026 		 (const :tag "Only deadline timestamps" deadline)
   4027 		 (const :tag "Only closed timestamps" closed))
   4028   :version "26.1"
   4029   :package-version '(Org . "8.3")
   4030   :group 'org-sparse-trees)
   4031 
   4032 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
   4033 
   4034 ;; Declare Column View Code
   4035 
   4036 (declare-function org-columns-get-format-and-top-level "org-colview" ())
   4037 (declare-function org-columns-compute "org-colview" (property))
   4038 
   4039 ;; Declare ID code
   4040 
   4041 (declare-function org-id-store-link "org-id")
   4042 (declare-function org-id-locations-load "org-id")
   4043 (declare-function org-id-locations-save "org-id")
   4044 (defvar org-id-track-globally)
   4045 
   4046 ;;; Variables for pre-computed regular expressions, all buffer local
   4047 
   4048 (defvar-local org-todo-regexp nil
   4049   "Matches any of the TODO state keywords.
   4050 Since TODO keywords are case-sensitive, `case-fold-search' is
   4051 expected to be bound to nil when matching against this regexp.")
   4052 
   4053 (defvar-local org-not-done-regexp nil
   4054   "Matches any of the TODO state keywords except the last one.
   4055 Since TODO keywords are case-sensitive, `case-fold-search' is
   4056 expected to be bound to nil when matching against this regexp.")
   4057 
   4058 (defvar-local org-not-done-heading-regexp nil
   4059   "Matches a TODO headline that is not done.
   4060 Since TODO keywords are case-sensitive, `case-fold-search' is
   4061 expected to be bound to nil when matching against this regexp.")
   4062 
   4063 (defvar-local org-todo-line-regexp nil
   4064   "Matches a headline and puts TODO state into group 2 if present.
   4065 Since TODO keywords are case-sensitive, `case-fold-search' is
   4066 expected to be bound to nil when matching against this regexp.")
   4067 
   4068 (defvar-local org-complex-heading-regexp nil
   4069   "Matches a headline and puts everything into groups:
   4070 
   4071 group 1: Stars
   4072 group 2: The TODO keyword, maybe
   4073 group 3: Priority cookie
   4074 group 4: True headline
   4075 group 5: Tags
   4076 
   4077 Since TODO keywords are case-sensitive, `case-fold-search' is
   4078 expected to be bound to nil when matching against this regexp.")
   4079 
   4080 (defvar-local org-complex-heading-regexp-format nil
   4081   "Printf format to make regexp to match an exact headline.
   4082 This regexp will match the headline of any node which has the
   4083 exact headline text that is put into the format, but may have any
   4084 TODO state, priority, tags, statistics cookies (at the beginning
   4085 or end of the headline title), or COMMENT keyword.")
   4086 
   4087 (defvar-local org-todo-line-tags-regexp nil
   4088   "Matches a headline and puts TODO state into group 2 if present.
   4089 Also put tags into group 4 if tags are present.")
   4090 
   4091 (defconst org-plain-time-of-day-regexp
   4092   (concat
   4093    "\\(\\<[012]?[0-9]"
   4094    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   4095    "\\(--?"
   4096    "\\(\\<[012]?[0-9]"
   4097    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   4098    "\\)?")
   4099   "Regular expression to match a plain time or time range.
   4100 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
   4101 groups carry important information:
   4102 0  the full match
   4103 1  the first time, range or not
   4104 8  the second time, if it is a range.")
   4105 
   4106 (defconst org-plain-time-extension-regexp
   4107   (concat
   4108    "\\(\\<[012]?[0-9]"
   4109    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   4110    "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
   4111   "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
   4112 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
   4113 groups carry important information:
   4114 0  the full match
   4115 7  hours of duration
   4116 9  minutes of duration")
   4117 
   4118 (defconst org-stamp-time-of-day-regexp
   4119   (concat
   4120    "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
   4121    "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
   4122    "\\(--?"
   4123    "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
   4124   "Regular expression to match a timestamp time or time range.
   4125 After a match, the following groups carry important information:
   4126 0  the full match
   4127 1  date plus weekday, for back referencing to make sure
   4128      both times are on the same day
   4129 2  the first time, range or not
   4130 4  the second time, if it is a range.")
   4131 
   4132 (defconst org-startup-options
   4133   '(("fold" org-startup-folded fold)
   4134     ("overview" org-startup-folded overview)
   4135     ("nofold" org-startup-folded nofold)
   4136     ("showall" org-startup-folded showall)
   4137     ("show2levels" org-startup-folded show2levels)
   4138     ("show3levels" org-startup-folded show3levels)
   4139     ("show4levels" org-startup-folded show4levels)
   4140     ("show5levels" org-startup-folded show5levels)
   4141     ("showeverything" org-startup-folded showeverything)
   4142     ("content" org-startup-folded content)
   4143     ("indent" org-startup-indented t)
   4144     ("noindent" org-startup-indented nil)
   4145     ("num" org-startup-numerated t)
   4146     ("nonum" org-startup-numerated nil)
   4147     ("hidestars" org-hide-leading-stars t)
   4148     ("showstars" org-hide-leading-stars nil)
   4149     ("odd" org-odd-levels-only t)
   4150     ("oddeven" org-odd-levels-only nil)
   4151     ("align" org-startup-align-all-tables t)
   4152     ("noalign" org-startup-align-all-tables nil)
   4153     ("shrink" org-startup-shrink-all-tables t)
   4154     ("descriptivelinks" org-link-descriptive t)
   4155     ("literallinks" org-link-descriptive nil)
   4156     ("inlineimages" org-startup-with-inline-images t)
   4157     ("noinlineimages" org-startup-with-inline-images nil)
   4158     ("latexpreview" org-startup-with-latex-preview t)
   4159     ("nolatexpreview" org-startup-with-latex-preview nil)
   4160     ("customtime" org-display-custom-times t)
   4161     ("logdone" org-log-done time)
   4162     ("lognotedone" org-log-done note)
   4163     ("nologdone" org-log-done nil)
   4164     ("lognoteclock-out" org-log-note-clock-out t)
   4165     ("nolognoteclock-out" org-log-note-clock-out nil)
   4166     ("logrepeat" org-log-repeat state)
   4167     ("lognoterepeat" org-log-repeat note)
   4168     ("logdrawer" org-log-into-drawer t)
   4169     ("nologdrawer" org-log-into-drawer nil)
   4170     ("logstatesreversed" org-log-states-order-reversed t)
   4171     ("nologstatesreversed" org-log-states-order-reversed nil)
   4172     ("nologrepeat" org-log-repeat nil)
   4173     ("logreschedule" org-log-reschedule time)
   4174     ("lognotereschedule" org-log-reschedule note)
   4175     ("nologreschedule" org-log-reschedule nil)
   4176     ("logredeadline" org-log-redeadline time)
   4177     ("lognoteredeadline" org-log-redeadline note)
   4178     ("nologredeadline" org-log-redeadline nil)
   4179     ("logrefile" org-log-refile time)
   4180     ("lognoterefile" org-log-refile note)
   4181     ("nologrefile" org-log-refile nil)
   4182     ("fninline" org-footnote-define-inline t)
   4183     ("nofninline" org-footnote-define-inline nil)
   4184     ("fnlocal" org-footnote-section nil)
   4185     ("fnauto" org-footnote-auto-label t)
   4186     ("fnprompt" org-footnote-auto-label nil)
   4187     ("fnconfirm" org-footnote-auto-label confirm)
   4188     ("fnplain" org-footnote-auto-label plain)
   4189     ("fnadjust" org-footnote-auto-adjust t)
   4190     ("nofnadjust" org-footnote-auto-adjust nil)
   4191     ("fnanon" org-footnote-auto-label anonymous)
   4192     ("constcgs" constants-unit-system cgs)
   4193     ("constSI" constants-unit-system SI)
   4194     ("noptag" org-tag-persistent-alist nil)
   4195     ("hideblocks" org-hide-block-startup t)
   4196     ("nohideblocks" org-hide-block-startup nil)
   4197     ("hidedrawers" org-hide-drawer-startup t)
   4198     ("nohidedrawers" org-hide-drawer-startup nil)
   4199     ("beamer" org-startup-with-beamer-mode t)
   4200     ("entitiespretty" org-pretty-entities t)
   4201     ("entitiesplain" org-pretty-entities nil))
   4202   "Variable associated with STARTUP options for Org.
   4203 Each element is a list of three items: the startup options (as written
   4204 in the #+STARTUP line), the corresponding variable, and the value to set
   4205 this variable to if the option is found.  An optional fourth element PUSH
   4206 means to push this value onto the list in the variable.")
   4207 
   4208 (defcustom org-group-tags t
   4209   "When non-nil (the default), use group tags.
   4210 This can be turned on/off through `org-toggle-tags-groups'."
   4211   :group 'org-tags
   4212   :group 'org-startup
   4213   :type 'boolean)
   4214 
   4215 (defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
   4216 
   4217 (defun org-toggle-tags-groups ()
   4218   "Toggle support for group tags.
   4219 Support for group tags is controlled by the option
   4220 `org-group-tags', which is non-nil by default."
   4221   (interactive)
   4222   (setq org-group-tags (not org-group-tags))
   4223   (cond ((and (derived-mode-p 'org-agenda-mode)
   4224 	      org-group-tags)
   4225 	 (org-agenda-redo))
   4226 	((derived-mode-p 'org-mode)
   4227 	 (let ((org-inhibit-startup t)) (org-mode))))
   4228   (message "Groups tags support has been turned %s"
   4229 	   (if org-group-tags "on" "off")))
   4230 
   4231 (defun org--tag-add-to-alist (alist1 alist2)
   4232   "Merge tags from ALIST1 into ALIST2.
   4233 
   4234 Duplicates tags outside a group are removed.  Keywords and order
   4235 are preserved.
   4236 
   4237 The function assumes ALIST1 and ALIST2 are proper tag alists.
   4238 See `org-tag-alist' for their structure."
   4239   (cond
   4240    ((null alist2) alist1)
   4241    ((null alist1) alist2)
   4242    (t
   4243     (let ((to-add nil)
   4244 	  (group-flag nil))
   4245       (dolist (tag-pair alist1)
   4246 	(pcase tag-pair
   4247 	  (`(,(or :startgrouptag :startgroup))
   4248 	   (setq group-flag t)
   4249 	   (push tag-pair to-add))
   4250 	  (`(,(or :endgrouptag :endgroup))
   4251 	   (setq group-flag nil)
   4252 	   (push tag-pair to-add))
   4253 	  (`(,(or :grouptags :newline))
   4254 	   (push tag-pair to-add))
   4255 	  (`(,tag . ,_)
   4256 	   ;; Remove duplicates from ALIST1, unless they are in
   4257 	   ;; a group.  Indeed, it makes sense to have a tag appear in
   4258 	   ;; multiple groups.
   4259 	   (when (or group-flag (not (assoc tag alist2)))
   4260 	     (push tag-pair to-add)))
   4261 	  (_ (error "Invalid association in tag alist: %S" tag-pair))))
   4262       ;; Preserve order of ALIST1.
   4263       (append (nreverse to-add) alist2)))))
   4264 
   4265 (defun org-priority-to-value (s)
   4266   "Convert priority string S to its numeric value."
   4267   (or (save-match-data
   4268 	(and (string-match "\\([0-9]+\\)" s)
   4269 	     (string-to-number (match-string 1 s))))
   4270       (string-to-char s)))
   4271 
   4272 (defun org-set-regexps-and-options (&optional tags-only)
   4273   "Precompute regular expressions used in the current buffer.
   4274 When optional argument TAGS-ONLY is non-nil, only compute tags
   4275 related expressions."
   4276   (when (derived-mode-p 'org-mode)
   4277     (let ((alist (org-collect-keywords
   4278 		  (append '("FILETAGS" "TAGS")
   4279 			  (and (not tags-only)
   4280 			       '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
   4281 				 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
   4282 				 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
   4283 		  '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
   4284       ;; Startup options.  Get this early since it does change
   4285       ;; behavior for other options (e.g., tags).
   4286       (let ((startup (cl-mapcan (lambda (value) (split-string value))
   4287 				(cdr (assoc "STARTUP" alist)))))
   4288 	(dolist (option startup)
   4289 	  (pcase (assoc-string option org-startup-options t)
   4290 	    (`(,_ ,variable ,value t)
   4291 	     (unless (listp (symbol-value variable))
   4292 	       (set (make-local-variable variable) nil))
   4293 	     (add-to-list variable value))
   4294 	    (`(,_ ,variable ,value . ,_)
   4295 	     (set (make-local-variable variable) value))
   4296 	    (_ nil))))
   4297       (setq-local org-file-tags
   4298 		  (mapcar #'org-add-prop-inherited
   4299 			  (cl-mapcan (lambda (value)
   4300 				       (cl-mapcan
   4301 					(lambda (k) (org-split-string k ":"))
   4302 					(split-string value)))
   4303 				     (cdr (assoc "FILETAGS" alist)))))
   4304       (setq org-current-tag-alist
   4305 	    (org--tag-add-to-alist
   4306 	     org-tag-persistent-alist
   4307 	     (let ((tags (cdr (assoc "TAGS" alist))))
   4308 	       (if tags
   4309 		   (org-tag-string-to-alist
   4310 		    (mapconcat #'identity tags "\n"))
   4311 		 org-tag-alist))))
   4312       (setq org-tag-groups-alist
   4313 	    (org-tag-alist-to-groups org-current-tag-alist))
   4314       (unless tags-only
   4315 	;; Properties.
   4316 	(let ((properties nil))
   4317 	  (dolist (value (cdr (assoc "PROPERTY" alist)))
   4318 	    (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
   4319 	      (setq properties (org--update-property-plist
   4320 				(match-string-no-properties 1 value)
   4321 				(match-string-no-properties 2 value)
   4322 				properties))))
   4323 	  (setq-local org-keyword-properties properties))
   4324 	;; Archive location.
   4325 	(let ((archive (cdr (assoc "ARCHIVE" alist))))
   4326 	  (when archive (setq-local org-archive-location archive)))
   4327 	;; Category.
   4328 	(let ((category (cdr (assoc "CATEGORY" alist))))
   4329 	  (when category
   4330 	    (setq-local org-category (intern category))
   4331 	    (setq-local org-keyword-properties
   4332 			(org--update-property-plist
   4333 			 "CATEGORY" category org-keyword-properties))))
   4334 	;; Columns.
   4335 	(let ((column (cdr (assoc "COLUMNS" alist))))
   4336 	  (when column (setq-local org-columns-default-format column)))
   4337 	;; Constants.
   4338 	(let ((store nil))
   4339 	  (dolist (pair (cl-mapcan #'split-string
   4340 				   (cdr (assoc "CONSTANTS" alist))))
   4341 	    (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
   4342 	      (let* ((name (match-string 1 pair))
   4343 		     (value (match-string 2 pair))
   4344 		     (old (assoc name store)))
   4345 		(if old (setcdr old value)
   4346 		  (push (cons name value) store)))))
   4347 	  (setq org-table-formula-constants-local store))
   4348 	;; Link abbreviations.
   4349 	(let ((links
   4350 	       (delq nil
   4351 		     (mapcar
   4352 		      (lambda (value)
   4353 			(and (or
   4354                               ;; "abbrev with spaces" spec
   4355                               (string-match "\\`\"\\(.+[^\\]\\)\"[ \t]+\\(.+\\)" value)
   4356                               ;; abbrev spec
   4357                               (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value))
   4358 			     (cons (match-string-no-properties 1 value)
   4359 				   (match-string-no-properties 2 value))))
   4360 		      (cdr (assoc "LINK" alist))))))
   4361 	  (when links (setq org-link-abbrev-alist-local (nreverse links))))
   4362 	;; Priorities.
   4363 	(let ((value (cdr (assoc "PRIORITIES" alist))))
   4364 	  (pcase (and value (split-string value))
   4365 	    (`(,high ,low ,default . ,_)
   4366 	     (setq-local org-priority-highest (org-priority-to-value high))
   4367 	     (setq-local org-priority-lowest (org-priority-to-value low))
   4368 	     (setq-local org-priority-default (org-priority-to-value default)))))
   4369 	;; Scripts.
   4370 	(let ((value (cdr (assoc "OPTIONS" alist))))
   4371 	  (dolist (option value)
   4372 	    (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
   4373 	      (setq-local org-use-sub-superscripts
   4374 			  (read (match-string 1 option))))))
   4375 	;; TODO keywords.
   4376 	(setq-local org-todo-kwd-alist nil)
   4377 	(setq-local org-todo-key-alist nil)
   4378 	(setq-local org-todo-key-trigger nil)
   4379 	(setq-local org-todo-keywords-1 nil)
   4380 	(setq-local org-done-keywords nil)
   4381 	(setq-local org-todo-heads nil)
   4382 	(setq-local org-todo-sets nil)
   4383 	(setq-local org-todo-log-states nil)
   4384 	(let ((todo-sequences
   4385 	       (or (append (mapcar (lambda (value)
   4386 				     (cons 'type (split-string value)))
   4387 				   (cdr (assoc "TYP_TODO" alist)))
   4388 			   (mapcar (lambda (value)
   4389 				     (cons 'sequence (split-string value)))
   4390 				   (append (cdr (assoc "TODO" alist))
   4391 					   (cdr (assoc "SEQ_TODO" alist)))))
   4392 		   (let ((d (default-value 'org-todo-keywords)))
   4393 		     (if (not (stringp (car d))) d
   4394 		       ;; XXX: Backward compatibility code.
   4395 		       (list (cons org-todo-interpretation d)))))))
   4396 	  (dolist (sequence todo-sequences)
   4397 	    (let* ((sequence (or (run-hook-with-args-until-success
   4398 				  'org-todo-setup-filter-hook sequence)
   4399 				 sequence))
   4400 		   (sequence-type (car sequence))
   4401 		   (keywords (cdr sequence))
   4402 		   (sep (member "|" keywords))
   4403 		   names alist)
   4404 	      (dolist (k (remove "|" keywords))
   4405 		(unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
   4406 				      k)
   4407 		  (error "Invalid TODO keyword %s" k))
   4408 		(let ((name (match-string 1 k))
   4409 		      (key (match-string 2 k))
   4410 		      (log (org-extract-log-state-settings k)))
   4411 		  (push name names)
   4412 		  (push (cons name (and key (string-to-char key))) alist)
   4413 		  (when log (push log org-todo-log-states))))
   4414 	      (let* ((names (nreverse names))
   4415 		     (done (if sep (org-remove-keyword-keys (cdr sep))
   4416 			     (last names)))
   4417 		     (head (car names))
   4418 		     (tail (list sequence-type head (car done) (org-last done))))
   4419 		(add-to-list 'org-todo-heads head 'append)
   4420 		(push names org-todo-sets)
   4421 		(setq org-done-keywords (append org-done-keywords done nil))
   4422 		(setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
   4423 		(setq org-todo-key-alist
   4424 		      (append org-todo-key-alist
   4425 			      (and alist
   4426 				   (append '((:startgroup))
   4427 					   (nreverse alist)
   4428 					   '((:endgroup))))))
   4429 		(dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
   4430 	(setq org-todo-sets (nreverse org-todo-sets)
   4431 	      org-todo-kwd-alist (nreverse org-todo-kwd-alist)
   4432 	      org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
   4433 	      org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
   4434 	;; Compute the regular expressions and other local variables.
   4435 	;; Using `org-outline-regexp-bol' would complicate them much,
   4436 	;; because of the fixed white space at the end of that string.
   4437 	(unless org-done-keywords
   4438 	  (setq org-done-keywords
   4439 		(and org-todo-keywords-1 (last org-todo-keywords-1))))
   4440 	(setq org-not-done-keywords
   4441 	      (org-delete-all org-done-keywords
   4442 			      (copy-sequence org-todo-keywords-1))
   4443 	      org-todo-regexp (regexp-opt org-todo-keywords-1 t)
   4444 	      org-not-done-regexp (regexp-opt org-not-done-keywords t)
   4445 	      org-not-done-heading-regexp
   4446 	      (format org-heading-keyword-regexp-format org-not-done-regexp)
   4447 	      org-todo-line-regexp
   4448 	      (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
   4449 	      org-complex-heading-regexp
   4450 	      (concat "^\\(\\*+\\)"
   4451 		      "\\(?: +" org-todo-regexp "\\)?"
   4452 		      "\\(?: +\\(\\[#.\\]\\)\\)?"
   4453 		      "\\(?: +\\(.*?\\)\\)??"
   4454 		      "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
   4455 		      "[ \t]*$")
   4456 	      org-complex-heading-regexp-format
   4457 	      (concat "^\\(\\*+\\)"
   4458 		      "\\(?: +" org-todo-regexp "\\)?"
   4459 		      "\\(?: +\\(\\[#.\\]\\)\\)?"
   4460 		      "\\(?: +"
   4461                       ;; Headline might be commented
   4462                       "\\(?:" org-comment-string " +\\)?"
   4463 		      ;; Stats cookies can be stuck to body.
   4464 		      "\\(?:\\[[0-9%%/]+\\] *\\)*"
   4465 		      "\\(%s\\)"
   4466 		      "\\(?: *\\[[0-9%%/]+\\]\\)*"
   4467 		      "\\)"
   4468 		      "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
   4469 		      "[ \t]*$")
   4470 	      org-todo-line-tags-regexp
   4471 	      (concat "^\\(\\*+\\)"
   4472 		      "\\(?: +" org-todo-regexp "\\)?"
   4473 		      "\\(?: +\\(.*?\\)\\)??"
   4474 		      "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
   4475 		      "[ \t]*$"))
   4476 	(org-compute-latex-and-related-regexp)))))
   4477 
   4478 (defun org-collect-keywords (keywords &optional unique directory)
   4479   "Return values for KEYWORDS in current buffer, as an alist.
   4480 
   4481 KEYWORDS is a list of strings.  Return value is a list of
   4482 elements with the pattern:
   4483 
   4484   (NAME . LIST-OF-VALUES)
   4485 
   4486 where NAME is the upcase name of the keyword, and LIST-OF-VALUES
   4487 is a list of non-empty values, as strings, in order of appearance
   4488 in the buffer.
   4489 
   4490 When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
   4491 value, empty or not, appearing in the buffer, as a string.
   4492 
   4493 When KEYWORD appears in DIRECTORIES, each value is a cons cell:
   4494 
   4495   (VALUE . DIRECTORY)
   4496 
   4497 where VALUE is the regular value, and DIRECTORY is the variable
   4498 `default-directory' for the buffer containing the keyword.  This
   4499 is important for values containing relative file names, since the
   4500 function follows SETUPFILE keywords, and may change its working
   4501 directory."
   4502   (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
   4503 	 (unique (mapcar #'upcase unique))
   4504 	 (alist (org--collect-keywords-1
   4505 		 keywords unique directory
   4506 		 (and buffer-file-name (list buffer-file-name))
   4507 		 nil)))
   4508     ;; Re-order results.
   4509     (dolist (entry alist)
   4510       (pcase entry
   4511 	(`(,_ . ,(and value (pred consp)))
   4512 	 (setcdr entry (nreverse value)))))
   4513     (nreverse alist)))
   4514 
   4515 (defun org--collect-keywords-1 (keywords unique directory files alist)
   4516   (org-with-point-at 1
   4517     (let ((case-fold-search t)
   4518 	  (regexp (org-make-options-regexp keywords)))
   4519       (while (and keywords (re-search-forward regexp nil t))
   4520         (let ((element (org-element-at-point)))
   4521           (when (org-element-type-p element 'keyword)
   4522             (let ((value (org-element-property :value element)))
   4523               (pcase (org-element-property :key element)
   4524 		("SETUPFILE"
   4525 		 (when (org-string-nw-p value)
   4526 		   (let* ((uri (org-strip-quotes value))
   4527 			  (uri-is-url (org-url-p uri))
   4528 			  (uri (if uri-is-url
   4529 				   uri
   4530                                  ;; In case of error, be safe.
   4531                                  ;; See bug#68976.
   4532                                  (ignore-errors ; return nil when expansion fails.
   4533 				   (expand-file-name uri)))))
   4534 		     (unless (or (not uri) (member uri files))
   4535 		       (with-temp-buffer
   4536 			 (unless uri-is-url
   4537 			   (setq default-directory (file-name-directory uri)))
   4538 			 (let ((contents (org-file-contents uri :noerror)))
   4539 			   (when contents
   4540 			     (insert contents)
   4541 			     ;; Fake Org mode: `org-element-at-point'
   4542 			     ;; doesn't need full set-up.
   4543 			     (let ((major-mode 'org-mode))
   4544                                (setq-local tab-width 8)
   4545 			       (setq alist
   4546 				     (org--collect-keywords-1
   4547 				      keywords unique directory
   4548 				      (cons uri files)
   4549 				      alist))))))))))
   4550 		(keyword
   4551 		 (let ((entry (assoc keyword alist))
   4552 		       (final
   4553 			(cond ((not (member keyword directory)) value)
   4554 			      (buffer-file-name
   4555 			       (cons value
   4556 				     (file-name-directory buffer-file-name)))
   4557 			      (t (cons value default-directory)))))
   4558 		   (cond ((member keyword unique)
   4559 			  (push (cons keyword final) alist)
   4560 			  (setq keywords (remove keyword keywords))
   4561 			  (setq regexp (org-make-options-regexp keywords)))
   4562 			 ((null entry) (push (list keyword final) alist))
   4563 			 (t (push final (cdr entry)))))))))))
   4564       alist)))
   4565 
   4566 (defun org-tag-string-to-alist (s)
   4567   "Return tag alist associated to string S.
   4568 S is a value for TAGS keyword or produced with
   4569 `org-tag-alist-to-string'.  Return value is an alist suitable for
   4570 `org-tag-alist' or `org-tag-persistent-alist'."
   4571   (let ((lines (mapcar #'split-string (split-string s "\n" t)))
   4572 	(tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
   4573 			"\\(?:(\\(.\\))\\)?\\'"))
   4574 	alist group-flag)
   4575     (dolist (tokens lines (cdr (nreverse alist)))
   4576       (push '(:newline) alist)
   4577       (while tokens
   4578 	(let ((token (pop tokens)))
   4579 	  (pcase token
   4580 	    ("{"
   4581 	     (push '(:startgroup) alist)
   4582 	     (when (equal (nth 1 tokens) ":") (setq group-flag t)))
   4583 	    ("}"
   4584 	     (push '(:endgroup) alist)
   4585 	     (setq group-flag nil))
   4586 	    ("["
   4587 	     (push '(:startgrouptag) alist)
   4588 	     (when (equal (nth 1 tokens) ":") (setq group-flag t)))
   4589 	    ("]"
   4590 	     (push '(:endgrouptag) alist)
   4591 	     (setq group-flag nil))
   4592 	    (":"
   4593 	     (push '(:grouptags) alist))
   4594 	    ((guard (string-match tag-re token))
   4595 	     (let ((tag (match-string 1 token))
   4596 		   (key (and (match-beginning 2)
   4597 			     (string-to-char (match-string 2 token)))))
   4598 	       ;; Push all tags in groups, no matter if they already
   4599 	       ;; appear somewhere else in the list.
   4600 	       (when (or group-flag (not (assoc tag alist)))
   4601 		 (push (cons tag key) alist))))))))))
   4602 
   4603 (defun org-tag-alist-to-string (alist &optional skip-key)
   4604   "Return tag string associated to ALIST.
   4605 
   4606 ALIST is an alist, as defined in `org-tag-alist' or
   4607 `org-tag-persistent-alist', or produced with
   4608 `org-tag-string-to-alist'.
   4609 
   4610 Return value is a string suitable as a value for \"TAGS\"
   4611 keyword.
   4612 
   4613 When optional argument SKIP-KEY is non-nil, skip selection keys
   4614 next to tags."
   4615   (mapconcat (lambda (token)
   4616 	       (pcase token
   4617 		 (`(:startgroup) "{")
   4618 		 (`(:endgroup) "}")
   4619 		 (`(:startgrouptag) "[")
   4620 		 (`(:endgrouptag) "]")
   4621 		 (`(:grouptags) ":")
   4622 		 (`(:newline) "\\n")
   4623 		 ((and
   4624 		   (guard (not skip-key))
   4625 		   `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
   4626 		  (format "%s(%c)" tag key))
   4627 		 (`(,(and tag (pred stringp)) . ,_) tag)
   4628 		 (_ (user-error "Invalid tag token: %S" token))))
   4629 	     alist
   4630 	     " "))
   4631 
   4632 (defun org-tag-alist-to-groups (alist)
   4633   "Return group alist from tag ALIST.
   4634 ALIST is an alist, as defined in `org-tag-alist' or
   4635 `org-tag-persistent-alist', or produced with
   4636 `org-tag-string-to-alist'.  Return value is an alist following
   4637 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
   4638 a string, summarizing TAGS, as a list of strings."
   4639   (let (groups group-status current-group)
   4640     (dolist (token alist (nreverse groups))
   4641       (pcase token
   4642 	(`(,(or :startgroup :startgrouptag)) (setq group-status t))
   4643 	(`(,(or :endgroup :endgrouptag))
   4644 	 (when (eq group-status 'append)
   4645 	   (push (nreverse current-group) groups))
   4646 	 (setq group-status nil current-group nil))
   4647 	(`(:grouptags) (setq group-status 'append))
   4648 	((and `(,tag . ,_) (guard group-status))
   4649 	 (if (eq group-status 'append) (push tag current-group)
   4650 	   (setq current-group (list tag))))
   4651 	(_ nil)))))
   4652 
   4653 (defvar org--file-cache (make-hash-table :test #'equal)
   4654   "Hash table to store contents of files referenced via a URL.
   4655 This is the cache of file URLs read using `org-file-contents'.")
   4656 
   4657 (defun org-reset-file-cache ()
   4658   "Reset the cache of files downloaded by `org-file-contents'."
   4659   (clrhash org--file-cache))
   4660 
   4661 (defun org-file-contents (file &optional noerror nocache)
   4662   "Return the contents of FILE, as a string.
   4663 
   4664 FILE can be a file name or URL.
   4665 
   4666 If FILE is a URL, download the contents.  If the URL contents are
   4667 already cached in the `org--file-cache' hash table, the download step
   4668 is skipped.
   4669 
   4670 If NOERROR is non-nil, ignore the error when unable to read the FILE
   4671 from file or URL, and return nil.
   4672 
   4673 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
   4674 is available.  This option applies only if FILE is a URL."
   4675   (let* ((is-url (org-url-p file))
   4676          (is-remote (condition-case nil
   4677                         (file-remote-p file)
   4678                       ;; In case of error, be safe.
   4679                       ;; See bug#68976.
   4680                       (t t)))
   4681          (cache (and is-url
   4682                      (not nocache)
   4683                      (gethash file org--file-cache))))
   4684     (cond
   4685      (cache)
   4686      ((or is-url is-remote)
   4687       (if (org--should-fetch-remote-resource-p file)
   4688           (condition-case error
   4689               (with-current-buffer (url-retrieve-synchronously file)
   4690                 (goto-char (point-min))
   4691                 ;; Move point to after the url-retrieve header.
   4692                 (search-forward "\n\n" nil :move)
   4693                 ;; Search for the success code only in the url-retrieve header.
   4694                 (if (save-excursion
   4695                       (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
   4696                     ;; Update the cache `org--file-cache' and return contents.
   4697                     (puthash file
   4698                              (buffer-substring-no-properties (point) (point-max))
   4699                              org--file-cache)
   4700                   (funcall (if noerror #'message #'user-error)
   4701                            "Unable to fetch file from %S"
   4702                            file)
   4703                   nil))
   4704             (error (if noerror
   4705                        (message "Org couldn't download \"%s\": %s %S" file (car error) (cdr error))
   4706                      (signal (car error) (cdr error)))))
   4707         (funcall (if noerror #'message #'user-error)
   4708                  "The remote resource %S is considered unsafe, and will not be downloaded."
   4709                  file)))
   4710      (t
   4711       (with-temp-buffer
   4712         (condition-case nil
   4713 	    (progn
   4714 	      (insert-file-contents file)
   4715 	      (buffer-string))
   4716 	  (file-error
   4717            (funcall (if noerror #'message #'user-error)
   4718 		    "Unable to read file %S"
   4719 		    file)
   4720 	   nil)))))))
   4721 
   4722 (defun org--should-fetch-remote-resource-p (uri)
   4723   "Return non-nil if the URI should be fetched."
   4724   (or (eq org-resource-download-policy t)
   4725       (org--safe-remote-resource-p uri)
   4726       (and (eq org-resource-download-policy 'prompt)
   4727            (org--confirm-resource-safe uri))))
   4728 
   4729 (defun org--safe-remote-resource-p (uri)
   4730   "Return non-nil if URI is considered safe.
   4731 This checks every pattern in `org-safe-remote-resources', and
   4732 returns non-nil if any of them match."
   4733   (let ((uri-patterns org-safe-remote-resources)
   4734         (file-uri (and (buffer-file-name (buffer-base-buffer))
   4735                        (concat "file://" (file-truename (buffer-file-name (buffer-base-buffer))))))
   4736         match-p)
   4737     (while (and (not match-p) uri-patterns)
   4738       (setq match-p (or (string-match-p (car uri-patterns) uri)
   4739                         (and file-uri (string-match-p (car uri-patterns) file-uri)))
   4740             uri-patterns (cdr uri-patterns)))
   4741     match-p))
   4742 
   4743 (defun org--confirm-resource-safe (uri)
   4744   "Ask the user if URI should be considered safe, returning non-nil if so."
   4745   (unless noninteractive
   4746     (let ((current-file (and (buffer-file-name (buffer-base-buffer))
   4747                              (file-truename (buffer-file-name (buffer-base-buffer)))))
   4748           (domain (and (string-match
   4749                         (rx (seq "http" (? "s") "://")
   4750                             (optional (+ (not (any "@/\n"))) "@")
   4751                             (optional "www.")
   4752                             (one-or-more (not (any ":/?\n"))))
   4753                         uri)
   4754                        (match-string 0 uri)))
   4755           (buf (get-buffer-create "*Org Remote Resource*")))
   4756       ;; Set up the contents of the *Org Remote Resource* buffer.
   4757       (with-current-buffer buf
   4758         (erase-buffer)
   4759         (insert "An org-mode document would like to download "
   4760                 (propertize uri 'face '(:inherit org-link :weight normal))
   4761                 ", which is not considered safe.\n\n"
   4762                 "Do you want to download this?  You can type\n "
   4763                 (propertize "!" 'face 'success)
   4764                 " to download this resource, and permanently mark it as safe.\n "
   4765                 (if domain
   4766                     (concat
   4767                      (propertize "d" 'face 'success)
   4768                      " to download this resource, and mark the domain ("
   4769                      (propertize domain 'face '(:inherit org-link :weight normal))
   4770                      ") as safe.\n ")
   4771                   "")
   4772                 (if current-file
   4773                     (concat
   4774                      (propertize "f" 'face 'success)
   4775                      " to download this resource, and permanently mark all resources in "
   4776                      (propertize current-file 'face 'underline)
   4777                      " as safe.\n ")
   4778                   "")
   4779                 (propertize "y" 'face 'warning)
   4780                 " to download this resource, just this once.\n "
   4781                 (propertize "n" 'face 'error)
   4782                 " to skip this resource.\n")
   4783         (setq-local cursor-type nil)
   4784         (set-buffer-modified-p nil)
   4785         (goto-char (point-min)))
   4786       ;; Display the buffer and read a choice.
   4787       (save-window-excursion
   4788         (pop-to-buffer buf)
   4789         (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
   4790                (prompt (format "Please type y, n%s, d, or !%s: "
   4791                                (if current-file ", f" "")
   4792                                (if (< (line-number-at-pos (point-max))
   4793                                       (window-body-height))
   4794                                    ""
   4795                                  ", or C-v/M-v to scroll")))
   4796                char)
   4797           (setq char (read-char-choice prompt exit-chars))
   4798           (when (memq char '(?! ?f ?d))
   4799             (customize-push-and-save
   4800              'org-safe-remote-resources
   4801              (list (if (eq char ?d)
   4802                        (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
   4803                      (concat "\\`"
   4804                              (regexp-quote
   4805                               (if (and (= char ?f) current-file)
   4806                                   (concat "file://" current-file) uri))
   4807                              "\\'")))))
   4808           (prog1 (memq char '(?y ?! ?d ?\s ?f))
   4809             (quit-window t)))))))
   4810 
   4811 (defun org-extract-log-state-settings (x)
   4812   "Extract the log state setting from a TODO keyword string.
   4813 This will extract info from a string like \"WAIT(w@/!)\"."
   4814   (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
   4815     (let ((kw (match-string 1 x))
   4816 	  (log1 (and (match-end 3) (match-string 3 x)))
   4817 	  (log2 (and (match-end 4) (match-string 4 x))))
   4818       (and (or log1 log2)
   4819 	   (list kw
   4820 		 (and log1 (if (equal log1 "!") 'time 'note))
   4821 		 (and log2 (if (equal log2 "!") 'time 'note)))))))
   4822 
   4823 (defun org-remove-keyword-keys (list)
   4824   "Remove a pair of parenthesis at the end of each string in LIST."
   4825   (mapcar (lambda (x)
   4826 	    (if (string-match "(.*)$" x)
   4827 		(substring x 0 (match-beginning 0))
   4828 	      x))
   4829 	  list))
   4830 
   4831 (defun org-assign-fast-keys (alist)
   4832   "Assign fast keys to a keyword-key alist.
   4833 Respect keys that are already there."
   4834   (let (new e (alt ?0))
   4835     (while (setq e (pop alist))
   4836       (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
   4837 	      (cdr e)) ;; Key already assigned.
   4838 	  (push e new)
   4839 	(let ((clist (string-to-list (downcase (car e))))
   4840 	      (used (append new alist)))
   4841 	  (when (= (car clist) ?@)
   4842 	    (pop clist))
   4843 	  (while (and clist (rassoc (car clist) used))
   4844 	    (pop clist))
   4845 	  (unless clist
   4846 	    (while (rassoc alt used)
   4847 	      (cl-incf alt)))
   4848 	  (push (cons (car e) (or (car clist) alt)) new))))
   4849     (nreverse new)))
   4850 
   4851 ;;; Some variables used in various places
   4852 
   4853 (defvar org-window-configuration nil
   4854   "Used in various places to store a window configuration.")
   4855 (defvar org-selected-window nil
   4856   "Used in various places to store a window configuration.")
   4857 (defvar org-finish-function nil
   4858   "Function to be called when \\`C-c C-c' is used.
   4859 This is for getting out of special buffers like capture.")
   4860 (defvar org-last-state)
   4861 
   4862 ;; Defined somewhere in this file, but used before definition.
   4863 (defvar org-entities)     ;; defined in org-entities.el
   4864 (defvar org-struct-menu)
   4865 (defvar org-org-menu)
   4866 (defvar org-tbl-menu)
   4867 
   4868 ;;;; Define the Org mode
   4869 
   4870 (defun org-before-change-function (_beg _end)
   4871   "Every change indicates that a table might need an update."
   4872   (setq org-table-may-need-update t))
   4873 (defvar org-mode-map)
   4874 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
   4875 (defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
   4876 (defvar org-inhibit-logging nil)        ; Dynamically-scoped param.
   4877 (defvar org-inhibit-blocking nil)       ; Dynamically-scoped param.
   4878 
   4879 (defvar bidi-paragraph-direction)
   4880 (defvar buffer-face-mode-face)
   4881 
   4882 (require 'outline)
   4883 
   4884 ;; Other stuff we need.
   4885 (require 'time-date)
   4886 (when (< emacs-major-version 28)  ; preloaded in Emacs 28
   4887   (require 'easymenu))
   4888 
   4889 (require 'org-entities)
   4890 (require 'org-faces)
   4891 (require 'org-list)
   4892 (require 'org-pcomplete)
   4893 (require 'org-src)
   4894 (require 'org-footnote)
   4895 (require 'org-macro)
   4896 
   4897 ;; babel
   4898 (require 'ob)
   4899 
   4900 (defvar org-element-cache-version); Defined in org-element.el
   4901 (defvar org-element-cache-persistent); Defined in org-element.el
   4902 (defvar org-element-use-cache); Defined in org-element.el
   4903 (defvar org-mode-loading nil
   4904   "Non-nil during Org mode initialization.")
   4905 
   4906 (defvar org-agenda-file-menu-enabled t
   4907   "When non-nil, refresh Agenda files in Org menu when loading Org.")
   4908 
   4909 (defvar org-mode-syntax-table
   4910   (let ((st (make-syntax-table outline-mode-syntax-table)))
   4911     (modify-syntax-entry ?\" "\"" st)
   4912     (modify-syntax-entry ?\\ "_" st)
   4913     (modify-syntax-entry ?~ "_" st)
   4914     (modify-syntax-entry ?< "(>" st)
   4915     (modify-syntax-entry ?> ")<" st)
   4916     st)
   4917   "Standard syntax table for Org mode buffers.")
   4918 
   4919 (defvar org-mode-tags-syntax-table
   4920   (let ((st (make-syntax-table org-mode-syntax-table)))
   4921     (modify-syntax-entry ?@ "w" st)
   4922     (modify-syntax-entry ?_ "w" st)
   4923     st)
   4924   "Syntax table including \"@\" and \"_\" as word constituents.")
   4925 
   4926 ;;;###autoload
   4927 (define-derived-mode org-mode outline-mode "Org"
   4928   "Outline-based notes management and organizer, alias
   4929 \"Carsten's outline-mode for keeping track of everything.\"
   4930 
   4931 Org mode develops organizational tasks around a NOTES file which
   4932 contains information about projects as plain text.  Org mode is
   4933 implemented on top of Outline mode, which is ideal to keep the content
   4934 of large files well structured.  It supports ToDo items, deadlines and
   4935 time stamps, which magically appear in the diary listing of the Emacs
   4936 calendar.  Tables are easily created with a built-in table editor.
   4937 Plain text URL-like links connect to websites, emails (VM), Usenet
   4938 messages (Gnus), BBDB entries, and any files related to the project.
   4939 For printing and sharing of notes, an Org file (or a part of it)
   4940 can be exported as a structured ASCII or HTML file.
   4941 
   4942 The following commands are available:
   4943 
   4944 \\{org-mode-map}"
   4945   (setq-local org-mode-loading t)
   4946   ;; Force tab width - indentation is significant in lists, so we need
   4947   ;; to make sure that it is consistent across configurations.
   4948   (setq-local tab-width 8)
   4949   (org-load-modules-maybe)
   4950   (when org-agenda-file-menu-enabled
   4951     (org-install-agenda-files-menu))
   4952   (setq-local outline-regexp org-outline-regexp)
   4953   (setq-local outline-level 'org-outline-level)
   4954   ;; Initialize cache.
   4955   (org-element-cache-reset)
   4956   (when (and org-element-cache-persistent
   4957              org-element-use-cache)
   4958     (org-persist-load
   4959      `((elisp org-element--cache) (version ,org-element-cache-version))
   4960      (current-buffer)
   4961      'match-hash :read-related t))
   4962   (org-set-regexps-and-options)
   4963   (add-to-invisibility-spec '(org-link))
   4964   (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
   4965                            "..."))
   4966   (make-local-variable 'org-link-descriptive)
   4967   (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
   4968   (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
   4969     (unless org-display-table
   4970       (setq org-display-table (make-display-table)))
   4971     (set-display-table-slot
   4972      org-display-table 4
   4973      (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
   4974 		      org-ellipsis)))
   4975     (setq buffer-display-table org-display-table))
   4976   (org-set-font-lock-defaults)
   4977   (when (and org-tag-faces (not org-tags-special-faces-re))
   4978     ;; tag faces set outside customize.... force initialization.
   4979     (org-set-tag-faces 'org-tag-faces org-tag-faces))
   4980   ;; Calc embedded
   4981   (setq-local calc-embedded-open-mode "# ")
   4982   ;; Set syntax table.  Ensure that buffer-local changes to the syntax
   4983   ;; table do not affect other Org buffers.
   4984   (set-syntax-table (make-syntax-table org-mode-syntax-table))
   4985   (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
   4986   ;; Activate before-change-function
   4987   (setq-local org-table-may-need-update t)
   4988   (add-hook 'before-change-functions 'org-before-change-function nil 'local)
   4989   ;; Check for running clock before killing a buffer
   4990   (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
   4991   ;; Check for invisible edits.
   4992   (org-fold--advice-edit-commands)
   4993   ;; Initialize macros templates.
   4994   (org-macro-initialize-templates)
   4995   ;; Initialize radio targets.
   4996   (org-update-radio-target-regexp)
   4997   ;; Indentation.
   4998   (setq-local indent-line-function 'org-indent-line)
   4999   (setq-local indent-region-function 'org-indent-region)
   5000   ;; Filling and auto-filling.
   5001   (org-setup-filling)
   5002   ;; Comments.
   5003   (org-setup-comments-handling)
   5004   ;; Beginning/end of defun
   5005   (setq-local beginning-of-defun-function 'org-backward-element)
   5006   (setq-local end-of-defun-function
   5007 	      (lambda ()
   5008 		(if (not (org-at-heading-p))
   5009 		    (org-forward-element)
   5010 		  (org-forward-element)
   5011 		  (forward-char -1))))
   5012   ;; Next error for sparse trees
   5013   (setq-local next-error-function 'org-occur-next-match)
   5014   ;; Make commit log messages from Org documents easier.
   5015   (setq-local add-log-current-defun-function #'org-add-log-current-headline)
   5016   ;; Make sure dependence stuff works reliably, even for users who set it
   5017   ;; too late :-(
   5018   (if org-enforce-todo-dependencies
   5019       (add-hook 'org-blocker-hook
   5020 		'org-block-todo-from-children-or-siblings-or-parent)
   5021     (remove-hook 'org-blocker-hook
   5022 		 'org-block-todo-from-children-or-siblings-or-parent))
   5023   (if org-enforce-todo-checkbox-dependencies
   5024       (add-hook 'org-blocker-hook
   5025 		'org-block-todo-from-checkboxes)
   5026     (remove-hook 'org-blocker-hook
   5027 		 'org-block-todo-from-checkboxes))
   5028 
   5029   ;; Align options lines
   5030   (setq-local
   5031    align-mode-rules-list
   5032    '((org-in-buffer-settings
   5033       (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
   5034       (modes . '(org-mode)))))
   5035 
   5036   ;; Setup the pcomplete hooks
   5037   (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
   5038   (setq-local pcomplete-command-name-function #'org-command-at-point)
   5039   (setq-local pcomplete-default-completion-function #'ignore)
   5040   (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
   5041   (setq-local pcomplete-termination-string "")
   5042   (add-hook 'completion-at-point-functions
   5043             #'pcomplete-completions-at-point nil t)
   5044   (setq-local buffer-face-mode-face 'org-default)
   5045 
   5046   ;; `thing-at-point' support
   5047   (when (boundp 'thing-at-point-provider-alist)
   5048     (setq-local thing-at-point-provider-alist
   5049                 (cons '(url . org--link-at-point)
   5050                       thing-at-point-provider-alist)))
   5051   (when (boundp 'forward-thing-provider-alist)
   5052     (setq-local forward-thing-provider-alist
   5053                 (cons '(url . org-next-link)
   5054                       forward-thing-provider-alist)))
   5055   (when (boundp 'bounds-of-thing-at-point-provider-alist)
   5056     (setq-local bounds-of-thing-at-point-provider-alist
   5057                 (cons '(url . org--bounds-of-link-at-point)
   5058                       bounds-of-thing-at-point-provider-alist)))
   5059 
   5060   ;; If empty file that did not turn on Org mode automatically, make
   5061   ;; it to.
   5062   (when (and org-insert-mode-line-in-empty-file
   5063 	     (called-interactively-p 'any)
   5064 	     (= (point-min) (point-max)))
   5065     (insert "#    -*- mode: org -*-\n\n"))
   5066   (unless org-inhibit-startup
   5067     (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
   5068       (org-table-map-tables
   5069        (cond ((and org-startup-align-all-tables
   5070 		   org-startup-shrink-all-tables)
   5071 	      (lambda () (org-table-align) (org-table-shrink)))
   5072 	     (org-startup-align-all-tables #'org-table-align)
   5073 	     (t #'org-table-shrink))
   5074        t))
   5075     ;; Suppress modification hooks to speed up the startup.
   5076     ;; However, do it only when text properties/overlays, but not
   5077     ;; buffer text are actually modified.  We still need to track text
   5078     ;; modifications to make cache updates work reliably.
   5079     (org-unmodified
   5080      (when org-startup-with-beamer-mode (org-beamer-mode))
   5081      (when org-startup-with-inline-images (org-display-inline-images))
   5082      (when org-startup-with-latex-preview (org-latex-preview '(16)))
   5083      (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
   5084      (when org-startup-truncated (setq truncate-lines t))
   5085      (when org-startup-numerated (require 'org-num) (org-num-mode 1))
   5086      (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
   5087 
   5088   ;; Add a custom keymap for `visual-line-mode' so that activating
   5089   ;; this minor mode does not override Org's keybindings.
   5090   ;; FIXME: Probably `visual-line-mode' should take care of this.
   5091   (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
   5092         (newmap (make-sparse-keymap)))
   5093     (set-keymap-parent newmap oldmap)
   5094     (define-key newmap [remap move-beginning-of-line] nil)
   5095     (define-key newmap [remap move-end-of-line] nil)
   5096     (define-key newmap [remap kill-line] nil)
   5097     (make-local-variable 'minor-mode-overriding-map-alist)
   5098     (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
   5099 
   5100   ;; Activate `org-table-header-line-mode'
   5101   (when org-table-header-line-p
   5102     (org-table-header-line-mode 1))
   5103   ;; Try to set `org-hide' face correctly.
   5104   (let ((foreground (org-find-invisible-foreground)))
   5105     (when foreground
   5106       (set-face-foreground 'org-hide foreground)))
   5107   ;; Set face extension as requested.
   5108   (org--set-faces-extend '(org-block-begin-line org-block-end-line)
   5109                          org-fontify-whole-block-delimiter-line)
   5110   (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
   5111   (setq-local org-mode-loading nil)
   5112 
   5113   ;; `yank-media' handler and DND support.
   5114   (org-setup-yank-dnd-handlers))
   5115 
   5116 ;; Update `customize-package-emacs-version-alist'
   5117 (add-to-list 'customize-package-emacs-version-alist
   5118 	     '(Org ("8.0" . "24.4")
   5119 		   ("8.1" . "24.4")
   5120 		   ("8.2" . "24.4")
   5121 		   ("8.2.7" . "24.4")
   5122 		   ("8.3" . "26.1")
   5123 		   ("9.0" . "26.1")
   5124 		   ("9.1" . "26.1")
   5125 		   ("9.2" . "27.1")
   5126 		   ("9.3" . "27.1")
   5127 		   ("9.4" . "27.2")
   5128 		   ("9.5" . "28.1")
   5129 		   ("9.6" . "29.1")
   5130                    ("9.7" . "30.1")))
   5131 
   5132 (defvar org-mode-transpose-word-syntax-table
   5133   (let ((st (make-syntax-table text-mode-syntax-table)))
   5134     (dolist (c org-emphasis-alist st)
   5135       (modify-syntax-entry (string-to-char (car c)) "w p" st))))
   5136 
   5137 (when (fboundp 'abbrev-table-put)
   5138   (abbrev-table-put org-mode-abbrev-table
   5139 		    :parents (list text-mode-abbrev-table)))
   5140 
   5141 (defun org-find-invisible-foreground ()
   5142   (let ((candidates (remove
   5143 		     "unspecified-bg"
   5144 		     (nconc
   5145 		      (list (face-background 'default)
   5146 			    (face-background 'org-default))
   5147 		      (mapcar
   5148 		       (lambda (alist)
   5149 			 (when (boundp alist)
   5150 			   (cdr (assq 'background-color (symbol-value alist)))))
   5151 		       '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
   5152 		      (list (face-foreground 'org-hide))))))
   5153     (car (remove nil candidates))))
   5154 
   5155 (defun org-current-time (&optional rounding-minutes past)
   5156   "Current time, possibly rounded to ROUNDING-MINUTES.
   5157 When ROUNDING-MINUTES is not an integer, fall back on the car of
   5158 `org-timestamp-rounding-minutes'.  When PAST is non-nil, ensure
   5159 the rounding returns a past time."
   5160   (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
   5161 	       (car org-timestamp-rounding-minutes)))
   5162 	(now (current-time)))
   5163     (if (< r 1)
   5164 	now
   5165       (let* ((time (decode-time now))
   5166 	     (res (org-encode-time
   5167                    (apply #'list
   5168                           0 (* r (round (nth 1 time) r))
   5169                           (nthcdr 2 time)))))
   5170 	(if (or (not past) (time-less-p res now))
   5171 	    res
   5172 	  (time-subtract res (* r 60)))))))
   5173 
   5174 (defun org-today ()
   5175   "Return today date, considering `org-extend-today-until'."
   5176   (time-to-days
   5177    (time-since (* 3600 org-extend-today-until))))
   5178 
   5179 ;;;; Font-Lock stuff, including the activators
   5180 
   5181 (defconst org-match-sexp-depth 3
   5182   "Number of stacked braces for sub/superscript matching.")
   5183 
   5184 (defun org-create-multibrace-regexp (left right n)
   5185   "Create a regular expression which will match a balanced sexp.
   5186 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
   5187 as single character strings.
   5188 The regexp returned will match the entire expression including the
   5189 delimiters.  It will also define a single group which contains the
   5190 match except for the outermost delimiters.  The maximum depth of
   5191 stacked delimiters is N.  Escaping delimiters is not possible."
   5192   (let* ((nothing (concat "[^" left right "]*?"))
   5193 	 (or "\\|")
   5194 	 (re nothing)
   5195 	 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
   5196     (while (> n 1)
   5197       (setq n (1- n)
   5198 	    re (concat re or next)
   5199 	    next (concat "\\(?:" nothing left next right "\\)+" nothing)))
   5200     (concat left "\\(" re "\\)" right)))
   5201 
   5202 (defconst org-match-substring-regexp
   5203   (concat
   5204    "\\(\\S-\\)\\([_^]\\)\\("
   5205    "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
   5206    "\\|"
   5207    "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
   5208    "\\|"
   5209    "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
   5210   "The regular expression matching a sub- or superscript.")
   5211 
   5212 (defconst org-match-substring-with-braces-regexp
   5213   (concat
   5214    "\\(\\S-\\)\\([_^]\\)"
   5215    "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
   5216   "The regular expression matching a sub- or superscript, forcing braces.")
   5217 
   5218 (defvar org-emph-face nil)
   5219 
   5220 (defconst org-nonsticky-props
   5221   '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
   5222 
   5223 (defsubst org-rear-nonsticky-at (pos)
   5224   (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
   5225 
   5226 (defun org-do-emphasis-faces (limit)
   5227   "Run through the buffer and emphasize strings."
   5228   (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
   5229 			  (car org-emphasis-regexp-components))))
   5230     (catch :exit
   5231       (while (re-search-forward quick-re limit t)
   5232 	(let* ((marker (match-string 2))
   5233 	       (verbatim? (member marker '("~" "="))))
   5234 	  (when (save-excursion
   5235 		  (goto-char (match-beginning 0))
   5236 		  (and
   5237 		   ;; Do not match table hlines.
   5238 		   (not (and (equal marker "+")
   5239 			     (org-match-line
   5240 			      "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
   5241 		   ;; Do not match headline stars.  Do not consider
   5242 		   ;; stars of a headline as closing marker for bold
   5243 		   ;; markup either.
   5244 		   (not (and (equal marker "*")
   5245 			     (save-excursion
   5246 			       (forward-char)
   5247 			       (skip-chars-backward "*")
   5248 			       (looking-at-p org-outline-regexp-bol))))
   5249 		   ;; Match full emphasis markup regexp.
   5250 		   (looking-at (if verbatim? org-verbatim-re org-emph-re))
   5251 		   ;; Do not span over paragraph boundaries.
   5252 		   (not (string-match-p org-element-paragraph-separate
   5253 					(match-string 2)))
   5254 		   ;; Do not span over cells in table rows.
   5255 		   (not (and (save-match-data (org-match-line "[ \t]*|"))
   5256 			     (string-match-p "|" (match-string 4))))))
   5257 	    (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
   5258 			(m (if org-hide-emphasis-markers 4 2)))
   5259 	      (font-lock-prepend-text-property
   5260 	       (match-beginning m) (match-end m) 'face face)
   5261 	      (when verbatim?
   5262 		(org-remove-flyspell-overlays-in
   5263 		 (match-beginning 0) (match-end 0))
   5264 		(remove-text-properties (match-beginning 2) (match-end 2)
   5265 					'(display t invisible t intangible t)))
   5266 	      (add-text-properties (match-beginning 2) (match-end 2)
   5267 				   '(font-lock-multiline t org-emphasis t))
   5268 	      (when (and org-hide-emphasis-markers
   5269 			 (not (org-at-comment-p)))
   5270 		(add-text-properties (match-end 4) (match-beginning 5)
   5271 				     '(invisible t))
   5272                 ;; https://orgmode.org/list/8b691a7f-6b62-d573-e5a8-80fac3dc9bc6@vodafonemail.de
   5273                 (org-rear-nonsticky-at (match-beginning 5))
   5274 		(add-text-properties (match-beginning 3) (match-end 3)
   5275 				     '(invisible t))
   5276                 ;; FIXME: This would break current behavior with point
   5277                 ;; being adjusted before hidden emphasis marker when
   5278                 ;; using M-b.  A proper fix would require custom
   5279                 ;; syntax function that will mark emphasis markers as
   5280                 ;; word constituents where appropriate.
   5281                 ;; https://orgmode.org/list/87edl41jf0.fsf@localhost
   5282                 ;; (org-rear-nonsticky-at (match-end 3))
   5283                 )
   5284 	      (throw :exit t))))))))
   5285 
   5286 (defun org-emphasize (&optional char)
   5287   "Insert or change an emphasis, i.e. a font like bold or italic.
   5288 If there is an active region, change that region to a new emphasis.
   5289 If there is no region, just insert the marker characters and position
   5290 the cursor between them.
   5291 CHAR should be the marker character.  If it is a space, it means to
   5292 remove the emphasis of the selected region.
   5293 If CHAR is not given (for example in an interactive call) it will be
   5294 prompted for."
   5295   (interactive)
   5296   (let ((erc org-emphasis-regexp-components)
   5297 	(string "") beg end move s)
   5298     (if (org-region-active-p)
   5299 	(setq beg (region-beginning)
   5300 	      end (region-end)
   5301 	      string (buffer-substring beg end))
   5302       (setq move t))
   5303 
   5304     (unless char
   5305       (message "Emphasis marker or tag: [%s]"
   5306 	       (mapconcat #'car org-emphasis-alist ""))
   5307       (setq char (read-char-exclusive)))
   5308     (if (equal char ?\s)
   5309 	(setq s ""
   5310 	      move nil)
   5311       (unless (assoc (char-to-string char) org-emphasis-alist)
   5312 	(user-error "No such emphasis marker: \"%c\"" char))
   5313       (setq s (char-to-string char)))
   5314     (while (and (> (length string) 1)
   5315 		(equal (substring string 0 1) (substring string -1))
   5316 		(assoc (substring string 0 1) org-emphasis-alist))
   5317       (setq string (substring string 1 -1)))
   5318     (setq string (concat s string s))
   5319     (when beg (delete-region beg end))
   5320     (unless (or (bolp)
   5321 		(string-match (concat "[" (nth 0 erc) "\n]")
   5322 			      (char-to-string (char-before (point)))))
   5323       (insert " "))
   5324     (unless (or (eobp)
   5325 		(string-match (concat "[" (nth 1 erc) "\n]")
   5326 			      (char-to-string (char-after (point)))))
   5327       (insert " ") (backward-char 1))
   5328     (insert string)
   5329     (and move (backward-char 1))))
   5330 
   5331 (defun org-activate-links (limit)
   5332   "Add link properties to links.
   5333 This includes angle, plain, and bracket links."
   5334   (catch :exit
   5335     (while (re-search-forward org-link-any-re limit t)
   5336       (let* ((start (match-beginning 0))
   5337 	     (end (match-end 0))
   5338 	     (visible-start (or (match-beginning 3) (match-beginning 2)))
   5339 	     (visible-end (or (match-end 3) (match-end 2)))
   5340 	     (style (cond ((eq ?< (char-after start)) 'angle)
   5341 			  ((eq ?\[ (char-after (1+ start))) 'bracket)
   5342 			  (t 'plain))))
   5343 	(when (and (memq style org-highlight-links)
   5344 		   ;; Do not span over paragraph boundaries.
   5345 		   (not (string-match-p org-element-paragraph-separate
   5346 				      (match-string 0)))
   5347 		   ;; Do not confuse plain links with tags.
   5348 		   (not (and (eq style 'plain)
   5349 			   (let ((face (get-text-property
   5350 					(max (1- start) (point-min)) 'face)))
   5351 			     (if (consp face) (memq 'org-tag face)
   5352 			       (eq 'org-tag face))))))
   5353 	  (let* ((link-object (save-excursion
   5354 				(goto-char start)
   5355 				(save-match-data (org-element-link-parser))))
   5356 		 (link (org-element-property :raw-link link-object))
   5357 		 (type (org-element-property :type link-object))
   5358 		 (path (org-element-property :path link-object))
   5359                  (face-property (pcase (org-link-get-parameter type :face)
   5360 				  ((and (pred functionp) face) (funcall face path))
   5361 				  ((and (pred facep) face) face)
   5362 				  ((and (pred consp) face) face) ;anonymous
   5363 				  (_ 'org-link)))
   5364 		 (properties		;for link's visible part
   5365 		  (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
   5366 					'highlight)
   5367 			'keymap (or (org-link-get-parameter type :keymap)
   5368 				    org-mouse-map)
   5369 			'help-echo (pcase (org-link-get-parameter type :help-echo)
   5370 				     ((and (pred stringp) echo) echo)
   5371 				     ((and (pred functionp) echo) echo)
   5372 				     (_ (concat "LINK: " link)))
   5373 			'htmlize-link (pcase (org-link-get-parameter type
   5374 								     :htmlize-link)
   5375 					((and (pred functionp) f) (funcall f))
   5376 					(_ `(:uri ,link)))
   5377 			'font-lock-multiline t)))
   5378 	    (org-remove-flyspell-overlays-in start end)
   5379 	    (org-rear-nonsticky-at end)
   5380 	    (if (not (eq 'bracket style))
   5381 		(progn
   5382                   (add-face-text-property start end face-property)
   5383 		  (add-text-properties start end properties))
   5384 	      ;; Handle invisible parts in bracket links.
   5385 	      (remove-text-properties start end '(invisible nil))
   5386 	      (let ((hidden
   5387                      (if org-link-descriptive
   5388 		         (append `(invisible
   5389 			           ,(or (org-link-get-parameter type :display)
   5390 				        'org-link))
   5391 			         properties)
   5392                        properties)))
   5393 		(add-text-properties start visible-start hidden)
   5394                 (add-face-text-property start end face-property)
   5395 		(add-text-properties visible-start visible-end properties)
   5396 		(add-text-properties visible-end end hidden)
   5397 		(org-rear-nonsticky-at visible-start)
   5398 		(org-rear-nonsticky-at visible-end)))
   5399 	    (let ((f (org-link-get-parameter type :activate-func)))
   5400 	      (when (functionp f)
   5401 		(funcall f start end path (eq style 'bracket))))
   5402 	    (throw :exit t)))))		;signal success
   5403     nil))
   5404 
   5405 (defun org-activate-code (limit)
   5406   (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
   5407     (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5408     (remove-text-properties (match-beginning 0) (match-end 0)
   5409 			    '(display t invisible t intangible t))
   5410     t))
   5411 
   5412 (defcustom org-src-fontify-natively t
   5413   "When non-nil, fontify code in code blocks.
   5414 See also the `org-block' face."
   5415   :type 'boolean
   5416   :version "26.1"
   5417   :package-version '(Org . "8.3")
   5418   :group 'org-appearance
   5419   :group 'org-babel)
   5420 
   5421 (defcustom org-allow-promoting-top-level-subtree nil
   5422   "When non-nil, allow promoting a top level subtree.
   5423 The leading star of the top level headline will be replaced
   5424 by a #."
   5425   :type 'boolean
   5426   :version "24.1"
   5427   :group 'org-appearance)
   5428 
   5429 (defun org-fontify-meta-lines-and-blocks (limit)
   5430   (condition-case-unless-debug nil
   5431       (org-fontify-meta-lines-and-blocks-1 limit)
   5432     (error (message "Org mode fontification error in %S at %d"
   5433 		    (current-buffer)
   5434 		    (line-number-at-pos)))))
   5435 
   5436 (defun org-fontify-meta-lines-and-blocks-1 (limit)
   5437   "Fontify #+ lines and blocks."
   5438   (let ((case-fold-search t))
   5439     (when (re-search-forward
   5440 	   (rx bol (group (zero-or-more (any " \t")) "#"
   5441 			  (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
   5442 					    (any " \t")
   5443 					    eol))
   5444 				 (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
   5445 			  (zero-or-more (any " \t"))
   5446 			  (group (group (zero-or-more (not (any " \t\n"))))
   5447 				 (zero-or-more (any " \t"))
   5448 				 (group (zero-or-more nonl)))))
   5449 	   limit t)
   5450       (let ((beg (match-beginning 0))
   5451 	    (end-of-beginline (match-end 0))
   5452 	    ;; Including \n at end of #+begin line will include \n
   5453 	    ;; after the end of block content.
   5454 	    (block-start (match-end 0))
   5455 	    (block-end nil)
   5456 	    (lang (match-string 7)) ; The language, if it is a source block.
   5457 	    (bol-after-beginline (line-beginning-position 2))
   5458 	    (dc1 (downcase (match-string 2)))
   5459 	    (dc3 (downcase (match-string 3)))
   5460 	    (whole-blockline org-fontify-whole-block-delimiter-line)
   5461 	    beg-of-endline end-of-endline nl-before-endline quoting block-type)
   5462 	(cond
   5463 	 ((and (match-end 4) (equal dc3 "+begin"))
   5464 	  ;; Truly a block
   5465 	  (setq block-type (downcase (match-string 5))
   5466 		;; Src, example, export, maybe more.
   5467 		quoting (member block-type org-protecting-blocks))
   5468 	  (when (re-search-forward
   5469 		 (rx-to-string `(group bol (or (seq (one-or-more "*") space)
   5470 					       (seq (zero-or-more (any " \t"))
   5471 						    "#+end"
   5472 						    ,(match-string 4)
   5473 						    word-end
   5474 						    (zero-or-more nonl)))))
   5475 		 ;; We look further than LIMIT on purpose.
   5476 		 nil t)
   5477 	    ;; We do have a matching #+end line.
   5478 	    (setq beg-of-endline (match-beginning 0)
   5479 		  end-of-endline (match-end 0)
   5480 		  nl-before-endline (1- (match-beginning 0)))
   5481 	    (setq block-end (match-beginning 0)) ; Include the final newline.
   5482 	    (when quoting
   5483 	      (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
   5484 	      (remove-text-properties beg end-of-endline
   5485 				      '(display t invisible t intangible t)))
   5486 	    (add-text-properties
   5487 	     beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
   5488 	    (org-remove-flyspell-overlays-in beg bol-after-beginline)
   5489 	    (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
   5490             (cond
   5491 	     ((and org-src-fontify-natively
   5492                    ;; Technically, according to the
   5493                    ;; `org-src-fontify-natively' docstring, we should
   5494                    ;; only fontify src blocks.  However, it is common
   5495                    ;; to use undocumented fontification of export and
   5496                    ;; example blocks. (The latter which do not support a
   5497                    ;; language specifier.) Keep this undocumented feature
   5498                    ;; for user convenience.
   5499                    (member block-type '("src" "export" "example")))
   5500 	      (save-match-data
   5501                 (org-src-font-lock-fontify-block (or lang "") block-start block-end))
   5502 	      (add-text-properties bol-after-beginline block-end '(src-block t)))
   5503 	     (quoting
   5504 	      (add-text-properties
   5505 	       bol-after-beginline beg-of-endline
   5506 	       (list 'face
   5507 		     (list :inherit
   5508 			   (let ((face-name
   5509 				  (intern (format "org-block-%s" lang))))
   5510 			     (append (and (facep face-name) (list face-name))
   5511 				     '(org-block)))))))
   5512 	     ((not org-fontify-quote-and-verse-blocks))
   5513 	     ((string= block-type "quote")
   5514 	      (add-face-text-property
   5515 	       bol-after-beginline beg-of-endline 'org-quote t))
   5516 	     ((string= block-type "verse")
   5517 	      (add-face-text-property
   5518 	       bol-after-beginline beg-of-endline 'org-verse t)))
   5519 	    ;; Fontify the #+begin and #+end lines of the blocks
   5520 	    (add-text-properties
   5521 	     beg (if whole-blockline bol-after-beginline end-of-beginline)
   5522 	     '(face org-block-begin-line))
   5523 	    (unless (eq (char-after beg-of-endline) ?*)
   5524 	      (add-text-properties
   5525 	       beg-of-endline
   5526 	       (if whole-blockline
   5527 		   (let ((beg-of-next-line (1+ end-of-endline)))
   5528 		     (min (point-max) beg-of-next-line))
   5529 		 (min (point-max) end-of-endline))
   5530 	       '(face org-block-end-line)))
   5531 	    t))
   5532 	 ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
   5533 	  (org-remove-flyspell-overlays-in
   5534 	   (match-beginning 0)
   5535 	   (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
   5536 	  (add-text-properties
   5537 	   beg (match-end 3)
   5538 	   (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
   5539 	       '(font-lock-fontified t invisible t)
   5540 	     '(font-lock-fontified t face org-document-info-keyword)))
   5541 	  (add-text-properties
   5542 	   (match-beginning 6) (min (point-max) (1+ (match-end 6)))
   5543 	   (if (string-equal dc1 "+title:")
   5544 	       '(font-lock-fontified t face org-document-title)
   5545 	     '(font-lock-fontified t face org-document-info))))
   5546 	 ((string-prefix-p "+caption" dc1)
   5547 	  (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
   5548 	  (remove-text-properties (match-beginning 0) (match-end 0)
   5549 				  '(display t invisible t intangible t))
   5550 	  ;; Handle short captions
   5551 	  (save-excursion
   5552 	    (forward-line 0)
   5553 	    (looking-at (rx (group (zero-or-more (any " \t"))
   5554 				   "#+caption"
   5555 				   (optional "[" (zero-or-more nonl) "]")
   5556 				   ":")
   5557 			    (zero-or-more (any " \t")))))
   5558 	  (add-text-properties (line-beginning-position) (match-end 1)
   5559 			       '(font-lock-fontified t face org-meta-line))
   5560 	  (add-text-properties (match-end 0) (line-end-position)
   5561 			       '(font-lock-fontified t face org-block))
   5562 	  t)
   5563 	 ((member dc3 '(" " ""))
   5564 	  ;; Just a comment, the plus was not there
   5565 	  (org-remove-flyspell-overlays-in beg (match-end 0))
   5566 	  (add-text-properties
   5567 	   beg (match-end 0)
   5568 	   '(font-lock-fontified t face font-lock-comment-face)))
   5569 	 (t ;; Just any other in-buffer setting, but not indented
   5570 	  (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5571 	  (remove-text-properties (match-beginning 0) (match-end 0)
   5572 				  '(display t invisible t intangible t))
   5573 	  (add-text-properties beg (match-end 0)
   5574 			       '(font-lock-fontified t face org-meta-line))
   5575 	  t))))))
   5576 
   5577 (defun org-fontify-drawers (limit)
   5578   "Fontify drawers."
   5579   (when (re-search-forward org-drawer-regexp limit t)
   5580     (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
   5581 			 '(font-lock-fontified t face org-drawer))
   5582     (org-remove-flyspell-overlays-in
   5583      (line-beginning-position) (line-beginning-position 2))
   5584     t))
   5585 
   5586 (defun org-fontify-macros (limit)
   5587   "Fontify macros."
   5588   (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
   5589     (let ((begin (match-beginning 0))
   5590 	  (opening-end (match-beginning 1)))
   5591       (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
   5592 		 (match-string 1))
   5593 	(let ((end (match-end 1))
   5594 	      (closing-start (match-beginning 1)))
   5595           (add-face-text-property begin end 'org-macro)
   5596 	  (add-text-properties
   5597 	   begin end
   5598 	   '(font-lock-multiline t font-lock-fontified t))
   5599 	  (org-remove-flyspell-overlays-in begin end)
   5600 	  (when org-hide-macro-markers
   5601 	    (add-text-properties begin opening-end '(invisible t))
   5602 	    (add-text-properties closing-start end '(invisible t)))
   5603 	  t)))))
   5604 
   5605 (defun org-fontify-extend-region (beg end _old-len)
   5606   (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
   5607                  (min (point-max) (1+ end))
   5608                ;; See `font-lock-extend-jit-lock-region-after-change' and bug#68849.
   5609                (min (point-max) (1+ end))))
   5610         (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
   5611 	(end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
   5612 	(extend
   5613          (lambda (r1 r2 dir)
   5614 	   (let ((re (replace-regexp-in-string
   5615                       "\\(begin\\|end\\)" r1
   5616 		      (replace-regexp-in-string
   5617                        "[][]" r2
   5618 		       (match-string-no-properties 0)))))
   5619 	     (re-search-forward (regexp-quote re) nil t dir)))))
   5620     (goto-char beg)
   5621     (back-to-indentation)
   5622     (save-match-data
   5623       (cond ((looking-at end-re)
   5624 	     (cons (or (funcall extend "begin" "[" -1) beg) end))
   5625 	    ((looking-at begin-re)
   5626 	     (cons beg (or (funcall extend "end" "]" 1) end)))
   5627 	    (t (cons beg end))))))
   5628 
   5629 (defun org-activate-footnote-links (limit)
   5630   "Add text properties for footnotes."
   5631   (let ((fn (org-footnote-next-reference-or-definition limit)))
   5632     (when fn
   5633       (let* ((beg (nth 1 fn))
   5634 	     (end (nth 2 fn))
   5635 	     (label (car fn))
   5636 	     (referencep (/= (line-beginning-position) beg)))
   5637 	(when (and referencep (nth 3 fn))
   5638 	  (save-excursion
   5639 	    (goto-char beg)
   5640 	    (search-forward (or label "fn:"))
   5641 	    (org-remove-flyspell-overlays-in beg (match-end 0))))
   5642         (add-face-text-property beg end 'org-footnote)
   5643 	(add-text-properties beg end
   5644 			     (list 'mouse-face 'highlight
   5645 				   'keymap org-mouse-map
   5646 				   'help-echo
   5647 				   (if referencep "Footnote reference"
   5648 				     "Footnote definition")
   5649 				   'font-lock-fontified t
   5650 				   'font-lock-multiline t))))))
   5651 
   5652 (defun org-activate-dates (limit)
   5653   "Add text properties for dates."
   5654   (when (and (re-search-forward org-tsr-regexp-both limit t)
   5655 	     (not (equal (char-before (match-beginning 0)) 91)))
   5656     (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5657     (add-text-properties (match-beginning 0) (match-end 0)
   5658 			 (list 'mouse-face 'highlight
   5659 			       'keymap org-mouse-map))
   5660     (org-rear-nonsticky-at (match-end 0))
   5661     (when org-display-custom-times
   5662       ;; If it's a date range, activate custom time for second date.
   5663       (when (match-end 3)
   5664 	(org-display-custom-time (match-beginning 3) (match-end 3)))
   5665       (org-display-custom-time (match-beginning 1) (match-end 1)))
   5666     t))
   5667 
   5668 (defun org-activate-target-links (limit)
   5669   "Add text properties for target matches."
   5670   (when org-target-link-regexp
   5671     (let ((case-fold-search t))
   5672       ;; `org-target-link-regexp' matches one character before the
   5673       ;; actual target.
   5674       (unless (bolp) (forward-char -1))
   5675       (when (if org-target-link-regexps
   5676                 (org--re-list-search-forward org-target-link-regexps limit t)
   5677               (re-search-forward org-target-link-regexp limit t))
   5678 	(org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
   5679 	(add-text-properties (match-beginning 1) (match-end 1)
   5680 			     (list 'mouse-face 'highlight
   5681 				   'keymap org-mouse-map
   5682 				   'help-echo "Radio target link"
   5683 				   'org-linked-text t))
   5684 	(org-rear-nonsticky-at (match-end 1))
   5685 	t))))
   5686 
   5687 (defvar org-latex-and-related-regexp nil
   5688   "Regular expression for highlighting LaTeX, entities and sub/superscript.")
   5689 
   5690 (defun org-compute-latex-and-related-regexp ()
   5691   "Compute regular expression for LaTeX, entities and sub/superscript.
   5692 Result depends on variable `org-highlight-latex-and-related'."
   5693   (let ((re-sub
   5694 	 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
   5695 	       ((eq org-use-sub-superscripts '{})
   5696 		(list org-match-substring-with-braces-regexp))
   5697 	       (org-use-sub-superscripts (list org-match-substring-regexp))))
   5698 	(re-latex
   5699 	 (when (or (memq 'latex org-highlight-latex-and-related)
   5700 		   (memq 'native org-highlight-latex-and-related))
   5701 	   (let ((matchers (plist-get org-format-latex-options :matchers)))
   5702 	     (delq nil
   5703 		   (mapcar (lambda (x)
   5704 			     (and (member (car x) matchers) (nth 1 x)))
   5705 			   org-latex-regexps)))))
   5706 	(re-entities
   5707 	 (when (memq 'entities org-highlight-latex-and-related)
   5708 	   (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
   5709 \\($\\|{}\\|[^[:alpha:]]\\)"))))
   5710     (setq-local org-latex-and-related-regexp
   5711 		(mapconcat #'identity
   5712 			   (append re-latex re-entities re-sub)
   5713 			   "\\|"))))
   5714 
   5715 (defun org-do-latex-and-related (limit)
   5716   "Highlight LaTeX snippets and environments, entities and sub/superscript.
   5717 Stop at first highlighted object, if any.  Return t if some
   5718 highlighting was done, nil otherwise."
   5719   (when (org-string-nw-p org-latex-and-related-regexp)
   5720     (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
   5721 	  (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
   5722       (catch 'found
   5723 	(while (and (< (point) limit)
   5724 		    (re-search-forward org-latex-and-related-regexp nil t))
   5725 	  (cond
   5726            ((>= (match-beginning 0) limit)
   5727 	    (throw 'found nil))
   5728 	   ((cl-some (lambda (f)
   5729 		       (memq f '(org-code org-verbatim underline
   5730 					  org-special-keyword)))
   5731 		     (save-excursion
   5732 		       (goto-char (1+ (match-beginning 0)))
   5733 		       (face-at-point nil t))))
   5734 	   ;; Try to limit false positives.  In this case, ignore
   5735 	   ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
   5736 	   ;; contain an empty line.
   5737 	   ((save-excursion
   5738 	      (goto-char (match-beginning 0))
   5739 	      (and (looking-at-p latex-prefix-re)
   5740 		   (save-match-data
   5741 		     (re-search-forward blank-line-re (1- (match-end 0)) t)))))
   5742 	   (t
   5743 	    (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
   5744 				     '(?_ ?^))
   5745 			       1
   5746 			     0))
   5747 		   (start (+ offset (match-beginning 0)))
   5748 		   (end (match-end 0)))
   5749 	      (if (memq 'native org-highlight-latex-and-related)
   5750 		  (org-src-font-lock-fontify-block "latex" start end)
   5751 		(font-lock-prepend-text-property start end
   5752 						 'face 'org-latex-and-related))
   5753 	      (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
   5754 				   '(font-lock-multiline t))
   5755 	      (throw 'found t)))))
   5756 	nil))))
   5757 
   5758 (defun org-restart-font-lock ()
   5759   "Restart `font-lock-mode', to force refontification."
   5760   (when font-lock-mode
   5761     (font-lock-mode -1)
   5762     (font-lock-mode 1)))
   5763 
   5764 (defun org-activate-tags (limit)
   5765   (when (re-search-forward org-tag-line-re limit t)
   5766     (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
   5767     (add-text-properties (match-beginning 1) (match-end 1)
   5768 			 (list 'mouse-face 'highlight
   5769 			       'keymap org-mouse-map))
   5770     (org-rear-nonsticky-at (match-end 1))
   5771     t))
   5772 
   5773 (defun org-activate-folds (limit)
   5774   "Arrange trailing newlines after folds to inherit face before the fold."
   5775   (let ((next-unfolded-newline (search-forward "\n" limit 'move)))
   5776     (while (and next-unfolded-newline (org-fold-folded-p) (not (eobp)))
   5777       (goto-char (org-fold-core-next-visibility-change nil limit))
   5778       (setq next-unfolded-newline (search-forward "\n" limit 'move)))
   5779     (when next-unfolded-newline
   5780       (org-with-wide-buffer
   5781        (when (and (> (match-beginning 0) (point-min))
   5782                   (org-fold-folded-p (1- (match-beginning 0))))
   5783          (put-text-property
   5784           (match-beginning 0) (match-end 0)
   5785           'face
   5786           (get-text-property
   5787            (org-fold-previous-visibility-change
   5788             (1- (match-beginning 0)))
   5789            'face)))
   5790        t))))
   5791 
   5792 (defun org-outline-level ()
   5793   "Compute the outline level of the heading at point.
   5794 
   5795 If this is called at a normal headline, the level is the number
   5796 of stars.  Use `org-reduced-level' to remove the effect of
   5797 `org-odd-levels-only'.  Unlike `org-current-level', this function
   5798 takes into consideration inlinetasks."
   5799   (org-with-wide-buffer
   5800    (end-of-line)
   5801    (if (re-search-backward org-outline-regexp-bol nil t)
   5802        (1- (- (match-end 0) (match-beginning 0)))
   5803      0)))
   5804 
   5805 (defvar org-font-lock-keywords nil)
   5806 
   5807 (defsubst org-re-property (property &optional literal allow-null value)
   5808   "Return a regexp matching a PROPERTY line.
   5809 
   5810 When optional argument LITERAL is non-nil, do not quote PROPERTY.
   5811 This is useful when PROPERTY is a regexp.  When ALLOW-NULL is
   5812 non-nil, match properties even without a value.
   5813 
   5814 Match group 3 is set to the value when it exists.  If there is no
   5815 value and ALLOW-NULL is non-nil, it is set to the empty string.
   5816 
   5817 With optional argument VALUE, match only property lines with
   5818 that value; in this case, ALLOW-NULL is ignored.  VALUE is quoted
   5819 unless LITERAL is non-nil."
   5820   (concat
   5821    "^\\(?4:[ \t]*\\)"
   5822    (format "\\(?1::\\(?2:%s\\):\\)"
   5823 	   (if literal property (regexp-quote property)))
   5824    (cond (value
   5825 	  (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
   5826 		  (if literal value (regexp-quote value))))
   5827 	 (allow-null
   5828 	  "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
   5829 	 (t
   5830 	  "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
   5831 
   5832 (defconst org-property-re
   5833   (org-re-property "\\S-+" 'literal t)
   5834   "Regular expression matching a property line.
   5835 There are four matching groups:
   5836 1: :PROPKEY: including the leading and trailing colon,
   5837 2: PROPKEY without the leading and trailing colon,
   5838 3: PROPVAL without leading or trailing spaces,
   5839 4: the indentation of the current line,
   5840 5: trailing whitespace.")
   5841 
   5842 (defvar org-font-lock-hook nil
   5843   "Functions to be called for special font lock stuff.")
   5844 
   5845 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
   5846 
   5847 (defvar org-font-lock-set-keywords-hook nil
   5848   "Functions that can manipulate `org-font-lock-extra-keywords'.
   5849 This is called after `org-font-lock-extra-keywords' is defined, but before
   5850 it is installed to be used by font lock.  This can be useful if something
   5851 needs to be inserted at a specific position in the font-lock sequence.")
   5852 
   5853 (defun org-font-lock-hook (limit)
   5854   "Run `org-font-lock-hook' within LIMIT."
   5855   (run-hook-with-args 'org-font-lock-hook limit))
   5856 
   5857 (defun org-set-font-lock-defaults ()
   5858   "Set font lock defaults for the current buffer."
   5859   (let ((org-font-lock-extra-keywords
   5860          ;; As a general rule, we apply the element (container) faces
   5861          ;; first and then prepend the object faces on top.
   5862 	 (list
   5863 	  ;; Call the hook
   5864 	  '(org-font-lock-hook)
   5865 	  ;; Headlines
   5866 	  `(,(if org-fontify-whole-heading-line
   5867 		 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
   5868 	       "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
   5869 	    (1 (org-get-level-face 1))
   5870 	    (2 (org-get-level-face 2))
   5871 	    (3 (org-get-level-face 3)))
   5872 	  ;; Table lines
   5873 	  '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)\n?"
   5874             (0 'org-table-row t)
   5875 	    (1 'org-table t))
   5876 	  ;; Table internals
   5877 	  '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
   5878 	  '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
   5879 	  '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
   5880 	  '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
   5881 	  ;; Properties
   5882 	  (list org-property-re
   5883 		'(1 'org-special-keyword t)
   5884 		'(3 'org-property-value t))
   5885 	  ;; Drawer boundaries.
   5886 	  '(org-fontify-drawers)
   5887 	  ;; Diary sexps.
   5888 	  '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
   5889 	  ;; Link related fontification.
   5890 	  '(org-activate-links) ; `org-activate-links' prepends faces
   5891 	  (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
   5892 	  (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link prepend)))
   5893 	  (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date prepend)))
   5894           ;; `org-activate-footnote-links' prepends faces
   5895 	  (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
   5896           ;; Targets.
   5897           (list org-radio-target-regexp '(0 'org-target prepend))
   5898 	  (list org-target-regexp '(0 'org-target prepend))
   5899 	  ;; Macro
   5900 	  '(org-fontify-macros) ; `org-fontify-macro' pepends faces
   5901 	  ;; TODO keyword
   5902 	  (list (format org-heading-keyword-regexp-format
   5903 			org-todo-regexp)
   5904 		'(2 (org-get-todo-face 2) prepend))
   5905 	  ;; TODO
   5906 	  (when org-fontify-todo-headline
   5907 	    (list (format org-heading-keyword-regexp-format
   5908 			  (concat
   5909 			   "\\(?:"
   5910 			   (mapconcat 'regexp-quote org-not-done-keywords "\\|")
   5911 			   "\\)"))
   5912 		  '(2 'org-headline-todo prepend)))
   5913 	  ;; DONE
   5914 	  (when org-fontify-done-headline
   5915 	    (list (format org-heading-keyword-regexp-format
   5916 			  (concat
   5917 			   "\\(?:"
   5918 			   (mapconcat 'regexp-quote org-done-keywords "\\|")
   5919 			   "\\)"))
   5920 		  '(2 'org-headline-done prepend)))
   5921 	  ;; Priorities
   5922           ;; `org-font-lock-add-priority-faces' prepends faces
   5923 	  '(org-font-lock-add-priority-faces)
   5924 	  ;; Tags
   5925           ;; `org-font-lock-add-tag-faces' prepends faces
   5926 	  '(org-font-lock-add-tag-faces)
   5927 	  ;; Tags groups
   5928 	  (when (and org-group-tags org-tag-groups-alist)
   5929 	    (list (concat org-outline-regexp-bol ".+\\(:"
   5930 			  (regexp-opt (mapcar 'car org-tag-groups-alist))
   5931 			  ":\\).*$")
   5932 		  '(1 'org-tag-group prepend)))
   5933 	  ;; Special keywords (as a part of planning)
   5934 	  (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
   5935 	  (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
   5936 	  (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
   5937 	  (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
   5938 	  ;; Emphasis
   5939           ;; `org-do-emphasis-faces' prepends faces
   5940 	  (when org-fontify-emphasized-text '(org-do-emphasis-faces))
   5941 	  ;; Checkboxes
   5942 	  `(,org-list-full-item-re 3 'org-checkbox prepend lax)
   5943 	  (when (cdr (assq 'checkbox org-list-automatic-rules))
   5944 	    '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
   5945 	      (0 (org-get-checkbox-statistics-face) prepend)))
   5946 	  ;; Description list items
   5947           '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
   5948 	    1 'org-list-dt prepend)
   5949           ;; Inline export snippets
   5950           '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
   5951             (1 'font-lock-comment-face prepend)
   5952             (2 'org-tag prepend)
   5953             (3 'font-lock-comment-face prepend))
   5954 	  ;; ARCHIVEd headings
   5955 	  (list (concat
   5956 		 org-outline-regexp-bol
   5957 		 "\\(.*:" org-archive-tag ":.*\\)")
   5958 		'(1 'org-archived prepend))
   5959 	  ;; Specials
   5960 	  '(org-do-latex-and-related) ; prepends faces
   5961 	  '(org-fontify-entities) ; applies composition
   5962 	  '(org-raise-scripts) ; applies display
   5963 	  ;; Code
   5964 	  '(org-activate-code (1 'org-code prepend))
   5965 	  ;; Blocks and meta lines
   5966           ;; Their face is an override - keywords, affiliated
   5967           ;; keywords, blocks, and block boundaries are all
   5968           ;; containers or part of container-only markup.
   5969 	  '(org-fontify-meta-lines-and-blocks)
   5970           ;; `org-fontify-inline-src-blocks' prepends object boundary
   5971           ;; faces and overrides native faces.
   5972           '(org-fontify-inline-src-blocks)
   5973           ;; Citations.  When an activate processor is specified, if
   5974           ;; specified, try loading it beforehand.
   5975           (progn
   5976             (unless (null org-cite-activate-processor)
   5977               (org-cite-try-load-processor org-cite-activate-processor))
   5978             ;; prepends faces
   5979             '(org-cite-activate))
   5980 	  ;; COMMENT
   5981           ;; Apply this last, after all the markup is highlighted, so
   5982           ;; that even "bright" markup will become dim.
   5983 	  (list (format
   5984 		 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
   5985 		 org-todo-regexp
   5986 		 org-comment-string)
   5987 		'(9 'org-special-keyword prepend))
   5988           '(org-activate-folds))))
   5989     (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
   5990     (run-hooks 'org-font-lock-set-keywords-hook)
   5991     ;; Now set the full font-lock-keywords
   5992     (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
   5993     (setq-local font-lock-defaults
   5994 		'(org-font-lock-keywords t nil nil backward-paragraph))
   5995     (setq-local font-lock-extend-after-change-region-function
   5996 		#'org-fontify-extend-region)
   5997     (kill-local-variable 'font-lock-keywords)
   5998     nil))
   5999 
   6000 (defun org-toggle-pretty-entities ()
   6001   "Toggle the composition display of entities as UTF8 characters."
   6002   (interactive)
   6003   (setq-local org-pretty-entities (not org-pretty-entities))
   6004   (org-restart-font-lock)
   6005   (if org-pretty-entities
   6006       (message "Entities are now displayed as UTF8 characters")
   6007     (save-restriction
   6008       (widen)
   6009       (decompose-region (point-min) (point-max))
   6010       (message "Entities are now displayed as plain text"))))
   6011 
   6012 (defvar-local org-custom-properties-overlays nil
   6013   "List of overlays used for custom properties.")
   6014 ;; Preserve when switching modes or when restarting Org.
   6015 (put 'org-custom-properties-overlays 'permanent-local t)
   6016 
   6017 (defun org-toggle-custom-properties-visibility ()
   6018   "Display or hide properties in `org-custom-properties'."
   6019   (interactive)
   6020   (if org-custom-properties-overlays
   6021       (progn (mapc #'delete-overlay org-custom-properties-overlays)
   6022 	     (setq org-custom-properties-overlays nil))
   6023     (when org-custom-properties
   6024       (org-with-wide-buffer
   6025        (goto-char (point-min))
   6026        (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
   6027 	 (while (re-search-forward regexp nil t)
   6028 	   (let ((end (cdr (save-match-data (org-get-property-block)))))
   6029 	     (when (and end (< (point) end))
   6030 	       ;; Hide first custom property in current drawer.
   6031 	       (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
   6032 		 (overlay-put o 'invisible t)
   6033 		 (overlay-put o 'org-custom-property t)
   6034 		 (push o org-custom-properties-overlays))
   6035 	       ;; Hide additional custom properties in the same drawer.
   6036 	       (while (re-search-forward regexp end t)
   6037 		 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
   6038 		   (overlay-put o 'invisible t)
   6039 		   (overlay-put o 'org-custom-property t)
   6040 		   (push o org-custom-properties-overlays)))))
   6041 	   ;; Each entry is limited to a single property drawer.
   6042 	   (outline-next-heading)))))))
   6043 
   6044 (defun org-fontify-entities (limit)
   6045   "Find an entity to fontify."
   6046   (let (ee)
   6047     (when org-pretty-entities
   6048       (catch 'match
   6049 	;; "\_ "-family is left out on purpose.  Only the first one,
   6050 	;; i.e., "\_ ", could be fontified anyway, and it would be
   6051 	;; confusing when adding a second white space character.
   6052 	(while (re-search-forward
   6053 		"\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
   6054 		limit t)
   6055 	  (when (and (not (org-at-comment-p))
   6056 		     (setq ee (org-entity-get (match-string 1)))
   6057 		     (= (length (nth 6 ee)) 1))
   6058 	    (let* ((end (if (equal (match-string 2) "{}")
   6059 			    (match-end 2)
   6060 			  (match-end 1))))
   6061 	      (add-text-properties
   6062 	       (match-beginning 0) end
   6063 	       (list 'font-lock-fontified t))
   6064 	      (compose-region (match-beginning 0) end
   6065 			      (nth 6 ee) nil)
   6066 	      (backward-char 1)
   6067 	      (throw 'match t))))
   6068 	nil))))
   6069 
   6070 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
   6071   "Fontify string S like in Org mode."
   6072   (with-temp-buffer
   6073     (insert s)
   6074     (let ((org-odd-levels-only odd-levels))
   6075       (org-mode)
   6076       (font-lock-ensure)
   6077       (if org-link-descriptive
   6078           (org-link-display-format
   6079            (buffer-string))
   6080         (buffer-string)))))
   6081 
   6082 (defun org-get-level-face (n)
   6083   "Get the right face for match N in font-lock matching of headlines."
   6084   (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
   6085 	 (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
   6086 	 (org-f (if org-cycle-level-faces
   6087 		    (nth (% (1- org-l) org-n-level-faces) org-level-faces)
   6088 		  (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
   6089     (cond
   6090      ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
   6091      ((eq n 2) org-f)
   6092      (t (unless org-level-color-stars-only org-f)))))
   6093 
   6094 (defun org-face-from-face-or-color (context inherit face-or-color)
   6095   "Create a face list that inherits INHERIT, but sets the foreground color.
   6096 When FACE-OR-COLOR is not a string, just return it."
   6097   (if (stringp face-or-color)
   6098       (list :inherit inherit
   6099 	    (cdr (assoc context org-faces-easy-properties))
   6100 	    face-or-color)
   6101     face-or-color))
   6102 
   6103 (defun org-get-todo-face (kwd)
   6104   "Get the right face for a TODO keyword KWD.
   6105 If KWD is a number, get the corresponding match group."
   6106   (when (numberp kwd) (setq kwd (match-string kwd)))
   6107   (or (org-face-from-face-or-color
   6108        'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
   6109       (and (member kwd org-done-keywords) 'org-done)
   6110       'org-todo))
   6111 
   6112 (defun org-get-priority-face (priority)
   6113   "Get the right face for PRIORITY.
   6114 PRIORITY is a character."
   6115   (or (org-face-from-face-or-color
   6116        'priority 'org-priority (cdr (assq priority org-priority-faces)))
   6117       'org-priority))
   6118 
   6119 (defun org-get-tag-face (tag)
   6120   "Get the right face for TAG.
   6121 If TAG is a number, get the corresponding match group."
   6122   (let ((tag (if (wholenump tag) (match-string tag) tag)))
   6123     (or (org-face-from-face-or-color
   6124 	 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
   6125 	'org-tag)))
   6126 
   6127 (defvar org-priority-regexp) ; defined later in the file
   6128 
   6129 (defun org-font-lock-add-priority-faces (limit)
   6130   "Add the special priority faces."
   6131   (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
   6132     (let ((beg (match-beginning 1))
   6133 	  (end (1+ (match-end 2))))
   6134       (add-face-text-property
   6135        beg end
   6136        (org-get-priority-face (string-to-char (match-string 2))))
   6137       (add-text-properties
   6138        beg end
   6139        (list 'font-lock-fontified t)))))
   6140 
   6141 (defun org-font-lock-add-tag-faces (limit)
   6142   "Add the special tag faces."
   6143   (when (and org-tag-faces org-tags-special-faces-re)
   6144     (while (re-search-forward org-tags-special-faces-re limit t)
   6145       (add-face-text-property
   6146        (match-beginning 1)
   6147        (match-end 1)
   6148        (org-get-tag-face 1))
   6149       (add-text-properties (match-beginning 1) (match-end 1)
   6150 			   (list 'font-lock-fontified t))
   6151       (backward-char 1))))
   6152 
   6153 (defun org-unfontify-region (beg end &optional _maybe_loudly)
   6154   "Remove fontification and activation overlays from links."
   6155   (font-lock-default-unfontify-region beg end)
   6156   (with-silent-modifications
   6157     (decompose-region beg end)
   6158     (remove-text-properties beg end
   6159 			    '(mouse-face t keymap t org-linked-text t
   6160 					 invisible t intangible t
   6161 					 org-emphasis t))
   6162     (org-fold-core-update-optimisation beg end)
   6163     (org-remove-font-lock-display-properties beg end)))
   6164 
   6165 (defconst org-script-display  '(((raise -0.3) (height 0.7))
   6166 				((raise 0.3)  (height 0.7))
   6167 				((raise -0.5))
   6168 				((raise 0.5)))
   6169   "Display properties for showing superscripts and subscripts.")
   6170 
   6171 (defun org-remove-font-lock-display-properties (beg end)
   6172   "Remove specific display properties that have been added by font lock.
   6173 The will remove the raise properties that are used to show superscripts
   6174 and subscripts."
   6175   (let (next prop)
   6176     (while (< beg end)
   6177       (setq next (next-single-property-change beg 'display nil end)
   6178 	    prop (get-text-property beg 'display))
   6179       (when (member prop org-script-display)
   6180 	(put-text-property beg next 'display nil))
   6181       (setq beg next))))
   6182 
   6183 (defun org-raise-scripts (limit)
   6184   "Add raise properties to sub/superscripts."
   6185   (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
   6186 	     (re-search-forward
   6187 	      (if (eq org-use-sub-superscripts t)
   6188 		  org-match-substring-regexp
   6189 		org-match-substring-with-braces-regexp)
   6190 	      limit t))
   6191     (let* ((pos (point)) table-p comment-p
   6192 	   (mpos (match-beginning 3))
   6193 	   (emph-p (get-text-property mpos 'org-emphasis))
   6194 	   (link-p (get-text-property mpos 'mouse-face))
   6195 	   (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
   6196       (goto-char (line-beginning-position))
   6197       (setq table-p (looking-at-p org-table-dataline-regexp)
   6198 	    comment-p (looking-at-p "^[ \t]*#[ +]"))
   6199       (goto-char pos)
   6200       ;; Handle a_b^c
   6201       (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
   6202       (unless (or comment-p emph-p link-p keyw-p)
   6203 	(put-text-property (match-beginning 3) (match-end 0)
   6204 			   'display
   6205 			   (if (equal (char-after (match-beginning 2)) ?^)
   6206 			       (nth (if table-p 3 1) org-script-display)
   6207 			     (nth (if table-p 2 0) org-script-display)))
   6208         (put-text-property (match-beginning 2) (match-end 3)
   6209                            'org-emphasis t)
   6210 	(add-text-properties (match-beginning 2) (match-end 2)
   6211 			     (list 'invisible t))
   6212 	(when (and (eq (char-after (match-beginning 3)) ?{)
   6213 		   (eq (char-before (match-end 3)) ?}))
   6214 	  (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
   6215 			       (list 'invisible t))
   6216 	  (add-text-properties (1- (match-end 3)) (match-end 3)
   6217 			       (list 'invisible t))))
   6218       t)))
   6219 
   6220 (defun org-remove-empty-overlays-at (pos)
   6221   "Remove outline overlays that do not contain non-white stuff."
   6222   (dolist (o (overlays-at pos))
   6223     (and (eq 'outline (overlay-get o 'invisible))
   6224 	 (not (string-match-p
   6225                "\\S-" (buffer-substring (overlay-start o)
   6226 					(overlay-end o))))
   6227 	 (delete-overlay o))))
   6228 
   6229 ;; FIXME: This function is unused.
   6230 (defun org-show-empty-lines-in-parent ()
   6231   "Move to the parent and re-show empty lines before visible headlines."
   6232   (save-excursion
   6233     (let ((context (if (org-up-heading-safe) 'children 'overview)))
   6234       (org-cycle-show-empty-lines context))))
   6235 
   6236 (defun org-files-list ()
   6237   "Return `org-agenda-files' list, plus all open Org files.
   6238 This is useful for operations that need to scan all of a user's
   6239 open and agenda-wise Org files."
   6240   (let ((files (mapcar #'expand-file-name (org-agenda-files))))
   6241     (dolist (buf (buffer-list))
   6242       (with-current-buffer buf
   6243 	(when (and (derived-mode-p 'org-mode) (buffer-file-name))
   6244 	  (cl-pushnew (expand-file-name (buffer-file-name)) files
   6245 		      :test #'equal))))
   6246     files))
   6247 
   6248 (defsubst org-entry-beginning-position ()
   6249   "Return the beginning position of the current entry."
   6250   (save-excursion (org-back-to-heading t) (point)))
   6251 
   6252 (defsubst org-entry-end-position ()
   6253   "Return the end position of the current entry."
   6254   (save-excursion (outline-next-heading) (point)))
   6255 
   6256 (defun org-subtree-end-visible-p ()
   6257   "Is the end of the current subtree visible?"
   6258   (pos-visible-in-window-p
   6259    (save-excursion (org-end-of-subtree t) (point))))
   6260 
   6261 (defun org-first-headline-recenter ()
   6262   "Move cursor to the first headline and recenter the headline."
   6263   (let ((window (get-buffer-window)))
   6264     (when window
   6265       (goto-char (point-min))
   6266       (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
   6267 	(set-window-start window (line-beginning-position))))))
   6268 
   6269 
   6270 
   6271 ;; FIXME: It was in the middle of visibility section. Where should it go to?
   6272 (defvar org-called-with-limited-levels nil
   6273   "Non-nil when `org-with-limited-levels' is currently active.")
   6274 
   6275 
   6276 ;;; Indirect buffer display of subtrees
   6277 
   6278 (defvar org-indirect-dedicated-frame nil
   6279   "This is the frame being used for indirect tree display.")
   6280 (defvar org-last-indirect-buffer nil)
   6281 
   6282 (defun org-tree-to-indirect-buffer (&optional arg)
   6283   "Create indirect buffer and narrow it to current subtree.
   6284 
   6285 With a numerical prefix ARG, go up to this level and then take that tree.
   6286 If ARG is negative, go up that many levels.
   6287 
   6288 If `org-indirect-buffer-display' is not `new-frame', the command removes the
   6289 indirect buffer previously made with this command, to avoid proliferation of
   6290 indirect buffers.  However, when you call the command with a \
   6291 `\\[universal-argument]' prefix, or
   6292 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
   6293 so that you can work with several indirect buffers at the same time.  If
   6294 `org-indirect-buffer-display' is `dedicated-frame', the \
   6295 `\\[universal-argument]' prefix also
   6296 requests that a new frame be made for the new buffer, so that the dedicated
   6297 frame is not changed."
   6298   (interactive "P")
   6299   (let ((cbuf (current-buffer))
   6300 	(cwin (selected-window))
   6301 	(pos (point))
   6302 	beg end level heading ibuf
   6303         (last-indirect-window
   6304          (and org-last-indirect-buffer
   6305               (get-buffer-window org-last-indirect-buffer))))
   6306     (save-excursion
   6307       (org-back-to-heading t)
   6308       (when (numberp arg)
   6309 	(setq level (org-outline-level))
   6310 	(when (< arg 0) (setq arg (+ level arg)))
   6311 	(while (> (setq level (org-outline-level)) arg)
   6312 	  (org-up-heading-safe)))
   6313       (setq beg (point)
   6314 	    heading (org-get-heading 'no-tags))
   6315       (org-end-of-subtree t t)
   6316       (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
   6317       (setq end (point)))
   6318     (when (and (buffer-live-p org-last-indirect-buffer)
   6319 	       (not (eq org-indirect-buffer-display 'new-frame))
   6320 	       (not arg))
   6321       (kill-buffer org-last-indirect-buffer))
   6322     (setq ibuf (org-get-indirect-buffer cbuf heading)
   6323 	  org-last-indirect-buffer ibuf)
   6324     (cond
   6325      ((or (eq org-indirect-buffer-display 'new-frame)
   6326 	  (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
   6327       (select-frame (make-frame))
   6328       (pop-to-buffer ibuf '(org-display-buffer-full-frame))
   6329       (org-set-frame-title heading))
   6330      ((eq org-indirect-buffer-display 'dedicated-frame)
   6331       (raise-frame
   6332        (select-frame (or (and org-indirect-dedicated-frame
   6333 			      (frame-live-p org-indirect-dedicated-frame)
   6334 			      org-indirect-dedicated-frame)
   6335 			 (setq org-indirect-dedicated-frame (make-frame)))))
   6336       (pop-to-buffer ibuf '(org-display-buffer-full-frame))
   6337       (org-set-frame-title (concat "Indirect: " heading)))
   6338      ((eq org-indirect-buffer-display 'current-window)
   6339       (pop-to-buffer-same-window ibuf))
   6340      ((eq org-indirect-buffer-display 'other-window)
   6341       (pop-to-buffer
   6342        ibuf
   6343        `(org-display-buffer-in-window (window . ,last-indirect-window)
   6344                                       (same-frame . t))))
   6345      (t (error "Invalid value")))
   6346     (narrow-to-region beg end)
   6347     (org-fold-show-all '(headings drawers blocks))
   6348     (goto-char pos)
   6349     (run-hook-with-args 'org-cycle-hook 'all)
   6350     (and (window-live-p cwin) (select-window cwin))))
   6351 
   6352 (cl-defun org-get-indirect-buffer (&optional (buffer (current-buffer)) heading)
   6353   "Return an indirect buffer based on BUFFER.
   6354 If HEADING, append it to the name of the new buffer."
   6355   (let* ((base-buffer (or (buffer-base-buffer buffer) buffer))
   6356          (buffer-name (generate-new-buffer-name
   6357                        (format "%s%s"
   6358                                (buffer-name base-buffer)
   6359                                (if heading
   6360                                    (concat "::" heading)
   6361                                  ""))))
   6362          (indirect-buffer (make-indirect-buffer base-buffer buffer-name 'clone)))
   6363     ;; Decouple folding state.  We need to do it manually since
   6364     ;; `make-indirect-buffer' does not run
   6365     ;; `clone-indirect-buffer-hook'.
   6366     (org-fold-core-decouple-indirect-buffer-folds)
   6367     indirect-buffer))
   6368 
   6369 (defun org-set-frame-title (title)
   6370   "Set the title of the current frame to the string TITLE."
   6371   (modify-frame-parameters (selected-frame) (list (cons 'name title))))
   6372 
   6373 ;;;; Structure editing
   6374 
   6375 ;;; Inserting headlines
   6376 
   6377 (defun org--blank-before-heading-p (&optional parent)
   6378   "Non-nil when an empty line should precede a new heading here.
   6379 When optional argument PARENT is non-nil, consider parent
   6380 headline instead of current one."
   6381   (pcase (assq 'heading org-blank-before-new-entry)
   6382     (`(heading . auto)
   6383      (save-excursion
   6384        (org-with-limited-levels
   6385         (unless (and (org-before-first-heading-p)
   6386                      (not (outline-next-heading)))
   6387           (org-back-to-heading t)
   6388           (when parent (org-up-heading-safe))
   6389           (cond ((not (bobp))
   6390                  (org-previous-line-empty-p))
   6391 		((outline-next-heading)
   6392 		 (org-previous-line-empty-p))
   6393 		;; Ignore trailing spaces on last buffer line.
   6394 		((progn (skip-chars-backward " \t") (bolp))
   6395 		 (org-previous-line-empty-p))
   6396 		(t nil))))))
   6397     (`(heading . ,value) value)
   6398     (_ nil)))
   6399 
   6400 (defun org-insert-heading (&optional arg invisible-ok level)
   6401   "Insert a new heading or an item with the same depth at point.
   6402 
   6403 If point is at the beginning of a heading, insert a new heading
   6404 or a new headline above the current one.  When at the beginning
   6405 of a regular line of text, turn it into a heading.
   6406 
   6407 If point is in the middle of a line, split it and create a new
   6408 headline with the text in the current line after point (see
   6409 `org-M-RET-may-split-line' on how to modify this behavior).  As
   6410 a special case, on a headline, splitting can only happen on the
   6411 title itself.  E.g., this excludes breaking stars or tags.
   6412 
   6413 With a `\\[universal-argument]' prefix, set \
   6414 `org-insert-heading-respect-content' to
   6415 a non-nil value for the duration of the command.  This forces the
   6416 insertion of a heading after the current subtree, independently
   6417 on the location of point.
   6418 
   6419 With a `\\[universal-argument] \\[universal-argument]' prefix, \
   6420 insert the heading at the end of the tree
   6421 above the current heading.  For example, if point is within a
   6422 2nd-level heading, then it will insert a 2nd-level heading at
   6423 the end of the 1st-level parent subtree.
   6424 
   6425 When INVISIBLE-OK is set, stop at invisible headlines when going
   6426 back.  This is important for non-interactive uses of the
   6427 command.
   6428 
   6429 When optional argument LEVEL is a number, insert a heading at
   6430 that level.  For backwards compatibility, when LEVEL is non-nil
   6431 but not a number, insert a level-1 heading."
   6432   (interactive "P")
   6433   (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
   6434          (current-level (org-current-level))
   6435          (num-stars (or
   6436                      ;; Backwards compat: if LEVEL non-nil, level is 1
   6437                      (and level (if (wholenump level) level 1))
   6438                      current-level
   6439                      ;; This `1' is for when before first headline
   6440                      1))
   6441          (stars (make-string num-stars ?*))
   6442          (maybe-add-blank-after
   6443           (lambda (blank?)
   6444             "Add a blank line before next heading when BLANK? is non-nil.
   6445 Assume that point is on the inserted heading."
   6446             (save-excursion
   6447               (end-of-line)
   6448               (unless (eobp)
   6449                 (forward-char)
   6450                 (when (and blank? (org-at-heading-p))
   6451                   (insert "\n")))))))
   6452     (cond
   6453      ((or org-insert-heading-respect-content
   6454 	  (member arg '((4) (16)))
   6455 	  (and (not invisible-ok)
   6456 	       (invisible-p (max (1- (point)) (point-min)))))
   6457       ;; Position point at the location of insertion.  Make sure we
   6458       ;; end up on a visible headline if INVISIBLE-OK is nil.
   6459       (org-with-limited-levels
   6460        (if (not current-level) (outline-next-heading) ;before first headline
   6461 	 (org-back-to-heading invisible-ok)
   6462 	 (when (equal arg '(16)) (org-up-heading-safe))
   6463 	 (org-end-of-subtree invisible-ok 'to-heading)))
   6464       ;; At `point-max', if the file does not have ending newline,
   6465       ;; create one, so that we are not appending stars at non-empty
   6466       ;; line.
   6467       (unless (bolp) (insert "\n"))
   6468       (when (and blank? (save-excursion
   6469                           (backward-char)
   6470                           (org-before-first-heading-p)))
   6471         (insert "\n")
   6472         (backward-char))
   6473       (when (and (not current-level) (not (eobp)) (not (bobp)))
   6474         (when (org-at-heading-p) (insert "\n"))
   6475         (backward-char))
   6476       (unless (and blank? (org-previous-line-empty-p))
   6477 	(org-N-empty-lines-before-current (if blank? 1 0)))
   6478       (insert stars " " "\n")
   6479       ;; Move point after stars.
   6480       (backward-char)
   6481       ;; Retain blank lines before next heading.
   6482       (funcall maybe-add-blank-after blank?)
   6483       ;; When INVISIBLE-OK is non-nil, ensure newly created headline
   6484       ;; is visible.
   6485       (unless invisible-ok
   6486         (if (eq org-fold-core-style 'text-properties)
   6487 	    (cond
   6488 	     ((org-fold-folded-p
   6489                (max (point-min)
   6490                     (1- (line-beginning-position)))
   6491                'headline)
   6492 	      (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
   6493 	     (t nil))
   6494           (pcase (get-char-property-and-overlay (point) 'invisible)
   6495 	    (`(outline . ,o)
   6496 	     (move-overlay o (overlay-start o) (line-end-position 0)))
   6497 	    (_ nil)))))
   6498      ;; At a headline...
   6499      ((org-at-heading-p)
   6500       (cond ((bolp)
   6501 	     (when blank? (save-excursion (insert "\n")))
   6502 	     (save-excursion (insert stars " \n"))
   6503 	     (unless (and blank? (org-previous-line-empty-p))
   6504 	       (org-N-empty-lines-before-current (if blank? 1 0)))
   6505 	     (end-of-line))
   6506 	    ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
   6507 		  (org-match-line org-complex-heading-regexp)
   6508 		  (org-pos-in-match-range (point) 4))
   6509 	     ;; Grab the text that should moved to the new headline.
   6510 	     ;; Preserve tags.
   6511 	     (let ((split (delete-and-extract-region (point) (match-end 4))))
   6512 	       (if (looking-at "[ \t]*$") (replace-match "")
   6513 		 (when org-auto-align-tags (org-align-tags)))
   6514 	       (end-of-line)
   6515 	       (when blank? (insert "\n"))
   6516 	       (insert "\n" stars " ")
   6517                ;; Retain blank lines before next heading.
   6518                (funcall maybe-add-blank-after blank?)
   6519 	       (when (org-string-nw-p split) (insert split))))
   6520 	    (t
   6521 	     (end-of-line)
   6522 	     (when blank? (insert "\n"))
   6523 	     (insert "\n" stars " ")
   6524              ;; Retain blank lines before next heading.
   6525              (funcall maybe-add-blank-after blank?))))
   6526      ;; On regular text, turn line into a headline or split, if
   6527      ;; appropriate.
   6528      ((bolp)
   6529       (insert stars " ")
   6530       (unless (and blank? (org-previous-line-empty-p))
   6531         (org-N-empty-lines-before-current (if blank? 1 0)))
   6532       ;; Retain blank lines before next heading.
   6533       (funcall maybe-add-blank-after blank?))
   6534      (t
   6535       (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
   6536         (end-of-line))
   6537       (insert "\n" stars " ")
   6538       (unless (and blank? (org-previous-line-empty-p))
   6539         (org-N-empty-lines-before-current (if blank? 1 0)))
   6540       ;; Retain blank lines before next heading.
   6541       (funcall maybe-add-blank-after blank?))))
   6542   (run-hooks 'org-insert-heading-hook))
   6543 
   6544 (defun org-N-empty-lines-before-current (n)
   6545   "Make the number of empty lines before current exactly N.
   6546 So this will delete or add empty lines."
   6547   (let ((column (current-column)))
   6548     (forward-line 0)
   6549     (unless (bobp)
   6550       (let ((start (save-excursion
   6551 		     (skip-chars-backward " \r\t\n")
   6552 		     (line-end-position))))
   6553 	(delete-region start (line-end-position 0))))
   6554     (insert (make-string n ?\n))
   6555     (move-to-column column)))
   6556 
   6557 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
   6558   "Return the heading of the current entry, without the stars.
   6559 When NO-TAGS is non-nil, don't include tags.
   6560 When NO-TODO is non-nil, don't include TODO keywords.
   6561 When NO-PRIORITY is non-nil, don't include priority cookie.
   6562 When NO-COMMENT is non-nil, don't include COMMENT string.
   6563 Return nil before first heading."
   6564   (unless (org-before-first-heading-p)
   6565     (save-excursion
   6566       (org-back-to-heading t)
   6567       (let ((case-fold-search nil))
   6568 	(looking-at org-complex-heading-regexp)
   6569         ;; When using `org-fold-core--optimise-for-huge-buffers',
   6570         ;; returned text will be invisible.  Clear it up.
   6571         (save-match-data
   6572           (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
   6573         (let ((todo (and (not no-todo) (match-string 2)))
   6574 	      (priority (and (not no-priority) (match-string 3)))
   6575 	      (headline (pcase (match-string 4)
   6576 			  (`nil "")
   6577 			  ((and (guard no-comment) h)
   6578 			   (replace-regexp-in-string
   6579 			    (eval-when-compile
   6580 			      (format "\\`%s[ \t]+" org-comment-string))
   6581 			    "" h))
   6582 			  (h h)))
   6583 	      (tags (and (not no-tags) (match-string 5))))
   6584           ;; Restore cleared optimization.
   6585           (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
   6586 	  (mapconcat #'identity
   6587 		     (delq nil (list todo priority headline tags))
   6588 		     " "))))))
   6589 
   6590 (defun org-heading-components ()
   6591   "Return the components of the current heading.
   6592 This is a list with the following elements:
   6593 - the level as an integer
   6594 - the reduced level, different if `org-odd-levels-only' is set.
   6595 - the TODO keyword, or nil
   6596 - the priority character, like ?A, or nil if no priority is given
   6597 - the headline text itself, or the tags string if no headline text
   6598 - the tags string, or nil."
   6599   (save-excursion
   6600     (org-back-to-heading t)
   6601     (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
   6602       (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
   6603       (prog1
   6604           (list (length (match-string 1))
   6605 	        (org-reduced-level (length (match-string 1)))
   6606 	        (match-string-no-properties 2)
   6607 	        (and (match-end 3) (aref (match-string 3) 2))
   6608 	        (match-string-no-properties 4)
   6609 	        (match-string-no-properties 5))
   6610         (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
   6611 
   6612 (defun org-get-entry ()
   6613   "Get the entry text, after heading, entire subtree."
   6614   (save-excursion
   6615     (org-back-to-heading t)
   6616     (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
   6617 
   6618 (defun org-edit-headline (&optional heading)
   6619   "Edit the current headline.
   6620 Set it to HEADING when provided."
   6621   (interactive)
   6622   (org-with-wide-buffer
   6623    (org-back-to-heading t)
   6624    (let ((case-fold-search nil))
   6625      (when (looking-at org-complex-heading-regexp)
   6626        (let* ((old (match-string-no-properties 4))
   6627 	      (new (save-match-data
   6628 		     (org-trim (or heading (read-string "Edit: " old))))))
   6629 	 (unless (equal old new)
   6630 	   (if old (replace-match new t t nil 4)
   6631 	     (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
   6632 	     (insert " " new))
   6633 	   (when org-auto-align-tags (org-align-tags))
   6634 	   (when (looking-at "[ \t]*$") (replace-match ""))))))))
   6635 
   6636 (defun org-insert-heading-after-current ()
   6637   "Insert a new heading with same level as current, after current subtree."
   6638   (interactive)
   6639   (org-back-to-heading)
   6640   (org-insert-heading)
   6641   (org-move-subtree-down)
   6642   (end-of-line 1))
   6643 
   6644 (defun org-insert-heading-respect-content (&optional invisible-ok)
   6645   "Insert heading with `org-insert-heading-respect-content' set to t."
   6646   (interactive)
   6647   (org-insert-heading '(4) invisible-ok))
   6648 
   6649 (defun org-insert-todo-heading-respect-content (&optional arg)
   6650   "Call `org-insert-todo-heading', inserting after current subtree.
   6651 ARG is passed to `org-insert-todo-heading'.
   6652 This command temporarily sets `org-insert-heading-respect-content' to t."
   6653   (interactive "P")
   6654   (let ((org-insert-heading-respect-content t))
   6655     (org-insert-todo-heading arg t)))
   6656 
   6657 (defun org-insert-todo-heading (arg &optional force-heading)
   6658   "Insert a new heading with the same level and TODO state as current heading.
   6659 
   6660 If the heading has no TODO state, or if the state is DONE, use
   6661 the first state (TODO by default).  Also with `\\[universal-argument]'
   6662 prefix, force first state.  With a `\\[universal-argument]
   6663 \\[universal-argument]' prefix, force inserting at the end of the
   6664 parent subtree.
   6665 
   6666 When called at a plain list item, insert a new item with an
   6667 unchecked check box."
   6668   (interactive "P")
   6669   (when (or force-heading (not (org-insert-item 'checkbox)))
   6670     (org-insert-heading (or (and (equal arg '(16)) '(16))
   6671 			    force-heading))
   6672     (save-excursion
   6673       (org-forward-heading-same-level -1)
   6674       (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
   6675     (let* ((new-mark-x
   6676 	    (if (or (equal arg '(4))
   6677 		    (not (match-beginning 2))
   6678 		    (member (match-string 2) org-done-keywords))
   6679 		(car org-todo-keywords-1)
   6680 	      (match-string 2)))
   6681 	   (new-mark
   6682 	    (or
   6683 	     (run-hook-with-args-until-success
   6684 	      'org-todo-get-default-hook new-mark-x nil)
   6685 	     new-mark-x)))
   6686       (forward-line 0)
   6687       (and (looking-at org-outline-regexp) (goto-char (match-end 0))
   6688 	   (if org-treat-insert-todo-heading-as-state-change
   6689 	       (org-todo new-mark)
   6690 	     (insert new-mark " "))))
   6691     (when org-provide-todo-statistics
   6692       (org-update-parent-todo-statistics))))
   6693 
   6694 (defun org-insert-subheading (arg)
   6695   "Insert a new subheading and demote it.
   6696 Works for outline headings and for plain lists alike.
   6697 The prefix argument ARG is passed to `org-insert-heading'.
   6698 Unlike `org-insert-heading', when point is at the beginning of a
   6699 heading, still insert the new sub-heading below."
   6700   (interactive "P")
   6701   (when (and (bolp) (not (eobp)) (not (eolp))) (forward-char))
   6702   (org-insert-heading arg)
   6703   (cond
   6704    ((org-at-heading-p) (org-do-demote))
   6705    ((org-at-item-p) (org-indent-item))))
   6706 
   6707 (defun org-insert-todo-subheading (arg)
   6708   "Insert a new subheading with TODO keyword or checkbox and demote it.
   6709 Works for outline headings and for plain lists alike.
   6710 The prefix argument ARG is passed to `org-insert-todo-heading'."
   6711   (interactive "P")
   6712   (org-insert-todo-heading arg)
   6713   (cond
   6714    ((org-at-heading-p) (org-do-demote))
   6715    ((org-at-item-p) (org-indent-item))))
   6716 
   6717 ;;; Promotion and Demotion
   6718 
   6719 (defvar org-after-demote-entry-hook nil
   6720   "Hook run after an entry has been demoted.
   6721 The cursor will be at the beginning of the entry.
   6722 When a subtree is being demoted, the hook will be called for each node.")
   6723 
   6724 (defvar org-after-promote-entry-hook nil
   6725   "Hook run after an entry has been promoted.
   6726 The cursor will be at the beginning of the entry.
   6727 When a subtree is being promoted, the hook will be called for each node.")
   6728 
   6729 (defun org-promote-subtree ()
   6730   "Promote the entire subtree.
   6731 See also `org-promote'."
   6732   (interactive)
   6733   (save-excursion
   6734     (org-back-to-heading t)
   6735     (org-combine-change-calls (point) (save-excursion (org-end-of-subtree t))
   6736       (org-with-limited-levels (org-map-tree 'org-promote))))
   6737   (org-fix-position-after-promote))
   6738 
   6739 (defun org-demote-subtree ()
   6740   "Demote the entire subtree.
   6741 See `org-demote' and `org-promote'."
   6742   (interactive)
   6743   (save-excursion
   6744     (org-back-to-heading t)
   6745     (org-combine-change-calls (point) (save-excursion (org-end-of-subtree t))
   6746       (org-with-limited-levels (org-map-tree 'org-demote))))
   6747   (org-fix-position-after-promote))
   6748 
   6749 (defun org-do-promote ()
   6750   "Promote the current heading higher up the tree.
   6751 If the region is active in `transient-mark-mode', promote all
   6752 headings in the region."
   6753   (interactive)
   6754   (save-excursion
   6755     (if (org-region-active-p)
   6756         (let ((deactivate-mark nil))
   6757           (org-map-region 'org-promote (region-beginning) (region-end)))
   6758       (org-promote)))
   6759   (org-fix-position-after-promote))
   6760 
   6761 (defun org-do-demote ()
   6762   "Demote the current heading lower down the tree.
   6763 If the region is active in `transient-mark-mode', demote all
   6764 headings in the region."
   6765   (interactive)
   6766   (save-excursion
   6767     (if (org-region-active-p)
   6768         (let ((deactivate-mark nil))
   6769           (org-map-region 'org-demote (region-beginning) (region-end)))
   6770       (org-demote)))
   6771   (org-fix-position-after-promote))
   6772 
   6773 (defun org-fix-position-after-promote ()
   6774   "Fix cursor position and indentation after demoting/promoting."
   6775   (let ((pos (point)))
   6776     (when (save-excursion
   6777 	    (forward-line 0)
   6778 	    (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
   6779 	    (or (eq pos (match-end 1)) (eq pos (match-end 2))))
   6780       (cond ((eobp) (insert " "))
   6781 	    ((eolp) (insert " "))
   6782 	    ((equal (char-after) ?\s) (forward-char 1))))))
   6783 
   6784 (defun org-current-level ()
   6785   "Return the level of the current entry, or nil if before the first headline.
   6786 The level is the number of stars at the beginning of the
   6787 headline.  Use `org-reduced-level' to remove the effect of
   6788 `org-odd-levels-only'.  Unlike `org-outline-level', this function
   6789 ignores inlinetasks."
   6790   (let ((level (org-with-limited-levels (org-outline-level))))
   6791     (and (> level 0) level)))
   6792 
   6793 (defun org-get-previous-line-level ()
   6794   "Return the outline depth of the last headline before the current line.
   6795 Returns 0 for the first headline in the buffer, and nil if before the
   6796 first headline."
   6797   (and (org-current-level)
   6798        (or (and (/= (line-beginning-position) (point-min))
   6799 		(save-excursion (forward-line -1) (org-current-level)))
   6800 	   0)))
   6801 
   6802 (defun org-reduced-level (l)
   6803   "Compute the effective level of a heading.
   6804 This takes into account the setting of `org-odd-levels-only'."
   6805   (cond
   6806    ((zerop l) 0)
   6807    (org-odd-levels-only (1+ (floor (/ l 2))))
   6808    (t l)))
   6809 
   6810 (defun org-level-increment ()
   6811   "Return the number of stars that will be added or removed at a
   6812 time to headlines when structure editing, based on the value of
   6813 `org-odd-levels-only'."
   6814   (if org-odd-levels-only 2 1))
   6815 
   6816 (defun org-get-valid-level (level &optional change)
   6817   "Rectify a level change under the influence of `org-odd-levels-only'.
   6818 LEVEL is a current level, CHANGE is by how much the level should
   6819 be modified.  Even if CHANGE is nil, LEVEL may be returned
   6820 modified because even level numbers will become the next higher
   6821 odd number.  Returns values greater than 0."
   6822   (if org-odd-levels-only
   6823       (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
   6824 	    ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
   6825 	    ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
   6826     (max 1 (+ level (or change 0)))))
   6827 
   6828 (defun org-promote ()
   6829   "Promote the current heading higher up the tree."
   6830   (org-with-wide-buffer
   6831    (org-back-to-heading t)
   6832    (let* ((after-change-functions (remq 'flyspell-after-change-function
   6833 					after-change-functions))
   6834 	  (level (save-match-data (funcall outline-level)))
   6835 	  (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
   6836 	  (diff (abs (- level (length up-head) -1))))
   6837      (cond
   6838       ((and (= level 1) org-allow-promoting-top-level-subtree)
   6839        (replace-match "# " nil t))
   6840       ((= level 1)
   6841        (user-error "Cannot promote to level 0.  UNDO to recover if necessary"))
   6842       (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
   6843      (unless (= level 1)
   6844        (when org-auto-align-tags (org-align-tags))
   6845        (when org-adapt-indentation (org-fixup-indentation (- diff))))
   6846      (run-hooks 'org-after-promote-entry-hook))))
   6847 
   6848 (defun org-demote ()
   6849   "Demote the current heading lower down the tree."
   6850   (org-with-wide-buffer
   6851    (org-back-to-heading t)
   6852    (let* ((after-change-functions (remq 'flyspell-after-change-function
   6853 					after-change-functions))
   6854 	  (level (save-match-data (funcall outline-level)))
   6855 	  (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
   6856 	  (diff (abs (- level (length down-head) -1))))
   6857      (org-fold-core-ignore-fragility-checks
   6858        (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
   6859        (when org-auto-align-tags (org-align-tags))
   6860        (when org-adapt-indentation (org-fixup-indentation diff)))
   6861      (run-hooks 'org-after-demote-entry-hook))))
   6862 
   6863 (defun org-cycle-level ()
   6864   "Cycle the level of an empty headline through possible states.
   6865 This goes first to child, then to parent, level, then up the hierarchy.
   6866 After top level, it switches back to sibling level."
   6867   (interactive)
   6868   (let ((org-adapt-indentation nil))
   6869     (when (and (org-point-at-end-of-empty-headline)
   6870                (not (and (featurep 'org-inlinetask)
   6871                        (org-inlinetask-in-task-p))))
   6872       (setq this-command 'org-cycle-level) ; Only needed for caching
   6873       (let ((cur-level (org-current-level))
   6874             (prev-level (org-get-previous-line-level)))
   6875         (cond
   6876          ;; If first headline in file, promote to top-level.
   6877          ((= prev-level 0)
   6878           (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
   6879 		   do (org-do-promote)))
   6880          ;; If same level as prev, demote one.
   6881          ((= prev-level cur-level)
   6882           (org-do-demote))
   6883          ;; If parent is top-level, promote to top level if not already.
   6884          ((= prev-level 1)
   6885           (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
   6886 		   do (org-do-promote)))
   6887          ;; If top-level, return to prev-level.
   6888          ((= cur-level 1)
   6889           (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
   6890 		   do (org-do-demote)))
   6891          ;; If less than prev-level, promote one.
   6892          ((< cur-level prev-level)
   6893           (org-do-promote))
   6894          ;; If deeper than prev-level, promote until higher than
   6895          ;; prev-level.
   6896          ((> cur-level prev-level)
   6897           (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
   6898 		   do (org-do-promote))))
   6899         t))))
   6900 
   6901 (defun org-map-tree (fun)
   6902   "Call FUN for every heading underneath the current one."
   6903   (org-back-to-heading t)
   6904   (let ((level (funcall outline-level)))
   6905     (save-excursion
   6906       (funcall fun)
   6907       (while (and (progn
   6908 		    (outline-next-heading)
   6909 		    (> (funcall outline-level) level))
   6910 		  (not (eobp)))
   6911 	(funcall fun)))))
   6912 
   6913 (defun org-map-region (fun beg end)
   6914   "Call FUN for every heading between BEG and END."
   6915   (let ((org-ignore-region t))
   6916     (save-excursion
   6917       (setq end (copy-marker end))
   6918       (goto-char beg)
   6919       (when (and (re-search-forward org-outline-regexp-bol nil t)
   6920 		 (< (point) end))
   6921 	(funcall fun))
   6922       (while (and (progn
   6923 		    (outline-next-heading)
   6924 		    (< (point) end))
   6925 		  (not (eobp)))
   6926 	(funcall fun)))))
   6927 
   6928 (defun org-fixup-indentation (diff)
   6929   "Change the indentation in the current entry by DIFF.
   6930 
   6931 DIFF is an integer.  Indentation is done according to the
   6932 following rules:
   6933 
   6934   - Planning information and property drawers are always indented
   6935     according to the new level of the headline;
   6936 
   6937   - Footnote definitions and their contents are ignored;
   6938 
   6939   - Inlinetasks' boundaries are not shifted;
   6940 
   6941   - Empty lines are ignored;
   6942 
   6943   - Other lines' indentation are shifted by DIFF columns, unless
   6944     it would introduce a structural change in the document, in
   6945     which case no shifting is done at all.
   6946 
   6947 Assume point is at a heading or an inlinetask beginning."
   6948   (org-with-wide-buffer
   6949    (narrow-to-region (line-beginning-position)
   6950 		     (save-excursion
   6951 		       (if (org-with-limited-levels (org-at-heading-p))
   6952 			   (org-with-limited-levels (outline-next-heading))
   6953 			 (org-inlinetask-goto-end))
   6954 		       (point)))
   6955    (forward-line)
   6956    ;; Indent properly planning info and property drawer.
   6957    (when (looking-at-p org-planning-line-re)
   6958      (org-indent-line)
   6959      (forward-line))
   6960    (when (looking-at org-property-drawer-re)
   6961      (goto-char (match-end 0))
   6962      (forward-line)
   6963      (org-indent-region (match-beginning 0) (match-end 0)))
   6964    (when (looking-at org-logbook-drawer-re)
   6965      (let ((end-marker  (move-marker (make-marker) (match-end 0)))
   6966 	   (col (+ (current-indentation) diff)))
   6967        (when (wholenump col)
   6968 	 (while (< (point) end-marker)
   6969            (if (natnump diff)
   6970 	       (insert (make-string diff 32))
   6971              (delete-char (abs diff)))
   6972 	   (forward-line)))))
   6973    (catch 'no-shift
   6974      (when (or (zerop diff) (not (eq org-adapt-indentation t)))
   6975        (throw 'no-shift nil))
   6976      ;; If DIFF is negative, first check if a shift is possible at all
   6977      ;; (e.g., it doesn't break structure).  This can only happen if
   6978      ;; some contents are not properly indented.
   6979      (let ((case-fold-search t))
   6980        (when (< diff 0)
   6981 	 (let ((diff (- diff))
   6982 	       (forbidden-re (concat org-outline-regexp
   6983 				     "\\|"
   6984 				     (substring org-footnote-definition-re 1))))
   6985 	   (save-excursion
   6986 	     (while (not (eobp))
   6987 	       (cond
   6988 		((looking-at-p "[ \t]*$") (forward-line))
   6989 		((and (looking-at-p org-footnote-definition-re)
   6990 		      (let ((e (org-element-at-point)))
   6991 			(and (org-element-type-p e 'footnote-definition)
   6992 			     (goto-char (org-element-end e))))))
   6993 		((looking-at-p org-outline-regexp) (forward-line))
   6994 		;; Give up if shifting would move before column 0 or
   6995 		;; if it would introduce a headline or a footnote
   6996 		;; definition.
   6997 		(t
   6998 		 (skip-chars-forward " \t")
   6999 		 (let ((ind (current-column)))
   7000 		   (when (or (< ind diff)
   7001 			     (and (= ind diff) (looking-at-p forbidden-re)))
   7002 		     (throw 'no-shift nil)))
   7003 		 ;; Ignore contents of example blocks and source
   7004 		 ;; blocks if their indentation is meant to be
   7005 		 ;; preserved.  Jump to block's closing line.
   7006 		 (forward-line 0)
   7007 		 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
   7008 			  (let ((e (org-element-at-point)))
   7009 			    (and (org-src-preserve-indentation-p e)
   7010 			         (goto-char (org-element-end e))
   7011 			         (progn (skip-chars-backward " \r\t\n")
   7012 				        (forward-line 0)
   7013 				        t))))
   7014 		     (forward-line))))))))
   7015        ;; Shift lines but footnote definitions, inlinetasks boundaries
   7016        ;; by DIFF.  Also skip contents of source or example blocks
   7017        ;; when indentation is meant to be preserved.
   7018        (while (not (eobp))
   7019 	 (cond
   7020 	  ((and (looking-at-p org-footnote-definition-re)
   7021 		(let ((e (org-element-at-point)))
   7022 		  (and (org-element-type-p e 'footnote-definition)
   7023 		       (goto-char (org-element-end e))))))
   7024 	  ((looking-at-p org-outline-regexp) (forward-line))
   7025 	  ((looking-at-p "[ \t]*$") (forward-line))
   7026 	  (t
   7027 	   (indent-line-to (+ (current-indentation) diff))
   7028 	   (forward-line 0)
   7029 	   (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
   7030 		    (let ((e (org-element-at-point)))
   7031 		      (and (org-src-preserve-indentation-p e)
   7032 			   (goto-char (org-element-end e))
   7033 			   (progn (skip-chars-backward " \r\t\n")
   7034 				  (forward-line 0)
   7035 				  t))))
   7036 	       (forward-line)))))))))
   7037 
   7038 (defun org-convert-to-odd-levels ()
   7039   "Convert an Org file with all levels allowed to one with odd levels.
   7040 This will leave level 1 alone, convert level 2 to level 3, level 3 to
   7041 level 5 etc."
   7042   (interactive)
   7043   (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
   7044     (let ((outline-level 'org-outline-level)
   7045 	  (org-odd-levels-only nil) n)
   7046       (save-excursion
   7047 	(goto-char (point-min))
   7048 	(while (re-search-forward "^\\*\\*+ " nil t)
   7049 	  (setq n (- (length (match-string 0)) 2))
   7050 	  (while (>= (setq n (1- n)) 0)
   7051 	    (org-demote))
   7052 	  (end-of-line 1))))))
   7053 
   7054 (defun org-convert-to-oddeven-levels ()
   7055   "Convert an Org file with only odd levels to one with odd/even levels.
   7056 This promotes level 3 to level 2, level 5 to level 3 etc.  If the
   7057 file contains a section with an even level, conversion would
   7058 destroy the structure of the file.  An error is signaled in this
   7059 case."
   7060   (interactive)
   7061   (goto-char (point-min))
   7062   ;; First check if there are no even levels
   7063   (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
   7064     (org-fold-show-set-visibility 'canonical)
   7065     (error "Not all levels are odd in this file.  Conversion not possible"))
   7066   (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
   7067     (let ((outline-regexp org-outline-regexp)
   7068 	  (outline-level 'org-outline-level)
   7069 	  (org-odd-levels-only nil) n)
   7070       (save-excursion
   7071 	(goto-char (point-min))
   7072 	(while (re-search-forward "^\\*\\*+ " nil t)
   7073 	  (setq n (/ (1- (length (match-string 0))) 2))
   7074 	  (while (>= (setq n (1- n)) 0)
   7075 	    (org-promote))
   7076 	  (end-of-line 1))))))
   7077 
   7078 (defun org-tr-level (n)
   7079   "Make N odd if required."
   7080   (if org-odd-levels-only (1+ (/ n 2)) n))
   7081 
   7082 ;;; Vertical tree motion, cutting and pasting of subtrees
   7083 
   7084 (defun org-move-subtree-up (&optional arg)
   7085   "Move the current subtree up past ARG headlines of the same level."
   7086   (interactive "p")
   7087   (org-move-subtree-down (- (prefix-numeric-value arg))))
   7088 
   7089 (defun org-clean-visibility-after-subtree-move ()
   7090   "Fix visibility issues after moving a subtree."
   7091   ;; First, find a reasonable region to look at:
   7092   ;; Start two siblings above, end three below
   7093   (let* ((beg (save-excursion
   7094 		(and (org-get-previous-sibling)
   7095 		     (org-get-previous-sibling))
   7096 		(point)))
   7097 	 (end (save-excursion
   7098 		(and (org-get-next-sibling)
   7099 		     (org-get-next-sibling)
   7100 		     (org-get-next-sibling))
   7101 		(if (org-at-heading-p)
   7102 		    (line-end-position)
   7103 		  (point))))
   7104 	 (level (looking-at "\\*+"))
   7105 	 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
   7106     (save-excursion
   7107       (save-restriction
   7108 	(narrow-to-region beg end)
   7109 	(when re
   7110 	  ;; Properly fold already folded siblings
   7111 	  (goto-char (point-min))
   7112 	  (while (re-search-forward re nil t)
   7113 	    (when (and (not (org-invisible-p))
   7114 		       (org-invisible-p (line-end-position)))
   7115 	      (org-fold-heading nil))))
   7116 	(org-cycle-hide-drawers 'all)
   7117 	(org-cycle-show-empty-lines 'overview)))))
   7118 
   7119 (defun org-move-subtree-down (&optional arg)
   7120   "Move the current subtree down past ARG headlines of the same level."
   7121   (interactive "p")
   7122   (setq arg (prefix-numeric-value arg))
   7123   (org-preserve-local-variables
   7124    (let ((movfunc (if (> arg 0) 'org-get-next-sibling
   7125 		    'org-get-previous-sibling))
   7126 	 (ins-point (make-marker))
   7127 	 (cnt (abs arg))
   7128 	 (col (current-column))
   7129 	 beg end txt folded)
   7130      ;; Select the tree
   7131      (org-back-to-heading)
   7132      (setq beg (point))
   7133      (save-match-data
   7134        (save-excursion (outline-end-of-heading)
   7135 		       (setq folded (org-invisible-p)))
   7136        (progn (org-end-of-subtree nil t)
   7137 	      (unless (eobp) (backward-char))))
   7138      (outline-next-heading)
   7139      (setq end (point))
   7140      (goto-char beg)
   7141      ;; Find insertion point, with error handling
   7142      (while (> cnt 0)
   7143        (unless (and (funcall movfunc) (looking-at org-outline-regexp))
   7144 	 (goto-char beg)
   7145 	 (user-error "Cannot move past superior level or buffer limit"))
   7146        (setq cnt (1- cnt)))
   7147      (when (> arg 0)
   7148        ;; Moving forward - still need to move over subtree
   7149        (org-end-of-subtree t t)
   7150        (save-excursion
   7151 	 (org-back-over-empty-lines)
   7152 	 (or (bolp) (newline))))
   7153      (move-marker ins-point (point))
   7154      (setq txt (buffer-substring beg end))
   7155      (org-save-markers-in-region beg end)
   7156      (delete-region beg end)
   7157      (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
   7158      (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
   7159      (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
   7160      (and (not (bolp)) (looking-at "\n") (forward-char 1))
   7161      (let ((bbb (point)))
   7162        (insert-before-markers txt)
   7163        (org-reinstall-markers-in-region bbb)
   7164        (move-marker ins-point bbb))
   7165      (or (bolp) (insert "\n"))
   7166      (goto-char ins-point)
   7167      (org-skip-whitespace)
   7168      (move-marker ins-point nil)
   7169      (if folded
   7170 	 (org-fold-subtree t)
   7171        (org-fold-show-entry 'hide-drawers)
   7172        (org-fold-show-children))
   7173      (org-clean-visibility-after-subtree-move)
   7174      ;; move back to the initial column we were at
   7175      (move-to-column col))))
   7176 
   7177 (defvar org-subtree-clip ""
   7178   "Clipboard for cut and paste of subtrees.
   7179 This is actually only a copy of the kill, because we use the normal kill
   7180 ring.  We need it to check if the kill was created by `org-copy-subtree'.")
   7181 
   7182 (defvar org-subtree-clip-folded nil
   7183   "Was the last copied subtree folded?
   7184 This is used to fold the tree back after pasting.")
   7185 
   7186 (defun org-cut-subtree (&optional n)
   7187   "Cut the current subtree into the clipboard.
   7188 With prefix arg N, cut this many sequential subtrees.
   7189 This is a short-hand for marking the subtree and then cutting it."
   7190   (interactive "p")
   7191   (org-copy-subtree n 'cut))
   7192 
   7193 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
   7194   "Copy the current subtree into the clipboard.
   7195 With prefix arg N, copy this many sequential subtrees.
   7196 This is a short-hand for marking the subtree and then copying it.
   7197 If CUT is non-nil, actually cut the subtree.
   7198 If FORCE-STORE-MARKERS is non-nil, store the relative locations
   7199 of some markers in the region, even if CUT is non-nil.  This is
   7200 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
   7201   (interactive "p")
   7202   (org-preserve-local-variables
   7203    (let (beg end folded (beg0 (point)))
   7204      (if (called-interactively-p 'any)
   7205 	 (org-back-to-heading nil)    ; take what looks like a subtree
   7206        (org-back-to-heading t))	      ; take what is really there
   7207      ;; Do not consider inlinetasks as a subtree.
   7208      (when (org-element-type-p (org-element-at-point) 'inlinetask)
   7209        (org-up-element))
   7210      (setq beg (point))
   7211      (skip-chars-forward " \t\r\n")
   7212      (save-match-data
   7213        (if nosubtrees
   7214 	   (outline-next-heading)
   7215 	 (save-excursion (outline-end-of-heading)
   7216 			 (setq folded (org-invisible-p)))
   7217 	 (ignore-errors (org-forward-heading-same-level (1- n) t))
   7218 	 (org-end-of-subtree t t)))
   7219      ;; Include the end of an inlinetask
   7220      (when (and (featurep 'org-inlinetask)
   7221 		(looking-at-p (concat (org-inlinetask-outline-regexp)
   7222 				      "END[ \t]*$")))
   7223        (end-of-line))
   7224      (setq end (point))
   7225      (goto-char beg0)
   7226      (when (> end beg)
   7227        (setq org-subtree-clip-folded folded)
   7228        (when (or cut force-store-markers)
   7229 	 (org-save-markers-in-region beg end))
   7230        (if cut (kill-region beg end) (copy-region-as-kill beg end))
   7231        (setq org-subtree-clip (current-kill 0))
   7232        (message "%s: Subtree(s) with %d characters"
   7233 		(if cut "Cut" "Copied")
   7234 		(length org-subtree-clip))))))
   7235 
   7236 (defun org-paste-subtree (&optional level tree for-yank remove)
   7237   "Paste the clipboard as a subtree, with modification of headline level.
   7238 
   7239 The entire subtree is promoted or demoted in order to match a new headline
   7240 level.
   7241 
   7242 If the cursor is at the beginning of a headline, the same level as
   7243 that headline is used to paste the tree before current headline.
   7244 
   7245 With `\\[universal-argument]' prefix, force inserting at the same level
   7246 as current headline, after subtree at point.
   7247 
   7248 With `\\[universal-argument]' `\\[universal-argument]' prefix, force
   7249 inserting as a child headline, as the first child.
   7250 
   7251 If not, the new level is derived from the *visible* headings
   7252 before and after the insertion point, and taken to be the inferior headline
   7253 level of the two.  So if the previous visible heading is level 3 and the
   7254 next is level 4 (or vice versa), level 4 will be used for insertion.
   7255 This makes sure that the subtree remains an independent subtree and does
   7256 not swallow low level entries.
   7257 
   7258 You can also force a different level, either by using a numeric prefix
   7259 argument, or by inserting the heading marker by hand.  For example, if the
   7260 cursor is after \"*****\", then the tree will be shifted to level 5.
   7261 
   7262 If optional TREE is given, use this text instead of the kill ring.
   7263 
   7264 When FOR-YANK is set, this is called by `org-yank'.  In this case, do not
   7265 move back over whitespace before inserting, and move point to the end of
   7266 the inserted text when done.
   7267 
   7268 When REMOVE is non-nil, remove the subtree from the clipboard."
   7269   (interactive "P")
   7270   (setq tree (or tree (current-kill 0)))
   7271   (unless (org-kill-is-subtree-p tree)
   7272     (user-error
   7273      (substitute-command-keys
   7274       "The kill is not a (set of) tree(s).  Use `\\[yank]' to yank anyway")))
   7275   (org-with-limited-levels
   7276    (org-fold-core-ignore-fragility-checks
   7277      (let* ((visp (not (org-invisible-p)))
   7278 	    (txt tree)
   7279 	    (old-level (if (string-match org-outline-regexp-bol txt)
   7280 			   (- (match-end 0) (match-beginning 0) 1)
   7281 		         -1))
   7282             level-indicator?
   7283 	    (force-level
   7284 	     (cond
   7285 	      ;; When point is after the stars in an otherwise empty
   7286 	      ;; headline, use the number of stars as the forced level.
   7287 	      ((and (or (not level) (member level '((4) (16))))
   7288                     (org-match-line "^\\*+[ \t]*$")
   7289 		    (not (eq ?* (char-after))))
   7290 	       (setq level-indicator? (org-outline-level)))
   7291               ((equal level '(4)) (org-outline-level))
   7292               ((equal level '(16)) nil) ; handle later
   7293 	      (level (prefix-numeric-value level))
   7294 	      ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
   7295 	    (previous-level
   7296 	     (save-excursion
   7297 	       (unless (org-at-heading-p) (org-previous-visible-heading 1))
   7298 	       (if (org-at-heading-p) (org-outline-level) 1)))
   7299 	    (next-level
   7300 	     (save-excursion
   7301 	       (org-next-visible-heading 1)
   7302 	       (if (org-at-heading-p) (org-outline-level) 1)))
   7303 	    (new-level (or force-level
   7304                            (max
   7305                             ;; C-u C-u forces child.
   7306                             (if (equal level '(16)) (1+ previous-level) 0)
   7307                             previous-level
   7308                             next-level)))
   7309 	    (shift (if (or (= old-level -1)
   7310 			   (= new-level -1)
   7311 			   (= old-level new-level))
   7312 		       0
   7313 		     (- new-level old-level)))
   7314 	    (delta (if (> shift 0) -1 1))
   7315 	    (func (if (> shift 0) #'org-demote #'org-promote))
   7316 	    (org-odd-levels-only nil)
   7317 	    beg end newend)
   7318        ;; Remove the forced level indicator.
   7319        (when level-indicator?
   7320          (delete-region (line-beginning-position) (line-beginning-position 2)))
   7321        ;; Paste before the next visible heading or at end of buffer,
   7322        ;; unless point is at the beginning of a headline.
   7323        (unless (and (bolp) (org-at-heading-p) (not (member level '((4) (16)))))
   7324          (when (equal level '(4)) (org-end-of-subtree t))
   7325          (org-next-visible-heading 1)
   7326          (unless (bolp) (insert "\n")))
   7327        (setq beg (point))
   7328        ;; Avoid re-parsing cache elements when i.e. level 1 heading
   7329        ;; is inserted and then promoted.
   7330        (org-combine-change-calls beg beg
   7331          (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
   7332          (insert txt)
   7333          (unless (string-suffix-p "\n" txt) (insert "\n"))
   7334          (setq newend (point))
   7335          (org-reinstall-markers-in-region beg)
   7336          (setq end (point))
   7337          (goto-char beg)
   7338          (skip-chars-forward " \t\n\r")
   7339          (setq beg (point))
   7340          (when (and (org-invisible-p) visp)
   7341            (save-excursion (org-fold-heading nil)))
   7342          ;; Shift if necessary.
   7343          (unless (= shift 0)
   7344            (save-restriction
   7345 	     (narrow-to-region beg end)
   7346 	     (while (not (= shift 0))
   7347 	       (org-map-region func (point-min) (point-max))
   7348 	       (setq shift (+ delta shift)))
   7349 	     (goto-char (point-min))
   7350 	     (setq newend (point-max)))))
   7351        (when (or for-yank (called-interactively-p 'interactive))
   7352          (message "Clipboard pasted as level %d subtree" new-level))
   7353        (when (and (not for-yank) ; in this case, org-yank will decide about folding
   7354 		  (equal org-subtree-clip tree)
   7355 		  org-subtree-clip-folded)
   7356          ;; The tree was folded before it was killed/copied
   7357          (org-fold-subtree t))
   7358        (when for-yank (goto-char newend))
   7359        (when remove (pop kill-ring))))))
   7360 
   7361 (defun org-kill-is-subtree-p (&optional txt)
   7362   "Check if the current kill is an outline subtree, or a set of trees.
   7363 Returns nil if kill does not start with a headline, or if the first
   7364 headline level is not the largest headline level in the tree.
   7365 So this will actually accept several entries of equal levels as well,
   7366 which is OK for `org-paste-subtree'.
   7367 If optional TXT is given, check this string instead of the current kill."
   7368   (let* ((kill (or txt (ignore-errors (current-kill 0))))
   7369 	 (re (org-get-limited-outline-regexp))
   7370 	 (^re (concat "^" re))
   7371 	 (start-level (and kill
   7372 			   (string-match
   7373 			    (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
   7374 			    kill)
   7375 			   (- (match-end 2) (match-beginning 2) 1)))
   7376 	 (start (1+ (or (match-beginning 2) -1))))
   7377     (if (not start-level)
   7378 	(progn
   7379 	  nil)  ;; does not even start with a heading
   7380       (catch 'exit
   7381 	(while (setq start (string-match ^re kill (1+ start)))
   7382 	  (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
   7383 	    (throw 'exit nil)))
   7384 	t))))
   7385 
   7386 (defvar org-markers-to-move nil
   7387   "Markers that should be moved with a cut-and-paste operation.
   7388 Those markers are stored together with their positions relative to
   7389 the start of the region.")
   7390 
   7391 (defvar org-log-note-marker) ; defined later
   7392 (defun org-save-markers-in-region (beg end)
   7393   "Check markers in region.
   7394 If these markers are between BEG and END, record their position relative
   7395 to BEG, so that after moving the block of text, we can put the markers back
   7396 into place.
   7397 This function gets called just before an entry or tree gets cut from the
   7398 buffer.  After re-insertion, `org-reinstall-markers-in-region' must be
   7399 called immediately, to move the markers with the entries."
   7400   (setq org-markers-to-move nil)
   7401   (org-check-and-save-marker org-log-note-marker beg end)
   7402   (when (featurep 'org-clock)
   7403     (org-clock-save-markers-for-cut-and-paste beg end))
   7404   (when (featurep 'org-agenda)
   7405     (org-agenda-save-markers-for-cut-and-paste beg end)))
   7406 
   7407 (defun org-check-and-save-marker (marker beg end)
   7408   "Check if MARKER is between BEG and END.
   7409 If yes, remember the marker and the distance to BEG."
   7410   (when (and (marker-buffer marker)
   7411 	     (or (equal (marker-buffer marker) (current-buffer))
   7412                  (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
   7413 	     (>= marker beg) (< marker end))
   7414     (push (cons marker (- marker beg)) org-markers-to-move)))
   7415 
   7416 (defun org-reinstall-markers-in-region (beg)
   7417   "Move all remembered markers to their position relative to BEG."
   7418   (dolist (x org-markers-to-move)
   7419     (move-marker (car x) (+ beg (cdr x))))
   7420   (setq org-markers-to-move nil))
   7421 
   7422 (defun org-narrow-to-subtree (&optional element)
   7423   "Narrow buffer to the current subtree.
   7424 Use the command `\\[widen]' to see the whole buffer again.
   7425 With optional argument ELEMENT narrow to subtree around ELEMENT."
   7426   (interactive)
   7427   (let* ((heading
   7428           (org-element-lineage
   7429            (or element (org-element-at-point))
   7430            'headline 'with-self))
   7431          (begin (org-element-begin heading))
   7432          (end (org-element-end heading)))
   7433     (if (and heading end
   7434              ;; Preserve historical behavior throwing an error when
   7435              ;; current heading starts before active narrowing.
   7436              (<= (point-min) begin))
   7437         (narrow-to-region
   7438          begin
   7439          ;; Preserve historical behavior not extending the active
   7440          ;; narrowing when the subtree extends beyond it.
   7441          (min (point-max)
   7442               (if (= end (point-max))
   7443                   end (1- end))))
   7444       (signal 'outline-before-first-heading nil))))
   7445 
   7446 (defun org-toggle-narrow-to-subtree ()
   7447   "Narrow to the subtree at point or widen a narrowed buffer.
   7448 Use the command `\\[widen]' to see the whole buffer again."
   7449   (interactive)
   7450   (if (buffer-narrowed-p)
   7451       (progn (widen) (message "Buffer widen"))
   7452     (org-narrow-to-subtree)
   7453     (message "Buffer narrowed to current subtree")))
   7454 
   7455 (defun org-narrow-to-block ()
   7456   "Narrow buffer to the current block.
   7457 Use the command `\\[widen]' to see the whole buffer again."
   7458   (interactive)
   7459   (let* ((case-fold-search t)
   7460          (element (org-element-at-point)))
   7461     (if (string-match-p "block" (symbol-name (org-element-type element)))
   7462         (org-narrow-to-element)
   7463       (user-error "Not in a block"))))
   7464 
   7465 (defun org-clone-subtree-with-time-shift (n &optional shift)
   7466   "Clone the task (subtree) at point N times.
   7467 The clones will be inserted as siblings.
   7468 
   7469 In interactive use, the user will be prompted for the number of
   7470 clones to be produced.  If the entry has a timestamp, the user
   7471 will also be prompted for a time shift, which may be a repeater
   7472 as used in time stamps, for example `+3d'.  To disable this,
   7473 you can call the function with a universal prefix argument.
   7474 
   7475 When a valid repeater is given and the entry contains any time
   7476 stamps, the clones will become a sequence in time, with time
   7477 stamps in the subtree shifted for each clone produced.  If SHIFT
   7478 is nil or the empty string, time stamps will be left alone.  The
   7479 ID property of the original subtree is removed.
   7480 
   7481 In each clone, all the CLOCK entries will be removed.  This
   7482 prevents Org from considering that the clocked times overlap.
   7483 
   7484 If the original subtree did contain time stamps with a repeater,
   7485 the following will happen:
   7486 - the repeater will be removed in each clone
   7487 - an additional clone will be produced, with the current, unshifted
   7488   date(s) in the entry.
   7489 - the original entry will be placed *after* all the clones, with
   7490   repeater intact.
   7491 - the start days in the repeater in the original entry will be shifted
   7492   to past the last clone.
   7493 In this way you can spell out a number of instances of a repeating task,
   7494 and still retain the repeater to cover future instances of the task.
   7495 
   7496 As described above, N+1 clones are produced when the original
   7497 subtree has a repeater.  Setting N to 0, then, can be used to
   7498 remove the repeater from a subtree and create a shifted clone
   7499 with the original repeater."
   7500   (interactive "nNumber of clones to produce: ")
   7501   (unless (wholenump n) (user-error "Invalid number of replications %s" n))
   7502   (when (org-before-first-heading-p) (user-error "No subtree to clone"))
   7503   (let* ((beg (save-excursion (org-back-to-heading t) (point)))
   7504 	 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
   7505 	 (shift
   7506 	  (or shift
   7507 	      (if (and (not (equal current-prefix-arg '(4)))
   7508 		       (save-excursion
   7509 			 (goto-char beg)
   7510 			 (re-search-forward org-ts-regexp-both end-of-tree t)))
   7511 		  (read-from-minibuffer
   7512 		   "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
   7513 		"")))			;No time shift
   7514 	 (doshift
   7515 	  (and (org-string-nw-p shift)
   7516 	       (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
   7517 				 shift)
   7518 		   (user-error "Invalid shift specification %s" shift)))))
   7519     (goto-char end-of-tree)
   7520     (unless (bolp) (insert "\n"))
   7521     (let* ((end (point))
   7522 	   (template (buffer-substring beg end))
   7523 	   (shift-n (and doshift (string-to-number (match-string 1 shift))))
   7524 	   (shift-what (pcase (and doshift (match-string 2 shift))
   7525 			 (`nil nil)
   7526 			 ("h" 'hour)
   7527 			 ("d" 'day)
   7528 			 ("w" (setq shift-n (* 7 shift-n)) 'day)
   7529 			 ("m" 'month)
   7530 			 ("y" 'year)
   7531 			 (_ (error "Unsupported time unit"))))
   7532 	   (nmin 1)
   7533 	   (nmax n)
   7534 	   (n-no-remove -1)
   7535 	   (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
   7536 	   (idprop (org-entry-get beg "ID")))
   7537       (when (and doshift
   7538 		 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
   7539 				 template))
   7540 	(delete-region beg end)
   7541 	(setq end beg)
   7542 	(setq nmin 0)
   7543 	(setq nmax (1+ nmax))
   7544 	(setq n-no-remove nmax))
   7545       (goto-char end)
   7546       (cl-loop for n from nmin to nmax do
   7547 	       (insert
   7548 		;; Prepare clone.
   7549 		(with-temp-buffer
   7550 		  (insert template)
   7551 		  (org-mode)
   7552 		  (goto-char (point-min))
   7553 		  (org-fold-show-subtree)
   7554 		  (and idprop (if org-clone-delete-id
   7555 				  (org-entry-delete nil "ID")
   7556 				(org-id-get-create t)))
   7557 		  (unless (= n 0)
   7558 		    (while (re-search-forward org-clock-line-re nil t)
   7559 		      (delete-region (line-beginning-position)
   7560 				     (line-beginning-position 2)))
   7561 		    (goto-char (point-min))
   7562 		    (while (re-search-forward org-drawer-regexp nil t)
   7563 		      (org-remove-empty-drawer-at (point))))
   7564 		  (goto-char (point-min))
   7565 		  (when doshift
   7566 		    (while (re-search-forward org-ts-regexp-both nil t)
   7567 		      (org-timestamp-change (* n shift-n) shift-what))
   7568 		    (unless (= n n-no-remove)
   7569 		      (goto-char (point-min))
   7570 		      (while (re-search-forward org-ts-regexp nil t)
   7571 			(save-excursion
   7572 			  (goto-char (match-beginning 0))
   7573 			  (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
   7574 			    (delete-region (match-beginning 1) (match-end 1)))))))
   7575 		  (buffer-string)))))
   7576     (goto-char beg)))
   7577 
   7578 ;;; Outline path
   7579 
   7580 (defvar org-outline-path-cache nil
   7581   "Alist between buffer positions and outline paths.
   7582 It value is an alist (POSITION . PATH) where POSITION is the
   7583 buffer position at the beginning of an entry and PATH is a list
   7584 of strings describing the outline path for that entry, in reverse
   7585 order.")
   7586 
   7587 (defun org--get-outline-path-1 (&optional use-cache)
   7588   "Return outline path to current headline.
   7589 
   7590 Outline path is a list of strings, in reverse order.  When
   7591 optional argument USE-CACHE is non-nil, make use of a cache.  See
   7592 `org-get-outline-path' for details.
   7593 
   7594 Assume buffer is widened and point is on a headline."
   7595   (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
   7596       (let ((p (point))
   7597 	    (heading (let ((case-fold-search nil))
   7598 		       (looking-at org-complex-heading-regexp)
   7599 		       (if (not (match-end 4)) ""
   7600 			 ;; Remove statistics cookies.
   7601 			 (org-trim
   7602 			  (org-link-display-format
   7603 			   (replace-regexp-in-string
   7604 			    "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
   7605 			    (match-string-no-properties 4))))))))
   7606         (when (org-element-property :commentedp (org-element-at-point))
   7607           (setq heading (replace-regexp-in-string (format "^%s[ \t]*" org-comment-string) "" heading)))
   7608 	(if (org-up-heading-safe)
   7609 	    (let ((path (cons heading (org--get-outline-path-1 use-cache))))
   7610 	      (when use-cache
   7611 		(push (cons p path) org-outline-path-cache))
   7612 	      path)
   7613 	  ;; This is a new root node.  Since we assume we are moving
   7614 	  ;; forward, we can drop previous cache so as to limit number
   7615 	  ;; of associations there.
   7616 	  (let ((path (list heading)))
   7617 	    (when use-cache (setq org-outline-path-cache (list (cons p path))))
   7618 	    path)))))
   7619 
   7620 (defun org-get-outline-path (&optional with-self use-cache)
   7621   "Return the outline path to the current entry.
   7622 
   7623 An outline path is a list of ancestors for current headline, as
   7624 a list of strings.  Statistics cookies are removed and links are
   7625 replaced with their description, if any, or their path otherwise.
   7626 
   7627 When optional argument WITH-SELF is non-nil, the path also
   7628 includes the current headline.
   7629 
   7630 When optional argument USE-CACHE is non-nil, cache outline paths
   7631 between calls to this function so as to avoid backtracking.  This
   7632 argument is useful when planning to find more than one outline
   7633 path in the same document.  In that case, there are two
   7634 conditions to satisfy:
   7635   - `org-outline-path-cache' is set to nil before starting the
   7636     process;
   7637   - outline paths are computed by increasing buffer positions."
   7638   (org-with-wide-buffer
   7639    (and (or (and with-self (org-back-to-heading t))
   7640 	    (org-up-heading-safe))
   7641 	(reverse (org--get-outline-path-1 use-cache)))))
   7642 
   7643 (defun org-format-outline-path (path &optional width prefix separator)
   7644   "Format the outline path PATH for display.
   7645 WIDTH is the maximum number of characters that is available.
   7646 PREFIX is a prefix to be included in the returned string,
   7647 such as the file name.
   7648 SEPARATOR is inserted between the different parts of the path,
   7649 the default is \"/\"."
   7650   (setq width (or width 79))
   7651   (setq path (delq nil path))
   7652   (unless (> width 0)
   7653     (user-error "Argument `width' must be positive"))
   7654   (setq separator (or separator "/"))
   7655   (let* ((org-odd-levels-only nil)
   7656 	 (fpath (concat
   7657 		 prefix (and prefix path separator)
   7658 		 (mapconcat
   7659 		  (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
   7660 		  (cl-loop for head in path
   7661 			   for n from 0
   7662 			   collect (org-add-props
   7663 				       head nil 'face
   7664 				       (nth (% n org-n-level-faces) org-level-faces)))
   7665 		  separator))))
   7666     (when (> (length fpath) width)
   7667       (if (< width 7)
   7668 	  ;; It's unlikely that `width' will be this small, but don't
   7669 	  ;; waste characters by adding ".." if it is.
   7670 	  (setq fpath (substring fpath 0 width))
   7671 	(setf (substring fpath (- width 2)) "..")))
   7672     fpath))
   7673 
   7674 (defun org-get-title (&optional buffer-or-file)
   7675   "Collect title from the provided `org-mode' BUFFER-OR-FILE.
   7676 
   7677 Returns nil if there are no #+TITLE property."
   7678   (let ((buffer (cond ((bufferp buffer-or-file) buffer-or-file)
   7679                       ((stringp buffer-or-file) (find-file-noselect
   7680                                                  buffer-or-file))
   7681                       (t (current-buffer)))))
   7682     (with-current-buffer buffer
   7683       (org-macro-initialize-templates)
   7684       (let ((title (assoc-default "title" org-macro-templates)))
   7685         (unless (string= "" title)
   7686           title)))))
   7687 
   7688 (defun org-display-outline-path (&optional file-or-title current separator just-return-string)
   7689   "Display the current outline path in the echo area.
   7690 
   7691 If FILE-OR-TITLE is `title', prepend outline with file title.  If
   7692 it is non-nil or title is not present in document, prepend
   7693 outline path with the file name.
   7694 If CURRENT is non-nil, append the current heading to the output.
   7695 SEPARATOR is passed through to `org-format-outline-path'.  It separates
   7696 the different parts of the path and defaults to \"/\".
   7697 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
   7698   (interactive "P")
   7699   (let* (case-fold-search
   7700 	 (bfn (buffer-file-name (buffer-base-buffer)))
   7701          (title-prop (when (eq file-or-title 'title) (org-get-title)))
   7702 	 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
   7703 	 res)
   7704     (when current (setq path (append path
   7705 				     (save-excursion
   7706 				       (org-back-to-heading t)
   7707 				       (when (looking-at org-complex-heading-regexp)
   7708 					 (list (match-string 4)))))))
   7709     (setq res
   7710 	  (org-format-outline-path
   7711 	   path
   7712 	   (1- (frame-width))
   7713 	   (and file-or-title bfn (concat (if (and (eq file-or-title 'title) title-prop)
   7714 					      title-prop
   7715 					    (file-name-nondirectory bfn))
   7716 				 separator))
   7717 	   separator))
   7718     (add-face-text-property 0 (length res)
   7719 			    `(:height ,(face-attribute 'default :height))
   7720 			    nil res)
   7721     (if just-return-string
   7722 	res
   7723       (org-unlogged-message "%s" res))))
   7724 
   7725 ;;; Outline Sorting
   7726 
   7727 (defun org-sort (&optional with-case)
   7728   "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
   7729 Optional argument WITH-CASE means sort case-sensitively."
   7730   (interactive "P")
   7731   (org-call-with-arg
   7732    (cond ((org-at-table-p) #'org-table-sort-lines)
   7733 	 ((org-at-item-p) #'org-sort-list)
   7734 	 (t #'org-sort-entries))
   7735    with-case))
   7736 
   7737 (defun org-sort-remove-invisible (s)
   7738   "Remove emphasis markers and any invisible property from string S.
   7739 Assume S may contain only objects."
   7740   ;; org-element-interpret-data clears any text property, including
   7741   ;; invisible part.
   7742   (org-element-interpret-data
   7743    (let ((tree (org-element-parse-secondary-string
   7744                 s (org-element-restriction 'paragraph))))
   7745      (org-element-map tree '(bold code italic link strike-through underline verbatim)
   7746        (lambda (o)
   7747          (pcase (org-element-type o)
   7748            ;; Terminal object.  Replace it with its value.
   7749            ((or `code `verbatim)
   7750             (let ((new (org-element-property :value o)))
   7751               (org-element-insert-before new o)
   7752               (org-element-put-property
   7753                new :post-blank (org-element-post-blank o))))
   7754            ;; Non-terminal objects.  Splice contents.
   7755            (type
   7756             (let ((contents
   7757                    (or (org-element-contents o)
   7758                        (and (eq type 'link)
   7759                             (list (org-element-property :raw-link o)))))
   7760                   (c nil))
   7761               (while contents
   7762                 (setq c (pop contents))
   7763                 (org-element-insert-before c o))
   7764               (org-element-put-property
   7765                c :post-blank (org-element-post-blank o)))))
   7766          (org-element-extract o)))
   7767      ;; Return modified tree.
   7768      tree)))
   7769 
   7770 (defvar org-after-sorting-entries-or-items-hook nil
   7771   "Hook that is run after a bunch of entries or items have been sorted.
   7772 When children are sorted, the cursor is in the parent line when this
   7773 hook gets called.  When a region or a plain list is sorted, the cursor
   7774 will be in the first entry of the sorted region/list.")
   7775 
   7776 (defun org-sort-entries
   7777     (&optional with-case sorting-type getkey-func compare-func property
   7778 	       interactive?)
   7779   "Sort entries on a certain level of an outline tree.
   7780 If there is an active region, the entries in the region are sorted.
   7781 Else, if the cursor is before the first entry, sort the top-level items.
   7782 Else, the children of the entry at point are sorted.
   7783 
   7784 Sorting can be alphabetically, numerically, by date/time as given by
   7785 a time stamp, by a property, by priority order, or by a custom function.
   7786 
   7787 The command prompts for the sorting type unless it has been given to the
   7788 function through the SORTING-TYPE argument, which needs to be a character,
   7789 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K).  Here is
   7790 the precise meaning of each character:
   7791 
   7792 a   Alphabetically, ignoring the TODO keyword and the priority, if any.
   7793 c   By creation time, which is assumed to be the first inactive time stamp
   7794     at the beginning of a line.
   7795 d   By deadline date/time.
   7796 k   By clocking time.
   7797 n   Numerically, by converting the beginning of the entry/item to a number.
   7798 o   By order of TODO keywords.
   7799 p   By priority according to the cookie.
   7800 r   By the value of a property.
   7801 s   By scheduled date/time.
   7802 t   By date/time, either the first active time stamp in the entry, or, if
   7803     none exist, by the first inactive one.
   7804 
   7805 Capital letters will reverse the sort order.
   7806 
   7807 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
   7808 called with point at the beginning of the record.  It must return a
   7809 value that is compatible with COMPARE-FUNC, the function used to
   7810 compare entries.
   7811 
   7812 Comparing entries ignores case by default.  However, with an optional argument
   7813 WITH-CASE, the sorting considers case as well.
   7814 
   7815 Sorting is done against the visible part of the headlines, it ignores hidden
   7816 links.
   7817 
   7818 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
   7819 
   7820 A non-nil value for INTERACTIVE? is used to signal that this
   7821 function is being called interactively."
   7822   (interactive (list current-prefix-arg nil nil nil nil t))
   7823   (let ((case-func (if with-case 'identity 'downcase))
   7824         start beg end stars re re2
   7825         txt what tmp)
   7826     ;; Find beginning and end of region to sort
   7827     (cond
   7828      ((org-region-active-p)
   7829       (setq start (region-beginning)
   7830             end (region-end))
   7831       ;; we will sort the region
   7832       ;; Limit the region to full headings.
   7833       (goto-char start)
   7834       ;; Move to beginning of heading.
   7835       ;; If we are inside heading, move to next.
   7836       ;; If we are on heading, move to its begin position.
   7837       (if (org-at-heading-p)
   7838           (forward-line 0)
   7839         (outline-next-heading))
   7840       (setq start (point))
   7841       ;; Extend region end beyond the last subtree.
   7842       (goto-char end)
   7843       (org-end-of-subtree nil t)
   7844       (setq end (point)
   7845             what "region")
   7846       (goto-char start))
   7847      ((or (org-at-heading-p)
   7848           (ignore-errors (progn (org-back-to-heading) t)))
   7849       ;; we will sort the children of the current headline
   7850       (org-back-to-heading)
   7851       (setq start (point)
   7852 	    end (progn (org-end-of-subtree t t)
   7853 		       (or (bolp) (insert "\n"))
   7854 		       (when (>= (org-back-over-empty-lines) 1)
   7855 			 (forward-line 1))
   7856 		       (point))
   7857 	    what "children")
   7858       (goto-char start)
   7859       (org-fold-show-subtree)
   7860       (outline-next-heading))
   7861      (t
   7862       ;; we will sort the top-level entries in this file
   7863       (goto-char (point-min))
   7864       (or (org-at-heading-p) (outline-next-heading))
   7865       (setq start (point))
   7866       (goto-char (point-max))
   7867       (forward-line 0)
   7868       (when (looking-at ".*?\\S-")
   7869 	;; File ends in a non-white line
   7870 	(end-of-line 1)
   7871 	(insert "\n"))
   7872       (setq end (point-max))
   7873       (setq what "top-level")
   7874       (goto-char start)
   7875       (org-fold-show-all '(headings drawers blocks))))
   7876 
   7877     (setq beg (point))
   7878     (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
   7879 
   7880     (looking-at "\\(\\*+\\)")
   7881     (setq stars (match-string 1)
   7882 	  re (concat "^" (regexp-quote stars) " +")
   7883 	  re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
   7884 	  txt (buffer-substring beg end))
   7885     (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
   7886     (when (and (not (equal stars "*")) (string-match re2 txt))
   7887       (user-error "Region to sort contains a level above the first entry"))
   7888 
   7889     (unless sorting-type
   7890       (message
   7891        "Sort %s: [a]lpha  [n]umeric  [p]riority  p[r]operty  todo[o]rder  [f]unc
   7892                [t]ime [s]cheduled  [d]eadline  [c]reated  cloc[k]ing
   7893                A/N/P/R/O/F/T/S/D/C/K means reversed:"
   7894        what)
   7895       (setq sorting-type (read-char-exclusive)))
   7896 
   7897     (unless getkey-func
   7898       (and (= (downcase sorting-type) ?f)
   7899 	   (setq getkey-func
   7900 		 (or (and interactive?
   7901 			  (org-read-function
   7902 			   "Function for extracting keys: "))
   7903 		     (error "Missing key extractor")))))
   7904 
   7905     (and (= (downcase sorting-type) ?r)
   7906 	 (not property)
   7907 	 (setq property
   7908 	       (completing-read "Property: "
   7909 				(mapcar #'list (org-buffer-property-keys t))
   7910 				nil t)))
   7911 
   7912     (when (member sorting-type '(?k ?K)) (org-clock-sum))
   7913     (message "Sorting entries...")
   7914 
   7915     (save-restriction
   7916       (narrow-to-region start end)
   7917       ;; No trailing newline - add one to avoid
   7918       ;; * heading
   7919       ;; text* another heading
   7920       (save-excursion
   7921         (goto-char end)
   7922         (unless (bolp) (insert "\n")))
   7923       (let ((restore-clock?
   7924 	     ;; The clock marker is lost when using `sort-subr'; mark
   7925 	     ;; the clock with temporary `:org-clock-marker-backup'
   7926 	     ;; text property.
   7927 	     (when (and (eq (org-clocking-buffer) (current-buffer))
   7928 			(<= start (marker-position org-clock-marker))
   7929 			(>= end (marker-position org-clock-marker)))
   7930 	       (with-silent-modifications
   7931 		 (put-text-property (1- org-clock-marker) org-clock-marker
   7932 				    :org-clock-marker-backup t))
   7933 	       t))
   7934 	    (dcst (downcase sorting-type))
   7935 	    (case-fold-search nil)
   7936 	    (now (current-time)))
   7937         (org-preserve-local-variables
   7938 	 (sort-subr
   7939 	  (/= dcst sorting-type)
   7940 	  ;; This function moves to the beginning character of the
   7941 	  ;; "record" to be sorted.
   7942 	  (lambda nil
   7943 	    (if (re-search-forward re nil t)
   7944 		(goto-char (match-beginning 0))
   7945 	      (goto-char (point-max))))
   7946 	  ;; This function moves to the last character of the "record" being
   7947 	  ;; sorted.
   7948 	  (lambda nil
   7949 	    (save-match-data
   7950 	      (condition-case nil
   7951 		  (outline-forward-same-level 1)
   7952 		(error
   7953 		 (goto-char (point-max))))))
   7954 	  ;; This function returns the value that gets sorted against.
   7955 	  (lambda ()
   7956 	    (cond
   7957 	     ((= dcst ?n)
   7958 	      (string-to-number
   7959 	       (org-sort-remove-invisible (org-get-heading t t t t))))
   7960 	     ((= dcst ?a)
   7961 	      (funcall case-func
   7962 		       (org-sort-remove-invisible (org-get-heading t t t t))))
   7963 	     ((= dcst ?k)
   7964 	      (or (get-text-property (point) :org-clock-minutes) 0))
   7965 	     ((= dcst ?t)
   7966 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7967 		(if (or (re-search-forward org-ts-regexp end t)
   7968 			(re-search-forward org-ts-regexp-both end t))
   7969 		    (org-time-string-to-seconds (match-string 0))
   7970 		  (float-time now))))
   7971 	     ((= dcst ?c)
   7972 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7973 		(if (re-search-forward
   7974 		     (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
   7975 		     end t)
   7976 		    (org-time-string-to-seconds (match-string 0))
   7977 		  (float-time now))))
   7978 	     ((= dcst ?s)
   7979 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7980 		(if (re-search-forward org-scheduled-time-regexp end t)
   7981 		    (org-time-string-to-seconds (match-string 1))
   7982 		  (float-time now))))
   7983 	     ((= dcst ?d)
   7984 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7985 		(if (re-search-forward org-deadline-time-regexp end t)
   7986 		    (org-time-string-to-seconds (match-string 1))
   7987 		  (float-time now))))
   7988 	     ((= dcst ?p)
   7989               (if (re-search-forward org-priority-regexp (line-end-position) t)
   7990 		  (string-to-char (match-string 2))
   7991 		org-priority-default))
   7992 	     ((= dcst ?r)
   7993 	      (or (org-entry-get nil property) ""))
   7994 	     ((= dcst ?o)
   7995 	      (when (looking-at org-complex-heading-regexp)
   7996 		(let* ((m (match-string 2))
   7997 		       (s (if (member m org-done-keywords) '- '+)))
   7998 		  (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
   7999 	     ((= dcst ?f)
   8000 	      (if getkey-func
   8001 		  (progn
   8002 		    (setq tmp (funcall getkey-func))
   8003 		    (when (stringp tmp) (setq tmp (funcall case-func tmp)))
   8004 		    tmp)
   8005 		(error "Invalid key function `%s'" getkey-func)))
   8006 	     (t (error "Invalid sorting type `%c'" sorting-type))))
   8007 	  nil
   8008 	  (cond
   8009 	   ((= dcst ?a) #'org-string<)
   8010 	   ((= dcst ?f)
   8011 	    (or compare-func
   8012 		(and interactive?
   8013 		     (org-read-function
   8014 		      (concat "Function for comparing keys "
   8015 			      "(empty for default `sort-subr' predicate): ")
   8016 		      'allow-empty))))
   8017 	   ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
   8018 	(org-cycle-hide-drawers 'all)
   8019 	(when restore-clock?
   8020 	  (move-marker org-clock-marker
   8021 		       (1+ (next-single-property-change
   8022 			    start :org-clock-marker-backup)))
   8023 	  (remove-text-properties (1- org-clock-marker) org-clock-marker
   8024 				  '(:org-clock-marker-backup t)))))
   8025     (run-hooks 'org-after-sorting-entries-or-items-hook)
   8026     (message "Sorting entries...done")))
   8027 
   8028 (defun org-contextualize-keys (alist contexts)
   8029   "Return valid elements in ALIST depending on CONTEXTS.
   8030 
   8031 `org-agenda-custom-commands' or `org-capture-templates' are the
   8032 values used for ALIST, and `org-agenda-custom-commands-contexts'
   8033 or `org-capture-templates-contexts' are the associated contexts
   8034 definitions."
   8035   (let ((contexts
   8036 	 ;; normalize contexts
   8037 	 (mapcar
   8038 	  (lambda(c) (cond ((listp (cadr c))
   8039 			    (list (car c) (car c) (nth 1 c)))
   8040 			   ((string= "" (cadr c))
   8041 			    (list (car c) (car c) (nth 2 c)))
   8042 			   (t c)))
   8043           contexts))
   8044 	(a alist) r s)
   8045     ;; loop over all commands or templates
   8046     (dolist (c a)
   8047       (let (vrules repl)
   8048 	(cond
   8049 	 ((not (assoc (car c) contexts))
   8050 	  (push c r))
   8051 	 ((and (assoc (car c) contexts)
   8052 	       (setq vrules (org-contextualize-validate-key
   8053 			     (car c) contexts)))
   8054 	  (mapc (lambda (vr)
   8055 		  (unless (equal (car vr) (cadr vr))
   8056 		    (setq repl vr)))
   8057                 vrules)
   8058 	  (if (not repl) (push c r)
   8059 	    (push (cadr repl) s)
   8060 	    (push
   8061 	     (cons (car c)
   8062 		   (cdr (or (assoc (cadr repl) alist)
   8063 			    (error "Undefined key `%s' as contextual replacement for `%s'"
   8064 				   (cadr repl) (car c)))))
   8065 	     r))))))
   8066     ;; Return limited ALIST, possibly with keys modified, and deduplicated
   8067     (delq
   8068      nil
   8069      (delete-dups
   8070       (mapcar (lambda (x)
   8071 		(let ((tpl (car x)))
   8072 		  (unless (delq
   8073 			   nil
   8074 			   (mapcar (lambda (y)
   8075 				     (equal y tpl))
   8076 				   s))
   8077                     x)))
   8078 	      (reverse r))))))
   8079 
   8080 (defun org-contextualize-validate-key (key contexts)
   8081   "Check CONTEXTS for agenda or capture KEY."
   8082   (let (res)
   8083     (dolist (r contexts)
   8084       (dolist (rr (car (last r)))
   8085 	(when
   8086 	    (and (equal key (car r))
   8087 		 (if (functionp rr) (funcall rr)
   8088 		   (or (and (eq (car rr) 'in-file)
   8089 			    (buffer-file-name)
   8090 			    (string-match (cdr rr) (buffer-file-name)))
   8091 		       (and (eq (car rr) 'in-mode)
   8092 			    (string-match (cdr rr) (symbol-name major-mode)))
   8093 		       (and (eq (car rr) 'in-buffer)
   8094 			    (string-match (cdr rr) (buffer-name)))
   8095 		       (when (and (eq (car rr) 'not-in-file)
   8096 				  (buffer-file-name))
   8097 			 (not (string-match (cdr rr) (buffer-file-name))))
   8098 		       (when (eq (car rr) 'not-in-mode)
   8099 			 (not (string-match (cdr rr) (symbol-name major-mode))))
   8100 		       (when (eq (car rr) 'not-in-buffer)
   8101 			 (not (string-match (cdr rr) (buffer-name)))))))
   8102 	  (push r res))))
   8103     (delete-dups (delq nil res))))
   8104 
   8105 ;; Defined to provide a value for defcustom, since there is no
   8106 ;; string-collate-greaterp in Emacs.
   8107 (defun org-string-collate-greaterp (s1 s2)
   8108   "Return non-nil if S1 is greater than S2 in collation order."
   8109   (not (string-collate-lessp s1 s2)))
   8110 
   8111 ;;;###autoload
   8112 (defun org-run-like-in-org-mode (cmd)
   8113   "Run a command, pretending that the current buffer is in Org mode.
   8114 This will temporarily bind local variables that are typically bound in
   8115 Org mode to the values they have in Org mode, and then interactively
   8116 call CMD."
   8117   (org-load-modules-maybe)
   8118   (let (vars vals)
   8119     (dolist (var (org-get-local-variables))
   8120       (when (or (not (boundp (car var)))
   8121 		(eq (symbol-value (car var))
   8122 		    (default-value (car var))))
   8123 	(push (car var) vars)
   8124 	(push (cadr var) vals)))
   8125     (cl-progv vars vals
   8126       (call-interactively cmd))))
   8127 
   8128 (defun org-get-category (&optional pos _)
   8129   "Get the category applying to position POS.
   8130 Return \"???\" when no category is set.
   8131 
   8132 This function may modify the match data."
   8133   ;; Sync cache.
   8134   (or (org-entry-get-with-inheritance
   8135        "CATEGORY" nil (or pos (point)))
   8136       "???"))
   8137 
   8138 ;;; Refresh properties
   8139 
   8140 (defun org-refresh-properties (dprop tprop)
   8141   "Refresh buffer text properties.
   8142 DPROP is the drawer property and TPROP is either the
   8143 corresponding text property to set, or an alist with each element
   8144 being a text property (as a symbol) and a function to apply to
   8145 the value of the drawer property."
   8146   (let* ((case-fold-search t)
   8147 	 (inhibit-read-only t)
   8148 	 (inherit? (org-property-inherit-p dprop))
   8149 	 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
   8150 	 (global-or-keyword (and inherit?
   8151 				 (org--property-global-or-keyword-value dprop nil))))
   8152     (with-silent-modifications
   8153       (org-with-point-at 1
   8154 	;; Set global and keyword based values to the whole buffer.
   8155 	(when global-or-keyword
   8156 	  (put-text-property (point-min) (point-max) tprop global-or-keyword))
   8157 	;; Set values based on property-drawers throughout the document.
   8158 	(while (re-search-forward property-re nil t)
   8159 	  (when (org-at-property-p)
   8160 	    (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
   8161 	  (outline-next-heading))))))
   8162 
   8163 (defun org-refresh-property (tprop p &optional inherit)
   8164   "Refresh the buffer text property TPROP from the drawer property P.
   8165 
   8166 The refresh happens only for the current entry, or the whole
   8167 sub-tree if optional argument INHERIT is non-nil.
   8168 
   8169 If point is before first headline, the function applies to the
   8170 part before the first headline.  In that particular case, when
   8171 optional argument INHERIT is non-nil, it refreshes properties for
   8172 the whole buffer."
   8173   (save-excursion
   8174     (org-back-to-heading-or-point-min t)
   8175     (let ((start (point))
   8176 	  (end (save-excursion
   8177 		 (cond ((and inherit (org-before-first-heading-p))
   8178 			(point-max))
   8179 		       (inherit
   8180 			(org-end-of-subtree t t))
   8181 		       ((outline-next-heading))
   8182 		       ((point-max))))))
   8183       (with-silent-modifications
   8184 	(if (symbolp tprop)
   8185 	    ;; TPROP is a text property symbol.
   8186 	    (put-text-property start end tprop p)
   8187 	  ;; TPROP is an alist with (property . function) elements.
   8188 	  (pcase-dolist (`(,prop . ,f) tprop)
   8189 	    (put-text-property start end prop (funcall f p))))))))
   8190 
   8191 (defun org-refresh-category-properties ()
   8192   "Refresh category text properties in the buffer."
   8193   (let ((case-fold-search t)
   8194 	(inhibit-read-only t)
   8195 	(default-category
   8196 	 (cond ((null org-category)
   8197 		(if buffer-file-name
   8198 		    (file-name-sans-extension
   8199 		     (file-name-nondirectory buffer-file-name))
   8200 		  "???"))
   8201 	       ((symbolp org-category) (symbol-name org-category))
   8202 	       (t org-category))))
   8203     (let ((category (catch 'buffer-category
   8204                       (org-with-wide-buffer
   8205 	               (goto-char (point-max))
   8206 	               (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
   8207 	                 (let ((element (org-element-at-point-no-context)))
   8208 	                   (when (org-element-type-p element 'keyword)
   8209 		             (throw 'buffer-category
   8210 		                    (org-element-property :value element))))))
   8211 	              default-category)))
   8212       (with-silent-modifications
   8213         (org-with-wide-buffer
   8214          ;; Set buffer-wide property from keyword.  Search last #+CATEGORY
   8215          ;; keyword.  If none is found, fall-back to `org-category' or
   8216          ;; buffer file name, or set it by the document property drawer.
   8217          (put-text-property (point-min) (point-max)
   8218                             'org-category category)
   8219          ;; Set categories from the document property drawer or
   8220          ;; property drawers in the outline.  If category is found in
   8221          ;; the property drawer for the whole buffer that value
   8222          ;; overrides the keyword-based value set above.
   8223          (goto-char (point-min))
   8224          (let ((regexp (org-re-property "CATEGORY")))
   8225            (while (re-search-forward regexp nil t)
   8226              (let ((value (match-string-no-properties 3)))
   8227                (when (org-at-property-p)
   8228                  (put-text-property
   8229                   (save-excursion (org-back-to-heading-or-point-min t))
   8230                   (save-excursion (if (org-before-first-heading-p)
   8231                                       (point-max)
   8232                                     (org-end-of-subtree t t)))
   8233                   'org-category
   8234                   value))))))))))
   8235 
   8236 (defun org-refresh-stats-properties ()
   8237   "Refresh stats text properties in the buffer."
   8238   (with-silent-modifications
   8239     (org-with-point-at 1
   8240       (let ((regexp (concat org-outline-regexp-bol
   8241 			    ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
   8242 	(while (re-search-forward regexp nil t)
   8243 	  (let* ((numerator (string-to-number (match-string 1)))
   8244 		 (denominator (and (match-end 2)
   8245 				   (string-to-number (match-string 2))))
   8246 		 (stats (cond ((not denominator) numerator) ;percent
   8247 			      ((= denominator 0) 0)
   8248 			      (t (/ (* numerator 100) denominator)))))
   8249 	    (put-text-property (point) (progn (org-end-of-subtree t t) (point))
   8250 			       'org-stats stats)))))))
   8251 
   8252 (defun org-refresh-effort-properties ()
   8253   "Refresh effort properties."
   8254   (org-refresh-properties
   8255    org-effort-property
   8256    '((effort . identity)
   8257      (effort-minutes . org-duration-to-minutes))))
   8258 
   8259 (defun org-find-file-at-mouse (ev)
   8260   "Open file link or URL at mouse."
   8261   (interactive "e")
   8262   (mouse-set-point ev)
   8263   (org-open-at-point 'in-emacs))
   8264 
   8265 (defun org-open-at-mouse (ev)
   8266   "Open file link or URL at mouse.
   8267 See the docstring of `org-open-file' for details."
   8268   (interactive "e")
   8269   (mouse-set-point ev)
   8270   (when (eq major-mode 'org-agenda-mode)
   8271     (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
   8272   ;; FIXME: This feature is actually unreliable - if we are in non-Org
   8273   ;; buffer and the link happens to be inside what Org parser
   8274   ;; recognizes as verbarim (for exampe, src block),
   8275   ;; `org-open-at-point' will do nothing.
   8276   ;; We might have used `org-open-at-point-global' instead, but it is
   8277   ;; not exactly the same. For example, it will have no way to open
   8278   ;; link abbreviations. So, suppressing parser complains about
   8279   ;; non-Org buffer to keep the feature working at least to the extent
   8280   ;; it did before.
   8281   (require 'warnings) ; Emacs <30
   8282   (defvar warning-suppress-types) ; warnings.el
   8283   (let ((warning-suppress-types
   8284          (cons '(org-element org-element-parser)
   8285                warning-suppress-types)))
   8286     ;; FIXME: Suppress warning in Emacs <30
   8287     ;; (ignore warning-suppress-types)
   8288     (org-open-at-point)))
   8289 
   8290 (defvar org-window-config-before-follow-link nil
   8291   "The window configuration before following a link.
   8292 This is saved in case the need arises to restore it.")
   8293 
   8294 (defun org--file-default-apps ()
   8295   "Return the default applications for this operating system."
   8296   (pcase system-type
   8297     (`darwin org-file-apps-macos)
   8298     (`windows-nt org-file-apps-windowsnt)
   8299     (_ org-file-apps-gnu)))
   8300 
   8301 (defun org--file-apps-entry-locator-p (entry)
   8302   "Non-nil if ENTRY should be matched against the link by `org-open-file'.
   8303 
   8304 It assumes that is the case when the entry uses a regular
   8305 expression which has at least one grouping construct and the
   8306 action is either a Lisp form or a command string containing
   8307 \"%1\", i.e., using at least one subexpression match as
   8308 a parameter."
   8309   (pcase entry
   8310     (`(,selector . ,action)
   8311      (and (stringp selector)
   8312 	  (> (regexp-opt-depth selector) 0)
   8313 	  (or (and (stringp action)
   8314 		   (string-match "%[0-9]" action))
   8315 	      (functionp action))))
   8316     (_ nil)))
   8317 
   8318 (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
   8319   "Convert extensions to regular expressions in the cars of LIST.
   8320 
   8321 Also, weed out any non-string entries, because the return value
   8322 is used only for regexp matching.
   8323 
   8324 When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
   8325 point to the symbol `emacs', indicating that the file should be
   8326 opened in Emacs."
   8327   (append
   8328    (delq nil
   8329 	 (mapcar (lambda (x)
   8330 		   (unless (not (stringp (car x)))
   8331 		     (if (string-match "\\W" (car x))
   8332 			 x
   8333 		       (cons (concat "\\." (car x) "\\'") (cdr x)))))
   8334 		 list))
   8335    (when add-auto-mode
   8336      (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
   8337 
   8338 (defun org--open-file-format-command
   8339     (mailcap-command file link match-data)
   8340   "Format MAILCAP-COMMAND to launch viewer for the FILE.
   8341 
   8342 MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
   8343 field from mailcap file loaded to `mailcap-mime-data'.  See \"RFC
   8344 1524.  A User Agent Configuration Mechanism For Multimedia Mail Format
   8345 Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
   8346 details, man page `mailcap(5)' for brief summary, and Info node
   8347 `(emacs-mime) mailcap' for specific related to Emacs.  Only a part of
   8348 mailcap specification is supported.
   8349 
   8350 The following substitutions are interpolated in the MAILCAP-COMMAND
   8351 string:
   8352 
   8353 - \"%s\" to FILE name passed through
   8354   `convert-standard-filename', so it must be absolute path.
   8355 
   8356 - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
   8357   the regular expression in the key part of the `org-file-apps' entry.
   8358   (performed by caller).  Not recommended, consider a lisp function
   8359   instead of a shell command.  For example, the following link in an
   8360   Org file
   8361 
   8362        <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
   8363 
   8364    may be handled by an `org-file-apps' entry like
   8365 
   8366        (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
   8367         . \"okular --find %2 %s%1\")
   8368 
   8369 Use backslash \"\\\" to quote percent \"%\" or any other character
   8370 including backslash itself.
   8371 
   8372 In addition, each argument is passed through `shell-quote-argument',
   8373 so quotes around substitutions should not be used.  For compliance
   8374 with mailcap files shipped e.g. in Debian GNU/Linux, single or double
   8375 quotes around substitutions are stripped.  It deviates from mailcap
   8376 specification that requires file name to be safe for shell and for the
   8377 application."
   8378   (let ((spec (list (cons ?s  (convert-standard-filename file))))
   8379         (ngroups (min 9 (- (/ (length match-data) 2) 1))))
   8380     (when (> ngroups 0)
   8381       (set-match-data match-data)
   8382       (dolist (i (number-sequence 1 ngroups))
   8383         (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
   8384     (replace-regexp-in-string
   8385      (rx (or (and "\\" (or (group anything) string-end))
   8386              (and (optional (group (any "'\"")))
   8387                   "%"
   8388                   (or (group anything) string-end)
   8389                   (optional (group (backref 2))))))
   8390      (lambda (fmt)
   8391        (let* ((backslash (match-string-no-properties 1 fmt))
   8392               (key (match-string 3 fmt))
   8393               (value (and key (alist-get (string-to-char key) spec))))
   8394          (cond
   8395           (backslash)
   8396           (value (let ((quot (match-string 2 fmt))
   8397                        (subst (shell-quote-argument value)))
   8398                    ;; Remove quotes around the file name - we use
   8399                    ;; `shell-quote-argument'.
   8400                    (if (match-string 4 fmt)
   8401                        subst
   8402                      (concat quot subst))))
   8403           (t (error "Invalid format `%s'" fmt)))))
   8404      mailcap-command nil 'literal)))
   8405 
   8406 ;;;###autoload
   8407 (defun org-open-file (path &optional in-emacs line search)
   8408   "Open the file at PATH.
   8409 First, this expands any special file name abbreviations.  Then the
   8410 configuration variable `org-file-apps' is checked if it contains an
   8411 entry for this file type, and if yes, the corresponding command is launched.
   8412 
   8413 If no application is found, Emacs simply visits the file.
   8414 
   8415 With optional prefix argument IN-EMACS, Emacs will visit the file.
   8416 With a double \\[universal-argument] \\[universal-argument] \
   8417 prefix arg, Org tries to avoid opening in Emacs
   8418 and to use an external application to visit the file.
   8419 
   8420 Optional LINE specifies a line to go to, optional SEARCH a string
   8421 to search for.  If LINE or SEARCH is given, the file will be
   8422 opened in Emacs, unless an entry from `org-file-apps' that makes
   8423 use of groups in a regexp matches.
   8424 
   8425 If you want to change the way frames are used when following a
   8426 link, please customize `org-link-frame-setup'.
   8427 
   8428 If the file does not exist, throw an error."
   8429   (let* ((file (if (equal path "") buffer-file-name
   8430 		 (substitute-in-file-name (expand-file-name path))))
   8431 	 (file-apps (append org-file-apps (org--file-default-apps)))
   8432 	 (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
   8433 	 (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
   8434                                          file-apps))
   8435 	 (remp (and (assq 'remote apps) (file-remote-p file)))
   8436 	 (dirp (unless remp (file-directory-p file)))
   8437 	 (file (if (and dirp org-open-directory-means-index-dot-org)
   8438 		   (concat (file-name-as-directory file) "index.org")
   8439 		 file))
   8440 	 (a-m-a-p (assq 'auto-mode apps))
   8441 	 (dfile (downcase file))
   8442 	 ;; Reconstruct the original link from the PATH, LINE and
   8443 	 ;; SEARCH args.
   8444 	 (link (cond (line (concat file "::" (number-to-string line)))
   8445 		     (search (concat file "::" search))
   8446 		     (t file)))
   8447 	 (ext
   8448 	  (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
   8449 	       (match-string 1 dfile)))
   8450 	 (save-position-maybe
   8451 	  (let ((old-buffer (current-buffer))
   8452 		(old-pos (point))
   8453 		(old-mode major-mode))
   8454 	    (lambda ()
   8455 	      (and (derived-mode-p 'org-mode)
   8456 		   (eq old-mode 'org-mode)
   8457 		   (or (not (eq old-buffer (current-buffer)))
   8458 		       (not (eq old-pos (point))))
   8459 		   (org-mark-ring-push old-pos old-buffer)))))
   8460 	 cmd link-match-data)
   8461     (cond
   8462      ((member in-emacs '((16) system))
   8463       (setq cmd (cdr (assq 'system apps))))
   8464      (in-emacs (setq cmd 'emacs))
   8465      (t
   8466       (setq cmd (or (and remp (cdr (assq 'remote apps)))
   8467 		    (and dirp (cdr (assq 'directory apps)))
   8468 		    ;; First, try matching against apps-locator if we
   8469 		    ;; get a match here, store the match data for
   8470 		    ;; later.
   8471 		    (let* ((case-fold-search t)
   8472                            (match (assoc-default link apps-locator
   8473                                                  'string-match)))
   8474 		      (if match
   8475 			  (progn (setq link-match-data (match-data))
   8476 				 match)
   8477 			(progn (setq in-emacs (or in-emacs line search))
   8478 			       nil))) ; if we have no match in apps-locator,
   8479 					; always open the file in emacs if line or search
   8480 					; is given (for backwards compatibility)
   8481 		    (assoc-default dfile
   8482 				   (org--file-apps-regexp-alist apps a-m-a-p)
   8483 				   'string-match)
   8484 		    (cdr (assoc ext apps))
   8485 		    (cdr (assq t apps))))))
   8486     (when (eq cmd 'system)
   8487       (setq cmd (cdr (assq 'system apps))))
   8488     (when (eq cmd 'default)
   8489       (setq cmd (cdr (assoc t apps))))
   8490     (when (eq cmd 'mailcap)
   8491       (require 'mailcap)
   8492       (mailcap-parse-mailcaps)
   8493       (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
   8494 	     (command (mailcap-mime-info mime-type)))
   8495 	(if (stringp command)
   8496 	    (setq cmd command)
   8497 	  (setq cmd 'emacs))))
   8498     (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
   8499 	       (not (file-exists-p file))
   8500 	       (not org-open-non-existing-files))
   8501       (user-error "No such file: %s" file))
   8502     (cond
   8503      ((org-string-nw-p cmd)
   8504       (setq cmd (org--open-file-format-command cmd file link link-match-data))
   8505 
   8506       (save-window-excursion
   8507 	(message "Running %s...done" cmd)
   8508         ;; Handlers such as "gio open" and kde-open5 start viewer in background
   8509         ;; and exit immediately.  Use pipe connection type instead of pty to
   8510         ;; avoid killing children processes with SIGHUP when temporary terminal
   8511         ;; session is finished.
   8512         ;;
   8513         ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
   8514         ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
   8515         ;; error messages.
   8516         (let ((process-connection-type nil))
   8517 	  (start-process-shell-command cmd nil cmd))
   8518 	(and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
   8519      ((or (stringp cmd)
   8520 	  (eq cmd 'emacs))
   8521       (funcall (cdr (assq 'file org-link-frame-setup)) file)
   8522       (widen)
   8523       (cond (line (org-goto-line line)
   8524 		  (when (derived-mode-p 'org-mode) (org-fold-reveal)))
   8525 	    (search (condition-case err
   8526 			(org-link-search search)
   8527 		      ;; Save position before error-ing out so user
   8528 		      ;; can easily move back to the original buffer.
   8529 		      (error (funcall save-position-maybe)
   8530 			     (error "%s" (error-message-string err)))))))
   8531      ((functionp cmd)
   8532       (save-match-data
   8533 	(set-match-data link-match-data)
   8534 	(condition-case nil
   8535 	    (funcall cmd file link)
   8536 	  ;; FIXME: Remove this check when most default installations
   8537 	  ;; of Emacs have at least Org 9.0.
   8538 	  ((debug wrong-number-of-arguments wrong-type-argument
   8539 		  invalid-function)
   8540 	   (user-error "Please see Org News for version 9.0 about \
   8541 `org-file-apps'--Lisp error: %S" cmd)))))
   8542      ((consp cmd)
   8543       ;; FIXME: Remove this check when most default installations of
   8544       ;; Emacs have at least Org 9.0.  Heads-up instead of silently
   8545       ;; fall back to `org-link-frame-setup' for an old usage of
   8546       ;; `org-file-apps' with sexp instead of a function for `cmd'.
   8547       (user-error "Please see Org News for version 9.0 about \
   8548 `org-file-apps'--Error: Deprecated usage of %S" cmd))
   8549      (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
   8550     (funcall save-position-maybe)))
   8551 
   8552 ;;;###autoload
   8553 (defun org-open-at-point-global ()
   8554   "Follow a link or a timestamp like Org mode does.
   8555 Also follow links and emails as seen by `thing-at-point'.
   8556 This command can be called in any mode to follow an external
   8557 link or a timestamp that has Org mode syntax.  Its behavior
   8558 is undefined when called on internal links like fuzzy links.
   8559 Raise a user error when there is nothing to follow."
   8560   (interactive)
   8561   (let ((tap-url (thing-at-point 'url))
   8562 	(tap-email (thing-at-point 'email)))
   8563     (cond ((org-in-regexp
   8564             org-link-any-re
   8565             (let ((origin (point)))
   8566               (max
   8567                (save-excursion
   8568                  (backward-paragraph)
   8569                  (count-lines (point) origin))
   8570                (save-excursion
   8571                  (forward-paragraph)
   8572                  (count-lines origin (point))))))
   8573 	   (org-link-open-from-string (match-string-no-properties 0)))
   8574 	  ((or (org-in-regexp org-ts-regexp-both nil t)
   8575 	       (org-in-regexp org-tsr-regexp-both nil t))
   8576 	   (org-follow-timestamp-link))
   8577 	  (tap-url (org-link-open-from-string tap-url))
   8578 	  (tap-email (org-link-open-from-string
   8579 		      (concat "mailto:" tap-email)))
   8580 	  (t (user-error "No link found")))))
   8581 
   8582 (defvar org-open-at-point-functions nil
   8583   "Hook that is run when following a link at point.
   8584 
   8585 Functions in this hook must return t if they identify and follow
   8586 a link at point.  If they don't find anything interesting at point,
   8587 they must return nil.")
   8588 
   8589 (defun org-open-at-point (&optional arg)
   8590   "Open thing at point.
   8591 The thing can be a link, citation, timestamp, footnote, src-block or
   8592 tags.
   8593 
   8594 When point is on a link, follow it.  Normally, files will be opened by
   8595 an appropriate application (see `org-file-apps').  If the optional prefix
   8596 argument ARG is non-nil, Emacs will visit the file.  With a double
   8597 prefix argument, try to open outside of Emacs, in the application the
   8598 system uses for this file type.
   8599 
   8600 When point is on a timestamp, open the agenda at the day
   8601 specified.
   8602 
   8603 When point is a footnote definition, move to the first reference
   8604 found.  If it is on a reference, move to the associated
   8605 definition.
   8606 
   8607 When point is on a src-block of inline src-block, open its result.
   8608 
   8609 When point is on a citation, follow it.
   8610 
   8611 When point is on a headline, display a list of every link in the
   8612 entry, so it is possible to pick one, or all, of them.  If point
   8613 is on a tag, call `org-tags-view' instead.
   8614 
   8615 On top of syntactically correct links, this function also tries
   8616 to open links and timestamps in comments, node properties, and
   8617 keywords if point is on something looking like a timestamp or
   8618 a link."
   8619   (interactive "P")
   8620   (org-load-modules-maybe)
   8621   (setq org-window-config-before-follow-link (current-window-configuration))
   8622   (org-remove-occur-highlights nil nil t)
   8623   (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
   8624     (let* ((context
   8625 	    ;; Only consider supported types, even if they are not the
   8626 	    ;; closest one.
   8627 	    (org-element-lineage
   8628 	     (org-element-context)
   8629 	     '(citation citation-reference clock comment comment-block
   8630                         footnote-definition footnote-reference headline
   8631                         inline-src-block inlinetask keyword link node-property
   8632                         planning src-block timestamp)
   8633 	     t))
   8634 	   (type (org-element-type context))
   8635 	   (value (org-element-property :value context)))
   8636       (cond
   8637        ((not type) (user-error "No link found"))
   8638        ;; No valid link at point.  For convenience, look if something
   8639        ;; looks like a link under point in some specific places.
   8640        ((memq type '(comment comment-block node-property keyword))
   8641 	(call-interactively #'org-open-at-point-global))
   8642        ;; On a headline or an inlinetask, but not on a timestamp,
   8643        ;; a link, a footnote reference or a citation.
   8644        ((memq type '(headline inlinetask))
   8645 	(org-match-line org-complex-heading-regexp)
   8646 	(let ((tags-beg (match-beginning 5))
   8647 	      (tags-end (match-end 5)))
   8648 	  (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
   8649 	      ;; On tags.
   8650 	      (org-tags-view
   8651 	       arg
   8652 	       (save-excursion
   8653 		 (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
   8654 			(end-tag (search-forward ":" tags-end nil 2)))
   8655 		   (buffer-substring (1+ beg-tag) (1- end-tag)))))
   8656 	    ;; Not on tags.
   8657 	    (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
   8658 	      (`(nil . ,_)
   8659 	       (require 'org-attach)
   8660 	       (when (org-attach-dir)
   8661 		 (message "Opening attachment")
   8662 		 (if (equal arg '(4))
   8663 		     (org-attach-reveal-in-emacs)
   8664 		   (org-attach-reveal))))
   8665 	      (`(,links . ,links-end)
   8666                (let ((link-marker (make-marker))
   8667                      (last-moved-marker (point-marker)))
   8668 	         (dolist (link (if (stringp links) (list links) links))
   8669 		   (search-forward link nil links-end)
   8670 		   (goto-char (match-beginning 0))
   8671                    (move-marker link-marker (point))
   8672                    (save-excursion
   8673 		     (org-open-at-point arg)
   8674                      (unless (equal (point-marker) link-marker)
   8675                        (move-marker last-moved-marker (point-marker)))))
   8676                  ;; If any of the links moved point in current buffer,
   8677                  ;; move to the point corresponding to such latest link.
   8678                  ;; Otherwise, restore the original point position.
   8679                  (goto-char last-moved-marker)))))))
   8680        ;; On a footnote reference or at definition's label.
   8681        ((or (eq type 'footnote-reference)
   8682 	    (and (eq type 'footnote-definition)
   8683 		 (save-excursion
   8684 		   ;; Do not validate action when point is on the
   8685 		   ;; spaces right after the footnote label, in order
   8686 		   ;; to be on par with behavior on links.
   8687 		   (skip-chars-forward " \t")
   8688 		   (let ((begin
   8689 			  (org-element-contents-begin context)))
   8690 		     (if begin (< (point) begin)
   8691 		       (= (org-element-post-affiliated context)
   8692 			  (line-beginning-position)))))))
   8693 	(org-footnote-action))
   8694        ;; On a planning line.  Check if we are really on a timestamp.
   8695        ((and (eq type 'planning)
   8696 	     (org-in-regexp org-ts-regexp-both nil t))
   8697 	(org-follow-timestamp-link))
   8698        ;; On a clock line, make sure point is on the timestamp
   8699        ;; before opening it.
   8700        ((and (eq type 'clock)
   8701 	     value
   8702 	     (>= (point) (org-element-begin value))
   8703 	     (<= (point) (org-element-end value)))
   8704 	(org-follow-timestamp-link))
   8705        ((eq type 'src-block) (org-babel-open-src-block-result))
   8706        ;; Do nothing on white spaces after an object.
   8707        ((>= (point)
   8708 	    (save-excursion
   8709 	      (goto-char (org-element-end context))
   8710 	      (skip-chars-backward " \t")
   8711 	      (point)))
   8712 	(user-error "No link found"))
   8713        ((eq type 'inline-src-block) (org-babel-open-src-block-result))
   8714        ((eq type 'timestamp) (org-follow-timestamp-link))
   8715        ((eq type 'link) (org-link-open context arg))
   8716        ((memq type '(citation citation-reference)) (org-cite-follow context arg))
   8717        (t (user-error "No link found")))))
   8718   (run-hook-with-args 'org-follow-link-hook))
   8719 
   8720 ;;;###autoload
   8721 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
   8722   "Offer links in the current entry and return the selected link.
   8723 If there is only one link, return it.
   8724 If NTH is an integer, return the NTH link found.
   8725 If ZERO is a string, check also this string for a link, and if
   8726 there is one, return it."
   8727   (with-current-buffer buffer
   8728     (org-with-wide-buffer
   8729      (goto-char marker)
   8730      (let ((cnt ?0)
   8731 	   have-zero end links link c)
   8732        (when (and (stringp zero) (string-match org-link-bracket-re zero))
   8733 	 (push (match-string 0 zero) links)
   8734 	 (setq cnt (1- cnt) have-zero t))
   8735        (save-excursion
   8736 	 (org-back-to-heading t)
   8737 	 (setq end (save-excursion (outline-next-heading) (point)))
   8738 	 (while (re-search-forward org-link-any-re end t)
   8739            ;; Only consider valid links or links openable via
   8740            ;; `org-open-at-point'.
   8741            (when (org-element-type-p
   8742                   (save-match-data (org-element-context))
   8743                   '(link comment comment-block node-property keyword))
   8744 	     (push (match-string 0) links)))
   8745 	 (setq links (org-uniquify (reverse links))))
   8746        (cond
   8747 	((null links)
   8748 	 (message "No links"))
   8749 	((equal (length links) 1)
   8750 	 (setq link (car links)))
   8751 	((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
   8752 	 (setq link (nth (if have-zero nth (1- nth)) links)))
   8753 	(t				; we have to select a link
   8754 	 (save-excursion
   8755 	   (save-window-excursion
   8756              ;; We have no direct control over how
   8757              ;; `with-output-to-temp-buffer' displays the buffer.  Try
   8758              ;; to gain more space, making sure that only the Org
   8759              ;; buffer and the *Select link* buffer are displayed for
   8760              ;; the duration of selection.
   8761 	     (ignore-errors (delete-other-windows))
   8762 	     (with-output-to-temp-buffer "*Select Link*"
   8763 	       (dolist (l links)
   8764 		 (cond
   8765 		  ((not (string-match org-link-bracket-re l))
   8766 		   (princ (format "[%c]  %s\n" (cl-incf cnt)
   8767 				  (org-unbracket-string "<" ">" l))))
   8768 		  ((match-end 2)
   8769 		   (princ (format "[%c]  %s (%s)\n" (cl-incf cnt)
   8770 				  (match-string 2 l) (match-string 1 l))))
   8771 		  (t (princ (format "[%c]  %s\n" (cl-incf cnt)
   8772 				    (match-string 1 l)))))))
   8773 	     (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
   8774 	     (message "Select link to open, RET to open all:")
   8775              (unwind-protect (setq c (read-char-exclusive))
   8776                (and (get-buffer-window "*Select Link*" t)
   8777                     (quit-window 'kill (get-buffer-window "*Select Link*" t)))
   8778 	       (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*")))))
   8779 	 (when (equal c ?q) (user-error "Abort"))
   8780 	 (if (equal c ?\C-m)
   8781 	     (setq link links)
   8782 	   (setq nth (- c ?0))
   8783 	   (when have-zero (setq nth (1+ nth)))
   8784 	   (unless (and (integerp nth) (>= (length links) nth))
   8785 	     (user-error "Invalid link selection"))
   8786 	   (setq link (nth (1- nth) links)))))
   8787        (cons link end)))))
   8788 
   8789 (defun org--link-at-point ()
   8790   "`thing-at-point' provider function."
   8791   (org-element-property :raw-link (org-element-context)))
   8792 
   8793 (defun org--bounds-of-link-at-point ()
   8794   "`bounds-of-thing-at-point' provider function."
   8795   (let ((context (org-element-context)))
   8796     (when (eq (org-element-type context) 'link)
   8797       (cons (org-element-begin context)
   8798             (org-element-end context)))))
   8799 
   8800 ;;; File search
   8801 
   8802 (defun org-do-occur (regexp &optional cleanup)
   8803   "Call the Emacs command `occur'.
   8804 If CLEANUP is non-nil, remove the printout of the regular expression
   8805 in the *Occur* buffer.  This is useful if the regex is long and not useful
   8806 to read."
   8807   (occur regexp)
   8808   (when cleanup
   8809     (let ((cwin (selected-window)) win beg end)
   8810       (when (setq win (get-buffer-window "*Occur*"))
   8811 	(select-window win))
   8812       (goto-char (point-min))
   8813       (when (re-search-forward "match[a-z]+" nil t)
   8814 	(setq beg (match-end 0))
   8815 	(when (re-search-forward "^[ \t]*[0-9]+" nil t)
   8816 	  (setq end (1- (match-beginning 0)))))
   8817       (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
   8818       (goto-char (point-min))
   8819       (select-window cwin))))
   8820 
   8821 
   8822 ;;; The Mark Ring
   8823 
   8824 (defvar org-mark-ring nil
   8825   "Mark ring for positions before jumps in Org mode.")
   8826 
   8827 (defvar org-mark-ring-last-goto nil
   8828   "Last position in the mark ring used to go back.")
   8829 
   8830 ;; Fill and close the ring
   8831 (setq org-mark-ring nil)
   8832 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
   8833 
   8834 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
   8835 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
   8836 	org-mark-ring)
   8837 
   8838 (defun org-mark-ring-push (&optional pos buffer)
   8839   "Put the current position into the mark ring and rotate it.
   8840 Also push position into the Emacs mark ring.  If optional
   8841 argument POS and BUFFER are not nil, mark this location instead."
   8842   (interactive)
   8843   (let ((pos (or pos (point)))
   8844 	(buffer (or buffer (current-buffer))))
   8845     (with-current-buffer buffer
   8846       (org-with-point-at pos (push-mark nil t)))
   8847     (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
   8848     (move-marker (car org-mark-ring) pos buffer))
   8849   (message
   8850    (substitute-command-keys
   8851     "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
   8852 
   8853 (defun org-mark-ring-goto (&optional n)
   8854   "Jump to the previous position in the mark ring.
   8855 With prefix arg N, jump back that many stored positions.  When
   8856 called several times in succession, walk through the entire ring.
   8857 Org mode commands jumping to a different position in the current file,
   8858 or to another Org file, automatically push the old position onto the ring."
   8859   (interactive "p")
   8860   (let (p m)
   8861     (if (eq last-command this-command)
   8862 	(setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
   8863       (setq p org-mark-ring))
   8864     (setq org-mark-ring-last-goto p)
   8865     (setq m (car p))
   8866     (pop-to-buffer-same-window (marker-buffer m))
   8867     (goto-char m)
   8868     (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
   8869 
   8870 ;;; Following specific links
   8871 
   8872 (defvar org-agenda-buffer-tmp-name)
   8873 (defvar org-agenda-start-on-weekday)
   8874 (defvar org-agenda-buffer-name)
   8875 (defun org-follow-timestamp-link ()
   8876   "Open an agenda view for the timestamp date/range at point."
   8877   (require 'org-agenda)
   8878   ;; Avoid changing the global value.
   8879   (let ((org-agenda-buffer-name org-agenda-buffer-name))
   8880     (cond
   8881      ((org-at-date-range-p t)
   8882       (let ((org-agenda-start-on-weekday)
   8883 	    (t1 (match-string 1))
   8884 	    (t2 (match-string 2)) tt1 tt2)
   8885 	(setq tt1 (time-to-days (org-time-string-to-time t1))
   8886 	      tt2 (time-to-days (org-time-string-to-time t2)))
   8887 	(let ((org-agenda-buffer-tmp-name
   8888 	       (format "*Org Agenda(a:%s)"
   8889 		       (concat (substring t1 0 10) "--" (substring t2 0 10)))))
   8890 	  (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
   8891      ((org-at-timestamp-p 'lax)
   8892       (let ((org-agenda-buffer-tmp-name
   8893 	     (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
   8894 	(org-agenda-list nil (time-to-days (org-time-string-to-time
   8895 					    (substring (match-string 1) 0 10)))
   8896 			 1)))
   8897      (t (error "This should not happen")))))
   8898 
   8899 
   8900 ;;; Following file links
   8901 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
   8902 (declare-function mailcap-extension-to-mime "mailcap" (extn))
   8903 (declare-function mailcap-mime-info
   8904 		  "mailcap" (string &optional request no-decode))
   8905 (defvar org-wait nil)
   8906 
   8907 ;;;; Refiling
   8908 
   8909 (defun org-get-org-file ()
   8910   "Read a filename, with default directory `org-directory'."
   8911   (let ((default (or org-default-notes-file remember-data-file)))
   8912     (read-file-name (format "File name [%s]: " default)
   8913 		    (file-name-as-directory org-directory)
   8914 		    default)))
   8915 
   8916 (defun org-notes-order-reversed-p ()
   8917   "Check if the current file should receive notes in reversed order."
   8918   (cond
   8919    ((not org-reverse-note-order) nil)
   8920    ((listp org-reverse-note-order)
   8921     (catch 'exit
   8922         (dolist (entry org-reverse-note-order)
   8923           (when (string-match (car entry) buffer-file-name)
   8924 	    (throw 'exit (cdr entry))))))
   8925    (t org-reverse-note-order)))
   8926 
   8927 (defvar org-agenda-new-buffers nil
   8928   "Buffers created to visit agenda files.")
   8929 
   8930 (declare-function org-string-nw-p "org-macs" (s))
   8931 ;;;; Dynamic blocks
   8932 
   8933 (defun org-find-dblock (name)
   8934   "Find the first dynamic block with name NAME in the buffer.
   8935 If not found, stay at current position and return nil."
   8936   (let ((case-fold-search t) pos)
   8937     (save-excursion
   8938       (goto-char (point-min))
   8939       (setq pos (and (re-search-forward
   8940 		      (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
   8941 		     (match-beginning 0))))
   8942     (when pos (goto-char pos))
   8943     pos))
   8944 
   8945 (defun org-create-dblock (plist)
   8946   "Create a dynamic block section, with parameters taken from PLIST.
   8947 PLIST must contain a :name entry which is used as the name of the block."
   8948   (when (string-match "\\S-" (buffer-substring (line-beginning-position)
   8949                                               (line-end-position)))
   8950     (end-of-line 1)
   8951     (newline))
   8952   (let ((col (current-column))
   8953 	(name (plist-get plist :name)))
   8954     (insert "#+BEGIN: " name)
   8955     (while plist
   8956       (if (eq (car plist) :name)
   8957 	  (setq plist (cddr plist))
   8958 	(insert " " (prin1-to-string (pop plist)))))
   8959     (insert "\n\n" (make-string col ?\ ) "#+END:\n")
   8960     (forward-line -3)))
   8961 
   8962 (defun org-prepare-dblock ()
   8963   "Prepare dynamic block for refresh.
   8964 This empties the block, puts the cursor at the insert position and returns
   8965 the property list including an extra property :name with the block name."
   8966   (unless (looking-at org-dblock-start-re)
   8967     (user-error "Not at a dynamic block"))
   8968   (let* ((begdel (1+ (match-end 0)))
   8969 	 (name (org-no-properties (match-string 1)))
   8970 	 (params (append (list :name name)
   8971 			 (read (concat "(" (match-string 3) ")")))))
   8972     (save-excursion
   8973       (forward-line 0)
   8974       (skip-chars-forward " \t")
   8975       (setq params (plist-put params :indentation-column (current-column))))
   8976     (unless (re-search-forward org-dblock-end-re nil t)
   8977       (error "Dynamic block not terminated"))
   8978     (setq params
   8979 	  (append params
   8980 		  (list :content (buffer-substring
   8981 				  begdel (match-beginning 0)))))
   8982     (delete-region begdel (match-beginning 0))
   8983     (goto-char begdel)
   8984     (open-line 1)
   8985     params))
   8986 
   8987 (defun org-map-dblocks (&optional command)
   8988   "Apply COMMAND to all dynamic blocks in the current buffer.
   8989 If COMMAND is not given, use `org-update-dblock'."
   8990   (let ((cmd (or command 'org-update-dblock)))
   8991     (save-excursion
   8992       (goto-char (point-min))
   8993       (while (re-search-forward org-dblock-start-re nil t)
   8994 	(goto-char (match-beginning 0))
   8995         (save-excursion
   8996           (condition-case-unless-debug nil
   8997               (funcall cmd)
   8998             (error (message "Error during update of dynamic block"))))
   8999 	(unless (re-search-forward org-dblock-end-re nil t)
   9000 	  (error "Dynamic block not terminated"))))))
   9001 
   9002 (defvar org-dynamic-block-alist nil
   9003   "Alist defining all the Org dynamic blocks.
   9004 
   9005 The key is the dynamic block type name, as a string.  The value
   9006 is the function used to insert the dynamic block.
   9007 
   9008 Use `org-dynamic-block-define' to populate it.")
   9009 
   9010 (defun org-dynamic-block-function (type)
   9011   "Return function associated to a given dynamic block type.
   9012 TYPE is the dynamic block type, as a string."
   9013   (cdr (assoc type org-dynamic-block-alist)))
   9014 
   9015 (defun org-dynamic-block-types ()
   9016   "List all defined dynamic block types."
   9017   (mapcar #'car org-dynamic-block-alist))
   9018 
   9019 ;;;###org-autoload
   9020 (defun org-dynamic-block-define (type func)
   9021   "Define dynamic block TYPE with FUNC.
   9022 TYPE is a string.  FUNC is the function creating the dynamic
   9023 block of such type.  FUNC must be able to accept zero arguments."
   9024   (pcase (assoc type org-dynamic-block-alist)
   9025     (`nil (push (cons type func) org-dynamic-block-alist))
   9026     (def (setcdr def func))))
   9027 
   9028 (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
   9029   "Insert a dynamic block of type TYPE.
   9030 When used interactively, select the dynamic block types among
   9031 defined types, per `org-dynamic-block-define'.  If INTERACTIVE-P
   9032 is non-nil, call the dynamic block function interactively."
   9033   (interactive (list (completing-read "Dynamic block: "
   9034 				      (org-dynamic-block-types))
   9035 		     t))
   9036   (pcase (org-dynamic-block-function type)
   9037     (`nil (error "No such dynamic block: %S" type))
   9038     ((and f (pred functionp))
   9039      (if (and interactive-p (commandp f)) (call-interactively f) (funcall f)))
   9040     (_ (error "Invalid function for dynamic block %S" type))))
   9041 
   9042 (defun org-dblock-update (&optional arg)
   9043   "User command for updating dynamic blocks.
   9044 Update the dynamic block at point.  With prefix ARG, update all dynamic
   9045 blocks in the buffer."
   9046   (interactive "P")
   9047   (if arg
   9048       (org-update-all-dblocks)
   9049     (or (looking-at org-dblock-start-re)
   9050 	(org-beginning-of-dblock))
   9051     (org-update-dblock)))
   9052 
   9053 (defun org-update-dblock ()
   9054   "Update the dynamic block at point.
   9055 This means to empty the block, parse for parameters and then call
   9056 the correct writing function."
   9057   (interactive)
   9058   (save-excursion
   9059     (let* ((win (selected-window))
   9060 	   (pos (point))
   9061 	   (line (org-current-line))
   9062 	   (params
   9063             ;; Called for side effect.
   9064             (org-prepare-dblock))
   9065 	   (name (plist-get params :name))
   9066 	   (indent (plist-get params :indentation-column))
   9067 	   (cmd (intern (concat "org-dblock-write:" name))))
   9068       (message "Updating dynamic block `%s' at line %d..." name line)
   9069       (funcall cmd params)
   9070       (message "Updating dynamic block `%s' at line %d...done" name line)
   9071       (goto-char pos)
   9072       (when (and indent (> indent 0))
   9073 	(setq indent (make-string indent ?\ ))
   9074 	(save-excursion
   9075 	  (select-window win)
   9076 	  (org-beginning-of-dblock)
   9077 	  (forward-line 1)
   9078 	  (while (not (looking-at org-dblock-end-re))
   9079 	    (insert indent)
   9080 	    (forward-line 1))
   9081 	  (when (looking-at org-dblock-end-re)
   9082 	    (and (looking-at "[ \t]+")
   9083 		 (replace-match ""))
   9084 	    (insert indent)))))))
   9085 
   9086 (defun org-beginning-of-dblock ()
   9087   "Find the beginning of the dynamic block at point.
   9088 Error if there is no such block at point."
   9089   (let ((pos (point))
   9090 	beg)
   9091     (end-of-line 1)
   9092     (if (and (re-search-backward org-dblock-start-re nil t)
   9093 	     (setq beg (match-beginning 0))
   9094 	     (re-search-forward org-dblock-end-re nil t)
   9095 	     (> (match-end 0) pos))
   9096 	(goto-char beg)
   9097       (goto-char pos)
   9098       (error "Not in a dynamic block"))))
   9099 
   9100 (defun org-update-all-dblocks ()
   9101   "Update all dynamic blocks in the buffer.
   9102 This function can be used in a hook."
   9103   (interactive)
   9104   (when (derived-mode-p 'org-mode)
   9105     (org-map-dblocks 'org-update-dblock)))
   9106 
   9107 
   9108 ;;;; Completion
   9109 
   9110 (declare-function org-export-backend-options "ox" (cl-x) t)
   9111 (defun org-get-export-keywords ()
   9112   "Return a list of all currently understood export keywords.
   9113 Export keywords include options, block names, attributes and
   9114 keywords relative to each registered export backend."
   9115   (let (keywords)
   9116     (dolist (backend
   9117 	     (bound-and-true-p org-export-registered-backends)
   9118 	     (delq nil keywords))
   9119       ;; Backend name (for keywords, like #+LATEX:)
   9120       (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
   9121       ;; Backend attributes, like #+ATTR_LATEX:
   9122       (push (format "ATTR_%s" (upcase (symbol-name (org-export-backend-name backend)))) keywords)
   9123       (dolist (option-entry (org-export-backend-options backend))
   9124 	;; Backend options.
   9125 	(push (nth 1 option-entry) keywords)))))
   9126 
   9127 (defconst org-options-keywords
   9128   '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
   9129     "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
   9130     "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
   9131     "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY:" "PRIORITIES:"
   9132     "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
   9133     "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "EXPORT_FILE_NAME:"))
   9134 
   9135 (defcustom org-structure-template-alist
   9136   '(("a" . "export ascii")
   9137     ("c" . "center")
   9138     ("C" . "comment")
   9139     ("e" . "example")
   9140     ("E" . "export")
   9141     ("h" . "export html")
   9142     ("l" . "export latex")
   9143     ("q" . "quote")
   9144     ("s" . "src")
   9145     ("v" . "verse"))
   9146   "An alist of keys and block types.
   9147 `org-insert-structure-template' will display a menu with this list of
   9148 templates to choose from.  The block type is inserted, with
   9149 \"#+begin_\" and \"#+end_\" added automatically.  If the block type
   9150 consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
   9151 added instead.
   9152 
   9153 The menu keys are defined by the car of each entry in this alist.
   9154 If two entries have the keys \"a\" and \"aa\" respectively, the
   9155 former will be inserted by typing \"a TAB/RET/SPC\" and the
   9156 latter will be inserted by typing \"aa\".  If an entry with the
   9157 key \"aab\" is later added, it can be inserted by typing \"ab\".
   9158 
   9159 If loaded, Org Tempo also uses `org-structure-template-alist'.  A
   9160 block can be inserted by pressing TAB after the string \"<KEY\"."
   9161   :group 'org-edit-structure
   9162   :type '(repeat
   9163 	  (cons (string :tag "Key")
   9164 		(string :tag "Template")))
   9165   :package-version '(Org . "9.6"))
   9166 
   9167 (defun org--check-org-structure-template-alist (&optional checklist)
   9168   "Check whether `org-structure-template-alist' is set up correctly.
   9169 In particular, check if the Org 9.2 format is used as opposed to
   9170 previous format."
   9171   (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
   9172 			       (or (symbol-value checklist)
   9173 				   org-structure-template-alist))))
   9174     (when elm
   9175       (org-display-warning
   9176        (format "
   9177 Please update the entries of `%s'.
   9178 
   9179 In Org 9.2 the format was changed from something like
   9180 
   9181     (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
   9182 
   9183 to something like
   9184 
   9185     (\"s\" . \"src\")
   9186 
   9187 Please refer to the documentation of `org-structure-template-alist'.
   9188 
   9189 The following entries must be updated:
   9190 
   9191 %s"
   9192 	       (or checklist 'org-structure-template-alist)
   9193 	       (pp-to-string elm))))))
   9194 
   9195 (defun org--insert-structure-template-mks ()
   9196   "Present `org-structure-template-alist' with `org-mks'.
   9197 
   9198 Menus are added if keys require more than one keystroke.  Tabs
   9199 are added to single key entries when more than one stroke is
   9200 needed.  Keys longer than two characters are reduced to two
   9201 characters."
   9202   (org--check-org-structure-template-alist)
   9203   (let* (case-fold-search
   9204 	 (templates (append org-structure-template-alist
   9205 			    '(("\t" . "Press TAB, RET or SPC to write block name"))))
   9206          (keys (mapcar #'car templates))
   9207          (start-letters
   9208 	  (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
   9209 	 ;; Sort each element of `org-structure-template-alist' into
   9210 	 ;; sublists according to the first letter.
   9211          (superlist
   9212 	  (mapcar (lambda (letter)
   9213                     (list letter
   9214 			  (cl-remove-if-not
   9215 			   (apply-partially #'string-match-p (concat "^" letter))
   9216 			   templates :key #'car)))
   9217 		  start-letters)))
   9218     (org-mks
   9219      (apply #'append
   9220 	    ;; Make an `org-mks' table.  If only one element is
   9221 	    ;; present in a sublist, make it part of the top-menu,
   9222 	    ;; otherwise make a submenu according to the starting
   9223 	    ;; letter and populate it.
   9224 	    (mapcar (lambda (sublist)
   9225 		      (if (eq 1 (length (cadr sublist)))
   9226                           (mapcar (lambda (elm)
   9227 				    (list (substring (car elm) 0 1)
   9228                                           (cdr elm) ""))
   9229                                   (cadr sublist))
   9230 			;; Create submenu.
   9231                         (let* ((topkey (car sublist))
   9232 			       (elms (cadr sublist))
   9233 			       (keys (mapcar #'car elms))
   9234 			       (long (> (length elms) 3)))
   9235                           (append
   9236 			   (list
   9237 			    ;; Make a description of the submenu.
   9238 			    (list topkey
   9239 				  (concat
   9240 				   (mapconcat #'cdr
   9241 					      (cl-subseq elms 0 (if long 3 (length elms)))
   9242 					      ", ")
   9243                                    (when long ", ..."))))
   9244 			   ;; List of entries in submenu.
   9245 			   (cl-mapcar #'list
   9246 				      (org--insert-structure-template-unique-keys keys)
   9247 				      (mapcar #'cdr elms)
   9248 				      (make-list (length elms) ""))))))
   9249 		    superlist))
   9250      "Select a key\n============"
   9251      "Key: ")))
   9252 
   9253 (defun org--insert-structure-template-unique-keys (keys)
   9254   "Make a list of unique, two characters long elements from KEYS.
   9255 
   9256 Elements of length one have a tab appended.  Elements of length
   9257 two are kept as is.  Longer elements are truncated to length two.
   9258 
   9259 If an element cannot be made unique, an error is raised."
   9260   (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
   9261 	menu-keys)
   9262     (dolist (key ordered-keys)
   9263       (let ((potential-key
   9264 	     (cl-case (length key)
   9265 	       (1 (concat key "\t"))
   9266 	       (2 key)
   9267 	       (otherwise
   9268 		(cl-find-if-not (lambda (k) (assoc k menu-keys))
   9269 				(mapcar (apply-partially #'concat (substring  key 0 1))
   9270 					(split-string (substring key 1) "" t)))))))
   9271 	(if (or (not potential-key) (assoc potential-key menu-keys))
   9272             (user-error "Could not make unique key for `%s'" key)
   9273 	  (push (cons potential-key key) menu-keys))))
   9274     (mapcar #'car
   9275 	    (cl-sort menu-keys #'<
   9276 		     :key (lambda (elm) (cl-position (cdr elm) keys))))))
   9277 
   9278 (defun org-insert-structure-template (type)
   9279   "Insert a block structure of the type #+begin_foo/#+end_foo.
   9280 Select a block from `org-structure-template-alist' then type
   9281 either RET, TAB or SPC to write the block type.  With an active
   9282 region, wrap the region in the block.  Otherwise, insert an empty
   9283 block.
   9284 
   9285 When foo is written as FOO, upcase the #+BEGIN/END as well."
   9286   (interactive
   9287    (list (pcase (org--insert-structure-template-mks)
   9288 	   (`("\t" . ,_)
   9289             (let ((type (read-string "Structure type: ")))
   9290               (when (string-empty-p type) (user-error "Empty structure type"))
   9291               type))
   9292 	   (`(,_ ,choice . ,_) choice))))
   9293   (when (or (not (stringp type)) (string-empty-p type))
   9294     (error "Invalid structure type: %S" type))
   9295   (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
   9296          (region? (use-region-p))
   9297 	 (region-start (and region? (region-beginning)))
   9298 	 (region-end (and region? (copy-marker (region-end))))
   9299 	 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
   9300 	 (verbatim? (string-match-p
   9301 		     (concat "\\`" (regexp-opt '("example" "export"
   9302                                                 "src" "comment")))
   9303 		     type))
   9304          (upcase? (string= (car (split-string type))
   9305                            (upcase (car (split-string type))))))
   9306     (when region? (goto-char region-start))
   9307     (let ((column (current-indentation)))
   9308       (if (save-excursion (skip-chars-backward " \t") (bolp))
   9309 	  (forward-line 0)
   9310 	(insert "\n"))
   9311       (save-excursion
   9312 	(indent-to column)
   9313 	(insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
   9314 	(when region?
   9315 	  (when verbatim? (org-escape-code-in-region (point) region-end))
   9316 	  (goto-char region-end)
   9317 	  ;; Ignore empty lines at the end of the region.
   9318 	  (skip-chars-backward " \r\t\n")
   9319 	  (end-of-line))
   9320 	(unless (bolp) (insert "\n"))
   9321 	(indent-to column)
   9322 	(insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
   9323 	(if (looking-at "[ \t]*$") (replace-match "")
   9324 	  (insert "\n"))
   9325 	(when (and (eobp) (not (bolp))) (insert "\n")))
   9326       (if extended? (end-of-line)
   9327 	(forward-line)
   9328 	(skip-chars-forward " \t")))))
   9329 
   9330 
   9331 ;;;; TODO, DEADLINE, Comments
   9332 
   9333 (defun org-toggle-comment ()
   9334   "Change the COMMENT state of an entry."
   9335   (interactive)
   9336   (save-excursion
   9337     (org-back-to-heading)
   9338     (let ((case-fold-search nil))
   9339       (looking-at org-complex-heading-regexp))
   9340     (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
   9341     (skip-chars-forward " \t")
   9342     (unless (memq (char-before) '(?\s ?\t)) (insert " "))
   9343     (if (org-in-commented-heading-p t)
   9344 	(delete-region (point)
   9345 		       (progn (search-forward " " (line-end-position) 'move)
   9346 			      (skip-chars-forward " \t")
   9347 			      (point)))
   9348       (insert org-comment-string)
   9349       (unless (eolp) (insert " ")))))
   9350 
   9351 (defvar org-last-todo-state-is-todo nil
   9352   "This is non-nil when the last TODO state change led to a TODO state.
   9353 If the last change removed the TODO tag or switched to DONE, then
   9354 this is nil.")
   9355 
   9356 (defvar org-todo-setup-filter-hook nil
   9357   "Hook for functions that pre-filter todo specs.
   9358 Each function takes a todo spec and returns either nil or the spec
   9359 transformed into canonical form." )
   9360 
   9361 (defvar org-todo-get-default-hook nil
   9362   "Hook for functions that get a default item for todo.
   9363 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
   9364 nil or a string to be used for the todo mark." )
   9365 
   9366 (defvar org-agenda-headline-snapshot-before-repeat)
   9367 
   9368 (defun org-current-effective-time ()
   9369   "Return current time adjusted for `org-extend-today-until' variable."
   9370   (let* ((ct (org-current-time))
   9371 	 (dct (decode-time ct))
   9372 	 (ct1
   9373 	  (cond
   9374 	   (org-use-last-clock-out-time-as-effective-time
   9375 	    (or (org-clock-get-last-clock-out-time) ct))
   9376 	   ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
   9377 	    (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
   9378 	   (t ct))))
   9379     ct1))
   9380 
   9381 (defun org-todo-yesterday (&optional arg)
   9382   "Like `org-todo' but the time of change will be 23:59 of yesterday."
   9383   (interactive "P")
   9384   (if (eq major-mode 'org-agenda-mode)
   9385       (org-agenda-todo-yesterday arg)
   9386     (let* ((org-use-effective-time t)
   9387 	   (hour (nth 2 (decode-time (org-current-time))))
   9388 	   (org-extend-today-until (1+ hour)))
   9389       (org-todo arg))))
   9390 
   9391 (defvar org-block-entry-blocking ""
   9392   "First entry preventing the TODO state change.")
   9393 
   9394 (defun org-cancel-repeater ()
   9395   "Cancel a repeater by setting its numeric value to zero."
   9396   (interactive)
   9397   (save-excursion
   9398     (org-back-to-heading t)
   9399     (let ((bound1 (point))
   9400 	  (bound0 (save-excursion (outline-next-heading) (point))))
   9401       (when (and (re-search-forward
   9402 		  (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
   9403 			  org-deadline-time-regexp "\\)\\|\\("
   9404 			  org-ts-regexp "\\)")
   9405 		  bound0 t)
   9406 		 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
   9407 				     bound1 t))
   9408 	(replace-match "0" t nil nil 1)))))
   9409 
   9410 (defvar org-state)
   9411 ;; FIXME: We should refactor this and similar dynamically scoped blocker flags.
   9412 (defvar org-blocked-by-checkboxes nil) ; dynamically scoped
   9413 (defun org-todo (&optional arg)
   9414   "Change the TODO state of an item.
   9415 
   9416 The state of an item is given by a keyword at the start of the heading,
   9417 like
   9418      *** TODO Write paper
   9419      *** DONE Call mom
   9420 
   9421 The different keywords are specified in the variable `org-todo-keywords'.
   9422 By default the available states are \"TODO\" and \"DONE\".  So, for this
   9423 example: when the item starts with TODO, it is changed to DONE.
   9424 When it starts with DONE, the DONE is removed.  And when neither TODO nor
   9425 DONE are present, add TODO at the beginning of the heading.
   9426 You can set up single-character keys to fast-select the new state.  See the
   9427 `org-todo-keywords' and `org-use-fast-todo-selection' for details.
   9428 
   9429 With `\\[universal-argument]' prefix ARG, force logging the state change \
   9430 and take a
   9431 logging note.
   9432 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
   9433 next set of TODO \
   9434 keywords (nextset).
   9435 Another way to achieve this is `S-C-<right>'.
   9436 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
   9437 prefix, circumvent any state blocking.
   9438 With numeric prefix arg, switch to the Nth state.
   9439 
   9440 With a numeric prefix arg of 0, inhibit note taking for the change.
   9441 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
   9442 
   9443 When called through ELisp, arg is also interpreted in the following way:
   9444 `none'        -> empty state
   9445 \"\"            -> switch to empty state
   9446 `done'        -> switch to DONE
   9447 `nextset'     -> switch to the next set of keywords
   9448 `previousset' -> switch to the previous set of keywords
   9449 \"WAITING\"     -> switch to the specified keyword, but only if it
   9450                  really is a member of `org-todo-keywords'."
   9451   (interactive "P")
   9452   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
   9453       (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
   9454 		    'region-start-level 'region))
   9455 	    org-loop-over-headlines-in-active-region)
   9456 	(org-map-entries
   9457 	 (lambda () (org-todo arg))
   9458 	 nil cl
   9459 	 (when (org-invisible-p) (org-end-of-subtree nil t))))
   9460     (when (equal arg '(16)) (setq arg 'nextset))
   9461     (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
   9462     (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
   9463     (let ((org-blocker-hook org-blocker-hook)
   9464 	  commentp
   9465 	  case-fold-search)
   9466       (when (equal arg '(64))
   9467 	(setq arg nil org-blocker-hook nil))
   9468       (when (and org-blocker-hook
   9469 		 (or org-inhibit-blocking
   9470 		     (org-entry-get nil "NOBLOCKING")))
   9471 	(setq org-blocker-hook nil))
   9472       (save-excursion
   9473 	(catch 'exit
   9474 	  (org-back-to-heading t)
   9475 	  (when (org-in-commented-heading-p t)
   9476 	    (org-toggle-comment)
   9477 	    (setq commentp t))
   9478 	  (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
   9479 	  (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
   9480 	      (looking-at "\\(?: *\\|[ \t]*$\\)"))
   9481 	  (let* ((match-data (match-data))
   9482 		 (startpos (copy-marker (line-beginning-position)))
   9483 		 (force-log (and  (equal arg '(4)) (prog1 t (setq arg nil))))
   9484 		 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
   9485 		 (org-log-done org-log-done)
   9486 		 (org-log-repeat org-log-repeat)
   9487 		 (org-todo-log-states org-todo-log-states)
   9488 		 (org-inhibit-logging
   9489 		  (if (equal arg 0)
   9490 		      (progn (setq arg nil) 'note) org-inhibit-logging))
   9491 		 (this (match-string 1))
   9492 		 (hl-pos (match-beginning 0))
   9493 		 (head (org-get-todo-sequence-head this))
   9494 		 (ass (assoc head org-todo-kwd-alist))
   9495 		 (interpret (nth 1 ass))
   9496 		 (done-word (nth 3 ass))
   9497 		 (final-done-word (nth 4 ass))
   9498 		 (org-last-state (or this ""))
   9499 		 (completion-ignore-case t)
   9500 		 (member (member this org-todo-keywords-1))
   9501 		 (tail (cdr member))
   9502 		 (org-state (cond
   9503 			     ((eq arg 'right)
   9504 			      ;; Next state
   9505 			      (if this
   9506 			          (if tail (car tail) nil)
   9507 			        (car org-todo-keywords-1)))
   9508 			     ((eq arg 'left)
   9509 			      ;; Previous state
   9510 			      (unless (equal member org-todo-keywords-1)
   9511 			        (if this
   9512 				    (nth (- (length org-todo-keywords-1)
   9513 					    (length tail) 2)
   9514 				         org-todo-keywords-1)
   9515 			          (org-last org-todo-keywords-1))))
   9516 			     (arg
   9517 			      ;; User or caller requests a specific state.
   9518 			      (cond
   9519 			       ((equal arg "") nil)
   9520 			       ((eq arg 'none) nil)
   9521 			       ((eq arg 'done) (or done-word (car org-done-keywords)))
   9522 			       ((eq arg 'nextset)
   9523 			        (or (car (cdr (member head org-todo-heads)))
   9524 				    (car org-todo-heads)))
   9525 			       ((eq arg 'previousset)
   9526 			        (let ((org-todo-heads (reverse org-todo-heads)))
   9527 			          (or (car (cdr (member head org-todo-heads)))
   9528 				      (car org-todo-heads))))
   9529 			       ((car (member arg org-todo-keywords-1)))
   9530 			       ((stringp arg)
   9531 			        (user-error "State `%s' not valid in this file" arg))
   9532 			       ((nth (1- (prefix-numeric-value arg))
   9533 				     org-todo-keywords-1))))
   9534 			     ((and org-todo-key-trigger org-use-fast-todo-selection)
   9535 			      ;; Use fast selection.
   9536 			      (org-fast-todo-selection this))
   9537 			     ((null member) (or head (car org-todo-keywords-1)))
   9538 			     ((equal this final-done-word) nil) ;-> make empty
   9539 			     ((null tail) nil) ;-> first entry
   9540 			     ((memq interpret '(type priority))
   9541 			      (if (eq this-command last-command)
   9542 			          (car tail)
   9543 			        (if (> (length tail) 0)
   9544 				    (or done-word (car org-done-keywords))
   9545 			          nil)))
   9546 			     (t
   9547 			      (car tail))))
   9548 		 (org-state (or
   9549 			     (run-hook-with-args-until-success
   9550 			      'org-todo-get-default-hook org-state org-last-state)
   9551 			     org-state))
   9552 		 (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
   9553 		 (change-plist (list :type 'todo-state-change :from this :to org-state
   9554 				     :position startpos))
   9555 		 dolog now-done-p)
   9556 	    (when org-blocker-hook
   9557 	      (let (org-blocked-by-checkboxes block-reason)
   9558 		(setq org-last-todo-state-is-todo
   9559 		      (not (member this org-done-keywords)))
   9560 		(unless (save-excursion
   9561 			  (save-match-data
   9562 			    (org-with-wide-buffer
   9563 			     (run-hook-with-args-until-failure
   9564 			      'org-blocker-hook change-plist))))
   9565 		  (setq block-reason (if org-blocked-by-checkboxes
   9566 					 "contained checkboxes"
   9567 				       (format "\"%s\"" org-block-entry-blocking)))
   9568 		  (if (called-interactively-p 'interactive)
   9569 		      (user-error "TODO state change from %s to %s blocked (by %s)"
   9570 				  this org-state block-reason)
   9571 		    ;; Fail silently.
   9572 		    (message "TODO state change from %s to %s blocked (by %s)"
   9573 			     this org-state block-reason)
   9574 		    (throw 'exit nil)))))
   9575 	    (store-match-data match-data)
   9576             (org-fold-core-ignore-modifications
   9577               (goto-char (match-beginning 0))
   9578               (replace-match "")
   9579               ;; We need to use `insert-before-markers-and-inherit'
   9580               ;; because: (1) We want to preserve the folding state
   9581               ;; text properties; (2) We do not want to make point
   9582               ;; move before new todo state when inserting a new todo
   9583               ;; into an empty heading.  In (2), the above
   9584               ;; `save-excursion' is relying on markers saved before.
   9585               (insert-before-markers-and-inherit next)
   9586               (unless (org-invisible-p (line-beginning-position))
   9587                 (org-fold-region (line-beginning-position)
   9588                                  (line-end-position)
   9589                                  nil 'outline)))
   9590 	    (cond ((and org-state (equal this org-state))
   9591 		   (message "TODO state was already %s" (org-trim next)))
   9592 		  ((not (pos-visible-in-window-p hl-pos))
   9593 		   (message "TODO state changed to %s" (org-trim next))))
   9594 	    (unless head
   9595 	      (setq head (org-get-todo-sequence-head org-state)
   9596 		    ass (assoc head org-todo-kwd-alist)
   9597 		    interpret (nth 1 ass)
   9598 		    done-word (nth 3 ass)
   9599 		    final-done-word (nth 4 ass)))
   9600 	    (when (memq arg '(nextset previousset))
   9601 	      (message "Keyword-Set %d/%d: %s"
   9602 		       (- (length org-todo-sets) -1
   9603 			  (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
   9604 		       (length org-todo-sets)
   9605 		       (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
   9606 	    (setq org-last-todo-state-is-todo
   9607 		  (not (member org-state org-done-keywords)))
   9608 	    (setq now-done-p (and (member org-state org-done-keywords)
   9609 				  (not (member this org-done-keywords))))
   9610 	    (and logging (org-local-logging logging))
   9611 	    (when (or (and (or org-todo-log-states org-log-done)
   9612 			   (not (eq org-inhibit-logging t))
   9613 			   (not (memq arg '(nextset previousset))))
   9614 		      force-log)
   9615 	      ;; We need to look at recording a time and note.
   9616 	      (setq dolog (or (if force-log 'note)
   9617 			      (nth 1 (assoc org-state org-todo-log-states))
   9618 			      (nth 2 (assoc this org-todo-log-states))))
   9619 	      (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
   9620 		(setq dolog 'time))
   9621 	      (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
   9622 			(and org-state
   9623 			     (member org-state org-not-done-keywords)
   9624 			     (not (member this org-not-done-keywords))))
   9625 		;; This is now a todo state and was not one before
   9626 		;; If there was a CLOSED time stamp, get rid of it.
   9627 		(org-add-planning-info nil nil 'closed))
   9628 	      (when (and now-done-p org-log-done)
   9629 		;; It is now done, and it was not done before.
   9630 		(org-add-planning-info 'closed (org-current-effective-time))
   9631 		(when (and (not dolog) (eq 'note org-log-done))
   9632 		  (org-add-log-setup 'done org-state this 'note)))
   9633 	      (when (and org-state dolog)
   9634 		;; This is a non-nil state, and we need to log it.
   9635 		(org-add-log-setup 'state org-state this dolog)))
   9636 	    ;; Fixup tag positioning.
   9637 	    (org-todo-trigger-tag-changes org-state)
   9638 	    (when org-auto-align-tags (org-align-tags))
   9639 	    (when org-provide-todo-statistics
   9640 	      (org-update-parent-todo-statistics))
   9641 	    (when (bound-and-true-p org-clock-out-when-done)
   9642 	      (org-clock-out-if-current))
   9643 	    (run-hooks 'org-after-todo-state-change-hook)
   9644 	    (when (and arg (not (member org-state org-done-keywords)))
   9645 	      (setq head (org-get-todo-sequence-head org-state)))
   9646             (put-text-property (line-beginning-position)
   9647                                (line-end-position) 'org-todo-head head)
   9648 	    ;; Do we need to trigger a repeat?
   9649 	    (when now-done-p
   9650 	      (when (boundp 'org-agenda-headline-snapshot-before-repeat)
   9651 		;; This is for the agenda, take a snapshot of the headline.
   9652 		(save-match-data
   9653 		  (setq org-agenda-headline-snapshot-before-repeat
   9654 			(org-get-heading))))
   9655 	      (org-auto-repeat-maybe org-state))
   9656 	    ;; Fixup cursor location if close to the keyword.
   9657 	    (when (and (outline-on-heading-p)
   9658 		       (not (bolp))
   9659 		       (save-excursion
   9660                          (forward-line 0)
   9661 			 (looking-at org-todo-line-regexp))
   9662 		       (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
   9663 	      (goto-char (or (match-end 2) (match-end 1)))
   9664 	      (and (looking-at " ")
   9665 		   (not (looking-at " *:"))
   9666 		   (just-one-space)))
   9667 	    (when org-trigger-hook
   9668 	      (save-excursion
   9669 		(run-hook-with-args 'org-trigger-hook change-plist)))
   9670 	    (when commentp (org-toggle-comment))))))))
   9671 
   9672 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
   9673   "Block turning an entry into a TODO, using the hierarchy.
   9674 This checks whether the current task should be blocked from state
   9675 changes.  Such blocking occurs when:
   9676 
   9677   1. The task has children which are not all in a completed state.
   9678 
   9679   2. A task has a parent with the property :ORDERED:, and there
   9680      are siblings prior to the current task with incomplete
   9681      status.
   9682 
   9683   3. The parent of the task is blocked because it has siblings that should
   9684      be done first, or is child of a block grandparent TODO entry."
   9685 
   9686   (if (not org-enforce-todo-dependencies)
   9687       t ; if locally turned off don't block
   9688     (catch 'dont-block
   9689       ;; If this is not a todo state change, or if this entry is already DONE,
   9690       ;; do not block
   9691       (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
   9692 		(member (plist-get change-plist :from)
   9693 			(cons 'done org-done-keywords))
   9694 		(member (plist-get change-plist :to)
   9695 			(cons 'todo org-not-done-keywords))
   9696 		(not (plist-get change-plist :to)))
   9697 	(throw 'dont-block t))
   9698       ;; If this task has children, and any are undone, it's blocked
   9699       (save-excursion
   9700 	(org-back-to-heading t)
   9701 	(let ((this-level (funcall outline-level)))
   9702 	  (outline-next-heading)
   9703 	  (let ((child-level (funcall outline-level)))
   9704 	    (while (and (not (eobp))
   9705 			(> child-level this-level))
   9706 	      ;; this todo has children, check whether they are all
   9707 	      ;; completed
   9708 	      (when (and (not (org-entry-is-done-p))
   9709 			 (org-entry-is-todo-p))
   9710 		(setq org-block-entry-blocking (org-get-heading))
   9711 		(throw 'dont-block nil))
   9712 	      (outline-next-heading)
   9713 	      (setq child-level (funcall outline-level))))))
   9714       ;; Otherwise, if the task's parent has the :ORDERED: property, and
   9715       ;; any previous siblings are undone, it's blocked
   9716       (save-excursion
   9717 	(org-back-to-heading t)
   9718 	(let* ((pos (point))
   9719 	       (parent-pos (and (org-up-heading-safe) (point)))
   9720 	       (case-fold-search nil))
   9721 	  (unless parent-pos (throw 'dont-block t)) ; no parent
   9722 	  (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
   9723 		     (forward-line 1)
   9724 		     (re-search-forward org-not-done-heading-regexp pos t))
   9725 	    (setq org-block-entry-blocking (match-string 0))
   9726 	    (throw 'dont-block nil))  ; block, there is an older sibling not done.
   9727 	  ;; Search further up the hierarchy, to see if an ancestor is blocked
   9728 	  (while t
   9729 	    (goto-char parent-pos)
   9730 	    (unless (looking-at org-not-done-heading-regexp)
   9731 	      (throw 'dont-block t))	; do not block, parent is not a TODO
   9732 	    (setq pos (point))
   9733 	    (setq parent-pos (and (org-up-heading-safe) (point)))
   9734 	    (unless parent-pos (throw 'dont-block t)) ; no parent
   9735 	    (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
   9736 		       (forward-line 1)
   9737 		       (re-search-forward org-not-done-heading-regexp pos t)
   9738 		       (setq org-block-entry-blocking (org-get-heading)))
   9739 	      (throw 'dont-block nil)))))))) ; block, older sibling not done.
   9740 
   9741 (defcustom org-track-ordered-property-with-tag nil
   9742   "Should the ORDERED property also be shown as a tag?
   9743 The ORDERED property decides if an entry should require subtasks to be
   9744 completed in sequence.  Since a property is not very visible, setting
   9745 this option means that toggling the ORDERED property with the command
   9746 `org-toggle-ordered-property' will also toggle a tag ORDERED.  That tag is
   9747 not relevant for the behavior, but it makes things more visible.
   9748 
   9749 Note that toggling the tag with tags commands will not change the property
   9750 and therefore not influence behavior!
   9751 
   9752 This can be t, meaning the tag ORDERED should be used.  It can also be a
   9753 string to select a different tag for this task."
   9754   :group 'org-todo
   9755   :type '(choice
   9756 	  (const :tag "No tracking" nil)
   9757 	  (const :tag "Track with ORDERED tag" t)
   9758 	  (string :tag "Use other tag")))
   9759 
   9760 (defun org-toggle-ordered-property ()
   9761   "Toggle the ORDERED property of the current entry.
   9762 For better visibility, you can track the value of this property with a tag.
   9763 See variable `org-track-ordered-property-with-tag'."
   9764   (interactive)
   9765   (let* ((t1 org-track-ordered-property-with-tag)
   9766 	 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
   9767     (save-excursion
   9768       (org-back-to-heading)
   9769       (if (org-entry-get nil "ORDERED")
   9770 	  (progn
   9771 	    (org-delete-property "ORDERED")
   9772 	    (and tag (org-toggle-tag tag 'off))
   9773 	    (message "Subtasks can be completed in arbitrary order"))
   9774 	(org-entry-put nil "ORDERED" "t")
   9775 	(and tag (org-toggle-tag tag 'on))
   9776 	(message "Subtasks must be completed in sequence")))))
   9777 
   9778 (defun org-block-todo-from-checkboxes (change-plist)
   9779   "Block turning an entry into a TODO, using checkboxes.
   9780 This checks whether the current task should be blocked from state
   9781 changes because there are unchecked boxes in this entry."
   9782   (if (not org-enforce-todo-checkbox-dependencies)
   9783       t ; if locally turned off don't block
   9784     (catch 'dont-block
   9785       ;; If this is not a todo state change, or if this entry is already DONE,
   9786       ;; do not block
   9787       (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
   9788 		(member (plist-get change-plist :from)
   9789 			(cons 'done org-done-keywords))
   9790 		(member (plist-get change-plist :to)
   9791 			(cons 'todo org-not-done-keywords))
   9792 		(not (plist-get change-plist :to)))
   9793 	(throw 'dont-block t))
   9794       ;; If this task has checkboxes that are not checked, it's blocked
   9795       (save-excursion
   9796 	(org-back-to-heading t)
   9797 	(let ((beg (point)) end)
   9798 	  (outline-next-heading)
   9799 	  (setq end (point))
   9800 	  (goto-char beg)
   9801 	  (when (org-list-search-forward
   9802 		 (concat (org-item-beginning-re)
   9803 			 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
   9804 			 "\\[[- ]\\]")
   9805 		 end t)
   9806 	    (when (boundp 'org-blocked-by-checkboxes)
   9807 	      (setq org-blocked-by-checkboxes t))
   9808 	    (throw 'dont-block nil))))
   9809       t))) ; do not block
   9810 
   9811 (defun org-entry-blocked-p ()
   9812   "Non-nil if entry at point is blocked."
   9813   (and (not (org-entry-get nil "NOBLOCKING"))
   9814        (member (org-entry-get nil "TODO") org-not-done-keywords)
   9815        (not (run-hook-with-args-until-failure
   9816 	     'org-blocker-hook
   9817 	     (list :type 'todo-state-change
   9818 		   :position (point)
   9819 		   :from 'todo
   9820 		   :to 'done)))))
   9821 
   9822 (defun org-update-statistics-cookies (all)
   9823   "Update the statistics cookie, either from TODO or from checkboxes.
   9824 This should be called with the cursor in a line with a statistics
   9825 cookie.  When called with a \\[universal-argument] prefix, update
   9826 all statistics cookies in the buffer."
   9827   (interactive "P")
   9828   (if all
   9829       (progn
   9830 	(org-update-checkbox-count 'all)
   9831 	(org-map-region 'org-update-parent-todo-statistics
   9832                         (point-min) (point-max)))
   9833     (if (not (org-at-heading-p))
   9834 	(org-update-checkbox-count)
   9835       (let ((pos (point-marker))
   9836 	    end l1 l2)
   9837 	(ignore-errors (org-back-to-heading t))
   9838 	(if (not (org-at-heading-p))
   9839 	    (org-update-checkbox-count)
   9840 	  (setq l1 (org-outline-level))
   9841 	  (setq end
   9842                 (save-excursion
   9843 		  (outline-next-heading)
   9844 		  (when (org-at-heading-p) (setq l2 (org-outline-level)))
   9845 		  (point)))
   9846 	  (if (and (save-excursion
   9847 		     (re-search-forward
   9848 		      "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
   9849 	           (not (save-excursion
   9850                         (re-search-forward
   9851 			 ":COOKIE_DATA:.*\\<todo\\>" end t))))
   9852 	      (org-update-checkbox-count)
   9853 	    (if (and l2 (> l2 l1))
   9854 		(progn
   9855 		  (goto-char end)
   9856 		  (org-update-parent-todo-statistics))
   9857 	      (goto-char pos)
   9858 	      (forward-line 0)
   9859 	      (while (re-search-forward
   9860 		      "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
   9861                       (line-end-position) t)
   9862 		(replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
   9863 	(goto-char pos)
   9864 	(move-marker pos nil)))))
   9865 
   9866 (defvar org-entry-property-inherited-from) ;; defined below
   9867 (defun org-update-parent-todo-statistics ()
   9868   "Update any statistics cookie in the parent of the current headline.
   9869 When `org-hierarchical-todo-statistics' is nil, statistics will cover
   9870 the entire subtree and this will travel up the hierarchy and update
   9871 statistics everywhere."
   9872   (let* ((prop (save-excursion
   9873                  (org-up-heading-safe)
   9874 		 (org-entry-get nil "COOKIE_DATA" 'inherit)))
   9875 	 (recursive (or (not org-hierarchical-todo-statistics)
   9876 			(and prop (string-match "\\<recursive\\>" prop))))
   9877 	 (lim (or (and prop (marker-position org-entry-property-inherited-from))
   9878 		  0))
   9879 	 (first t)
   9880 	 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
   9881 	 level ltoggle l1 new ndel
   9882 	 (cnt-all 0) (cnt-done 0) is-percent kwd
   9883 	 checkbox-beg cookie-present)
   9884     (catch 'exit
   9885       (save-excursion
   9886 	(forward-line 0)
   9887 	(setq ltoggle (funcall outline-level))
   9888 	;; Three situations are to consider:
   9889 
   9890 	;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
   9891 	;;    to the top-level ancestor on the headline;
   9892 
   9893 	;; 2. If parent has "recursive" property, repeat up to the
   9894 	;;    headline setting that property, taking inheritance into
   9895 	;;    account;
   9896 
   9897 	;; 3. Else, move up to direct parent and proceed only once.
   9898 	(while (and (setq level (org-up-heading-safe))
   9899 		    (or recursive first)
   9900 		    (>= (point) lim))
   9901 	  (setq first nil cookie-present nil)
   9902 	  (unless (and level
   9903 		       (not (string-match
   9904 			   "\\<checkbox\\>"
   9905 			   (downcase (or (org-entry-get nil "COOKIE_DATA")
   9906 					 "")))))
   9907 	    (throw 'exit nil))
   9908           (while (re-search-forward box-re (line-end-position) t)
   9909 	    (setq cnt-all 0 cnt-done 0 cookie-present t)
   9910 	    (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
   9911             (when (org-element-type-p
   9912                    (save-excursion
   9913                      (goto-char checkbox-beg)
   9914                      (save-match-data (org-element-context)))
   9915                    '(statistics-cookie
   9916                      ;; Special case - statistics cookie inside properties.
   9917                      keyword))
   9918 	      (save-match-data
   9919 	        (unless (outline-next-heading) (throw 'exit nil))
   9920 	        (while (and (looking-at org-complex-heading-regexp)
   9921                             (> (setq l1 (length (match-string 1))) level))
   9922                   (setq kwd (and (or recursive (= l1 ltoggle))
   9923                                  (match-string 2)))
   9924                   (if (or (eq org-provide-todo-statistics 'all-headlines)
   9925                           (and (eq org-provide-todo-statistics t)
   9926 			       (or (member kwd org-done-keywords)))
   9927                           (and (listp org-provide-todo-statistics)
   9928 			       (stringp (car org-provide-todo-statistics))
   9929                                (or (member kwd org-provide-todo-statistics)
   9930 				   (member kwd org-done-keywords)))
   9931 			  (and (listp org-provide-todo-statistics)
   9932 			       (listp (car org-provide-todo-statistics))
   9933 			       (or (member kwd (car org-provide-todo-statistics))
   9934 				   (and (member kwd org-done-keywords)
   9935 				        (member kwd (cadr org-provide-todo-statistics))))))
   9936                       (setq cnt-all (1+ cnt-all))
   9937 		    (and (eq org-provide-todo-statistics t)
   9938 		         kwd
   9939 		         (setq cnt-all (1+ cnt-all))))
   9940 		  (when (or (and (member org-provide-todo-statistics '(t all-headlines))
   9941 			         (member kwd org-done-keywords))
   9942 			    (and (listp org-provide-todo-statistics)
   9943 			         (listp (car org-provide-todo-statistics))
   9944 			         (member kwd org-done-keywords)
   9945 			         (member kwd (cadr org-provide-todo-statistics)))
   9946 			    (and (listp org-provide-todo-statistics)
   9947 			         (stringp (car org-provide-todo-statistics))
   9948 			         (member kwd org-done-keywords)))
   9949 		    (setq cnt-done (1+ cnt-done)))
   9950                   (outline-next-heading)))
   9951 	      (setq new
   9952                     (if is-percent
   9953                         (format "[%d%%]" (floor (* 100.0 cnt-done)
   9954 					        (max 1 cnt-all)))
   9955                       (format "[%d/%d]" cnt-done cnt-all))
   9956                     ndel (- (match-end 0) checkbox-beg))
   9957               (goto-char (match-end 0))
   9958               (unless (string-equal new (buffer-substring checkbox-beg (match-end 0)))
   9959 	        (goto-char checkbox-beg)
   9960 	        (insert new)
   9961 	        (delete-region (point) (+ (point) ndel))
   9962 	        (when org-auto-align-tags (org-fix-tags-on-the-fly)))))
   9963 	  (when cookie-present
   9964 	    (run-hook-with-args 'org-after-todo-statistics-hook
   9965 				cnt-done (- cnt-all cnt-done))))))
   9966     (run-hooks 'org-todo-statistics-hook)))
   9967 
   9968 (defvar org-after-todo-statistics-hook nil
   9969   "Hook that is called after a TODO statistics cookie has been updated.
   9970 Each function is called with two arguments: the number of not-done entries
   9971 and the number of done entries.
   9972 
   9973 For example, the following function, when added to this hook, will switch
   9974 an entry to DONE when all children are done, and back to TODO when new
   9975 entries are set to a TODO status.  Note that this hook is only called
   9976 when there is a statistics cookie in the headline!
   9977 
   9978  (defun org-summary-todo (n-done n-not-done)
   9979    \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
   9980    (let (org-log-done org-todo-log-states)   ; turn off logging
   9981      (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
   9982 
   9983 (defvar org-todo-statistics-hook nil
   9984   "Hook that is run whenever Org thinks TODO statistics should be updated.
   9985 This hook runs even if there is no statistics cookie present, in which case
   9986 `org-after-todo-statistics-hook' would not run.")
   9987 
   9988 (defun org-todo-trigger-tag-changes (state)
   9989   "Apply the changes defined in `org-todo-state-tags-triggers'."
   9990   (let ((l org-todo-state-tags-triggers)
   9991 	changes)
   9992     (when (or (not state) (equal state ""))
   9993       (setq changes (append changes (cdr (assoc "" l)))))
   9994     (when (and (stringp state) (> (length state) 0))
   9995       (setq changes (append changes (cdr (assoc state l)))))
   9996     (when (member state org-not-done-keywords)
   9997       (setq changes (append changes (cdr (assq 'todo l)))))
   9998     (when (member state org-done-keywords)
   9999       (setq changes (append changes (cdr (assq 'done l)))))
  10000     (dolist (c changes)
  10001       (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  10002 
  10003 (defun org-local-logging (value)
  10004   "Get logging settings from a property VALUE."
  10005   ;; Directly set the variables, they are already local.
  10006   (setq org-log-done nil
  10007         org-log-repeat nil
  10008         org-todo-log-states nil)
  10009   (dolist (w (split-string value))
  10010     (let (a)
  10011       (cond
  10012        ((setq a (assoc w org-startup-options))
  10013         (and (member (nth 1 a) '(org-log-done org-log-repeat))
  10014              (set (nth 1 a) (nth 2 a))))
  10015        ((setq a (org-extract-log-state-settings w))
  10016         (and (member (car a) org-todo-keywords-1)
  10017              (push a org-todo-log-states)))))))
  10018 
  10019 (defun org-get-todo-sequence-head (kwd)
  10020   "Return the head of the TODO sequence to which KWD belongs.
  10021 If KWD is not set, check if there is a text property remembering the
  10022 right sequence."
  10023   (let (p)
  10024     (cond
  10025      ((not kwd)
  10026       (or (get-text-property (line-beginning-position) 'org-todo-head)
  10027 	  (progn
  10028             (setq p (next-single-property-change (line-beginning-position)
  10029                                                  'org-todo-head
  10030                                                  nil (line-end-position)))
  10031 	    (get-text-property p 'org-todo-head))))
  10032      ((not (member kwd org-todo-keywords-1))
  10033       (car org-todo-keywords-1))
  10034      (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  10035 
  10036 (defun org-fast-todo-selection (&optional current-todo-keyword)
  10037   "Fast TODO keyword selection with single keys.
  10038 Returns the new TODO keyword, or nil if no state change should occur.
  10039 
  10040 When CURRENT-TODO-KEYWORD is given and selection letters are not
  10041 unique globally, prefer a state in the current todo keyword sequence
  10042 where CURRENT-TODO-KEYWORD belongs over on in another sequence."
  10043   (let* ((todo-alist org-todo-key-alist) ; copy from the original Org buffer.
  10044          (todo-alist-tail todo-alist)
  10045          ;; TODO keyword sequence that takes priority in case if there is binding collision.
  10046 	 (preferred-sequence-head (org-get-todo-sequence-head current-todo-keyword))
  10047          in-preferred-sequence preferred-todo-alist
  10048 	 (done-keywords org-done-keywords) ;; needed for the faces when calling `org-get-todo-face'.
  10049 	 (expert-interface (equal org-use-fast-todo-selection 'expert))
  10050 	 (prompt "") ; Additional expert prompt, listing todo keyword bindings.
  10051          ;; Max width occupied by a single todo record in the completion buffer.
  10052          (field-width
  10053           (+ 3 ; keep space for "[c]" binding.
  10054              1 ; ensure that there is at least one space between adjacent todo fields.
  10055              3 ; FIXME: likely coped from `org-fast-tag-selection'
  10056              ;; The longest todo keyword.
  10057              (apply 'max (mapcar
  10058 			  (lambda (x)
  10059 			    (if (stringp (car x)) (string-width (car x)) 0))
  10060 			  org-todo-key-alist))))
  10061          field-number ; current todo keyword column in the completion buffer.
  10062          todo-binding-spec todo-keyword todo-char input-char)
  10063     ;; Display todo selection dialog, read the user input, and return.
  10064     (save-excursion
  10065       (save-window-excursion
  10066         ;; Select todo keyword list buffer, and display it unless EXPERT-INTERFACE.
  10067 	(if expert-interface
  10068 	    (set-buffer (get-buffer-create " *Org todo*"))
  10069           (pop-to-buffer
  10070            (get-buffer-create (get-buffer-create " *Org todo*"))
  10071            '(org-display-buffer-split (direction . down))))
  10072         ;; Fill text in *Org todo* buffer.
  10073 	(erase-buffer)
  10074         ;; Copy `org-done-keywords' from the original Org buffer to be
  10075         ;; used by `org-get-todo-face'.
  10076 	(setq-local org-done-keywords done-keywords)
  10077         ;; Show todo keyword sequences and bindings in a grid.
  10078         ;; Each todo keyword in the grid occupies FIELD-WIDTH characters.
  10079         ;; The keywords are filled up to `window-width'.
  10080 	(setq field-number 0)
  10081 	(while (setq todo-binding-spec (pop todo-alist-tail))
  10082 	  (pcase todo-binding-spec
  10083             ;; Group keywords as { KWD1 KWD2 ... }
  10084 	    (`(:startgroup)
  10085 	     (unless (= field-number 0)
  10086 	       (setq field-number 0)
  10087 	       (insert "\n"))
  10088 	     (setq prompt (concat prompt "{"))
  10089 	     (insert "{ "))
  10090 	    (`(:endgroup)
  10091 	     (setq field-number 0
  10092                    ;; End of a group.  Reset flag indicating preferred keyword sequence.
  10093                    in-preferred-sequence nil)
  10094 	     (setq prompt (concat prompt "}"))
  10095 	     (insert "}\n"))
  10096 	    (`(:newline)
  10097 	     (unless (= field-number 0)
  10098 	       (insert "\n")
  10099 	       (setq field-number 0)
  10100 	       (setq todo-binding-spec (car todo-alist-tail))
  10101 	       (while (equal (car todo-alist-tail) '(:newline))
  10102 		 (insert "\n")
  10103 		 (pop todo-alist-tail))))
  10104 	    (_
  10105 	     (setq todo-keyword (car todo-binding-spec)
  10106                    todo-char (cdr todo-binding-spec))
  10107              ;; For the first keyword in a preferred sequence, set flag.
  10108 	     (if (equal todo-keyword preferred-sequence-head)
  10109                  (setq in-preferred-sequence t))
  10110              ;; Store the preferred todo keyword sequence.
  10111 	     (when in-preferred-sequence (push todo-binding-spec preferred-todo-alist))
  10112              ;; Assign face to the todo keyword.
  10113 	     (setq todo-keyword
  10114                    (org-add-props
  10115                        todo-keyword nil
  10116                      'face (org-get-todo-face todo-keyword)))
  10117 	     (when (= field-number 0) (insert "  "))
  10118 	     (setq prompt (concat prompt "[" (char-to-string todo-char) "] " todo-keyword " "))
  10119 	     (insert "[" todo-char "] " todo-keyword
  10120                      ;; Fill spaces up to FIELD-WIDTH.
  10121                      (make-string
  10122 		      (- field-width 4 (length todo-keyword)) ?\ ))
  10123              ;; Last column in the row.
  10124 	     (when (and (= (setq field-number (1+ field-number))
  10125                            (/ (- (window-width) 4) field-width))
  10126 		        ;; Avoid lines with just a closing delimiter.
  10127 		        (not (equal (car todo-alist-tail) '(:endgroup))))
  10128 	       (insert "\n")
  10129 	       (setq field-number 0)))))
  10130 	(insert "\n")
  10131 	(goto-char (point-min))
  10132 	(unless expert-interface (org-fit-window-to-buffer))
  10133 	(message (concat "[a-z..]:Set [SPC]:clear"
  10134 			 (if expert-interface (concat "\n" prompt) "")))
  10135         ;; Read the todo keyword input and exit.
  10136 	(setq input-char
  10137               (let ((inhibit-quit t)) ; intercept C-g.
  10138                 (read-char-exclusive)))
  10139         ;; Restore the original keyword order.  Previously, it was reversed using `push'.
  10140 	(setq preferred-todo-alist (nreverse preferred-todo-alist))
  10141 	(cond
  10142 	 ((equal input-char ?\s) nil)
  10143          ((or (= input-char ?\C-g)
  10144 	      (and (= input-char ?q) (not (rassoc input-char todo-alist))))
  10145           (signal 'quit nil))
  10146 	 ((setq todo-binding-spec (or
  10147                                    ;; Prefer bindings from todo sequence containing CURRENT-TODO-KEYWORD.
  10148                                    (rassoc input-char preferred-todo-alist)
  10149                                    (rassoc input-char todo-alist))
  10150 	        todo-keyword (car todo-binding-spec))
  10151 	  todo-keyword)
  10152          (t (signal 'quit nil)))))))
  10153 
  10154 (defun org-entry-is-todo-p ()
  10155   (member (org-get-todo-state) org-not-done-keywords))
  10156 
  10157 (defun org-entry-is-done-p ()
  10158   (member (org-get-todo-state) org-done-keywords))
  10159 
  10160 (defun org-get-todo-state ()
  10161   "Return the TODO keyword of the current subtree."
  10162   (save-excursion
  10163     (org-back-to-heading t)
  10164     (and (let ((case-fold-search nil))
  10165            (looking-at org-todo-line-regexp))
  10166 	 (match-end 2)
  10167 	 (match-string 2))))
  10168 
  10169 (defun org-at-date-range-p (&optional inactive-ok)
  10170   "Non-nil if point is inside a date range.
  10171 
  10172 When optional argument INACTIVE-OK is non-nil, also consider
  10173 inactive time ranges.
  10174 
  10175 When this function returns a non-nil value, match data is set
  10176 according to `org-tr-regexp-both' or `org-tr-regexp', depending
  10177 on INACTIVE-OK."
  10178   (save-excursion
  10179     (catch 'exit
  10180       (let ((pos (point)))
  10181 	(skip-chars-backward "^[<\r\n")
  10182 	(skip-chars-backward "<[")
  10183 	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  10184 	     (>= (match-end 0) pos)
  10185 	     (throw 'exit t))
  10186 	(skip-chars-backward "^<[\r\n")
  10187 	(skip-chars-backward "<[")
  10188 	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  10189 	     (>= (match-end 0) pos)
  10190 	     (throw 'exit t)))
  10191       nil)))
  10192 
  10193 (defun org-get-repeat (&optional timestamp)
  10194   "Check if there is a timestamp with repeater in this entry.
  10195 
  10196 Return the repeater, as a string, or nil.  Also return nil when
  10197 this function is called before first heading.
  10198 
  10199 When optional argument TIMESTAMP is a string, extract the
  10200 repeater from there instead."
  10201   (save-match-data
  10202     (cond
  10203      (timestamp
  10204       (and (string-match org-repeat-re timestamp)
  10205 	   (match-string-no-properties 1 timestamp)))
  10206      ((org-before-first-heading-p) nil)
  10207      (t
  10208       (save-excursion
  10209 	(org-back-to-heading t)
  10210 	(let ((end (org-entry-end-position)))
  10211 	  (catch :repeat
  10212 	    (while (re-search-forward org-repeat-re end t)
  10213 	      (when (save-match-data (org-at-timestamp-p 'agenda))
  10214 		(throw :repeat (match-string-no-properties 1)))))))))))
  10215 
  10216 (defvar org-last-changed-timestamp)
  10217 (defvar org-last-inserted-timestamp)
  10218 (defvar org-log-post-message)
  10219 (defvar org-log-note-purpose)
  10220 (defvar org-log-note-how nil)
  10221 (defvar org-log-note-extra)
  10222 (defvar org-log-setup nil)
  10223 (defun org-auto-repeat-maybe (done-word)
  10224   "Check if the current headline contains a repeated timestamp.
  10225 
  10226 If yes, set TODO state back to what it was and change the base date
  10227 of repeating deadline/scheduled time stamps to new date.
  10228 
  10229 This function is run automatically after each state change to a DONE state."
  10230   (let* ((repeat (org-get-repeat))
  10231 	 (aa (assoc org-last-state org-todo-kwd-alist))
  10232 	 (interpret (nth 1 aa))
  10233 	 (head (nth 2 aa))
  10234 	 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  10235 	 (msg "Entry repeats: ")
  10236 	 (org-log-done nil)
  10237 	 (org-todo-log-states nil)
  10238 	 (end (copy-marker (org-entry-end-position))))
  10239     (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  10240       (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  10241       (let ((to-state
  10242              (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  10243 		 (and (stringp org-todo-repeat-to-state)
  10244 		      org-todo-repeat-to-state)
  10245 		 (and org-todo-repeat-to-state org-last-state))))
  10246 	(org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  10247 			 to-state)
  10248 			((eq interpret 'type) org-last-state)
  10249 			(head)
  10250 			(t 'none))))
  10251       (org-back-to-heading t)
  10252       (org-add-planning-info nil nil 'closed)
  10253       ;; When `org-log-repeat' is non-nil or entry contains
  10254       ;; a clock, set LAST_REPEAT property.
  10255       (when (or org-log-repeat
  10256 		(catch :clock
  10257 		  (save-excursion
  10258 		    (while (re-search-forward org-clock-line-re end t)
  10259 		      (when (org-at-clock-log-p) (throw :clock t))))))
  10260 	(org-entry-put nil "LAST_REPEAT" (format-time-string
  10261 					  (org-time-stamp-format t t)
  10262                                           (org-current-effective-time))))
  10263       (when org-log-repeat
  10264 	(if org-log-setup
  10265 	    ;; We are already setup for some record.
  10266 	    (when (eq org-log-repeat 'note)
  10267 	      ;; Make sure we take a note, not only a time stamp.
  10268 	      (setq org-log-note-how 'note))
  10269 	  ;; Set up for taking a record.
  10270 	  (org-add-log-setup 'state
  10271 			     (or done-word (car org-done-keywords))
  10272 			     org-last-state
  10273 			     org-log-repeat)))
  10274       ;; Timestamps without a repeater are usually skipped.  However,
  10275       ;; a SCHEDULED timestamp without one is removed, as they are no
  10276       ;; longer relevant.
  10277       (save-excursion
  10278 	(let ((scheduled (org-entry-get (point) "SCHEDULED")))
  10279 	  (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  10280 	    (org-remove-timestamp-with-keyword org-scheduled-string))))
  10281       ;; Update every timestamp with a repeater in the entry.
  10282       (let ((planning-re (regexp-opt
  10283 			  (list org-scheduled-string org-deadline-string))))
  10284 	(while (re-search-forward org-repeat-re end t)
  10285 	  (let* ((ts (match-string 0))
  10286 		 (type (if (not (org-at-planning-p)) "Plain:"
  10287 			 (save-excursion
  10288 			   (re-search-backward
  10289 			    planning-re (line-beginning-position) t)
  10290 			   (match-string 0)))))
  10291 	    (when (and (org-at-timestamp-p 'agenda)
  10292 		       (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  10293 	      (let ((n (string-to-number (match-string 2 ts)))
  10294 		    (what (match-string 3 ts)))
  10295 		(when (equal what "w") (setq n (* n 7) what "d"))
  10296 		(when (and (equal what "h")
  10297 			   (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  10298 						ts)))
  10299 		  (user-error
  10300 		   "Cannot repeat in %d hour(s) because no hour has been set"
  10301 		   n))
  10302 		;; Preparation, see if we need to modify the start
  10303 		;; date for the change.
  10304 		(when (match-end 1)
  10305 		  (let ((time (save-match-data (org-time-string-to-time ts)))
  10306 			(repeater-type (match-string 1 ts)))
  10307 		    (cond
  10308 		     ((equal "." repeater-type)
  10309 		      ;; Shift starting date to today, or now if
  10310 		      ;; repeater is by hours.
  10311 		      (if (equal what "h")
  10312 			  (org-timestamp-change
  10313 			   (floor (- (org-timestamp-to-now ts t)) 60) 'minute)
  10314 			(org-timestamp-change
  10315 			 (- (org-today) (time-to-days time)) 'day)))
  10316 		     ((equal "+" repeater-type)
  10317 		      (let ((nshiftmax 10)
  10318 			    (nshift 0))
  10319 			(while (or (= nshift 0)
  10320 				   (if (equal what "h")
  10321 				       (not (time-less-p nil time))
  10322 				     (>= (org-today)
  10323 					 (time-to-days time))))
  10324 			  (when (= nshiftmax (cl-incf nshift))
  10325 			    (or (y-or-n-p
  10326 				 (format "%d repeater intervals were not \
  10327 enough to shift date past today.  Continue? "
  10328 					 nshift))
  10329 				(user-error "Abort")))
  10330 			  (org-timestamp-change n (cdr (assoc what whata)))
  10331 			  (org-in-regexp org-ts-regexp3)
  10332 			  (setq ts (match-string 1))
  10333 			  (setq time
  10334 				(save-match-data
  10335 				  (org-time-string-to-time ts)))))
  10336 		      (org-timestamp-change (- n) (cdr (assoc what whata)))
  10337 		      ;; Rematch, so that we have everything in place
  10338 		      ;; for the real shift.
  10339 		      (org-in-regexp org-ts-regexp3)
  10340 		      (setq ts (match-string 1))
  10341 		      (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  10342 				    ts)))))
  10343 		(save-excursion
  10344 		  (org-timestamp-change n (cdr (assoc what whata)) nil t))
  10345 		(setq msg
  10346 		      (concat msg type " " org-last-changed-timestamp " ")))))))
  10347       (run-hooks 'org-todo-repeat-hook)
  10348       (setq org-log-post-message msg)
  10349       (message msg))))
  10350 
  10351 (defun org-show-todo-tree (arg)
  10352   "Make a compact tree which shows all headlines marked with TODO.
  10353 The tree will show the lines where the regexp matches, and all higher
  10354 headlines above the match.
  10355 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  10356 With a numeric prefix N, construct a sparse tree for the Nth element
  10357 of `org-todo-keywords-1'."
  10358   (interactive "P")
  10359   (let ((case-fold-search nil)
  10360 	(kwd-re
  10361 	 (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  10362 	       ((equal arg '(4))
  10363 		(let ((kwd
  10364 		       (completing-read "Keyword (or KWD1|KWD2|...): "
  10365 					(mapcar #'list org-todo-keywords-1))))
  10366 		  (concat "\\("
  10367 			  (mapconcat #'regexp-quote (org-split-string kwd "|") "\\|")
  10368 			  "\\)\\(?:[ \t]\\|$\\)")))
  10369 	       ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  10370 		(regexp-quote (nth (1- (prefix-numeric-value arg))
  10371 				   org-todo-keywords-1)))
  10372 	       (t (user-error "Invalid prefix argument: %s" arg)))))
  10373     (message "%d TODO entries found"
  10374 	     (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  10375 
  10376 (defun org--deadline-or-schedule (arg type time)
  10377   "Insert DEADLINE or SCHEDULE information in current entry.
  10378 TYPE is either `deadline' or `scheduled'.  See `org-deadline' or
  10379 `org-schedule' for information about ARG and TIME arguments."
  10380   (org-fold-core-ignore-modifications
  10381     (let* ((deadline? (eq type 'deadline))
  10382 	   (keyword (if deadline? org-deadline-string org-scheduled-string))
  10383 	   (log (if deadline? org-log-redeadline org-log-reschedule))
  10384 	   (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  10385 	   (old-date-time (and old-date (org-time-string-to-time old-date)))
  10386 	   ;; Save repeater cookie from either TIME or current scheduled
  10387 	   ;; time stamp.  We are going to insert it back at the end of
  10388 	   ;; the process.
  10389 	   (repeater (or (and (org-string-nw-p time)
  10390 			      ;; We use `org-ts-regexp-both' because we
  10391 			      ;; need to tell the difference between a
  10392 			      ;; real repeater and a time delta, e.g.
  10393 			      ;; "+2d".
  10394                               (string-match-p org-ts-regexp-both time)
  10395                               (string-match "\\([.+-]+[0-9]+[hdwmy]\
  10396 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  10397 					    time)
  10398 			      (match-string 1 time))
  10399 		         (and (org-string-nw-p old-date)
  10400 			      (string-match "\\([.+-]+[0-9]+[hdwmy]\
  10401 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  10402 					    old-date)
  10403 			      (match-string 1 old-date)))))
  10404       (pcase arg
  10405         (`(4)
  10406          (if (not old-date)
  10407 	     (message (if deadline? "Entry had no deadline to remove"
  10408 		        "Entry was not scheduled"))
  10409 	   (when (and old-date log)
  10410 	     (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  10411 			     nil old-date log))
  10412 	   (org-remove-timestamp-with-keyword keyword)
  10413 	   (message (if deadline? "Entry no longer has a deadline."
  10414 		      "Entry is no longer scheduled."))))
  10415         (`(16)
  10416          (save-excursion
  10417 	   (org-back-to-heading t)
  10418 	   (let ((regexp (if deadline? org-deadline-time-regexp
  10419 			   org-scheduled-time-regexp)))
  10420 	     (if (not (re-search-forward regexp (line-end-position 2) t))
  10421 	         (user-error (if deadline? "No deadline information to update"
  10422 			       "No scheduled information to update"))
  10423 	       (let* ((rpl0 (match-string 1))
  10424 		      (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  10425 		      (msg (if deadline? "Warn starting from" "Delay until")))
  10426 	         (replace-match
  10427 		  (concat keyword
  10428 			  " <" rpl
  10429 			  (format " -%dd"
  10430 				  (abs (- (time-to-days
  10431 					   (save-match-data
  10432 					     (org-read-date
  10433 					      nil t nil msg old-date-time)))
  10434 					  (time-to-days old-date-time))))
  10435 			  ">") t t))))))
  10436         (_
  10437          (org-add-planning-info type time 'closed)
  10438          (when (and old-date
  10439 		    log
  10440 		    (not (equal old-date org-last-inserted-timestamp)))
  10441 	   (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  10442 			      org-last-inserted-timestamp
  10443 			      old-date
  10444 			      log))
  10445          (when repeater
  10446 	   (save-excursion
  10447 	     (org-back-to-heading t)
  10448 	     (when (re-search-forward
  10449 		    (concat keyword " " org-last-inserted-timestamp)
  10450 		    (line-end-position 2)
  10451 		    t)
  10452 	       (goto-char (1- (match-end 0)))
  10453 	       (insert-and-inherit " " repeater)
  10454 	       (setq org-last-inserted-timestamp
  10455 		     (concat (substring org-last-inserted-timestamp 0 -1)
  10456 			     " " repeater
  10457 			     (substring org-last-inserted-timestamp -1))))))
  10458          (message (if deadline? "Deadline on %s" "Scheduled to %s")
  10459 		  org-last-inserted-timestamp))))))
  10460 
  10461 (defun org-deadline (arg &optional time)
  10462   "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  10463 
  10464 When called interactively, this command pops up the Emacs calendar to let
  10465 the user select a date.
  10466 
  10467 With one universal prefix argument, remove any deadline from the item.
  10468 With two universal prefix arguments, prompt for a warning delay.
  10469 With argument TIME, set the deadline at the corresponding date.  TIME
  10470 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  10471   (interactive "P")
  10472   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10473       (org-map-entries
  10474        (lambda () (org--deadline-or-schedule arg 'deadline time))
  10475        nil
  10476        (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10477 	   'region-start-level
  10478 	 'region)
  10479        (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  10480     (org--deadline-or-schedule arg 'deadline time)))
  10481 
  10482 (defun org-schedule (arg &optional time)
  10483   "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  10484 
  10485 When called interactively, this command pops up the Emacs calendar to let
  10486 the user select a date.
  10487 
  10488 With one universal prefix argument, remove any scheduling date from the item.
  10489 With two universal prefix arguments, prompt for a delay cookie.
  10490 With argument TIME, scheduled at the corresponding date.  TIME can
  10491 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  10492   (interactive "P")
  10493   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10494       (org-map-entries
  10495        (lambda () (org--deadline-or-schedule arg 'scheduled time))
  10496        nil
  10497        (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10498 	   'region-start-level
  10499 	 'region)
  10500        (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  10501     (org--deadline-or-schedule arg 'scheduled time)))
  10502 
  10503 (defun org-get-scheduled-time (pom &optional inherit)
  10504   "Get the scheduled time as a time tuple, of a format suitable
  10505 for calling org-schedule with, or if there is no scheduling,
  10506 returns nil."
  10507   (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  10508     (when time
  10509       (org-time-string-to-time time))))
  10510 
  10511 (defun org-get-deadline-time (pom &optional inherit)
  10512   "Get the deadline as a time tuple, of a format suitable for
  10513 calling org-deadline with, or if there is no scheduling, returns
  10514 nil."
  10515   (let ((time (org-entry-get pom "DEADLINE" inherit)))
  10516     (when time
  10517       (org-time-string-to-time time))))
  10518 
  10519 (defun org-remove-timestamp-with-keyword (keyword)
  10520   "Remove all time stamps with KEYWORD in the current entry."
  10521   (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  10522 	beg)
  10523     (save-excursion
  10524       (org-back-to-heading t)
  10525       (setq beg (point))
  10526       (outline-next-heading)
  10527       (while (re-search-backward re beg t)
  10528 	(replace-match "")
  10529         (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  10530 		 (equal (char-before) ?\ ))
  10531 	    (delete-char -1)
  10532 	  (when (string-match "^[ \t]*$" (buffer-substring
  10533                                           (line-beginning-position) (line-end-position)))
  10534             (delete-region (line-beginning-position)
  10535                            (min (point-max) (1+ (line-end-position))))))))))
  10536 
  10537 (defvar org-time-was-given) ; dynamically scoped parameter
  10538 (defvar org-end-time-was-given) ; dynamically scoped parameter
  10539 
  10540 (defun org-at-planning-p ()
  10541   "Non-nil when point is on a planning info line."
  10542   ;; This is as accurate and faster than `org-element-at-point' since
  10543   ;; planning info location is fixed in the section.
  10544   (or (let ((cached (org-element-at-point nil 'cached)))
  10545         (and cached (org-element-type-p cached 'planning)))
  10546       (org-with-wide-buffer
  10547        (forward-line 0)
  10548        (and (looking-at-p org-planning-line-re)
  10549 	    (eq (point)
  10550 	        (ignore-errors
  10551 	          (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  10552 		      (org-back-to-heading t)
  10553 		    (org-with-limited-levels (org-back-to-heading t)))
  10554 	          (line-beginning-position 2)))))))
  10555 
  10556 (defun org-add-planning-info (what &optional time &rest remove)
  10557   "Insert new timestamp with keyword in the planning line.
  10558 WHAT indicates what kind of time stamp to add.  It is a symbol
  10559 among `closed', `deadline', `scheduled' and nil.  TIME indicates
  10560 the time to use.  If none is given, the user is prompted for
  10561 a date.  REMOVE indicates what kind of entries to remove.  An old
  10562 WHAT entry will also be removed."
  10563   (org-fold-core-ignore-modifications
  10564     (let (org-time-was-given org-end-time-was-given default-time default-input)
  10565       (when (and (memq what '(scheduled deadline))
  10566 	         (or (not time)
  10567 		     (and (stringp time)
  10568 			  (string-match "^[-+]+[0-9]" time))))
  10569         ;; Try to get a default date/time from existing timestamp
  10570         (save-excursion
  10571 	  (org-back-to-heading t)
  10572 	  (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10573 	    (when (re-search-forward (if (eq what 'scheduled)
  10574 				         org-scheduled-time-regexp
  10575 				       org-deadline-time-regexp)
  10576 				     end t)
  10577 	      (setq ts (match-string 1)
  10578 		    default-time (org-time-string-to-time ts)
  10579 		    default-input (and ts (org-get-compact-tod ts)))))))
  10580       (when what
  10581         (setq time
  10582 	      (if (stringp time)
  10583 		  ;; This is a string (relative or absolute), set
  10584 		  ;; proper date.
  10585 		  (org-encode-time
  10586 		   (org-read-date-analyze
  10587 		    time default-time (decode-time default-time)))
  10588 	        ;; If necessary, get the time from the user
  10589 	        (or time (org-read-date nil 'to-time nil
  10590 				     (cl-case what
  10591 				       (deadline "DEADLINE")
  10592 				       (scheduled "SCHEDULED")
  10593 				       (otherwise nil))
  10594 				     default-time default-input)))))
  10595       (org-with-wide-buffer
  10596        (org-back-to-heading t)
  10597        (let ((planning? (save-excursion
  10598 			  (forward-line)
  10599 			  (looking-at-p org-planning-line-re))))
  10600          (cond
  10601 	  (planning?
  10602 	   (forward-line)
  10603 	   ;; Move to current indentation.
  10604 	   (skip-chars-forward " \t")
  10605 	   ;; Check if we have to remove something.
  10606 	   (dolist (type (if what (cons what remove) remove))
  10607 	     (save-excursion
  10608 	       (when (re-search-forward
  10609 		      (cl-case type
  10610 		        (closed org-closed-time-regexp)
  10611 		        (deadline org-deadline-time-regexp)
  10612 		        (scheduled org-scheduled-time-regexp)
  10613 		        (otherwise (error "Invalid planning type: %s" type)))
  10614 		      (line-end-position)
  10615 		      t)
  10616 	         ;; Delete until next keyword or end of line.
  10617 	         (delete-region
  10618 		  (match-beginning 0)
  10619 		  (if (re-search-forward org-keyword-time-not-clock-regexp
  10620 				         (line-end-position)
  10621 				         t)
  10622 		      (match-beginning 0)
  10623 		    (line-end-position))))))
  10624 	   ;; If there is nothing more to add and no more keyword is
  10625 	   ;; left, remove the line completely.
  10626 	   (if (and (looking-at-p "[ \t]*$") (not what))
  10627 	       (delete-region (line-end-position 0)
  10628 			      (line-end-position))
  10629 	     ;; If we removed last keyword, do not leave trailing white
  10630 	     ;; space at the end of line.
  10631 	     (let ((p (point)))
  10632 	       (save-excursion
  10633 	         (end-of-line)
  10634 	         (unless (= (skip-chars-backward " \t" p) 0)
  10635 		   (delete-region (point) (line-end-position)))))))
  10636 	  (what
  10637 	   (end-of-line)
  10638 	   (insert-and-inherit "\n")
  10639 	   (when org-adapt-indentation
  10640 	     (indent-to-column (1+ (org-outline-level)))))
  10641 	  (t nil)))
  10642        (when what
  10643          ;; Insert planning keyword.
  10644          (insert-and-inherit (cl-case what
  10645 		               (closed org-closed-string)
  10646 		               (deadline org-deadline-string)
  10647 		               (scheduled org-scheduled-string)
  10648 		               (otherwise (error "Invalid planning type: %s" what)))
  10649 	                     " ")
  10650          ;; Insert associated timestamp.
  10651          (let ((ts (org-insert-timestamp
  10652 		    time
  10653 		    (or org-time-was-given
  10654 		        (and (eq what 'closed) org-log-done-with-time))
  10655 		    (eq what 'closed)
  10656 		    nil nil (list org-end-time-was-given))))
  10657 	   (unless (eolp) (insert " "))
  10658 	   ts))))))
  10659 
  10660 (defvar org-log-note-marker (make-marker)
  10661   "Marker pointing at the entry where the note is to be inserted.")
  10662 (defvar org-log-note-purpose nil)
  10663 (defvar org-log-note-state nil)
  10664 (defvar org-log-note-previous-state nil)
  10665 (defvar org-log-note-extra nil)
  10666 (defvar org-log-note-window-configuration nil)
  10667 (defvar org-log-note-return-to (make-marker))
  10668 (defvar org-log-note-effective-time nil
  10669   "Remembered current time.
  10670 So that dynamically scoped `org-extend-today-until' affects
  10671 timestamps in state change log.")
  10672 (defvar org-log-note-this-command
  10673   "`this-command' when `org-add-log-setup' is called.")
  10674 (defvar org-log-note-recursion-depth
  10675   "`recursion-depth' when `org-add-log-setup' is called.")
  10676 
  10677 (defvar org-log-post-message nil
  10678   "Message to be displayed after a log note has been stored.
  10679 The auto-repeater uses this.")
  10680 
  10681 (defun org-add-note ()
  10682   "Add a note to the current entry.
  10683 This is done in the same way as adding a state change note."
  10684   (interactive)
  10685   (org-add-log-setup 'note))
  10686 
  10687 (defun org-log-beginning (&optional create)
  10688   "Return expected start of log notes in current entry.
  10689 When optional argument CREATE is non-nil, the function creates
  10690 a drawer to store notes, if necessary.  Returned position ignores
  10691 narrowing."
  10692   (org-with-wide-buffer
  10693    (let ((drawer (org-log-into-drawer)))
  10694      (cond
  10695       (drawer
  10696        ;; This either moves past planning and property drawer, to
  10697        ;; first line below heading, or to `eob' (if heading is the
  10698        ;; last heading in buffer without contents).
  10699        (org-end-of-meta-data)
  10700        (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10701 	     (end (if (org-at-heading-p) (point)
  10702 		    (save-excursion (outline-next-heading) (point))))
  10703 	     (case-fold-search t))
  10704 	 (catch 'exit
  10705 	   ;; Try to find existing drawer.
  10706 	   (while (re-search-forward regexp end t)
  10707 	     (let ((element (org-element-at-point)))
  10708 	       (when (org-element-type-p element 'drawer)
  10709 		 (let ((cend  (org-element-contents-end element)))
  10710 		   (when (and (not org-log-states-order-reversed) cend)
  10711 		     (goto-char cend)))
  10712 		 (throw 'exit nil))))
  10713 	   ;; No drawer found.  Create one, if permitted.
  10714 	   (when create
  10715              ;; `org-end-of-meta-data' ended up at next heading
  10716              ;; * Heading to insert darawer<maybe folded>
  10717              ;; * Another heading
  10718              ;;
  10719              ;; Unless current heading is the last heading in buffer
  10720              ;; and does not have a newline, `org-end-of-meta-data'
  10721              ;; can move us to the next heading.
  10722              ;; Avoid situation when we insert drawer right before
  10723              ;; first "*".  Otherwise, if the heading is folded, we
  10724              ;; are inserting after visible newline at the end of the
  10725              ;; fold, thus breaking the fold continuity.
  10726              (unless (eobp)
  10727                (when (org-at-heading-p) (backward-char)))
  10728              (org-fold-core-ignore-modifications
  10729                (let (;; Heading
  10730                      ;; <point>
  10731                      ;; Text
  10732                      (at-blank-line? (looking-at-p "^[ \t]*$"))
  10733                      ;; Heading
  10734                      ;; <point>Text
  10735                      (at-beginning-of-non-blank-line?
  10736                       (and (bolp) (not (eolp)))))
  10737 	         (unless (bolp)
  10738                    ;; Heading<point> (see `backward-char' branch above)
  10739                    (insert-and-inherit "\n"))
  10740 	         (let ((beg (point)) cbeg)
  10741 	           (insert-and-inherit ":" drawer ":")
  10742                    (setq cbeg (point))
  10743                    (insert-and-inherit "\n:END:")
  10744                    (cond
  10745                     (at-blank-line?
  10746                      ;; Heading
  10747                      ;; :LOGBOOK:
  10748                      ;; :END:
  10749                      ;;
  10750                      ;; Text
  10751                      (insert "\n")
  10752                      (backward-char))
  10753                     (at-beginning-of-non-blank-line?
  10754                      ;; Heading
  10755                      ;; :LOGBOOK:
  10756                      ;; :END:
  10757                      ;; Text
  10758                      (insert "\n")
  10759                      (backward-char)))
  10760 	           (org-indent-region beg (point))
  10761 	           (org-fold-region cbeg (point) t 'drawer)))))
  10762 	   (end-of-line 0))))
  10763       (t
  10764        (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10765        (let ((endpos (point)))
  10766          (skip-chars-forward " \t\n")
  10767          (forward-line 0)
  10768          (unless org-log-states-order-reversed
  10769 	   (org-skip-over-state-notes)
  10770 	   (skip-chars-backward " \t\n")
  10771 	   (forward-line 1))
  10772          ;; When current headline is at the end of buffer and does not
  10773          ;; end with trailing newline the above can move to the
  10774          ;; beginning of the headline.
  10775          (when (< (point) endpos) (goto-char endpos))))))
  10776    (if (bolp) (point) (line-beginning-position 2))))
  10777 
  10778 (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10779   "Set up the post command hook to take a note.
  10780 If this is about to TODO state change, the new state is expected in STATE.
  10781 HOW is an indicator what kind of note should be created.
  10782 EXTRA is additional text that will be inserted into the notes buffer."
  10783   (move-marker org-log-note-marker (point))
  10784   (setq org-log-note-purpose purpose
  10785 	org-log-note-state state
  10786 	org-log-note-previous-state prev-state
  10787 	org-log-note-how how
  10788 	org-log-note-extra extra
  10789 	org-log-note-effective-time (org-current-effective-time)
  10790         org-log-note-this-command this-command
  10791         org-log-note-recursion-depth (recursion-depth)
  10792         org-log-setup t)
  10793   (add-hook 'post-command-hook 'org-add-log-note 'append))
  10794 
  10795 (defun org-skip-over-state-notes ()
  10796   "Skip past the list of State notes in an entry.
  10797 The point is assumed to be on a list of State notes, each matching
  10798 `org-log-note-headings'.  The function moves point to the first list
  10799 item that is not a State note or to the end of the list if all the
  10800 items are State notes."
  10801   (when (ignore-errors (goto-char (org-in-item-p)))
  10802     (let* ((struct (org-list-struct))
  10803 	   (prevs (org-list-prevs-alist struct))
  10804 	   (regexp
  10805 	    (concat "[ \t]*- +"
  10806 		    (replace-regexp-in-string
  10807 		     " +" " +"
  10808 		     (org-replace-escapes
  10809 		      (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10810 		      `(("%d" . ,org-ts-regexp-inactive)
  10811 			("%D" . ,org-ts-regexp)
  10812 			("%s" . "\\(?:\"\\S-+\"\\)?")
  10813 			("%S" . "\\(?:\"\\S-+\"\\)?")
  10814 			("%t" . ,org-ts-regexp-inactive)
  10815 			("%T" . ,org-ts-regexp)
  10816 			("%u" . ".*?")
  10817 			("%U" . ".*?")))))))
  10818       (while (looking-at-p regexp)
  10819 	(goto-char (or (org-list-get-next-item (point) struct prevs)
  10820 		       (org-list-get-item-end (point) struct)))))))
  10821 
  10822 (defun org-add-log-note (&optional _purpose)
  10823   "Pop up a window for taking a note, and add this note later."
  10824   (when (and (equal org-log-note-this-command this-command)
  10825              (= org-log-note-recursion-depth (recursion-depth)))
  10826     (remove-hook 'post-command-hook 'org-add-log-note)
  10827     (setq org-log-setup nil)
  10828     (setq org-log-note-window-configuration (current-window-configuration))
  10829     (move-marker org-log-note-return-to (point))
  10830     (pop-to-buffer (marker-buffer org-log-note-marker) '(org-display-buffer-full-frame))
  10831     (goto-char org-log-note-marker)
  10832     (pop-to-buffer "*Org Note*" '(org-display-buffer-split))
  10833     (erase-buffer)
  10834     (if (memq org-log-note-how '(time state))
  10835         (org-store-log-note)
  10836       (let ((org-inhibit-startup t)) (org-mode))
  10837       (insert (format "# Insert note for %s.
  10838 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10839                       (cl-case org-log-note-purpose
  10840                         (clock-out "stopped clock")
  10841                         (done  "closed todo item")
  10842                         (reschedule "rescheduling")
  10843                         (delschedule "no longer scheduled")
  10844                         (redeadline "changing deadline")
  10845                         (deldeadline "removing deadline")
  10846                         (refile "refiling")
  10847                         (note "this entry")
  10848                         (state
  10849                          (format "state change from \"%s\" to \"%s\""
  10850                                  (or org-log-note-previous-state "")
  10851                                  (or org-log-note-state "")))
  10852                         (t (error "This should not happen")))))
  10853       (when org-log-note-extra (insert org-log-note-extra))
  10854       (setq-local org-finish-function 'org-store-log-note)
  10855       (run-hooks 'org-log-buffer-setup-hook))))
  10856 
  10857 (defvar org-note-abort nil) ; dynamically scoped
  10858 (defun org-store-log-note ()
  10859   "Finish taking a log note, and insert it to where it belongs."
  10860   (let ((txt (prog1 (buffer-string)
  10861 	       (kill-buffer)))
  10862 	(note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10863 	lines)
  10864     (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10865       (setq txt (replace-match "" t t txt)))
  10866     (when (string-match "\\s-+\\'" txt)
  10867       (setq txt (replace-match "" t t txt)))
  10868     (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10869     (when (org-string-nw-p note)
  10870       (setq note
  10871 	    (org-replace-escapes
  10872 	     note
  10873 	     (list (cons "%u" (user-login-name))
  10874 		   (cons "%U" user-full-name)
  10875 		   (cons "%t" (format-time-string
  10876 			       (org-time-stamp-format 'long 'inactive)
  10877 			       org-log-note-effective-time))
  10878 		   (cons "%T" (format-time-string
  10879 			       (org-time-stamp-format 'long nil)
  10880 			       org-log-note-effective-time))
  10881 		   (cons "%d" (format-time-string
  10882 			       (org-time-stamp-format nil 'inactive)
  10883 			       org-log-note-effective-time))
  10884 		   (cons "%D" (format-time-string
  10885 			       (org-time-stamp-format nil nil)
  10886 			       org-log-note-effective-time))
  10887 		   (cons "%s" (cond
  10888 			       ((not org-log-note-state) "")
  10889 			       ((string-match-p org-ts-regexp
  10890 						org-log-note-state)
  10891 				(format "\"[%s]\""
  10892 					(substring org-log-note-state 1 -1)))
  10893 			       (t (format "\"%s\"" org-log-note-state))))
  10894 		   (cons "%S"
  10895 			 (cond
  10896 			  ((not org-log-note-previous-state) "")
  10897 			  ((string-match-p org-ts-regexp
  10898 					   org-log-note-previous-state)
  10899 			   (format "\"[%s]\""
  10900 				   (substring
  10901 				    org-log-note-previous-state 1 -1)))
  10902 			  (t (format "\"%s\""
  10903 				     org-log-note-previous-state)))))))
  10904       (when lines (setq note (concat note " \\\\")))
  10905       (push note lines))
  10906     (when (and lines (not org-note-abort))
  10907       (with-current-buffer (marker-buffer org-log-note-marker)
  10908         (org-fold-core-ignore-modifications
  10909 	  (org-with-wide-buffer
  10910 	   ;; Find location for the new note.
  10911 	   (goto-char org-log-note-marker)
  10912 	   (set-marker org-log-note-marker nil)
  10913 	   ;; Note associated to a clock is to be located right after
  10914 	   ;; the clock.  Do not move point.
  10915 	   (unless (eq org-log-note-purpose 'clock-out)
  10916 	     (goto-char (org-log-beginning t)))
  10917 	   ;; Make sure point is at the beginning of an empty line.
  10918 	   (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  10919 	         ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  10920 	   ;; In an existing list, add a new item at the top level.
  10921 	   ;; Otherwise, indent line like a regular one.
  10922 	   (let ((itemp (org-in-item-p)))
  10923 	     (if itemp
  10924 	         (indent-line-to
  10925 		  (let ((struct (save-excursion
  10926 				  (goto-char itemp) (org-list-struct))))
  10927 		    (org-list-get-ind (org-list-get-top-point struct) struct)))
  10928 	       (org-indent-line)))
  10929 	   (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  10930 	   (let ((ind (org-list-item-body-column (line-beginning-position))))
  10931 	     (dolist (line lines)
  10932 	       (insert-and-inherit "\n")
  10933                (unless (string-empty-p line)
  10934 	         (indent-line-to ind)
  10935 	         (insert-and-inherit line))))
  10936            (run-hooks 'org-after-note-stored-hook)
  10937 	   (message "Note stored")
  10938 	   (org-back-to-heading t))))))
  10939   ;; Don't add undo information when called from `org-agenda-todo'.
  10940   (set-window-configuration org-log-note-window-configuration)
  10941   (with-current-buffer (marker-buffer org-log-note-return-to)
  10942     (goto-char org-log-note-return-to))
  10943   (move-marker org-log-note-return-to nil)
  10944   (when org-log-post-message (message "%s" org-log-post-message)))
  10945 
  10946 (defun org-remove-empty-drawer-at (pos)
  10947   "Remove an empty drawer at position POS.
  10948 POS may also be a marker."
  10949   (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10950     (org-with-wide-buffer
  10951      (goto-char pos)
  10952      (let ((drawer (org-element-at-point)))
  10953        (when (and (org-element-type-p drawer '(drawer property-drawer))
  10954 		  (not (org-element-contents-begin drawer)))
  10955 	 (delete-region (org-element-begin drawer)
  10956 			(progn (goto-char (org-element-end drawer))
  10957 			       (skip-chars-backward " \r\t\n")
  10958 			       (forward-line)
  10959 			       (point))))))))
  10960 
  10961 (defvar org-ts-type nil)
  10962 (defun org-sparse-tree (&optional arg type)
  10963   "Create a sparse tree, prompt for the details.
  10964 This command can create sparse trees.  You first need to select the type
  10965 of match used to create the tree:
  10966 
  10967 t      Show all TODO entries.
  10968 T      Show entries with a specific TODO keyword.
  10969 m      Show entries selected by a tags/property match.
  10970 p      Enter a property name and its value (both with completion on existing
  10971        names/values) and show entries with that property.
  10972 r      Show entries matching a regular expression (`/' can be used as well).
  10973 b      Show deadlines and scheduled items before a date.
  10974 a      Show deadlines and scheduled items after a date.
  10975 d      Show deadlines due within `org-deadline-warning-days'.
  10976 D      Show deadlines and scheduled items between a date range."
  10977   (interactive "P")
  10978   (setq type (or type org-sparse-tree-default-date-type))
  10979   (setq org-ts-type type)
  10980   (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10981              [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10982              [c]ycle through date types: %s"
  10983 	   (cl-case type
  10984 	     (all "all timestamps")
  10985 	     (scheduled "only scheduled")
  10986 	     (deadline "only deadline")
  10987 	     (active "only active timestamps")
  10988 	     (inactive "only inactive timestamps")
  10989 	     (closed "with a closed timestamp")
  10990 	     (otherwise "scheduled/deadline")))
  10991   (let ((answer (read-char-exclusive)))
  10992     (cl-case answer
  10993       (?c
  10994        (org-sparse-tree
  10995 	arg
  10996 	(cadr
  10997 	 (memq type '(nil all scheduled deadline active inactive closed)))))
  10998       (?d (call-interactively 'org-check-deadlines))
  10999       (?b (call-interactively 'org-check-before-date))
  11000       (?a (call-interactively 'org-check-after-date))
  11001       (?D (call-interactively 'org-check-dates-range))
  11002       (?t (call-interactively 'org-show-todo-tree))
  11003       (?T (org-show-todo-tree '(4)))
  11004       (?m (call-interactively 'org-match-sparse-tree))
  11005       ((?p ?P)
  11006        (let* ((kwd (completing-read
  11007 		    "Property: " (mapcar #'list (org-buffer-property-keys))))
  11008               (kwd
  11009                ;; Escape "-" in property names.
  11010                (replace-regexp-in-string "-" "\\\\-" kwd))
  11011 	      (value (completing-read
  11012 		      "Value: " (mapcar #'list (org-property-values kwd)))))
  11013 	 (unless (string-match "\\`{.*}\\'" value)
  11014 	   (setq value (concat "\"" value "\"")))
  11015 	 (org-match-sparse-tree arg (concat kwd "=" value))))
  11016       ((?r ?R ?/) (call-interactively 'org-occur))
  11017       (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  11018 
  11019 (defvar-local org-occur-highlights nil
  11020   "List of overlays used for occur matches.")
  11021 (put 'org-occur-highlights 'permanent-local t)
  11022 (defvar-local org-occur-parameters nil
  11023   "Parameters of the active org-occur calls.
  11024 This is a list, each call to org-occur pushes as cons cell,
  11025 containing the regular expression and the callback, onto the list.
  11026 The list can contain several entries if `org-occur' has been called
  11027 several time with the KEEP-PREVIOUS argument.  Otherwise, this list
  11028 will only contain one set of parameters.  When the highlights are
  11029 removed (for example with \\`C-c C-c', or with the next edit (depending
  11030 on `org-remove-highlights-with-change'), this variable is emptied
  11031 as well.")
  11032 
  11033 (defun org-occur (regexp &optional keep-previous callback)
  11034   "Make a compact tree showing all matches of REGEXP.
  11035 
  11036 The tree will show the lines where the regexp matches, and any other context
  11037 defined in `org-fold-show-context-detail', which see.
  11038 
  11039 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  11040 done by a previous call to `org-occur' will be kept, to allow stacking of
  11041 calls to this command.
  11042 
  11043 Optional argument CALLBACK can be a function of no argument.  In this case,
  11044 it is called with point at the end of the match, match data being set
  11045 accordingly.  Current match is shown only if the return value is non-nil.
  11046 The function must neither move point nor alter narrowing."
  11047   (interactive "sRegexp: \nP")
  11048   (when (equal regexp "")
  11049     (user-error "Regexp cannot be empty"))
  11050   (unless keep-previous
  11051     (org-remove-occur-highlights nil nil t))
  11052   (push (cons regexp callback) org-occur-parameters)
  11053   (let ((cnt 0))
  11054     (save-excursion
  11055       (goto-char (point-min))
  11056       (when (or (not keep-previous)	    ; do not want to keep
  11057 		(not org-occur-highlights)) ; no previous matches
  11058 	;; hide everything
  11059 	(org-cycle-overview))
  11060       (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  11061 				  (isearch-no-upper-case-p regexp t)
  11062 				org-occur-case-fold-search)))
  11063 	(while (re-search-forward regexp nil t)
  11064 	  (when (or (not callback)
  11065 		    (save-match-data (funcall callback)))
  11066 	    (setq cnt (1+ cnt))
  11067 	    (when org-highlight-sparse-tree-matches
  11068 	      (org-highlight-new-match (match-beginning 0) (match-end 0)))
  11069 	    (org-fold-show-context 'occur-tree)))))
  11070     (when org-remove-highlights-with-change
  11071       (add-hook 'before-change-functions 'org-remove-occur-highlights
  11072 		nil 'local))
  11073     (unless org-sparse-tree-open-archived-trees
  11074       (org-fold-hide-archived-subtrees (point-min) (point-max)))
  11075     (run-hooks 'org-occur-hook)
  11076     (when (called-interactively-p 'interactive)
  11077       (message "%d match(es) for regexp %s" cnt regexp))
  11078     cnt))
  11079 
  11080 (defun org-occur-next-match (&optional n _reset)
  11081   "Function for `next-error-function' to find sparse tree matches.
  11082 N is the number of matches to move, when negative move backwards.
  11083 This function always goes back to the starting point when no
  11084 match is found."
  11085   (let* ((limit (if (< n 0) (point-min) (point-max)))
  11086 	 (search-func (if (< n 0)
  11087 			  'previous-single-char-property-change
  11088 			'next-single-char-property-change))
  11089 	 (n (abs n))
  11090 	 (pos (point))
  11091 	 p1)
  11092     (catch 'exit
  11093       (while (setq p1 (funcall search-func (point) 'org-type))
  11094 	(when (equal p1 limit)
  11095 	  (goto-char pos)
  11096 	  (user-error "No more matches"))
  11097 	(when (equal (get-char-property p1 'org-type) 'org-occur)
  11098 	  (setq n (1- n))
  11099 	  (when (= n 0)
  11100 	    (goto-char p1)
  11101 	    (throw 'exit (point))))
  11102 	(goto-char p1))
  11103       (goto-char p1)
  11104       (user-error "No more matches"))))
  11105 
  11106 (defun org-highlight-new-match (beg end)
  11107   "Highlight from BEG to END and mark the highlight is an occur headline."
  11108   (let ((ov (make-overlay beg end)))
  11109     (overlay-put ov 'face 'secondary-selection)
  11110     (overlay-put ov 'org-type 'org-occur)
  11111     (push ov org-occur-highlights)))
  11112 
  11113 (defun org-remove-occur-highlights (&optional _beg _end noremove)
  11114   "Remove the occur highlights from the buffer.
  11115 BEG and END are ignored.  If NOREMOVE is nil, remove this function
  11116 from the `before-change-functions' in the current buffer."
  11117   (interactive)
  11118   (unless org-inhibit-highlight-removal
  11119     (mapc #'delete-overlay org-occur-highlights)
  11120     (setq org-occur-highlights nil)
  11121     (setq org-occur-parameters nil)
  11122     (unless noremove
  11123       (remove-hook 'before-change-functions
  11124 		   'org-remove-occur-highlights 'local))))
  11125 
  11126 ;;;; Priorities
  11127 
  11128 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  11129   "Regular expression matching the priority indicator.
  11130 A priority indicator can be e.g. [#A] or [#1].
  11131 This regular expression matches these groups:
  11132 0 : the whole match, e.g. \"TODO [#A] Hack\"
  11133 1 : the priority cookie, e.g. \"[#A]\"
  11134 2 : the value of the priority cookie, e.g. \"A\".")
  11135 
  11136 (defun org-priority-up ()
  11137   "Increase the priority of the current item."
  11138   (interactive)
  11139   (org-priority 'up))
  11140 
  11141 (defun org-priority-down ()
  11142   "Decrease the priority of the current item."
  11143   (interactive)
  11144   (org-priority 'down))
  11145 
  11146 (defun org-priority (&optional action show)
  11147   "Change the priority of an item.
  11148 
  11149 When called interactively with a `\\[universal-argument]' prefix,
  11150 show the priority in the minibuffer instead of changing it.
  11151 
  11152 When called programmatically, ACTION can be `set', `up', `down',
  11153 or a character."
  11154   (interactive "P")
  11155   (when show
  11156     ;; Deprecation warning inserted for Org 9.2; once enough time has
  11157     ;; passed the SHOW argument should be removed.
  11158     (warn "`org-priority' called with deprecated SHOW argument"))
  11159   (if (equal action '(4))
  11160       (org-priority-show)
  11161     (unless org-priority-enable-commands
  11162       (user-error "Priority commands are disabled"))
  11163     (setq action (or action 'set))
  11164     (let ((nump (< org-priority-lowest 65))
  11165 	  current new news have remove)
  11166       (save-excursion
  11167 	(org-back-to-heading t)
  11168 	(when (looking-at org-priority-regexp)
  11169 	  (let ((ms (match-string 2)))
  11170 	    (setq current (org-priority-to-value ms)
  11171 		  have t)))
  11172 	(cond
  11173 	 ((eq action 'remove)
  11174 	  (setq remove t new ?\ ))
  11175 	 ((or (eq action 'set)
  11176 	      (integerp action))
  11177 	  (if (not (eq action 'set))
  11178 	      (setq new action)
  11179 	    (setq
  11180 	     new
  11181 	     (if nump
  11182                  (let* ((msg (format "Priority %s-%s, SPC to remove: "
  11183                                      (number-to-string org-priority-highest)
  11184                                      (number-to-string org-priority-lowest)))
  11185                         (s (if (< 9 org-priority-lowest)
  11186                                (read-string msg)
  11187                              (message msg)
  11188                              (char-to-string (read-char-exclusive)))))
  11189                    (if (equal s " ") ?\s (string-to-number s)))
  11190 	       (progn (message "Priority %c-%c, SPC to remove: "
  11191 			       org-priority-highest org-priority-lowest)
  11192 		      (save-match-data
  11193 			(setq new (read-char-exclusive)))))))
  11194 	  (when (and (= (upcase org-priority-highest) org-priority-highest)
  11195 		     (= (upcase org-priority-lowest) org-priority-lowest))
  11196 	    (setq new (upcase new)))
  11197 	  (cond ((equal new ?\s) (setq remove t))
  11198 		((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  11199 		 (user-error
  11200 		  (if nump
  11201 		      "Priority must be between `%s' and `%s'"
  11202 		    "Priority must be between `%c' and `%c'")
  11203 		  org-priority-highest org-priority-lowest))))
  11204 	 ((eq action 'up)
  11205 	  (setq new (if have
  11206 			(1- current)  ; normal cycling
  11207 		      ;; last priority was empty
  11208 		      (if (eq last-command this-command)
  11209 			  org-priority-lowest  ; wrap around empty to lowest
  11210 			;; default
  11211 			(if org-priority-start-cycle-with-default
  11212 			    org-priority-default
  11213 			  (1- org-priority-default))))))
  11214 	 ((eq action 'down)
  11215 	  (setq new (if have
  11216 			(1+ current)  ; normal cycling
  11217 		      ;; last priority was empty
  11218 		      (if (eq last-command this-command)
  11219 			  org-priority-highest  ; wrap around empty to highest
  11220 			;; default
  11221 			(if org-priority-start-cycle-with-default
  11222 			    org-priority-default
  11223 			  (1+ org-priority-default))))))
  11224 	 (t (user-error "Invalid action")))
  11225 	(when (or (< (upcase new) org-priority-highest)
  11226 		  (> (upcase new) org-priority-lowest))
  11227 	  (if (and (memq action '(up down))
  11228 		   (not have) (not (eq last-command this-command)))
  11229 	      ;; `new' is from default priority
  11230 	      (error
  11231 	       "The default can not be set, see `org-priority-default' why")
  11232 	    ;; normal cycling: `new' is beyond highest/lowest priority
  11233 	    ;; and is wrapped around to the empty priority
  11234 	    (setq remove t)))
  11235 	;; Numerical priorities are limited to 64, beyond that number,
  11236 	;; assume the priority cookie is a character.
  11237 	(setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  11238 	(if have
  11239 	    (if remove
  11240 		(replace-match "" t t nil 1)
  11241 	      (replace-match news t t nil 2))
  11242 	  (if remove
  11243 	      (user-error "No priority cookie found in line")
  11244 	    (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11245 	    (if (match-end 2)
  11246 		(progn
  11247 		  (goto-char (match-end 2))
  11248 		  (insert " [#" news "]"))
  11249 	      (goto-char (match-beginning 3))
  11250 	      (insert "[#" news "] "))))
  11251 	(when org-auto-align-tags (org-align-tags)))
  11252       (if remove
  11253 	  (message "Priority removed")
  11254 	(message "Priority of current item set to %s" news)))))
  11255 
  11256 (defalias 'org-show-priority 'org-priority-show)
  11257 (defun org-priority-show ()
  11258   "Show the priority of the current item as number.
  11259 Return the priority value."
  11260   (interactive)
  11261   (let ((pri (if (eq major-mode 'org-agenda-mode)
  11262 		 (org-get-at-bol 'priority)
  11263 	       (save-excursion
  11264 		 (save-match-data
  11265 		   (forward-line 0)
  11266 		   (and (looking-at org-heading-regexp)
  11267 			(org-get-priority (match-string 0))))))))
  11268     (message "Priority is %d" (if pri pri -1000))))
  11269 
  11270 (defun org-get-priority (s)
  11271   "Find priority cookie and return priority.
  11272 S is a string against which you can match `org-priority-regexp'.
  11273 If `org-priority-get-priority-function' is set to a custom
  11274 function, use it.  Otherwise process S and output the priority
  11275 value, an integer."
  11276   (save-match-data
  11277     (if (functionp org-priority-get-priority-function)
  11278 	(funcall org-priority-get-priority-function s)
  11279       (if (not (string-match org-priority-regexp s))
  11280 	  (* 1000 (- org-priority-lowest org-priority-default))
  11281 	(* 1000 (- org-priority-lowest
  11282 		   (org-priority-to-value (match-string 2 s))))))))
  11283 
  11284 ;;;; Tags
  11285 
  11286 (defvar org-agenda-archives-mode)
  11287 (defvar org-map-continue-from nil
  11288   "Position from where mapping should continue.
  11289 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  11290 
  11291 (defvar org-scanner-tags nil
  11292   "The current tag list while the tags scanner is running.")
  11293 
  11294 (defvar org-trust-scanner-tags nil
  11295   "Should `org-get-tags' use the tags for the scanner.
  11296 This is for internal dynamical scoping only.
  11297 When this is non-nil, the function `org-get-tags' will return the value
  11298 of `org-scanner-tags' instead of building the list by itself.  This
  11299 can lead to large speed-ups when the tags scanner is used in a file with
  11300 many entries, and when the list of tags is retrieved, for example to
  11301 obtain a list of properties.  Building the tags list for each entry in such
  11302 a file becomes an N^2 operation - but with this variable set, it scales
  11303 as N.")
  11304 
  11305 (defvar org--matcher-tags-todo-only nil)
  11306 
  11307 (defun org-scan-tags (action matcher todo-only &optional start-level)
  11308   "Scan headline tags with inheritance and produce output ACTION.
  11309 
  11310 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  11311 or `agenda' to produce an entry list for an agenda view.  It can also be
  11312 a Lisp form or a function that should be called at each matched headline, in
  11313 this case the return value is a list of all return values from these calls.
  11314 
  11315 MATCHER is a function accepting three arguments, returning
  11316 a non-nil value whenever a given set of tags qualifies a headline
  11317 for inclusion.  See `org-make-tags-matcher' for more information.
  11318 As a special case, it can also be set to t (respectively nil) in
  11319 order to match all (respectively none) headline.
  11320 
  11321 When TODO-ONLY is non-nil, only lines with a TODO keyword are
  11322 included in the output.
  11323 
  11324 START-LEVEL can be a string with asterisks, reducing the scope to
  11325 headlines matching this string."
  11326   (require 'org-agenda)
  11327   (let* ((heading-re
  11328           (concat ;;FIXME: use cache
  11329            "^"
  11330            (if start-level
  11331 	       ;; Get the correct level to match
  11332 	       (concat "\\*\\{" (number-to-string start-level) "\\} ")
  11333 	     org-outline-regexp)))
  11334 	 (props (list 'face 'default
  11335 		      'done-face 'org-agenda-done
  11336 		      'undone-face 'default
  11337 		      'mouse-face 'highlight
  11338 		      'org-not-done-regexp org-not-done-regexp
  11339 		      'org-todo-regexp org-todo-regexp
  11340 		      'org-complex-heading-regexp org-complex-heading-regexp
  11341 		      'help-echo
  11342 		      (format "mouse-2 or RET jump to Org file %S"
  11343 			      (abbreviate-file-name
  11344 			       (or (buffer-file-name (buffer-base-buffer))
  11345 				   (buffer-name (buffer-base-buffer)))))))
  11346 	 (org-map-continue-from nil)
  11347          tags-list rtn rtn1 level category txt
  11348 	 todo marker priority
  11349 	 ts-date ts-date-type ts-date-pair)
  11350     (unless (or (member action '(agenda sparse-tree)) (functionp action))
  11351       (setq action (list 'lambda nil action)))
  11352     (save-excursion
  11353       (goto-char (point-min))
  11354       (when (eq action 'sparse-tree)
  11355 	(org-cycle-overview)
  11356 	(org-remove-occur-highlights))
  11357       (org-element-cache-map
  11358        (lambda (el)
  11359          (goto-char (org-element-begin el))
  11360          (setq todo (org-element-property :todo-keyword el)
  11361                level (org-element-property :level el)
  11362                category (org-entry-get-with-inheritance "CATEGORY" nil el)
  11363                tags-list (org-get-tags el)
  11364                org-scanner-tags tags-list)
  11365          (when (eq action 'agenda)
  11366            (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp el)
  11367 		 ts-date (car ts-date-pair)
  11368 		 ts-date-type (cdr ts-date-pair)))
  11369          (catch :skip
  11370            (when (and
  11371 
  11372 		  ;; eval matcher only when the todo condition is OK
  11373 		  (and (or (not todo-only) (member todo org-todo-keywords-1))
  11374 		       (if (functionp matcher)
  11375 			   (let ((case-fold-search t) (org-trust-scanner-tags t))
  11376 			     (funcall matcher todo tags-list level))
  11377 			 matcher))
  11378 
  11379 		  ;; Call the skipper, but return t if it does not
  11380 		  ;; skip, so that the `and' form continues evaluating.
  11381 		  (progn
  11382 		    (unless (eq action 'sparse-tree) (org-agenda-skip el))
  11383 		    t)
  11384 
  11385 		  ;; Check if timestamps are deselecting this entry
  11386 		  (or (not todo-only)
  11387 		      (and (member todo org-todo-keywords-1)
  11388 			   (or (not org-agenda-tags-todo-honor-ignore-options)
  11389 			       (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  11390 
  11391 	     ;; select this headline
  11392 	     (cond
  11393 	      ((eq action 'sparse-tree)
  11394 	       (and org-highlight-sparse-tree-matches
  11395 		    (org-get-heading) (match-end 0)
  11396 		    (org-highlight-new-match
  11397 		     (match-beginning 1) (match-end 1)))
  11398 	       (org-fold-show-context 'tags-tree))
  11399 	      ((eq action 'agenda)
  11400                (let* ((effort (org-entry-get (point) org-effort-property))
  11401                       (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  11402 	         (setq txt (org-agenda-format-item
  11403 			    ""
  11404                             ;; Add `effort' and `effort-minutes'
  11405                             ;; properties for prefix format.
  11406                             (org-add-props
  11407                                 (concat
  11408 			         (if (eq org-tags-match-list-sublevels 'indented)
  11409 			             (make-string (1- level) ?.) "")
  11410 			         (org-get-heading))
  11411                                 nil
  11412                               'effort effort
  11413                               'effort-minutes effort-minutes)
  11414 			    (make-string level ?\s)
  11415 			    category
  11416 			    tags-list)
  11417 		       priority (org-get-priority txt))
  11418                  ;; Now add `effort' and `effort-minutes' to
  11419                  ;; full agenda line.
  11420                  (setq txt (org-add-props txt nil
  11421                              'effort effort
  11422                              'effort-minutes effort-minutes)))
  11423 	       (goto-char (org-element-begin el))
  11424 	       (setq marker (org-agenda-new-marker))
  11425 	       (org-add-props txt props
  11426 		 'org-marker marker 'org-hd-marker marker 'org-category category
  11427 		 'todo-state todo
  11428                  'ts-date ts-date
  11429 		 'priority priority
  11430                  'type (concat "tagsmatch" ts-date-type))
  11431 	       (push txt rtn))
  11432 	      ((functionp action)
  11433 	       (setq org-map-continue-from nil)
  11434 	       (save-excursion
  11435 		 (setq rtn1 (funcall action))
  11436 		 (push rtn1 rtn)))
  11437 	      (t (user-error "Invalid action")))
  11438 
  11439 	     ;; if we are to skip sublevels, jump to end of subtree
  11440 	     (unless org-tags-match-list-sublevels
  11441 	       (goto-char (1- (org-element-end el))))))
  11442          ;; Get the correct position from where to continue
  11443 	 (when org-map-continue-from
  11444            (setq org-element-cache-map-continue-from org-map-continue-from)
  11445 	   (goto-char org-map-continue-from))
  11446          ;; Return nil.
  11447          nil)
  11448        :next-re heading-re
  11449        :fail-re heading-re
  11450        :narrow t))
  11451     (when (and (eq action 'sparse-tree)
  11452 	       (not org-sparse-tree-open-archived-trees))
  11453       (org-fold-hide-archived-subtrees (point-min) (point-max)))
  11454     (nreverse rtn)))
  11455 
  11456 (defun org-remove-uninherited-tags (tags)
  11457   "Remove all tags that are not inherited from the list TAGS."
  11458   (cond
  11459    ((eq org-use-tag-inheritance t)
  11460     (if org-tags-exclude-from-inheritance
  11461 	(org-delete-all org-tags-exclude-from-inheritance tags)
  11462       tags))
  11463    ((not org-use-tag-inheritance) nil)
  11464    ((stringp org-use-tag-inheritance)
  11465     (delq nil (mapcar
  11466 	       (lambda (x)
  11467 		 (if (and (string-match org-use-tag-inheritance x)
  11468 			  (not (member x org-tags-exclude-from-inheritance)))
  11469 		     x nil))
  11470 	       tags)))
  11471    ((listp org-use-tag-inheritance)
  11472     (delq nil (mapcar
  11473 	       (lambda (x)
  11474 		 (if (member x org-use-tag-inheritance) x nil))
  11475 	       tags)))))
  11476 
  11477 (defun org-match-sparse-tree (&optional todo-only match)
  11478   "Create a sparse tree according to tags string MATCH.
  11479 
  11480 MATCH is a string with match syntax.  It can contain a selection
  11481 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  11482 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  11483 those.  See the manual for details.
  11484 
  11485 If optional argument TODO-ONLY is non-nil, only select lines that
  11486 are also TODO tasks."
  11487   (interactive "P")
  11488   (org-agenda-prepare-buffers (list (current-buffer)))
  11489   (let ((org--matcher-tags-todo-only todo-only))
  11490     (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  11491 		   org--matcher-tags-todo-only)))
  11492 
  11493 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  11494 
  11495 (defun org-global-tags-completion-table (&optional files)
  11496   "Return the list of all tags in all agenda buffer/files.
  11497 Optional FILES argument is a list of files which can be used
  11498 instead of the agenda files."
  11499   (save-excursion
  11500     (org-uniquify
  11501      (delq nil
  11502 	   (apply #'append
  11503 		  (mapcar
  11504 		   (lambda (file)
  11505 		     (set-buffer (find-file-noselect file))
  11506 		     (org--tag-add-to-alist
  11507 		      (org-get-buffer-tags)
  11508 		      (mapcar (lambda (x)
  11509 				(and (stringp (car-safe x))
  11510 				     (list (car-safe x))))
  11511 			      org-current-tag-alist)))
  11512 		   (if (car-safe files) files
  11513 		     (org-agenda-files))))))))
  11514 
  11515 (defun org-make-tags-matcher (match &optional only-local-tags)
  11516   "Create the TAGS/TODO matcher form for the selection string MATCH.
  11517 
  11518 Returns a cons of the selection string MATCH and a function
  11519 implementing the matcher.
  11520 
  11521 The matcher is to be called at an Org entry, with point on the
  11522 headline, and returns non-nil if the entry matches the selection
  11523 string MATCH.  It must be called with three arguments: the TODO
  11524 keyword at the entry (or nil if none), the list of all tags at
  11525 the entry including inherited ones and the reduced level of the
  11526 headline.  Additionally, the category of the entry, if any, must
  11527 be specified as the text property `org-category' on the headline.
  11528 
  11529 This function sets the variable `org--matcher-tags-todo-only' to
  11530 a non-nil value if the matcher restricts matching to TODO
  11531 entries, otherwise it is not touched.
  11532 
  11533 When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  11534 table, only get buffer tags.
  11535 
  11536 See also `org-scan-tags'."
  11537   (unless match
  11538     ;; Get a new match request, with completion against the global
  11539     ;; tags table and the local tags in current buffer.
  11540     (let ((org-last-tags-completion-table
  11541 	   (org--tag-add-to-alist
  11542             (when (derived-mode-p 'org-mode)
  11543 	      (org-get-buffer-tags))
  11544 	    (unless only-local-tags
  11545 	      (org-global-tags-completion-table)))))
  11546       (setq match
  11547 	    (completing-read
  11548 	     "Match: "
  11549 	     'org-tags-completion-function nil nil nil 'org-tags-history))))
  11550 
  11551   (let* ((match0 match)
  11552          (opre "[<=>]=?\\|[!/]=\\|<>")
  11553          (re (concat
  11554               "^"
  11555               ;; implicit AND operator (OR is done by global splitting)
  11556               "&?"
  11557               ;; exclusion and inclusion (the latter being implicit)
  11558               "\\(?1:[-+:]\\)?"
  11559               ;; query term
  11560               "\\(?2:"
  11561                   ;; tag regexp match
  11562                   "{[^}]+}\\|"
  11563                   ;; property match.  Try to keep this subre generic
  11564                   ;; and rather handle special properties like LEVEL
  11565                   ;; and CATEGORY further below.  This ensures that
  11566                   ;; the same quoting mechanics can be used for all
  11567                   ;; property names.
  11568                   "\\(?:"
  11569                       ;; property name [1]
  11570                       "\\(?5:\\(?:[[:alnum:]_]+\\|\\\\[^[:space:]]\\)+\\)"
  11571                       ;; operator, optionally starred
  11572                       "\\(?6:" opre "\\)\\(?7:\\*\\)?"
  11573                       ;; operand (regexp, double-quoted string,
  11574                       ;; number)
  11575                       "\\(?8:"
  11576                           "{[^}]+}\\|"
  11577                           "\"[^\"]*\"\\|"
  11578                           "-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?"
  11579                       "\\)"
  11580                   "\\)\\|"
  11581                   ;; exact tag match
  11582                   org-tag-re
  11583               "\\)"))
  11584          (start 0)
  11585          tagsmatch todomatch tagsmatcher todomatcher)
  11586 
  11587     ;; [1] The history of this particular subre:
  11588     ;; - \\([[:alnum:]_]+\\) [pre-19b0e03]
  11589     ;;   Does not allow for minus characters in property names.
  11590     ;; - "\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)" [19b0e03]
  11591     ;;   Incomplete fix of above issue, still resulting in, e.g.,
  11592     ;;   https://orgmode.org/list/87jzv67k3p.fsf@localhost.
  11593     ;; - "\\(?5:[[:alnum:]_-]+\\)" [f689eb4]
  11594     ;;   Allows for unquoted minus characters in property names, but
  11595     ;;   conflicts with searches like -TAG-PROP="VALUE".  See
  11596     ;;   https://orgmode.org/list/87h6oq2nu1.fsf@gmail.com.
  11597     ;; - current subre
  11598     ;;   Like second solution, but with proper unquoting and allowing
  11599     ;;   for all possible characters in property names to be quoted.
  11600 
  11601     ;; Expand group tags.
  11602     (setq match (org-tags-expand match))
  11603 
  11604     ;; Check if there is a TODO part of this match, which would be the
  11605     ;; part after a "/".  To make sure that this slash is not part of
  11606     ;; a property value to be matched against, we also check that
  11607     ;; there is no / after that slash.  First, find the last slash.
  11608     (let ((s 0))
  11609       (while (string-match "/+" match s)
  11610 	(setq start (match-beginning 0))
  11611 	(setq s (match-end 0))))
  11612     (if (and (string-match "/+" match start)
  11613 	     (not (string-match-p "\"" match start)))
  11614 	;; Match contains also a TODO-matching request.
  11615 	(progn
  11616 	  (setq tagsmatch (substring match 0 (match-beginning 0)))
  11617 	  (setq todomatch (substring match (match-end 0)))
  11618 	  (when (string-prefix-p "!" todomatch)
  11619 	    (setq org--matcher-tags-todo-only t)
  11620 	    (setq todomatch (substring todomatch 1)))
  11621 	  (when (string-match "\\`\\s-*\\'" todomatch)
  11622 	    (setq todomatch nil)))
  11623       ;; Only matching tags.
  11624       (setq tagsmatch match)
  11625       (setq todomatch nil))
  11626 
  11627     ;; Make the tags matcher.
  11628     (when (org-string-nw-p tagsmatch)
  11629       (let ((orlist nil)
  11630 	    (orterms (org-split-string tagsmatch "|"))
  11631 	    term)
  11632 	(while (setq term (pop orterms))
  11633 	  (while (and (equal (substring term -1) "\\") orterms)
  11634 	    (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  11635 	  (while (string-match re term)
  11636 	    (let* ((rest (substring term (match-end 0)))
  11637 		   (minus (and (match-end 1)
  11638 			       (equal (match-string 1 term) "-")))
  11639 		   ;; Bind the whole query term to `tag' and use that
  11640 		   ;; variable for a tag regexp match in [2] or as an
  11641 		   ;; exact tag match in [3].
  11642 		   (tag (match-string 2 term))
  11643 		   (regexp (eq (string-to-char tag) ?{))
  11644 		   (propp (match-end 5))
  11645 		   (mm
  11646 		    (cond
  11647 		     (regexp			; [2]
  11648                       `(with-syntax-table org-mode-tags-syntax-table
  11649                          (org-match-any-p ,(substring tag 1 -1) tags-list)))
  11650 		     (propp
  11651 		      (let* (;; Determine property name.
  11652                              (pn (upcase
  11653                                   (save-match-data
  11654                                     (replace-regexp-in-string
  11655                                      "\\\\\\(.\\)" "\\1"
  11656                                      (match-string 5 term)
  11657                                      t nil))))
  11658                              ;; Convert property name to an Elisp
  11659 			     ;; accessor for that property (aka. as
  11660 			     ;; getter value).  Symbols LEVEL and TODO
  11661 			     ;; referenced below get bound by the
  11662 			     ;; matcher that this function returns.
  11663 			     (gv (pcase pn
  11664 				   ("LEVEL"
  11665                                     '(number-to-string level))
  11666 				   ("CATEGORY"
  11667 				    '(org-get-category (point)))
  11668 				   ("TODO" 'todo)
  11669 				   (p `(org-entry-get (point) ,p 'selective))))
  11670 			     ;; Determine operand (aka. property
  11671 			     ;; value).
  11672 			     (pv (match-string 8 term))
  11673 			     ;; Determine type of operand.  Note that
  11674 			     ;; these are not exclusive: Any TIMEP is
  11675 			     ;; also STRP.
  11676 			     (regexp (eq (string-to-char pv) ?{))
  11677 			     (strp (eq (string-to-char pv) ?\"))
  11678 			     (timep (string-match-p "^\"[[<]\\(?:[0-9]+\\|now\\|today\\|tomorrow\\|[+-][0-9]+[dmwy]\\).*[]>]\"$" pv))
  11679 			     ;; Massage operand.  TIMEP must come
  11680 			     ;; before STRP.
  11681 			     (pv (cond (regexp (substring pv 1 -1))
  11682 				       (timep  (org-matcher-time
  11683 						(substring pv 1 -1)))
  11684 				       (strp   (substring pv 1 -1))
  11685 				       (t      pv)))
  11686 			     ;; Convert operator to Elisp.
  11687 			     (po (org-op-to-function (match-string 6 term)
  11688 						     (if timep 'time strp)))
  11689 			     ;; Convert whole property term to Elisp.
  11690 			     (pt (cond ((and regexp (eq po '/=))
  11691 					`(not (string-match ,pv (or ,gv ""))))
  11692 				       (regexp `(string-match ,pv (or ,gv "")))
  11693 				       (strp `(,po (or ,gv "") ,pv))
  11694 				       (t
  11695 					`(,po
  11696 					  (string-to-number (or ,gv ""))
  11697 					  ,(string-to-number pv)))))
  11698 			     ;; Respect the star after the operand.
  11699 			     (pt (if (match-end 7) `(and ,gv ,pt) pt)))
  11700 			pt))
  11701 		     (t `(member ,tag tags-list))))) ; [3]
  11702 	      (push (if minus `(not ,mm) mm) tagsmatcher)
  11703 	      (setq term rest)))
  11704 	  (push `(and ,@tagsmatcher) orlist)
  11705 	  (setq tagsmatcher nil))
  11706 	(setq tagsmatcher `(or ,@orlist))))
  11707 
  11708     ;; Make the TODO matcher.
  11709     (when (org-string-nw-p todomatch)
  11710       (let ((orlist nil))
  11711 	(dolist (term (org-split-string todomatch "|"))
  11712 	  (while (string-match re term)
  11713 	    (let* ((minus (and (match-end 1)
  11714 			       (equal (match-string 1 term) "-")))
  11715 		   (kwd (match-string 2 term))
  11716 		   (regexp (eq (string-to-char kwd) ?{))
  11717 		   (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  11718 			 `(equal todo ,kwd))))
  11719 	      (push (if minus `(not ,mm) mm) todomatcher))
  11720 	    (setq term (substring term (match-end 0))))
  11721 	  (push (if (> (length todomatcher) 1)
  11722 		    (cons 'and todomatcher)
  11723 		  (car todomatcher))
  11724 		orlist)
  11725 	  (setq todomatcher nil))
  11726 	(setq todomatcher (cons 'or orlist))))
  11727 
  11728     ;; Return the string and function of the matcher.  If no
  11729     ;; tags-specific or todo-specific matcher exists, match
  11730     ;; everything.
  11731     (let ((matcher (if (and tagsmatcher todomatcher)
  11732 		       `(and ,tagsmatcher ,todomatcher)
  11733 		     (or tagsmatcher todomatcher t))))
  11734       (when org--matcher-tags-todo-only
  11735 	(setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  11736       (cons match0
  11737             (byte-compile
  11738              `(lambda (todo tags-list level)
  11739                 ;; Pacify byte-compiler.
  11740                 (ignore todo) (ignore tags-list) (ignore level)
  11741                 ,matcher))))))
  11742 
  11743 (defun org--tags-expand-group (group tag-groups expanded)
  11744   "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  11745 TAG-GROUPS is the list of groups used for expansion.  EXPANDED is
  11746 an accumulator used in recursive calls."
  11747   (dolist (tag group)
  11748     (unless (member tag expanded)
  11749       (let ((group (assoc tag tag-groups)))
  11750 	(push tag expanded)
  11751 	(when group
  11752 	  (setq expanded
  11753 		(org--tags-expand-group (cdr group) tag-groups expanded))))))
  11754   expanded)
  11755 
  11756 (defun org-tags-expand (match &optional single-as-list)
  11757   "Expand group tags in MATCH.
  11758 
  11759 This replaces every group tag in MATCH with a regexp tag search.
  11760 For example, a group tag \"Work\" defined as { Work : Lab Conf }
  11761 will be replaced like this:
  11762 
  11763    Work =>  {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11764   +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11765   -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11766 
  11767 Replacing by a regexp preserves the structure of the match.
  11768 E.g., this expansion
  11769 
  11770   Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  11771 
  11772 will match anything tagged with \"Lab\" and \"Home\", or tagged
  11773 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  11774 
  11775 A group tag in MATCH can contain regular expressions of its own.
  11776 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  11777 will be replaced like this:
  11778 
  11779    Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11780 
  11781 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11782 assumed to be a single group tag, and the function will return
  11783 the list of tags in this group."
  11784   (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11785   (let ((tag-groups
  11786          (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11787     (cond
  11788      (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11789      (org-group-tags
  11790       (let* ((case-fold-search t)
  11791 	     (group-keys (mapcar #'car tag-groups))
  11792 	     (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11793 	     (return-match match))
  11794 	;; Mark regexp-expressions in the match-expression so that we
  11795 	;; do not replace them later on.
  11796 	(let ((s 0))
  11797 	  (while (string-match "{.+?}" return-match s)
  11798 	    (setq s (match-end 0))
  11799 	    (add-text-properties
  11800 	     (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11801 	;; For each tag token found in MATCH, compute a regexp and  it
  11802 	(with-syntax-table org-mode-tags-syntax-table
  11803 	  (replace-regexp-in-string
  11804 	   key-regexp
  11805 	   (lambda (m)
  11806 	     (if (get-text-property (match-beginning 2) 'regexp m)
  11807 		 m			;regexp tag: ignore
  11808 	       (let* ((operator (match-string 1 m))
  11809 		      (tag-token (let ((tag (match-string 2 m)))
  11810 				   (list tag)))
  11811 		      regexp-tags regular-tags)
  11812 		 ;; Partition tags between regexp and regular tags.
  11813 		 ;; Remove curly bracket syntax from regexp tags.
  11814 		 (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11815 		   (save-match-data
  11816 		     (if (string-match "{\\(.+?\\)}" tag)
  11817 			 (push (match-string 1 tag) regexp-tags)
  11818 		       (push tag regular-tags))))
  11819 		 ;; Replace tag token by the appropriate regexp.
  11820 		 ;; Regular tags need to be regexp-quoted, whereas
  11821 		 ;; regexp-tags are inserted as-is.
  11822 		 (let ((regular (regexp-opt regular-tags))
  11823 		       (regexp (mapconcat #'identity regexp-tags "\\|")))
  11824 		   (concat operator
  11825 			   (cond
  11826 			    ((null regular-tags) (format "{%s}" regexp))
  11827 			    ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11828 			    (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11829 	   return-match
  11830 	   t t))))
  11831      (t match))))
  11832 
  11833 (defun org-op-to-function (op &optional stringp)
  11834   "Turn an operator into the appropriate function."
  11835   (setq op
  11836 	(cond
  11837 	 ((equal  op   "<"            ) '(<     org-string<  org-time<))
  11838 	 ((equal  op   ">"            ) '(>     org-string>  org-time>))
  11839 	 ((member op '("<=" "=<"     )) '(<=    org-string<= org-time<=))
  11840 	 ((member op '(">=" "=>"     )) '(>=    org-string>= org-time>=))
  11841 	 ((member op '("="  "=="     )) '(=     string=      org-time=))
  11842 	 ((member op '("<>" "!=" "/=")) '(/=    org-string<> org-time<>))))
  11843   (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11844 
  11845 (defvar org-add-colon-after-tag-completion nil)  ;; dynamically scoped param
  11846 (defvar org-tags-overlay (make-overlay 1 1))
  11847 (delete-overlay org-tags-overlay)
  11848 
  11849 (defun org-add-prop-inherited (s)
  11850   (propertize s 'inherited t))
  11851 
  11852 (defun org-toggle-tag (tag &optional onoff)
  11853   "Toggle the tag TAG for the current line.
  11854 If ONOFF is `on' or `off', don't toggle but set to this state."
  11855   (save-excursion
  11856     (org-back-to-heading t)
  11857     (let ((current
  11858 	   ;; Reverse the tags list so any new tag is appended to the
  11859 	   ;; current list of tags.
  11860 	   (nreverse (org-get-tags nil t)))
  11861 	  res)
  11862       (pcase onoff
  11863 	(`off (setq current (delete tag current)))
  11864 	((or `on (guard (not (member tag current))))
  11865 	 (setq res t)
  11866 	 (cl-pushnew tag current :test #'equal))
  11867 	(_ (setq current (delete tag current))))
  11868       (org-set-tags (nreverse current))
  11869       res)))
  11870 
  11871 (defun org--align-tags-here (to-col)
  11872   "Align tags on the current headline to TO-COL.
  11873 Assume point is on a headline.  Preserve point when aligning
  11874 tags."
  11875   (when (org-match-line org-tag-line-re)
  11876     (let* ((tags-start (match-beginning 1))
  11877 	   (blank-start (save-excursion
  11878 			  (goto-char tags-start)
  11879 			  (skip-chars-backward " \t")
  11880 			  (point)))
  11881 	   (new (max (if (>= to-col 0) to-col
  11882 		       (- (abs to-col) (string-width (match-string 1))))
  11883 		     ;; Introduce at least one space after the heading
  11884 		     ;; or the stars.
  11885 		     (save-excursion
  11886 		       (goto-char blank-start)
  11887 		       (1+ (current-column)))))
  11888 	   (current
  11889 	    (save-excursion (goto-char tags-start) (current-column)))
  11890 	   (origin (point-marker))
  11891 	   (column (current-column))
  11892 	   (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11893       (when (/= new current)
  11894 	(delete-region blank-start tags-start)
  11895 	(goto-char blank-start)
  11896 	(let ((indent-tabs-mode nil)) (indent-to new))
  11897 	;; Try to move back to original position.  If point was in the
  11898 	;; blanks before the tags, ORIGIN marker is of no use because
  11899 	;; it now points to BLANK-START.  Use COLUMN instead.
  11900 	(if in-blank? (org-move-to-column column) (goto-char origin))))))
  11901 
  11902 (defun org-set-tags-command (&optional arg)
  11903   "Set the tags for the current visible entry.
  11904 
  11905 When called with `\\[universal-argument]' prefix argument ARG, \
  11906 realign all tags
  11907 in the current buffer.
  11908 
  11909 When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11910 unconditionally do not
  11911 offer the fast tag selection interface.
  11912 
  11913 If a region is active, set tags in the region according to the
  11914 setting of `org-loop-over-headlines-in-active-region'.
  11915 
  11916 This function is for interactive use only;
  11917 in Lisp code use `org-set-tags' instead."
  11918   (interactive "P")
  11919   (let ((org-use-fast-tag-selection
  11920 	 (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11921     (cond
  11922      ((equal '(4) arg) (org-align-tags t))
  11923      ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11924       (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11925 		    'region-start-level 'region))
  11926             org-loop-over-headlines-in-active-region) ;  hint: infinite recursion.
  11927 	(org-map-entries
  11928 	 #'org-set-tags-command
  11929 	 nil cl
  11930 	 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11931      (t
  11932       (save-excursion
  11933         ;; FIXME: We need to add support setting #+FILETAGS.
  11934         (when (org-before-first-heading-p)
  11935           (user-error "Setting file tags is not supported yet"))
  11936 	(org-back-to-heading)
  11937 	(let* ((all-tags (org-get-tags))
  11938                (local-table (or org-current-tag-alist (org-get-buffer-tags)))
  11939 	       (table (setq org-last-tags-completion-table
  11940                             (append
  11941                              ;; Put local tags in front.
  11942                              local-table
  11943                              (cl-set-difference
  11944 			      (org--tag-add-to-alist
  11945 			       (and org-complete-tags-always-offer-all-agenda-tags
  11946 				    (org-global-tags-completion-table
  11947 				     (org-agenda-files)))
  11948 			       local-table)
  11949                               local-table))))
  11950 	       (current-tags
  11951 		(cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11952 			      all-tags))
  11953 	       (inherited-tags
  11954 		(cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11955 				  all-tags))
  11956 	       (tags
  11957 		(replace-regexp-in-string
  11958 		 ;; Ignore all forbidden characters in tags.
  11959 		 "[^[:alnum:]_@#%]+" ":"
  11960 		 (if (or (eq t org-use-fast-tag-selection)
  11961 			 (and org-use-fast-tag-selection
  11962 			      (delq nil (mapcar #'cdr table))))
  11963 		     (org-fast-tag-selection
  11964 		      current-tags
  11965 		      inherited-tags
  11966 		      table
  11967 		      (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11968 		   (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  11969                          (crm-separator "[ \t]*:[ \t]*"))
  11970 		     (mapconcat #'identity
  11971                                 (completing-read-multiple
  11972 			         "Tags: "
  11973 			         org-last-tags-completion-table
  11974 			         nil nil (org-make-tag-string current-tags)
  11975 			         'org-tags-history)
  11976                                 ":"))))))
  11977 	  (org-set-tags tags)))))
  11978     ;; `save-excursion' may not replace the point at the right
  11979     ;; position.
  11980     (when (and (save-excursion (skip-chars-backward "*") (bolp))
  11981 	       (looking-at-p " "))
  11982       (forward-char))))
  11983 
  11984 (defun org-align-tags (&optional all)
  11985   "Align tags in current entry.
  11986 When optional argument ALL is non-nil, align all tags in the
  11987 visible part of the buffer."
  11988   (let ((get-indent-column
  11989 	 (lambda ()
  11990 	   (let ((offset (if (bound-and-true-p org-indent-mode)
  11991                              (save-excursion
  11992                                (org-back-to-heading-or-point-min)
  11993                                (length
  11994                                 (get-text-property
  11995                                  (line-end-position)
  11996                                  'line-prefix)))
  11997 			   0)))
  11998 	     (+ org-tags-column
  11999 		(if (> org-tags-column 0) (- offset) offset))))))
  12000     (if (and (not all) (org-at-heading-p))
  12001 	(org--align-tags-here (funcall get-indent-column))
  12002       (save-excursion
  12003 	(if all
  12004 	    (progn
  12005 	      (goto-char (point-min))
  12006 	      (while (re-search-forward org-tag-line-re nil t)
  12007 		(org--align-tags-here (funcall get-indent-column))))
  12008 	  (org-back-to-heading t)
  12009 	  (org--align-tags-here (funcall get-indent-column)))))))
  12010 
  12011 (defun org-set-tags (tags)
  12012   "Set the tags of the current entry to TAGS, replacing current tags.
  12013 
  12014 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12015 If TAGS is nil or the empty string, all tags are removed.
  12016 
  12017 This function assumes point is on a headline."
  12018   (org-with-wide-buffer
  12019    (org-fold-core-ignore-modifications
  12020      (let ((tags (pcase tags
  12021 		   ((pred listp) tags)
  12022 		   ((pred stringp) (split-string (org-trim tags) ":" t))
  12023 		   (_ (error "Invalid tag specification: %S" tags))))
  12024 	   (old-tags (org-get-tags nil t))
  12025 	   (tags-change? nil))
  12026        (when (functionp org-tags-sort-function)
  12027          (setq tags (sort tags org-tags-sort-function)))
  12028        (setq tags-change? (not (equal tags old-tags)))
  12029        (when tags-change?
  12030          ;; Delete previous tags and any trailing white space.
  12031          (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  12032 		      (line-end-position)))
  12033          (skip-chars-backward " \t")
  12034          (delete-region (point) (line-end-position))
  12035          ;; Deleting white spaces may break an otherwise empty headline.
  12036          ;; Re-introduce one space in this case.
  12037          (unless (org-at-heading-p) (insert " "))
  12038          (when tags
  12039 	   (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  12040 	   ;; When text is being inserted on an invisible region
  12041 	   ;; boundary, it can be inadvertently sucked into
  12042 	   ;; invisibility.
  12043 	   (unless (org-invisible-p (line-beginning-position))
  12044 	     (org-fold-region (point) (line-end-position) nil 'outline))))
  12045        ;; Align tags, if any.
  12046        (when (and tags org-auto-align-tags) (org-align-tags))
  12047        (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  12048 
  12049 (defun org-change-tag-in-region (beg end tag off)
  12050   "Add or remove TAG for each entry in the region.
  12051 This works in the agenda, and also in an Org buffer."
  12052   (interactive
  12053    (list (region-beginning) (region-end)
  12054 	 (let ((org-last-tags-completion-table
  12055 		(if (derived-mode-p 'org-mode)
  12056 		    (org--tag-add-to-alist
  12057 		     (org-get-buffer-tags)
  12058 		     (org-global-tags-completion-table))
  12059 		  (org-global-tags-completion-table))))
  12060 	   (completing-read
  12061 	    "Tag: " org-last-tags-completion-table nil nil nil
  12062 	    'org-tags-history))
  12063 	 (progn
  12064 	   (message "[s]et or [r]emove? ")
  12065 	   (equal (read-char-exclusive) ?r))))
  12066   (deactivate-mark)
  12067   (let ((agendap (equal major-mode 'org-agenda-mode))
  12068 	l1 l2 m buf pos newhead (cnt 0))
  12069     (goto-char end)
  12070     (setq l2 (1- (org-current-line)))
  12071     (goto-char beg)
  12072     (setq l1 (org-current-line))
  12073     (cl-loop for l from l1 to l2 do
  12074 	     (org-goto-line l)
  12075 	     (setq m (get-text-property (point) 'org-hd-marker))
  12076 	     (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  12077 		       (and agendap m))
  12078 	       (setq buf (if agendap (marker-buffer m) (current-buffer))
  12079 		     pos (if agendap m (point)))
  12080 	       (with-current-buffer buf
  12081 		 (save-excursion
  12082 		   (save-restriction
  12083 		     (goto-char pos)
  12084 		     (setq cnt (1+ cnt))
  12085 		     (org-toggle-tag tag (if off 'off 'on))
  12086 		     (setq newhead (org-get-heading)))))
  12087 	       (and agendap (org-agenda-change-all-lines newhead m))))
  12088     (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  12089 
  12090 (defun org-tags-completion-function (string _predicate &optional flag)
  12091   "Complete tag STRING.
  12092 FLAG specifies the type of completion operation to perform.  This
  12093 function is passed as a collection function to `completing-read',
  12094 which see."
  12095   (let ((completion-ignore-case nil)	;tags are case-sensitive
  12096 	(confirm (lambda (x) (stringp (car x))))
  12097 	(prefix "")
  12098         begin)
  12099     (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  12100       (setq prefix (match-string 1 string))
  12101       (setq begin (match-beginning 2))
  12102       (setq string (match-string 2 string)))
  12103     (pcase flag
  12104       (`t (all-completions string org-last-tags-completion-table confirm))
  12105       (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  12106       (`(boundaries . ,suffix)
  12107        (let ((end (if (string-match "[-+:&,|]" suffix)
  12108                       (match-string 0 suffix)
  12109                     (length suffix))))
  12110          `(boundaries ,(or begin 0) . ,end)))
  12111       (`nil
  12112        (pcase (try-completion string org-last-tags-completion-table confirm)
  12113 	 ((and completion (pred stringp))
  12114 	  (concat prefix
  12115 		  completion
  12116 		  (if (and org-add-colon-after-tag-completion
  12117 			   (assoc completion org-last-tags-completion-table))
  12118 		      ":"
  12119 		    "")))
  12120 	 (completion completion)))
  12121       (_ nil))))
  12122 
  12123 (defun org-fast-tag-insert (kwd tags face &optional end)
  12124   "Insert KWD, and the TAGS, the latter with face FACE.
  12125 Also insert END."
  12126   (insert (format "%-12s" (concat kwd ":"))
  12127 	  (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  12128 	  (or end "")))
  12129 
  12130 (defun org-fast-tag-show-exit (flag)
  12131   (save-excursion
  12132     (org-goto-line 3)
  12133     (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  12134       (replace-match ""))
  12135     (when flag
  12136       (end-of-line 1)
  12137       (org-move-to-column (- (window-width) 19) t)
  12138       (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  12139 
  12140 (defun org-set-current-tags-overlay (current prefix)
  12141   "Add an overlay to CURRENT tag with PREFIX."
  12142   (let ((s (org-make-tag-string current)))
  12143     (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  12144     (org-overlay-display org-tags-overlay (concat prefix s))))
  12145 
  12146 (defun org--add-or-remove-tag (tag current-tags &optional groups)
  12147   "Add or remove TAG entered by user to/from CURRENT-TAGS.
  12148 Return the modified CURRENT-TAGS.
  12149 
  12150 When TAG is present in CURRENT-TAGS, remove it.  Otherwise, add it.
  12151 When TAG is a part of a tag group from GROUPS, make sure that no
  12152 exclusive tags from the same group remain in CURRENT-TAGS.
  12153 
  12154 CURRENT-TAGS may be modified by side effect."
  12155   (if (member tag current-tags)
  12156       ;; Remove the tag.
  12157       (delete tag current-tags)
  12158     ;; Add the tag.  If the tag is from a tag
  12159     ;; group, exclude selected alternative tags
  12160     ;; from the group, if any.
  12161     (dolist (g groups)
  12162       (when (member tag g)
  12163 	(dolist (x g) (setq current-tags (delete x current-tags)))))
  12164     (cons tag current-tags)))
  12165 
  12166 (defvar org-last-tag-selection-key nil)
  12167 (defun org-fast-tag-selection (current-tags inherited-tags tag-table &optional todo-table)
  12168   "Fast tag selection with single keys.
  12169 CURRENT-TAGS is the current list of tags in the headline,
  12170 INHERITED-TAGS is the list of inherited tags, and TAG-TABLE is an
  12171 alist of tags and corresponding keys, possibly with grouping
  12172 information.  TODO-TABLE is a similar table with TODO keywords, should
  12173 these have keys assigned to them.
  12174 If the keys are nil, a-z are automatically assigned.
  12175 Returns the new tags string, or nil to not change the current settings."
  12176   (let* (;; Combined alist of all the tags and todo keywords.
  12177          (tag-alist (append tag-table todo-table))
  12178          ;; Max width occupied by a single tag record in the completion buffer.
  12179 	 (field-width
  12180           (+ 3 ; keep space for "[c]" binding.
  12181              1 ; ensure that there is at least one space between adjacent tag fields.
  12182              3 ; keep space for group tag " : " delimiter.
  12183              ;; The longest tag.
  12184              (if (null tag-alist) 0
  12185 	       (apply #'max
  12186 		      (mapcar (lambda (x)
  12187 			        (if (stringp (car x)) (string-width (car x))
  12188 			          0))
  12189 			      tag-alist)))))
  12190 	 (origin-buffer (current-buffer))
  12191 	 (expert-interface (eq org-fast-tag-selection-single-key 'expert))
  12192          ;; Tag completion table, for normal completion (<TAB>).
  12193 	 (tab-tags nil)
  12194 	 (inherited-face 'org-done)
  12195 	 (current-face 'org-todo)
  12196          ;; Characters available for auto-assignment.
  12197          (tag-binding-char-list org--fast-tag-selection-keys)
  12198          (tag-binding-chars-left org-fast-tag-selection-maximum-tags)
  12199          field-number ; current tag column in the completion buffer.
  12200          tag-binding-spec ; Alist element.
  12201          current-tag current-tag-char auto-tag-char
  12202          tag-table-local ; table holding all the displayed tags together with auto-assigned bindings.
  12203          input-char rtn
  12204 	 ov-start ov-end ov-prefix
  12205 	 (exit-after-next org-fast-tag-selection-single-key)
  12206 	 (done-keywords org-done-keywords)
  12207 	 groups ingroup intaggroup)
  12208     ;; Calculate the number of tags with explicit user bindings + tags in groups.
  12209     ;; These tags will be displayed unconditionally.  Other tags will
  12210     ;; be displayed only when there are free bindings left according
  12211     ;; to `org-fast-tag-selection-maximum-tags'.
  12212     (dolist (tag-binding-spec tag-alist)
  12213       (pcase tag-binding-spec
  12214         (`((or :startgroup :startgrouptag) . _)
  12215          (setq ingroup t))
  12216         (`((or :endgroup :endgrouptag) . _)
  12217          (setq ingroup nil))
  12218         ((guard (cdr tag-binding-spec))
  12219          (cl-decf tag-binding-chars-left))
  12220         (`((or :newline :grouptags))) ; pass
  12221         ((guard ingroup)
  12222          (cl-decf tag-binding-chars-left))))
  12223     (setq ingroup nil) ; It t, it means malformed tag alist.  Reset just in case.
  12224     ;; Move global `org-tags-overlay' overlay to current heading.
  12225     ;; Calls to `org-set-current-tags-overlay' will take care about
  12226     ;; updating the overlay text.
  12227     ;; FIXME: What if we are setting file tags?
  12228     (save-excursion
  12229       (forward-line 0)
  12230       (if (looking-at org-tag-line-re)
  12231 	  (setq ov-start (match-beginning 1)
  12232 		ov-end (match-end 1)
  12233 		ov-prefix "")
  12234         (setq ov-start (1- (line-end-position))
  12235 	      ov-end (1+ ov-start))
  12236 	(skip-chars-forward "^\n\r")
  12237 	(setq ov-prefix
  12238 	      (concat
  12239 	       (buffer-substring (1- (point)) (point))
  12240 	       (if (> (current-column) org-tags-column)
  12241 		   " "
  12242 		 (make-string (- org-tags-column (current-column)) ?\ ))))))
  12243     (move-overlay org-tags-overlay ov-start ov-end)
  12244     ;; Highlight tags overlay in Org buffer.
  12245     (org-set-current-tags-overlay current-tags ov-prefix)
  12246     ;; Display tag selection dialog, read the user input, and return.
  12247     (save-excursion
  12248       (save-window-excursion
  12249         ;; Select tag list buffer, and display it unless EXPERT-INTERFACE.
  12250 	(if expert-interface
  12251 	    (set-buffer (get-buffer-create " *Org tags*"))
  12252           (pop-to-buffer
  12253            (get-buffer-create " *Org tags*")
  12254            '(org-display-buffer-split (direction . down))))
  12255         ;; Fill text in *Org tags* buffer.
  12256 	(erase-buffer)
  12257 	(setq-local org-done-keywords done-keywords)
  12258         ;; Insert current tags.
  12259 	(org-fast-tag-insert "Inherited" inherited-tags inherited-face "\n")
  12260 	(org-fast-tag-insert "Current" current-tags current-face "\n\n")
  12261         ;; Display whether next change exits selection dialog.
  12262 	(org-fast-tag-show-exit exit-after-next)
  12263         ;; Show tags, tag groups, and bindings in a grid.
  12264         ;; Each tag in the grid occupies FIELD-WIDTH characters.
  12265         ;; The tags are filled up to `window-width'.
  12266 	(setq field-number 0)
  12267 	(while (setq tag-binding-spec (pop tag-alist))
  12268 	  (pcase tag-binding-spec
  12269             ;; Display tag groups on starting from a new line.
  12270 	    (`(:startgroup . ,group-name)
  12271 	     (push '() groups) (setq ingroup t)
  12272 	     (unless (zerop field-number)
  12273 	       (setq field-number 0)
  12274 	       (insert "\n"))
  12275 	     (insert (if group-name (format "%s: " group-name) "") "{ "))
  12276             ;; Tag group end is followed by newline.
  12277 	    (`(:endgroup . ,group-name)
  12278 	     (setq ingroup nil field-number 0)
  12279 	     (insert "}" (if group-name (format " (%s) " group-name) "") "\n"))
  12280             ;; Group tags start at newline.
  12281 	    (`(:startgrouptag)
  12282 	     (setq intaggroup t)
  12283 	     (unless (zerop field-number)
  12284 	       (setq field-number 0)
  12285 	       (insert "\n"))
  12286 	     (insert "[ "))
  12287             ;; Group tags end with a newline.
  12288 	    (`(:endgrouptag)
  12289 	     (setq intaggroup nil field-number 0)
  12290 	     (insert "]\n"))
  12291 	    (`(:newline)
  12292 	     (unless (zerop field-number)
  12293 	       (setq field-number 0)
  12294 	       (insert "\n")
  12295 	       (setq tag-binding-spec (car tag-alist))
  12296 	       (while (equal (car tag-alist) '(:newline))
  12297 		 (insert "\n")
  12298 		 (setq tag-alist (cdr tag-alist)))))
  12299 	    (`(:grouptags)
  12300              ;; Previous tag is the tag representing the following group.
  12301              ;; It was inserted as "[c] TAG " with spaces filling up
  12302              ;; to the field width. Replace the trailing spaces with
  12303              ;; " : ", keeping to total field width unchanged.
  12304              (delete-char -3)
  12305              (insert " : "))
  12306 	    (_
  12307 	     (setq current-tag (copy-sequence (car tag-binding-spec))) ; will be modified by side effect
  12308              ;; Compute tag binding.
  12309 	     (if (cdr tag-binding-spec)
  12310                  ;; Custom binding.
  12311 		 (setq current-tag-char (cdr tag-binding-spec))
  12312                ;; No auto-binding.  Update `tag-binding-chars-left'.
  12313                (unless (or ingroup intaggroup) ; groups are always displayed.
  12314                  (cl-decf tag-binding-chars-left))
  12315 	       ;; Automatically assign a character according to the tag string.
  12316 	       (setq auto-tag-char
  12317                      (string-to-char
  12318 		      (downcase (substring
  12319 				 current-tag (if (= (string-to-char current-tag) ?@) 1 0)))))
  12320 	       (if (or (rassoc auto-tag-char tag-table-local)
  12321                        (rassoc auto-tag-char tag-table))
  12322                    ;; Already bound.  Assign first unbound char instead.
  12323                    (progn
  12324 		     (while (and tag-binding-char-list
  12325                                  (or (rassoc (car tag-binding-char-list) tag-table-local)
  12326                                      (rassoc (car tag-binding-char-list) tag-table)))
  12327 		       (pop tag-binding-char-list))
  12328                      (setq current-tag-char (or (car tag-binding-char-list)
  12329                                                 ;; Fall back to display "[ ]".
  12330                                                 ?\s)))
  12331                  ;; Can safely use binding derived from the tag string.
  12332 		 (setq current-tag-char auto-tag-char)))
  12333              ;; Record all the tags in the group.  `:startgroup'
  12334              ;; clause earlier added '() to `groups'.
  12335              ;; `(car groups)' now contains the tag list for the
  12336              ;; current group.
  12337 	     (when ingroup (push current-tag (car groups)))
  12338              ;; Compute tag face.
  12339 	     (setq current-tag (org-add-props current-tag nil 'face
  12340 				              (cond
  12341 				               ((not (assoc current-tag tag-table))
  12342                                                 ;; The tag is from TODO-TABLE.
  12343 				                (org-get-todo-face current-tag))
  12344 				               ((member current-tag current-tags) current-face)
  12345 				               ((member current-tag inherited-tags) inherited-face))))
  12346 	     (when (equal (caar tag-alist) :grouptags)
  12347 	       (org-add-props current-tag nil 'face 'org-tag-group))
  12348              ;; Respect `org-fast-tag-selection-maximum-tags'.
  12349              (when (or ingroup intaggroup (cdr tag-binding-spec) (> tag-binding-chars-left 0))
  12350                ;; Insert the tag.
  12351 	       (when (and (zerop field-number) (not ingroup) (not intaggroup)) (insert "  "))
  12352 	       (insert "[" current-tag-char "] " current-tag
  12353                        ;; Fill spaces up to FIELD-WIDTH.
  12354                        (make-string
  12355 		        (- field-width 4 (length current-tag)) ?\ ))
  12356                ;; Record tag and the binding/auto-binding.
  12357 	       (push (cons current-tag current-tag-char) tag-table-local)
  12358                ;; Last column in the row.
  12359 	       (when (= (cl-incf field-number) (/ (- (window-width) 4) field-width))
  12360 	         (unless (memq (caar tag-alist) '(:endgroup :endgrouptag))
  12361 	           (insert "\n")
  12362 	           (when (or ingroup intaggroup) (insert "  ")))
  12363 	         (setq field-number 0))))))
  12364         (insert "\n")
  12365         ;; Keep the tags in order displayed.  Will be used later for sorting.
  12366         (setq tag-table-local (nreverse tag-table-local))
  12367         (goto-char (point-min))
  12368         (unless expert-interface (org-fit-window-to-buffer))
  12369         ;; Read user input.
  12370         (setq rtn
  12371 	      (catch 'exit
  12372 	        (while t
  12373 		  (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  12374 			   (if (not groups) "no " "")
  12375 			   (if expert-interface " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  12376 		  (setq input-char
  12377                         (let ((inhibit-quit t)) ; intercept C-g.
  12378                           (read-char-exclusive)))
  12379                   ;; FIXME: Global variable used by `org-beamer-select-environment'.
  12380                   ;; Should factor it out.
  12381 		  (setq org-last-tag-selection-key input-char)
  12382 		  (pcase input-char
  12383                     ;; <RET>
  12384                     (?\r (throw 'exit t))
  12385                     ;; Toggle tag groups.
  12386 		    (?!
  12387 		     (setq groups (not groups))
  12388 		     (goto-char (point-min))
  12389 		     (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  12390                     ;; Toggle expert interface.
  12391 		    (?\C-c
  12392 		     (if (not expert-interface)
  12393 		         (org-fast-tag-show-exit
  12394 		          (setq exit-after-next (not exit-after-next)))
  12395 		       (setq expert-interface nil)
  12396                        (pop-to-buffer
  12397                         " *Org tags*"
  12398                         '((org-display-buffer-split (direction down))))
  12399 		       (org-fit-window-to-buffer)))
  12400                     ;; Quit.
  12401 		    ((or ?\C-g
  12402 		         (and ?q (guard (not (rassoc input-char tag-table-local)))))
  12403 		     (delete-overlay org-tags-overlay)
  12404                      ;; Quit as C-g does.
  12405 		     (keyboard-quit))
  12406                     ;; Clear tags.
  12407 		    (?\s
  12408 		     (setq current-tags nil)
  12409 		     (when exit-after-next (setq exit-after-next 'now)))
  12410                     ;; Use normal completion.
  12411 		    (?\t
  12412                      ;; Compute completion table, unless already computed.
  12413                      (unless tab-tags
  12414                        (setq tab-tags
  12415                              (delq nil
  12416                                    (mapcar (lambda (x)
  12417                                              (let ((item (car-safe x)))
  12418                                                (and (stringp item)
  12419                                                     (list item))))
  12420                                            ;; Complete using all tags; tags from current buffer first.
  12421                                            (org--tag-add-to-alist
  12422                                             (with-current-buffer origin-buffer
  12423                                               (org-get-buffer-tags))
  12424                                             tag-table)))))
  12425                      (setq current-tag (completing-read "Tag: " tab-tags))
  12426 		     (when (string-match "\\S-" current-tag)
  12427 		       (cl-pushnew (list current-tag) tab-tags :test #'equal)
  12428                        (setq current-tags (org--add-or-remove-tag current-tag current-tags groups)))
  12429 		     (when exit-after-next (setq exit-after-next 'now)))
  12430                     ;; INPUT-CHAR is for a todo keyword.
  12431 		    ((let (and todo-keyword (guard todo-keyword))
  12432                        (car (rassoc input-char todo-table)))
  12433 		     (with-current-buffer origin-buffer
  12434 		       (save-excursion (org-todo todo-keyword)))
  12435 		     (when exit-after-next (setq exit-after-next 'now)))
  12436                     ;; INPUT-CHAR is for a tag.
  12437 		    ((let (and tag (guard tag))
  12438                        (car (rassoc input-char tag-table-local)))
  12439                      (setq current-tags (org--add-or-remove-tag tag current-tags groups))
  12440 		     (when exit-after-next (setq exit-after-next 'now))))
  12441 		  ;; Create a sorted tag list.
  12442 		  (setq current-tags
  12443 		        (sort current-tags
  12444 			      (lambda (a b)
  12445                                 ;; b is after a.
  12446                                 ;; `memq' returns tail of the list after the match + the match.
  12447 			        (assoc b (cdr (memq (assoc a tag-table-local) tag-table-local))))))
  12448                   ;; Exit when we are set to exit immediately.
  12449 		  (when (eq exit-after-next 'now) (throw 'exit t))
  12450                   ;; Continue setting tags in the loop.
  12451                   ;; Update the currently active tags indication in the completion buffer.
  12452 		  (goto-char (point-min))
  12453 		  (forward-line 1)
  12454                   (delete-region (point) (line-end-position))
  12455 		  (org-fast-tag-insert "Current" current-tags current-face)
  12456                   ;; Update the active tags displayed in the overlay in Org buffer.
  12457 		  (org-set-current-tags-overlay current-tags ov-prefix)
  12458                   ;; Update tag faces in the displayed tag grid.
  12459 		  (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  12460 		    (while (re-search-forward tag-re nil t)
  12461 		      (let ((tag (match-string 1)))
  12462 		        (add-text-properties
  12463 		         (match-beginning 1) (match-end 1)
  12464 		         (list 'face
  12465 			       (cond
  12466 			        ((member tag current-tags) current-face)
  12467 			        ((member tag inherited-tags) inherited-face)
  12468 			        (t 'default)))))))
  12469 		  (goto-char (point-min)))))
  12470         ;; Clear the tag overlay in Org buffer.
  12471         (delete-overlay org-tags-overlay)
  12472         ;; Return the new tag list.
  12473         (if rtn
  12474 	    (mapconcat 'identity current-tags ":")
  12475 	  nil)))))
  12476 
  12477 (defun org-make-tag-string (tags)
  12478   "Return string associated to TAGS.
  12479 TAGS is a list of strings."
  12480   (if (null tags) ""
  12481     (format ":%s:" (mapconcat #'identity tags ":"))))
  12482 
  12483 (defun org--get-local-tags (&optional epom)
  12484   "Return list of tags for headline at EPOM.
  12485 When EPOM is non-nil, it should be a marker, point, or element
  12486 representing headline."
  12487   ;; If we do not explicitly copy the result, reference would
  12488   ;; be returned and cache element might be modified directly.
  12489   (mapcar
  12490    #'copy-sequence
  12491    (org-element-property
  12492     :tags
  12493     (org-element-lineage
  12494      (org-element-at-point epom)
  12495      '(headline inlinetask)
  12496      'with-self))))
  12497 
  12498 (defun org-get-tags (&optional epom local)
  12499   "Get the list of tags specified in the headline at EPOM.
  12500 
  12501 When argument EPOM is non-nil, it should be point, marker, or headline
  12502 element.
  12503 
  12504 According to `org-use-tag-inheritance', tags may be inherited
  12505 from parent headlines, and from the whole document, through
  12506 `org-file-tags'.  In this case, the returned list of tags
  12507 contains tags in this order: file tags, tags inherited from
  12508 parent headlines, local tags.  If a tag appears multiple times,
  12509 only the most local tag is returned.
  12510 
  12511 However, when optional argument LOCAL is non-nil, only return
  12512 tags specified at the headline.
  12513 
  12514 Inherited tags have the `inherited' text property.
  12515 
  12516 This function may modify the match data."
  12517   (if (and org-trust-scanner-tags
  12518            (or (not epom) (eq epom (point)))
  12519            (not local))
  12520       org-scanner-tags
  12521     (setq epom (org-element-lineage
  12522                 (org-element-at-point epom)
  12523                 '(headline inlinetask)
  12524                 'with-self))
  12525     (let ((ltags (org--get-local-tags epom))
  12526           itags)
  12527       (if (or local (not org-use-tag-inheritance)) ltags
  12528         (setq
  12529          itags
  12530          (mapcar
  12531           #'org-add-prop-inherited
  12532           (org-element-property-inherited :tags epom nil 'acc)))
  12533         (setq itags (append org-file-tags itags))
  12534         (nreverse
  12535 	 (delete-dups
  12536 	  (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))
  12537 
  12538 (defun org-get-buffer-tags ()
  12539   "Get a table of all tags used in the buffer, for completion."
  12540   (let ((hashed (make-hash-table :test #'equal)))
  12541     (org-element-cache-map
  12542      (lambda (el)
  12543        (dolist (tag (org-element-property :tags el))
  12544          ;; Do not carry over the text properties.  They may look
  12545          ;; ugly in the completion.
  12546          (puthash (list (substring-no-properties tag)) t hashed))))
  12547     (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  12548     (hash-table-keys hashed)))
  12549 
  12550 ;;;; The mapping API
  12551 
  12552 (defvar org-agenda-skip-comment-trees)
  12553 (defvar org-agenda-skip-function)
  12554 (defun org-map-entries (func &optional match scope &rest skip)
  12555   "Call FUNC at each headline selected by MATCH in SCOPE.
  12556 
  12557 FUNC is a function or a Lisp form.  The function will be called without
  12558 arguments, with the cursor positioned at the beginning of the headline.
  12559 The return values of all calls to the function will be collected and
  12560 returned as a list.
  12561 
  12562 The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  12563 does not need to preserve point.  After evaluation, the cursor will be
  12564 moved to the end of the line (presumably of the headline of the
  12565 processed entry) and search continues from there.  Under some
  12566 circumstances, this may not produce the wanted results.  For example,
  12567 if you have removed (e.g. archived) the current (sub)tree it could
  12568 mean that the next entry will be skipped entirely.  In such cases, you
  12569 can specify the position from where search should continue by making
  12570 FUNC set the variable `org-map-continue-from' to the desired buffer
  12571 position.
  12572 
  12573 MATCH is a tags/property/todo match as it is used in the agenda tags view.
  12574 Only headlines that are matched by this query will be considered during
  12575 the iteration.  When MATCH is nil or t, all headlines will be
  12576 visited by the iteration.
  12577 
  12578 SCOPE determines the scope of this command.  It can be any of:
  12579 
  12580 nil     The current buffer, respecting the restriction if any
  12581 tree    The subtree started with the entry at point
  12582 region  The entries within the active region, if any
  12583 region-start-level
  12584         The entries within the active region, but only those at
  12585         the same level than the first one.
  12586 file    The current buffer, without restriction
  12587 file-with-archives
  12588         The current buffer, and any archives associated with it
  12589 agenda  All agenda files
  12590 agenda-with-archives
  12591         All agenda files with any archive files associated with them
  12592 \(file1 file2 ...)
  12593         If this is a list, all files in the list will be scanned
  12594 
  12595 The remaining args are treated as settings for the skipping facilities of
  12596 the scanner.  The following items can be given here:
  12597 
  12598   archive    skip trees with the archive tag
  12599   comment    skip trees with the COMMENT keyword
  12600   function or Emacs Lisp form:
  12601              will be used as value for `org-agenda-skip-function', so
  12602              whenever the function returns a position, FUNC will not be
  12603              called for that entry and search will continue from the
  12604              position returned
  12605 
  12606 If your function needs to retrieve the tags including inherited tags
  12607 at the *current* entry, you can use the value of the variable
  12608 `org-scanner-tags' which will be much faster than getting the value
  12609 with `org-get-tags'.  If your function gets properties with
  12610 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  12611 to t around the call to `org-entry-properties' to get the same speedup.
  12612 Note that if your function moves around to retrieve tags and properties at
  12613 a *different* entry, you cannot use these techniques."
  12614   (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  12615 	       (not (org-region-active-p)))
  12616     (let* ((org-agenda-archives-mode nil) ; just to make sure
  12617 	   (org-agenda-skip-archived-trees (memq 'archive skip))
  12618 	   (org-agenda-skip-comment-trees (memq 'comment skip))
  12619 	   (org-agenda-skip-function
  12620 	    (car (org-delete-all '(comment archive) skip)))
  12621 	   (org-tags-match-list-sublevels t)
  12622 	   (start-level (eq scope 'region-start-level))
  12623 	   matcher res
  12624 	   org-todo-keywords-for-agenda
  12625 	   org-done-keywords-for-agenda
  12626 	   org-todo-keyword-alist-for-agenda
  12627 	   org-tag-alist-for-agenda
  12628 	   org--matcher-tags-todo-only)
  12629 
  12630       (cond
  12631        ((eq match t)   (setq matcher t))
  12632        ((eq match nil) (setq matcher t))
  12633        (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  12634 
  12635       (save-excursion
  12636 	(save-restriction
  12637 	  (cond ((eq scope 'tree)
  12638 		 (org-back-to-heading t)
  12639 		 (org-narrow-to-subtree)
  12640 		 (setq scope nil))
  12641 		((and (or (eq scope 'region) (eq scope 'region-start-level))
  12642 		      (org-region-active-p))
  12643 		 ;; If needed, set start-level to a string like "2"
  12644 		 (when start-level
  12645 		   (save-excursion
  12646 		     (goto-char (region-beginning))
  12647 		     (unless (org-at-heading-p) (outline-next-heading))
  12648 		     (setq start-level (org-current-level))))
  12649 		 (narrow-to-region (region-beginning)
  12650 				   (save-excursion
  12651 				     (goto-char (region-end))
  12652 				     (unless (and (bolp) (org-at-heading-p))
  12653 				       (outline-next-heading))
  12654 				     (point)))
  12655 		 (setq scope nil)))
  12656 
  12657 	  (if (not scope)
  12658 	      (progn
  12659                 ;; Agenda expects a file buffer.  Skip over refreshing
  12660                 ;; agenda cache for non-file buffers.
  12661                 (when buffer-file-name
  12662 		  (org-agenda-prepare-buffers
  12663 		   (and buffer-file-name (list (current-buffer)))))
  12664 		(setq res
  12665 		      (org-scan-tags
  12666 		       func matcher org--matcher-tags-todo-only start-level)))
  12667 	    ;; Get the right scope
  12668 	    (cond
  12669 	     ((and scope (listp scope) (symbolp (car scope)))
  12670 	      (setq scope (eval scope t)))
  12671 	     ((eq scope 'agenda)
  12672 	      (setq scope (org-agenda-files t)))
  12673 	     ((eq scope 'agenda-with-archives)
  12674 	      (setq scope (org-agenda-files t))
  12675 	      (setq scope (org-add-archive-files scope)))
  12676 	     ((eq scope 'file)
  12677 	      (setq scope (and buffer-file-name (list buffer-file-name))))
  12678 	     ((eq scope 'file-with-archives)
  12679 	      (setq scope (org-add-archive-files (list (buffer-file-name))))))
  12680 	    (org-agenda-prepare-buffers scope)
  12681 	    (dolist (file scope)
  12682 	      (with-current-buffer (org-find-base-buffer-visiting file)
  12683 		(org-with-wide-buffer
  12684 		 (goto-char (point-min))
  12685 		 (setq res
  12686 		       (append
  12687 			res
  12688 			(org-scan-tags
  12689 			 func matcher org--matcher-tags-todo-only)))))))))
  12690       res)))
  12691 
  12692 ;;; Properties API
  12693 
  12694 (defconst org-special-properties
  12695   '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  12696     "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  12697   "The special properties valid in Org mode.
  12698 These are properties that are not defined in the property drawer,
  12699 but in some other way.")
  12700 
  12701 (defconst org-default-properties
  12702   '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  12703     "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  12704     "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  12705     "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  12706     "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  12707     "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  12708     "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS"
  12709     "ORG-IMAGE-ACTUAL-WIDTH")
  12710   "Some properties that are used by Org mode for various purposes.
  12711 Being in this list makes sure that they are offered for completion.")
  12712 
  12713 (defun org--valid-property-p (property)
  12714   "Non-nil when string PROPERTY is a valid property name."
  12715   (not
  12716    (or (equal property "")
  12717        (string-match-p "\\s-" property))))
  12718 
  12719 (defun org--update-property-plist (key val props)
  12720   "Associate KEY to VAL in alist PROPS.
  12721 Modifications are made by side-effect.  Return new alist."
  12722   (let* ((appending (string= (substring key -1) "+"))
  12723 	 (key (if appending (substring key 0 -1) key))
  12724 	 (old (assoc-string key props t)))
  12725     (if (not old) (cons (cons key val) props)
  12726       (setcdr old (if appending (concat (cdr old) " " val) val))
  12727       props)))
  12728 
  12729 (defun org-get-property-block (&optional beg force)
  12730   "Return the (beg . end) range of the body of the property drawer.
  12731 BEG is the beginning of the current subtree or the beginning of
  12732 the document if before the first headline.  If it is not given,
  12733 it will be found.  If the drawer does not exist, create it if
  12734 FORCE is non-nil, or return nil."
  12735   (org-with-wide-buffer
  12736    (let ((beg (cond (beg (goto-char beg))
  12737 		    ((or (not (featurep 'org-inlinetask))
  12738 			 (org-inlinetask-in-task-p))
  12739 		     (org-back-to-heading-or-point-min t) (point))
  12740 		    (t (org-with-limited-levels
  12741 			(org-back-to-heading-or-point-min t))
  12742 		       (point)))))
  12743      ;; Move point to its position according to its positional rules.
  12744      (cond ((org-before-first-heading-p)
  12745 	    (while (and (org-at-comment-p) (bolp)) (forward-line)))
  12746 	   (t (forward-line)
  12747 	      (when (looking-at-p org-planning-line-re) (forward-line))))
  12748      (cond ((looking-at org-property-drawer-re)
  12749 	    (forward-line)
  12750 	    (cons (point) (progn (goto-char (match-end 0))
  12751 				 (line-beginning-position))))
  12752 	   (force
  12753 	    (goto-char beg)
  12754 	    (org-insert-property-drawer)
  12755 	    (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  12756 				       (line-beginning-position))))
  12757 	      (cons pos pos)))))))
  12758 
  12759 (defun org-at-property-drawer-p ()
  12760   "Non-nil when point is at the first line of a property drawer."
  12761   (org-with-wide-buffer
  12762    (forward-line 0)
  12763    (and (looking-at org-property-drawer-re)
  12764 	(or (bobp)
  12765 	    (progn
  12766 	      (forward-line -1)
  12767 	      (cond ((org-at-heading-p))
  12768 		    ((looking-at org-planning-line-re)
  12769 		     (forward-line -1)
  12770 		     (org-at-heading-p))
  12771 		    ((looking-at org-comment-regexp)
  12772 		     (forward-line -1)
  12773 		     (while (and (not (bobp)) (looking-at org-comment-regexp))
  12774 		       (forward-line -1))
  12775 		     (looking-at org-comment-regexp))
  12776 		    (t nil)))))))
  12777 
  12778 (defun org-at-property-p ()
  12779   "Non-nil when point is inside a property drawer.
  12780 See `org-property-re' for match data, if applicable."
  12781   (save-excursion
  12782     (forward-line 0)
  12783     (and (looking-at org-property-re)
  12784 	 (let ((property-drawer (save-match-data (org-get-property-block))))
  12785 	   (and property-drawer
  12786 		(>= (point) (car property-drawer))
  12787 		(< (point) (cdr property-drawer)))))))
  12788 
  12789 (defun org-property-action ()
  12790   "Do an action on properties."
  12791   (interactive)
  12792   (message "Property Action:  [s]et  [d]elete  [D]elete globally  [c]ompute")
  12793   (let ((c (read-char-exclusive)))
  12794     (cl-case c
  12795       (?s (call-interactively #'org-set-property))
  12796       (?d (call-interactively #'org-delete-property))
  12797       (?D (call-interactively #'org-delete-property-globally))
  12798       (?c (call-interactively #'org-compute-property-at-point))
  12799       (otherwise (user-error "No such property action %c" c)))))
  12800 
  12801 (defun org-inc-effort ()
  12802   "Increment the value of the effort property in the current entry."
  12803   (interactive)
  12804   (org-set-effort t))
  12805 
  12806 (defvar org-clock-effort)       ; Defined in org-clock.el.
  12807 (defvar org-clock-current-task) ; Defined in org-clock.el.
  12808 (defun org-set-effort (&optional increment value)
  12809   "Set the effort property of the current entry.
  12810 If INCREMENT is non-nil, set the property to the next allowed
  12811 value.  Otherwise, if optional argument VALUE is provided, use
  12812 it.  Eventually, prompt for the new value if none of the previous
  12813 variables is set."
  12814   (interactive "P")
  12815   (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  12816 	 (current (org-entry-get nil org-effort-property))
  12817 	 (value
  12818 	  (cond
  12819 	   (increment
  12820 	    (unless allowed (user-error "Allowed effort values are not set"))
  12821 	    (or (cl-caadr (member (list current) allowed))
  12822 		(user-error "Unknown value %S among allowed values" current)))
  12823 	   (value
  12824 	    (if (stringp value) value
  12825 	      (error "Invalid effort value: %S" value)))
  12826 	   (t
  12827 	    (let ((must-match
  12828 		   (and allowed
  12829 			(not (get-text-property 0 'org-unrestricted
  12830 						(caar allowed))))))
  12831 	      (completing-read "Effort: " allowed nil must-match))))))
  12832     ;; Test whether the value can be interpreted as a duration before
  12833     ;; inserting it in the buffer:
  12834     (org-duration-to-minutes value)
  12835     ;; Maybe update the effort value:
  12836     (unless (equal current value)
  12837       (org-entry-put nil org-effort-property value))
  12838     (when (equal (org-get-heading t t t t)
  12839 		 (bound-and-true-p org-clock-current-task))
  12840       (setq org-clock-effort value)
  12841       (org-clock-update-mode-line))
  12842     (message "%s is now %s" org-effort-property value)))
  12843 
  12844 (defun org-entry-properties (&optional epom which)
  12845   "Get all properties of the current entry.
  12846 
  12847 When EPOM is a buffer position, marker, or element, get all properties
  12848 from the entry there instead.
  12849 
  12850 This includes the TODO keyword, the tags, time strings for
  12851 deadline, scheduled, and clocking, and any additional properties
  12852 defined in the entry.
  12853 
  12854 If WHICH is nil or `all', get all properties.  If WHICH is
  12855 `special' or `standard', only get that subclass.  If WHICH is
  12856 a string, only get that property.
  12857 
  12858 Return value is an alist.  Keys are properties, as upcased
  12859 strings."
  12860   (org-with-point-at epom
  12861     (when (and (derived-mode-p 'org-mode)
  12862 	       (org-back-to-heading-or-point-min t))
  12863       (catch 'exit
  12864 	(let* ((beg (point))
  12865 	       (specific (and (stringp which) (upcase which)))
  12866 	       (which (cond ((not specific) which)
  12867 			    ((member specific org-special-properties) 'special)
  12868 			    (t 'standard)))
  12869 	       props)
  12870 	  ;; Get the special properties, like TODO and TAGS.
  12871 	  (when (memq which '(nil all special))
  12872 	    (when (or (not specific) (string= specific "CLOCKSUM"))
  12873 	      (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  12874 		(when clocksum
  12875 		  (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  12876 			props)))
  12877 	      (when specific (throw 'exit props)))
  12878 	    (when (or (not specific) (string= specific "CLOCKSUM_T"))
  12879 	      (let ((clocksumt (get-text-property (point)
  12880 						  :org-clock-minutes-today)))
  12881 		(when clocksumt
  12882 		  (push (cons "CLOCKSUM_T"
  12883 			      (org-duration-from-minutes clocksumt))
  12884 			props)))
  12885 	      (when specific (throw 'exit props)))
  12886 	    (when (or (not specific) (string= specific "ITEM"))
  12887 	      (let ((case-fold-search nil))
  12888 		(when (looking-at org-complex-heading-regexp)
  12889 		  (push (cons "ITEM"
  12890 			      (let ((title (match-string-no-properties 4)))
  12891 				(if (org-string-nw-p title)
  12892 				    (org-remove-tabs title)
  12893 				  "")))
  12894 			props)))
  12895 	      (when specific (throw 'exit props)))
  12896 	    (when (or (not specific) (string= specific "TODO"))
  12897 	      (let ((case-fold-search nil))
  12898 		(when (and (looking-at org-todo-line-regexp) (match-end 2))
  12899 		  (push (cons "TODO" (match-string-no-properties 2)) props)))
  12900 	      (when specific (throw 'exit props)))
  12901 	    (when (or (not specific) (string= specific "PRIORITY"))
  12902 	      (push (cons "PRIORITY"
  12903 			  (if (looking-at org-priority-regexp)
  12904 			      (match-string-no-properties 2)
  12905 			    (char-to-string org-priority-default)))
  12906 		    props)
  12907 	      (when specific (throw 'exit props)))
  12908 	    (when (or (not specific) (string= specific "FILE"))
  12909 	      (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  12910 		    props)
  12911 	      (when specific (throw 'exit props)))
  12912 	    (when (or (not specific) (string= specific "TAGS"))
  12913 	      (let ((tags (org-get-tags nil t)))
  12914 		(when tags
  12915 		  (push (cons "TAGS" (org-make-tag-string tags))
  12916 			props)))
  12917 	      (when specific (throw 'exit props)))
  12918 	    (when (or (not specific) (string= specific "ALLTAGS"))
  12919 	      (let ((tags (org-get-tags)))
  12920 		(when tags
  12921 		  (push (cons "ALLTAGS" (org-make-tag-string tags))
  12922 			props)))
  12923 	      (when specific (throw 'exit props)))
  12924 	    (when (or (not specific) (string= specific "BLOCKED"))
  12925 	      (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  12926 	      (when specific (throw 'exit props)))
  12927 	    (when (or (not specific)
  12928 		      (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  12929 	      (forward-line)
  12930 	      (when (looking-at-p org-planning-line-re)
  12931 		(end-of-line)
  12932 		(let ((bol (line-beginning-position))
  12933 		      ;; Backward compatibility: time keywords used to
  12934 		      ;; be configurable (before 8.3).  Make sure we
  12935 		      ;; get the correct keyword.
  12936 		      (key-assoc `(("CLOSED" . ,org-closed-string)
  12937 				   ("DEADLINE" . ,org-deadline-string)
  12938 				   ("SCHEDULED" . ,org-scheduled-string))))
  12939 		  (dolist (pair (if specific (list (assoc specific key-assoc))
  12940 				  key-assoc))
  12941 		    (save-excursion
  12942 		      (when (search-backward (cdr pair) bol t)
  12943 			(goto-char (match-end 0))
  12944 			(skip-chars-forward " \t")
  12945 			(and (looking-at org-ts-regexp-both)
  12946 			     (push (cons (car pair)
  12947 					 (match-string-no-properties 0))
  12948 				   props)))))))
  12949 	      (when specific (throw 'exit props)))
  12950 	    (when (or (not specific)
  12951 		      (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  12952 	      (let ((find-ts
  12953 		     (lambda (end ts)
  12954 		       ;; Fix next timestamp before END.  TS is the
  12955 		       ;; list of timestamps found so far.
  12956 		       (let ((ts ts)
  12957 			     (regexp (cond
  12958 				      ((string= specific "TIMESTAMP")
  12959 				       org-ts-regexp)
  12960 				      ((string= specific "TIMESTAMP_IA")
  12961 				       org-ts-regexp-inactive)
  12962 				      ((assoc "TIMESTAMP_IA" ts)
  12963 				       org-ts-regexp)
  12964 				      ((assoc "TIMESTAMP" ts)
  12965 				       org-ts-regexp-inactive)
  12966 				      (t org-ts-regexp-both))))
  12967 			 (catch 'next
  12968 			   (while (re-search-forward regexp end t)
  12969 			     (backward-char)
  12970 			     (let ((object (org-element-context)))
  12971 			       ;; Accept to match timestamps in node
  12972 			       ;; properties, too.
  12973 			       (when (org-element-type-p
  12974                                       object '(node-property timestamp))
  12975 				 (let ((type
  12976 					(org-element-property :type object)))
  12977 				   (cond
  12978 				    ((and (memq type '(active active-range))
  12979 					  (not (equal specific "TIMESTAMP_IA")))
  12980 				     (unless (assoc "TIMESTAMP" ts)
  12981 				       (push (cons "TIMESTAMP"
  12982 						   (org-element-property
  12983 						    :raw-value object))
  12984 					     ts)
  12985 				       (when specific (throw 'exit ts))))
  12986 				    ((and (memq type '(inactive inactive-range))
  12987 					  (not (string= specific "TIMESTAMP")))
  12988 				     (unless (assoc "TIMESTAMP_IA" ts)
  12989 				       (push (cons "TIMESTAMP_IA"
  12990 						   (org-element-property
  12991 						    :raw-value object))
  12992 					     ts)
  12993 				       (when specific (throw 'exit ts))))))
  12994 				 ;; Both timestamp types are found,
  12995 				 ;; move to next part.
  12996 				 (when (= (length ts) 2) (throw 'next ts)))))
  12997 			   ts)))))
  12998 		(goto-char beg)
  12999 		;; First look for timestamps within headline.
  13000 		(let ((ts (funcall find-ts (line-end-position) nil)))
  13001 		  (if (= (length ts) 2) (setq props (nconc ts props))
  13002 		    ;; Then find timestamps in the section, skipping
  13003 		    ;; planning line.
  13004 		    (let ((end (save-excursion (outline-next-heading))))
  13005 		      (forward-line)
  13006 		      (when (looking-at-p org-planning-line-re) (forward-line))
  13007 		      (setq props (nconc (funcall find-ts end ts) props))))))))
  13008 	  ;; Get the standard properties, like :PROP:.
  13009 	  (when (memq which '(nil all standard))
  13010 	    ;; If we are looking after a specific property, delegate
  13011 	    ;; to `org-entry-get', which is faster.  However, make an
  13012 	    ;; exception for "CATEGORY", since it can be also set
  13013 	    ;; through keywords (i.e. #+CATEGORY).
  13014 	    (if (and specific (not (equal specific "CATEGORY")))
  13015 		(let ((value (org-entry-get beg specific nil t)))
  13016 		  (throw 'exit (and value (list (cons specific value)))))
  13017 	      (let ((range (org-get-property-block beg)))
  13018 		(when range
  13019 		  (let ((end (cdr range)) seen-base)
  13020 		    (goto-char (car range))
  13021 		    ;; Unlike to `org--update-property-plist', we
  13022 		    ;; handle the case where base values is found
  13023 		    ;; after its extension.  We also forbid standard
  13024 		    ;; properties to be named as special properties.
  13025 		    (while (re-search-forward org-property-re end t)
  13026 		      (let* ((key (upcase (match-string-no-properties 2)))
  13027 			     (extendp (string-match-p "\\+\\'" key))
  13028 			     (key-base (if extendp (substring key 0 -1) key))
  13029 			     (value (match-string-no-properties 3)))
  13030 			(cond
  13031 			 ((member-ignore-case key-base org-special-properties))
  13032 			 (extendp
  13033 			  (setq props
  13034 				(org--update-property-plist key value props)))
  13035 			 ((member key seen-base))
  13036 			 (t (push key seen-base)
  13037 			    (let ((p (assoc-string key props t)))
  13038 			      (if p (setcdr p (concat value " " (cdr p)))
  13039 				(push (cons key value) props))))))))))))
  13040 	  (unless (assoc "CATEGORY" props)
  13041 	    (push (cons "CATEGORY" (org-get-category beg)) props)
  13042 	    (when (string= specific "CATEGORY") (throw 'exit props)))
  13043 	  ;; Return value.
  13044 	  props)))))
  13045 
  13046 (defun org--property-local-values (property literal-nil &optional epom)
  13047   "Return value for PROPERTY in current entry or at EPOM.
  13048 EPOM can be point, marker, or syntax node.
  13049 
  13050 Value is a list whose car is the base value for PROPERTY and cdr
  13051 a list of accumulated values.  Return nil if neither is found in
  13052 the entry.  Also return nil when PROPERTY is set to \"nil\",
  13053 unless LITERAL-NIL is non-nil."
  13054   (setq epom
  13055         (org-element-lineage
  13056          (org-element-at-point epom)
  13057          '(headline inlinetask org-data)
  13058          'with-self))
  13059   (let* ((base-value  (org-element-property (intern (concat ":" (upcase property)    )) epom))
  13060          (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) epom))
  13061          (extra-value (if (listp extra-value) extra-value (list extra-value)))
  13062          (value (if literal-nil (cons base-value extra-value)
  13063                   (cons (org-not-nil base-value) (org-not-nil extra-value)))))
  13064     (and (not (equal value '(nil))) value)))
  13065 
  13066 (defun org--property-global-or-keyword-value (property literal-nil)
  13067   "Return value for PROPERTY as defined by global properties or by keyword.
  13068 Return value is a string.  Return nil if property is not set
  13069 globally or by keyword.  Also return nil when PROPERTY is set to
  13070 \"nil\", unless LITERAL-NIL is non-nil."
  13071   (let ((global
  13072 	 (cdr (or (assoc-string property org-keyword-properties t)
  13073 		  (assoc-string property org-global-properties t)
  13074 		  (assoc-string property org-global-properties-fixed t)))))
  13075     (if literal-nil global (org-not-nil global))))
  13076 
  13077 (defun org-entry-get (epom property &optional inherit literal-nil)
  13078   "Get value of PROPERTY for entry or content at EPOM.
  13079 
  13080 EPOM is an element, marker, or buffer position.
  13081 
  13082 If INHERIT is non-nil and the entry does not have the property,
  13083 then also check higher levels of the hierarchy.  If INHERIT is
  13084 the symbol `selective', use inheritance only if the setting in
  13085 `org-use-property-inheritance' selects PROPERTY for inheritance.
  13086 
  13087 If the property is present but empty, the return value is the
  13088 empty string.  If the property is not present at all, nil is
  13089 returned.  In any other case, return the value as a string.
  13090 Search is case-insensitive.
  13091 
  13092 If LITERAL-NIL is set, return the string value \"nil\" as
  13093 a string, do not interpret it as the list atom nil.  This is used
  13094 for inheritance when a \"nil\" value can supersede a non-nil
  13095 value higher up the hierarchy."
  13096   (cond
  13097    ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13098     ;; We need a special property.  Use `org-entry-properties' to
  13099     ;; retrieve it, but specify the wanted property.
  13100     (cdr (assoc-string property (org-entry-properties epom property))))
  13101    ((and inherit
  13102 	 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13103     (org-entry-get-with-inheritance property literal-nil epom))
  13104    (t
  13105     (let* ((local (org--property-local-values property literal-nil epom))
  13106 	   (value (and local (mapconcat #'identity
  13107                                         (delq nil local)
  13108                                         (org--property-get-separator property)))))
  13109       (if literal-nil value (org-not-nil value))))))
  13110 
  13111 (defun org-property-or-variable-value (var &optional inherit)
  13112   "Check if there is a property fixing the value of VAR.
  13113 If yes, return this value.  If not, return the current value of the variable."
  13114   (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13115     (if (and prop (stringp prop) (string-match "\\S-" prop))
  13116 	(read prop)
  13117       (symbol-value var))))
  13118 
  13119 (defun org-entry-delete (epom property)
  13120   "Delete PROPERTY from entry at element, point, or marker EPOM.
  13121 Accumulated properties, i.e. PROPERTY+, are also removed.  Return
  13122 non-nil when a property was removed."
  13123   (org-with-point-at epom
  13124     (pcase (org-get-property-block)
  13125       (`(,begin . ,origin)
  13126        (let* ((end (copy-marker origin))
  13127 	      (re (org-re-property
  13128 		   (concat (regexp-quote property) "\\+?") t t)))
  13129 	 (goto-char begin)
  13130 	 (while (re-search-forward re end t)
  13131 	   (delete-region (match-beginning 0) (line-beginning-position 2)))
  13132 	 ;; If drawer is empty, remove it altogether.
  13133 	 (when (= begin end)
  13134 	   (delete-region (line-beginning-position 0)
  13135 			  (line-beginning-position 2)))
  13136 	 ;; Return non-nil if some property was removed.
  13137 	 (prog1 (/= end origin) (set-marker end nil))))
  13138       (_ nil))))
  13139 
  13140 ;; Multi-values properties are properties that contain multiple values
  13141 ;; These values are assumed to be single words, separated by whitespace.
  13142 (defun org-entry-add-to-multivalued-property (epom property value)
  13143   "Add VALUE to the words in the PROPERTY in entry at EPOM.
  13144 EPOM is an element, marker, or buffer position."
  13145   (let* ((old (org-entry-get epom property))
  13146 	 (values (and old (split-string old))))
  13147     (setq value (org-entry-protect-space value))
  13148     (unless (member value values)
  13149       (setq values (append values (list value)))
  13150       (org-entry-put epom property (mapconcat #'identity values " ")))))
  13151 
  13152 (defun org-entry-remove-from-multivalued-property (epom property value)
  13153   "Remove VALUE from words in the PROPERTY in entry at EPOM.
  13154 EPOM is an element, marker, or buffer position."
  13155   (let* ((old (org-entry-get epom property))
  13156 	 (values (and old (split-string old))))
  13157     (setq value (org-entry-protect-space value))
  13158     (when (member value values)
  13159       (setq values (delete value values))
  13160       (org-entry-put epom property (mapconcat #'identity values " ")))))
  13161 
  13162 (defun org-entry-member-in-multivalued-property (epom property value)
  13163   "Is VALUE one of the words in the PROPERTY in EPOM?
  13164 EPOM is an element, marker, or buffer position."
  13165   (let* ((old (org-entry-get epom property))
  13166 	 (values (and old (split-string old))))
  13167     (setq value (org-entry-protect-space value))
  13168     (member value values)))
  13169 
  13170 (defun org-entry-get-multivalued-property (pom property)
  13171   "Return a list of values in a multivalued property."
  13172   (let* ((value (org-entry-get pom property))
  13173 	 (values (and value (split-string value))))
  13174     (mapcar #'org-entry-restore-space values)))
  13175 
  13176 (defun org-entry-put-multivalued-property (epom property &rest values)
  13177   "Set multivalued PROPERTY at EPOM to VALUES.
  13178 VALUES should be a list of strings.  Spaces will be protected.
  13179 EPOM is an element, marker, or buffer position."
  13180   (org-entry-put epom property (mapconcat #'org-entry-protect-space values " "))
  13181   (let* ((value (org-entry-get epom property))
  13182 	 (values (and value (split-string value))))
  13183     (mapcar #'org-entry-restore-space values)))
  13184 
  13185 (defun org-entry-protect-space (s)
  13186   "Protect spaces and newline in string S."
  13187   (while (string-match " " s)
  13188     (setq s (replace-match "%20" t t s)))
  13189   (while (string-match "\n" s)
  13190     (setq s (replace-match "%0A" t t s)))
  13191   s)
  13192 
  13193 (defun org-entry-restore-space (s)
  13194   "Restore spaces and newline in string S."
  13195   (while (string-match "%20" s)
  13196     (setq s (replace-match " " t t s)))
  13197   (while (string-match "%0A" s)
  13198     (setq s (replace-match "\n" t t s)))
  13199   s)
  13200 
  13201 (defvar org-entry-property-inherited-from (make-marker)
  13202   "Marker pointing to the entry from where a property was inherited.
  13203 Each call to `org-entry-get-with-inheritance' will set this marker to the
  13204 location of the entry where the inheritance search matched.  If there was
  13205 no match, the marker will point nowhere.
  13206 Note that also `org-entry-get' calls this function, if the INHERIT flag
  13207 is set.")
  13208 
  13209 (defun org-entry-get-with-inheritance (property &optional literal-nil epom)
  13210   "Get PROPERTY of entry or content at EPOM, search higher levels if needed.
  13211 EPOM can be a point, marker, or syntax node.
  13212 The search will stop at the first ancestor which has the property defined.
  13213 If the value found is \"nil\", return nil to show that the property
  13214 should be considered as undefined (this is the meaning of nil here).
  13215 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13216   (move-marker org-entry-property-inherited-from nil)
  13217   (let (values found-inherited?)
  13218     (org-element-lineage-map
  13219         (org-element-at-point epom)
  13220         (lambda (el)
  13221           (pcase-let ((`(,val . ,val+)
  13222                        ;; Force LITERAL-NIL t.
  13223                        (org--property-local-values property t el)))
  13224             (if (not val)
  13225                 ;; PROPERTY+
  13226                 (prog1 nil ; keep looking for PROPERTY
  13227                   (when val+ (setq values (nconc (delq nil val+) values))))
  13228               (setq values (cons val (nconc (delq nil val+) values)))
  13229               (move-marker
  13230                org-entry-property-inherited-from
  13231                (org-element-begin el)
  13232                (org-element-property :buffer el))
  13233               ;; Found inherited direct PROPERTY.
  13234               (setq found-inherited? t))))
  13235       '(inlinetask headline org-data)
  13236       'with-self 'first-match)
  13237     ;; Consider global properties, if we found no PROPERTY (or maybe
  13238     ;; only PROPERTY+).
  13239     (unless found-inherited?
  13240       (when-let* ((global (org--property-global-or-keyword-value
  13241                            property t)))
  13242         (setq values (cons global values))))
  13243     (when values
  13244       (setq values (mapconcat
  13245                     #'identity values
  13246                     (org--property-get-separator property))))
  13247     (if literal-nil values (org-not-nil values))))
  13248 
  13249 (defvar org-property-changed-functions nil
  13250   "Hook called when the value of a property has changed.
  13251 Each hook function should accept two arguments, the name of the property
  13252 and the new value.")
  13253 
  13254 (defun org-entry-put (epom property value)
  13255   "Set PROPERTY to VALUE for entry at EPOM.
  13256 
  13257 EPOM is an element, marker, or buffer position.
  13258 
  13259 If the value is nil, it is converted to the empty string.  If it
  13260 is not a string, an error is raised.  Also raise an error on
  13261 invalid property names.
  13262 
  13263 PROPERTY can be any regular property (see
  13264 `org-special-properties').  It can also be \"TODO\",
  13265 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13266 
  13267 For the last two properties, VALUE may have any of the special
  13268 values \"earlier\" and \"later\".  The function then increases or
  13269 decreases scheduled or deadline date by one day."
  13270   (cond ((null value) (setq value ""))
  13271 	((not (stringp value)) (error "Properties values should be strings"))
  13272 	((not (org--valid-property-p property))
  13273 	 (user-error "Invalid property name: \"%s\"" property)))
  13274   (org-no-read-only
  13275    (org-with-point-at epom
  13276      (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13277 	 (org-back-to-heading-or-point-min t)
  13278        (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  13279      (let ((beg (point)))
  13280        (cond
  13281         ((equal property "TODO")
  13282 	 (cond ((not (org-string-nw-p value)) (setq value 'none))
  13283 	       ((not (member value org-todo-keywords-1))
  13284 	        (user-error "\"%s\" is not a valid TODO state" value)))
  13285 	 (org-todo value)
  13286 	 (when org-auto-align-tags (org-align-tags)))
  13287         ((equal property "PRIORITY")
  13288 	 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13289 	 (when org-auto-align-tags (org-align-tags)))
  13290         ((equal property "SCHEDULED")
  13291 	 (forward-line)
  13292 	 (if (and (looking-at-p org-planning-line-re)
  13293 		  (re-search-forward
  13294 		   org-scheduled-time-regexp (line-end-position) t))
  13295 	     (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13296 		   ((string= value "later") (org-timestamp-change 1 'day))
  13297 		   ((string= value "") (org-schedule '(4)))
  13298 		   (t (org-schedule nil value)))
  13299 	   (if (member value '("earlier" "later" ""))
  13300 	       (call-interactively #'org-schedule)
  13301 	     (org-schedule nil value))))
  13302         ((equal property "DEADLINE")
  13303 	 (forward-line)
  13304 	 (if (and (looking-at-p org-planning-line-re)
  13305 		  (re-search-forward
  13306 		   org-deadline-time-regexp (line-end-position) t))
  13307 	     (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13308 		   ((string= value "later") (org-timestamp-change 1 'day))
  13309 		   ((string= value "") (org-deadline '(4)))
  13310 		   (t (org-deadline nil value)))
  13311 	   (if (member value '("earlier" "later" ""))
  13312 	       (call-interactively #'org-deadline)
  13313 	     (org-deadline nil value))))
  13314         ((member property org-special-properties)
  13315 	 (error "The %s property cannot be set with `org-entry-put'" property))
  13316         (t
  13317          (org-fold-core-ignore-modifications
  13318 	   (let* ((range (org-get-property-block beg 'force))
  13319 	          (end (cdr range))
  13320 	          (case-fold-search t))
  13321 	     (goto-char (car range))
  13322 	     (if (re-search-forward (org-re-property property nil t) end t)
  13323 	         (progn (delete-region (match-beginning 0) (match-end 0))
  13324 		        (goto-char (match-beginning 0)))
  13325 	       (goto-char end)
  13326 	       (insert-and-inherit "\n")
  13327 	       (backward-char))
  13328 	     (insert-and-inherit ":" property ":")
  13329 	     (when value (insert-and-inherit " " value))
  13330 	     (org-indent-line))))))
  13331      (run-hook-with-args 'org-property-changed-functions property value))))
  13332 
  13333 (defun org-buffer-property-keys (&optional specials defaults columns)
  13334   "Get all property keys in the current buffer.
  13335 
  13336 When SPECIALS is non-nil, also list the special properties that
  13337 reflect things like tags and TODO state.
  13338 
  13339 When DEFAULTS is non-nil, also include properties that has
  13340 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  13341 DESCRIPTION, LOCATION, and LOGGING and others.
  13342 
  13343 When COLUMNS in non-nil, also include property names given in
  13344 COLUMN formats in the current buffer."
  13345   (let ((case-fold-search t)
  13346 	(props (append
  13347 		(and specials org-special-properties)
  13348 		(and defaults (cons org-effort-property org-default-properties))
  13349 		;; Get property names from #+PROPERTY keywords as well
  13350 		(mapcar (lambda (s)
  13351 			  (nth 0 (split-string s)))
  13352 			(cdar (org-collect-keywords '("PROPERTY")))))))
  13353     (org-with-wide-buffer
  13354      (goto-char (point-min))
  13355      (while (re-search-forward org-property-start-re nil t)
  13356        (catch :skip
  13357 	 (let ((range (org-get-property-block)))
  13358 	   (unless range (throw :skip nil))
  13359 	   (goto-char (car range))
  13360 	   (let ((begin (car range))
  13361 		 (end (cdr range)))
  13362 	     ;; Make sure that found property block is not located
  13363 	     ;; before current point, as it would generate an infloop.
  13364 	     ;; It can happen, for example, in the following
  13365 	     ;; situation:
  13366 	     ;;
  13367 	     ;; * Headline
  13368 	     ;;   :PROPERTIES:
  13369 	     ;;   ...
  13370 	     ;;   :END:
  13371 	     ;; *************** Inlinetask
  13372 	     ;; #+BEGIN_EXAMPLE
  13373 	     ;; :PROPERTIES:
  13374 	     ;; #+END_EXAMPLE
  13375 	     ;;
  13376 	     (if (< begin (point)) (throw :skip nil) (goto-char begin))
  13377 	     (while (< (point) end)
  13378 	       (let ((p (progn (looking-at org-property-re)
  13379 			       (match-string-no-properties 2))))
  13380 		 ;; Only add true property name, not extension symbol.
  13381 		 (push (if (not (string-match-p "\\+\\'" p)) p
  13382 			 (substring p 0 -1))
  13383 		       props))
  13384 	       (forward-line))))
  13385 	 (outline-next-heading)))
  13386      (when columns
  13387        (goto-char (point-min))
  13388        (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  13389 	 (let ((element (org-element-at-point)))
  13390 	   (when (org-element-type-p element '(keyword node-property))
  13391 	     (let ((value (org-element-property :value element))
  13392 		   (start 0))
  13393 	       (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  13394 \\(?:{[^}]+}\\)?"
  13395 				    value start)
  13396 		 (setq start (match-end 0))
  13397 		 (let ((p (match-string-no-properties 1 value)))
  13398 		   (unless (member-ignore-case p org-special-properties)
  13399 		     (push p props))))))))))
  13400     (sort (delete-dups
  13401 	   (append props
  13402 		   ;; for each xxx_ALL property, make sure the bare
  13403 		   ;; xxx property is also included
  13404 		   (delq nil (mapcar (lambda (p)
  13405 				     (and (string-match-p "._ALL\\'" p)
  13406 					  (substring p 0 -4)))
  13407 				   props))))
  13408 	  (lambda (a b) (string< (upcase a) (upcase b))))))
  13409 
  13410 (defun org-property-values (key)
  13411   "List all non-nil values of property KEY in current buffer."
  13412   (org-with-wide-buffer
  13413    (goto-char (point-min))
  13414    (let ((case-fold-search t)
  13415 	 (re (org-re-property key))
  13416 	 values)
  13417      (while (re-search-forward re nil t)
  13418        (push (org-entry-get (point) key) values))
  13419      (delete-dups values))))
  13420 
  13421 (defun org-insert-property-drawer ()
  13422   "Insert a property drawer into the current entry.
  13423 Do nothing if the drawer already exists.  The newly created
  13424 drawer is immediately hidden."
  13425   (org-with-wide-buffer
  13426    ;; Set point to the position where the drawer should be inserted.
  13427    (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13428        (org-back-to-heading-or-point-min t)
  13429      (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  13430    (if (org-before-first-heading-p)
  13431        (while (and (org-at-comment-p) (bolp)) (forward-line))
  13432      (forward-line)
  13433      (when (looking-at-p org-planning-line-re) (forward-line)))
  13434    (unless (looking-at-p org-property-drawer-re)
  13435      ;; Make sure we start editing a line from current entry, not from
  13436      ;; next one.  It prevents extending text properties or overlays
  13437      ;; belonging to the latter.
  13438      (when (and (bolp) (> (point) (point-min))) (backward-char))
  13439      (let ((begin (if (bobp) (point) (1+ (point))))
  13440 	   (inhibit-read-only t))
  13441        (unless (bobp) (insert "\n"))
  13442        (insert ":PROPERTIES:\n:END:")
  13443        (org-fold-region (line-end-position 0) (point) t 'drawer)
  13444        (when (or (eobp) (= begin (point-min))) (insert "\n"))
  13445        (org-indent-region begin (point))))))
  13446 
  13447 (defun org-insert-drawer (&optional arg drawer)
  13448   "Insert a drawer at point.
  13449 
  13450 When optional argument ARG is non-nil, insert a property drawer.
  13451 
  13452 Optional argument DRAWER, when non-nil, is a string representing
  13453 drawer's name.  Otherwise, the user is prompted for a name.
  13454 
  13455 If a region is active, insert the drawer around that region
  13456 instead.
  13457 
  13458 Point is left between drawer's boundaries."
  13459   (interactive "P")
  13460   (let* ((drawer (if arg "PROPERTIES"
  13461 		   (or drawer (read-from-minibuffer "Drawer: ")))))
  13462     (cond
  13463      ;; With C-u, fall back on `org-insert-property-drawer'
  13464      (arg
  13465       (org-insert-property-drawer)
  13466       (org-back-to-heading-or-point-min t)
  13467       ;; Move inside.
  13468       (re-search-forward org-property-end-re)
  13469       (forward-line 0)
  13470       (unless (org-element-contents-begin (org-element-at-point))
  13471         ;; Empty drawer.
  13472         (insert "\n")
  13473         (forward-char -1))
  13474       (org-reveal))
  13475      ;; Check validity of suggested drawer's name.
  13476      ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  13477       (user-error "Invalid drawer name"))
  13478      ;; With an active region, insert a drawer at point.
  13479      ((not (org-region-active-p))
  13480       (progn
  13481 	(unless (bolp) (insert "\n"))
  13482 	(insert (format ":%s:\n\n:END:\n" drawer))
  13483 	(forward-line -2)))
  13484      ;; Otherwise, insert the drawer at point
  13485      (t
  13486       (let ((rbeg (region-beginning))
  13487 	    (rend (copy-marker (region-end))))
  13488 	(unwind-protect
  13489 	    (progn
  13490 	      (goto-char rbeg)
  13491 	      (forward-line 0)
  13492 	      (when (save-excursion
  13493 		      (re-search-forward org-outline-regexp-bol rend t))
  13494 		(user-error "Drawers cannot contain headlines"))
  13495 	      ;; Position point at the beginning of the first
  13496 	      ;; non-blank line in region.  Insert drawer's opening
  13497 	      ;; there, then indent it.
  13498 	      (org-skip-whitespace)
  13499 	      (forward-line 0)
  13500 	      (insert ":" drawer ":\n")
  13501 	      (forward-line -1)
  13502 	      (indent-for-tab-command)
  13503 	      ;; Move point to the beginning of the first blank line
  13504 	      ;; after the last non-blank line in region.  Insert
  13505 	      ;; drawer's closing, then indent it.
  13506 	      (goto-char rend)
  13507 	      (skip-chars-backward " \r\t\n")
  13508 	      (insert "\n:END:")
  13509 	      (deactivate-mark t)
  13510 	      (indent-for-tab-command)
  13511 	      (unless (eolp) (insert "\n"))
  13512               ;; Leave point inside drawer boundaries.
  13513               (search-backward ":END:")
  13514               (forward-char -1))
  13515 	  ;; Clear marker, whatever the outcome of insertion is.
  13516 	  (set-marker rend nil)))))))
  13517 
  13518 (defvar org-property-set-functions-alist nil
  13519   "Property set function alist.
  13520 Each entry should have the following format:
  13521 
  13522  (PROPERTY . READ-FUNCTION)
  13523 
  13524 The read function will be called with the same argument as
  13525 `org-completing-read'.")
  13526 
  13527 (defun org-set-property-function (property)
  13528   "Get the function that should be used to set PROPERTY.
  13529 This is computed according to `org-property-set-functions-alist'."
  13530   (or (cdr (assoc property org-property-set-functions-alist))
  13531       'org-completing-read))
  13532 
  13533 (defun org-read-property-value (property &optional epom default)
  13534   "Read value for PROPERTY, as a string.
  13535 When optional argument EPOM is non-nil, completion uses additional
  13536 information, i.e., allowed or existing values at element, point, or
  13537 marker EPOM.
  13538 Optional argument DEFAULT provides a default value for PROPERTY."
  13539   (let* ((completion-ignore-case t)
  13540 	 (allowed
  13541 	  (or (org-property-get-allowed-values nil property 'table)
  13542 	      (and epom (org-property-get-allowed-values epom property 'table))))
  13543 	 (current (org-entry-get nil property))
  13544 	 (prompt (format "%s value%s: "
  13545 			 property
  13546 			 (if (org-string-nw-p current)
  13547 			     (format " [%s]" current)
  13548 			   "")))
  13549 	 (set-function (org-set-property-function property))
  13550          (default (cond
  13551                    ((not allowed) default)
  13552                    ((member default allowed) default)
  13553                    (t nil))))
  13554     (org-trim
  13555      (if allowed
  13556 	 (funcall set-function
  13557 		  prompt allowed nil
  13558 		  (not (get-text-property 0 'org-unrestricted (caar allowed)))
  13559 		  default nil default)
  13560        (let ((all (mapcar #'list
  13561 			  (append (org-property-values property)
  13562 				  (and epom
  13563 				       (org-with-point-at epom
  13564 					 (org-property-values property)))))))
  13565 	 (funcall set-function prompt all nil nil default nil current))))))
  13566 
  13567 (defvar org-last-set-property nil)
  13568 (defvar org-last-set-property-value nil)
  13569 (defun org-read-property-name ()
  13570   "Read a property name."
  13571   (let ((completion-ignore-case t)
  13572 	(default-prop (or (and (org-at-property-p)
  13573 			       (match-string-no-properties 2))
  13574 			  org-last-set-property)))
  13575     (org-completing-read
  13576      (concat "Property"
  13577 	     (if default-prop (concat " [" default-prop "]") "")
  13578 	     ": ")
  13579      (mapcar #'list (org-buffer-property-keys nil t t))
  13580      nil nil nil nil default-prop)))
  13581 
  13582 (defun org-set-property-and-value (use-last)
  13583   "Allow setting [PROPERTY]: [value] direction from prompt.
  13584 When use-default, don't even ask, just use the last
  13585 \"[PROPERTY]: [value]\" string from the history."
  13586   (interactive "P")
  13587   (let* ((completion-ignore-case t)
  13588 	 (pv (or (and use-last org-last-set-property-value)
  13589 		 (org-completing-read
  13590 		  "Enter a \"[Property]: [value]\" pair: "
  13591 		  nil nil nil nil nil
  13592 		  org-last-set-property-value)))
  13593 	 prop val)
  13594     (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  13595       (setq prop (match-string 1 pv)
  13596 	    val (match-string 2 pv))
  13597       (org-set-property prop val))))
  13598 
  13599 (defun org-set-property (property value)
  13600   "In the current entry, set PROPERTY to VALUE.
  13601 
  13602 When called interactively, this will prompt for a property name, offering
  13603 completion on existing and default properties.  And then it will prompt
  13604 for a value, offering completion either on allowed values (via an inherited
  13605 xxx_ALL property) or on existing values in other instances of this property
  13606 in the current file.
  13607 
  13608 Throw an error when trying to set a property with an invalid name."
  13609   (interactive (list nil nil))
  13610   (let ((property (or property (org-read-property-name))))
  13611     ;; `org-entry-put' also makes the following check, but this one
  13612     ;; avoids polluting `org-last-set-property' and
  13613     ;; `org-last-set-property-value' needlessly.
  13614     (unless (org--valid-property-p property)
  13615       (user-error "Invalid property name: \"%s\"" property))
  13616     (let ((value (or value (org-read-property-value property)))
  13617 	  (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  13618       (setq org-last-set-property property)
  13619       (setq org-last-set-property-value (concat property ": " value))
  13620       ;; Possibly postprocess the inserted value:
  13621       (when fn (setq value (funcall fn value)))
  13622       (unless (equal (org-entry-get nil property) value)
  13623 	(org-entry-put nil property value)))))
  13624 
  13625 (defun org-find-property (property &optional value)
  13626   "Find first entry in buffer that sets PROPERTY.
  13627 
  13628 When optional argument VALUE is non-nil, only consider an entry
  13629 if it contains PROPERTY set to this value.  If PROPERTY should be
  13630 explicitly set to nil, use string \"nil\" for VALUE.
  13631 
  13632 Return position where the entry begins, or nil if there is no
  13633 such entry.  If narrowing is in effect, only search the visible
  13634 part of the buffer."
  13635   (save-excursion
  13636     (goto-char (point-min))
  13637     (let ((case-fold-search t)
  13638 	  (re (org-re-property property nil (not value) value)))
  13639       (catch 'exit
  13640 	(while (re-search-forward re nil t)
  13641 	  (when (if value (org-at-property-p)
  13642 		  (org-entry-get (point) property nil t))
  13643 	    (throw 'exit (progn (org-back-to-heading-or-point-min t)
  13644 				(point)))))))))
  13645 
  13646 (defun org-delete-property (property)
  13647   "In the current entry, delete PROPERTY."
  13648   (interactive
  13649    (let* ((completion-ignore-case t)
  13650 	  (cat (org-entry-get (point) "CATEGORY"))
  13651 	  (props0 (org-entry-properties nil 'standard))
  13652 	  (props (if cat props0
  13653 		   (delete `("CATEGORY" . ,(org-get-category)) props0)))
  13654 	  (prop (if (< 1 (length props))
  13655 		    (completing-read "Property: " props nil t)
  13656 		  (caar props))))
  13657      (list prop)))
  13658   (if (not property)
  13659       (message "No property to delete in this entry")
  13660     (org-entry-delete nil property)
  13661     (message "Property \"%s\" deleted" property)))
  13662 
  13663 (defun org-delete-property-globally (property)
  13664   "Remove PROPERTY globally, from all entries.
  13665 This function ignores narrowing, if any."
  13666   (interactive
  13667    (let* ((completion-ignore-case t)
  13668 	  (prop (completing-read
  13669 		 "Globally remove property: "
  13670 		 (mapcar #'list (org-buffer-property-keys)))))
  13671      (list prop)))
  13672   (org-with-wide-buffer
  13673    (goto-char (point-min))
  13674    (let ((count 0)
  13675 	 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  13676      (while (re-search-forward re nil t)
  13677        (when (org-entry-delete (point) property) (cl-incf count)))
  13678      (message "Property \"%s\" removed from %d entries" property count))))
  13679 
  13680 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  13681 
  13682 (defun org-compute-property-at-point ()
  13683   "Compute the property at point.
  13684 This looks for an enclosing column format, extracts the operator and
  13685 then applies it to the property in the column format's scope."
  13686   (interactive)
  13687   (unless (org-at-property-p)
  13688     (user-error "Not at a property"))
  13689   (let ((prop (match-string-no-properties 2)))
  13690     (org-columns-get-format-and-top-level)
  13691     (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  13692       (user-error "No operator defined for property %s" prop))
  13693     (org-columns-compute prop)))
  13694 
  13695 (defvar org-property-allowed-value-functions nil
  13696   "Hook for functions supplying allowed values for a specific property.
  13697 The functions must take a single argument, the name of the property, and
  13698 return a flat list of allowed values.  If \":ETC\" is one of
  13699 the values, this means that these values are intended as defaults for
  13700 completion, but that other values should be allowed too.
  13701 The functions must return nil if they are not responsible for this
  13702 property.")
  13703 
  13704 (defun org-property-get-allowed-values (epom property &optional table)
  13705   "Get allowed values at EPOM for the property PROPERTY.
  13706 EPOM can be an element, marker, or buffer position.
  13707 When TABLE is non-nil, return an alist that can directly be used for
  13708 completion."
  13709   (let (vals)
  13710     (cond
  13711      ((equal property "TODO")
  13712       (setq vals (org-with-point-at epom
  13713 		   (append org-todo-keywords-1 '("")))))
  13714      ((equal property "PRIORITY")
  13715       (let ((n org-priority-lowest))
  13716 	(while (>= n org-priority-highest)
  13717 	  (push (char-to-string n) vals)
  13718 	  (setq n (1- n)))))
  13719      ((equal property "CATEGORY"))
  13720      ((member property org-special-properties))
  13721      ((setq vals (run-hook-with-args-until-success
  13722 		  'org-property-allowed-value-functions property)))
  13723      (t
  13724       (setq vals (org-entry-get epom (concat property "_ALL") 'inherit))
  13725       (when (and vals (string-match "\\S-" vals))
  13726 	(setq vals (car (read-from-string (concat "(" vals ")"))))
  13727 	(setq vals (mapcar (lambda (x)
  13728 			     (cond ((stringp x) x)
  13729 				   ((numberp x) (number-to-string x))
  13730 				   ((symbolp x) (symbol-name x))
  13731 				   (t "???")))
  13732 			   vals)))))
  13733     (when (member ":ETC" vals)
  13734       (setq vals (remove ":ETC" vals))
  13735       (org-add-props (car vals) '(org-unrestricted t)))
  13736     (if table (mapcar 'list vals) vals)))
  13737 
  13738 (defun org-property-previous-allowed-value (&optional _previous)
  13739   "Switch to the next allowed value for this property."
  13740   (interactive)
  13741   (org-property-next-allowed-value t))
  13742 
  13743 (defun org-property-next-allowed-value (&optional previous)
  13744   "Switch to the next allowed value for this property."
  13745   (interactive)
  13746   (unless (org-at-property-p)
  13747     (user-error "Not at a property"))
  13748   (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  13749 	 (key (match-string 2))
  13750 	 (value (match-string 3))
  13751 	 (allowed (or (org-property-get-allowed-values (point) key)
  13752 		      (and (member value  '("[ ]" "[-]" "[X]"))
  13753 			   '("[ ]" "[X]"))))
  13754 	 (heading (save-match-data (nth 4 (org-heading-components))))
  13755 	 nval)
  13756     (unless allowed
  13757       (user-error "Allowed values for this property have not been defined"))
  13758     (when previous (setq allowed (reverse allowed)))
  13759     (when (member value allowed)
  13760       (setq nval (car (cdr (member value allowed)))))
  13761     (setq nval (or nval (car allowed)))
  13762     (when (equal nval value)
  13763       (user-error "Only one allowed value for this property"))
  13764     (org-at-property-p)
  13765     (replace-match (concat " :" key ": " nval) t t)
  13766     (org-indent-line)
  13767     (forward-line 0)
  13768     (skip-chars-forward " \t")
  13769     (when (equal prop org-effort-property)
  13770       (when (string= org-clock-current-task heading)
  13771 	(setq org-clock-effort nval)
  13772 	(org-clock-update-mode-line)))
  13773     (run-hook-with-args 'org-property-changed-functions key nval)))
  13774 
  13775 (defun org-find-olp (path &optional this-buffer)
  13776   "Return a marker pointing to the entry at outline path OLP.
  13777 If anything goes wrong, throw an error, and if you need to do
  13778 something based on this error, you can catch it with
  13779 `condition-case'.
  13780 
  13781 If THIS-BUFFER is set, the outline path does not contain a file,
  13782 only headings."
  13783   (let* ((file (if this-buffer buffer-file-name (pop path)))
  13784 	 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  13785 	 (level 1)
  13786 	 (lmin 1)
  13787 	 (lmax 1)
  13788 	 end found flevel)
  13789     (unless buffer (error "File not found :%s" file))
  13790     (with-current-buffer buffer
  13791       (unless (derived-mode-p 'org-mode)
  13792 	(error "Buffer %s needs to be in Org mode" buffer))
  13793       (org-with-wide-buffer
  13794        (goto-char (point-min))
  13795        (dolist (heading path)
  13796 	 (let ((re (format org-complex-heading-regexp-format
  13797 			   (regexp-quote heading)))
  13798 	       (cnt 0))
  13799 	   (while (re-search-forward re end t)
  13800 	     (setq level (- (match-end 1) (match-beginning 1)))
  13801 	     (when (and (>= level lmin) (<= level lmax))
  13802 	       (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  13803 	   (when (= cnt 0)
  13804 	     (error "Heading not found on level %d: %s" lmax heading))
  13805 	   (when (> cnt 1)
  13806 	     (error "Heading not unique on level %d: %s" lmax heading))
  13807 	   (goto-char found)
  13808 	   (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  13809 	   (setq end (save-excursion (org-end-of-subtree t t)))))
  13810        (when (org-at-heading-p)
  13811 	 (point-marker))))))
  13812 
  13813 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  13814   "Find node HEADING in BUFFER.
  13815 Return a marker to the heading if it was found, or nil if not.
  13816 If POS-ONLY is set, return just the position instead of a marker.
  13817 
  13818 The heading text must match exact, but it may have a TODO keyword,
  13819 a priority cookie and tags in the standard locations."
  13820   (with-current-buffer (or buffer (current-buffer))
  13821     (org-with-wide-buffer
  13822      (goto-char (point-min))
  13823      (let (case-fold-search)
  13824        (when (re-search-forward
  13825 	      (format org-complex-heading-regexp-format
  13826 		      (regexp-quote heading)) nil t)
  13827 	 (if pos-only
  13828 	     (match-beginning 0)
  13829 	   (move-marker (make-marker) (match-beginning 0))))))))
  13830 
  13831 (defun org-find-exact-heading-in-directory (heading &optional dir)
  13832   "Find Org node headline HEADING in all \".org\" files in directory DIR.
  13833 When the target headline is found, return a marker to this location."
  13834   (let ((files (directory-files (or dir default-directory)
  13835 				t "\\`[^.#].*\\.org\\'"))
  13836 	visiting m buffer)
  13837     (catch 'found
  13838       (dolist (file files)
  13839         (message "trying %s" file)
  13840         (setq visiting (org-find-base-buffer-visiting file))
  13841         (setq buffer (or visiting (find-file-noselect file)))
  13842         (setq m (org-find-exact-headline-in-buffer
  13843                  heading buffer))
  13844         (when (and (not m) (not visiting)) (kill-buffer buffer))
  13845         (and m (throw 'found m))))))
  13846 
  13847 (defun org-find-entry-with-id (ident)
  13848   "Locate the entry that contains the ID property with exact value IDENT.
  13849 IDENT can be a string, a symbol or a number, this function will search for
  13850 the string representation of it.
  13851 Return the position where this entry starts, or nil if there is no such entry."
  13852   (interactive "sID: ")
  13853   (let ((id (cond
  13854 	     ((stringp ident) ident)
  13855 	     ((symbolp ident) (symbol-name ident))
  13856 	     ((numberp ident) (number-to-string ident))
  13857 	     (t (error "IDENT %s must be a string, symbol or number" ident)))))
  13858     (org-with-wide-buffer (org-find-property "ID" id))))
  13859 
  13860 ;;;; Timestamps
  13861 
  13862 (defvar org-last-changed-timestamp nil)
  13863 (defvar org-last-inserted-timestamp nil
  13864   "The last time stamp inserted with `org-insert-timestamp'.")
  13865 
  13866 (defalias 'org-time-stamp #'org-timestamp)
  13867 (defun org-timestamp (arg &optional inactive)
  13868   "Prompt for a date/time and insert a time stamp.
  13869 
  13870 If the user specifies a time like HH:MM or if this command is
  13871 called with at least one prefix argument, the time stamp contains
  13872 the date and the time.  Otherwise, only the date is included.
  13873 
  13874 All parts of a date not specified by the user are filled in from
  13875 the timestamp at point, if any, or the current date/time
  13876 otherwise.
  13877 
  13878 If there is already a timestamp at the cursor, it is replaced.
  13879 
  13880 With two universal prefix arguments, insert an active timestamp
  13881 with the current time without prompting the user.
  13882 
  13883 When called from Lisp, the timestamp is inactive if INACTIVE is
  13884 non-nil."
  13885   (interactive "P")
  13886   (let* ((ts (cond
  13887 	      ((org-at-date-range-p t)
  13888 	       (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  13889 	      ((org-at-timestamp-p 'lax) (match-string 0))))
  13890 	 ;; Default time is either the timestamp at point or today.
  13891 	 ;; When entering a range, only the range start is considered.
  13892          (default-time (and ts (org-time-string-to-time ts)))
  13893          (default-input (and ts (org-get-compact-tod ts)))
  13894          (repeater (and ts
  13895 			(string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  13896 			(match-string 0 ts)))
  13897 	 org-time-was-given
  13898 	 org-end-time-was-given
  13899 	 (time
  13900 	  (if (equal arg '(16)) (current-time)
  13901 	    ;; Preserve `this-command' and `last-command'.
  13902 	    (let ((this-command this-command)
  13903 		  (last-command last-command))
  13904 	      (org-read-date
  13905 	       arg 'totime nil nil default-time default-input
  13906 	       inactive)))))
  13907     (cond
  13908      ((and ts
  13909            (memq last-command '( org-time-stamp org-time-stamp-inactive
  13910                                  org-timestamp org-timestamp-inactive))
  13911            (memq this-command '( org-time-stamp org-time-stamp-inactive
  13912                                  org-timestamp org-timestamp-inactive)))
  13913       (insert "--")
  13914       (org-insert-timestamp time (or org-time-was-given arg) inactive))
  13915      (ts
  13916       ;; Make sure we're on a timestamp.  When in the middle of a date
  13917       ;; range, move arbitrarily to range end.
  13918       (unless (org-at-timestamp-p 'lax)
  13919 	(skip-chars-forward "-")
  13920 	(org-at-timestamp-p 'lax))
  13921       (replace-match "")
  13922       (setq org-last-changed-timestamp
  13923 	    (org-insert-timestamp
  13924 	     time (or org-time-was-given arg)
  13925 	     inactive nil nil (list org-end-time-was-given)))
  13926       (when repeater
  13927 	(backward-char)
  13928 	(insert " " repeater)
  13929 	(setq org-last-changed-timestamp
  13930 	      (concat (substring org-last-inserted-timestamp 0 -1)
  13931 		      " " repeater ">")))
  13932       (message "Timestamp updated"))
  13933      ((equal arg '(16)) (org-insert-timestamp time t inactive))
  13934      (t (org-insert-timestamp
  13935 	 time (or org-time-was-given arg) inactive nil nil
  13936 	 (list org-end-time-was-given))))))
  13937 
  13938 ;; FIXME: can we use this for something else, like computing time differences?
  13939 (defun org-get-compact-tod (s)
  13940   (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  13941     (let* ((t1 (match-string 1 s))
  13942 	   (h1 (string-to-number (match-string 2 s)))
  13943 	   (m1 (string-to-number (match-string 3 s)))
  13944 	   (t2 (and (match-end 4) (match-string 5 s)))
  13945 	   (h2 (and t2 (string-to-number (match-string 6 s))))
  13946 	   (m2 (and t2 (string-to-number (match-string 7 s))))
  13947 	   dh dm)
  13948       (if (not t2)
  13949 	  t1
  13950 	(setq dh (- h2 h1) dm (- m2 m1))
  13951 	(when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  13952 	(concat t1 "+" (number-to-string dh)
  13953 		(and (/= 0 dm) (format ":%02d" dm)))))))
  13954 
  13955 (defalias 'org-time-stamp-inactive #'org-timestamp-inactive)
  13956 (defun org-timestamp-inactive (&optional arg)
  13957   "Insert an inactive time stamp.
  13958 
  13959 An inactive time stamp is enclosed in square brackets instead of
  13960 angle brackets.  It is inactive in the sense that it does not
  13961 trigger agenda entries.  So these are more for recording a
  13962 certain time/date.
  13963 
  13964 If the user specifies a time like HH:MM or if this command is called with
  13965 at least one prefix argument, the time stamp contains the date and the time.
  13966 Otherwise, only the date is included.
  13967 
  13968 When called with two universal prefix arguments, insert an inactive time stamp
  13969 with the current time without prompting the user."
  13970   (interactive "P")
  13971   (org-timestamp arg 'inactive))
  13972 
  13973 (defvar org-date-ovl (make-overlay 1 1))
  13974 (overlay-put org-date-ovl 'face 'org-date-selected)
  13975 (delete-overlay org-date-ovl)
  13976 
  13977 (defvar org-ans1) ; dynamically scoped parameter
  13978 (defvar org-ans2) ; dynamically scoped parameter
  13979 
  13980 (defvar org-plain-time-of-day-regexp) ; defined below
  13981 
  13982 (defvar org-overriding-default-time nil) ; dynamically scoped
  13983 (defvar org-read-date-overlay nil)
  13984 (defvar org-read-date-history nil)
  13985 (defvar org-read-date-final-answer nil)
  13986 (defvar org-read-date-analyze-futurep nil)
  13987 (defvar org-read-date-analyze-forced-year nil)
  13988 (defvar org-read-date-inactive)
  13989 (defvar org-def)
  13990 (defvar org-defdecode)
  13991 (defvar org-with-time)
  13992 
  13993 (defvar calendar-setup)			; Dynamically scoped.
  13994 (defun org-read-date (&optional with-time to-time from-string prompt
  13995 				default-time default-input inactive)
  13996   "Read a date, possibly a time, and make things smooth for the user.
  13997 The prompt will suggest to enter an ISO date, but you can also enter anything
  13998 which will at least partially be understood by `parse-time-string'.
  13999 Unrecognized parts of the date will default to the current day, month, year,
  14000 hour and minute.  If this command is called to replace a timestamp at point,
  14001 or to enter the second timestamp of a range, the default time is taken
  14002 from the existing stamp.  Furthermore, the command prefers the future,
  14003 so if you are giving a date where the year is not given, and the day-month
  14004 combination is already past in the current year, it will assume you
  14005 mean next year.  For details, see the manual.  A few examples:
  14006 
  14007   3-2-5         --> 2003-02-05
  14008   feb 15        --> currentyear-02-15
  14009   2/15          --> currentyear-02-15
  14010   sep 12 9      --> 2009-09-12
  14011   12:45         --> today 12:45
  14012   22 sept 0:34  --> currentyear-09-22 0:34
  14013   12            --> currentyear-currentmonth-12
  14014   Fri           --> nearest Friday after today
  14015   -Tue          --> last Tuesday
  14016   etc.
  14017 
  14018 Furthermore you can specify a relative date by giving, as the *first* thing
  14019 in the input:  a plus/minus sign, a number and a letter [hdwmy] to indicate
  14020 change in days weeks, months, years.
  14021 With a single plus or minus, the date is relative to today.  With a double
  14022 plus or minus, it is relative to the date in DEFAULT-TIME.  E.g.
  14023   +4d           --> four days from today
  14024   +4            --> same as above
  14025   +2w           --> two weeks from today
  14026   ++5           --> five days from default date
  14027 
  14028 The function understands only English month and weekday abbreviations.
  14029 
  14030 While prompting, a calendar is popped up - you can also select the
  14031 date with the mouse (button 1).  The calendar shows a period of three
  14032 months.  To scroll it to other months, use the keys `>' and `<'.
  14033 There are many other calendar navigation commands available, see
  14034 Info node `(org) The date/time prompt' for a full list.
  14035 
  14036 If you don't like the calendar, turn it off with
  14037        (setq org-read-date-popup-calendar nil)
  14038 
  14039 With optional argument TO-TIME, the date will immediately be converted
  14040 to an internal time.
  14041 With an optional argument WITH-TIME, the prompt will suggest to
  14042 also insert a time.  Note that when WITH-TIME is not set, you can
  14043 still enter a time, and this function will inform the calling routine
  14044 about this change.  The calling routine may then choose to change the
  14045 format used to insert the time stamp into the buffer to include the time.
  14046 With optional argument FROM-STRING, read from this string instead from
  14047 the user.  PROMPT can overwrite the default prompt.  DEFAULT-TIME is
  14048 the time/date that is used for everything that is not specified by the
  14049 user."
  14050   (require 'parse-time)
  14051   (let* ((org-with-time with-time)
  14052 	 (org-timestamp-rounding-minutes
  14053 	  (if (equal org-with-time '(16))
  14054 	      '(0 0)
  14055 	    org-timestamp-rounding-minutes))
  14056 	 (ct (org-current-time))
  14057 	 (org-def (or org-overriding-default-time default-time ct))
  14058 	 (org-defdecode (decode-time org-def))
  14059          (cur-frame (selected-frame))
  14060 	 (mouse-autoselect-window nil)	; Don't let the mouse jump
  14061 	 (calendar-setup
  14062 	  (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14063 	 (calendar-move-hook nil)
  14064 	 (calendar-view-diary-initially-flag nil)
  14065 	 (calendar-view-holidays-initially-flag nil)
  14066 	 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14067     ;; Rationalize `org-def' and `org-defdecode', if required.
  14068     ;; Only consider `org-extend-today-until' when explicit reference
  14069     ;; time is not given.
  14070     (when (and (not default-time)
  14071                (not org-overriding-default-time)
  14072                (< (nth 2 org-defdecode) org-extend-today-until))
  14073       (setf (nth 2 org-defdecode) -1)
  14074       (setf (nth 1 org-defdecode) 59)
  14075       (setq org-def (org-encode-time org-defdecode))
  14076       (setq org-defdecode (decode-time org-def)))
  14077     (let* ((timestr (format-time-string
  14078 		     (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14079 		     org-def))
  14080 	   (prompt (concat (if prompt (concat prompt " ") "")
  14081 			   (format "Date+time [%s]: " timestr))))
  14082       (cond
  14083        (from-string (setq ans from-string))
  14084        (org-read-date-popup-calendar
  14085 	(save-excursion
  14086 	  (save-window-excursion
  14087 	    (calendar)
  14088 	    (when (eq calendar-setup 'calendar-only)
  14089 	      (setq cal-frame
  14090 		    (window-frame (get-buffer-window calendar-buffer 'visible)))
  14091 	      (select-frame cal-frame))
  14092 	    (org-eval-in-calendar '(setq cursor-type nil) t)
  14093 	    (unwind-protect
  14094 		(progn
  14095 		  (calendar-forward-day (- (time-to-days org-def)
  14096 					   (calendar-absolute-from-gregorian
  14097 					    (calendar-current-date))))
  14098 		  (org-eval-in-calendar nil t)
  14099 		  (let* ((old-map (current-local-map))
  14100 			 (map (copy-keymap calendar-mode-map))
  14101 			 (minibuffer-local-map
  14102 			  (copy-keymap org-read-date-minibuffer-local-map)))
  14103 		    (org-defkey map (kbd "RET") 'org-calendar-select)
  14104 		    (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14105 		    (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14106 		    (unwind-protect
  14107 			(progn
  14108 			  (use-local-map map)
  14109 			  (setq org-read-date-inactive inactive)
  14110 			  (add-hook 'post-command-hook 'org-read-date-display)
  14111 			  (setq org-ans0
  14112 				(read-string prompt
  14113 					     default-input
  14114 					     'org-read-date-history
  14115 					     nil))
  14116 			  ;; org-ans0: from prompt
  14117 			  ;; org-ans1: from mouse click
  14118 			  ;; org-ans2: from calendar motion
  14119 			  (setq ans
  14120 				(concat org-ans0 " " (or org-ans1 org-ans2))))
  14121 		      (remove-hook 'post-command-hook 'org-read-date-display)
  14122 		      (use-local-map old-map)
  14123 		      (when org-read-date-overlay
  14124 			(delete-overlay org-read-date-overlay)
  14125 			(setq org-read-date-overlay nil)))))
  14126 	      (bury-buffer calendar-buffer)
  14127 	      (when cal-frame
  14128 		(delete-frame cal-frame)
  14129 		(select-frame-set-input-focus cur-frame))))))
  14130 
  14131        (t				; Naked prompt only
  14132 	(unwind-protect
  14133 	    (setq ans (read-string prompt default-input
  14134 				   'org-read-date-history timestr))
  14135 	  (when org-read-date-overlay
  14136 	    (delete-overlay org-read-date-overlay)
  14137 	    (setq org-read-date-overlay nil))))))
  14138 
  14139     (setq final (org-read-date-analyze ans org-def org-defdecode))
  14140 
  14141     (when org-read-date-analyze-forced-year
  14142       (message "Year was forced into %s"
  14143 	       (if org-read-date-force-compatible-dates
  14144 		   "compatible range (1970-2037)"
  14145 		 "range representable on this machine"))
  14146       (ding))
  14147 
  14148     (setq final (org-encode-time final))
  14149 
  14150     (setq org-read-date-final-answer ans)
  14151 
  14152     (if to-time
  14153 	final
  14154       ;; This round-trip gets rid of 34th of August and stuff like that....
  14155       (setq final (decode-time final))
  14156       (if (and (boundp 'org-time-was-given) org-time-was-given)
  14157 	  (format "%04d-%02d-%02d %02d:%02d"
  14158 		  (nth 5 final) (nth 4 final) (nth 3 final)
  14159 		  (nth 2 final) (nth 1 final))
  14160 	(format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14161 
  14162 (defun org-read-date-display ()
  14163   "Display the current date prompt interpretation in the minibuffer."
  14164   (when org-read-date-display-live
  14165     (when org-read-date-overlay
  14166       (delete-overlay org-read-date-overlay))
  14167     (when (minibufferp (current-buffer))
  14168       (save-excursion
  14169 	(end-of-line 1)
  14170 	(while (not (equal (buffer-substring
  14171 			  (max (point-min) (- (point) 4)) (point))
  14172 			 "    "))
  14173 	  (insert " ")))
  14174       (let* ((ans (concat (buffer-substring (line-beginning-position)
  14175                                             (point-max))
  14176 			  " " (or org-ans1 org-ans2)))
  14177 	     (org-end-time-was-given nil)
  14178 	     (f (org-read-date-analyze ans org-def org-defdecode))
  14179 	     (fmt (org-time-stamp-format
  14180                    (or org-with-time
  14181                        (and (boundp 'org-time-was-given) org-time-was-given))
  14182                    org-read-date-inactive
  14183                    org-display-custom-times))
  14184 	     (txt (format-time-string fmt (org-encode-time f)))
  14185 	     (txt (concat "=> " txt)))
  14186 	(when (and org-end-time-was-given
  14187 		   (string-match org-plain-time-of-day-regexp txt))
  14188 	  (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14189 			    org-end-time-was-given
  14190 			    (substring txt (match-end 0)))))
  14191 	(when org-read-date-analyze-futurep
  14192 	  (setq txt (concat txt " (=>F)")))
  14193 	(setq org-read-date-overlay
  14194               (make-overlay (1- (line-end-position)) (line-end-position)))
  14195         ;; Avoid priority race with overlay used by calendar.el.
  14196         ;; See bug#69271.
  14197         (overlay-put org-read-date-overlay 'priority 1)
  14198 	(org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14199 
  14200 (defun org-read-date-analyze (ans def defdecode)
  14201   "Analyze the combined answer of the date prompt."
  14202   ;; FIXME: cleanup and comment
  14203   (let ((org-def def)
  14204 	(org-defdecode defdecode)
  14205 	(nowdecode (decode-time))
  14206 	delta deltan deltaw deltadef year month day
  14207 	hour minute second wday pm h2 m2 tl wday1
  14208 	iso-year iso-weekday iso-week iso-date futurep kill-year)
  14209     (setq org-read-date-analyze-futurep nil
  14210 	  org-read-date-analyze-forced-year nil)
  14211     (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14212       (setq ans "+0"))
  14213 
  14214     (when (setq delta (org-read-date-get-relative ans nil org-def))
  14215       (setq ans (replace-match "" t t ans)
  14216 	    deltan (car delta)
  14217 	    deltaw (nth 1 delta)
  14218 	    deltadef (nth 2 delta)))
  14219 
  14220     ;; Check if there is an iso week date in there.  If yes, store the
  14221     ;; info and postpone interpreting it until the rest of the parsing
  14222     ;; is done.
  14223     (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14224       (setq iso-year (when (match-end 1)
  14225 		       (org-small-year-to-year
  14226 			(string-to-number (match-string 1 ans))))
  14227 	    iso-weekday (when (match-end 3)
  14228 			  (string-to-number (match-string 3 ans)))
  14229 	    iso-week (string-to-number (match-string 2 ans)))
  14230       (setq ans (replace-match "" t t ans)))
  14231 
  14232     ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14233     (when (string-match
  14234 	   "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14235       (setq year (if (match-end 2)
  14236 		     (string-to-number (match-string 2 ans))
  14237 		   (progn (setq kill-year t)
  14238 			  (string-to-number (format-time-string "%Y"))))
  14239 	    month (string-to-number (match-string 3 ans))
  14240 	    day (string-to-number (match-string 4 ans)))
  14241       (setq year (org-small-year-to-year year))
  14242       (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14243 			       t nil ans)))
  14244 
  14245     ;; Help matching dotted european dates
  14246     (when (string-match
  14247 	   "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14248       (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14249 		   (setq kill-year t)
  14250 		   (string-to-number (format-time-string "%Y")))
  14251 	    day (string-to-number (match-string 1 ans))
  14252 	    month (string-to-number (match-string 2 ans))
  14253 	    ans (replace-match (format "%04d-%02d-%02d" year month day)
  14254 			       t nil ans)))
  14255 
  14256     ;; Help matching american dates, like 5/30 or 5/30/7
  14257     (when (string-match
  14258 	   "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14259       (setq year (if (match-end 4)
  14260 		     (string-to-number (match-string 4 ans))
  14261 		   (progn (setq kill-year t)
  14262 			  (string-to-number (format-time-string "%Y"))))
  14263 	    month (string-to-number (match-string 1 ans))
  14264 	    day (string-to-number (match-string 2 ans)))
  14265       (setq year (org-small-year-to-year year))
  14266       (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14267 			       t nil ans)))
  14268     ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14269     ;; If there is a time with am/pm, and *no* time without it, we convert
  14270     ;; so that matching will be successful.
  14271     (cl-loop for i from 1 to 2 do	; twice, for end time as well
  14272 	     (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14273 			(string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14274 	       (setq hour (string-to-number (match-string 1 ans))
  14275 		     minute (if (match-end 3)
  14276 				(string-to-number (match-string 3 ans))
  14277 			      0)
  14278 		     pm (equal ?p
  14279 			       (string-to-char (downcase (match-string 4 ans)))))
  14280 	       (if (and (= hour 12) (not pm))
  14281 		   (setq hour 0)
  14282 		 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14283 	       (setq ans (replace-match (format "%02d:%02d" hour minute)
  14284 					t t ans))))
  14285 
  14286     ;; Help matching HHhMM times, similarly as for am/pm times.
  14287     (cl-loop for i from 1 to 2 do	; twice, for end time as well
  14288 	     (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14289 			(string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  14290 	       (setq hour (if (match-end 1)
  14291 			      (string-to-number (match-string 1 ans))
  14292 			    0)
  14293 		     minute (if (match-end 2)
  14294 				(string-to-number (match-string 2 ans))
  14295 			      0))
  14296 	       (setq ans (replace-match (format "%02d:%02d" hour minute)
  14297 					t t ans))))
  14298 
  14299     ;; Check if a time range is given as a duration
  14300     (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14301       (setq hour (string-to-number (match-string 1 ans))
  14302 	    h2 (+ hour (string-to-number (match-string 3 ans)))
  14303 	    minute (string-to-number (match-string 2 ans))
  14304 	    m2 (+ minute (if (match-end 5) (string-to-number
  14305 					    (match-string 5 ans))0)))
  14306       (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14307       (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14308 			       t t ans)))
  14309 
  14310     ;; Check if there is a time range
  14311     (when (boundp 'org-end-time-was-given)
  14312       (setq org-time-was-given nil)
  14313       (when (and (string-match org-plain-time-of-day-regexp ans)
  14314 		 (match-end 8))
  14315 	(setq org-end-time-was-given (match-string 8 ans))
  14316 	(setq ans (concat (substring ans 0 (match-beginning 7))
  14317 			  (substring ans (match-end 7))))))
  14318 
  14319     (setq tl (parse-time-string ans)
  14320 	  day (or (nth 3 tl) (nth 3 org-defdecode))
  14321 	  month
  14322 	  (cond ((nth 4 tl))
  14323 		((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14324 		;; Day was specified.  Make sure DAY+MONTH
  14325 		;; combination happens in the future.
  14326 		((nth 3 tl)
  14327 		 (setq futurep t)
  14328 		 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14329 		   (nth 4 nowdecode)))
  14330 		(t (nth 4 org-defdecode)))
  14331 	  year
  14332 	  (cond ((and (not kill-year) (nth 5 tl)))
  14333 		((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14334 		;; Month was guessed in the future and is at least
  14335 		;; equal to NOWDECODE's.  Fix year accordingly.
  14336 		(futurep
  14337 		 (if (or (> month (nth 4 nowdecode))
  14338 			 (>= day (nth 3 nowdecode)))
  14339 		     (nth 5 nowdecode)
  14340 		   (1+ (nth 5 nowdecode))))
  14341 		;; Month was specified.  Make sure MONTH+YEAR
  14342 		;; combination happens in the future.
  14343 		((nth 4 tl)
  14344 		 (setq futurep t)
  14345 		 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14346 		       ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14347 		       ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14348 		       (t (nth 5 nowdecode))))
  14349 		(t (nth 5 org-defdecode)))
  14350 	  hour (or (nth 2 tl) (nth 2 org-defdecode))
  14351 	  minute (or (nth 1 tl) (nth 1 org-defdecode))
  14352 	  second (or (nth 0 tl) 0)
  14353 	  wday (nth 6 tl))
  14354 
  14355     (when (and (eq org-read-date-prefer-future 'time)
  14356 	       (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14357 	       (equal day (nth 3 nowdecode))
  14358 	       (equal month (nth 4 nowdecode))
  14359 	       (equal year (nth 5 nowdecode))
  14360 	       (nth 2 tl)
  14361 	       (or (< (nth 2 tl) (nth 2 nowdecode))
  14362 		   (and (= (nth 2 tl) (nth 2 nowdecode))
  14363 			(nth 1 tl)
  14364 			(< (nth 1 tl) (nth 1 nowdecode)))))
  14365       (setq day (1+ day)
  14366 	    futurep t))
  14367 
  14368     ;; Special date definitions below
  14369     (cond
  14370      (iso-week
  14371       ;; There was an iso week
  14372       (require 'cal-iso)
  14373       (setq futurep nil)
  14374       (setq year (or iso-year year)
  14375 	    day (or iso-weekday wday 1)
  14376 	    wday nil ; to make sure that the trigger below does not match
  14377 	    iso-date (calendar-gregorian-from-absolute
  14378 		      (calendar-iso-to-absolute
  14379 		       (list iso-week day year))))
  14380 					; FIXME:  Should we also push ISO weeks into the future?
  14381 					;      (when (and org-read-date-prefer-future
  14382 					;		 (not iso-year)
  14383 					;		 (< (calendar-absolute-from-gregorian iso-date)
  14384 					;		    (time-to-days nil)))
  14385 					;	(setq year (1+ year)
  14386 					;	      iso-date (calendar-gregorian-from-absolute
  14387 					;			(calendar-iso-to-absolute
  14388 					;			 (list iso-week day year)))))
  14389       (setq month (car iso-date)
  14390 	    year (nth 2 iso-date)
  14391 	    day (nth 1 iso-date)))
  14392      (deltan
  14393       (setq futurep nil)
  14394       (unless deltadef
  14395 	(let ((now (decode-time)))
  14396 	  (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  14397       ;; FIXME: Duplicated value in ‘cond’: ""
  14398       (cond ((member deltaw '("h" ""))
  14399              (when (boundp 'org-time-was-given)
  14400                (setq org-time-was-given t))
  14401              (setq hour (+ hour deltan)))
  14402             ((member deltaw '("d" "")) (setq day (+ day deltan)))
  14403             ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  14404             ((equal deltaw "m") (setq month (+ month deltan)))
  14405             ((equal deltaw "y") (setq year (+ year deltan)))))
  14406      ((and wday (not (nth 3 tl)))
  14407       ;; Weekday was given, but no day, so pick that day in the week
  14408       ;; on or after the derived date.
  14409       (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  14410       (unless (equal wday wday1)
  14411 	(setq day (+ day (% (- wday wday1 -7) 7))))))
  14412     (when (and (boundp 'org-time-was-given)
  14413 	       (nth 2 tl))
  14414       (setq org-time-was-given t))
  14415     (when (< year 100) (setq year (+ 2000 year)))
  14416     ;; Check of the date is representable
  14417     (if org-read-date-force-compatible-dates
  14418 	(progn
  14419 	  (when (< year 1970)
  14420 	    (setq year 1970 org-read-date-analyze-forced-year t))
  14421 	  (when (> year 2037)
  14422 	    (setq year 2037 org-read-date-analyze-forced-year t)))
  14423       (condition-case nil
  14424 	  (ignore (org-encode-time second minute hour day month year))
  14425 	(error
  14426 	 (setq year (nth 5 org-defdecode))
  14427 	 (setq org-read-date-analyze-forced-year t))))
  14428     (setq org-read-date-analyze-futurep futurep)
  14429     (list second minute hour day month year nil -1 nil)))
  14430 
  14431 (defvar parse-time-weekdays)
  14432 (defun org-read-date-get-relative (s today default)
  14433   "Check string S for special relative date string.
  14434 TODAY and DEFAULT are internal times, for today and for a default.
  14435 Return shift list (N what def-flag)
  14436 WHAT       is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  14437 N          is the number of WHATs to shift.
  14438 DEF-FLAG   is t when a double ++ or -- indicates shift relative to
  14439            the DEFAULT date rather than TODAY."
  14440   (require 'parse-time)
  14441   (when (and
  14442          ;; Force case-insensitive.
  14443          (let ((case-fold-search t))
  14444 	   (string-match
  14445 	    (concat
  14446 	     "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  14447 	     "\\([0-9]+\\)?"
  14448 	     "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  14449 	     "\\([ \t]\\|$\\)") s))
  14450 	 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  14451     (let* ((dir (if (> (match-end 1) (match-beginning 1))
  14452 		    (string-to-char (substring (match-string 1 s) -1))
  14453 		  ?+))
  14454 	   (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  14455 	   (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  14456 	   (what (if (match-end 3) (match-string 3 s) "d"))
  14457 	   (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  14458 	   (date (if rel default today))
  14459 	   (wday (nth 6 (decode-time date)))
  14460 	   delta)
  14461       (if wday1
  14462 	  (progn
  14463 	    (setq delta (mod (+ 7 (- wday1 wday)) 7))
  14464 	    (when (= delta 0) (setq delta 7))
  14465 	    (when (= dir ?-)
  14466 	      (setq delta (- delta 7))
  14467 	      (when (= delta 0) (setq delta -7)))
  14468 	    (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  14469 	    (list delta "d" rel))
  14470 	(list (* n (if (= dir ?-) -1 1)) what rel)))))
  14471 
  14472 (defun org-order-calendar-date-args (arg1 arg2 arg3)
  14473   "Turn a user-specified date into the internal representation.
  14474 The internal representation needed by the calendar is (month day year).
  14475 This is a wrapper to handle the brain-dead convention in calendar that
  14476 user function argument order change dependent on argument order."
  14477   (pcase calendar-date-style
  14478     (`american (list arg1 arg2 arg3))
  14479     (`european (list arg2 arg1 arg3))
  14480     (`iso (list arg2 arg3 arg1))))
  14481 
  14482 (defun org-eval-in-calendar (form &optional keepdate)
  14483   "Eval FORM in the calendar window and return to current window.
  14484 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  14485   (let ((sf (selected-frame))
  14486 	(sw (selected-window)))
  14487     (select-window (get-buffer-window calendar-buffer t))
  14488     (eval form t)
  14489     (when (and (not keepdate) (calendar-cursor-to-date))
  14490       (let* ((date (calendar-cursor-to-date))
  14491 	     (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14492 	(setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  14493     (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  14494     (select-window sw)
  14495     (select-frame-set-input-focus sf)))
  14496 
  14497 (defun org-calendar-goto-today-or-insert-dot ()
  14498   "Go to the current date, or insert a dot.
  14499 
  14500 If at the beginning of the prompt, behave as `org-calendar-goto-today' else
  14501 insert \".\"."
  14502   (interactive)
  14503   ;; Are we at the beginning of the prompt?
  14504   (if (looking-back "^[^:]+: "
  14505 		    (let ((inhibit-field-text-motion t))
  14506 		      (line-beginning-position)))
  14507       (org-eval-in-calendar '(calendar-goto-today))
  14508     (insert ".")))
  14509 
  14510 (defun org-calendar-goto-today ()
  14511   "Reposition the calendar window so the current date is visible."
  14512   (interactive)
  14513   (org-eval-in-calendar '(calendar-goto-today)))
  14514 
  14515 (defun org-calendar-backward-month ()
  14516   "Move the cursor backward by one month."
  14517   (interactive)
  14518   (org-eval-in-calendar '(calendar-backward-month 1)))
  14519 
  14520 (defun org-calendar-forward-month ()
  14521   "Move the cursor forward by one month."
  14522   (interactive)
  14523   (org-eval-in-calendar '(calendar-forward-month 1)))
  14524 
  14525 (defun org-calendar-backward-year ()
  14526   "Move the cursor backward by one year."
  14527   (interactive)
  14528   (org-eval-in-calendar '(calendar-backward-year 1)))
  14529 
  14530 (defun org-calendar-forward-year ()
  14531   "Move the cursor forward by one year."
  14532   (interactive)
  14533   (org-eval-in-calendar '(calendar-forward-year 1)))
  14534 
  14535 (defun org-calendar-backward-week ()
  14536   "Move the cursor backward by one week."
  14537   (interactive)
  14538   (org-eval-in-calendar '(calendar-backward-week 1)))
  14539 
  14540 (defun org-calendar-forward-week ()
  14541   "Move the cursor forward by one week."
  14542   (interactive)
  14543   (org-eval-in-calendar '(calendar-forward-week 1)))
  14544 
  14545 (defun org-calendar-backward-day ()
  14546   "Move the cursor backward by one day."
  14547   (interactive)
  14548   (org-eval-in-calendar '(calendar-backward-day 1)))
  14549 
  14550 (defun org-calendar-forward-day ()
  14551   "Move the cursor forward by one day."
  14552   (interactive)
  14553   (org-eval-in-calendar '(calendar-forward-day 1)))
  14554 
  14555 (defun org-calendar-view-entries ()
  14556   "Prepare and display a buffer with diary entries."
  14557   (interactive)
  14558   (org-eval-in-calendar '(diary-view-entries))
  14559   (message ""))
  14560 
  14561 (defun org-calendar-scroll-month-left ()
  14562   "Scroll the displayed calendar left by one month."
  14563   (interactive)
  14564   (org-eval-in-calendar '(calendar-scroll-left 1)))
  14565 
  14566 (defun org-calendar-scroll-month-right ()
  14567   "Scroll the displayed calendar right by one month."
  14568   (interactive)
  14569   (org-eval-in-calendar '(calendar-scroll-right 1)))
  14570 
  14571 (defun org-calendar-scroll-three-months-left ()
  14572   "Scroll the displayed calendar left by three months."
  14573   (interactive)
  14574   (org-eval-in-calendar
  14575    '(calendar-scroll-left-three-months 1)))
  14576 
  14577 (defun org-calendar-scroll-three-months-right ()
  14578   "Scroll the displayed calendar right by three months."
  14579   (interactive)
  14580   (org-eval-in-calendar
  14581    '(calendar-scroll-right-three-months 1)))
  14582 
  14583 (defun org-calendar-select ()
  14584   "Return to `org-read-date' with the date currently selected.
  14585 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14586   (interactive)
  14587   (when (calendar-cursor-to-date)
  14588     (let* ((date (calendar-cursor-to-date))
  14589 	   (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14590       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14591     (when (active-minibuffer-window) (exit-minibuffer))))
  14592 
  14593 (defalias 'org-insert-time-stamp #'org-insert-timestamp)
  14594 (defun org-insert-timestamp (time &optional with-hm inactive pre post extra)
  14595   "Insert a date stamp for the date given by the internal TIME.
  14596 See `format-time-string' for the format of TIME.
  14597 WITH-HM means use the stamp format that includes the time of the day.
  14598 INACTIVE means use square brackets instead of angular ones, so that the
  14599 stamp will not contribute to the agenda.
  14600 PRE and POST are optional strings to be inserted before and after the
  14601 stamp.
  14602 The command returns the inserted time stamp."
  14603   (org-fold-core-ignore-modifications
  14604     (let ((fmt (org-time-stamp-format with-hm inactive))
  14605 	  stamp)
  14606       (insert-before-markers-and-inherit (or pre ""))
  14607       (when (listp extra)
  14608         (setq extra (car extra))
  14609         (if (and (stringp extra)
  14610 	         (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  14611 	    (setq extra (format "-%02d:%02d"
  14612 			        (string-to-number (match-string 1 extra))
  14613 			        (string-to-number (match-string 2 extra))))
  14614 	  (setq extra nil)))
  14615       (when extra
  14616         (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  14617       (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  14618       (insert-before-markers-and-inherit (or post ""))
  14619       (setq org-last-inserted-timestamp stamp))))
  14620 
  14621 (defalias 'org-toggle-time-stamp-overlays #'org-toggle-timestamp-overlays)
  14622 (defun org-toggle-timestamp-overlays ()
  14623   "Toggle the use of custom time stamp formats."
  14624   (interactive)
  14625   (setq org-display-custom-times (not org-display-custom-times))
  14626   (unless org-display-custom-times
  14627     (let ((p (point-min)) (bmp (buffer-modified-p)))
  14628       (while (setq p (next-single-property-change p 'display))
  14629 	(when (and (get-text-property p 'display)
  14630 		   (eq (get-text-property p 'face) 'org-date))
  14631 	  (remove-text-properties
  14632 	   p (setq p (next-single-property-change p 'display))
  14633 	   '(display t))))
  14634       (set-buffer-modified-p bmp)))
  14635   (org-restart-font-lock)
  14636   (setq org-table-may-need-update t)
  14637   (if org-display-custom-times
  14638       (message "Time stamps are overlaid with custom format")
  14639     (message "Time stamp overlays removed")))
  14640 
  14641 (defun org-display-custom-time (beg end)
  14642   "Overlay modified time stamp format over timestamp between BEG and END."
  14643   (let* ((ts (buffer-substring beg end))
  14644 	 t1 with-hm tf time str (off 0))
  14645     (save-match-data
  14646       (setq t1 (org-parse-time-string ts t))
  14647       (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  14648 	(setq off (- (match-end 0) (match-beginning 0)))))
  14649     (setq end (- end off))
  14650     (setq with-hm (and (nth 1 t1) (nth 2 t1))
  14651 	  tf (org-time-stamp-format with-hm 'no-brackets 'custom)
  14652 	  time (org-fix-decoded-time t1)
  14653 	  str (org-add-props
  14654 		  (format-time-string tf (org-encode-time time))
  14655 		  nil 'mouse-face 'highlight))
  14656     (put-text-property beg end 'display str)))
  14657 
  14658 (defun org-fix-decoded-time (time)
  14659   "Set 0 instead of nil for the first 6 elements of time.
  14660 Don't touch the rest."
  14661   (let ((n 0))
  14662     (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  14663 
  14664 (defalias 'org-time-stamp-to-now #'org-timestamp-to-now)
  14665 (defun org-timestamp-to-now (timestamp-string &optional seconds)
  14666   "Difference between TIMESTAMP-STRING and now in days.
  14667 If SECONDS is non-nil, return the difference in seconds."
  14668   (let ((fdiff (if seconds #'float-time #'time-to-days)))
  14669     (- (funcall fdiff (org-time-string-to-time timestamp-string))
  14670        (funcall fdiff nil))))
  14671 
  14672 (defun org-deadline-close-p (timestamp-string &optional ndays)
  14673   "Is the time in TIMESTAMP-STRING close to the current date?"
  14674   (setq ndays (or ndays (org-get-wdays timestamp-string)))
  14675   (and (<= (org-timestamp-to-now timestamp-string) ndays)
  14676        (not (org-entry-is-done-p))))
  14677 
  14678 (defun org-get-wdays (ts &optional delay zero-delay)
  14679   "Get the deadline lead time appropriate for timestring TS.
  14680 When DELAY is non-nil, get the delay time for scheduled items
  14681 instead of the deadline lead time.  When ZERO-DELAY is non-nil
  14682 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  14683 don't try to find the delay cookie in the scheduled timestamp."
  14684   (let ((tv (if delay org-scheduled-delay-days
  14685 	      org-deadline-warning-days)))
  14686     (cond
  14687      ((or (and delay (< tv 0))
  14688 	  (and delay zero-delay (<= tv 0))
  14689 	  (and (not delay) (<= tv 0)))
  14690       ;; Enforce this value no matter what
  14691       (- tv))
  14692      ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  14693       ;; lead time is specified.
  14694       (floor (* (string-to-number (match-string 1 ts))
  14695 		(cdr (assoc (match-string 2 ts)
  14696 			    '(("d" . 1)    ("w" . 7)
  14697 			      ("m" . 30.4) ("y" . 365.25)
  14698 			      ("h" . 0.041667)))))))
  14699      ;; go for the default.
  14700      (t tv))))
  14701 
  14702 (defun org-calendar-select-mouse (ev)
  14703   "Return to `org-read-date' with the date currently selected.
  14704 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14705   (interactive "e")
  14706   (mouse-set-point ev)
  14707   (when (calendar-cursor-to-date)
  14708     (let* ((date (calendar-cursor-to-date))
  14709 	   (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14710       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14711     (when (active-minibuffer-window) (exit-minibuffer))))
  14712 
  14713 (defun org-check-deadlines (ndays)
  14714   "Check if there are any deadlines due or past due.
  14715 A deadline is considered due if it happens within `org-deadline-warning-days'
  14716 days from today's date.  If the deadline appears in an entry marked DONE,
  14717 it is not shown.  A numeric prefix argument NDAYS can be used to test that
  14718 many days.  If the prefix is a raw `\\[universal-argument]', all deadlines \
  14719 are shown."
  14720   (interactive "P")
  14721   (let* ((org-warn-days
  14722 	  (cond
  14723 	   ((equal ndays '(4)) 100000)
  14724 	   (ndays (prefix-numeric-value ndays))
  14725 	   (t (abs org-deadline-warning-days))))
  14726 	 (case-fold-search nil)
  14727 	 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  14728 	 (callback
  14729 	  (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  14730     (message "%d deadlines past-due or due within %d days"
  14731 	     (org-occur regexp nil callback)
  14732 	     org-warn-days)))
  14733 
  14734 (defsubst org-re-timestamp (type)
  14735   "Return a regexp for timestamp TYPE.
  14736 Allowed values for TYPE are:
  14737 
  14738         all: all timestamps
  14739      active: only active timestamps (<...>)
  14740    inactive: only inactive timestamps ([...])
  14741   scheduled: only scheduled timestamps
  14742    deadline: only deadline timestamps
  14743      closed: only closed timestamps
  14744 
  14745 When TYPE is nil, fall back on returning a regexp that matches
  14746 both scheduled and deadline timestamps."
  14747   (cl-case type
  14748     (all org-ts-regexp-both)
  14749     (active org-ts-regexp)
  14750     (inactive org-ts-regexp-inactive)
  14751     (scheduled org-scheduled-time-regexp)
  14752     (deadline org-deadline-time-regexp)
  14753     (closed org-closed-time-regexp)
  14754     (otherwise
  14755      (concat "\\<"
  14756 	     (regexp-opt (list org-deadline-string org-scheduled-string))
  14757 	     " *<\\([^>]+\\)>"))))
  14758 
  14759 (defun org-check-before-date (d)
  14760   "Check if there are deadlines or scheduled entries before date D."
  14761   (interactive (list (org-read-date)))
  14762   (let* ((case-fold-search nil)
  14763 	 (regexp (org-re-timestamp org-ts-type))
  14764 	 (ts-type org-ts-type)
  14765 	 (callback
  14766 	  (lambda ()
  14767 	    (let ((match (match-string 1)))
  14768 	      (and (if (memq ts-type '(active inactive all))
  14769 		       (org-element-type-p
  14770                         (save-excursion
  14771 			  (backward-char)
  14772 			  (org-element-context))
  14773 			'timestamp)
  14774 		     (org-at-planning-p))
  14775 		   (time-less-p
  14776 		    (org-time-string-to-time match)
  14777 		    (org-time-string-to-time d)))))))
  14778     (message "%d entries before %s"
  14779 	     (org-occur regexp nil callback)
  14780 	     d)))
  14781 
  14782 (defun org-check-after-date (d)
  14783   "Check if there are deadlines or scheduled entries after date D."
  14784   (interactive (list (org-read-date)))
  14785   (let* ((case-fold-search nil)
  14786 	 (regexp (org-re-timestamp org-ts-type))
  14787 	 (ts-type org-ts-type)
  14788 	 (callback
  14789 	  (lambda ()
  14790 	    (let ((match (match-string 1)))
  14791 	      (and (if (memq ts-type '(active inactive all))
  14792 		       (org-element-type-p
  14793                         (save-excursion
  14794 			  (backward-char)
  14795 			  (org-element-context))
  14796 			'timestamp)
  14797 		     (org-at-planning-p))
  14798 		   (not (time-less-p
  14799 		       (org-time-string-to-time match)
  14800 		       (org-time-string-to-time d))))))))
  14801     (message "%d entries after %s"
  14802 	     (org-occur regexp nil callback)
  14803 	     d)))
  14804 
  14805 (defun org-check-dates-range (start-date end-date)
  14806   "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  14807   (interactive (list (org-read-date nil nil nil "Range starts")
  14808 		     (org-read-date nil nil nil "Range end")))
  14809   (let ((case-fold-search nil)
  14810 	(regexp (org-re-timestamp org-ts-type))
  14811 	(callback
  14812 	 (let ((type org-ts-type))
  14813 	   (lambda ()
  14814 	     (let ((match (match-string 1)))
  14815 	       (and
  14816 		(if (memq type '(active inactive all))
  14817 		    (org-element-type-p
  14818                      (save-excursion
  14819 		       (backward-char)
  14820 		       (org-element-context))
  14821 		     'timestamp)
  14822 		  (org-at-planning-p))
  14823 		(not (time-less-p
  14824 		    (org-time-string-to-time match)
  14825 		    (org-time-string-to-time start-date)))
  14826 		(time-less-p
  14827 		 (org-time-string-to-time match)
  14828 		 (org-time-string-to-time end-date))))))))
  14829     (message "%d entries between %s and %s"
  14830 	     (org-occur regexp nil callback) start-date end-date)))
  14831 
  14832 (defun org-evaluate-time-range (&optional to-buffer)
  14833   "Evaluate a time range by computing the difference between start and end.
  14834 Normally the result is just printed in the echo area, but with prefix arg
  14835 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  14836 If the time range is actually in a table, the result is inserted into the
  14837 next column.
  14838 For time difference computation, a year is assumed to be exactly 365
  14839 days in order to avoid rounding problems."
  14840   (interactive "P")
  14841   (or
  14842    (org-clock-update-time-maybe)
  14843    (save-excursion
  14844      (unless (org-at-date-range-p t)
  14845        (goto-char (line-beginning-position))
  14846        (re-search-forward org-tr-regexp-both (line-end-position) t))
  14847      (unless (org-at-date-range-p t)
  14848        (user-error "Not at a timestamp range, and none found in current line")))
  14849    (let* ((ts1 (match-string 1))
  14850 	  (ts2 (match-string 2))
  14851 	  (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  14852 	  (match-end (match-end 0))
  14853 	  (time1 (org-time-string-to-time ts1))
  14854 	  (time2 (org-time-string-to-time ts2))
  14855 	  (diff (abs (float-time (time-subtract time2 time1))))
  14856 	  (negative (time-less-p time2 time1))
  14857 	  ;; (ys (floor (* 365 24 60 60)))
  14858 	  (ds (* 24 60 60))
  14859 	  (hs (* 60 60))
  14860 	  (fy "%dy %dd %02d:%02d")
  14861 	  (fy1 "%dy %dd")
  14862 	  (fd "%dd %02d:%02d")
  14863 	  (fd1 "%dd")
  14864 	  (fh "%02d:%02d")
  14865 	  y d h m align)
  14866      (if havetime
  14867 	 (setq ; y (floor diff ys)  diff (mod diff ys)
  14868 	  y 0
  14869 	  d (floor diff ds)  diff (mod diff ds)
  14870 	  h (floor diff hs)  diff (mod diff hs)
  14871 	  m (floor diff 60))
  14872        (setq ; y (floor diff ys)  diff (mod diff ys)
  14873 	y 0
  14874 	d (round diff ds)
  14875 	h 0 m 0))
  14876      (if (not to-buffer)
  14877 	 (message "%s" (org-make-tdiff-string y d h m))
  14878        (if (org-at-table-p)
  14879 	   (progn
  14880 	     (goto-char match-end)
  14881 	     (setq align t)
  14882 	     (and (looking-at " *|") (goto-char (match-end 0))))
  14883 	 (goto-char match-end))
  14884        (when (looking-at
  14885 	      "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  14886 	 (replace-match ""))
  14887        (when negative (insert " -"))
  14888        (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  14889 	 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  14890 	   (insert " " (format fh h m))))
  14891        (when align (org-table-align))
  14892        (message "Time difference inserted")))))
  14893 
  14894 (defun org-make-tdiff-string (y d h m)
  14895   (let ((fmt "")
  14896 	(l nil))
  14897     (when (> y 0)
  14898       (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  14899       (push y l))
  14900     (when (> d 0)
  14901       (setq fmt (concat fmt "%d day"  (if (> d 1) "s" "") " "))
  14902       (push d l))
  14903     (when (> h 0)
  14904       (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  14905       (push h l))
  14906     (when (> m 0)
  14907       (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  14908       (push m l))
  14909     (apply 'format fmt (nreverse l))))
  14910 
  14911 (defun org-time-string-to-time (s)
  14912   "Convert timestamp string S into internal time."
  14913   (org-encode-time (org-parse-time-string s)))
  14914 
  14915 (defun org-time-string-to-seconds (s)
  14916   "Convert a timestamp string S into a number of seconds."
  14917   (float-time (org-time-string-to-time s)))
  14918 
  14919 (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  14920 
  14921 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  14922   "Convert time stamp S to an absolute day number.
  14923 
  14924 If DAYNR in non-nil, and there is a specifier for a cyclic time
  14925 stamp, get the closest date to DAYNR.  If PREFER is
  14926 `past' (respectively `future') return a date past (respectively
  14927 after) or equal to DAYNR.
  14928 
  14929 POS is the location of time stamp S, as a buffer position in
  14930 BUFFER.
  14931 
  14932 Diary sexp timestamps are matched against DAYNR, when non-nil.
  14933 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  14934 signaled."
  14935   (cond
  14936    ((string-match "\\`%%\\((.*)\\)" s)
  14937     ;; Sexp timestamp: try to match DAYNR, if available, since we're
  14938     ;; only able to match individual dates.  If it fails, raise an
  14939     ;; error.
  14940     (if (and daynr
  14941 	     (org-diary-sexp-entry
  14942 	      (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  14943 	daynr
  14944       (signal 'org-diary-sexp-no-match (list s))))
  14945    (daynr (org-closest-date s daynr prefer))
  14946    (t (time-to-days
  14947        (condition-case errdata
  14948 	   (org-time-string-to-time s)
  14949 	 (error (error "Bad timestamp `%s'%s\nError was: %s"
  14950 		       s
  14951 		       (if (not (and buffer pos)) ""
  14952 			 (format-message " at %d in buffer `%s'" pos buffer))
  14953 		       (cdr errdata))))))))
  14954 
  14955 (defun org-days-to-iso-week (days)
  14956   "Return the ISO week number."
  14957   (require 'cal-iso)
  14958   (car (calendar-iso-from-absolute days)))
  14959 
  14960 (defun org-small-year-to-year (year)
  14961   "Convert 2-digit years into 4-digit years.
  14962 YEAR is expanded into one of the 30 next years, if possible, or
  14963 into a past one.  Any year larger than 99 is returned unchanged."
  14964   (if (>= year 100) year
  14965     (let* ((current (string-to-number (format-time-string "%Y")))
  14966 	   (century (/ current 100))
  14967 	   (offset (- year (% current 100))))
  14968       (cond ((> offset 30) (+ (* (1- century) 100) year))
  14969 	    ((> offset -70) (+ (* century 100) year))
  14970 	    (t (+ (* (1+ century) 100) year))))))
  14971 
  14972 (defun org-time-from-absolute (d)
  14973   "Return the time corresponding to date D.
  14974 D may be an absolute day number, or a calendar-type list (month day year)."
  14975   (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  14976   (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  14977 
  14978 (defvar org-agenda-current-date)
  14979 (defun org-calendar-holiday ()
  14980   "List of holidays, for Diary display in Org mode."
  14981   (require 'holidays)
  14982   (let ((hl (calendar-check-holidays org-agenda-current-date)))
  14983     (and hl (mapconcat #'identity hl "; "))))
  14984 
  14985 (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
  14986   "Hash table holding return values of `org-diary-sexp-entry'.")
  14987 (defun org-diary-sexp-entry (sexp entry d)
  14988   "Process a SEXP diary ENTRY for date D."
  14989   (require 'diary-lib)
  14990   ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  14991   ;; dynamically.
  14992   (let ((cached (gethash (list sexp entry d) org--diary-sexp-entry-cache 'none)))
  14993     (if (not (eq 'none cached)) cached
  14994       (puthash (list sexp entry d)
  14995                (let* ((sexp `(let ((entry ,entry)
  14996 		                   (date ',d))
  14997 		               ,(car (read-from-string sexp))))
  14998                       ;; FIXME: Do not use (eval ... t) in the following sexp as
  14999                       ;; diary vars are still using dynamic scope.
  15000 	              (result (if calendar-debug-sexp (eval sexp)
  15001 		                (condition-case nil
  15002 		                    (eval sexp)
  15003 		                  (error
  15004 		                   (beep)
  15005 		                   (message "Bad sexp at line %d in %s: %s"
  15006 			                    (org-current-line)
  15007 			                    (buffer-file-name) sexp)
  15008 		                   (sleep-for 2))))))
  15009                  (cond ((stringp result) (split-string result "; "))
  15010 	               ((and (consp result)
  15011 		             (not (consp (cdr result)))
  15012 		             (stringp (cdr result)))
  15013 	                (cdr result))
  15014 	               ((and (consp result)
  15015 		             (stringp (car result)))
  15016 	                result)
  15017 	               (result entry)))
  15018                org--diary-sexp-entry-cache))))
  15019 
  15020 (defun org-diary-to-ical-string (frombuf)
  15021   "Get iCalendar entries from diary entries in buffer FROMBUF.
  15022 This uses the icalendar.el library."
  15023   (let* ((tmpdir temporary-file-directory)
  15024 	 (tmpfile (make-temp-name
  15025 		   (expand-file-name "orgics" tmpdir)))
  15026 	 buf rtn b e)
  15027     (unwind-protect
  15028         (with-current-buffer frombuf
  15029           (icalendar-export-region (point-min) (point-max) tmpfile)
  15030           (setq buf (find-buffer-visiting tmpfile))
  15031           (set-buffer buf)
  15032           (goto-char (point-min))
  15033           (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15034 	    (setq b (match-beginning 0)))
  15035           (goto-char (point-max))
  15036           (when (re-search-backward "^END:VEVENT" nil t)
  15037 	    (setq e (match-end 0)))
  15038           (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15039       (when (and buf (buffer-live-p buf)) (kill-buffer buf))
  15040       (delete-file tmpfile))
  15041     rtn))
  15042 
  15043 (defun org-closest-date (start current prefer)
  15044   "Return closest date to CURRENT starting from START.
  15045 
  15046 CURRENT and START are both time stamps.
  15047 
  15048 When PREFER is `past', return a date that is either CURRENT or
  15049 past.  When PREFER is `future', return a date that is either
  15050 CURRENT or future.
  15051 
  15052 Only time stamps with a repeater are modified.  Any other time
  15053 stamp stay unchanged.  In any case, return value is an absolute
  15054 day number."
  15055   (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15056       ;; No repeater.  Do not shift time stamp.
  15057       (time-to-days (org-time-string-to-time start))
  15058     (let ((value (string-to-number (match-string 1 start)))
  15059 	  (type (match-string 2 start)))
  15060       (if (= 0 value)
  15061 	  ;; Repeater with a 0-value is considered as void.
  15062 	  (time-to-days (org-time-string-to-time start))
  15063 	(let* ((base (org-date-to-gregorian start))
  15064 	       (target (org-date-to-gregorian current))
  15065 	       (sday (calendar-absolute-from-gregorian base))
  15066 	       (cday (calendar-absolute-from-gregorian target))
  15067 	       n1 n2)
  15068 	  ;; If START is already past CURRENT, just return START.
  15069 	  (if (<= cday sday) sday
  15070 	    ;; Compute closest date before (N1) and closest date past
  15071 	    ;; (N2) CURRENT.
  15072 	    (pcase type
  15073 	      ("h"
  15074 	       (let ((missing-hours
  15075 		      (mod (+ (- (* 24 (- cday sday))
  15076 				 (nth 2 (org-parse-time-string start)))
  15077 			      org-extend-today-until)
  15078 			   value)))
  15079 		 (setf n1 (if (= missing-hours 0) cday
  15080 			    (- cday (1+ (/ missing-hours 24)))))
  15081 		 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15082 	      ((or "d" "w")
  15083 	       (let ((value (if (equal type "w") (* 7 value) value)))
  15084 		 (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15085 		 (setf n2 (+ n1 value))))
  15086 	      ("m"
  15087 	       (let* ((add-months
  15088 		       (lambda (d n)
  15089 			 ;; Add N months to gregorian date D, i.e.,
  15090 			 ;; a list (MONTH DAY YEAR).  Return a valid
  15091 			 ;; gregorian date.
  15092 			 (let ((m (+ (nth 0 d) n)))
  15093 			   (list (mod m 12)
  15094 				 (nth 1 d)
  15095 				 (+ (/ m 12) (nth 2 d))))))
  15096 		      (months		; Complete months to TARGET.
  15097 		       (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15098 				(- (nth 0 target) (nth 0 base))
  15099 				;; If START's day is greater than
  15100 				;; TARGET's, remove incomplete month.
  15101 				(if (> (nth 1 target) (nth 1 base)) 0 -1))
  15102 			     value)
  15103 			  value))
  15104 		      (before (funcall add-months base months)))
  15105 		 (setf n1 (calendar-absolute-from-gregorian before))
  15106 		 (setf n2
  15107 		       (calendar-absolute-from-gregorian
  15108 			(funcall add-months before value)))))
  15109 	      (_
  15110 	       (let* ((d (nth 1 base))
  15111 		      (m (nth 0 base))
  15112 		      (y (nth 2 base))
  15113 		      (years		; Complete years to TARGET.
  15114 		       (* (/ (- (nth 2 target)
  15115 				y
  15116 				;; If START's month and day are
  15117 				;; greater than TARGET's, remove
  15118 				;; incomplete year.
  15119 				(if (or (> (nth 0 target) m)
  15120 					(and (= (nth 0 target) m)
  15121 					     (> (nth 1 target) d)))
  15122 				    0
  15123 				  1))
  15124 			     value)
  15125 			  value))
  15126 		      (before (list m d (+ y years))))
  15127 		 (setf n1 (calendar-absolute-from-gregorian before))
  15128 		 (setf n2 (calendar-absolute-from-gregorian
  15129 			   (list m d (+ (nth 2 before) value)))))))
  15130 	    ;; Handle PREFER parameter, if any.
  15131 	    (cond
  15132 	     ((eq prefer 'past)   (if (= cday n2) n2 n1))
  15133 	     ((eq prefer 'future) (if (= cday n1) n1 n2))
  15134 	     (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15135 
  15136 (defun org-date-to-gregorian (d)
  15137   "Turn any specification of date D into a Gregorian date for the calendar."
  15138   (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15139 	((and (listp d) (= (length d) 3)) d)
  15140 	((stringp d)
  15141 	 (let ((d (org-parse-time-string d)))
  15142 	   (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15143 	((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15144 
  15145 (defun org-timestamp-up (&optional arg)
  15146   "Increase the date item at the cursor by one.
  15147 If the cursor is on the year, change the year.  If it is on the month,
  15148 the day or the time, change that.  If the cursor is on the enclosing
  15149 bracket, change the timestamp type.
  15150 With prefix ARG, change by that many units."
  15151   (interactive "p")
  15152   (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15153 
  15154 (defun org-timestamp-down (&optional arg)
  15155   "Decrease the date item at the cursor by one.
  15156 If the cursor is on the year, change the year.  If it is on the month,
  15157 the day or the time, change that.  If the cursor is on the enclosing
  15158 bracket, change the timestamp type.
  15159 With prefix ARG, change by that many units."
  15160   (interactive "p")
  15161   (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15162 
  15163 (defun org-timestamp-up-day (&optional arg)
  15164   "Increase the date in the time stamp by one day.
  15165 With prefix ARG, change that many days."
  15166   (interactive "p")
  15167   (if (and (not (org-at-timestamp-p 'lax))
  15168 	   (org-at-heading-p))
  15169       (org-todo 'up)
  15170     (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15171 
  15172 (defun org-timestamp-down-day (&optional arg)
  15173   "Decrease the date in the time stamp by one day.
  15174 With prefix ARG, change that many days."
  15175   (interactive "p")
  15176   (if (and (not (org-at-timestamp-p 'lax))
  15177 	   (org-at-heading-p))
  15178       (org-todo 'down)
  15179     (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15180 
  15181 (defun org-at-timestamp-p (&optional extended)
  15182   "Non-nil if point is inside a timestamp.
  15183 
  15184 By default, the function only consider syntactically valid active
  15185 timestamps.  However, the caller may have a broader definition
  15186 for timestamps.  As a consequence, optional argument EXTENDED can
  15187 be set to the following values
  15188 
  15189   `inactive'
  15190 
  15191     Include also syntactically valid inactive timestamps.
  15192 
  15193   `agenda'
  15194 
  15195     Include timestamps allowed in Agenda, i.e., those in
  15196     properties drawers, planning lines and clock lines.
  15197 
  15198   `lax'
  15199 
  15200     Ignore context.  The function matches any part of the
  15201     document looking like a timestamp.  This includes comments,
  15202     example blocks...
  15203 
  15204 For backward-compatibility with Org 9.0, every other non-nil
  15205 value is equivalent to `inactive'.
  15206 
  15207 When at a timestamp, return the position of the point as a symbol
  15208 among `bracket', `after', `year', `month', `hour', `minute',
  15209 `day' or a number of character from the last know part of the
  15210 time stamp.  If diary sexp timestamps, any point inside the timestamp
  15211 is considered `day' (i.e. only `bracket', `day', and `after' return
  15212 values are possible).
  15213 
  15214 When matching, the match groups are the following:
  15215   group 2: year, if any
  15216   group 3: month, if any
  15217   group 4: day number, if any
  15218   group 5: day name, if any
  15219   group 7: hours, if any
  15220   group 8: minutes, if any"
  15221   (let* ((regexp
  15222           (if extended
  15223               (if (eq extended 'agenda)
  15224                   (rx-to-string
  15225                    `(or (regexp ,org-ts-regexp3)
  15226                         (regexp ,org-element--timestamp-regexp)))
  15227 		org-ts-regexp3)
  15228             org-ts-regexp2))
  15229 	 (pos (point))
  15230 	 (match?
  15231 	  (let ((boundaries (org-in-regexp regexp)))
  15232 	    (save-match-data
  15233 	      (cond ((null boundaries) nil)
  15234 		    ((eq extended 'lax) t)
  15235 		    (t
  15236 		     (or (and (eq extended 'agenda)
  15237 			      (or (org-at-planning-p)
  15238 				  (org-at-property-p)
  15239 				  (and (bound-and-true-p
  15240 					org-agenda-include-inactive-timestamps)
  15241 				       (org-at-clock-log-p))))
  15242 			 (eq 'timestamp
  15243 			     (save-excursion
  15244 			       (when (= pos (cdr boundaries)) (forward-char -1))
  15245 			       (org-element-type (org-element-context)))))))))))
  15246     (cond
  15247      ((not match?)                        nil)
  15248      ((= pos (match-beginning 0))         'bracket)
  15249      ;; Distinguish location right before the closing bracket from
  15250      ;; right after it.
  15251      ((= pos (1- (match-end 0)))          'bracket)
  15252      ((= pos (match-end 0))               'after)
  15253      ((org-pos-in-match-range pos 2)      'year)
  15254      ((org-pos-in-match-range pos 3)      'month)
  15255      ((org-pos-in-match-range pos 7)      'hour)
  15256      ((org-pos-in-match-range pos 8)      'minute)
  15257      ((or (org-pos-in-match-range pos 4)
  15258 	  (org-pos-in-match-range pos 5)) 'day)
  15259      ((and (or (match-end 8) (match-end 5))
  15260            (> pos (or (match-end 8) (match-end 5)))
  15261 	   (< pos (match-end 0)))
  15262       (- pos (or (match-end 8) (match-end 5))))
  15263      (t                                   'day))))
  15264 
  15265 (defun org-toggle-timestamp-type ()
  15266   "Toggle the type (<active> or [inactive]) of a time stamp."
  15267   (interactive)
  15268   (when (org-at-timestamp-p 'lax)
  15269     (let ((beg (match-beginning 0)) (end (match-end 0))
  15270 	  (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15271       (save-excursion
  15272 	(goto-char beg)
  15273 	(while (re-search-forward "[][<>]" end t)
  15274 	  (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15275 			 t t)))
  15276       (message "Timestamp is now %sactive"
  15277 	       (if (equal (char-after beg) ?<) "" "in")))))
  15278 
  15279 (defun org-at-clock-log-p ()
  15280   "Non-nil if point is on a clock log line."
  15281   (and (org-match-line org-clock-line-re)
  15282        (org-element-type-p
  15283         (save-match-data (org-element-at-point))
  15284         'clock)))
  15285 
  15286 (defvar org-clock-history)                     ; defined in org-clock.el
  15287 (defvar org-clock-adjust-closest nil)          ; defined in org-clock.el
  15288 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15289   "Change the date in the time stamp at point.
  15290 
  15291 The date is changed by N times WHAT.  WHAT can be `day', `month',
  15292 `year', `hour', or `minute'.  If WHAT is not given, the cursor
  15293 position in the timestamp determines what is changed.
  15294 
  15295 When optional argument UPDOWN is non-nil, minutes are rounded
  15296 according to `org-timestamp-rounding-minutes'.
  15297 
  15298 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  15299 \"--2d\"."
  15300   (let ((origin (point))
  15301 	(timestamp? (org-at-timestamp-p 'lax))
  15302 	origin-cat
  15303 	with-hm inactive
  15304 	(dm (max (nth 1 org-timestamp-rounding-minutes) 1))
  15305 	extra rem
  15306 	ts time time0 fixnext clrgx)
  15307     (unless timestamp? (user-error "Not at a timestamp"))
  15308     (if (and (not what) (eq timestamp? 'bracket))
  15309 	(org-toggle-timestamp-type)
  15310       ;; Point isn't on brackets.  Remember the part of the timestamp
  15311       ;; the point was in.  Indeed, size of timestamps may change,
  15312       ;; but point must be kept in the same category nonetheless.
  15313       (setq origin-cat timestamp?)
  15314       (when (and (not what) (not (eq timestamp? 'day))
  15315 		 org-display-custom-times
  15316 		 (get-text-property (point) 'display)
  15317 		 (not (get-text-property (1- (point)) 'display)))
  15318 	(setq timestamp? 'day))
  15319       (setq timestamp? (or what timestamp?)
  15320 	    inactive (= (char-after (match-beginning 0)) ?\[)
  15321 	    ts (match-string 0))
  15322       ;; FIXME: Instead of deleting everything and then inserting
  15323       ;; later, we should make use of `replace-match', which preserves
  15324       ;; markers.  The current implementation suffers from
  15325       ;; `save-excursion' not preserving point inside the timestamp
  15326       ;; once we delete the timestamp here.  The point moves to the
  15327       ;; updated timestamp end.
  15328       (replace-match "")
  15329       (when (string-match
  15330 	     "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15331 	     ts)
  15332 	(setq extra (match-string 1 ts))
  15333 	(when suppress-tmp-delay
  15334 	  (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15335       (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15336 	(setq with-hm t))
  15337       (setq time0 (org-parse-time-string ts))
  15338       (let ((increment n))
  15339         (if (and updown
  15340 	         (eq timestamp? 'minute)
  15341 	         (not current-prefix-arg))
  15342 	    ;; This looks like s-up and s-down.  Change by one rounding step.
  15343             (progn
  15344 	      (setq increment (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15345 	      (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15346 	        (setcar (cdr time0) (+ (nth 1 time0)
  15347 				       (if (> n 0) (- rem) (- dm rem))))))
  15348           ;; Do not round anything in `org-modify-ts-extra' when prefix
  15349           ;; argument is supplied - just use whatever is provided by the
  15350           ;; prefix argument.
  15351           (setq dm 1))
  15352         (setq time
  15353 	      (org-encode-time
  15354                (apply #'list
  15355                       (or (car time0) 0)
  15356                       (+ (if (eq timestamp? 'minute) increment 0) (nth 1 time0))
  15357                       (+ (if (eq timestamp? 'hour) increment 0)   (nth 2 time0))
  15358                       (+ (if (eq timestamp? 'day) increment 0)    (nth 3 time0))
  15359                       (+ (if (eq timestamp? 'month) increment 0)  (nth 4 time0))
  15360                       (+ (if (eq timestamp? 'year) increment 0)   (nth 5 time0))
  15361                       (nthcdr 6 time0)))))
  15362       (when (and (memq timestamp? '(hour minute))
  15363 		 extra
  15364 		 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15365         ;; When modifying the start time in HH:MM-HH:MM range, update
  15366         ;; end time as well.
  15367 	(setq extra (org-modify-ts-extra
  15368 		     extra ;; -HH:MM ...
  15369                      ;; Fake position in EXTRA to force changing hours
  15370                      ;; or minutes as needed.
  15371 		     (if (eq timestamp? 'hour)
  15372                          2 ;; -H<H>:MM
  15373                        5) ;; -HH:M<M>
  15374 		     n dm)))
  15375       (when (integerp timestamp?)
  15376 	(setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15377       (when (eq what 'calendar)
  15378 	(let ((cal-date (org-get-date-from-calendar)))
  15379 	  (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15380 	  (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15381 	  (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15382 	  (setcar time0 (or (car time0) 0))
  15383 	  (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15384 	  (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15385 	  (setq time (org-encode-time time0))))
  15386       ;; Insert the new timestamp, and ensure point stays in the same
  15387       ;; category as before (i.e. not after the last position in that
  15388       ;; category).
  15389       (let ((pos (point)))
  15390 	;; Stay before inserted string. `save-excursion' is of no use.
  15391 	(setq org-last-changed-timestamp
  15392 	      (org-insert-timestamp time with-hm inactive nil nil extra))
  15393 	(goto-char pos))
  15394       (save-match-data
  15395 	(looking-at org-ts-regexp3)
  15396 	(goto-char
  15397 	 (pcase origin-cat
  15398 	   ;; `day' category ends before `hour' if any, or at the end
  15399 	   ;; of the day name.
  15400 	   (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15401 	   (`hour (min (match-end 7) origin))
  15402 	   (`minute (min (1- (match-end 8)) origin))
  15403 	   ((pred integerp) (min (1- (match-end 0)) origin))
  15404 	   ;; Point was right after the timestamp.  However, the
  15405 	   ;; timestamp length might have changed, so refer to
  15406 	   ;; (match-end 0) instead.
  15407 	   (`after (match-end 0))
  15408 	   ;; `year' and `month' have both fixed size: point couldn't
  15409 	   ;; have moved into another part.
  15410 	   (_ origin))))
  15411       ;; Update clock if on a CLOCK line.
  15412       (org-clock-update-time-maybe)
  15413       ;; Maybe adjust the closest clock in `org-clock-history'
  15414       (when org-clock-adjust-closest
  15415 	(if (not (and (org-at-clock-log-p)
  15416 		      (< 1 (length (delq nil (mapcar 'marker-position
  15417 						     org-clock-history))))))
  15418 	    (message "No clock to adjust")
  15419 	  (cond ((save-excursion	; fix previous clock?
  15420 		   (re-search-backward org-ts-regexp0 nil t)
  15421 		   (looking-back (concat org-clock-string " \\[")
  15422 				 (line-beginning-position)))
  15423 		 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15424 		((save-excursion	; fix next clock?
  15425 		   (re-search-backward org-ts-regexp0 nil t)
  15426 		   (looking-at (concat org-ts-regexp0 "\\] =>")))
  15427 		 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15428 	  (save-window-excursion
  15429 	    ;; Find closest clock to point, adjust the previous/next one in history
  15430 	    (let* ((p (save-excursion (org-back-to-heading t)))
  15431 		   (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15432 		   (clfixnth
  15433 		    (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15434 		   (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15435 	      (if (not clfixpos)
  15436 		  (message "No clock to adjust")
  15437 		(save-excursion
  15438 		  (org-goto-marker-or-bmk clfixpos)
  15439 		  (org-fold-show-subtree)
  15440 		  (when (re-search-forward clrgx nil t)
  15441 		    (goto-char (match-beginning 1))
  15442 		    (let (org-clock-adjust-closest)
  15443 		      (org-timestamp-change n timestamp? updown))
  15444 		    (message "Clock adjusted in %s for heading: %s"
  15445 			     (file-name-nondirectory (buffer-file-name))
  15446 			     (org-get-heading t t)))))))))
  15447       ;; Try to recenter the calendar window, if any.
  15448       (when (and org-calendar-follow-timestamp-change
  15449 		 (get-buffer-window calendar-buffer t)
  15450 		 (memq timestamp? '(day month year)))
  15451 	(org-recenter-calendar (time-to-days time))))))
  15452 
  15453 (defun org-modify-ts-extra (ts-string pos nincrements increment-step)
  15454   "Change the lead-time/repeat fields at POS in timestamp string TS-STRING.
  15455 POS is the position in the timestamp string to be changed.
  15456 NINCREMENTS is the number of increments/decrements.
  15457 
  15458 INCREMENT-STEP is step used for a single increment when POS in on
  15459 minutes.  Before incrementing minutes, they are rounded to
  15460 INCREMENT-STEP divisor."
  15461   (let (;; increment order for dwmy: d-1=d; d+1=w; w+1=m; m+1=y; y+1=y.
  15462         (idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15463 	pos-match-group hour minute new rem)
  15464     (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" ts-string)
  15465       (cond
  15466        ((or (org-pos-in-match-range pos 2) ;; POS in end hours
  15467 	    (org-pos-in-match-range pos 3)) ;; POS in end minutes
  15468 	(setq minute (string-to-number (match-string 3 ts-string))
  15469 	      hour (string-to-number (match-string 2 ts-string)))
  15470 	(if (org-pos-in-match-range pos 2) ;; POS in end hours
  15471             ;; INCREMENT-STEP is only applicable to MINUTE.
  15472 	    (setq hour (+ hour nincrements))
  15473 	  (setq nincrements (* increment-step nincrements))
  15474 	  (unless (= 0 (setq rem (% minute increment-step)))
  15475             ;; Round the MINUTE to INCREMENT-STEP.
  15476 	    (setq minute (+ minute (if (> nincrements 0) (- rem) (- increment-step rem)))))
  15477 	  (setq minute (+ minute nincrements)))
  15478 	(when (< minute 0) (setq minute (+ minute 60) hour (1- hour)))
  15479 	(when (> minute 59) (setq minute (- minute 60) hour (1+ hour)))
  15480 	(setq hour (mod hour 24))
  15481 	(setq pos-match-group 1
  15482               new (format "-%02d:%02d" hour minute)))
  15483 
  15484        ((org-pos-in-match-range pos 6) ;; POS on "dmwy" repeater char.
  15485 	(setq pos-match-group 6
  15486               new (car (rassoc (+ nincrements (cdr (assoc (match-string 6 ts-string) idx))) idx))))
  15487 
  15488        ((org-pos-in-match-range pos 5) ;; POS on X in "Xd" repeater.
  15489 	(setq pos-match-group 5
  15490               ;; Never drop below X=1.
  15491               new (format "%d" (max 1 (+ nincrements (string-to-number (match-string 5 ts-string)))))))
  15492 
  15493        ((org-pos-in-match-range pos 9) ;; POS on "dmwy" repeater in warning interval.
  15494 	(setq pos-match-group 9
  15495               new (car (rassoc (+ nincrements (cdr (assoc (match-string 9 ts-string) idx))) idx))))
  15496 
  15497        ((org-pos-in-match-range pos 8) ;; POS on X in "Xd" in warning interval.
  15498 	(setq pos-match-group 8
  15499               ;; Never drop below X=0.
  15500               new (format "%d" (max 0 (+ nincrements (string-to-number (match-string 8 ts-string))))))))
  15501 
  15502       (when pos-match-group
  15503 	(setq ts-string (concat
  15504 		         (substring ts-string 0 (match-beginning pos-match-group))
  15505 		         new
  15506 		         (substring ts-string (match-end pos-match-group))))))
  15507     ts-string))
  15508 
  15509 (defun org-recenter-calendar (d)
  15510   "If the calendar is visible, recenter it to date D."
  15511   (let ((cwin (get-buffer-window calendar-buffer t)))
  15512     (when cwin
  15513       (let ((calendar-move-hook nil))
  15514 	(with-selected-window cwin
  15515 	  (calendar-goto-date
  15516 	   (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15517 
  15518 (defun org-goto-calendar (&optional arg)
  15519   "Go to the Emacs calendar at the current date.
  15520 If there is a time stamp in the current line, go to that date.
  15521 A prefix ARG can be used to force the current date."
  15522   (interactive "P")
  15523   (let ((calendar-move-hook nil)
  15524 	(calendar-view-holidays-initially-flag nil)
  15525 	(calendar-view-diary-initially-flag nil)
  15526 	diff)
  15527     (when (or (org-at-timestamp-p 'lax)
  15528 	      (org-match-line (concat ".*" org-ts-regexp)))
  15529       (let ((d1 (time-to-days nil))
  15530 	    (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15531 	(setq diff (- d2 d1))))
  15532     (calendar)
  15533     (calendar-goto-today)
  15534     (when (and diff (not arg)) (calendar-forward-day diff))))
  15535 
  15536 (defun org-get-date-from-calendar ()
  15537   "Return a list (month day year) of date at point in calendar."
  15538   (with-current-buffer calendar-buffer
  15539     (save-match-data
  15540       (calendar-cursor-to-date))))
  15541 
  15542 (defun org-date-from-calendar ()
  15543   "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15544 If there is already a time stamp at the cursor position, update it."
  15545   (interactive)
  15546   (if (org-at-timestamp-p 'lax)
  15547       (org-timestamp-change 0 'calendar)
  15548     (let ((cal-date (org-get-date-from-calendar)))
  15549       (org-insert-timestamp
  15550        (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15551 
  15552 (defcustom org-image-actual-width t
  15553   "When non-nil, use the actual width of images when inlining them.
  15554 
  15555 When set to a number, use imagemagick (when available) to set the
  15556 image's width to this value.
  15557 
  15558 When set to a number in a list, try to get the width from any
  15559 #+ATTR.* keyword if it matches a width specification like
  15560 
  15561   #+ATTR_HTML: :width 300px
  15562 
  15563 and fall back on that number if none is found.
  15564 
  15565 When set to nil, first try to get the width from #+ATTR_ORG.  If
  15566 that is not found, use the first #+ATTR_xxx :width specification.
  15567 If that is also not found, fall back on the original image width.
  15568 
  15569 Finally, Org mode is quite flexible in the width specifications it
  15570 supports and intelligently interprets width specifications for other
  15571 backends when rendering an image in an org buffer.  This behavior is
  15572 described presently.
  15573 
  15574 1. A floating point value between 0 and 2 is interpreted as the
  15575    percentage of the text area that should be taken up by the image.
  15576 2. A number followed by a percent sign is divided by 100 and then
  15577    interpreted as a floating point value.
  15578 3. If a number is followed by other text, extract the number and
  15579    discard the remaining text.  That number is then interpreted as a
  15580    floating-point value.  For example,
  15581 
  15582    #+ATTR_LATEX: :width 0.7\\linewidth
  15583 
  15584    would be interpreted as 70% of the text width.
  15585 4. If t is provided the original image width is used.  This is useful
  15586    when you want to specify a width for a backend, but still want to
  15587    use the original image width in the org buffer.
  15588 
  15589 This requires Emacs >= 24.1, built with imagemagick support."
  15590   :group 'org-appearance
  15591   :version "24.4"
  15592   :package-version '(Org . "8.0")
  15593   :type '(choice
  15594 	  (const :tag "Use the image width" t)
  15595 	  (integer :tag "Use a number of pixels")
  15596 	  (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15597 	  (const :tag "Use #+ATTR* or don't resize" nil)))
  15598 
  15599 (defcustom org-image-max-width 'fill-column
  15600   "When non-nil, limit the displayed image width.
  15601 This setting only takes effect when `org-image-actual-width' is set to
  15602 t or when #+ATTR* is set to t.
  15603 
  15604 Possible values:
  15605 - `fill-column' :: limit width to `fill-column'
  15606 - `window'      :: limit width to window width
  15607 - integer       :: limit width to number in pixels
  15608 - float         :: limit width to that fraction of window width
  15609 - nil             :: do not limit image width"
  15610   :group 'org-appearance
  15611   :package-version '(Org . "9.7")
  15612   :type '(choice
  15613           (const :tag "Do not limit image width" nil)
  15614           (const :tag "Limit to `fill-column'" fill-column)
  15615           (const :tag "Limit to window width" window)
  15616           (integer :tag "Limit to a number of pixels")
  15617           (float :tag "Limit to a fraction of window width")))
  15618 
  15619 (defcustom org-agenda-inhibit-startup nil
  15620   "Inhibit startup when preparing agenda buffers.
  15621 When this variable is t, the initialization of the Org agenda
  15622 buffers is inhibited: e.g. the visibility state is not set, the
  15623 tables are not re-aligned, etc."
  15624   :type 'boolean
  15625   :version "24.3"
  15626   :group 'org-agenda)
  15627 
  15628 (defcustom org-agenda-ignore-properties nil
  15629   "Avoid updating text properties when building the agenda.
  15630 Properties are used to prepare buffers for effort estimates,
  15631 appointments, statistics and subtree-local categories.
  15632 If you don't use these in the agenda, you can add them to this
  15633 list and agenda building will be a bit faster.
  15634 The value is a list, with symbol `stats'."
  15635   :type '(set :greedy t
  15636 	      (const stats))
  15637   :package-version '(Org . "9.7")
  15638   :group 'org-agenda)
  15639 
  15640 ;;;; Files
  15641 
  15642 (defun org-save-all-org-buffers ()
  15643   "Save all Org buffers without user confirmation."
  15644   (interactive)
  15645   (message "Saving all Org buffers...")
  15646   (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  15647   (when (featurep 'org-id) (org-id-locations-save))
  15648   (message "Saving all Org buffers... done"))
  15649 
  15650 (defun org-revert-all-org-buffers ()
  15651   "Revert all Org buffers.
  15652 Prompt for confirmation when there are unsaved changes.
  15653 Be sure you know what you are doing before letting this function
  15654 overwrite your changes.
  15655 
  15656 This function is useful in a setup where one tracks Org files
  15657 with a version control system, to revert on one machine after pulling
  15658 changes from another.  I believe the procedure must be like this:
  15659 
  15660 1. \\[org-save-all-org-buffers]
  15661 2. Pull changes from the other machine, resolve conflicts
  15662 3. \\[org-revert-all-org-buffers]"
  15663   (interactive)
  15664   (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  15665     (user-error "Abort"))
  15666   (save-excursion
  15667     (save-window-excursion
  15668       (dolist (b (buffer-list))
  15669 	(when (and (with-current-buffer b (derived-mode-p 'org-mode))
  15670 		   (with-current-buffer b buffer-file-name))
  15671 	  (pop-to-buffer-same-window b)
  15672 	  (revert-buffer t 'no-confirm)))
  15673       (when (and (featurep 'org-id) org-id-track-globally)
  15674 	(org-id-locations-load)))))
  15675 
  15676 ;;;; Agenda files
  15677 
  15678 ;;;###autoload
  15679 (defun org-switchb (&optional arg)
  15680   "Switch between Org buffers.
  15681 
  15682 With `\\[universal-argument]' prefix, restrict available buffers to files.
  15683 
  15684 With `\\[universal-argument] \\[universal-argument]' \
  15685 prefix, restrict available buffers to agenda files."
  15686   (interactive "P")
  15687   (let ((blist (org-buffer-list
  15688 		(cond ((equal arg '(4))  'files)
  15689 		      ((equal arg '(16)) 'agenda)))))
  15690     (pop-to-buffer-same-window
  15691      (completing-read "Org buffer: "
  15692 		      (mapcar #'list (mapcar #'buffer-name blist))
  15693 		      nil t))))
  15694 
  15695 (defun org-agenda-files (&optional unrestricted archives)
  15696   "Get the list of agenda files.
  15697 Optional UNRESTRICTED means return the full list even if a restriction
  15698 is currently in place.
  15699 When ARCHIVES is t, include all archive files that are really being
  15700 used by the agenda files.  If ARCHIVE is `ifmode', do this only if
  15701 `org-agenda-archives-mode' is t."
  15702   (let ((files
  15703 	 (cond
  15704 	  ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  15705 	  ((stringp org-agenda-files) (org-read-agenda-file-list))
  15706 	  ((listp org-agenda-files) org-agenda-files)
  15707 	  (t (error "Invalid value of `org-agenda-files'")))))
  15708     (setq files (apply 'append
  15709 		       (mapcar (lambda (f)
  15710 				 (if (file-directory-p f)
  15711 				     (directory-files
  15712 				      f t org-agenda-file-regexp)
  15713 				   (list (expand-file-name f org-directory))))
  15714 			       files)))
  15715     (when org-agenda-skip-unavailable-files
  15716       (setq files (delq nil
  15717 			(mapcar (lambda (file)
  15718 				  (and (file-readable-p file) file))
  15719 				files))))
  15720     (when (or (eq archives t)
  15721 	      (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  15722       (setq files (org-add-archive-files files)))
  15723     (delete-dups files)))
  15724 
  15725 (defun org-agenda-file-p (&optional file)
  15726   "Return non-nil, if FILE is an agenda file.
  15727 If FILE is omitted, use the file associated with the current
  15728 buffer."
  15729   (let ((fname (or file (buffer-file-name))))
  15730     (and fname
  15731          (member (file-truename fname)
  15732                  (mapcar #'file-truename (org-agenda-files t))))))
  15733 
  15734 (defun org-edit-agenda-file-list ()
  15735   "Edit the list of agenda files.
  15736 Depending on setup, this either uses customize to edit the variable
  15737 `org-agenda-files', or it visits the file that is holding the list.  In the
  15738 latter case, the buffer is set up in a way that saving it automatically kills
  15739 the buffer and restores the previous window configuration."
  15740   (interactive)
  15741   (if (stringp org-agenda-files)
  15742       (let ((cw (current-window-configuration)))
  15743 	(find-file org-agenda-files)
  15744 	(setq-local org-window-configuration cw)
  15745 	(add-hook 'after-save-hook
  15746 		  (lambda ()
  15747 		    (set-window-configuration
  15748 		     (prog1 org-window-configuration
  15749 		       (kill-buffer (current-buffer))))
  15750 		    (org-install-agenda-files-menu)
  15751 		    (message "New agenda file list installed"))
  15752 		  nil 'local)
  15753 	(message "%s" (substitute-command-keys
  15754 		       "Edit list and finish with \\[save-buffer]")))
  15755     (customize-variable 'org-agenda-files)))
  15756 
  15757 (defun org-store-new-agenda-file-list (list)
  15758   "Set new value for the agenda file list and save it correctly."
  15759   (if (stringp org-agenda-files)
  15760       (let ((fe (org-read-agenda-file-list t)) b u)
  15761 	(while (setq b (find-buffer-visiting org-agenda-files))
  15762 	  (kill-buffer b))
  15763 	(with-temp-file org-agenda-files
  15764 	  (insert
  15765 	   (mapconcat
  15766 	    (lambda (f) ;; Keep un-expanded entries.
  15767 	      (if (setq u (assoc f fe))
  15768 		  (cdr u)
  15769 		f))
  15770 	    list "\n")
  15771 	   "\n")))
  15772     (let ((org-mode-hook nil) (org-inhibit-startup t)
  15773 	  (org-insert-mode-line-in-empty-file nil))
  15774       (setq org-agenda-files list)
  15775       (customize-save-variable 'org-agenda-files org-agenda-files))))
  15776 
  15777 (defun org-read-agenda-file-list (&optional pair-with-expansion)
  15778   "Read the list of agenda files from a file.
  15779 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  15780 filenames, used by `org-store-new-agenda-file-list' to write back
  15781 un-expanded file names."
  15782   (when (file-directory-p org-agenda-files)
  15783     (error "`org-agenda-files' cannot be a single directory"))
  15784   (when (stringp org-agenda-files)
  15785     (with-temp-buffer
  15786       (insert-file-contents org-agenda-files)
  15787       (mapcar
  15788        (lambda (f)
  15789 	 (let ((e (expand-file-name (substitute-in-file-name f)
  15790 				    org-directory)))
  15791 	   (if pair-with-expansion
  15792 	       (cons e f)
  15793 	     e)))
  15794        (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  15795 
  15796 ;;;###autoload
  15797 (defun org-cycle-agenda-files ()
  15798   "Cycle through the files in `org-agenda-files'.
  15799 If the current buffer visits an agenda file, find the next one in the list.
  15800 If the current buffer does not, find the first agenda file."
  15801   (interactive)
  15802   (let* ((fs (or (org-agenda-files t)
  15803 		 (user-error "No agenda files")))
  15804 	 (files (copy-sequence fs))
  15805 	 (tcf (and buffer-file-name (file-truename buffer-file-name)))
  15806 	 file)
  15807     (when tcf
  15808       (while (and (setq file (pop files))
  15809 		  (not (equal (file-truename file) tcf)))))
  15810     (find-file (car (or files fs)))
  15811     (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  15812 
  15813 (defun org-agenda-file-to-front (&optional to-end)
  15814   "Move/add the current file to the top of the agenda file list.
  15815 If the file is not present in the list, it is added to the front.  If it is
  15816 present, it is moved there.  With optional argument TO-END, add/move to the
  15817 end of the list."
  15818   (interactive "P")
  15819   (let ((org-agenda-skip-unavailable-files nil)
  15820 	(file-alist (mapcar (lambda (x)
  15821 			      (cons (file-truename x) x))
  15822 			    (org-agenda-files t)))
  15823 	(ctf (file-truename
  15824 	      (or buffer-file-name
  15825 		  (user-error "Please save the current buffer to a file"))))
  15826 	x had)
  15827     (setq x (assoc ctf file-alist) had x)
  15828 
  15829     (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  15830     (if to-end
  15831 	(setq file-alist (append (delq x file-alist) (list x)))
  15832       (setq file-alist (cons x (delq x file-alist))))
  15833     (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  15834     (org-install-agenda-files-menu)
  15835     (message "File %s to %s of agenda file list"
  15836 	     (if had "moved" "added") (if to-end "end" "front"))))
  15837 
  15838 (defun org-remove-file (&optional file)
  15839   "Remove current file from the list of files in variable `org-agenda-files'.
  15840 These are the files which are being checked for agenda entries.
  15841 Optional argument FILE means use this file instead of the current."
  15842   (interactive)
  15843   (let* ((org-agenda-skip-unavailable-files nil)
  15844 	 (file (or file buffer-file-name
  15845 		   (user-error "Current buffer does not visit a file")))
  15846 	 (true-file (file-truename file))
  15847 	 (afile (abbreviate-file-name file))
  15848 	 (files (delq nil (mapcar
  15849 			   (lambda (x)
  15850 			     (unless (equal true-file
  15851 					    (file-truename x))
  15852 			       x))
  15853 			   (org-agenda-files t)))))
  15854     (if (not (= (length files) (length (org-agenda-files t))))
  15855 	(progn
  15856 	  (org-store-new-agenda-file-list files)
  15857 	  (org-install-agenda-files-menu)
  15858 	  (message "Removed from Org Agenda list: %s" afile))
  15859       (message "File was not in list: %s (not removed)" afile))))
  15860 
  15861 (defun org-file-menu-entry (file)
  15862   (vector file (list 'find-file file) t))
  15863 
  15864 (defun org-check-agenda-file (file)
  15865   "Make sure FILE exists.  If not, ask user what to do."
  15866   (unless (file-exists-p file)
  15867     (message "Non-existent agenda file %s.  [R]emove from list or [A]bort?"
  15868 	     (abbreviate-file-name file))
  15869     (let ((r (downcase (read-char-exclusive))))
  15870       (cond
  15871        ((equal r ?r)
  15872 	(org-remove-file file)
  15873 	(throw 'nextfile t))
  15874        (t (user-error "Abort"))))))
  15875 
  15876 (defun org-get-agenda-file-buffer (file)
  15877   "Get an agenda buffer visiting FILE.
  15878 If the buffer needs to be created, add it to the list of buffers
  15879 which might be released later."
  15880   (let ((buf (org-find-base-buffer-visiting file)))
  15881     (if buf
  15882 	buf ; just return it
  15883       ;; Make a new buffer and remember it
  15884       (setq buf (find-file-noselect file))
  15885       (when buf (push buf org-agenda-new-buffers))
  15886       buf)))
  15887 
  15888 (defun org-release-buffers (blist)
  15889   "Release all buffers in list, asking the user for confirmation when needed.
  15890 When a buffer is unmodified, it is just killed.  When modified, it is saved
  15891 \(if the user agrees) and then killed."
  15892   (let (file)
  15893     (dolist (buf blist)
  15894       (setq file (buffer-file-name buf))
  15895       (when (and (buffer-modified-p buf)
  15896 		 file
  15897 		 (y-or-n-p (format "Save file %s? " file)))
  15898 	(with-current-buffer buf (save-buffer)))
  15899       (kill-buffer buf))))
  15900 
  15901 (defun org-agenda-prepare-buffers (files)
  15902   "Create buffers for all agenda files, protect archived trees and comments."
  15903   (interactive)
  15904   (let ((inhibit-read-only t)
  15905 	(org-inhibit-startup org-agenda-inhibit-startup)
  15906         ;; Do not refresh list of agenda files in the menu when
  15907         ;; opening every new file.
  15908         (org-agenda-file-menu-enabled nil))
  15909     (setq org-tag-alist-for-agenda nil
  15910 	  org-tag-groups-alist-for-agenda nil)
  15911     (dolist (file files)
  15912       (catch 'nextfile
  15913         (with-current-buffer
  15914             (if (bufferp file)
  15915                 file
  15916               (org-check-agenda-file file)
  15917               (org-get-agenda-file-buffer file))
  15918           (org-with-wide-buffer
  15919 	   (org-set-regexps-and-options 'tags-only)
  15920 	   (or (memq 'stats org-agenda-ignore-properties)
  15921 	       (org-refresh-stats-properties))
  15922            (dolist (el org-todo-keywords-1)
  15923              (unless (member el org-todo-keywords-for-agenda)
  15924                (push el org-todo-keywords-for-agenda)))
  15925            (dolist (el org-done-keywords)
  15926              (unless (member el org-done-keywords-for-agenda)
  15927                (push el org-done-keywords-for-agenda)))
  15928 	   (setq org-todo-keyword-alist-for-agenda
  15929                  (org--tag-add-to-alist
  15930 		  org-todo-key-alist
  15931                   org-todo-keyword-alist-for-agenda))
  15932 	   (setq org-tag-alist-for-agenda
  15933 		 (org--tag-add-to-alist
  15934 		  org-current-tag-alist
  15935                   org-tag-alist-for-agenda))
  15936 	   ;; Merge current file's tag groups into global
  15937 	   ;; `org-tag-groups-alist-for-agenda'.
  15938 	   (when org-group-tags
  15939 	     (dolist (alist org-tag-groups-alist)
  15940 	       (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  15941 		 (if old
  15942 		     (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  15943 		   (push alist org-tag-groups-alist-for-agenda)))))))))
  15944     ;; Refresh the menu once after loading all the agenda buffers.
  15945     (when org-agenda-file-menu-enabled
  15946       (org-install-agenda-files-menu))))
  15947 
  15948 
  15949 ;;;; CDLaTeX minor mode
  15950 
  15951 (defvar org-cdlatex-mode-map (make-sparse-keymap)
  15952   "Keymap for the minor `org-cdlatex-mode'.")
  15953 
  15954 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  15955 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  15956 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  15957 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  15958 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  15959 
  15960 (defvar org-cdlatex-texmathp-advice-is-done nil
  15961   "Flag remembering if we have applied the advice to texmathp already.")
  15962 
  15963 (define-minor-mode org-cdlatex-mode
  15964   "Toggle the minor `org-cdlatex-mode'.
  15965 This mode supports entering LaTeX environment and math in LaTeX fragments
  15966 in Org mode.
  15967 \\{org-cdlatex-mode-map}"
  15968   :lighter " OCDL"
  15969   (when org-cdlatex-mode
  15970     ;; Try to load texmathp before cdlatex.  Otherwise, cdlatex can
  15971     ;; bind `cdlatex--texmathp' to `ignore', not using `texmathp' at
  15972     ;; all.
  15973     (org-require-package 'texmathp "Auctex")
  15974     (org-require-package 'cdlatex)
  15975     (run-hooks 'cdlatex-mode-hook)
  15976     (cdlatex-compute-tables))
  15977   (unless org-cdlatex-texmathp-advice-is-done
  15978     (setq org-cdlatex-texmathp-advice-is-done t)
  15979     (advice-add 'texmathp :around #'org--math-p)))
  15980 
  15981 (defun org--math-p (orig-fun &rest args)
  15982   "Return t inside math fragments or running `cdlatex-math-symbol'.
  15983 This function is intended to be an :around advice for `texmathp'.
  15984 
  15985 If Org mode thinks that point is actually inside
  15986 an embedded LaTeX environment, return t when the environment is math
  15987 or let `texmathp' do its job otherwise.
  15988 `\\[org-cdlatex-mode-map]'"
  15989   (cond
  15990    ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  15991    ((eq this-command 'cdlatex-math-symbol)
  15992     (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  15993     t)
  15994    (t
  15995     (let ((element (org-element-context)))
  15996       (when (org-inside-LaTeX-fragment-p element)
  15997         (pcase (substring-no-properties
  15998                 (org-element-property :value element)
  15999                 0 2)
  16000           ((or "\\(" "\\[" (pred (string-match-p (rx string-start "$"))))
  16001            (setq texmathp-why '("Org mode embedded math" . 0))
  16002            t)
  16003           (_ (apply orig-fun args))))))))
  16004 
  16005 (defun turn-on-org-cdlatex ()
  16006   "Unconditionally turn on `org-cdlatex-mode'."
  16007   (org-cdlatex-mode 1))
  16008 
  16009 (defun org-try-cdlatex-tab ()
  16010   "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16011 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16012   - inside a LaTeX fragment, or
  16013   - after the first word in a line, where an abbreviation expansion could
  16014     insert a LaTeX environment."
  16015   (when org-cdlatex-mode
  16016     (cond
  16017      ;; Before any word on the line: No expansion possible.
  16018      ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16019      ;; Just after first word on the line: Expand it.  Make sure it
  16020      ;; cannot happen on headlines, though.
  16021      ((save-excursion
  16022 	(skip-chars-backward "a-zA-Z0-9*")
  16023 	(skip-chars-backward " \t")
  16024 	(and (bolp) (not (org-at-heading-p))))
  16025       (cdlatex-tab) t)
  16026      ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16027 
  16028 (defun org-cdlatex-underscore-caret (&optional _arg)
  16029   "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16030 Revert to the normal definition outside of these fragments."
  16031   (interactive "P")
  16032   (if (org-inside-LaTeX-fragment-p)
  16033       (call-interactively 'cdlatex-sub-superscript)
  16034     (let (org-cdlatex-mode)
  16035       (call-interactively (key-binding (vector last-input-event))))))
  16036 
  16037 (defun org-cdlatex-math-modify (&optional _arg)
  16038   "Execute `cdlatex-math-modify' in LaTeX fragments.
  16039 Revert to the normal definition outside of these fragments."
  16040   (interactive "P")
  16041   (if (org-inside-LaTeX-fragment-p)
  16042       (call-interactively 'cdlatex-math-modify)
  16043     (let (org-cdlatex-mode)
  16044       (call-interactively (key-binding (vector last-input-event))))))
  16045 
  16046 (defun org-cdlatex-environment-indent (&optional environment item)
  16047   "Execute `cdlatex-environment' and indent the inserted environment.
  16048 
  16049 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16050 
  16051 The inserted environment is indented to current indentation
  16052 unless point is at the beginning of the line, in which the
  16053 environment remains unintended."
  16054   (interactive)
  16055   ;; cdlatex-environment always return nil.  Therefore, capture output
  16056   ;; first and determine if an environment was selected.
  16057   (let* ((beg (point-marker))
  16058 	 (end (copy-marker (point) t))
  16059 	 (inserted (progn
  16060 		     (ignore-errors (cdlatex-environment environment item))
  16061 		     (< beg end)))
  16062 	 ;; Figure out how many lines to move forward after the
  16063 	 ;; environment has been inserted.
  16064 	 (lines (when inserted
  16065 		  (save-excursion
  16066 		    (- (cl-loop while (< beg (point))
  16067 				with x = 0
  16068 				do (forward-line -1)
  16069 				(cl-incf x)
  16070 				finally return x)
  16071 		       (if (progn (goto-char beg)
  16072 				  (and (progn (skip-chars-forward " \t") (eolp))
  16073 				       (progn (skip-chars-backward " \t") (bolp))))
  16074 			   1 0)))))
  16075 	 (env (org-trim (delete-and-extract-region beg end))))
  16076     (when inserted
  16077       ;; Get indentation of next line unless at column 0.
  16078       (let ((ind (if (bolp) 0
  16079 		   (save-excursion
  16080 		     (org-return t)
  16081 		     (prog1 (current-indentation)
  16082 		       (when (progn (skip-chars-forward " \t") (eolp))
  16083 			 (delete-region beg (point)))))))
  16084 	    (bol (progn (skip-chars-backward " \t") (bolp))))
  16085 	;; Insert a newline before environment unless at column zero
  16086 	;; to "escape" the current line.  Insert a newline if
  16087 	;; something is one the same line as \end{ENVIRONMENT}.
  16088 	(insert
  16089 	 (concat (unless bol "\n") env
  16090 		 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16091 	(unless (zerop ind)
  16092 	  (save-excursion
  16093 	    (goto-char beg)
  16094 	    (while (< (point) end)
  16095 	      (unless (eolp) (indent-line-to ind))
  16096 	      (forward-line))))
  16097 	(goto-char beg)
  16098 	(forward-line lines)
  16099 	(indent-line-to ind)))
  16100     (set-marker beg nil)
  16101     (set-marker end nil)))
  16102 
  16103 
  16104 ;;;; LaTeX fragments
  16105 
  16106 (defun org-inside-LaTeX-fragment-p (&optional element)
  16107   "Test if point is inside a LaTeX fragment or environment.
  16108 
  16109 When optional argument ELEMENT is non-nil, it should be element/object
  16110 at point."
  16111   (org-element-type-p
  16112    (or element (org-element-context))
  16113    '(latex-fragment latex-environment)))
  16114 
  16115 (defun org-inside-latex-macro-p ()
  16116   "Is point inside a LaTeX macro or its arguments?"
  16117   (save-match-data
  16118     (org-in-regexp
  16119      "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16120 
  16121 (defun org--make-preview-overlay (beg end image &optional imagetype)
  16122   "Build an overlay between BEG and END using IMAGE file.
  16123 Argument IMAGETYPE is the extension of the displayed image,
  16124 as a string.  It defaults to \"png\"."
  16125   (let ((ov (make-overlay beg end))
  16126 	(imagetype (or (intern imagetype) 'png)))
  16127     (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16128     (overlay-put ov 'evaporate t)
  16129     (overlay-put ov
  16130 		 'modification-hooks
  16131 		 (list (lambda (o _flag _beg _end &optional _l)
  16132 			 (delete-overlay o))))
  16133     (overlay-put ov
  16134 		 'display
  16135 		 (list 'image :type imagetype :file image :ascent 'center))))
  16136 
  16137 (defun org-clear-latex-preview (&optional beg end)
  16138   "Remove all overlays with LaTeX fragment images in current buffer.
  16139 When optional arguments BEG and END are non-nil, remove all
  16140 overlays between them instead.  Return a non-nil value when some
  16141 overlays were removed, nil otherwise."
  16142   (let ((overlays
  16143 	 (cl-remove-if-not
  16144 	  (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16145 	  (overlays-in (or beg (point-min)) (or end (point-max))))))
  16146     (mapc #'delete-overlay overlays)
  16147     overlays))
  16148 
  16149 (defun org--latex-preview-region (beg end)
  16150   "Preview LaTeX fragments between BEG and END.
  16151 BEG and END are buffer positions."
  16152   (let ((file (buffer-file-name (buffer-base-buffer))))
  16153     (save-excursion
  16154       (org-format-latex
  16155        (concat org-preview-latex-image-directory "org-ltximg")
  16156        beg end
  16157        ;; Emacs cannot overlay images from remote hosts.  Create it in
  16158        ;; `temporary-file-directory' instead.
  16159        (if (or (not file) (file-remote-p file))
  16160 	   temporary-file-directory
  16161 	 default-directory)
  16162        'overlays nil 'forbuffer org-preview-latex-default-process))))
  16163 
  16164 (defun org-latex-preview (&optional arg)
  16165   "Toggle preview of the LaTeX fragment at point.
  16166 
  16167 If the cursor is on a LaTeX fragment, create the image and
  16168 overlay it over the source code, if there is none.  Remove it
  16169 otherwise.  If there is no fragment at point, display images for
  16170 all fragments in the current section.  With an active region,
  16171 display images for all fragments in the region.
  16172 
  16173 With a `\\[universal-argument]' prefix argument ARG, clear images \
  16174 for all fragments
  16175 in the current section.
  16176 
  16177 With a `\\[universal-argument] \\[universal-argument]' prefix \
  16178 argument ARG, display image for all
  16179 fragments in the buffer.
  16180 
  16181 With a `\\[universal-argument] \\[universal-argument] \
  16182 \\[universal-argument]' prefix argument ARG, clear image for all
  16183 fragments in the buffer."
  16184   (interactive "P")
  16185   (cond
  16186    ((not (display-graphic-p)) nil)
  16187    ((and untrusted-content (not org--latex-preview-when-risky)) nil)
  16188    ;; Clear whole buffer.
  16189    ((equal arg '(64))
  16190     (org-clear-latex-preview (point-min) (point-max))
  16191     (message "LaTeX previews removed from buffer"))
  16192    ;; Preview whole buffer.
  16193    ((equal arg '(16))
  16194     (message "Creating LaTeX previews in buffer...")
  16195     (org--latex-preview-region (point-min) (point-max))
  16196     (message "Creating LaTeX previews in buffer... done."))
  16197    ;; Clear current section.
  16198    ((equal arg '(4))
  16199     (org-clear-latex-preview
  16200      (if (use-region-p)
  16201          (region-beginning)
  16202        (if (org-before-first-heading-p) (point-min)
  16203          (save-excursion
  16204 	   (org-with-limited-levels (org-back-to-heading t) (point)))))
  16205      (if (use-region-p)
  16206          (region-end)
  16207        (org-with-limited-levels (org-entry-end-position)))))
  16208    ((use-region-p)
  16209     (message "Creating LaTeX previews in region...")
  16210     (org--latex-preview-region (region-beginning) (region-end))
  16211     (message "Creating LaTeX previews in region... done."))
  16212    ;; Toggle preview on LaTeX code at point.
  16213    ((let ((datum (org-element-context)))
  16214       (and (org-element-type-p datum '(latex-environment latex-fragment))
  16215 	   (let ((beg (org-element-begin datum))
  16216 		 (end (org-element-end datum)))
  16217 	     (if (org-clear-latex-preview beg end)
  16218 		 (message "LaTeX preview removed")
  16219 	       (message "Creating LaTeX preview...")
  16220 	       (org--latex-preview-region beg end)
  16221 	       (message "Creating LaTeX preview... done."))
  16222 	     t))))
  16223    ;; Preview current section.
  16224    (t
  16225     (let ((beg (if (org-before-first-heading-p) (point-min)
  16226 		 (save-excursion
  16227 		   (org-with-limited-levels (org-back-to-heading t) (point)))))
  16228 	  (end (org-with-limited-levels (org-entry-end-position))))
  16229       (message "Creating LaTeX previews in section...")
  16230       (org--latex-preview-region beg end)
  16231       (message "Creating LaTeX previews in section... done.")))))
  16232 
  16233 (defun org-format-latex
  16234     (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16235   "Replace LaTeX fragments with links to an image.
  16236 
  16237 The function takes care of creating the replacement image.
  16238 
  16239 Only consider fragments between BEG and END when those are
  16240 provided.
  16241 
  16242 When optional argument OVERLAYS is non-nil, display the image on
  16243 top of the fragment instead of replacing it.
  16244 
  16245 PROCESSING-TYPE is the conversion method to use, as a symbol.
  16246 
  16247 Some of the options can be changed using the variable
  16248 `org-format-latex-options', which see."
  16249   (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16250   (unless (eq processing-type 'verbatim)
  16251     (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16252 	   (cnt 0)
  16253 	   checkdir-flag)
  16254       (goto-char (or beg (point-min)))
  16255       ;; FIXME: `overlay-recenter' is not needed (and has no effect)
  16256       ;; since Emacs 29.
  16257       ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16258       (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16259 	(overlay-recenter (or end (point-max))))
  16260       (while (re-search-forward math-regexp end t)
  16261 	(unless (and overlays
  16262 		     (eq (get-char-property (point) 'org-overlay-type)
  16263 			 'org-latex-overlay))
  16264 	  (let* ((context (org-element-context))
  16265 		 (type (org-element-type context)))
  16266 	    (when (memq type '(latex-environment latex-fragment))
  16267 	      (let ((block-type (eq type 'latex-environment))
  16268 		    (value (org-element-property :value context))
  16269 		    (beg (org-element-begin context))
  16270 		    (end (save-excursion
  16271 			   (goto-char (org-element-end context))
  16272 			   (skip-chars-backward " \r\t\n")
  16273 			   (point))))
  16274 		(cond
  16275 		 ((eq processing-type 'mathjax)
  16276 		  ;; Prepare for MathJax processing.
  16277 		  (if (not (string-match "\\`\\$\\$?" value))
  16278 		      (goto-char end)
  16279 		    (delete-region beg end)
  16280 		    (if (string= (match-string 0 value) "$$")
  16281 			(insert "\\[" (substring value 2 -2) "\\]")
  16282 		      (insert "\\(" (substring value 1 -1) "\\)"))))
  16283 		 ((eq processing-type 'html)
  16284 		  (goto-char beg)
  16285 		  (delete-region beg end)
  16286 		  (insert (org-format-latex-as-html value)))
  16287 		 ((assq processing-type org-preview-latex-process-alist)
  16288 		  ;; Process to an image.
  16289 		  (cl-incf cnt)
  16290 		  (goto-char beg)
  16291 		  (let* ((processing-info
  16292 			  (cdr (assq processing-type org-preview-latex-process-alist)))
  16293 			 (face (face-at-point))
  16294 			 ;; Get the colors from the face at point.
  16295 			 (fg
  16296 			  (let ((color (plist-get org-format-latex-options
  16297 						  :foreground)))
  16298                             (if forbuffer
  16299                                 (cond
  16300                                  ((eq color 'auto)
  16301                                   (face-attribute face :foreground nil 'default))
  16302                                  ((eq color 'default)
  16303                                   (face-attribute 'default :foreground nil))
  16304                                  (t color))
  16305                               color)))
  16306 			 (bg
  16307 			  (let ((color (plist-get org-format-latex-options
  16308 						  :background)))
  16309                             (if forbuffer
  16310                                 (cond
  16311                                  ((eq color 'auto)
  16312                                   (face-attribute face :background nil 'default))
  16313                                  ((eq color 'default)
  16314                                   (face-attribute 'default :background nil))
  16315                                  (t color))
  16316                               color)))
  16317 			 (hash (sha1 (prin1-to-string
  16318 				      (list org-format-latex-header
  16319 					    org-latex-default-packages-alist
  16320 					    org-latex-packages-alist
  16321 					    org-format-latex-options
  16322 					    forbuffer value fg bg))))
  16323 			 (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16324 			 (absprefix (expand-file-name prefix dir))
  16325 			 (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16326 			 (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16327 			 (sep (and block-type "\n\n"))
  16328 			 (link (concat sep "[[file:" linkfile "]]" sep))
  16329 			 (options
  16330 			  (org-combine-plists
  16331 			   org-format-latex-options
  16332 			   `(:foreground ,fg :background ,bg))))
  16333 		    (when msg (message msg cnt))
  16334 		    (unless checkdir-flag ; Ensure the directory exists.
  16335 		      (setq checkdir-flag t)
  16336 		      (let ((todir (file-name-directory absprefix)))
  16337 			(unless (file-directory-p todir)
  16338 			  (make-directory todir t))))
  16339 		    (unless (file-exists-p movefile)
  16340 		      (org-create-formula-image
  16341 		       value movefile options forbuffer processing-type))
  16342                     (org-place-formula-image link block-type beg end value overlays movefile imagetype)))
  16343 		 ((eq processing-type 'mathml)
  16344 		  ;; Process to MathML.
  16345 		  (unless (org-format-latex-mathml-available-p)
  16346 		    (user-error "LaTeX to MathML converter not configured"))
  16347 		  (cl-incf cnt)
  16348 		  (when msg (message msg cnt))
  16349 		  (goto-char beg)
  16350 		  (delete-region beg end)
  16351 		  (insert (org-format-latex-as-mathml
  16352 			   value block-type prefix dir)))
  16353 		 (t
  16354 		  (error "Unknown conversion process %s for LaTeX fragments"
  16355 			 processing-type)))))))))))
  16356 
  16357 (defun org-place-formula-image (link block-type beg end value overlays movefile imagetype)
  16358   "Place an overlay from BEG to END showing MOVEFILE.
  16359 The overlay will be above BEG if OVERLAYS is non-nil."
  16360   (if overlays
  16361       (progn
  16362         (dolist (o (overlays-in beg end))
  16363           (when (eq (overlay-get o 'org-overlay-type)
  16364                     'org-latex-overlay)
  16365             (delete-overlay o)))
  16366         (org--make-preview-overlay beg end movefile imagetype)
  16367         (goto-char end))
  16368     (delete-region beg end)
  16369     (insert
  16370      (org-add-props link
  16371          (list 'org-latex-src
  16372                (replace-regexp-in-string "\"" "" value)
  16373                'org-latex-src-embed-type
  16374                (if block-type 'paragraph 'character))))))
  16375 
  16376 (defun org-create-math-formula (latex-frag &optional mathml-file)
  16377   "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16378 Use `org-latex-to-mathml-convert-command'.  If the conversion is
  16379 successful, return the portion between \"<math...> </math>\"
  16380 elements otherwise return nil.  When MATHML-FILE is specified,
  16381 write the results in to that file.  When invoked as an
  16382 interactive command, prompt for LATEX-FRAG, with initial value
  16383 set to the current active region and echo the results for user
  16384 inspection."
  16385   (interactive (list (let ((frag (when (org-region-active-p)
  16386 				   (buffer-substring-no-properties
  16387 				    (region-beginning) (region-end)))))
  16388 		       (read-string "LaTeX Fragment: " frag nil frag))))
  16389   (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16390   (let* ((tmp-in-file
  16391 	  (let ((file (file-relative-name
  16392 		       (make-temp-name (expand-file-name "ltxmathml-in")))))
  16393 	    (write-region latex-frag nil file)
  16394 	    file))
  16395 	 (tmp-out-file (file-relative-name
  16396 			(make-temp-name (expand-file-name  "ltxmathml-out"))))
  16397 	 (cmd (format-spec
  16398 	       org-latex-to-mathml-convert-command
  16399 	       `((?j . ,(and org-latex-to-mathml-jar-file
  16400 			     (shell-quote-argument
  16401 			      (expand-file-name
  16402 			       org-latex-to-mathml-jar-file))))
  16403 		 (?I . ,(shell-quote-argument tmp-in-file))
  16404 		 (?i . ,(shell-quote-argument latex-frag))
  16405 		 (?o . ,(shell-quote-argument tmp-out-file)))))
  16406 	 mathml shell-command-output)
  16407     (when (called-interactively-p 'any)
  16408       (unless (org-format-latex-mathml-available-p)
  16409 	(user-error "LaTeX to MathML converter not configured")))
  16410     (message "Running %s" cmd)
  16411     (setq shell-command-output (shell-command-to-string cmd))
  16412     (setq mathml
  16413 	  (when (file-readable-p tmp-out-file)
  16414 	    (with-temp-buffer
  16415               (insert-file-contents tmp-out-file)
  16416 	      (goto-char (point-min))
  16417 	      (when (re-search-forward
  16418 		     (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16419 			     (regexp-quote
  16420 			      "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16421 		     nil t)
  16422 		(match-string 0)))))
  16423     (cond
  16424      (mathml
  16425       (setq mathml
  16426 	    (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16427       (when mathml-file
  16428 	(write-region mathml nil mathml-file))
  16429       (when (called-interactively-p 'any)
  16430 	(message mathml)))
  16431      ((warn "LaTeX to MathML conversion failed")
  16432       (message shell-command-output)))
  16433     (delete-file tmp-in-file)
  16434     (when (file-exists-p tmp-out-file)
  16435       (delete-file tmp-out-file))
  16436     mathml))
  16437 
  16438 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16439 					      prefix &optional dir)
  16440   "Use `org-create-math-formula' but check local cache first."
  16441   (let* ((absprefix (expand-file-name prefix dir))
  16442 	 (print-length nil) (print-level nil)
  16443 	 (formula-id (concat
  16444 		      "formula-"
  16445 		      (sha1
  16446 		       (prin1-to-string
  16447 			(list latex-frag
  16448 			      org-latex-to-mathml-convert-command)))))
  16449 	 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16450 	 (formula-cache-dir (file-name-directory formula-cache)))
  16451 
  16452     (unless (file-directory-p formula-cache-dir)
  16453       (make-directory formula-cache-dir t))
  16454 
  16455     (unless (file-exists-p formula-cache)
  16456       (org-create-math-formula latex-frag formula-cache))
  16457 
  16458     (if (file-exists-p formula-cache)
  16459 	;; Successful conversion.  Return the link to MathML file.
  16460 	(org-add-props
  16461 	    (format  "[[file:%s]]" (file-relative-name formula-cache dir))
  16462 	    (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16463 		  'org-latex-src-embed-type (if latex-frag-type
  16464 						'paragraph 'character)))
  16465       ;; Failed conversion.  Return the LaTeX fragment verbatim
  16466       latex-frag)))
  16467 
  16468 (defun org-format-latex-as-html (latex-fragment)
  16469   "Convert LATEX-FRAGMENT to HTML.
  16470 This uses  `org-latex-to-html-convert-command', which see."
  16471   (let ((cmd (format-spec org-latex-to-html-convert-command
  16472 			  `((?i . ,(shell-quote-argument latex-fragment))))))
  16473     (message "Running %s" cmd)
  16474     (shell-command-to-string cmd)))
  16475 
  16476 (defun org--get-display-dpi ()
  16477   "Get the DPI of the display.
  16478 The function assumes that the display has the same pixel width in
  16479 the horizontal and vertical directions."
  16480   (if (display-graphic-p)
  16481       (round (/ (display-pixel-height)
  16482 		(/ (display-mm-height) 25.4)))
  16483     (error "Attempt to calculate the dpi of a non-graphic display")))
  16484 
  16485 (defun org-create-formula-image
  16486     (string tofile options buffer &optional processing-type)
  16487   "Create an image from LaTeX source using external processes.
  16488 
  16489 The LaTeX STRING is saved to a temporary LaTeX file, then
  16490 converted to an image file by process PROCESSING-TYPE defined in
  16491 `org-preview-latex-process-alist'.  A nil value defaults to
  16492 `org-preview-latex-default-process'.
  16493 
  16494 The generated image file is eventually moved to TOFILE.
  16495 
  16496 The OPTIONS argument controls the size, foreground color and
  16497 background color of the generated image.
  16498 
  16499 When BUFFER non-nil, this function is used for LaTeX previewing.
  16500 Otherwise, it is used to deal with LaTeX snippets showed in
  16501 a HTML file."
  16502   (let* ((processing-type (or processing-type
  16503 			      org-preview-latex-default-process))
  16504 	 (processing-info
  16505 	  (cdr (assq processing-type org-preview-latex-process-alist)))
  16506 	 (programs (plist-get processing-info :programs))
  16507 	 (error-message (or (plist-get processing-info :message) ""))
  16508 	 (image-input-type (plist-get processing-info :image-input-type))
  16509 	 (image-output-type (plist-get processing-info :image-output-type))
  16510 	 (post-clean (or (plist-get processing-info :post-clean)
  16511 			 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16512 			   ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16513 	 (latex-header
  16514 	  (or (plist-get processing-info :latex-header)
  16515 	      (org-latex-make-preamble
  16516 	       (org-export-get-environment (org-export-get-backend 'latex))
  16517 	       org-format-latex-header
  16518 	       'snippet)))
  16519 	 (latex-compiler (plist-get processing-info :latex-compiler))
  16520 	 (tmpdir temporary-file-directory)
  16521 	 (texfilebase (make-temp-name
  16522 		       (expand-file-name "orgtex" tmpdir)))
  16523 	 (texfile (concat texfilebase ".tex"))
  16524 	 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16525 				'(1.0 . 1.0)))
  16526 	 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16527 		   (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16528 	 (dpi (* scale (if (and buffer (display-graphic-p)) (org--get-display-dpi) 140.0)))
  16529 	 (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16530 		 "Black"))
  16531 	 (bg (or (plist-get options (if buffer :background :html-background))
  16532 		 "Transparent"))
  16533 	 (image-converter
  16534           (or (and (string= bg "Transparent")
  16535                    (plist-get processing-info :transparent-image-converter))
  16536               (plist-get processing-info :image-converter)))
  16537          (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16538 	 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16539     (dolist (program programs)
  16540       (org-check-external-command program error-message))
  16541     (if (eq fg 'default)
  16542 	(setq fg (org-latex-color :foreground))
  16543       (setq fg (org-latex-color-format fg)))
  16544     (setq bg (cond
  16545 	      ((eq bg 'default) (org-latex-color :background))
  16546 	      ((string= bg "Transparent") nil)
  16547 	      (t (org-latex-color-format bg))))
  16548     ;; Remove TeX \par at end of snippet to avoid trailing space.
  16549     (if (string-suffix-p string "\n")
  16550         (aset string (1- (length string)) ?%)
  16551       (setq string (concat string "%")))
  16552     (with-temp-file texfile
  16553       (insert latex-header)
  16554       (insert "\n\\begin{document}\n"
  16555 	      "\\definecolor{fg}{rgb}{" fg "}%\n"
  16556 	      (if bg
  16557 		  (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  16558 			  "\n\\pagecolor{bg}%\n")
  16559 		"")
  16560 	      "\n{\\color{fg}\n"
  16561 	      string
  16562 	      "\n}\n"
  16563 	      "\n\\end{document}\n"))
  16564     (let* ((err-msg (format "Please adjust `%s' part of \
  16565 `org-preview-latex-process-alist'."
  16566 			    processing-type))
  16567 	   (image-input-file
  16568 	    (org-compile-file
  16569 	     texfile latex-compiler image-input-type err-msg log-buf))
  16570 	   (image-output-file
  16571 	    (org-compile-file
  16572 	     image-input-file image-converter image-output-type err-msg log-buf
  16573 	     `((?D . ,(shell-quote-argument (format "%s" dpi)))
  16574 	       (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16575       (copy-file image-output-file tofile 'replace)
  16576       (dolist (e post-clean)
  16577 	(when (file-exists-p (concat texfilebase e))
  16578 	  (delete-file (concat texfilebase e))))
  16579       image-output-file)))
  16580 
  16581 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16582   "Fill a LaTeX header template TPL.
  16583 In the template, the following place holders will be recognized:
  16584 
  16585  [DEFAULT-PACKAGES]      \\usepackage statements for DEF-PKG
  16586  [NO-DEFAULT-PACKAGES]   do not include DEF-PKG
  16587  [PACKAGES]              \\usepackage statements for PKG
  16588  [NO-PACKAGES]           do not include PKG
  16589  [EXTRA]                 the string EXTRA
  16590  [NO-EXTRA]              do not include EXTRA
  16591 
  16592 For backward compatibility, if both the positive and the negative place
  16593 holder is missing, the positive one (without the \"NO-\") will be
  16594 assumed to be present at the end of the template.
  16595 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16596 EXTRA is a string.
  16597 SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16598   (let (rpl (end ""))
  16599     (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16600 	(setq rpl (if (or (match-end 1) (not def-pkg))
  16601 		      "" (org-latex-packages-to-string def-pkg snippets-p t))
  16602 	      tpl (replace-match rpl t t tpl))
  16603       (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16604 
  16605     (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16606 	(setq rpl (if (or (match-end 1) (not pkg))
  16607 		      "" (org-latex-packages-to-string pkg snippets-p t))
  16608 	      tpl (replace-match rpl t t tpl))
  16609       (when pkg (setq end
  16610 		      (concat end "\n"
  16611 			      (org-latex-packages-to-string pkg snippets-p)))))
  16612 
  16613     (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16614 	(setq rpl (if (or (match-end 1) (not extra))
  16615 		      "" (concat extra "\n"))
  16616 	      tpl (replace-match rpl t t tpl))
  16617       (when (and extra (string-match "\\S-" extra))
  16618 	(setq end (concat end "\n" extra))))
  16619 
  16620     (if (string-match "\\S-" end)
  16621 	(concat tpl "\n" end)
  16622       tpl)))
  16623 
  16624 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16625   "Turn an alist of packages into a string with the \\usepackage macros."
  16626   (setq pkg (mapconcat (lambda(p)
  16627 			 (cond
  16628 			  ((stringp p) p)
  16629 			  ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16630 			   (format "%% Package %s omitted" (cadr p)))
  16631 			  ((equal "" (car p))
  16632 			   (format "\\usepackage{%s}" (cadr p)))
  16633 			  (t
  16634 			   (format "\\usepackage[%s]{%s}"
  16635 				   (car p) (cadr p)))))
  16636 		       pkg
  16637 		       "\n"))
  16638   (if newline (concat pkg "\n") pkg))
  16639 
  16640 (defun org-dvipng-color (attr)
  16641   "Return a RGB color specification for dvipng."
  16642   (org-dvipng-color-format (face-attribute 'default attr nil)))
  16643 
  16644 (defun org-dvipng-color-format (color-name)
  16645   "Convert COLOR-NAME to a RGB color value for dvipng."
  16646   (apply #'format "rgb %s %s %s"
  16647 	 (mapcar 'org-normalize-color
  16648 		 (color-values color-name))))
  16649 
  16650 (defun org-latex-color (attr)
  16651   "Return a RGB color for the LaTeX color package."
  16652   (org-latex-color-format (face-attribute 'default attr nil)))
  16653 
  16654 (defun org-latex-color-format (color-name)
  16655   "Convert COLOR-NAME to a RGB color value."
  16656   (apply #'format "%s,%s,%s"
  16657 	 (mapcar 'org-normalize-color
  16658 		 (color-values color-name))))
  16659 
  16660 (defun org-normalize-color (value)
  16661   "Return string to be used as color value for an RGB component."
  16662   (format "%g" (/ value 65535.0)))
  16663 
  16664 
  16665 ;; Image display
  16666 
  16667 (defvar-local org-inline-image-overlays nil)
  16668 ;; Preserve when switching modes or when restarting Org.
  16669 ;; If we clear the overlay list and later enable Or mode, the existing
  16670 ;; image overlays will never be cleared by `org-toggle-inline-images'.
  16671 (put 'org-inline-image-overlays 'permanent-local t)
  16672 
  16673 (defun org--inline-image-overlays (&optional beg end)
  16674   "Return image overlays between BEG and END."
  16675   (let* ((beg (or beg (point-min)))
  16676          (end (or end (point-max)))
  16677          (overlays (overlays-in beg end))
  16678          result)
  16679     (dolist (ov overlays result)
  16680       (when (memq ov org-inline-image-overlays)
  16681         (push ov result)))))
  16682 
  16683 (defun org-toggle-inline-images (&optional include-linked beg end)
  16684   "Toggle the display of inline images.
  16685 INCLUDE-LINKED is passed to `org-display-inline-images'."
  16686   (interactive "P")
  16687   (if (org--inline-image-overlays beg end)
  16688       (progn
  16689         (org-remove-inline-images beg end)
  16690         (when (called-interactively-p 'interactive)
  16691 	  (message "Inline image display turned off")))
  16692     (org-display-inline-images include-linked nil beg end)
  16693     (when (called-interactively-p 'interactive)
  16694       (let ((new (org--inline-image-overlays beg end)))
  16695         (message (if new
  16696 		     (format "%d images displayed inline"
  16697 			     (length new))
  16698 		   "No images to display inline"))))))
  16699 
  16700 (defun org-redisplay-inline-images ()
  16701   "Assure display of inline images and refresh them."
  16702   (interactive)
  16703   (org-toggle-inline-images)
  16704   (unless org-inline-image-overlays
  16705     (org-toggle-inline-images)))
  16706 
  16707 ;; For without-x builds.
  16708 (declare-function image-flush "image" (spec &optional frame))
  16709 
  16710 (defcustom org-display-remote-inline-images 'skip
  16711   "How to display remote inline images.
  16712 Possible values of this option are:
  16713 
  16714 skip        Don't display remote images.
  16715 download    Always download and display remote images.
  16716 t
  16717 cache       Display remote images, and open them in separate buffers
  16718             for caching.  Silently update the image buffer when a file
  16719             change is detected."
  16720   :group 'org-appearance
  16721   :package-version '(Org . "9.7")
  16722   :type '(choice
  16723 	  (const :tag "Ignore remote images" skip)
  16724 	  (const :tag "Always display remote images" download)
  16725 	  (const :tag "Display and silently update remote images" cache))
  16726   :safe #'symbolp)
  16727 
  16728 (defcustom org-image-align 'left
  16729   "How to align images previewed using `org-display-inline-images'.
  16730 
  16731 Only stand-alone image links are affected by this setting.  These
  16732 are links without surrounding text.
  16733 
  16734 Possible values of this option are:
  16735 
  16736 left     Insert image at specified position.
  16737 center   Center image previews.
  16738 right    Right-align image previews."
  16739   :group 'org-appearance
  16740   :package-version '(Org . "9.7")
  16741   :type '(choice
  16742           (const :tag "Left align (or don\\='t align) image previews" left)
  16743 	  (const :tag "Center image previews" center)
  16744 	  (const :tag "Right align image previews" right))
  16745   :safe #'symbolp)
  16746 
  16747 (defun org--create-inline-image (file width)
  16748   "Create image located at FILE, or return nil.
  16749 WIDTH is the width of the image.  The image may not be created
  16750 according to the value of `org-display-remote-inline-images'."
  16751   (let* ((remote? (file-remote-p file))
  16752 	 (file-or-data
  16753 	  (pcase org-display-remote-inline-images
  16754 	    ((guard (not remote?)) file)
  16755 	    (`download (with-temp-buffer
  16756 			 (set-buffer-multibyte nil)
  16757 			 (insert-file-contents-literally file)
  16758 			 (buffer-string)))
  16759 	    ((or `cache `t)
  16760              (let ((revert-without-query '(".")))
  16761 	       (with-current-buffer (find-file-noselect file)
  16762 		 (buffer-string))))
  16763 	    (`skip nil)
  16764 	    (other
  16765 	     (message "Invalid value of `org-display-remote-inline-images': %S"
  16766 		      other)
  16767 	     nil))))
  16768     (when file-or-data
  16769       (create-image file-or-data
  16770 		    (and (image-type-available-p 'imagemagick)
  16771 			 width
  16772 			 'imagemagick)
  16773 		    remote?
  16774 		    :width width
  16775                     :max-width
  16776                     (pcase org-image-max-width
  16777                       (`fill-column (* fill-column (frame-char-width (selected-frame))))
  16778                       (`window (window-width nil t))
  16779                       ((pred integerp) org-image-max-width)
  16780                       ((pred floatp) (floor (* org-image-max-width (window-width nil t))))
  16781                       (`nil nil)
  16782                       (_ (error "Unsupported value of `org-image-max-width': %S"
  16783                                 org-image-max-width)))
  16784                     :scale 1))))
  16785 
  16786 (defun org-display-inline-images (&optional include-linked refresh beg end)
  16787   "Display inline images.
  16788 
  16789 An inline image is a link which follows either of these
  16790 conventions:
  16791 
  16792   1. Its path is a file with an extension matching return value
  16793      from `image-file-name-regexp' and it has no contents.
  16794 
  16795   2. Its description consists in a single link of the previous
  16796      type.  In this case, that link must be a well-formed plain
  16797      or angle link, i.e., it must have an explicit \"file\" or
  16798      \"attachment\" type.
  16799 
  16800 Equip each image with the key-map `image-map'.
  16801 
  16802 When optional argument INCLUDE-LINKED is non-nil, also links with
  16803 a text description part will be inlined.  This can be nice for
  16804 a quick look at those images, but it does not reflect what
  16805 exported files will look like.
  16806 
  16807 When optional argument REFRESH is non-nil, refresh existing
  16808 images between BEG and END.  This will create new image displays
  16809 only if necessary.
  16810 
  16811 BEG and END define the considered part.  They default to the
  16812 buffer boundaries with possible narrowing."
  16813   (interactive "P")
  16814   (when (display-graphic-p)
  16815     (when refresh
  16816       (org-remove-inline-images beg end)
  16817       (when (fboundp 'clear-image-cache) (clear-image-cache)))
  16818     (let ((end (or end (point-max))))
  16819       (org-with-point-at (or beg (point-min))
  16820 	(let* ((case-fold-search t)
  16821 	       (file-extension-re (image-file-name-regexp))
  16822 	       (link-abbrevs (mapcar #'car
  16823 				     (append org-link-abbrev-alist-local
  16824 					     org-link-abbrev-alist)))
  16825 	       ;; Check absolute, relative file names and explicit
  16826 	       ;; "file:" links.  Also check link abbreviations since
  16827 	       ;; some might expand to "file" links.
  16828 	       (file-types-re
  16829 		(format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?\\(?:file\\|attachment\\):\\)"
  16830 			(if (not link-abbrevs) ""
  16831 			  (concat "\\|" (regexp-opt link-abbrevs))))))
  16832 	  (while (re-search-forward file-types-re end t)
  16833 	    (let* ((link (org-element-lineage
  16834 			  (save-match-data (org-element-context))
  16835 			  'link t))
  16836                    (linktype (org-element-property :type link))
  16837 		   (inner-start (match-beginning 1))
  16838 		   (path
  16839 		    (cond
  16840 		     ;; No link at point; no inline image.
  16841 		     ((not link) nil)
  16842 		     ;; File link without a description.  Also handle
  16843 		     ;; INCLUDE-LINKED here since it should have
  16844 		     ;; precedence over the next case.  I.e., if link
  16845 		     ;; contains filenames in both the path and the
  16846 		     ;; description, prioritize the path only when
  16847 		     ;; INCLUDE-LINKED is non-nil.
  16848 		     ((or (not (org-element-contents-begin link))
  16849 			  include-linked)
  16850 		      (and (or (equal "file" linktype)
  16851                                (equal "attachment" linktype))
  16852 			   (org-element-property :path link)))
  16853 		     ;; Link with a description.  Check if description
  16854 		     ;; is a filename.  Even if Org doesn't have syntax
  16855 		     ;; for those -- clickable image -- constructs, fake
  16856 		     ;; them, as in `org-export-insert-image-links'.
  16857 		     ((not inner-start) nil)
  16858 		     (t
  16859 		      (org-with-point-at inner-start
  16860 			(and (looking-at
  16861 			      (if (char-equal ?< (char-after inner-start))
  16862 				  org-link-angle-re
  16863 				org-link-plain-re))
  16864 			     ;; File name must fill the whole
  16865 			     ;; description.
  16866 			     (= (org-element-contents-end link)
  16867 				(match-end 0))
  16868 			     (progn
  16869                                (setq linktype (match-string 1))
  16870                                (match-string 2))))))))
  16871 	      (when (and path (string-match-p file-extension-re path))
  16872 		(let ((file (if (equal "attachment" linktype)
  16873 				(progn
  16874                                   (require 'org-attach)
  16875 				  (ignore-errors (org-attach-expand path)))
  16876                               (expand-file-name path))))
  16877                   ;; Expand environment variables.
  16878                   (when file (setq file (substitute-in-file-name file)))
  16879 		  (when (and file (file-exists-p file))
  16880 		    (let ((width (org-display-inline-image--width link))
  16881 			  (align (org-image--align link))
  16882                           (old (get-char-property-and-overlay
  16883 				(org-element-begin link)
  16884 				'org-image-overlay)))
  16885 		      (if (and (car-safe old) refresh)
  16886                           (image-flush (overlay-get (cdr old) 'display))
  16887 			(let ((image (org--create-inline-image file width)))
  16888 			  (when image
  16889 			    (let ((ov (make-overlay
  16890 				       (org-element-begin link)
  16891 				       (progn
  16892 					 (goto-char
  16893 					  (org-element-end link))
  16894 					 (unless (eolp) (skip-chars-backward " \t"))
  16895 					 (point)))))
  16896                               ;; See bug#59902.  We cannot rely
  16897                               ;; on Emacs to update image if the file
  16898                               ;; has changed.
  16899                               (image-flush image)
  16900 			      (overlay-put ov 'display image)
  16901 			      (overlay-put ov 'face 'default)
  16902 			      (overlay-put ov 'org-image-overlay t)
  16903 			      (overlay-put
  16904 			       ov 'modification-hooks
  16905 			       (list 'org-display-inline-remove-overlay))
  16906 			      (when (boundp 'image-map)
  16907 				(overlay-put ov 'keymap image-map))
  16908                               (when align
  16909                                 (overlay-put
  16910                                  ov 'before-string
  16911                                  (propertize
  16912                                   " " 'face 'default
  16913                                   'display
  16914                                   (pcase align
  16915                                     ("center" `(space :align-to (- center (0.5 . ,image))))
  16916                                     ("right"  `(space :align-to (- right ,image)))))))
  16917 			      (push ov org-inline-image-overlays))))))))))))))))
  16918 
  16919 (declare-function org-export-read-attribute "ox"
  16920                   (attribute element &optional property))
  16921 (defvar visual-fill-column-width) ; Silence compiler warning
  16922 (defun org-display-inline-image--width (link)
  16923   "Determine the display width of the image LINK, in pixels.
  16924 - When `org-image-actual-width' is t, the image's pixel width is used.
  16925 - When `org-image-actual-width' is a number, that value will is used.
  16926 - When `org-image-actual-width' is nil or a list, :width attribute of
  16927   #+attr_org or the first #+attr_...  (if it exists) is used to set the
  16928   image width.  A width of X% is divided by 100.  If the value is a
  16929   float between 0 and 2, it interpreted as that proportion of the text
  16930   width in the buffer.
  16931 
  16932   If no :width attribute is given and `org-image-actual-width' is a
  16933   list with a number as the car, then that number is used as the
  16934   default value."
  16935   ;; Apply `org-image-actual-width' specifications.
  16936   ;; Support subtree-level property "ORG-IMAGE-ACTUAL-WIDTH" specified
  16937   ;; width.
  16938   (let ((org-image-actual-width (org-property-or-variable-value 'org-image-actual-width)))
  16939     (cond
  16940      ((eq org-image-actual-width t) nil)
  16941      ((listp org-image-actual-width)
  16942       (require 'ox)
  16943       (let* ((par (org-element-lineage link 'paragraph))
  16944              ;; Try to find an attribute providing a :width.
  16945              ;; #+ATTR_ORG: :width ...
  16946              (attr-width (org-export-read-attribute :attr_org par :width))
  16947              (width-unreadable?
  16948               (lambda (value)
  16949                 (or (not (stringp value))
  16950                     (unless (string= value "t")
  16951                       (or (not (string-match-p
  16952                               (rx bos (opt "+") (opt ".") (in "0-9"))
  16953                               value))
  16954                           (let ((number (string-to-number value)))
  16955                             (and (floatp number) (not (<= 0.0 number 2.0)))))))))
  16956              ;; #+ATTR_BACKEND: :width ...
  16957              (attr-other
  16958               (catch :found
  16959                 (org-element-properties-map
  16960                  (lambda (prop _)
  16961                    (when (and
  16962                           (not (eq prop :attr_org))
  16963                           (string-match-p "^:attr_" (symbol-name prop))
  16964                           (not (funcall width-unreadable? (org-export-read-attribute prop par :width))))
  16965                      (throw :found prop)))
  16966                  par)))
  16967              (attr-width
  16968               (if (not (funcall width-unreadable? attr-width))
  16969                   attr-width
  16970                 ;; When #+attr_org: does not have readable :width
  16971                 (and attr-other
  16972                      (org-export-read-attribute attr-other par :width))))
  16973              (width
  16974               (cond
  16975                ;; Treat :width t as if `org-image-actual-width' were t.
  16976                ((string= attr-width "t") nil)
  16977                ;; Fallback to `org-image-actual-width' if no interprable width is given.
  16978                ((funcall width-unreadable? attr-width)
  16979                 (car org-image-actual-width))
  16980                ;; Convert numeric widths to numbers, converting percentages.
  16981                ((string-match-p "\\`[[+]?[0-9.]+%" attr-width)
  16982                 (/ (string-to-number attr-width) 100.0))
  16983                (t (string-to-number attr-width)))))
  16984         (if (and (floatp width) (<= 0.0 width 2.0))
  16985             ;; A float in [0,2] should be interpereted as this portion of
  16986             ;; the text width in the window.  This works well with cases like
  16987             ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  16988             ;; as the "0.X" is pulled out as a float.  We use 2 as the upper
  16989             ;; bound as cases such as 1.2\linewidth are feasible.
  16990             (round (* width
  16991                       (window-pixel-width)
  16992                       (/ (or (and (bound-and-true-p visual-fill-column-mode)
  16993                                   (or visual-fill-column-width auto-fill-function))
  16994                              (when auto-fill-function fill-column)
  16995                              (- (window-text-width) (line-number-display-width)))
  16996                          (float (window-total-width)))))
  16997           width)))
  16998      ((numberp org-image-actual-width)
  16999       org-image-actual-width)
  17000      (t nil))))
  17001 
  17002 (defun org-image--align (link)
  17003   "Determine the alignment of the image LINK.
  17004 LINK is a link object.
  17005 
  17006 In decreasing order of priority, this is controlled:
  17007 - Per image by the value of `:center' or `:align' in the
  17008 affiliated keyword `#+attr_org'.
  17009 - By the `#+attr_html' or `#+attr_latex` keywords with valid
  17010   `:center' or `:align' values.
  17011 - Globally by the user option `org-image-align'.
  17012 
  17013 The result is either nil or one of the strings \"left\",
  17014 \"center\" or \"right\".
  17015 
  17016 \"center\" will cause the image preview to be centered, \"right\"
  17017 will cause it to be right-aligned.  A value of \"left\" or nil
  17018 implies no special alignment."
  17019   (let ((par (org-element-lineage link 'paragraph)))
  17020     ;; Only align when image is not surrounded by paragraph text:
  17021     (when (and par ; when image is not in paragraph, but in table/headline/etc, do not align
  17022                (= (org-element-begin link)
  17023                   (save-excursion
  17024                     (goto-char (org-element-contents-begin par))
  17025                     (skip-chars-forward "\t ")
  17026                     (point)))           ;account for leading space
  17027                                         ;before link
  17028                (<= (- (org-element-contents-end par)
  17029                      (org-element-end link))
  17030                   1))                  ;account for trailing newline
  17031                                         ;at end of paragraph
  17032       (save-match-data
  17033         ;; Look for a valid ":center t" or ":align left|center|right"
  17034         ;; attribute.
  17035         ;;
  17036         ;; An attr_org keyword has the highest priority, with
  17037         ;; any attr.* next.  Choosing between these is
  17038         ;; unspecified.
  17039         (let ((center-re ":\\(center\\)[[:space:]]+t\\b")
  17040               (align-re ":align[[:space:]]+\\(left\\|center\\|right\\)\\b")
  17041               attr-align)
  17042           (catch 'exit
  17043             (org-element-properties-mapc
  17044              (lambda (propname propval)
  17045                (when (and propval
  17046                           (string-match-p ":attr.*" (symbol-name propname)))
  17047                  (setq propval (car-safe propval))
  17048                  (when (or (string-match center-re propval)
  17049                            (string-match align-re propval))
  17050                    (setq attr-align (match-string 1 propval))
  17051                    (when (eq propname :attr_org)
  17052                      (throw 'exit t)))))
  17053              par))
  17054           (if attr-align
  17055               (when (member attr-align '("center" "right")) attr-align)
  17056             ;; No image-specific keyword, check global alignment property
  17057             (when (memq org-image-align '(center right))
  17058               (symbol-name org-image-align))))))))
  17059 
  17060 
  17061 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17062   "Remove inline-display overlay if a corresponding region is modified."
  17063   (when (and ov after)
  17064     (setq org-inline-image-overlays (delete ov org-inline-image-overlays))
  17065     ;; Clear image from cache to avoid image not updating upon
  17066     ;; changing on disk.  See Emacs bug#59902.
  17067     (when (overlay-get ov 'org-image-overlay)
  17068       (image-flush (overlay-get ov 'display)))
  17069     (delete-overlay ov)))
  17070 
  17071 (defun org-remove-inline-images (&optional beg end)
  17072   "Remove inline display of images."
  17073   (interactive)
  17074   (let* ((beg (or beg (point-min)))
  17075          (end (or end (point-max)))
  17076          (overlays (overlays-in beg end)))
  17077     (dolist (ov overlays)
  17078       (when (memq ov org-inline-image-overlays)
  17079         (setq org-inline-image-overlays (delq ov org-inline-image-overlays))
  17080         (delete-overlay ov)))
  17081     ;; Clear removed overlays.
  17082     (dolist (ov org-inline-image-overlays)
  17083       (unless (overlay-buffer ov)
  17084         (setq org-inline-image-overlays (delq ov org-inline-image-overlays))))))
  17085 
  17086 (defvar org-self-insert-command-undo-counter 0)
  17087 (defvar org-speed-command nil)
  17088 
  17089 (defun org-fix-tags-on-the-fly ()
  17090   "Align tags in headline at point.
  17091 Unlike `org-align-tags', this function does nothing if point is
  17092 either not currently on a tagged headline or on a tag."
  17093   (when (and (org-match-line org-tag-line-re)
  17094 	     (< (point) (match-beginning 1)))
  17095     (org-align-tags)))
  17096 
  17097 (defun org--speed-command-p ()
  17098   "Return non-nil when current command is a speed command.
  17099 Set `org-speed-command' to the appropriate command as a side effect."
  17100   (and org-use-speed-commands
  17101        (let ((kv (this-command-keys-vector)))
  17102 	 (setq org-speed-command
  17103 	       (run-hook-with-args-until-success
  17104 		'org-speed-command-hook
  17105 		(make-string 1 (aref kv (1- (length kv)))))))))
  17106 
  17107 (defun org-self-insert-command (N)
  17108   "Like `self-insert-command', use `overwrite-mode' for whitespace in tables.
  17109 If the cursor is in a table looking at whitespace, the whitespace is
  17110 overwritten, and the table is not marked as requiring realignment."
  17111   (interactive "p")
  17112   (cond
  17113    ((org--speed-command-p)
  17114     (cond
  17115      ((commandp org-speed-command)
  17116       (setq this-command org-speed-command)
  17117       (call-interactively org-speed-command))
  17118      ((functionp org-speed-command)
  17119       (funcall org-speed-command))
  17120      ((consp org-speed-command)
  17121       (eval org-speed-command t))
  17122      (t (let (org-use-speed-commands)
  17123 	  (call-interactively 'org-self-insert-command)))))
  17124    ((and
  17125      (= N 1)
  17126      (not (org-region-active-p))
  17127      (org-at-table-p)
  17128      (progn
  17129        ;; Check if we blank the field, and if that triggers align.
  17130        (and (featurep 'org-table)
  17131 	    org-table-auto-blank-field
  17132 	    (memq last-command
  17133 		  '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17134 	    (if (or (eq (char-after) ?\s) (looking-at "[^|\n]*  |"))
  17135 		;; Got extra space, this field does not determine
  17136 		;; column width.
  17137 		(let (org-table-may-need-update) (org-table-blank-field))
  17138 	      ;; No extra space, this field may determine column
  17139 	      ;; width.
  17140 	      (org-table-blank-field)))
  17141        t)
  17142      (looking-at "[^|\n]*  |"))
  17143     ;; There is room for insertion without re-aligning the table.
  17144     ;; Interactively, point should never be inside invisible regions
  17145     (org-fold-core-suppress-folding-fix
  17146       (self-insert-command N))
  17147     (org-table-with-shrunk-field
  17148      (save-excursion
  17149        (skip-chars-forward "^|")
  17150        ;; Do not delete last space, which is
  17151        ;; `org-table-separator-space', but the regular space before
  17152        ;; it.
  17153        (delete-region (- (point) 2) (1- (point))))))
  17154    (t
  17155     (setq org-table-may-need-update t)
  17156     ;; Interactively, point should never be inside invisible regions
  17157     (org-fold-core-suppress-folding-fix
  17158       (self-insert-command N)
  17159       (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  17160     (when org-self-insert-cluster-for-undo
  17161       (if (not (eq last-command 'org-self-insert-command))
  17162 	  (setq org-self-insert-command-undo-counter 1)
  17163 	(if (>= org-self-insert-command-undo-counter 20)
  17164 	    (setq org-self-insert-command-undo-counter 1)
  17165 	  (and (> org-self-insert-command-undo-counter 0)
  17166 	       buffer-undo-list (listp buffer-undo-list)
  17167 	       (not (cadr buffer-undo-list)) ; remove nil entry
  17168 	       (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17169 	  (setq org-self-insert-command-undo-counter
  17170 		(1+ org-self-insert-command-undo-counter))))))))
  17171 
  17172 (defun org-delete-backward-char (N)
  17173   "Like `delete-backward-char', insert whitespace at field end in tables.
  17174 When deleting backwards, in tables this function will insert whitespace in
  17175 front of the next \"|\" separator, to keep the table aligned.  The table will
  17176 still be marked for re-alignment if the field did fill the entire column,
  17177 because, in this case the deletion might narrow the column."
  17178   (interactive "p")
  17179   (save-match-data
  17180     (if (and (= N 1)
  17181 	     (not overwrite-mode)
  17182 	     (not (org-region-active-p))
  17183 	     (not (eq (char-before) ?|))
  17184 	     (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17185 	     (looking-at-p ".*?|")
  17186 	     (org-at-table-p))
  17187 	(progn (forward-char -1) (org-delete-char 1))
  17188       (funcall-interactively #'backward-delete-char N)
  17189       (when org-auto-align-tags (org-fix-tags-on-the-fly)))))
  17190 
  17191 (defun org-delete-char (N)
  17192   "Like `delete-char', but insert whitespace at field end in tables.
  17193 When deleting characters, in tables this function will insert whitespace in
  17194 front of the next \"|\" separator, to keep the table aligned.  The table will
  17195 still be marked for re-alignment if the field did fill the entire column,
  17196 because, in this case the deletion might narrow the column."
  17197   (interactive "p")
  17198   (save-match-data
  17199     (cond
  17200      ((or (/= N 1)
  17201 	  (eq (char-after) ?|)
  17202 	  (save-excursion (skip-chars-backward " \t") (bolp))
  17203 	  (not (org-at-table-p)))
  17204       (delete-char N)
  17205       (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  17206      ((looking-at ".\\(.*?\\)|")
  17207       (let* ((update? org-table-may-need-update)
  17208 	     (noalign (looking-at-p ".*?  |")))
  17209 	(delete-char 1)
  17210 	(org-table-with-shrunk-field
  17211 	 (save-excursion
  17212 	   ;; Last space is `org-table-separator-space', so insert
  17213 	   ;; a regular one before it instead.
  17214 	   (goto-char (- (match-end 0) 2))
  17215 	   (insert " ")))
  17216 	;; If there were two spaces at the end, this field does not
  17217 	;; determine the width of the column.
  17218 	(when noalign (setq org-table-may-need-update update?))))
  17219      (t
  17220       (delete-char N)))))
  17221 
  17222 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17223 (put 'org-self-insert-command 'delete-selection
  17224      (lambda ()
  17225        (unless (org--speed-command-p)
  17226          (not (run-hook-with-args-until-success
  17227              'self-insert-uses-region-functions)))))
  17228 (put 'orgtbl-self-insert-command 'delete-selection
  17229      (lambda ()
  17230        (not (run-hook-with-args-until-success
  17231              'self-insert-uses-region-functions))))
  17232 (put 'org-delete-char 'delete-selection 'supersede)
  17233 (put 'org-delete-backward-char 'delete-selection 'supersede)
  17234 (put 'org-yank 'delete-selection 'yank)
  17235 (put 'org-return 'delete-selection t)
  17236 
  17237 ;; Make `flyspell-mode' delay after some commands
  17238 (put 'org-self-insert-command 'flyspell-delayed t)
  17239 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17240 (put 'org-delete-char 'flyspell-delayed t)
  17241 (put 'org-delete-backward-char 'flyspell-delayed t)
  17242 
  17243 ;; Make pabbrev-mode expand after Org mode commands
  17244 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17245 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17246 
  17247 (defun org-transpose-words ()
  17248   "Transpose words for Org.
  17249 This uses the `org-mode-transpose-word-syntax-table' syntax
  17250 table, which interprets characters in `org-emphasis-alist' as
  17251 word constituents."
  17252   (interactive)
  17253   (with-syntax-table org-mode-transpose-word-syntax-table
  17254     (call-interactively 'transpose-words)))
  17255 
  17256 (defvar org-ctrl-c-ctrl-c-hook nil
  17257   "Hook for functions attaching themselves to \\`C-c C-c'.
  17258 
  17259 This can be used to add additional functionality to the \\`C-c C-c'
  17260 key which executes context-dependent commands.  This hook is run
  17261 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17262 run after the last test.
  17263 
  17264 Each function will be called with no arguments.  The function
  17265 must check if the context is appropriate for it to act.  If yes,
  17266 it should do its thing and then return a non-nil value.  If the
  17267 context is wrong, just do nothing and return nil.")
  17268 
  17269 (defvar org-ctrl-c-ctrl-c-final-hook nil
  17270   "Hook for functions attaching themselves to \\`C-c C-c'.
  17271 
  17272 This can be used to add additional functionality to the \\`C-c C-c'
  17273 key which executes context-dependent commands.  This hook is run
  17274 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17275 before the first test.
  17276 
  17277 Each function will be called with no arguments.  The function
  17278 must check if the context is appropriate for it to act.  If yes,
  17279 it should do its thing and then return a non-nil value.  If the
  17280 context is wrong, just do nothing and return nil.")
  17281 
  17282 (defvar org-tab-after-check-for-table-hook nil
  17283   "Hook for functions to attach themselves to TAB.
  17284 See `org-ctrl-c-ctrl-c-hook' for more information.
  17285 This hook runs after it has been established that the cursor is not in a
  17286 table, but before checking if the cursor is in a headline or if global cycling
  17287 should be done.
  17288 If any function in this hook returns t, not other actions like visibility
  17289 cycling will be done.")
  17290 
  17291 (defvar org-tab-after-check-for-cycling-hook nil
  17292   "Hook for functions to attach themselves to TAB.
  17293 See `org-ctrl-c-ctrl-c-hook' for more information.
  17294 This hook runs after it has been established that not table field motion and
  17295 not visibility should be done because of current context.  This is probably
  17296 the place where a package like yasnippets can hook in.")
  17297 
  17298 (defvar org-tab-before-tab-emulation-hook nil
  17299   "Hook for functions to attach themselves to TAB.
  17300 See `org-ctrl-c-ctrl-c-hook' for more information.
  17301 This hook runs after every other options for TAB have been exhausted, but
  17302 before indentation and \t insertion takes place.")
  17303 
  17304 (defvar org-metaleft-hook nil
  17305   "Hook for functions attaching themselves to `M-left'.
  17306 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17307 (defvar org-metaleft-final-hook nil
  17308   "Hook for functions attaching themselves to `M-left'.
  17309 This one runs after all options have been excluded.
  17310 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17311 (defvar org-metaright-hook nil
  17312   "Hook for functions attaching themselves to `M-right'.
  17313 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17314 (defvar org-metaright-final-hook nil
  17315   "Hook for functions attaching themselves to `M-right'.
  17316 This one runs after all options have been excluded.
  17317 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17318 (defvar org-metaup-hook nil
  17319   "Hook for functions attaching themselves to `M-up'.
  17320 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17321 (defvar org-metaup-final-hook nil
  17322   "Hook for functions attaching themselves to `M-up'.
  17323 This one runs after all other options except
  17324 `org-drag-element-backward' have been excluded.  See
  17325 `org-ctrl-c-ctrl-c-hook' for more information.")
  17326 (defvar org-metadown-hook nil
  17327   "Hook for functions attaching themselves to `M-down'.
  17328 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17329 (defvar org-metadown-final-hook nil
  17330   "Hook for functions attaching themselves to `M-down'.
  17331 This one runs after all other options except
  17332 `org-drag-element-forward' have been excluded.  See
  17333 `org-ctrl-c-ctrl-c-hook' for more information.")
  17334 (defvar org-shiftmetaleft-hook nil
  17335   "Hook for functions attaching themselves to `M-S-left'.
  17336 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17337 (defvar org-shiftmetaleft-final-hook nil
  17338   "Hook for functions attaching themselves to `M-S-left'.
  17339 This one runs after all other options have been excluded.  See
  17340 `org-ctrl-c-ctrl-c-hook' for more information.")
  17341 (defvar org-shiftmetaright-hook nil
  17342   "Hook for functions attaching themselves to `M-S-right'.
  17343 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17344 (defvar org-shiftmetaright-final-hook nil
  17345   "Hook for functions attaching themselves to `M-S-right'.
  17346 This one runs after all other options have been excluded.  See
  17347 `org-ctrl-c-ctrl-c-hook' for more information.")
  17348 (defvar org-shiftmetaup-hook nil
  17349   "Hook for functions attaching themselves to `M-S-up'.
  17350 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17351 (defvar org-shiftmetaup-final-hook nil
  17352   "Hook for functions attaching themselves to `M-S-up'.
  17353 This one runs after all other options except
  17354 `org-drag-line-backward' have been excluded.  See
  17355 `org-ctrl-c-ctrl-c-hook' for more information.")
  17356 (defvar org-shiftmetadown-hook nil
  17357   "Hook for functions attaching themselves to `M-S-down'.
  17358 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17359 (defvar org-shiftmetadown-final-hook nil
  17360   "Hook for functions attaching themselves to `M-S-down'.
  17361 This one runs after all other options except
  17362 `org-drag-line-forward' have been excluded.  See
  17363 `org-ctrl-c-ctrl-c-hook' for more information.")
  17364 (defvar org-metareturn-hook nil
  17365   "Hook for functions attaching themselves to `M-RET'.
  17366 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17367 (defvar org-shiftup-hook nil
  17368   "Hook for functions attaching themselves to `S-up'.
  17369 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17370 (defvar org-shiftup-final-hook nil
  17371   "Hook for functions attaching themselves to `S-up'.
  17372 This one runs after all other options except shift-select have been excluded.
  17373 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17374 (defvar org-shiftdown-hook nil
  17375   "Hook for functions attaching themselves to `S-down'.
  17376 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17377 (defvar org-shiftdown-final-hook nil
  17378   "Hook for functions attaching themselves to `S-down'.
  17379 This one runs after all other options except shift-select have been excluded.
  17380 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17381 (defvar org-shiftleft-hook nil
  17382   "Hook for functions attaching themselves to `S-left'.
  17383 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17384 (defvar org-shiftleft-final-hook nil
  17385   "Hook for functions attaching themselves to `S-left'.
  17386 This one runs after all other options except shift-select have been excluded.
  17387 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17388 (defvar org-shiftright-hook nil
  17389   "Hook for functions attaching themselves to `S-right'.
  17390 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17391 (defvar org-shiftright-final-hook nil
  17392   "Hook for functions attaching themselves to `S-right'.
  17393 This one runs after all other options except shift-select have been excluded.
  17394 See `org-ctrl-c-ctrl-c-hook' for more information.")
  17395 
  17396 (defun org-modifier-cursor-error ()
  17397   "Throw an error, a modified cursor command was applied in wrong context."
  17398   (user-error "This command is active in special context like tables, headlines or items"))
  17399 
  17400 (defun org-shiftselect-error ()
  17401   "Throw an error because Shift-Cursor command was applied in wrong context."
  17402   (if (and (boundp 'shift-select-mode) shift-select-mode)
  17403       (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17404     (user-error "This command works only in special context like headlines or timestamps")))
  17405 
  17406 (defun org-call-for-shift-select (cmd)
  17407   (let ((this-command-keys-shift-translated t))
  17408     (call-interactively cmd)))
  17409 
  17410 (defun org-shifttab (&optional arg)
  17411   "Global visibility cycling or move to previous table field.
  17412 Call `org-table-previous-field' within a table.
  17413 When ARG is nil, cycle globally through visibility states.
  17414 When ARG is a numeric prefix, show contents of this level."
  17415   (interactive "P")
  17416   (cond
  17417    ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17418    ((integerp arg)
  17419     (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17420       (message "Content view to level: %d" arg)
  17421       (org-cycle-content (prefix-numeric-value arg2))
  17422       (org-cycle-show-empty-lines t)
  17423       (setq org-cycle-global-status 'overview)
  17424       (run-hook-with-args 'org-cycle-hook 'overview)))
  17425    (t (call-interactively 'org-cycle-global))))
  17426 
  17427 (defun org-shiftmetaleft ()
  17428   "Promote subtree or delete table column.
  17429 Calls `org-promote-subtree', `org-outdent-item-tree', or
  17430 `org-table-delete-column', depending on context.  See the
  17431 individual commands for more information.
  17432 
  17433 This function runs the functions in `org-shiftmetaleft-hook' one
  17434 by one as a first step, and exits immediately if a function from
  17435 the hook returns non-nil.  In the absence of a specific context,
  17436 the function also runs `org-shiftmetaleft-final-hook' using the
  17437 same logic."
  17438   (interactive)
  17439   (cond
  17440    ((and (eq system-type 'darwin)
  17441          (or (eq org-support-shift-select 'always)
  17442              (and org-support-shift-select (org-region-active-p))))
  17443     (org-call-for-shift-select 'backward-char))
  17444    ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17445    ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17446    ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17447    ((if (not (org-region-active-p)) (org-at-item-p)
  17448       (save-excursion (goto-char (region-beginning))
  17449 		      (org-at-item-p)))
  17450     (call-interactively 'org-outdent-item-tree))
  17451    ((run-hook-with-args-until-success 'org-shiftmetaleft-final-hook))
  17452    (t (org-modifier-cursor-error))))
  17453 
  17454 (defun org-shiftmetaright ()
  17455   "Demote subtree or insert table column.
  17456 Calls `org-demote-subtree', `org-indent-item-tree', or
  17457 `org-table-insert-column', depending on context.  See the
  17458 individual commands for more information.
  17459 
  17460 This function runs the functions in `org-shiftmetaright-hook' one
  17461 by one as a first step, and exits immediately if a function from
  17462 the hook returns non-nil.  In the absence of a specific context,
  17463 the function also runs `org-shiftmetaright-final-hook' using the
  17464 same logic."
  17465   (interactive)
  17466   (cond
  17467    ((and (eq system-type 'darwin)
  17468          (or (eq org-support-shift-select 'always)
  17469              (and org-support-shift-select (org-region-active-p))))
  17470     (org-call-for-shift-select 'forward-char))
  17471    ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17472    ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17473    ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17474    ((if (not (org-region-active-p)) (org-at-item-p)
  17475       (save-excursion (goto-char (region-beginning))
  17476 		      (org-at-item-p)))
  17477     (call-interactively 'org-indent-item-tree))
  17478    ((run-hook-with-args-until-success 'org-shiftmetaright-final-hook))
  17479    (t (org-modifier-cursor-error))))
  17480 
  17481 (defun org-shiftmetaup (&optional _arg)
  17482   "Drag the line at point up.
  17483 In a table, kill the current row.
  17484 On a clock timestamp, update the value of the timestamp like `S-<up>'
  17485 but also adjust the previous clocked item in the clock history.
  17486 Everywhere else, drag the line at point up.
  17487 
  17488 This function runs the functions in `org-shiftmetaup-hook' one by
  17489 one as a first step, and exits immediately if a function from the
  17490 hook returns non-nil.  In the absence of a specific context, the
  17491 function also runs `org-shiftmetaup-final-hook' using the same
  17492 logic."
  17493   (interactive "P")
  17494   (cond
  17495    ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17496    ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17497    ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17498 			   (call-interactively 'org-timestamp-up)))
  17499    ((run-hook-with-args-until-success 'org-shiftmetaup-final-hook))
  17500    (t (call-interactively 'org-drag-line-backward))))
  17501 
  17502 (defun org-shiftmetadown (&optional _arg)
  17503   "Drag the line at point down.
  17504 In a table, insert an empty row at the current line.
  17505 On a clock timestamp, update the value of the timestamp like `S-<down>'
  17506 but also adjust the previous clocked item in the clock history.
  17507 Everywhere else, drag the line at point down.
  17508 
  17509 This function runs the functions in `org-shiftmetadown-hook' one
  17510 by one as a first step, and exits immediately if a function from
  17511 the hook returns non-nil.  In the absence of a specific context,
  17512 the function also runs `org-shiftmetadown-final-hook' using the
  17513 same logic."
  17514   (interactive "P")
  17515   (cond
  17516    ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17517    ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17518    ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17519 			   (call-interactively 'org-timestamp-down)))
  17520    ((run-hook-with-args-until-success 'org-shiftmetadown-final-hook))
  17521    (t (call-interactively 'org-drag-line-forward))))
  17522 
  17523 (defsubst org-hidden-tree-error ()
  17524   (user-error
  17525    "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17526 
  17527 (defun org-metaleft (&optional _arg)
  17528   "Promote heading, list item at point or move table column left.
  17529 
  17530 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17531 depending on context.  With no specific context, calls the Emacs
  17532 default `backward-word'.  See the individual commands for more
  17533 information.
  17534 
  17535 This function runs the functions in `org-metaleft-hook' one by
  17536 one as a first step, and exits immediately if a function from the
  17537 hook returns non-nil.  In the absence of a specific context, the
  17538 function runs `org-metaleft-final-hook' using the same logic."
  17539   (interactive "P")
  17540   (cond
  17541    ((run-hook-with-args-until-success 'org-metaleft-hook))
  17542    ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17543    ((org-with-limited-levels
  17544      (or (org-at-heading-p)
  17545 	 (and (org-region-active-p)
  17546 	      (save-excursion
  17547 		(goto-char (region-beginning))
  17548 		(org-at-heading-p)))))
  17549     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17550     (call-interactively 'org-do-promote))
  17551    ;; At an inline task.
  17552    ((org-at-heading-p)
  17553     (call-interactively 'org-inlinetask-promote))
  17554    ((or (org-at-item-p)
  17555 	(and (org-region-active-p)
  17556 	     (save-excursion
  17557 	       (goto-char (region-beginning))
  17558 	       (org-at-item-p))))
  17559     (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17560     (call-interactively 'org-outdent-item))
  17561    ((run-hook-with-args-until-success 'org-metaleft-final-hook))
  17562    (t (call-interactively 'backward-word))))
  17563 
  17564 (defun org-metaright (&optional _arg)
  17565   "Demote heading, list item at point or move table column right.
  17566 
  17567 In front of a drawer or a block keyword, indent it correctly.
  17568 
  17569 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17570 `org-indent-drawer' or `org-indent-block' depending on context.
  17571 With no specific context, calls the Emacs default `forward-word'.
  17572 See the individual commands for more information.
  17573 
  17574 This function runs the functions in `org-metaright-hook' one by
  17575 one as a first step, and exits immediately if a function from the
  17576 hook returns non-nil.  In the absence of a specific context, the
  17577 function runs `org-metaright-final-hook' using the same logic."
  17578   (interactive "P")
  17579   (cond
  17580    ((run-hook-with-args-until-success 'org-metaright-hook))
  17581    ((org-at-table-p) (call-interactively 'org-table-move-column))
  17582    ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17583    ((org-at-block-p) (call-interactively 'org-indent-block))
  17584    ((org-with-limited-levels
  17585      (or (org-at-heading-p)
  17586 	 (and (org-region-active-p)
  17587 	      (save-excursion
  17588 		(goto-char (region-beginning))
  17589 		(org-at-heading-p)))))
  17590     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17591     (call-interactively 'org-do-demote))
  17592    ;; At an inline task.
  17593    ((org-at-heading-p)
  17594     (call-interactively 'org-inlinetask-demote))
  17595    ((or (org-at-item-p)
  17596 	(and (org-region-active-p)
  17597 	     (save-excursion
  17598 	       (goto-char (region-beginning))
  17599 	       (org-at-item-p))))
  17600     (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17601     (call-interactively 'org-indent-item))
  17602    ((run-hook-with-args-until-success 'org-metaright-final-hook))
  17603    (t (call-interactively 'forward-word))))
  17604 
  17605 (defun org-check-for-hidden (what)
  17606   "Check if there are hidden headlines/items in the current visual line.
  17607 WHAT can be either `headlines' or `items'.  If the current line is
  17608 an outline or item heading and it has a folded subtree below it,
  17609 this function returns t, nil otherwise."
  17610   (let ((re (cond
  17611 	     ((eq what 'headlines) org-outline-regexp-bol)
  17612 	     ((eq what 'items) (org-item-beginning-re))
  17613 	     (t (error "This should not happen"))))
  17614 	beg end)
  17615     (save-excursion
  17616       (catch 'exit
  17617 	(unless (org-region-active-p)
  17618           (setq beg (line-beginning-position))
  17619 	  (forward-line 1)
  17620 	  (while (and (not (eobp)) ;; this is like `next-line'
  17621 		      (org-invisible-p (1- (point))))
  17622 	    (forward-line 1))
  17623 	  (setq end (point))
  17624 	  (goto-char beg)
  17625           (goto-char (line-end-position))
  17626 	  (setq end (max end (point)))
  17627 	  (while (re-search-forward re end t)
  17628 	    (when (org-invisible-p (match-beginning 0))
  17629 	      (throw 'exit t))))
  17630 	nil))))
  17631 
  17632 (defun org-metaup (&optional _arg)
  17633   "Move subtree up or move table row up.
  17634 Calls `org-move-subtree-up' or `org-table-move-row' or
  17635 `org-move-item-up', depending on context.  Everywhere else, move
  17636 backward the element at point.  See the individual commands for
  17637 more information.
  17638 
  17639 This function runs the functions in `org-metaup-hook' one by one
  17640 as a first step, and exits immediately if a function from the
  17641 hook returns non-nil.  In the absence of a specific context, the
  17642 function runs `org-metaup-final-hook' using the same logic."
  17643   (interactive "P")
  17644   (cond
  17645    ((run-hook-with-args-until-success 'org-metaup-hook))
  17646    ((and (org-region-active-p)
  17647          (org-with-limited-levels
  17648           (save-excursion
  17649             (goto-char (region-beginning))
  17650             (org-at-heading-p))))
  17651     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17652     (let ((beg (region-beginning))
  17653           (end (region-end)))
  17654       (save-excursion
  17655         ;; Go a little earlier because `org-move-subtree-down' will
  17656         ;; insert before markers and we may overshoot in some cases.
  17657         (goto-char (max beg (1- end)))
  17658         (setq end (point-marker))
  17659         (goto-char beg)
  17660         (let ((level (org-current-level)))
  17661           (when (or (and (> level 1) (re-search-forward (format "^\\*\\{1,%s\\} " (1- level)) end t))
  17662                     ;; Search previous subtree.
  17663                     (progn
  17664                       (goto-char beg)
  17665                       (forward-line 0)
  17666                       (not (re-search-backward (format "^\\*\\{%s\\} " level) nil t))))
  17667             (user-error "Cannot move past superior level or buffer limit"))
  17668           ;; Drag first subtree above below the selected.
  17669           (while (< (point) end)
  17670             (let ((deactivate-mark nil))
  17671               (call-interactively 'org-move-subtree-down)))))))
  17672    ((org-region-active-p)
  17673     (let* ((a (save-excursion
  17674                 (goto-char (region-beginning))
  17675                 (line-beginning-position)))
  17676            (b (save-excursion
  17677                 (goto-char (region-end))
  17678                 (if (bolp) (1- (point)) (line-end-position))))
  17679            (c (save-excursion
  17680                 (goto-char a)
  17681                 (move-beginning-of-line 0)
  17682                 (point)))
  17683            (d (save-excursion
  17684                 (goto-char a)
  17685                 (move-end-of-line 0)
  17686                 (point)))
  17687            (deactivate-mark nil)
  17688            (swap? (< (point) (mark))))
  17689       (transpose-regions a b c d)
  17690       (set-mark c)
  17691       (goto-char (+ c (- b a)))
  17692       (when swap? (exchange-point-and-mark))))
  17693    ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  17694    ((and (featurep 'org-inlinetask)
  17695          (org-inlinetask-in-task-p))
  17696     (org-drag-element-backward))
  17697    ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  17698    ((org-at-item-p) (call-interactively 'org-move-item-up))
  17699    ((run-hook-with-args-until-success 'org-metaup-final-hook))
  17700    (t (org-drag-element-backward))))
  17701 
  17702 (defun org-metadown (&optional _arg)
  17703   "Move subtree down or move table row down.
  17704 Calls `org-move-subtree-down' or `org-table-move-row' or
  17705 `org-move-item-down', depending on context.  Everywhere else,
  17706 move forward the element at point.  See the individual commands
  17707 for more information.
  17708 
  17709 This function runs the functions in `org-metadown-hook' one by
  17710 one as a first step, and exits immediately if a function from the
  17711 hook returns non-nil.  In the absence of a specific context, the
  17712 function runs `org-metadown-final-hook' using the same logic."
  17713   (interactive "P")
  17714   (cond
  17715    ((run-hook-with-args-until-success 'org-metadown-hook))
  17716    ((and (org-region-active-p)
  17717          (org-with-limited-levels
  17718           (save-excursion
  17719             (goto-char (region-beginning))
  17720             (org-at-heading-p))))
  17721     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17722     (let ((beg (region-beginning))
  17723           (end (region-end)))
  17724       (save-excursion
  17725         (goto-char beg)
  17726         (setq beg (point-marker))
  17727         (let ((level (org-current-level)))
  17728           (when (or (and (> level 1) (re-search-forward (format "^\\*\\{1,%s\\} " (1- level)) end t))
  17729                     ;; Search next subtree.
  17730                     (progn
  17731                       (goto-char end)
  17732                       (not (re-search-forward (format "^\\*\\{%s\\} " level) nil t))))
  17733             (user-error "Cannot move past superior level or buffer limit"))
  17734           ;; Drag first subtree below above the selected.
  17735           (while (> (point) beg)
  17736             (let ((deactivate-mark nil))
  17737               (call-interactively 'org-move-subtree-up)))))))
  17738    ((org-region-active-p)
  17739     (let* ((a (save-excursion
  17740                 (goto-char (region-beginning))
  17741                 (line-beginning-position)))
  17742 	   (b (save-excursion
  17743                 (goto-char (region-end))
  17744                 (if (bolp) (1- (point)) (line-end-position))))
  17745 	   (c (save-excursion
  17746                 (goto-char b)
  17747                 (move-beginning-of-line (if (bolp) 1 2))
  17748                 (point)))
  17749 	   (d (save-excursion
  17750                 (goto-char b)
  17751                 (move-end-of-line (if (bolp) 1 2))
  17752                 (point)))
  17753            (deactivate-mark nil)
  17754            (swap? (< (point) (mark))))
  17755       (transpose-regions a b c d)
  17756       (set-mark (+ 1 a (- d c)))
  17757       (goto-char (+ 1 a (- d c) (- b a)))
  17758       (when swap? (exchange-point-and-mark))))
  17759    ((org-at-table-p) (call-interactively 'org-table-move-row))
  17760    ((and (featurep 'org-inlinetask)
  17761          (org-inlinetask-in-task-p))
  17762     (org-drag-element-forward))
  17763    ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  17764    ((org-at-item-p) (call-interactively 'org-move-item-down))
  17765    ((run-hook-with-args-until-success 'org-metadown-final-hook))
  17766    (t (org-drag-element-forward))))
  17767 
  17768 (defun org-shiftup (&optional arg)
  17769   "Act on current element according to context.
  17770 Call `org-timestamp-up' or `org-priority-up', or
  17771 `org-previous-item', or `org-table-move-cell-up'.  See the
  17772 individual commands for more information.
  17773 
  17774 This function runs the functions in `org-shiftup-hook' one by one
  17775 as a first step, and exits immediately if a function from the
  17776 hook returns non-nil.  In the absence of a specific context, the
  17777 function also runs `org-shiftup-final-hook' using the same logic.
  17778 
  17779 If none of the previous steps succeed and
  17780 `org-support-shift-select' is non-nil, the function runs
  17781 `shift-select-mode' associated command.  See that variable for
  17782 more information."
  17783   (interactive "P")
  17784   (cond
  17785    ((run-hook-with-args-until-success 'org-shiftup-hook))
  17786    ((and org-support-shift-select (org-region-active-p))
  17787     (org-call-for-shift-select 'previous-line))
  17788    ((org-at-timestamp-p 'lax)
  17789     (call-interactively (if org-edit-timestamp-down-means-later
  17790 			    'org-timestamp-down 'org-timestamp-up)))
  17791    ((and (not (eq org-support-shift-select 'always))
  17792 	 org-priority-enable-commands
  17793 	 (org-at-heading-p))
  17794     (call-interactively 'org-priority-up))
  17795    ((and (not org-support-shift-select) (org-at-item-p))
  17796     (call-interactively 'org-previous-item))
  17797    ((org-clocktable-try-shift 'up arg))
  17798    ((and (not (eq org-support-shift-select 'always))
  17799 	 (org-at-table-p))
  17800     (org-table-move-cell-up))
  17801    ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  17802    (org-support-shift-select
  17803     (org-call-for-shift-select 'previous-line))
  17804    (t (org-shiftselect-error))))
  17805 
  17806 (defun org-shiftdown (&optional arg)
  17807   "Act on current element according to context.
  17808 Call `org-timestamp-down' or `org-priority-down', or
  17809 `org-next-item', or `org-table-move-cell-down'.  See the
  17810 individual commands for more information.
  17811 
  17812 This function runs the functions in `org-shiftdown-hook' one by
  17813 one as a first step, and exits immediately if a function from the
  17814 hook returns non-nil.  In the absence of a specific context, the
  17815 function also runs `org-shiftdown-final-hook' using the same
  17816 logic.
  17817 
  17818 If none of the previous steps succeed and
  17819 `org-support-shift-select' is non-nil, the function runs
  17820 `shift-select-mode' associated command.  See that variable for
  17821 more information."
  17822   (interactive "P")
  17823   (cond
  17824    ((run-hook-with-args-until-success 'org-shiftdown-hook))
  17825    ((and org-support-shift-select (org-region-active-p))
  17826     (org-call-for-shift-select 'next-line))
  17827    ((org-at-timestamp-p 'lax)
  17828     (call-interactively (if org-edit-timestamp-down-means-later
  17829 			    'org-timestamp-up 'org-timestamp-down)))
  17830    ((and (not (eq org-support-shift-select 'always))
  17831 	 org-priority-enable-commands
  17832 	 (org-at-heading-p))
  17833     (call-interactively 'org-priority-down))
  17834    ((and (not org-support-shift-select) (org-at-item-p))
  17835     (call-interactively 'org-next-item))
  17836    ((org-clocktable-try-shift 'down arg))
  17837    ((and (not (eq org-support-shift-select 'always))
  17838 	 (org-at-table-p))
  17839     (org-table-move-cell-down))
  17840    ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  17841    (org-support-shift-select
  17842     (org-call-for-shift-select 'next-line))
  17843    (t (org-shiftselect-error))))
  17844 
  17845 (defun org-shiftright (&optional arg)
  17846   "Act on the current element according to context.
  17847 This does one of the following:
  17848 
  17849 - switch a timestamp at point one day into the future
  17850 - on a headline, switch to the next TODO keyword
  17851 - on an item, switch entire list to the next bullet type
  17852 - on a property line, switch to the next allowed value
  17853 - on a clocktable definition line, move time block into the future
  17854 - in a table, move a single cell right
  17855 
  17856 This function runs the functions in `org-shiftright-hook' one by
  17857 one as a first step, and exits immediately if a function from the
  17858 hook returns non-nil.  In the absence of a specific context, the
  17859 function runs `org-shiftright-final-hook' using the same logic.
  17860 
  17861 If none of the above succeeds and `org-support-shift-select' is
  17862 non-nil, runs `shift-select-mode' specific command.  See that
  17863 variable for more information."
  17864   (interactive "P")
  17865   (cond
  17866    ((run-hook-with-args-until-success 'org-shiftright-hook))
  17867    ((and org-support-shift-select (org-region-active-p))
  17868     (org-call-for-shift-select 'forward-char))
  17869    ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  17870    ((and (not (eq org-support-shift-select 'always))
  17871 	 (org-at-heading-p))
  17872     (let ((org-inhibit-logging
  17873 	   (not org-treat-S-cursor-todo-selection-as-state-change))
  17874 	  (org-inhibit-blocking
  17875 	   (not org-treat-S-cursor-todo-selection-as-state-change)))
  17876       (org-call-with-arg 'org-todo 'right)))
  17877    ((or (and org-support-shift-select
  17878 	     (not (eq org-support-shift-select 'always))
  17879 	     (org-at-item-bullet-p))
  17880 	(and (not org-support-shift-select) (org-at-item-p)))
  17881     (org-call-with-arg 'org-cycle-list-bullet nil))
  17882    ((and (not (eq org-support-shift-select 'always))
  17883 	 (org-at-property-p))
  17884     (call-interactively 'org-property-next-allowed-value))
  17885    ((org-clocktable-try-shift 'right arg))
  17886    ((and (not (eq org-support-shift-select 'always))
  17887 	 (org-at-table-p))
  17888     (org-table-move-cell-right))
  17889    ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  17890    (org-support-shift-select
  17891     (org-call-for-shift-select 'forward-char))
  17892    (t (org-shiftselect-error))))
  17893 
  17894 (defun org-shiftleft (&optional arg)
  17895   "Act on current element according to context.
  17896 This does one of the following:
  17897 
  17898 - switch a timestamp at point one day into the past
  17899 - on a headline, switch to the previous TODO keyword.
  17900 - on an item, switch entire list to the previous bullet type
  17901 - on a property line, switch to the previous allowed value
  17902 - on a clocktable definition line, move time block into the past
  17903 - in a table, move a single cell left
  17904 
  17905 This function runs the functions in `org-shiftleft-hook' one by
  17906 one as a first step, and exits immediately if a function from the
  17907 hook returns non-nil.  In the absence of a specific context, the
  17908 function runs `org-shiftleft-final-hook' using the same logic.
  17909 
  17910 If none of the above succeeds and `org-support-shift-select' is
  17911 non-nil, runs `shift-select-mode' specific command.  See that
  17912 variable for more information."
  17913   (interactive "P")
  17914   (cond
  17915    ((run-hook-with-args-until-success 'org-shiftleft-hook))
  17916    ((and org-support-shift-select (org-region-active-p))
  17917     (org-call-for-shift-select 'backward-char))
  17918    ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  17919    ((and (not (eq org-support-shift-select 'always))
  17920 	 (org-at-heading-p))
  17921     (let ((org-inhibit-logging
  17922 	   (not org-treat-S-cursor-todo-selection-as-state-change))
  17923 	  (org-inhibit-blocking
  17924 	   (not org-treat-S-cursor-todo-selection-as-state-change)))
  17925       (org-call-with-arg 'org-todo 'left)))
  17926    ((or (and org-support-shift-select
  17927 	     (not (eq org-support-shift-select 'always))
  17928 	     (org-at-item-bullet-p))
  17929 	(and (not org-support-shift-select) (org-at-item-p)))
  17930     (org-call-with-arg 'org-cycle-list-bullet 'previous))
  17931    ((and (not (eq org-support-shift-select 'always))
  17932 	 (org-at-property-p))
  17933     (call-interactively 'org-property-previous-allowed-value))
  17934    ((org-clocktable-try-shift 'left arg))
  17935    ((and (not (eq org-support-shift-select 'always))
  17936 	 (org-at-table-p))
  17937     (org-table-move-cell-left))
  17938    ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  17939    (org-support-shift-select
  17940     (org-call-for-shift-select 'backward-char))
  17941    (t (org-shiftselect-error))))
  17942 
  17943 (defun org-shiftcontrolright ()
  17944   "Switch to next TODO set."
  17945   (interactive)
  17946   (cond
  17947    ((and org-support-shift-select (org-region-active-p))
  17948     (org-call-for-shift-select 'forward-word))
  17949    ((and (not (eq org-support-shift-select 'always))
  17950 	 (org-at-heading-p))
  17951     (org-call-with-arg 'org-todo 'nextset))
  17952    (org-support-shift-select
  17953     (org-call-for-shift-select 'forward-word))
  17954    (t (org-shiftselect-error))))
  17955 
  17956 (defun org-shiftcontrolleft ()
  17957   "Switch to previous TODO set."
  17958   (interactive)
  17959   (cond
  17960    ((and org-support-shift-select (org-region-active-p))
  17961     (org-call-for-shift-select 'backward-word))
  17962    ((and (not (eq org-support-shift-select 'always))
  17963 	 (org-at-heading-p))
  17964     (org-call-with-arg 'org-todo 'previousset))
  17965    (org-support-shift-select
  17966     (org-call-for-shift-select 'backward-word))
  17967    (t (org-shiftselect-error))))
  17968 
  17969 (defun org-shiftcontrolup (&optional n)
  17970   "Change timestamps synchronously up in CLOCK log lines.
  17971 Optional argument N tells to change by that many units."
  17972   (interactive "P")
  17973   (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17974       (let (org-support-shift-select)
  17975 	(org-clock-timestamps-up n))
  17976     (user-error "Not at a clock log")))
  17977 
  17978 (defun org-shiftcontroldown (&optional n)
  17979   "Change timestamps synchronously down in CLOCK log lines.
  17980 Optional argument N tells to change by that many units."
  17981   (interactive "P")
  17982   (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17983       (let (org-support-shift-select)
  17984 	(org-clock-timestamps-down n))
  17985     (user-error "Not at a clock log")))
  17986 
  17987 (defun org-increase-number-at-point (&optional inc)
  17988   "Increment the number at point.
  17989 With an optional prefix numeric argument INC, increment using
  17990 this numeric value."
  17991   (interactive "p")
  17992   (if (not (number-at-point))
  17993       (user-error "Not on a number")
  17994     (unless inc (setq inc 1))
  17995     (let ((pos (point))
  17996 	  (beg (skip-chars-backward "-+^/*0-9eE."))
  17997 	  (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  17998       (setq nap (buffer-substring-no-properties
  17999 		 (+ pos beg) (+ pos beg end)))
  18000       (delete-region (+ pos beg) (+ pos beg end))
  18001       (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18002     (when (org-at-table-p)
  18003       (org-table-align)
  18004       (org-table-end-of-field 1))))
  18005 
  18006 (defun org-decrease-number-at-point (&optional inc)
  18007   "Decrement the number at point.
  18008 With an optional prefix numeric argument INC, decrement using
  18009 this numeric value."
  18010   (interactive "p")
  18011   (org-increase-number-at-point (- (or inc 1))))
  18012 
  18013 (defun org-ctrl-c-ret ()
  18014   "Call `org-table-hline-and-move' or `org-insert-heading'."
  18015   (interactive)
  18016   (cond
  18017    ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18018    (t (call-interactively 'org-insert-heading))))
  18019 
  18020 (defun org-copy-visible (beg end)
  18021   "Copy the visible parts of the region."
  18022   (interactive "r")
  18023   (let ((result ""))
  18024     (while (/= beg end)
  18025       (while (org-invisible-p beg)
  18026 	(setq beg (org-fold-next-visibility-change beg end)))
  18027       (let ((next (org-fold-next-visibility-change beg end)))
  18028 	(setq result (concat result (buffer-substring beg next)))
  18029 	(setq beg next)))
  18030     ;; Prevent Emacs from adding full selected text to `kill-ring'
  18031     ;; when `select-enable-primary' is non-nil.  This special value of
  18032     ;; `deactivate-mark' only works since Emacs 29.
  18033     (setq deactivate-mark 'dont-save)
  18034     (kill-new result)
  18035     (message "Visible strings have been copied to the kill ring.")))
  18036 
  18037 (defun org-copy-special ()
  18038   "Copy region in table or copy current subtree.
  18039 Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18040 context.  See the individual commands for more information."
  18041   (interactive)
  18042   (call-interactively
  18043    (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18044 
  18045 (defun org-cut-special ()
  18046   "Cut region in table or cut current subtree.
  18047 Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18048 context.  See the individual commands for more information."
  18049   (interactive)
  18050   (call-interactively
  18051    (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18052 
  18053 (defun org-paste-special (arg)
  18054   "Paste rectangular region into table, or past subtree relative to level.
  18055 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18056 See the individual commands for more information."
  18057   (interactive "P")
  18058   (if (org-at-table-p)
  18059       (org-table-paste-rectangle)
  18060     (org-paste-subtree arg)))
  18061 
  18062 (defun org-edit-special (&optional arg)
  18063   "Call a special editor for the element at point.
  18064 When at a table, call the formula editor with `org-table-edit-formulas'.
  18065 When at table.el table, edit it in dedicated buffer.
  18066 When in a source code block, call `org-edit-src-code'; with prefix
  18067   argument, switch to session buffer.
  18068 When in an example block, call `org-edit-src-code'.
  18069 When in an inline code block, call `org-edit-inline-src-code'.
  18070 When in a fixed-width region, call `org-edit-fixed-width-region'.
  18071 When in an export block, call `org-edit-export-block'.
  18072 When in a comment block, call `org-edit-comment-block'.
  18073 When in a LaTeX environment, call `org-edit-latex-environment'.
  18074 When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  18075 When at a footnote reference, call `org-edit-footnote-reference'.
  18076 When at a planning line call, `org-deadline' and/or `org-schedule'.
  18077 When at an active timestamp, call `org-timestamp'.
  18078 When at an inactive timestamp, call `org-timestamp-inactive'.
  18079 On a link, call `ffap' to visit the link at point.
  18080 Otherwise, return a user error."
  18081   (interactive "P")
  18082   (let ((element (org-element-at-point)))
  18083     (barf-if-buffer-read-only)
  18084     (pcase (org-element-type element)
  18085       (`src-block
  18086        (if (not arg) (org-edit-src-code)
  18087 	 (let* ((info (org-babel-get-src-block-info))
  18088 		(lang (nth 0 info))
  18089 		(params (nth 2 info))
  18090 		(session (cdr (assq :session params))))
  18091 	   (if (not session) (org-edit-src-code)
  18092 	     ;; At a source block with a session and function called
  18093 	     ;; with an ARG: switch to the buffer related to the
  18094 	     ;; inferior process.
  18095 	     (switch-to-buffer
  18096 	      (funcall (intern (concat "org-babel-prep-session:" lang))
  18097 		       session params))))))
  18098       (`keyword
  18099        (unless (member (org-element-property :key element)
  18100 		       '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  18101 	 (user-error "No special environment to edit here"))
  18102        (let ((value (org-element-property :value element)))
  18103 	 (unless (org-string-nw-p value) (user-error "No file to edit"))
  18104 	 (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  18105 			  (or (match-string 1 value)
  18106 			      (match-string 0 value)))))
  18107 	   (when (org-url-p file)
  18108 	     (user-error "Files located with a URL cannot be edited"))
  18109 	   (org-link-open-from-string
  18110 	    (format "[[%s]]" (expand-file-name file))))))
  18111       (`table
  18112        (if (eq (org-element-property :type element) 'table.el)
  18113            (org-edit-table.el)
  18114          (call-interactively 'org-table-edit-formulas)))
  18115       ;; Only Org tables contain `table-row' type elements.
  18116       (`table-row (call-interactively 'org-table-edit-formulas))
  18117       (`example-block (org-edit-src-code))
  18118       (`export-block (org-edit-export-block))
  18119       (`comment-block (org-edit-comment-block))
  18120       (`fixed-width (org-edit-fixed-width-region))
  18121       (`latex-environment (org-edit-latex-environment))
  18122       (`planning
  18123        (let ((proplist (cadr element)))
  18124          (mapc #'call-interactively
  18125                (remq nil
  18126                      (list
  18127                       (when (plist-get proplist :deadline) #'org-deadline)
  18128                       (when (plist-get proplist :scheduled) #'org-schedule))))))
  18129       (_
  18130        ;; No notable element at point.  Though, we may be at a link or
  18131        ;; a footnote reference, which are objects.  Thus, scan deeper.
  18132        (let ((context (org-element-context element)))
  18133 	 (pcase (org-element-type context)
  18134 	   (`footnote-reference (org-edit-footnote-reference))
  18135 	   (`inline-src-block (org-edit-inline-src-code))
  18136 	   (`latex-fragment (org-edit-latex-fragment))
  18137 	   (`timestamp (if (eq 'inactive (org-element-property :type context))
  18138 			   (call-interactively #'org-timestamp-inactive)
  18139 			 (call-interactively #'org-timestamp)))
  18140 	   (`link (call-interactively #'ffap))
  18141 	   (_ (user-error "No special environment to edit here"))))))))
  18142 
  18143 (defun org-ctrl-c-ctrl-c (&optional arg)
  18144   "Set tags in headline, or update according to changed information at point.
  18145 
  18146 This command does many different things, depending on context:
  18147 
  18148 - If column view is active, in agenda or org buffers, quit it.
  18149 
  18150 - If there are highlights, remove them.
  18151 
  18152 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18153   this is what we do.
  18154 
  18155 - If the cursor is on a statistics cookie, update it.
  18156 
  18157 - If the cursor is in a headline, in an agenda or an org buffer,
  18158   prompt for tags and insert them into the current line, aligned
  18159   to `org-tags-column'.  When called with prefix arg, realign all
  18160   tags in the current buffer.
  18161 
  18162 - If the cursor is in one of the special #+KEYWORD lines, this
  18163   triggers scanning the buffer for these lines and updating the
  18164   information.
  18165 
  18166 - If the cursor is inside a table, realign the table.  This command
  18167   works even if the automatic table editor has been turned off.
  18168 
  18169 - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18170   the entire table.
  18171 
  18172 - If the cursor is at a footnote reference or definition, jump to
  18173   the corresponding definition or references, respectively.
  18174 
  18175 - If the cursor is a the beginning of a dynamic block, update it.
  18176 
  18177 - If the current buffer is a capture buffer, close note and file it.
  18178 
  18179 - If the cursor is on a <<<target>>>, update radio targets and
  18180   corresponding links in this buffer.
  18181 
  18182 - If the cursor is on a numbered item in a plain list, renumber the
  18183   ordered list.
  18184 
  18185 - If the cursor is on a checkbox, toggle it.
  18186 
  18187 - If the cursor is on a code block, evaluate it.  The variable
  18188   `org-confirm-babel-evaluate' can be used to control prompting
  18189   before code block evaluation, by default every code block
  18190   evaluation requires confirmation.  Code block evaluation can be
  18191   inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18192   (interactive "P")
  18193   (cond
  18194    ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  18195    ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18196     (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18197     (org-remove-occur-highlights)
  18198     (message "Temporary highlights/overlays removed from current buffer"))
  18199    ((and (local-variable-p 'org-finish-function)
  18200 	 (fboundp org-finish-function))
  18201     (funcall org-finish-function))
  18202    ((org-babel-hash-at-point))
  18203    ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18204    (t
  18205     (let* ((context
  18206 	    (org-element-lineage
  18207 	     (org-element-context)
  18208 	     ;; Limit to supported contexts.
  18209 	     '(babel-call clock dynamic-block footnote-definition
  18210 			  footnote-reference inline-babel-call inline-src-block
  18211 			  inlinetask item keyword node-property paragraph
  18212 			  plain-list planning property-drawer radio-target
  18213 			  src-block statistics-cookie table table-cell table-row
  18214 			  timestamp)
  18215 	     t))
  18216 	   (radio-list-p (org-at-radio-list-p))
  18217 	   (type (org-element-type context)))
  18218       ;; For convenience: at the first line of a paragraph on the same
  18219       ;; line as an item, apply function on that item instead.
  18220       (when (eq type 'paragraph)
  18221 	(let ((parent (org-element-parent context)))
  18222 	  (when (and (org-element-type-p parent 'item)
  18223 		     (= (line-beginning-position)
  18224 			(org-element-begin parent)))
  18225 	    (setq context parent)
  18226 	    (setq type 'item))))
  18227       ;; Act according to type of element or object at point.
  18228       ;;
  18229       ;; Do nothing on a blank line, except if it is contained in
  18230       ;; a source block.  Hence, we first check if point is in such
  18231       ;; a block and then if it is at a blank line.
  18232       (pcase type
  18233 	((or `inline-src-block `src-block)
  18234 	 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18235 	   (org-babel-eval-wipe-error-buffer)
  18236 	   (org-babel-execute-src-block
  18237 	    current-prefix-arg (org-babel-get-src-block-info nil context))))
  18238 	((guard (org-match-line "[ \t]*$"))
  18239 	 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18240 	     (user-error
  18241 	      (substitute-command-keys
  18242 	       "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18243 	((or `babel-call `inline-babel-call)
  18244 	 (let ((info (org-babel-lob-get-info context)))
  18245 	   (when info (org-babel-execute-src-block nil info nil type))))
  18246 	(`clock
  18247          (if (org-at-timestamp-p 'lax)
  18248              ;; Update the timestamp as well.  `org-timestamp-change'
  18249              ;; will call `org-clock-update-time-maybe'.
  18250              (org-timestamp-change 0 'day)
  18251            (org-clock-update-time-maybe)))
  18252 	(`dynamic-block
  18253 	 (save-excursion
  18254 	   (goto-char (org-element-post-affiliated context))
  18255 	   (org-update-dblock)))
  18256 	(`footnote-definition
  18257 	 (goto-char (org-element-post-affiliated context))
  18258 	 (call-interactively 'org-footnote-action))
  18259 	(`footnote-reference (call-interactively #'org-footnote-action))
  18260 	((or `headline `inlinetask)
  18261 	 (save-excursion (goto-char (org-element-begin context))
  18262 			 (call-interactively #'org-set-tags-command)))
  18263 	(`item
  18264 	 ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18265 	 ;; unconditionally, whereas `C-u' will toggle its presence.
  18266 	 ;; Without a universal argument, if the item has a checkbox,
  18267 	 ;; toggle it.  Otherwise repair the list.
  18268 	 (if (or radio-list-p
  18269 		 (and (boundp org-list-checkbox-radio-mode)
  18270 		      org-list-checkbox-radio-mode))
  18271 	     (org-toggle-radio-button arg)
  18272 	   (let* ((box (org-element-property :checkbox context))
  18273 		  (struct (org-element-property :structure context))
  18274 		  (old-struct (copy-tree struct))
  18275 		  (parents (org-list-parents-alist struct))
  18276 		  (prevs (org-list-prevs-alist struct))
  18277 		  (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18278 	     (org-list-set-checkbox
  18279 	      (org-element-begin context) struct
  18280 	      (cond ((equal arg '(16)) "[-]")
  18281 		    ((and (not box) (equal arg '(4))) "[ ]")
  18282 		    ((or (not box) (equal arg '(4))) nil)
  18283 		    ((eq box 'on) "[ ]")
  18284 		    (t "[X]")))
  18285 	     ;; Mimic `org-list-write-struct' but with grabbing a return
  18286 	     ;; value from `org-list-struct-fix-box'.
  18287 	     (org-list-struct-fix-ind struct parents 2)
  18288 	     (org-list-struct-fix-item-end struct)
  18289 	     (org-list-struct-fix-bul struct prevs)
  18290 	     (org-list-struct-fix-ind struct parents)
  18291 	     (let ((block-item
  18292 		    (org-list-struct-fix-box struct parents prevs orderedp)))
  18293 	       (if (and box (equal struct old-struct))
  18294 		   (if (equal arg '(16))
  18295 		       (message "Checkboxes already reset")
  18296 		     (user-error "Cannot toggle this checkbox: %s"
  18297 				 (if (eq box 'on)
  18298 				     "all subitems checked"
  18299 				   "unchecked subitems")))
  18300 		 (org-list-struct-apply-struct struct old-struct)
  18301 		 (org-update-checkbox-count-maybe))
  18302 	       (when block-item
  18303 		 (message "Checkboxes were removed due to empty box at line %d"
  18304 			  (org-current-line block-item)))))))
  18305 	(`plain-list
  18306 	 ;; At a plain list, with a double C-u argument, set
  18307 	 ;; checkboxes of each item to "[-]", whereas a single one
  18308 	 ;; will toggle their presence according to the state of the
  18309 	 ;; first item in the list.  Without an argument, repair the
  18310 	 ;; list.
  18311 	 (if (or radio-list-p
  18312 		 (and (boundp org-list-checkbox-radio-mode)
  18313 		      org-list-checkbox-radio-mode))
  18314 	     (org-toggle-radio-button arg)
  18315 	   (let* ((begin (org-element-contents-begin context))
  18316 		  (struct (org-element-property :structure context))
  18317 		  (old-struct (copy-tree struct))
  18318 		  (first-box (save-excursion
  18319 			       (goto-char begin)
  18320 			       (looking-at org-list-full-item-re)
  18321 			       (match-string-no-properties 3)))
  18322 		  (new-box (cond ((equal arg '(16)) "[-]")
  18323 				 ((equal arg '(4)) (unless first-box "[ ]"))
  18324 				 ((equal first-box "[X]") "[ ]")
  18325 				 (t "[X]"))))
  18326 	     (cond
  18327 	      (arg
  18328 	       (dolist (pos
  18329 			(org-list-get-all-items
  18330 			 begin struct (org-list-prevs-alist struct)))
  18331 		 (org-list-set-checkbox pos struct new-box)))
  18332 	      ((and first-box (eq (point) begin))
  18333 	       ;; For convenience, when point is at bol on the first
  18334 	       ;; item of the list and no argument is provided, simply
  18335 	       ;; toggle checkbox of that item, if any.
  18336 	       (org-list-set-checkbox begin struct new-box)))
  18337 	     (when (equal
  18338 		    (org-list-write-struct
  18339 		     struct (org-list-parents-alist struct) old-struct)
  18340 		    old-struct)
  18341 	       (message "Cannot update this checkbox"))
  18342 	     (org-update-checkbox-count-maybe))))
  18343 	(`keyword
  18344 	 (let ((org-inhibit-startup-visibility-stuff t)
  18345 	       (org-startup-align-all-tables nil))
  18346 	   (when (boundp 'org-table-coordinate-overlays)
  18347 	     (mapc #'delete-overlay org-table-coordinate-overlays)
  18348 	     (setq org-table-coordinate-overlays nil))
  18349 	   (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18350 	 (message "Local setup has been refreshed"))
  18351 	((or `property-drawer `node-property)
  18352 	 (call-interactively #'org-property-action))
  18353 	(`radio-target
  18354 	 (call-interactively #'org-update-radio-target-regexp))
  18355 	(`statistics-cookie
  18356 	 (call-interactively #'org-update-statistics-cookies))
  18357 	((or `table `table-cell `table-row)
  18358 	 ;; At a table, generate a plot if on the #+plot line,
  18359          ;; recalculate every field and align it otherwise.  Also
  18360 	 ;; send the table if necessary.
  18361          (cond
  18362           ((and (org-match-line "[ \t]*#\\+plot:")
  18363                 (< (point) (org-element-post-affiliated context)))
  18364            (org-plot/gnuplot))
  18365           ;; If the table has a `table.el' type, just give up.
  18366           ((eq (org-element-property :type context) 'table.el)
  18367            (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18368 Use `\\[org-edit-special]' to edit table.el tables")))
  18369           ;; At a table row or cell, maybe recalculate line but always
  18370 	  ;; align table.
  18371           ((or (eq type 'table)
  18372                ;; Check if point is at a TBLFM line.
  18373                (and (eq type 'table-row)
  18374                     (= (point) (org-element-end context))))
  18375            (save-excursion
  18376              (if (org-at-TBLFM-p)
  18377                  (progn (require 'org-table)
  18378                         (org-table-calc-current-TBLFM))
  18379                (goto-char (org-element-contents-begin context))
  18380                (org-call-with-arg 'org-table-recalculate (or arg t))
  18381                (orgtbl-send-table 'maybe))))
  18382           (t
  18383            (org-table-maybe-eval-formula)
  18384            (cond (arg (call-interactively #'org-table-recalculate))
  18385                  ((org-table-maybe-recalculate-line))
  18386                  (t (org-table-align))))))
  18387 	((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18388 	 (org-timestamp-change 0 'day))
  18389 	((and `nil (guard (org-at-heading-p)))
  18390 	 ;; When point is on an unsupported object type, we can miss
  18391 	 ;; the fact that it also is at a heading.  Handle it here.
  18392 	 (call-interactively #'org-set-tags-command))
  18393 	((guard
  18394 	  (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18395 	(_
  18396 	 (user-error
  18397 	  (substitute-command-keys
  18398 	   "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18399 
  18400 (defun org-mode-restart ()
  18401   "Restart `org-mode'."
  18402   (interactive)
  18403   (let ((indent-status (bound-and-true-p org-indent-mode)))
  18404     (funcall major-mode)
  18405     (hack-local-variables)
  18406     (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18407       (org-indent-mode -1))
  18408     (org-reset-file-cache))
  18409   (message "%s restarted" major-mode))
  18410 
  18411 (defun org-kill-note-or-show-branches ()
  18412   "Abort storing current note, or show just branches."
  18413   (interactive)
  18414   (cond (org-finish-function
  18415 	 (let ((org-note-abort t)) (funcall org-finish-function)))
  18416 	((org-before-first-heading-p)
  18417 	 (org-fold-show-branches-buffer)
  18418 	 (org-fold-hide-archived-subtrees (point-min) (point-max)))
  18419 	(t
  18420 	 (let ((beg (progn (org-back-to-heading) (point)))
  18421 	       (end (save-excursion (org-end-of-subtree t t) (point))))
  18422 	   (org-fold-hide-subtree)
  18423 	   (org-fold-show-branches)
  18424 	   (org-fold-hide-archived-subtrees beg end)))))
  18425 
  18426 (defun org-delete-indentation (&optional arg beg end)
  18427   "Join current line to previous and fix whitespace at join.
  18428 
  18429 If previous line is a headline add to headline title.  Otherwise
  18430 the function calls `delete-indentation'.
  18431 
  18432 If there is a region (BEG END), then join the lines in that region.
  18433 
  18434 With a non-nil prefix ARG, join the line with the following one,
  18435 ignoring region."
  18436   (interactive
  18437    (cons current-prefix-arg
  18438          (when (and (not current-prefix-arg) (use-region-p))
  18439            (list (region-beginning) (region-end)))))
  18440   (unless (and beg end)
  18441     ;; No region selected or BEG/END arguments not passed.
  18442     (setq beg (line-beginning-position (if arg 1 0))
  18443           end (line-end-position (if arg 2 1))))
  18444   (if (save-excursion
  18445         (goto-char beg)
  18446         (forward-line 0)
  18447         (and (< (line-end-position) end)
  18448              (let ((case-fold-search nil))
  18449 	       (looking-at org-complex-heading-regexp))))
  18450       ;; At headline.
  18451       (let ((tags-column (when (match-beginning 5)
  18452 			   (save-excursion (goto-char (match-beginning 5))
  18453 					   (current-column))))
  18454 	    string)
  18455         (goto-char beg)
  18456         ;; Join all but headline.
  18457         (save-excursion
  18458           (save-match-data
  18459             (if (version<= "27" emacs-version)
  18460                 (delete-indentation nil (line-beginning-position 2) end)
  18461               ;; FIXME: Emacs 26.  `delete-indentation' does not yet
  18462               ;; accept BEG/END arguments.
  18463               (save-restriction
  18464                 (narrow-to-region beg end)
  18465                 (goto-char beg)
  18466                 (forward-line 2)
  18467                 (while (< (point) (point-max))
  18468                   (delete-indentation)
  18469                   (forward-line 1))))))
  18470         (setq string (org-trim (delete-and-extract-region (line-end-position) (line-end-position 2))))
  18471 	(goto-char (or (match-end 4)
  18472 		       (match-beginning 5)
  18473 		       (match-end 0)))
  18474 	(skip-chars-backward " \t")
  18475 	(save-excursion (insert " " string))
  18476 	;; Adjust alignment of tags.
  18477 	(cond
  18478 	 ((not tags-column))		;no tags
  18479 	 (org-auto-align-tags (org-align-tags))
  18480 	 (t (org--align-tags-here tags-column)))) ;preserve tags column
  18481     (if (version<= "27" emacs-version)
  18482         (funcall-interactively #'delete-indentation arg beg end)
  18483       ;; FIXME: Emacs 26.  `delete-indentation' does not yet
  18484       ;; accept BEG/END arguments.
  18485       (save-restriction
  18486         (narrow-to-region beg end)
  18487         (goto-char beg)
  18488         (forward-line 1)
  18489         (while (< (point) (point-max))
  18490           (delete-indentation)
  18491           (forward-line 1))))))
  18492 
  18493 (defun org-open-line (n)
  18494   "Insert a new row in tables, call `open-line' elsewhere.
  18495 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18496 As a special case, when a document starts with a table, allow
  18497 calling `open-line' on the very first character."
  18498   (interactive "*p")
  18499   (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18500       (org-table-insert-row)
  18501     (open-line n)))
  18502 
  18503 (defun org--newline (indent arg interactive)
  18504   "Call `newline-and-indent' or just `newline'.
  18505 If INDENT is non-nil, call `newline-and-indent' with ARG to
  18506 indent unconditionally; otherwise, call `newline' with ARG and
  18507 INTERACTIVE, which can trigger indentation if
  18508 `electric-indent-mode' is enabled."
  18509   (if indent
  18510       (org-newline-and-indent arg)
  18511     (newline arg interactive)))
  18512 
  18513 (defun org-return (&optional indent arg interactive)
  18514   "Goto next table row or insert a newline.
  18515 
  18516 Calls `org-table-next-row' or `newline', depending on context.
  18517 
  18518 When optional INDENT argument is non-nil, call
  18519 `newline-and-indent' with ARG, otherwise call `newline' with ARG
  18520 and INTERACTIVE.
  18521 
  18522 When `org-return-follows-link' is non-nil and point is on
  18523 a timestamp, a link or a citation, call `org-open-at-point'.
  18524 However, it will not happen if point is in a table or on a \"dead\"
  18525 object (e.g., within a comment).  In these case, you need to use
  18526 `org-open-at-point' directly."
  18527   (interactive "i\nP\np")
  18528   (let* ((context (if org-return-follows-link (org-element-context)
  18529 		    (org-element-at-point)))
  18530          (element-type (org-element-type context)))
  18531     (cond
  18532      ;; In a table, call `org-table-next-row'.  However, before first
  18533      ;; column or after last one, split the table.
  18534      ((or (and (eq 'table element-type)
  18535 	       (not (eq 'table.el (org-element-property :type context)))
  18536 	       (>= (point) (org-element-contents-begin context))
  18537 	       (< (point) (org-element-contents-end context)))
  18538 	  (org-element-lineage context '(table-row table-cell) t))
  18539       (if (or (looking-at-p "[ \t]*$")
  18540 	      (save-excursion (skip-chars-backward " \t") (bolp)))
  18541 	  (insert "\n")
  18542 	(org-table-justify-field-maybe)
  18543 	(call-interactively #'org-table-next-row)))
  18544      ;; On a link, a timestamp or a citation, call `org-open-at-point'
  18545      ;; if `org-return-follows-link' allows it.  Tolerate fuzzy
  18546      ;; locations, e.g., in a comment, as `org-open-at-point'.
  18547      ((and org-return-follows-link
  18548 	   (or (and (eq 'link element-type)
  18549 		    ;; Ensure point is not on the white spaces after
  18550 		    ;; the link.
  18551 		    (let ((origin (point)))
  18552 		      (org-with-point-at (org-element-end context)
  18553 			(skip-chars-backward " \t")
  18554 			(> (point) origin))))
  18555 	       (org-in-regexp org-ts-regexp-both nil t)
  18556 	       (org-in-regexp org-tsr-regexp-both nil  t)
  18557                (org-element-lineage context '(citation citation-reference) 'include-self)
  18558 	       (org-in-regexp org-link-any-re nil t)))
  18559       (call-interactively #'org-open-at-point))
  18560      ;; Insert newline in heading, but preserve tags.
  18561      ((and (not (bolp))
  18562 	   (let ((case-fold-search nil))
  18563 	     (org-match-line org-complex-heading-regexp)))
  18564       ;; At headline.  Split line.  However, if point is on keyword,
  18565       ;; priority cookie or tags, do not break any of them: add
  18566       ;; a newline after the headline instead.
  18567       (let ((tags-column (and (match-beginning 5)
  18568 			      (save-excursion (goto-char (match-beginning 5))
  18569 					      (current-column))))
  18570 	    (string
  18571 	     (when (and (match-end 4) (org-point-in-group (point) 4))
  18572 	       (delete-and-extract-region (point) (match-end 4)))))
  18573 	;; Adjust tag alignment.
  18574 	(cond
  18575 	 ((not (and tags-column string)))
  18576 	 (org-auto-align-tags (org-align-tags))
  18577 	 (t (org--align-tags-here tags-column))) ;preserve tags column
  18578 	(end-of-line)
  18579 	(org-fold-show-entry 'hide-drawers)
  18580 	(org--newline indent arg interactive)
  18581 	(when string (save-excursion (insert (org-trim string))))))
  18582      ;; In a list, make sure indenting keeps trailing text within.
  18583      ((and (not (eolp))
  18584 	   (org-element-lineage context 'item))
  18585       (let ((trailing-data
  18586 	     (delete-and-extract-region (point) (line-end-position))))
  18587 	(org--newline indent arg interactive)
  18588 	(save-excursion (insert trailing-data))))
  18589      (t
  18590       ;; Do not auto-fill when point is in an Org property drawer.
  18591       (let ((auto-fill-function (and (not (org-at-property-p))
  18592 				     auto-fill-function)))
  18593 	(org--newline indent arg interactive))))))
  18594 
  18595 (defun org-return-and-maybe-indent ()
  18596   "Goto next table row, or insert a newline, maybe indented.
  18597 Call `org-table-next-row' or `org-return', depending on context.
  18598 See the individual commands for more information.
  18599 
  18600 When inserting a newline, if `org-adapt-indentation' is t:
  18601 indent the line if `electric-indent-mode' is disabled, don't
  18602 indent it if it is enabled."
  18603   (interactive)
  18604   (org-return (not electric-indent-mode)))
  18605 
  18606 (defun org-ctrl-c-tab (&optional arg)
  18607   "Toggle columns width in a table, or show children.
  18608 Call `org-table-toggle-column-width' if point is in a table.
  18609 Otherwise provide a compact view of the children.  ARG is the
  18610 level to hide."
  18611   (interactive "p")
  18612   (cond
  18613    ((org-at-table-p)
  18614     (call-interactively #'org-table-toggle-column-width))
  18615    ((org-before-first-heading-p)
  18616     (save-excursion
  18617       (org-fold-flag-above-first-heading)
  18618       (org-fold-hide-sublevels (or arg 1))))
  18619    (t
  18620     (org-fold-hide-subtree)
  18621     (org-fold-show-children arg))))
  18622 
  18623 (defun org-ctrl-c-star ()
  18624   "Compute table, or change heading status of lines.
  18625 Calls `org-table-recalculate' or `org-toggle-heading',
  18626 depending on context."
  18627   (interactive)
  18628   (cond
  18629    ((org-at-table-p)
  18630     (call-interactively 'org-table-recalculate))
  18631    (t
  18632     ;; Convert all lines in region to list items
  18633     (call-interactively 'org-toggle-heading))))
  18634 
  18635 (defun org-ctrl-c-minus ()
  18636   "Insert separator line in table or modify bullet status of line.
  18637 Also turns a plain line or a region of lines into list items.
  18638 Calls `org-table-insert-hline', `org-toggle-item', or
  18639 `org-cycle-list-bullet', depending on context."
  18640   (interactive)
  18641   (cond
  18642    ((org-at-table-p)
  18643     (call-interactively 'org-table-insert-hline))
  18644    ((org-region-active-p)
  18645     (call-interactively 'org-toggle-item))
  18646    ((org-in-item-p)
  18647     (call-interactively 'org-cycle-list-bullet))
  18648    (t
  18649     (call-interactively 'org-toggle-item))))
  18650 
  18651 (defun org-toggle-heading (&optional nstars)
  18652   "Convert headings to normal text, or items or text to headings.
  18653 If there is no active region, only convert the current line.
  18654 
  18655 With a `\\[universal-argument]' prefix, convert the whole list at
  18656 point into heading.
  18657 
  18658 In a region:
  18659 
  18660 - If the first non blank line is a headline, remove the stars
  18661   from all headlines in the region.
  18662 
  18663 - If it is a normal line, turn each and every normal line (i.e.,
  18664   not an heading or an item) in the region into headings.  If you
  18665   want to convert only the first line of this region, use one
  18666   universal prefix argument.
  18667 
  18668 - If it is a plain list item, turn all plain list items into headings.
  18669   The checkboxes are converted to appropriate TODO or DONE keywords
  18670   (using `car' or `org-done-keywords' and `org-not-done-keywords' when
  18671   available).
  18672 
  18673 When converting a line into a heading, the number of stars is chosen
  18674 such that the lines become children of the current entry.  However,
  18675 when a numeric prefix argument is given, its value determines the
  18676 number of stars to add."
  18677   (interactive "P")
  18678   (let ((skip-blanks
  18679 	 ;; Return beginning of first non-blank line, starting from
  18680 	 ;; line at POS.
  18681 	 (lambda (pos)
  18682 	   (save-excursion
  18683 	     (goto-char pos)
  18684 	     (while (org-at-comment-p) (forward-line))
  18685 	     (skip-chars-forward " \r\t\n")
  18686              (line-beginning-position))))
  18687 	beg end toggled)
  18688     ;; Determine boundaries of changes.  If a universal prefix has
  18689     ;; been given, put the list in a region.  If region ends at a bol,
  18690     ;; do not consider the last line to be in the region.
  18691 
  18692     (when (and current-prefix-arg (org-at-item-p))
  18693       (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18694       (org-mark-element))
  18695 
  18696     (if (org-region-active-p)
  18697 	(setq beg (funcall skip-blanks (region-beginning))
  18698 	      end (copy-marker (save-excursion
  18699 				 (goto-char (region-end))
  18700                                  (if (bolp) (point) (line-end-position)))))
  18701       (setq beg (funcall skip-blanks (line-beginning-position))
  18702             end (copy-marker (line-end-position))))
  18703     ;; Ensure inline tasks don't count as headings.
  18704     (org-with-limited-levels
  18705      (save-excursion
  18706        (goto-char beg)
  18707        (cond
  18708 	;; Case 1. Started at an heading: de-star headings.
  18709 	((org-at-heading-p)
  18710 	 (while (< (point) end)
  18711 	   (when (org-at-heading-p)
  18712 	     (looking-at org-outline-regexp) (replace-match "")
  18713 	     (setq toggled t))
  18714 	   (forward-line)))
  18715 	;; Case 2. Started at an item: change items into headlines.
  18716 	;;         One star will be added by `org-list-to-subtree'.
  18717 	((org-at-item-p)
  18718 	 (while (< (point) end)
  18719 	   (when (org-at-item-p)
  18720 	     ;; Pay attention to cases when region ends before list.
  18721 	     (let* ((struct (org-list-struct))
  18722 		    (list-end
  18723 		     (min (org-list-get-bottom-point struct) (1+ end))))
  18724 	       (save-restriction
  18725 		 (narrow-to-region (point) list-end)
  18726 		 (insert (org-list-to-subtree
  18727 			  (org-list-to-lisp t)
  18728 			  (pcase (org-current-level)
  18729 			    (`nil 1)
  18730 			    (l (1+ (org-reduced-level l))))
  18731                           ;; Keywords to replace checkboxes.
  18732                           (list
  18733                            ;; [X]
  18734                            :cbon (concat (or (car org-done-keywords) "DONE") " ")
  18735                            ;; [ ]
  18736                            :cboff (concat (or (car org-not-done-keywords) "TODO") " ")
  18737                            ;; [-]
  18738                            :cbtrans (concat (or (car org-not-done-keywords) "TODO") " ")))
  18739 			 "\n")))
  18740 	     (setq toggled t))
  18741 	   (forward-line)))
  18742 	;; Case 3. Started at normal text: make every line an heading,
  18743 	;;         skipping headlines and items.
  18744 	(t (let* ((stars
  18745 		   (make-string
  18746 		    (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18747 		  (add-stars
  18748 		   (cond (nstars "")	; stars from prefix only
  18749 			 ((equal stars "") "*")	; before first heading
  18750 			 (org-odd-levels-only "**") ; inside heading, odd
  18751 			 (t "*")))	; inside heading, oddeven
  18752 		  (rpl (concat stars add-stars " "))
  18753 		  (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18754 	     (while (< (point) (if (equal nstars '(4)) lend end))
  18755 	       (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18756 			  (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18757 		 (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18758 	       (forward-line)))))))
  18759     (unless toggled (message "Cannot toggle heading from here"))))
  18760 
  18761 (defun org-meta-return (&optional arg)
  18762   "Insert a new heading or wrap a region in a table.
  18763 Calls `org-insert-heading', `org-insert-item' or
  18764 `org-table-wrap-region', depending on context.  When called with
  18765 an argument, unconditionally call `org-insert-heading'."
  18766   (interactive "P")
  18767   (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18768       (call-interactively (cond (arg #'org-insert-heading)
  18769 				((org-at-table-p) #'org-table-wrap-region)
  18770 				((org-in-item-p) #'org-insert-item)
  18771 				(t #'org-insert-heading)))))
  18772 
  18773 ;;; Menu entries
  18774 (defsubst org-in-subtree-not-table-p ()
  18775   "Are we in a subtree and not in a table?"
  18776   (and (not (org-before-first-heading-p))
  18777        (not (org-at-table-p))))
  18778 
  18779 ;; Define the Org mode menus
  18780 (easy-menu-define org-org-menu org-mode-map "Org menu."
  18781   `("Org"
  18782     ("Show/Hide"
  18783      ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18784      ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18785      ["Sparse Tree..." org-sparse-tree t]
  18786      ["Reveal Context" org-fold-reveal t]
  18787      ["Show All" org-fold-show-all t]
  18788      "--"
  18789      ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18790     "--"
  18791     ["New Heading" org-insert-heading t]
  18792     ("Navigate Headings"
  18793      ["Up" outline-up-heading t]
  18794      ["Next" outline-next-visible-heading t]
  18795      ["Previous" outline-previous-visible-heading t]
  18796      ["Next Same Level" outline-forward-same-level t]
  18797      ["Previous Same Level" outline-backward-same-level t]
  18798      "--"
  18799      ["Jump" org-goto t])
  18800     ("Edit Structure"
  18801      ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18802      ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18803      "--"
  18804      ["Copy Subtree"  org-copy-special (org-in-subtree-not-table-p)]
  18805      ["Cut Subtree"  org-cut-special (org-in-subtree-not-table-p)]
  18806      ["Paste Subtree"  org-paste-special (not (org-at-table-p))]
  18807      "--"
  18808      ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18809      "--"
  18810      ["Copy visible text"  org-copy-visible t]
  18811      "--"
  18812      ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18813      ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18814      ["Demote Heading"  org-metaright (org-in-subtree-not-table-p)]
  18815      ["Demote Subtree"  org-shiftmetaright (org-in-subtree-not-table-p)]
  18816      "--"
  18817      ["Sort Region/Children" org-sort t]
  18818      "--"
  18819      ["Convert to odd levels" org-convert-to-odd-levels t]
  18820      ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18821     ("Editing"
  18822      ["Emphasis..." org-emphasize t]
  18823      ["Add block structure" org-insert-structure-template t]
  18824      ["Edit Source Example" org-edit-special t]
  18825      "--"
  18826      ["Footnote new/jump" org-footnote-action t]
  18827      ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18828     ("Archive"
  18829      ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18830      "--"
  18831      ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18832      ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18833      ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  18834     "--"
  18835     ("Hyperlinks"
  18836      ["Store Link (Global)" org-store-link t]
  18837      ["Find existing link to here" org-occur-link-in-agenda-files t]
  18838      ["Insert Link" org-insert-link t]
  18839      ["Follow Link" org-open-at-point t]
  18840      "--"
  18841      ["Next link" org-next-link t]
  18842      ["Previous link" org-previous-link t]
  18843      "--"
  18844      ["Descriptive Links"
  18845       org-toggle-link-display
  18846       :style radio
  18847       :selected org-descriptive-links
  18848       ]
  18849      ["Literal Links"
  18850       org-toggle-link-display
  18851       :style radio
  18852       :selected (not org-descriptive-links)])
  18853     "--"
  18854     ("TODO Lists"
  18855      ["TODO/DONE/-" org-todo t]
  18856      ("Select keyword"
  18857       ["Next keyword" org-shiftright (org-at-heading-p)]
  18858       ["Previous keyword" org-shiftleft (org-at-heading-p)]
  18859       ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  18860       ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  18861       ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  18862      ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  18863      ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  18864      "--"
  18865      ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  18866       :selected org-enforce-todo-dependencies :style toggle :active t]
  18867      "Settings for tree at point"
  18868      ["Do Children sequentially" org-toggle-ordered-property :style radio
  18869       :selected (org-entry-get nil "ORDERED")
  18870       :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18871      ["Do Children parallel" org-toggle-ordered-property :style radio
  18872       :selected (not (org-entry-get nil "ORDERED"))
  18873       :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18874      "--"
  18875      ["Set Priority" org-priority t]
  18876      ["Priority Up" org-shiftup t]
  18877      ["Priority Down" org-shiftdown t]
  18878      "--"
  18879      ["Get news from all feeds" org-feed-update-all t]
  18880      ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  18881      ["Customize feeds" (customize-variable 'org-feed-alist) t])
  18882     ("TAGS and Properties"
  18883      ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  18884      ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  18885      "--"
  18886      ["Set property" org-set-property (not (org-before-first-heading-p))]
  18887      ["Column view of properties" org-columns t]
  18888      ["Insert Column View DBlock" org-columns-insert-dblock t])
  18889     ("Dates and Scheduling"
  18890      ["Timestamp" org-timestamp (not (org-before-first-heading-p))]
  18891      ["Timestamp (inactive)" org-timestamp-inactive (not (org-before-first-heading-p))]
  18892      ("Change Date"
  18893       ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  18894       ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  18895       ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  18896       ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  18897      ["Compute Time Range" org-evaluate-time-range t]
  18898      ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  18899      ["Deadline" org-deadline (not (org-before-first-heading-p))]
  18900      "--"
  18901      ["Custom time format" org-toggle-timestamp-overlays
  18902       :style radio :selected org-display-custom-times]
  18903      "--"
  18904      ["Goto Calendar" org-goto-calendar t]
  18905      ["Date from Calendar" org-date-from-calendar t]
  18906      "--"
  18907      ["Start/Restart Timer" org-timer-start t]
  18908      ["Pause/Continue Timer" org-timer-pause-or-continue t]
  18909      ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  18910      ["Insert Timer String" org-timer t]
  18911      ["Insert Timer Item" org-timer-item t])
  18912     ("Logging work"
  18913      ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  18914      ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  18915      ["Clock out" org-clock-out t]
  18916      ["Clock cancel" org-clock-cancel t]
  18917      "--"
  18918      ["Mark as default task" org-clock-mark-default-task t]
  18919      ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  18920      ["Goto running clock" org-clock-goto t]
  18921      "--"
  18922      ["Display times" org-clock-display t]
  18923      ["Create clock table" org-clock-report t]
  18924      "--"
  18925      ["Record DONE time"
  18926       (progn (setq org-log-done (not org-log-done))
  18927 	     (message "Switching to %s will %s record a timestamp"
  18928 		      (car org-done-keywords)
  18929 		      (if org-log-done "automatically" "not")))
  18930       :style toggle :selected org-log-done])
  18931     "--"
  18932     ["Agenda Command..." org-agenda t]
  18933     ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  18934     ("File List for Agenda")
  18935     ("Special views current file"
  18936      ["TODO Tree"  org-show-todo-tree t]
  18937      ["Check Deadlines" org-check-deadlines t]
  18938      ["Tags/Property tree" org-match-sparse-tree t])
  18939     "--"
  18940     ["Export/Publish..." org-export-dispatch t]
  18941     ("LaTeX"
  18942      ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  18943       :style toggle :selected org-cdlatex-mode]
  18944      ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  18945      ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  18946      ["Modify math symbol" org-cdlatex-math-modify
  18947       (org-inside-LaTeX-fragment-p)]
  18948      ["Insert citation" org-reftex-citation t])
  18949     "--"
  18950     ("Documentation"
  18951      ["Show Version" org-version t]
  18952      ["Info Documentation" org-info t]
  18953      ["Browse Org News" org-browse-news t])
  18954     ("Customize"
  18955      ["Browse Org Group" org-customize t]
  18956      "--"
  18957      ["Expand This Menu" org-create-customize-menu t])
  18958     ["Send bug report" org-submit-bug-report t]
  18959     "--"
  18960     ("Refresh/Reload"
  18961      ["Refresh setup current buffer" org-mode-restart t]
  18962      ["Reload Org (after update)" org-reload t]
  18963      ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  18964 
  18965 (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  18966   '("Table"
  18967     ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18968     ["Next Field" org-cycle (org-at-table-p)]
  18969     ["Previous Field" org-shifttab (org-at-table-p)]
  18970     ["Next Row" org-return (org-at-table-p)]
  18971     "--"
  18972     ["Blank Field" org-table-blank-field (org-at-table-p)]
  18973     ["Edit Field" org-table-edit-field (org-at-table-p)]
  18974     ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18975     "--"
  18976     ("Column"
  18977      ["Move Column Left" org-metaleft (org-at-table-p)]
  18978      ["Move Column Right" org-metaright (org-at-table-p)]
  18979      ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18980      ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18981      ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18982     ("Row"
  18983      ["Move Row Up" org-metaup (org-at-table-p)]
  18984      ["Move Row Down" org-metadown (org-at-table-p)]
  18985      ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18986      ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18987      ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18988      "--"
  18989      ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18990     ("Rectangle"
  18991      ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18992      ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18993      ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18994      ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18995     "--"
  18996     ("Calculate"
  18997      ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18998      ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18999      ["Edit Formulas" org-edit-special (org-at-table-p)]
  19000      "--"
  19001      ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19002      ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19003      ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19004      "--"
  19005      ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19006      "--"
  19007      ["Sum Column/Rectangle" org-table-sum
  19008       (or (org-at-table-p) (org-region-active-p))]
  19009      ["Which Column?" org-table-current-column (org-at-table-p)])
  19010     ["Debug Formulas"
  19011      org-table-toggle-formula-debugger
  19012      :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19013     ["Show Col/Row Numbers"
  19014      org-table-toggle-coordinate-overlays
  19015      :style toggle
  19016      :selected (bound-and-true-p org-table-overlay-coordinates)]
  19017     "--"
  19018     ["Create" org-table-create (not (org-at-table-p))]
  19019     ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19020     ["Import from File" org-table-import (not (org-at-table-p))]
  19021     ["Export to File" org-table-export (org-at-table-p)]
  19022     "--"
  19023     ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19024     "--"
  19025     ("Plot"
  19026      ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19027      ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19028 
  19029 (defun org-info (&optional node)
  19030   "Read documentation for Org in the info system.
  19031 With optional NODE, go directly to that node."
  19032   (interactive)
  19033   (info (format "(org)%s" (or node ""))))
  19034 
  19035 (defun org-browse-news ()
  19036   "Browse the news for the latest major release."
  19037   (interactive)
  19038   (browse-url "https://orgmode.org/Changes.html"))
  19039 
  19040 (defvar org--warnings nil
  19041   "List of warnings to be added to the bug reports.")
  19042 ;;;###autoload
  19043 (defun org-submit-bug-report ()
  19044   "Submit a bug report on Org via mail.
  19045 
  19046 Don't hesitate to report any problems or inaccurate documentation.
  19047 
  19048 If you don't have setup sending mail from (X)Emacs, please copy the
  19049 output buffer into your mail program, as it gives us important
  19050 information about your Org version and configuration."
  19051   (interactive)
  19052   (require 'reporter)
  19053   (defvar reporter-prompt-for-summary-p)
  19054   (org-load-modules-maybe)
  19055   (org-require-autoloaded-modules)
  19056   (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19057     (reporter-submit-bug-report
  19058      "emacs-orgmode@gnu.org"
  19059      (org-version nil 'full)
  19060      (let (list)
  19061        (save-window-excursion
  19062 	 (pop-to-buffer
  19063           (get-buffer-create "*Warn about privacy*")
  19064           '(org-display-buffer-full-frame))
  19065 	 (erase-buffer)
  19066 	 (insert "You are about to submit a bug report to the Org mailing list.
  19067 
  19068 If your report is about Org installation, please read this section:
  19069 https://orgmode.org/org.html#Installation
  19070 
  19071 Please read https://orgmode.org/org.html#Feedback on how to make
  19072 a good report, it will help Org contributors fixing your problem.
  19073 
  19074 Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  19075 if the issue you are about to raise has already been dealt with.
  19076 
  19077 We also would like to add your full Org and Outline configuration
  19078 to the bug report.  It will help us debugging the issue.
  19079 
  19080 *HOWEVER*, some variables you have customized may contain private
  19081 information.  The names of customers, colleagues, or friends, might
  19082 appear in the form of file names, tags, todo states or search strings.
  19083 If you answer \"yes\" to the prompt, you might want to check and remove
  19084 such private information before sending the email.")
  19085 	 (add-text-properties (point-min) (point-max) '(face org-warning))
  19086          (when (yes-or-no-p "Include your Org configuration and Org warning log?")
  19087 	   (mapatoms
  19088 	    (lambda (v)
  19089 	      (and (boundp v)
  19090 		   (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19091 		   (or (and (symbol-value v)
  19092 			    (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19093                        (eq v 'org--warnings)
  19094 		       (and
  19095 			(get v 'custom-type) (get v 'standard-value)
  19096 			(not (equal (symbol-value v)
  19097 			            (eval (car (get v 'standard-value)) t)))))
  19098 		   (push v list)))))
  19099 	 (kill-buffer (get-buffer "*Warn about privacy*"))
  19100 	 list))
  19101      nil nil
  19102      "Remember to cover the basics, that is, what you expected to happen and
  19103 what in fact did happen.  You don't know how to make a good report?  See
  19104 
  19105      https://orgmode.org/manual/Feedback.html#Feedback
  19106 
  19107 Your bug report will be posted to the Org mailing list.
  19108 ------------------------------------------------------------------------")
  19109     (save-excursion
  19110       (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19111 	(replace-match "\\1[BUG] \\3 [\\2]")))))
  19112 
  19113 (defun org-install-agenda-files-menu ()
  19114   "Install agenda file menu."
  19115   (let ((bl (buffer-list)))
  19116     (save-excursion
  19117       (while bl
  19118 	(set-buffer (pop bl))
  19119 	(when (derived-mode-p 'org-mode) (setq bl nil)))
  19120       (when (derived-mode-p 'org-mode)
  19121 	(easy-menu-change
  19122 	 '("Org") "File List for Agenda"
  19123 	 (append
  19124 	  (list
  19125 	   ["Edit File List" (org-edit-agenda-file-list) t]
  19126 	   ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19127 	   ["Remove Current File from List" org-remove-file t]
  19128 	   ["Cycle through agenda files" org-cycle-agenda-files t]
  19129 	   ["Occur in all agenda files" org-occur-in-agenda-files t]
  19130 	   "--")
  19131 	  (mapcar 'org-file-menu-entry
  19132 		  ;; Prevent initialization from failing.
  19133 		  (ignore-errors (org-agenda-files t)))))))))
  19134 
  19135 ;;;; Documentation
  19136 
  19137 (defun org-require-autoloaded-modules ()
  19138   (interactive)
  19139   (mapc #'require
  19140 	'(org-agenda org-archive org-attach org-clock org-colview org-id
  19141 		     org-table org-timer)))
  19142 
  19143 ;;;###autoload
  19144 (defun org-reload (&optional uncompiled)
  19145   "Reload all Org Lisp files.
  19146 With prefix arg UNCOMPILED, load the uncompiled versions."
  19147   (interactive "P")
  19148   (require 'loadhist)
  19149   (let* ((org-dir     (org-find-library-dir "org"))
  19150 	 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19151 	 (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  19152 	 (remove-re (format "\\`%s\\'"
  19153 			    (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19154 	 (feats (delete-dups
  19155 		 (mapcar 'file-name-sans-extension
  19156 			 (mapcar 'file-name-nondirectory
  19157 				 (delq nil
  19158 				       (mapcar 'feature-file
  19159 					       features))))))
  19160 	 (lfeat (append
  19161 		 (sort
  19162 		  (setq feats
  19163 			(delq nil (mapcar
  19164 				   (lambda (f)
  19165 				     (if (and (string-match feature-re f)
  19166 					      (not (string-match remove-re f)))
  19167 					 f nil))
  19168 				   feats)))
  19169 		  'string-lessp)
  19170 		 (list "org-version" "org")))
  19171 	 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19172 	 load-uncore load-misses)
  19173     (setq load-misses
  19174 	  (delq t
  19175 		(mapcar (lambda (f)
  19176 			  (or (org-load-noerror-mustsuffix (concat org-dir f))
  19177 			      (and (string= org-dir contrib-dir)
  19178 				   (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19179 			      (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19180 				   (push f load-uncore)
  19181 				   t)
  19182 			      f))
  19183 			lfeat)))
  19184     (when load-uncore
  19185       (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19186 	       (if (> (length load-uncore) 1) "s were" " was")
  19187                (reverse load-uncore)))
  19188     (if load-misses
  19189 	(message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19190 		 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19191       (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19192 
  19193 ;;;###autoload
  19194 (defun org-customize ()
  19195   "Call the customize function with org as argument."
  19196   (interactive)
  19197   (org-load-modules-maybe)
  19198   (org-require-autoloaded-modules)
  19199   (customize-browse 'org))
  19200 
  19201 (defun org-create-customize-menu ()
  19202   "Create a full customization menu for Org mode, insert it into the menu."
  19203   (interactive)
  19204   (org-load-modules-maybe)
  19205   (org-require-autoloaded-modules)
  19206   (easy-menu-change
  19207    '("Org") "Customize"
  19208    `(["Browse Org group" org-customize t]
  19209      "--"
  19210      ,(customize-menu-create 'org)
  19211      ["Set" Custom-set t]
  19212      ["Save" Custom-save t]
  19213      ["Reset to Current" Custom-reset-current t]
  19214      ["Reset to Saved" Custom-reset-saved t]
  19215      ["Reset to Standard Settings" Custom-reset-standard t]))
  19216   (message "\"Org\"-menu now contains full customization menu"))
  19217 
  19218 ;;;; Miscellaneous stuff
  19219 
  19220 ;;; Generally useful functions
  19221 
  19222 (defun org-in-clocktable-p ()
  19223   "Check if the cursor is in a clocktable."
  19224   (let ((pos (point)) start)
  19225     (save-excursion
  19226       (end-of-line 1)
  19227       (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19228 	   (setq start (match-beginning 0))
  19229 	   (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19230 	   (>= (match-end 0) pos)
  19231 	   start))))
  19232 
  19233 (defun org-in-verbatim-emphasis ()
  19234   (save-match-data
  19235     (and (org-in-regexp org-verbatim-re 2)
  19236 	 (>= (point) (match-beginning 3))
  19237 	 (<= (point) (match-end 4)))))
  19238 
  19239 (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19240   "Go to MARKER, widen if necessary.  When marker is not live, try BOOKMARK."
  19241   (if (and marker (marker-buffer marker)
  19242 	   (buffer-live-p (marker-buffer marker)))
  19243       (progn
  19244 	(pop-to-buffer-same-window (marker-buffer marker))
  19245 	(when (or (> marker (point-max)) (< marker (point-min)))
  19246 	  (widen))
  19247 	(goto-char marker)
  19248 	(org-fold-show-context 'org-goto))
  19249     (if bookmark
  19250 	(bookmark-jump bookmark)
  19251       (error "Cannot find location"))))
  19252 
  19253 (defun org-quote-csv-field (s)
  19254   "Quote field for inclusion in CSV material."
  19255   (if (string-match "[\",]" s)
  19256       (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19257     s))
  19258 
  19259 (defun org-force-self-insert (N)
  19260   "Needed to enforce self-insert under remapping."
  19261   (interactive "p")
  19262   (self-insert-command N))
  19263 
  19264 (defun org-quote-vert (s)
  19265   "Replace \"|\" with \"\\vert\"."
  19266   (while (string-match "|" s)
  19267     (setq s (replace-match "\\vert" t t s)))
  19268   s)
  19269 
  19270 (defun org-in-src-block-p (&optional inside element)
  19271   "Return t when point is at a source block element.
  19272 When INSIDE is non-nil, return t only when point is between #+BEGIN_SRC
  19273 and #+END_SRC lines.
  19274 
  19275 Note that affiliated keywords and blank lines after are considered a
  19276 part of a source block.
  19277 
  19278 When ELEMENT is provided, it is considered to be element at point."
  19279   (save-match-data (setq element (or element (org-element-at-point))))
  19280   (when (org-element-type-p element 'src-block)
  19281     (or (not inside)
  19282         (not (or (<= (line-beginning-position)
  19283                   (org-element-post-affiliated element))
  19284                (>= (line-end-position)
  19285                   (org-with-point-at (org-element-end element)
  19286                     (skip-chars-backward " \t\n\r")
  19287                     (point))))))))
  19288 
  19289 (defun org-context ()
  19290   "Return a list of contexts of the current cursor position.
  19291 If several contexts apply, all are returned.
  19292 Each context entry is a list with a symbol naming the context, and
  19293 two positions indicating start and end of the context.  Possible
  19294 contexts are:
  19295 
  19296 :headline         anywhere in a headline
  19297 :headline-stars   on the leading stars in a headline
  19298 :todo-keyword     on a TODO keyword (including DONE) in a headline
  19299 :tags             on the TAGS in a headline
  19300 :priority         on the priority cookie in a headline
  19301 :item             on the first line of a plain list item
  19302 :item-bullet      on the bullet/number of a plain list item
  19303 :checkbox         on the checkbox in a plain list item
  19304 :table            in an Org table
  19305 :table-special    on a special filed in a table
  19306 :table-table      in a table.el table
  19307 :clocktable       in a clocktable
  19308 :src-block        in a source block
  19309 :link             on a hyperlink
  19310 :keyword          on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19311 :latex-fragment   on a LaTeX fragment
  19312 :latex-preview    on a LaTeX fragment with overlaid preview image
  19313 
  19314 This function expects the position to be visible because it uses font-lock
  19315 faces as a help to recognize the following contexts: :table-special, :link,
  19316 and :keyword."
  19317   (let* ((f (get-text-property (point) 'face))
  19318 	 (faces (if (listp f) f (list f)))
  19319 	 (case-fold-search t)
  19320 	 (p (point)) clist o)
  19321     ;; First the large context
  19322     (cond
  19323      ((org-at-heading-p)
  19324       (push (list :headline (line-beginning-position)
  19325                   (line-end-position))
  19326             clist)
  19327       (when (progn
  19328 	      (forward-line 0)
  19329 	      (looking-at org-todo-line-tags-regexp))
  19330 	(push (org-point-in-group p 1 :headline-stars) clist)
  19331 	(push (org-point-in-group p 2 :todo-keyword) clist)
  19332 	(push (org-point-in-group p 4 :tags) clist))
  19333       (goto-char p)
  19334       (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19335       (when (looking-at "\\[#[A-Z0-9]\\]")
  19336 	(push (org-point-in-group p 0 :priority) clist)))
  19337 
  19338      ((org-at-item-p)
  19339       (push (org-point-in-group p 2 :item-bullet) clist)
  19340       (push (list :item (line-beginning-position)
  19341 		  (save-excursion (org-end-of-item) (point)))
  19342 	    clist)
  19343       (and (org-at-item-checkbox-p)
  19344 	   (push (org-point-in-group p 0 :checkbox) clist)))
  19345 
  19346      ((org-at-table-p)
  19347       (push (list :table (org-table-begin) (org-table-end)) clist)
  19348       (when (memq 'org-formula faces)
  19349 	(push (list :table-special
  19350 		    (previous-single-property-change p 'face)
  19351 		    (next-single-property-change p 'face))
  19352 	      clist)))
  19353      ((org-at-table-p 'any)
  19354       (push (list :table-table) clist)))
  19355     (goto-char p)
  19356 
  19357     (let ((case-fold-search t))
  19358       ;; New the "medium" contexts: clocktables, source blocks
  19359       (cond ((org-in-clocktable-p)
  19360 	     (push (list :clocktable
  19361 			 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19362 				  (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19363 			      (match-beginning 1))
  19364 			 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19365 			      (match-end 0)))
  19366 		   clist))
  19367 	    ((org-in-src-block-p)
  19368 	     (push (list :src-block
  19369 			 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19370 				  (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19371 			      (match-beginning 1))
  19372 			 (and (search-forward "#+END_SRC" nil t)
  19373 			      (match-beginning 0)))
  19374 		   clist))))
  19375     (goto-char p)
  19376 
  19377     ;; Now the small context
  19378     (cond
  19379      ((org-at-timestamp-p)
  19380       (push (org-point-in-group p 0 :timestamp) clist))
  19381      ((memq 'org-link faces)
  19382       (push (list :link
  19383 		  (previous-single-property-change p 'face)
  19384 		  (next-single-property-change p 'face))
  19385 	    clist))
  19386      ((memq 'org-special-keyword faces)
  19387       (push (list :keyword
  19388 		  (previous-single-property-change p 'face)
  19389 		  (next-single-property-change p 'face))
  19390 	    clist))
  19391      ((setq o (cl-some
  19392 	       (lambda (o)
  19393 		 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19394 		      o))
  19395 	       (overlays-at (point))))
  19396       (push (list :latex-fragment
  19397 		  (overlay-start o) (overlay-end o))
  19398 	    clist)
  19399       (push (list :latex-preview
  19400 		  (overlay-start o) (overlay-end o))
  19401 	    clist))
  19402      ((org-inside-LaTeX-fragment-p)
  19403       ;; FIXME: positions wrong.
  19404       (push (list :latex-fragment (point) (point)) clist)))
  19405 
  19406     (setq clist (nreverse (delq nil clist)))
  19407     clist))
  19408 
  19409 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19410   "Non-nil when point is between matches of START-RE and END-RE.
  19411 
  19412 Also return a non-nil value when point is on one of the matches.
  19413 
  19414 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19415 buffer positions.  Default values are the positions of headlines
  19416 surrounding the point.
  19417 
  19418 The functions returns a cons cell whose car (resp. cdr) is the
  19419 position before START-RE (resp. after END-RE)."
  19420   (save-match-data
  19421     (let ((pos (point))
  19422 	  (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19423 	  (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19424 	  beg end)
  19425       (save-excursion
  19426 	;; Point is on a block when on START-RE or if START-RE can be
  19427 	;; found before it...
  19428 	(and (or (org-in-regexp start-re)
  19429 		 (re-search-backward start-re limit-up t))
  19430 	     (setq beg (match-beginning 0))
  19431 	     ;; ... and END-RE after it...
  19432 	     (goto-char (match-end 0))
  19433 	     (re-search-forward end-re limit-down t)
  19434 	     (> (setq end (match-end 0)) pos)
  19435 	     ;; ... without another START-RE in-between.
  19436 	     (goto-char (match-beginning 0))
  19437 	     (not (re-search-backward start-re (1+ beg) t))
  19438 	     ;; Return value.
  19439 	     (cons beg end))))))
  19440 
  19441 (defun org-in-block-p (names)
  19442   "Non-nil when point belongs to a block whose name belongs to NAMES.
  19443 
  19444 NAMES is a list of strings containing names of blocks.
  19445 
  19446 Return first block name matched, or nil.  Beware that in case of
  19447 nested blocks, the returned name may not belong to the closest
  19448 block from point."
  19449   (save-match-data
  19450     (catch 'exit
  19451       (let ((case-fold-search t)
  19452 	    (lim-up (save-excursion (outline-previous-heading)))
  19453 	    (lim-down (save-excursion (outline-next-heading))))
  19454 	(dolist (name names)
  19455 	  (let ((n (regexp-quote name)))
  19456 	    (when (org-between-regexps-p
  19457 		   (concat "^[ \t]*#\\+begin_" n)
  19458 		   (concat "^[ \t]*#\\+end_" n)
  19459 		   lim-up lim-down)
  19460 	      (throw 'exit n)))))
  19461       nil)))
  19462 
  19463 ;; Defined in org-agenda.el
  19464 (defvar org-agenda-restrict)
  19465 (defvar org-agenda-restrict-begin)
  19466 (defvar org-agenda-restrict-end)
  19467 (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19468   "Call `multi-occur' with buffers for all agenda files."
  19469   (interactive "sOrg-files matching: ")
  19470   (let* ((files (org-agenda-files))
  19471 	 (tnames (mapcar #'file-truename files))
  19472 	 (extra org-agenda-text-search-extra-files)
  19473          (narrows nil))
  19474     (when (and (eq (car extra) 'agenda-archives)
  19475                (not org-agenda-restrict))
  19476       (setq extra (cdr extra))
  19477       (setq files (org-add-archive-files files)))
  19478     (unless org-agenda-restrict
  19479       (dolist (f extra)
  19480         (unless (member (file-truename f) tnames)
  19481 	  (unless (member f files) (setq files (append files (list f))))
  19482 	  (setq tnames (append tnames (list (file-truename f)))))))
  19483     (multi-occur
  19484      (mapcar (lambda (x)
  19485 	       (with-current-buffer
  19486 		   ;; FIXME: Why not just (find-file-noselect x)?
  19487 		   ;; Is it to avoid the "revert buffer" prompt?
  19488 		   (or (get-file-buffer x) (find-file-noselect x))
  19489                  (if (eq (current-buffer) org-agenda-restrict)
  19490 		     (progn
  19491                        ;; Save the narrowing state.
  19492                        (push (list (current-buffer) (point-min) (point-max))
  19493                              narrows)
  19494                        (widen)
  19495                        (narrow-to-region org-agenda-restrict-begin
  19496 				         org-agenda-restrict-end))
  19497 		   (widen))
  19498 		 (current-buffer)))
  19499 	     files)
  19500      regexp)
  19501     ;; Restore the narrowing.
  19502     (dolist (narrow narrows)
  19503       (with-current-buffer (car narrow)
  19504         (widen)
  19505         (narrow-to-region (nth 1 narrow) (nth 2 narrow))))))
  19506 
  19507 (add-hook 'occur-mode-find-occurrence-hook
  19508 	  (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  19509 
  19510 (defun org-occur-link-in-agenda-files ()
  19511   "Create a link and search for it in the agendas.
  19512 The link is not stored in `org-stored-links', it is just created
  19513 for the search purpose."
  19514   (interactive)
  19515   (let ((link (condition-case nil
  19516 		  (org-store-link nil)
  19517 		(error "Unable to create a link to here"))))
  19518     (org-occur-in-agenda-files (regexp-quote link))))
  19519 
  19520 (defun org-back-over-empty-lines ()
  19521   "Move backwards over whitespace, to the beginning of the first empty line.
  19522 Returns the number of empty lines passed."
  19523   (let ((pos (point)))
  19524     (if (cdr (assq 'heading org-blank-before-new-entry))
  19525 	(skip-chars-backward " \t\n\r")
  19526       (unless (eobp)
  19527 	(forward-line -1)))
  19528     (forward-line 1)
  19529     (goto-char (min (point) pos))
  19530     (count-lines (point) pos)))
  19531 
  19532 ;;; TODO: Only called once, from ox-odt which should probably use
  19533 ;;; org-export-inline-image-p or something.
  19534 (defun org-file-image-p (file)
  19535   "Return non-nil if FILE is an image."
  19536   (save-match-data
  19537     (string-match (image-file-name-regexp) file)))
  19538 
  19539 (defun org-get-cursor-date (&optional with-time)
  19540   "Return the date at cursor in as a time.
  19541 This works in the calendar and in the agenda, anywhere else it just
  19542 returns the current time.
  19543 If WITH-TIME is non-nil, returns the time of the event at point (in
  19544 the agenda) or the current time of the day; otherwise returns the
  19545 earliest time on the cursor date that Org treats as that date
  19546 (bearing in mind `org-extend-today-until')."
  19547   (let (date day defd tp hod mod)
  19548     (when with-time
  19549       (setq tp (get-text-property (point) 'time))
  19550       (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  19551 	(setq hod (string-to-number (match-string 1 tp))
  19552 	      mod (string-to-number (match-string 2 tp))))
  19553       (or tp (let ((now (decode-time)))
  19554 	       (setq hod (nth 2 now)
  19555 		     mod (nth 1 now)))))
  19556     (cond
  19557      ((eq major-mode 'calendar-mode)
  19558       (setq date (calendar-cursor-to-date)
  19559 	    defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  19560                                   (nth 1 date) (nth 0 date) (nth 2 date))))
  19561      ((eq major-mode 'org-agenda-mode)
  19562       (setq day (get-text-property (point) 'day))
  19563       (when day
  19564 	(setq date (calendar-gregorian-from-absolute day)
  19565 	      defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  19566                                     (nth 1 date) (nth 0 date) (nth 2 date))))))
  19567     (or defd (current-time))))
  19568 
  19569 (defun org-mark-subtree (&optional up)
  19570   "Mark the current subtree.
  19571 This puts point at the start of the current subtree, and mark at
  19572 the end.  If a numeric prefix UP is given, move up into the
  19573 hierarchy of headlines by UP levels before marking the subtree."
  19574   (interactive "P")
  19575   (org-with-limited-levels
  19576    (cond ((org-at-heading-p) (forward-line 0))
  19577 	 ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19578 	 (t (outline-previous-visible-heading 1))))
  19579   (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19580   (if (called-interactively-p 'any)
  19581       (call-interactively 'org-mark-element)
  19582     (org-mark-element)))
  19583 
  19584 ;;; Indentation
  19585 
  19586 (defun org--at-headline-data-p (&optional beg element)
  19587   "Return non-nil when `point' or BEG is inside headline metadata.
  19588 
  19589 Metadata is planning line, properties drawer, logbook drawer right
  19590 after property drawer, or clock log line immediately following
  19591 properties drawer/planning line/ heading.
  19592 
  19593 Optional argument ELEMENT contains element at BEG."
  19594   (org-with-wide-buffer
  19595    (when beg (goto-char beg))
  19596    (setq element (or element (org-element-at-point)))
  19597    (if (or (org-element-type-p element 'headline)
  19598            (not (org-element-lineage element '(headline inlinetask))))
  19599        nil ; Not inside heading.
  19600      ;; Skip to top-level parent in section.
  19601      (while (not (org-element-type-p (org-element-parent element) 'section))
  19602        (setq element (org-element-parent element)))
  19603      (pcase (org-element-type element)
  19604        ((or `planning `property-drawer)
  19605         t)
  19606        (`drawer
  19607         ;; LOGBOOK drawer with appropriate name.
  19608         (equal
  19609          (org-log-into-drawer)
  19610          (org-element-property :drawer-name element)))
  19611        (`clock
  19612         ;; Previous element must be headline metadata or headline.
  19613         (goto-char (1- (org-element-begin element)))
  19614         (or (org-at-heading-p)
  19615             (org--at-headline-data-p)))))))
  19616 
  19617 (defvar org-element-greater-elements)
  19618 (defun org--get-expected-indentation (element contentsp)
  19619   "Expected indentation column for current line, according to ELEMENT.
  19620 ELEMENT is an element containing point.  CONTENTSP is non-nil
  19621 when indentation is to be computed according to contents of
  19622 ELEMENT."
  19623   (let ((type (org-element-type element))
  19624 	(start (org-element-begin element))
  19625 	(post-affiliated (org-element-post-affiliated element)))
  19626     (org-with-wide-buffer
  19627      (cond
  19628       (contentsp
  19629        (cl-case type
  19630 	 ((diary-sexp footnote-definition) 0)
  19631          (section
  19632           (org--get-expected-indentation
  19633            (org-element-parent element)
  19634            t))
  19635 	 ((headline inlinetask nil)
  19636 	  (if (not org-adapt-indentation) 0
  19637 	    (let ((level (org-current-level)))
  19638 	      (if level (1+ level) 0))))
  19639 	 ((item plain-list) (org-list-item-body-column post-affiliated))
  19640 	 (t
  19641 	  (when start (goto-char start))
  19642 	  (current-indentation))))
  19643       ((memq type '(headline inlinetask nil))
  19644        (if (org-match-line "[ \t]*$")
  19645 	   (org--get-expected-indentation element t)
  19646 	 0))
  19647       ((memq type '(diary-sexp footnote-definition)) 0)
  19648       ;; First paragraph of a footnote definition or an item.
  19649       ;; Indent like parent.
  19650       ((and start (< (line-beginning-position) start))
  19651        (org--get-expected-indentation
  19652 	(org-element-parent element) t))
  19653       ;; At first line: indent according to previous sibling, if any,
  19654       ;; ignoring footnote definitions and inline tasks, or parent's
  19655       ;; contents.  If `org-adapt-indentation' is `headline-data', ignore
  19656       ;; previous headline data siblings.
  19657       ((and start (= (line-beginning-position) start))
  19658        (catch 'exit
  19659 	 (while t
  19660 	   (if (= (point-min) start) (throw 'exit 0)
  19661 	     (goto-char (1- start))
  19662 	     (let* ((previous (org-element-at-point))
  19663 		    (parent previous))
  19664 	       (while (and parent (<= (org-element-end parent) start))
  19665 		 (setq previous parent
  19666 		       parent (org-element-parent parent)))
  19667 	       (cond
  19668 		((not previous) (throw 'exit 0))
  19669 		((> (org-element-end previous) start)
  19670 		 (throw 'exit (org--get-expected-indentation previous t)))
  19671 		((org-element-type-p
  19672                   previous '(footnote-definition inlinetask))
  19673 		 (setq start (org-element-begin previous)))
  19674                 ;; Do not indent like previous when the previous
  19675                 ;; element is headline data and `org-adapt-indentation'
  19676                 ;; is set to `headline-data'.
  19677                 ((and (eq 'headline-data org-adapt-indentation)
  19678                       (not (org--at-headline-data-p start element))
  19679                       (or (org-at-heading-p)
  19680                           (org--at-headline-data-p (1- start) previous)))
  19681                  (throw 'exit 0))
  19682 		(t (goto-char (org-element-begin previous))
  19683 		   (throw 'exit
  19684 			  (if (bolp) (current-indentation)
  19685 			    ;; At first paragraph in an item or
  19686 			    ;; a footnote definition.
  19687 			    (org--get-expected-indentation
  19688 			     (org-element-parent previous) t))))))))))
  19689       ;; Otherwise, move to the first non-blank line above.
  19690       (t
  19691        (forward-line 0)
  19692        (let ((pos (point)))
  19693 	 (skip-chars-backward " \r\t\n")
  19694 	 (cond
  19695 	  ;; Two blank lines end a footnote definition or a plain
  19696 	  ;; list.  When we indent an empty line after them, the
  19697 	  ;; containing list or footnote definition is over, so it
  19698 	  ;; qualifies as a previous sibling.  Therefore, we indent
  19699 	  ;; like its first line.
  19700 	  ((and (memq type '(footnote-definition plain-list))
  19701 		(> (count-lines (point) pos) 2))
  19702 	   (goto-char start)
  19703 	   (current-indentation))
  19704 	  ;; Line above is the first one of a paragraph at the
  19705 	  ;; beginning of an item or a footnote definition.  Indent
  19706 	  ;; like parent.
  19707 	  ((and start (< (line-beginning-position) start))
  19708 	   (org--get-expected-indentation
  19709 	    (org-element-parent element) t))
  19710 	  ;; Line above is the beginning of an element, i.e., point
  19711 	  ;; was originally on the blank lines between element's start
  19712 	  ;; and contents.
  19713 	  ((and post-affiliated (= (line-beginning-position) post-affiliated))
  19714 	   (org--get-expected-indentation element t))
  19715 	  ;; POS is after contents in a greater element.  Indent like
  19716 	  ;; the beginning of the element.
  19717 	  ((and (memq type org-element-greater-elements)
  19718 		(let ((cend (org-element-contents-end element)))
  19719 		  (and cend (<= cend pos))))
  19720 	   ;; As a special case, if point is at the end of a footnote
  19721 	   ;; definition or an item, indent like the very last element
  19722 	   ;; within.  If that last element is an item, indent like
  19723 	   ;; its contents.
  19724 	   (if (memq type '(footnote-definition item plain-list))
  19725 	       (let ((last (org-element-at-point)))
  19726 		 (goto-char pos)
  19727 		 (org--get-expected-indentation
  19728 		  last (org-element-type-p last 'item)))
  19729 	     (goto-char start)
  19730 	     (current-indentation)))
  19731 	  ;; In any other case, indent like the current line.
  19732 	  (t (current-indentation)))))))))
  19733 
  19734 (defun org--align-node-property ()
  19735   "Align node property at point.
  19736 Alignment is done according to `org-property-format', which see."
  19737   (when (save-excursion
  19738 	  (forward-line 0)
  19739 	  (looking-at org-property-re))
  19740     (org-combine-change-calls (match-beginning 0) (match-end 0)
  19741       (let ((newtext (concat (match-string 4)
  19742 	                     (org-trim
  19743 	                      (format org-property-format (match-string 1) (match-string 3))))))
  19744         ;; Do not use `replace-match' here as we want to inherit folding
  19745         ;; properties if inside fold.
  19746         (delete-region (match-beginning 0) (match-end 0))
  19747         (insert-and-inherit newtext)))))
  19748 
  19749 (defun org-indent-line ()
  19750   "Indent line depending on context.
  19751 
  19752 Indentation is done according to the following rules:
  19753 
  19754   - Footnote definitions, diary sexps, headlines and inline tasks
  19755     have to start at column 0.
  19756 
  19757   - On the very first line of an element, consider, in order, the
  19758     next rules until one matches:
  19759 
  19760     1. If there's a sibling element before, ignoring footnote
  19761        definitions and inline tasks, indent like its first line.
  19762 
  19763     2. If element has a parent, indent like its contents.  More
  19764        precisely, if parent is an item, indent after the bullet.
  19765        Else, indent like parent's first line.
  19766 
  19767     3. Otherwise, indent relatively to current level, if
  19768        `org-adapt-indentation' is t, or to left margin.
  19769 
  19770   - On a blank line at the end of an element, indent according to
  19771     the type of the element.  More precisely
  19772 
  19773     1. If element is a plain list, an item, or a footnote
  19774        definition, indent like the very last element within.
  19775 
  19776     2. If element is a paragraph, indent like its last non blank
  19777        line.
  19778 
  19779     3. Otherwise, indent like its very first line.
  19780 
  19781   - In the code part of a source block, use language major mode
  19782     to indent current line if `org-src-tab-acts-natively' is
  19783     non-nil.  If it is nil, do nothing.
  19784 
  19785   - Otherwise, indent like the first non-blank line above.
  19786 
  19787 The function doesn't indent an item as it could break the whole
  19788 list structure.  Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19789 `\\[org-shiftmetaright]'.
  19790 
  19791 Also align node properties according to `org-property-format'."
  19792   (interactive)
  19793   (let* ((element (save-excursion (forward-line 0) (org-element-at-point-no-context)))
  19794 	 (type (org-element-type element)))
  19795     (unless (or (org-at-heading-p) ; headline has no indent ever.
  19796                 ;; Do not indent first element after headline data.
  19797                 (and (eq org-adapt-indentation 'headline-data)
  19798                      (not (org--at-headline-data-p nil element))
  19799                      ;; Not at headline data and previous is headline data/headline.
  19800                      (or (memq type '(headline inlinetask)) ; blank lines after heading
  19801                          (and element
  19802                               (save-excursion
  19803                                 (goto-char (1- (org-element-begin element)))
  19804                                 (or (org-at-heading-p)
  19805                                     (org--at-headline-data-p)))))))
  19806       (cond ((and (memq type '(plain-list item))
  19807 		  (= (line-beginning-position)
  19808 		     (org-element-post-affiliated element)))
  19809 	     nil)
  19810 	    ((and (eq type 'latex-environment)
  19811 		  (>= (point) (org-element-post-affiliated element))
  19812 		  (< (point)
  19813 		     (org-with-point-at (org-element-end element)
  19814 		       (skip-chars-backward " \t\n")
  19815 		       (line-beginning-position 2))))
  19816 	     nil)
  19817 	    ((and (eq type 'src-block)
  19818 		  org-src-tab-acts-natively
  19819 		  (> (line-beginning-position)
  19820 		     (org-element-post-affiliated element))
  19821 		  (< (line-beginning-position)
  19822 		     (org-with-point-at (org-element-end element)
  19823 		       (skip-chars-backward " \t\n")
  19824 		       (line-beginning-position))))
  19825              (let ((block-content-ind
  19826                     (when (not (org-src-preserve-indentation-p element))
  19827                       (org-with-point-at (org-element-property :begin element)
  19828                         (+ (org-current-text-indentation)
  19829                            org-edit-src-content-indentation)))))
  19830                (ignore-errors ; do not err when there is no proper major mode
  19831                  ;; It is important to call `indent-according-to-mode'
  19832                  ;; rather than `indent-line-function' here or we may
  19833                  ;; sometimes break `electric-indent-mode'
  19834                  ;; https://orgmode.org/list/5O9VMGb6WRaqeHR5_NXTb832Z2Lek_5L40YPDA52-S3kPwGYJspI8kLWaGtuq3DXyhtHpj1J7jTIXb39RX9BtCa2ecrWHjijZqI8QAD742U=@proton.me
  19835                  (org-babel-do-in-edit-buffer (indent-according-to-mode)))
  19836                (when (and block-content-ind (looking-at-p "^$"))
  19837                  (indent-line-to block-content-ind))))
  19838 	    (t
  19839 	     (let ((column (org--get-expected-indentation element nil)))
  19840 	       ;; Preserve current column.
  19841 	       (if (<= (current-column) (current-indentation))
  19842 		   (indent-line-to column)
  19843 		 (save-excursion (indent-line-to column))))
  19844 	     ;; Align node property.  Also preserve current column.
  19845 	     (when (eq type 'node-property)
  19846 	       (let ((column (current-column)))
  19847 		 (org--align-node-property)
  19848 		 (org-move-to-column column))))))))
  19849 
  19850 (defun org-indent-region (start end)
  19851   "Indent each non-blank line in the region.
  19852 Called from a program, START and END specify the region to
  19853 indent.  The function will not indent contents of example blocks,
  19854 verse blocks and export blocks as leading white spaces are
  19855 assumed to be significant there."
  19856   (interactive "r")
  19857   (save-excursion
  19858     (goto-char start)
  19859     (skip-chars-forward " \r\t\n")
  19860     (unless (eobp) (forward-line 0))
  19861     (let ((indent-to
  19862 	   (lambda (ind pos)
  19863 	     ;; Set IND as indentation for all lines between point and
  19864 	     ;; POS.  Blank lines are ignored.  Leave point after POS
  19865 	     ;; once done.
  19866 	     (let ((limit (copy-marker pos)))
  19867 	       (while (< (point) limit)
  19868 		 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19869 		 (forward-line))
  19870 	       (set-marker limit nil))))
  19871 	  (end (copy-marker end)))
  19872       (while (< (point) end)
  19873 	(if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19874 	  (let* ((element (org-element-at-point))
  19875 		 (type (org-element-type element))
  19876 		 (element-end (copy-marker (org-element-end element)))
  19877 		 (ind (org--get-expected-indentation element nil)))
  19878 	    (cond
  19879 	     ;; Element indented as a single block.  Example blocks
  19880 	     ;; preserving indentation are a special case since the
  19881 	     ;; "contents" must not be indented whereas the block
  19882 	     ;; boundaries can.
  19883 	     ((or (memq type '(export-block latex-environment))
  19884 		  (and (eq type 'example-block)
  19885 		       (not (org-src-preserve-indentation-p element))))
  19886 	      (let ((offset (- ind (current-indentation))))
  19887 		(unless (zerop offset)
  19888 		  (indent-rigidly (org-element-begin element)
  19889 				  (org-element-end element)
  19890 				  offset)))
  19891 	      (goto-char element-end))
  19892 	     ;; Elements indented line wise.  Be sure to exclude
  19893 	     ;; example blocks (preserving indentation) and source
  19894 	     ;; blocks from this category as they are treated
  19895 	     ;; specially later.
  19896 	     ((or (memq type '(paragraph table table-row))
  19897 		  (not (or (org-element-contents-begin element)
  19898 			 (memq type '(example-block src-block)))))
  19899 	      (when (eq type 'node-property)
  19900 		(org--align-node-property)
  19901 		(forward-line 0))
  19902 	      (funcall indent-to ind (min element-end end)))
  19903 	     ;; Elements consisting of three parts: before the
  19904 	     ;; contents, the contents, and after the contents.  The
  19905 	     ;; contents are treated specially, according to the
  19906 	     ;; element type, or not indented at all.  Other parts are
  19907 	     ;; indented as a single block.
  19908 	     (t
  19909 	      (let* ((post (copy-marker
  19910 			    (org-element-post-affiliated element)))
  19911 		     (cbeg
  19912 		      (copy-marker
  19913 		       (cond
  19914 			((not (org-element-contents-begin element))
  19915 			 ;; Fake contents for source blocks.
  19916 			 (org-with-wide-buffer
  19917 			  (goto-char post)
  19918 			  (line-beginning-position 2)))
  19919 			((memq type '(footnote-definition item plain-list))
  19920 			 ;; Contents in these elements could start on
  19921 			 ;; the same line as the beginning of the
  19922 			 ;; element.  Make sure we start indenting
  19923 			 ;; from the second line.
  19924 			 (org-with-wide-buffer
  19925 			  (goto-char post)
  19926 			  (end-of-line)
  19927 			  (skip-chars-forward " \r\t\n")
  19928 			  (if (eobp) (point) (line-beginning-position))))
  19929 			(t (org-element-contents-begin element)))))
  19930 		     (cend (copy-marker
  19931 			    (or (org-element-contents-end element)
  19932 				;; Fake contents for source blocks.
  19933 				(org-with-wide-buffer
  19934 				 (goto-char element-end)
  19935 				 (skip-chars-backward " \r\t\n")
  19936 				 (line-beginning-position)))
  19937 			    t)))
  19938 		;; Do not change items indentation individually as it
  19939 		;; might break the list as a whole.  On the other
  19940 		;; hand, when at a plain list, indent it as a whole.
  19941 		(cond ((eq type 'plain-list)
  19942 		       (let ((offset (- ind (org-current-text-indentation))))
  19943 			 (unless (zerop offset)
  19944 			   (indent-rigidly (org-element-begin element)
  19945 					   (org-element-end element)
  19946 					   offset))
  19947 			 (goto-char cbeg)))
  19948 		      ((eq type 'item) (goto-char cbeg))
  19949 		      (t (funcall indent-to ind (min cbeg end))))
  19950 		(when (< (point) end)
  19951 		  (cl-case type
  19952 		    ((example-block verse-block))
  19953 		    (src-block
  19954 		     ;; In a source block, indent source code
  19955 		     ;; according to language major mode, but only if
  19956 		     ;; `org-src-tab-acts-natively' is non-nil.
  19957 		     (when (and (< (point) end) org-src-tab-acts-natively)
  19958 		       (ignore-errors
  19959 			 (org-babel-do-in-edit-buffer
  19960 			  (indent-region (point-min) (point-max))))))
  19961 		    (t (org-indent-region (point) (min cend end))))
  19962 		  (goto-char (min cend end))
  19963 		  (when (< (point) end)
  19964 		    (funcall indent-to ind (min element-end end))))
  19965 		(set-marker post nil)
  19966 		(set-marker cbeg nil)
  19967 		(set-marker cend nil))))
  19968 	    (set-marker element-end nil))))
  19969       (set-marker end nil))))
  19970 
  19971 (defun org-indent-drawer ()
  19972   "Indent the drawer at point.
  19973 Signal an error when not at a drawer."
  19974   (interactive)
  19975   (let ((element (org-element-at-point)))
  19976     (unless (org-element-type-p element '(drawer property-drawer))
  19977       (user-error "Not at a drawer"))
  19978     (org-with-wide-buffer
  19979      (org-indent-region (org-element-begin element)
  19980 			(org-element-end element))))
  19981   (message "Drawer at point indented"))
  19982 
  19983 (defun org-indent-block ()
  19984   "Indent the block at point.
  19985 Signal an error when not at a block."
  19986   (interactive)
  19987   (let ((element (org-element-at-point)))
  19988     (unless (org-element-type-p
  19989              element
  19990 	     '(comment-block center-block dynamic-block example-block
  19991 			     export-block quote-block special-block
  19992 			     src-block verse-block))
  19993       (user-error "Not at a block"))
  19994     (org-with-wide-buffer
  19995      (org-indent-region (org-element-begin element)
  19996 			(org-element-end element))))
  19997   (message "Block at point indented"))
  19998 
  19999 
  20000 ;;; Filling
  20001 
  20002 ;; We use our own fill-paragraph and auto-fill functions.
  20003 
  20004 ;; `org-fill-paragraph' relies on adaptive filling and context
  20005 ;; checking.  Appropriate `fill-prefix' is computed with
  20006 ;; `org-adaptive-fill-function'.
  20007 
  20008 ;; `org-auto-fill-function' takes care of auto-filling.  It calls
  20009 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20010 ;; `org-adaptive-fill-function' value.  Internally,
  20011 ;; `org-comment-line-break-function' breaks the line.
  20012 
  20013 ;; `org-setup-filling' installs filling and auto-filling related
  20014 ;; variables during `org-mode' initialization.
  20015 
  20016 (defvar org--single-lines-list-is-paragraph) ; defined later
  20017 
  20018 (defun org-setup-filling ()
  20019   (require 'org-element)
  20020   ;; Prevent auto-fill from inserting unwanted new items.
  20021   (setq-local fill-nobreak-predicate
  20022               (org-uniquify
  20023                (append fill-nobreak-predicate
  20024                        '(org-fill-line-break-nobreak-p
  20025                          org-fill-n-macro-as-item-nobreak-p
  20026                          org-fill-paragraph-with-timestamp-nobreak-p))))
  20027   (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20028     (setq-local paragraph-start paragraph-ending)
  20029     (setq-local paragraph-separate paragraph-ending))
  20030   (setq-local fill-paragraph-function 'org-fill-paragraph)
  20031   (setq-local fill-forward-paragraph-function
  20032               (lambda (&optional arg)
  20033                 (let ((org--single-lines-list-is-paragraph nil))
  20034                   (org-forward-paragraph arg))))
  20035   (setq-local auto-fill-inhibit-regexp nil)
  20036   (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20037   (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20038   (setq-local comment-line-break-function 'org-comment-line-break-function))
  20039 
  20040 (defun org-fill-line-break-nobreak-p ()
  20041   "Non-nil when a new line at point would create an Org line break."
  20042   (save-excursion
  20043     (skip-chars-backward " \t")
  20044     (skip-chars-backward "\\\\")
  20045     (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  20046 
  20047 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20048   "Non-nil when a new line at point would split a timestamp."
  20049   (and (org-at-timestamp-p 'lax)
  20050        (not (looking-at org-ts-regexp-both))))
  20051 
  20052 (defun org-fill-n-macro-as-item-nobreak-p ()
  20053   "Non-nil when a new line at point would create a new list."
  20054   ;; During export, a "n" macro followed by a dot or a closing
  20055   ;; parenthesis can end up being parsed as a new list item.
  20056   (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20057 
  20058 (defun org-adaptive-fill-function ()
  20059   "Compute a fill prefix for the current line.
  20060 Return fill prefix, as a string, or nil if current line isn't
  20061 meant to be filled.  For convenience, if `adaptive-fill-regexp'
  20062 matches in paragraphs or comments, use it."
  20063   (org-with-wide-buffer
  20064    (unless (org-at-heading-p)
  20065      (let* ((p (line-beginning-position))
  20066 	    (element (save-excursion
  20067 		       (forward-line 0)
  20068 		       (org-element-at-point)))
  20069 	    (type (org-element-type element))
  20070 	    (post-affiliated (org-element-post-affiliated element)))
  20071        (unless (< p post-affiliated)
  20072 	 (cl-case type
  20073 	   (comment
  20074 	    (save-excursion
  20075 	      (forward-line 0)
  20076 	      (looking-at "[ \t]*")
  20077 	      (concat (match-string 0) "# ")))
  20078 	   (footnote-definition "")
  20079 	   ((item plain-list)
  20080 	    (make-string (org-list-item-body-column post-affiliated) ?\s))
  20081 	   (paragraph
  20082 	    ;; Fill prefix is usually the same as the current line,
  20083 	    ;; unless the paragraph is at the beginning of an item.
  20084 	    (let ((parent (org-element-parent element)))
  20085 	      (save-excursion
  20086 		(forward-line 0)
  20087 		(cond ((org-element-type-p parent 'item)
  20088 		       (make-string (org-list-item-body-column
  20089 				     (org-element-begin parent))
  20090 				    ?\s))
  20091 		      ((and adaptive-fill-regexp
  20092 			    ;; Locally disable
  20093 			    ;; `adaptive-fill-function' to let
  20094 			    ;; `fill-context-prefix' handle
  20095 			    ;; `adaptive-fill-regexp' variable.
  20096 			    (let (adaptive-fill-function)
  20097 			      (fill-context-prefix
  20098 			       post-affiliated
  20099 			       (org-element-end element)))))
  20100 		      ((looking-at "[ \t]+") (match-string 0))
  20101 		      (t  "")))))
  20102 	   (comment-block
  20103 	    ;; Only fill contents if P is within block boundaries.
  20104 	    (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20105 					 (forward-line)
  20106 					 (point)))
  20107 		   (cend (save-excursion
  20108 			   (goto-char (org-element-end element))
  20109 			   (skip-chars-backward " \r\t\n")
  20110 			   (line-beginning-position))))
  20111 	      (when (and (>= p cbeg) (< p cend))
  20112 		(if (save-excursion (forward-line 0) (looking-at "[ \t]+"))
  20113 		    (match-string 0)
  20114 		  ""))))))))))
  20115 
  20116 (defun org-fill-element (&optional justify)
  20117   "Fill element at point, when applicable.
  20118 
  20119 This function only applies to comment blocks, comments, example
  20120 blocks and paragraphs.  Also, as a special case, re-align table
  20121 when point is at one.
  20122 
  20123 If JUSTIFY is non-nil (interactively, with prefix argument),
  20124 justify as well.  If `sentence-end-double-space' is non-nil, then
  20125 period followed by one space does not end a sentence, so don't
  20126 break a line there.  The variable `fill-column' controls the
  20127 width for filling.
  20128 
  20129 For convenience, when point is at a plain list, an item or
  20130 a footnote definition, try to fill the first paragraph within."
  20131   (with-syntax-table org-mode-transpose-word-syntax-table
  20132     ;; Move to end of line in order to get the first paragraph within
  20133     ;; a plain list or a footnote definition.
  20134     (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20135       ;; First check if point is in a blank line at the beginning of
  20136       ;; the buffer.  In that case, ignore filling.
  20137       (cl-case (org-element-type element)
  20138 	;; Use major mode filling function is source blocks.
  20139         (src-block
  20140          (let ((regionp (region-active-p)))
  20141            (org-babel-do-in-edit-buffer
  20142             ;; `org-babel-do-in-edit-buffer' will preserve region if it
  20143             ;; is within src block contents.  Otherwise, the region
  20144             ;; crosses src block boundaries.  We re-fill the whole src
  20145             ;; block in such scenario.
  20146             (when (and regionp (not (region-active-p)))
  20147               (push-mark (point-min))
  20148               (goto-char (point-max))
  20149               (setq mark-active t))
  20150             (funcall-interactively #'fill-paragraph justify 'region))))
  20151 	;; Align Org tables, leave table.el tables as-is.
  20152 	(table-row (org-table-align) t)
  20153 	(table
  20154 	 (when (eq (org-element-property :type element) 'org)
  20155 	   (save-excursion
  20156 	     (goto-char (org-element-post-affiliated element))
  20157 	     (org-table-align)))
  20158 	 t)
  20159 	(paragraph
  20160 	 ;; Paragraphs may contain `line-break' type objects.
  20161 	 (let ((beg (max (point-min)
  20162 			 (org-element-contents-begin element)))
  20163 	       (end (min (point-max)
  20164 			 (org-element-contents-end element))))
  20165 	   ;; Do nothing if point is at an affiliated keyword.
  20166 	   (if (< (line-end-position) beg) t
  20167 	     ;; Fill paragraph, taking line breaks into account.
  20168 	     (save-excursion
  20169 	       (goto-char beg)
  20170 	       (let ((cuts (list beg)))
  20171 		 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20172 		   (when (org-element-type-p
  20173 			  (save-excursion (backward-char)
  20174 					  (org-element-context))
  20175                           'line-break)
  20176 		     (push (point) cuts)))
  20177 		 (dolist (c (delq end cuts))
  20178 		   (fill-region-as-paragraph c end justify)
  20179 		   (setq end c))))
  20180 	     t)))
  20181 	;; Contents of `comment-block' type elements should be
  20182 	;; filled as plain text, but only if point is within block
  20183 	;; markers.
  20184 	(comment-block
  20185 	 (let* ((case-fold-search t)
  20186 		(beg (save-excursion
  20187 		       (goto-char (org-element-begin element))
  20188 		       (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20189 		       (forward-line)
  20190 		       (point)))
  20191 		(end (save-excursion
  20192 		       (goto-char (org-element-end element))
  20193 		       (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20194 		       (line-beginning-position))))
  20195 	   (if (or (< (point) beg) (> (point) end)) t
  20196 	     (fill-region-as-paragraph
  20197 	      (save-excursion (end-of-line)
  20198 			      (re-search-backward "^[ \t]*$" beg 'move)
  20199 			      (line-beginning-position))
  20200 	      (save-excursion (forward-line 0)
  20201 			      (re-search-forward "^[ \t]*$" end 'move)
  20202 			      (line-beginning-position))
  20203 	      justify))))
  20204 	;; Fill comments.
  20205 	(comment
  20206 	 (let ((begin (org-element-post-affiliated element))
  20207 	       (end (org-element-end element)))
  20208 	   (when (and (>= (point) begin) (<= (point) end))
  20209 	     (let ((begin (save-excursion
  20210 			    (end-of-line)
  20211 			    (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20212 				(progn (forward-line) (point))
  20213 			      begin)))
  20214 		   (end (save-excursion
  20215 			  (end-of-line)
  20216 			  (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20217 			      (1- (line-beginning-position))
  20218 			    (skip-chars-backward " \r\t\n")
  20219 			    (line-end-position)))))
  20220 	       ;; Do not fill comments when at a blank line.
  20221 	       (when (> end begin)
  20222 		 (let ((fill-prefix
  20223 			(save-excursion
  20224 			  (forward-line 0)
  20225 			  (looking-at "[ \t]*#")
  20226 			  (let ((comment-prefix (match-string 0)))
  20227 			    (goto-char (match-end 0))
  20228 			    (if (looking-at adaptive-fill-regexp)
  20229 				(concat comment-prefix (match-string 0))
  20230 			      (concat comment-prefix " "))))))
  20231 		   (save-excursion
  20232 		     (fill-region-as-paragraph begin end justify))))))
  20233 	   t))
  20234 	;; Ignore every other element.
  20235 	(otherwise t)))))
  20236 
  20237 (defun org-fill-paragraph (&optional justify region)
  20238   "Fill element at point, when applicable.
  20239 
  20240 This function only applies to comment blocks, comments, example
  20241 blocks and paragraphs.  Also, as a special case, re-align table
  20242 when point is at one.
  20243 
  20244 For convenience, when point is at a plain list, an item or
  20245 a footnote definition, try to fill the first paragraph within.
  20246 
  20247 If JUSTIFY is non-nil (interactively, with prefix argument),
  20248 justify as well.  If `sentence-end-double-space' is non-nil, then
  20249 period followed by one space does not end a sentence, so don't
  20250 break a line there.  The variable `fill-column' controls the
  20251 width for filling.
  20252 
  20253 The REGION argument is non-nil if called interactively; in that
  20254 case, if Transient Mark mode is enabled and the mark is active,
  20255 fill each of the elements in the active region, instead of just
  20256 filling the current element."
  20257   (interactive (progn
  20258 		 (barf-if-buffer-read-only)
  20259 		 (list (when current-prefix-arg 'full) t)))
  20260   (let ((hash (and (not (buffer-modified-p))
  20261 		   (org-buffer-hash))))
  20262     (cond
  20263      ((and region transient-mark-mode mark-active
  20264 	   (not (eq (region-beginning) (region-end))))
  20265       (let ((origin (point-marker))
  20266 	    (start (region-beginning)))
  20267 	(unwind-protect
  20268 	    (progn
  20269 	      (goto-char (region-end))
  20270 	      (skip-chars-backward " \t\n")
  20271 	      (let ((org--single-lines-list-is-paragraph nil))
  20272                 (while (> (point) start)
  20273 		  (org-fill-element justify)
  20274 		  (org-backward-paragraph)
  20275                   (skip-chars-backward " \t\n"))))
  20276 	  (goto-char origin)
  20277 	  (set-marker origin nil))))
  20278      (t
  20279       (save-excursion
  20280 	(when (org-match-line "[ \t]*$")
  20281 	  (skip-chars-forward " \t\n"))
  20282 	(org-fill-element justify))))
  20283     ;; If we didn't change anything in the buffer (and the buffer was
  20284     ;; previously unmodified), then flip the modification status back
  20285     ;; to "unchanged".
  20286     (when (and hash (equal hash (org-buffer-hash)))
  20287       (set-buffer-modified-p nil))
  20288     ;; Return non-nil.
  20289     t))
  20290 
  20291 (defun org-auto-fill-function ()
  20292   "Auto-fill function."
  20293   ;; Check if auto-filling is meaningful.
  20294   (let ((fc (current-fill-column)))
  20295     (when (and fc (> (current-column) fc))
  20296       (let* ((fill-prefix (org-adaptive-fill-function))
  20297 	     ;; Enforce empty fill prefix, if required.  Otherwise, it
  20298 	     ;; will be computed again.
  20299 	     (adaptive-fill-mode (not (equal fill-prefix ""))))
  20300 	(when fill-prefix (do-auto-fill))))))
  20301 
  20302 (defun org-comment-line-break-function (&optional soft)
  20303   "Break line at point and indent, continuing comment if within one.
  20304 The inserted newline is marked hard if variable
  20305 `use-hard-newlines' is true, unless optional argument SOFT is
  20306 non-nil.
  20307 
  20308 This function is a simplified version of `comment-indent-new-line'
  20309 that bypasses the complex Emacs machinery dealing with comments.
  20310 We instead rely on Org parser, utilizing `org-adaptive-fill-function'"
  20311   (let ((fill-prefix (org-adaptive-fill-function)))
  20312     (if soft (insert-and-inherit ?\n) (newline 1))
  20313     (save-excursion (forward-char -1) (delete-horizontal-space))
  20314     (delete-horizontal-space)
  20315     (indent-to-left-margin)
  20316     (when fill-prefix
  20317       (insert-before-markers-and-inherit fill-prefix))))
  20318 
  20319 
  20320 ;;; Fixed Width Areas
  20321 
  20322 (defun org-toggle-fixed-width ()
  20323   "Toggle fixed-width markup.
  20324 
  20325 Add or remove fixed-width markup on current line, whenever it
  20326 makes sense.  Return an error otherwise.
  20327 
  20328 If a region is active and if it contains only fixed-width areas
  20329 or blank lines, remove all fixed-width markup in it.  If the
  20330 region contains anything else, convert all non-fixed-width lines
  20331 to fixed-width ones.
  20332 
  20333 Blank lines at the end of the region are ignored unless the
  20334 region only contains such lines."
  20335   (interactive)
  20336   (if (not (org-region-active-p))
  20337       ;; No region:
  20338       ;;
  20339       ;; Remove fixed width marker only in a fixed-with element.
  20340       ;;
  20341       ;; Add fixed width maker in paragraphs, in blank lines after
  20342       ;; elements or at the beginning of a headline or an inlinetask,
  20343       ;; and before any one-line elements (e.g., a clock).
  20344       (progn
  20345         (forward-line 0)
  20346         (let* ((element (org-element-at-point))
  20347                (type (org-element-type element)))
  20348           (cond
  20349            ((and (eq type 'fixed-width)
  20350                  (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20351             (replace-match
  20352 	     "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20353            ((and (memq type '(babel-call clock comment diary-sexp headline
  20354 					 horizontal-rule keyword paragraph
  20355 					 planning))
  20356 		 (<= (org-element-post-affiliated element) (point)))
  20357             (skip-chars-forward " \t")
  20358             (insert ": "))
  20359            ((and (looking-at-p "[ \t]*$")
  20360                  (or (eq type 'inlinetask)
  20361                      (save-excursion
  20362                        (skip-chars-forward " \r\t\n")
  20363                        (<= (org-element-end element) (point)))))
  20364             (delete-region (point) (line-end-position))
  20365             (org-indent-line)
  20366             (insert ": "))
  20367            (t (user-error "Cannot insert a fixed-width line here")))))
  20368     ;; Region active.
  20369     (let* ((begin (save-excursion
  20370                     (goto-char (region-beginning))
  20371                     (line-beginning-position)))
  20372            (end (copy-marker
  20373                  (save-excursion
  20374                    (goto-char (region-end))
  20375                    (unless (eolp) (forward-line 0))
  20376                    (if (save-excursion (re-search-backward "\\S-" begin t))
  20377                        (progn (skip-chars-backward " \r\t\n") (point))
  20378                      (point)))))
  20379            (all-fixed-width-p
  20380             (catch 'not-all-p
  20381               (save-excursion
  20382                 (goto-char begin)
  20383                 (skip-chars-forward " \r\t\n")
  20384                 (when (eobp) (throw 'not-all-p nil))
  20385                 (while (< (point) end)
  20386                   (let ((element (org-element-at-point)))
  20387                     (if (org-element-type-p element 'fixed-width)
  20388                         (goto-char (org-element-end element))
  20389                       (throw 'not-all-p nil))))
  20390                 t))))
  20391       (if all-fixed-width-p
  20392           (save-excursion
  20393             (goto-char begin)
  20394             (while (< (point) end)
  20395               (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20396                 (replace-match
  20397                  "" nil nil nil
  20398                  (if (= (line-end-position) (match-end 0)) 0 1)))
  20399               (forward-line)))
  20400         (let ((min-ind (point-max)))
  20401           ;; Find minimum indentation across all lines.
  20402           (save-excursion
  20403             (goto-char begin)
  20404             (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20405                 (setq min-ind 0)
  20406               (catch 'zerop
  20407                 (while (< (point) end)
  20408                   (unless (looking-at-p "[ \t]*$")
  20409                     (let ((ind (org-current-text-indentation)))
  20410                       (setq min-ind (min min-ind ind))
  20411                       (when (zerop ind) (throw 'zerop t))))
  20412                   (forward-line)))))
  20413           ;; Loop over all lines and add fixed-width markup everywhere
  20414           ;; but in fixed-width lines.
  20415           (save-excursion
  20416             (goto-char begin)
  20417             (while (< (point) end)
  20418               (cond
  20419                ((org-at-heading-p)
  20420                 (insert ": ")
  20421                 (forward-line)
  20422                 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20423                   (insert ":")
  20424                   (forward-line)))
  20425                ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20426                 (let* ((element (org-element-at-point))
  20427                        (element-end (org-element-end element)))
  20428                   (if (org-element-type-p element 'fixed-width)
  20429                       (progn (goto-char element-end)
  20430                              (skip-chars-backward " \r\t\n")
  20431                              (forward-line))
  20432                     (let ((limit (min end element-end)))
  20433                       (while (< (point) limit)
  20434                         (org-move-to-column min-ind t)
  20435                         (insert ": ")
  20436                         (forward-line))))))
  20437                (t
  20438                 (org-move-to-column min-ind t)
  20439                 (insert ": ")
  20440                 (forward-line)))))))
  20441       (set-marker end nil))))
  20442 
  20443 
  20444 ;;; Blocks
  20445 
  20446 (defun org-block-map (function &optional start end)
  20447   "Call FUNCTION at the head of all source blocks in the current buffer.
  20448 Optional arguments START and END can be used to limit the range."
  20449   (let ((start (or start (point-min)))
  20450         (end (or end (point-max))))
  20451     (save-excursion
  20452       (goto-char start)
  20453       (while (and (< (point) end) (re-search-forward "^[ \t]*#\\+begin" end t))
  20454 	(save-excursion
  20455 	  (save-match-data
  20456             (goto-char (match-beginning 0))
  20457             (when (org-at-block-p)
  20458               (funcall function))))))))
  20459 
  20460 (defun org-next-block (arg &optional backward block-regexp)
  20461   "Jump to the next block.
  20462 
  20463 With a prefix argument ARG, jump forward ARG many blocks.
  20464 
  20465 When BACKWARD is non-nil, jump to the previous block.
  20466 
  20467 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20468 Match data is set according to this regexp when the function
  20469 returns.
  20470 
  20471 Return point at beginning of the opening line of found block.
  20472 Throw an error if no block is found."
  20473   (interactive "p")
  20474   (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20475 	(case-fold-search t)
  20476 	(search-fn (if backward #'re-search-backward #'re-search-forward))
  20477 	(count (or arg 1))
  20478 	(origin (point))
  20479 	last-element)
  20480     (if backward (forward-line 0)
  20481       (let ((inhibit-field-text-motion t)) (end-of-line)))
  20482     (while (and (> count 0) (funcall search-fn re nil t))
  20483       (let ((element (save-excursion
  20484 		       (goto-char (match-beginning 0))
  20485 		       (save-match-data (org-element-at-point)))))
  20486 	(when (and (org-element-type-p
  20487                     element
  20488 		    '(center-block comment-block dynamic-block
  20489 				   example-block export-block quote-block
  20490 				   special-block src-block verse-block))
  20491 		   (<= (match-beginning 0)
  20492 		      (org-element-post-affiliated element)))
  20493 	  (setq last-element element)
  20494 	  (cl-decf count))))
  20495     (if (= count 0)
  20496 	(prog1 (goto-char (org-element-post-affiliated last-element))
  20497 	  (save-match-data (org-fold-show-context)))
  20498       (goto-char origin)
  20499       (user-error "No %s code blocks" (if backward "previous" "further")))))
  20500 
  20501 (defun org-previous-block (arg &optional block-regexp)
  20502   "Jump to the previous block.
  20503 With a prefix argument ARG, jump backward ARG many source blocks.
  20504 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20505   (interactive "p")
  20506   (org-next-block arg t block-regexp))
  20507 
  20508 
  20509 ;;; Comments
  20510 
  20511 ;; Org comments syntax is quite complex.  It requires the entire line
  20512 ;; to be just a comment.  Also, even with the right syntax at the
  20513 ;; beginning of line, some elements (e.g., verse-block or
  20514 ;; example-block) don't accept comments.  Usual Emacs comment commands
  20515 ;; cannot cope with those requirements.  Therefore, Org replaces them.
  20516 
  20517 ;; Org still relies on 'comment-dwim', but cannot trust
  20518 ;; 'comment-only-p'.  So, 'comment-region-function' and
  20519 ;; 'uncomment-region-function' both point
  20520 ;; to 'org-comment-or-uncomment-region'.  Eventually,
  20521 ;; 'org-insert-comment' takes care of insertion of comments at the
  20522 ;; beginning of line.
  20523 
  20524 ;; 'org-setup-comments-handling' install comments related variables
  20525 ;; during 'org-mode' initialization.
  20526 
  20527 (defun org-setup-comments-handling ()
  20528   (interactive)
  20529   (setq-local comment-use-syntax nil)
  20530   (setq-local comment-start "# ")
  20531   (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20532   (setq-local comment-insert-comment-function 'org-insert-comment)
  20533   (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20534   (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20535 
  20536 (defun org-insert-comment ()
  20537   "Insert an empty comment above current line.
  20538 If the line is empty, insert comment at its beginning.  When
  20539 point is within a source block, comment according to the related
  20540 major mode."
  20541   (if (let ((element (org-element-at-point)))
  20542 	(and (org-element-type-p element 'src-block)
  20543 	     (< (save-excursion
  20544 		  (goto-char (org-element-post-affiliated element))
  20545 		  (line-end-position))
  20546 		(point))
  20547 	     (> (save-excursion
  20548 		  (goto-char (org-element-end element))
  20549 		  (skip-chars-backward " \r\t\n")
  20550 		  (line-beginning-position))
  20551 		(point))))
  20552       (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20553     (forward-line 0)
  20554     (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  20555       (open-line 1))
  20556     (org-indent-line)
  20557     (insert "# ")))
  20558 
  20559 (defvar comment-empty-lines)		; From newcomment.el.
  20560 (defun org-comment-or-uncomment-region (beg end &rest _)
  20561   "Comment or uncomment each non-blank line in the region.
  20562 Uncomment each non-blank line between BEG and END if it only
  20563 contains commented lines.  Otherwise, comment them.  If region is
  20564 strictly within a source block, use appropriate comment syntax."
  20565   (if (let ((element (org-element-at-point)))
  20566 	(and (org-element-type-p element 'src-block)
  20567 	     (< (save-excursion
  20568 		  (goto-char (org-element-post-affiliated element))
  20569 		  (line-end-position))
  20570 		beg)
  20571 	     (>= (save-excursion
  20572 		  (goto-char (org-element-end element))
  20573 		  (skip-chars-backward " \r\t\n")
  20574 		  (line-beginning-position))
  20575 		end)))
  20576       ;; Translate region boundaries for the Org buffer to the source
  20577       ;; buffer.
  20578       (let (src-end)
  20579         (save-excursion
  20580           (goto-char end)
  20581           (org-babel-do-in-edit-buffer
  20582            (setq src-end (point))))
  20583 	(save-excursion
  20584 	  (goto-char beg)
  20585 	  (org-babel-do-in-edit-buffer
  20586 	   (comment-or-uncomment-region (point) src-end))))
  20587     (save-restriction
  20588       ;; Restrict region
  20589       (narrow-to-region (save-excursion (goto-char beg)
  20590 					(skip-chars-forward " \r\t\n" end)
  20591 					(line-beginning-position))
  20592 			(save-excursion (goto-char end)
  20593 					(skip-chars-backward " \r\t\n" beg)
  20594 					(line-end-position)))
  20595       (let ((uncommentp
  20596 	     ;; UNCOMMENTP is non-nil when every non blank line between
  20597 	     ;; BEG and END is a comment.
  20598 	     (save-excursion
  20599 	       (goto-char (point-min))
  20600 	       (while (and (not (eobp))
  20601 			   (let ((element (org-element-at-point)))
  20602 			     (and (org-element-type-p element 'comment)
  20603 				  (goto-char (min (point-max)
  20604 						  (org-element-property
  20605 						   :end element)))))))
  20606 	       (eobp))))
  20607 	(if uncommentp
  20608 	    ;; Only blank lines and comments in region: uncomment it.
  20609 	    (save-excursion
  20610 	      (goto-char (point-min))
  20611 	      (while (not (eobp))
  20612 		(when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20613 		  (replace-match "" nil nil nil 1))
  20614 		(forward-line)))
  20615 	  ;; Comment each line in region.
  20616 	  (let ((min-indent (point-max)))
  20617 	    ;; First find the minimum indentation across all lines.
  20618 	    (save-excursion
  20619 	      (goto-char (point-min))
  20620 	      (while (and (not (eobp)) (not (zerop min-indent)))
  20621 		(unless (looking-at "[ \t]*$")
  20622 		  (setq min-indent (min min-indent (org-current-text-indentation))))
  20623 		(forward-line)))
  20624 	    ;; Then loop over all lines.
  20625 	    (save-excursion
  20626 	      (goto-char (point-min))
  20627 	      (while (not (eobp))
  20628 		(unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20629 		  ;; Don't get fooled by invisible text (e.g. link path)
  20630 		  ;; when moving to column MIN-INDENT.
  20631 		  (let ((buffer-invisibility-spec nil))
  20632 		    (org-move-to-column min-indent t))
  20633 		  (insert comment-start))
  20634 		(forward-line)))))))))
  20635 
  20636 (defun org-comment-dwim (_arg)
  20637   "Call the comment command you mean.
  20638 Call `org-toggle-comment' if on a heading, otherwise call
  20639 `comment-dwim'."
  20640   (interactive "*P")
  20641   (cond ((org-at-heading-p)
  20642 	 (call-interactively #'org-toggle-comment))
  20643 	(t (call-interactively #'comment-dwim))))
  20644 
  20645 
  20646 ;;; Timestamps API
  20647 
  20648 ;; This section contains tools to operate on, or create, timestamp
  20649 ;; objects, as returned by, e.g. `org-element-context'.
  20650 
  20651 (defun org-timestamp-from-string (s)
  20652   "Convert Org timestamp S, as a string, into a timestamp object.
  20653 Return nil if S is not a valid timestamp string."
  20654   (when (org-string-nw-p s)
  20655     (with-temp-buffer
  20656       (save-excursion (insert s))
  20657       (org-element-timestamp-parser))))
  20658 
  20659 (defun org-timestamp-from-time (time &optional with-time inactive)
  20660   "Convert a time value into a timestamp object.
  20661 
  20662 TIME is an Emacs internal time representation, as returned, e.g.,
  20663 by `current-time'.
  20664 
  20665 When optional argument WITH-TIME is non-nil, return a timestamp
  20666 object with a time part, i.e., with hours and minutes.
  20667 
  20668 Return an inactive timestamp if INACTIVE is non-nil.  Otherwise,
  20669 return an active timestamp."
  20670   (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20671     (org-element-create 'timestamp
  20672 			(list :type (if inactive 'inactive 'active)
  20673 			      :year-start year
  20674 			      :month-start month
  20675 			      :day-start day
  20676 			      :hour-start (and with-time hour)
  20677 			      :minute-start (and with-time minute)))))
  20678 
  20679 (defun org-timestamp-to-time (timestamp &optional end)
  20680   "Convert TIMESTAMP object into an Emacs internal time value.
  20681 Use end of date range or time range when END is non-nil.
  20682 Otherwise, use its start."
  20683   (org-encode-time
  20684    (append '(0)
  20685            (mapcar
  20686             (lambda (prop) (or (org-element-property prop timestamp) 0))
  20687             (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20688               '(:minute-start :hour-start :day-start :month-start
  20689                               :year-start)))
  20690            '(nil -1 nil))))
  20691 
  20692 (defun org-timestamp-has-time-p (timestamp)
  20693   "Non-nil when TIMESTAMP has a time specified."
  20694   (org-element-property :hour-start timestamp))
  20695 
  20696 (defun org-format-timestamp (timestamp format &optional end utc)
  20697   "Format a TIMESTAMP object into a string.
  20698 
  20699 FORMAT is a format specifier to be passed to
  20700 `format-time-string'.
  20701 
  20702 When optional argument END is non-nil, use end of date-range or
  20703 time-range, if possible.
  20704 
  20705 When optional argument UTC is non-nil, time is be expressed as
  20706 Universal Time."
  20707   (format-time-string format (org-timestamp-to-time timestamp end)
  20708 		      (and utc t)))
  20709 
  20710 (defun org-timestamp-split-range (timestamp &optional end)
  20711   "Extract a TIMESTAMP object from a date or time range.
  20712 
  20713 END, when non-nil, means extract the end of the range.
  20714 Otherwise, extract its start.
  20715 
  20716 Return a new timestamp object."
  20717   (let ((type (org-element-property :type timestamp)))
  20718     (if (memq type '(active inactive diary)) timestamp
  20719       (let ((split-ts (org-element-copy timestamp)))
  20720 	;; Set new type.
  20721 	(org-element-put-property
  20722 	 split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20723         (org-element-put-property split-ts :range-type nil)
  20724 	;; Copy start properties over end properties if END is
  20725 	;; non-nil.  Otherwise, copy end properties over `start' ones.
  20726 	(let ((p-alist '((:minute-start . :minute-end)
  20727 			 (:hour-start . :hour-end)
  20728 			 (:day-start . :day-end)
  20729 			 (:month-start . :month-end)
  20730 			 (:year-start . :year-end))))
  20731 	  (dolist (p-cell p-alist)
  20732 	    (org-element-put-property
  20733 	     split-ts
  20734 	     (funcall (if end #'car #'cdr) p-cell)
  20735 	     (org-element-property
  20736 	      (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20737 	  ;; Eventually refresh `:raw-value'.
  20738 	  (org-element-put-property split-ts :raw-value nil)
  20739 	  (org-element-put-property
  20740 	   split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20741 
  20742 (defun org-timestamp-translate (timestamp &optional boundary)
  20743   "Translate TIMESTAMP object to custom format.
  20744 
  20745 Format string is defined in `org-timestamp-custom-formats',
  20746 which see.
  20747 
  20748 When optional argument BOUNDARY is non-nil, it is either the
  20749 symbol `start' or `end'.  In this case, only translate the
  20750 starting or ending part of TIMESTAMP if it is a date or time
  20751 range.  Otherwise, translate both parts.
  20752 
  20753 Return timestamp as-is if `org-display-custom-times' is nil or if
  20754 it has a `diary' type."
  20755   (let ((type (org-element-property :type timestamp)))
  20756     (if (or (not org-display-custom-times) (eq type 'diary))
  20757 	(org-element-interpret-data timestamp)
  20758       (let ((fmt (org-time-stamp-format
  20759                   (org-timestamp-has-time-p timestamp) nil 'custom)))
  20760 	(if (and (not boundary) (memq type '(active-range inactive-range)))
  20761 	    (concat (org-format-timestamp timestamp fmt)
  20762 		    "--"
  20763 		    (org-format-timestamp timestamp fmt t))
  20764 	  (org-format-timestamp timestamp fmt (eq boundary 'end)))))))
  20765 
  20766 ;;; Yank media handler and DND
  20767 (defun org-setup-yank-dnd-handlers ()
  20768   "Setup the `yank-media' and DND handlers for buffer."
  20769   (let ((handler (if (>= emacs-major-version 30)
  20770                      #'org--dnd-multi-local-file-handler
  20771                    #'org--dnd-local-file-handler)))
  20772     (setq-local dnd-protocol-alist
  20773                 (append
  20774                  (list (cons "^file:///" handler)
  20775                        (cons "^file:/[^/]" handler)
  20776                        (cons "^file:[^/]" handler))
  20777                  dnd-protocol-alist)))
  20778   (when (fboundp 'yank-media-handler)
  20779     (yank-media-handler "image/.*" #'org--image-yank-media-handler)
  20780     ;; Looks like different DEs go for different handler names,
  20781     ;; https://larsee.com/blog/2019/05/clipboard-files/.
  20782     (yank-media-handler "x/special-\\(?:gnome\\|KDE\\|mate\\)-files"
  20783                         #'org--copied-files-yank-media-handler))
  20784   (when (boundp 'x-dnd-direct-save-function)
  20785     (setq-local x-dnd-direct-save-function #'org--dnd-xds-function)))
  20786 
  20787 (defcustom org-yank-image-save-method 'attach
  20788   "Method to save images yanked from clipboard and dropped to Emacs.
  20789 It can be the symbol `attach' to add it as an attachment, or a
  20790 directory name to copy/cut the image to that directory."
  20791   :group 'org
  20792   :package-version '(Org . "9.7")
  20793   :type '(choice (const :tag "Add it as attachment" attach)
  20794                  (directory :tag "Save it in directory"))
  20795   :safe (lambda (x) (eq x 'attach)))
  20796 
  20797 (defcustom org-yank-image-file-name-function #'org-yank-image-autogen-filename
  20798   "Function to generate filename for image yanked from clipboard.
  20799 By default, this autogenerates a filename based on the current
  20800 time.
  20801 It is called with no arguments and should return a string without
  20802 any extension which is used as the filename."
  20803   :group 'org
  20804   :package-version '(Org . "9.7")
  20805   :type '(radio (function-item :doc "Autogenerate filename"
  20806                                org-yank-image-autogen-filename)
  20807                 (function-item :doc "Ask for filename"
  20808                                org-yank-image-read-filename)
  20809                 function))
  20810 
  20811 (defun org-yank-image-autogen-filename ()
  20812   "Autogenerate filename for image in clipboard."
  20813   (format-time-string "clipboard-%Y%m%dT%H%M%S.%6N"))
  20814 
  20815 (defun org-yank-image-read-filename ()
  20816   "Read filename for image in clipboard."
  20817   (read-string "Basename for image file without extension: "))
  20818 
  20819 (declare-function org-attach-attach "org-attach" (file &optional visit-dir method))
  20820 
  20821 (defun org--image-yank-media-handler (mimetype data)
  20822   "Save image DATA of mime-type MIMETYPE and insert link at point.
  20823 It is saved as per `org-yank-image-save-method'.  The name for the
  20824 image is prompted and the extension is automatically added to the
  20825 end."
  20826   (cl-assert (fboundp 'mailcap-mime-type-to-extension)) ; Emacs >=29
  20827   (cl-assert (fboundp 'file-name-with-extension)) ; Emacs >=28
  20828   (let* ((ext (symbol-name
  20829                (with-no-warnings ; Suppress warning in Emacs <29
  20830                  (mailcap-mime-type-to-extension mimetype))))
  20831          (iname (funcall org-yank-image-file-name-function))
  20832          (filename (with-no-warnings ; Suppress warning in Emacs <28
  20833                      (file-name-with-extension iname ext)))
  20834          (absname (expand-file-name
  20835                    filename
  20836                    (if (eq org-yank-image-save-method 'attach)
  20837                        temporary-file-directory
  20838                      org-yank-image-save-method)))
  20839          link)
  20840     (when (and (not (eq org-yank-image-save-method 'attach))
  20841                (not (file-directory-p org-yank-image-save-method)))
  20842       (make-directory org-yank-image-save-method t))
  20843     ;; DATA is a raw image.  Tell Emacs to write it raw, without
  20844     ;; trying to auto-detect the coding system.
  20845     (let ((coding-system-for-write 'emacs-internal))
  20846       (with-temp-file absname
  20847         (insert data)))
  20848     (if (null (eq org-yank-image-save-method 'attach))
  20849         (setq link (org-link-make-string (concat "file:" (file-relative-name absname))))
  20850       (require 'org-attach)
  20851       (org-attach-attach absname nil 'mv)
  20852       (setq link (org-link-make-string (concat "attachment:" filename))))
  20853     (insert link)))
  20854 
  20855 ;; I cannot find a spec for this but
  20856 ;; https://indigo.re/posts/2021-12-21-clipboard-data.html and pcmanfm
  20857 ;; suggests that this is the format.
  20858 (defun org--copied-files-yank-media-handler (_mimetype data)
  20859   "Handle copied or cut files from file manager.
  20860 They are handled as per `org-yank-dnd-method'.
  20861 DATA is a string where the first line is the operation to
  20862 perform: copy or cut.  Rest of the lines are file: links to the
  20863 concerned files."
  20864   ;; pcmanfm adds a null byte at the end for some reason.
  20865   (let* ((data (split-string data "[\0\n\r]" t))
  20866          (files (cdr data))
  20867          (action (if (equal (car data) "cut")
  20868                      'copy
  20869                    'move))
  20870          (sep (if (= (length files) 1) "" " ")))
  20871     (dolist (f files)
  20872       (if (file-readable-p f)
  20873           (org--dnd-local-file-handler f action sep)
  20874         (message "File `%s' is not readable, skipping" f)))))
  20875 
  20876 (defcustom org-yank-dnd-method 'ask
  20877   "Action to perform on the dropped and the pasted files.
  20878 When the value is the symbol,
  20879   . `attach' -- attach dropped/pasted file
  20880   . `open' -- visit/open dropped/pasted file in Emacs
  20881   . `file-link' -- insert file: link to dropped/pasted file
  20882   . `ask' -- ask what to do out of the above."
  20883   :group 'org
  20884   :package-version '(Org . "9.7")
  20885   :type '(choice (const :tag "Attach" attach)
  20886                  (const :tag "Open/Visit file" open)
  20887                  (const :tag "Insert file: link" file-link)
  20888                  (const :tag "Ask what to do" ask)))
  20889 
  20890 (defcustom org-yank-dnd-default-attach-method nil
  20891   "Default attach method to use when DND action is unspecified.
  20892 This attach method is used when the DND action is `private'.
  20893 This is also used when `org-yank-image-save-method' is nil.
  20894 When nil, use `org-attach-method'."
  20895   :group 'org
  20896   :package-version '(Org . "9.7")
  20897   :type '(choice (const :tag "Default attach method" nil)
  20898                  (const :tag "Copy" cp)
  20899                  (const :tag "Move" mv)
  20900                  (const :tag "Hard link" ln)
  20901                  (const :tag "Symbolic link" lns)))
  20902 
  20903 (declare-function mailcap-file-name-to-mime-type "mailcap" (file-name))
  20904 (defvar org-attach-method)
  20905 
  20906 (defun org--dnd-rmc (prompt choices)
  20907   "Display a menu or dialog and select with PROMPT among CHOICES.
  20908 PROMPT is the prompt string.  CHOICES is a list of choices.  Each
  20909 choice is a list of (key description value).  VALUE from the selected
  20910 choice is returned."
  20911   (if (null (and
  20912              ;; Emacs <=28 does not have `use-dialog-box-p'.
  20913              (fboundp 'use-dialog-box-p)
  20914              (use-dialog-box-p)))
  20915       (progn
  20916         (setq choices
  20917               (mapcar
  20918                (pcase-lambda (`(,key ,message ,val))
  20919                  ;; `read-multiple-choice' expects VAL to be a long
  20920                  ;; description of the choice - string or nil.  Move VAL
  20921                  ;; further, so that it is not seen by the extended
  20922                  ;; help in `read-multiple-choice'.
  20923                  (list key message nil val))
  20924                choices))
  20925         (nth 3 (read-multiple-choice prompt choices)))
  20926     (setq choices
  20927           (mapcar
  20928            (pcase-lambda (`(_key ,message ,val))
  20929              (cons (capitalize message) val))
  20930            choices))
  20931     (x-popup-menu t (list prompt (cons "" choices)))))
  20932 
  20933 (defun org--dnd-multi-local-file-handler (urls action)
  20934   "Handle file URLS as per ACTION.
  20935 URLS is a list of file URL."
  20936   (let ((sep (if (= (length urls) 1) "" " ")))
  20937     (dolist (u urls)
  20938       (org--dnd-local-file-handler u action sep))))
  20939 
  20940 (put 'org--dnd-multi-local-file-handler 'dnd-multiple-handler t)
  20941 
  20942 (defun org--dnd-local-file-handler (url action &optional separator)
  20943   "Handle file URL as per ACTION.
  20944 SEPARATOR is the string to insert after each link.  It may be nil
  20945 in which case, space is inserted."
  20946   (unless separator
  20947     (setq separator " "))
  20948   (let ((method (if (eq org-yank-dnd-method 'ask)
  20949                     (org--dnd-rmc
  20950                      "What to do with file?"
  20951                      '((?a "attach" attach)
  20952                        (?o "open" open)
  20953                        (?f "insert file: link" file-link)))
  20954                   org-yank-dnd-method)))
  20955     (pcase method
  20956       (`attach (org--dnd-attach-file url action separator))
  20957       (`open (dnd-open-local-file url action))
  20958       (`file-link
  20959        (let ((filename (dnd-get-local-file-name url)))
  20960          (insert (org-link-make-string (concat "file:" filename)) separator))))))
  20961 
  20962 (defun org--dnd-attach-file (url action separator)
  20963   "Attach filename given by URL using method pertaining to ACTION.
  20964 If ACTION is `move', use `mv' attach method.
  20965 If `copy', use `cp' attach method.
  20966 If `ask', ask the user.
  20967 If `private', use the method denoted in `org-yank-dnd-default-attach-method'.
  20968 The action `private' is always returned.
  20969 
  20970 SEPARATOR is the string to insert after each link."
  20971   (require 'mailcap)
  20972   (require 'org-attach)
  20973   (let* ((filename (dnd-get-local-file-name url))
  20974          (mimetype (mailcap-file-name-to-mime-type filename))
  20975          (separatep (and (string-prefix-p "image/" mimetype)
  20976                          (not (eq 'attach org-yank-image-save-method))))
  20977          (method (pcase action
  20978                    ('copy 'cp)
  20979                    ('move 'mv)
  20980                    ('ask (org--dnd-rmc
  20981                           "Attach using method"
  20982                           '((?c "copy" cp)
  20983                             (?m "move" mv)
  20984                             (?l "hard link" ln)
  20985                             (?s "symbolic link" lns))))
  20986                    ('private (or org-yank-dnd-default-attach-method
  20987                                  org-attach-method)))))
  20988     (if separatep
  20989         (progn
  20990           (unless (file-directory-p org-yank-image-save-method)
  20991             (make-directory org-yank-image-save-method t))
  20992           (funcall
  20993            (pcase method
  20994              ('cp #'copy-file)
  20995              ('mv #'rename-file)
  20996              ('ln #'add-name-to-file)
  20997              ('lns #'make-symbolic-link))
  20998            filename
  20999            (expand-file-name (file-name-nondirectory filename)
  21000                              org-yank-image-save-method)))
  21001       (org-attach-attach filename nil method))
  21002     (insert
  21003      (org-link-make-string
  21004       (concat (if separatep
  21005                   "file:"
  21006                 "attachment:")
  21007               (if separatep
  21008                   (expand-file-name (file-name-nondirectory filename)
  21009                                     org-yank-image-save-method)
  21010                 (file-name-nondirectory filename))))
  21011      separator)
  21012     'private))
  21013 
  21014 (defvar-local org--dnd-xds-method nil
  21015   "The method to use for dropped file.")
  21016 (defun org--dnd-xds-function (need-name filename)
  21017   "Handle file with FILENAME dropped via XDS protocol.
  21018 When NEED-NAME is t, FILENAME is the base name of the file to be
  21019 saved.
  21020 When NEED-NAME is nil, the drop is complete."
  21021   (if need-name
  21022       (let ((method (if (eq org-yank-dnd-method 'ask)
  21023                         (org--dnd-rmc
  21024                          "What to do with dropped file?"
  21025                          '((?a "attach" attach)
  21026                            (?o "open" open)
  21027                            (?f "insert file: link" file-link)))
  21028                       org-yank-dnd-method)))
  21029         (setq-local org--dnd-xds-method method)
  21030         (pcase method
  21031           (`attach (expand-file-name filename (org-attach-dir 'create)))
  21032           (`open (expand-file-name (make-temp-name "emacs.") temporary-file-directory))
  21033           (`file-link (read-file-name "Write file to: " nil nil nil filename))))
  21034     (pcase org--dnd-xds-method
  21035       (`attach (insert (org-link-make-string
  21036                         (concat "attachment:" (file-name-nondirectory filename)))))
  21037       (`file-link (insert (org-link-make-string (concat "file:" filename))))
  21038       (`open (find-file filename)))
  21039     (setq-local org--dnd-xds-method nil)))
  21040 
  21041 ;;; Other stuff
  21042 
  21043 (defvar reftex-docstruct-symbol)
  21044 (defvar org--rds)
  21045 
  21046 (defun org-reftex-citation ()
  21047   "Use `reftex-citation' to insert a citation into the buffer.
  21048 This looks for a line like
  21049 
  21050 #+BIBLIOGRAPHY: foo plain option:-d
  21051 
  21052 and derives from it that foo.bib is the bibliography file relevant
  21053 for this document.  It then installs the necessary environment for RefTeX
  21054 to work in this buffer and calls `reftex-citation'  to insert a citation
  21055 into the buffer.
  21056 
  21057 Export of such citations to both LaTeX and HTML is handled by the contributed
  21058 package ox-bibtex by Taru Karttunen."
  21059   (interactive)
  21060   (let ((reftex-docstruct-symbol 'org--rds)
  21061 	org--rds bib)
  21062     (org-with-wide-buffer
  21063      (let ((case-fold-search t)
  21064 	   (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21065        (if (not (save-excursion
  21066 		  (or (re-search-forward re nil t)
  21067 		      (re-search-backward re nil t))))
  21068 	   (user-error "No bibliography defined in file")
  21069 	 (setq bib (concat (match-string 1) ".bib")
  21070 	       org--rds (list (list 'bib bib))))))
  21071     (call-interactively 'reftex-citation)))
  21072 
  21073 ;;;; Functions extending outline functionality
  21074 
  21075 (defun org-beginning-of-line (&optional n)
  21076   "Go to the beginning of the current visible line.
  21077 
  21078 If this is a headline, and `org-special-ctrl-a/e' is not nil or
  21079 symbol `reversed', on the first attempt move to where the
  21080 headline text starts, and only move to beginning of line when the
  21081 cursor is already before the start of the text of the headline.
  21082 
  21083 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  21084 start of the text on the second attempt.
  21085 
  21086 With argument N not nil or 1, move forward N - 1 lines first."
  21087   (interactive "^p")
  21088   (let ((origin (point))
  21089 	(special (pcase org-special-ctrl-a/e
  21090 		   (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21091 	deactivate-mark)
  21092     ;; First move to a visible line.
  21093     (if (bound-and-true-p visual-line-mode)
  21094 	(beginning-of-visual-line n)
  21095       (move-beginning-of-line n)
  21096       ;; `move-beginning-of-line' may leave point after invisible
  21097       ;; characters if line starts with such of these (e.g., with
  21098       ;; a link at column 0).  Really move to the beginning of the
  21099       ;; current visible line.
  21100       (forward-line 0))
  21101     (cond
  21102      ;; No special behavior.  Point is already at the beginning of
  21103      ;; a line, logical or visual.
  21104      ((not special))
  21105      ;; `beginning-of-visual-line' left point before logical beginning
  21106      ;; of line: point is at the beginning of a visual line.  Bail
  21107      ;; out.
  21108      ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21109      ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21110       ;; At a headline, special position is before the title, but
  21111       ;; after any TODO keyword or priority cookie.
  21112       (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21113 			 (line-end-position)))
  21114 	    (bol (point)))
  21115 	(if (eq special 'reversed)
  21116 	    (when (and (= origin bol) (eq last-command this-command))
  21117 	      (goto-char refpos))
  21118 	  (when (or (> origin refpos) (<= origin bol))
  21119 	    (goto-char refpos)))))
  21120      ((and (looking-at org-list-full-item-re)
  21121 	   (org-element-type-p
  21122             (save-match-data (org-element-at-point))
  21123 	    '(item plain-list)))
  21124       ;; Set special position at first white space character after
  21125       ;; bullet, and check-box, if any.
  21126       (let ((after-bullet
  21127 	     (let ((box (match-end 3)))
  21128 	       (cond ((not box) (match-end 1))
  21129 		     ((eq (char-after box) ?\s) (1+ box))
  21130 		     (t box)))))
  21131 	(if (eq special 'reversed)
  21132 	    (when (and (= (point) origin) (eq last-command this-command))
  21133 	      (goto-char after-bullet))
  21134 	  (when (or (> origin after-bullet) (>= (point) origin))
  21135 	    (goto-char after-bullet)))))
  21136      ;; No special context.  Point is already at beginning of line.
  21137      (t nil))))
  21138 
  21139 (defun org-end-of-line (&optional n)
  21140   "Go to the end of the line, but before ellipsis, if any.
  21141 
  21142 If this is a headline, and `org-special-ctrl-a/e' is not nil or
  21143 symbol `reversed', ignore tags on the first attempt, and only
  21144 move to after the tags when the cursor is already beyond the end
  21145 of the headline.
  21146 
  21147 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  21148 on the second attempt.
  21149 
  21150 With argument N not nil or 1, move forward N - 1 lines first."
  21151   (interactive "^p")
  21152   (let ((origin (point))
  21153 	(special (pcase org-special-ctrl-a/e
  21154 		   (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21155 	deactivate-mark)
  21156     ;; First move to a visible line.
  21157     (if (bound-and-true-p visual-line-mode)
  21158 	(beginning-of-visual-line n)
  21159       (move-beginning-of-line n))
  21160     (cond
  21161      ;; At a headline, with tags.
  21162      ((and special
  21163 	   (save-excursion
  21164 	     (forward-line 0)
  21165 	     (let ((case-fold-search nil))
  21166 	       (looking-at org-complex-heading-regexp)))
  21167 	   (match-end 5))
  21168       (let ((tags (save-excursion
  21169 		    (goto-char (match-beginning 5))
  21170 		    (skip-chars-backward " \t")
  21171 		    (point)))
  21172 	    (visual-end (and (bound-and-true-p visual-line-mode)
  21173 			     (save-excursion
  21174 			       (end-of-visual-line)
  21175 			       (point)))))
  21176 	;; If `end-of-visual-line' brings us before end of line or
  21177 	;; even tags, i.e., the headline spans over multiple visual
  21178 	;; lines, move there.
  21179 	(cond ((and visual-end
  21180 		    (< visual-end tags)
  21181 		    (<= origin visual-end))
  21182 	       (goto-char visual-end))
  21183 	      ((eq special 'reversed)
  21184 	       (if (and (= origin (line-end-position))
  21185 			(eq this-command last-command))
  21186 		   (goto-char tags)
  21187 		 (end-of-line)))
  21188 	      (t
  21189 	       (if (or (< origin tags) (>= origin (line-end-position)))
  21190 		   (goto-char tags)
  21191 		 (end-of-line))))))
  21192      ((bound-and-true-p visual-line-mode)
  21193       (let ((bol (line-beginning-position)))
  21194 	(end-of-visual-line)
  21195 	;; If `end-of-visual-line' gets us past the ellipsis at the
  21196 	;; end of a line, backtrack and use `end-of-line' instead.
  21197 	(when (/= bol (line-beginning-position))
  21198 	  (goto-char bol)
  21199 	  (end-of-line))))
  21200      (t (end-of-line)))))
  21201 
  21202 (defun org-backward-sentence (&optional _arg)
  21203   "Go to beginning of sentence, or beginning of table field.
  21204 This will call `backward-sentence' or `org-table-beginning-of-field',
  21205 depending on context."
  21206   (interactive)
  21207   (let* ((element (org-element-at-point))
  21208 	 (contents-begin (org-element-contents-begin element))
  21209 	 (table (org-element-lineage element 'table t)))
  21210     (if (and table
  21211 	     (> (point) contents-begin)
  21212 	     (<= (point) (org-element-contents-end table)))
  21213 	(call-interactively #'org-table-beginning-of-field)
  21214       (save-restriction
  21215 	(when (and contents-begin
  21216 		   (< (point-min) contents-begin)
  21217 		   (> (point) contents-begin))
  21218 	  (narrow-to-region contents-begin
  21219 			    (org-element-contents-end element)))
  21220 	(call-interactively #'backward-sentence)))))
  21221 
  21222 (defun org-forward-sentence (&optional _arg)
  21223   "Go to end of sentence, or end of table field.
  21224 This will call `forward-sentence' or `org-table-end-of-field',
  21225 depending on context."
  21226   (interactive)
  21227   (if (and (org-at-heading-p)
  21228 	   (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21229       (save-restriction
  21230 	(narrow-to-region (line-beginning-position) (line-end-position))
  21231 	(call-interactively #'forward-sentence))
  21232     (let* ((element (org-element-at-point))
  21233 	   (contents-end (org-element-contents-end element))
  21234 	   (table (org-element-lineage element 'table t)))
  21235       (if (and table
  21236 	       (>= (point) (org-element-contents-begin table))
  21237 	       (< (point) contents-end))
  21238 	  (call-interactively #'org-table-end-of-field)
  21239 	(save-restriction
  21240 	  (when (and contents-end
  21241 		     (> (point-max) contents-end)
  21242 		     ;; Skip blank lines between elements.
  21243 		     (< (org-element-end element)
  21244 			(save-excursion (goto-char contents-end)
  21245 					(skip-chars-forward " \r\t\n"))))
  21246 	    (narrow-to-region (org-element-contents-begin element)
  21247 			      contents-end))
  21248 	  ;; End of heading is considered as the end of a sentence.
  21249 	  (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21250 	    (call-interactively #'forward-sentence)))))))
  21251 
  21252 (defun org-kill-line (&optional _arg)
  21253   "Kill line, to tags or end of line.
  21254 
  21255 The behavior of this command depends on the user options
  21256 `org-special-ctrl-k' and `org-ctrl-k-protect-subtree' (which
  21257 see)."
  21258   (interactive)
  21259   (cond
  21260    ((or (not org-special-ctrl-k)
  21261 	(bolp)
  21262 	(not (org-at-heading-p)))
  21263     (when (and (org-invisible-p (line-end-position))
  21264 	       org-ctrl-k-protect-subtree
  21265 	       (or (eq org-ctrl-k-protect-subtree 'error)
  21266 		   (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21267       (user-error
  21268        (substitute-command-keys
  21269 	"`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  21270     (call-interactively
  21271      (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21272    ((org-match-line org-tag-line-re)
  21273     (let ((end (save-excursion
  21274 		 (goto-char (match-beginning 1))
  21275 		 (skip-chars-backward " \t")
  21276 		 (point))))
  21277       (if (<= end (point))		;on tags part
  21278 	  (kill-region (point) (line-end-position))
  21279 	(kill-region (point) end)))
  21280     ;; Only align tags when we are still on a heading:
  21281     (if (and (org-at-heading-p) org-auto-align-tags) (org-align-tags)))
  21282    (t (kill-region (point) (line-end-position)))))
  21283 
  21284 (defun org-yank (&optional arg)
  21285   "Yank.  If the kill is a subtree, treat it specially.
  21286 This command will look at the current kill and check if is a single
  21287 subtree, or a series of subtrees[1].  If it passes the test, and if the
  21288 cursor is at the beginning of a line or after the stars of a currently
  21289 empty headline, then the yank is handled specially.  How exactly depends
  21290 on the value of the following variables.
  21291 
  21292 `org-yank-folded-subtrees'
  21293     By default, this variable is non-nil, which results in
  21294     subtree(s) being folded after insertion, except if doing so
  21295     would swallow text after the yanked text.
  21296 
  21297 `org-yank-adjusted-subtrees'
  21298     When non-nil (the default value is nil), the subtree will be
  21299     promoted or demoted in order to fit into the local outline tree
  21300     structure, which means that the level will be adjusted so that it
  21301     becomes the smaller one of the two *visible* surrounding headings.
  21302 
  21303 Any prefix to this command will cause `yank' to be called directly with
  21304 no special treatment.  In particular, a simple `\\[universal-argument]' prefix \
  21305 will just
  21306 plainly yank the text as it is.
  21307 
  21308 \[1] The test checks if the first non-white line is a heading
  21309     and if there are no other headings with fewer stars."
  21310   (interactive "P")
  21311   (org-yank-generic 'yank arg))
  21312 
  21313 (defun org-yank-generic (command arg)
  21314   "Perform some yank-like command.
  21315 
  21316 This function implements the behavior described in the `org-yank'
  21317 documentation.  However, it has been generalized to work for any
  21318 interactive command with similar behavior."
  21319 
  21320   ;; pretend to be command COMMAND
  21321   (setq this-command command)
  21322 
  21323   (if arg
  21324       (call-interactively command)
  21325 
  21326     (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21327 	   (and (org-kill-is-subtree-p)
  21328 		(or (bolp)
  21329 		    (and (looking-at "[ \t]*$")
  21330 			 (string-match
  21331 			  "\\`\\*+\\'"
  21332                           (buffer-substring (line-beginning-position) (point)))))))
  21333 	  swallowp)
  21334       (cond
  21335        ((and subtreep org-yank-folded-subtrees)
  21336 	(let ((beg (point))
  21337 	      end)
  21338 	  (if (and subtreep org-yank-adjusted-subtrees)
  21339 	      (org-paste-subtree nil nil 'for-yank)
  21340 	    (call-interactively command))
  21341 
  21342 	  (setq end (point))
  21343 	  (goto-char beg)
  21344 	  (when (and (bolp) subtreep
  21345 		     (not (setq swallowp
  21346 			      (org-yank-folding-would-swallow-text beg end))))
  21347 	    (org-with-limited-levels
  21348 	     (or (looking-at org-outline-regexp)
  21349 		 (re-search-forward org-outline-regexp-bol end t))
  21350 	     (while (and (< (point) end) (looking-at org-outline-regexp))
  21351 	       (org-fold-subtree t)
  21352 	       (org-cycle-show-empty-lines 'folded)
  21353 	       (condition-case nil
  21354 		   (outline-forward-same-level 1)
  21355 		 (error (goto-char end))))))
  21356 	  (when swallowp
  21357 	    (message
  21358 	     "Inserted text not folded because that would swallow text"))
  21359 
  21360 	  (goto-char end)
  21361 	  (skip-chars-forward " \t\n\r")
  21362 	  (forward-line 0)
  21363 	  (push-mark beg 'nomsg)))
  21364        ((and subtreep org-yank-adjusted-subtrees)
  21365         (let ((beg (line-beginning-position)))
  21366 	  (org-paste-subtree nil nil 'for-yank)
  21367 	  (push-mark beg 'nomsg)))
  21368        (t
  21369 	(call-interactively command))))))
  21370 
  21371 (defun org-yank-folding-would-swallow-text (beg end)
  21372   "Would `hide-subtree' at BEG swallow any text after END?"
  21373   (let (level)
  21374     (org-with-limited-levels
  21375      (save-excursion
  21376        (goto-char beg)
  21377        (when (or (looking-at org-outline-regexp)
  21378 		 (re-search-forward org-outline-regexp-bol end t))
  21379 	 (setq level (org-outline-level)))
  21380        (goto-char end)
  21381        (skip-chars-forward " \t\r\n\v\f")
  21382        (not (or (eobp)
  21383 		(and (bolp) (looking-at-p org-outline-regexp)
  21384 		     (<= (org-outline-level) level))))))))
  21385 
  21386 (defun org-back-to-heading (&optional invisible-ok)
  21387   "Go back to beginning of heading or inlinetask."
  21388   (forward-line 0)
  21389   (or (and (org-at-heading-p (not invisible-ok))
  21390            (not (and (featurep 'org-inlinetask)
  21391                    (fboundp 'org-inlinetask-end-p)
  21392                    (org-inlinetask-end-p))))
  21393       (unless
  21394           (org-element-lineage-map
  21395               (org-element-at-point)
  21396               (lambda (el)
  21397                 (goto-char (org-element-begin el))
  21398                 (or invisible-ok (not (org-fold-folded-p))))
  21399             '(headline inlinetask)
  21400             'with-self 'first-match)
  21401         (user-error "Before first headline at position %d in buffer %s"
  21402 		    (point) (current-buffer))))
  21403   (point))
  21404 
  21405 (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  21406   "Go back to heading or first point in buffer.
  21407 If point is before first heading go to first point in buffer
  21408 instead of back to heading."
  21409   (if (org-before-first-heading-p)
  21410       (goto-char (point-min))
  21411     (org-back-to-heading invisible-ok)))
  21412 
  21413 (defun org-before-first-heading-p ()
  21414   "Before first heading?
  21415 Respect narrowing."
  21416   (let ((cached (org-element-at-point nil 'cached)))
  21417     (if cached
  21418         (let ((cached-headline (org-element-lineage cached 'headline t)))
  21419           (or (not cached-headline)
  21420               (< (org-element-begin cached-headline) (point-min))))
  21421       (org-with-limited-levels
  21422        (save-excursion
  21423          (end-of-line)
  21424          (null (re-search-backward org-outline-regexp-bol nil t)))))))
  21425 
  21426 (defun org-at-heading-p (&optional invisible-not-ok)
  21427   "Return t if point is on a (possibly invisible) heading line.
  21428 If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  21429   (save-excursion
  21430     (forward-line 0)
  21431     (and (or (not invisible-not-ok) (not (org-fold-folded-p)))
  21432 	 (looking-at outline-regexp))))
  21433 
  21434 (defun org-in-commented-heading-p (&optional no-inheritance element)
  21435   "Non-nil if point is under a commented heading.
  21436 This function also checks ancestors of the current headline,
  21437 unless optional argument NO-INHERITANCE is non-nil.
  21438 
  21439 Optional argument ELEMENT contains element at point."
  21440   (unless element
  21441     (setq
  21442      element
  21443      (org-element-lineage
  21444       (org-element-at-point)
  21445       '(headline inlinetask) 'with-self)))
  21446   (if no-inheritance
  21447       (org-element-property :commentedp element)
  21448     (org-element-property-inherited :commentedp element 'with-self)))
  21449 
  21450 (defun org-in-archived-heading-p (&optional no-inheritance element)
  21451   "Non-nil if point is under an archived heading.
  21452 This function also checks ancestors of the current headline,
  21453 unless optional argument NO-INHERITANCE is non-nil.
  21454 
  21455 Optional argument ELEMENT contains element at point."
  21456   (unless element
  21457     (setq
  21458      element
  21459      (org-element-lineage
  21460       (org-element-at-point)
  21461       '(headline inlinetask) 'with-self)))
  21462   (if no-inheritance
  21463       (org-element-property :archivedp element)
  21464     (org-element-property-inherited :archivedp element 'with-self)))
  21465 
  21466 (defun org-at-comment-p nil
  21467   "Return t if cursor is in a commented line."
  21468   (save-excursion
  21469     (save-match-data
  21470       (forward-line 0)
  21471       (looking-at org-comment-regexp))))
  21472 
  21473 (defun org-at-keyword-p nil
  21474   "Return t if cursor is at a keyword-line."
  21475   (save-excursion
  21476     (move-beginning-of-line 1)
  21477     (looking-at org-keyword-regexp)))
  21478 
  21479 (defun org-at-drawer-p nil
  21480   "Return t if cursor is at a drawer keyword."
  21481   (save-excursion
  21482     (move-beginning-of-line 1)
  21483     (looking-at org-drawer-regexp)))
  21484 
  21485 (defun org-at-block-p nil
  21486   "Return t if cursor is at a block keyword."
  21487   (save-excursion
  21488     (move-beginning-of-line 1)
  21489     (looking-at org-block-regexp)))
  21490 
  21491 (defun org-point-at-end-of-empty-headline ()
  21492   "If point is at the end of an empty headline, return t, else nil.
  21493 If the heading only contains a TODO keyword, it is still considered
  21494 empty."
  21495   (let ((case-fold-search nil))
  21496     (and (looking-at "[ \t]*$")
  21497 	 org-todo-line-regexp
  21498 	 (save-excursion
  21499 	   (forward-line 0)
  21500 	   (looking-at org-todo-line-regexp)
  21501 	   (string= (match-string 3) "")))))
  21502 
  21503 (defun org-at-heading-or-item-p ()
  21504   (or (org-at-heading-p) (org-at-item-p)))
  21505 
  21506 (defun org-up-heading-all (arg)
  21507   "Move to the heading line of which the present line is a subheading.
  21508 This function considers both visible and invisible heading lines.
  21509 With argument, move up ARG levels."
  21510   (outline-up-heading arg t))
  21511 
  21512 (defun org-up-heading-safe ()
  21513   "Move to the heading line of which the present line is a subheading.
  21514 Return the true heading level, as number or nil when there is no such
  21515 heading.
  21516 
  21517 When point is not at heading, go to the parent of the current heading.
  21518 When point is at or inside an inlinetask, go to the containing
  21519 heading.
  21520 
  21521 This version will not throw an error.  It will return the true level
  21522 of the headline found, or nil if no higher level is found.
  21523 
  21524 When no higher level is found, the still move point to the containing
  21525 heading, if there is any in the accessible portion of the buffer.
  21526 
  21527 When narrowing is in effect, ignore headings starting before the
  21528 available portion of the buffer."
  21529   (let* ((current-heading (org-element-lineage
  21530                            (org-element-at-point)
  21531                            '(headline inlinetask)
  21532                            'with-self))
  21533          (parent (org-element-lineage current-heading 'headline)))
  21534     (if (and parent
  21535              (<= (point-min) (org-element-begin parent)))
  21536         (progn
  21537           (goto-char (org-element-begin parent))
  21538           (org-element-property :true-level parent))
  21539       (when (and current-heading
  21540                  (<= (point-min) (org-element-begin current-heading)))
  21541         (goto-char (org-element-begin current-heading))
  21542         nil))))
  21543 
  21544 (defun org-up-heading-or-point-min ()
  21545   "Move to the heading line of which the present is a subheading, or point-min.
  21546 This version is needed to make point-min behave like a virtual
  21547 heading of level 0 for property-inheritance.  It will return the
  21548 level of the headline found (down to 0) or nil if already at a
  21549 point before the first headline or at point-min."
  21550   (when (ignore-errors (org-back-to-heading t))
  21551     (if (< 1 (funcall outline-level))
  21552 	(or (org-up-heading-safe)
  21553             ;; The first heading may not be level 1 heading.
  21554             (goto-char (point-min)))
  21555       (unless (= (point) (point-min)) (goto-char (point-min))))))
  21556 
  21557 (defun org-first-sibling-p ()
  21558   "Is this heading the first child of its parents?"
  21559   (let ((re org-outline-regexp-bol)
  21560 	level l)
  21561     (unless (org-at-heading-p t)
  21562       (user-error "Not at a heading"))
  21563     (setq level (funcall outline-level))
  21564     (save-excursion
  21565       (if (not (re-search-backward re nil t))
  21566 	  t
  21567 	(setq l (funcall outline-level))
  21568 	(< l level)))))
  21569 
  21570 (defun org-goto-sibling (&optional previous)
  21571   "Goto the next sibling heading, even if it is invisible.
  21572 When PREVIOUS is set, go to the previous sibling instead.  Returns t
  21573 when a sibling was found.  When none is found, return nil and don't
  21574 move point."
  21575   (let ((fun (if previous 're-search-backward 're-search-forward))
  21576 	(pos (point))
  21577 	(re org-outline-regexp-bol)
  21578 	level l)
  21579     (when (ignore-errors (org-back-to-heading t))
  21580       (when (org-element-type-p (org-element-at-point) 'inlinetask)
  21581         (org-up-heading-safe))
  21582       (setq level (funcall outline-level))
  21583       (catch 'exit
  21584 	(or previous (forward-char 1))
  21585 	(while (funcall fun re nil t)
  21586 	  (setq l (funcall outline-level))
  21587 	  (when (< l level) (goto-char pos) (throw 'exit nil))
  21588 	  (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21589 	(goto-char pos)
  21590 	nil))))
  21591 
  21592 (defun org-goto-first-child (&optional element)
  21593   "Goto the first child, even if it is invisible.
  21594 Return t when a child was found.  Otherwise don't move point and
  21595 return nil."
  21596   (let ((heading (org-element-lineage
  21597                   (or element (org-element-at-point))
  21598                   '(headline inlinetask org-data)
  21599                   'with-self)))
  21600     (when heading
  21601       (unless (or (org-element-type-p heading 'inlinetask)
  21602                   (not (org-element-contents-begin heading)))
  21603         (let ((pos (point)))
  21604           (goto-char (org-element-contents-begin heading))
  21605           (if (re-search-forward
  21606                org-outline-regexp-bol
  21607                (org-element-end heading)
  21608                t)
  21609               (progn (goto-char (match-beginning 0)) t)
  21610             (goto-char pos) nil))))))
  21611 
  21612 (defun org-get-next-sibling ()
  21613   "Move to next heading of the same level, and return point.
  21614 If there is no such heading, return nil.
  21615 This is like outline-next-sibling, but invisible headings are ok."
  21616   (let ((level (funcall outline-level)))
  21617     (outline-next-heading)
  21618     (while (and (not (eobp)) (> (funcall outline-level) level))
  21619       (outline-next-heading))
  21620     (unless (or (eobp) (< (funcall outline-level) level))
  21621       (point))))
  21622 
  21623 (defun org-get-previous-sibling ()
  21624   "Move to previous heading of the same level, and return point.
  21625 If there is no such heading, return nil."
  21626   (let ((opoint (point))
  21627 	(level (funcall outline-level)))
  21628     (outline-previous-heading)
  21629     (when (and (/= (point) opoint) (outline-on-heading-p t))
  21630       (while (and (> (funcall outline-level) level)
  21631 		  (not (bobp)))
  21632 	(outline-previous-heading))
  21633       (unless (< (funcall outline-level) level)
  21634         (point)))))
  21635 
  21636 (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  21637   "Goto to the end of a visible subtree at point or ELEMENT and return point.
  21638 The subtree is considered at first heading parent containing point or
  21639 ELEMENT.
  21640 
  21641 When end of the subtree has blank lines, move point before these blank
  21642 lines.
  21643 
  21644 When INVISIBLE-OK is non-nil, ignore visibility.
  21645 
  21646 When before first heading, goto `point-max' minus blank lines.
  21647 When TO-HEADING is non-nil, go to the next heading or `point-max'."
  21648   (when element
  21649     (setq element (org-element-lineage
  21650                    element
  21651                    '(headline)
  21652                    'include-self))
  21653     (goto-char (org-element-begin element)))
  21654   (unless (and invisible-ok element)
  21655     (org-back-to-heading-or-point-min invisible-ok)
  21656     (setq element
  21657           (org-element-lineage
  21658            (org-element-at-point)
  21659            '(headline)
  21660            'include-self)))
  21661   (if (org-element-type-p element 'headline)
  21662       (goto-char (org-element-end element))
  21663     (goto-char (point-max)))
  21664   (unless to-heading
  21665     (when (memq (preceding-char) '(?\n ?\^M))
  21666       ;; Go to end of line before heading
  21667       (forward-char -1)
  21668       ;; Skip blank lines
  21669       (skip-chars-backward "\n\r\t ")))
  21670   (point))
  21671 
  21672 (defun org-end-of-meta-data (&optional full)
  21673   "Skip planning line and properties drawer in current entry.
  21674 
  21675 When optional argument FULL is t, also skip planning information,
  21676 clocking lines, any kind of drawer, and blank lines
  21677 
  21678 When FULL is non-nil but not t, skip planning information,
  21679 properties, clocking lines, logbook drawers, and blank lines."
  21680   (org-back-to-heading t)
  21681   (forward-line)
  21682   ;; Skip planning information.
  21683   (when (looking-at-p org-planning-line-re) (forward-line))
  21684   ;; Skip property drawer.
  21685   (when (looking-at org-property-drawer-re)
  21686     (goto-char (match-end 0))
  21687     (forward-line))
  21688   ;; When FULL is not nil, skip more.
  21689   (when (and full (not (org-at-heading-p)))
  21690     (catch 'exit
  21691       (let ((end (save-excursion (outline-next-heading) (point)))
  21692 	    (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21693 	(while (not (eobp))
  21694 	  (cond ;; Skip clock lines and blank lines.
  21695 	   ((looking-at-p re) (forward-line))
  21696 	   ;; Skip logbook drawer.
  21697 	   ((looking-at-p org-logbook-drawer-re)
  21698 	    (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21699 		(forward-line)
  21700 	      (throw 'exit t)))
  21701 	   ;; When FULL is t, skip regular drawer too.
  21702 	   ((and (eq full t) (looking-at-p org-drawer-regexp))
  21703 	    (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21704 		(forward-line)
  21705 	      (throw 'exit t)))
  21706 	   (t (throw 'exit t))))))))
  21707 
  21708 (defun org--line-fully-invisible-p ()
  21709   "Return non-nil if the current line is fully invisible."
  21710   (let ((line-beg (line-beginning-position))
  21711 	(line-pos (1- (line-end-position)))
  21712 	(is-invisible t))
  21713     (while (and (< line-beg line-pos) is-invisible)
  21714       (setq is-invisible (org-invisible-p line-pos))
  21715       (setq line-pos (1- line-pos)))
  21716     is-invisible))
  21717 
  21718 (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21719   "Move forward to the ARG'th subheading at same level as this one.
  21720 Stop at the first and last subheadings of a superior heading.
  21721 Normally this only looks at visible headings, but when INVISIBLE-OK is
  21722 non-nil it will also look at invisible ones."
  21723   (interactive "p")
  21724   (let ((backward? (and arg (< arg 0))))
  21725     (if (org-before-first-heading-p)
  21726 	(if backward? (goto-char (point-min)) (outline-next-heading))
  21727       (org-back-to-heading invisible-ok)
  21728       (unless backward? (end-of-line))	;do not match current headline
  21729       (let ((level (org-current-level))
  21730 	    (f (if backward? #'re-search-backward #'re-search-forward))
  21731 	    (count (if arg (abs arg) 1))
  21732 	    (result (point)))
  21733 	(while (and (> count 0)
  21734 		    (funcall f org-outline-regexp-bol nil 'move))
  21735 	  (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21736 	    (cond ((< l level) (setq count 0))
  21737 		  ((and (= l level)
  21738 			(or invisible-ok
  21739 			    ;; FIXME: See commit a700fadd72 and the
  21740 			    ;; related discussion on why using
  21741 			    ;; `org--line-fully-invisible-p' is needed
  21742 			    ;; here, which is to serve the needs of an
  21743 			    ;; external package.  If the change is
  21744 			    ;; wrong regarding Org itself, it should
  21745 			    ;; be removed.
  21746 			    (not (org--line-fully-invisible-p))))
  21747 		   (cl-decf count)
  21748 		   (when (= l level) (setq result (point)))))))
  21749 	(goto-char result))
  21750       (forward-line 0))))
  21751 
  21752 (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21753   "Move backward to the ARG'th subheading at same level as this one.
  21754 Stop at the first and last subheadings of a superior heading."
  21755   (interactive "p")
  21756   (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21757 
  21758 (defun org-next-visible-heading (arg)
  21759   "Move to the next visible heading line.
  21760 With ARG, repeats or can move backward if negative."
  21761   (interactive "p")
  21762   (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  21763     (if (< arg 0)
  21764 	(forward-line 0)
  21765       (end-of-line))
  21766     (while (and (< arg 0) (re-search-backward regexp nil :move))
  21767       (unless (bobp)
  21768 	(when (org-invisible-p nil t)
  21769 	  (goto-char (org-fold-previous-visibility-change))
  21770           (unless (looking-at-p regexp)
  21771             (re-search-backward regexp nil :mode))))
  21772       (cl-incf arg))
  21773     (while (and (> arg 0) (re-search-forward regexp nil :move))
  21774       (when (org-invisible-p nil t)
  21775 	(goto-char (org-fold-next-visibility-change))
  21776         (skip-chars-forward " \t\n")
  21777 	(end-of-line))
  21778       (cl-decf arg))
  21779     (if (> arg 0) (goto-char (point-max)) (forward-line 0))))
  21780 
  21781 (defun org-previous-visible-heading (arg)
  21782   "Move to the previous visible heading.
  21783 With ARG, repeats or can move forward if negative."
  21784   (interactive "p")
  21785   (org-next-visible-heading (- arg)))
  21786 
  21787 (defun org-forward-paragraph (&optional arg)
  21788   "Move forward by a paragraph, or equivalent, unit.
  21789 
  21790 With argument ARG, do it ARG times;
  21791 a negative argument ARG = -N means move backward N paragraphs.
  21792 
  21793 The function moves point between two structural
  21794 elements (paragraphs, tables, lists, etc.).
  21795 
  21796 It also provides the following special moves for convenience:
  21797 
  21798   - on a table or a property drawer, move to its beginning;
  21799   - on comment, example, export, source and verse blocks, stop
  21800     at blank lines;
  21801   - skip consecutive clocks, diary S-exps, and keywords."
  21802   (interactive "^p")
  21803   (unless arg (setq arg 1))
  21804   (if (< arg 0) (org-backward-paragraph (- arg))
  21805     (while (and (> arg 0) (not (eobp)))
  21806       (org--forward-paragraph-once)
  21807       (cl-decf arg))
  21808     ;; Return moves left.
  21809     arg))
  21810 
  21811 (defun org-backward-paragraph (&optional arg)
  21812   "Move backward by a paragraph, or equivalent, unit.
  21813 
  21814 With argument ARG, do it ARG times;
  21815 a negative argument ARG = -N means move forward N paragraphs.
  21816 
  21817 The function moves point between two structural
  21818 elements (paragraphs, tables, lists, etc.).
  21819 
  21820 It also provides the following special moves for convenience:
  21821 
  21822   - on a table or a property drawer, move to its beginning;
  21823   - on comment, example, export, source and verse blocks, stop
  21824     at blank lines;
  21825   - skip consecutive clocks, diary S-exps, and keywords."
  21826   (interactive "^p")
  21827   (unless arg (setq arg 1))
  21828   (if (< arg 0) (org-forward-paragraph (- arg))
  21829     (while (and (> arg 0) (not (bobp)))
  21830       (org--backward-paragraph-once)
  21831       (cl-decf arg))
  21832     ;; Return moves left.
  21833     arg))
  21834 
  21835 (defvar org--single-lines-list-is-paragraph t
  21836   "Treat plain lists with single line items as a whole paragraph.")
  21837 
  21838 (defun org--paragraph-at-point ()
  21839   "Return paragraph, or equivalent, element at point.
  21840 
  21841 Paragraph element at point is the element at point, with the
  21842 following special cases:
  21843 
  21844 - treat table rows (resp. node properties) as the table
  21845   \(resp. property drawer) containing them.
  21846 
  21847 - treat plain lists with an item every line as a whole.
  21848 
  21849 - treat consecutive keywords, clocks, and diary-sexps as a single
  21850   block.
  21851 
  21852 Function may return a real element, or a pseudo-element with type
  21853 `pseudo-paragraph'."
  21854   (let* ((e (org-element-at-point))
  21855 	 (type (org-element-type e))
  21856 	 ;; If we need to fake a new pseudo-element, triplet is
  21857 	 ;;
  21858 	 ;;   (BEG END PARENT)
  21859 	 ;;
  21860 	 ;; where BEG and END are element boundaries, and PARENT the
  21861 	 ;; element containing it, or nil.
  21862 	 (triplet
  21863 	  (cond
  21864 	   ((memq type '(table property-drawer))
  21865 	    (list (org-element-begin e)
  21866 		  (org-element-end e)
  21867 		  (org-element-parent e)))
  21868 	   ((memq type '(node-property table-row))
  21869 	    (let ((e (org-element-parent e)))
  21870 	      (list (org-element-begin e)
  21871 		    (org-element-end e)
  21872 		    (org-element-parent e))))
  21873 	   ((memq type '(clock diary-sexp keyword))
  21874 	    (let* ((regexp (pcase type
  21875 			     (`clock org-clock-line-re)
  21876 			     (`diary-sexp "%%(")
  21877 			     (_ org-keyword-regexp)))
  21878 		   (end (if (< 0 (org-element-post-blank e))
  21879 			    (org-element-end e)
  21880 			  (org-with-wide-buffer
  21881 			   (forward-line)
  21882 			   (while (looking-at regexp) (forward-line))
  21883 			   (skip-chars-forward " \t\n")
  21884 			   (line-beginning-position))))
  21885 		   (begin (org-with-point-at (org-element-begin e)
  21886 			    (while (and (not (bobp)) (looking-at regexp))
  21887 			      (forward-line -1))
  21888 			    ;; We may have gotten one line too far.
  21889 			    (if (looking-at regexp)
  21890 				(point)
  21891 			      (line-beginning-position 2)))))
  21892 	      (list begin end (org-element-parent e))))
  21893 	   ;; Find the full plain list containing point, the check it
  21894 	   ;; contains exactly one line per item.
  21895 	   ((let ((l (org-element-lineage e 'plain-list t)))
  21896 	      (while (org-element-type-p
  21897                       (org-element-parent l)
  21898                       '(item plain-list))
  21899 		(setq l (org-element-parent l)))
  21900 	      (and l org--single-lines-list-is-paragraph
  21901 		   (org-with-point-at (org-element-post-affiliated l)
  21902 		     (forward-line (length (org-element-property :structure l)))
  21903 		     (= (point) (org-element-contents-end l)))
  21904 		   ;; Return value.
  21905 		   (list (org-element-begin l)
  21906 			 (org-element-end l)
  21907 			 (org-element-parent l)))))
  21908 	   (t nil))))			;no triplet: return element
  21909     (pcase triplet
  21910       (`(,b ,e ,p)
  21911        (org-element-create
  21912 	'pseudo-paragraph
  21913 	(list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  21914       (_ e))))
  21915 
  21916 (defun org--forward-paragraph-once ()
  21917   "Move forward to end of paragraph or equivalent, once.
  21918 See `org-forward-paragraph'."
  21919   (interactive)
  21920   (save-restriction
  21921     (widen)
  21922     (skip-chars-forward " \t\n")
  21923     (cond
  21924      ((eobp) nil)
  21925      ;; When inside a folded part, move out of it.
  21926      ((when (org-invisible-p nil t)
  21927         (goto-char (cdr (org-fold-get-region-at-point)))
  21928         (forward-line)
  21929         t))
  21930      (t
  21931       (let* ((element (org--paragraph-at-point))
  21932 	     (type (org-element-type element))
  21933 	     (contents-begin (org-element-contents-begin element))
  21934 	     (end (org-element-end element))
  21935 	     (post-affiliated (org-element-post-affiliated element)))
  21936 	(cond
  21937 	 ((eq type 'plain-list)
  21938 	  (forward-char)
  21939 	  (org--forward-paragraph-once))
  21940 	 ;; If the element is folded, skip it altogether.
  21941          ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  21942             (goto-char (cdr (org-fold-get-region-at-point
  21943 			     nil
  21944 			     (org-with-point-at post-affiliated
  21945 			       (line-end-position)))))
  21946 	    (forward-line)
  21947 	    t))
  21948 	 ;; At a greater element, move inside.
  21949 	 ((and contents-begin
  21950 	       (> contents-begin (point))
  21951 	       (not (eq type 'paragraph)))
  21952 	  (goto-char contents-begin)
  21953 	  ;; Items and footnote definitions contents may not start at
  21954 	  ;; the beginning of the line.  In this case, skip until the
  21955 	  ;; next paragraph.
  21956 	  (cond
  21957 	   ((not (bolp)) (org--forward-paragraph-once))
  21958 	   ((org-previous-line-empty-p) (forward-line -1))
  21959 	   (t nil)))
  21960 	 ;; Move between empty lines in some blocks.
  21961 	 ((memq type '(comment-block example-block export-block src-block
  21962 				     verse-block))
  21963 	  (let ((contents-start
  21964 		 (org-with-point-at post-affiliated
  21965 		   (line-beginning-position 2))))
  21966 	    (if (< (point) contents-start)
  21967 		(goto-char contents-start)
  21968 	      (let ((contents-end
  21969 		     (org-with-point-at end
  21970 		       (skip-chars-backward " \t\n")
  21971 		       (line-beginning-position))))
  21972 		(cond
  21973 		 ((>= (point) contents-end)
  21974 		  (goto-char end)
  21975 		  (skip-chars-backward " \t\n")
  21976 		  (forward-line))
  21977 		 ((re-search-forward "^[ \t]*\n" contents-end :move)
  21978 		  (forward-line -1))
  21979 		 (t nil))))))
  21980 	 (t
  21981 	  ;; Move to element's end.
  21982 	  (goto-char end)
  21983 	  (skip-chars-backward " \t\n")
  21984 	  (forward-line))))))))
  21985 
  21986 (defun org--backward-paragraph-once ()
  21987   "Move backward to start of paragraph or equivalent, once.
  21988 See `org-backward-paragraph'."
  21989   (interactive)
  21990   (save-restriction
  21991     (widen)
  21992     (cond
  21993      ((bobp) nil)
  21994      ;; Blank lines at the beginning of the buffer.
  21995      ((and (org-match-line "^[ \t]*$")
  21996 	   (save-excursion (skip-chars-backward " \t\n") (bobp)))
  21997       (goto-char (point-min)))
  21998      ;; When inside a folded part, move out of it.
  21999      ((when (org-invisible-p (1- (point)) t)
  22000         (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  22001 	(org--backward-paragraph-once)
  22002 	t))
  22003      (t
  22004       (let* ((element (org--paragraph-at-point))
  22005 	     (type (org-element-type element))
  22006 	     (begin (org-element-begin element))
  22007 	     (post-affiliated (org-element-post-affiliated element))
  22008 	     (contents-end (org-element-contents-end element))
  22009 	     (end (org-element-end element))
  22010 	     (parent (org-element-parent element))
  22011 	     (reach
  22012 	      ;; Move to the visible empty line above position P, or
  22013 	      ;; to position P.  Return t.
  22014 	      (lambda (p)
  22015 		(goto-char p)
  22016 		(when (and (org-previous-line-empty-p)
  22017 			   (let ((end (line-end-position 0)))
  22018 			     (or (= end (point-min))
  22019 				 (not (org-invisible-p (1- end))))))
  22020 		  (forward-line -1))
  22021 		t)))
  22022 	(cond
  22023 	 ;; Already at the beginning of an element.
  22024 	 ((= begin (point))
  22025 	  (cond
  22026 	   ;; There is a blank line above.  Move there.
  22027 	   ((and (org-previous-line-empty-p)
  22028 		 (not (org-invisible-p (1- (line-end-position 0)))))
  22029 	    (forward-line -1))
  22030 	   ;; At the beginning of the first element within a greater
  22031 	   ;; element.  Move to the beginning of the greater element.
  22032 	   ((and parent
  22033                  (not (org-element-type-p parent 'section))
  22034                  (= begin (org-element-contents-begin parent)))
  22035 	    (funcall reach (org-element-begin parent)))
  22036 	   ;; Since we have to move anyway, find the beginning
  22037 	   ;; position of the element above.
  22038 	   (t
  22039 	    (forward-char -1)
  22040 	    (org--backward-paragraph-once))))
  22041 	 ;; Skip paragraphs at the very beginning of footnote
  22042 	 ;; definitions or items.
  22043 	 ((and (eq type 'paragraph)
  22044 	       (org-with-point-at begin (not (bolp))))
  22045 	  (funcall reach (progn (goto-char begin) (line-beginning-position))))
  22046 	 ;; If the element is folded, skip it altogether.
  22047 	 ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  22048 	  (funcall reach begin))
  22049 	 ;; At the end of a greater element, move inside.
  22050 	 ((and contents-end
  22051 	       (<= contents-end (point))
  22052 	       (not (eq type 'paragraph)))
  22053 	  (cond
  22054 	   ((memq type '(footnote-definition plain-list))
  22055 	    (skip-chars-backward " \t\n")
  22056 	    (org--backward-paragraph-once))
  22057 	   ((= contents-end (point))
  22058 	    (forward-char -1)
  22059 	    (org--backward-paragraph-once))
  22060 	   (t
  22061 	    (goto-char contents-end))))
  22062 	 ;; Move between empty lines in some blocks.
  22063 	 ((and (memq type '(comment-block example-block export-block src-block
  22064 					  verse-block))
  22065 	       (let ((contents-start
  22066 		      (org-with-point-at post-affiliated
  22067 			(line-beginning-position 2))))
  22068 		 (when (> (point) contents-start)
  22069 		   (let ((contents-end
  22070 			  (org-with-point-at end
  22071 			    (skip-chars-backward " \t\n")
  22072 			    (line-beginning-position))))
  22073 		     (if (> (point) contents-end)
  22074 			 (progn (goto-char contents-end) t)
  22075 		       (skip-chars-backward " \t\n" begin)
  22076 		       (re-search-backward "^[ \t]*\n" contents-start :move)
  22077 		       t))))))
  22078 	 ;; Move to element's start.
  22079 	 (t
  22080 	  (funcall reach begin))))))))
  22081 
  22082 (defun org-forward-element ()
  22083   "Move forward by one element.
  22084 Move to the next element at the same level, when possible."
  22085   (interactive)
  22086   (cond ((eobp) (user-error "Cannot move further down"))
  22087 	((org-with-limited-levels (org-at-heading-p))
  22088 	 (let ((origin (point)))
  22089 	   (goto-char (org-end-of-subtree nil t))
  22090 	   (unless (org-with-limited-levels (org-at-heading-p))
  22091 	     (goto-char origin)
  22092 	     (user-error "Cannot move further down"))))
  22093 	(t
  22094 	 (let* ((elem (org-element-at-point))
  22095 		(end (org-element-end elem))
  22096 		(parent (org-element-parent elem)))
  22097 	   (cond ((and parent (= (org-element-contents-end parent) end))
  22098 		  (goto-char (org-element-end parent)))
  22099 		 ((integer-or-marker-p end) (goto-char end))
  22100 		 (t (message "No element at point")))))))
  22101 
  22102 (defun org-backward-element ()
  22103   "Move backward by one element.
  22104 Move to the previous element at the same level, when possible."
  22105   (interactive)
  22106   (cond ((bobp) (user-error "Cannot move further up"))
  22107 	((org-with-limited-levels (org-at-heading-p))
  22108 	 ;; At a headline, move to the previous one, if any, or stay
  22109 	 ;; here.
  22110 	 (let ((origin (point)))
  22111 	   (org-with-limited-levels (org-backward-heading-same-level 1))
  22112 	   ;; When current headline has no sibling above, move to its
  22113 	   ;; parent.
  22114 	   (when (= (point) origin)
  22115 	     (or (org-with-limited-levels (org-up-heading-safe))
  22116 		 (progn (goto-char origin)
  22117 			(user-error "Cannot move further up"))))))
  22118 	(t
  22119 	 (let* ((elem (org-element-at-point))
  22120 		(beg (org-element-begin elem)))
  22121 	   (cond
  22122 	    ;; Move to beginning of current element if point isn't
  22123 	    ;; there already.
  22124 	    ((null beg) (message "No element at point"))
  22125 	    ((/= (point) beg) (goto-char beg))
  22126 	    (t (goto-char beg)
  22127 	       (skip-chars-backward " \r\t\n")
  22128 	       (unless (bobp)
  22129 		 (let ((prev (org-element-at-point)))
  22130 		   (goto-char (org-element-begin prev))
  22131 		   (while (and (setq prev (org-element-parent prev))
  22132 			       (<= (org-element-end prev) beg))
  22133 		     (goto-char (org-element-begin prev)))))))))))
  22134 
  22135 (defun org-up-element ()
  22136   "Move to upper element."
  22137   (interactive)
  22138   (if (org-with-limited-levels (org-at-heading-p))
  22139       (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22140     (let* ((elem (org-element-at-point))
  22141 	   (parent (org-element-parent elem)))
  22142       ;; Skip sections
  22143       (when (org-element-type-p parent 'section)
  22144         (setq parent (org-element-parent parent)))
  22145       (if (and parent
  22146                (not (org-element-type-p parent 'org-data)))
  22147           (goto-char (org-element-begin parent))
  22148 	(if (org-with-limited-levels (org-before-first-heading-p))
  22149 	    (user-error "No surrounding element")
  22150 	  (org-with-limited-levels (org-back-to-heading)))))))
  22151 
  22152 (defun org-down-element ()
  22153   "Move to inner element."
  22154   (interactive)
  22155   (let ((element (org-element-at-point)))
  22156     (cond
  22157      ((org-element-type-p element '(plain-list table))
  22158       (goto-char (org-element-contents-begin element))
  22159       (forward-char))
  22160      ((org-element-type-p element org-element-greater-elements)
  22161       ;; If contents are hidden, first disclose them.
  22162       (when (org-invisible-p (line-end-position)) (org-cycle))
  22163       (goto-char (or (org-element-contents-begin element)
  22164 		     (user-error "No content for this element"))))
  22165      (t (user-error "No inner element")))))
  22166 
  22167 (defun org-drag-element-backward ()
  22168   "Move backward element at point."
  22169   (interactive)
  22170   (let ((elem (or (org-element-at-point)
  22171 		  (user-error "No element at point"))))
  22172     (if (org-element-type-p elem 'headline)
  22173 	;; Preserve point when moving a whole tree, even if point was
  22174 	;; on blank lines below the headline.
  22175 	(let ((offset (skip-chars-backward " \t\n")))
  22176 	  (unwind-protect (org-move-subtree-up)
  22177 	    (forward-char (- offset))))
  22178       (let ((prev-elem
  22179 	     (save-excursion
  22180 	       (goto-char (org-element-begin elem))
  22181 	       (skip-chars-backward " \r\t\n")
  22182 	       (unless (bobp)
  22183 		 (let* ((beg (org-element-begin elem))
  22184 			(prev (org-element-at-point))
  22185 			(up prev))
  22186 		   (while (and (setq up (org-element-parent up))
  22187 			       (<= (org-element-end up) beg))
  22188 		     (setq prev up))
  22189 		   prev)))))
  22190 	;; Error out if no previous element or previous element is
  22191 	;; a parent of the current one.
  22192 	(if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22193 	    (user-error "Cannot drag element backward")
  22194 	  (let ((pos (point)))
  22195 	    (org-element-swap-A-B prev-elem elem)
  22196 	    (goto-char (+ (org-element-begin prev-elem)
  22197 			  (- pos (org-element-begin elem))))))))))
  22198 
  22199 (defun org-drag-element-forward ()
  22200   "Move forward element at point."
  22201   (interactive)
  22202   (let* ((pos (point))
  22203 	 (elem (or (org-element-at-point)
  22204 		   (user-error "No element at point"))))
  22205     (when (= (point-max) (org-element-end elem))
  22206       (user-error "Cannot drag element forward"))
  22207     (goto-char (org-element-end elem))
  22208     (let ((next-elem (org-element-at-point)))
  22209       (when (or (org-element-nested-p elem next-elem)
  22210 		(and (org-element-type-p next-elem 'headline)
  22211 		     (not (org-element-type-p elem 'headline))))
  22212 	(goto-char pos)
  22213 	(user-error "Cannot drag element forward"))
  22214       ;; Compute new position of point: it's shifted by NEXT-ELEM
  22215       ;; body's length (without final blanks) and by the length of
  22216       ;; blanks between ELEM and NEXT-ELEM.
  22217       (let ((size-next (- (save-excursion
  22218 			    (goto-char (org-element-end next-elem))
  22219 			    (skip-chars-backward " \r\t\n")
  22220 			    (forward-line)
  22221 			    ;; Small correction if buffer doesn't end
  22222 			    ;; with a newline character.
  22223 			    (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22224 			  (org-element-begin next-elem)))
  22225 	    (size-blank (- (org-element-end elem)
  22226 			   (save-excursion
  22227 			     (goto-char (org-element-end elem))
  22228 			     (skip-chars-backward " \r\t\n")
  22229 			     (forward-line)
  22230 			     (point)))))
  22231 	(org-element-swap-A-B elem next-elem)
  22232 	(goto-char (+ pos size-next size-blank))))))
  22233 
  22234 (defun org-drag-line-forward (arg)
  22235   "Drag the line at point ARG lines forward."
  22236   (interactive "p")
  22237   (dotimes (_ (abs arg))
  22238     (let ((c (current-column)))
  22239       (if (< 0 arg)
  22240 	  (progn
  22241 	    (forward-line 1)
  22242 	    (transpose-lines 1)
  22243 	    (forward-line -1))
  22244 	(transpose-lines 1)
  22245 	(forward-line -2))
  22246       (org-move-to-column c))))
  22247 
  22248 (defun org-drag-line-backward (arg)
  22249   "Drag the line at point ARG lines backward."
  22250   (interactive "p")
  22251   (org-drag-line-forward (- arg)))
  22252 
  22253 (defun org-mark-element ()
  22254   "Put point at beginning of this element, mark at end.
  22255 
  22256 Interactively, if this command is repeated or (in Transient Mark
  22257 mode) if the mark is active, it marks the next element after the
  22258 ones already marked."
  22259   (interactive)
  22260   (let (deactivate-mark)
  22261     (if (and (called-interactively-p 'any)
  22262 	     (or (and (eq last-command this-command) (mark t))
  22263 		 (and transient-mark-mode mark-active)))
  22264 	(set-mark
  22265 	 (save-excursion
  22266 	   (goto-char (mark))
  22267 	   (goto-char (org-element-end (org-element-at-point)))
  22268 	   (point)))
  22269       (let ((element (org-element-at-point)))
  22270 	(end-of-line)
  22271 	(push-mark (min (point-max) (org-element-end element)) t t)
  22272 	(goto-char (org-element-begin element))))))
  22273 
  22274 (defun org-narrow-to-element ()
  22275   "Narrow buffer to current element.
  22276 Use the command `\\[widen]' to see the whole buffer again."
  22277   (interactive)
  22278   (let ((elem (org-element-at-point)))
  22279     (cond
  22280      ((eq (car elem) 'headline)
  22281       (narrow-to-region
  22282        (org-element-begin elem)
  22283        (org-element-end elem)))
  22284      ((memq (car elem) org-element-greater-elements)
  22285       (narrow-to-region
  22286        (org-element-contents-begin elem)
  22287        (org-element-contents-end elem)))
  22288      (t
  22289       (narrow-to-region
  22290        (org-element-begin elem)
  22291        (org-element-end elem))))))
  22292 
  22293 (defun org-transpose-element ()
  22294   "Transpose current and previous elements, keeping blank lines between.
  22295 Point is moved after both elements."
  22296   (interactive)
  22297   (org-skip-whitespace)
  22298   (let ((end (org-element-end (org-element-at-point))))
  22299     (org-drag-element-backward)
  22300     (goto-char end)))
  22301 
  22302 (defun org-unindent-buffer ()
  22303   "Un-indent the visible part of the buffer.
  22304 Relative indentation (between items, inside blocks, etc.) isn't
  22305 modified."
  22306   (interactive)
  22307   (unless (eq major-mode 'org-mode)
  22308     (user-error "Cannot un-indent a buffer not in Org mode"))
  22309   (letrec ((parse-tree (org-element-parse-buffer 'greater-element nil 'defer))
  22310 	   (unindent-tree
  22311 	    (lambda (contents)
  22312 	      (dolist (element (reverse contents))
  22313 		(if (org-element-type-p element '(headline section))
  22314 		    (funcall unindent-tree (org-element-contents element))
  22315 		  (save-excursion
  22316 		    (save-restriction
  22317 		      (narrow-to-region
  22318 		       (org-element-begin element)
  22319 		       (org-element-end element))
  22320 		      (org-do-remove-indentation))))))))
  22321     (funcall unindent-tree (org-element-contents parse-tree))))
  22322 
  22323 (defun org-make-options-regexp (kwds &optional extra)
  22324   "Make a regular expression for keyword lines.
  22325 KWDS is a list of keywords, as strings.  Optional argument EXTRA,
  22326 when non-nil, is a regexp matching keywords names."
  22327   (concat "^[ \t]*#\\+\\("
  22328 	  (regexp-opt kwds)
  22329 	  (and extra (concat (and kwds "\\|") extra))
  22330 	  "\\):[ \t]*\\(.*\\)"))
  22331 
  22332 
  22333 ;;; Conveniently switch to Info nodes
  22334 
  22335 (defun org-info-find-node (&optional nodename)
  22336   "Find Info documentation NODENAME or Org documentation according context.
  22337 Started from `gnus-info-find-node'."
  22338   (interactive)
  22339   (Info-goto-node
  22340    (or nodename
  22341        (let ((default-org-info-node "(org) Top"))
  22342          (cond
  22343           ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  22344           ((eq 'org-mode major-mode)
  22345            (let* ((context (org-element-at-point))
  22346                   (element-info-nodes ; compare to `org-element-all-elements'.
  22347                    `((babel-call . "(org) Evaluating Code Blocks")
  22348                      (center-block . "(org) Paragraphs")
  22349                      (clock . ,default-org-info-node)
  22350                      (comment . "(org) Comment Lines")
  22351                      (comment-block . "(org) Comment Lines")
  22352                      (diary-sexp . ,default-org-info-node)
  22353                      (drawer . "(org) Drawers")
  22354                      (dynamic-block . "(org) Dynamic Blocks")
  22355                      (example-block . "(org) Literal Examples")
  22356                      (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  22357                      (fixed-width . ,default-org-info-node)
  22358                      (footnote-definition . "(org) Creating Footnotes")
  22359                      (headline . "(org) Document Structure")
  22360                      (horizontal-rule . "(org) Built-in Table Editor")
  22361                      (inlinetask . ,default-org-info-node)
  22362                      (item . "(org) Plain Lists")
  22363                      (keyword . "(org) Per-file keywords")
  22364                      (latex-environment . "(org) LaTeX Export")
  22365                      (node-property . "(org) Properties and Columns")
  22366                      (paragraph . "(org) Paragraphs")
  22367                      (plain-list . "(org) Plain Lists")
  22368                      (planning . "(org) Deadlines and Scheduling")
  22369                      (property-drawer . "(org) Properties and Columns")
  22370                      (quote-block . "(org) Paragraphs")
  22371                      (section . ,default-org-info-node)
  22372                      (special-block . ,default-org-info-node)
  22373                      (src-block . "(org) Working with Source Code")
  22374                      (table . "(org) Tables")
  22375                      (table-row . "(org) Tables")
  22376                      (verse-block . "(org) Paragraphs"))))
  22377              (or (cdr (assoc (car context) element-info-nodes))
  22378                  default-org-info-node)))
  22379           (t default-org-info-node))))))
  22380 
  22381 
  22382 ;;; Finish up
  22383 
  22384 (add-hook 'org-mode-hook     ;remove folds when changing major mode
  22385 	  (lambda () (add-hook 'change-major-mode-hook
  22386 			  'org-fold-show-all 'append 'local)))
  22387 
  22388 (provide 'org)
  22389 
  22390 (run-hooks 'org-load-hook)
  22391 
  22392 ;;; org.el ends here